MIPS/GAS: Unify GP-relative percent-ops
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2017 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
947 /* TRUE if checks are suppressed for invalid branches between ISA modes.
948    Needed for broken assembly produced by some GCC versions and some
949    sloppy code out there, where branches to data labels are present.  */
950 static bfd_boolean mips_ignore_branch_isa;
951 \f
952 /* The expansion of many macros depends on the type of symbol that
953    they refer to.  For example, when generating position-dependent code,
954    a macro that refers to a symbol may have two different expansions,
955    one which uses GP-relative addresses and one which uses absolute
956    addresses.  When generating SVR4-style PIC, a macro may have
957    different expansions for local and global symbols.
958
959    We handle these situations by generating both sequences and putting
960    them in variant frags.  In position-dependent code, the first sequence
961    will be the GP-relative one and the second sequence will be the
962    absolute one.  In SVR4 PIC, the first sequence will be for global
963    symbols and the second will be for local symbols.
964
965    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
966    SECOND are the lengths of the two sequences in bytes.  These fields
967    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
968    the subtype has the following flags:
969
970    RELAX_PIC
971         Set if generating PIC code.
972
973    RELAX_USE_SECOND
974         Set if it has been decided that we should use the second
975         sequence instead of the first.
976
977    RELAX_SECOND_LONGER
978         Set in the first variant frag if the macro's second implementation
979         is longer than its first.  This refers to the macro as a whole,
980         not an individual relaxation.
981
982    RELAX_NOMACRO
983         Set in the first variant frag if the macro appeared in a .set nomacro
984         block and if one alternative requires a warning but the other does not.
985
986    RELAX_DELAY_SLOT
987         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
988         delay slot.
989
990    RELAX_DELAY_SLOT_16BIT
991         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
992         16-bit instruction.
993
994    RELAX_DELAY_SLOT_SIZE_FIRST
995         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
996         the macro is of the wrong size for the branch delay slot.
997
998    RELAX_DELAY_SLOT_SIZE_SECOND
999         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
1000         the macro is of the wrong size for the branch delay slot.
1001
1002    The frag's "opcode" points to the first fixup for relaxable code.
1003
1004    Relaxable macros are generated using a sequence such as:
1005
1006       relax_start (SYMBOL);
1007       ... generate first expansion ...
1008       relax_switch ();
1009       ... generate second expansion ...
1010       relax_end ();
1011
1012    The code and fixups for the unwanted alternative are discarded
1013    by md_convert_frag.  */
1014 #define RELAX_ENCODE(FIRST, SECOND, PIC)                        \
1015   (((FIRST) << 8) | (SECOND) | ((PIC) ? 0x10000 : 0))
1016
1017 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1018 #define RELAX_SECOND(X) ((X) & 0xff)
1019 #define RELAX_PIC(X) (((X) & 0x10000) != 0)
1020 #define RELAX_USE_SECOND 0x20000
1021 #define RELAX_SECOND_LONGER 0x40000
1022 #define RELAX_NOMACRO 0x80000
1023 #define RELAX_DELAY_SLOT 0x100000
1024 #define RELAX_DELAY_SLOT_16BIT 0x200000
1025 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x400000
1026 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x800000
1027
1028 /* Branch without likely bit.  If label is out of range, we turn:
1029
1030         beq reg1, reg2, label
1031         delay slot
1032
1033    into
1034
1035         bne reg1, reg2, 0f
1036         nop
1037         j label
1038      0: delay slot
1039
1040    with the following opcode replacements:
1041
1042         beq <-> bne
1043         blez <-> bgtz
1044         bltz <-> bgez
1045         bc1f <-> bc1t
1046
1047         bltzal <-> bgezal  (with jal label instead of j label)
1048
1049    Even though keeping the delay slot instruction in the delay slot of
1050    the branch would be more efficient, it would be very tricky to do
1051    correctly, because we'd have to introduce a variable frag *after*
1052    the delay slot instruction, and expand that instead.  Let's do it
1053    the easy way for now, even if the branch-not-taken case now costs
1054    one additional instruction.  Out-of-range branches are not supposed
1055    to be common, anyway.
1056
1057    Branch likely.  If label is out of range, we turn:
1058
1059         beql reg1, reg2, label
1060         delay slot (annulled if branch not taken)
1061
1062    into
1063
1064         beql reg1, reg2, 1f
1065         nop
1066         beql $0, $0, 2f
1067         nop
1068      1: j[al] label
1069         delay slot (executed only if branch taken)
1070      2:
1071
1072    It would be possible to generate a shorter sequence by losing the
1073    likely bit, generating something like:
1074
1075         bne reg1, reg2, 0f
1076         nop
1077         j[al] label
1078         delay slot (executed only if branch taken)
1079      0:
1080
1081         beql -> bne
1082         bnel -> beq
1083         blezl -> bgtz
1084         bgtzl -> blez
1085         bltzl -> bgez
1086         bgezl -> bltz
1087         bc1fl -> bc1t
1088         bc1tl -> bc1f
1089
1090         bltzall -> bgezal  (with jal label instead of j label)
1091         bgezall -> bltzal  (ditto)
1092
1093
1094    but it's not clear that it would actually improve performance.  */
1095 #define RELAX_BRANCH_ENCODE(at, pic,                            \
1096                             uncond, likely, link, toofar)       \
1097   ((relax_substateT)                                            \
1098    (0xc0000000                                                  \
1099     | ((at) & 0x1f)                                             \
1100     | ((pic) ? 0x20 : 0)                                        \
1101     | ((toofar) ? 0x40 : 0)                                     \
1102     | ((link) ? 0x80 : 0)                                       \
1103     | ((likely) ? 0x100 : 0)                                    \
1104     | ((uncond) ? 0x200 : 0)))
1105 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1106 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x200) != 0)
1107 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x100) != 0)
1108 #define RELAX_BRANCH_LINK(i) (((i) & 0x80) != 0)
1109 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x40) != 0)
1110 #define RELAX_BRANCH_PIC(i) (((i) & 0x20) != 0)
1111 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1112
1113 /* For mips16 code, we use an entirely different form of relaxation.
1114    mips16 supports two versions of most instructions which take
1115    immediate values: a small one which takes some small value, and a
1116    larger one which takes a 16 bit value.  Since branches also follow
1117    this pattern, relaxing these values is required.
1118
1119    We can assemble both mips16 and normal MIPS code in a single
1120    object.  Therefore, we need to support this type of relaxation at
1121    the same time that we support the relaxation described above.  We
1122    use the high bit of the subtype field to distinguish these cases.
1123
1124    The information we store for this type of relaxation is the
1125    argument code found in the opcode file for this relocation, whether
1126    the user explicitly requested a small or extended form, and whether
1127    the relocation is in a jump or jal delay slot.  That tells us the
1128    size of the value, and how it should be stored.  We also store
1129    whether the fragment is considered to be extended or not.  We also
1130    store whether this is known to be a branch to a different section,
1131    whether we have tried to relax this frag yet, and whether we have
1132    ever extended a PC relative fragment because of a shift count.  */
1133 #define RELAX_MIPS16_ENCODE(type, pic, sym32, nomacro,          \
1134                             small, ext,                         \
1135                             dslot, jal_dslot)                   \
1136   (0x80000000                                                   \
1137    | ((type) & 0xff)                                            \
1138    | ((pic) ? 0x100 : 0)                                        \
1139    | ((sym32) ? 0x200 : 0)                                      \
1140    | ((nomacro) ? 0x400 : 0)                                    \
1141    | ((small) ? 0x800 : 0)                                      \
1142    | ((ext) ? 0x1000 : 0)                                       \
1143    | ((dslot) ? 0x2000 : 0)                                     \
1144    | ((jal_dslot) ? 0x4000 : 0))
1145
1146 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1147 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1148 #define RELAX_MIPS16_PIC(i) (((i) & 0x100) != 0)
1149 #define RELAX_MIPS16_SYM32(i) (((i) & 0x200) != 0)
1150 #define RELAX_MIPS16_NOMACRO(i) (((i) & 0x400) != 0)
1151 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x800) != 0)
1152 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x1000) != 0)
1153 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x2000) != 0)
1154 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x4000) != 0)
1155
1156 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x8000) != 0)
1157 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x8000)
1158 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) & ~0x8000)
1159 #define RELAX_MIPS16_ALWAYS_EXTENDED(i) (((i) & 0x10000) != 0)
1160 #define RELAX_MIPS16_MARK_ALWAYS_EXTENDED(i) ((i) | 0x10000)
1161 #define RELAX_MIPS16_CLEAR_ALWAYS_EXTENDED(i) ((i) & ~0x10000)
1162 #define RELAX_MIPS16_MACRO(i) (((i) & 0x20000) != 0)
1163 #define RELAX_MIPS16_MARK_MACRO(i) ((i) | 0x20000)
1164 #define RELAX_MIPS16_CLEAR_MACRO(i) ((i) & ~0x20000)
1165
1166 /* For microMIPS code, we use relaxation similar to one we use for
1167    MIPS16 code.  Some instructions that take immediate values support
1168    two encodings: a small one which takes some small value, and a
1169    larger one which takes a 16 bit value.  As some branches also follow
1170    this pattern, relaxing these values is required.
1171
1172    We can assemble both microMIPS and normal MIPS code in a single
1173    object.  Therefore, we need to support this type of relaxation at
1174    the same time that we support the relaxation described above.  We
1175    use one of the high bits of the subtype field to distinguish these
1176    cases.
1177
1178    The information we store for this type of relaxation is the argument
1179    code found in the opcode file for this relocation, the register
1180    selected as the assembler temporary, whether in the 32-bit
1181    instruction mode, whether the branch is unconditional, whether it is
1182    compact, whether there is no delay-slot instruction available to fill
1183    in, whether it stores the link address implicitly in $ra, whether
1184    relaxation of out-of-range 32-bit branches to a sequence of
1185    instructions is enabled, and whether the displacement of a branch is
1186    too large to fit as an immediate argument of a 16-bit and a 32-bit
1187    branch, respectively.  */
1188 #define RELAX_MICROMIPS_ENCODE(type, at, insn32, pic,           \
1189                                uncond, compact, link, nods,     \
1190                                relax32, toofar16, toofar32)     \
1191   (0x40000000                                                   \
1192    | ((type) & 0xff)                                            \
1193    | (((at) & 0x1f) << 8)                                       \
1194    | ((insn32) ? 0x2000 : 0)                                    \
1195    | ((pic) ? 0x4000 : 0)                                       \
1196    | ((uncond) ? 0x8000 : 0)                                    \
1197    | ((compact) ? 0x10000 : 0)                                  \
1198    | ((link) ? 0x20000 : 0)                                     \
1199    | ((nods) ? 0x40000 : 0)                                     \
1200    | ((relax32) ? 0x80000 : 0)                                  \
1201    | ((toofar16) ? 0x100000 : 0)                                \
1202    | ((toofar32) ? 0x200000 : 0))
1203 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1204 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1205 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1206 #define RELAX_MICROMIPS_INSN32(i) (((i) & 0x2000) != 0)
1207 #define RELAX_MICROMIPS_PIC(i) (((i) & 0x4000) != 0)
1208 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x8000) != 0)
1209 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x10000) != 0)
1210 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x20000) != 0)
1211 #define RELAX_MICROMIPS_NODS(i) (((i) & 0x40000) != 0)
1212 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x80000) != 0)
1213
1214 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x100000) != 0)
1215 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x100000)
1216 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x100000)
1217 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x200000) != 0)
1218 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x200000)
1219 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x200000)
1220
1221 /* Sign-extend 16-bit value X.  */
1222 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1223
1224 /* Is the given value a sign-extended 32-bit value?  */
1225 #define IS_SEXT_32BIT_NUM(x)                                            \
1226   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1227    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1228
1229 /* Is the given value a sign-extended 16-bit value?  */
1230 #define IS_SEXT_16BIT_NUM(x)                                            \
1231   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1232    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1233
1234 /* Is the given value a sign-extended 12-bit value?  */
1235 #define IS_SEXT_12BIT_NUM(x)                                            \
1236   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1237
1238 /* Is the given value a sign-extended 9-bit value?  */
1239 #define IS_SEXT_9BIT_NUM(x)                                             \
1240   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1241
1242 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1243 #define IS_ZEXT_32BIT_NUM(x)                                            \
1244   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1245    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1246
1247 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1248    SHIFT places.  */
1249 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1250   (((STRUCT) >> (SHIFT)) & (MASK))
1251
1252 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1253 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1254   (!(MICROMIPS) \
1255    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1256    : EXTRACT_BITS ((INSN).insn_opcode, \
1257                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1258 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1259   EXTRACT_BITS ((INSN).insn_opcode, \
1260                 MIPS16OP_MASK_##FIELD, \
1261                 MIPS16OP_SH_##FIELD)
1262
1263 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1264 #define MIPS16_EXTEND (0xf000U << 16)
1265 \f
1266 /* Whether or not we are emitting a branch-likely macro.  */
1267 static bfd_boolean emit_branch_likely_macro = FALSE;
1268
1269 /* Global variables used when generating relaxable macros.  See the
1270    comment above RELAX_ENCODE for more details about how relaxation
1271    is used.  */
1272 static struct {
1273   /* 0 if we're not emitting a relaxable macro.
1274      1 if we're emitting the first of the two relaxation alternatives.
1275      2 if we're emitting the second alternative.  */
1276   int sequence;
1277
1278   /* The first relaxable fixup in the current frag.  (In other words,
1279      the first fixup that refers to relaxable code.)  */
1280   fixS *first_fixup;
1281
1282   /* sizes[0] says how many bytes of the first alternative are stored in
1283      the current frag.  Likewise sizes[1] for the second alternative.  */
1284   unsigned int sizes[2];
1285
1286   /* The symbol on which the choice of sequence depends.  */
1287   symbolS *symbol;
1288 } mips_relax;
1289 \f
1290 /* Global variables used to decide whether a macro needs a warning.  */
1291 static struct {
1292   /* True if the macro is in a branch delay slot.  */
1293   bfd_boolean delay_slot_p;
1294
1295   /* Set to the length in bytes required if the macro is in a delay slot
1296      that requires a specific length of instruction, otherwise zero.  */
1297   unsigned int delay_slot_length;
1298
1299   /* For relaxable macros, sizes[0] is the length of the first alternative
1300      in bytes and sizes[1] is the length of the second alternative.
1301      For non-relaxable macros, both elements give the length of the
1302      macro in bytes.  */
1303   unsigned int sizes[2];
1304
1305   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1306      instruction of the first alternative in bytes and first_insn_sizes[1]
1307      is the length of the first instruction of the second alternative.
1308      For non-relaxable macros, both elements give the length of the first
1309      instruction in bytes.
1310
1311      Set to zero if we haven't yet seen the first instruction.  */
1312   unsigned int first_insn_sizes[2];
1313
1314   /* For relaxable macros, insns[0] is the number of instructions for the
1315      first alternative and insns[1] is the number of instructions for the
1316      second alternative.
1317
1318      For non-relaxable macros, both elements give the number of
1319      instructions for the macro.  */
1320   unsigned int insns[2];
1321
1322   /* The first variant frag for this macro.  */
1323   fragS *first_frag;
1324 } mips_macro_warning;
1325 \f
1326 /* Prototypes for static functions.  */
1327
1328 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1329
1330 static void append_insn
1331   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1332    bfd_boolean expansionp);
1333 static void mips_no_prev_insn (void);
1334 static void macro_build (expressionS *, const char *, const char *, ...);
1335 static void mips16_macro_build
1336   (expressionS *, const char *, const char *, va_list *);
1337 static void load_register (int, expressionS *, int);
1338 static void macro_start (void);
1339 static void macro_end (void);
1340 static void macro (struct mips_cl_insn *ip, char *str);
1341 static void mips16_macro (struct mips_cl_insn * ip);
1342 static void mips_ip (char *str, struct mips_cl_insn * ip);
1343 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1344 static void mips16_immed
1345   (const char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1346    unsigned int, unsigned long *);
1347 static size_t my_getSmallExpression
1348   (expressionS *, bfd_reloc_code_real_type *, char *);
1349 static void my_getExpression (expressionS *, char *);
1350 static void s_align (int);
1351 static void s_change_sec (int);
1352 static void s_change_section (int);
1353 static void s_cons (int);
1354 static void s_float_cons (int);
1355 static void s_mips_globl (int);
1356 static void s_option (int);
1357 static void s_mipsset (int);
1358 static void s_abicalls (int);
1359 static void s_cpload (int);
1360 static void s_cpsetup (int);
1361 static void s_cplocal (int);
1362 static void s_cprestore (int);
1363 static void s_cpreturn (int);
1364 static void s_dtprelword (int);
1365 static void s_dtpreldword (int);
1366 static void s_tprelword (int);
1367 static void s_tpreldword (int);
1368 static void s_gpvalue (int);
1369 static void s_gpword (int);
1370 static void s_gpdword (int);
1371 static void s_ehword (int);
1372 static void s_cpadd (int);
1373 static void s_insn (int);
1374 static void s_nan (int);
1375 static void s_module (int);
1376 static void s_mips_ent (int);
1377 static void s_mips_end (int);
1378 static void s_mips_frame (int);
1379 static void s_mips_mask (int reg_type);
1380 static void s_mips_stab (int);
1381 static void s_mips_weakext (int);
1382 static void s_mips_file (int);
1383 static void s_mips_loc (int);
1384 static bfd_boolean pic_need_relax (symbolS *);
1385 static int relaxed_branch_length (fragS *, asection *, int);
1386 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1387 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1388 static void file_mips_check_options (void);
1389
1390 /* Table and functions used to map between CPU/ISA names, and
1391    ISA levels, and CPU numbers.  */
1392
1393 struct mips_cpu_info
1394 {
1395   const char *name;           /* CPU or ISA name.  */
1396   int flags;                  /* MIPS_CPU_* flags.  */
1397   int ase;                    /* Set of ASEs implemented by the CPU.  */
1398   int isa;                    /* ISA level.  */
1399   int cpu;                    /* CPU number (default CPU if ISA).  */
1400 };
1401
1402 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1403
1404 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1405 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1406 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1407 \f
1408 /* Command-line options.  */
1409 const char *md_shortopts = "O::g::G:";
1410
1411 enum options
1412   {
1413     OPTION_MARCH = OPTION_MD_BASE,
1414     OPTION_MTUNE,
1415     OPTION_MIPS1,
1416     OPTION_MIPS2,
1417     OPTION_MIPS3,
1418     OPTION_MIPS4,
1419     OPTION_MIPS5,
1420     OPTION_MIPS32,
1421     OPTION_MIPS64,
1422     OPTION_MIPS32R2,
1423     OPTION_MIPS32R3,
1424     OPTION_MIPS32R5,
1425     OPTION_MIPS32R6,
1426     OPTION_MIPS64R2,
1427     OPTION_MIPS64R3,
1428     OPTION_MIPS64R5,
1429     OPTION_MIPS64R6,
1430     OPTION_MIPS16,
1431     OPTION_NO_MIPS16,
1432     OPTION_MIPS3D,
1433     OPTION_NO_MIPS3D,
1434     OPTION_MDMX,
1435     OPTION_NO_MDMX,
1436     OPTION_DSP,
1437     OPTION_NO_DSP,
1438     OPTION_MT,
1439     OPTION_NO_MT,
1440     OPTION_VIRT,
1441     OPTION_NO_VIRT,
1442     OPTION_MSA,
1443     OPTION_NO_MSA,
1444     OPTION_SMARTMIPS,
1445     OPTION_NO_SMARTMIPS,
1446     OPTION_DSPR2,
1447     OPTION_NO_DSPR2,
1448     OPTION_DSPR3,
1449     OPTION_NO_DSPR3,
1450     OPTION_EVA,
1451     OPTION_NO_EVA,
1452     OPTION_XPA,
1453     OPTION_NO_XPA,
1454     OPTION_MICROMIPS,
1455     OPTION_NO_MICROMIPS,
1456     OPTION_MCU,
1457     OPTION_NO_MCU,
1458     OPTION_COMPAT_ARCH_BASE,
1459     OPTION_M4650,
1460     OPTION_NO_M4650,
1461     OPTION_M4010,
1462     OPTION_NO_M4010,
1463     OPTION_M4100,
1464     OPTION_NO_M4100,
1465     OPTION_M3900,
1466     OPTION_NO_M3900,
1467     OPTION_M7000_HILO_FIX,
1468     OPTION_MNO_7000_HILO_FIX,
1469     OPTION_FIX_24K,
1470     OPTION_NO_FIX_24K,
1471     OPTION_FIX_RM7000,
1472     OPTION_NO_FIX_RM7000,
1473     OPTION_FIX_LOONGSON2F_JUMP,
1474     OPTION_NO_FIX_LOONGSON2F_JUMP,
1475     OPTION_FIX_LOONGSON2F_NOP,
1476     OPTION_NO_FIX_LOONGSON2F_NOP,
1477     OPTION_FIX_VR4120,
1478     OPTION_NO_FIX_VR4120,
1479     OPTION_FIX_VR4130,
1480     OPTION_NO_FIX_VR4130,
1481     OPTION_FIX_CN63XXP1,
1482     OPTION_NO_FIX_CN63XXP1,
1483     OPTION_TRAP,
1484     OPTION_BREAK,
1485     OPTION_EB,
1486     OPTION_EL,
1487     OPTION_FP32,
1488     OPTION_GP32,
1489     OPTION_CONSTRUCT_FLOATS,
1490     OPTION_NO_CONSTRUCT_FLOATS,
1491     OPTION_FP64,
1492     OPTION_FPXX,
1493     OPTION_GP64,
1494     OPTION_RELAX_BRANCH,
1495     OPTION_NO_RELAX_BRANCH,
1496     OPTION_IGNORE_BRANCH_ISA,
1497     OPTION_NO_IGNORE_BRANCH_ISA,
1498     OPTION_INSN32,
1499     OPTION_NO_INSN32,
1500     OPTION_MSHARED,
1501     OPTION_MNO_SHARED,
1502     OPTION_MSYM32,
1503     OPTION_MNO_SYM32,
1504     OPTION_SOFT_FLOAT,
1505     OPTION_HARD_FLOAT,
1506     OPTION_SINGLE_FLOAT,
1507     OPTION_DOUBLE_FLOAT,
1508     OPTION_32,
1509     OPTION_CALL_SHARED,
1510     OPTION_CALL_NONPIC,
1511     OPTION_NON_SHARED,
1512     OPTION_XGOT,
1513     OPTION_MABI,
1514     OPTION_N32,
1515     OPTION_64,
1516     OPTION_MDEBUG,
1517     OPTION_NO_MDEBUG,
1518     OPTION_PDR,
1519     OPTION_NO_PDR,
1520     OPTION_MVXWORKS_PIC,
1521     OPTION_NAN,
1522     OPTION_ODD_SPREG,
1523     OPTION_NO_ODD_SPREG,
1524     OPTION_END_OF_ENUM
1525   };
1526
1527 struct option md_longopts[] =
1528 {
1529   /* Options which specify architecture.  */
1530   {"march", required_argument, NULL, OPTION_MARCH},
1531   {"mtune", required_argument, NULL, OPTION_MTUNE},
1532   {"mips0", no_argument, NULL, OPTION_MIPS1},
1533   {"mips1", no_argument, NULL, OPTION_MIPS1},
1534   {"mips2", no_argument, NULL, OPTION_MIPS2},
1535   {"mips3", no_argument, NULL, OPTION_MIPS3},
1536   {"mips4", no_argument, NULL, OPTION_MIPS4},
1537   {"mips5", no_argument, NULL, OPTION_MIPS5},
1538   {"mips32", no_argument, NULL, OPTION_MIPS32},
1539   {"mips64", no_argument, NULL, OPTION_MIPS64},
1540   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1541   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1542   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1543   {"mips32r6", no_argument, NULL, OPTION_MIPS32R6},
1544   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1545   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1546   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1547   {"mips64r6", no_argument, NULL, OPTION_MIPS64R6},
1548
1549   /* Options which specify Application Specific Extensions (ASEs).  */
1550   {"mips16", no_argument, NULL, OPTION_MIPS16},
1551   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1552   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1553   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1554   {"mdmx", no_argument, NULL, OPTION_MDMX},
1555   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1556   {"mdsp", no_argument, NULL, OPTION_DSP},
1557   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1558   {"mmt", no_argument, NULL, OPTION_MT},
1559   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1560   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1561   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1562   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1563   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1564   {"mdspr3", no_argument, NULL, OPTION_DSPR3},
1565   {"mno-dspr3", no_argument, NULL, OPTION_NO_DSPR3},
1566   {"meva", no_argument, NULL, OPTION_EVA},
1567   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1568   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1569   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1570   {"mmcu", no_argument, NULL, OPTION_MCU},
1571   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1572   {"mvirt", no_argument, NULL, OPTION_VIRT},
1573   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1574   {"mmsa", no_argument, NULL, OPTION_MSA},
1575   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1576   {"mxpa", no_argument, NULL, OPTION_XPA},
1577   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1578
1579   /* Old-style architecture options.  Don't add more of these.  */
1580   {"m4650", no_argument, NULL, OPTION_M4650},
1581   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1582   {"m4010", no_argument, NULL, OPTION_M4010},
1583   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1584   {"m4100", no_argument, NULL, OPTION_M4100},
1585   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1586   {"m3900", no_argument, NULL, OPTION_M3900},
1587   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1588
1589   /* Options which enable bug fixes.  */
1590   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1591   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1592   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1593   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1594   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1595   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1596   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1597   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1598   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1599   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1600   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1601   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1602   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1603   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1604   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1605   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1606   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1607
1608   /* Miscellaneous options.  */
1609   {"trap", no_argument, NULL, OPTION_TRAP},
1610   {"no-break", no_argument, NULL, OPTION_TRAP},
1611   {"break", no_argument, NULL, OPTION_BREAK},
1612   {"no-trap", no_argument, NULL, OPTION_BREAK},
1613   {"EB", no_argument, NULL, OPTION_EB},
1614   {"EL", no_argument, NULL, OPTION_EL},
1615   {"mfp32", no_argument, NULL, OPTION_FP32},
1616   {"mgp32", no_argument, NULL, OPTION_GP32},
1617   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1618   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1619   {"mfp64", no_argument, NULL, OPTION_FP64},
1620   {"mfpxx", no_argument, NULL, OPTION_FPXX},
1621   {"mgp64", no_argument, NULL, OPTION_GP64},
1622   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1623   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1624   {"mignore-branch-isa", no_argument, NULL, OPTION_IGNORE_BRANCH_ISA},
1625   {"mno-ignore-branch-isa", no_argument, NULL, OPTION_NO_IGNORE_BRANCH_ISA},
1626   {"minsn32", no_argument, NULL, OPTION_INSN32},
1627   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1628   {"mshared", no_argument, NULL, OPTION_MSHARED},
1629   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1630   {"msym32", no_argument, NULL, OPTION_MSYM32},
1631   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1632   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1633   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1634   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1635   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1636   {"modd-spreg", no_argument, NULL, OPTION_ODD_SPREG},
1637   {"mno-odd-spreg", no_argument, NULL, OPTION_NO_ODD_SPREG},
1638
1639   /* Strictly speaking this next option is ELF specific,
1640      but we allow it for other ports as well in order to
1641      make testing easier.  */
1642   {"32", no_argument, NULL, OPTION_32},
1643
1644   /* ELF-specific options.  */
1645   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1646   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1647   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1648   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1649   {"xgot", no_argument, NULL, OPTION_XGOT},
1650   {"mabi", required_argument, NULL, OPTION_MABI},
1651   {"n32", no_argument, NULL, OPTION_N32},
1652   {"64", no_argument, NULL, OPTION_64},
1653   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1654   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1655   {"mpdr", no_argument, NULL, OPTION_PDR},
1656   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1657   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1658   {"mnan", required_argument, NULL, OPTION_NAN},
1659
1660   {NULL, no_argument, NULL, 0}
1661 };
1662 size_t md_longopts_size = sizeof (md_longopts);
1663 \f
1664 /* Information about either an Application Specific Extension or an
1665    optional architecture feature that, for simplicity, we treat in the
1666    same way as an ASE.  */
1667 struct mips_ase
1668 {
1669   /* The name of the ASE, used in both the command-line and .set options.  */
1670   const char *name;
1671
1672   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1673      and 64-bit architectures, the flags here refer to the subset that
1674      is available on both.  */
1675   unsigned int flags;
1676
1677   /* The ASE_* flag used for instructions that are available on 64-bit
1678      architectures but that are not included in FLAGS.  */
1679   unsigned int flags64;
1680
1681   /* The command-line options that turn the ASE on and off.  */
1682   int option_on;
1683   int option_off;
1684
1685   /* The minimum required architecture revisions for MIPS32, MIPS64,
1686      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1687   int mips32_rev;
1688   int mips64_rev;
1689   int micromips32_rev;
1690   int micromips64_rev;
1691
1692   /* The architecture where the ASE was removed or -1 if the extension has not
1693      been removed.  */
1694   int rem_rev;
1695 };
1696
1697 /* A table of all supported ASEs.  */
1698 static const struct mips_ase mips_ases[] = {
1699   { "dsp", ASE_DSP, ASE_DSP64,
1700     OPTION_DSP, OPTION_NO_DSP,
1701     2, 2, 2, 2,
1702     -1 },
1703
1704   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1705     OPTION_DSPR2, OPTION_NO_DSPR2,
1706     2, 2, 2, 2,
1707     -1 },
1708
1709   { "dspr3", ASE_DSP | ASE_DSPR2 | ASE_DSPR3, 0,
1710     OPTION_DSPR3, OPTION_NO_DSPR3,
1711     6, 6, -1, -1,
1712     -1 },
1713
1714   { "eva", ASE_EVA, 0,
1715     OPTION_EVA, OPTION_NO_EVA,
1716      2,  2,  2,  2,
1717     -1 },
1718
1719   { "mcu", ASE_MCU, 0,
1720     OPTION_MCU, OPTION_NO_MCU,
1721      2,  2,  2,  2,
1722     -1 },
1723
1724   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1725   { "mdmx", ASE_MDMX, 0,
1726     OPTION_MDMX, OPTION_NO_MDMX,
1727     -1, 1, -1, -1,
1728      6 },
1729
1730   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1731   { "mips3d", ASE_MIPS3D, 0,
1732     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1733     2, 1, -1, -1,
1734     6 },
1735
1736   { "mt", ASE_MT, 0,
1737     OPTION_MT, OPTION_NO_MT,
1738      2,  2, -1, -1,
1739     -1 },
1740
1741   { "smartmips", ASE_SMARTMIPS, 0,
1742     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1743     1, -1, -1, -1,
1744     6 },
1745
1746   { "virt", ASE_VIRT, ASE_VIRT64,
1747     OPTION_VIRT, OPTION_NO_VIRT,
1748      2,  2,  2,  2,
1749     -1 },
1750
1751   { "msa", ASE_MSA, ASE_MSA64,
1752     OPTION_MSA, OPTION_NO_MSA,
1753      2,  2,  2,  2,
1754     -1 },
1755
1756   { "xpa", ASE_XPA, 0,
1757     OPTION_XPA, OPTION_NO_XPA,
1758      2,  2, -1, -1,
1759     -1 },
1760 };
1761
1762 /* The set of ASEs that require -mfp64.  */
1763 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1764
1765 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1766 static const unsigned int mips_ase_groups[] = {
1767   ASE_DSP | ASE_DSPR2 | ASE_DSPR3
1768 };
1769 \f
1770 /* Pseudo-op table.
1771
1772    The following pseudo-ops from the Kane and Heinrich MIPS book
1773    should be defined here, but are currently unsupported: .alias,
1774    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1775
1776    The following pseudo-ops from the Kane and Heinrich MIPS book are
1777    specific to the type of debugging information being generated, and
1778    should be defined by the object format: .aent, .begin, .bend,
1779    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1780    .vreg.
1781
1782    The following pseudo-ops from the Kane and Heinrich MIPS book are
1783    not MIPS CPU specific, but are also not specific to the object file
1784    format.  This file is probably the best place to define them, but
1785    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1786
1787 static const pseudo_typeS mips_pseudo_table[] =
1788 {
1789   /* MIPS specific pseudo-ops.  */
1790   {"option", s_option, 0},
1791   {"set", s_mipsset, 0},
1792   {"rdata", s_change_sec, 'r'},
1793   {"sdata", s_change_sec, 's'},
1794   {"livereg", s_ignore, 0},
1795   {"abicalls", s_abicalls, 0},
1796   {"cpload", s_cpload, 0},
1797   {"cpsetup", s_cpsetup, 0},
1798   {"cplocal", s_cplocal, 0},
1799   {"cprestore", s_cprestore, 0},
1800   {"cpreturn", s_cpreturn, 0},
1801   {"dtprelword", s_dtprelword, 0},
1802   {"dtpreldword", s_dtpreldword, 0},
1803   {"tprelword", s_tprelword, 0},
1804   {"tpreldword", s_tpreldword, 0},
1805   {"gpvalue", s_gpvalue, 0},
1806   {"gpword", s_gpword, 0},
1807   {"gpdword", s_gpdword, 0},
1808   {"ehword", s_ehword, 0},
1809   {"cpadd", s_cpadd, 0},
1810   {"insn", s_insn, 0},
1811   {"nan", s_nan, 0},
1812   {"module", s_module, 0},
1813
1814   /* Relatively generic pseudo-ops that happen to be used on MIPS
1815      chips.  */
1816   {"asciiz", stringer, 8 + 1},
1817   {"bss", s_change_sec, 'b'},
1818   {"err", s_err, 0},
1819   {"half", s_cons, 1},
1820   {"dword", s_cons, 3},
1821   {"weakext", s_mips_weakext, 0},
1822   {"origin", s_org, 0},
1823   {"repeat", s_rept, 0},
1824
1825   /* For MIPS this is non-standard, but we define it for consistency.  */
1826   {"sbss", s_change_sec, 'B'},
1827
1828   /* These pseudo-ops are defined in read.c, but must be overridden
1829      here for one reason or another.  */
1830   {"align", s_align, 0},
1831   {"byte", s_cons, 0},
1832   {"data", s_change_sec, 'd'},
1833   {"double", s_float_cons, 'd'},
1834   {"float", s_float_cons, 'f'},
1835   {"globl", s_mips_globl, 0},
1836   {"global", s_mips_globl, 0},
1837   {"hword", s_cons, 1},
1838   {"int", s_cons, 2},
1839   {"long", s_cons, 2},
1840   {"octa", s_cons, 4},
1841   {"quad", s_cons, 3},
1842   {"section", s_change_section, 0},
1843   {"short", s_cons, 1},
1844   {"single", s_float_cons, 'f'},
1845   {"stabd", s_mips_stab, 'd'},
1846   {"stabn", s_mips_stab, 'n'},
1847   {"stabs", s_mips_stab, 's'},
1848   {"text", s_change_sec, 't'},
1849   {"word", s_cons, 2},
1850
1851   { "extern", ecoff_directive_extern, 0},
1852
1853   { NULL, NULL, 0 },
1854 };
1855
1856 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1857 {
1858   /* These pseudo-ops should be defined by the object file format.
1859      However, a.out doesn't support them, so we have versions here.  */
1860   {"aent", s_mips_ent, 1},
1861   {"bgnb", s_ignore, 0},
1862   {"end", s_mips_end, 0},
1863   {"endb", s_ignore, 0},
1864   {"ent", s_mips_ent, 0},
1865   {"file", s_mips_file, 0},
1866   {"fmask", s_mips_mask, 'F'},
1867   {"frame", s_mips_frame, 0},
1868   {"loc", s_mips_loc, 0},
1869   {"mask", s_mips_mask, 'R'},
1870   {"verstamp", s_ignore, 0},
1871   { NULL, NULL, 0 },
1872 };
1873
1874 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1875    purpose of the `.dc.a' internal pseudo-op.  */
1876
1877 int
1878 mips_address_bytes (void)
1879 {
1880   file_mips_check_options ();
1881   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1882 }
1883
1884 extern void pop_insert (const pseudo_typeS *);
1885
1886 void
1887 mips_pop_insert (void)
1888 {
1889   pop_insert (mips_pseudo_table);
1890   if (! ECOFF_DEBUGGING)
1891     pop_insert (mips_nonecoff_pseudo_table);
1892 }
1893 \f
1894 /* Symbols labelling the current insn.  */
1895
1896 struct insn_label_list
1897 {
1898   struct insn_label_list *next;
1899   symbolS *label;
1900 };
1901
1902 static struct insn_label_list *free_insn_labels;
1903 #define label_list tc_segment_info_data.labels
1904
1905 static void mips_clear_insn_labels (void);
1906 static void mips_mark_labels (void);
1907 static void mips_compressed_mark_labels (void);
1908
1909 static inline void
1910 mips_clear_insn_labels (void)
1911 {
1912   struct insn_label_list **pl;
1913   segment_info_type *si;
1914
1915   if (now_seg)
1916     {
1917       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1918         ;
1919
1920       si = seg_info (now_seg);
1921       *pl = si->label_list;
1922       si->label_list = NULL;
1923     }
1924 }
1925
1926 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1927
1928 static inline void
1929 mips_mark_labels (void)
1930 {
1931   if (HAVE_CODE_COMPRESSION)
1932     mips_compressed_mark_labels ();
1933 }
1934 \f
1935 static char *expr_end;
1936
1937 /* An expression in a macro instruction.  This is set by mips_ip and
1938    mips16_ip and when populated is always an O_constant.  */
1939
1940 static expressionS imm_expr;
1941
1942 /* The relocatable field in an instruction and the relocs associated
1943    with it.  These variables are used for instructions like LUI and
1944    JAL as well as true offsets.  They are also used for address
1945    operands in macros.  */
1946
1947 static expressionS offset_expr;
1948 static bfd_reloc_code_real_type offset_reloc[3]
1949   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1950
1951 /* This is set to the resulting size of the instruction to be produced
1952    by mips16_ip if an explicit extension is used or by mips_ip if an
1953    explicit size is supplied.  */
1954
1955 static unsigned int forced_insn_length;
1956
1957 /* True if we are assembling an instruction.  All dot symbols defined during
1958    this time should be treated as code labels.  */
1959
1960 static bfd_boolean mips_assembling_insn;
1961
1962 /* The pdr segment for per procedure frame/regmask info.  Not used for
1963    ECOFF debugging.  */
1964
1965 static segT pdr_seg;
1966
1967 /* The default target format to use.  */
1968
1969 #if defined (TE_FreeBSD)
1970 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1971 #elif defined (TE_TMIPS)
1972 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1973 #else
1974 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1975 #endif
1976
1977 const char *
1978 mips_target_format (void)
1979 {
1980   switch (OUTPUT_FLAVOR)
1981     {
1982     case bfd_target_elf_flavour:
1983 #ifdef TE_VXWORKS
1984       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1985         return (target_big_endian
1986                 ? "elf32-bigmips-vxworks"
1987                 : "elf32-littlemips-vxworks");
1988 #endif
1989       return (target_big_endian
1990               ? (HAVE_64BIT_OBJECTS
1991                  ? ELF_TARGET ("elf64-", "big")
1992                  : (HAVE_NEWABI
1993                     ? ELF_TARGET ("elf32-n", "big")
1994                     : ELF_TARGET ("elf32-", "big")))
1995               : (HAVE_64BIT_OBJECTS
1996                  ? ELF_TARGET ("elf64-", "little")
1997                  : (HAVE_NEWABI
1998                     ? ELF_TARGET ("elf32-n", "little")
1999                     : ELF_TARGET ("elf32-", "little"))));
2000     default:
2001       abort ();
2002       return NULL;
2003     }
2004 }
2005
2006 /* Return the ISA revision that is currently in use, or 0 if we are
2007    generating code for MIPS V or below.  */
2008
2009 static int
2010 mips_isa_rev (void)
2011 {
2012   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
2013     return 2;
2014
2015   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
2016     return 3;
2017
2018   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
2019     return 5;
2020
2021   if (mips_opts.isa == ISA_MIPS32R6 || mips_opts.isa == ISA_MIPS64R6)
2022     return 6;
2023
2024   /* microMIPS implies revision 2 or above.  */
2025   if (mips_opts.micromips)
2026     return 2;
2027
2028   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
2029     return 1;
2030
2031   return 0;
2032 }
2033
2034 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
2035
2036 static unsigned int
2037 mips_ase_mask (unsigned int flags)
2038 {
2039   unsigned int i;
2040
2041   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
2042     if (flags & mips_ase_groups[i])
2043       flags |= mips_ase_groups[i];
2044   return flags;
2045 }
2046
2047 /* Check whether the current ISA supports ASE.  Issue a warning if
2048    appropriate.  */
2049
2050 static void
2051 mips_check_isa_supports_ase (const struct mips_ase *ase)
2052 {
2053   const char *base;
2054   int min_rev, size;
2055   static unsigned int warned_isa;
2056   static unsigned int warned_fp32;
2057
2058   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2059     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
2060   else
2061     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
2062   if ((min_rev < 0 || mips_isa_rev () < min_rev)
2063       && (warned_isa & ase->flags) != ase->flags)
2064     {
2065       warned_isa |= ase->flags;
2066       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2067       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2068       if (min_rev < 0)
2069         as_warn (_("the %d-bit %s architecture does not support the"
2070                    " `%s' extension"), size, base, ase->name);
2071       else
2072         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
2073                  ase->name, base, size, min_rev);
2074     }
2075   else if ((ase->rem_rev > 0 && mips_isa_rev () >= ase->rem_rev)
2076            && (warned_isa & ase->flags) != ase->flags)
2077     {
2078       warned_isa |= ase->flags;
2079       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2080       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2081       as_warn (_("the `%s' extension was removed in %s%d revision %d"),
2082                ase->name, base, size, ase->rem_rev);
2083     }
2084
2085   if ((ase->flags & FP64_ASES)
2086       && mips_opts.fp != 64
2087       && (warned_fp32 & ase->flags) != ase->flags)
2088     {
2089       warned_fp32 |= ase->flags;
2090       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
2091     }
2092 }
2093
2094 /* Check all enabled ASEs to see whether they are supported by the
2095    chosen architecture.  */
2096
2097 static void
2098 mips_check_isa_supports_ases (void)
2099 {
2100   unsigned int i, mask;
2101
2102   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2103     {
2104       mask = mips_ase_mask (mips_ases[i].flags);
2105       if ((mips_opts.ase & mask) == mips_ases[i].flags)
2106         mips_check_isa_supports_ase (&mips_ases[i]);
2107     }
2108 }
2109
2110 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
2111    that were affected.  */
2112
2113 static unsigned int
2114 mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
2115               bfd_boolean enabled_p)
2116 {
2117   unsigned int mask;
2118
2119   mask = mips_ase_mask (ase->flags);
2120   opts->ase &= ~mask;
2121   if (enabled_p)
2122     opts->ase |= ase->flags;
2123   return mask;
2124 }
2125
2126 /* Return the ASE called NAME, or null if none.  */
2127
2128 static const struct mips_ase *
2129 mips_lookup_ase (const char *name)
2130 {
2131   unsigned int i;
2132
2133   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2134     if (strcmp (name, mips_ases[i].name) == 0)
2135       return &mips_ases[i];
2136   return NULL;
2137 }
2138
2139 /* Return the length of a microMIPS instruction in bytes.  If bits of
2140    the mask beyond the low 16 are 0, then it is a 16-bit instruction,
2141    otherwise it is a 32-bit instruction.  */
2142
2143 static inline unsigned int
2144 micromips_insn_length (const struct mips_opcode *mo)
2145 {
2146   return mips_opcode_32bit_p (mo) ? 4 : 2;
2147 }
2148
2149 /* Return the length of MIPS16 instruction OPCODE.  */
2150
2151 static inline unsigned int
2152 mips16_opcode_length (unsigned long opcode)
2153 {
2154   return (opcode >> 16) == 0 ? 2 : 4;
2155 }
2156
2157 /* Return the length of instruction INSN.  */
2158
2159 static inline unsigned int
2160 insn_length (const struct mips_cl_insn *insn)
2161 {
2162   if (mips_opts.micromips)
2163     return micromips_insn_length (insn->insn_mo);
2164   else if (mips_opts.mips16)
2165     return mips16_opcode_length (insn->insn_opcode);
2166   else
2167     return 4;
2168 }
2169
2170 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2171
2172 static void
2173 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2174 {
2175   size_t i;
2176
2177   insn->insn_mo = mo;
2178   insn->insn_opcode = mo->match;
2179   insn->frag = NULL;
2180   insn->where = 0;
2181   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2182     insn->fixp[i] = NULL;
2183   insn->fixed_p = (mips_opts.noreorder > 0);
2184   insn->noreorder_p = (mips_opts.noreorder > 0);
2185   insn->mips16_absolute_jump_p = 0;
2186   insn->complete_p = 0;
2187   insn->cleared_p = 0;
2188 }
2189
2190 /* Get a list of all the operands in INSN.  */
2191
2192 static const struct mips_operand_array *
2193 insn_operands (const struct mips_cl_insn *insn)
2194 {
2195   if (insn->insn_mo >= &mips_opcodes[0]
2196       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2197     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2198
2199   if (insn->insn_mo >= &mips16_opcodes[0]
2200       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2201     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2202
2203   if (insn->insn_mo >= &micromips_opcodes[0]
2204       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2205     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2206
2207   abort ();
2208 }
2209
2210 /* Get a description of operand OPNO of INSN.  */
2211
2212 static const struct mips_operand *
2213 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2214 {
2215   const struct mips_operand_array *operands;
2216
2217   operands = insn_operands (insn);
2218   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2219     abort ();
2220   return operands->operand[opno];
2221 }
2222
2223 /* Install UVAL as the value of OPERAND in INSN.  */
2224
2225 static inline void
2226 insn_insert_operand (struct mips_cl_insn *insn,
2227                      const struct mips_operand *operand, unsigned int uval)
2228 {
2229   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2230 }
2231
2232 /* Extract the value of OPERAND from INSN.  */
2233
2234 static inline unsigned
2235 insn_extract_operand (const struct mips_cl_insn *insn,
2236                       const struct mips_operand *operand)
2237 {
2238   return mips_extract_operand (operand, insn->insn_opcode);
2239 }
2240
2241 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2242
2243 static void
2244 mips_record_compressed_mode (void)
2245 {
2246   segment_info_type *si;
2247
2248   si = seg_info (now_seg);
2249   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2250     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2251   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2252     si->tc_segment_info_data.micromips = mips_opts.micromips;
2253 }
2254
2255 /* Read a standard MIPS instruction from BUF.  */
2256
2257 static unsigned long
2258 read_insn (char *buf)
2259 {
2260   if (target_big_endian)
2261     return bfd_getb32 ((bfd_byte *) buf);
2262   else
2263     return bfd_getl32 ((bfd_byte *) buf);
2264 }
2265
2266 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2267    the next byte.  */
2268
2269 static char *
2270 write_insn (char *buf, unsigned int insn)
2271 {
2272   md_number_to_chars (buf, insn, 4);
2273   return buf + 4;
2274 }
2275
2276 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2277    has length LENGTH.  */
2278
2279 static unsigned long
2280 read_compressed_insn (char *buf, unsigned int length)
2281 {
2282   unsigned long insn;
2283   unsigned int i;
2284
2285   insn = 0;
2286   for (i = 0; i < length; i += 2)
2287     {
2288       insn <<= 16;
2289       if (target_big_endian)
2290         insn |= bfd_getb16 ((char *) buf);
2291       else
2292         insn |= bfd_getl16 ((char *) buf);
2293       buf += 2;
2294     }
2295   return insn;
2296 }
2297
2298 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2299    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2300
2301 static char *
2302 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2303 {
2304   unsigned int i;
2305
2306   for (i = 0; i < length; i += 2)
2307     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2308   return buf + length;
2309 }
2310
2311 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2312
2313 static void
2314 install_insn (const struct mips_cl_insn *insn)
2315 {
2316   char *f = insn->frag->fr_literal + insn->where;
2317   if (HAVE_CODE_COMPRESSION)
2318     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2319   else
2320     write_insn (f, insn->insn_opcode);
2321   mips_record_compressed_mode ();
2322 }
2323
2324 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2325    and install the opcode in the new location.  */
2326
2327 static void
2328 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2329 {
2330   size_t i;
2331
2332   insn->frag = frag;
2333   insn->where = where;
2334   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2335     if (insn->fixp[i] != NULL)
2336       {
2337         insn->fixp[i]->fx_frag = frag;
2338         insn->fixp[i]->fx_where = where;
2339       }
2340   install_insn (insn);
2341 }
2342
2343 /* Add INSN to the end of the output.  */
2344
2345 static void
2346 add_fixed_insn (struct mips_cl_insn *insn)
2347 {
2348   char *f = frag_more (insn_length (insn));
2349   move_insn (insn, frag_now, f - frag_now->fr_literal);
2350 }
2351
2352 /* Start a variant frag and move INSN to the start of the variant part,
2353    marking it as fixed.  The other arguments are as for frag_var.  */
2354
2355 static void
2356 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2357                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2358 {
2359   frag_grow (max_chars);
2360   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2361   insn->fixed_p = 1;
2362   frag_var (rs_machine_dependent, max_chars, var,
2363             subtype, symbol, offset, NULL);
2364 }
2365
2366 /* Insert N copies of INSN into the history buffer, starting at
2367    position FIRST.  Neither FIRST nor N need to be clipped.  */
2368
2369 static void
2370 insert_into_history (unsigned int first, unsigned int n,
2371                      const struct mips_cl_insn *insn)
2372 {
2373   if (mips_relax.sequence != 2)
2374     {
2375       unsigned int i;
2376
2377       for (i = ARRAY_SIZE (history); i-- > first;)
2378         if (i >= first + n)
2379           history[i] = history[i - n];
2380         else
2381           history[i] = *insn;
2382     }
2383 }
2384
2385 /* Clear the error in insn_error.  */
2386
2387 static void
2388 clear_insn_error (void)
2389 {
2390   memset (&insn_error, 0, sizeof (insn_error));
2391 }
2392
2393 /* Possibly record error message MSG for the current instruction.
2394    If the error is about a particular argument, ARGNUM is the 1-based
2395    number of that argument, otherwise it is 0.  FORMAT is the format
2396    of MSG.  Return true if MSG was used, false if the current message
2397    was kept.  */
2398
2399 static bfd_boolean
2400 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2401                        const char *msg)
2402 {
2403   if (argnum == 0)
2404     {
2405       /* Give priority to errors against specific arguments, and to
2406          the first whole-instruction message.  */
2407       if (insn_error.msg)
2408         return FALSE;
2409     }
2410   else
2411     {
2412       /* Keep insn_error if it is against a later argument.  */
2413       if (argnum < insn_error.min_argnum)
2414         return FALSE;
2415
2416       /* If both errors are against the same argument but are different,
2417          give up on reporting a specific error for this argument.
2418          See the comment about mips_insn_error for details.  */
2419       if (argnum == insn_error.min_argnum
2420           && insn_error.msg
2421           && strcmp (insn_error.msg, msg) != 0)
2422         {
2423           insn_error.msg = 0;
2424           insn_error.min_argnum += 1;
2425           return FALSE;
2426         }
2427     }
2428   insn_error.min_argnum = argnum;
2429   insn_error.format = format;
2430   insn_error.msg = msg;
2431   return TRUE;
2432 }
2433
2434 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2435    as for set_insn_error_format.  */
2436
2437 static void
2438 set_insn_error (int argnum, const char *msg)
2439 {
2440   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2441 }
2442
2443 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2444    as for set_insn_error_format.  */
2445
2446 static void
2447 set_insn_error_i (int argnum, const char *msg, int i)
2448 {
2449   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2450     insn_error.u.i = i;
2451 }
2452
2453 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2454    are as for set_insn_error_format.  */
2455
2456 static void
2457 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2458 {
2459   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2460     {
2461       insn_error.u.ss[0] = s1;
2462       insn_error.u.ss[1] = s2;
2463     }
2464 }
2465
2466 /* Report the error in insn_error, which is against assembly code STR.  */
2467
2468 static void
2469 report_insn_error (const char *str)
2470 {
2471   const char *msg = concat (insn_error.msg, " `%s'", NULL);
2472
2473   switch (insn_error.format)
2474     {
2475     case ERR_FMT_PLAIN:
2476       as_bad (msg, str);
2477       break;
2478
2479     case ERR_FMT_I:
2480       as_bad (msg, insn_error.u.i, str);
2481       break;
2482
2483     case ERR_FMT_SS:
2484       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2485       break;
2486     }
2487
2488   free ((char *) msg);
2489 }
2490
2491 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2492    the idea is to make it obvious at a glance that each errata is
2493    included.  */
2494
2495 static void
2496 init_vr4120_conflicts (void)
2497 {
2498 #define CONFLICT(FIRST, SECOND) \
2499     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2500
2501   /* Errata 21 - [D]DIV[U] after [D]MACC */
2502   CONFLICT (MACC, DIV);
2503   CONFLICT (DMACC, DIV);
2504
2505   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2506   CONFLICT (DMULT, DMULT);
2507   CONFLICT (DMULT, DMACC);
2508   CONFLICT (DMACC, DMULT);
2509   CONFLICT (DMACC, DMACC);
2510
2511   /* Errata 24 - MT{LO,HI} after [D]MACC */
2512   CONFLICT (MACC, MTHILO);
2513   CONFLICT (DMACC, MTHILO);
2514
2515   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2516      instruction is executed immediately after a MACC or DMACC
2517      instruction, the result of [either instruction] is incorrect."  */
2518   CONFLICT (MACC, MULT);
2519   CONFLICT (MACC, DMULT);
2520   CONFLICT (DMACC, MULT);
2521   CONFLICT (DMACC, DMULT);
2522
2523   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2524      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2525      DDIV or DDIVU instruction, the result of the MACC or
2526      DMACC instruction is incorrect.".  */
2527   CONFLICT (DMULT, MACC);
2528   CONFLICT (DMULT, DMACC);
2529   CONFLICT (DIV, MACC);
2530   CONFLICT (DIV, DMACC);
2531
2532 #undef CONFLICT
2533 }
2534
2535 struct regname {
2536   const char *name;
2537   unsigned int num;
2538 };
2539
2540 #define RNUM_MASK       0x00000ff
2541 #define RTYPE_MASK      0x0ffff00
2542 #define RTYPE_NUM       0x0000100
2543 #define RTYPE_FPU       0x0000200
2544 #define RTYPE_FCC       0x0000400
2545 #define RTYPE_VEC       0x0000800
2546 #define RTYPE_GP        0x0001000
2547 #define RTYPE_CP0       0x0002000
2548 #define RTYPE_PC        0x0004000
2549 #define RTYPE_ACC       0x0008000
2550 #define RTYPE_CCC       0x0010000
2551 #define RTYPE_VI        0x0020000
2552 #define RTYPE_VF        0x0040000
2553 #define RTYPE_R5900_I   0x0080000
2554 #define RTYPE_R5900_Q   0x0100000
2555 #define RTYPE_R5900_R   0x0200000
2556 #define RTYPE_R5900_ACC 0x0400000
2557 #define RTYPE_MSA       0x0800000
2558 #define RWARN           0x8000000
2559
2560 #define GENERIC_REGISTER_NUMBERS \
2561     {"$0",      RTYPE_NUM | 0},  \
2562     {"$1",      RTYPE_NUM | 1},  \
2563     {"$2",      RTYPE_NUM | 2},  \
2564     {"$3",      RTYPE_NUM | 3},  \
2565     {"$4",      RTYPE_NUM | 4},  \
2566     {"$5",      RTYPE_NUM | 5},  \
2567     {"$6",      RTYPE_NUM | 6},  \
2568     {"$7",      RTYPE_NUM | 7},  \
2569     {"$8",      RTYPE_NUM | 8},  \
2570     {"$9",      RTYPE_NUM | 9},  \
2571     {"$10",     RTYPE_NUM | 10}, \
2572     {"$11",     RTYPE_NUM | 11}, \
2573     {"$12",     RTYPE_NUM | 12}, \
2574     {"$13",     RTYPE_NUM | 13}, \
2575     {"$14",     RTYPE_NUM | 14}, \
2576     {"$15",     RTYPE_NUM | 15}, \
2577     {"$16",     RTYPE_NUM | 16}, \
2578     {"$17",     RTYPE_NUM | 17}, \
2579     {"$18",     RTYPE_NUM | 18}, \
2580     {"$19",     RTYPE_NUM | 19}, \
2581     {"$20",     RTYPE_NUM | 20}, \
2582     {"$21",     RTYPE_NUM | 21}, \
2583     {"$22",     RTYPE_NUM | 22}, \
2584     {"$23",     RTYPE_NUM | 23}, \
2585     {"$24",     RTYPE_NUM | 24}, \
2586     {"$25",     RTYPE_NUM | 25}, \
2587     {"$26",     RTYPE_NUM | 26}, \
2588     {"$27",     RTYPE_NUM | 27}, \
2589     {"$28",     RTYPE_NUM | 28}, \
2590     {"$29",     RTYPE_NUM | 29}, \
2591     {"$30",     RTYPE_NUM | 30}, \
2592     {"$31",     RTYPE_NUM | 31}
2593
2594 #define FPU_REGISTER_NAMES       \
2595     {"$f0",     RTYPE_FPU | 0},  \
2596     {"$f1",     RTYPE_FPU | 1},  \
2597     {"$f2",     RTYPE_FPU | 2},  \
2598     {"$f3",     RTYPE_FPU | 3},  \
2599     {"$f4",     RTYPE_FPU | 4},  \
2600     {"$f5",     RTYPE_FPU | 5},  \
2601     {"$f6",     RTYPE_FPU | 6},  \
2602     {"$f7",     RTYPE_FPU | 7},  \
2603     {"$f8",     RTYPE_FPU | 8},  \
2604     {"$f9",     RTYPE_FPU | 9},  \
2605     {"$f10",    RTYPE_FPU | 10}, \
2606     {"$f11",    RTYPE_FPU | 11}, \
2607     {"$f12",    RTYPE_FPU | 12}, \
2608     {"$f13",    RTYPE_FPU | 13}, \
2609     {"$f14",    RTYPE_FPU | 14}, \
2610     {"$f15",    RTYPE_FPU | 15}, \
2611     {"$f16",    RTYPE_FPU | 16}, \
2612     {"$f17",    RTYPE_FPU | 17}, \
2613     {"$f18",    RTYPE_FPU | 18}, \
2614     {"$f19",    RTYPE_FPU | 19}, \
2615     {"$f20",    RTYPE_FPU | 20}, \
2616     {"$f21",    RTYPE_FPU | 21}, \
2617     {"$f22",    RTYPE_FPU | 22}, \
2618     {"$f23",    RTYPE_FPU | 23}, \
2619     {"$f24",    RTYPE_FPU | 24}, \
2620     {"$f25",    RTYPE_FPU | 25}, \
2621     {"$f26",    RTYPE_FPU | 26}, \
2622     {"$f27",    RTYPE_FPU | 27}, \
2623     {"$f28",    RTYPE_FPU | 28}, \
2624     {"$f29",    RTYPE_FPU | 29}, \
2625     {"$f30",    RTYPE_FPU | 30}, \
2626     {"$f31",    RTYPE_FPU | 31}
2627
2628 #define FPU_CONDITION_CODE_NAMES \
2629     {"$fcc0",   RTYPE_FCC | 0},  \
2630     {"$fcc1",   RTYPE_FCC | 1},  \
2631     {"$fcc2",   RTYPE_FCC | 2},  \
2632     {"$fcc3",   RTYPE_FCC | 3},  \
2633     {"$fcc4",   RTYPE_FCC | 4},  \
2634     {"$fcc5",   RTYPE_FCC | 5},  \
2635     {"$fcc6",   RTYPE_FCC | 6},  \
2636     {"$fcc7",   RTYPE_FCC | 7}
2637
2638 #define COPROC_CONDITION_CODE_NAMES         \
2639     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2640     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2641     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2642     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2643     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2644     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2645     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2646     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2647
2648 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2649     {"$a4",     RTYPE_GP | 8},  \
2650     {"$a5",     RTYPE_GP | 9},  \
2651     {"$a6",     RTYPE_GP | 10}, \
2652     {"$a7",     RTYPE_GP | 11}, \
2653     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2654     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2655     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2656     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2657     {"$t0",     RTYPE_GP | 12}, \
2658     {"$t1",     RTYPE_GP | 13}, \
2659     {"$t2",     RTYPE_GP | 14}, \
2660     {"$t3",     RTYPE_GP | 15}
2661
2662 #define O32_SYMBOLIC_REGISTER_NAMES \
2663     {"$t0",     RTYPE_GP | 8},  \
2664     {"$t1",     RTYPE_GP | 9},  \
2665     {"$t2",     RTYPE_GP | 10}, \
2666     {"$t3",     RTYPE_GP | 11}, \
2667     {"$t4",     RTYPE_GP | 12}, \
2668     {"$t5",     RTYPE_GP | 13}, \
2669     {"$t6",     RTYPE_GP | 14}, \
2670     {"$t7",     RTYPE_GP | 15}, \
2671     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2672     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2673     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2674     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */
2675
2676 /* Remaining symbolic register names */
2677 #define SYMBOLIC_REGISTER_NAMES \
2678     {"$zero",   RTYPE_GP | 0},  \
2679     {"$at",     RTYPE_GP | 1},  \
2680     {"$AT",     RTYPE_GP | 1},  \
2681     {"$v0",     RTYPE_GP | 2},  \
2682     {"$v1",     RTYPE_GP | 3},  \
2683     {"$a0",     RTYPE_GP | 4},  \
2684     {"$a1",     RTYPE_GP | 5},  \
2685     {"$a2",     RTYPE_GP | 6},  \
2686     {"$a3",     RTYPE_GP | 7},  \
2687     {"$s0",     RTYPE_GP | 16}, \
2688     {"$s1",     RTYPE_GP | 17}, \
2689     {"$s2",     RTYPE_GP | 18}, \
2690     {"$s3",     RTYPE_GP | 19}, \
2691     {"$s4",     RTYPE_GP | 20}, \
2692     {"$s5",     RTYPE_GP | 21}, \
2693     {"$s6",     RTYPE_GP | 22}, \
2694     {"$s7",     RTYPE_GP | 23}, \
2695     {"$t8",     RTYPE_GP | 24}, \
2696     {"$t9",     RTYPE_GP | 25}, \
2697     {"$k0",     RTYPE_GP | 26}, \
2698     {"$kt0",    RTYPE_GP | 26}, \
2699     {"$k1",     RTYPE_GP | 27}, \
2700     {"$kt1",    RTYPE_GP | 27}, \
2701     {"$gp",     RTYPE_GP | 28}, \
2702     {"$sp",     RTYPE_GP | 29}, \
2703     {"$s8",     RTYPE_GP | 30}, \
2704     {"$fp",     RTYPE_GP | 30}, \
2705     {"$ra",     RTYPE_GP | 31}
2706
2707 #define MIPS16_SPECIAL_REGISTER_NAMES \
2708     {"$pc",     RTYPE_PC | 0}
2709
2710 #define MDMX_VECTOR_REGISTER_NAMES \
2711     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2712     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2713     {"$v2",     RTYPE_VEC | 2},  \
2714     {"$v3",     RTYPE_VEC | 3},  \
2715     {"$v4",     RTYPE_VEC | 4},  \
2716     {"$v5",     RTYPE_VEC | 5},  \
2717     {"$v6",     RTYPE_VEC | 6},  \
2718     {"$v7",     RTYPE_VEC | 7},  \
2719     {"$v8",     RTYPE_VEC | 8},  \
2720     {"$v9",     RTYPE_VEC | 9},  \
2721     {"$v10",    RTYPE_VEC | 10}, \
2722     {"$v11",    RTYPE_VEC | 11}, \
2723     {"$v12",    RTYPE_VEC | 12}, \
2724     {"$v13",    RTYPE_VEC | 13}, \
2725     {"$v14",    RTYPE_VEC | 14}, \
2726     {"$v15",    RTYPE_VEC | 15}, \
2727     {"$v16",    RTYPE_VEC | 16}, \
2728     {"$v17",    RTYPE_VEC | 17}, \
2729     {"$v18",    RTYPE_VEC | 18}, \
2730     {"$v19",    RTYPE_VEC | 19}, \
2731     {"$v20",    RTYPE_VEC | 20}, \
2732     {"$v21",    RTYPE_VEC | 21}, \
2733     {"$v22",    RTYPE_VEC | 22}, \
2734     {"$v23",    RTYPE_VEC | 23}, \
2735     {"$v24",    RTYPE_VEC | 24}, \
2736     {"$v25",    RTYPE_VEC | 25}, \
2737     {"$v26",    RTYPE_VEC | 26}, \
2738     {"$v27",    RTYPE_VEC | 27}, \
2739     {"$v28",    RTYPE_VEC | 28}, \
2740     {"$v29",    RTYPE_VEC | 29}, \
2741     {"$v30",    RTYPE_VEC | 30}, \
2742     {"$v31",    RTYPE_VEC | 31}
2743
2744 #define R5900_I_NAMES \
2745     {"$I",      RTYPE_R5900_I | 0}
2746
2747 #define R5900_Q_NAMES \
2748     {"$Q",      RTYPE_R5900_Q | 0}
2749
2750 #define R5900_R_NAMES \
2751     {"$R",      RTYPE_R5900_R | 0}
2752
2753 #define R5900_ACC_NAMES \
2754     {"$ACC",    RTYPE_R5900_ACC | 0 }
2755
2756 #define MIPS_DSP_ACCUMULATOR_NAMES \
2757     {"$ac0",    RTYPE_ACC | 0}, \
2758     {"$ac1",    RTYPE_ACC | 1}, \
2759     {"$ac2",    RTYPE_ACC | 2}, \
2760     {"$ac3",    RTYPE_ACC | 3}
2761
2762 static const struct regname reg_names[] = {
2763   GENERIC_REGISTER_NUMBERS,
2764   FPU_REGISTER_NAMES,
2765   FPU_CONDITION_CODE_NAMES,
2766   COPROC_CONDITION_CODE_NAMES,
2767
2768   /* The $txx registers depends on the abi,
2769      these will be added later into the symbol table from
2770      one of the tables below once mips_abi is set after
2771      parsing of arguments from the command line. */
2772   SYMBOLIC_REGISTER_NAMES,
2773
2774   MIPS16_SPECIAL_REGISTER_NAMES,
2775   MDMX_VECTOR_REGISTER_NAMES,
2776   R5900_I_NAMES,
2777   R5900_Q_NAMES,
2778   R5900_R_NAMES,
2779   R5900_ACC_NAMES,
2780   MIPS_DSP_ACCUMULATOR_NAMES,
2781   {0, 0}
2782 };
2783
2784 static const struct regname reg_names_o32[] = {
2785   O32_SYMBOLIC_REGISTER_NAMES,
2786   {0, 0}
2787 };
2788
2789 static const struct regname reg_names_n32n64[] = {
2790   N32N64_SYMBOLIC_REGISTER_NAMES,
2791   {0, 0}
2792 };
2793
2794 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2795    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2796    of these register symbols, return the associated vector register,
2797    otherwise return SYMVAL itself.  */
2798
2799 static unsigned int
2800 mips_prefer_vec_regno (unsigned int symval)
2801 {
2802   if ((symval & -2) == (RTYPE_GP | 2))
2803     return RTYPE_VEC | (symval & 1);
2804   return symval;
2805 }
2806
2807 /* Return true if string [S, E) is a valid register name, storing its
2808    symbol value in *SYMVAL_PTR if so.  */
2809
2810 static bfd_boolean
2811 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2812 {
2813   char save_c;
2814   symbolS *symbol;
2815
2816   /* Terminate name.  */
2817   save_c = *e;
2818   *e = '\0';
2819
2820   /* Look up the name.  */
2821   symbol = symbol_find (s);
2822   *e = save_c;
2823
2824   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2825     return FALSE;
2826
2827   *symval_ptr = S_GET_VALUE (symbol);
2828   return TRUE;
2829 }
2830
2831 /* Return true if the string at *SPTR is a valid register name.  Allow it
2832    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2833    is nonnull.
2834
2835    When returning true, move *SPTR past the register, store the
2836    register's symbol value in *SYMVAL_PTR and the channel mask in
2837    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2838    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2839    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2840
2841 static bfd_boolean
2842 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2843                      unsigned int *channels_ptr)
2844 {
2845   char *s, *e, *m;
2846   const char *q;
2847   unsigned int channels, symval, bit;
2848
2849   /* Find end of name.  */
2850   s = e = *sptr;
2851   if (is_name_beginner (*e))
2852     ++e;
2853   while (is_part_of_name (*e))
2854     ++e;
2855
2856   channels = 0;
2857   if (!mips_parse_register_1 (s, e, &symval))
2858     {
2859       if (!channels_ptr)
2860         return FALSE;
2861
2862       /* Eat characters from the end of the string that are valid
2863          channel suffixes.  The preceding register must be $ACC or
2864          end with a digit, so there is no ambiguity.  */
2865       bit = 1;
2866       m = e;
2867       for (q = "wzyx"; *q; q++, bit <<= 1)
2868         if (m > s && m[-1] == *q)
2869           {
2870             --m;
2871             channels |= bit;
2872           }
2873
2874       if (channels == 0
2875           || !mips_parse_register_1 (s, m, &symval)
2876           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2877         return FALSE;
2878     }
2879
2880   *sptr = e;
2881   *symval_ptr = symval;
2882   if (channels_ptr)
2883     *channels_ptr = channels;
2884   return TRUE;
2885 }
2886
2887 /* Check if SPTR points at a valid register specifier according to TYPES.
2888    If so, then return 1, advance S to consume the specifier and store
2889    the register's number in REGNOP, otherwise return 0.  */
2890
2891 static int
2892 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2893 {
2894   unsigned int regno;
2895
2896   if (mips_parse_register (s, &regno, NULL))
2897     {
2898       if (types & RTYPE_VEC)
2899         regno = mips_prefer_vec_regno (regno);
2900       if (regno & types)
2901         regno &= RNUM_MASK;
2902       else
2903         regno = ~0;
2904     }
2905   else
2906     {
2907       if (types & RWARN)
2908         as_warn (_("unrecognized register name `%s'"), *s);
2909       regno = ~0;
2910     }
2911   if (regnop)
2912     *regnop = regno;
2913   return regno <= RNUM_MASK;
2914 }
2915
2916 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2917    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2918
2919 static char *
2920 mips_parse_vu0_channels (char *s, unsigned int *channels)
2921 {
2922   unsigned int i;
2923
2924   *channels = 0;
2925   for (i = 0; i < 4; i++)
2926     if (*s == "xyzw"[i])
2927       {
2928         *channels |= 1 << (3 - i);
2929         ++s;
2930       }
2931   return s;
2932 }
2933
2934 /* Token types for parsed operand lists.  */
2935 enum mips_operand_token_type {
2936   /* A plain register, e.g. $f2.  */
2937   OT_REG,
2938
2939   /* A 4-bit XYZW channel mask.  */
2940   OT_CHANNELS,
2941
2942   /* A constant vector index, e.g. [1].  */
2943   OT_INTEGER_INDEX,
2944
2945   /* A register vector index, e.g. [$2].  */
2946   OT_REG_INDEX,
2947
2948   /* A continuous range of registers, e.g. $s0-$s4.  */
2949   OT_REG_RANGE,
2950
2951   /* A (possibly relocated) expression.  */
2952   OT_INTEGER,
2953
2954   /* A floating-point value.  */
2955   OT_FLOAT,
2956
2957   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2958      before OT_REGs.  */
2959   OT_CHAR,
2960
2961   /* A doubled character, either "--" or "++".  */
2962   OT_DOUBLE_CHAR,
2963
2964   /* The end of the operand list.  */
2965   OT_END
2966 };
2967
2968 /* A parsed operand token.  */
2969 struct mips_operand_token
2970 {
2971   /* The type of token.  */
2972   enum mips_operand_token_type type;
2973   union
2974   {
2975     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2976     unsigned int regno;
2977
2978     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2979     unsigned int channels;
2980
2981     /* The integer value of an OT_INTEGER_INDEX.  */
2982     addressT index;
2983
2984     /* The two register symbol values involved in an OT_REG_RANGE.  */
2985     struct {
2986       unsigned int regno1;
2987       unsigned int regno2;
2988     } reg_range;
2989
2990     /* The value of an OT_INTEGER.  The value is represented as an
2991        expression and the relocation operators that were applied to
2992        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2993        relocation operators were used.  */
2994     struct {
2995       expressionS value;
2996       bfd_reloc_code_real_type relocs[3];
2997     } integer;
2998
2999     /* The binary data for an OT_FLOAT constant, and the number of bytes
3000        in the constant.  */
3001     struct {
3002       unsigned char data[8];
3003       int length;
3004     } flt;
3005
3006     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
3007     char ch;
3008   } u;
3009 };
3010
3011 /* An obstack used to construct lists of mips_operand_tokens.  */
3012 static struct obstack mips_operand_tokens;
3013
3014 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
3015
3016 static void
3017 mips_add_token (struct mips_operand_token *token,
3018                 enum mips_operand_token_type type)
3019 {
3020   token->type = type;
3021   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
3022 }
3023
3024 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
3025    and OT_REG tokens for them if so, and return a pointer to the first
3026    unconsumed character.  Return null otherwise.  */
3027
3028 static char *
3029 mips_parse_base_start (char *s)
3030 {
3031   struct mips_operand_token token;
3032   unsigned int regno, channels;
3033   bfd_boolean decrement_p;
3034
3035   if (*s != '(')
3036     return 0;
3037
3038   ++s;
3039   SKIP_SPACE_TABS (s);
3040
3041   /* Only match "--" as part of a base expression.  In other contexts "--X"
3042      is a double negative.  */
3043   decrement_p = (s[0] == '-' && s[1] == '-');
3044   if (decrement_p)
3045     {
3046       s += 2;
3047       SKIP_SPACE_TABS (s);
3048     }
3049
3050   /* Allow a channel specifier because that leads to better error messages
3051      than treating something like "$vf0x++" as an expression.  */
3052   if (!mips_parse_register (&s, &regno, &channels))
3053     return 0;
3054
3055   token.u.ch = '(';
3056   mips_add_token (&token, OT_CHAR);
3057
3058   if (decrement_p)
3059     {
3060       token.u.ch = '-';
3061       mips_add_token (&token, OT_DOUBLE_CHAR);
3062     }
3063
3064   token.u.regno = regno;
3065   mips_add_token (&token, OT_REG);
3066
3067   if (channels)
3068     {
3069       token.u.channels = channels;
3070       mips_add_token (&token, OT_CHANNELS);
3071     }
3072
3073   /* For consistency, only match "++" as part of base expressions too.  */
3074   SKIP_SPACE_TABS (s);
3075   if (s[0] == '+' && s[1] == '+')
3076     {
3077       s += 2;
3078       token.u.ch = '+';
3079       mips_add_token (&token, OT_DOUBLE_CHAR);
3080     }
3081
3082   return s;
3083 }
3084
3085 /* Parse one or more tokens from S.  Return a pointer to the first
3086    unconsumed character on success.  Return null if an error was found
3087    and store the error text in insn_error.  FLOAT_FORMAT is as for
3088    mips_parse_arguments.  */
3089
3090 static char *
3091 mips_parse_argument_token (char *s, char float_format)
3092 {
3093   char *end, *save_in;
3094   const char *err;
3095   unsigned int regno1, regno2, channels;
3096   struct mips_operand_token token;
3097
3098   /* First look for "($reg", since we want to treat that as an
3099      OT_CHAR and OT_REG rather than an expression.  */
3100   end = mips_parse_base_start (s);
3101   if (end)
3102     return end;
3103
3104   /* Handle other characters that end up as OT_CHARs.  */
3105   if (*s == ')' || *s == ',')
3106     {
3107       token.u.ch = *s;
3108       mips_add_token (&token, OT_CHAR);
3109       ++s;
3110       return s;
3111     }
3112
3113   /* Handle tokens that start with a register.  */
3114   if (mips_parse_register (&s, &regno1, &channels))
3115     {
3116       if (channels)
3117         {
3118           /* A register and a VU0 channel suffix.  */
3119           token.u.regno = regno1;
3120           mips_add_token (&token, OT_REG);
3121
3122           token.u.channels = channels;
3123           mips_add_token (&token, OT_CHANNELS);
3124           return s;
3125         }
3126
3127       SKIP_SPACE_TABS (s);
3128       if (*s == '-')
3129         {
3130           /* A register range.  */
3131           ++s;
3132           SKIP_SPACE_TABS (s);
3133           if (!mips_parse_register (&s, &regno2, NULL))
3134             {
3135               set_insn_error (0, _("invalid register range"));
3136               return 0;
3137             }
3138
3139           token.u.reg_range.regno1 = regno1;
3140           token.u.reg_range.regno2 = regno2;
3141           mips_add_token (&token, OT_REG_RANGE);
3142           return s;
3143         }
3144
3145       /* Add the register itself.  */
3146       token.u.regno = regno1;
3147       mips_add_token (&token, OT_REG);
3148
3149       /* Check for a vector index.  */
3150       if (*s == '[')
3151         {
3152           ++s;
3153           SKIP_SPACE_TABS (s);
3154           if (mips_parse_register (&s, &token.u.regno, NULL))
3155             mips_add_token (&token, OT_REG_INDEX);
3156           else
3157             {
3158               expressionS element;
3159
3160               my_getExpression (&element, s);
3161               if (element.X_op != O_constant)
3162                 {
3163                   set_insn_error (0, _("vector element must be constant"));
3164                   return 0;
3165                 }
3166               s = expr_end;
3167               token.u.index = element.X_add_number;
3168               mips_add_token (&token, OT_INTEGER_INDEX);
3169             }
3170           SKIP_SPACE_TABS (s);
3171           if (*s != ']')
3172             {
3173               set_insn_error (0, _("missing `]'"));
3174               return 0;
3175             }
3176           ++s;
3177         }
3178       return s;
3179     }
3180
3181   if (float_format)
3182     {
3183       /* First try to treat expressions as floats.  */
3184       save_in = input_line_pointer;
3185       input_line_pointer = s;
3186       err = md_atof (float_format, (char *) token.u.flt.data,
3187                      &token.u.flt.length);
3188       end = input_line_pointer;
3189       input_line_pointer = save_in;
3190       if (err && *err)
3191         {
3192           set_insn_error (0, err);
3193           return 0;
3194         }
3195       if (s != end)
3196         {
3197           mips_add_token (&token, OT_FLOAT);
3198           return end;
3199         }
3200     }
3201
3202   /* Treat everything else as an integer expression.  */
3203   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3204   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3205   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3206   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3207   s = expr_end;
3208   mips_add_token (&token, OT_INTEGER);
3209   return s;
3210 }
3211
3212 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3213    if expressions should be treated as 32-bit floating-point constants,
3214    'd' if they should be treated as 64-bit floating-point constants,
3215    or 0 if they should be treated as integer expressions (the usual case).
3216
3217    Return a list of tokens on success, otherwise return 0.  The caller
3218    must obstack_free the list after use.  */
3219
3220 static struct mips_operand_token *
3221 mips_parse_arguments (char *s, char float_format)
3222 {
3223   struct mips_operand_token token;
3224
3225   SKIP_SPACE_TABS (s);
3226   while (*s)
3227     {
3228       s = mips_parse_argument_token (s, float_format);
3229       if (!s)
3230         {
3231           obstack_free (&mips_operand_tokens,
3232                         obstack_finish (&mips_operand_tokens));
3233           return 0;
3234         }
3235       SKIP_SPACE_TABS (s);
3236     }
3237   mips_add_token (&token, OT_END);
3238   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3239 }
3240
3241 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3242    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3243
3244 static bfd_boolean
3245 is_opcode_valid (const struct mips_opcode *mo)
3246 {
3247   int isa = mips_opts.isa;
3248   int ase = mips_opts.ase;
3249   int fp_s, fp_d;
3250   unsigned int i;
3251
3252   if (ISA_HAS_64BIT_REGS (isa))
3253     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3254       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3255         ase |= mips_ases[i].flags64;
3256
3257   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3258     return FALSE;
3259
3260   /* Check whether the instruction or macro requires single-precision or
3261      double-precision floating-point support.  Note that this information is
3262      stored differently in the opcode table for insns and macros.  */
3263   if (mo->pinfo == INSN_MACRO)
3264     {
3265       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3266       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3267     }
3268   else
3269     {
3270       fp_s = mo->pinfo & FP_S;
3271       fp_d = mo->pinfo & FP_D;
3272     }
3273
3274   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3275     return FALSE;
3276
3277   if (fp_s && mips_opts.soft_float)
3278     return FALSE;
3279
3280   return TRUE;
3281 }
3282
3283 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3284    selected ISA and architecture.  */
3285
3286 static bfd_boolean
3287 is_opcode_valid_16 (const struct mips_opcode *mo)
3288 {
3289   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3290 }
3291
3292 /* Return TRUE if the size of the microMIPS opcode MO matches one
3293    explicitly requested.  Always TRUE in the standard MIPS mode.
3294    Use is_size_valid_16 for MIPS16 opcodes.  */
3295
3296 static bfd_boolean
3297 is_size_valid (const struct mips_opcode *mo)
3298 {
3299   if (!mips_opts.micromips)
3300     return TRUE;
3301
3302   if (mips_opts.insn32)
3303     {
3304       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3305         return FALSE;
3306       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3307         return FALSE;
3308     }
3309   if (!forced_insn_length)
3310     return TRUE;
3311   if (mo->pinfo == INSN_MACRO)
3312     return FALSE;
3313   return forced_insn_length == micromips_insn_length (mo);
3314 }
3315
3316 /* Return TRUE if the size of the MIPS16 opcode MO matches one
3317    explicitly requested.  */
3318
3319 static bfd_boolean
3320 is_size_valid_16 (const struct mips_opcode *mo)
3321 {
3322   if (!forced_insn_length)
3323     return TRUE;
3324   if (mo->pinfo == INSN_MACRO)
3325     return FALSE;
3326   if (forced_insn_length == 2 && mips_opcode_32bit_p (mo))
3327     return FALSE;
3328   if (forced_insn_length == 4 && (mo->pinfo2 & INSN2_SHORT_ONLY))
3329     return FALSE;
3330   return TRUE;
3331 }
3332
3333 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3334    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3335
3336    We don't accept macros in 16-bit delay slots to avoid a case where
3337    a macro expansion fails because it relies on a preceding 32-bit real
3338    instruction to have matched and does not handle the operands correctly.
3339    The only macros that may expand to 16-bit instructions are JAL that
3340    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3341    and BGT (that likewise cannot be placed in a delay slot) that decay to
3342    a NOP.  In all these cases the macros precede any corresponding real
3343    instruction definitions in the opcode table, so they will match in the
3344    second pass where the size of the delay slot is ignored and therefore
3345    produce correct code.  */
3346
3347 static bfd_boolean
3348 is_delay_slot_valid (const struct mips_opcode *mo)
3349 {
3350   if (!mips_opts.micromips)
3351     return TRUE;
3352
3353   if (mo->pinfo == INSN_MACRO)
3354     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3355   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3356       && micromips_insn_length (mo) != 4)
3357     return FALSE;
3358   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3359       && micromips_insn_length (mo) != 2)
3360     return FALSE;
3361
3362   return TRUE;
3363 }
3364
3365 /* For consistency checking, verify that all bits of OPCODE are specified
3366    either by the match/mask part of the instruction definition, or by the
3367    operand list.  Also build up a list of operands in OPERANDS.
3368
3369    INSN_BITS says which bits of the instruction are significant.
3370    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3371    provides the mips_operand description of each operand.  DECODE_OPERAND
3372    is null for MIPS16 instructions.  */
3373
3374 static int
3375 validate_mips_insn (const struct mips_opcode *opcode,
3376                     unsigned long insn_bits,
3377                     const struct mips_operand *(*decode_operand) (const char *),
3378                     struct mips_operand_array *operands)
3379 {
3380   const char *s;
3381   unsigned long used_bits, doubled, undefined, opno, mask;
3382   const struct mips_operand *operand;
3383
3384   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3385   if ((mask & opcode->match) != opcode->match)
3386     {
3387       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3388               opcode->name, opcode->args);
3389       return 0;
3390     }
3391   used_bits = 0;
3392   opno = 0;
3393   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3394     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3395   for (s = opcode->args; *s; ++s)
3396     switch (*s)
3397       {
3398       case ',':
3399       case '(':
3400       case ')':
3401         break;
3402
3403       case '#':
3404         s++;
3405         break;
3406
3407       default:
3408         if (!decode_operand)
3409           operand = decode_mips16_operand (*s, mips_opcode_32bit_p (opcode));
3410         else
3411           operand = decode_operand (s);
3412         if (!operand && opcode->pinfo != INSN_MACRO)
3413           {
3414             as_bad (_("internal: unknown operand type: %s %s"),
3415                     opcode->name, opcode->args);
3416             return 0;
3417           }
3418         gas_assert (opno < MAX_OPERANDS);
3419         operands->operand[opno] = operand;
3420         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3421           {
3422             used_bits = mips_insert_operand (operand, used_bits, -1);
3423             if (operand->type == OP_MDMX_IMM_REG)
3424               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3425                  has separate entries for each format.  */
3426               used_bits &= ~(1 << (operand->lsb + 5));
3427             if (operand->type == OP_ENTRY_EXIT_LIST)
3428               used_bits &= ~(mask & 0x700);
3429           }
3430         /* Skip prefix characters.  */
3431         if (decode_operand && (*s == '+' || *s == 'm' || *s == '-'))
3432           ++s;
3433         opno += 1;
3434         break;
3435       }
3436   doubled = used_bits & mask & insn_bits;
3437   if (doubled)
3438     {
3439       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3440                 " %s %s"), doubled, opcode->name, opcode->args);
3441       return 0;
3442     }
3443   used_bits |= mask;
3444   undefined = ~used_bits & insn_bits;
3445   if (opcode->pinfo != INSN_MACRO && undefined)
3446     {
3447       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3448               undefined, opcode->name, opcode->args);
3449       return 0;
3450     }
3451   used_bits &= ~insn_bits;
3452   if (used_bits)
3453     {
3454       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3455               used_bits, opcode->name, opcode->args);
3456       return 0;
3457     }
3458   return 1;
3459 }
3460
3461 /* The MIPS16 version of validate_mips_insn.  */
3462
3463 static int
3464 validate_mips16_insn (const struct mips_opcode *opcode,
3465                       struct mips_operand_array *operands)
3466 {
3467   unsigned long insn_bits = mips_opcode_32bit_p (opcode) ? 0xffffffff : 0xffff;
3468
3469   return validate_mips_insn (opcode, insn_bits, 0, operands);
3470 }
3471
3472 /* The microMIPS version of validate_mips_insn.  */
3473
3474 static int
3475 validate_micromips_insn (const struct mips_opcode *opc,
3476                          struct mips_operand_array *operands)
3477 {
3478   unsigned long insn_bits;
3479   unsigned long major;
3480   unsigned int length;
3481
3482   if (opc->pinfo == INSN_MACRO)
3483     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3484                                operands);
3485
3486   length = micromips_insn_length (opc);
3487   if (length != 2 && length != 4)
3488     {
3489       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3490                 "%s %s"), length, opc->name, opc->args);
3491       return 0;
3492     }
3493   major = opc->match >> (10 + 8 * (length - 2));
3494   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3495       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3496     {
3497       as_bad (_("internal error: bad microMIPS opcode "
3498                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3499       return 0;
3500     }
3501
3502   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3503   insn_bits = 1 << 4 * length;
3504   insn_bits <<= 4 * length;
3505   insn_bits -= 1;
3506   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3507                              operands);
3508 }
3509
3510 /* This function is called once, at assembler startup time.  It should set up
3511    all the tables, etc. that the MD part of the assembler will need.  */
3512
3513 void
3514 md_begin (void)
3515 {
3516   const char *retval = NULL;
3517   int i = 0;
3518   int broken = 0;
3519
3520   if (mips_pic != NO_PIC)
3521     {
3522       if (g_switch_seen && g_switch_value != 0)
3523         as_bad (_("-G may not be used in position-independent code"));
3524       g_switch_value = 0;
3525     }
3526   else if (mips_abicalls)
3527     {
3528       if (g_switch_seen && g_switch_value != 0)
3529         as_bad (_("-G may not be used with abicalls"));
3530       g_switch_value = 0;
3531     }
3532
3533   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3534     as_warn (_("could not set architecture and machine"));
3535
3536   op_hash = hash_new ();
3537
3538   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3539   for (i = 0; i < NUMOPCODES;)
3540     {
3541       const char *name = mips_opcodes[i].name;
3542
3543       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3544       if (retval != NULL)
3545         {
3546           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3547                    mips_opcodes[i].name, retval);
3548           /* Probably a memory allocation problem?  Give up now.  */
3549           as_fatal (_("broken assembler, no assembly attempted"));
3550         }
3551       do
3552         {
3553           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3554                                    decode_mips_operand, &mips_operands[i]))
3555             broken = 1;
3556           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3557             {
3558               create_insn (&nop_insn, mips_opcodes + i);
3559               if (mips_fix_loongson2f_nop)
3560                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3561               nop_insn.fixed_p = 1;
3562             }
3563           ++i;
3564         }
3565       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3566     }
3567
3568   mips16_op_hash = hash_new ();
3569   mips16_operands = XCNEWVEC (struct mips_operand_array,
3570                               bfd_mips16_num_opcodes);
3571
3572   i = 0;
3573   while (i < bfd_mips16_num_opcodes)
3574     {
3575       const char *name = mips16_opcodes[i].name;
3576
3577       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3578       if (retval != NULL)
3579         as_fatal (_("internal: can't hash `%s': %s"),
3580                   mips16_opcodes[i].name, retval);
3581       do
3582         {
3583           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3584             broken = 1;
3585           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3586             {
3587               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3588               mips16_nop_insn.fixed_p = 1;
3589             }
3590           ++i;
3591         }
3592       while (i < bfd_mips16_num_opcodes
3593              && strcmp (mips16_opcodes[i].name, name) == 0);
3594     }
3595
3596   micromips_op_hash = hash_new ();
3597   micromips_operands = XCNEWVEC (struct mips_operand_array,
3598                                  bfd_micromips_num_opcodes);
3599
3600   i = 0;
3601   while (i < bfd_micromips_num_opcodes)
3602     {
3603       const char *name = micromips_opcodes[i].name;
3604
3605       retval = hash_insert (micromips_op_hash, name,
3606                             (void *) &micromips_opcodes[i]);
3607       if (retval != NULL)
3608         as_fatal (_("internal: can't hash `%s': %s"),
3609                   micromips_opcodes[i].name, retval);
3610       do
3611         {
3612           struct mips_cl_insn *micromips_nop_insn;
3613
3614           if (!validate_micromips_insn (&micromips_opcodes[i],
3615                                         &micromips_operands[i]))
3616             broken = 1;
3617
3618           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3619             {
3620               if (micromips_insn_length (micromips_opcodes + i) == 2)
3621                 micromips_nop_insn = &micromips_nop16_insn;
3622               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3623                 micromips_nop_insn = &micromips_nop32_insn;
3624               else
3625                 continue;
3626
3627               if (micromips_nop_insn->insn_mo == NULL
3628                   && strcmp (name, "nop") == 0)
3629                 {
3630                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3631                   micromips_nop_insn->fixed_p = 1;
3632                 }
3633             }
3634         }
3635       while (++i < bfd_micromips_num_opcodes
3636              && strcmp (micromips_opcodes[i].name, name) == 0);
3637     }
3638
3639   if (broken)
3640     as_fatal (_("broken assembler, no assembly attempted"));
3641
3642   /* We add all the general register names to the symbol table.  This
3643      helps us detect invalid uses of them.  */
3644   for (i = 0; reg_names[i].name; i++)
3645     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3646                                      reg_names[i].num, /* & RNUM_MASK, */
3647                                      &zero_address_frag));
3648   if (HAVE_NEWABI)
3649     for (i = 0; reg_names_n32n64[i].name; i++)
3650       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3651                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3652                                        &zero_address_frag));
3653   else
3654     for (i = 0; reg_names_o32[i].name; i++)
3655       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3656                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3657                                        &zero_address_frag));
3658
3659   for (i = 0; i < 32; i++)
3660     {
3661       char regname[6];
3662
3663       /* R5900 VU0 floating-point register.  */
3664       sprintf (regname, "$vf%d", i);
3665       symbol_table_insert (symbol_new (regname, reg_section,
3666                                        RTYPE_VF | i, &zero_address_frag));
3667
3668       /* R5900 VU0 integer register.  */
3669       sprintf (regname, "$vi%d", i);
3670       symbol_table_insert (symbol_new (regname, reg_section,
3671                                        RTYPE_VI | i, &zero_address_frag));
3672
3673       /* MSA register.  */
3674       sprintf (regname, "$w%d", i);
3675       symbol_table_insert (symbol_new (regname, reg_section,
3676                                        RTYPE_MSA | i, &zero_address_frag));
3677     }
3678
3679   obstack_init (&mips_operand_tokens);
3680
3681   mips_no_prev_insn ();
3682
3683   mips_gprmask = 0;
3684   mips_cprmask[0] = 0;
3685   mips_cprmask[1] = 0;
3686   mips_cprmask[2] = 0;
3687   mips_cprmask[3] = 0;
3688
3689   /* set the default alignment for the text section (2**2) */
3690   record_alignment (text_section, 2);
3691
3692   bfd_set_gp_size (stdoutput, g_switch_value);
3693
3694   /* On a native system other than VxWorks, sections must be aligned
3695      to 16 byte boundaries.  When configured for an embedded ELF
3696      target, we don't bother.  */
3697   if (strncmp (TARGET_OS, "elf", 3) != 0
3698       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3699     {
3700       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3701       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3702       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3703     }
3704
3705   /* Create a .reginfo section for register masks and a .mdebug
3706      section for debugging information.  */
3707   {
3708     segT seg;
3709     subsegT subseg;
3710     flagword flags;
3711     segT sec;
3712
3713     seg = now_seg;
3714     subseg = now_subseg;
3715
3716     /* The ABI says this section should be loaded so that the
3717        running program can access it.  However, we don't load it
3718        if we are configured for an embedded target */
3719     flags = SEC_READONLY | SEC_DATA;
3720     if (strncmp (TARGET_OS, "elf", 3) != 0)
3721       flags |= SEC_ALLOC | SEC_LOAD;
3722
3723     if (mips_abi != N64_ABI)
3724       {
3725         sec = subseg_new (".reginfo", (subsegT) 0);
3726
3727         bfd_set_section_flags (stdoutput, sec, flags);
3728         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3729
3730         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3731       }
3732     else
3733       {
3734         /* The 64-bit ABI uses a .MIPS.options section rather than
3735            .reginfo section.  */
3736         sec = subseg_new (".MIPS.options", (subsegT) 0);
3737         bfd_set_section_flags (stdoutput, sec, flags);
3738         bfd_set_section_alignment (stdoutput, sec, 3);
3739
3740         /* Set up the option header.  */
3741         {
3742           Elf_Internal_Options opthdr;
3743           char *f;
3744
3745           opthdr.kind = ODK_REGINFO;
3746           opthdr.size = (sizeof (Elf_External_Options)
3747                          + sizeof (Elf64_External_RegInfo));
3748           opthdr.section = 0;
3749           opthdr.info = 0;
3750           f = frag_more (sizeof (Elf_External_Options));
3751           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3752                                          (Elf_External_Options *) f);
3753
3754           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3755         }
3756       }
3757
3758     sec = subseg_new (".MIPS.abiflags", (subsegT) 0);
3759     bfd_set_section_flags (stdoutput, sec,
3760                            SEC_READONLY | SEC_DATA | SEC_ALLOC | SEC_LOAD);
3761     bfd_set_section_alignment (stdoutput, sec, 3);
3762     mips_flags_frag = frag_more (sizeof (Elf_External_ABIFlags_v0));
3763
3764     if (ECOFF_DEBUGGING)
3765       {
3766         sec = subseg_new (".mdebug", (subsegT) 0);
3767         (void) bfd_set_section_flags (stdoutput, sec,
3768                                       SEC_HAS_CONTENTS | SEC_READONLY);
3769         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3770       }
3771     else if (mips_flag_pdr)
3772       {
3773         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3774         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3775                                       SEC_READONLY | SEC_RELOC
3776                                       | SEC_DEBUGGING);
3777         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3778       }
3779
3780     subseg_set (seg, subseg);
3781   }
3782
3783   if (mips_fix_vr4120)
3784     init_vr4120_conflicts ();
3785 }
3786
3787 static inline void
3788 fpabi_incompatible_with (int fpabi, const char *what)
3789 {
3790   as_warn (_(".gnu_attribute %d,%d is incompatible with `%s'"),
3791            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3792 }
3793
3794 static inline void
3795 fpabi_requires (int fpabi, const char *what)
3796 {
3797   as_warn (_(".gnu_attribute %d,%d requires `%s'"),
3798            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3799 }
3800
3801 /* Check -mabi and register sizes against the specified FP ABI.  */
3802 static void
3803 check_fpabi (int fpabi)
3804 {
3805   switch (fpabi)
3806     {
3807     case Val_GNU_MIPS_ABI_FP_DOUBLE:
3808       if (file_mips_opts.soft_float)
3809         fpabi_incompatible_with (fpabi, "softfloat");
3810       else if (file_mips_opts.single_float)
3811         fpabi_incompatible_with (fpabi, "singlefloat");
3812       if (file_mips_opts.gp == 64 && file_mips_opts.fp == 32)
3813         fpabi_incompatible_with (fpabi, "gp=64 fp=32");
3814       else if (file_mips_opts.gp == 32 && file_mips_opts.fp == 64)
3815         fpabi_incompatible_with (fpabi, "gp=32 fp=64");
3816       break;
3817
3818     case Val_GNU_MIPS_ABI_FP_XX:
3819       if (mips_abi != O32_ABI)
3820         fpabi_requires (fpabi, "-mabi=32");
3821       else if (file_mips_opts.soft_float)
3822         fpabi_incompatible_with (fpabi, "softfloat");
3823       else if (file_mips_opts.single_float)
3824         fpabi_incompatible_with (fpabi, "singlefloat");
3825       else if (file_mips_opts.fp != 0)
3826         fpabi_requires (fpabi, "fp=xx");
3827       break;
3828
3829     case Val_GNU_MIPS_ABI_FP_64A:
3830     case Val_GNU_MIPS_ABI_FP_64:
3831       if (mips_abi != O32_ABI)
3832         fpabi_requires (fpabi, "-mabi=32");
3833       else if (file_mips_opts.soft_float)
3834         fpabi_incompatible_with (fpabi, "softfloat");
3835       else if (file_mips_opts.single_float)
3836         fpabi_incompatible_with (fpabi, "singlefloat");
3837       else if (file_mips_opts.fp != 64)
3838         fpabi_requires (fpabi, "fp=64");
3839       else if (fpabi == Val_GNU_MIPS_ABI_FP_64 && !file_mips_opts.oddspreg)
3840         fpabi_incompatible_with (fpabi, "nooddspreg");
3841       else if (fpabi == Val_GNU_MIPS_ABI_FP_64A && file_mips_opts.oddspreg)
3842         fpabi_requires (fpabi, "nooddspreg");
3843       break;
3844
3845     case Val_GNU_MIPS_ABI_FP_SINGLE:
3846       if (file_mips_opts.soft_float)
3847         fpabi_incompatible_with (fpabi, "softfloat");
3848       else if (!file_mips_opts.single_float)
3849         fpabi_requires (fpabi, "singlefloat");
3850       break;
3851
3852     case Val_GNU_MIPS_ABI_FP_SOFT:
3853       if (!file_mips_opts.soft_float)
3854         fpabi_requires (fpabi, "softfloat");
3855       break;
3856
3857     case Val_GNU_MIPS_ABI_FP_OLD_64:
3858       as_warn (_(".gnu_attribute %d,%d is no longer supported"),
3859                Tag_GNU_MIPS_ABI_FP, fpabi);
3860       break;
3861
3862     case Val_GNU_MIPS_ABI_FP_NAN2008:
3863       /* Silently ignore compatibility value.  */
3864       break;
3865
3866     default:
3867       as_warn (_(".gnu_attribute %d,%d is not a recognized"
3868                  " floating-point ABI"), Tag_GNU_MIPS_ABI_FP, fpabi);
3869       break;
3870     }
3871 }
3872
3873 /* Perform consistency checks on the current options.  */
3874
3875 static void
3876 mips_check_options (struct mips_set_options *opts, bfd_boolean abi_checks)
3877 {
3878   /* Check the size of integer registers agrees with the ABI and ISA.  */
3879   if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
3880     as_bad (_("`gp=64' used with a 32-bit processor"));
3881   else if (abi_checks
3882            && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
3883     as_bad (_("`gp=32' used with a 64-bit ABI"));
3884   else if (abi_checks
3885            && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
3886     as_bad (_("`gp=64' used with a 32-bit ABI"));
3887
3888   /* Check the size of the float registers agrees with the ABI and ISA.  */
3889   switch (opts->fp)
3890     {
3891     case 0:
3892       if (!CPU_HAS_LDC1_SDC1 (opts->arch))
3893         as_bad (_("`fp=xx' used with a cpu lacking ldc1/sdc1 instructions"));
3894       else if (opts->single_float == 1)
3895         as_bad (_("`fp=xx' cannot be used with `singlefloat'"));
3896       break;
3897     case 64:
3898       if (!ISA_HAS_64BIT_FPRS (opts->isa))
3899         as_bad (_("`fp=64' used with a 32-bit fpu"));
3900       else if (abi_checks
3901                && ABI_NEEDS_32BIT_REGS (mips_abi)
3902                && !ISA_HAS_MXHC1 (opts->isa))
3903         as_warn (_("`fp=64' used with a 32-bit ABI"));
3904       break;
3905     case 32:
3906       if (abi_checks
3907           && ABI_NEEDS_64BIT_REGS (mips_abi))
3908         as_warn (_("`fp=32' used with a 64-bit ABI"));
3909       if (ISA_IS_R6 (opts->isa) && opts->single_float == 0)
3910         as_bad (_("`fp=32' used with a MIPS R6 cpu"));
3911       break;
3912     default:
3913       as_bad (_("Unknown size of floating point registers"));
3914       break;
3915     }
3916
3917   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !opts->oddspreg)
3918     as_bad (_("`nooddspreg` cannot be used with a 64-bit ABI"));
3919
3920   if (opts->micromips == 1 && opts->mips16 == 1)
3921     as_bad (_("`%s' cannot be used with `%s'"), "mips16", "micromips");
3922   else if (ISA_IS_R6 (opts->isa)
3923            && (opts->micromips == 1
3924                || opts->mips16 == 1))
3925     as_fatal (_("`%s' cannot be used with `%s'"),
3926               opts->micromips ? "micromips" : "mips16",
3927               mips_cpu_info_from_isa (opts->isa)->name);
3928
3929   if (ISA_IS_R6 (opts->isa) && mips_relax_branch)
3930     as_fatal (_("branch relaxation is not supported in `%s'"),
3931               mips_cpu_info_from_isa (opts->isa)->name);
3932 }
3933
3934 /* Perform consistency checks on the module level options exactly once.
3935    This is a deferred check that happens:
3936      at the first .set directive
3937      or, at the first pseudo op that generates code (inc .dc.a)
3938      or, at the first instruction
3939      or, at the end.  */
3940
3941 static void
3942 file_mips_check_options (void)
3943 {
3944   const struct mips_cpu_info *arch_info = 0;
3945
3946   if (file_mips_opts_checked)
3947     return;
3948
3949   /* The following code determines the register size.
3950      Similar code was added to GCC 3.3 (see override_options() in
3951      config/mips/mips.c).  The GAS and GCC code should be kept in sync
3952      as much as possible.  */
3953
3954   if (file_mips_opts.gp < 0)
3955     {
3956       /* Infer the integer register size from the ABI and processor.
3957          Restrict ourselves to 32-bit registers if that's all the
3958          processor has, or if the ABI cannot handle 64-bit registers.  */
3959       file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
3960                            || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
3961                           ? 32 : 64;
3962     }
3963
3964   if (file_mips_opts.fp < 0)
3965     {
3966       /* No user specified float register size.
3967          ??? GAS treats single-float processors as though they had 64-bit
3968          float registers (although it complains when double-precision
3969          instructions are used).  As things stand, saying they have 32-bit
3970          registers would lead to spurious "register must be even" messages.
3971          So here we assume float registers are never smaller than the
3972          integer ones.  */
3973       if (file_mips_opts.gp == 64)
3974         /* 64-bit integer registers implies 64-bit float registers.  */
3975         file_mips_opts.fp = 64;
3976       else if ((file_mips_opts.ase & FP64_ASES)
3977                && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
3978         /* Handle ASEs that require 64-bit float registers, if possible.  */
3979         file_mips_opts.fp = 64;
3980       else if (ISA_IS_R6 (mips_opts.isa))
3981         /* R6 implies 64-bit float registers.  */
3982         file_mips_opts.fp = 64;
3983       else
3984         /* 32-bit float registers.  */
3985         file_mips_opts.fp = 32;
3986     }
3987
3988   arch_info = mips_cpu_info_from_arch (file_mips_opts.arch);
3989
3990   /* Disable operations on odd-numbered floating-point registers by default
3991      when using the FPXX ABI.  */
3992   if (file_mips_opts.oddspreg < 0)
3993     {
3994       if (file_mips_opts.fp == 0)
3995         file_mips_opts.oddspreg = 0;
3996       else
3997         file_mips_opts.oddspreg = 1;
3998     }
3999
4000   /* End of GCC-shared inference code.  */
4001
4002   /* This flag is set when we have a 64-bit capable CPU but use only
4003      32-bit wide registers.  Note that EABI does not use it.  */
4004   if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
4005       && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
4006           || mips_abi == O32_ABI))
4007     mips_32bitmode = 1;
4008
4009   if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
4010     as_bad (_("trap exception not supported at ISA 1"));
4011
4012   /* If the selected architecture includes support for ASEs, enable
4013      generation of code for them.  */
4014   if (file_mips_opts.mips16 == -1)
4015     file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
4016   if (file_mips_opts.micromips == -1)
4017     file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
4018                                 ? 1 : 0;
4019
4020   if (mips_nan2008 == -1)
4021     mips_nan2008 = (ISA_HAS_LEGACY_NAN (file_mips_opts.isa)) ? 0 : 1;
4022   else if (!ISA_HAS_LEGACY_NAN (file_mips_opts.isa) && mips_nan2008 == 0)
4023     as_fatal (_("`%s' does not support legacy NaN"),
4024               mips_cpu_info_from_arch (file_mips_opts.arch)->name);
4025
4026   /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
4027      being selected implicitly.  */
4028   if (file_mips_opts.fp != 64)
4029     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
4030
4031   /* If the user didn't explicitly select or deselect a particular ASE,
4032      use the default setting for the CPU.  */
4033   file_mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
4034
4035   /* Set up the current options.  These may change throughout assembly.  */
4036   mips_opts = file_mips_opts;
4037
4038   mips_check_isa_supports_ases ();
4039   mips_check_options (&file_mips_opts, TRUE);
4040   file_mips_opts_checked = TRUE;
4041
4042   if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
4043     as_warn (_("could not set architecture and machine"));
4044 }
4045
4046 void
4047 md_assemble (char *str)
4048 {
4049   struct mips_cl_insn insn;
4050   bfd_reloc_code_real_type unused_reloc[3]
4051     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
4052
4053   file_mips_check_options ();
4054
4055   imm_expr.X_op = O_absent;
4056   offset_expr.X_op = O_absent;
4057   offset_reloc[0] = BFD_RELOC_UNUSED;
4058   offset_reloc[1] = BFD_RELOC_UNUSED;
4059   offset_reloc[2] = BFD_RELOC_UNUSED;
4060
4061   mips_mark_labels ();
4062   mips_assembling_insn = TRUE;
4063   clear_insn_error ();
4064
4065   if (mips_opts.mips16)
4066     mips16_ip (str, &insn);
4067   else
4068     {
4069       mips_ip (str, &insn);
4070       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
4071             str, insn.insn_opcode));
4072     }
4073
4074   if (insn_error.msg)
4075     report_insn_error (str);
4076   else if (insn.insn_mo->pinfo == INSN_MACRO)
4077     {
4078       macro_start ();
4079       if (mips_opts.mips16)
4080         mips16_macro (&insn);
4081       else
4082         macro (&insn, str);
4083       macro_end ();
4084     }
4085   else
4086     {
4087       if (offset_expr.X_op != O_absent)
4088         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
4089       else
4090         append_insn (&insn, NULL, unused_reloc, FALSE);
4091     }
4092
4093   mips_assembling_insn = FALSE;
4094 }
4095
4096 /* Convenience functions for abstracting away the differences between
4097    MIPS16 and non-MIPS16 relocations.  */
4098
4099 static inline bfd_boolean
4100 mips16_reloc_p (bfd_reloc_code_real_type reloc)
4101 {
4102   switch (reloc)
4103     {
4104     case BFD_RELOC_MIPS16_JMP:
4105     case BFD_RELOC_MIPS16_GPREL:
4106     case BFD_RELOC_MIPS16_GOT16:
4107     case BFD_RELOC_MIPS16_CALL16:
4108     case BFD_RELOC_MIPS16_HI16_S:
4109     case BFD_RELOC_MIPS16_HI16:
4110     case BFD_RELOC_MIPS16_LO16:
4111     case BFD_RELOC_MIPS16_16_PCREL_S1:
4112       return TRUE;
4113
4114     default:
4115       return FALSE;
4116     }
4117 }
4118
4119 static inline bfd_boolean
4120 micromips_reloc_p (bfd_reloc_code_real_type reloc)
4121 {
4122   switch (reloc)
4123     {
4124     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4125     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4126     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4127     case BFD_RELOC_MICROMIPS_GPREL16:
4128     case BFD_RELOC_MICROMIPS_JMP:
4129     case BFD_RELOC_MICROMIPS_HI16:
4130     case BFD_RELOC_MICROMIPS_HI16_S:
4131     case BFD_RELOC_MICROMIPS_LO16:
4132     case BFD_RELOC_MICROMIPS_LITERAL:
4133     case BFD_RELOC_MICROMIPS_GOT16:
4134     case BFD_RELOC_MICROMIPS_CALL16:
4135     case BFD_RELOC_MICROMIPS_GOT_HI16:
4136     case BFD_RELOC_MICROMIPS_GOT_LO16:
4137     case BFD_RELOC_MICROMIPS_CALL_HI16:
4138     case BFD_RELOC_MICROMIPS_CALL_LO16:
4139     case BFD_RELOC_MICROMIPS_SUB:
4140     case BFD_RELOC_MICROMIPS_GOT_PAGE:
4141     case BFD_RELOC_MICROMIPS_GOT_OFST:
4142     case BFD_RELOC_MICROMIPS_GOT_DISP:
4143     case BFD_RELOC_MICROMIPS_HIGHEST:
4144     case BFD_RELOC_MICROMIPS_HIGHER:
4145     case BFD_RELOC_MICROMIPS_SCN_DISP:
4146     case BFD_RELOC_MICROMIPS_JALR:
4147       return TRUE;
4148
4149     default:
4150       return FALSE;
4151     }
4152 }
4153
4154 static inline bfd_boolean
4155 jmp_reloc_p (bfd_reloc_code_real_type reloc)
4156 {
4157   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
4158 }
4159
4160 static inline bfd_boolean
4161 b_reloc_p (bfd_reloc_code_real_type reloc)
4162 {
4163   return (reloc == BFD_RELOC_MIPS_26_PCREL_S2
4164           || reloc == BFD_RELOC_MIPS_21_PCREL_S2
4165           || reloc == BFD_RELOC_16_PCREL_S2
4166           || reloc == BFD_RELOC_MIPS16_16_PCREL_S1
4167           || reloc == BFD_RELOC_MICROMIPS_16_PCREL_S1
4168           || reloc == BFD_RELOC_MICROMIPS_10_PCREL_S1
4169           || reloc == BFD_RELOC_MICROMIPS_7_PCREL_S1);
4170 }
4171
4172 static inline bfd_boolean
4173 got16_reloc_p (bfd_reloc_code_real_type reloc)
4174 {
4175   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
4176           || reloc == BFD_RELOC_MICROMIPS_GOT16);
4177 }
4178
4179 static inline bfd_boolean
4180 hi16_reloc_p (bfd_reloc_code_real_type reloc)
4181 {
4182   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
4183           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
4184 }
4185
4186 static inline bfd_boolean
4187 lo16_reloc_p (bfd_reloc_code_real_type reloc)
4188 {
4189   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
4190           || reloc == BFD_RELOC_MICROMIPS_LO16);
4191 }
4192
4193 static inline bfd_boolean
4194 jalr_reloc_p (bfd_reloc_code_real_type reloc)
4195 {
4196   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
4197 }
4198
4199 static inline bfd_boolean
4200 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
4201 {
4202   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
4203           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
4204 }
4205
4206 /* Return true if RELOC is a PC-relative relocation that does not have
4207    full address range.  */
4208
4209 static inline bfd_boolean
4210 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
4211 {
4212   switch (reloc)
4213     {
4214     case BFD_RELOC_16_PCREL_S2:
4215     case BFD_RELOC_MIPS16_16_PCREL_S1:
4216     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4217     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4218     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4219     case BFD_RELOC_MIPS_21_PCREL_S2:
4220     case BFD_RELOC_MIPS_26_PCREL_S2:
4221     case BFD_RELOC_MIPS_18_PCREL_S3:
4222     case BFD_RELOC_MIPS_19_PCREL_S2:
4223       return TRUE;
4224
4225     case BFD_RELOC_32_PCREL:
4226     case BFD_RELOC_HI16_S_PCREL:
4227     case BFD_RELOC_LO16_PCREL:
4228       return HAVE_64BIT_ADDRESSES;
4229
4230     default:
4231       return FALSE;
4232     }
4233 }
4234
4235 /* Return true if the given relocation might need a matching %lo().
4236    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
4237    need a matching %lo() when applied to local symbols.  */
4238
4239 static inline bfd_boolean
4240 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
4241 {
4242   return (HAVE_IN_PLACE_ADDENDS
4243           && (hi16_reloc_p (reloc)
4244               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
4245                  all GOT16 relocations evaluate to "G".  */
4246               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
4247 }
4248
4249 /* Return the type of %lo() reloc needed by RELOC, given that
4250    reloc_needs_lo_p.  */
4251
4252 static inline bfd_reloc_code_real_type
4253 matching_lo_reloc (bfd_reloc_code_real_type reloc)
4254 {
4255   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
4256           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
4257              : BFD_RELOC_LO16));
4258 }
4259
4260 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
4261    relocation.  */
4262
4263 static inline bfd_boolean
4264 fixup_has_matching_lo_p (fixS *fixp)
4265 {
4266   return (fixp->fx_next != NULL
4267           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
4268           && fixp->fx_addsy == fixp->fx_next->fx_addsy
4269           && fixp->fx_offset == fixp->fx_next->fx_offset);
4270 }
4271
4272 /* Move all labels in LABELS to the current insertion point.  TEXT_P
4273    says whether the labels refer to text or data.  */
4274
4275 static void
4276 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
4277 {
4278   struct insn_label_list *l;
4279   valueT val;
4280
4281   for (l = labels; l != NULL; l = l->next)
4282     {
4283       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
4284       symbol_set_frag (l->label, frag_now);
4285       val = (valueT) frag_now_fix ();
4286       /* MIPS16/microMIPS text labels are stored as odd.  */
4287       if (text_p && HAVE_CODE_COMPRESSION)
4288         ++val;
4289       S_SET_VALUE (l->label, val);
4290     }
4291 }
4292
4293 /* Move all labels in insn_labels to the current insertion point
4294    and treat them as text labels.  */
4295
4296 static void
4297 mips_move_text_labels (void)
4298 {
4299   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
4300 }
4301
4302 /* Duplicate the test for LINK_ONCE sections as in `adjust_reloc_syms'.  */
4303
4304 static bfd_boolean
4305 s_is_linkonce (symbolS *sym, segT from_seg)
4306 {
4307   bfd_boolean linkonce = FALSE;
4308   segT symseg = S_GET_SEGMENT (sym);
4309
4310   if (symseg != from_seg && !S_IS_LOCAL (sym))
4311     {
4312       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
4313         linkonce = TRUE;
4314       /* The GNU toolchain uses an extension for ELF: a section
4315          beginning with the magic string .gnu.linkonce is a
4316          linkonce section.  */
4317       if (strncmp (segment_name (symseg), ".gnu.linkonce",
4318                    sizeof ".gnu.linkonce" - 1) == 0)
4319         linkonce = TRUE;
4320     }
4321   return linkonce;
4322 }
4323
4324 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4325    linker to handle them specially, such as generating jalx instructions
4326    when needed.  We also make them odd for the duration of the assembly,
4327    in order to generate the right sort of code.  We will make them even
4328    in the adjust_symtab routine, while leaving them marked.  This is
4329    convenient for the debugger and the disassembler.  The linker knows
4330    to make them odd again.  */
4331
4332 static void
4333 mips_compressed_mark_label (symbolS *label)
4334 {
4335   gas_assert (HAVE_CODE_COMPRESSION);
4336
4337   if (mips_opts.mips16)
4338     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4339   else
4340     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4341   if ((S_GET_VALUE (label) & 1) == 0
4342       /* Don't adjust the address if the label is global or weak, or
4343          in a link-once section, since we'll be emitting symbol reloc
4344          references to it which will be patched up by the linker, and
4345          the final value of the symbol may or may not be MIPS16/microMIPS.  */
4346       && !S_IS_WEAK (label)
4347       && !S_IS_EXTERNAL (label)
4348       && !s_is_linkonce (label, now_seg))
4349     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4350 }
4351
4352 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
4353
4354 static void
4355 mips_compressed_mark_labels (void)
4356 {
4357   struct insn_label_list *l;
4358
4359   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4360     mips_compressed_mark_label (l->label);
4361 }
4362
4363 /* End the current frag.  Make it a variant frag and record the
4364    relaxation info.  */
4365
4366 static void
4367 relax_close_frag (void)
4368 {
4369   mips_macro_warning.first_frag = frag_now;
4370   frag_var (rs_machine_dependent, 0, 0,
4371             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1],
4372                           mips_pic != NO_PIC),
4373             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4374
4375   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4376   mips_relax.first_fixup = 0;
4377 }
4378
4379 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
4380    See the comment above RELAX_ENCODE for more details.  */
4381
4382 static void
4383 relax_start (symbolS *symbol)
4384 {
4385   gas_assert (mips_relax.sequence == 0);
4386   mips_relax.sequence = 1;
4387   mips_relax.symbol = symbol;
4388 }
4389
4390 /* Start generating the second version of a relaxable sequence.
4391    See the comment above RELAX_ENCODE for more details.  */
4392
4393 static void
4394 relax_switch (void)
4395 {
4396   gas_assert (mips_relax.sequence == 1);
4397   mips_relax.sequence = 2;
4398 }
4399
4400 /* End the current relaxable sequence.  */
4401
4402 static void
4403 relax_end (void)
4404 {
4405   gas_assert (mips_relax.sequence == 2);
4406   relax_close_frag ();
4407   mips_relax.sequence = 0;
4408 }
4409
4410 /* Return true if IP is a delayed branch or jump.  */
4411
4412 static inline bfd_boolean
4413 delayed_branch_p (const struct mips_cl_insn *ip)
4414 {
4415   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4416                                 | INSN_COND_BRANCH_DELAY
4417                                 | INSN_COND_BRANCH_LIKELY)) != 0;
4418 }
4419
4420 /* Return true if IP is a compact branch or jump.  */
4421
4422 static inline bfd_boolean
4423 compact_branch_p (const struct mips_cl_insn *ip)
4424 {
4425   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4426                                  | INSN2_COND_BRANCH)) != 0;
4427 }
4428
4429 /* Return true if IP is an unconditional branch or jump.  */
4430
4431 static inline bfd_boolean
4432 uncond_branch_p (const struct mips_cl_insn *ip)
4433 {
4434   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4435           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4436 }
4437
4438 /* Return true if IP is a branch-likely instruction.  */
4439
4440 static inline bfd_boolean
4441 branch_likely_p (const struct mips_cl_insn *ip)
4442 {
4443   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4444 }
4445
4446 /* Return the type of nop that should be used to fill the delay slot
4447    of delayed branch IP.  */
4448
4449 static struct mips_cl_insn *
4450 get_delay_slot_nop (const struct mips_cl_insn *ip)
4451 {
4452   if (mips_opts.micromips
4453       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4454     return &micromips_nop32_insn;
4455   return NOP_INSN;
4456 }
4457
4458 /* Return a mask that has bit N set if OPCODE reads the register(s)
4459    in operand N.  */
4460
4461 static unsigned int
4462 insn_read_mask (const struct mips_opcode *opcode)
4463 {
4464   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4465 }
4466
4467 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4468    in operand N.  */
4469
4470 static unsigned int
4471 insn_write_mask (const struct mips_opcode *opcode)
4472 {
4473   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4474 }
4475
4476 /* Return a mask of the registers specified by operand OPERAND of INSN.
4477    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4478    is set.  */
4479
4480 static unsigned int
4481 operand_reg_mask (const struct mips_cl_insn *insn,
4482                   const struct mips_operand *operand,
4483                   unsigned int type_mask)
4484 {
4485   unsigned int uval, vsel;
4486
4487   switch (operand->type)
4488     {
4489     case OP_INT:
4490     case OP_MAPPED_INT:
4491     case OP_MSB:
4492     case OP_PCREL:
4493     case OP_PERF_REG:
4494     case OP_ADDIUSP_INT:
4495     case OP_ENTRY_EXIT_LIST:
4496     case OP_REPEAT_DEST_REG:
4497     case OP_REPEAT_PREV_REG:
4498     case OP_PC:
4499     case OP_VU0_SUFFIX:
4500     case OP_VU0_MATCH_SUFFIX:
4501     case OP_IMM_INDEX:
4502       abort ();
4503
4504     case OP_REG:
4505     case OP_OPTIONAL_REG:
4506       {
4507         const struct mips_reg_operand *reg_op;
4508
4509         reg_op = (const struct mips_reg_operand *) operand;
4510         if (!(type_mask & (1 << reg_op->reg_type)))
4511           return 0;
4512         uval = insn_extract_operand (insn, operand);
4513         return 1 << mips_decode_reg_operand (reg_op, uval);
4514       }
4515
4516     case OP_REG_PAIR:
4517       {
4518         const struct mips_reg_pair_operand *pair_op;
4519
4520         pair_op = (const struct mips_reg_pair_operand *) operand;
4521         if (!(type_mask & (1 << pair_op->reg_type)))
4522           return 0;
4523         uval = insn_extract_operand (insn, operand);
4524         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4525       }
4526
4527     case OP_CLO_CLZ_DEST:
4528       if (!(type_mask & (1 << OP_REG_GP)))
4529         return 0;
4530       uval = insn_extract_operand (insn, operand);
4531       return (1 << (uval & 31)) | (1 << (uval >> 5));
4532
4533     case OP_SAME_RS_RT:
4534       if (!(type_mask & (1 << OP_REG_GP)))
4535         return 0;
4536       uval = insn_extract_operand (insn, operand);
4537       gas_assert ((uval & 31) == (uval >> 5));
4538       return 1 << (uval & 31);
4539
4540     case OP_CHECK_PREV:
4541     case OP_NON_ZERO_REG:
4542       if (!(type_mask & (1 << OP_REG_GP)))
4543         return 0;
4544       uval = insn_extract_operand (insn, operand);
4545       return 1 << (uval & 31);
4546
4547     case OP_LWM_SWM_LIST:
4548       abort ();
4549
4550     case OP_SAVE_RESTORE_LIST:
4551       abort ();
4552
4553     case OP_MDMX_IMM_REG:
4554       if (!(type_mask & (1 << OP_REG_VEC)))
4555         return 0;
4556       uval = insn_extract_operand (insn, operand);
4557       vsel = uval >> 5;
4558       if ((vsel & 0x18) == 0x18)
4559         return 0;
4560       return 1 << (uval & 31);
4561
4562     case OP_REG_INDEX:
4563       if (!(type_mask & (1 << OP_REG_GP)))
4564         return 0;
4565       return 1 << insn_extract_operand (insn, operand);
4566     }
4567   abort ();
4568 }
4569
4570 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4571    where bit N of OPNO_MASK is set if operand N should be included.
4572    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4573    is set.  */
4574
4575 static unsigned int
4576 insn_reg_mask (const struct mips_cl_insn *insn,
4577                unsigned int type_mask, unsigned int opno_mask)
4578 {
4579   unsigned int opno, reg_mask;
4580
4581   opno = 0;
4582   reg_mask = 0;
4583   while (opno_mask != 0)
4584     {
4585       if (opno_mask & 1)
4586         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4587       opno_mask >>= 1;
4588       opno += 1;
4589     }
4590   return reg_mask;
4591 }
4592
4593 /* Return the mask of core registers that IP reads.  */
4594
4595 static unsigned int
4596 gpr_read_mask (const struct mips_cl_insn *ip)
4597 {
4598   unsigned long pinfo, pinfo2;
4599   unsigned int mask;
4600
4601   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4602   pinfo = ip->insn_mo->pinfo;
4603   pinfo2 = ip->insn_mo->pinfo2;
4604   if (pinfo & INSN_UDI)
4605     {
4606       /* UDI instructions have traditionally been assumed to read RS
4607          and RT.  */
4608       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4609       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4610     }
4611   if (pinfo & INSN_READ_GPR_24)
4612     mask |= 1 << 24;
4613   if (pinfo2 & INSN2_READ_GPR_16)
4614     mask |= 1 << 16;
4615   if (pinfo2 & INSN2_READ_SP)
4616     mask |= 1 << SP;
4617   if (pinfo2 & INSN2_READ_GPR_31)
4618     mask |= 1 << 31;
4619   /* Don't include register 0.  */
4620   return mask & ~1;
4621 }
4622
4623 /* Return the mask of core registers that IP writes.  */
4624
4625 static unsigned int
4626 gpr_write_mask (const struct mips_cl_insn *ip)
4627 {
4628   unsigned long pinfo, pinfo2;
4629   unsigned int mask;
4630
4631   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4632   pinfo = ip->insn_mo->pinfo;
4633   pinfo2 = ip->insn_mo->pinfo2;
4634   if (pinfo & INSN_WRITE_GPR_24)
4635     mask |= 1 << 24;
4636   if (pinfo & INSN_WRITE_GPR_31)
4637     mask |= 1 << 31;
4638   if (pinfo & INSN_UDI)
4639     /* UDI instructions have traditionally been assumed to write to RD.  */
4640     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4641   if (pinfo2 & INSN2_WRITE_SP)
4642     mask |= 1 << SP;
4643   /* Don't include register 0.  */
4644   return mask & ~1;
4645 }
4646
4647 /* Return the mask of floating-point registers that IP reads.  */
4648
4649 static unsigned int
4650 fpr_read_mask (const struct mips_cl_insn *ip)
4651 {
4652   unsigned long pinfo;
4653   unsigned int mask;
4654
4655   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4656                              | (1 << OP_REG_MSA)),
4657                         insn_read_mask (ip->insn_mo));
4658   pinfo = ip->insn_mo->pinfo;
4659   /* Conservatively treat all operands to an FP_D instruction are doubles.
4660      (This is overly pessimistic for things like cvt.d.s.)  */
4661   if (FPR_SIZE != 64 && (pinfo & FP_D))
4662     mask |= mask << 1;
4663   return mask;
4664 }
4665
4666 /* Return the mask of floating-point registers that IP writes.  */
4667
4668 static unsigned int
4669 fpr_write_mask (const struct mips_cl_insn *ip)
4670 {
4671   unsigned long pinfo;
4672   unsigned int mask;
4673
4674   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4675                              | (1 << OP_REG_MSA)),
4676                         insn_write_mask (ip->insn_mo));
4677   pinfo = ip->insn_mo->pinfo;
4678   /* Conservatively treat all operands to an FP_D instruction are doubles.
4679      (This is overly pessimistic for things like cvt.s.d.)  */
4680   if (FPR_SIZE != 64 && (pinfo & FP_D))
4681     mask |= mask << 1;
4682   return mask;
4683 }
4684
4685 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4686    Check whether that is allowed.  */
4687
4688 static bfd_boolean
4689 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4690 {
4691   const char *s = insn->name;
4692   bfd_boolean oddspreg = (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa, mips_opts.arch)
4693                           || FPR_SIZE == 64)
4694                          && mips_opts.oddspreg;
4695
4696   if (insn->pinfo == INSN_MACRO)
4697     /* Let a macro pass, we'll catch it later when it is expanded.  */
4698     return TRUE;
4699
4700   /* Single-precision coprocessor loads and moves are OK for 32-bit registers,
4701      otherwise it depends on oddspreg.  */
4702   if ((insn->pinfo & FP_S)
4703       && (insn->pinfo & (INSN_LOAD_MEMORY | INSN_STORE_MEMORY
4704                          | INSN_LOAD_COPROC | INSN_COPROC_MOVE)))
4705     return FPR_SIZE == 32 || oddspreg;
4706
4707   /* Allow odd registers for single-precision ops and double-precision if the
4708      floating-point registers are 64-bit wide.  */
4709   switch (insn->pinfo & (FP_S | FP_D))
4710     {
4711     case FP_S:
4712     case 0:
4713       return oddspreg;
4714     case FP_D:
4715       return FPR_SIZE == 64;
4716     default:
4717       break;
4718     }
4719
4720   /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4721   s = strchr (insn->name, '.');
4722   if (s != NULL && opnum == 2)
4723     s = strchr (s + 1, '.');
4724   if (s != NULL && (s[1] == 'w' || s[1] == 's'))
4725     return oddspreg;
4726
4727   return FPR_SIZE == 64;
4728 }
4729
4730 /* Information about an instruction argument that we're trying to match.  */
4731 struct mips_arg_info
4732 {
4733   /* The instruction so far.  */
4734   struct mips_cl_insn *insn;
4735
4736   /* The first unconsumed operand token.  */
4737   struct mips_operand_token *token;
4738
4739   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4740   int opnum;
4741
4742   /* The 1-based argument number, for error reporting.  This does not
4743      count elided optional registers, etc..  */
4744   int argnum;
4745
4746   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4747   unsigned int last_regno;
4748
4749   /* If the first operand was an OP_REG, this is the register that it
4750      specified, otherwise it is ILLEGAL_REG.  */
4751   unsigned int dest_regno;
4752
4753   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4754      where it gives the lsb position.  */
4755   unsigned int last_op_int;
4756
4757   /* If true, match routines should assume that no later instruction
4758      alternative matches and should therefore be as accommodating as
4759      possible.  Match routines should not report errors if something
4760      is only invalid for !LAX_MATCH.  */
4761   bfd_boolean lax_match;
4762
4763   /* True if a reference to the current AT register was seen.  */
4764   bfd_boolean seen_at;
4765 };
4766
4767 /* Record that the argument is out of range.  */
4768
4769 static void
4770 match_out_of_range (struct mips_arg_info *arg)
4771 {
4772   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4773 }
4774
4775 /* Record that the argument isn't constant but needs to be.  */
4776
4777 static void
4778 match_not_constant (struct mips_arg_info *arg)
4779 {
4780   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4781                     arg->argnum);
4782 }
4783
4784 /* Try to match an OT_CHAR token for character CH.  Consume the token
4785    and return true on success, otherwise return false.  */
4786
4787 static bfd_boolean
4788 match_char (struct mips_arg_info *arg, char ch)
4789 {
4790   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4791     {
4792       ++arg->token;
4793       if (ch == ',')
4794         arg->argnum += 1;
4795       return TRUE;
4796     }
4797   return FALSE;
4798 }
4799
4800 /* Try to get an expression from the next tokens in ARG.  Consume the
4801    tokens and return true on success, storing the expression value in
4802    VALUE and relocation types in R.  */
4803
4804 static bfd_boolean
4805 match_expression (struct mips_arg_info *arg, expressionS *value,
4806                   bfd_reloc_code_real_type *r)
4807 {
4808   /* If the next token is a '(' that was parsed as being part of a base
4809      expression, assume we have an elided offset.  The later match will fail
4810      if this turns out to be wrong.  */
4811   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4812     {
4813       value->X_op = O_constant;
4814       value->X_add_number = 0;
4815       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4816       return TRUE;
4817     }
4818
4819   /* Reject register-based expressions such as "0+$2" and "(($2))".
4820      For plain registers the default error seems more appropriate.  */
4821   if (arg->token->type == OT_INTEGER
4822       && arg->token->u.integer.value.X_op == O_register)
4823     {
4824       set_insn_error (arg->argnum, _("register value used as expression"));
4825       return FALSE;
4826     }
4827
4828   if (arg->token->type == OT_INTEGER)
4829     {
4830       *value = arg->token->u.integer.value;
4831       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4832       ++arg->token;
4833       return TRUE;
4834     }
4835
4836   set_insn_error_i
4837     (arg->argnum, _("operand %d must be an immediate expression"),
4838      arg->argnum);
4839   return FALSE;
4840 }
4841
4842 /* Try to get a constant expression from the next tokens in ARG.  Consume
4843    the tokens and return return true on success, storing the constant value
4844    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4845    error.  */
4846
4847 static bfd_boolean
4848 match_const_int (struct mips_arg_info *arg, offsetT *value)
4849 {
4850   expressionS ex;
4851   bfd_reloc_code_real_type r[3];
4852
4853   if (!match_expression (arg, &ex, r))
4854     return FALSE;
4855
4856   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4857     *value = ex.X_add_number;
4858   else
4859     {
4860       match_not_constant (arg);
4861       return FALSE;
4862     }
4863   return TRUE;
4864 }
4865
4866 /* Return the RTYPE_* flags for a register operand of type TYPE that
4867    appears in instruction OPCODE.  */
4868
4869 static unsigned int
4870 convert_reg_type (const struct mips_opcode *opcode,
4871                   enum mips_reg_operand_type type)
4872 {
4873   switch (type)
4874     {
4875     case OP_REG_GP:
4876       return RTYPE_NUM | RTYPE_GP;
4877
4878     case OP_REG_FP:
4879       /* Allow vector register names for MDMX if the instruction is a 64-bit
4880          FPR load, store or move (including moves to and from GPRs).  */
4881       if ((mips_opts.ase & ASE_MDMX)
4882           && (opcode->pinfo & FP_D)
4883           && (opcode->pinfo & (INSN_COPROC_MOVE
4884                                | INSN_COPROC_MEMORY_DELAY
4885                                | INSN_LOAD_COPROC
4886                                | INSN_LOAD_MEMORY
4887                                | INSN_STORE_MEMORY)))
4888         return RTYPE_FPU | RTYPE_VEC;
4889       return RTYPE_FPU;
4890
4891     case OP_REG_CCC:
4892       if (opcode->pinfo & (FP_D | FP_S))
4893         return RTYPE_CCC | RTYPE_FCC;
4894       return RTYPE_CCC;
4895
4896     case OP_REG_VEC:
4897       if (opcode->membership & INSN_5400)
4898         return RTYPE_FPU;
4899       return RTYPE_FPU | RTYPE_VEC;
4900
4901     case OP_REG_ACC:
4902       return RTYPE_ACC;
4903
4904     case OP_REG_COPRO:
4905       if (opcode->name[strlen (opcode->name) - 1] == '0')
4906         return RTYPE_NUM | RTYPE_CP0;
4907       return RTYPE_NUM;
4908
4909     case OP_REG_HW:
4910       return RTYPE_NUM;
4911
4912     case OP_REG_VI:
4913       return RTYPE_NUM | RTYPE_VI;
4914
4915     case OP_REG_VF:
4916       return RTYPE_NUM | RTYPE_VF;
4917
4918     case OP_REG_R5900_I:
4919       return RTYPE_R5900_I;
4920
4921     case OP_REG_R5900_Q:
4922       return RTYPE_R5900_Q;
4923
4924     case OP_REG_R5900_R:
4925       return RTYPE_R5900_R;
4926
4927     case OP_REG_R5900_ACC:
4928       return RTYPE_R5900_ACC;
4929
4930     case OP_REG_MSA:
4931       return RTYPE_MSA;
4932
4933     case OP_REG_MSA_CTRL:
4934       return RTYPE_NUM;
4935     }
4936   abort ();
4937 }
4938
4939 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4940
4941 static void
4942 check_regno (struct mips_arg_info *arg,
4943              enum mips_reg_operand_type type, unsigned int regno)
4944 {
4945   if (AT && type == OP_REG_GP && regno == AT)
4946     arg->seen_at = TRUE;
4947
4948   if (type == OP_REG_FP
4949       && (regno & 1) != 0
4950       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4951     {
4952       /* This was a warning prior to introducing O32 FPXX and FP64 support
4953          so maintain a warning for FP32 but raise an error for the new
4954          cases.  */
4955       if (FPR_SIZE == 32)
4956         as_warn (_("float register should be even, was %d"), regno);
4957       else
4958         as_bad (_("float register should be even, was %d"), regno);
4959     }
4960
4961   if (type == OP_REG_CCC)
4962     {
4963       const char *name;
4964       size_t length;
4965
4966       name = arg->insn->insn_mo->name;
4967       length = strlen (name);
4968       if ((regno & 1) != 0
4969           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4970               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4971         as_warn (_("condition code register should be even for %s, was %d"),
4972                  name, regno);
4973
4974       if ((regno & 3) != 0
4975           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4976         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4977                  name, regno);
4978     }
4979 }
4980
4981 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4982    a register of type TYPE.  Return true on success, storing the register
4983    number in *REGNO and warning about any dubious uses.  */
4984
4985 static bfd_boolean
4986 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4987              unsigned int symval, unsigned int *regno)
4988 {
4989   if (type == OP_REG_VEC)
4990     symval = mips_prefer_vec_regno (symval);
4991   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4992     return FALSE;
4993
4994   *regno = symval & RNUM_MASK;
4995   check_regno (arg, type, *regno);
4996   return TRUE;
4997 }
4998
4999 /* Try to interpret the next token in ARG as a register of type TYPE.
5000    Consume the token and return true on success, storing the register
5001    number in *REGNO.  Return false on failure.  */
5002
5003 static bfd_boolean
5004 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5005            unsigned int *regno)
5006 {
5007   if (arg->token->type == OT_REG
5008       && match_regno (arg, type, arg->token->u.regno, regno))
5009     {
5010       ++arg->token;
5011       return TRUE;
5012     }
5013   return FALSE;
5014 }
5015
5016 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
5017    Consume the token and return true on success, storing the register numbers
5018    in *REGNO1 and *REGNO2.  Return false on failure.  */
5019
5020 static bfd_boolean
5021 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5022                  unsigned int *regno1, unsigned int *regno2)
5023 {
5024   if (match_reg (arg, type, regno1))
5025     {
5026       *regno2 = *regno1;
5027       return TRUE;
5028     }
5029   if (arg->token->type == OT_REG_RANGE
5030       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
5031       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
5032       && *regno1 <= *regno2)
5033     {
5034       ++arg->token;
5035       return TRUE;
5036     }
5037   return FALSE;
5038 }
5039
5040 /* OP_INT matcher.  */
5041
5042 static bfd_boolean
5043 match_int_operand (struct mips_arg_info *arg,
5044                    const struct mips_operand *operand_base)
5045 {
5046   const struct mips_int_operand *operand;
5047   unsigned int uval;
5048   int min_val, max_val, factor;
5049   offsetT sval;
5050
5051   operand = (const struct mips_int_operand *) operand_base;
5052   factor = 1 << operand->shift;
5053   min_val = mips_int_operand_min (operand);
5054   max_val = mips_int_operand_max (operand);
5055
5056   if (operand_base->lsb == 0
5057       && operand_base->size == 16
5058       && operand->shift == 0
5059       && operand->bias == 0
5060       && (operand->max_val == 32767 || operand->max_val == 65535))
5061     {
5062       /* The operand can be relocated.  */
5063       if (!match_expression (arg, &offset_expr, offset_reloc))
5064         return FALSE;
5065
5066       if (offset_reloc[0] != BFD_RELOC_UNUSED)
5067         /* Relocation operators were used.  Accept the argument and
5068            leave the relocation value in offset_expr and offset_relocs
5069            for the caller to process.  */
5070         return TRUE;
5071
5072       if (offset_expr.X_op != O_constant)
5073         {
5074           /* Accept non-constant operands if no later alternative matches,
5075              leaving it for the caller to process.  */
5076           if (!arg->lax_match)
5077             return FALSE;
5078           offset_reloc[0] = BFD_RELOC_LO16;
5079           return TRUE;
5080         }
5081
5082       /* Clear the global state; we're going to install the operand
5083          ourselves.  */
5084       sval = offset_expr.X_add_number;
5085       offset_expr.X_op = O_absent;
5086
5087       /* For compatibility with older assemblers, we accept
5088          0x8000-0xffff as signed 16-bit numbers when only
5089          signed numbers are allowed.  */
5090       if (sval > max_val)
5091         {
5092           max_val = ((1 << operand_base->size) - 1) << operand->shift;
5093           if (!arg->lax_match && sval <= max_val)
5094             return FALSE;
5095         }
5096     }
5097   else
5098     {
5099       if (!match_const_int (arg, &sval))
5100         return FALSE;
5101     }
5102
5103   arg->last_op_int = sval;
5104
5105   if (sval < min_val || sval > max_val || sval % factor)
5106     {
5107       match_out_of_range (arg);
5108       return FALSE;
5109     }
5110
5111   uval = (unsigned int) sval >> operand->shift;
5112   uval -= operand->bias;
5113
5114   /* Handle -mfix-cn63xxp1.  */
5115   if (arg->opnum == 1
5116       && mips_fix_cn63xxp1
5117       && !mips_opts.micromips
5118       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
5119     switch (uval)
5120       {
5121       case 5:
5122       case 25:
5123       case 26:
5124       case 27:
5125       case 28:
5126       case 29:
5127       case 30:
5128       case 31:
5129         /* These are ok.  */
5130         break;
5131
5132       default:
5133         /* The rest must be changed to 28.  */
5134         uval = 28;
5135         break;
5136       }
5137
5138   insn_insert_operand (arg->insn, operand_base, uval);
5139   return TRUE;
5140 }
5141
5142 /* OP_MAPPED_INT matcher.  */
5143
5144 static bfd_boolean
5145 match_mapped_int_operand (struct mips_arg_info *arg,
5146                           const struct mips_operand *operand_base)
5147 {
5148   const struct mips_mapped_int_operand *operand;
5149   unsigned int uval, num_vals;
5150   offsetT sval;
5151
5152   operand = (const struct mips_mapped_int_operand *) operand_base;
5153   if (!match_const_int (arg, &sval))
5154     return FALSE;
5155
5156   num_vals = 1 << operand_base->size;
5157   for (uval = 0; uval < num_vals; uval++)
5158     if (operand->int_map[uval] == sval)
5159       break;
5160   if (uval == num_vals)
5161     {
5162       match_out_of_range (arg);
5163       return FALSE;
5164     }
5165
5166   insn_insert_operand (arg->insn, operand_base, uval);
5167   return TRUE;
5168 }
5169
5170 /* OP_MSB matcher.  */
5171
5172 static bfd_boolean
5173 match_msb_operand (struct mips_arg_info *arg,
5174                    const struct mips_operand *operand_base)
5175 {
5176   const struct mips_msb_operand *operand;
5177   int min_val, max_val, max_high;
5178   offsetT size, sval, high;
5179
5180   operand = (const struct mips_msb_operand *) operand_base;
5181   min_val = operand->bias;
5182   max_val = min_val + (1 << operand_base->size) - 1;
5183   max_high = operand->opsize;
5184
5185   if (!match_const_int (arg, &size))
5186     return FALSE;
5187
5188   high = size + arg->last_op_int;
5189   sval = operand->add_lsb ? high : size;
5190
5191   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
5192     {
5193       match_out_of_range (arg);
5194       return FALSE;
5195     }
5196   insn_insert_operand (arg->insn, operand_base, sval - min_val);
5197   return TRUE;
5198 }
5199
5200 /* OP_REG matcher.  */
5201
5202 static bfd_boolean
5203 match_reg_operand (struct mips_arg_info *arg,
5204                    const struct mips_operand *operand_base)
5205 {
5206   const struct mips_reg_operand *operand;
5207   unsigned int regno, uval, num_vals;
5208
5209   operand = (const struct mips_reg_operand *) operand_base;
5210   if (!match_reg (arg, operand->reg_type, &regno))
5211     return FALSE;
5212
5213   if (operand->reg_map)
5214     {
5215       num_vals = 1 << operand->root.size;
5216       for (uval = 0; uval < num_vals; uval++)
5217         if (operand->reg_map[uval] == regno)
5218           break;
5219       if (num_vals == uval)
5220         return FALSE;
5221     }
5222   else
5223     uval = regno;
5224
5225   arg->last_regno = regno;
5226   if (arg->opnum == 1)
5227     arg->dest_regno = regno;
5228   insn_insert_operand (arg->insn, operand_base, uval);
5229   return TRUE;
5230 }
5231
5232 /* OP_REG_PAIR matcher.  */
5233
5234 static bfd_boolean
5235 match_reg_pair_operand (struct mips_arg_info *arg,
5236                         const struct mips_operand *operand_base)
5237 {
5238   const struct mips_reg_pair_operand *operand;
5239   unsigned int regno1, regno2, uval, num_vals;
5240
5241   operand = (const struct mips_reg_pair_operand *) operand_base;
5242   if (!match_reg (arg, operand->reg_type, &regno1)
5243       || !match_char (arg, ',')
5244       || !match_reg (arg, operand->reg_type, &regno2))
5245     return FALSE;
5246
5247   num_vals = 1 << operand_base->size;
5248   for (uval = 0; uval < num_vals; uval++)
5249     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
5250       break;
5251   if (uval == num_vals)
5252     return FALSE;
5253
5254   insn_insert_operand (arg->insn, operand_base, uval);
5255   return TRUE;
5256 }
5257
5258 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
5259
5260 static bfd_boolean
5261 match_pcrel_operand (struct mips_arg_info *arg)
5262 {
5263   bfd_reloc_code_real_type r[3];
5264
5265   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
5266 }
5267
5268 /* OP_PERF_REG matcher.  */
5269
5270 static bfd_boolean
5271 match_perf_reg_operand (struct mips_arg_info *arg,
5272                         const struct mips_operand *operand)
5273 {
5274   offsetT sval;
5275
5276   if (!match_const_int (arg, &sval))
5277     return FALSE;
5278
5279   if (sval != 0
5280       && (sval != 1
5281           || (mips_opts.arch == CPU_R5900
5282               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
5283                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
5284     {
5285       set_insn_error (arg->argnum, _("invalid performance register"));
5286       return FALSE;
5287     }
5288
5289   insn_insert_operand (arg->insn, operand, sval);
5290   return TRUE;
5291 }
5292
5293 /* OP_ADDIUSP matcher.  */
5294
5295 static bfd_boolean
5296 match_addiusp_operand (struct mips_arg_info *arg,
5297                        const struct mips_operand *operand)
5298 {
5299   offsetT sval;
5300   unsigned int uval;
5301
5302   if (!match_const_int (arg, &sval))
5303     return FALSE;
5304
5305   if (sval % 4)
5306     {
5307       match_out_of_range (arg);
5308       return FALSE;
5309     }
5310
5311   sval /= 4;
5312   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
5313     {
5314       match_out_of_range (arg);
5315       return FALSE;
5316     }
5317
5318   uval = (unsigned int) sval;
5319   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
5320   insn_insert_operand (arg->insn, operand, uval);
5321   return TRUE;
5322 }
5323
5324 /* OP_CLO_CLZ_DEST matcher.  */
5325
5326 static bfd_boolean
5327 match_clo_clz_dest_operand (struct mips_arg_info *arg,
5328                             const struct mips_operand *operand)
5329 {
5330   unsigned int regno;
5331
5332   if (!match_reg (arg, OP_REG_GP, &regno))
5333     return FALSE;
5334
5335   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5336   return TRUE;
5337 }
5338
5339 /* OP_CHECK_PREV matcher.  */
5340
5341 static bfd_boolean
5342 match_check_prev_operand (struct mips_arg_info *arg,
5343                           const struct mips_operand *operand_base)
5344 {
5345   const struct mips_check_prev_operand *operand;
5346   unsigned int regno;
5347
5348   operand = (const struct mips_check_prev_operand *) operand_base;
5349
5350   if (!match_reg (arg, OP_REG_GP, &regno))
5351     return FALSE;
5352
5353   if (!operand->zero_ok && regno == 0)
5354     return FALSE;
5355
5356   if ((operand->less_than_ok && regno < arg->last_regno)
5357       || (operand->greater_than_ok && regno > arg->last_regno)
5358       || (operand->equal_ok && regno == arg->last_regno))
5359     {
5360       arg->last_regno = regno;
5361       insn_insert_operand (arg->insn, operand_base, regno);
5362       return TRUE;
5363     }
5364
5365   return FALSE;
5366 }
5367
5368 /* OP_SAME_RS_RT matcher.  */
5369
5370 static bfd_boolean
5371 match_same_rs_rt_operand (struct mips_arg_info *arg,
5372                           const struct mips_operand *operand)
5373 {
5374   unsigned int regno;
5375
5376   if (!match_reg (arg, OP_REG_GP, &regno))
5377     return FALSE;
5378
5379   if (regno == 0)
5380     {
5381       set_insn_error (arg->argnum, _("the source register must not be $0"));
5382       return FALSE;
5383     }
5384
5385   arg->last_regno = regno;
5386
5387   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5388   return TRUE;
5389 }
5390
5391 /* OP_LWM_SWM_LIST matcher.  */
5392
5393 static bfd_boolean
5394 match_lwm_swm_list_operand (struct mips_arg_info *arg,
5395                             const struct mips_operand *operand)
5396 {
5397   unsigned int reglist, sregs, ra, regno1, regno2;
5398   struct mips_arg_info reset;
5399
5400   reglist = 0;
5401   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5402     return FALSE;
5403   do
5404     {
5405       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5406         {
5407           reglist |= 1 << FP;
5408           regno2 = S7;
5409         }
5410       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5411       reset = *arg;
5412     }
5413   while (match_char (arg, ',')
5414          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5415   *arg = reset;
5416
5417   if (operand->size == 2)
5418     {
5419       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5420
5421          s0, ra
5422          s0, s1, ra, s2, s3
5423          s0-s2, ra
5424
5425          and any permutations of these.  */
5426       if ((reglist & 0xfff1ffff) != 0x80010000)
5427         return FALSE;
5428
5429       sregs = (reglist >> 17) & 7;
5430       ra = 0;
5431     }
5432   else
5433     {
5434       /* The list must include at least one of ra and s0-sN,
5435          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5436          which are $23 and $30 respectively.)  E.g.:
5437
5438          ra
5439          s0
5440          ra, s0, s1, s2
5441          s0-s8
5442          s0-s5, ra
5443
5444          and any permutations of these.  */
5445       if ((reglist & 0x3f00ffff) != 0)
5446         return FALSE;
5447
5448       ra = (reglist >> 27) & 0x10;
5449       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5450     }
5451   sregs += 1;
5452   if ((sregs & -sregs) != sregs)
5453     return FALSE;
5454
5455   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5456   return TRUE;
5457 }
5458
5459 /* OP_ENTRY_EXIT_LIST matcher.  */
5460
5461 static unsigned int
5462 match_entry_exit_operand (struct mips_arg_info *arg,
5463                           const struct mips_operand *operand)
5464 {
5465   unsigned int mask;
5466   bfd_boolean is_exit;
5467
5468   /* The format is the same for both ENTRY and EXIT, but the constraints
5469      are different.  */
5470   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5471   mask = (is_exit ? 7 << 3 : 0);
5472   do
5473     {
5474       unsigned int regno1, regno2;
5475       bfd_boolean is_freg;
5476
5477       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5478         is_freg = FALSE;
5479       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5480         is_freg = TRUE;
5481       else
5482         return FALSE;
5483
5484       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5485         {
5486           mask &= ~(7 << 3);
5487           mask |= (5 + regno2) << 3;
5488         }
5489       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5490         mask |= (regno2 - 3) << 3;
5491       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5492         mask |= (regno2 - 15) << 1;
5493       else if (regno1 == RA && regno2 == RA)
5494         mask |= 1;
5495       else
5496         return FALSE;
5497     }
5498   while (match_char (arg, ','));
5499
5500   insn_insert_operand (arg->insn, operand, mask);
5501   return TRUE;
5502 }
5503
5504 /* OP_SAVE_RESTORE_LIST matcher.  */
5505
5506 static bfd_boolean
5507 match_save_restore_list_operand (struct mips_arg_info *arg)
5508 {
5509   unsigned int opcode, args, statics, sregs;
5510   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5511   offsetT frame_size;
5512
5513   opcode = arg->insn->insn_opcode;
5514   frame_size = 0;
5515   num_frame_sizes = 0;
5516   args = 0;
5517   statics = 0;
5518   sregs = 0;
5519   do
5520     {
5521       unsigned int regno1, regno2;
5522
5523       if (arg->token->type == OT_INTEGER)
5524         {
5525           /* Handle the frame size.  */
5526           if (!match_const_int (arg, &frame_size))
5527             return FALSE;
5528           num_frame_sizes += 1;
5529         }
5530       else
5531         {
5532           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5533             return FALSE;
5534
5535           while (regno1 <= regno2)
5536             {
5537               if (regno1 >= 4 && regno1 <= 7)
5538                 {
5539                   if (num_frame_sizes == 0)
5540                     /* args $a0-$a3 */
5541                     args |= 1 << (regno1 - 4);
5542                   else
5543                     /* statics $a0-$a3 */
5544                     statics |= 1 << (regno1 - 4);
5545                 }
5546               else if (regno1 >= 16 && regno1 <= 23)
5547                 /* $s0-$s7 */
5548                 sregs |= 1 << (regno1 - 16);
5549               else if (regno1 == 30)
5550                 /* $s8 */
5551                 sregs |= 1 << 8;
5552               else if (regno1 == 31)
5553                 /* Add $ra to insn.  */
5554                 opcode |= 0x40;
5555               else
5556                 return FALSE;
5557               regno1 += 1;
5558               if (regno1 == 24)
5559                 regno1 = 30;
5560             }
5561         }
5562     }
5563   while (match_char (arg, ','));
5564
5565   /* Encode args/statics combination.  */
5566   if (args & statics)
5567     return FALSE;
5568   else if (args == 0xf)
5569     /* All $a0-$a3 are args.  */
5570     opcode |= MIPS16_ALL_ARGS << 16;
5571   else if (statics == 0xf)
5572     /* All $a0-$a3 are statics.  */
5573     opcode |= MIPS16_ALL_STATICS << 16;
5574   else
5575     {
5576       /* Count arg registers.  */
5577       num_args = 0;
5578       while (args & 0x1)
5579         {
5580           args >>= 1;
5581           num_args += 1;
5582         }
5583       if (args != 0)
5584         return FALSE;
5585
5586       /* Count static registers.  */
5587       num_statics = 0;
5588       while (statics & 0x8)
5589         {
5590           statics = (statics << 1) & 0xf;
5591           num_statics += 1;
5592         }
5593       if (statics != 0)
5594         return FALSE;
5595
5596       /* Encode args/statics.  */
5597       opcode |= ((num_args << 2) | num_statics) << 16;
5598     }
5599
5600   /* Encode $s0/$s1.  */
5601   if (sregs & (1 << 0))         /* $s0 */
5602     opcode |= 0x20;
5603   if (sregs & (1 << 1))         /* $s1 */
5604     opcode |= 0x10;
5605   sregs >>= 2;
5606
5607   /* Encode $s2-$s8. */
5608   num_sregs = 0;
5609   while (sregs & 1)
5610     {
5611       sregs >>= 1;
5612       num_sregs += 1;
5613     }
5614   if (sregs != 0)
5615     return FALSE;
5616   opcode |= num_sregs << 24;
5617
5618   /* Encode frame size.  */
5619   if (num_frame_sizes == 0)
5620     {
5621       set_insn_error (arg->argnum, _("missing frame size"));
5622       return FALSE;
5623     }
5624   if (num_frame_sizes > 1)
5625     {
5626       set_insn_error (arg->argnum, _("frame size specified twice"));
5627       return FALSE;
5628     }
5629   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5630     {
5631       set_insn_error (arg->argnum, _("invalid frame size"));
5632       return FALSE;
5633     }
5634   if (frame_size != 128 || (opcode >> 16) != 0)
5635     {
5636       frame_size /= 8;
5637       opcode |= (((frame_size & 0xf0) << 16)
5638                  | (frame_size & 0x0f));
5639     }
5640
5641   /* Finally build the instruction.  */
5642   if ((opcode >> 16) != 0 || frame_size == 0)
5643     opcode |= MIPS16_EXTEND;
5644   arg->insn->insn_opcode = opcode;
5645   return TRUE;
5646 }
5647
5648 /* OP_MDMX_IMM_REG matcher.  */
5649
5650 static bfd_boolean
5651 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5652                             const struct mips_operand *operand)
5653 {
5654   unsigned int regno, uval;
5655   bfd_boolean is_qh;
5656   const struct mips_opcode *opcode;
5657
5658   /* The mips_opcode records whether this is an octobyte or quadhalf
5659      instruction.  Start out with that bit in place.  */
5660   opcode = arg->insn->insn_mo;
5661   uval = mips_extract_operand (operand, opcode->match);
5662   is_qh = (uval != 0);
5663
5664   if (arg->token->type == OT_REG)
5665     {
5666       if ((opcode->membership & INSN_5400)
5667           && strcmp (opcode->name, "rzu.ob") == 0)
5668         {
5669           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5670                             arg->argnum);
5671           return FALSE;
5672         }
5673
5674       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5675         return FALSE;
5676       ++arg->token;
5677
5678       /* Check whether this is a vector register or a broadcast of
5679          a single element.  */
5680       if (arg->token->type == OT_INTEGER_INDEX)
5681         {
5682           if (arg->token->u.index > (is_qh ? 3 : 7))
5683             {
5684               set_insn_error (arg->argnum, _("invalid element selector"));
5685               return FALSE;
5686             }
5687           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5688           ++arg->token;
5689         }
5690       else
5691         {
5692           /* A full vector.  */
5693           if ((opcode->membership & INSN_5400)
5694               && (strcmp (opcode->name, "sll.ob") == 0
5695                   || strcmp (opcode->name, "srl.ob") == 0))
5696             {
5697               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5698                                 arg->argnum);
5699               return FALSE;
5700             }
5701
5702           if (is_qh)
5703             uval |= MDMX_FMTSEL_VEC_QH << 5;
5704           else
5705             uval |= MDMX_FMTSEL_VEC_OB << 5;
5706         }
5707       uval |= regno;
5708     }
5709   else
5710     {
5711       offsetT sval;
5712
5713       if (!match_const_int (arg, &sval))
5714         return FALSE;
5715       if (sval < 0 || sval > 31)
5716         {
5717           match_out_of_range (arg);
5718           return FALSE;
5719         }
5720       uval |= (sval & 31);
5721       if (is_qh)
5722         uval |= MDMX_FMTSEL_IMM_QH << 5;
5723       else
5724         uval |= MDMX_FMTSEL_IMM_OB << 5;
5725     }
5726   insn_insert_operand (arg->insn, operand, uval);
5727   return TRUE;
5728 }
5729
5730 /* OP_IMM_INDEX matcher.  */
5731
5732 static bfd_boolean
5733 match_imm_index_operand (struct mips_arg_info *arg,
5734                          const struct mips_operand *operand)
5735 {
5736   unsigned int max_val;
5737
5738   if (arg->token->type != OT_INTEGER_INDEX)
5739     return FALSE;
5740
5741   max_val = (1 << operand->size) - 1;
5742   if (arg->token->u.index > max_val)
5743     {
5744       match_out_of_range (arg);
5745       return FALSE;
5746     }
5747   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5748   ++arg->token;
5749   return TRUE;
5750 }
5751
5752 /* OP_REG_INDEX matcher.  */
5753
5754 static bfd_boolean
5755 match_reg_index_operand (struct mips_arg_info *arg,
5756                          const struct mips_operand *operand)
5757 {
5758   unsigned int regno;
5759
5760   if (arg->token->type != OT_REG_INDEX)
5761     return FALSE;
5762
5763   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5764     return FALSE;
5765
5766   insn_insert_operand (arg->insn, operand, regno);
5767   ++arg->token;
5768   return TRUE;
5769 }
5770
5771 /* OP_PC matcher.  */
5772
5773 static bfd_boolean
5774 match_pc_operand (struct mips_arg_info *arg)
5775 {
5776   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5777     {
5778       ++arg->token;
5779       return TRUE;
5780     }
5781   return FALSE;
5782 }
5783
5784 /* OP_NON_ZERO_REG matcher.  */
5785
5786 static bfd_boolean
5787 match_non_zero_reg_operand (struct mips_arg_info *arg,
5788                             const struct mips_operand *operand)
5789 {
5790   unsigned int regno;
5791
5792   if (!match_reg (arg, OP_REG_GP, &regno))
5793     return FALSE;
5794
5795   if (regno == 0)
5796     return FALSE;
5797
5798   arg->last_regno = regno;
5799   insn_insert_operand (arg->insn, operand, regno);
5800   return TRUE;
5801 }
5802
5803 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5804    register that we need to match.  */
5805
5806 static bfd_boolean
5807 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5808 {
5809   unsigned int regno;
5810
5811   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5812 }
5813
5814 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5815    the length of the value in bytes (4 for float, 8 for double) and
5816    USING_GPRS says whether the destination is a GPR rather than an FPR.
5817
5818    Return the constant in IMM and OFFSET as follows:
5819
5820    - If the constant should be loaded via memory, set IMM to O_absent and
5821      OFFSET to the memory address.
5822
5823    - Otherwise, if the constant should be loaded into two 32-bit registers,
5824      set IMM to the O_constant to load into the high register and OFFSET
5825      to the corresponding value for the low register.
5826
5827    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5828
5829    These constants only appear as the last operand in an instruction,
5830    and every instruction that accepts them in any variant accepts them
5831    in all variants.  This means we don't have to worry about backing out
5832    any changes if the instruction does not match.  We just match
5833    unconditionally and report an error if the constant is invalid.  */
5834
5835 static bfd_boolean
5836 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5837                       expressionS *offset, int length, bfd_boolean using_gprs)
5838 {
5839   char *p;
5840   segT seg, new_seg;
5841   subsegT subseg;
5842   const char *newname;
5843   unsigned char *data;
5844
5845   /* Where the constant is placed is based on how the MIPS assembler
5846      does things:
5847
5848      length == 4 && using_gprs  -- immediate value only
5849      length == 8 && using_gprs  -- .rdata or immediate value
5850      length == 4 && !using_gprs -- .lit4 or immediate value
5851      length == 8 && !using_gprs -- .lit8 or immediate value
5852
5853      The .lit4 and .lit8 sections are only used if permitted by the
5854      -G argument.  */
5855   if (arg->token->type != OT_FLOAT)
5856     {
5857       set_insn_error (arg->argnum, _("floating-point expression required"));
5858       return FALSE;
5859     }
5860
5861   gas_assert (arg->token->u.flt.length == length);
5862   data = arg->token->u.flt.data;
5863   ++arg->token;
5864
5865   /* Handle 32-bit constants for which an immediate value is best.  */
5866   if (length == 4
5867       && (using_gprs
5868           || g_switch_value < 4
5869           || (data[0] == 0 && data[1] == 0)
5870           || (data[2] == 0 && data[3] == 0)))
5871     {
5872       imm->X_op = O_constant;
5873       if (!target_big_endian)
5874         imm->X_add_number = bfd_getl32 (data);
5875       else
5876         imm->X_add_number = bfd_getb32 (data);
5877       offset->X_op = O_absent;
5878       return TRUE;
5879     }
5880
5881   /* Handle 64-bit constants for which an immediate value is best.  */
5882   if (length == 8
5883       && !mips_disable_float_construction
5884       /* Constants can only be constructed in GPRs and copied to FPRs if the
5885          GPRs are at least as wide as the FPRs or MTHC1 is available.
5886          Unlike most tests for 32-bit floating-point registers this check
5887          specifically looks for GPR_SIZE == 32 as the FPXX ABI does not
5888          permit 64-bit moves without MXHC1.
5889          Force the constant into memory otherwise.  */
5890       && (using_gprs
5891           || GPR_SIZE == 64
5892           || ISA_HAS_MXHC1 (mips_opts.isa)
5893           || FPR_SIZE == 32)
5894       && ((data[0] == 0 && data[1] == 0)
5895           || (data[2] == 0 && data[3] == 0))
5896       && ((data[4] == 0 && data[5] == 0)
5897           || (data[6] == 0 && data[7] == 0)))
5898     {
5899       /* The value is simple enough to load with a couple of instructions.
5900          If using 32-bit registers, set IMM to the high order 32 bits and
5901          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5902          64 bit constant.  */
5903       if (GPR_SIZE == 32 || (!using_gprs && FPR_SIZE != 64))
5904         {
5905           imm->X_op = O_constant;
5906           offset->X_op = O_constant;
5907           if (!target_big_endian)
5908             {
5909               imm->X_add_number = bfd_getl32 (data + 4);
5910               offset->X_add_number = bfd_getl32 (data);
5911             }
5912           else
5913             {
5914               imm->X_add_number = bfd_getb32 (data);
5915               offset->X_add_number = bfd_getb32 (data + 4);
5916             }
5917           if (offset->X_add_number == 0)
5918             offset->X_op = O_absent;
5919         }
5920       else
5921         {
5922           imm->X_op = O_constant;
5923           if (!target_big_endian)
5924             imm->X_add_number = bfd_getl64 (data);
5925           else
5926             imm->X_add_number = bfd_getb64 (data);
5927           offset->X_op = O_absent;
5928         }
5929       return TRUE;
5930     }
5931
5932   /* Switch to the right section.  */
5933   seg = now_seg;
5934   subseg = now_subseg;
5935   if (length == 4)
5936     {
5937       gas_assert (!using_gprs && g_switch_value >= 4);
5938       newname = ".lit4";
5939     }
5940   else
5941     {
5942       if (using_gprs || g_switch_value < 8)
5943         newname = RDATA_SECTION_NAME;
5944       else
5945         newname = ".lit8";
5946     }
5947
5948   new_seg = subseg_new (newname, (subsegT) 0);
5949   bfd_set_section_flags (stdoutput, new_seg,
5950                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5951   frag_align (length == 4 ? 2 : 3, 0, 0);
5952   if (strncmp (TARGET_OS, "elf", 3) != 0)
5953     record_alignment (new_seg, 4);
5954   else
5955     record_alignment (new_seg, length == 4 ? 2 : 3);
5956   if (seg == now_seg)
5957     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5958
5959   /* Set the argument to the current address in the section.  */
5960   imm->X_op = O_absent;
5961   offset->X_op = O_symbol;
5962   offset->X_add_symbol = symbol_temp_new_now ();
5963   offset->X_add_number = 0;
5964
5965   /* Put the floating point number into the section.  */
5966   p = frag_more (length);
5967   memcpy (p, data, length);
5968
5969   /* Switch back to the original section.  */
5970   subseg_set (seg, subseg);
5971   return TRUE;
5972 }
5973
5974 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5975    them.  */
5976
5977 static bfd_boolean
5978 match_vu0_suffix_operand (struct mips_arg_info *arg,
5979                           const struct mips_operand *operand,
5980                           bfd_boolean match_p)
5981 {
5982   unsigned int uval;
5983
5984   /* The operand can be an XYZW mask or a single 2-bit channel index
5985      (with X being 0).  */
5986   gas_assert (operand->size == 2 || operand->size == 4);
5987
5988   /* The suffix can be omitted when it is already part of the opcode.  */
5989   if (arg->token->type != OT_CHANNELS)
5990     return match_p;
5991
5992   uval = arg->token->u.channels;
5993   if (operand->size == 2)
5994     {
5995       /* Check that a single bit is set and convert it into a 2-bit index.  */
5996       if ((uval & -uval) != uval)
5997         return FALSE;
5998       uval = 4 - ffs (uval);
5999     }
6000
6001   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
6002     return FALSE;
6003
6004   ++arg->token;
6005   if (!match_p)
6006     insn_insert_operand (arg->insn, operand, uval);
6007   return TRUE;
6008 }
6009
6010 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
6011    of the argument text if the match is successful, otherwise return null.  */
6012
6013 static bfd_boolean
6014 match_operand (struct mips_arg_info *arg,
6015                const struct mips_operand *operand)
6016 {
6017   switch (operand->type)
6018     {
6019     case OP_INT:
6020       return match_int_operand (arg, operand);
6021
6022     case OP_MAPPED_INT:
6023       return match_mapped_int_operand (arg, operand);
6024
6025     case OP_MSB:
6026       return match_msb_operand (arg, operand);
6027
6028     case OP_REG:
6029     case OP_OPTIONAL_REG:
6030       return match_reg_operand (arg, operand);
6031
6032     case OP_REG_PAIR:
6033       return match_reg_pair_operand (arg, operand);
6034
6035     case OP_PCREL:
6036       return match_pcrel_operand (arg);
6037
6038     case OP_PERF_REG:
6039       return match_perf_reg_operand (arg, operand);
6040
6041     case OP_ADDIUSP_INT:
6042       return match_addiusp_operand (arg, operand);
6043
6044     case OP_CLO_CLZ_DEST:
6045       return match_clo_clz_dest_operand (arg, operand);
6046
6047     case OP_LWM_SWM_LIST:
6048       return match_lwm_swm_list_operand (arg, operand);
6049
6050     case OP_ENTRY_EXIT_LIST:
6051       return match_entry_exit_operand (arg, operand);
6052
6053     case OP_SAVE_RESTORE_LIST:
6054       return match_save_restore_list_operand (arg);
6055
6056     case OP_MDMX_IMM_REG:
6057       return match_mdmx_imm_reg_operand (arg, operand);
6058
6059     case OP_REPEAT_DEST_REG:
6060       return match_tied_reg_operand (arg, arg->dest_regno);
6061
6062     case OP_REPEAT_PREV_REG:
6063       return match_tied_reg_operand (arg, arg->last_regno);
6064
6065     case OP_PC:
6066       return match_pc_operand (arg);
6067
6068     case OP_VU0_SUFFIX:
6069       return match_vu0_suffix_operand (arg, operand, FALSE);
6070
6071     case OP_VU0_MATCH_SUFFIX:
6072       return match_vu0_suffix_operand (arg, operand, TRUE);
6073
6074     case OP_IMM_INDEX:
6075       return match_imm_index_operand (arg, operand);
6076
6077     case OP_REG_INDEX:
6078       return match_reg_index_operand (arg, operand);
6079
6080     case OP_SAME_RS_RT:
6081       return match_same_rs_rt_operand (arg, operand);
6082
6083     case OP_CHECK_PREV:
6084       return match_check_prev_operand (arg, operand);
6085
6086     case OP_NON_ZERO_REG:
6087       return match_non_zero_reg_operand (arg, operand);
6088     }
6089   abort ();
6090 }
6091
6092 /* ARG is the state after successfully matching an instruction.
6093    Issue any queued-up warnings.  */
6094
6095 static void
6096 check_completed_insn (struct mips_arg_info *arg)
6097 {
6098   if (arg->seen_at)
6099     {
6100       if (AT == ATREG)
6101         as_warn (_("used $at without \".set noat\""));
6102       else
6103         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
6104     }
6105 }
6106
6107 /* Return true if modifying general-purpose register REG needs a delay.  */
6108
6109 static bfd_boolean
6110 reg_needs_delay (unsigned int reg)
6111 {
6112   unsigned long prev_pinfo;
6113
6114   prev_pinfo = history[0].insn_mo->pinfo;
6115   if (!mips_opts.noreorder
6116       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
6117           || ((prev_pinfo & INSN_LOAD_COPROC) && !cop_interlocks))
6118       && (gpr_write_mask (&history[0]) & (1 << reg)))
6119     return TRUE;
6120
6121   return FALSE;
6122 }
6123
6124 /* Classify an instruction according to the FIX_VR4120_* enumeration.
6125    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
6126    by VR4120 errata.  */
6127
6128 static unsigned int
6129 classify_vr4120_insn (const char *name)
6130 {
6131   if (strncmp (name, "macc", 4) == 0)
6132     return FIX_VR4120_MACC;
6133   if (strncmp (name, "dmacc", 5) == 0)
6134     return FIX_VR4120_DMACC;
6135   if (strncmp (name, "mult", 4) == 0)
6136     return FIX_VR4120_MULT;
6137   if (strncmp (name, "dmult", 5) == 0)
6138     return FIX_VR4120_DMULT;
6139   if (strstr (name, "div"))
6140     return FIX_VR4120_DIV;
6141   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
6142     return FIX_VR4120_MTHILO;
6143   return NUM_FIX_VR4120_CLASSES;
6144 }
6145
6146 #define INSN_ERET       0x42000018
6147 #define INSN_DERET      0x4200001f
6148 #define INSN_DMULT      0x1c
6149 #define INSN_DMULTU     0x1d
6150
6151 /* Return the number of instructions that must separate INSN1 and INSN2,
6152    where INSN1 is the earlier instruction.  Return the worst-case value
6153    for any INSN2 if INSN2 is null.  */
6154
6155 static unsigned int
6156 insns_between (const struct mips_cl_insn *insn1,
6157                const struct mips_cl_insn *insn2)
6158 {
6159   unsigned long pinfo1, pinfo2;
6160   unsigned int mask;
6161
6162   /* If INFO2 is null, pessimistically assume that all flags are set for
6163      the second instruction.  */
6164   pinfo1 = insn1->insn_mo->pinfo;
6165   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
6166
6167   /* For most targets, write-after-read dependencies on the HI and LO
6168      registers must be separated by at least two instructions.  */
6169   if (!hilo_interlocks)
6170     {
6171       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
6172         return 2;
6173       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
6174         return 2;
6175     }
6176
6177   /* If we're working around r7000 errata, there must be two instructions
6178      between an mfhi or mflo and any instruction that uses the result.  */
6179   if (mips_7000_hilo_fix
6180       && !mips_opts.micromips
6181       && MF_HILO_INSN (pinfo1)
6182       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
6183     return 2;
6184
6185   /* If we're working around 24K errata, one instruction is required
6186      if an ERET or DERET is followed by a branch instruction.  */
6187   if (mips_fix_24k && !mips_opts.micromips)
6188     {
6189       if (insn1->insn_opcode == INSN_ERET
6190           || insn1->insn_opcode == INSN_DERET)
6191         {
6192           if (insn2 == NULL
6193               || insn2->insn_opcode == INSN_ERET
6194               || insn2->insn_opcode == INSN_DERET
6195               || delayed_branch_p (insn2))
6196             return 1;
6197         }
6198     }
6199
6200   /* If we're working around PMC RM7000 errata, there must be three
6201      nops between a dmult and a load instruction.  */
6202   if (mips_fix_rm7000 && !mips_opts.micromips)
6203     {
6204       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
6205           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
6206         {
6207           if (pinfo2 & INSN_LOAD_MEMORY)
6208            return 3;
6209         }
6210     }
6211
6212   /* If working around VR4120 errata, check for combinations that need
6213      a single intervening instruction.  */
6214   if (mips_fix_vr4120 && !mips_opts.micromips)
6215     {
6216       unsigned int class1, class2;
6217
6218       class1 = classify_vr4120_insn (insn1->insn_mo->name);
6219       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
6220         {
6221           if (insn2 == NULL)
6222             return 1;
6223           class2 = classify_vr4120_insn (insn2->insn_mo->name);
6224           if (vr4120_conflicts[class1] & (1 << class2))
6225             return 1;
6226         }
6227     }
6228
6229   if (!HAVE_CODE_COMPRESSION)
6230     {
6231       /* Check for GPR or coprocessor load delays.  All such delays
6232          are on the RT register.  */
6233       /* Itbl support may require additional care here.  */
6234       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
6235           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC)))
6236         {
6237           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
6238             return 1;
6239         }
6240
6241       /* Check for generic coprocessor hazards.
6242
6243          This case is not handled very well.  There is no special
6244          knowledge of CP0 handling, and the coprocessors other than
6245          the floating point unit are not distinguished at all.  */
6246       /* Itbl support may require additional care here. FIXME!
6247          Need to modify this to include knowledge about
6248          user specified delays!  */
6249       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE))
6250                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
6251         {
6252           /* Handle cases where INSN1 writes to a known general coprocessor
6253              register.  There must be a one instruction delay before INSN2
6254              if INSN2 reads that register, otherwise no delay is needed.  */
6255           mask = fpr_write_mask (insn1);
6256           if (mask != 0)
6257             {
6258               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
6259                 return 1;
6260             }
6261           else
6262             {
6263               /* Read-after-write dependencies on the control registers
6264                  require a two-instruction gap.  */
6265               if ((pinfo1 & INSN_WRITE_COND_CODE)
6266                   && (pinfo2 & INSN_READ_COND_CODE))
6267                 return 2;
6268
6269               /* We don't know exactly what INSN1 does.  If INSN2 is
6270                  also a coprocessor instruction, assume there must be
6271                  a one instruction gap.  */
6272               if (pinfo2 & INSN_COP)
6273                 return 1;
6274             }
6275         }
6276
6277       /* Check for read-after-write dependencies on the coprocessor
6278          control registers in cases where INSN1 does not need a general
6279          coprocessor delay.  This means that INSN1 is a floating point
6280          comparison instruction.  */
6281       /* Itbl support may require additional care here.  */
6282       else if (!cop_interlocks
6283                && (pinfo1 & INSN_WRITE_COND_CODE)
6284                && (pinfo2 & INSN_READ_COND_CODE))
6285         return 1;
6286     }
6287
6288   /* Forbidden slots can not contain Control Transfer Instructions (CTIs)
6289      CTIs include all branches and jumps, nal, eret, eretnc, deret, wait
6290      and pause.  */
6291   if ((insn1->insn_mo->pinfo2 & INSN2_FORBIDDEN_SLOT)
6292       && ((pinfo2 & INSN_NO_DELAY_SLOT)
6293           || (insn2 && delayed_branch_p (insn2))))
6294     return 1;
6295
6296   return 0;
6297 }
6298
6299 /* Return the number of nops that would be needed to work around the
6300    VR4130 mflo/mfhi errata if instruction INSN immediately followed
6301    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
6302    that are contained within the first IGNORE instructions of HIST.  */
6303
6304 static int
6305 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
6306                  const struct mips_cl_insn *insn)
6307 {
6308   int i, j;
6309   unsigned int mask;
6310
6311   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
6312      are not affected by the errata.  */
6313   if (insn != 0
6314       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
6315           || strcmp (insn->insn_mo->name, "mtlo") == 0
6316           || strcmp (insn->insn_mo->name, "mthi") == 0))
6317     return 0;
6318
6319   /* Search for the first MFLO or MFHI.  */
6320   for (i = 0; i < MAX_VR4130_NOPS; i++)
6321     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
6322       {
6323         /* Extract the destination register.  */
6324         mask = gpr_write_mask (&hist[i]);
6325
6326         /* No nops are needed if INSN reads that register.  */
6327         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
6328           return 0;
6329
6330         /* ...or if any of the intervening instructions do.  */
6331         for (j = 0; j < i; j++)
6332           if (gpr_read_mask (&hist[j]) & mask)
6333             return 0;
6334
6335         if (i >= ignore)
6336           return MAX_VR4130_NOPS - i;
6337       }
6338   return 0;
6339 }
6340
6341 #define BASE_REG_EQ(INSN1, INSN2)       \
6342   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
6343       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
6344
6345 /* Return the minimum alignment for this store instruction.  */
6346
6347 static int
6348 fix_24k_align_to (const struct mips_opcode *mo)
6349 {
6350   if (strcmp (mo->name, "sh") == 0)
6351     return 2;
6352
6353   if (strcmp (mo->name, "swc1") == 0
6354       || strcmp (mo->name, "swc2") == 0
6355       || strcmp (mo->name, "sw") == 0
6356       || strcmp (mo->name, "sc") == 0
6357       || strcmp (mo->name, "s.s") == 0)
6358     return 4;
6359
6360   if (strcmp (mo->name, "sdc1") == 0
6361       || strcmp (mo->name, "sdc2") == 0
6362       || strcmp (mo->name, "s.d") == 0)
6363     return 8;
6364
6365   /* sb, swl, swr */
6366   return 1;
6367 }
6368
6369 struct fix_24k_store_info
6370   {
6371     /* Immediate offset, if any, for this store instruction.  */
6372     short off;
6373     /* Alignment required by this store instruction.  */
6374     int align_to;
6375     /* True for register offsets.  */
6376     int register_offset;
6377   };
6378
6379 /* Comparison function used by qsort.  */
6380
6381 static int
6382 fix_24k_sort (const void *a, const void *b)
6383 {
6384   const struct fix_24k_store_info *pos1 = a;
6385   const struct fix_24k_store_info *pos2 = b;
6386
6387   return (pos1->off - pos2->off);
6388 }
6389
6390 /* INSN is a store instruction.  Try to record the store information
6391    in STINFO.  Return false if the information isn't known.  */
6392
6393 static bfd_boolean
6394 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
6395                            const struct mips_cl_insn *insn)
6396 {
6397   /* The instruction must have a known offset.  */
6398   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
6399     return FALSE;
6400
6401   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
6402   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
6403   return TRUE;
6404 }
6405
6406 /* Return the number of nops that would be needed to work around the 24k
6407    "lost data on stores during refill" errata if instruction INSN
6408    immediately followed the 2 instructions described by HIST.
6409    Ignore hazards that are contained within the first IGNORE
6410    instructions of HIST.
6411
6412    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6413    for the data cache refills and store data. The following describes
6414    the scenario where the store data could be lost.
6415
6416    * A data cache miss, due to either a load or a store, causing fill
6417      data to be supplied by the memory subsystem
6418    * The first three doublewords of fill data are returned and written
6419      into the cache
6420    * A sequence of four stores occurs in consecutive cycles around the
6421      final doubleword of the fill:
6422    * Store A
6423    * Store B
6424    * Store C
6425    * Zero, One or more instructions
6426    * Store D
6427
6428    The four stores A-D must be to different doublewords of the line that
6429    is being filled. The fourth instruction in the sequence above permits
6430    the fill of the final doubleword to be transferred from the FSB into
6431    the cache. In the sequence above, the stores may be either integer
6432    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6433    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6434    different doublewords on the line. If the floating point unit is
6435    running in 1:2 mode, it is not possible to create the sequence above
6436    using only floating point store instructions.
6437
6438    In this case, the cache line being filled is incorrectly marked
6439    invalid, thereby losing the data from any store to the line that
6440    occurs between the original miss and the completion of the five
6441    cycle sequence shown above.
6442
6443    The workarounds are:
6444
6445    * Run the data cache in write-through mode.
6446    * Insert a non-store instruction between
6447      Store A and Store B or Store B and Store C.  */
6448
6449 static int
6450 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6451               const struct mips_cl_insn *insn)
6452 {
6453   struct fix_24k_store_info pos[3];
6454   int align, i, base_offset;
6455
6456   if (ignore >= 2)
6457     return 0;
6458
6459   /* If the previous instruction wasn't a store, there's nothing to
6460      worry about.  */
6461   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6462     return 0;
6463
6464   /* If the instructions after the previous one are unknown, we have
6465      to assume the worst.  */
6466   if (!insn)
6467     return 1;
6468
6469   /* Check whether we are dealing with three consecutive stores.  */
6470   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6471       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6472     return 0;
6473
6474   /* If we don't know the relationship between the store addresses,
6475      assume the worst.  */
6476   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6477       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6478     return 1;
6479
6480   if (!fix_24k_record_store_info (&pos[0], insn)
6481       || !fix_24k_record_store_info (&pos[1], &hist[0])
6482       || !fix_24k_record_store_info (&pos[2], &hist[1]))
6483     return 1;
6484
6485   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6486
6487   /* Pick a value of ALIGN and X such that all offsets are adjusted by
6488      X bytes and such that the base register + X is known to be aligned
6489      to align bytes.  */
6490
6491   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6492     align = 8;
6493   else
6494     {
6495       align = pos[0].align_to;
6496       base_offset = pos[0].off;
6497       for (i = 1; i < 3; i++)
6498         if (align < pos[i].align_to)
6499           {
6500             align = pos[i].align_to;
6501             base_offset = pos[i].off;
6502           }
6503       for (i = 0; i < 3; i++)
6504         pos[i].off -= base_offset;
6505     }
6506
6507   pos[0].off &= ~align + 1;
6508   pos[1].off &= ~align + 1;
6509   pos[2].off &= ~align + 1;
6510
6511   /* If any two stores write to the same chunk, they also write to the
6512      same doubleword.  The offsets are still sorted at this point.  */
6513   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6514     return 0;
6515
6516   /* A range of at least 9 bytes is needed for the stores to be in
6517      non-overlapping doublewords.  */
6518   if (pos[2].off - pos[0].off <= 8)
6519     return 0;
6520
6521   if (pos[2].off - pos[1].off >= 24
6522       || pos[1].off - pos[0].off >= 24
6523       || pos[2].off - pos[0].off >= 32)
6524     return 0;
6525
6526   return 1;
6527 }
6528
6529 /* Return the number of nops that would be needed if instruction INSN
6530    immediately followed the MAX_NOPS instructions given by HIST,
6531    where HIST[0] is the most recent instruction.  Ignore hazards
6532    between INSN and the first IGNORE instructions in HIST.
6533
6534    If INSN is null, return the worse-case number of nops for any
6535    instruction.  */
6536
6537 static int
6538 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6539                const struct mips_cl_insn *insn)
6540 {
6541   int i, nops, tmp_nops;
6542
6543   nops = 0;
6544   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6545     {
6546       tmp_nops = insns_between (hist + i, insn) - i;
6547       if (tmp_nops > nops)
6548         nops = tmp_nops;
6549     }
6550
6551   if (mips_fix_vr4130 && !mips_opts.micromips)
6552     {
6553       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6554       if (tmp_nops > nops)
6555         nops = tmp_nops;
6556     }
6557
6558   if (mips_fix_24k && !mips_opts.micromips)
6559     {
6560       tmp_nops = nops_for_24k (ignore, hist, insn);
6561       if (tmp_nops > nops)
6562         nops = tmp_nops;
6563     }
6564
6565   return nops;
6566 }
6567
6568 /* The variable arguments provide NUM_INSNS extra instructions that
6569    might be added to HIST.  Return the largest number of nops that
6570    would be needed after the extended sequence, ignoring hazards
6571    in the first IGNORE instructions.  */
6572
6573 static int
6574 nops_for_sequence (int num_insns, int ignore,
6575                    const struct mips_cl_insn *hist, ...)
6576 {
6577   va_list args;
6578   struct mips_cl_insn buffer[MAX_NOPS];
6579   struct mips_cl_insn *cursor;
6580   int nops;
6581
6582   va_start (args, hist);
6583   cursor = buffer + num_insns;
6584   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6585   while (cursor > buffer)
6586     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6587
6588   nops = nops_for_insn (ignore, buffer, NULL);
6589   va_end (args);
6590   return nops;
6591 }
6592
6593 /* Like nops_for_insn, but if INSN is a branch, take into account the
6594    worst-case delay for the branch target.  */
6595
6596 static int
6597 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6598                          const struct mips_cl_insn *insn)
6599 {
6600   int nops, tmp_nops;
6601
6602   nops = nops_for_insn (ignore, hist, insn);
6603   if (delayed_branch_p (insn))
6604     {
6605       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6606                                     hist, insn, get_delay_slot_nop (insn));
6607       if (tmp_nops > nops)
6608         nops = tmp_nops;
6609     }
6610   else if (compact_branch_p (insn))
6611     {
6612       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6613       if (tmp_nops > nops)
6614         nops = tmp_nops;
6615     }
6616   return nops;
6617 }
6618
6619 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6620
6621 static void
6622 fix_loongson2f_nop (struct mips_cl_insn * ip)
6623 {
6624   gas_assert (!HAVE_CODE_COMPRESSION);
6625   if (strcmp (ip->insn_mo->name, "nop") == 0)
6626     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6627 }
6628
6629 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6630                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6631
6632 static void
6633 fix_loongson2f_jump (struct mips_cl_insn * ip)
6634 {
6635   gas_assert (!HAVE_CODE_COMPRESSION);
6636   if (strcmp (ip->insn_mo->name, "j") == 0
6637       || strcmp (ip->insn_mo->name, "jr") == 0
6638       || strcmp (ip->insn_mo->name, "jalr") == 0)
6639     {
6640       int sreg;
6641       expressionS ep;
6642
6643       if (! mips_opts.at)
6644         return;
6645
6646       sreg = EXTRACT_OPERAND (0, RS, *ip);
6647       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6648         return;
6649
6650       ep.X_op = O_constant;
6651       ep.X_add_number = 0xcfff0000;
6652       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6653       ep.X_add_number = 0xffff;
6654       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6655       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6656     }
6657 }
6658
6659 static void
6660 fix_loongson2f (struct mips_cl_insn * ip)
6661 {
6662   if (mips_fix_loongson2f_nop)
6663     fix_loongson2f_nop (ip);
6664
6665   if (mips_fix_loongson2f_jump)
6666     fix_loongson2f_jump (ip);
6667 }
6668
6669 /* IP is a branch that has a delay slot, and we need to fill it
6670    automatically.   Return true if we can do that by swapping IP
6671    with the previous instruction.
6672    ADDRESS_EXPR is an operand of the instruction to be used with
6673    RELOC_TYPE.  */
6674
6675 static bfd_boolean
6676 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6677                    bfd_reloc_code_real_type *reloc_type)
6678 {
6679   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6680   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6681   unsigned int fpr_read, prev_fpr_write;
6682
6683   /* -O2 and above is required for this optimization.  */
6684   if (mips_optimize < 2)
6685     return FALSE;
6686
6687   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6688   if (mips_opts.nomove)
6689     return FALSE;
6690
6691   /* We can't swap if the previous instruction's position is fixed.  */
6692   if (history[0].fixed_p)
6693     return FALSE;
6694
6695   /* If the previous previous insn was in a .set noreorder, we can't
6696      swap.  Actually, the MIPS assembler will swap in this situation.
6697      However, gcc configured -with-gnu-as will generate code like
6698
6699         .set    noreorder
6700         lw      $4,XXX
6701         .set    reorder
6702         INSN
6703         bne     $4,$0,foo
6704
6705      in which we can not swap the bne and INSN.  If gcc is not configured
6706      -with-gnu-as, it does not output the .set pseudo-ops.  */
6707   if (history[1].noreorder_p)
6708     return FALSE;
6709
6710   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6711      This means that the previous instruction was a 4-byte one anyhow.  */
6712   if (mips_opts.mips16 && history[0].fixp[0])
6713     return FALSE;
6714
6715   /* If the branch is itself the target of a branch, we can not swap.
6716      We cheat on this; all we check for is whether there is a label on
6717      this instruction.  If there are any branches to anything other than
6718      a label, users must use .set noreorder.  */
6719   if (seg_info (now_seg)->label_list)
6720     return FALSE;
6721
6722   /* If the previous instruction is in a variant frag other than this
6723      branch's one, we cannot do the swap.  This does not apply to
6724      MIPS16 code, which uses variant frags for different purposes.  */
6725   if (!mips_opts.mips16
6726       && history[0].frag
6727       && history[0].frag->fr_type == rs_machine_dependent)
6728     return FALSE;
6729
6730   /* We do not swap with instructions that cannot architecturally
6731      be placed in a branch delay slot, such as SYNC or ERET.  We
6732      also refrain from swapping with a trap instruction, since it
6733      complicates trap handlers to have the trap instruction be in
6734      a delay slot.  */
6735   prev_pinfo = history[0].insn_mo->pinfo;
6736   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6737     return FALSE;
6738
6739   /* Check for conflicts between the branch and the instructions
6740      before the candidate delay slot.  */
6741   if (nops_for_insn (0, history + 1, ip) > 0)
6742     return FALSE;
6743
6744   /* Check for conflicts between the swapped sequence and the
6745      target of the branch.  */
6746   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6747     return FALSE;
6748
6749   /* If the branch reads a register that the previous
6750      instruction sets, we can not swap.  */
6751   gpr_read = gpr_read_mask (ip);
6752   prev_gpr_write = gpr_write_mask (&history[0]);
6753   if (gpr_read & prev_gpr_write)
6754     return FALSE;
6755
6756   fpr_read = fpr_read_mask (ip);
6757   prev_fpr_write = fpr_write_mask (&history[0]);
6758   if (fpr_read & prev_fpr_write)
6759     return FALSE;
6760
6761   /* If the branch writes a register that the previous
6762      instruction sets, we can not swap.  */
6763   gpr_write = gpr_write_mask (ip);
6764   if (gpr_write & prev_gpr_write)
6765     return FALSE;
6766
6767   /* If the branch writes a register that the previous
6768      instruction reads, we can not swap.  */
6769   prev_gpr_read = gpr_read_mask (&history[0]);
6770   if (gpr_write & prev_gpr_read)
6771     return FALSE;
6772
6773   /* If one instruction sets a condition code and the
6774      other one uses a condition code, we can not swap.  */
6775   pinfo = ip->insn_mo->pinfo;
6776   if ((pinfo & INSN_READ_COND_CODE)
6777       && (prev_pinfo & INSN_WRITE_COND_CODE))
6778     return FALSE;
6779   if ((pinfo & INSN_WRITE_COND_CODE)
6780       && (prev_pinfo & INSN_READ_COND_CODE))
6781     return FALSE;
6782
6783   /* If the previous instruction uses the PC, we can not swap.  */
6784   prev_pinfo2 = history[0].insn_mo->pinfo2;
6785   if (prev_pinfo2 & INSN2_READ_PC)
6786     return FALSE;
6787
6788   /* If the previous instruction has an incorrect size for a fixed
6789      branch delay slot in microMIPS mode, we cannot swap.  */
6790   pinfo2 = ip->insn_mo->pinfo2;
6791   if (mips_opts.micromips
6792       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6793       && insn_length (history) != 2)
6794     return FALSE;
6795   if (mips_opts.micromips
6796       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6797       && insn_length (history) != 4)
6798     return FALSE;
6799
6800   /* On R5900 short loops need to be fixed by inserting a nop in
6801      the branch delay slots.
6802      A short loop can be terminated too early.  */
6803   if (mips_opts.arch == CPU_R5900
6804       /* Check if instruction has a parameter, ignore "j $31". */
6805       && (address_expr != NULL)
6806       /* Parameter must be 16 bit. */
6807       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6808       /* Branch to same segment. */
6809       && (S_GET_SEGMENT (address_expr->X_add_symbol) == now_seg)
6810       /* Branch to same code fragment. */
6811       && (symbol_get_frag (address_expr->X_add_symbol) == frag_now)
6812       /* Can only calculate branch offset if value is known. */
6813       && symbol_constant_p (address_expr->X_add_symbol)
6814       /* Check if branch is really conditional. */
6815       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6816         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6817         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6818     {
6819       int distance;
6820       /* Check if loop is shorter than 6 instructions including
6821          branch and delay slot.  */
6822       distance = frag_now_fix () - S_GET_VALUE (address_expr->X_add_symbol);
6823       if (distance <= 20)
6824         {
6825           int i;
6826           int rv;
6827
6828           rv = FALSE;
6829           /* When the loop includes branches or jumps,
6830              it is not a short loop. */
6831           for (i = 0; i < (distance / 4); i++)
6832             {
6833               if ((history[i].cleared_p)
6834                   || delayed_branch_p (&history[i]))
6835                 {
6836                   rv = TRUE;
6837                   break;
6838                 }
6839             }
6840           if (rv == FALSE)
6841             {
6842               /* Insert nop after branch to fix short loop. */
6843               return FALSE;
6844             }
6845         }
6846     }
6847
6848   return TRUE;
6849 }
6850
6851 /* Decide how we should add IP to the instruction stream.
6852    ADDRESS_EXPR is an operand of the instruction to be used with
6853    RELOC_TYPE.  */
6854
6855 static enum append_method
6856 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6857                    bfd_reloc_code_real_type *reloc_type)
6858 {
6859   /* The relaxed version of a macro sequence must be inherently
6860      hazard-free.  */
6861   if (mips_relax.sequence == 2)
6862     return APPEND_ADD;
6863
6864   /* We must not dabble with instructions in a ".set noreorder" block.  */
6865   if (mips_opts.noreorder)
6866     return APPEND_ADD;
6867
6868   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6869   if (delayed_branch_p (ip))
6870     {
6871       if (!branch_likely_p (ip)
6872           && can_swap_branch_p (ip, address_expr, reloc_type))
6873         return APPEND_SWAP;
6874
6875       if (mips_opts.mips16
6876           && ISA_SUPPORTS_MIPS16E
6877           && gpr_read_mask (ip) != 0)
6878         return APPEND_ADD_COMPACT;
6879
6880       if (mips_opts.micromips
6881           && ((ip->insn_opcode & 0xffe0) == 0x4580
6882               || (!forced_insn_length
6883                   && ((ip->insn_opcode & 0xfc00) == 0xcc00
6884                       || (ip->insn_opcode & 0xdc00) == 0x8c00))
6885               || (ip->insn_opcode & 0xdfe00000) == 0x94000000
6886               || (ip->insn_opcode & 0xdc1f0000) == 0x94000000))
6887         return APPEND_ADD_COMPACT;
6888
6889       return APPEND_ADD_WITH_NOP;
6890     }
6891
6892   return APPEND_ADD;
6893 }
6894
6895 /* IP is an instruction whose opcode we have just changed, END points
6896    to the end of the opcode table processed.  Point IP->insn_mo to the
6897    new opcode's definition.  */
6898
6899 static void
6900 find_altered_opcode (struct mips_cl_insn *ip, const struct mips_opcode *end)
6901 {
6902   const struct mips_opcode *mo;
6903
6904   for (mo = ip->insn_mo; mo < end; mo++)
6905     if (mo->pinfo != INSN_MACRO
6906         && (ip->insn_opcode & mo->mask) == mo->match)
6907       {
6908         ip->insn_mo = mo;
6909         return;
6910       }
6911   abort ();
6912 }
6913
6914 /* IP is a MIPS16 instruction whose opcode we have just changed.
6915    Point IP->insn_mo to the new opcode's definition.  */
6916
6917 static void
6918 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6919 {
6920   find_altered_opcode (ip, &mips16_opcodes[bfd_mips16_num_opcodes]);
6921 }
6922
6923 /* IP is a microMIPS instruction whose opcode we have just changed.
6924    Point IP->insn_mo to the new opcode's definition.  */
6925
6926 static void
6927 find_altered_micromips_opcode (struct mips_cl_insn *ip)
6928 {
6929   find_altered_opcode (ip, &micromips_opcodes[bfd_micromips_num_opcodes]);
6930 }
6931
6932 /* For microMIPS macros, we need to generate a local number label
6933    as the target of branches.  */
6934 #define MICROMIPS_LABEL_CHAR            '\037'
6935 static unsigned long micromips_target_label;
6936 static char micromips_target_name[32];
6937
6938 static char *
6939 micromips_label_name (void)
6940 {
6941   char *p = micromips_target_name;
6942   char symbol_name_temporary[24];
6943   unsigned long l;
6944   int i;
6945
6946   if (*p)
6947     return p;
6948
6949   i = 0;
6950   l = micromips_target_label;
6951 #ifdef LOCAL_LABEL_PREFIX
6952   *p++ = LOCAL_LABEL_PREFIX;
6953 #endif
6954   *p++ = 'L';
6955   *p++ = MICROMIPS_LABEL_CHAR;
6956   do
6957     {
6958       symbol_name_temporary[i++] = l % 10 + '0';
6959       l /= 10;
6960     }
6961   while (l != 0);
6962   while (i > 0)
6963     *p++ = symbol_name_temporary[--i];
6964   *p = '\0';
6965
6966   return micromips_target_name;
6967 }
6968
6969 static void
6970 micromips_label_expr (expressionS *label_expr)
6971 {
6972   label_expr->X_op = O_symbol;
6973   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6974   label_expr->X_add_number = 0;
6975 }
6976
6977 static void
6978 micromips_label_inc (void)
6979 {
6980   micromips_target_label++;
6981   *micromips_target_name = '\0';
6982 }
6983
6984 static void
6985 micromips_add_label (void)
6986 {
6987   symbolS *s;
6988
6989   s = colon (micromips_label_name ());
6990   micromips_label_inc ();
6991   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6992 }
6993
6994 /* If assembling microMIPS code, then return the microMIPS reloc
6995    corresponding to the requested one if any.  Otherwise return
6996    the reloc unchanged.  */
6997
6998 static bfd_reloc_code_real_type
6999 micromips_map_reloc (bfd_reloc_code_real_type reloc)
7000 {
7001   static const bfd_reloc_code_real_type relocs[][2] =
7002     {
7003       /* Keep sorted incrementally by the left-hand key.  */
7004       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
7005       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
7006       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
7007       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
7008       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
7009       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
7010       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
7011       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
7012       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
7013       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
7014       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
7015       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
7016       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
7017       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
7018       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
7019       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
7020       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
7021       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
7022       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
7023       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
7024       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
7025       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
7026       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
7027       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
7028       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
7029       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
7030       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
7031     };
7032   bfd_reloc_code_real_type r;
7033   size_t i;
7034
7035   if (!mips_opts.micromips)
7036     return reloc;
7037   for (i = 0; i < ARRAY_SIZE (relocs); i++)
7038     {
7039       r = relocs[i][0];
7040       if (r > reloc)
7041         return reloc;
7042       if (r == reloc)
7043         return relocs[i][1];
7044     }
7045   return reloc;
7046 }
7047
7048 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
7049    Return true on success, storing the resolved value in RESULT.  */
7050
7051 static bfd_boolean
7052 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
7053                  offsetT *result)
7054 {
7055   switch (reloc)
7056     {
7057     case BFD_RELOC_MIPS_HIGHEST:
7058     case BFD_RELOC_MICROMIPS_HIGHEST:
7059       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
7060       return TRUE;
7061
7062     case BFD_RELOC_MIPS_HIGHER:
7063     case BFD_RELOC_MICROMIPS_HIGHER:
7064       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
7065       return TRUE;
7066
7067     case BFD_RELOC_HI16_S:
7068     case BFD_RELOC_HI16_S_PCREL:
7069     case BFD_RELOC_MICROMIPS_HI16_S:
7070     case BFD_RELOC_MIPS16_HI16_S:
7071       *result = ((operand + 0x8000) >> 16) & 0xffff;
7072       return TRUE;
7073
7074     case BFD_RELOC_HI16:
7075     case BFD_RELOC_MICROMIPS_HI16:
7076     case BFD_RELOC_MIPS16_HI16:
7077       *result = (operand >> 16) & 0xffff;
7078       return TRUE;
7079
7080     case BFD_RELOC_LO16:
7081     case BFD_RELOC_LO16_PCREL:
7082     case BFD_RELOC_MICROMIPS_LO16:
7083     case BFD_RELOC_MIPS16_LO16:
7084       *result = operand & 0xffff;
7085       return TRUE;
7086
7087     case BFD_RELOC_UNUSED:
7088       *result = operand;
7089       return TRUE;
7090
7091     default:
7092       return FALSE;
7093     }
7094 }
7095
7096 /* Output an instruction.  IP is the instruction information.
7097    ADDRESS_EXPR is an operand of the instruction to be used with
7098    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
7099    a macro expansion.  */
7100
7101 static void
7102 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
7103              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
7104 {
7105   unsigned long prev_pinfo2, pinfo;
7106   bfd_boolean relaxed_branch = FALSE;
7107   enum append_method method;
7108   bfd_boolean relax32;
7109   int branch_disp;
7110
7111   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
7112     fix_loongson2f (ip);
7113
7114   file_ase_mips16 |= mips_opts.mips16;
7115   file_ase_micromips |= mips_opts.micromips;
7116
7117   prev_pinfo2 = history[0].insn_mo->pinfo2;
7118   pinfo = ip->insn_mo->pinfo;
7119
7120   /* Don't raise alarm about `nods' frags as they'll fill in the right
7121      kind of nop in relaxation if required.  */
7122   if (mips_opts.micromips
7123       && !expansionp
7124       && !(history[0].frag
7125            && history[0].frag->fr_type == rs_machine_dependent
7126            && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
7127            && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
7128       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
7129            && micromips_insn_length (ip->insn_mo) != 2)
7130           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
7131               && micromips_insn_length (ip->insn_mo) != 4)))
7132     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
7133              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
7134
7135   if (address_expr == NULL)
7136     ip->complete_p = 1;
7137   else if (reloc_type[0] <= BFD_RELOC_UNUSED
7138            && reloc_type[1] == BFD_RELOC_UNUSED
7139            && reloc_type[2] == BFD_RELOC_UNUSED
7140            && address_expr->X_op == O_constant)
7141     {
7142       switch (*reloc_type)
7143         {
7144         case BFD_RELOC_MIPS_JMP:
7145           {
7146             int shift;
7147
7148             /* Shift is 2, unusually, for microMIPS JALX.  */
7149             shift = (mips_opts.micromips
7150                      && strcmp (ip->insn_mo->name, "jalx") != 0) ? 1 : 2;
7151             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7152               as_bad (_("jump to misaligned address (0x%lx)"),
7153                       (unsigned long) address_expr->X_add_number);
7154             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7155                                 & 0x3ffffff);
7156             ip->complete_p = 1;
7157           }
7158           break;
7159
7160         case BFD_RELOC_MIPS16_JMP:
7161           if ((address_expr->X_add_number & 3) != 0)
7162             as_bad (_("jump to misaligned address (0x%lx)"),
7163                     (unsigned long) address_expr->X_add_number);
7164           ip->insn_opcode |=
7165             (((address_expr->X_add_number & 0x7c0000) << 3)
7166                | ((address_expr->X_add_number & 0xf800000) >> 7)
7167                | ((address_expr->X_add_number & 0x3fffc) >> 2));
7168           ip->complete_p = 1;
7169           break;
7170
7171         case BFD_RELOC_16_PCREL_S2:
7172           {
7173             int shift;
7174
7175             shift = mips_opts.micromips ? 1 : 2;
7176             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7177               as_bad (_("branch to misaligned address (0x%lx)"),
7178                       (unsigned long) address_expr->X_add_number);
7179             if (!mips_relax_branch)
7180               {
7181                 if ((address_expr->X_add_number + (1 << (shift + 15)))
7182                     & ~((1 << (shift + 16)) - 1))
7183                   as_bad (_("branch address range overflow (0x%lx)"),
7184                           (unsigned long) address_expr->X_add_number);
7185                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7186                                     & 0xffff);
7187               }
7188           }
7189           break;
7190
7191         case BFD_RELOC_MIPS_21_PCREL_S2:
7192           {
7193             int shift;
7194
7195             shift = 2;
7196             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7197               as_bad (_("branch to misaligned address (0x%lx)"),
7198                       (unsigned long) address_expr->X_add_number);
7199             if ((address_expr->X_add_number + (1 << (shift + 20)))
7200                 & ~((1 << (shift + 21)) - 1))
7201               as_bad (_("branch address range overflow (0x%lx)"),
7202                       (unsigned long) address_expr->X_add_number);
7203             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7204                                 & 0x1fffff);
7205           }
7206           break;
7207
7208         case BFD_RELOC_MIPS_26_PCREL_S2:
7209           {
7210             int shift;
7211
7212             shift = 2;
7213             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7214               as_bad (_("branch to misaligned address (0x%lx)"),
7215                       (unsigned long) address_expr->X_add_number);
7216             if ((address_expr->X_add_number + (1 << (shift + 25)))
7217                 & ~((1 << (shift + 26)) - 1))
7218               as_bad (_("branch address range overflow (0x%lx)"),
7219                       (unsigned long) address_expr->X_add_number);
7220             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7221                                 & 0x3ffffff);
7222           }
7223           break;
7224
7225         default:
7226           {
7227             offsetT value;
7228
7229             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
7230                                  &value))
7231               {
7232                 ip->insn_opcode |= value & 0xffff;
7233                 ip->complete_p = 1;
7234               }
7235           }
7236           break;
7237         }
7238     }
7239
7240   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
7241     {
7242       /* There are a lot of optimizations we could do that we don't.
7243          In particular, we do not, in general, reorder instructions.
7244          If you use gcc with optimization, it will reorder
7245          instructions and generally do much more optimization then we
7246          do here; repeating all that work in the assembler would only
7247          benefit hand written assembly code, and does not seem worth
7248          it.  */
7249       int nops = (mips_optimize == 0
7250                   ? nops_for_insn (0, history, NULL)
7251                   : nops_for_insn_or_target (0, history, ip));
7252       if (nops > 0)
7253         {
7254           fragS *old_frag;
7255           unsigned long old_frag_offset;
7256           int i;
7257
7258           old_frag = frag_now;
7259           old_frag_offset = frag_now_fix ();
7260
7261           for (i = 0; i < nops; i++)
7262             add_fixed_insn (NOP_INSN);
7263           insert_into_history (0, nops, NOP_INSN);
7264
7265           if (listing)
7266             {
7267               listing_prev_line ();
7268               /* We may be at the start of a variant frag.  In case we
7269                  are, make sure there is enough space for the frag
7270                  after the frags created by listing_prev_line.  The
7271                  argument to frag_grow here must be at least as large
7272                  as the argument to all other calls to frag_grow in
7273                  this file.  We don't have to worry about being in the
7274                  middle of a variant frag, because the variants insert
7275                  all needed nop instructions themselves.  */
7276               frag_grow (40);
7277             }
7278
7279           mips_move_text_labels ();
7280
7281 #ifndef NO_ECOFF_DEBUGGING
7282           if (ECOFF_DEBUGGING)
7283             ecoff_fix_loc (old_frag, old_frag_offset);
7284 #endif
7285         }
7286     }
7287   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
7288     {
7289       int nops;
7290
7291       /* Work out how many nops in prev_nop_frag are needed by IP,
7292          ignoring hazards generated by the first prev_nop_frag_since
7293          instructions.  */
7294       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
7295       gas_assert (nops <= prev_nop_frag_holds);
7296
7297       /* Enforce NOPS as a minimum.  */
7298       if (nops > prev_nop_frag_required)
7299         prev_nop_frag_required = nops;
7300
7301       if (prev_nop_frag_holds == prev_nop_frag_required)
7302         {
7303           /* Settle for the current number of nops.  Update the history
7304              accordingly (for the benefit of any future .set reorder code).  */
7305           prev_nop_frag = NULL;
7306           insert_into_history (prev_nop_frag_since,
7307                                prev_nop_frag_holds, NOP_INSN);
7308         }
7309       else
7310         {
7311           /* Allow this instruction to replace one of the nops that was
7312              tentatively added to prev_nop_frag.  */
7313           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
7314           prev_nop_frag_holds--;
7315           prev_nop_frag_since++;
7316         }
7317     }
7318
7319   method = get_append_method (ip, address_expr, reloc_type);
7320   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
7321
7322   dwarf2_emit_insn (0);
7323   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
7324      so "move" the instruction address accordingly.
7325
7326      Also, it doesn't seem appropriate for the assembler to reorder .loc
7327      entries.  If this instruction is a branch that we are going to swap
7328      with the previous instruction, the two instructions should be
7329      treated as a unit, and the debug information for both instructions
7330      should refer to the start of the branch sequence.  Using the
7331      current position is certainly wrong when swapping a 32-bit branch
7332      and a 16-bit delay slot, since the current position would then be
7333      in the middle of a branch.  */
7334   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
7335
7336   relax32 = (mips_relax_branch
7337              /* Don't try branch relaxation within .set nomacro, or within
7338                 .set noat if we use $at for PIC computations.  If it turns
7339                 out that the branch was out-of-range, we'll get an error.  */
7340              && !mips_opts.warn_about_macros
7341              && (mips_opts.at || mips_pic == NO_PIC)
7342              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
7343                 as they have no complementing branches.  */
7344              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
7345
7346   if (!HAVE_CODE_COMPRESSION
7347       && address_expr
7348       && relax32
7349       && *reloc_type == BFD_RELOC_16_PCREL_S2
7350       && delayed_branch_p (ip))
7351     {
7352       relaxed_branch = TRUE;
7353       add_relaxed_insn (ip, (relaxed_branch_length
7354                              (NULL, NULL,
7355                               uncond_branch_p (ip) ? -1
7356                               : branch_likely_p (ip) ? 1
7357                               : 0)), 4,
7358                         RELAX_BRANCH_ENCODE
7359                         (AT, mips_pic != NO_PIC,
7360                          uncond_branch_p (ip),
7361                          branch_likely_p (ip),
7362                          pinfo & INSN_WRITE_GPR_31,
7363                          0),
7364                         address_expr->X_add_symbol,
7365                         address_expr->X_add_number);
7366       *reloc_type = BFD_RELOC_UNUSED;
7367     }
7368   else if (mips_opts.micromips
7369            && address_expr
7370            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
7371                || *reloc_type > BFD_RELOC_UNUSED)
7372            && (delayed_branch_p (ip) || compact_branch_p (ip))
7373            /* Don't try branch relaxation when users specify
7374               16-bit/32-bit instructions.  */
7375            && !forced_insn_length)
7376     {
7377       bfd_boolean relax16 = (method != APPEND_ADD_COMPACT
7378                              && *reloc_type > BFD_RELOC_UNUSED);
7379       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
7380       int uncond = uncond_branch_p (ip) ? -1 : 0;
7381       int compact = compact_branch_p (ip) || method == APPEND_ADD_COMPACT;
7382       int nods = method == APPEND_ADD_WITH_NOP;
7383       int al = pinfo & INSN_WRITE_GPR_31;
7384       int length32 = nods ? 8 : 4;
7385
7386       gas_assert (address_expr != NULL);
7387       gas_assert (!mips_relax.sequence);
7388
7389       relaxed_branch = TRUE;
7390       if (nods)
7391         method = APPEND_ADD;
7392       if (relax32)
7393         length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
7394       add_relaxed_insn (ip, length32, relax16 ? 2 : 4,
7395                         RELAX_MICROMIPS_ENCODE (type, AT, mips_opts.insn32,
7396                                                 mips_pic != NO_PIC,
7397                                                 uncond, compact, al, nods,
7398                                                 relax32, 0, 0),
7399                         address_expr->X_add_symbol,
7400                         address_expr->X_add_number);
7401       *reloc_type = BFD_RELOC_UNUSED;
7402     }
7403   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
7404     {
7405       bfd_boolean require_unextended;
7406       bfd_boolean require_extended;
7407       symbolS *symbol;
7408       offsetT offset;
7409
7410       if (forced_insn_length != 0)
7411         {
7412           require_unextended = forced_insn_length == 2;
7413           require_extended = forced_insn_length == 4;
7414         }
7415       else
7416         {
7417           require_unextended = (mips_opts.noautoextend
7418                                 && !mips_opcode_32bit_p (ip->insn_mo));
7419           require_extended = 0;
7420         }
7421
7422       /* We need to set up a variant frag.  */
7423       gas_assert (address_expr != NULL);
7424       /* Pass any `O_symbol' expression unchanged as an `expr_section'
7425          symbol created by `make_expr_symbol' may not get a necessary
7426          external relocation produced.  */
7427       if (address_expr->X_op == O_symbol)
7428         {
7429           symbol = address_expr->X_add_symbol;
7430           offset = address_expr->X_add_number;
7431         }
7432       else
7433         {
7434           symbol = make_expr_symbol (address_expr);
7435           symbol_append (symbol, symbol_lastP, &symbol_rootP, &symbol_lastP);
7436           offset = 0;
7437         }
7438       add_relaxed_insn (ip, 12, 0,
7439                         RELAX_MIPS16_ENCODE
7440                         (*reloc_type - BFD_RELOC_UNUSED,
7441                          mips_pic != NO_PIC,
7442                          HAVE_32BIT_SYMBOLS,
7443                          mips_opts.warn_about_macros,
7444                          require_unextended, require_extended,
7445                          delayed_branch_p (&history[0]),
7446                          history[0].mips16_absolute_jump_p),
7447                         symbol, offset);
7448     }
7449   else if (mips_opts.mips16 && insn_length (ip) == 2)
7450     {
7451       if (!delayed_branch_p (ip))
7452         /* Make sure there is enough room to swap this instruction with
7453            a following jump instruction.  */
7454         frag_grow (6);
7455       add_fixed_insn (ip);
7456     }
7457   else
7458     {
7459       if (mips_opts.mips16
7460           && mips_opts.noreorder
7461           && delayed_branch_p (&history[0]))
7462         as_warn (_("extended instruction in delay slot"));
7463
7464       if (mips_relax.sequence)
7465         {
7466           /* If we've reached the end of this frag, turn it into a variant
7467              frag and record the information for the instructions we've
7468              written so far.  */
7469           if (frag_room () < 4)
7470             relax_close_frag ();
7471           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
7472         }
7473
7474       if (mips_relax.sequence != 2)
7475         {
7476           if (mips_macro_warning.first_insn_sizes[0] == 0)
7477             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
7478           mips_macro_warning.sizes[0] += insn_length (ip);
7479           mips_macro_warning.insns[0]++;
7480         }
7481       if (mips_relax.sequence != 1)
7482         {
7483           if (mips_macro_warning.first_insn_sizes[1] == 0)
7484             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
7485           mips_macro_warning.sizes[1] += insn_length (ip);
7486           mips_macro_warning.insns[1]++;
7487         }
7488
7489       if (mips_opts.mips16)
7490         {
7491           ip->fixed_p = 1;
7492           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
7493         }
7494       add_fixed_insn (ip);
7495     }
7496
7497   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
7498     {
7499       bfd_reloc_code_real_type final_type[3];
7500       reloc_howto_type *howto0;
7501       reloc_howto_type *howto;
7502       int i;
7503
7504       /* Perform any necessary conversion to microMIPS relocations
7505          and find out how many relocations there actually are.  */
7506       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
7507         final_type[i] = micromips_map_reloc (reloc_type[i]);
7508
7509       /* In a compound relocation, it is the final (outermost)
7510          operator that determines the relocated field.  */
7511       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
7512       if (!howto)
7513         abort ();
7514
7515       if (i > 1)
7516         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
7517       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
7518                                  bfd_get_reloc_size (howto),
7519                                  address_expr,
7520                                  howto0 && howto0->pc_relative,
7521                                  final_type[0]);
7522       /* Record non-PIC mode in `fx_tcbit2' for `md_apply_fix'.  */
7523       ip->fixp[0]->fx_tcbit2 = mips_pic == NO_PIC;
7524
7525       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
7526       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
7527         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7528
7529       /* These relocations can have an addend that won't fit in
7530          4 octets for 64bit assembly.  */
7531       if (GPR_SIZE == 64
7532           && ! howto->partial_inplace
7533           && (reloc_type[0] == BFD_RELOC_16
7534               || reloc_type[0] == BFD_RELOC_32
7535               || reloc_type[0] == BFD_RELOC_MIPS_JMP
7536               || reloc_type[0] == BFD_RELOC_GPREL16
7537               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
7538               || reloc_type[0] == BFD_RELOC_GPREL32
7539               || reloc_type[0] == BFD_RELOC_64
7540               || reloc_type[0] == BFD_RELOC_CTOR
7541               || reloc_type[0] == BFD_RELOC_MIPS_SUB
7542               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
7543               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
7544               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
7545               || reloc_type[0] == BFD_RELOC_MIPS_REL16
7546               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
7547               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
7548               || hi16_reloc_p (reloc_type[0])
7549               || lo16_reloc_p (reloc_type[0])))
7550         ip->fixp[0]->fx_no_overflow = 1;
7551
7552       /* These relocations can have an addend that won't fit in 2 octets.  */
7553       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
7554           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
7555         ip->fixp[0]->fx_no_overflow = 1;
7556
7557       if (mips_relax.sequence)
7558         {
7559           if (mips_relax.first_fixup == 0)
7560             mips_relax.first_fixup = ip->fixp[0];
7561         }
7562       else if (reloc_needs_lo_p (*reloc_type))
7563         {
7564           struct mips_hi_fixup *hi_fixup;
7565
7566           /* Reuse the last entry if it already has a matching %lo.  */
7567           hi_fixup = mips_hi_fixup_list;
7568           if (hi_fixup == 0
7569               || !fixup_has_matching_lo_p (hi_fixup->fixp))
7570             {
7571               hi_fixup = XNEW (struct mips_hi_fixup);
7572               hi_fixup->next = mips_hi_fixup_list;
7573               mips_hi_fixup_list = hi_fixup;
7574             }
7575           hi_fixup->fixp = ip->fixp[0];
7576           hi_fixup->seg = now_seg;
7577         }
7578
7579       /* Add fixups for the second and third relocations, if given.
7580          Note that the ABI allows the second relocation to be
7581          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
7582          moment we only use RSS_UNDEF, but we could add support
7583          for the others if it ever becomes necessary.  */
7584       for (i = 1; i < 3; i++)
7585         if (reloc_type[i] != BFD_RELOC_UNUSED)
7586           {
7587             ip->fixp[i] = fix_new (ip->frag, ip->where,
7588                                    ip->fixp[0]->fx_size, NULL, 0,
7589                                    FALSE, final_type[i]);
7590
7591             /* Use fx_tcbit to mark compound relocs.  */
7592             ip->fixp[0]->fx_tcbit = 1;
7593             ip->fixp[i]->fx_tcbit = 1;
7594           }
7595     }
7596
7597   /* Update the register mask information.  */
7598   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
7599   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
7600
7601   switch (method)
7602     {
7603     case APPEND_ADD:
7604       insert_into_history (0, 1, ip);
7605       break;
7606
7607     case APPEND_ADD_WITH_NOP:
7608       {
7609         struct mips_cl_insn *nop;
7610
7611         insert_into_history (0, 1, ip);
7612         nop = get_delay_slot_nop (ip);
7613         add_fixed_insn (nop);
7614         insert_into_history (0, 1, nop);
7615         if (mips_relax.sequence)
7616           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
7617       }
7618       break;
7619
7620     case APPEND_ADD_COMPACT:
7621       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
7622       if (mips_opts.mips16)
7623         {
7624           ip->insn_opcode |= 0x0080;
7625           find_altered_mips16_opcode (ip);
7626         }
7627       /* Convert microMIPS instructions.  */
7628       else if (mips_opts.micromips)
7629         {
7630           /* jr16->jrc */
7631           if ((ip->insn_opcode & 0xffe0) == 0x4580)
7632             ip->insn_opcode |= 0x0020;
7633           /* b16->bc */
7634           else if ((ip->insn_opcode & 0xfc00) == 0xcc00)
7635             ip->insn_opcode = 0x40e00000;
7636           /* beqz16->beqzc, bnez16->bnezc */
7637           else if ((ip->insn_opcode & 0xdc00) == 0x8c00)
7638             {
7639               unsigned long regno;
7640
7641               regno = ip->insn_opcode >> MICROMIPSOP_SH_MD;
7642               regno &= MICROMIPSOP_MASK_MD;
7643               regno = micromips_to_32_reg_d_map[regno];
7644               ip->insn_opcode = (((ip->insn_opcode << 9) & 0x00400000)
7645                                  | (regno << MICROMIPSOP_SH_RS)
7646                                  | 0x40a00000) ^ 0x00400000;
7647             }
7648           /* beqz->beqzc, bnez->bnezc */
7649           else if ((ip->insn_opcode & 0xdfe00000) == 0x94000000)
7650             ip->insn_opcode = ((ip->insn_opcode & 0x001f0000)
7651                                | ((ip->insn_opcode >> 7) & 0x00400000)
7652                                | 0x40a00000) ^ 0x00400000;
7653           /* beq $0->beqzc, bne $0->bnezc */
7654           else if ((ip->insn_opcode & 0xdc1f0000) == 0x94000000)
7655             ip->insn_opcode = (((ip->insn_opcode >>
7656                                  (MICROMIPSOP_SH_RT - MICROMIPSOP_SH_RS))
7657                                 & (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS))
7658                                | ((ip->insn_opcode >> 7) & 0x00400000)
7659                                | 0x40a00000) ^ 0x00400000;
7660           else
7661             abort ();
7662           find_altered_micromips_opcode (ip);
7663         }
7664       else
7665         abort ();
7666       install_insn (ip);
7667       insert_into_history (0, 1, ip);
7668       break;
7669
7670     case APPEND_SWAP:
7671       {
7672         struct mips_cl_insn delay = history[0];
7673
7674         if (relaxed_branch || delay.frag != ip->frag)
7675           {
7676             /* Add the delay slot instruction to the end of the
7677                current frag and shrink the fixed part of the
7678                original frag.  If the branch occupies the tail of
7679                the latter, move it backwards to cover the gap.  */
7680             delay.frag->fr_fix -= branch_disp;
7681             if (delay.frag == ip->frag)
7682               move_insn (ip, ip->frag, ip->where - branch_disp);
7683             add_fixed_insn (&delay);
7684           }
7685         else
7686           {
7687             /* If this is not a relaxed branch and we are in the
7688                same frag, then just swap the instructions.  */
7689             move_insn (ip, delay.frag, delay.where);
7690             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
7691           }
7692         history[0] = *ip;
7693         delay.fixed_p = 1;
7694         insert_into_history (0, 1, &delay);
7695       }
7696       break;
7697     }
7698
7699   /* If we have just completed an unconditional branch, clear the history.  */
7700   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7701       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7702     {
7703       unsigned int i;
7704
7705       mips_no_prev_insn ();
7706
7707       for (i = 0; i < ARRAY_SIZE (history); i++)
7708         history[i].cleared_p = 1;
7709     }
7710
7711   /* We need to emit a label at the end of branch-likely macros.  */
7712   if (emit_branch_likely_macro)
7713     {
7714       emit_branch_likely_macro = FALSE;
7715       micromips_add_label ();
7716     }
7717
7718   /* We just output an insn, so the next one doesn't have a label.  */
7719   mips_clear_insn_labels ();
7720 }
7721
7722 /* Forget that there was any previous instruction or label.
7723    When BRANCH is true, the branch history is also flushed.  */
7724
7725 static void
7726 mips_no_prev_insn (void)
7727 {
7728   prev_nop_frag = NULL;
7729   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7730   mips_clear_insn_labels ();
7731 }
7732
7733 /* This function must be called before we emit something other than
7734    instructions.  It is like mips_no_prev_insn except that it inserts
7735    any NOPS that might be needed by previous instructions.  */
7736
7737 void
7738 mips_emit_delays (void)
7739 {
7740   if (! mips_opts.noreorder)
7741     {
7742       int nops = nops_for_insn (0, history, NULL);
7743       if (nops > 0)
7744         {
7745           while (nops-- > 0)
7746             add_fixed_insn (NOP_INSN);
7747           mips_move_text_labels ();
7748         }
7749     }
7750   mips_no_prev_insn ();
7751 }
7752
7753 /* Start a (possibly nested) noreorder block.  */
7754
7755 static void
7756 start_noreorder (void)
7757 {
7758   if (mips_opts.noreorder == 0)
7759     {
7760       unsigned int i;
7761       int nops;
7762
7763       /* None of the instructions before the .set noreorder can be moved.  */
7764       for (i = 0; i < ARRAY_SIZE (history); i++)
7765         history[i].fixed_p = 1;
7766
7767       /* Insert any nops that might be needed between the .set noreorder
7768          block and the previous instructions.  We will later remove any
7769          nops that turn out not to be needed.  */
7770       nops = nops_for_insn (0, history, NULL);
7771       if (nops > 0)
7772         {
7773           if (mips_optimize != 0)
7774             {
7775               /* Record the frag which holds the nop instructions, so
7776                  that we can remove them if we don't need them.  */
7777               frag_grow (nops * NOP_INSN_SIZE);
7778               prev_nop_frag = frag_now;
7779               prev_nop_frag_holds = nops;
7780               prev_nop_frag_required = 0;
7781               prev_nop_frag_since = 0;
7782             }
7783
7784           for (; nops > 0; --nops)
7785             add_fixed_insn (NOP_INSN);
7786
7787           /* Move on to a new frag, so that it is safe to simply
7788              decrease the size of prev_nop_frag.  */
7789           frag_wane (frag_now);
7790           frag_new (0);
7791           mips_move_text_labels ();
7792         }
7793       mips_mark_labels ();
7794       mips_clear_insn_labels ();
7795     }
7796   mips_opts.noreorder++;
7797   mips_any_noreorder = 1;
7798 }
7799
7800 /* End a nested noreorder block.  */
7801
7802 static void
7803 end_noreorder (void)
7804 {
7805   mips_opts.noreorder--;
7806   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7807     {
7808       /* Commit to inserting prev_nop_frag_required nops and go back to
7809          handling nop insertion the .set reorder way.  */
7810       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7811                                 * NOP_INSN_SIZE);
7812       insert_into_history (prev_nop_frag_since,
7813                            prev_nop_frag_required, NOP_INSN);
7814       prev_nop_frag = NULL;
7815     }
7816 }
7817
7818 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7819    higher bits unset.  */
7820
7821 static void
7822 normalize_constant_expr (expressionS *ex)
7823 {
7824   if (ex->X_op == O_constant
7825       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7826     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7827                         - 0x80000000);
7828 }
7829
7830 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7831    all higher bits unset.  */
7832
7833 static void
7834 normalize_address_expr (expressionS *ex)
7835 {
7836   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7837         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7838       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7839     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7840                         - 0x80000000);
7841 }
7842
7843 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7844    Return true if the match was successful.
7845
7846    OPCODE_EXTRA is a value that should be ORed into the opcode
7847    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7848    there are more alternatives after OPCODE and SOFT_MATCH is
7849    as for mips_arg_info.  */
7850
7851 static bfd_boolean
7852 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7853             struct mips_operand_token *tokens, unsigned int opcode_extra,
7854             bfd_boolean lax_match, bfd_boolean complete_p)
7855 {
7856   const char *args;
7857   struct mips_arg_info arg;
7858   const struct mips_operand *operand;
7859   char c;
7860
7861   imm_expr.X_op = O_absent;
7862   offset_expr.X_op = O_absent;
7863   offset_reloc[0] = BFD_RELOC_UNUSED;
7864   offset_reloc[1] = BFD_RELOC_UNUSED;
7865   offset_reloc[2] = BFD_RELOC_UNUSED;
7866
7867   create_insn (insn, opcode);
7868   /* When no opcode suffix is specified, assume ".xyzw". */
7869   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7870     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7871   else
7872     insn->insn_opcode |= opcode_extra;
7873   memset (&arg, 0, sizeof (arg));
7874   arg.insn = insn;
7875   arg.token = tokens;
7876   arg.argnum = 1;
7877   arg.last_regno = ILLEGAL_REG;
7878   arg.dest_regno = ILLEGAL_REG;
7879   arg.lax_match = lax_match;
7880   for (args = opcode->args;; ++args)
7881     {
7882       if (arg.token->type == OT_END)
7883         {
7884           /* Handle unary instructions in which only one operand is given.
7885              The source is then the same as the destination.  */
7886           if (arg.opnum == 1 && *args == ',')
7887             {
7888               operand = (mips_opts.micromips
7889                          ? decode_micromips_operand (args + 1)
7890                          : decode_mips_operand (args + 1));
7891               if (operand && mips_optional_operand_p (operand))
7892                 {
7893                   arg.token = tokens;
7894                   arg.argnum = 1;
7895                   continue;
7896                 }
7897             }
7898
7899           /* Treat elided base registers as $0.  */
7900           if (strcmp (args, "(b)") == 0)
7901             args += 3;
7902
7903           if (args[0] == '+')
7904             switch (args[1])
7905               {
7906               case 'K':
7907               case 'N':
7908                 /* The register suffix is optional. */
7909                 args += 2;
7910                 break;
7911               }
7912
7913           /* Fail the match if there were too few operands.  */
7914           if (*args)
7915             return FALSE;
7916
7917           /* Successful match.  */
7918           if (!complete_p)
7919             return TRUE;
7920           clear_insn_error ();
7921           if (arg.dest_regno == arg.last_regno
7922               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7923             {
7924               if (arg.opnum == 2)
7925                 set_insn_error
7926                   (0, _("source and destination must be different"));
7927               else if (arg.last_regno == 31)
7928                 set_insn_error
7929                   (0, _("a destination register must be supplied"));
7930             }
7931           else if (arg.last_regno == 31
7932                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7933                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7934             set_insn_error (0, _("the source register must not be $31"));
7935           check_completed_insn (&arg);
7936           return TRUE;
7937         }
7938
7939       /* Fail the match if the line has too many operands.   */
7940       if (*args == 0)
7941         return FALSE;
7942
7943       /* Handle characters that need to match exactly.  */
7944       if (*args == '(' || *args == ')' || *args == ',')
7945         {
7946           if (match_char (&arg, *args))
7947             continue;
7948           return FALSE;
7949         }
7950       if (*args == '#')
7951         {
7952           ++args;
7953           if (arg.token->type == OT_DOUBLE_CHAR
7954               && arg.token->u.ch == *args)
7955             {
7956               ++arg.token;
7957               continue;
7958             }
7959           return FALSE;
7960         }
7961
7962       /* Handle special macro operands.  Work out the properties of
7963          other operands.  */
7964       arg.opnum += 1;
7965       switch (*args)
7966         {
7967         case '-':
7968           switch (args[1])
7969             {
7970             case 'A':
7971               *offset_reloc = BFD_RELOC_MIPS_19_PCREL_S2;
7972               break;
7973
7974             case 'B':
7975               *offset_reloc = BFD_RELOC_MIPS_18_PCREL_S3;
7976               break;
7977             }
7978           break;
7979
7980         case '+':
7981           switch (args[1])
7982             {
7983             case 'i':
7984               *offset_reloc = BFD_RELOC_MIPS_JMP;
7985               break;
7986
7987             case '\'':
7988               *offset_reloc = BFD_RELOC_MIPS_26_PCREL_S2;
7989               break;
7990
7991             case '\"':
7992               *offset_reloc = BFD_RELOC_MIPS_21_PCREL_S2;
7993               break;
7994             }
7995           break;
7996
7997         case 'I':
7998           if (!match_const_int (&arg, &imm_expr.X_add_number))
7999             return FALSE;
8000           imm_expr.X_op = O_constant;
8001           if (GPR_SIZE == 32)
8002             normalize_constant_expr (&imm_expr);
8003           continue;
8004
8005         case 'A':
8006           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8007             {
8008               /* Assume that the offset has been elided and that what
8009                  we saw was a base register.  The match will fail later
8010                  if that assumption turns out to be wrong.  */
8011               offset_expr.X_op = O_constant;
8012               offset_expr.X_add_number = 0;
8013             }
8014           else
8015             {
8016               if (!match_expression (&arg, &offset_expr, offset_reloc))
8017                 return FALSE;
8018               normalize_address_expr (&offset_expr);
8019             }
8020           continue;
8021
8022         case 'F':
8023           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8024                                      8, TRUE))
8025             return FALSE;
8026           continue;
8027
8028         case 'L':
8029           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8030                                      8, FALSE))
8031             return FALSE;
8032           continue;
8033
8034         case 'f':
8035           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8036                                      4, TRUE))
8037             return FALSE;
8038           continue;
8039
8040         case 'l':
8041           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8042                                      4, FALSE))
8043             return FALSE;
8044           continue;
8045
8046         case 'p':
8047           *offset_reloc = BFD_RELOC_16_PCREL_S2;
8048           break;
8049
8050         case 'a':
8051           *offset_reloc = BFD_RELOC_MIPS_JMP;
8052           break;
8053
8054         case 'm':
8055           gas_assert (mips_opts.micromips);
8056           c = args[1];
8057           switch (c)
8058             {
8059             case 'D':
8060             case 'E':
8061               if (!forced_insn_length)
8062                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
8063               else if (c == 'D')
8064                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
8065               else
8066                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
8067               break;
8068             }
8069           break;
8070         }
8071
8072       operand = (mips_opts.micromips
8073                  ? decode_micromips_operand (args)
8074                  : decode_mips_operand (args));
8075       if (!operand)
8076         abort ();
8077
8078       /* Skip prefixes.  */
8079       if (*args == '+' || *args == 'm' || *args == '-')
8080         args++;
8081
8082       if (mips_optional_operand_p (operand)
8083           && args[1] == ','
8084           && (arg.token[0].type != OT_REG
8085               || arg.token[1].type == OT_END))
8086         {
8087           /* Assume that the register has been elided and is the
8088              same as the first operand.  */
8089           arg.token = tokens;
8090           arg.argnum = 1;
8091         }
8092
8093       if (!match_operand (&arg, operand))
8094         return FALSE;
8095     }
8096 }
8097
8098 /* Like match_insn, but for MIPS16.  */
8099
8100 static bfd_boolean
8101 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8102                    struct mips_operand_token *tokens)
8103 {
8104   const char *args;
8105   const struct mips_operand *operand;
8106   const struct mips_operand *ext_operand;
8107   bfd_boolean pcrel = FALSE;
8108   int required_insn_length;
8109   struct mips_arg_info arg;
8110   int relax_char;
8111
8112   if (forced_insn_length)
8113     required_insn_length = forced_insn_length;
8114   else if (mips_opts.noautoextend && !mips_opcode_32bit_p (opcode))
8115     required_insn_length = 2;
8116   else
8117     required_insn_length = 0;
8118
8119   create_insn (insn, opcode);
8120   imm_expr.X_op = O_absent;
8121   offset_expr.X_op = O_absent;
8122   offset_reloc[0] = BFD_RELOC_UNUSED;
8123   offset_reloc[1] = BFD_RELOC_UNUSED;
8124   offset_reloc[2] = BFD_RELOC_UNUSED;
8125   relax_char = 0;
8126
8127   memset (&arg, 0, sizeof (arg));
8128   arg.insn = insn;
8129   arg.token = tokens;
8130   arg.argnum = 1;
8131   arg.last_regno = ILLEGAL_REG;
8132   arg.dest_regno = ILLEGAL_REG;
8133   relax_char = 0;
8134   for (args = opcode->args;; ++args)
8135     {
8136       int c;
8137
8138       if (arg.token->type == OT_END)
8139         {
8140           offsetT value;
8141
8142           /* Handle unary instructions in which only one operand is given.
8143              The source is then the same as the destination.  */
8144           if (arg.opnum == 1 && *args == ',')
8145             {
8146               operand = decode_mips16_operand (args[1], FALSE);
8147               if (operand && mips_optional_operand_p (operand))
8148                 {
8149                   arg.token = tokens;
8150                   arg.argnum = 1;
8151                   continue;
8152                 }
8153             }
8154
8155           /* Fail the match if there were too few operands.  */
8156           if (*args)
8157             return FALSE;
8158
8159           /* Successful match.  Stuff the immediate value in now, if
8160              we can.  */
8161           clear_insn_error ();
8162           if (opcode->pinfo == INSN_MACRO)
8163             {
8164               gas_assert (relax_char == 0 || relax_char == 'p');
8165               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
8166             }
8167           else if (relax_char
8168                    && offset_expr.X_op == O_constant
8169                    && !pcrel
8170                    && calculate_reloc (*offset_reloc,
8171                                        offset_expr.X_add_number,
8172                                        &value))
8173             {
8174               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
8175                             required_insn_length, &insn->insn_opcode);
8176               offset_expr.X_op = O_absent;
8177               *offset_reloc = BFD_RELOC_UNUSED;
8178             }
8179           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
8180             {
8181               if (required_insn_length == 2)
8182                 set_insn_error (0, _("invalid unextended operand value"));
8183               else
8184                 {
8185                   forced_insn_length = 4;
8186                   insn->insn_opcode |= MIPS16_EXTEND;
8187                 }
8188             }
8189           else if (relax_char)
8190             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
8191
8192           check_completed_insn (&arg);
8193           return TRUE;
8194         }
8195
8196       /* Fail the match if the line has too many operands.   */
8197       if (*args == 0)
8198         return FALSE;
8199
8200       /* Handle characters that need to match exactly.  */
8201       if (*args == '(' || *args == ')' || *args == ',')
8202         {
8203           if (match_char (&arg, *args))
8204             continue;
8205           return FALSE;
8206         }
8207
8208       arg.opnum += 1;
8209       c = *args;
8210       switch (c)
8211         {
8212         case 'p':
8213         case 'q':
8214         case 'A':
8215         case 'B':
8216         case 'E':
8217           relax_char = c;
8218           break;
8219
8220         case 'I':
8221           if (!match_const_int (&arg, &imm_expr.X_add_number))
8222             return FALSE;
8223           imm_expr.X_op = O_constant;
8224           if (GPR_SIZE == 32)
8225             normalize_constant_expr (&imm_expr);
8226           continue;
8227
8228         case 'a':
8229         case 'i':
8230           *offset_reloc = BFD_RELOC_MIPS16_JMP;
8231           break;
8232         }
8233
8234       operand = decode_mips16_operand (c, mips_opcode_32bit_p (opcode));
8235       if (!operand)
8236         abort ();
8237
8238       if (operand->type == OP_PCREL)
8239         pcrel = TRUE;
8240       else
8241         {
8242           ext_operand = decode_mips16_operand (c, TRUE);
8243           if (operand != ext_operand)
8244             {
8245               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8246                 {
8247                   offset_expr.X_op = O_constant;
8248                   offset_expr.X_add_number = 0;
8249                   relax_char = c;
8250                   continue;
8251                 }
8252
8253               /* We need the OT_INTEGER check because some MIPS16
8254                  immediate variants are listed before the register ones.  */
8255               if (arg.token->type != OT_INTEGER
8256                   || !match_expression (&arg, &offset_expr, offset_reloc))
8257                 return FALSE;
8258
8259               /* '8' is used for SLTI(U) and has traditionally not
8260                  been allowed to take relocation operators.  */
8261               if (offset_reloc[0] != BFD_RELOC_UNUSED
8262                   && (ext_operand->size != 16 || c == '8'))
8263                 return FALSE;
8264
8265               relax_char = c;
8266               continue;
8267             }
8268         }
8269
8270       if (mips_optional_operand_p (operand)
8271           && args[1] == ','
8272           && (arg.token[0].type != OT_REG
8273               || arg.token[1].type == OT_END))
8274         {
8275           /* Assume that the register has been elided and is the
8276              same as the first operand.  */
8277           arg.token = tokens;
8278           arg.argnum = 1;
8279         }
8280
8281       if (!match_operand (&arg, operand))
8282         return FALSE;
8283     }
8284 }
8285
8286 /* Record that the current instruction is invalid for the current ISA.  */
8287
8288 static void
8289 match_invalid_for_isa (void)
8290 {
8291   set_insn_error_ss
8292     (0, _("opcode not supported on this processor: %s (%s)"),
8293      mips_cpu_info_from_arch (mips_opts.arch)->name,
8294      mips_cpu_info_from_isa (mips_opts.isa)->name);
8295 }
8296
8297 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
8298    Return true if a definite match or failure was found, storing any match
8299    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
8300    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
8301    tried and failed to match under normal conditions and now want to try a
8302    more relaxed match.  */
8303
8304 static bfd_boolean
8305 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8306              const struct mips_opcode *past, struct mips_operand_token *tokens,
8307              int opcode_extra, bfd_boolean lax_match)
8308 {
8309   const struct mips_opcode *opcode;
8310   const struct mips_opcode *invalid_delay_slot;
8311   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
8312
8313   /* Search for a match, ignoring alternatives that don't satisfy the
8314      current ISA or forced_length.  */
8315   invalid_delay_slot = 0;
8316   seen_valid_for_isa = FALSE;
8317   seen_valid_for_size = FALSE;
8318   opcode = first;
8319   do
8320     {
8321       gas_assert (strcmp (opcode->name, first->name) == 0);
8322       if (is_opcode_valid (opcode))
8323         {
8324           seen_valid_for_isa = TRUE;
8325           if (is_size_valid (opcode))
8326             {
8327               bfd_boolean delay_slot_ok;
8328
8329               seen_valid_for_size = TRUE;
8330               delay_slot_ok = is_delay_slot_valid (opcode);
8331               if (match_insn (insn, opcode, tokens, opcode_extra,
8332                               lax_match, delay_slot_ok))
8333                 {
8334                   if (!delay_slot_ok)
8335                     {
8336                       if (!invalid_delay_slot)
8337                         invalid_delay_slot = opcode;
8338                     }
8339                   else
8340                     return TRUE;
8341                 }
8342             }
8343         }
8344       ++opcode;
8345     }
8346   while (opcode < past && strcmp (opcode->name, first->name) == 0);
8347
8348   /* If the only matches we found had the wrong length for the delay slot,
8349      pick the first such match.  We'll issue an appropriate warning later.  */
8350   if (invalid_delay_slot)
8351     {
8352       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
8353                       lax_match, TRUE))
8354         return TRUE;
8355       abort ();
8356     }
8357
8358   /* Handle the case where we didn't try to match an instruction because
8359      all the alternatives were incompatible with the current ISA.  */
8360   if (!seen_valid_for_isa)
8361     {
8362       match_invalid_for_isa ();
8363       return TRUE;
8364     }
8365
8366   /* Handle the case where we didn't try to match an instruction because
8367      all the alternatives were of the wrong size.  */
8368   if (!seen_valid_for_size)
8369     {
8370       if (mips_opts.insn32)
8371         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
8372       else
8373         set_insn_error_i
8374           (0, _("unrecognized %d-bit version of microMIPS opcode"),
8375            8 * forced_insn_length);
8376       return TRUE;
8377     }
8378
8379   return FALSE;
8380 }
8381
8382 /* Like match_insns, but for MIPS16.  */
8383
8384 static bfd_boolean
8385 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8386                     struct mips_operand_token *tokens)
8387 {
8388   const struct mips_opcode *opcode;
8389   bfd_boolean seen_valid_for_isa;
8390   bfd_boolean seen_valid_for_size;
8391
8392   /* Search for a match, ignoring alternatives that don't satisfy the
8393      current ISA.  There are no separate entries for extended forms so
8394      we deal with forced_length later.  */
8395   seen_valid_for_isa = FALSE;
8396   seen_valid_for_size = FALSE;
8397   opcode = first;
8398   do
8399     {
8400       gas_assert (strcmp (opcode->name, first->name) == 0);
8401       if (is_opcode_valid_16 (opcode))
8402         {
8403           seen_valid_for_isa = TRUE;
8404           if (is_size_valid_16 (opcode))
8405             {
8406               seen_valid_for_size = TRUE;
8407               if (match_mips16_insn (insn, opcode, tokens))
8408                 return TRUE;
8409             }
8410         }
8411       ++opcode;
8412     }
8413   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
8414          && strcmp (opcode->name, first->name) == 0);
8415
8416   /* Handle the case where we didn't try to match an instruction because
8417      all the alternatives were incompatible with the current ISA.  */
8418   if (!seen_valid_for_isa)
8419     {
8420       match_invalid_for_isa ();
8421       return TRUE;
8422     }
8423
8424   /* Handle the case where we didn't try to match an instruction because
8425      all the alternatives were of the wrong size.  */
8426   if (!seen_valid_for_size)
8427     {
8428       if (forced_insn_length == 2)
8429         set_insn_error
8430           (0, _("unrecognized unextended version of MIPS16 opcode"));
8431       else
8432         set_insn_error
8433           (0, _("unrecognized extended version of MIPS16 opcode"));
8434       return TRUE;
8435     }
8436
8437   return FALSE;
8438 }
8439
8440 /* Set up global variables for the start of a new macro.  */
8441
8442 static void
8443 macro_start (void)
8444 {
8445   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
8446   memset (&mips_macro_warning.first_insn_sizes, 0,
8447           sizeof (mips_macro_warning.first_insn_sizes));
8448   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
8449   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
8450                                      && delayed_branch_p (&history[0]));
8451   if (history[0].frag
8452       && history[0].frag->fr_type == rs_machine_dependent
8453       && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
8454       && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
8455     mips_macro_warning.delay_slot_length = 0;
8456   else
8457     switch (history[0].insn_mo->pinfo2
8458             & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
8459       {
8460       case INSN2_BRANCH_DELAY_32BIT:
8461         mips_macro_warning.delay_slot_length = 4;
8462         break;
8463       case INSN2_BRANCH_DELAY_16BIT:
8464         mips_macro_warning.delay_slot_length = 2;
8465         break;
8466       default:
8467         mips_macro_warning.delay_slot_length = 0;
8468         break;
8469       }
8470   mips_macro_warning.first_frag = NULL;
8471 }
8472
8473 /* Given that a macro is longer than one instruction or of the wrong size,
8474    return the appropriate warning for it.  Return null if no warning is
8475    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
8476    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
8477    and RELAX_NOMACRO.  */
8478
8479 static const char *
8480 macro_warning (relax_substateT subtype)
8481 {
8482   if (subtype & RELAX_DELAY_SLOT)
8483     return _("macro instruction expanded into multiple instructions"
8484              " in a branch delay slot");
8485   else if (subtype & RELAX_NOMACRO)
8486     return _("macro instruction expanded into multiple instructions");
8487   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
8488                       | RELAX_DELAY_SLOT_SIZE_SECOND))
8489     return ((subtype & RELAX_DELAY_SLOT_16BIT)
8490             ? _("macro instruction expanded into a wrong size instruction"
8491                 " in a 16-bit branch delay slot")
8492             : _("macro instruction expanded into a wrong size instruction"
8493                 " in a 32-bit branch delay slot"));
8494   else
8495     return 0;
8496 }
8497
8498 /* Finish up a macro.  Emit warnings as appropriate.  */
8499
8500 static void
8501 macro_end (void)
8502 {
8503   /* Relaxation warning flags.  */
8504   relax_substateT subtype = 0;
8505
8506   /* Check delay slot size requirements.  */
8507   if (mips_macro_warning.delay_slot_length == 2)
8508     subtype |= RELAX_DELAY_SLOT_16BIT;
8509   if (mips_macro_warning.delay_slot_length != 0)
8510     {
8511       if (mips_macro_warning.delay_slot_length
8512           != mips_macro_warning.first_insn_sizes[0])
8513         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
8514       if (mips_macro_warning.delay_slot_length
8515           != mips_macro_warning.first_insn_sizes[1])
8516         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
8517     }
8518
8519   /* Check instruction count requirements.  */
8520   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
8521     {
8522       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
8523         subtype |= RELAX_SECOND_LONGER;
8524       if (mips_opts.warn_about_macros)
8525         subtype |= RELAX_NOMACRO;
8526       if (mips_macro_warning.delay_slot_p)
8527         subtype |= RELAX_DELAY_SLOT;
8528     }
8529
8530   /* If both alternatives fail to fill a delay slot correctly,
8531      emit the warning now.  */
8532   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
8533       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
8534     {
8535       relax_substateT s;
8536       const char *msg;
8537
8538       s = subtype & (RELAX_DELAY_SLOT_16BIT
8539                      | RELAX_DELAY_SLOT_SIZE_FIRST
8540                      | RELAX_DELAY_SLOT_SIZE_SECOND);
8541       msg = macro_warning (s);
8542       if (msg != NULL)
8543         as_warn ("%s", msg);
8544       subtype &= ~s;
8545     }
8546
8547   /* If both implementations are longer than 1 instruction, then emit the
8548      warning now.  */
8549   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
8550     {
8551       relax_substateT s;
8552       const char *msg;
8553
8554       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
8555       msg = macro_warning (s);
8556       if (msg != NULL)
8557         as_warn ("%s", msg);
8558       subtype &= ~s;
8559     }
8560
8561   /* If any flags still set, then one implementation might need a warning
8562      and the other either will need one of a different kind or none at all.
8563      Pass any remaining flags over to relaxation.  */
8564   if (mips_macro_warning.first_frag != NULL)
8565     mips_macro_warning.first_frag->fr_subtype |= subtype;
8566 }
8567
8568 /* Instruction operand formats used in macros that vary between
8569    standard MIPS and microMIPS code.  */
8570
8571 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
8572 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
8573 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
8574 static const char * const lui_fmt[2] = { "t,u", "s,u" };
8575 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
8576 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
8577 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
8578 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
8579
8580 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
8581 #define COP12_FMT (ISA_IS_R6 (mips_opts.isa) ? "E,+:(d)" \
8582                                              : cop12_fmt[mips_opts.micromips])
8583 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
8584 #define LUI_FMT (lui_fmt[mips_opts.micromips])
8585 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
8586 #define LL_SC_FMT (ISA_IS_R6 (mips_opts.isa) ? "t,+j(b)" \
8587                                              : mem12_fmt[mips_opts.micromips])
8588 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
8589 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
8590 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
8591
8592 /* Read a macro's relocation codes from *ARGS and store them in *R.
8593    The first argument in *ARGS will be either the code for a single
8594    relocation or -1 followed by the three codes that make up a
8595    composite relocation.  */
8596
8597 static void
8598 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
8599 {
8600   int i, next;
8601
8602   next = va_arg (*args, int);
8603   if (next >= 0)
8604     r[0] = (bfd_reloc_code_real_type) next;
8605   else
8606     {
8607       for (i = 0; i < 3; i++)
8608         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
8609       /* This function is only used for 16-bit relocation fields.
8610          To make the macro code simpler, treat an unrelocated value
8611          in the same way as BFD_RELOC_LO16.  */
8612       if (r[0] == BFD_RELOC_UNUSED)
8613         r[0] = BFD_RELOC_LO16;
8614     }
8615 }
8616
8617 /* Build an instruction created by a macro expansion.  This is passed
8618    a pointer to the count of instructions created so far, an
8619    expression, the name of the instruction to build, an operand format
8620    string, and corresponding arguments.  */
8621
8622 static void
8623 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
8624 {
8625   const struct mips_opcode *mo = NULL;
8626   bfd_reloc_code_real_type r[3];
8627   const struct mips_opcode *amo;
8628   const struct mips_operand *operand;
8629   struct hash_control *hash;
8630   struct mips_cl_insn insn;
8631   va_list args;
8632   unsigned int uval;
8633
8634   va_start (args, fmt);
8635
8636   if (mips_opts.mips16)
8637     {
8638       mips16_macro_build (ep, name, fmt, &args);
8639       va_end (args);
8640       return;
8641     }
8642
8643   r[0] = BFD_RELOC_UNUSED;
8644   r[1] = BFD_RELOC_UNUSED;
8645   r[2] = BFD_RELOC_UNUSED;
8646   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
8647   amo = (struct mips_opcode *) hash_find (hash, name);
8648   gas_assert (amo);
8649   gas_assert (strcmp (name, amo->name) == 0);
8650
8651   do
8652     {
8653       /* Search until we get a match for NAME.  It is assumed here that
8654          macros will never generate MDMX, MIPS-3D, or MT instructions.
8655          We try to match an instruction that fulfills the branch delay
8656          slot instruction length requirement (if any) of the previous
8657          instruction.  While doing this we record the first instruction
8658          seen that matches all the other conditions and use it anyway
8659          if the requirement cannot be met; we will issue an appropriate
8660          warning later on.  */
8661       if (strcmp (fmt, amo->args) == 0
8662           && amo->pinfo != INSN_MACRO
8663           && is_opcode_valid (amo)
8664           && is_size_valid (amo))
8665         {
8666           if (is_delay_slot_valid (amo))
8667             {
8668               mo = amo;
8669               break;
8670             }
8671           else if (!mo)
8672             mo = amo;
8673         }
8674
8675       ++amo;
8676       gas_assert (amo->name);
8677     }
8678   while (strcmp (name, amo->name) == 0);
8679
8680   gas_assert (mo);
8681   create_insn (&insn, mo);
8682   for (; *fmt; ++fmt)
8683     {
8684       switch (*fmt)
8685         {
8686         case ',':
8687         case '(':
8688         case ')':
8689         case 'z':
8690           break;
8691
8692         case 'i':
8693         case 'j':
8694           macro_read_relocs (&args, r);
8695           gas_assert (*r == BFD_RELOC_GPREL16
8696                       || *r == BFD_RELOC_MIPS_HIGHER
8697                       || *r == BFD_RELOC_HI16_S
8698                       || *r == BFD_RELOC_LO16
8699                       || *r == BFD_RELOC_MIPS_GOT_OFST);
8700           break;
8701
8702         case 'o':
8703           macro_read_relocs (&args, r);
8704           break;
8705
8706         case 'u':
8707           macro_read_relocs (&args, r);
8708           gas_assert (ep != NULL
8709                       && (ep->X_op == O_constant
8710                           || (ep->X_op == O_symbol
8711                               && (*r == BFD_RELOC_MIPS_HIGHEST
8712                                   || *r == BFD_RELOC_HI16_S
8713                                   || *r == BFD_RELOC_HI16
8714                                   || *r == BFD_RELOC_GPREL16
8715                                   || *r == BFD_RELOC_MIPS_GOT_HI16
8716                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
8717           break;
8718
8719         case 'p':
8720           gas_assert (ep != NULL);
8721
8722           /*
8723            * This allows macro() to pass an immediate expression for
8724            * creating short branches without creating a symbol.
8725            *
8726            * We don't allow branch relaxation for these branches, as
8727            * they should only appear in ".set nomacro" anyway.
8728            */
8729           if (ep->X_op == O_constant)
8730             {
8731               /* For microMIPS we always use relocations for branches.
8732                  So we should not resolve immediate values.  */
8733               gas_assert (!mips_opts.micromips);
8734
8735               if ((ep->X_add_number & 3) != 0)
8736                 as_bad (_("branch to misaligned address (0x%lx)"),
8737                         (unsigned long) ep->X_add_number);
8738               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
8739                 as_bad (_("branch address range overflow (0x%lx)"),
8740                         (unsigned long) ep->X_add_number);
8741               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8742               ep = NULL;
8743             }
8744           else
8745             *r = BFD_RELOC_16_PCREL_S2;
8746           break;
8747
8748         case 'a':
8749           gas_assert (ep != NULL);
8750           *r = BFD_RELOC_MIPS_JMP;
8751           break;
8752
8753         default:
8754           operand = (mips_opts.micromips
8755                      ? decode_micromips_operand (fmt)
8756                      : decode_mips_operand (fmt));
8757           if (!operand)
8758             abort ();
8759
8760           uval = va_arg (args, int);
8761           if (operand->type == OP_CLO_CLZ_DEST)
8762             uval |= (uval << 5);
8763           insn_insert_operand (&insn, operand, uval);
8764
8765           if (*fmt == '+' || *fmt == 'm' || *fmt == '-')
8766             ++fmt;
8767           break;
8768         }
8769     }
8770   va_end (args);
8771   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8772
8773   append_insn (&insn, ep, r, TRUE);
8774 }
8775
8776 static void
8777 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8778                     va_list *args)
8779 {
8780   struct mips_opcode *mo;
8781   struct mips_cl_insn insn;
8782   const struct mips_operand *operand;
8783   bfd_reloc_code_real_type r[3]
8784     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8785
8786   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8787   gas_assert (mo);
8788   gas_assert (strcmp (name, mo->name) == 0);
8789
8790   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8791     {
8792       ++mo;
8793       gas_assert (mo->name);
8794       gas_assert (strcmp (name, mo->name) == 0);
8795     }
8796
8797   create_insn (&insn, mo);
8798   for (; *fmt; ++fmt)
8799     {
8800       int c;
8801
8802       c = *fmt;
8803       switch (c)
8804         {
8805         case ',':
8806         case '(':
8807         case ')':
8808           break;
8809
8810         case '.':
8811         case 'S':
8812         case 'P':
8813         case 'R':
8814           break;
8815
8816         case '<':
8817         case '5':
8818         case 'F':
8819         case 'H':
8820         case 'W':
8821         case 'D':
8822         case 'j':
8823         case '8':
8824         case 'V':
8825         case 'C':
8826         case 'U':
8827         case 'k':
8828         case 'K':
8829         case 'p':
8830         case 'q':
8831           {
8832             offsetT value;
8833
8834             gas_assert (ep != NULL);
8835
8836             if (ep->X_op != O_constant)
8837               *r = (int) BFD_RELOC_UNUSED + c;
8838             else if (calculate_reloc (*r, ep->X_add_number, &value))
8839               {
8840                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8841                 ep = NULL;
8842                 *r = BFD_RELOC_UNUSED;
8843               }
8844           }
8845           break;
8846
8847         default:
8848           operand = decode_mips16_operand (c, FALSE);
8849           if (!operand)
8850             abort ();
8851
8852           insn_insert_operand (&insn, operand, va_arg (*args, int));
8853           break;
8854         }
8855     }
8856
8857   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8858
8859   append_insn (&insn, ep, r, TRUE);
8860 }
8861
8862 /*
8863  * Generate a "jalr" instruction with a relocation hint to the called
8864  * function.  This occurs in NewABI PIC code.
8865  */
8866 static void
8867 macro_build_jalr (expressionS *ep, int cprestore)
8868 {
8869   static const bfd_reloc_code_real_type jalr_relocs[2]
8870     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8871   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8872   const char *jalr;
8873   char *f = NULL;
8874
8875   if (MIPS_JALR_HINT_P (ep))
8876     {
8877       frag_grow (8);
8878       f = frag_more (0);
8879     }
8880   if (mips_opts.micromips)
8881     {
8882       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8883               ? "jalr" : "jalrs");
8884       if (MIPS_JALR_HINT_P (ep)
8885           || mips_opts.insn32
8886           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8887         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8888       else
8889         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8890     }
8891   else
8892     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8893   if (MIPS_JALR_HINT_P (ep))
8894     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8895 }
8896
8897 /*
8898  * Generate a "lui" instruction.
8899  */
8900 static void
8901 macro_build_lui (expressionS *ep, int regnum)
8902 {
8903   gas_assert (! mips_opts.mips16);
8904
8905   if (ep->X_op != O_constant)
8906     {
8907       gas_assert (ep->X_op == O_symbol);
8908       /* _gp_disp is a special case, used from s_cpload.
8909          __gnu_local_gp is used if mips_no_shared.  */
8910       gas_assert (mips_pic == NO_PIC
8911               || (! HAVE_NEWABI
8912                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8913               || (! mips_in_shared
8914                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8915                              "__gnu_local_gp") == 0));
8916     }
8917
8918   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8919 }
8920
8921 /* Generate a sequence of instructions to do a load or store from a constant
8922    offset off of a base register (breg) into/from a target register (treg),
8923    using AT if necessary.  */
8924 static void
8925 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8926                               int treg, int breg, int dbl)
8927 {
8928   gas_assert (ep->X_op == O_constant);
8929
8930   /* Sign-extending 32-bit constants makes their handling easier.  */
8931   if (!dbl)
8932     normalize_constant_expr (ep);
8933
8934   /* Right now, this routine can only handle signed 32-bit constants.  */
8935   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8936     as_warn (_("operand overflow"));
8937
8938   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8939     {
8940       /* Signed 16-bit offset will fit in the op.  Easy!  */
8941       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8942     }
8943   else
8944     {
8945       /* 32-bit offset, need multiple instructions and AT, like:
8946            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8947            addu     $tempreg,$tempreg,$breg
8948            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8949          to handle the complete offset.  */
8950       macro_build_lui (ep, AT);
8951       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8952       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8953
8954       if (!mips_opts.at)
8955         as_bad (_("macro used $at after \".set noat\""));
8956     }
8957 }
8958
8959 /*                      set_at()
8960  * Generates code to set the $at register to true (one)
8961  * if reg is less than the immediate expression.
8962  */
8963 static void
8964 set_at (int reg, int unsignedp)
8965 {
8966   if (imm_expr.X_add_number >= -0x8000
8967       && imm_expr.X_add_number < 0x8000)
8968     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8969                  AT, reg, BFD_RELOC_LO16);
8970   else
8971     {
8972       load_register (AT, &imm_expr, GPR_SIZE == 64);
8973       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8974     }
8975 }
8976
8977 /* Count the leading zeroes by performing a binary chop. This is a
8978    bulky bit of source, but performance is a LOT better for the
8979    majority of values than a simple loop to count the bits:
8980        for (lcnt = 0; (lcnt < 32); lcnt++)
8981          if ((v) & (1 << (31 - lcnt)))
8982            break;
8983   However it is not code size friendly, and the gain will drop a bit
8984   on certain cached systems.
8985 */
8986 #define COUNT_TOP_ZEROES(v)             \
8987   (((v) & ~0xffff) == 0                 \
8988    ? ((v) & ~0xff) == 0                 \
8989      ? ((v) & ~0xf) == 0                \
8990        ? ((v) & ~0x3) == 0              \
8991          ? ((v) & ~0x1) == 0            \
8992            ? !(v)                       \
8993              ? 32                       \
8994              : 31                       \
8995            : 30                         \
8996          : ((v) & ~0x7) == 0            \
8997            ? 29                         \
8998            : 28                         \
8999        : ((v) & ~0x3f) == 0             \
9000          ? ((v) & ~0x1f) == 0           \
9001            ? 27                         \
9002            : 26                         \
9003          : ((v) & ~0x7f) == 0           \
9004            ? 25                         \
9005            : 24                         \
9006      : ((v) & ~0xfff) == 0              \
9007        ? ((v) & ~0x3ff) == 0            \
9008          ? ((v) & ~0x1ff) == 0          \
9009            ? 23                         \
9010            : 22                         \
9011          : ((v) & ~0x7ff) == 0          \
9012            ? 21                         \
9013            : 20                         \
9014        : ((v) & ~0x3fff) == 0           \
9015          ? ((v) & ~0x1fff) == 0         \
9016            ? 19                         \
9017            : 18                         \
9018          : ((v) & ~0x7fff) == 0         \
9019            ? 17                         \
9020            : 16                         \
9021    : ((v) & ~0xffffff) == 0             \
9022      ? ((v) & ~0xfffff) == 0            \
9023        ? ((v) & ~0x3ffff) == 0          \
9024          ? ((v) & ~0x1ffff) == 0        \
9025            ? 15                         \
9026            : 14                         \
9027          : ((v) & ~0x7ffff) == 0        \
9028            ? 13                         \
9029            : 12                         \
9030        : ((v) & ~0x3fffff) == 0         \
9031          ? ((v) & ~0x1fffff) == 0       \
9032            ? 11                         \
9033            : 10                         \
9034          : ((v) & ~0x7fffff) == 0       \
9035            ? 9                          \
9036            : 8                          \
9037      : ((v) & ~0xfffffff) == 0          \
9038        ? ((v) & ~0x3ffffff) == 0        \
9039          ? ((v) & ~0x1ffffff) == 0      \
9040            ? 7                          \
9041            : 6                          \
9042          : ((v) & ~0x7ffffff) == 0      \
9043            ? 5                          \
9044            : 4                          \
9045        : ((v) & ~0x3fffffff) == 0       \
9046          ? ((v) & ~0x1fffffff) == 0     \
9047            ? 3                          \
9048            : 2                          \
9049          : ((v) & ~0x7fffffff) == 0     \
9050            ? 1                          \
9051            : 0)
9052
9053 /*                      load_register()
9054  *  This routine generates the least number of instructions necessary to load
9055  *  an absolute expression value into a register.
9056  */
9057 static void
9058 load_register (int reg, expressionS *ep, int dbl)
9059 {
9060   int freg;
9061   expressionS hi32, lo32;
9062
9063   if (ep->X_op != O_big)
9064     {
9065       gas_assert (ep->X_op == O_constant);
9066
9067       /* Sign-extending 32-bit constants makes their handling easier.  */
9068       if (!dbl)
9069         normalize_constant_expr (ep);
9070
9071       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
9072         {
9073           /* We can handle 16 bit signed values with an addiu to
9074              $zero.  No need to ever use daddiu here, since $zero and
9075              the result are always correct in 32 bit mode.  */
9076           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9077           return;
9078         }
9079       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
9080         {
9081           /* We can handle 16 bit unsigned values with an ori to
9082              $zero.  */
9083           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9084           return;
9085         }
9086       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
9087         {
9088           /* 32 bit values require an lui.  */
9089           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9090           if ((ep->X_add_number & 0xffff) != 0)
9091             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9092           return;
9093         }
9094     }
9095
9096   /* The value is larger than 32 bits.  */
9097
9098   if (!dbl || GPR_SIZE == 32)
9099     {
9100       char value[32];
9101
9102       sprintf_vma (value, ep->X_add_number);
9103       as_bad (_("number (0x%s) larger than 32 bits"), value);
9104       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9105       return;
9106     }
9107
9108   if (ep->X_op != O_big)
9109     {
9110       hi32 = *ep;
9111       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9112       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9113       hi32.X_add_number &= 0xffffffff;
9114       lo32 = *ep;
9115       lo32.X_add_number &= 0xffffffff;
9116     }
9117   else
9118     {
9119       gas_assert (ep->X_add_number > 2);
9120       if (ep->X_add_number == 3)
9121         generic_bignum[3] = 0;
9122       else if (ep->X_add_number > 4)
9123         as_bad (_("number larger than 64 bits"));
9124       lo32.X_op = O_constant;
9125       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
9126       hi32.X_op = O_constant;
9127       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
9128     }
9129
9130   if (hi32.X_add_number == 0)
9131     freg = 0;
9132   else
9133     {
9134       int shift, bit;
9135       unsigned long hi, lo;
9136
9137       if (hi32.X_add_number == (offsetT) 0xffffffff)
9138         {
9139           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
9140             {
9141               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9142               return;
9143             }
9144           if (lo32.X_add_number & 0x80000000)
9145             {
9146               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9147               if (lo32.X_add_number & 0xffff)
9148                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9149               return;
9150             }
9151         }
9152
9153       /* Check for 16bit shifted constant.  We know that hi32 is
9154          non-zero, so start the mask on the first bit of the hi32
9155          value.  */
9156       shift = 17;
9157       do
9158         {
9159           unsigned long himask, lomask;
9160
9161           if (shift < 32)
9162             {
9163               himask = 0xffff >> (32 - shift);
9164               lomask = (0xffff << shift) & 0xffffffff;
9165             }
9166           else
9167             {
9168               himask = 0xffff << (shift - 32);
9169               lomask = 0;
9170             }
9171           if ((hi32.X_add_number & ~(offsetT) himask) == 0
9172               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
9173             {
9174               expressionS tmp;
9175
9176               tmp.X_op = O_constant;
9177               if (shift < 32)
9178                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
9179                                     | (lo32.X_add_number >> shift));
9180               else
9181                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
9182               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9183               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9184                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9185               return;
9186             }
9187           ++shift;
9188         }
9189       while (shift <= (64 - 16));
9190
9191       /* Find the bit number of the lowest one bit, and store the
9192          shifted value in hi/lo.  */
9193       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
9194       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
9195       if (lo != 0)
9196         {
9197           bit = 0;
9198           while ((lo & 1) == 0)
9199             {
9200               lo >>= 1;
9201               ++bit;
9202             }
9203           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
9204           hi >>= bit;
9205         }
9206       else
9207         {
9208           bit = 32;
9209           while ((hi & 1) == 0)
9210             {
9211               hi >>= 1;
9212               ++bit;
9213             }
9214           lo = hi;
9215           hi = 0;
9216         }
9217
9218       /* Optimize if the shifted value is a (power of 2) - 1.  */
9219       if ((hi == 0 && ((lo + 1) & lo) == 0)
9220           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
9221         {
9222           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
9223           if (shift != 0)
9224             {
9225               expressionS tmp;
9226
9227               /* This instruction will set the register to be all
9228                  ones.  */
9229               tmp.X_op = O_constant;
9230               tmp.X_add_number = (offsetT) -1;
9231               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9232               if (bit != 0)
9233                 {
9234                   bit += shift;
9235                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9236                                reg, reg, (bit >= 32) ? bit - 32 : bit);
9237                 }
9238               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
9239                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9240               return;
9241             }
9242         }
9243
9244       /* Sign extend hi32 before calling load_register, because we can
9245          generally get better code when we load a sign extended value.  */
9246       if ((hi32.X_add_number & 0x80000000) != 0)
9247         hi32.X_add_number |= ~(offsetT) 0xffffffff;
9248       load_register (reg, &hi32, 0);
9249       freg = reg;
9250     }
9251   if ((lo32.X_add_number & 0xffff0000) == 0)
9252     {
9253       if (freg != 0)
9254         {
9255           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
9256           freg = reg;
9257         }
9258     }
9259   else
9260     {
9261       expressionS mid16;
9262
9263       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
9264         {
9265           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9266           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
9267           return;
9268         }
9269
9270       if (freg != 0)
9271         {
9272           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
9273           freg = reg;
9274         }
9275       mid16 = lo32;
9276       mid16.X_add_number >>= 16;
9277       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9278       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9279       freg = reg;
9280     }
9281   if ((lo32.X_add_number & 0xffff) != 0)
9282     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9283 }
9284
9285 static inline void
9286 load_delay_nop (void)
9287 {
9288   if (!gpr_interlocks)
9289     macro_build (NULL, "nop", "");
9290 }
9291
9292 /* Load an address into a register.  */
9293
9294 static void
9295 load_address (int reg, expressionS *ep, int *used_at)
9296 {
9297   if (ep->X_op != O_constant
9298       && ep->X_op != O_symbol)
9299     {
9300       as_bad (_("expression too complex"));
9301       ep->X_op = O_constant;
9302     }
9303
9304   if (ep->X_op == O_constant)
9305     {
9306       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
9307       return;
9308     }
9309
9310   if (mips_pic == NO_PIC)
9311     {
9312       /* If this is a reference to a GP relative symbol, we want
9313            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
9314          Otherwise we want
9315            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
9316            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9317          If we have an addend, we always use the latter form.
9318
9319          With 64bit address space and a usable $at we want
9320            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9321            lui          $at,<sym>               (BFD_RELOC_HI16_S)
9322            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9323            daddiu       $at,<sym>               (BFD_RELOC_LO16)
9324            dsll32       $reg,0
9325            daddu        $reg,$reg,$at
9326
9327          If $at is already in use, we use a path which is suboptimal
9328          on superscalar processors.
9329            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9330            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9331            dsll         $reg,16
9332            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
9333            dsll         $reg,16
9334            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
9335
9336          For GP relative symbols in 64bit address space we can use
9337          the same sequence as in 32bit address space.  */
9338       if (HAVE_64BIT_SYMBOLS)
9339         {
9340           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9341               && !nopic_need_relax (ep->X_add_symbol, 1))
9342             {
9343               relax_start (ep->X_add_symbol);
9344               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9345                            mips_gp_register, BFD_RELOC_GPREL16);
9346               relax_switch ();
9347             }
9348
9349           if (*used_at == 0 && mips_opts.at)
9350             {
9351               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9352               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
9353               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9354                            BFD_RELOC_MIPS_HIGHER);
9355               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
9356               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
9357               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
9358               *used_at = 1;
9359             }
9360           else
9361             {
9362               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9363               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9364                            BFD_RELOC_MIPS_HIGHER);
9365               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9366               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
9367               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9368               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
9369             }
9370
9371           if (mips_relax.sequence)
9372             relax_end ();
9373         }
9374       else
9375         {
9376           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9377               && !nopic_need_relax (ep->X_add_symbol, 1))
9378             {
9379               relax_start (ep->X_add_symbol);
9380               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9381                            mips_gp_register, BFD_RELOC_GPREL16);
9382               relax_switch ();
9383             }
9384           macro_build_lui (ep, reg);
9385           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
9386                        reg, reg, BFD_RELOC_LO16);
9387           if (mips_relax.sequence)
9388             relax_end ();
9389         }
9390     }
9391   else if (!mips_big_got)
9392     {
9393       expressionS ex;
9394
9395       /* If this is a reference to an external symbol, we want
9396            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9397          Otherwise we want
9398            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9399            nop
9400            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9401          If there is a constant, it must be added in after.
9402
9403          If we have NewABI, we want
9404            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9405          unless we're referencing a global symbol with a non-zero
9406          offset, in which case cst must be added separately.  */
9407       if (HAVE_NEWABI)
9408         {
9409           if (ep->X_add_number)
9410             {
9411               ex.X_add_number = ep->X_add_number;
9412               ep->X_add_number = 0;
9413               relax_start (ep->X_add_symbol);
9414               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9415                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9416               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9417                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9418               ex.X_op = O_constant;
9419               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9420                            reg, reg, BFD_RELOC_LO16);
9421               ep->X_add_number = ex.X_add_number;
9422               relax_switch ();
9423             }
9424           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9425                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9426           if (mips_relax.sequence)
9427             relax_end ();
9428         }
9429       else
9430         {
9431           ex.X_add_number = ep->X_add_number;
9432           ep->X_add_number = 0;
9433           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9434                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9435           load_delay_nop ();
9436           relax_start (ep->X_add_symbol);
9437           relax_switch ();
9438           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9439                        BFD_RELOC_LO16);
9440           relax_end ();
9441
9442           if (ex.X_add_number != 0)
9443             {
9444               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9445                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9446               ex.X_op = O_constant;
9447               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9448                            reg, reg, BFD_RELOC_LO16);
9449             }
9450         }
9451     }
9452   else if (mips_big_got)
9453     {
9454       expressionS ex;
9455
9456       /* This is the large GOT case.  If this is a reference to an
9457          external symbol, we want
9458            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
9459            addu         $reg,$reg,$gp
9460            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
9461
9462          Otherwise, for a reference to a local symbol in old ABI, we want
9463            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9464            nop
9465            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9466          If there is a constant, it must be added in after.
9467
9468          In the NewABI, for local symbols, with or without offsets, we want:
9469            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
9470            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
9471       */
9472       if (HAVE_NEWABI)
9473         {
9474           ex.X_add_number = ep->X_add_number;
9475           ep->X_add_number = 0;
9476           relax_start (ep->X_add_symbol);
9477           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9478           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9479                        reg, reg, mips_gp_register);
9480           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9481                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9482           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9483             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9484           else if (ex.X_add_number)
9485             {
9486               ex.X_op = O_constant;
9487               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9488                            BFD_RELOC_LO16);
9489             }
9490
9491           ep->X_add_number = ex.X_add_number;
9492           relax_switch ();
9493           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9494                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9495           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9496                        BFD_RELOC_MIPS_GOT_OFST);
9497           relax_end ();
9498         }
9499       else
9500         {
9501           ex.X_add_number = ep->X_add_number;
9502           ep->X_add_number = 0;
9503           relax_start (ep->X_add_symbol);
9504           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9505           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9506                        reg, reg, mips_gp_register);
9507           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9508                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9509           relax_switch ();
9510           if (reg_needs_delay (mips_gp_register))
9511             {
9512               /* We need a nop before loading from $gp.  This special
9513                  check is required because the lui which starts the main
9514                  instruction stream does not refer to $gp, and so will not
9515                  insert the nop which may be required.  */
9516               macro_build (NULL, "nop", "");
9517             }
9518           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9519                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9520           load_delay_nop ();
9521           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9522                        BFD_RELOC_LO16);
9523           relax_end ();
9524
9525           if (ex.X_add_number != 0)
9526             {
9527               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9528                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9529               ex.X_op = O_constant;
9530               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9531                            BFD_RELOC_LO16);
9532             }
9533         }
9534     }
9535   else
9536     abort ();
9537
9538   if (!mips_opts.at && *used_at == 1)
9539     as_bad (_("macro used $at after \".set noat\""));
9540 }
9541
9542 /* Move the contents of register SOURCE into register DEST.  */
9543
9544 static void
9545 move_register (int dest, int source)
9546 {
9547   /* Prefer to use a 16-bit microMIPS instruction unless the previous
9548      instruction specifically requires a 32-bit one.  */
9549   if (mips_opts.micromips
9550       && !mips_opts.insn32
9551       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9552     macro_build (NULL, "move", "mp,mj", dest, source);
9553   else
9554     macro_build (NULL, "or", "d,v,t", dest, source, 0);
9555 }
9556
9557 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
9558    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
9559    The two alternatives are:
9560
9561    Global symbol                Local symbol
9562    -------------                ------------
9563    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
9564    ...                          ...
9565    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
9566
9567    load_got_offset emits the first instruction and add_got_offset
9568    emits the second for a 16-bit offset or add_got_offset_hilo emits
9569    a sequence to add a 32-bit offset using a scratch register.  */
9570
9571 static void
9572 load_got_offset (int dest, expressionS *local)
9573 {
9574   expressionS global;
9575
9576   global = *local;
9577   global.X_add_number = 0;
9578
9579   relax_start (local->X_add_symbol);
9580   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9581                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9582   relax_switch ();
9583   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9584                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9585   relax_end ();
9586 }
9587
9588 static void
9589 add_got_offset (int dest, expressionS *local)
9590 {
9591   expressionS global;
9592
9593   global.X_op = O_constant;
9594   global.X_op_symbol = NULL;
9595   global.X_add_symbol = NULL;
9596   global.X_add_number = local->X_add_number;
9597
9598   relax_start (local->X_add_symbol);
9599   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
9600                dest, dest, BFD_RELOC_LO16);
9601   relax_switch ();
9602   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
9603   relax_end ();
9604 }
9605
9606 static void
9607 add_got_offset_hilo (int dest, expressionS *local, int tmp)
9608 {
9609   expressionS global;
9610   int hold_mips_optimize;
9611
9612   global.X_op = O_constant;
9613   global.X_op_symbol = NULL;
9614   global.X_add_symbol = NULL;
9615   global.X_add_number = local->X_add_number;
9616
9617   relax_start (local->X_add_symbol);
9618   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
9619   relax_switch ();
9620   /* Set mips_optimize around the lui instruction to avoid
9621      inserting an unnecessary nop after the lw.  */
9622   hold_mips_optimize = mips_optimize;
9623   mips_optimize = 2;
9624   macro_build_lui (&global, tmp);
9625   mips_optimize = hold_mips_optimize;
9626   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
9627   relax_end ();
9628
9629   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
9630 }
9631
9632 /* Emit a sequence of instructions to emulate a branch likely operation.
9633    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
9634    is its complementing branch with the original condition negated.
9635    CALL is set if the original branch specified the link operation.
9636    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
9637
9638    Code like this is produced in the noreorder mode:
9639
9640         BRNEG   <args>, 1f
9641          nop
9642         b       <sym>
9643          delay slot (executed only if branch taken)
9644     1:
9645
9646    or, if CALL is set:
9647
9648         BRNEG   <args>, 1f
9649          nop
9650         bal     <sym>
9651          delay slot (executed only if branch taken)
9652     1:
9653
9654    In the reorder mode the delay slot would be filled with a nop anyway,
9655    so code produced is simply:
9656
9657         BR      <args>, <sym>
9658          nop
9659
9660    This function is used when producing code for the microMIPS ASE that
9661    does not implement branch likely instructions in hardware.  */
9662
9663 static void
9664 macro_build_branch_likely (const char *br, const char *brneg,
9665                            int call, expressionS *ep, const char *fmt,
9666                            unsigned int sreg, unsigned int treg)
9667 {
9668   int noreorder = mips_opts.noreorder;
9669   expressionS expr1;
9670
9671   gas_assert (mips_opts.micromips);
9672   start_noreorder ();
9673   if (noreorder)
9674     {
9675       micromips_label_expr (&expr1);
9676       macro_build (&expr1, brneg, fmt, sreg, treg);
9677       macro_build (NULL, "nop", "");
9678       macro_build (ep, call ? "bal" : "b", "p");
9679
9680       /* Set to true so that append_insn adds a label.  */
9681       emit_branch_likely_macro = TRUE;
9682     }
9683   else
9684     {
9685       macro_build (ep, br, fmt, sreg, treg);
9686       macro_build (NULL, "nop", "");
9687     }
9688   end_noreorder ();
9689 }
9690
9691 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
9692    the condition code tested.  EP specifies the branch target.  */
9693
9694 static void
9695 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
9696 {
9697   const int call = 0;
9698   const char *brneg;
9699   const char *br;
9700
9701   switch (type)
9702     {
9703     case M_BC1FL:
9704       br = "bc1f";
9705       brneg = "bc1t";
9706       break;
9707     case M_BC1TL:
9708       br = "bc1t";
9709       brneg = "bc1f";
9710       break;
9711     case M_BC2FL:
9712       br = "bc2f";
9713       brneg = "bc2t";
9714       break;
9715     case M_BC2TL:
9716       br = "bc2t";
9717       brneg = "bc2f";
9718       break;
9719     default:
9720       abort ();
9721     }
9722   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
9723 }
9724
9725 /* Emit a two-argument branch macro specified by TYPE, using SREG as
9726    the register tested.  EP specifies the branch target.  */
9727
9728 static void
9729 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
9730 {
9731   const char *brneg = NULL;
9732   const char *br;
9733   int call = 0;
9734
9735   switch (type)
9736     {
9737     case M_BGEZ:
9738       br = "bgez";
9739       break;
9740     case M_BGEZL:
9741       br = mips_opts.micromips ? "bgez" : "bgezl";
9742       brneg = "bltz";
9743       break;
9744     case M_BGEZALL:
9745       gas_assert (mips_opts.micromips);
9746       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9747       brneg = "bltz";
9748       call = 1;
9749       break;
9750     case M_BGTZ:
9751       br = "bgtz";
9752       break;
9753     case M_BGTZL:
9754       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9755       brneg = "blez";
9756       break;
9757     case M_BLEZ:
9758       br = "blez";
9759       break;
9760     case M_BLEZL:
9761       br = mips_opts.micromips ? "blez" : "blezl";
9762       brneg = "bgtz";
9763       break;
9764     case M_BLTZ:
9765       br = "bltz";
9766       break;
9767     case M_BLTZL:
9768       br = mips_opts.micromips ? "bltz" : "bltzl";
9769       brneg = "bgez";
9770       break;
9771     case M_BLTZALL:
9772       gas_assert (mips_opts.micromips);
9773       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9774       brneg = "bgez";
9775       call = 1;
9776       break;
9777     default:
9778       abort ();
9779     }
9780   if (mips_opts.micromips && brneg)
9781     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9782   else
9783     macro_build (ep, br, "s,p", sreg);
9784 }
9785
9786 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9787    TREG as the registers tested.  EP specifies the branch target.  */
9788
9789 static void
9790 macro_build_branch_rsrt (int type, expressionS *ep,
9791                          unsigned int sreg, unsigned int treg)
9792 {
9793   const char *brneg = NULL;
9794   const int call = 0;
9795   const char *br;
9796
9797   switch (type)
9798     {
9799     case M_BEQ:
9800     case M_BEQ_I:
9801       br = "beq";
9802       break;
9803     case M_BEQL:
9804     case M_BEQL_I:
9805       br = mips_opts.micromips ? "beq" : "beql";
9806       brneg = "bne";
9807       break;
9808     case M_BNE:
9809     case M_BNE_I:
9810       br = "bne";
9811       break;
9812     case M_BNEL:
9813     case M_BNEL_I:
9814       br = mips_opts.micromips ? "bne" : "bnel";
9815       brneg = "beq";
9816       break;
9817     default:
9818       abort ();
9819     }
9820   if (mips_opts.micromips && brneg)
9821     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9822   else
9823     macro_build (ep, br, "s,t,p", sreg, treg);
9824 }
9825
9826 /* Return the high part that should be loaded in order to make the low
9827    part of VALUE accessible using an offset of OFFBITS bits.  */
9828
9829 static offsetT
9830 offset_high_part (offsetT value, unsigned int offbits)
9831 {
9832   offsetT bias;
9833   addressT low_mask;
9834
9835   if (offbits == 0)
9836     return value;
9837   bias = 1 << (offbits - 1);
9838   low_mask = bias * 2 - 1;
9839   return (value + bias) & ~low_mask;
9840 }
9841
9842 /* Return true if the value stored in offset_expr and offset_reloc
9843    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9844    amount that the caller wants to add without inducing overflow
9845    and ALIGN is the known alignment of the value in bytes.  */
9846
9847 static bfd_boolean
9848 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9849 {
9850   if (offbits == 16)
9851     {
9852       /* Accept any relocation operator if overflow isn't a concern.  */
9853       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9854         return TRUE;
9855
9856       /* These relocations are guaranteed not to overflow in correct links.  */
9857       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9858           || gprel16_reloc_p (*offset_reloc))
9859         return TRUE;
9860     }
9861   if (offset_expr.X_op == O_constant
9862       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9863       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9864     return TRUE;
9865   return FALSE;
9866 }
9867
9868 /*
9869  *                      Build macros
9870  *   This routine implements the seemingly endless macro or synthesized
9871  * instructions and addressing modes in the mips assembly language. Many
9872  * of these macros are simple and are similar to each other. These could
9873  * probably be handled by some kind of table or grammar approach instead of
9874  * this verbose method. Others are not simple macros but are more like
9875  * optimizing code generation.
9876  *   One interesting optimization is when several store macros appear
9877  * consecutively that would load AT with the upper half of the same address.
9878  * The ensuing load upper instructions are omitted. This implies some kind
9879  * of global optimization. We currently only optimize within a single macro.
9880  *   For many of the load and store macros if the address is specified as a
9881  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9882  * first load register 'at' with zero and use it as the base register. The
9883  * mips assembler simply uses register $zero. Just one tiny optimization
9884  * we're missing.
9885  */
9886 static void
9887 macro (struct mips_cl_insn *ip, char *str)
9888 {
9889   const struct mips_operand_array *operands;
9890   unsigned int breg, i;
9891   unsigned int tempreg;
9892   int mask;
9893   int used_at = 0;
9894   expressionS label_expr;
9895   expressionS expr1;
9896   expressionS *ep;
9897   const char *s;
9898   const char *s2;
9899   const char *fmt;
9900   int likely = 0;
9901   int coproc = 0;
9902   int offbits = 16;
9903   int call = 0;
9904   int jals = 0;
9905   int dbl = 0;
9906   int imm = 0;
9907   int ust = 0;
9908   int lp = 0;
9909   bfd_boolean large_offset;
9910   int off;
9911   int hold_mips_optimize;
9912   unsigned int align;
9913   unsigned int op[MAX_OPERANDS];
9914
9915   gas_assert (! mips_opts.mips16);
9916
9917   operands = insn_operands (ip);
9918   for (i = 0; i < MAX_OPERANDS; i++)
9919     if (operands->operand[i])
9920       op[i] = insn_extract_operand (ip, operands->operand[i]);
9921     else
9922       op[i] = -1;
9923
9924   mask = ip->insn_mo->mask;
9925
9926   label_expr.X_op = O_constant;
9927   label_expr.X_op_symbol = NULL;
9928   label_expr.X_add_symbol = NULL;
9929   label_expr.X_add_number = 0;
9930
9931   expr1.X_op = O_constant;
9932   expr1.X_op_symbol = NULL;
9933   expr1.X_add_symbol = NULL;
9934   expr1.X_add_number = 1;
9935   align = 1;
9936
9937   switch (mask)
9938     {
9939     case M_DABS:
9940       dbl = 1;
9941       /* Fall through.  */
9942     case M_ABS:
9943       /*    bgez    $a0,1f
9944             move    v0,$a0
9945             sub     v0,$zero,$a0
9946          1:
9947        */
9948
9949       start_noreorder ();
9950
9951       if (mips_opts.micromips)
9952         micromips_label_expr (&label_expr);
9953       else
9954         label_expr.X_add_number = 8;
9955       macro_build (&label_expr, "bgez", "s,p", op[1]);
9956       if (op[0] == op[1])
9957         macro_build (NULL, "nop", "");
9958       else
9959         move_register (op[0], op[1]);
9960       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9961       if (mips_opts.micromips)
9962         micromips_add_label ();
9963
9964       end_noreorder ();
9965       break;
9966
9967     case M_ADD_I:
9968       s = "addi";
9969       s2 = "add";
9970       goto do_addi;
9971     case M_ADDU_I:
9972       s = "addiu";
9973       s2 = "addu";
9974       goto do_addi;
9975     case M_DADD_I:
9976       dbl = 1;
9977       s = "daddi";
9978       s2 = "dadd";
9979       if (!mips_opts.micromips)
9980         goto do_addi;
9981       if (imm_expr.X_add_number >= -0x200
9982           && imm_expr.X_add_number < 0x200)
9983         {
9984           macro_build (NULL, s, "t,r,.", op[0], op[1],
9985                        (int) imm_expr.X_add_number);
9986           break;
9987         }
9988       goto do_addi_i;
9989     case M_DADDU_I:
9990       dbl = 1;
9991       s = "daddiu";
9992       s2 = "daddu";
9993     do_addi:
9994       if (imm_expr.X_add_number >= -0x8000
9995           && imm_expr.X_add_number < 0x8000)
9996         {
9997           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9998           break;
9999         }
10000     do_addi_i:
10001       used_at = 1;
10002       load_register (AT, &imm_expr, dbl);
10003       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10004       break;
10005
10006     case M_AND_I:
10007       s = "andi";
10008       s2 = "and";
10009       goto do_bit;
10010     case M_OR_I:
10011       s = "ori";
10012       s2 = "or";
10013       goto do_bit;
10014     case M_NOR_I:
10015       s = "";
10016       s2 = "nor";
10017       goto do_bit;
10018     case M_XOR_I:
10019       s = "xori";
10020       s2 = "xor";
10021     do_bit:
10022       if (imm_expr.X_add_number >= 0
10023           && imm_expr.X_add_number < 0x10000)
10024         {
10025           if (mask != M_NOR_I)
10026             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
10027           else
10028             {
10029               macro_build (&imm_expr, "ori", "t,r,i",
10030                            op[0], op[1], BFD_RELOC_LO16);
10031               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
10032             }
10033           break;
10034         }
10035
10036       used_at = 1;
10037       load_register (AT, &imm_expr, GPR_SIZE == 64);
10038       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10039       break;
10040
10041     case M_BALIGN:
10042       switch (imm_expr.X_add_number)
10043         {
10044         case 0:
10045           macro_build (NULL, "nop", "");
10046           break;
10047         case 2:
10048           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
10049           break;
10050         case 1:
10051         case 3:
10052           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
10053                        (int) imm_expr.X_add_number);
10054           break;
10055         default:
10056           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
10057                   (unsigned long) imm_expr.X_add_number);
10058           break;
10059         }
10060       break;
10061
10062     case M_BC1FL:
10063     case M_BC1TL:
10064     case M_BC2FL:
10065     case M_BC2TL:
10066       gas_assert (mips_opts.micromips);
10067       macro_build_branch_ccl (mask, &offset_expr,
10068                               EXTRACT_OPERAND (1, BCC, *ip));
10069       break;
10070
10071     case M_BEQ_I:
10072     case M_BEQL_I:
10073     case M_BNE_I:
10074     case M_BNEL_I:
10075       if (imm_expr.X_add_number == 0)
10076         op[1] = 0;
10077       else
10078         {
10079           op[1] = AT;
10080           used_at = 1;
10081           load_register (op[1], &imm_expr, GPR_SIZE == 64);
10082         }
10083       /* Fall through.  */
10084     case M_BEQL:
10085     case M_BNEL:
10086       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
10087       break;
10088
10089     case M_BGEL:
10090       likely = 1;
10091       /* Fall through.  */
10092     case M_BGE:
10093       if (op[1] == 0)
10094         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
10095       else if (op[0] == 0)
10096         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
10097       else
10098         {
10099           used_at = 1;
10100           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10101           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10102                                    &offset_expr, AT, ZERO);
10103         }
10104       break;
10105
10106     case M_BGEZL:
10107     case M_BGEZALL:
10108     case M_BGTZL:
10109     case M_BLEZL:
10110     case M_BLTZL:
10111     case M_BLTZALL:
10112       macro_build_branch_rs (mask, &offset_expr, op[0]);
10113       break;
10114
10115     case M_BGTL_I:
10116       likely = 1;
10117       /* Fall through.  */
10118     case M_BGT_I:
10119       /* Check for > max integer.  */
10120       if (imm_expr.X_add_number >= GPR_SMAX)
10121         {
10122         do_false:
10123           /* Result is always false.  */
10124           if (! likely)
10125             macro_build (NULL, "nop", "");
10126           else
10127             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
10128           break;
10129         }
10130       ++imm_expr.X_add_number;
10131       /* FALLTHROUGH */
10132     case M_BGE_I:
10133     case M_BGEL_I:
10134       if (mask == M_BGEL_I)
10135         likely = 1;
10136       if (imm_expr.X_add_number == 0)
10137         {
10138           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
10139                                  &offset_expr, op[0]);
10140           break;
10141         }
10142       if (imm_expr.X_add_number == 1)
10143         {
10144           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
10145                                  &offset_expr, op[0]);
10146           break;
10147         }
10148       if (imm_expr.X_add_number <= GPR_SMIN)
10149         {
10150         do_true:
10151           /* result is always true */
10152           as_warn (_("branch %s is always true"), ip->insn_mo->name);
10153           macro_build (&offset_expr, "b", "p");
10154           break;
10155         }
10156       used_at = 1;
10157       set_at (op[0], 0);
10158       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10159                                &offset_expr, AT, ZERO);
10160       break;
10161
10162     case M_BGEUL:
10163       likely = 1;
10164       /* Fall through.  */
10165     case M_BGEU:
10166       if (op[1] == 0)
10167         goto do_true;
10168       else if (op[0] == 0)
10169         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10170                                  &offset_expr, ZERO, op[1]);
10171       else
10172         {
10173           used_at = 1;
10174           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10175           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10176                                    &offset_expr, AT, ZERO);
10177         }
10178       break;
10179
10180     case M_BGTUL_I:
10181       likely = 1;
10182       /* Fall through.  */
10183     case M_BGTU_I:
10184       if (op[0] == 0
10185           || (GPR_SIZE == 32
10186               && imm_expr.X_add_number == -1))
10187         goto do_false;
10188       ++imm_expr.X_add_number;
10189       /* FALLTHROUGH */
10190     case M_BGEU_I:
10191     case M_BGEUL_I:
10192       if (mask == M_BGEUL_I)
10193         likely = 1;
10194       if (imm_expr.X_add_number == 0)
10195         goto do_true;
10196       else if (imm_expr.X_add_number == 1)
10197         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10198                                  &offset_expr, op[0], ZERO);
10199       else
10200         {
10201           used_at = 1;
10202           set_at (op[0], 1);
10203           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10204                                    &offset_expr, AT, ZERO);
10205         }
10206       break;
10207
10208     case M_BGTL:
10209       likely = 1;
10210       /* Fall through.  */
10211     case M_BGT:
10212       if (op[1] == 0)
10213         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
10214       else if (op[0] == 0)
10215         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
10216       else
10217         {
10218           used_at = 1;
10219           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10220           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10221                                    &offset_expr, AT, ZERO);
10222         }
10223       break;
10224
10225     case M_BGTUL:
10226       likely = 1;
10227       /* Fall through.  */
10228     case M_BGTU:
10229       if (op[1] == 0)
10230         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10231                                  &offset_expr, op[0], ZERO);
10232       else if (op[0] == 0)
10233         goto do_false;
10234       else
10235         {
10236           used_at = 1;
10237           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10238           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10239                                    &offset_expr, AT, ZERO);
10240         }
10241       break;
10242
10243     case M_BLEL:
10244       likely = 1;
10245       /* Fall through.  */
10246     case M_BLE:
10247       if (op[1] == 0)
10248         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10249       else if (op[0] == 0)
10250         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
10251       else
10252         {
10253           used_at = 1;
10254           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10255           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10256                                    &offset_expr, AT, ZERO);
10257         }
10258       break;
10259
10260     case M_BLEL_I:
10261       likely = 1;
10262       /* Fall through.  */
10263     case M_BLE_I:
10264       if (imm_expr.X_add_number >= GPR_SMAX)
10265         goto do_true;
10266       ++imm_expr.X_add_number;
10267       /* FALLTHROUGH */
10268     case M_BLT_I:
10269     case M_BLTL_I:
10270       if (mask == M_BLTL_I)
10271         likely = 1;
10272       if (imm_expr.X_add_number == 0)
10273         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10274       else if (imm_expr.X_add_number == 1)
10275         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10276       else
10277         {
10278           used_at = 1;
10279           set_at (op[0], 0);
10280           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10281                                    &offset_expr, AT, ZERO);
10282         }
10283       break;
10284
10285     case M_BLEUL:
10286       likely = 1;
10287       /* Fall through.  */
10288     case M_BLEU:
10289       if (op[1] == 0)
10290         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10291                                  &offset_expr, op[0], ZERO);
10292       else if (op[0] == 0)
10293         goto do_true;
10294       else
10295         {
10296           used_at = 1;
10297           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10298           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10299                                    &offset_expr, AT, ZERO);
10300         }
10301       break;
10302
10303     case M_BLEUL_I:
10304       likely = 1;
10305       /* Fall through.  */
10306     case M_BLEU_I:
10307       if (op[0] == 0
10308           || (GPR_SIZE == 32
10309               && imm_expr.X_add_number == -1))
10310         goto do_true;
10311       ++imm_expr.X_add_number;
10312       /* FALLTHROUGH */
10313     case M_BLTU_I:
10314     case M_BLTUL_I:
10315       if (mask == M_BLTUL_I)
10316         likely = 1;
10317       if (imm_expr.X_add_number == 0)
10318         goto do_false;
10319       else if (imm_expr.X_add_number == 1)
10320         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10321                                  &offset_expr, op[0], ZERO);
10322       else
10323         {
10324           used_at = 1;
10325           set_at (op[0], 1);
10326           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10327                                    &offset_expr, AT, ZERO);
10328         }
10329       break;
10330
10331     case M_BLTL:
10332       likely = 1;
10333       /* Fall through.  */
10334     case M_BLT:
10335       if (op[1] == 0)
10336         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10337       else if (op[0] == 0)
10338         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
10339       else
10340         {
10341           used_at = 1;
10342           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10343           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10344                                    &offset_expr, AT, ZERO);
10345         }
10346       break;
10347
10348     case M_BLTUL:
10349       likely = 1;
10350       /* Fall through.  */
10351     case M_BLTU:
10352       if (op[1] == 0)
10353         goto do_false;
10354       else if (op[0] == 0)
10355         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10356                                  &offset_expr, ZERO, op[1]);
10357       else
10358         {
10359           used_at = 1;
10360           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10361           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10362                                    &offset_expr, AT, ZERO);
10363         }
10364       break;
10365
10366     case M_DDIV_3:
10367       dbl = 1;
10368       /* Fall through.  */
10369     case M_DIV_3:
10370       s = "mflo";
10371       goto do_div3;
10372     case M_DREM_3:
10373       dbl = 1;
10374       /* Fall through.  */
10375     case M_REM_3:
10376       s = "mfhi";
10377     do_div3:
10378       if (op[2] == 0)
10379         {
10380           as_warn (_("divide by zero"));
10381           if (mips_trap)
10382             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10383           else
10384             macro_build (NULL, "break", BRK_FMT, 7);
10385           break;
10386         }
10387
10388       start_noreorder ();
10389       if (mips_trap)
10390         {
10391           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10392           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10393         }
10394       else
10395         {
10396           if (mips_opts.micromips)
10397             micromips_label_expr (&label_expr);
10398           else
10399             label_expr.X_add_number = 8;
10400           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10401           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10402           macro_build (NULL, "break", BRK_FMT, 7);
10403           if (mips_opts.micromips)
10404             micromips_add_label ();
10405         }
10406       expr1.X_add_number = -1;
10407       used_at = 1;
10408       load_register (AT, &expr1, dbl);
10409       if (mips_opts.micromips)
10410         micromips_label_expr (&label_expr);
10411       else
10412         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
10413       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
10414       if (dbl)
10415         {
10416           expr1.X_add_number = 1;
10417           load_register (AT, &expr1, dbl);
10418           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
10419         }
10420       else
10421         {
10422           expr1.X_add_number = 0x80000000;
10423           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
10424         }
10425       if (mips_trap)
10426         {
10427           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
10428           /* We want to close the noreorder block as soon as possible, so
10429              that later insns are available for delay slot filling.  */
10430           end_noreorder ();
10431         }
10432       else
10433         {
10434           if (mips_opts.micromips)
10435             micromips_label_expr (&label_expr);
10436           else
10437             label_expr.X_add_number = 8;
10438           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
10439           macro_build (NULL, "nop", "");
10440
10441           /* We want to close the noreorder block as soon as possible, so
10442              that later insns are available for delay slot filling.  */
10443           end_noreorder ();
10444
10445           macro_build (NULL, "break", BRK_FMT, 6);
10446         }
10447       if (mips_opts.micromips)
10448         micromips_add_label ();
10449       macro_build (NULL, s, MFHL_FMT, op[0]);
10450       break;
10451
10452     case M_DIV_3I:
10453       s = "div";
10454       s2 = "mflo";
10455       goto do_divi;
10456     case M_DIVU_3I:
10457       s = "divu";
10458       s2 = "mflo";
10459       goto do_divi;
10460     case M_REM_3I:
10461       s = "div";
10462       s2 = "mfhi";
10463       goto do_divi;
10464     case M_REMU_3I:
10465       s = "divu";
10466       s2 = "mfhi";
10467       goto do_divi;
10468     case M_DDIV_3I:
10469       dbl = 1;
10470       s = "ddiv";
10471       s2 = "mflo";
10472       goto do_divi;
10473     case M_DDIVU_3I:
10474       dbl = 1;
10475       s = "ddivu";
10476       s2 = "mflo";
10477       goto do_divi;
10478     case M_DREM_3I:
10479       dbl = 1;
10480       s = "ddiv";
10481       s2 = "mfhi";
10482       goto do_divi;
10483     case M_DREMU_3I:
10484       dbl = 1;
10485       s = "ddivu";
10486       s2 = "mfhi";
10487     do_divi:
10488       if (imm_expr.X_add_number == 0)
10489         {
10490           as_warn (_("divide by zero"));
10491           if (mips_trap)
10492             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10493           else
10494             macro_build (NULL, "break", BRK_FMT, 7);
10495           break;
10496         }
10497       if (imm_expr.X_add_number == 1)
10498         {
10499           if (strcmp (s2, "mflo") == 0)
10500             move_register (op[0], op[1]);
10501           else
10502             move_register (op[0], ZERO);
10503           break;
10504         }
10505       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
10506         {
10507           if (strcmp (s2, "mflo") == 0)
10508             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
10509           else
10510             move_register (op[0], ZERO);
10511           break;
10512         }
10513
10514       used_at = 1;
10515       load_register (AT, &imm_expr, dbl);
10516       macro_build (NULL, s, "z,s,t", op[1], AT);
10517       macro_build (NULL, s2, MFHL_FMT, op[0]);
10518       break;
10519
10520     case M_DIVU_3:
10521       s = "divu";
10522       s2 = "mflo";
10523       goto do_divu3;
10524     case M_REMU_3:
10525       s = "divu";
10526       s2 = "mfhi";
10527       goto do_divu3;
10528     case M_DDIVU_3:
10529       s = "ddivu";
10530       s2 = "mflo";
10531       goto do_divu3;
10532     case M_DREMU_3:
10533       s = "ddivu";
10534       s2 = "mfhi";
10535     do_divu3:
10536       start_noreorder ();
10537       if (mips_trap)
10538         {
10539           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10540           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10541           /* We want to close the noreorder block as soon as possible, so
10542              that later insns are available for delay slot filling.  */
10543           end_noreorder ();
10544         }
10545       else
10546         {
10547           if (mips_opts.micromips)
10548             micromips_label_expr (&label_expr);
10549           else
10550             label_expr.X_add_number = 8;
10551           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10552           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10553
10554           /* We want to close the noreorder block as soon as possible, so
10555              that later insns are available for delay slot filling.  */
10556           end_noreorder ();
10557           macro_build (NULL, "break", BRK_FMT, 7);
10558           if (mips_opts.micromips)
10559             micromips_add_label ();
10560         }
10561       macro_build (NULL, s2, MFHL_FMT, op[0]);
10562       break;
10563
10564     case M_DLCA_AB:
10565       dbl = 1;
10566       /* Fall through.  */
10567     case M_LCA_AB:
10568       call = 1;
10569       goto do_la;
10570     case M_DLA_AB:
10571       dbl = 1;
10572       /* Fall through.  */
10573     case M_LA_AB:
10574     do_la:
10575       /* Load the address of a symbol into a register.  If breg is not
10576          zero, we then add a base register to it.  */
10577
10578       breg = op[2];
10579       if (dbl && GPR_SIZE == 32)
10580         as_warn (_("dla used to load 32-bit register; recommend using la "
10581                    "instead"));
10582
10583       if (!dbl && HAVE_64BIT_OBJECTS)
10584         as_warn (_("la used to load 64-bit address; recommend using dla "
10585                    "instead"));
10586
10587       if (small_offset_p (0, align, 16))
10588         {
10589           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
10590                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10591           break;
10592         }
10593
10594       if (mips_opts.at && (op[0] == breg))
10595         {
10596           tempreg = AT;
10597           used_at = 1;
10598         }
10599       else
10600         tempreg = op[0];
10601
10602       if (offset_expr.X_op != O_symbol
10603           && offset_expr.X_op != O_constant)
10604         {
10605           as_bad (_("expression too complex"));
10606           offset_expr.X_op = O_constant;
10607         }
10608
10609       if (offset_expr.X_op == O_constant)
10610         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
10611       else if (mips_pic == NO_PIC)
10612         {
10613           /* If this is a reference to a GP relative symbol, we want
10614                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
10615              Otherwise we want
10616                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10617                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10618              If we have a constant, we need two instructions anyhow,
10619              so we may as well always use the latter form.
10620
10621              With 64bit address space and a usable $at we want
10622                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10623                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10624                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10625                daddiu   $at,<sym>               (BFD_RELOC_LO16)
10626                dsll32   $tempreg,0
10627                daddu    $tempreg,$tempreg,$at
10628
10629              If $at is already in use, we use a path which is suboptimal
10630              on superscalar processors.
10631                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10632                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10633                dsll     $tempreg,16
10634                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10635                dsll     $tempreg,16
10636                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
10637
10638              For GP relative symbols in 64bit address space we can use
10639              the same sequence as in 32bit address space.  */
10640           if (HAVE_64BIT_SYMBOLS)
10641             {
10642               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10643                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10644                 {
10645                   relax_start (offset_expr.X_add_symbol);
10646                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10647                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10648                   relax_switch ();
10649                 }
10650
10651               if (used_at == 0 && mips_opts.at)
10652                 {
10653                   macro_build (&offset_expr, "lui", LUI_FMT,
10654                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10655                   macro_build (&offset_expr, "lui", LUI_FMT,
10656                                AT, BFD_RELOC_HI16_S);
10657                   macro_build (&offset_expr, "daddiu", "t,r,j",
10658                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10659                   macro_build (&offset_expr, "daddiu", "t,r,j",
10660                                AT, AT, BFD_RELOC_LO16);
10661                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10662                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10663                   used_at = 1;
10664                 }
10665               else
10666                 {
10667                   macro_build (&offset_expr, "lui", LUI_FMT,
10668                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10669                   macro_build (&offset_expr, "daddiu", "t,r,j",
10670                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10671                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10672                   macro_build (&offset_expr, "daddiu", "t,r,j",
10673                                tempreg, tempreg, BFD_RELOC_HI16_S);
10674                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10675                   macro_build (&offset_expr, "daddiu", "t,r,j",
10676                                tempreg, tempreg, BFD_RELOC_LO16);
10677                 }
10678
10679               if (mips_relax.sequence)
10680                 relax_end ();
10681             }
10682           else
10683             {
10684               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10685                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10686                 {
10687                   relax_start (offset_expr.X_add_symbol);
10688                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10689                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10690                   relax_switch ();
10691                 }
10692               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10693                 as_bad (_("offset too large"));
10694               macro_build_lui (&offset_expr, tempreg);
10695               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10696                            tempreg, tempreg, BFD_RELOC_LO16);
10697               if (mips_relax.sequence)
10698                 relax_end ();
10699             }
10700         }
10701       else if (!mips_big_got && !HAVE_NEWABI)
10702         {
10703           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10704
10705           /* If this is a reference to an external symbol, and there
10706              is no constant, we want
10707                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10708              or for lca or if tempreg is PIC_CALL_REG
10709                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10710              For a local symbol, we want
10711                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10712                nop
10713                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10714
10715              If we have a small constant, and this is a reference to
10716              an external symbol, we want
10717                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10718                nop
10719                addiu    $tempreg,$tempreg,<constant>
10720              For a local symbol, we want the same instruction
10721              sequence, but we output a BFD_RELOC_LO16 reloc on the
10722              addiu instruction.
10723
10724              If we have a large constant, and this is a reference to
10725              an external symbol, we want
10726                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10727                lui      $at,<hiconstant>
10728                addiu    $at,$at,<loconstant>
10729                addu     $tempreg,$tempreg,$at
10730              For a local symbol, we want the same instruction
10731              sequence, but we output a BFD_RELOC_LO16 reloc on the
10732              addiu instruction.
10733            */
10734
10735           if (offset_expr.X_add_number == 0)
10736             {
10737               if (mips_pic == SVR4_PIC
10738                   && breg == 0
10739                   && (call || tempreg == PIC_CALL_REG))
10740                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
10741
10742               relax_start (offset_expr.X_add_symbol);
10743               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10744                            lw_reloc_type, mips_gp_register);
10745               if (breg != 0)
10746                 {
10747                   /* We're going to put in an addu instruction using
10748                      tempreg, so we may as well insert the nop right
10749                      now.  */
10750                   load_delay_nop ();
10751                 }
10752               relax_switch ();
10753               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10754                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
10755               load_delay_nop ();
10756               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10757                            tempreg, tempreg, BFD_RELOC_LO16);
10758               relax_end ();
10759               /* FIXME: If breg == 0, and the next instruction uses
10760                  $tempreg, then if this variant case is used an extra
10761                  nop will be generated.  */
10762             }
10763           else if (offset_expr.X_add_number >= -0x8000
10764                    && offset_expr.X_add_number < 0x8000)
10765             {
10766               load_got_offset (tempreg, &offset_expr);
10767               load_delay_nop ();
10768               add_got_offset (tempreg, &offset_expr);
10769             }
10770           else
10771             {
10772               expr1.X_add_number = offset_expr.X_add_number;
10773               offset_expr.X_add_number =
10774                 SEXT_16BIT (offset_expr.X_add_number);
10775               load_got_offset (tempreg, &offset_expr);
10776               offset_expr.X_add_number = expr1.X_add_number;
10777               /* If we are going to add in a base register, and the
10778                  target register and the base register are the same,
10779                  then we are using AT as a temporary register.  Since
10780                  we want to load the constant into AT, we add our
10781                  current AT (from the global offset table) and the
10782                  register into the register now, and pretend we were
10783                  not using a base register.  */
10784               if (breg == op[0])
10785                 {
10786                   load_delay_nop ();
10787                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10788                                op[0], AT, breg);
10789                   breg = 0;
10790                   tempreg = op[0];
10791                 }
10792               add_got_offset_hilo (tempreg, &offset_expr, AT);
10793               used_at = 1;
10794             }
10795         }
10796       else if (!mips_big_got && HAVE_NEWABI)
10797         {
10798           int add_breg_early = 0;
10799
10800           /* If this is a reference to an external, and there is no
10801              constant, or local symbol (*), with or without a
10802              constant, we want
10803                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10804              or for lca or if tempreg is PIC_CALL_REG
10805                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10806
10807              If we have a small constant, and this is a reference to
10808              an external symbol, we want
10809                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10810                addiu    $tempreg,$tempreg,<constant>
10811
10812              If we have a large constant, and this is a reference to
10813              an external symbol, we want
10814                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10815                lui      $at,<hiconstant>
10816                addiu    $at,$at,<loconstant>
10817                addu     $tempreg,$tempreg,$at
10818
10819              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10820              local symbols, even though it introduces an additional
10821              instruction.  */
10822
10823           if (offset_expr.X_add_number)
10824             {
10825               expr1.X_add_number = offset_expr.X_add_number;
10826               offset_expr.X_add_number = 0;
10827
10828               relax_start (offset_expr.X_add_symbol);
10829               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10830                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10831
10832               if (expr1.X_add_number >= -0x8000
10833                   && expr1.X_add_number < 0x8000)
10834                 {
10835                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10836                                tempreg, tempreg, BFD_RELOC_LO16);
10837                 }
10838               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10839                 {
10840                   unsigned int dreg;
10841
10842                   /* If we are going to add in a base register, and the
10843                      target register and the base register are the same,
10844                      then we are using AT as a temporary register.  Since
10845                      we want to load the constant into AT, we add our
10846                      current AT (from the global offset table) and the
10847                      register into the register now, and pretend we were
10848                      not using a base register.  */
10849                   if (breg != op[0])
10850                     dreg = tempreg;
10851                   else
10852                     {
10853                       gas_assert (tempreg == AT);
10854                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10855                                    op[0], AT, breg);
10856                       dreg = op[0];
10857                       add_breg_early = 1;
10858                     }
10859
10860                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10861                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10862                                dreg, dreg, AT);
10863
10864                   used_at = 1;
10865                 }
10866               else
10867                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10868
10869               relax_switch ();
10870               offset_expr.X_add_number = expr1.X_add_number;
10871
10872               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10873                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10874               if (add_breg_early)
10875                 {
10876                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10877                                op[0], tempreg, breg);
10878                   breg = 0;
10879                   tempreg = op[0];
10880                 }
10881               relax_end ();
10882             }
10883           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10884             {
10885               relax_start (offset_expr.X_add_symbol);
10886               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10887                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10888               relax_switch ();
10889               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10890                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10891               relax_end ();
10892             }
10893           else
10894             {
10895               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10896                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10897             }
10898         }
10899       else if (mips_big_got && !HAVE_NEWABI)
10900         {
10901           int gpdelay;
10902           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10903           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10904           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10905
10906           /* This is the large GOT case.  If this is a reference to an
10907              external symbol, and there is no constant, we want
10908                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10909                addu     $tempreg,$tempreg,$gp
10910                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10911              or for lca or if tempreg is PIC_CALL_REG
10912                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10913                addu     $tempreg,$tempreg,$gp
10914                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10915              For a local symbol, we want
10916                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10917                nop
10918                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10919
10920              If we have a small constant, and this is a reference to
10921              an external symbol, we want
10922                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10923                addu     $tempreg,$tempreg,$gp
10924                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10925                nop
10926                addiu    $tempreg,$tempreg,<constant>
10927              For a local symbol, we want
10928                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10929                nop
10930                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10931
10932              If we have a large constant, and this is a reference to
10933              an external symbol, we want
10934                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10935                addu     $tempreg,$tempreg,$gp
10936                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10937                lui      $at,<hiconstant>
10938                addiu    $at,$at,<loconstant>
10939                addu     $tempreg,$tempreg,$at
10940              For a local symbol, we want
10941                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10942                lui      $at,<hiconstant>
10943                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10944                addu     $tempreg,$tempreg,$at
10945           */
10946
10947           expr1.X_add_number = offset_expr.X_add_number;
10948           offset_expr.X_add_number = 0;
10949           relax_start (offset_expr.X_add_symbol);
10950           gpdelay = reg_needs_delay (mips_gp_register);
10951           if (expr1.X_add_number == 0 && breg == 0
10952               && (call || tempreg == PIC_CALL_REG))
10953             {
10954               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10955               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10956             }
10957           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10958           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10959                        tempreg, tempreg, mips_gp_register);
10960           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10961                        tempreg, lw_reloc_type, tempreg);
10962           if (expr1.X_add_number == 0)
10963             {
10964               if (breg != 0)
10965                 {
10966                   /* We're going to put in an addu instruction using
10967                      tempreg, so we may as well insert the nop right
10968                      now.  */
10969                   load_delay_nop ();
10970                 }
10971             }
10972           else if (expr1.X_add_number >= -0x8000
10973                    && expr1.X_add_number < 0x8000)
10974             {
10975               load_delay_nop ();
10976               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10977                            tempreg, tempreg, BFD_RELOC_LO16);
10978             }
10979           else
10980             {
10981               unsigned int dreg;
10982
10983               /* If we are going to add in a base register, and the
10984                  target register and the base register are the same,
10985                  then we are using AT as a temporary register.  Since
10986                  we want to load the constant into AT, we add our
10987                  current AT (from the global offset table) and the
10988                  register into the register now, and pretend we were
10989                  not using a base register.  */
10990               if (breg != op[0])
10991                 dreg = tempreg;
10992               else
10993                 {
10994                   gas_assert (tempreg == AT);
10995                   load_delay_nop ();
10996                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10997                                op[0], AT, breg);
10998                   dreg = op[0];
10999                 }
11000
11001               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11002               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11003
11004               used_at = 1;
11005             }
11006           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
11007           relax_switch ();
11008
11009           if (gpdelay)
11010             {
11011               /* This is needed because this instruction uses $gp, but
11012                  the first instruction on the main stream does not.  */
11013               macro_build (NULL, "nop", "");
11014             }
11015
11016           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11017                        local_reloc_type, mips_gp_register);
11018           if (expr1.X_add_number >= -0x8000
11019               && expr1.X_add_number < 0x8000)
11020             {
11021               load_delay_nop ();
11022               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11023                            tempreg, tempreg, BFD_RELOC_LO16);
11024               /* FIXME: If add_number is 0, and there was no base
11025                  register, the external symbol case ended with a load,
11026                  so if the symbol turns out to not be external, and
11027                  the next instruction uses tempreg, an unnecessary nop
11028                  will be inserted.  */
11029             }
11030           else
11031             {
11032               if (breg == op[0])
11033                 {
11034                   /* We must add in the base register now, as in the
11035                      external symbol case.  */
11036                   gas_assert (tempreg == AT);
11037                   load_delay_nop ();
11038                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11039                                op[0], AT, breg);
11040                   tempreg = op[0];
11041                   /* We set breg to 0 because we have arranged to add
11042                      it in in both cases.  */
11043                   breg = 0;
11044                 }
11045
11046               macro_build_lui (&expr1, AT);
11047               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11048                            AT, AT, BFD_RELOC_LO16);
11049               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11050                            tempreg, tempreg, AT);
11051               used_at = 1;
11052             }
11053           relax_end ();
11054         }
11055       else if (mips_big_got && HAVE_NEWABI)
11056         {
11057           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11058           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11059           int add_breg_early = 0;
11060
11061           /* This is the large GOT case.  If this is a reference to an
11062              external symbol, and there is no constant, we want
11063                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11064                add      $tempreg,$tempreg,$gp
11065                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11066              or for lca or if tempreg is PIC_CALL_REG
11067                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
11068                add      $tempreg,$tempreg,$gp
11069                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11070
11071              If we have a small constant, and this is a reference to
11072              an external symbol, we want
11073                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11074                add      $tempreg,$tempreg,$gp
11075                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11076                addi     $tempreg,$tempreg,<constant>
11077
11078              If we have a large constant, and this is a reference to
11079              an external symbol, we want
11080                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11081                addu     $tempreg,$tempreg,$gp
11082                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11083                lui      $at,<hiconstant>
11084                addi     $at,$at,<loconstant>
11085                add      $tempreg,$tempreg,$at
11086
11087              If we have NewABI, and we know it's a local symbol, we want
11088                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
11089                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
11090              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
11091
11092           relax_start (offset_expr.X_add_symbol);
11093
11094           expr1.X_add_number = offset_expr.X_add_number;
11095           offset_expr.X_add_number = 0;
11096
11097           if (expr1.X_add_number == 0 && breg == 0
11098               && (call || tempreg == PIC_CALL_REG))
11099             {
11100               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11101               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11102             }
11103           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11104           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11105                        tempreg, tempreg, mips_gp_register);
11106           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11107                        tempreg, lw_reloc_type, tempreg);
11108
11109           if (expr1.X_add_number == 0)
11110             ;
11111           else if (expr1.X_add_number >= -0x8000
11112                    && expr1.X_add_number < 0x8000)
11113             {
11114               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11115                            tempreg, tempreg, BFD_RELOC_LO16);
11116             }
11117           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11118             {
11119               unsigned int dreg;
11120
11121               /* If we are going to add in a base register, and the
11122                  target register and the base register are the same,
11123                  then we are using AT as a temporary register.  Since
11124                  we want to load the constant into AT, we add our
11125                  current AT (from the global offset table) and the
11126                  register into the register now, and pretend we were
11127                  not using a base register.  */
11128               if (breg != op[0])
11129                 dreg = tempreg;
11130               else
11131                 {
11132                   gas_assert (tempreg == AT);
11133                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11134                                op[0], AT, breg);
11135                   dreg = op[0];
11136                   add_breg_early = 1;
11137                 }
11138
11139               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11140               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11141
11142               used_at = 1;
11143             }
11144           else
11145             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11146
11147           relax_switch ();
11148           offset_expr.X_add_number = expr1.X_add_number;
11149           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11150                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11151           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11152                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
11153           if (add_breg_early)
11154             {
11155               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11156                            op[0], tempreg, breg);
11157               breg = 0;
11158               tempreg = op[0];
11159             }
11160           relax_end ();
11161         }
11162       else
11163         abort ();
11164
11165       if (breg != 0)
11166         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
11167       break;
11168
11169     case M_MSGSND:
11170       gas_assert (!mips_opts.micromips);
11171       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
11172       break;
11173
11174     case M_MSGLD:
11175       gas_assert (!mips_opts.micromips);
11176       macro_build (NULL, "c2", "C", 0x02);
11177       break;
11178
11179     case M_MSGLD_T:
11180       gas_assert (!mips_opts.micromips);
11181       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
11182       break;
11183
11184     case M_MSGWAIT:
11185       gas_assert (!mips_opts.micromips);
11186       macro_build (NULL, "c2", "C", 3);
11187       break;
11188
11189     case M_MSGWAIT_T:
11190       gas_assert (!mips_opts.micromips);
11191       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
11192       break;
11193
11194     case M_J_A:
11195       /* The j instruction may not be used in PIC code, since it
11196          requires an absolute address.  We convert it to a b
11197          instruction.  */
11198       if (mips_pic == NO_PIC)
11199         macro_build (&offset_expr, "j", "a");
11200       else
11201         macro_build (&offset_expr, "b", "p");
11202       break;
11203
11204       /* The jal instructions must be handled as macros because when
11205          generating PIC code they expand to multi-instruction
11206          sequences.  Normally they are simple instructions.  */
11207     case M_JALS_1:
11208       op[1] = op[0];
11209       op[0] = RA;
11210       /* Fall through.  */
11211     case M_JALS_2:
11212       gas_assert (mips_opts.micromips);
11213       if (mips_opts.insn32)
11214         {
11215           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11216           break;
11217         }
11218       jals = 1;
11219       goto jal;
11220     case M_JAL_1:
11221       op[1] = op[0];
11222       op[0] = RA;
11223       /* Fall through.  */
11224     case M_JAL_2:
11225     jal:
11226       if (mips_pic == NO_PIC)
11227         {
11228           s = jals ? "jalrs" : "jalr";
11229           if (mips_opts.micromips
11230               && !mips_opts.insn32
11231               && op[0] == RA
11232               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11233             macro_build (NULL, s, "mj", op[1]);
11234           else
11235             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11236         }
11237       else
11238         {
11239           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
11240                            && mips_cprestore_offset >= 0);
11241
11242           if (op[1] != PIC_CALL_REG)
11243             as_warn (_("MIPS PIC call to register other than $25"));
11244
11245           s = ((mips_opts.micromips
11246                 && !mips_opts.insn32
11247                 && (!mips_opts.noreorder || cprestore))
11248                ? "jalrs" : "jalr");
11249           if (mips_opts.micromips
11250               && !mips_opts.insn32
11251               && op[0] == RA
11252               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11253             macro_build (NULL, s, "mj", op[1]);
11254           else
11255             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11256           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
11257             {
11258               if (mips_cprestore_offset < 0)
11259                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11260               else
11261                 {
11262                   if (!mips_frame_reg_valid)
11263                     {
11264                       as_warn (_("no .frame pseudo-op used in PIC code"));
11265                       /* Quiet this warning.  */
11266                       mips_frame_reg_valid = 1;
11267                     }
11268                   if (!mips_cprestore_valid)
11269                     {
11270                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11271                       /* Quiet this warning.  */
11272                       mips_cprestore_valid = 1;
11273                     }
11274                   if (mips_opts.noreorder)
11275                     macro_build (NULL, "nop", "");
11276                   expr1.X_add_number = mips_cprestore_offset;
11277                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11278                                                 mips_gp_register,
11279                                                 mips_frame_reg,
11280                                                 HAVE_64BIT_ADDRESSES);
11281                 }
11282             }
11283         }
11284
11285       break;
11286
11287     case M_JALS_A:
11288       gas_assert (mips_opts.micromips);
11289       if (mips_opts.insn32)
11290         {
11291           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11292           break;
11293         }
11294       jals = 1;
11295       /* Fall through.  */
11296     case M_JAL_A:
11297       if (mips_pic == NO_PIC)
11298         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
11299       else if (mips_pic == SVR4_PIC)
11300         {
11301           /* If this is a reference to an external symbol, and we are
11302              using a small GOT, we want
11303                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
11304                nop
11305                jalr     $ra,$25
11306                nop
11307                lw       $gp,cprestore($sp)
11308              The cprestore value is set using the .cprestore
11309              pseudo-op.  If we are using a big GOT, we want
11310                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
11311                addu     $25,$25,$gp
11312                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
11313                nop
11314                jalr     $ra,$25
11315                nop
11316                lw       $gp,cprestore($sp)
11317              If the symbol is not external, we want
11318                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11319                nop
11320                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
11321                jalr     $ra,$25
11322                nop
11323                lw $gp,cprestore($sp)
11324
11325              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
11326              sequences above, minus nops, unless the symbol is local,
11327              which enables us to use GOT_PAGE/GOT_OFST (big got) or
11328              GOT_DISP.  */
11329           if (HAVE_NEWABI)
11330             {
11331               if (!mips_big_got)
11332                 {
11333                   relax_start (offset_expr.X_add_symbol);
11334                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11335                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11336                                mips_gp_register);
11337                   relax_switch ();
11338                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11339                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
11340                                mips_gp_register);
11341                   relax_end ();
11342                 }
11343               else
11344                 {
11345                   relax_start (offset_expr.X_add_symbol);
11346                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11347                                BFD_RELOC_MIPS_CALL_HI16);
11348                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11349                                PIC_CALL_REG, mips_gp_register);
11350                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11351                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11352                                PIC_CALL_REG);
11353                   relax_switch ();
11354                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11355                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
11356                                mips_gp_register);
11357                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11358                                PIC_CALL_REG, PIC_CALL_REG,
11359                                BFD_RELOC_MIPS_GOT_OFST);
11360                   relax_end ();
11361                 }
11362
11363               macro_build_jalr (&offset_expr, 0);
11364             }
11365           else
11366             {
11367               relax_start (offset_expr.X_add_symbol);
11368               if (!mips_big_got)
11369                 {
11370                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11371                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11372                                mips_gp_register);
11373                   load_delay_nop ();
11374                   relax_switch ();
11375                 }
11376               else
11377                 {
11378                   int gpdelay;
11379
11380                   gpdelay = reg_needs_delay (mips_gp_register);
11381                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11382                                BFD_RELOC_MIPS_CALL_HI16);
11383                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11384                                PIC_CALL_REG, mips_gp_register);
11385                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11386                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11387                                PIC_CALL_REG);
11388                   load_delay_nop ();
11389                   relax_switch ();
11390                   if (gpdelay)
11391                     macro_build (NULL, "nop", "");
11392                 }
11393               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11394                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
11395                            mips_gp_register);
11396               load_delay_nop ();
11397               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11398                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
11399               relax_end ();
11400               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
11401
11402               if (mips_cprestore_offset < 0)
11403                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11404               else
11405                 {
11406                   if (!mips_frame_reg_valid)
11407                     {
11408                       as_warn (_("no .frame pseudo-op used in PIC code"));
11409                       /* Quiet this warning.  */
11410                       mips_frame_reg_valid = 1;
11411                     }
11412                   if (!mips_cprestore_valid)
11413                     {
11414                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11415                       /* Quiet this warning.  */
11416                       mips_cprestore_valid = 1;
11417                     }
11418                   if (mips_opts.noreorder)
11419                     macro_build (NULL, "nop", "");
11420                   expr1.X_add_number = mips_cprestore_offset;
11421                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11422                                                 mips_gp_register,
11423                                                 mips_frame_reg,
11424                                                 HAVE_64BIT_ADDRESSES);
11425                 }
11426             }
11427         }
11428       else if (mips_pic == VXWORKS_PIC)
11429         as_bad (_("non-PIC jump used in PIC library"));
11430       else
11431         abort ();
11432
11433       break;
11434
11435     case M_LBUE_AB:
11436       s = "lbue";
11437       fmt = "t,+j(b)";
11438       offbits = 9;
11439       goto ld_st;
11440     case M_LHUE_AB:
11441       s = "lhue";
11442       fmt = "t,+j(b)";
11443       offbits = 9;
11444       goto ld_st;
11445     case M_LBE_AB:
11446       s = "lbe";
11447       fmt = "t,+j(b)";
11448       offbits = 9;
11449       goto ld_st;
11450     case M_LHE_AB:
11451       s = "lhe";
11452       fmt = "t,+j(b)";
11453       offbits = 9;
11454       goto ld_st;
11455     case M_LLE_AB:
11456       s = "lle";
11457       fmt = "t,+j(b)";
11458       offbits = 9;
11459       goto ld_st;
11460     case M_LWE_AB:
11461       s = "lwe";
11462       fmt = "t,+j(b)";
11463       offbits = 9;
11464       goto ld_st;
11465     case M_LWLE_AB:
11466       s = "lwle";
11467       fmt = "t,+j(b)";
11468       offbits = 9;
11469       goto ld_st;
11470     case M_LWRE_AB:
11471       s = "lwre";
11472       fmt = "t,+j(b)";
11473       offbits = 9;
11474       goto ld_st;
11475     case M_SBE_AB:
11476       s = "sbe";
11477       fmt = "t,+j(b)";
11478       offbits = 9;
11479       goto ld_st;
11480     case M_SCE_AB:
11481       s = "sce";
11482       fmt = "t,+j(b)";
11483       offbits = 9;
11484       goto ld_st;
11485     case M_SHE_AB:
11486       s = "she";
11487       fmt = "t,+j(b)";
11488       offbits = 9;
11489       goto ld_st;
11490     case M_SWE_AB:
11491       s = "swe";
11492       fmt = "t,+j(b)";
11493       offbits = 9;
11494       goto ld_st;
11495     case M_SWLE_AB:
11496       s = "swle";
11497       fmt = "t,+j(b)";
11498       offbits = 9;
11499       goto ld_st;
11500     case M_SWRE_AB:
11501       s = "swre";
11502       fmt = "t,+j(b)";
11503       offbits = 9;
11504       goto ld_st;
11505     case M_ACLR_AB:
11506       s = "aclr";
11507       fmt = "\\,~(b)";
11508       offbits = 12;
11509       goto ld_st;
11510     case M_ASET_AB:
11511       s = "aset";
11512       fmt = "\\,~(b)";
11513       offbits = 12;
11514       goto ld_st;
11515     case M_LB_AB:
11516       s = "lb";
11517       fmt = "t,o(b)";
11518       goto ld;
11519     case M_LBU_AB:
11520       s = "lbu";
11521       fmt = "t,o(b)";
11522       goto ld;
11523     case M_LH_AB:
11524       s = "lh";
11525       fmt = "t,o(b)";
11526       goto ld;
11527     case M_LHU_AB:
11528       s = "lhu";
11529       fmt = "t,o(b)";
11530       goto ld;
11531     case M_LW_AB:
11532       s = "lw";
11533       fmt = "t,o(b)";
11534       goto ld;
11535     case M_LWC0_AB:
11536       gas_assert (!mips_opts.micromips);
11537       s = "lwc0";
11538       fmt = "E,o(b)";
11539       /* Itbl support may require additional care here.  */
11540       coproc = 1;
11541       goto ld_st;
11542     case M_LWC1_AB:
11543       s = "lwc1";
11544       fmt = "T,o(b)";
11545       /* Itbl support may require additional care here.  */
11546       coproc = 1;
11547       goto ld_st;
11548     case M_LWC2_AB:
11549       s = "lwc2";
11550       fmt = COP12_FMT;
11551       offbits = (mips_opts.micromips ? 12
11552                  : ISA_IS_R6 (mips_opts.isa) ? 11
11553                  : 16);
11554       /* Itbl support may require additional care here.  */
11555       coproc = 1;
11556       goto ld_st;
11557     case M_LWC3_AB:
11558       gas_assert (!mips_opts.micromips);
11559       s = "lwc3";
11560       fmt = "E,o(b)";
11561       /* Itbl support may require additional care here.  */
11562       coproc = 1;
11563       goto ld_st;
11564     case M_LWL_AB:
11565       s = "lwl";
11566       fmt = MEM12_FMT;
11567       offbits = (mips_opts.micromips ? 12 : 16);
11568       goto ld_st;
11569     case M_LWR_AB:
11570       s = "lwr";
11571       fmt = MEM12_FMT;
11572       offbits = (mips_opts.micromips ? 12 : 16);
11573       goto ld_st;
11574     case M_LDC1_AB:
11575       s = "ldc1";
11576       fmt = "T,o(b)";
11577       /* Itbl support may require additional care here.  */
11578       coproc = 1;
11579       goto ld_st;
11580     case M_LDC2_AB:
11581       s = "ldc2";
11582       fmt = COP12_FMT;
11583       offbits = (mips_opts.micromips ? 12
11584                  : ISA_IS_R6 (mips_opts.isa) ? 11
11585                  : 16);
11586       /* Itbl support may require additional care here.  */
11587       coproc = 1;
11588       goto ld_st;
11589     case M_LQC2_AB:
11590       s = "lqc2";
11591       fmt = "+7,o(b)";
11592       /* Itbl support may require additional care here.  */
11593       coproc = 1;
11594       goto ld_st;
11595     case M_LDC3_AB:
11596       s = "ldc3";
11597       fmt = "E,o(b)";
11598       /* Itbl support may require additional care here.  */
11599       coproc = 1;
11600       goto ld_st;
11601     case M_LDL_AB:
11602       s = "ldl";
11603       fmt = MEM12_FMT;
11604       offbits = (mips_opts.micromips ? 12 : 16);
11605       goto ld_st;
11606     case M_LDR_AB:
11607       s = "ldr";
11608       fmt = MEM12_FMT;
11609       offbits = (mips_opts.micromips ? 12 : 16);
11610       goto ld_st;
11611     case M_LL_AB:
11612       s = "ll";
11613       fmt = LL_SC_FMT;
11614       offbits = (mips_opts.micromips ? 12
11615                  : ISA_IS_R6 (mips_opts.isa) ? 9
11616                  : 16);
11617       goto ld;
11618     case M_LLD_AB:
11619       s = "lld";
11620       fmt = LL_SC_FMT;
11621       offbits = (mips_opts.micromips ? 12
11622                  : ISA_IS_R6 (mips_opts.isa) ? 9
11623                  : 16);
11624       goto ld;
11625     case M_LWU_AB:
11626       s = "lwu";
11627       fmt = MEM12_FMT;
11628       offbits = (mips_opts.micromips ? 12 : 16);
11629       goto ld;
11630     case M_LWP_AB:
11631       gas_assert (mips_opts.micromips);
11632       s = "lwp";
11633       fmt = "t,~(b)";
11634       offbits = 12;
11635       lp = 1;
11636       goto ld;
11637     case M_LDP_AB:
11638       gas_assert (mips_opts.micromips);
11639       s = "ldp";
11640       fmt = "t,~(b)";
11641       offbits = 12;
11642       lp = 1;
11643       goto ld;
11644     case M_LWM_AB:
11645       gas_assert (mips_opts.micromips);
11646       s = "lwm";
11647       fmt = "n,~(b)";
11648       offbits = 12;
11649       goto ld_st;
11650     case M_LDM_AB:
11651       gas_assert (mips_opts.micromips);
11652       s = "ldm";
11653       fmt = "n,~(b)";
11654       offbits = 12;
11655       goto ld_st;
11656
11657     ld:
11658       /* We don't want to use $0 as tempreg.  */
11659       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
11660         goto ld_st;
11661       else
11662         tempreg = op[0] + lp;
11663       goto ld_noat;
11664
11665     case M_SB_AB:
11666       s = "sb";
11667       fmt = "t,o(b)";
11668       goto ld_st;
11669     case M_SH_AB:
11670       s = "sh";
11671       fmt = "t,o(b)";
11672       goto ld_st;
11673     case M_SW_AB:
11674       s = "sw";
11675       fmt = "t,o(b)";
11676       goto ld_st;
11677     case M_SWC0_AB:
11678       gas_assert (!mips_opts.micromips);
11679       s = "swc0";
11680       fmt = "E,o(b)";
11681       /* Itbl support may require additional care here.  */
11682       coproc = 1;
11683       goto ld_st;
11684     case M_SWC1_AB:
11685       s = "swc1";
11686       fmt = "T,o(b)";
11687       /* Itbl support may require additional care here.  */
11688       coproc = 1;
11689       goto ld_st;
11690     case M_SWC2_AB:
11691       s = "swc2";
11692       fmt = COP12_FMT;
11693       offbits = (mips_opts.micromips ? 12
11694                  : ISA_IS_R6 (mips_opts.isa) ? 11
11695                  : 16);
11696       /* Itbl support may require additional care here.  */
11697       coproc = 1;
11698       goto ld_st;
11699     case M_SWC3_AB:
11700       gas_assert (!mips_opts.micromips);
11701       s = "swc3";
11702       fmt = "E,o(b)";
11703       /* Itbl support may require additional care here.  */
11704       coproc = 1;
11705       goto ld_st;
11706     case M_SWL_AB:
11707       s = "swl";
11708       fmt = MEM12_FMT;
11709       offbits = (mips_opts.micromips ? 12 : 16);
11710       goto ld_st;
11711     case M_SWR_AB:
11712       s = "swr";
11713       fmt = MEM12_FMT;
11714       offbits = (mips_opts.micromips ? 12 : 16);
11715       goto ld_st;
11716     case M_SC_AB:
11717       s = "sc";
11718       fmt = LL_SC_FMT;
11719       offbits = (mips_opts.micromips ? 12
11720                  : ISA_IS_R6 (mips_opts.isa) ? 9
11721                  : 16);
11722       goto ld_st;
11723     case M_SCD_AB:
11724       s = "scd";
11725       fmt = LL_SC_FMT;
11726       offbits = (mips_opts.micromips ? 12
11727                  : ISA_IS_R6 (mips_opts.isa) ? 9
11728                  : 16);
11729       goto ld_st;
11730     case M_CACHE_AB:
11731       s = "cache";
11732       fmt = (mips_opts.micromips ? "k,~(b)"
11733              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11734              : "k,o(b)");
11735       offbits = (mips_opts.micromips ? 12
11736                  : ISA_IS_R6 (mips_opts.isa) ? 9
11737                  : 16);
11738       goto ld_st;
11739     case M_CACHEE_AB:
11740       s = "cachee";
11741       fmt = "k,+j(b)";
11742       offbits = 9;
11743       goto ld_st;
11744     case M_PREF_AB:
11745       s = "pref";
11746       fmt = (mips_opts.micromips ? "k,~(b)"
11747              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11748              : "k,o(b)");
11749       offbits = (mips_opts.micromips ? 12
11750                  : ISA_IS_R6 (mips_opts.isa) ? 9
11751                  : 16);
11752       goto ld_st;
11753     case M_PREFE_AB:
11754       s = "prefe";
11755       fmt = "k,+j(b)";
11756       offbits = 9;
11757       goto ld_st;
11758     case M_SDC1_AB:
11759       s = "sdc1";
11760       fmt = "T,o(b)";
11761       coproc = 1;
11762       /* Itbl support may require additional care here.  */
11763       goto ld_st;
11764     case M_SDC2_AB:
11765       s = "sdc2";
11766       fmt = COP12_FMT;
11767       offbits = (mips_opts.micromips ? 12
11768                  : ISA_IS_R6 (mips_opts.isa) ? 11
11769                  : 16);
11770       /* Itbl support may require additional care here.  */
11771       coproc = 1;
11772       goto ld_st;
11773     case M_SQC2_AB:
11774       s = "sqc2";
11775       fmt = "+7,o(b)";
11776       /* Itbl support may require additional care here.  */
11777       coproc = 1;
11778       goto ld_st;
11779     case M_SDC3_AB:
11780       gas_assert (!mips_opts.micromips);
11781       s = "sdc3";
11782       fmt = "E,o(b)";
11783       /* Itbl support may require additional care here.  */
11784       coproc = 1;
11785       goto ld_st;
11786     case M_SDL_AB:
11787       s = "sdl";
11788       fmt = MEM12_FMT;
11789       offbits = (mips_opts.micromips ? 12 : 16);
11790       goto ld_st;
11791     case M_SDR_AB:
11792       s = "sdr";
11793       fmt = MEM12_FMT;
11794       offbits = (mips_opts.micromips ? 12 : 16);
11795       goto ld_st;
11796     case M_SWP_AB:
11797       gas_assert (mips_opts.micromips);
11798       s = "swp";
11799       fmt = "t,~(b)";
11800       offbits = 12;
11801       goto ld_st;
11802     case M_SDP_AB:
11803       gas_assert (mips_opts.micromips);
11804       s = "sdp";
11805       fmt = "t,~(b)";
11806       offbits = 12;
11807       goto ld_st;
11808     case M_SWM_AB:
11809       gas_assert (mips_opts.micromips);
11810       s = "swm";
11811       fmt = "n,~(b)";
11812       offbits = 12;
11813       goto ld_st;
11814     case M_SDM_AB:
11815       gas_assert (mips_opts.micromips);
11816       s = "sdm";
11817       fmt = "n,~(b)";
11818       offbits = 12;
11819
11820     ld_st:
11821       tempreg = AT;
11822     ld_noat:
11823       breg = op[2];
11824       if (small_offset_p (0, align, 16))
11825         {
11826           /* The first case exists for M_LD_AB and M_SD_AB, which are
11827              macros for o32 but which should act like normal instructions
11828              otherwise.  */
11829           if (offbits == 16)
11830             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
11831                          offset_reloc[1], offset_reloc[2], breg);
11832           else if (small_offset_p (0, align, offbits))
11833             {
11834               if (offbits == 0)
11835                 macro_build (NULL, s, fmt, op[0], breg);
11836               else
11837                 macro_build (NULL, s, fmt, op[0],
11838                              (int) offset_expr.X_add_number, breg);
11839             }
11840           else
11841             {
11842               if (tempreg == AT)
11843                 used_at = 1;
11844               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11845                            tempreg, breg, -1, offset_reloc[0],
11846                            offset_reloc[1], offset_reloc[2]);
11847               if (offbits == 0)
11848                 macro_build (NULL, s, fmt, op[0], tempreg);
11849               else
11850                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11851             }
11852           break;
11853         }
11854
11855       if (tempreg == AT)
11856         used_at = 1;
11857
11858       if (offset_expr.X_op != O_constant
11859           && offset_expr.X_op != O_symbol)
11860         {
11861           as_bad (_("expression too complex"));
11862           offset_expr.X_op = O_constant;
11863         }
11864
11865       if (HAVE_32BIT_ADDRESSES
11866           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11867         {
11868           char value [32];
11869
11870           sprintf_vma (value, offset_expr.X_add_number);
11871           as_bad (_("number (0x%s) larger than 32 bits"), value);
11872         }
11873
11874       /* A constant expression in PIC code can be handled just as it
11875          is in non PIC code.  */
11876       if (offset_expr.X_op == O_constant)
11877         {
11878           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11879                                                  offbits == 0 ? 16 : offbits);
11880           offset_expr.X_add_number -= expr1.X_add_number;
11881
11882           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11883           if (breg != 0)
11884             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11885                          tempreg, tempreg, breg);
11886           if (offbits == 0)
11887             {
11888               if (offset_expr.X_add_number != 0)
11889                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11890                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11891               macro_build (NULL, s, fmt, op[0], tempreg);
11892             }
11893           else if (offbits == 16)
11894             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11895           else
11896             macro_build (NULL, s, fmt, op[0],
11897                          (int) offset_expr.X_add_number, tempreg);
11898         }
11899       else if (offbits != 16)
11900         {
11901           /* The offset field is too narrow to be used for a low-part
11902              relocation, so load the whole address into the auxiliary
11903              register.  */
11904           load_address (tempreg, &offset_expr, &used_at);
11905           if (breg != 0)
11906             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11907                          tempreg, tempreg, breg);
11908           if (offbits == 0)
11909             macro_build (NULL, s, fmt, op[0], tempreg);
11910           else
11911             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11912         }
11913       else if (mips_pic == NO_PIC)
11914         {
11915           /* If this is a reference to a GP relative symbol, and there
11916              is no base register, we want
11917                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11918              Otherwise, if there is no base register, we want
11919                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11920                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11921              If we have a constant, we need two instructions anyhow,
11922              so we always use the latter form.
11923
11924              If we have a base register, and this is a reference to a
11925              GP relative symbol, we want
11926                addu     $tempreg,$breg,$gp
11927                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11928              Otherwise we want
11929                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11930                addu     $tempreg,$tempreg,$breg
11931                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11932              With a constant we always use the latter case.
11933
11934              With 64bit address space and no base register and $at usable,
11935              we want
11936                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11937                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11938                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11939                dsll32   $tempreg,0
11940                daddu    $tempreg,$at
11941                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11942              If we have a base register, we want
11943                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11944                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11945                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11946                daddu    $at,$breg
11947                dsll32   $tempreg,0
11948                daddu    $tempreg,$at
11949                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11950
11951              Without $at we can't generate the optimal path for superscalar
11952              processors here since this would require two temporary registers.
11953                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11954                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11955                dsll     $tempreg,16
11956                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11957                dsll     $tempreg,16
11958                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11959              If we have a base register, we want
11960                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11961                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11962                dsll     $tempreg,16
11963                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11964                dsll     $tempreg,16
11965                daddu    $tempreg,$tempreg,$breg
11966                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11967
11968              For GP relative symbols in 64bit address space we can use
11969              the same sequence as in 32bit address space.  */
11970           if (HAVE_64BIT_SYMBOLS)
11971             {
11972               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11973                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11974                 {
11975                   relax_start (offset_expr.X_add_symbol);
11976                   if (breg == 0)
11977                     {
11978                       macro_build (&offset_expr, s, fmt, op[0],
11979                                    BFD_RELOC_GPREL16, mips_gp_register);
11980                     }
11981                   else
11982                     {
11983                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11984                                    tempreg, breg, mips_gp_register);
11985                       macro_build (&offset_expr, s, fmt, op[0],
11986                                    BFD_RELOC_GPREL16, tempreg);
11987                     }
11988                   relax_switch ();
11989                 }
11990
11991               if (used_at == 0 && mips_opts.at)
11992                 {
11993                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11994                                BFD_RELOC_MIPS_HIGHEST);
11995                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11996                                BFD_RELOC_HI16_S);
11997                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11998                                tempreg, BFD_RELOC_MIPS_HIGHER);
11999                   if (breg != 0)
12000                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
12001                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
12002                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
12003                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
12004                                tempreg);
12005                   used_at = 1;
12006                 }
12007               else
12008                 {
12009                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12010                                BFD_RELOC_MIPS_HIGHEST);
12011                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12012                                tempreg, BFD_RELOC_MIPS_HIGHER);
12013                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12014                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12015                                tempreg, BFD_RELOC_HI16_S);
12016                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12017                   if (breg != 0)
12018                     macro_build (NULL, "daddu", "d,v,t",
12019                                  tempreg, tempreg, breg);
12020                   macro_build (&offset_expr, s, fmt, op[0],
12021                                BFD_RELOC_LO16, tempreg);
12022                 }
12023
12024               if (mips_relax.sequence)
12025                 relax_end ();
12026               break;
12027             }
12028
12029           if (breg == 0)
12030             {
12031               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12032                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12033                 {
12034                   relax_start (offset_expr.X_add_symbol);
12035                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
12036                                mips_gp_register);
12037                   relax_switch ();
12038                 }
12039               macro_build_lui (&offset_expr, tempreg);
12040               macro_build (&offset_expr, s, fmt, op[0],
12041                            BFD_RELOC_LO16, tempreg);
12042               if (mips_relax.sequence)
12043                 relax_end ();
12044             }
12045           else
12046             {
12047               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12048                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12049                 {
12050                   relax_start (offset_expr.X_add_symbol);
12051                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12052                                tempreg, breg, mips_gp_register);
12053                   macro_build (&offset_expr, s, fmt, op[0],
12054                                BFD_RELOC_GPREL16, tempreg);
12055                   relax_switch ();
12056                 }
12057               macro_build_lui (&offset_expr, tempreg);
12058               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12059                            tempreg, tempreg, breg);
12060               macro_build (&offset_expr, s, fmt, op[0],
12061                            BFD_RELOC_LO16, tempreg);
12062               if (mips_relax.sequence)
12063                 relax_end ();
12064             }
12065         }
12066       else if (!mips_big_got)
12067         {
12068           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
12069
12070           /* If this is a reference to an external symbol, we want
12071                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12072                nop
12073                <op>     op[0],0($tempreg)
12074              Otherwise we want
12075                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12076                nop
12077                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12078                <op>     op[0],0($tempreg)
12079
12080              For NewABI, we want
12081                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12082                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
12083
12084              If there is a base register, we add it to $tempreg before
12085              the <op>.  If there is a constant, we stick it in the
12086              <op> instruction.  We don't handle constants larger than
12087              16 bits, because we have no way to load the upper 16 bits
12088              (actually, we could handle them for the subset of cases
12089              in which we are not using $at).  */
12090           gas_assert (offset_expr.X_op == O_symbol);
12091           if (HAVE_NEWABI)
12092             {
12093               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12094                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12095               if (breg != 0)
12096                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12097                              tempreg, tempreg, breg);
12098               macro_build (&offset_expr, s, fmt, op[0],
12099                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
12100               break;
12101             }
12102           expr1.X_add_number = offset_expr.X_add_number;
12103           offset_expr.X_add_number = 0;
12104           if (expr1.X_add_number < -0x8000
12105               || expr1.X_add_number >= 0x8000)
12106             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12107           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12108                        lw_reloc_type, mips_gp_register);
12109           load_delay_nop ();
12110           relax_start (offset_expr.X_add_symbol);
12111           relax_switch ();
12112           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12113                        tempreg, BFD_RELOC_LO16);
12114           relax_end ();
12115           if (breg != 0)
12116             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12117                          tempreg, tempreg, breg);
12118           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12119         }
12120       else if (mips_big_got && !HAVE_NEWABI)
12121         {
12122           int gpdelay;
12123
12124           /* If this is a reference to an external symbol, we want
12125                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12126                addu     $tempreg,$tempreg,$gp
12127                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12128                <op>     op[0],0($tempreg)
12129              Otherwise we want
12130                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12131                nop
12132                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12133                <op>     op[0],0($tempreg)
12134              If there is a base register, we add it to $tempreg before
12135              the <op>.  If there is a constant, we stick it in the
12136              <op> instruction.  We don't handle constants larger than
12137              16 bits, because we have no way to load the upper 16 bits
12138              (actually, we could handle them for the subset of cases
12139              in which we are not using $at).  */
12140           gas_assert (offset_expr.X_op == O_symbol);
12141           expr1.X_add_number = offset_expr.X_add_number;
12142           offset_expr.X_add_number = 0;
12143           if (expr1.X_add_number < -0x8000
12144               || expr1.X_add_number >= 0x8000)
12145             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12146           gpdelay = reg_needs_delay (mips_gp_register);
12147           relax_start (offset_expr.X_add_symbol);
12148           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12149                        BFD_RELOC_MIPS_GOT_HI16);
12150           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12151                        mips_gp_register);
12152           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12153                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12154           relax_switch ();
12155           if (gpdelay)
12156             macro_build (NULL, "nop", "");
12157           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12158                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12159           load_delay_nop ();
12160           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12161                        tempreg, BFD_RELOC_LO16);
12162           relax_end ();
12163
12164           if (breg != 0)
12165             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12166                          tempreg, tempreg, breg);
12167           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12168         }
12169       else if (mips_big_got && HAVE_NEWABI)
12170         {
12171           /* If this is a reference to an external symbol, we want
12172                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12173                add      $tempreg,$tempreg,$gp
12174                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12175                <op>     op[0],<ofst>($tempreg)
12176              Otherwise, for local symbols, we want:
12177                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12178                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
12179           gas_assert (offset_expr.X_op == O_symbol);
12180           expr1.X_add_number = offset_expr.X_add_number;
12181           offset_expr.X_add_number = 0;
12182           if (expr1.X_add_number < -0x8000
12183               || expr1.X_add_number >= 0x8000)
12184             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12185           relax_start (offset_expr.X_add_symbol);
12186           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12187                        BFD_RELOC_MIPS_GOT_HI16);
12188           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12189                        mips_gp_register);
12190           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12191                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12192           if (breg != 0)
12193             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12194                          tempreg, tempreg, breg);
12195           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12196
12197           relax_switch ();
12198           offset_expr.X_add_number = expr1.X_add_number;
12199           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12200                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12201           if (breg != 0)
12202             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12203                          tempreg, tempreg, breg);
12204           macro_build (&offset_expr, s, fmt, op[0],
12205                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
12206           relax_end ();
12207         }
12208       else
12209         abort ();
12210
12211       break;
12212
12213     case M_JRADDIUSP:
12214       gas_assert (mips_opts.micromips);
12215       gas_assert (mips_opts.insn32);
12216       start_noreorder ();
12217       macro_build (NULL, "jr", "s", RA);
12218       expr1.X_add_number = op[0] << 2;
12219       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
12220       end_noreorder ();
12221       break;
12222
12223     case M_JRC:
12224       gas_assert (mips_opts.micromips);
12225       gas_assert (mips_opts.insn32);
12226       macro_build (NULL, "jr", "s", op[0]);
12227       if (mips_opts.noreorder)
12228         macro_build (NULL, "nop", "");
12229       break;
12230
12231     case M_LI:
12232     case M_LI_S:
12233       load_register (op[0], &imm_expr, 0);
12234       break;
12235
12236     case M_DLI:
12237       load_register (op[0], &imm_expr, 1);
12238       break;
12239
12240     case M_LI_SS:
12241       if (imm_expr.X_op == O_constant)
12242         {
12243           used_at = 1;
12244           load_register (AT, &imm_expr, 0);
12245           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12246           break;
12247         }
12248       else
12249         {
12250           gas_assert (imm_expr.X_op == O_absent
12251                       && offset_expr.X_op == O_symbol
12252                       && strcmp (segment_name (S_GET_SEGMENT
12253                                                (offset_expr.X_add_symbol)),
12254                                  ".lit4") == 0
12255                       && offset_expr.X_add_number == 0);
12256           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
12257                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
12258           break;
12259         }
12260
12261     case M_LI_D:
12262       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
12263          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
12264          order 32 bits of the value and the low order 32 bits are either
12265          zero or in OFFSET_EXPR.  */
12266       if (imm_expr.X_op == O_constant)
12267         {
12268           if (GPR_SIZE == 64)
12269             load_register (op[0], &imm_expr, 1);
12270           else
12271             {
12272               int hreg, lreg;
12273
12274               if (target_big_endian)
12275                 {
12276                   hreg = op[0];
12277                   lreg = op[0] + 1;
12278                 }
12279               else
12280                 {
12281                   hreg = op[0] + 1;
12282                   lreg = op[0];
12283                 }
12284
12285               if (hreg <= 31)
12286                 load_register (hreg, &imm_expr, 0);
12287               if (lreg <= 31)
12288                 {
12289                   if (offset_expr.X_op == O_absent)
12290                     move_register (lreg, 0);
12291                   else
12292                     {
12293                       gas_assert (offset_expr.X_op == O_constant);
12294                       load_register (lreg, &offset_expr, 0);
12295                     }
12296                 }
12297             }
12298           break;
12299         }
12300       gas_assert (imm_expr.X_op == O_absent);
12301
12302       /* We know that sym is in the .rdata section.  First we get the
12303          upper 16 bits of the address.  */
12304       if (mips_pic == NO_PIC)
12305         {
12306           macro_build_lui (&offset_expr, AT);
12307           used_at = 1;
12308         }
12309       else
12310         {
12311           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12312                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12313           used_at = 1;
12314         }
12315
12316       /* Now we load the register(s).  */
12317       if (GPR_SIZE == 64)
12318         {
12319           used_at = 1;
12320           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
12321                        BFD_RELOC_LO16, AT);
12322         }
12323       else
12324         {
12325           used_at = 1;
12326           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
12327                        BFD_RELOC_LO16, AT);
12328           if (op[0] != RA)
12329             {
12330               /* FIXME: How in the world do we deal with the possible
12331                  overflow here?  */
12332               offset_expr.X_add_number += 4;
12333               macro_build (&offset_expr, "lw", "t,o(b)",
12334                            op[0] + 1, BFD_RELOC_LO16, AT);
12335             }
12336         }
12337       break;
12338
12339     case M_LI_DD:
12340       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
12341          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
12342          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
12343          the value and the low order 32 bits are either zero or in
12344          OFFSET_EXPR.  */
12345       if (imm_expr.X_op == O_constant)
12346         {
12347           used_at = 1;
12348           load_register (AT, &imm_expr, FPR_SIZE == 64);
12349           if (FPR_SIZE == 64 && GPR_SIZE == 64)
12350             macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
12351           else
12352             {
12353               if (ISA_HAS_MXHC1 (mips_opts.isa))
12354                 macro_build (NULL, "mthc1", "t,G", AT, op[0]);
12355               else if (FPR_SIZE != 32)
12356                 as_bad (_("Unable to generate `%s' compliant code "
12357                           "without mthc1"),
12358                         (FPR_SIZE == 64) ? "fp64" : "fpxx");
12359               else
12360                 macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
12361               if (offset_expr.X_op == O_absent)
12362                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
12363               else
12364                 {
12365                   gas_assert (offset_expr.X_op == O_constant);
12366                   load_register (AT, &offset_expr, 0);
12367                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12368                 }
12369             }
12370           break;
12371         }
12372
12373       gas_assert (imm_expr.X_op == O_absent
12374                   && offset_expr.X_op == O_symbol
12375                   && offset_expr.X_add_number == 0);
12376       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
12377       if (strcmp (s, ".lit8") == 0)
12378         {
12379           op[2] = mips_gp_register;
12380           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
12381           offset_reloc[1] = BFD_RELOC_UNUSED;
12382           offset_reloc[2] = BFD_RELOC_UNUSED;
12383         }
12384       else
12385         {
12386           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
12387           used_at = 1;
12388           if (mips_pic != NO_PIC)
12389             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12390                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
12391           else
12392             {
12393               /* FIXME: This won't work for a 64 bit address.  */
12394               macro_build_lui (&offset_expr, AT);
12395             }
12396
12397           op[2] = AT;
12398           offset_reloc[0] = BFD_RELOC_LO16;
12399           offset_reloc[1] = BFD_RELOC_UNUSED;
12400           offset_reloc[2] = BFD_RELOC_UNUSED;
12401         }
12402       align = 8;
12403       /* Fall through */
12404
12405     case M_L_DAB:
12406       /*
12407        * The MIPS assembler seems to check for X_add_number not
12408        * being double aligned and generating:
12409        *        lui     at,%hi(foo+1)
12410        *        addu    at,at,v1
12411        *        addiu   at,at,%lo(foo+1)
12412        *        lwc1    f2,0(at)
12413        *        lwc1    f3,4(at)
12414        * But, the resulting address is the same after relocation so why
12415        * generate the extra instruction?
12416        */
12417       /* Itbl support may require additional care here.  */
12418       coproc = 1;
12419       fmt = "T,o(b)";
12420       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12421         {
12422           s = "ldc1";
12423           goto ld_st;
12424         }
12425       s = "lwc1";
12426       goto ldd_std;
12427
12428     case M_S_DAB:
12429       gas_assert (!mips_opts.micromips);
12430       /* Itbl support may require additional care here.  */
12431       coproc = 1;
12432       fmt = "T,o(b)";
12433       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12434         {
12435           s = "sdc1";
12436           goto ld_st;
12437         }
12438       s = "swc1";
12439       goto ldd_std;
12440
12441     case M_LQ_AB:
12442       fmt = "t,o(b)";
12443       s = "lq";
12444       goto ld;
12445
12446     case M_SQ_AB:
12447       fmt = "t,o(b)";
12448       s = "sq";
12449       goto ld_st;
12450
12451     case M_LD_AB:
12452       fmt = "t,o(b)";
12453       if (GPR_SIZE == 64)
12454         {
12455           s = "ld";
12456           goto ld;
12457         }
12458       s = "lw";
12459       goto ldd_std;
12460
12461     case M_SD_AB:
12462       fmt = "t,o(b)";
12463       if (GPR_SIZE == 64)
12464         {
12465           s = "sd";
12466           goto ld_st;
12467         }
12468       s = "sw";
12469
12470     ldd_std:
12471       /* Even on a big endian machine $fn comes before $fn+1.  We have
12472          to adjust when loading from memory.  We set coproc if we must
12473          load $fn+1 first.  */
12474       /* Itbl support may require additional care here.  */
12475       if (!target_big_endian)
12476         coproc = 0;
12477
12478       breg = op[2];
12479       if (small_offset_p (0, align, 16))
12480         {
12481           ep = &offset_expr;
12482           if (!small_offset_p (4, align, 16))
12483             {
12484               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
12485                            -1, offset_reloc[0], offset_reloc[1],
12486                            offset_reloc[2]);
12487               expr1.X_add_number = 0;
12488               ep = &expr1;
12489               breg = AT;
12490               used_at = 1;
12491               offset_reloc[0] = BFD_RELOC_LO16;
12492               offset_reloc[1] = BFD_RELOC_UNUSED;
12493               offset_reloc[2] = BFD_RELOC_UNUSED;
12494             }
12495           if (strcmp (s, "lw") == 0 && op[0] == breg)
12496             {
12497               ep->X_add_number += 4;
12498               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
12499                            offset_reloc[1], offset_reloc[2], breg);
12500               ep->X_add_number -= 4;
12501               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
12502                            offset_reloc[1], offset_reloc[2], breg);
12503             }
12504           else
12505             {
12506               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
12507                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12508                            breg);
12509               ep->X_add_number += 4;
12510               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
12511                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12512                            breg);
12513             }
12514           break;
12515         }
12516
12517       if (offset_expr.X_op != O_symbol
12518           && offset_expr.X_op != O_constant)
12519         {
12520           as_bad (_("expression too complex"));
12521           offset_expr.X_op = O_constant;
12522         }
12523
12524       if (HAVE_32BIT_ADDRESSES
12525           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12526         {
12527           char value [32];
12528
12529           sprintf_vma (value, offset_expr.X_add_number);
12530           as_bad (_("number (0x%s) larger than 32 bits"), value);
12531         }
12532
12533       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
12534         {
12535           /* If this is a reference to a GP relative symbol, we want
12536                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12537                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
12538              If we have a base register, we use this
12539                addu     $at,$breg,$gp
12540                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
12541                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
12542              If this is not a GP relative symbol, we want
12543                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12544                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12545                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12546              If there is a base register, we add it to $at after the
12547              lui instruction.  If there is a constant, we always use
12548              the last case.  */
12549           if (offset_expr.X_op == O_symbol
12550               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12551               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12552             {
12553               relax_start (offset_expr.X_add_symbol);
12554               if (breg == 0)
12555                 {
12556                   tempreg = mips_gp_register;
12557                 }
12558               else
12559                 {
12560                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12561                                AT, breg, mips_gp_register);
12562                   tempreg = AT;
12563                   used_at = 1;
12564                 }
12565
12566               /* Itbl support may require additional care here.  */
12567               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12568                            BFD_RELOC_GPREL16, tempreg);
12569               offset_expr.X_add_number += 4;
12570
12571               /* Set mips_optimize to 2 to avoid inserting an
12572                  undesired nop.  */
12573               hold_mips_optimize = mips_optimize;
12574               mips_optimize = 2;
12575               /* Itbl support may require additional care here.  */
12576               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12577                            BFD_RELOC_GPREL16, tempreg);
12578               mips_optimize = hold_mips_optimize;
12579
12580               relax_switch ();
12581
12582               offset_expr.X_add_number -= 4;
12583             }
12584           used_at = 1;
12585           if (offset_high_part (offset_expr.X_add_number, 16)
12586               != offset_high_part (offset_expr.X_add_number + 4, 16))
12587             {
12588               load_address (AT, &offset_expr, &used_at);
12589               offset_expr.X_op = O_constant;
12590               offset_expr.X_add_number = 0;
12591             }
12592           else
12593             macro_build_lui (&offset_expr, AT);
12594           if (breg != 0)
12595             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12596           /* Itbl support may require additional care here.  */
12597           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12598                        BFD_RELOC_LO16, AT);
12599           /* FIXME: How do we handle overflow here?  */
12600           offset_expr.X_add_number += 4;
12601           /* Itbl support may require additional care here.  */
12602           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12603                        BFD_RELOC_LO16, AT);
12604           if (mips_relax.sequence)
12605             relax_end ();
12606         }
12607       else if (!mips_big_got)
12608         {
12609           /* If this is a reference to an external symbol, we want
12610                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12611                nop
12612                <op>     op[0],0($at)
12613                <op>     op[0]+1,4($at)
12614              Otherwise we want
12615                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12616                nop
12617                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12618                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12619              If there is a base register we add it to $at before the
12620              lwc1 instructions.  If there is a constant we include it
12621              in the lwc1 instructions.  */
12622           used_at = 1;
12623           expr1.X_add_number = offset_expr.X_add_number;
12624           if (expr1.X_add_number < -0x8000
12625               || expr1.X_add_number >= 0x8000 - 4)
12626             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12627           load_got_offset (AT, &offset_expr);
12628           load_delay_nop ();
12629           if (breg != 0)
12630             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12631
12632           /* Set mips_optimize to 2 to avoid inserting an undesired
12633              nop.  */
12634           hold_mips_optimize = mips_optimize;
12635           mips_optimize = 2;
12636
12637           /* Itbl support may require additional care here.  */
12638           relax_start (offset_expr.X_add_symbol);
12639           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12640                        BFD_RELOC_LO16, AT);
12641           expr1.X_add_number += 4;
12642           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12643                        BFD_RELOC_LO16, AT);
12644           relax_switch ();
12645           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12646                        BFD_RELOC_LO16, AT);
12647           offset_expr.X_add_number += 4;
12648           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12649                        BFD_RELOC_LO16, AT);
12650           relax_end ();
12651
12652           mips_optimize = hold_mips_optimize;
12653         }
12654       else if (mips_big_got)
12655         {
12656           int gpdelay;
12657
12658           /* If this is a reference to an external symbol, we want
12659                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
12660                addu     $at,$at,$gp
12661                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
12662                nop
12663                <op>     op[0],0($at)
12664                <op>     op[0]+1,4($at)
12665              Otherwise we want
12666                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12667                nop
12668                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12669                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12670              If there is a base register we add it to $at before the
12671              lwc1 instructions.  If there is a constant we include it
12672              in the lwc1 instructions.  */
12673           used_at = 1;
12674           expr1.X_add_number = offset_expr.X_add_number;
12675           offset_expr.X_add_number = 0;
12676           if (expr1.X_add_number < -0x8000
12677               || expr1.X_add_number >= 0x8000 - 4)
12678             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12679           gpdelay = reg_needs_delay (mips_gp_register);
12680           relax_start (offset_expr.X_add_symbol);
12681           macro_build (&offset_expr, "lui", LUI_FMT,
12682                        AT, BFD_RELOC_MIPS_GOT_HI16);
12683           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12684                        AT, AT, mips_gp_register);
12685           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
12686                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
12687           load_delay_nop ();
12688           if (breg != 0)
12689             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12690           /* Itbl support may require additional care here.  */
12691           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12692                        BFD_RELOC_LO16, AT);
12693           expr1.X_add_number += 4;
12694
12695           /* Set mips_optimize to 2 to avoid inserting an undesired
12696              nop.  */
12697           hold_mips_optimize = mips_optimize;
12698           mips_optimize = 2;
12699           /* Itbl support may require additional care here.  */
12700           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12701                        BFD_RELOC_LO16, AT);
12702           mips_optimize = hold_mips_optimize;
12703           expr1.X_add_number -= 4;
12704
12705           relax_switch ();
12706           offset_expr.X_add_number = expr1.X_add_number;
12707           if (gpdelay)
12708             macro_build (NULL, "nop", "");
12709           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12710                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12711           load_delay_nop ();
12712           if (breg != 0)
12713             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12714           /* Itbl support may require additional care here.  */
12715           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12716                        BFD_RELOC_LO16, AT);
12717           offset_expr.X_add_number += 4;
12718
12719           /* Set mips_optimize to 2 to avoid inserting an undesired
12720              nop.  */
12721           hold_mips_optimize = mips_optimize;
12722           mips_optimize = 2;
12723           /* Itbl support may require additional care here.  */
12724           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12725                        BFD_RELOC_LO16, AT);
12726           mips_optimize = hold_mips_optimize;
12727           relax_end ();
12728         }
12729       else
12730         abort ();
12731
12732       break;
12733
12734     case M_SAA_AB:
12735       s = "saa";
12736       goto saa_saad;
12737     case M_SAAD_AB:
12738       s = "saad";
12739     saa_saad:
12740       gas_assert (!mips_opts.micromips);
12741       offbits = 0;
12742       fmt = "t,(b)";
12743       goto ld_st;
12744
12745    /* New code added to support COPZ instructions.
12746       This code builds table entries out of the macros in mip_opcodes.
12747       R4000 uses interlocks to handle coproc delays.
12748       Other chips (like the R3000) require nops to be inserted for delays.
12749
12750       FIXME: Currently, we require that the user handle delays.
12751       In order to fill delay slots for non-interlocked chips,
12752       we must have a way to specify delays based on the coprocessor.
12753       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
12754       What are the side-effects of the cop instruction?
12755       What cache support might we have and what are its effects?
12756       Both coprocessor & memory require delays. how long???
12757       What registers are read/set/modified?
12758
12759       If an itbl is provided to interpret cop instructions,
12760       this knowledge can be encoded in the itbl spec.  */
12761
12762     case M_COP0:
12763       s = "c0";
12764       goto copz;
12765     case M_COP1:
12766       s = "c1";
12767       goto copz;
12768     case M_COP2:
12769       s = "c2";
12770       goto copz;
12771     case M_COP3:
12772       s = "c3";
12773     copz:
12774       gas_assert (!mips_opts.micromips);
12775       /* For now we just do C (same as Cz).  The parameter will be
12776          stored in insn_opcode by mips_ip.  */
12777       macro_build (NULL, s, "C", (int) ip->insn_opcode);
12778       break;
12779
12780     case M_MOVE:
12781       move_register (op[0], op[1]);
12782       break;
12783
12784     case M_MOVEP:
12785       gas_assert (mips_opts.micromips);
12786       gas_assert (mips_opts.insn32);
12787       move_register (micromips_to_32_reg_h_map1[op[0]],
12788                      micromips_to_32_reg_m_map[op[1]]);
12789       move_register (micromips_to_32_reg_h_map2[op[0]],
12790                      micromips_to_32_reg_n_map[op[2]]);
12791       break;
12792
12793     case M_DMUL:
12794       dbl = 1;
12795       /* Fall through.  */
12796     case M_MUL:
12797       if (mips_opts.arch == CPU_R5900)
12798         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
12799                      op[2]);
12800       else
12801         {
12802           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
12803           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12804         }
12805       break;
12806
12807     case M_DMUL_I:
12808       dbl = 1;
12809       /* Fall through.  */
12810     case M_MUL_I:
12811       /* The MIPS assembler some times generates shifts and adds.  I'm
12812          not trying to be that fancy. GCC should do this for us
12813          anyway.  */
12814       used_at = 1;
12815       load_register (AT, &imm_expr, dbl);
12816       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
12817       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12818       break;
12819
12820     case M_DMULO_I:
12821       dbl = 1;
12822       /* Fall through.  */
12823     case M_MULO_I:
12824       imm = 1;
12825       goto do_mulo;
12826
12827     case M_DMULO:
12828       dbl = 1;
12829       /* Fall through.  */
12830     case M_MULO:
12831     do_mulo:
12832       start_noreorder ();
12833       used_at = 1;
12834       if (imm)
12835         load_register (AT, &imm_expr, dbl);
12836       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
12837                    op[1], imm ? AT : op[2]);
12838       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12839       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12840       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12841       if (mips_trap)
12842         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12843       else
12844         {
12845           if (mips_opts.micromips)
12846             micromips_label_expr (&label_expr);
12847           else
12848             label_expr.X_add_number = 8;
12849           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12850           macro_build (NULL, "nop", "");
12851           macro_build (NULL, "break", BRK_FMT, 6);
12852           if (mips_opts.micromips)
12853             micromips_add_label ();
12854         }
12855       end_noreorder ();
12856       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12857       break;
12858
12859     case M_DMULOU_I:
12860       dbl = 1;
12861       /* Fall through.  */
12862     case M_MULOU_I:
12863       imm = 1;
12864       goto do_mulou;
12865
12866     case M_DMULOU:
12867       dbl = 1;
12868       /* Fall through.  */
12869     case M_MULOU:
12870     do_mulou:
12871       start_noreorder ();
12872       used_at = 1;
12873       if (imm)
12874         load_register (AT, &imm_expr, dbl);
12875       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12876                    op[1], imm ? AT : op[2]);
12877       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12878       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12879       if (mips_trap)
12880         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12881       else
12882         {
12883           if (mips_opts.micromips)
12884             micromips_label_expr (&label_expr);
12885           else
12886             label_expr.X_add_number = 8;
12887           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12888           macro_build (NULL, "nop", "");
12889           macro_build (NULL, "break", BRK_FMT, 6);
12890           if (mips_opts.micromips)
12891             micromips_add_label ();
12892         }
12893       end_noreorder ();
12894       break;
12895
12896     case M_DROL:
12897       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12898         {
12899           if (op[0] == op[1])
12900             {
12901               tempreg = AT;
12902               used_at = 1;
12903             }
12904           else
12905             tempreg = op[0];
12906           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12907           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12908           break;
12909         }
12910       used_at = 1;
12911       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12912       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12913       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12914       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12915       break;
12916
12917     case M_ROL:
12918       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12919         {
12920           if (op[0] == op[1])
12921             {
12922               tempreg = AT;
12923               used_at = 1;
12924             }
12925           else
12926             tempreg = op[0];
12927           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12928           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12929           break;
12930         }
12931       used_at = 1;
12932       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12933       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12934       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12935       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12936       break;
12937
12938     case M_DROL_I:
12939       {
12940         unsigned int rot;
12941         const char *l;
12942         const char *rr;
12943
12944         rot = imm_expr.X_add_number & 0x3f;
12945         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12946           {
12947             rot = (64 - rot) & 0x3f;
12948             if (rot >= 32)
12949               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12950             else
12951               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12952             break;
12953           }
12954         if (rot == 0)
12955           {
12956             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12957             break;
12958           }
12959         l = (rot < 0x20) ? "dsll" : "dsll32";
12960         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12961         rot &= 0x1f;
12962         used_at = 1;
12963         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12964         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12965         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12966       }
12967       break;
12968
12969     case M_ROL_I:
12970       {
12971         unsigned int rot;
12972
12973         rot = imm_expr.X_add_number & 0x1f;
12974         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12975           {
12976             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12977                          (32 - rot) & 0x1f);
12978             break;
12979           }
12980         if (rot == 0)
12981           {
12982             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12983             break;
12984           }
12985         used_at = 1;
12986         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12987         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12988         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12989       }
12990       break;
12991
12992     case M_DROR:
12993       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12994         {
12995           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12996           break;
12997         }
12998       used_at = 1;
12999       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13000       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
13001       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
13002       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13003       break;
13004
13005     case M_ROR:
13006       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13007         {
13008           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
13009           break;
13010         }
13011       used_at = 1;
13012       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13013       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
13014       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
13015       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13016       break;
13017
13018     case M_DROR_I:
13019       {
13020         unsigned int rot;
13021         const char *l;
13022         const char *rr;
13023
13024         rot = imm_expr.X_add_number & 0x3f;
13025         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13026           {
13027             if (rot >= 32)
13028               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13029             else
13030               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13031             break;
13032           }
13033         if (rot == 0)
13034           {
13035             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13036             break;
13037           }
13038         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
13039         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
13040         rot &= 0x1f;
13041         used_at = 1;
13042         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
13043         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13044         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13045       }
13046       break;
13047
13048     case M_ROR_I:
13049       {
13050         unsigned int rot;
13051
13052         rot = imm_expr.X_add_number & 0x1f;
13053         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13054           {
13055             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
13056             break;
13057           }
13058         if (rot == 0)
13059           {
13060             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13061             break;
13062           }
13063         used_at = 1;
13064         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
13065         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13066         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13067       }
13068       break;
13069
13070     case M_SEQ:
13071       if (op[1] == 0)
13072         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
13073       else if (op[2] == 0)
13074         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13075       else
13076         {
13077           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13078           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13079         }
13080       break;
13081
13082     case M_SEQ_I:
13083       if (imm_expr.X_add_number == 0)
13084         {
13085           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13086           break;
13087         }
13088       if (op[1] == 0)
13089         {
13090           as_warn (_("instruction %s: result is always false"),
13091                    ip->insn_mo->name);
13092           move_register (op[0], 0);
13093           break;
13094         }
13095       if (CPU_HAS_SEQ (mips_opts.arch)
13096           && -512 <= imm_expr.X_add_number
13097           && imm_expr.X_add_number < 512)
13098         {
13099           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
13100                        (int) imm_expr.X_add_number);
13101           break;
13102         }
13103       if (imm_expr.X_add_number >= 0
13104           && imm_expr.X_add_number < 0x10000)
13105         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
13106       else if (imm_expr.X_add_number > -0x8000
13107                && imm_expr.X_add_number < 0)
13108         {
13109           imm_expr.X_add_number = -imm_expr.X_add_number;
13110           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13111                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13112         }
13113       else if (CPU_HAS_SEQ (mips_opts.arch))
13114         {
13115           used_at = 1;
13116           load_register (AT, &imm_expr, GPR_SIZE == 64);
13117           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
13118           break;
13119         }
13120       else
13121         {
13122           load_register (AT, &imm_expr, GPR_SIZE == 64);
13123           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13124           used_at = 1;
13125         }
13126       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13127       break;
13128
13129     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
13130       s = "slt";
13131       goto sge;
13132     case M_SGEU:
13133       s = "sltu";
13134     sge:
13135       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
13136       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13137       break;
13138
13139     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
13140     case M_SGEU_I:
13141       if (imm_expr.X_add_number >= -0x8000
13142           && imm_expr.X_add_number < 0x8000)
13143         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
13144                      op[0], op[1], BFD_RELOC_LO16);
13145       else
13146         {
13147           load_register (AT, &imm_expr, GPR_SIZE == 64);
13148           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
13149                        op[0], op[1], AT);
13150           used_at = 1;
13151         }
13152       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13153       break;
13154
13155     case M_SGT:         /* X > Y  <==>  Y < X */
13156       s = "slt";
13157       goto sgt;
13158     case M_SGTU:
13159       s = "sltu";
13160     sgt:
13161       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13162       break;
13163
13164     case M_SGT_I:       /* X > I  <==>  I < X */
13165       s = "slt";
13166       goto sgti;
13167     case M_SGTU_I:
13168       s = "sltu";
13169     sgti:
13170       used_at = 1;
13171       load_register (AT, &imm_expr, GPR_SIZE == 64);
13172       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13173       break;
13174
13175     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
13176       s = "slt";
13177       goto sle;
13178     case M_SLEU:
13179       s = "sltu";
13180     sle:
13181       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13182       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13183       break;
13184
13185     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
13186       s = "slt";
13187       goto slei;
13188     case M_SLEU_I:
13189       s = "sltu";
13190     slei:
13191       used_at = 1;
13192       load_register (AT, &imm_expr, GPR_SIZE == 64);
13193       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13194       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13195       break;
13196
13197     case M_SLT_I:
13198       if (imm_expr.X_add_number >= -0x8000
13199           && imm_expr.X_add_number < 0x8000)
13200         {
13201           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
13202                        BFD_RELOC_LO16);
13203           break;
13204         }
13205       used_at = 1;
13206       load_register (AT, &imm_expr, GPR_SIZE == 64);
13207       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
13208       break;
13209
13210     case M_SLTU_I:
13211       if (imm_expr.X_add_number >= -0x8000
13212           && imm_expr.X_add_number < 0x8000)
13213         {
13214           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
13215                        BFD_RELOC_LO16);
13216           break;
13217         }
13218       used_at = 1;
13219       load_register (AT, &imm_expr, GPR_SIZE == 64);
13220       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
13221       break;
13222
13223     case M_SNE:
13224       if (op[1] == 0)
13225         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
13226       else if (op[2] == 0)
13227         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13228       else
13229         {
13230           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13231           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13232         }
13233       break;
13234
13235     case M_SNE_I:
13236       if (imm_expr.X_add_number == 0)
13237         {
13238           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13239           break;
13240         }
13241       if (op[1] == 0)
13242         {
13243           as_warn (_("instruction %s: result is always true"),
13244                    ip->insn_mo->name);
13245           macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
13246                        op[0], 0, BFD_RELOC_LO16);
13247           break;
13248         }
13249       if (CPU_HAS_SEQ (mips_opts.arch)
13250           && -512 <= imm_expr.X_add_number
13251           && imm_expr.X_add_number < 512)
13252         {
13253           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
13254                        (int) imm_expr.X_add_number);
13255           break;
13256         }
13257       if (imm_expr.X_add_number >= 0
13258           && imm_expr.X_add_number < 0x10000)
13259         {
13260           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
13261                        BFD_RELOC_LO16);
13262         }
13263       else if (imm_expr.X_add_number > -0x8000
13264                && imm_expr.X_add_number < 0)
13265         {
13266           imm_expr.X_add_number = -imm_expr.X_add_number;
13267           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13268                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13269         }
13270       else if (CPU_HAS_SEQ (mips_opts.arch))
13271         {
13272           used_at = 1;
13273           load_register (AT, &imm_expr, GPR_SIZE == 64);
13274           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
13275           break;
13276         }
13277       else
13278         {
13279           load_register (AT, &imm_expr, GPR_SIZE == 64);
13280           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13281           used_at = 1;
13282         }
13283       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13284       break;
13285
13286     case M_SUB_I:
13287       s = "addi";
13288       s2 = "sub";
13289       goto do_subi;
13290     case M_SUBU_I:
13291       s = "addiu";
13292       s2 = "subu";
13293       goto do_subi;
13294     case M_DSUB_I:
13295       dbl = 1;
13296       s = "daddi";
13297       s2 = "dsub";
13298       if (!mips_opts.micromips)
13299         goto do_subi;
13300       if (imm_expr.X_add_number > -0x200
13301           && imm_expr.X_add_number <= 0x200)
13302         {
13303           macro_build (NULL, s, "t,r,.", op[0], op[1],
13304                        (int) -imm_expr.X_add_number);
13305           break;
13306         }
13307       goto do_subi_i;
13308     case M_DSUBU_I:
13309       dbl = 1;
13310       s = "daddiu";
13311       s2 = "dsubu";
13312     do_subi:
13313       if (imm_expr.X_add_number > -0x8000
13314           && imm_expr.X_add_number <= 0x8000)
13315         {
13316           imm_expr.X_add_number = -imm_expr.X_add_number;
13317           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13318           break;
13319         }
13320     do_subi_i:
13321       used_at = 1;
13322       load_register (AT, &imm_expr, dbl);
13323       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
13324       break;
13325
13326     case M_TEQ_I:
13327       s = "teq";
13328       goto trap;
13329     case M_TGE_I:
13330       s = "tge";
13331       goto trap;
13332     case M_TGEU_I:
13333       s = "tgeu";
13334       goto trap;
13335     case M_TLT_I:
13336       s = "tlt";
13337       goto trap;
13338     case M_TLTU_I:
13339       s = "tltu";
13340       goto trap;
13341     case M_TNE_I:
13342       s = "tne";
13343     trap:
13344       used_at = 1;
13345       load_register (AT, &imm_expr, GPR_SIZE == 64);
13346       macro_build (NULL, s, "s,t", op[0], AT);
13347       break;
13348
13349     case M_TRUNCWS:
13350     case M_TRUNCWD:
13351       gas_assert (!mips_opts.micromips);
13352       gas_assert (mips_opts.isa == ISA_MIPS1);
13353       used_at = 1;
13354
13355       /*
13356        * Is the double cfc1 instruction a bug in the mips assembler;
13357        * or is there a reason for it?
13358        */
13359       start_noreorder ();
13360       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13361       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13362       macro_build (NULL, "nop", "");
13363       expr1.X_add_number = 3;
13364       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
13365       expr1.X_add_number = 2;
13366       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
13367       macro_build (NULL, "ctc1", "t,G", AT, RA);
13368       macro_build (NULL, "nop", "");
13369       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
13370                    op[0], op[1]);
13371       macro_build (NULL, "ctc1", "t,G", op[2], RA);
13372       macro_build (NULL, "nop", "");
13373       end_noreorder ();
13374       break;
13375
13376     case M_ULH_AB:
13377       s = "lb";
13378       s2 = "lbu";
13379       off = 1;
13380       goto uld_st;
13381     case M_ULHU_AB:
13382       s = "lbu";
13383       s2 = "lbu";
13384       off = 1;
13385       goto uld_st;
13386     case M_ULW_AB:
13387       s = "lwl";
13388       s2 = "lwr";
13389       offbits = (mips_opts.micromips ? 12 : 16);
13390       off = 3;
13391       goto uld_st;
13392     case M_ULD_AB:
13393       s = "ldl";
13394       s2 = "ldr";
13395       offbits = (mips_opts.micromips ? 12 : 16);
13396       off = 7;
13397       goto uld_st;
13398     case M_USH_AB:
13399       s = "sb";
13400       s2 = "sb";
13401       off = 1;
13402       ust = 1;
13403       goto uld_st;
13404     case M_USW_AB:
13405       s = "swl";
13406       s2 = "swr";
13407       offbits = (mips_opts.micromips ? 12 : 16);
13408       off = 3;
13409       ust = 1;
13410       goto uld_st;
13411     case M_USD_AB:
13412       s = "sdl";
13413       s2 = "sdr";
13414       offbits = (mips_opts.micromips ? 12 : 16);
13415       off = 7;
13416       ust = 1;
13417
13418     uld_st:
13419       breg = op[2];
13420       large_offset = !small_offset_p (off, align, offbits);
13421       ep = &offset_expr;
13422       expr1.X_add_number = 0;
13423       if (large_offset)
13424         {
13425           used_at = 1;
13426           tempreg = AT;
13427           if (small_offset_p (0, align, 16))
13428             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
13429                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
13430           else
13431             {
13432               load_address (tempreg, ep, &used_at);
13433               if (breg != 0)
13434                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
13435                              tempreg, tempreg, breg);
13436             }
13437           offset_reloc[0] = BFD_RELOC_LO16;
13438           offset_reloc[1] = BFD_RELOC_UNUSED;
13439           offset_reloc[2] = BFD_RELOC_UNUSED;
13440           breg = tempreg;
13441           tempreg = op[0];
13442           ep = &expr1;
13443         }
13444       else if (!ust && op[0] == breg)
13445         {
13446           used_at = 1;
13447           tempreg = AT;
13448         }
13449       else
13450         tempreg = op[0];
13451
13452       if (off == 1)
13453         goto ulh_sh;
13454
13455       if (!target_big_endian)
13456         ep->X_add_number += off;
13457       if (offbits == 12)
13458         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
13459       else
13460         macro_build (ep, s, "t,o(b)", tempreg, -1,
13461                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13462
13463       if (!target_big_endian)
13464         ep->X_add_number -= off;
13465       else
13466         ep->X_add_number += off;
13467       if (offbits == 12)
13468         macro_build (NULL, s2, "t,~(b)",
13469                      tempreg, (int) ep->X_add_number, breg);
13470       else
13471         macro_build (ep, s2, "t,o(b)", tempreg, -1,
13472                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13473
13474       /* If necessary, move the result in tempreg to the final destination.  */
13475       if (!ust && op[0] != tempreg)
13476         {
13477           /* Protect second load's delay slot.  */
13478           load_delay_nop ();
13479           move_register (op[0], tempreg);
13480         }
13481       break;
13482
13483     ulh_sh:
13484       used_at = 1;
13485       if (target_big_endian == ust)
13486         ep->X_add_number += off;
13487       tempreg = ust || large_offset ? op[0] : AT;
13488       macro_build (ep, s, "t,o(b)", tempreg, -1,
13489                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13490
13491       /* For halfword transfers we need a temporary register to shuffle
13492          bytes.  Unfortunately for M_USH_A we have none available before
13493          the next store as AT holds the base address.  We deal with this
13494          case by clobbering TREG and then restoring it as with ULH.  */
13495       tempreg = ust == large_offset ? op[0] : AT;
13496       if (ust)
13497         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
13498
13499       if (target_big_endian == ust)
13500         ep->X_add_number -= off;
13501       else
13502         ep->X_add_number += off;
13503       macro_build (ep, s2, "t,o(b)", tempreg, -1,
13504                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13505
13506       /* For M_USH_A re-retrieve the LSB.  */
13507       if (ust && large_offset)
13508         {
13509           if (target_big_endian)
13510             ep->X_add_number += off;
13511           else
13512             ep->X_add_number -= off;
13513           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
13514                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
13515         }
13516       /* For ULH and M_USH_A OR the LSB in.  */
13517       if (!ust || large_offset)
13518         {
13519           tempreg = !large_offset ? AT : op[0];
13520           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
13521           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13522         }
13523       break;
13524
13525     default:
13526       /* FIXME: Check if this is one of the itbl macros, since they
13527          are added dynamically.  */
13528       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
13529       break;
13530     }
13531   if (!mips_opts.at && used_at)
13532     as_bad (_("macro used $at after \".set noat\""));
13533 }
13534
13535 /* Implement macros in mips16 mode.  */
13536
13537 static void
13538 mips16_macro (struct mips_cl_insn *ip)
13539 {
13540   const struct mips_operand_array *operands;
13541   int mask;
13542   int tmp;
13543   expressionS expr1;
13544   int dbl;
13545   const char *s, *s2, *s3;
13546   unsigned int op[MAX_OPERANDS];
13547   unsigned int i;
13548
13549   mask = ip->insn_mo->mask;
13550
13551   operands = insn_operands (ip);
13552   for (i = 0; i < MAX_OPERANDS; i++)
13553     if (operands->operand[i])
13554       op[i] = insn_extract_operand (ip, operands->operand[i]);
13555     else
13556       op[i] = -1;
13557
13558   expr1.X_op = O_constant;
13559   expr1.X_op_symbol = NULL;
13560   expr1.X_add_symbol = NULL;
13561   expr1.X_add_number = 1;
13562
13563   dbl = 0;
13564
13565   switch (mask)
13566     {
13567     default:
13568       abort ();
13569
13570     case M_DDIV_3:
13571       dbl = 1;
13572       /* Fall through.  */
13573     case M_DIV_3:
13574       s = "mflo";
13575       goto do_div3;
13576     case M_DREM_3:
13577       dbl = 1;
13578       /* Fall through.  */
13579     case M_REM_3:
13580       s = "mfhi";
13581     do_div3:
13582       start_noreorder ();
13583       macro_build (NULL, dbl ? "ddiv" : "div", ".,x,y", op[1], op[2]);
13584       expr1.X_add_number = 2;
13585       macro_build (&expr1, "bnez", "x,p", op[2]);
13586       macro_build (NULL, "break", "6", 7);
13587
13588       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
13589          since that causes an overflow.  We should do that as well,
13590          but I don't see how to do the comparisons without a temporary
13591          register.  */
13592       end_noreorder ();
13593       macro_build (NULL, s, "x", op[0]);
13594       break;
13595
13596     case M_DIVU_3:
13597       s = "divu";
13598       s2 = "mflo";
13599       goto do_divu3;
13600     case M_REMU_3:
13601       s = "divu";
13602       s2 = "mfhi";
13603       goto do_divu3;
13604     case M_DDIVU_3:
13605       s = "ddivu";
13606       s2 = "mflo";
13607       goto do_divu3;
13608     case M_DREMU_3:
13609       s = "ddivu";
13610       s2 = "mfhi";
13611     do_divu3:
13612       start_noreorder ();
13613       macro_build (NULL, s, ".,x,y", op[1], op[2]);
13614       expr1.X_add_number = 2;
13615       macro_build (&expr1, "bnez", "x,p", op[2]);
13616       macro_build (NULL, "break", "6", 7);
13617       end_noreorder ();
13618       macro_build (NULL, s2, "x", op[0]);
13619       break;
13620
13621     case M_DMUL:
13622       dbl = 1;
13623       /* Fall through.  */
13624     case M_MUL:
13625       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
13626       macro_build (NULL, "mflo", "x", op[0]);
13627       break;
13628
13629     case M_DSUBU_I:
13630       dbl = 1;
13631       goto do_subu;
13632     case M_SUBU_I:
13633     do_subu:
13634       imm_expr.X_add_number = -imm_expr.X_add_number;
13635       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,F", op[0], op[1]);
13636       break;
13637
13638     case M_SUBU_I_2:
13639       imm_expr.X_add_number = -imm_expr.X_add_number;
13640       macro_build (&imm_expr, "addiu", "x,k", op[0]);
13641       break;
13642
13643     case M_DSUBU_I_2:
13644       imm_expr.X_add_number = -imm_expr.X_add_number;
13645       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
13646       break;
13647
13648     case M_BEQ:
13649       s = "cmp";
13650       s2 = "bteqz";
13651       goto do_branch;
13652     case M_BNE:
13653       s = "cmp";
13654       s2 = "btnez";
13655       goto do_branch;
13656     case M_BLT:
13657       s = "slt";
13658       s2 = "btnez";
13659       goto do_branch;
13660     case M_BLTU:
13661       s = "sltu";
13662       s2 = "btnez";
13663       goto do_branch;
13664     case M_BLE:
13665       s = "slt";
13666       s2 = "bteqz";
13667       goto do_reverse_branch;
13668     case M_BLEU:
13669       s = "sltu";
13670       s2 = "bteqz";
13671       goto do_reverse_branch;
13672     case M_BGE:
13673       s = "slt";
13674       s2 = "bteqz";
13675       goto do_branch;
13676     case M_BGEU:
13677       s = "sltu";
13678       s2 = "bteqz";
13679       goto do_branch;
13680     case M_BGT:
13681       s = "slt";
13682       s2 = "btnez";
13683       goto do_reverse_branch;
13684     case M_BGTU:
13685       s = "sltu";
13686       s2 = "btnez";
13687
13688     do_reverse_branch:
13689       tmp = op[1];
13690       op[1] = op[0];
13691       op[0] = tmp;
13692
13693     do_branch:
13694       macro_build (NULL, s, "x,y", op[0], op[1]);
13695       macro_build (&offset_expr, s2, "p");
13696       break;
13697
13698     case M_BEQ_I:
13699       s = "cmpi";
13700       s2 = "bteqz";
13701       s3 = "x,U";
13702       goto do_branch_i;
13703     case M_BNE_I:
13704       s = "cmpi";
13705       s2 = "btnez";
13706       s3 = "x,U";
13707       goto do_branch_i;
13708     case M_BLT_I:
13709       s = "slti";
13710       s2 = "btnez";
13711       s3 = "x,8";
13712       goto do_branch_i;
13713     case M_BLTU_I:
13714       s = "sltiu";
13715       s2 = "btnez";
13716       s3 = "x,8";
13717       goto do_branch_i;
13718     case M_BLE_I:
13719       s = "slti";
13720       s2 = "btnez";
13721       s3 = "x,8";
13722       goto do_addone_branch_i;
13723     case M_BLEU_I:
13724       s = "sltiu";
13725       s2 = "btnez";
13726       s3 = "x,8";
13727       goto do_addone_branch_i;
13728     case M_BGE_I:
13729       s = "slti";
13730       s2 = "bteqz";
13731       s3 = "x,8";
13732       goto do_branch_i;
13733     case M_BGEU_I:
13734       s = "sltiu";
13735       s2 = "bteqz";
13736       s3 = "x,8";
13737       goto do_branch_i;
13738     case M_BGT_I:
13739       s = "slti";
13740       s2 = "bteqz";
13741       s3 = "x,8";
13742       goto do_addone_branch_i;
13743     case M_BGTU_I:
13744       s = "sltiu";
13745       s2 = "bteqz";
13746       s3 = "x,8";
13747
13748     do_addone_branch_i:
13749       ++imm_expr.X_add_number;
13750
13751     do_branch_i:
13752       macro_build (&imm_expr, s, s3, op[0]);
13753       macro_build (&offset_expr, s2, "p");
13754       break;
13755
13756     case M_ABS:
13757       expr1.X_add_number = 0;
13758       macro_build (&expr1, "slti", "x,8", op[1]);
13759       if (op[0] != op[1])
13760         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
13761       expr1.X_add_number = 2;
13762       macro_build (&expr1, "bteqz", "p");
13763       macro_build (NULL, "neg", "x,w", op[0], op[0]);
13764       break;
13765     }
13766 }
13767
13768 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
13769    opcode bits in *OPCODE_EXTRA.  */
13770
13771 static struct mips_opcode *
13772 mips_lookup_insn (struct hash_control *hash, const char *start,
13773                   ssize_t length, unsigned int *opcode_extra)
13774 {
13775   char *name, *dot, *p;
13776   unsigned int mask, suffix;
13777   ssize_t opend;
13778   struct mips_opcode *insn;
13779
13780   /* Make a copy of the instruction so that we can fiddle with it.  */
13781   name = xstrndup (start, length);
13782
13783   /* Look up the instruction as-is.  */
13784   insn = (struct mips_opcode *) hash_find (hash, name);
13785   if (insn)
13786     goto end;
13787
13788   dot = strchr (name, '.');
13789   if (dot && dot[1])
13790     {
13791       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
13792       p = mips_parse_vu0_channels (dot + 1, &mask);
13793       if (*p == 0 && mask != 0)
13794         {
13795           *dot = 0;
13796           insn = (struct mips_opcode *) hash_find (hash, name);
13797           *dot = '.';
13798           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
13799             {
13800               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
13801               goto end;
13802             }
13803         }
13804     }
13805
13806   if (mips_opts.micromips)
13807     {
13808       /* See if there's an instruction size override suffix,
13809          either `16' or `32', at the end of the mnemonic proper,
13810          that defines the operation, i.e. before the first `.'
13811          character if any.  Strip it and retry.  */
13812       opend = dot != NULL ? dot - name : length;
13813       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
13814         suffix = 2;
13815       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
13816         suffix = 4;
13817       else
13818         suffix = 0;
13819       if (suffix)
13820         {
13821           memcpy (name + opend - 2, name + opend, length - opend + 1);
13822           insn = (struct mips_opcode *) hash_find (hash, name);
13823           if (insn)
13824             {
13825               forced_insn_length = suffix;
13826               goto end;
13827             }
13828         }
13829     }
13830
13831   insn = NULL;
13832  end:
13833   free (name);
13834   return insn;
13835 }
13836
13837 /* Assemble an instruction into its binary format.  If the instruction
13838    is a macro, set imm_expr and offset_expr to the values associated
13839    with "I" and "A" operands respectively.  Otherwise store the value
13840    of the relocatable field (if any) in offset_expr.  In both cases
13841    set offset_reloc to the relocation operators applied to offset_expr.  */
13842
13843 static void
13844 mips_ip (char *str, struct mips_cl_insn *insn)
13845 {
13846   const struct mips_opcode *first, *past;
13847   struct hash_control *hash;
13848   char format;
13849   size_t end;
13850   struct mips_operand_token *tokens;
13851   unsigned int opcode_extra;
13852
13853   if (mips_opts.micromips)
13854     {
13855       hash = micromips_op_hash;
13856       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13857     }
13858   else
13859     {
13860       hash = op_hash;
13861       past = &mips_opcodes[NUMOPCODES];
13862     }
13863   forced_insn_length = 0;
13864   opcode_extra = 0;
13865
13866   /* We first try to match an instruction up to a space or to the end.  */
13867   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13868     continue;
13869
13870   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13871   if (first == NULL)
13872     {
13873       set_insn_error (0, _("unrecognized opcode"));
13874       return;
13875     }
13876
13877   if (strcmp (first->name, "li.s") == 0)
13878     format = 'f';
13879   else if (strcmp (first->name, "li.d") == 0)
13880     format = 'd';
13881   else
13882     format = 0;
13883   tokens = mips_parse_arguments (str + end, format);
13884   if (!tokens)
13885     return;
13886
13887   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13888       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13889     set_insn_error (0, _("invalid operands"));
13890
13891   obstack_free (&mips_operand_tokens, tokens);
13892 }
13893
13894 /* As for mips_ip, but used when assembling MIPS16 code.
13895    Also set forced_insn_length to the resulting instruction size in
13896    bytes if the user explicitly requested a small or extended instruction.  */
13897
13898 static void
13899 mips16_ip (char *str, struct mips_cl_insn *insn)
13900 {
13901   char *end, *s, c;
13902   struct mips_opcode *first;
13903   struct mips_operand_token *tokens;
13904   unsigned int l;
13905
13906   for (s = str; ISLOWER (*s); ++s)
13907     ;
13908   end = s;
13909   c = *end;
13910
13911   l = 0;
13912   switch (c)
13913     {
13914     case '\0':
13915       break;
13916
13917     case ' ':
13918       s++;
13919       break;
13920
13921     case '.':
13922       s++;
13923       if (*s == 't')
13924         {
13925           l = 2;
13926           s++;
13927         }
13928       else if (*s == 'e')
13929         {
13930           l = 4;
13931           s++;
13932         }
13933       if (*s == '\0')
13934         break;
13935       else if (*s++ == ' ')
13936         break;
13937       /* Fall through.  */
13938     default:
13939       set_insn_error (0, _("unrecognized opcode"));
13940       return;
13941     }
13942   forced_insn_length = l;
13943
13944   *end = 0;
13945   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13946   *end = c;
13947
13948   if (!first)
13949     {
13950       set_insn_error (0, _("unrecognized opcode"));
13951       return;
13952     }
13953
13954   tokens = mips_parse_arguments (s, 0);
13955   if (!tokens)
13956     return;
13957
13958   if (!match_mips16_insns (insn, first, tokens))
13959     set_insn_error (0, _("invalid operands"));
13960
13961   obstack_free (&mips_operand_tokens, tokens);
13962 }
13963
13964 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13965    NBITS is the number of significant bits in VAL.  */
13966
13967 static unsigned long
13968 mips16_immed_extend (offsetT val, unsigned int nbits)
13969 {
13970   int extval;
13971   if (nbits == 16)
13972     {
13973       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13974       val &= 0x1f;
13975     }
13976   else if (nbits == 15)
13977     {
13978       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13979       val &= 0xf;
13980     }
13981   else
13982     {
13983       extval = ((val & 0x1f) << 6) | (val & 0x20);
13984       val = 0;
13985     }
13986   return (extval << 16) | val;
13987 }
13988
13989 /* Like decode_mips16_operand, but require the operand to be defined and
13990    require it to be an integer.  */
13991
13992 static const struct mips_int_operand *
13993 mips16_immed_operand (int type, bfd_boolean extended_p)
13994 {
13995   const struct mips_operand *operand;
13996
13997   operand = decode_mips16_operand (type, extended_p);
13998   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13999     abort ();
14000   return (const struct mips_int_operand *) operand;
14001 }
14002
14003 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
14004
14005 static bfd_boolean
14006 mips16_immed_in_range_p (const struct mips_int_operand *operand,
14007                          bfd_reloc_code_real_type reloc, offsetT sval)
14008 {
14009   int min_val, max_val;
14010
14011   min_val = mips_int_operand_min (operand);
14012   max_val = mips_int_operand_max (operand);
14013   if (reloc != BFD_RELOC_UNUSED)
14014     {
14015       if (min_val < 0)
14016         sval = SEXT_16BIT (sval);
14017       else
14018         sval &= 0xffff;
14019     }
14020
14021   return (sval >= min_val
14022           && sval <= max_val
14023           && (sval & ((1 << operand->shift) - 1)) == 0);
14024 }
14025
14026 /* Install immediate value VAL into MIPS16 instruction *INSN,
14027    extending it if necessary.  The instruction in *INSN may
14028    already be extended.
14029
14030    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14031    if none.  In the former case, VAL is a 16-bit number with no
14032    defined signedness.
14033
14034    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14035    is the length that the user requested, or 0 if none.  */
14036
14037 static void
14038 mips16_immed (const char *file, unsigned int line, int type,
14039               bfd_reloc_code_real_type reloc, offsetT val,
14040               unsigned int user_insn_length, unsigned long *insn)
14041 {
14042   const struct mips_int_operand *operand;
14043   unsigned int uval, length;
14044
14045   operand = mips16_immed_operand (type, FALSE);
14046   if (!mips16_immed_in_range_p (operand, reloc, val))
14047     {
14048       /* We need an extended instruction.  */
14049       if (user_insn_length == 2)
14050         as_bad_where (file, line, _("invalid unextended operand value"));
14051       else
14052         *insn |= MIPS16_EXTEND;
14053     }
14054   else if (user_insn_length == 4)
14055     {
14056       /* The operand doesn't force an unextended instruction to be extended.
14057          Warn if the user wanted an extended instruction anyway.  */
14058       *insn |= MIPS16_EXTEND;
14059       as_warn_where (file, line,
14060                      _("extended operand requested but not required"));
14061     }
14062
14063   length = mips16_opcode_length (*insn);
14064   if (length == 4)
14065     {
14066       operand = mips16_immed_operand (type, TRUE);
14067       if (!mips16_immed_in_range_p (operand, reloc, val))
14068         as_bad_where (file, line,
14069                       _("operand value out of range for instruction"));
14070     }
14071   uval = ((unsigned int) val >> operand->shift) - operand->bias;
14072   if (length == 2 || operand->root.lsb != 0)
14073     *insn = mips_insert_operand (&operand->root, *insn, uval);
14074   else
14075     *insn |= mips16_immed_extend (uval, operand->root.size);
14076 }
14077 \f
14078 struct percent_op_match
14079 {
14080   const char *str;
14081   bfd_reloc_code_real_type reloc;
14082 };
14083
14084 static const struct percent_op_match mips_percent_op[] =
14085 {
14086   {"%lo", BFD_RELOC_LO16},
14087   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14088   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14089   {"%call16", BFD_RELOC_MIPS_CALL16},
14090   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14091   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14092   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14093   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14094   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14095   {"%got", BFD_RELOC_MIPS_GOT16},
14096   {"%gp_rel", BFD_RELOC_GPREL16},
14097   {"%gprel", BFD_RELOC_GPREL16},
14098   {"%half", BFD_RELOC_16},
14099   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14100   {"%higher", BFD_RELOC_MIPS_HIGHER},
14101   {"%neg", BFD_RELOC_MIPS_SUB},
14102   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14103   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14104   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14105   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14106   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14107   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14108   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14109   {"%hi", BFD_RELOC_HI16_S},
14110   {"%pcrel_hi", BFD_RELOC_HI16_S_PCREL},
14111   {"%pcrel_lo", BFD_RELOC_LO16_PCREL}
14112 };
14113
14114 static const struct percent_op_match mips16_percent_op[] =
14115 {
14116   {"%lo", BFD_RELOC_MIPS16_LO16},
14117   {"%gp_rel", BFD_RELOC_MIPS16_GPREL},
14118   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14119   {"%got", BFD_RELOC_MIPS16_GOT16},
14120   {"%call16", BFD_RELOC_MIPS16_CALL16},
14121   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14122   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14123   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14124   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14125   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14126   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14127   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14128   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14129 };
14130
14131
14132 /* Return true if *STR points to a relocation operator.  When returning true,
14133    move *STR over the operator and store its relocation code in *RELOC.
14134    Leave both *STR and *RELOC alone when returning false.  */
14135
14136 static bfd_boolean
14137 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14138 {
14139   const struct percent_op_match *percent_op;
14140   size_t limit, i;
14141
14142   if (mips_opts.mips16)
14143     {
14144       percent_op = mips16_percent_op;
14145       limit = ARRAY_SIZE (mips16_percent_op);
14146     }
14147   else
14148     {
14149       percent_op = mips_percent_op;
14150       limit = ARRAY_SIZE (mips_percent_op);
14151     }
14152
14153   for (i = 0; i < limit; i++)
14154     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14155       {
14156         int len = strlen (percent_op[i].str);
14157
14158         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14159           continue;
14160
14161         *str += strlen (percent_op[i].str);
14162         *reloc = percent_op[i].reloc;
14163
14164         /* Check whether the output BFD supports this relocation.
14165            If not, issue an error and fall back on something safe.  */
14166         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14167           {
14168             as_bad (_("relocation %s isn't supported by the current ABI"),
14169                     percent_op[i].str);
14170             *reloc = BFD_RELOC_UNUSED;
14171           }
14172         return TRUE;
14173       }
14174   return FALSE;
14175 }
14176
14177
14178 /* Parse string STR as a 16-bit relocatable operand.  Store the
14179    expression in *EP and the relocations in the array starting
14180    at RELOC.  Return the number of relocation operators used.
14181
14182    On exit, EXPR_END points to the first character after the expression.  */
14183
14184 static size_t
14185 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14186                        char *str)
14187 {
14188   bfd_reloc_code_real_type reversed_reloc[3];
14189   size_t reloc_index, i;
14190   int crux_depth, str_depth;
14191   char *crux;
14192
14193   /* Search for the start of the main expression, recoding relocations
14194      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14195      of the main expression and with CRUX_DEPTH containing the number
14196      of open brackets at that point.  */
14197   reloc_index = -1;
14198   str_depth = 0;
14199   do
14200     {
14201       reloc_index++;
14202       crux = str;
14203       crux_depth = str_depth;
14204
14205       /* Skip over whitespace and brackets, keeping count of the number
14206          of brackets.  */
14207       while (*str == ' ' || *str == '\t' || *str == '(')
14208         if (*str++ == '(')
14209           str_depth++;
14210     }
14211   while (*str == '%'
14212          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14213          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14214
14215   my_getExpression (ep, crux);
14216   str = expr_end;
14217
14218   /* Match every open bracket.  */
14219   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14220     if (*str++ == ')')
14221       crux_depth--;
14222
14223   if (crux_depth > 0)
14224     as_bad (_("unclosed '('"));
14225
14226   expr_end = str;
14227
14228   if (reloc_index != 0)
14229     {
14230       prev_reloc_op_frag = frag_now;
14231       for (i = 0; i < reloc_index; i++)
14232         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14233     }
14234
14235   return reloc_index;
14236 }
14237
14238 static void
14239 my_getExpression (expressionS *ep, char *str)
14240 {
14241   char *save_in;
14242
14243   save_in = input_line_pointer;
14244   input_line_pointer = str;
14245   expression (ep);
14246   expr_end = input_line_pointer;
14247   input_line_pointer = save_in;
14248 }
14249
14250 const char *
14251 md_atof (int type, char *litP, int *sizeP)
14252 {
14253   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14254 }
14255
14256 void
14257 md_number_to_chars (char *buf, valueT val, int n)
14258 {
14259   if (target_big_endian)
14260     number_to_chars_bigendian (buf, val, n);
14261   else
14262     number_to_chars_littleendian (buf, val, n);
14263 }
14264 \f
14265 static int support_64bit_objects(void)
14266 {
14267   const char **list, **l;
14268   int yes;
14269
14270   list = bfd_target_list ();
14271   for (l = list; *l != NULL; l++)
14272     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14273         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14274       break;
14275   yes = (*l != NULL);
14276   free (list);
14277   return yes;
14278 }
14279
14280 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14281    NEW_VALUE.  Warn if another value was already specified.  Note:
14282    we have to defer parsing the -march and -mtune arguments in order
14283    to handle 'from-abi' correctly, since the ABI might be specified
14284    in a later argument.  */
14285
14286 static void
14287 mips_set_option_string (const char **string_ptr, const char *new_value)
14288 {
14289   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14290     as_warn (_("a different %s was already specified, is now %s"),
14291              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14292              new_value);
14293
14294   *string_ptr = new_value;
14295 }
14296
14297 int
14298 md_parse_option (int c, const char *arg)
14299 {
14300   unsigned int i;
14301
14302   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14303     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14304       {
14305         file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
14306                                            c == mips_ases[i].option_on);
14307         return 1;
14308       }
14309
14310   switch (c)
14311     {
14312     case OPTION_CONSTRUCT_FLOATS:
14313       mips_disable_float_construction = 0;
14314       break;
14315
14316     case OPTION_NO_CONSTRUCT_FLOATS:
14317       mips_disable_float_construction = 1;
14318       break;
14319
14320     case OPTION_TRAP:
14321       mips_trap = 1;
14322       break;
14323
14324     case OPTION_BREAK:
14325       mips_trap = 0;
14326       break;
14327
14328     case OPTION_EB:
14329       target_big_endian = 1;
14330       break;
14331
14332     case OPTION_EL:
14333       target_big_endian = 0;
14334       break;
14335
14336     case 'O':
14337       if (arg == NULL)
14338         mips_optimize = 1;
14339       else if (arg[0] == '0')
14340         mips_optimize = 0;
14341       else if (arg[0] == '1')
14342         mips_optimize = 1;
14343       else
14344         mips_optimize = 2;
14345       break;
14346
14347     case 'g':
14348       if (arg == NULL)
14349         mips_debug = 2;
14350       else
14351         mips_debug = atoi (arg);
14352       break;
14353
14354     case OPTION_MIPS1:
14355       file_mips_opts.isa = ISA_MIPS1;
14356       break;
14357
14358     case OPTION_MIPS2:
14359       file_mips_opts.isa = ISA_MIPS2;
14360       break;
14361
14362     case OPTION_MIPS3:
14363       file_mips_opts.isa = ISA_MIPS3;
14364       break;
14365
14366     case OPTION_MIPS4:
14367       file_mips_opts.isa = ISA_MIPS4;
14368       break;
14369
14370     case OPTION_MIPS5:
14371       file_mips_opts.isa = ISA_MIPS5;
14372       break;
14373
14374     case OPTION_MIPS32:
14375       file_mips_opts.isa = ISA_MIPS32;
14376       break;
14377
14378     case OPTION_MIPS32R2:
14379       file_mips_opts.isa = ISA_MIPS32R2;
14380       break;
14381
14382     case OPTION_MIPS32R3:
14383       file_mips_opts.isa = ISA_MIPS32R3;
14384       break;
14385
14386     case OPTION_MIPS32R5:
14387       file_mips_opts.isa = ISA_MIPS32R5;
14388       break;
14389
14390     case OPTION_MIPS32R6:
14391       file_mips_opts.isa = ISA_MIPS32R6;
14392       break;
14393
14394     case OPTION_MIPS64R2:
14395       file_mips_opts.isa = ISA_MIPS64R2;
14396       break;
14397
14398     case OPTION_MIPS64R3:
14399       file_mips_opts.isa = ISA_MIPS64R3;
14400       break;
14401
14402     case OPTION_MIPS64R5:
14403       file_mips_opts.isa = ISA_MIPS64R5;
14404       break;
14405
14406     case OPTION_MIPS64R6:
14407       file_mips_opts.isa = ISA_MIPS64R6;
14408       break;
14409
14410     case OPTION_MIPS64:
14411       file_mips_opts.isa = ISA_MIPS64;
14412       break;
14413
14414     case OPTION_MTUNE:
14415       mips_set_option_string (&mips_tune_string, arg);
14416       break;
14417
14418     case OPTION_MARCH:
14419       mips_set_option_string (&mips_arch_string, arg);
14420       break;
14421
14422     case OPTION_M4650:
14423       mips_set_option_string (&mips_arch_string, "4650");
14424       mips_set_option_string (&mips_tune_string, "4650");
14425       break;
14426
14427     case OPTION_NO_M4650:
14428       break;
14429
14430     case OPTION_M4010:
14431       mips_set_option_string (&mips_arch_string, "4010");
14432       mips_set_option_string (&mips_tune_string, "4010");
14433       break;
14434
14435     case OPTION_NO_M4010:
14436       break;
14437
14438     case OPTION_M4100:
14439       mips_set_option_string (&mips_arch_string, "4100");
14440       mips_set_option_string (&mips_tune_string, "4100");
14441       break;
14442
14443     case OPTION_NO_M4100:
14444       break;
14445
14446     case OPTION_M3900:
14447       mips_set_option_string (&mips_arch_string, "3900");
14448       mips_set_option_string (&mips_tune_string, "3900");
14449       break;
14450
14451     case OPTION_NO_M3900:
14452       break;
14453
14454     case OPTION_MICROMIPS:
14455       if (file_mips_opts.mips16 == 1)
14456         {
14457           as_bad (_("-mmicromips cannot be used with -mips16"));
14458           return 0;
14459         }
14460       file_mips_opts.micromips = 1;
14461       mips_no_prev_insn ();
14462       break;
14463
14464     case OPTION_NO_MICROMIPS:
14465       file_mips_opts.micromips = 0;
14466       mips_no_prev_insn ();
14467       break;
14468
14469     case OPTION_MIPS16:
14470       if (file_mips_opts.micromips == 1)
14471         {
14472           as_bad (_("-mips16 cannot be used with -micromips"));
14473           return 0;
14474         }
14475       file_mips_opts.mips16 = 1;
14476       mips_no_prev_insn ();
14477       break;
14478
14479     case OPTION_NO_MIPS16:
14480       file_mips_opts.mips16 = 0;
14481       mips_no_prev_insn ();
14482       break;
14483
14484     case OPTION_FIX_24K:
14485       mips_fix_24k = 1;
14486       break;
14487
14488     case OPTION_NO_FIX_24K:
14489       mips_fix_24k = 0;
14490       break;
14491
14492     case OPTION_FIX_RM7000:
14493       mips_fix_rm7000 = 1;
14494       break;
14495
14496     case OPTION_NO_FIX_RM7000:
14497       mips_fix_rm7000 = 0;
14498       break;
14499
14500     case OPTION_FIX_LOONGSON2F_JUMP:
14501       mips_fix_loongson2f_jump = TRUE;
14502       break;
14503
14504     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14505       mips_fix_loongson2f_jump = FALSE;
14506       break;
14507
14508     case OPTION_FIX_LOONGSON2F_NOP:
14509       mips_fix_loongson2f_nop = TRUE;
14510       break;
14511
14512     case OPTION_NO_FIX_LOONGSON2F_NOP:
14513       mips_fix_loongson2f_nop = FALSE;
14514       break;
14515
14516     case OPTION_FIX_VR4120:
14517       mips_fix_vr4120 = 1;
14518       break;
14519
14520     case OPTION_NO_FIX_VR4120:
14521       mips_fix_vr4120 = 0;
14522       break;
14523
14524     case OPTION_FIX_VR4130:
14525       mips_fix_vr4130 = 1;
14526       break;
14527
14528     case OPTION_NO_FIX_VR4130:
14529       mips_fix_vr4130 = 0;
14530       break;
14531
14532     case OPTION_FIX_CN63XXP1:
14533       mips_fix_cn63xxp1 = TRUE;
14534       break;
14535
14536     case OPTION_NO_FIX_CN63XXP1:
14537       mips_fix_cn63xxp1 = FALSE;
14538       break;
14539
14540     case OPTION_RELAX_BRANCH:
14541       mips_relax_branch = 1;
14542       break;
14543
14544     case OPTION_NO_RELAX_BRANCH:
14545       mips_relax_branch = 0;
14546       break;
14547
14548     case OPTION_IGNORE_BRANCH_ISA:
14549       mips_ignore_branch_isa = TRUE;
14550       break;
14551
14552     case OPTION_NO_IGNORE_BRANCH_ISA:
14553       mips_ignore_branch_isa = FALSE;
14554       break;
14555
14556     case OPTION_INSN32:
14557       file_mips_opts.insn32 = TRUE;
14558       break;
14559
14560     case OPTION_NO_INSN32:
14561       file_mips_opts.insn32 = FALSE;
14562       break;
14563
14564     case OPTION_MSHARED:
14565       mips_in_shared = TRUE;
14566       break;
14567
14568     case OPTION_MNO_SHARED:
14569       mips_in_shared = FALSE;
14570       break;
14571
14572     case OPTION_MSYM32:
14573       file_mips_opts.sym32 = TRUE;
14574       break;
14575
14576     case OPTION_MNO_SYM32:
14577       file_mips_opts.sym32 = FALSE;
14578       break;
14579
14580       /* When generating ELF code, we permit -KPIC and -call_shared to
14581          select SVR4_PIC, and -non_shared to select no PIC.  This is
14582          intended to be compatible with Irix 5.  */
14583     case OPTION_CALL_SHARED:
14584       mips_pic = SVR4_PIC;
14585       mips_abicalls = TRUE;
14586       break;
14587
14588     case OPTION_CALL_NONPIC:
14589       mips_pic = NO_PIC;
14590       mips_abicalls = TRUE;
14591       break;
14592
14593     case OPTION_NON_SHARED:
14594       mips_pic = NO_PIC;
14595       mips_abicalls = FALSE;
14596       break;
14597
14598       /* The -xgot option tells the assembler to use 32 bit offsets
14599          when accessing the got in SVR4_PIC mode.  It is for Irix
14600          compatibility.  */
14601     case OPTION_XGOT:
14602       mips_big_got = 1;
14603       break;
14604
14605     case 'G':
14606       g_switch_value = atoi (arg);
14607       g_switch_seen = 1;
14608       break;
14609
14610       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14611          and -mabi=64.  */
14612     case OPTION_32:
14613       mips_abi = O32_ABI;
14614       break;
14615
14616     case OPTION_N32:
14617       mips_abi = N32_ABI;
14618       break;
14619
14620     case OPTION_64:
14621       mips_abi = N64_ABI;
14622       if (!support_64bit_objects())
14623         as_fatal (_("no compiled in support for 64 bit object file format"));
14624       break;
14625
14626     case OPTION_GP32:
14627       file_mips_opts.gp = 32;
14628       break;
14629
14630     case OPTION_GP64:
14631       file_mips_opts.gp = 64;
14632       break;
14633
14634     case OPTION_FP32:
14635       file_mips_opts.fp = 32;
14636       break;
14637
14638     case OPTION_FPXX:
14639       file_mips_opts.fp = 0;
14640       break;
14641
14642     case OPTION_FP64:
14643       file_mips_opts.fp = 64;
14644       break;
14645
14646     case OPTION_ODD_SPREG:
14647       file_mips_opts.oddspreg = 1;
14648       break;
14649
14650     case OPTION_NO_ODD_SPREG:
14651       file_mips_opts.oddspreg = 0;
14652       break;
14653
14654     case OPTION_SINGLE_FLOAT:
14655       file_mips_opts.single_float = 1;
14656       break;
14657
14658     case OPTION_DOUBLE_FLOAT:
14659       file_mips_opts.single_float = 0;
14660       break;
14661
14662     case OPTION_SOFT_FLOAT:
14663       file_mips_opts.soft_float = 1;
14664       break;
14665
14666     case OPTION_HARD_FLOAT:
14667       file_mips_opts.soft_float = 0;
14668       break;
14669
14670     case OPTION_MABI:
14671       if (strcmp (arg, "32") == 0)
14672         mips_abi = O32_ABI;
14673       else if (strcmp (arg, "o64") == 0)
14674         mips_abi = O64_ABI;
14675       else if (strcmp (arg, "n32") == 0)
14676         mips_abi = N32_ABI;
14677       else if (strcmp (arg, "64") == 0)
14678         {
14679           mips_abi = N64_ABI;
14680           if (! support_64bit_objects())
14681             as_fatal (_("no compiled in support for 64 bit object file "
14682                         "format"));
14683         }
14684       else if (strcmp (arg, "eabi") == 0)
14685         mips_abi = EABI_ABI;
14686       else
14687         {
14688           as_fatal (_("invalid abi -mabi=%s"), arg);
14689           return 0;
14690         }
14691       break;
14692
14693     case OPTION_M7000_HILO_FIX:
14694       mips_7000_hilo_fix = TRUE;
14695       break;
14696
14697     case OPTION_MNO_7000_HILO_FIX:
14698       mips_7000_hilo_fix = FALSE;
14699       break;
14700
14701     case OPTION_MDEBUG:
14702       mips_flag_mdebug = TRUE;
14703       break;
14704
14705     case OPTION_NO_MDEBUG:
14706       mips_flag_mdebug = FALSE;
14707       break;
14708
14709     case OPTION_PDR:
14710       mips_flag_pdr = TRUE;
14711       break;
14712
14713     case OPTION_NO_PDR:
14714       mips_flag_pdr = FALSE;
14715       break;
14716
14717     case OPTION_MVXWORKS_PIC:
14718       mips_pic = VXWORKS_PIC;
14719       break;
14720
14721     case OPTION_NAN:
14722       if (strcmp (arg, "2008") == 0)
14723         mips_nan2008 = 1;
14724       else if (strcmp (arg, "legacy") == 0)
14725         mips_nan2008 = 0;
14726       else
14727         {
14728           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
14729           return 0;
14730         }
14731       break;
14732
14733     default:
14734       return 0;
14735     }
14736
14737     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14738
14739   return 1;
14740 }
14741 \f
14742 /* Set up globals to tune for the ISA or processor described by INFO.  */
14743
14744 static void
14745 mips_set_tune (const struct mips_cpu_info *info)
14746 {
14747   if (info != 0)
14748     mips_tune = info->cpu;
14749 }
14750
14751
14752 void
14753 mips_after_parse_args (void)
14754 {
14755   const struct mips_cpu_info *arch_info = 0;
14756   const struct mips_cpu_info *tune_info = 0;
14757
14758   /* GP relative stuff not working for PE */
14759   if (strncmp (TARGET_OS, "pe", 2) == 0)
14760     {
14761       if (g_switch_seen && g_switch_value != 0)
14762         as_bad (_("-G not supported in this configuration"));
14763       g_switch_value = 0;
14764     }
14765
14766   if (mips_abi == NO_ABI)
14767     mips_abi = MIPS_DEFAULT_ABI;
14768
14769   /* The following code determines the architecture.
14770      Similar code was added to GCC 3.3 (see override_options() in
14771      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14772      as much as possible.  */
14773
14774   if (mips_arch_string != 0)
14775     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14776
14777   if (file_mips_opts.isa != ISA_UNKNOWN)
14778     {
14779       /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
14780          ISA level specified by -mipsN, while arch_info->isa contains
14781          the -march selection (if any).  */
14782       if (arch_info != 0)
14783         {
14784           /* -march takes precedence over -mipsN, since it is more descriptive.
14785              There's no harm in specifying both as long as the ISA levels
14786              are the same.  */
14787           if (file_mips_opts.isa != arch_info->isa)
14788             as_bad (_("-%s conflicts with the other architecture options,"
14789                       " which imply -%s"),
14790                     mips_cpu_info_from_isa (file_mips_opts.isa)->name,
14791                     mips_cpu_info_from_isa (arch_info->isa)->name);
14792         }
14793       else
14794         arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
14795     }
14796
14797   if (arch_info == 0)
14798     {
14799       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14800       gas_assert (arch_info);
14801     }
14802
14803   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14804     as_bad (_("-march=%s is not compatible with the selected ABI"),
14805             arch_info->name);
14806
14807   file_mips_opts.arch = arch_info->cpu;
14808   file_mips_opts.isa = arch_info->isa;
14809
14810   /* Set up initial mips_opts state.  */
14811   mips_opts = file_mips_opts;
14812
14813   /* The register size inference code is now placed in
14814      file_mips_check_options.  */
14815
14816   /* Optimize for file_mips_opts.arch, unless -mtune selects a different
14817      processor.  */
14818   if (mips_tune_string != 0)
14819     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14820
14821   if (tune_info == 0)
14822     mips_set_tune (arch_info);
14823   else
14824     mips_set_tune (tune_info);
14825
14826   if (mips_flag_mdebug < 0)
14827     mips_flag_mdebug = 0;
14828 }
14829 \f
14830 void
14831 mips_init_after_args (void)
14832 {
14833   /* initialize opcodes */
14834   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14835   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14836 }
14837
14838 long
14839 md_pcrel_from (fixS *fixP)
14840 {
14841   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14842   switch (fixP->fx_r_type)
14843     {
14844     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14845     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14846       /* Return the address of the delay slot.  */
14847       return addr + 2;
14848
14849     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14850     case BFD_RELOC_MICROMIPS_JMP:
14851     case BFD_RELOC_MIPS16_16_PCREL_S1:
14852     case BFD_RELOC_16_PCREL_S2:
14853     case BFD_RELOC_MIPS_21_PCREL_S2:
14854     case BFD_RELOC_MIPS_26_PCREL_S2:
14855     case BFD_RELOC_MIPS_JMP:
14856       /* Return the address of the delay slot.  */
14857       return addr + 4;
14858
14859     case BFD_RELOC_MIPS_18_PCREL_S3:
14860       /* Return the aligned address of the doubleword containing
14861          the instruction.  */
14862       return addr & ~7;
14863
14864     default:
14865       return addr;
14866     }
14867 }
14868
14869 /* This is called before the symbol table is processed.  In order to
14870    work with gcc when using mips-tfile, we must keep all local labels.
14871    However, in other cases, we want to discard them.  If we were
14872    called with -g, but we didn't see any debugging information, it may
14873    mean that gcc is smuggling debugging information through to
14874    mips-tfile, in which case we must generate all local labels.  */
14875
14876 void
14877 mips_frob_file_before_adjust (void)
14878 {
14879 #ifndef NO_ECOFF_DEBUGGING
14880   if (ECOFF_DEBUGGING
14881       && mips_debug != 0
14882       && ! ecoff_debugging_seen)
14883     flag_keep_locals = 1;
14884 #endif
14885 }
14886
14887 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14888    the corresponding LO16 reloc.  This is called before md_apply_fix and
14889    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14890    relocation operators.
14891
14892    For our purposes, a %lo() expression matches a %got() or %hi()
14893    expression if:
14894
14895       (a) it refers to the same symbol; and
14896       (b) the offset applied in the %lo() expression is no lower than
14897           the offset applied in the %got() or %hi().
14898
14899    (b) allows us to cope with code like:
14900
14901         lui     $4,%hi(foo)
14902         lh      $4,%lo(foo+2)($4)
14903
14904    ...which is legal on RELA targets, and has a well-defined behaviour
14905    if the user knows that adding 2 to "foo" will not induce a carry to
14906    the high 16 bits.
14907
14908    When several %lo()s match a particular %got() or %hi(), we use the
14909    following rules to distinguish them:
14910
14911      (1) %lo()s with smaller offsets are a better match than %lo()s with
14912          higher offsets.
14913
14914      (2) %lo()s with no matching %got() or %hi() are better than those
14915          that already have a matching %got() or %hi().
14916
14917      (3) later %lo()s are better than earlier %lo()s.
14918
14919    These rules are applied in order.
14920
14921    (1) means, among other things, that %lo()s with identical offsets are
14922    chosen if they exist.
14923
14924    (2) means that we won't associate several high-part relocations with
14925    the same low-part relocation unless there's no alternative.  Having
14926    several high parts for the same low part is a GNU extension; this rule
14927    allows careful users to avoid it.
14928
14929    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14930    with the last high-part relocation being at the front of the list.
14931    It therefore makes sense to choose the last matching low-part
14932    relocation, all other things being equal.  It's also easier
14933    to code that way.  */
14934
14935 void
14936 mips_frob_file (void)
14937 {
14938   struct mips_hi_fixup *l;
14939   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14940
14941   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14942     {
14943       segment_info_type *seginfo;
14944       bfd_boolean matched_lo_p;
14945       fixS **hi_pos, **lo_pos, **pos;
14946
14947       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14948
14949       /* If a GOT16 relocation turns out to be against a global symbol,
14950          there isn't supposed to be a matching LO.  Ignore %gots against
14951          constants; we'll report an error for those later.  */
14952       if (got16_reloc_p (l->fixp->fx_r_type)
14953           && !(l->fixp->fx_addsy
14954                && pic_need_relax (l->fixp->fx_addsy)))
14955         continue;
14956
14957       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14958       if (fixup_has_matching_lo_p (l->fixp))
14959         continue;
14960
14961       seginfo = seg_info (l->seg);
14962
14963       /* Set HI_POS to the position of this relocation in the chain.
14964          Set LO_POS to the position of the chosen low-part relocation.
14965          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14966          relocation that matches an immediately-preceding high-part
14967          relocation.  */
14968       hi_pos = NULL;
14969       lo_pos = NULL;
14970       matched_lo_p = FALSE;
14971       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14972
14973       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14974         {
14975           if (*pos == l->fixp)
14976             hi_pos = pos;
14977
14978           if ((*pos)->fx_r_type == looking_for_rtype
14979               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14980               && (*pos)->fx_offset >= l->fixp->fx_offset
14981               && (lo_pos == NULL
14982                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14983                   || (!matched_lo_p
14984                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14985             lo_pos = pos;
14986
14987           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14988                           && fixup_has_matching_lo_p (*pos));
14989         }
14990
14991       /* If we found a match, remove the high-part relocation from its
14992          current position and insert it before the low-part relocation.
14993          Make the offsets match so that fixup_has_matching_lo_p()
14994          will return true.
14995
14996          We don't warn about unmatched high-part relocations since some
14997          versions of gcc have been known to emit dead "lui ...%hi(...)"
14998          instructions.  */
14999       if (lo_pos != NULL)
15000         {
15001           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15002           if (l->fixp->fx_next != *lo_pos)
15003             {
15004               *hi_pos = l->fixp->fx_next;
15005               l->fixp->fx_next = *lo_pos;
15006               *lo_pos = l->fixp;
15007             }
15008         }
15009     }
15010 }
15011
15012 int
15013 mips_force_relocation (fixS *fixp)
15014 {
15015   if (generic_force_reloc (fixp))
15016     return 1;
15017
15018   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15019      so that the linker relaxation can update targets.  */
15020   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15021       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15022       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15023     return 1;
15024
15025   /* We want to keep BFD_RELOC_16_PCREL_S2 BFD_RELOC_MIPS_21_PCREL_S2
15026      and BFD_RELOC_MIPS_26_PCREL_S2 relocations against MIPS16 and
15027      microMIPS symbols so that we can do cross-mode branch diagnostics
15028      and BAL to JALX conversion by the linker.  */
15029   if ((fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15030        || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15031        || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2)
15032       && fixp->fx_addsy
15033       && ELF_ST_IS_COMPRESSED (S_GET_OTHER (fixp->fx_addsy)))
15034     return 1;
15035
15036   /* We want all PC-relative relocations to be kept for R6 relaxation.  */
15037   if (ISA_IS_R6 (file_mips_opts.isa)
15038       && (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15039           || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15040           || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
15041           || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
15042           || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
15043           || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
15044           || fixp->fx_r_type == BFD_RELOC_LO16_PCREL))
15045     return 1;
15046
15047   return 0;
15048 }
15049
15050 /* Implement TC_FORCE_RELOCATION_ABS.  */
15051
15052 bfd_boolean
15053 mips_force_relocation_abs (fixS *fixp)
15054 {
15055   if (generic_force_reloc (fixp))
15056     return TRUE;
15057
15058   /* These relocations do not have enough bits in the in-place addend
15059      to hold an arbitrary absolute section's offset.  */
15060   if (HAVE_IN_PLACE_ADDENDS && limited_pcrel_reloc_p (fixp->fx_r_type))
15061     return TRUE;
15062
15063   return FALSE;
15064 }
15065
15066 /* Read the instruction associated with RELOC from BUF.  */
15067
15068 static unsigned int
15069 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15070 {
15071   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15072     return read_compressed_insn (buf, 4);
15073   else
15074     return read_insn (buf);
15075 }
15076
15077 /* Write instruction INSN to BUF, given that it has been relocated
15078    by RELOC.  */
15079
15080 static void
15081 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15082                   unsigned long insn)
15083 {
15084   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15085     write_compressed_insn (buf, insn, 4);
15086   else
15087     write_insn (buf, insn);
15088 }
15089
15090 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15091    to a symbol in another ISA mode, which cannot be converted to JALX.  */
15092
15093 static bfd_boolean
15094 fix_bad_cross_mode_jump_p (fixS *fixP)
15095 {
15096   unsigned long opcode;
15097   int other;
15098   char *buf;
15099
15100   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15101     return FALSE;
15102
15103   other = S_GET_OTHER (fixP->fx_addsy);
15104   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15105   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15106   switch (fixP->fx_r_type)
15107     {
15108     case BFD_RELOC_MIPS_JMP:
15109       return opcode != 0x1d && opcode != 0x03 && ELF_ST_IS_COMPRESSED (other);
15110     case BFD_RELOC_MICROMIPS_JMP:
15111       return opcode != 0x3c && opcode != 0x3d && !ELF_ST_IS_MICROMIPS (other);
15112     default:
15113       return FALSE;
15114     }
15115 }
15116
15117 /* Return TRUE if the instruction pointed to by FIXP is an invalid JALX
15118    jump to a symbol in the same ISA mode.  */
15119
15120 static bfd_boolean
15121 fix_bad_same_mode_jalx_p (fixS *fixP)
15122 {
15123   unsigned long opcode;
15124   int other;
15125   char *buf;
15126
15127   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15128     return FALSE;
15129
15130   other = S_GET_OTHER (fixP->fx_addsy);
15131   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15132   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15133   switch (fixP->fx_r_type)
15134     {
15135     case BFD_RELOC_MIPS_JMP:
15136       return opcode == 0x1d && !ELF_ST_IS_COMPRESSED (other);
15137     case BFD_RELOC_MIPS16_JMP:
15138       return opcode == 0x07 && ELF_ST_IS_COMPRESSED (other);
15139     case BFD_RELOC_MICROMIPS_JMP:
15140       return opcode == 0x3c && ELF_ST_IS_COMPRESSED (other);
15141     default:
15142       return FALSE;
15143     }
15144 }
15145
15146 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15147    to a symbol whose value plus addend is not aligned according to the
15148    ultimate (after linker relaxation) jump instruction's immediate field
15149    requirement, either to (1 << SHIFT), or, for jumps from microMIPS to
15150    regular MIPS code, to (1 << 2).  */
15151
15152 static bfd_boolean
15153 fix_bad_misaligned_jump_p (fixS *fixP, int shift)
15154 {
15155   bfd_boolean micro_to_mips_p;
15156   valueT val;
15157   int other;
15158
15159   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15160     return FALSE;
15161
15162   other = S_GET_OTHER (fixP->fx_addsy);
15163   val = S_GET_VALUE (fixP->fx_addsy) | ELF_ST_IS_COMPRESSED (other);
15164   val += fixP->fx_offset;
15165   micro_to_mips_p = (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15166                      && !ELF_ST_IS_MICROMIPS (other));
15167   return ((val & ((1 << (micro_to_mips_p ? 2 : shift)) - 1))
15168           != ELF_ST_IS_COMPRESSED (other));
15169 }
15170
15171 /* Return TRUE if the instruction pointed to by FIXP is an invalid branch
15172    to a symbol whose annotation indicates another ISA mode.  For absolute
15173    symbols check the ISA bit instead.
15174
15175    We accept BFD_RELOC_16_PCREL_S2 relocations against MIPS16 and microMIPS
15176    symbols or BFD_RELOC_MICROMIPS_16_PCREL_S1 relocations against regular
15177    MIPS symbols and associated with BAL instructions as these instructions
15178    may be be converted to JALX by the linker.  */
15179
15180 static bfd_boolean
15181 fix_bad_cross_mode_branch_p (fixS *fixP)
15182 {
15183   bfd_boolean absolute_p;
15184   unsigned long opcode;
15185   asection *symsec;
15186   valueT val;
15187   int other;
15188   char *buf;
15189
15190   if (mips_ignore_branch_isa)
15191     return FALSE;
15192
15193   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15194     return FALSE;
15195
15196   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15197   absolute_p = bfd_is_abs_section (symsec);
15198
15199   val = S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset;
15200   other = S_GET_OTHER (fixP->fx_addsy);
15201
15202   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15203   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 16;
15204   switch (fixP->fx_r_type)
15205     {
15206     case BFD_RELOC_16_PCREL_S2:
15207       return ((absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other))
15208               && opcode != 0x0411);
15209     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15210       return ((absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other))
15211               && opcode != 0x4060);
15212     case BFD_RELOC_MIPS_21_PCREL_S2:
15213     case BFD_RELOC_MIPS_26_PCREL_S2:
15214       return absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other);
15215     case BFD_RELOC_MIPS16_16_PCREL_S1:
15216       return absolute_p ? !(val & 1) : !ELF_ST_IS_MIPS16 (other);
15217     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15218     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15219       return absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other);
15220     default:
15221       abort ();
15222     }
15223 }
15224
15225 /* Return TRUE if the symbol plus addend associated with a regular MIPS
15226    branch instruction pointed to by FIXP is not aligned according to the
15227    branch instruction's immediate field requirement.  We need the addend
15228    to preserve the ISA bit and also the sum must not have bit 2 set.  We
15229    must explicitly OR in the ISA bit from symbol annotation as the bit
15230    won't be set in the symbol's value then.  */
15231
15232 static bfd_boolean
15233 fix_bad_misaligned_branch_p (fixS *fixP)
15234 {
15235   bfd_boolean absolute_p;
15236   asection *symsec;
15237   valueT isa_bit;
15238   valueT val;
15239   valueT off;
15240   int other;
15241
15242   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15243     return FALSE;
15244
15245   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15246   absolute_p = bfd_is_abs_section (symsec);
15247
15248   val = S_GET_VALUE (fixP->fx_addsy);
15249   other = S_GET_OTHER (fixP->fx_addsy);
15250   off = fixP->fx_offset;
15251
15252   isa_bit = absolute_p ? (val + off) & 1 : ELF_ST_IS_COMPRESSED (other);
15253   val |= ELF_ST_IS_COMPRESSED (other);
15254   val += off;
15255   return (val & 0x3) != isa_bit;
15256 }
15257
15258 /* Make the necessary checks on a regular MIPS branch pointed to by FIXP
15259    and its calculated value VAL.  */
15260
15261 static void
15262 fix_validate_branch (fixS *fixP, valueT val)
15263 {
15264   if (fixP->fx_done && (val & 0x3) != 0)
15265     as_bad_where (fixP->fx_file, fixP->fx_line,
15266                   _("branch to misaligned address (0x%lx)"),
15267                   (long) (val + md_pcrel_from (fixP)));
15268   else if (fix_bad_cross_mode_branch_p (fixP))
15269     as_bad_where (fixP->fx_file, fixP->fx_line,
15270                   _("branch to a symbol in another ISA mode"));
15271   else if (fix_bad_misaligned_branch_p (fixP))
15272     as_bad_where (fixP->fx_file, fixP->fx_line,
15273                   _("branch to misaligned address (0x%lx)"),
15274                   (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15275   else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x3) != 0)
15276     as_bad_where (fixP->fx_file, fixP->fx_line,
15277                   _("cannot encode misaligned addend "
15278                     "in the relocatable field (0x%lx)"),
15279                   (long) fixP->fx_offset);
15280 }
15281
15282 /* Apply a fixup to the object file.  */
15283
15284 void
15285 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15286 {
15287   char *buf;
15288   unsigned long insn;
15289   reloc_howto_type *howto;
15290
15291   if (fixP->fx_pcrel)
15292     switch (fixP->fx_r_type)
15293       {
15294       case BFD_RELOC_16_PCREL_S2:
15295       case BFD_RELOC_MIPS16_16_PCREL_S1:
15296       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15297       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15298       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15299       case BFD_RELOC_32_PCREL:
15300       case BFD_RELOC_MIPS_21_PCREL_S2:
15301       case BFD_RELOC_MIPS_26_PCREL_S2:
15302       case BFD_RELOC_MIPS_18_PCREL_S3:
15303       case BFD_RELOC_MIPS_19_PCREL_S2:
15304       case BFD_RELOC_HI16_S_PCREL:
15305       case BFD_RELOC_LO16_PCREL:
15306         break;
15307
15308       case BFD_RELOC_32:
15309         fixP->fx_r_type = BFD_RELOC_32_PCREL;
15310         break;
15311
15312       default:
15313         as_bad_where (fixP->fx_file, fixP->fx_line,
15314                       _("PC-relative reference to a different section"));
15315         break;
15316       }
15317
15318   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
15319      that have no MIPS ELF equivalent.  */
15320   if (fixP->fx_r_type != BFD_RELOC_8)
15321     {
15322       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15323       if (!howto)
15324         return;
15325     }
15326
15327   gas_assert (fixP->fx_size == 2
15328               || fixP->fx_size == 4
15329               || fixP->fx_r_type == BFD_RELOC_8
15330               || fixP->fx_r_type == BFD_RELOC_16
15331               || fixP->fx_r_type == BFD_RELOC_64
15332               || fixP->fx_r_type == BFD_RELOC_CTOR
15333               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15334               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15335               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15336               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15337               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64
15338               || fixP->fx_r_type == BFD_RELOC_NONE);
15339
15340   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15341
15342   /* Don't treat parts of a composite relocation as done.  There are two
15343      reasons for this:
15344
15345      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15346          should nevertheless be emitted if the first part is.
15347
15348      (2) In normal usage, composite relocations are never assembly-time
15349          constants.  The easiest way of dealing with the pathological
15350          exceptions is to generate a relocation against STN_UNDEF and
15351          leave everything up to the linker.  */
15352   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15353     fixP->fx_done = 1;
15354
15355   switch (fixP->fx_r_type)
15356     {
15357     case BFD_RELOC_MIPS_TLS_GD:
15358     case BFD_RELOC_MIPS_TLS_LDM:
15359     case BFD_RELOC_MIPS_TLS_DTPREL32:
15360     case BFD_RELOC_MIPS_TLS_DTPREL64:
15361     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15362     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15363     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15364     case BFD_RELOC_MIPS_TLS_TPREL32:
15365     case BFD_RELOC_MIPS_TLS_TPREL64:
15366     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15367     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15368     case BFD_RELOC_MICROMIPS_TLS_GD:
15369     case BFD_RELOC_MICROMIPS_TLS_LDM:
15370     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15371     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15372     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15373     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15374     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15375     case BFD_RELOC_MIPS16_TLS_GD:
15376     case BFD_RELOC_MIPS16_TLS_LDM:
15377     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15378     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15379     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15380     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15381     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15382       if (fixP->fx_addsy)
15383         S_SET_THREAD_LOCAL (fixP->fx_addsy);
15384       else
15385         as_bad_where (fixP->fx_file, fixP->fx_line,
15386                       _("TLS relocation against a constant"));
15387       break;
15388
15389     case BFD_RELOC_MIPS_JMP:
15390     case BFD_RELOC_MIPS16_JMP:
15391     case BFD_RELOC_MICROMIPS_JMP:
15392       {
15393         int shift;
15394
15395         gas_assert (!fixP->fx_done);
15396
15397         /* Shift is 2, unusually, for microMIPS JALX.  */
15398         if (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15399             && (read_compressed_insn (buf, 4) >> 26) != 0x3c)
15400           shift = 1;
15401         else
15402           shift = 2;
15403
15404         if (fix_bad_cross_mode_jump_p (fixP))
15405           as_bad_where (fixP->fx_file, fixP->fx_line,
15406                         _("jump to a symbol in another ISA mode"));
15407         else if (fix_bad_same_mode_jalx_p (fixP))
15408           as_bad_where (fixP->fx_file, fixP->fx_line,
15409                         _("JALX to a symbol in the same ISA mode"));
15410         else if (fix_bad_misaligned_jump_p (fixP, shift))
15411           as_bad_where (fixP->fx_file, fixP->fx_line,
15412                         _("jump to misaligned address (0x%lx)"),
15413                         (long) (S_GET_VALUE (fixP->fx_addsy)
15414                                 + fixP->fx_offset));
15415         else if (HAVE_IN_PLACE_ADDENDS
15416                  && (fixP->fx_offset & ((1 << shift) - 1)) != 0)
15417           as_bad_where (fixP->fx_file, fixP->fx_line,
15418                         _("cannot encode misaligned addend "
15419                           "in the relocatable field (0x%lx)"),
15420                         (long) fixP->fx_offset);
15421       }
15422       /* Fall through.  */
15423
15424     case BFD_RELOC_MIPS_SHIFT5:
15425     case BFD_RELOC_MIPS_SHIFT6:
15426     case BFD_RELOC_MIPS_GOT_DISP:
15427     case BFD_RELOC_MIPS_GOT_PAGE:
15428     case BFD_RELOC_MIPS_GOT_OFST:
15429     case BFD_RELOC_MIPS_SUB:
15430     case BFD_RELOC_MIPS_INSERT_A:
15431     case BFD_RELOC_MIPS_INSERT_B:
15432     case BFD_RELOC_MIPS_DELETE:
15433     case BFD_RELOC_MIPS_HIGHEST:
15434     case BFD_RELOC_MIPS_HIGHER:
15435     case BFD_RELOC_MIPS_SCN_DISP:
15436     case BFD_RELOC_MIPS_REL16:
15437     case BFD_RELOC_MIPS_RELGOT:
15438     case BFD_RELOC_MIPS_JALR:
15439     case BFD_RELOC_HI16:
15440     case BFD_RELOC_HI16_S:
15441     case BFD_RELOC_LO16:
15442     case BFD_RELOC_GPREL16:
15443     case BFD_RELOC_MIPS_LITERAL:
15444     case BFD_RELOC_MIPS_CALL16:
15445     case BFD_RELOC_MIPS_GOT16:
15446     case BFD_RELOC_GPREL32:
15447     case BFD_RELOC_MIPS_GOT_HI16:
15448     case BFD_RELOC_MIPS_GOT_LO16:
15449     case BFD_RELOC_MIPS_CALL_HI16:
15450     case BFD_RELOC_MIPS_CALL_LO16:
15451     case BFD_RELOC_HI16_S_PCREL:
15452     case BFD_RELOC_LO16_PCREL:
15453     case BFD_RELOC_MIPS16_GPREL:
15454     case BFD_RELOC_MIPS16_GOT16:
15455     case BFD_RELOC_MIPS16_CALL16:
15456     case BFD_RELOC_MIPS16_HI16:
15457     case BFD_RELOC_MIPS16_HI16_S:
15458     case BFD_RELOC_MIPS16_LO16:
15459     case BFD_RELOC_MICROMIPS_GOT_DISP:
15460     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15461     case BFD_RELOC_MICROMIPS_GOT_OFST:
15462     case BFD_RELOC_MICROMIPS_SUB:
15463     case BFD_RELOC_MICROMIPS_HIGHEST:
15464     case BFD_RELOC_MICROMIPS_HIGHER:
15465     case BFD_RELOC_MICROMIPS_SCN_DISP:
15466     case BFD_RELOC_MICROMIPS_JALR:
15467     case BFD_RELOC_MICROMIPS_HI16:
15468     case BFD_RELOC_MICROMIPS_HI16_S:
15469     case BFD_RELOC_MICROMIPS_LO16:
15470     case BFD_RELOC_MICROMIPS_GPREL16:
15471     case BFD_RELOC_MICROMIPS_LITERAL:
15472     case BFD_RELOC_MICROMIPS_CALL16:
15473     case BFD_RELOC_MICROMIPS_GOT16:
15474     case BFD_RELOC_MICROMIPS_GOT_HI16:
15475     case BFD_RELOC_MICROMIPS_GOT_LO16:
15476     case BFD_RELOC_MICROMIPS_CALL_HI16:
15477     case BFD_RELOC_MICROMIPS_CALL_LO16:
15478     case BFD_RELOC_MIPS_EH:
15479       if (fixP->fx_done)
15480         {
15481           offsetT value;
15482
15483           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15484             {
15485               insn = read_reloc_insn (buf, fixP->fx_r_type);
15486               if (mips16_reloc_p (fixP->fx_r_type))
15487                 insn |= mips16_immed_extend (value, 16);
15488               else
15489                 insn |= (value & 0xffff);
15490               write_reloc_insn (buf, fixP->fx_r_type, insn);
15491             }
15492           else
15493             as_bad_where (fixP->fx_file, fixP->fx_line,
15494                           _("unsupported constant in relocation"));
15495         }
15496       break;
15497
15498     case BFD_RELOC_64:
15499       /* This is handled like BFD_RELOC_32, but we output a sign
15500          extended value if we are only 32 bits.  */
15501       if (fixP->fx_done)
15502         {
15503           if (8 <= sizeof (valueT))
15504             md_number_to_chars (buf, *valP, 8);
15505           else
15506             {
15507               valueT hiv;
15508
15509               if ((*valP & 0x80000000) != 0)
15510                 hiv = 0xffffffff;
15511               else
15512                 hiv = 0;
15513               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
15514               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
15515             }
15516         }
15517       break;
15518
15519     case BFD_RELOC_RVA:
15520     case BFD_RELOC_32:
15521     case BFD_RELOC_32_PCREL:
15522     case BFD_RELOC_16:
15523     case BFD_RELOC_8:
15524       /* If we are deleting this reloc entry, we must fill in the
15525          value now.  This can happen if we have a .word which is not
15526          resolved when it appears but is later defined.  */
15527       if (fixP->fx_done)
15528         md_number_to_chars (buf, *valP, fixP->fx_size);
15529       break;
15530
15531     case BFD_RELOC_MIPS_21_PCREL_S2:
15532       fix_validate_branch (fixP, *valP);
15533       if (!fixP->fx_done)
15534         break;
15535
15536       if (*valP + 0x400000 <= 0x7fffff)
15537         {
15538           insn = read_insn (buf);
15539           insn |= (*valP >> 2) & 0x1fffff;
15540           write_insn (buf, insn);
15541         }
15542       else
15543         as_bad_where (fixP->fx_file, fixP->fx_line,
15544                       _("branch out of range"));
15545       break;
15546
15547     case BFD_RELOC_MIPS_26_PCREL_S2:
15548       fix_validate_branch (fixP, *valP);
15549       if (!fixP->fx_done)
15550         break;
15551
15552       if (*valP + 0x8000000 <= 0xfffffff)
15553         {
15554           insn = read_insn (buf);
15555           insn |= (*valP >> 2) & 0x3ffffff;
15556           write_insn (buf, insn);
15557         }
15558       else
15559         as_bad_where (fixP->fx_file, fixP->fx_line,
15560                       _("branch out of range"));
15561       break;
15562
15563     case BFD_RELOC_MIPS_18_PCREL_S3:
15564       if (fixP->fx_addsy && (S_GET_VALUE (fixP->fx_addsy) & 0x7) != 0)
15565         as_bad_where (fixP->fx_file, fixP->fx_line,
15566                       _("PC-relative access using misaligned symbol (%lx)"),
15567                       (long) S_GET_VALUE (fixP->fx_addsy));
15568       if ((fixP->fx_offset & 0x7) != 0)
15569         as_bad_where (fixP->fx_file, fixP->fx_line,
15570                       _("PC-relative access using misaligned offset (%lx)"),
15571                       (long) fixP->fx_offset);
15572       if (!fixP->fx_done)
15573         break;
15574
15575       if (*valP + 0x100000 <= 0x1fffff)
15576         {
15577           insn = read_insn (buf);
15578           insn |= (*valP >> 3) & 0x3ffff;
15579           write_insn (buf, insn);
15580         }
15581       else
15582         as_bad_where (fixP->fx_file, fixP->fx_line,
15583                       _("PC-relative access out of range"));
15584       break;
15585
15586     case BFD_RELOC_MIPS_19_PCREL_S2:
15587       if ((*valP & 0x3) != 0)
15588         as_bad_where (fixP->fx_file, fixP->fx_line,
15589                       _("PC-relative access to misaligned address (%lx)"),
15590                       (long) *valP);
15591       if (!fixP->fx_done)
15592         break;
15593
15594       if (*valP + 0x100000 <= 0x1fffff)
15595         {
15596           insn = read_insn (buf);
15597           insn |= (*valP >> 2) & 0x7ffff;
15598           write_insn (buf, insn);
15599         }
15600       else
15601         as_bad_where (fixP->fx_file, fixP->fx_line,
15602                       _("PC-relative access out of range"));
15603       break;
15604
15605     case BFD_RELOC_16_PCREL_S2:
15606       fix_validate_branch (fixP, *valP);
15607
15608       /* We need to save the bits in the instruction since fixup_segment()
15609          might be deleting the relocation entry (i.e., a branch within
15610          the current segment).  */
15611       if (! fixP->fx_done)
15612         break;
15613
15614       /* Update old instruction data.  */
15615       insn = read_insn (buf);
15616
15617       if (*valP + 0x20000 <= 0x3ffff)
15618         {
15619           insn |= (*valP >> 2) & 0xffff;
15620           write_insn (buf, insn);
15621         }
15622       else if (fixP->fx_tcbit2
15623                && fixP->fx_done
15624                && fixP->fx_frag->fr_address >= text_section->vma
15625                && (fixP->fx_frag->fr_address
15626                    < text_section->vma + bfd_get_section_size (text_section))
15627                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15628                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15629                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15630         {
15631           /* The branch offset is too large.  If this is an
15632              unconditional branch, and we are not generating PIC code,
15633              we can convert it to an absolute jump instruction.  */
15634           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15635             insn = 0x0c000000;  /* jal */
15636           else
15637             insn = 0x08000000;  /* j */
15638           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15639           fixP->fx_done = 0;
15640           fixP->fx_addsy = section_symbol (text_section);
15641           *valP += md_pcrel_from (fixP);
15642           write_insn (buf, insn);
15643         }
15644       else
15645         {
15646           /* If we got here, we have branch-relaxation disabled,
15647              and there's nothing we can do to fix this instruction
15648              without turning it into a longer sequence.  */
15649           as_bad_where (fixP->fx_file, fixP->fx_line,
15650                         _("branch out of range"));
15651         }
15652       break;
15653
15654     case BFD_RELOC_MIPS16_16_PCREL_S1:
15655     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15656     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15657     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15658       gas_assert (!fixP->fx_done);
15659       if (fix_bad_cross_mode_branch_p (fixP))
15660         as_bad_where (fixP->fx_file, fixP->fx_line,
15661                       _("branch to a symbol in another ISA mode"));
15662       else if (fixP->fx_addsy
15663                && !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
15664                && !bfd_is_abs_section (S_GET_SEGMENT (fixP->fx_addsy))
15665                && (fixP->fx_offset & 0x1) != 0)
15666         as_bad_where (fixP->fx_file, fixP->fx_line,
15667                       _("branch to misaligned address (0x%lx)"),
15668                       (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15669       else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x1) != 0)
15670         as_bad_where (fixP->fx_file, fixP->fx_line,
15671                       _("cannot encode misaligned addend "
15672                         "in the relocatable field (0x%lx)"),
15673                       (long) fixP->fx_offset);
15674       break;
15675
15676     case BFD_RELOC_VTABLE_INHERIT:
15677       fixP->fx_done = 0;
15678       if (fixP->fx_addsy
15679           && !S_IS_DEFINED (fixP->fx_addsy)
15680           && !S_IS_WEAK (fixP->fx_addsy))
15681         S_SET_WEAK (fixP->fx_addsy);
15682       break;
15683
15684     case BFD_RELOC_NONE:
15685     case BFD_RELOC_VTABLE_ENTRY:
15686       fixP->fx_done = 0;
15687       break;
15688
15689     default:
15690       abort ();
15691     }
15692
15693   /* Remember value for tc_gen_reloc.  */
15694   fixP->fx_addnumber = *valP;
15695 }
15696
15697 static symbolS *
15698 get_symbol (void)
15699 {
15700   int c;
15701   char *name;
15702   symbolS *p;
15703
15704   c = get_symbol_name (&name);
15705   p = (symbolS *) symbol_find_or_make (name);
15706   (void) restore_line_pointer (c);
15707   return p;
15708 }
15709
15710 /* Align the current frag to a given power of two.  If a particular
15711    fill byte should be used, FILL points to an integer that contains
15712    that byte, otherwise FILL is null.
15713
15714    This function used to have the comment:
15715
15716       The MIPS assembler also automatically adjusts any preceding label.
15717
15718    The implementation therefore applied the adjustment to a maximum of
15719    one label.  However, other label adjustments are applied to batches
15720    of labels, and adjusting just one caused problems when new labels
15721    were added for the sake of debugging or unwind information.
15722    We therefore adjust all preceding labels (given as LABELS) instead.  */
15723
15724 static void
15725 mips_align (int to, int *fill, struct insn_label_list *labels)
15726 {
15727   mips_emit_delays ();
15728   mips_record_compressed_mode ();
15729   if (fill == NULL && subseg_text_p (now_seg))
15730     frag_align_code (to, 0);
15731   else
15732     frag_align (to, fill ? *fill : 0, 0);
15733   record_alignment (now_seg, to);
15734   mips_move_labels (labels, FALSE);
15735 }
15736
15737 /* Align to a given power of two.  .align 0 turns off the automatic
15738    alignment used by the data creating pseudo-ops.  */
15739
15740 static void
15741 s_align (int x ATTRIBUTE_UNUSED)
15742 {
15743   int temp, fill_value, *fill_ptr;
15744   long max_alignment = 28;
15745
15746   /* o Note that the assembler pulls down any immediately preceding label
15747        to the aligned address.
15748      o It's not documented but auto alignment is reinstated by
15749        a .align pseudo instruction.
15750      o Note also that after auto alignment is turned off the mips assembler
15751        issues an error on attempt to assemble an improperly aligned data item.
15752        We don't.  */
15753
15754   temp = get_absolute_expression ();
15755   if (temp > max_alignment)
15756     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
15757   else if (temp < 0)
15758     {
15759       as_warn (_("alignment negative, 0 assumed"));
15760       temp = 0;
15761     }
15762   if (*input_line_pointer == ',')
15763     {
15764       ++input_line_pointer;
15765       fill_value = get_absolute_expression ();
15766       fill_ptr = &fill_value;
15767     }
15768   else
15769     fill_ptr = 0;
15770   if (temp)
15771     {
15772       segment_info_type *si = seg_info (now_seg);
15773       struct insn_label_list *l = si->label_list;
15774       /* Auto alignment should be switched on by next section change.  */
15775       auto_align = 1;
15776       mips_align (temp, fill_ptr, l);
15777     }
15778   else
15779     {
15780       auto_align = 0;
15781     }
15782
15783   demand_empty_rest_of_line ();
15784 }
15785
15786 static void
15787 s_change_sec (int sec)
15788 {
15789   segT seg;
15790
15791   /* The ELF backend needs to know that we are changing sections, so
15792      that .previous works correctly.  We could do something like check
15793      for an obj_section_change_hook macro, but that might be confusing
15794      as it would not be appropriate to use it in the section changing
15795      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15796      This should be cleaner, somehow.  */
15797   obj_elf_section_change_hook ();
15798
15799   mips_emit_delays ();
15800
15801   switch (sec)
15802     {
15803     case 't':
15804       s_text (0);
15805       break;
15806     case 'd':
15807       s_data (0);
15808       break;
15809     case 'b':
15810       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15811       demand_empty_rest_of_line ();
15812       break;
15813
15814     case 'r':
15815       seg = subseg_new (RDATA_SECTION_NAME,
15816                         (subsegT) get_absolute_expression ());
15817       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15818                                               | SEC_READONLY | SEC_RELOC
15819                                               | SEC_DATA));
15820       if (strncmp (TARGET_OS, "elf", 3) != 0)
15821         record_alignment (seg, 4);
15822       demand_empty_rest_of_line ();
15823       break;
15824
15825     case 's':
15826       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15827       bfd_set_section_flags (stdoutput, seg,
15828                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15829       if (strncmp (TARGET_OS, "elf", 3) != 0)
15830         record_alignment (seg, 4);
15831       demand_empty_rest_of_line ();
15832       break;
15833
15834     case 'B':
15835       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15836       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15837       if (strncmp (TARGET_OS, "elf", 3) != 0)
15838         record_alignment (seg, 4);
15839       demand_empty_rest_of_line ();
15840       break;
15841     }
15842
15843   auto_align = 1;
15844 }
15845
15846 void
15847 s_change_section (int ignore ATTRIBUTE_UNUSED)
15848 {
15849   char *saved_ilp;
15850   char *section_name;
15851   char c, endc;
15852   char next_c = 0;
15853   int section_type;
15854   int section_flag;
15855   int section_entry_size;
15856   int section_alignment;
15857
15858   saved_ilp = input_line_pointer;
15859   endc = get_symbol_name (&section_name);
15860   c = (endc == '"' ? input_line_pointer[1] : endc);
15861   if (c)
15862     next_c = input_line_pointer [(endc == '"' ? 2 : 1)];
15863
15864   /* Do we have .section Name<,"flags">?  */
15865   if (c != ',' || (c == ',' && next_c == '"'))
15866     {
15867       /* Just after name is now '\0'.  */
15868       (void) restore_line_pointer (endc);
15869       input_line_pointer = saved_ilp;
15870       obj_elf_section (ignore);
15871       return;
15872     }
15873
15874   section_name = xstrdup (section_name);
15875   c = restore_line_pointer (endc);
15876
15877   input_line_pointer++;
15878
15879   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
15880   if (c == ',')
15881     section_type = get_absolute_expression ();
15882   else
15883     section_type = 0;
15884
15885   if (*input_line_pointer++ == ',')
15886     section_flag = get_absolute_expression ();
15887   else
15888     section_flag = 0;
15889
15890   if (*input_line_pointer++ == ',')
15891     section_entry_size = get_absolute_expression ();
15892   else
15893     section_entry_size = 0;
15894
15895   if (*input_line_pointer++ == ',')
15896     section_alignment = get_absolute_expression ();
15897   else
15898     section_alignment = 0;
15899
15900   /* FIXME: really ignore?  */
15901   (void) section_alignment;
15902
15903   /* When using the generic form of .section (as implemented by obj-elf.c),
15904      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
15905      traditionally had to fall back on the more common @progbits instead.
15906
15907      There's nothing really harmful in this, since bfd will correct
15908      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
15909      means that, for backwards compatibility, the special_section entries
15910      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
15911
15912      Even so, we shouldn't force users of the MIPS .section syntax to
15913      incorrectly label the sections as SHT_PROGBITS.  The best compromise
15914      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
15915      generic type-checking code.  */
15916   if (section_type == SHT_MIPS_DWARF)
15917     section_type = SHT_PROGBITS;
15918
15919   obj_elf_change_section (section_name, section_type, 0, section_flag,
15920                           section_entry_size, 0, 0, 0);
15921
15922   if (now_seg->name != section_name)
15923     free (section_name);
15924 }
15925
15926 void
15927 mips_enable_auto_align (void)
15928 {
15929   auto_align = 1;
15930 }
15931
15932 static void
15933 s_cons (int log_size)
15934 {
15935   segment_info_type *si = seg_info (now_seg);
15936   struct insn_label_list *l = si->label_list;
15937
15938   mips_emit_delays ();
15939   if (log_size > 0 && auto_align)
15940     mips_align (log_size, 0, l);
15941   cons (1 << log_size);
15942   mips_clear_insn_labels ();
15943 }
15944
15945 static void
15946 s_float_cons (int type)
15947 {
15948   segment_info_type *si = seg_info (now_seg);
15949   struct insn_label_list *l = si->label_list;
15950
15951   mips_emit_delays ();
15952
15953   if (auto_align)
15954     {
15955       if (type == 'd')
15956         mips_align (3, 0, l);
15957       else
15958         mips_align (2, 0, l);
15959     }
15960
15961   float_cons (type);
15962   mips_clear_insn_labels ();
15963 }
15964
15965 /* Handle .globl.  We need to override it because on Irix 5 you are
15966    permitted to say
15967        .globl foo .text
15968    where foo is an undefined symbol, to mean that foo should be
15969    considered to be the address of a function.  */
15970
15971 static void
15972 s_mips_globl (int x ATTRIBUTE_UNUSED)
15973 {
15974   char *name;
15975   int c;
15976   symbolS *symbolP;
15977   flagword flag;
15978
15979   do
15980     {
15981       c = get_symbol_name (&name);
15982       symbolP = symbol_find_or_make (name);
15983       S_SET_EXTERNAL (symbolP);
15984
15985       *input_line_pointer = c;
15986       SKIP_WHITESPACE_AFTER_NAME ();
15987
15988       /* On Irix 5, every global symbol that is not explicitly labelled as
15989          being a function is apparently labelled as being an object.  */
15990       flag = BSF_OBJECT;
15991
15992       if (!is_end_of_line[(unsigned char) *input_line_pointer]
15993           && (*input_line_pointer != ','))
15994         {
15995           char *secname;
15996           asection *sec;
15997
15998           c = get_symbol_name (&secname);
15999           sec = bfd_get_section_by_name (stdoutput, secname);
16000           if (sec == NULL)
16001             as_bad (_("%s: no such section"), secname);
16002           (void) restore_line_pointer (c);
16003
16004           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16005             flag = BSF_FUNCTION;
16006         }
16007
16008       symbol_get_bfdsym (symbolP)->flags |= flag;
16009
16010       c = *input_line_pointer;
16011       if (c == ',')
16012         {
16013           input_line_pointer++;
16014           SKIP_WHITESPACE ();
16015           if (is_end_of_line[(unsigned char) *input_line_pointer])
16016             c = '\n';
16017         }
16018     }
16019   while (c == ',');
16020
16021   demand_empty_rest_of_line ();
16022 }
16023
16024 static void
16025 s_option (int x ATTRIBUTE_UNUSED)
16026 {
16027   char *opt;
16028   char c;
16029
16030   c = get_symbol_name (&opt);
16031
16032   if (*opt == 'O')
16033     {
16034       /* FIXME: What does this mean?  */
16035     }
16036   else if (strncmp (opt, "pic", 3) == 0 && ISDIGIT (opt[3]) && opt[4] == '\0')
16037     {
16038       int i;
16039
16040       i = atoi (opt + 3);
16041       if (i != 0 && i != 2)
16042         as_bad (_(".option pic%d not supported"), i);
16043       else if (mips_pic == VXWORKS_PIC)
16044         as_bad (_(".option pic%d not supported in VxWorks PIC mode"), i);
16045       else if (i == 0)
16046         mips_pic = NO_PIC;
16047       else if (i == 2)
16048         {
16049           mips_pic = SVR4_PIC;
16050           mips_abicalls = TRUE;
16051         }
16052
16053       if (mips_pic == SVR4_PIC)
16054         {
16055           if (g_switch_seen && g_switch_value != 0)
16056             as_warn (_("-G may not be used with SVR4 PIC code"));
16057           g_switch_value = 0;
16058           bfd_set_gp_size (stdoutput, 0);
16059         }
16060     }
16061   else
16062     as_warn (_("unrecognized option \"%s\""), opt);
16063
16064   (void) restore_line_pointer (c);
16065   demand_empty_rest_of_line ();
16066 }
16067
16068 /* This structure is used to hold a stack of .set values.  */
16069
16070 struct mips_option_stack
16071 {
16072   struct mips_option_stack *next;
16073   struct mips_set_options options;
16074 };
16075
16076 static struct mips_option_stack *mips_opts_stack;
16077
16078 /* Return status for .set/.module option handling.  */
16079
16080 enum code_option_type
16081 {
16082   /* Unrecognized option.  */
16083   OPTION_TYPE_BAD = -1,
16084
16085   /* Ordinary option.  */
16086   OPTION_TYPE_NORMAL,
16087
16088   /* ISA changing option.  */
16089   OPTION_TYPE_ISA
16090 };
16091
16092 /* Handle common .set/.module options.  Return status indicating option
16093    type.  */
16094
16095 static enum code_option_type
16096 parse_code_option (char * name)
16097 {
16098   bfd_boolean isa_set = FALSE;
16099   const struct mips_ase *ase;
16100
16101   if (strncmp (name, "at=", 3) == 0)
16102     {
16103       char *s = name + 3;
16104
16105       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16106         as_bad (_("unrecognized register name `%s'"), s);
16107     }
16108   else if (strcmp (name, "at") == 0)
16109     mips_opts.at = ATREG;
16110   else if (strcmp (name, "noat") == 0)
16111     mips_opts.at = ZERO;
16112   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16113     mips_opts.nomove = 0;
16114   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16115     mips_opts.nomove = 1;
16116   else if (strcmp (name, "bopt") == 0)
16117     mips_opts.nobopt = 0;
16118   else if (strcmp (name, "nobopt") == 0)
16119     mips_opts.nobopt = 1;
16120   else if (strcmp (name, "gp=32") == 0)
16121     mips_opts.gp = 32;
16122   else if (strcmp (name, "gp=64") == 0)
16123     mips_opts.gp = 64;
16124   else if (strcmp (name, "fp=32") == 0)
16125     mips_opts.fp = 32;
16126   else if (strcmp (name, "fp=xx") == 0)
16127     mips_opts.fp = 0;
16128   else if (strcmp (name, "fp=64") == 0)
16129     mips_opts.fp = 64;
16130   else if (strcmp (name, "softfloat") == 0)
16131     mips_opts.soft_float = 1;
16132   else if (strcmp (name, "hardfloat") == 0)
16133     mips_opts.soft_float = 0;
16134   else if (strcmp (name, "singlefloat") == 0)
16135     mips_opts.single_float = 1;
16136   else if (strcmp (name, "doublefloat") == 0)
16137     mips_opts.single_float = 0;
16138   else if (strcmp (name, "nooddspreg") == 0)
16139     mips_opts.oddspreg = 0;
16140   else if (strcmp (name, "oddspreg") == 0)
16141     mips_opts.oddspreg = 1;
16142   else if (strcmp (name, "mips16") == 0
16143            || strcmp (name, "MIPS-16") == 0)
16144     mips_opts.mips16 = 1;
16145   else if (strcmp (name, "nomips16") == 0
16146            || strcmp (name, "noMIPS-16") == 0)
16147     mips_opts.mips16 = 0;
16148   else if (strcmp (name, "micromips") == 0)
16149     mips_opts.micromips = 1;
16150   else if (strcmp (name, "nomicromips") == 0)
16151     mips_opts.micromips = 0;
16152   else if (name[0] == 'n'
16153            && name[1] == 'o'
16154            && (ase = mips_lookup_ase (name + 2)))
16155     mips_set_ase (ase, &mips_opts, FALSE);
16156   else if ((ase = mips_lookup_ase (name)))
16157     mips_set_ase (ase, &mips_opts, TRUE);
16158   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16159     {
16160       /* Permit the user to change the ISA and architecture on the fly.
16161          Needless to say, misuse can cause serious problems.  */
16162       if (strncmp (name, "arch=", 5) == 0)
16163         {
16164           const struct mips_cpu_info *p;
16165
16166           p = mips_parse_cpu ("internal use", name + 5);
16167           if (!p)
16168             as_bad (_("unknown architecture %s"), name + 5);
16169           else
16170             {
16171               mips_opts.arch = p->cpu;
16172               mips_opts.isa = p->isa;
16173               isa_set = TRUE;
16174             }
16175         }
16176       else if (strncmp (name, "mips", 4) == 0)
16177         {
16178           const struct mips_cpu_info *p;
16179
16180           p = mips_parse_cpu ("internal use", name);
16181           if (!p)
16182             as_bad (_("unknown ISA level %s"), name + 4);
16183           else
16184             {
16185               mips_opts.arch = p->cpu;
16186               mips_opts.isa = p->isa;
16187               isa_set = TRUE;
16188             }
16189         }
16190       else
16191         as_bad (_("unknown ISA or architecture %s"), name);
16192     }
16193   else if (strcmp (name, "autoextend") == 0)
16194     mips_opts.noautoextend = 0;
16195   else if (strcmp (name, "noautoextend") == 0)
16196     mips_opts.noautoextend = 1;
16197   else if (strcmp (name, "insn32") == 0)
16198     mips_opts.insn32 = TRUE;
16199   else if (strcmp (name, "noinsn32") == 0)
16200     mips_opts.insn32 = FALSE;
16201   else if (strcmp (name, "sym32") == 0)
16202     mips_opts.sym32 = TRUE;
16203   else if (strcmp (name, "nosym32") == 0)
16204     mips_opts.sym32 = FALSE;
16205   else
16206     return OPTION_TYPE_BAD;
16207
16208   return isa_set ? OPTION_TYPE_ISA : OPTION_TYPE_NORMAL;
16209 }
16210
16211 /* Handle the .set pseudo-op.  */
16212
16213 static void
16214 s_mipsset (int x ATTRIBUTE_UNUSED)
16215 {
16216   enum code_option_type type = OPTION_TYPE_NORMAL;
16217   char *name = input_line_pointer, ch;
16218
16219   file_mips_check_options ();
16220
16221   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16222     ++input_line_pointer;
16223   ch = *input_line_pointer;
16224   *input_line_pointer = '\0';
16225
16226   if (strchr (name, ','))
16227     {
16228       /* Generic ".set" directive; use the generic handler.  */
16229       *input_line_pointer = ch;
16230       input_line_pointer = name;
16231       s_set (0);
16232       return;
16233     }
16234
16235   if (strcmp (name, "reorder") == 0)
16236     {
16237       if (mips_opts.noreorder)
16238         end_noreorder ();
16239     }
16240   else if (strcmp (name, "noreorder") == 0)
16241     {
16242       if (!mips_opts.noreorder)
16243         start_noreorder ();
16244     }
16245   else if (strcmp (name, "macro") == 0)
16246     mips_opts.warn_about_macros = 0;
16247   else if (strcmp (name, "nomacro") == 0)
16248     {
16249       if (mips_opts.noreorder == 0)
16250         as_bad (_("`noreorder' must be set before `nomacro'"));
16251       mips_opts.warn_about_macros = 1;
16252     }
16253   else if (strcmp (name, "gp=default") == 0)
16254     mips_opts.gp = file_mips_opts.gp;
16255   else if (strcmp (name, "fp=default") == 0)
16256     mips_opts.fp = file_mips_opts.fp;
16257   else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16258     {
16259       mips_opts.isa = file_mips_opts.isa;
16260       mips_opts.arch = file_mips_opts.arch;
16261       mips_opts.gp = file_mips_opts.gp;
16262       mips_opts.fp = file_mips_opts.fp;
16263     }
16264   else if (strcmp (name, "push") == 0)
16265     {
16266       struct mips_option_stack *s;
16267
16268       s = XNEW (struct mips_option_stack);
16269       s->next = mips_opts_stack;
16270       s->options = mips_opts;
16271       mips_opts_stack = s;
16272     }
16273   else if (strcmp (name, "pop") == 0)
16274     {
16275       struct mips_option_stack *s;
16276
16277       s = mips_opts_stack;
16278       if (s == NULL)
16279         as_bad (_(".set pop with no .set push"));
16280       else
16281         {
16282           /* If we're changing the reorder mode we need to handle
16283              delay slots correctly.  */
16284           if (s->options.noreorder && ! mips_opts.noreorder)
16285             start_noreorder ();
16286           else if (! s->options.noreorder && mips_opts.noreorder)
16287             end_noreorder ();
16288
16289           mips_opts = s->options;
16290           mips_opts_stack = s->next;
16291           free (s);
16292         }
16293     }
16294   else
16295     {
16296       type = parse_code_option (name);
16297       if (type == OPTION_TYPE_BAD)
16298         as_warn (_("tried to set unrecognized symbol: %s\n"), name);
16299     }
16300
16301   /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
16302      registers based on what is supported by the arch/cpu.  */
16303   if (type == OPTION_TYPE_ISA)
16304     {
16305       switch (mips_opts.isa)
16306         {
16307         case 0:
16308           break;
16309         case ISA_MIPS1:
16310           /* MIPS I cannot support FPXX.  */
16311           mips_opts.fp = 32;
16312           /* fall-through.  */
16313         case ISA_MIPS2:
16314         case ISA_MIPS32:
16315         case ISA_MIPS32R2:
16316         case ISA_MIPS32R3:
16317         case ISA_MIPS32R5:
16318           mips_opts.gp = 32;
16319           if (mips_opts.fp != 0)
16320             mips_opts.fp = 32;
16321           break;
16322         case ISA_MIPS32R6:
16323           mips_opts.gp = 32;
16324           mips_opts.fp = 64;
16325           break;
16326         case ISA_MIPS3:
16327         case ISA_MIPS4:
16328         case ISA_MIPS5:
16329         case ISA_MIPS64:
16330         case ISA_MIPS64R2:
16331         case ISA_MIPS64R3:
16332         case ISA_MIPS64R5:
16333         case ISA_MIPS64R6:
16334           mips_opts.gp = 64;
16335           if (mips_opts.fp != 0)
16336             {
16337               if (mips_opts.arch == CPU_R5900)
16338                 mips_opts.fp = 32;
16339               else
16340                 mips_opts.fp = 64;
16341             }
16342           break;
16343         default:
16344           as_bad (_("unknown ISA level %s"), name + 4);
16345           break;
16346         }
16347     }
16348
16349   mips_check_options (&mips_opts, FALSE);
16350
16351   mips_check_isa_supports_ases ();
16352   *input_line_pointer = ch;
16353   demand_empty_rest_of_line ();
16354 }
16355
16356 /* Handle the .module pseudo-op.  */
16357
16358 static void
16359 s_module (int ignore ATTRIBUTE_UNUSED)
16360 {
16361   char *name = input_line_pointer, ch;
16362
16363   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16364     ++input_line_pointer;
16365   ch = *input_line_pointer;
16366   *input_line_pointer = '\0';
16367
16368   if (!file_mips_opts_checked)
16369     {
16370       if (parse_code_option (name) == OPTION_TYPE_BAD)
16371         as_bad (_(".module used with unrecognized symbol: %s\n"), name);
16372
16373       /* Update module level settings from mips_opts.  */
16374       file_mips_opts = mips_opts;
16375     }
16376   else
16377     as_bad (_(".module is not permitted after generating code"));
16378
16379   *input_line_pointer = ch;
16380   demand_empty_rest_of_line ();
16381 }
16382
16383 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16384    .option pic2.  It means to generate SVR4 PIC calls.  */
16385
16386 static void
16387 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16388 {
16389   mips_pic = SVR4_PIC;
16390   mips_abicalls = TRUE;
16391
16392   if (g_switch_seen && g_switch_value != 0)
16393     as_warn (_("-G may not be used with SVR4 PIC code"));
16394   g_switch_value = 0;
16395
16396   bfd_set_gp_size (stdoutput, 0);
16397   demand_empty_rest_of_line ();
16398 }
16399
16400 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16401    PIC code.  It sets the $gp register for the function based on the
16402    function address, which is in the register named in the argument.
16403    This uses a relocation against _gp_disp, which is handled specially
16404    by the linker.  The result is:
16405         lui     $gp,%hi(_gp_disp)
16406         addiu   $gp,$gp,%lo(_gp_disp)
16407         addu    $gp,$gp,.cpload argument
16408    The .cpload argument is normally $25 == $t9.
16409
16410    The -mno-shared option changes this to:
16411         lui     $gp,%hi(__gnu_local_gp)
16412         addiu   $gp,$gp,%lo(__gnu_local_gp)
16413    and the argument is ignored.  This saves an instruction, but the
16414    resulting code is not position independent; it uses an absolute
16415    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16416    can go into an ordinary executable, but not into a shared library.  */
16417
16418 static void
16419 s_cpload (int ignore ATTRIBUTE_UNUSED)
16420 {
16421   expressionS ex;
16422   int reg;
16423   int in_shared;
16424
16425   file_mips_check_options ();
16426
16427   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16428      .cpload is ignored.  */
16429   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16430     {
16431       s_ignore (0);
16432       return;
16433     }
16434
16435   if (mips_opts.mips16)
16436     {
16437       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16438       ignore_rest_of_line ();
16439       return;
16440     }
16441
16442   /* .cpload should be in a .set noreorder section.  */
16443   if (mips_opts.noreorder == 0)
16444     as_warn (_(".cpload not in noreorder section"));
16445
16446   reg = tc_get_register (0);
16447
16448   /* If we need to produce a 64-bit address, we are better off using
16449      the default instruction sequence.  */
16450   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16451
16452   ex.X_op = O_symbol;
16453   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16454                                          "__gnu_local_gp");
16455   ex.X_op_symbol = NULL;
16456   ex.X_add_number = 0;
16457
16458   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16459   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16460
16461   mips_mark_labels ();
16462   mips_assembling_insn = TRUE;
16463
16464   macro_start ();
16465   macro_build_lui (&ex, mips_gp_register);
16466   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16467                mips_gp_register, BFD_RELOC_LO16);
16468   if (in_shared)
16469     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16470                  mips_gp_register, reg);
16471   macro_end ();
16472
16473   mips_assembling_insn = FALSE;
16474   demand_empty_rest_of_line ();
16475 }
16476
16477 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16478      .cpsetup $reg1, offset|$reg2, label
16479
16480    If offset is given, this results in:
16481      sd         $gp, offset($sp)
16482      lui        $gp, %hi(%neg(%gp_rel(label)))
16483      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16484      daddu      $gp, $gp, $reg1
16485
16486    If $reg2 is given, this results in:
16487      or         $reg2, $gp, $0
16488      lui        $gp, %hi(%neg(%gp_rel(label)))
16489      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16490      daddu      $gp, $gp, $reg1
16491    $reg1 is normally $25 == $t9.
16492
16493    The -mno-shared option replaces the last three instructions with
16494         lui     $gp,%hi(_gp)
16495         addiu   $gp,$gp,%lo(_gp)  */
16496
16497 static void
16498 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16499 {
16500   expressionS ex_off;
16501   expressionS ex_sym;
16502   int reg1;
16503
16504   file_mips_check_options ();
16505
16506   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16507      We also need NewABI support.  */
16508   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16509     {
16510       s_ignore (0);
16511       return;
16512     }
16513
16514   if (mips_opts.mips16)
16515     {
16516       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16517       ignore_rest_of_line ();
16518       return;
16519     }
16520
16521   reg1 = tc_get_register (0);
16522   SKIP_WHITESPACE ();
16523   if (*input_line_pointer != ',')
16524     {
16525       as_bad (_("missing argument separator ',' for .cpsetup"));
16526       return;
16527     }
16528   else
16529     ++input_line_pointer;
16530   SKIP_WHITESPACE ();
16531   if (*input_line_pointer == '$')
16532     {
16533       mips_cpreturn_register = tc_get_register (0);
16534       mips_cpreturn_offset = -1;
16535     }
16536   else
16537     {
16538       mips_cpreturn_offset = get_absolute_expression ();
16539       mips_cpreturn_register = -1;
16540     }
16541   SKIP_WHITESPACE ();
16542   if (*input_line_pointer != ',')
16543     {
16544       as_bad (_("missing argument separator ',' for .cpsetup"));
16545       return;
16546     }
16547   else
16548     ++input_line_pointer;
16549   SKIP_WHITESPACE ();
16550   expression (&ex_sym);
16551
16552   mips_mark_labels ();
16553   mips_assembling_insn = TRUE;
16554
16555   macro_start ();
16556   if (mips_cpreturn_register == -1)
16557     {
16558       ex_off.X_op = O_constant;
16559       ex_off.X_add_symbol = NULL;
16560       ex_off.X_op_symbol = NULL;
16561       ex_off.X_add_number = mips_cpreturn_offset;
16562
16563       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16564                    BFD_RELOC_LO16, SP);
16565     }
16566   else
16567     move_register (mips_cpreturn_register, mips_gp_register);
16568
16569   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16570     {
16571       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16572                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16573                    BFD_RELOC_HI16_S);
16574
16575       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16576                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16577                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16578
16579       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16580                    mips_gp_register, reg1);
16581     }
16582   else
16583     {
16584       expressionS ex;
16585
16586       ex.X_op = O_symbol;
16587       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16588       ex.X_op_symbol = NULL;
16589       ex.X_add_number = 0;
16590
16591       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16592       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16593
16594       macro_build_lui (&ex, mips_gp_register);
16595       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16596                    mips_gp_register, BFD_RELOC_LO16);
16597     }
16598
16599   macro_end ();
16600
16601   mips_assembling_insn = FALSE;
16602   demand_empty_rest_of_line ();
16603 }
16604
16605 static void
16606 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16607 {
16608   file_mips_check_options ();
16609
16610   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16611      .cplocal is ignored.  */
16612   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16613     {
16614       s_ignore (0);
16615       return;
16616     }
16617
16618   if (mips_opts.mips16)
16619     {
16620       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16621       ignore_rest_of_line ();
16622       return;
16623     }
16624
16625   mips_gp_register = tc_get_register (0);
16626   demand_empty_rest_of_line ();
16627 }
16628
16629 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16630    offset from $sp.  The offset is remembered, and after making a PIC
16631    call $gp is restored from that location.  */
16632
16633 static void
16634 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16635 {
16636   expressionS ex;
16637
16638   file_mips_check_options ();
16639
16640   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16641      .cprestore is ignored.  */
16642   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16643     {
16644       s_ignore (0);
16645       return;
16646     }
16647
16648   if (mips_opts.mips16)
16649     {
16650       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
16651       ignore_rest_of_line ();
16652       return;
16653     }
16654
16655   mips_cprestore_offset = get_absolute_expression ();
16656   mips_cprestore_valid = 1;
16657
16658   ex.X_op = O_constant;
16659   ex.X_add_symbol = NULL;
16660   ex.X_op_symbol = NULL;
16661   ex.X_add_number = mips_cprestore_offset;
16662
16663   mips_mark_labels ();
16664   mips_assembling_insn = TRUE;
16665
16666   macro_start ();
16667   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16668                                 SP, HAVE_64BIT_ADDRESSES);
16669   macro_end ();
16670
16671   mips_assembling_insn = FALSE;
16672   demand_empty_rest_of_line ();
16673 }
16674
16675 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16676    was given in the preceding .cpsetup, it results in:
16677      ld         $gp, offset($sp)
16678
16679    If a register $reg2 was given there, it results in:
16680      or         $gp, $reg2, $0  */
16681
16682 static void
16683 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16684 {
16685   expressionS ex;
16686
16687   file_mips_check_options ();
16688
16689   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16690      We also need NewABI support.  */
16691   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16692     {
16693       s_ignore (0);
16694       return;
16695     }
16696
16697   if (mips_opts.mips16)
16698     {
16699       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
16700       ignore_rest_of_line ();
16701       return;
16702     }
16703
16704   mips_mark_labels ();
16705   mips_assembling_insn = TRUE;
16706
16707   macro_start ();
16708   if (mips_cpreturn_register == -1)
16709     {
16710       ex.X_op = O_constant;
16711       ex.X_add_symbol = NULL;
16712       ex.X_op_symbol = NULL;
16713       ex.X_add_number = mips_cpreturn_offset;
16714
16715       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16716     }
16717   else
16718     move_register (mips_gp_register, mips_cpreturn_register);
16719
16720   macro_end ();
16721
16722   mips_assembling_insn = FALSE;
16723   demand_empty_rest_of_line ();
16724 }
16725
16726 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16727    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16728    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16729    debug information or MIPS16 TLS.  */
16730
16731 static void
16732 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16733                      bfd_reloc_code_real_type rtype)
16734 {
16735   expressionS ex;
16736   char *p;
16737
16738   expression (&ex);
16739
16740   if (ex.X_op != O_symbol)
16741     {
16742       as_bad (_("unsupported use of %s"), dirstr);
16743       ignore_rest_of_line ();
16744     }
16745
16746   p = frag_more (bytes);
16747   md_number_to_chars (p, 0, bytes);
16748   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16749   demand_empty_rest_of_line ();
16750   mips_clear_insn_labels ();
16751 }
16752
16753 /* Handle .dtprelword.  */
16754
16755 static void
16756 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16757 {
16758   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16759 }
16760
16761 /* Handle .dtpreldword.  */
16762
16763 static void
16764 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16765 {
16766   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16767 }
16768
16769 /* Handle .tprelword.  */
16770
16771 static void
16772 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16773 {
16774   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16775 }
16776
16777 /* Handle .tpreldword.  */
16778
16779 static void
16780 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16781 {
16782   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16783 }
16784
16785 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16786    code.  It sets the offset to use in gp_rel relocations.  */
16787
16788 static void
16789 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16790 {
16791   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16792      We also need NewABI support.  */
16793   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16794     {
16795       s_ignore (0);
16796       return;
16797     }
16798
16799   mips_gprel_offset = get_absolute_expression ();
16800
16801   demand_empty_rest_of_line ();
16802 }
16803
16804 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16805    code.  It generates a 32 bit GP relative reloc.  */
16806
16807 static void
16808 s_gpword (int ignore ATTRIBUTE_UNUSED)
16809 {
16810   segment_info_type *si;
16811   struct insn_label_list *l;
16812   expressionS ex;
16813   char *p;
16814
16815   /* When not generating PIC code, this is treated as .word.  */
16816   if (mips_pic != SVR4_PIC)
16817     {
16818       s_cons (2);
16819       return;
16820     }
16821
16822   si = seg_info (now_seg);
16823   l = si->label_list;
16824   mips_emit_delays ();
16825   if (auto_align)
16826     mips_align (2, 0, l);
16827
16828   expression (&ex);
16829   mips_clear_insn_labels ();
16830
16831   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16832     {
16833       as_bad (_("unsupported use of .gpword"));
16834       ignore_rest_of_line ();
16835     }
16836
16837   p = frag_more (4);
16838   md_number_to_chars (p, 0, 4);
16839   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16840                BFD_RELOC_GPREL32);
16841
16842   demand_empty_rest_of_line ();
16843 }
16844
16845 static void
16846 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16847 {
16848   segment_info_type *si;
16849   struct insn_label_list *l;
16850   expressionS ex;
16851   char *p;
16852
16853   /* When not generating PIC code, this is treated as .dword.  */
16854   if (mips_pic != SVR4_PIC)
16855     {
16856       s_cons (3);
16857       return;
16858     }
16859
16860   si = seg_info (now_seg);
16861   l = si->label_list;
16862   mips_emit_delays ();
16863   if (auto_align)
16864     mips_align (3, 0, l);
16865
16866   expression (&ex);
16867   mips_clear_insn_labels ();
16868
16869   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16870     {
16871       as_bad (_("unsupported use of .gpdword"));
16872       ignore_rest_of_line ();
16873     }
16874
16875   p = frag_more (8);
16876   md_number_to_chars (p, 0, 8);
16877   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16878                BFD_RELOC_GPREL32)->fx_tcbit = 1;
16879
16880   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
16881   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
16882            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
16883
16884   demand_empty_rest_of_line ();
16885 }
16886
16887 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
16888    tables.  It generates a R_MIPS_EH reloc.  */
16889
16890 static void
16891 s_ehword (int ignore ATTRIBUTE_UNUSED)
16892 {
16893   expressionS ex;
16894   char *p;
16895
16896   mips_emit_delays ();
16897
16898   expression (&ex);
16899   mips_clear_insn_labels ();
16900
16901   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16902     {
16903       as_bad (_("unsupported use of .ehword"));
16904       ignore_rest_of_line ();
16905     }
16906
16907   p = frag_more (4);
16908   md_number_to_chars (p, 0, 4);
16909   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16910                BFD_RELOC_32_PCREL);
16911
16912   demand_empty_rest_of_line ();
16913 }
16914
16915 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
16916    tables in SVR4 PIC code.  */
16917
16918 static void
16919 s_cpadd (int ignore ATTRIBUTE_UNUSED)
16920 {
16921   int reg;
16922
16923   file_mips_check_options ();
16924
16925   /* This is ignored when not generating SVR4 PIC code.  */
16926   if (mips_pic != SVR4_PIC)
16927     {
16928       s_ignore (0);
16929       return;
16930     }
16931
16932   mips_mark_labels ();
16933   mips_assembling_insn = TRUE;
16934
16935   /* Add $gp to the register named as an argument.  */
16936   macro_start ();
16937   reg = tc_get_register (0);
16938   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
16939   macro_end ();
16940
16941   mips_assembling_insn = FALSE;
16942   demand_empty_rest_of_line ();
16943 }
16944
16945 /* Handle the .insn pseudo-op.  This marks instruction labels in
16946    mips16/micromips mode.  This permits the linker to handle them specially,
16947    such as generating jalx instructions when needed.  We also make
16948    them odd for the duration of the assembly, in order to generate the
16949    right sort of code.  We will make them even in the adjust_symtab
16950    routine, while leaving them marked.  This is convenient for the
16951    debugger and the disassembler.  The linker knows to make them odd
16952    again.  */
16953
16954 static void
16955 s_insn (int ignore ATTRIBUTE_UNUSED)
16956 {
16957   file_mips_check_options ();
16958   file_ase_mips16 |= mips_opts.mips16;
16959   file_ase_micromips |= mips_opts.micromips;
16960
16961   mips_mark_labels ();
16962
16963   demand_empty_rest_of_line ();
16964 }
16965
16966 /* Handle the .nan pseudo-op.  */
16967
16968 static void
16969 s_nan (int ignore ATTRIBUTE_UNUSED)
16970 {
16971   static const char str_legacy[] = "legacy";
16972   static const char str_2008[] = "2008";
16973   size_t i;
16974
16975   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
16976
16977   if (i == sizeof (str_2008) - 1
16978       && memcmp (input_line_pointer, str_2008, i) == 0)
16979     mips_nan2008 = 1;
16980   else if (i == sizeof (str_legacy) - 1
16981            && memcmp (input_line_pointer, str_legacy, i) == 0)
16982     {
16983       if (ISA_HAS_LEGACY_NAN (file_mips_opts.isa))
16984         mips_nan2008 = 0;
16985       else
16986         as_bad (_("`%s' does not support legacy NaN"),
16987                   mips_cpu_info_from_isa (file_mips_opts.isa)->name);
16988     }
16989   else
16990     as_bad (_("bad .nan directive"));
16991
16992   input_line_pointer += i;
16993   demand_empty_rest_of_line ();
16994 }
16995
16996 /* Handle a .stab[snd] directive.  Ideally these directives would be
16997    implemented in a transparent way, so that removing them would not
16998    have any effect on the generated instructions.  However, s_stab
16999    internally changes the section, so in practice we need to decide
17000    now whether the preceding label marks compressed code.  We do not
17001    support changing the compression mode of a label after a .stab*
17002    directive, such as in:
17003
17004    foo:
17005         .stabs ...
17006         .set mips16
17007
17008    so the current mode wins.  */
17009
17010 static void
17011 s_mips_stab (int type)
17012 {
17013   mips_mark_labels ();
17014   s_stab (type);
17015 }
17016
17017 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
17018
17019 static void
17020 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
17021 {
17022   char *name;
17023   int c;
17024   symbolS *symbolP;
17025   expressionS exp;
17026
17027   c = get_symbol_name (&name);
17028   symbolP = symbol_find_or_make (name);
17029   S_SET_WEAK (symbolP);
17030   *input_line_pointer = c;
17031
17032   SKIP_WHITESPACE_AFTER_NAME ();
17033
17034   if (! is_end_of_line[(unsigned char) *input_line_pointer])
17035     {
17036       if (S_IS_DEFINED (symbolP))
17037         {
17038           as_bad (_("ignoring attempt to redefine symbol %s"),
17039                   S_GET_NAME (symbolP));
17040           ignore_rest_of_line ();
17041           return;
17042         }
17043
17044       if (*input_line_pointer == ',')
17045         {
17046           ++input_line_pointer;
17047           SKIP_WHITESPACE ();
17048         }
17049
17050       expression (&exp);
17051       if (exp.X_op != O_symbol)
17052         {
17053           as_bad (_("bad .weakext directive"));
17054           ignore_rest_of_line ();
17055           return;
17056         }
17057       symbol_set_value_expression (symbolP, &exp);
17058     }
17059
17060   demand_empty_rest_of_line ();
17061 }
17062
17063 /* Parse a register string into a number.  Called from the ECOFF code
17064    to parse .frame.  The argument is non-zero if this is the frame
17065    register, so that we can record it in mips_frame_reg.  */
17066
17067 int
17068 tc_get_register (int frame)
17069 {
17070   unsigned int reg;
17071
17072   SKIP_WHITESPACE ();
17073   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17074     reg = 0;
17075   if (frame)
17076     {
17077       mips_frame_reg = reg != 0 ? reg : SP;
17078       mips_frame_reg_valid = 1;
17079       mips_cprestore_valid = 0;
17080     }
17081   return reg;
17082 }
17083
17084 valueT
17085 md_section_align (asection *seg, valueT addr)
17086 {
17087   int align = bfd_get_section_alignment (stdoutput, seg);
17088
17089   /* We don't need to align ELF sections to the full alignment.
17090      However, Irix 5 may prefer that we align them at least to a 16
17091      byte boundary.  We don't bother to align the sections if we
17092      are targeted for an embedded system.  */
17093   if (strncmp (TARGET_OS, "elf", 3) == 0)
17094     return addr;
17095   if (align > 4)
17096     align = 4;
17097
17098   return ((addr + (1 << align) - 1) & -(1 << align));
17099 }
17100
17101 /* Utility routine, called from above as well.  If called while the
17102    input file is still being read, it's only an approximation.  (For
17103    example, a symbol may later become defined which appeared to be
17104    undefined earlier.)  */
17105
17106 static int
17107 nopic_need_relax (symbolS *sym, int before_relaxing)
17108 {
17109   if (sym == 0)
17110     return 0;
17111
17112   if (g_switch_value > 0)
17113     {
17114       const char *symname;
17115       int change;
17116
17117       /* Find out whether this symbol can be referenced off the $gp
17118          register.  It can be if it is smaller than the -G size or if
17119          it is in the .sdata or .sbss section.  Certain symbols can
17120          not be referenced off the $gp, although it appears as though
17121          they can.  */
17122       symname = S_GET_NAME (sym);
17123       if (symname != (const char *) NULL
17124           && (strcmp (symname, "eprol") == 0
17125               || strcmp (symname, "etext") == 0
17126               || strcmp (symname, "_gp") == 0
17127               || strcmp (symname, "edata") == 0
17128               || strcmp (symname, "_fbss") == 0
17129               || strcmp (symname, "_fdata") == 0
17130               || strcmp (symname, "_ftext") == 0
17131               || strcmp (symname, "end") == 0
17132               || strcmp (symname, "_gp_disp") == 0))
17133         change = 1;
17134       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17135                && (0
17136 #ifndef NO_ECOFF_DEBUGGING
17137                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
17138                        && (symbol_get_obj (sym)->ecoff_extern_size
17139                            <= g_switch_value))
17140 #endif
17141                    /* We must defer this decision until after the whole
17142                       file has been read, since there might be a .extern
17143                       after the first use of this symbol.  */
17144                    || (before_relaxing
17145 #ifndef NO_ECOFF_DEBUGGING
17146                        && symbol_get_obj (sym)->ecoff_extern_size == 0
17147 #endif
17148                        && S_GET_VALUE (sym) == 0)
17149                    || (S_GET_VALUE (sym) != 0
17150                        && S_GET_VALUE (sym) <= g_switch_value)))
17151         change = 0;
17152       else
17153         {
17154           const char *segname;
17155
17156           segname = segment_name (S_GET_SEGMENT (sym));
17157           gas_assert (strcmp (segname, ".lit8") != 0
17158                   && strcmp (segname, ".lit4") != 0);
17159           change = (strcmp (segname, ".sdata") != 0
17160                     && strcmp (segname, ".sbss") != 0
17161                     && strncmp (segname, ".sdata.", 7) != 0
17162                     && strncmp (segname, ".sbss.", 6) != 0
17163                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
17164                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
17165         }
17166       return change;
17167     }
17168   else
17169     /* We are not optimizing for the $gp register.  */
17170     return 1;
17171 }
17172
17173
17174 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
17175
17176 static bfd_boolean
17177 pic_need_relax (symbolS *sym)
17178 {
17179   asection *symsec;
17180
17181   /* Handle the case of a symbol equated to another symbol.  */
17182   while (symbol_equated_reloc_p (sym))
17183     {
17184       symbolS *n;
17185
17186       /* It's possible to get a loop here in a badly written program.  */
17187       n = symbol_get_value_expression (sym)->X_add_symbol;
17188       if (n == sym)
17189         break;
17190       sym = n;
17191     }
17192
17193   if (symbol_section_p (sym))
17194     return TRUE;
17195
17196   symsec = S_GET_SEGMENT (sym);
17197
17198   /* This must duplicate the test in adjust_reloc_syms.  */
17199   return (!bfd_is_und_section (symsec)
17200           && !bfd_is_abs_section (symsec)
17201           && !bfd_is_com_section (symsec)
17202           /* A global or weak symbol is treated as external.  */
17203           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
17204 }
17205 \f
17206 /* Given a MIPS16 variant frag FRAGP and PC-relative operand PCREL_OP
17207    convert a section-relative value VAL to the equivalent PC-relative
17208    value.  */
17209
17210 static offsetT
17211 mips16_pcrel_val (fragS *fragp, const struct mips_pcrel_operand *pcrel_op,
17212                   offsetT val, long stretch)
17213 {
17214   fragS *sym_frag;
17215   addressT addr;
17216
17217   gas_assert (pcrel_op->root.root.type == OP_PCREL);
17218
17219   sym_frag = symbol_get_frag (fragp->fr_symbol);
17220
17221   /* If the relax_marker of the symbol fragment differs from the
17222      relax_marker of this fragment, we have not yet adjusted the
17223      symbol fragment fr_address.  We want to add in STRETCH in
17224      order to get a better estimate of the address.  This
17225      particularly matters because of the shift bits.  */
17226   if (stretch != 0 && sym_frag->relax_marker != fragp->relax_marker)
17227     {
17228       fragS *f;
17229
17230       /* Adjust stretch for any alignment frag.  Note that if have
17231          been expanding the earlier code, the symbol may be
17232          defined in what appears to be an earlier frag.  FIXME:
17233          This doesn't handle the fr_subtype field, which specifies
17234          a maximum number of bytes to skip when doing an
17235          alignment.  */
17236       for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17237         {
17238           if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17239             {
17240               if (stretch < 0)
17241                 stretch = -(-stretch & ~((1 << (int) f->fr_offset) - 1));
17242               else
17243                 stretch &= ~((1 << (int) f->fr_offset) - 1);
17244               if (stretch == 0)
17245                 break;
17246             }
17247         }
17248       if (f != NULL)
17249         val += stretch;
17250     }
17251
17252   addr = fragp->fr_address + fragp->fr_fix;
17253
17254   /* The base address rules are complicated.  The base address of
17255      a branch is the following instruction.  The base address of a
17256      PC relative load or add is the instruction itself, but if it
17257      is in a delay slot (in which case it can not be extended) use
17258      the address of the instruction whose delay slot it is in.  */
17259   if (pcrel_op->include_isa_bit)
17260     {
17261       addr += 2;
17262
17263       /* If we are currently assuming that this frag should be
17264          extended, then the current address is two bytes higher.  */
17265       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17266         addr += 2;
17267
17268       /* Ignore the low bit in the target, since it will be set
17269          for a text label.  */
17270       val &= -2;
17271     }
17272   else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17273     addr -= 4;
17274   else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17275     addr -= 2;
17276
17277   val -= addr & -(1 << pcrel_op->align_log2);
17278
17279   return val;
17280 }
17281
17282 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17283    extended opcode.  SEC is the section the frag is in.  */
17284
17285 static int
17286 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17287 {
17288   const struct mips_int_operand *operand;
17289   offsetT val;
17290   segT symsec;
17291   int type;
17292
17293   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17294     return 0;
17295   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17296     return 1;
17297
17298   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17299   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17300   operand = mips16_immed_operand (type, FALSE);
17301   if (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
17302       || (operand->root.type == OP_PCREL
17303           ? sec != symsec
17304           : !bfd_is_abs_section (symsec)))
17305     return 1;
17306
17307   val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17308
17309   if (operand->root.type == OP_PCREL)
17310     {
17311       const struct mips_pcrel_operand *pcrel_op;
17312       offsetT maxtiny;
17313
17314       if (RELAX_MIPS16_ALWAYS_EXTENDED (fragp->fr_subtype))
17315         return 1;
17316
17317       pcrel_op = (const struct mips_pcrel_operand *) operand;
17318       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17319
17320       /* If any of the shifted bits are set, we must use an extended
17321          opcode.  If the address depends on the size of this
17322          instruction, this can lead to a loop, so we arrange to always
17323          use an extended opcode.  */
17324       if ((val & ((1 << operand->shift) - 1)) != 0)
17325         {
17326           fragp->fr_subtype =
17327             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17328           return 1;
17329         }
17330
17331       /* If we are about to mark a frag as extended because the value
17332          is precisely the next value above maxtiny, then there is a
17333          chance of an infinite loop as in the following code:
17334              la $4,foo
17335              .skip      1020
17336              .align     2
17337            foo:
17338          In this case when the la is extended, foo is 0x3fc bytes
17339          away, so the la can be shrunk, but then foo is 0x400 away, so
17340          the la must be extended.  To avoid this loop, we mark the
17341          frag as extended if it was small, and is about to become
17342          extended with the next value above maxtiny.  */
17343       maxtiny = mips_int_operand_max (operand);
17344       if (val == maxtiny + (1 << operand->shift)
17345           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17346         {
17347           fragp->fr_subtype =
17348             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17349           return 1;
17350         }
17351     }
17352
17353   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17354 }
17355
17356 /* Given a MIPS16 variant frag FRAGP, return non-zero if it needs
17357    macro expansion.  SEC is the section the frag is in.  We only
17358    support PC-relative instructions (LA, DLA, LW, LD) here, in
17359    non-PIC code using 32-bit addressing.  */
17360
17361 static int
17362 mips16_macro_frag (fragS *fragp, asection *sec, long stretch)
17363 {
17364   const struct mips_pcrel_operand *pcrel_op;
17365   const struct mips_int_operand *operand;
17366   offsetT val;
17367   segT symsec;
17368   int type;
17369
17370   gas_assert (!RELAX_MIPS16_USER_SMALL (fragp->fr_subtype));
17371
17372   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17373     return 0;
17374   if (!RELAX_MIPS16_SYM32 (fragp->fr_subtype))
17375     return 0;
17376
17377   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17378   switch (type)
17379     {
17380     case 'A':
17381     case 'B':
17382     case 'E':
17383       symsec = S_GET_SEGMENT (fragp->fr_symbol);
17384       if (bfd_is_abs_section (symsec))
17385         return 1;
17386       if (RELAX_MIPS16_PIC (fragp->fr_subtype))
17387         return 0;
17388       if (S_FORCE_RELOC (fragp->fr_symbol, TRUE) || sec != symsec)
17389         return 1;
17390
17391       operand = mips16_immed_operand (type, TRUE);
17392       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17393       pcrel_op = (const struct mips_pcrel_operand *) operand;
17394       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17395
17396       return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17397
17398     default:
17399       return 0;
17400     }
17401 }
17402
17403 /* Compute the length of a branch sequence, and adjust the
17404    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17405    worst-case length is computed, with UPDATE being used to indicate
17406    whether an unconditional (-1), branch-likely (+1) or regular (0)
17407    branch is to be computed.  */
17408 static int
17409 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17410 {
17411   bfd_boolean toofar;
17412   int length;
17413
17414   if (fragp
17415       && S_IS_DEFINED (fragp->fr_symbol)
17416       && !S_IS_WEAK (fragp->fr_symbol)
17417       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17418     {
17419       addressT addr;
17420       offsetT val;
17421
17422       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17423
17424       addr = fragp->fr_address + fragp->fr_fix + 4;
17425
17426       val -= addr;
17427
17428       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17429     }
17430   else
17431     /* If the symbol is not defined or it's in a different segment,
17432        we emit the long sequence.  */
17433     toofar = TRUE;
17434
17435   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17436     fragp->fr_subtype
17437       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17438                              RELAX_BRANCH_PIC (fragp->fr_subtype),
17439                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17440                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17441                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17442                              toofar);
17443
17444   length = 4;
17445   if (toofar)
17446     {
17447       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17448         length += 8;
17449
17450       if (!fragp || RELAX_BRANCH_PIC (fragp->fr_subtype))
17451         {
17452           /* Additional space for PIC loading of target address.  */
17453           length += 8;
17454           if (mips_opts.isa == ISA_MIPS1)
17455             /* Additional space for $at-stabilizing nop.  */
17456             length += 4;
17457         }
17458
17459       /* If branch is conditional.  */
17460       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17461         length += 8;
17462     }
17463
17464   return length;
17465 }
17466
17467 /* Get a FRAG's branch instruction delay slot size, either from the
17468    short-delay-slot bit of a branch-and-link instruction if AL is TRUE,
17469    or SHORT_INSN_SIZE otherwise.  */
17470
17471 static int
17472 frag_branch_delay_slot_size (fragS *fragp, bfd_boolean al, int short_insn_size)
17473 {
17474   char *buf = fragp->fr_literal + fragp->fr_fix;
17475
17476   if (al)
17477     return (read_compressed_insn (buf, 4) & 0x02000000) ? 2 : 4;
17478   else
17479     return short_insn_size;
17480 }
17481
17482 /* Compute the length of a branch sequence, and adjust the
17483    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17484    worst-case length is computed, with UPDATE being used to indicate
17485    whether an unconditional (-1), or regular (0) branch is to be
17486    computed.  */
17487
17488 static int
17489 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17490 {
17491   bfd_boolean insn32 = TRUE;
17492   bfd_boolean nods = TRUE;
17493   bfd_boolean pic = TRUE;
17494   bfd_boolean al = TRUE;
17495   int short_insn_size;
17496   bfd_boolean toofar;
17497   int length;
17498
17499   if (fragp)
17500     {
17501       insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
17502       nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
17503       pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
17504       al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17505     }
17506   short_insn_size = insn32 ? 4 : 2;
17507
17508   if (fragp
17509       && S_IS_DEFINED (fragp->fr_symbol)
17510       && !S_IS_WEAK (fragp->fr_symbol)
17511       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17512     {
17513       addressT addr;
17514       offsetT val;
17515
17516       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17517       /* Ignore the low bit in the target, since it will be set
17518          for a text label.  */
17519       if ((val & 1) != 0)
17520         --val;
17521
17522       addr = fragp->fr_address + fragp->fr_fix + 4;
17523
17524       val -= addr;
17525
17526       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17527     }
17528   else
17529     /* If the symbol is not defined or it's in a different segment,
17530        we emit the long sequence.  */
17531     toofar = TRUE;
17532
17533   if (fragp && update
17534       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17535     fragp->fr_subtype = (toofar
17536                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17537                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17538
17539   length = 4;
17540   if (toofar)
17541     {
17542       bfd_boolean compact_known = fragp != NULL;
17543       bfd_boolean compact = FALSE;
17544       bfd_boolean uncond;
17545
17546       if (fragp)
17547         {
17548           compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17549           uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17550         }
17551       else
17552         uncond = update < 0;
17553
17554       /* If label is out of range, we turn branch <br>:
17555
17556                 <br>    label                   # 4 bytes
17557             0:
17558
17559          into:
17560
17561                 j       label                   # 4 bytes
17562                 nop                             # 2/4 bytes if
17563                                                 #  compact && (!PIC || insn32)
17564             0:
17565        */
17566       if ((!pic || insn32) && (!compact_known || compact))
17567         length += short_insn_size;
17568
17569       /* If assembling PIC code, we further turn:
17570
17571                         j       label                   # 4 bytes
17572
17573          into:
17574
17575                         lw/ld   at, %got(label)(gp)     # 4 bytes
17576                         d/addiu at, %lo(label)          # 4 bytes
17577                         jr/c    at                      # 2/4 bytes
17578        */
17579       if (pic)
17580         length += 4 + short_insn_size;
17581
17582       /* Add an extra nop if the jump has no compact form and we need
17583          to fill the delay slot.  */
17584       if ((!pic || al) && nods)
17585         length += (fragp
17586                    ? frag_branch_delay_slot_size (fragp, al, short_insn_size)
17587                    : short_insn_size);
17588
17589       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17590
17591                         <brneg> 0f                      # 4 bytes
17592                         nop                             # 2/4 bytes if !compact
17593        */
17594       if (!uncond)
17595         length += (compact_known && compact) ? 4 : 4 + short_insn_size;
17596     }
17597   else if (nods)
17598     {
17599       /* Add an extra nop to fill the delay slot.  */
17600       gas_assert (fragp);
17601       length += frag_branch_delay_slot_size (fragp, al, short_insn_size);
17602     }
17603
17604   return length;
17605 }
17606
17607 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17608    bit accordingly.  */
17609
17610 static int
17611 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17612 {
17613   bfd_boolean toofar;
17614
17615   if (fragp
17616       && S_IS_DEFINED (fragp->fr_symbol)
17617       && !S_IS_WEAK (fragp->fr_symbol)
17618       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17619     {
17620       addressT addr;
17621       offsetT val;
17622       int type;
17623
17624       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17625       /* Ignore the low bit in the target, since it will be set
17626          for a text label.  */
17627       if ((val & 1) != 0)
17628         --val;
17629
17630       /* Assume this is a 2-byte branch.  */
17631       addr = fragp->fr_address + fragp->fr_fix + 2;
17632
17633       /* We try to avoid the infinite loop by not adding 2 more bytes for
17634          long branches.  */
17635
17636       val -= addr;
17637
17638       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17639       if (type == 'D')
17640         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17641       else if (type == 'E')
17642         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17643       else
17644         abort ();
17645     }
17646   else
17647     /* If the symbol is not defined or it's in a different segment,
17648        we emit a normal 32-bit branch.  */
17649     toofar = TRUE;
17650
17651   if (fragp && update
17652       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17653     fragp->fr_subtype
17654       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17655                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17656
17657   if (toofar)
17658     return 4;
17659
17660   return 2;
17661 }
17662
17663 /* Estimate the size of a frag before relaxing.  Unless this is the
17664    mips16, we are not really relaxing here, and the final size is
17665    encoded in the subtype information.  For the mips16, we have to
17666    decide whether we are using an extended opcode or not.  */
17667
17668 int
17669 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17670 {
17671   int change;
17672
17673   if (RELAX_BRANCH_P (fragp->fr_subtype))
17674     {
17675
17676       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17677
17678       return fragp->fr_var;
17679     }
17680
17681   if (RELAX_MIPS16_P (fragp->fr_subtype))
17682     {
17683       /* We don't want to modify the EXTENDED bit here; it might get us
17684          into infinite loops.  We change it only in mips_relax_frag().  */
17685       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17686         return 12;
17687       else
17688         return RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2;
17689     }
17690
17691   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17692     {
17693       int length = 4;
17694
17695       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17696         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17697       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17698         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17699       fragp->fr_var = length;
17700
17701       return length;
17702     }
17703
17704   if (mips_pic == VXWORKS_PIC)
17705     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17706     change = 0;
17707   else if (RELAX_PIC (fragp->fr_subtype))
17708     change = pic_need_relax (fragp->fr_symbol);
17709   else
17710     change = nopic_need_relax (fragp->fr_symbol, 0);
17711
17712   if (change)
17713     {
17714       fragp->fr_subtype |= RELAX_USE_SECOND;
17715       return -RELAX_FIRST (fragp->fr_subtype);
17716     }
17717   else
17718     return -RELAX_SECOND (fragp->fr_subtype);
17719 }
17720
17721 /* This is called to see whether a reloc against a defined symbol
17722    should be converted into a reloc against a section.  */
17723
17724 int
17725 mips_fix_adjustable (fixS *fixp)
17726 {
17727   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17728       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17729     return 0;
17730
17731   if (fixp->fx_addsy == NULL)
17732     return 1;
17733
17734   /* Allow relocs used for EH tables.  */
17735   if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
17736     return 1;
17737
17738   /* If symbol SYM is in a mergeable section, relocations of the form
17739      SYM + 0 can usually be made section-relative.  The mergeable data
17740      is then identified by the section offset rather than by the symbol.
17741
17742      However, if we're generating REL LO16 relocations, the offset is split
17743      between the LO16 and partnering high part relocation.  The linker will
17744      need to recalculate the complete offset in order to correctly identify
17745      the merge data.
17746
17747      The linker has traditionally not looked for the partnering high part
17748      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17749      placed anywhere.  Rather than break backwards compatibility by changing
17750      this, it seems better not to force the issue, and instead keep the
17751      original symbol.  This will work with either linker behavior.  */
17752   if ((lo16_reloc_p (fixp->fx_r_type)
17753        || reloc_needs_lo_p (fixp->fx_r_type))
17754       && HAVE_IN_PLACE_ADDENDS
17755       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17756     return 0;
17757
17758   /* There is no place to store an in-place offset for JALR relocations.  */
17759   if (jalr_reloc_p (fixp->fx_r_type) && HAVE_IN_PLACE_ADDENDS)
17760     return 0;
17761
17762   /* Likewise an in-range offset of limited PC-relative relocations may
17763      overflow the in-place relocatable field if recalculated against the
17764      start address of the symbol's containing section.
17765
17766      Also, PC relative relocations for MIPS R6 need to be symbol rather than
17767      section relative to allow linker relaxations to be performed later on.  */
17768   if (limited_pcrel_reloc_p (fixp->fx_r_type)
17769       && (HAVE_IN_PLACE_ADDENDS || ISA_IS_R6 (file_mips_opts.isa)))
17770     return 0;
17771
17772   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17773      to a floating-point stub.  The same is true for non-R_MIPS16_26
17774      relocations against MIPS16 functions; in this case, the stub becomes
17775      the function's canonical address.
17776
17777      Floating-point stubs are stored in unique .mips16.call.* or
17778      .mips16.fn.* sections.  If a stub T for function F is in section S,
17779      the first relocation in section S must be against F; this is how the
17780      linker determines the target function.  All relocations that might
17781      resolve to T must also be against F.  We therefore have the following
17782      restrictions, which are given in an intentionally-redundant way:
17783
17784        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17785           symbols.
17786
17787        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17788           if that stub might be used.
17789
17790        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17791           symbols.
17792
17793        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17794           that stub might be used.
17795
17796      There is a further restriction:
17797
17798        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17799           R_MICROMIPS_26_S1) or branch relocations (R_MIPS_PC26_S2,
17800           R_MIPS_PC21_S2, R_MIPS_PC16, R_MIPS16_PC16_S1,
17801           R_MICROMIPS_PC16_S1, R_MICROMIPS_PC10_S1 or R_MICROMIPS_PC7_S1)
17802           against MIPS16 or microMIPS symbols because we need to keep the
17803           MIPS16 or microMIPS symbol for the purpose of mode mismatch
17804           detection and JAL or BAL to JALX instruction conversion in the
17805           linker.
17806
17807      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17808      against a MIPS16 symbol.  We deal with (5) by additionally leaving
17809      alone any jump and branch relocations against a microMIPS symbol.
17810
17811      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17812      relocation against some symbol R, no relocation against R may be
17813      reduced.  (Note that this deals with (2) as well as (1) because
17814      relocations against global symbols will never be reduced on ELF
17815      targets.)  This approach is a little simpler than trying to detect
17816      stub sections, and gives the "all or nothing" per-symbol consistency
17817      that we have for MIPS16 symbols.  */
17818   if (fixp->fx_subsy == NULL
17819       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17820           || (ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17821               && (jmp_reloc_p (fixp->fx_r_type)
17822                   || b_reloc_p (fixp->fx_r_type)))
17823           || *symbol_get_tc (fixp->fx_addsy)))
17824     return 0;
17825
17826   return 1;
17827 }
17828
17829 /* Translate internal representation of relocation info to BFD target
17830    format.  */
17831
17832 arelent **
17833 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17834 {
17835   static arelent *retval[4];
17836   arelent *reloc;
17837   bfd_reloc_code_real_type code;
17838
17839   memset (retval, 0, sizeof(retval));
17840   reloc = retval[0] = XCNEW (arelent);
17841   reloc->sym_ptr_ptr = XNEW (asymbol *);
17842   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17843   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17844
17845   if (fixp->fx_pcrel)
17846     {
17847       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17848                   || fixp->fx_r_type == BFD_RELOC_MIPS16_16_PCREL_S1
17849                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17850                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17851                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
17852                   || fixp->fx_r_type == BFD_RELOC_32_PCREL
17853                   || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
17854                   || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
17855                   || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
17856                   || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
17857                   || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
17858                   || fixp->fx_r_type == BFD_RELOC_LO16_PCREL);
17859
17860       /* At this point, fx_addnumber is "symbol offset - pcrel address".
17861          Relocations want only the symbol offset.  */
17862       switch (fixp->fx_r_type)
17863         {
17864         case BFD_RELOC_MIPS_18_PCREL_S3:
17865           reloc->addend = fixp->fx_addnumber + (reloc->address & ~7);
17866           break;
17867         default:
17868           reloc->addend = fixp->fx_addnumber + reloc->address;
17869           break;
17870         }
17871     }
17872   else if (HAVE_IN_PLACE_ADDENDS
17873            && fixp->fx_r_type == BFD_RELOC_MICROMIPS_JMP
17874            && (read_compressed_insn (fixp->fx_frag->fr_literal
17875                                      + fixp->fx_where, 4) >> 26) == 0x3c)
17876     {
17877       /* Shift is 2, unusually, for microMIPS JALX.  Adjust the in-place
17878          addend accordingly.  */
17879       reloc->addend = fixp->fx_addnumber >> 1;
17880     }
17881   else
17882     reloc->addend = fixp->fx_addnumber;
17883
17884   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
17885      entry to be used in the relocation's section offset.  */
17886   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17887     {
17888       reloc->address = reloc->addend;
17889       reloc->addend = 0;
17890     }
17891
17892   code = fixp->fx_r_type;
17893
17894   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
17895   if (reloc->howto == NULL)
17896     {
17897       as_bad_where (fixp->fx_file, fixp->fx_line,
17898                     _("cannot represent %s relocation in this object file"
17899                       " format"),
17900                     bfd_get_reloc_code_name (code));
17901       retval[0] = NULL;
17902     }
17903
17904   return retval;
17905 }
17906
17907 /* Relax a machine dependent frag.  This returns the amount by which
17908    the current size of the frag should change.  */
17909
17910 int
17911 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
17912 {
17913   if (RELAX_BRANCH_P (fragp->fr_subtype))
17914     {
17915       offsetT old_var = fragp->fr_var;
17916
17917       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
17918
17919       return fragp->fr_var - old_var;
17920     }
17921
17922   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17923     {
17924       offsetT old_var = fragp->fr_var;
17925       offsetT new_var = 4;
17926
17927       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17928         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
17929       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17930         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
17931       fragp->fr_var = new_var;
17932
17933       return new_var - old_var;
17934     }
17935
17936   if (! RELAX_MIPS16_P (fragp->fr_subtype))
17937     return 0;
17938
17939   if (!mips16_extended_frag (fragp, sec, stretch))
17940     {
17941       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17942         {
17943           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
17944           return -10;
17945         }
17946       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17947         {
17948           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17949           return -2;
17950         }
17951       else
17952         return 0;
17953     }
17954   else if (!mips16_macro_frag (fragp, sec, stretch))
17955     {
17956       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17957         {
17958           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
17959           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17960           return -8;
17961         }
17962       else if (!RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17963         {
17964           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17965           return 2;
17966         }
17967       else
17968         return 0;
17969     }
17970   else
17971     {
17972       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17973         return 0;
17974       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17975         {
17976           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17977           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
17978           return 8;
17979         }
17980       else
17981         {
17982           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
17983           return 10;
17984         }
17985     }
17986
17987   return 0;
17988 }
17989
17990 /* Convert a machine dependent frag.  */
17991
17992 void
17993 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
17994 {
17995   if (RELAX_BRANCH_P (fragp->fr_subtype))
17996     {
17997       char *buf;
17998       unsigned long insn;
17999       expressionS exp;
18000       fixS *fixp;
18001
18002       buf = fragp->fr_literal + fragp->fr_fix;
18003       insn = read_insn (buf);
18004
18005       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18006         {
18007           /* We generate a fixup instead of applying it right now
18008              because, if there are linker relaxations, we're going to
18009              need the relocations.  */
18010           exp.X_op = O_symbol;
18011           exp.X_add_symbol = fragp->fr_symbol;
18012           exp.X_add_number = fragp->fr_offset;
18013
18014           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18015                               BFD_RELOC_16_PCREL_S2);
18016           fixp->fx_file = fragp->fr_file;
18017           fixp->fx_line = fragp->fr_line;
18018
18019           buf = write_insn (buf, insn);
18020         }
18021       else
18022         {
18023           int i;
18024
18025           as_warn_where (fragp->fr_file, fragp->fr_line,
18026                          _("relaxed out-of-range branch into a jump"));
18027
18028           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
18029             goto uncond;
18030
18031           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18032             {
18033               /* Reverse the branch.  */
18034               switch ((insn >> 28) & 0xf)
18035                 {
18036                 case 4:
18037                   if ((insn & 0xff000000) == 0x47000000
18038                       || (insn & 0xff600000) == 0x45600000)
18039                     {
18040                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
18041                          reversed by tweaking bit 23.  */
18042                       insn ^= 0x00800000;
18043                     }
18044                   else
18045                     {
18046                       /* bc[0-3][tf]l? instructions can have the condition
18047                          reversed by tweaking a single TF bit, and their
18048                          opcodes all have 0x4???????.  */
18049                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
18050                       insn ^= 0x00010000;
18051                     }
18052                   break;
18053
18054                 case 0:
18055                   /* bltz       0x04000000      bgez    0x04010000
18056                      bltzal     0x04100000      bgezal  0x04110000  */
18057                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
18058                   insn ^= 0x00010000;
18059                   break;
18060
18061                 case 1:
18062                   /* beq        0x10000000      bne     0x14000000
18063                      blez       0x18000000      bgtz    0x1c000000  */
18064                   insn ^= 0x04000000;
18065                   break;
18066
18067                 default:
18068                   abort ();
18069                 }
18070             }
18071
18072           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18073             {
18074               /* Clear the and-link bit.  */
18075               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
18076
18077               /* bltzal         0x04100000      bgezal  0x04110000
18078                  bltzall        0x04120000      bgezall 0x04130000  */
18079               insn &= ~0x00100000;
18080             }
18081
18082           /* Branch over the branch (if the branch was likely) or the
18083              full jump (not likely case).  Compute the offset from the
18084              current instruction to branch to.  */
18085           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18086             i = 16;
18087           else
18088             {
18089               /* How many bytes in instructions we've already emitted?  */
18090               i = buf - fragp->fr_literal - fragp->fr_fix;
18091               /* How many bytes in instructions from here to the end?  */
18092               i = fragp->fr_var - i;
18093             }
18094           /* Convert to instruction count.  */
18095           i >>= 2;
18096           /* Branch counts from the next instruction.  */
18097           i--;
18098           insn |= i;
18099           /* Branch over the jump.  */
18100           buf = write_insn (buf, insn);
18101
18102           /* nop */
18103           buf = write_insn (buf, 0);
18104
18105           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18106             {
18107               /* beql $0, $0, 2f */
18108               insn = 0x50000000;
18109               /* Compute the PC offset from the current instruction to
18110                  the end of the variable frag.  */
18111               /* How many bytes in instructions we've already emitted?  */
18112               i = buf - fragp->fr_literal - fragp->fr_fix;
18113               /* How many bytes in instructions from here to the end?  */
18114               i = fragp->fr_var - i;
18115               /* Convert to instruction count.  */
18116               i >>= 2;
18117               /* Don't decrement i, because we want to branch over the
18118                  delay slot.  */
18119               insn |= i;
18120
18121               buf = write_insn (buf, insn);
18122               buf = write_insn (buf, 0);
18123             }
18124
18125         uncond:
18126           if (!RELAX_BRANCH_PIC (fragp->fr_subtype))
18127             {
18128               /* j or jal.  */
18129               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
18130                       ? 0x0c000000 : 0x08000000);
18131               exp.X_op = O_symbol;
18132               exp.X_add_symbol = fragp->fr_symbol;
18133               exp.X_add_number = fragp->fr_offset;
18134
18135               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18136                                   FALSE, BFD_RELOC_MIPS_JMP);
18137               fixp->fx_file = fragp->fr_file;
18138               fixp->fx_line = fragp->fr_line;
18139
18140               buf = write_insn (buf, insn);
18141             }
18142           else
18143             {
18144               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
18145
18146               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
18147               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
18148               insn |= at << OP_SH_RT;
18149               exp.X_op = O_symbol;
18150               exp.X_add_symbol = fragp->fr_symbol;
18151               exp.X_add_number = fragp->fr_offset;
18152
18153               if (fragp->fr_offset)
18154                 {
18155                   exp.X_add_symbol = make_expr_symbol (&exp);
18156                   exp.X_add_number = 0;
18157                 }
18158
18159               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18160                                   FALSE, BFD_RELOC_MIPS_GOT16);
18161               fixp->fx_file = fragp->fr_file;
18162               fixp->fx_line = fragp->fr_line;
18163
18164               buf = write_insn (buf, insn);
18165
18166               if (mips_opts.isa == ISA_MIPS1)
18167                 /* nop */
18168                 buf = write_insn (buf, 0);
18169
18170               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
18171               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
18172               insn |= at << OP_SH_RS | at << OP_SH_RT;
18173
18174               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18175                                   FALSE, BFD_RELOC_LO16);
18176               fixp->fx_file = fragp->fr_file;
18177               fixp->fx_line = fragp->fr_line;
18178
18179               buf = write_insn (buf, insn);
18180
18181               /* j(al)r $at.  */
18182               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18183                 insn = 0x0000f809;
18184               else
18185                 insn = 0x00000008;
18186               insn |= at << OP_SH_RS;
18187
18188               buf = write_insn (buf, insn);
18189             }
18190         }
18191
18192       fragp->fr_fix += fragp->fr_var;
18193       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18194       return;
18195     }
18196
18197   /* Relax microMIPS branches.  */
18198   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18199     {
18200       char *buf = fragp->fr_literal + fragp->fr_fix;
18201       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18202       bfd_boolean insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
18203       bfd_boolean nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
18204       bfd_boolean pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
18205       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18206       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18207       bfd_boolean short_ds;
18208       unsigned long insn;
18209       expressionS exp;
18210       fixS *fixp;
18211
18212       exp.X_op = O_symbol;
18213       exp.X_add_symbol = fragp->fr_symbol;
18214       exp.X_add_number = fragp->fr_offset;
18215
18216       fragp->fr_fix += fragp->fr_var;
18217
18218       /* Handle 16-bit branches that fit or are forced to fit.  */
18219       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18220         {
18221           /* We generate a fixup instead of applying it right now,
18222              because if there is linker relaxation, we're going to
18223              need the relocations.  */
18224           if (type == 'D')
18225             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18226                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
18227           else if (type == 'E')
18228             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18229                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
18230           else
18231             abort ();
18232
18233           fixp->fx_file = fragp->fr_file;
18234           fixp->fx_line = fragp->fr_line;
18235
18236           /* These relocations can have an addend that won't fit in
18237              2 octets.  */
18238           fixp->fx_no_overflow = 1;
18239
18240           return;
18241         }
18242
18243       /* Handle 32-bit branches that fit or are forced to fit.  */
18244       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18245           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18246         {
18247           /* We generate a fixup instead of applying it right now,
18248              because if there is linker relaxation, we're going to
18249              need the relocations.  */
18250           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18251                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
18252           fixp->fx_file = fragp->fr_file;
18253           fixp->fx_line = fragp->fr_line;
18254
18255           if (type == 0)
18256             {
18257               insn = read_compressed_insn (buf, 4);
18258               buf += 4;
18259
18260               if (nods)
18261                 {
18262                   /* Check the short-delay-slot bit.  */
18263                   if (!al || (insn & 0x02000000) != 0)
18264                     buf = write_compressed_insn (buf, 0x0c00, 2);
18265                   else
18266                     buf = write_compressed_insn (buf, 0x00000000, 4);
18267                 }
18268
18269               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18270               return;
18271             }
18272         }
18273
18274       /* Relax 16-bit branches to 32-bit branches.  */
18275       if (type != 0)
18276         {
18277           insn = read_compressed_insn (buf, 2);
18278
18279           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
18280             insn = 0x94000000;                          /* beq  */
18281           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
18282             {
18283               unsigned long regno;
18284
18285               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18286               regno = micromips_to_32_reg_d_map [regno];
18287               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
18288               insn |= regno << MICROMIPSOP_SH_RS;
18289             }
18290           else
18291             abort ();
18292
18293           /* Nothing else to do, just write it out.  */
18294           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18295               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18296             {
18297               buf = write_compressed_insn (buf, insn, 4);
18298               if (nods)
18299                 buf = write_compressed_insn (buf, 0x0c00, 2);
18300               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18301               return;
18302             }
18303         }
18304       else
18305         insn = read_compressed_insn (buf, 4);
18306
18307       /* Relax 32-bit branches to a sequence of instructions.  */
18308       as_warn_where (fragp->fr_file, fragp->fr_line,
18309                      _("relaxed out-of-range branch into a jump"));
18310
18311       /* Set the short-delay-slot bit.  */
18312       short_ds = !al || (insn & 0x02000000) != 0;
18313
18314       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18315         {
18316           symbolS *l;
18317
18318           /* Reverse the branch.  */
18319           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18320               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18321             insn ^= 0x20000000;
18322           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18323                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18324                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18325                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18326                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18327                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18328                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18329                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18330                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18331                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18332             insn ^= 0x00400000;
18333           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18334                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18335                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18336                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18337             insn ^= 0x00200000;
18338           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
18339                                                                    BNZ.df  */
18340                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
18341                                                                    BNZ.V */
18342             insn ^= 0x00800000;
18343           else
18344             abort ();
18345
18346           if (al)
18347             {
18348               /* Clear the and-link and short-delay-slot bits.  */
18349               gas_assert ((insn & 0xfda00000) == 0x40200000);
18350
18351               /* bltzal  0x40200000     bgezal  0x40600000  */
18352               /* bltzals 0x42200000     bgezals 0x42600000  */
18353               insn &= ~0x02200000;
18354             }
18355
18356           /* Make a label at the end for use with the branch.  */
18357           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18358           micromips_label_inc ();
18359           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18360
18361           /* Refer to it.  */
18362           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
18363                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
18364           fixp->fx_file = fragp->fr_file;
18365           fixp->fx_line = fragp->fr_line;
18366
18367           /* Branch over the jump.  */
18368           buf = write_compressed_insn (buf, insn, 4);
18369
18370           if (!compact)
18371             {
18372               /* nop  */
18373               if (insn32)
18374                 buf = write_compressed_insn (buf, 0x00000000, 4);
18375               else
18376                 buf = write_compressed_insn (buf, 0x0c00, 2);
18377             }
18378         }
18379
18380       if (!pic)
18381         {
18382           unsigned long jal = (short_ds || nods
18383                                ? 0x74000000 : 0xf4000000);      /* jal/s  */
18384
18385           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18386           insn = al ? jal : 0xd4000000;
18387
18388           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18389                               BFD_RELOC_MICROMIPS_JMP);
18390           fixp->fx_file = fragp->fr_file;
18391           fixp->fx_line = fragp->fr_line;
18392
18393           buf = write_compressed_insn (buf, insn, 4);
18394
18395           if (compact || nods)
18396             {
18397               /* nop  */
18398               if (insn32)
18399                 buf = write_compressed_insn (buf, 0x00000000, 4);
18400               else
18401                 buf = write_compressed_insn (buf, 0x0c00, 2);
18402             }
18403         }
18404       else
18405         {
18406           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18407
18408           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18409           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18410           insn |= at << MICROMIPSOP_SH_RT;
18411
18412           if (exp.X_add_number)
18413             {
18414               exp.X_add_symbol = make_expr_symbol (&exp);
18415               exp.X_add_number = 0;
18416             }
18417
18418           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18419                               BFD_RELOC_MICROMIPS_GOT16);
18420           fixp->fx_file = fragp->fr_file;
18421           fixp->fx_line = fragp->fr_line;
18422
18423           buf = write_compressed_insn (buf, insn, 4);
18424
18425           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18426           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18427           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18428
18429           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18430                               BFD_RELOC_MICROMIPS_LO16);
18431           fixp->fx_file = fragp->fr_file;
18432           fixp->fx_line = fragp->fr_line;
18433
18434           buf = write_compressed_insn (buf, insn, 4);
18435
18436           if (insn32)
18437             {
18438               /* jr/jalr $at  */
18439               insn = 0x00000f3c | (al ? RA : ZERO) << MICROMIPSOP_SH_RT;
18440               insn |= at << MICROMIPSOP_SH_RS;
18441
18442               buf = write_compressed_insn (buf, insn, 4);
18443
18444               if (compact || nods)
18445                 /* nop  */
18446                 buf = write_compressed_insn (buf, 0x00000000, 4);
18447             }
18448           else
18449             {
18450               /* jr/jrc/jalr/jalrs $at  */
18451               unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;  /* jalr/s  */
18452               unsigned long jr = compact || nods ? 0x45a0 : 0x4580; /* jr/c  */
18453
18454               insn = al ? jalr : jr;
18455               insn |= at << MICROMIPSOP_SH_MJ;
18456
18457               buf = write_compressed_insn (buf, insn, 2);
18458               if (al && nods)
18459                 {
18460                   /* nop  */
18461                   if (short_ds)
18462                     buf = write_compressed_insn (buf, 0x0c00, 2);
18463                   else
18464                     buf = write_compressed_insn (buf, 0x00000000, 4);
18465                 }
18466             }
18467         }
18468
18469       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18470       return;
18471     }
18472
18473   if (RELAX_MIPS16_P (fragp->fr_subtype))
18474     {
18475       int type;
18476       const struct mips_int_operand *operand;
18477       offsetT val;
18478       char *buf;
18479       unsigned int user_length;
18480       bfd_boolean need_reloc;
18481       unsigned long insn;
18482       bfd_boolean mac;
18483       bfd_boolean ext;
18484       segT symsec;
18485
18486       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18487       operand = mips16_immed_operand (type, FALSE);
18488
18489       mac = RELAX_MIPS16_MACRO (fragp->fr_subtype);
18490       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18491       val = resolve_symbol_value (fragp->fr_symbol) + fragp->fr_offset;
18492
18493       symsec = S_GET_SEGMENT (fragp->fr_symbol);
18494       need_reloc = (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
18495                     || (operand->root.type == OP_PCREL && !mac
18496                         ? asec != symsec
18497                         : !bfd_is_abs_section (symsec)));
18498
18499       if (operand->root.type == OP_PCREL && !mac)
18500         {
18501           const struct mips_pcrel_operand *pcrel_op;
18502
18503           pcrel_op = (const struct mips_pcrel_operand *) operand;
18504
18505           if (pcrel_op->include_isa_bit && !need_reloc)
18506             {
18507               if (!ELF_ST_IS_MIPS16 (S_GET_OTHER (fragp->fr_symbol)))
18508                 as_bad_where (fragp->fr_file, fragp->fr_line,
18509                               _("branch to a symbol in another ISA mode"));
18510               else if ((fragp->fr_offset & 0x1) != 0)
18511                 as_bad_where (fragp->fr_file, fragp->fr_line,
18512                               _("branch to misaligned address (0x%lx)"),
18513                               (long) val);
18514             }
18515
18516           val = mips16_pcrel_val (fragp, pcrel_op, val, 0);
18517
18518           /* Make sure the section winds up with the alignment we have
18519              assumed.  */
18520           if (operand->shift > 0)
18521             record_alignment (asec, operand->shift);
18522         }
18523
18524       if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18525           || RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18526         {
18527           if (mac)
18528             as_warn_where (fragp->fr_file, fragp->fr_line,
18529                            _("macro instruction expanded into multiple "
18530                              "instructions in a branch delay slot"));
18531           else if (ext)
18532             as_warn_where (fragp->fr_file, fragp->fr_line,
18533                            _("extended instruction in a branch delay slot"));
18534         }
18535       else if (RELAX_MIPS16_NOMACRO (fragp->fr_subtype) && mac)
18536         as_warn_where (fragp->fr_file, fragp->fr_line,
18537                        _("macro instruction expanded into multiple "
18538                          "instructions"));
18539
18540       buf = fragp->fr_literal + fragp->fr_fix;
18541
18542       insn = read_compressed_insn (buf, 2);
18543       if (ext)
18544         insn |= MIPS16_EXTEND;
18545
18546       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18547         user_length = 4;
18548       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18549         user_length = 2;
18550       else
18551         user_length = 0;
18552
18553       if (mac)
18554         {
18555           unsigned long reg;
18556           unsigned long new;
18557           unsigned long op;
18558
18559           gas_assert (type == 'A' || type == 'B' || type == 'E');
18560           gas_assert (RELAX_MIPS16_SYM32 (fragp->fr_subtype));
18561
18562           if (need_reloc)
18563             {
18564               fixS *fixp;
18565
18566               gas_assert (!RELAX_MIPS16_PIC (fragp->fr_subtype));
18567
18568               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18569                               fragp->fr_symbol, fragp->fr_offset,
18570                               FALSE, BFD_RELOC_MIPS16_HI16_S);
18571               fixp->fx_file = fragp->fr_file;
18572               fixp->fx_line = fragp->fr_line;
18573
18574               fixp = fix_new (fragp, buf - fragp->fr_literal + 8, 4,
18575                               fragp->fr_symbol, fragp->fr_offset,
18576                               FALSE, BFD_RELOC_MIPS16_LO16);
18577               fixp->fx_file = fragp->fr_file;
18578               fixp->fx_line = fragp->fr_line;
18579
18580               val = 0;
18581             }
18582
18583           switch (insn & 0xf800)
18584             {
18585             case 0x0800:                                        /* ADDIU */
18586               reg = (insn >> 8) & 0x7;
18587               op = 0xf0004800 | (reg << 8);
18588               break;
18589             case 0xb000:                                        /* LW */
18590               reg = (insn >> 8) & 0x7;
18591               op = 0xf0009800 | (reg << 8) | (reg << 5);
18592               break;
18593             case 0xf800:                                        /* I64 */
18594               reg = (insn >> 5) & 0x7;
18595               switch (insn & 0x0700)
18596                 {
18597                 case 0x0400:                                    /* LD */
18598                   op = 0xf0003800 | (reg << 8) | (reg << 5);
18599                   break;
18600                 case 0x0600:                                    /* DADDIU */
18601                   op = 0xf000fd00 | (reg << 5);
18602                   break;
18603                 default:
18604                   abort ();
18605                 }
18606               break;
18607             default:
18608               abort ();
18609             }
18610
18611           new = 0xf0006800 | (reg << 8);                        /* LI */
18612           new |= mips16_immed_extend ((val + 0x8000) >> 16, 16);
18613           buf = write_compressed_insn (buf, new, 4);
18614           new = 0xf4003000 | (reg << 8) | (reg << 5);           /* SLL */
18615           buf = write_compressed_insn (buf, new, 4);
18616           op |= mips16_immed_extend (val, 16);
18617           buf = write_compressed_insn (buf, op, 4);
18618
18619           fragp->fr_fix += 12;
18620         }
18621       else
18622         {
18623           unsigned int length = ext ? 4 : 2;
18624
18625           if (need_reloc)
18626             {
18627               bfd_reloc_code_real_type reloc = BFD_RELOC_NONE;
18628               expressionS exp;
18629               fixS *fixp;
18630
18631               switch (type)
18632                 {
18633                 case 'p':
18634                 case 'q':
18635                   reloc = BFD_RELOC_MIPS16_16_PCREL_S1;
18636                   break;
18637                 default:
18638                   break;
18639                 }
18640               if (mac || reloc == BFD_RELOC_NONE)
18641                 as_bad_where (fragp->fr_file, fragp->fr_line,
18642                               _("unsupported relocation"));
18643               else if (ext)
18644                 {
18645                   exp.X_op = O_symbol;
18646                   exp.X_add_symbol = fragp->fr_symbol;
18647                   exp.X_add_number = fragp->fr_offset;
18648
18649                   fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18650                                       TRUE, reloc);
18651
18652                   fixp->fx_file = fragp->fr_file;
18653                   fixp->fx_line = fragp->fr_line;
18654                 }
18655               else
18656                 as_bad_where (fragp->fr_file, fragp->fr_line,
18657                               _("invalid unextended operand value"));
18658             }
18659           else
18660             mips16_immed (fragp->fr_file, fragp->fr_line, type,
18661                           BFD_RELOC_UNUSED, val, user_length, &insn);
18662
18663           gas_assert (mips16_opcode_length (insn) == length);
18664           write_compressed_insn (buf, insn, length);
18665           fragp->fr_fix += length;
18666         }
18667     }
18668   else
18669     {
18670       relax_substateT subtype = fragp->fr_subtype;
18671       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18672       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18673       int first, second;
18674       fixS *fixp;
18675
18676       first = RELAX_FIRST (subtype);
18677       second = RELAX_SECOND (subtype);
18678       fixp = (fixS *) fragp->fr_opcode;
18679
18680       /* If the delay slot chosen does not match the size of the instruction,
18681          then emit a warning.  */
18682       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18683            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18684         {
18685           relax_substateT s;
18686           const char *msg;
18687
18688           s = subtype & (RELAX_DELAY_SLOT_16BIT
18689                          | RELAX_DELAY_SLOT_SIZE_FIRST
18690                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18691           msg = macro_warning (s);
18692           if (msg != NULL)
18693             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18694           subtype &= ~s;
18695         }
18696
18697       /* Possibly emit a warning if we've chosen the longer option.  */
18698       if (use_second == second_longer)
18699         {
18700           relax_substateT s;
18701           const char *msg;
18702
18703           s = (subtype
18704                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18705           msg = macro_warning (s);
18706           if (msg != NULL)
18707             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18708           subtype &= ~s;
18709         }
18710
18711       /* Go through all the fixups for the first sequence.  Disable them
18712          (by marking them as done) if we're going to use the second
18713          sequence instead.  */
18714       while (fixp
18715              && fixp->fx_frag == fragp
18716              && fixp->fx_where < fragp->fr_fix - second)
18717         {
18718           if (subtype & RELAX_USE_SECOND)
18719             fixp->fx_done = 1;
18720           fixp = fixp->fx_next;
18721         }
18722
18723       /* Go through the fixups for the second sequence.  Disable them if
18724          we're going to use the first sequence, otherwise adjust their
18725          addresses to account for the relaxation.  */
18726       while (fixp && fixp->fx_frag == fragp)
18727         {
18728           if (subtype & RELAX_USE_SECOND)
18729             fixp->fx_where -= first;
18730           else
18731             fixp->fx_done = 1;
18732           fixp = fixp->fx_next;
18733         }
18734
18735       /* Now modify the frag contents.  */
18736       if (subtype & RELAX_USE_SECOND)
18737         {
18738           char *start;
18739
18740           start = fragp->fr_literal + fragp->fr_fix - first - second;
18741           memmove (start, start + first, second);
18742           fragp->fr_fix -= first;
18743         }
18744       else
18745         fragp->fr_fix -= second;
18746     }
18747 }
18748
18749 /* This function is called after the relocs have been generated.
18750    We've been storing mips16 text labels as odd.  Here we convert them
18751    back to even for the convenience of the debugger.  */
18752
18753 void
18754 mips_frob_file_after_relocs (void)
18755 {
18756   asymbol **syms;
18757   unsigned int count, i;
18758
18759   syms = bfd_get_outsymbols (stdoutput);
18760   count = bfd_get_symcount (stdoutput);
18761   for (i = 0; i < count; i++, syms++)
18762     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18763         && ((*syms)->value & 1) != 0)
18764       {
18765         (*syms)->value &= ~1;
18766         /* If the symbol has an odd size, it was probably computed
18767            incorrectly, so adjust that as well.  */
18768         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18769           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18770       }
18771 }
18772
18773 /* This function is called whenever a label is defined, including fake
18774    labels instantiated off the dot special symbol.  It is used when
18775    handling branch delays; if a branch has a label, we assume we cannot
18776    move it.  This also bumps the value of the symbol by 1 in compressed
18777    code.  */
18778
18779 static void
18780 mips_record_label (symbolS *sym)
18781 {
18782   segment_info_type *si = seg_info (now_seg);
18783   struct insn_label_list *l;
18784
18785   if (free_insn_labels == NULL)
18786     l = XNEW (struct insn_label_list);
18787   else
18788     {
18789       l = free_insn_labels;
18790       free_insn_labels = l->next;
18791     }
18792
18793   l->label = sym;
18794   l->next = si->label_list;
18795   si->label_list = l;
18796 }
18797
18798 /* This function is called as tc_frob_label() whenever a label is defined
18799    and adds a DWARF-2 record we only want for true labels.  */
18800
18801 void
18802 mips_define_label (symbolS *sym)
18803 {
18804   mips_record_label (sym);
18805   dwarf2_emit_label (sym);
18806 }
18807
18808 /* This function is called by tc_new_dot_label whenever a new dot symbol
18809    is defined.  */
18810
18811 void
18812 mips_add_dot_label (symbolS *sym)
18813 {
18814   mips_record_label (sym);
18815   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
18816     mips_compressed_mark_label (sym);
18817 }
18818 \f
18819 /* Converting ASE flags from internal to .MIPS.abiflags values.  */
18820 static unsigned int
18821 mips_convert_ase_flags (int ase)
18822 {
18823   unsigned int ext_ases = 0;
18824
18825   if (ase & ASE_DSP)
18826     ext_ases |= AFL_ASE_DSP;
18827   if (ase & ASE_DSPR2)
18828     ext_ases |= AFL_ASE_DSPR2;
18829   if (ase & ASE_DSPR3)
18830     ext_ases |= AFL_ASE_DSPR3;
18831   if (ase & ASE_EVA)
18832     ext_ases |= AFL_ASE_EVA;
18833   if (ase & ASE_MCU)
18834     ext_ases |= AFL_ASE_MCU;
18835   if (ase & ASE_MDMX)
18836     ext_ases |= AFL_ASE_MDMX;
18837   if (ase & ASE_MIPS3D)
18838     ext_ases |= AFL_ASE_MIPS3D;
18839   if (ase & ASE_MT)
18840     ext_ases |= AFL_ASE_MT;
18841   if (ase & ASE_SMARTMIPS)
18842     ext_ases |= AFL_ASE_SMARTMIPS;
18843   if (ase & ASE_VIRT)
18844     ext_ases |= AFL_ASE_VIRT;
18845   if (ase & ASE_MSA)
18846     ext_ases |= AFL_ASE_MSA;
18847   if (ase & ASE_XPA)
18848     ext_ases |= AFL_ASE_XPA;
18849
18850   return ext_ases;
18851 }
18852 /* Some special processing for a MIPS ELF file.  */
18853
18854 void
18855 mips_elf_final_processing (void)
18856 {
18857   int fpabi;
18858   Elf_Internal_ABIFlags_v0 flags;
18859
18860   flags.version = 0;
18861   flags.isa_rev = 0;
18862   switch (file_mips_opts.isa)
18863     {
18864     case INSN_ISA1:
18865       flags.isa_level = 1;
18866       break;
18867     case INSN_ISA2:
18868       flags.isa_level = 2;
18869       break;
18870     case INSN_ISA3:
18871       flags.isa_level = 3;
18872       break;
18873     case INSN_ISA4:
18874       flags.isa_level = 4;
18875       break;
18876     case INSN_ISA5:
18877       flags.isa_level = 5;
18878       break;
18879     case INSN_ISA32:
18880       flags.isa_level = 32;
18881       flags.isa_rev = 1;
18882       break;
18883     case INSN_ISA32R2:
18884       flags.isa_level = 32;
18885       flags.isa_rev = 2;
18886       break;
18887     case INSN_ISA32R3:
18888       flags.isa_level = 32;
18889       flags.isa_rev = 3;
18890       break;
18891     case INSN_ISA32R5:
18892       flags.isa_level = 32;
18893       flags.isa_rev = 5;
18894       break;
18895     case INSN_ISA32R6:
18896       flags.isa_level = 32;
18897       flags.isa_rev = 6;
18898       break;
18899     case INSN_ISA64:
18900       flags.isa_level = 64;
18901       flags.isa_rev = 1;
18902       break;
18903     case INSN_ISA64R2:
18904       flags.isa_level = 64;
18905       flags.isa_rev = 2;
18906       break;
18907     case INSN_ISA64R3:
18908       flags.isa_level = 64;
18909       flags.isa_rev = 3;
18910       break;
18911     case INSN_ISA64R5:
18912       flags.isa_level = 64;
18913       flags.isa_rev = 5;
18914       break;
18915     case INSN_ISA64R6:
18916       flags.isa_level = 64;
18917       flags.isa_rev = 6;
18918       break;
18919     }
18920
18921   flags.gpr_size = file_mips_opts.gp == 32 ? AFL_REG_32 : AFL_REG_64;
18922   flags.cpr1_size = file_mips_opts.soft_float ? AFL_REG_NONE
18923                     : (file_mips_opts.ase & ASE_MSA) ? AFL_REG_128
18924                     : (file_mips_opts.fp == 64) ? AFL_REG_64
18925                     : AFL_REG_32;
18926   flags.cpr2_size = AFL_REG_NONE;
18927   flags.fp_abi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
18928                                            Tag_GNU_MIPS_ABI_FP);
18929   flags.isa_ext = bfd_mips_isa_ext (stdoutput);
18930   flags.ases = mips_convert_ase_flags (file_mips_opts.ase);
18931   if (file_ase_mips16)
18932     flags.ases |= AFL_ASE_MIPS16;
18933   if (file_ase_micromips)
18934     flags.ases |= AFL_ASE_MICROMIPS;
18935   flags.flags1 = 0;
18936   if ((ISA_HAS_ODD_SINGLE_FPR (file_mips_opts.isa, file_mips_opts.arch)
18937        || file_mips_opts.fp == 64)
18938       && file_mips_opts.oddspreg)
18939     flags.flags1 |= AFL_FLAGS1_ODDSPREG;
18940   flags.flags2 = 0;
18941
18942   bfd_mips_elf_swap_abiflags_v0_out (stdoutput, &flags,
18943                                      ((Elf_External_ABIFlags_v0 *)
18944                                      mips_flags_frag));
18945
18946   /* Write out the register information.  */
18947   if (mips_abi != N64_ABI)
18948     {
18949       Elf32_RegInfo s;
18950
18951       s.ri_gprmask = mips_gprmask;
18952       s.ri_cprmask[0] = mips_cprmask[0];
18953       s.ri_cprmask[1] = mips_cprmask[1];
18954       s.ri_cprmask[2] = mips_cprmask[2];
18955       s.ri_cprmask[3] = mips_cprmask[3];
18956       /* The gp_value field is set by the MIPS ELF backend.  */
18957
18958       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18959                                        ((Elf32_External_RegInfo *)
18960                                         mips_regmask_frag));
18961     }
18962   else
18963     {
18964       Elf64_Internal_RegInfo s;
18965
18966       s.ri_gprmask = mips_gprmask;
18967       s.ri_pad = 0;
18968       s.ri_cprmask[0] = mips_cprmask[0];
18969       s.ri_cprmask[1] = mips_cprmask[1];
18970       s.ri_cprmask[2] = mips_cprmask[2];
18971       s.ri_cprmask[3] = mips_cprmask[3];
18972       /* The gp_value field is set by the MIPS ELF backend.  */
18973
18974       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18975                                        ((Elf64_External_RegInfo *)
18976                                         mips_regmask_frag));
18977     }
18978
18979   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18980      sort of BFD interface for this.  */
18981   if (mips_any_noreorder)
18982     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18983   if (mips_pic != NO_PIC)
18984     {
18985       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
18986       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18987     }
18988   if (mips_abicalls)
18989     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18990
18991   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
18992      defined at present; this might need to change in future.  */
18993   if (file_ase_mips16)
18994     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
18995   if (file_ase_micromips)
18996     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
18997   if (file_mips_opts.ase & ASE_MDMX)
18998     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
18999
19000   /* Set the MIPS ELF ABI flags.  */
19001   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
19002     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
19003   else if (mips_abi == O64_ABI)
19004     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
19005   else if (mips_abi == EABI_ABI)
19006     {
19007       if (file_mips_opts.gp == 64)
19008         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
19009       else
19010         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
19011     }
19012   else if (mips_abi == N32_ABI)
19013     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
19014
19015   /* Nothing to do for N64_ABI.  */
19016
19017   if (mips_32bitmode)
19018     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
19019
19020   if (mips_nan2008 == 1)
19021     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
19022
19023   /* 32 bit code with 64 bit FP registers.  */
19024   fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19025                                     Tag_GNU_MIPS_ABI_FP);
19026   if (fpabi == Val_GNU_MIPS_ABI_FP_OLD_64)
19027     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
19028 }
19029 \f
19030 typedef struct proc {
19031   symbolS *func_sym;
19032   symbolS *func_end_sym;
19033   unsigned long reg_mask;
19034   unsigned long reg_offset;
19035   unsigned long fpreg_mask;
19036   unsigned long fpreg_offset;
19037   unsigned long frame_offset;
19038   unsigned long frame_reg;
19039   unsigned long pc_reg;
19040 } procS;
19041
19042 static procS cur_proc;
19043 static procS *cur_proc_ptr;
19044 static int numprocs;
19045
19046 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
19047    as "2", and a normal nop as "0".  */
19048
19049 #define NOP_OPCODE_MIPS         0
19050 #define NOP_OPCODE_MIPS16       1
19051 #define NOP_OPCODE_MICROMIPS    2
19052
19053 char
19054 mips_nop_opcode (void)
19055 {
19056   if (seg_info (now_seg)->tc_segment_info_data.micromips)
19057     return NOP_OPCODE_MICROMIPS;
19058   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
19059     return NOP_OPCODE_MIPS16;
19060   else
19061     return NOP_OPCODE_MIPS;
19062 }
19063
19064 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
19065    32-bit microMIPS NOPs here (if applicable).  */
19066
19067 void
19068 mips_handle_align (fragS *fragp)
19069 {
19070   char nop_opcode;
19071   char *p;
19072   int bytes, size, excess;
19073   valueT opcode;
19074
19075   if (fragp->fr_type != rs_align_code)
19076     return;
19077
19078   p = fragp->fr_literal + fragp->fr_fix;
19079   nop_opcode = *p;
19080   switch (nop_opcode)
19081     {
19082     case NOP_OPCODE_MICROMIPS:
19083       opcode = micromips_nop32_insn.insn_opcode;
19084       size = 4;
19085       break;
19086     case NOP_OPCODE_MIPS16:
19087       opcode = mips16_nop_insn.insn_opcode;
19088       size = 2;
19089       break;
19090     case NOP_OPCODE_MIPS:
19091     default:
19092       opcode = nop_insn.insn_opcode;
19093       size = 4;
19094       break;
19095     }
19096
19097   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
19098   excess = bytes % size;
19099
19100   /* Handle the leading part if we're not inserting a whole number of
19101      instructions, and make it the end of the fixed part of the frag.
19102      Try to fit in a short microMIPS NOP if applicable and possible,
19103      and use zeroes otherwise.  */
19104   gas_assert (excess < 4);
19105   fragp->fr_fix += excess;
19106   switch (excess)
19107     {
19108     case 3:
19109       *p++ = '\0';
19110       /* Fall through.  */
19111     case 2:
19112       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
19113         {
19114           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
19115           break;
19116         }
19117       *p++ = '\0';
19118       /* Fall through.  */
19119     case 1:
19120       *p++ = '\0';
19121       /* Fall through.  */
19122     case 0:
19123       break;
19124     }
19125
19126   md_number_to_chars (p, opcode, size);
19127   fragp->fr_var = size;
19128 }
19129
19130 static long
19131 get_number (void)
19132 {
19133   int negative = 0;
19134   long val = 0;
19135
19136   if (*input_line_pointer == '-')
19137     {
19138       ++input_line_pointer;
19139       negative = 1;
19140     }
19141   if (!ISDIGIT (*input_line_pointer))
19142     as_bad (_("expected simple number"));
19143   if (input_line_pointer[0] == '0')
19144     {
19145       if (input_line_pointer[1] == 'x')
19146         {
19147           input_line_pointer += 2;
19148           while (ISXDIGIT (*input_line_pointer))
19149             {
19150               val <<= 4;
19151               val |= hex_value (*input_line_pointer++);
19152             }
19153           return negative ? -val : val;
19154         }
19155       else
19156         {
19157           ++input_line_pointer;
19158           while (ISDIGIT (*input_line_pointer))
19159             {
19160               val <<= 3;
19161               val |= *input_line_pointer++ - '0';
19162             }
19163           return negative ? -val : val;
19164         }
19165     }
19166   if (!ISDIGIT (*input_line_pointer))
19167     {
19168       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
19169               *input_line_pointer, *input_line_pointer);
19170       as_warn (_("invalid number"));
19171       return -1;
19172     }
19173   while (ISDIGIT (*input_line_pointer))
19174     {
19175       val *= 10;
19176       val += *input_line_pointer++ - '0';
19177     }
19178   return negative ? -val : val;
19179 }
19180
19181 /* The .file directive; just like the usual .file directive, but there
19182    is an initial number which is the ECOFF file index.  In the non-ECOFF
19183    case .file implies DWARF-2.  */
19184
19185 static void
19186 s_mips_file (int x ATTRIBUTE_UNUSED)
19187 {
19188   static int first_file_directive = 0;
19189
19190   if (ECOFF_DEBUGGING)
19191     {
19192       get_number ();
19193       s_app_file (0);
19194     }
19195   else
19196     {
19197       char *filename;
19198
19199       filename = dwarf2_directive_file (0);
19200
19201       /* Versions of GCC up to 3.1 start files with a ".file"
19202          directive even for stabs output.  Make sure that this
19203          ".file" is handled.  Note that you need a version of GCC
19204          after 3.1 in order to support DWARF-2 on MIPS.  */
19205       if (filename != NULL && ! first_file_directive)
19206         {
19207           (void) new_logical_line (filename, -1);
19208           s_app_file_string (filename, 0);
19209         }
19210       first_file_directive = 1;
19211     }
19212 }
19213
19214 /* The .loc directive, implying DWARF-2.  */
19215
19216 static void
19217 s_mips_loc (int x ATTRIBUTE_UNUSED)
19218 {
19219   if (!ECOFF_DEBUGGING)
19220     dwarf2_directive_loc (0);
19221 }
19222
19223 /* The .end directive.  */
19224
19225 static void
19226 s_mips_end (int x ATTRIBUTE_UNUSED)
19227 {
19228   symbolS *p;
19229
19230   /* Following functions need their own .frame and .cprestore directives.  */
19231   mips_frame_reg_valid = 0;
19232   mips_cprestore_valid = 0;
19233
19234   if (!is_end_of_line[(unsigned char) *input_line_pointer])
19235     {
19236       p = get_symbol ();
19237       demand_empty_rest_of_line ();
19238     }
19239   else
19240     p = NULL;
19241
19242   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19243     as_warn (_(".end not in text section"));
19244
19245   if (!cur_proc_ptr)
19246     {
19247       as_warn (_(".end directive without a preceding .ent directive"));
19248       demand_empty_rest_of_line ();
19249       return;
19250     }
19251
19252   if (p != NULL)
19253     {
19254       gas_assert (S_GET_NAME (p));
19255       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
19256         as_warn (_(".end symbol does not match .ent symbol"));
19257
19258       if (debug_type == DEBUG_STABS)
19259         stabs_generate_asm_endfunc (S_GET_NAME (p),
19260                                     S_GET_NAME (p));
19261     }
19262   else
19263     as_warn (_(".end directive missing or unknown symbol"));
19264
19265   /* Create an expression to calculate the size of the function.  */
19266   if (p && cur_proc_ptr)
19267     {
19268       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
19269       expressionS *exp = XNEW (expressionS);
19270
19271       obj->size = exp;
19272       exp->X_op = O_subtract;
19273       exp->X_add_symbol = symbol_temp_new_now ();
19274       exp->X_op_symbol = p;
19275       exp->X_add_number = 0;
19276
19277       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
19278     }
19279
19280 #ifdef md_flush_pending_output
19281   md_flush_pending_output ();
19282 #endif
19283
19284   /* Generate a .pdr section.  */
19285   if (!ECOFF_DEBUGGING && mips_flag_pdr)
19286     {
19287       segT saved_seg = now_seg;
19288       subsegT saved_subseg = now_subseg;
19289       expressionS exp;
19290       char *fragp;
19291
19292       gas_assert (pdr_seg);
19293       subseg_set (pdr_seg, 0);
19294
19295       /* Write the symbol.  */
19296       exp.X_op = O_symbol;
19297       exp.X_add_symbol = p;
19298       exp.X_add_number = 0;
19299       emit_expr (&exp, 4);
19300
19301       fragp = frag_more (7 * 4);
19302
19303       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
19304       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
19305       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
19306       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
19307       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
19308       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
19309       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
19310
19311       subseg_set (saved_seg, saved_subseg);
19312     }
19313
19314   cur_proc_ptr = NULL;
19315 }
19316
19317 /* The .aent and .ent directives.  */
19318
19319 static void
19320 s_mips_ent (int aent)
19321 {
19322   symbolS *symbolP;
19323
19324   symbolP = get_symbol ();
19325   if (*input_line_pointer == ',')
19326     ++input_line_pointer;
19327   SKIP_WHITESPACE ();
19328   if (ISDIGIT (*input_line_pointer)
19329       || *input_line_pointer == '-')
19330     get_number ();
19331
19332   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19333     as_warn (_(".ent or .aent not in text section"));
19334
19335   if (!aent && cur_proc_ptr)
19336     as_warn (_("missing .end"));
19337
19338   if (!aent)
19339     {
19340       /* This function needs its own .frame and .cprestore directives.  */
19341       mips_frame_reg_valid = 0;
19342       mips_cprestore_valid = 0;
19343
19344       cur_proc_ptr = &cur_proc;
19345       memset (cur_proc_ptr, '\0', sizeof (procS));
19346
19347       cur_proc_ptr->func_sym = symbolP;
19348
19349       ++numprocs;
19350
19351       if (debug_type == DEBUG_STABS)
19352         stabs_generate_asm_func (S_GET_NAME (symbolP),
19353                                  S_GET_NAME (symbolP));
19354     }
19355
19356   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
19357
19358   demand_empty_rest_of_line ();
19359 }
19360
19361 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
19362    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
19363    s_mips_frame is used so that we can set the PDR information correctly.
19364    We can't use the ecoff routines because they make reference to the ecoff
19365    symbol table (in the mdebug section).  */
19366
19367 static void
19368 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
19369 {
19370   if (ECOFF_DEBUGGING)
19371     s_ignore (ignore);
19372   else
19373     {
19374       long val;
19375
19376       if (cur_proc_ptr == (procS *) NULL)
19377         {
19378           as_warn (_(".frame outside of .ent"));
19379           demand_empty_rest_of_line ();
19380           return;
19381         }
19382
19383       cur_proc_ptr->frame_reg = tc_get_register (1);
19384
19385       SKIP_WHITESPACE ();
19386       if (*input_line_pointer++ != ','
19387           || get_absolute_expression_and_terminator (&val) != ',')
19388         {
19389           as_warn (_("bad .frame directive"));
19390           --input_line_pointer;
19391           demand_empty_rest_of_line ();
19392           return;
19393         }
19394
19395       cur_proc_ptr->frame_offset = val;
19396       cur_proc_ptr->pc_reg = tc_get_register (0);
19397
19398       demand_empty_rest_of_line ();
19399     }
19400 }
19401
19402 /* The .fmask and .mask directives. If the mdebug section is present
19403    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
19404    embedded targets, s_mips_mask is used so that we can set the PDR
19405    information correctly. We can't use the ecoff routines because they
19406    make reference to the ecoff symbol table (in the mdebug section).  */
19407
19408 static void
19409 s_mips_mask (int reg_type)
19410 {
19411   if (ECOFF_DEBUGGING)
19412     s_ignore (reg_type);
19413   else
19414     {
19415       long mask, off;
19416
19417       if (cur_proc_ptr == (procS *) NULL)
19418         {
19419           as_warn (_(".mask/.fmask outside of .ent"));
19420           demand_empty_rest_of_line ();
19421           return;
19422         }
19423
19424       if (get_absolute_expression_and_terminator (&mask) != ',')
19425         {
19426           as_warn (_("bad .mask/.fmask directive"));
19427           --input_line_pointer;
19428           demand_empty_rest_of_line ();
19429           return;
19430         }
19431
19432       off = get_absolute_expression ();
19433
19434       if (reg_type == 'F')
19435         {
19436           cur_proc_ptr->fpreg_mask = mask;
19437           cur_proc_ptr->fpreg_offset = off;
19438         }
19439       else
19440         {
19441           cur_proc_ptr->reg_mask = mask;
19442           cur_proc_ptr->reg_offset = off;
19443         }
19444
19445       demand_empty_rest_of_line ();
19446     }
19447 }
19448
19449 /* A table describing all the processors gas knows about.  Names are
19450    matched in the order listed.
19451
19452    To ease comparison, please keep this table in the same order as
19453    gcc's mips_cpu_info_table[].  */
19454 static const struct mips_cpu_info mips_cpu_info_table[] =
19455 {
19456   /* Entries for generic ISAs */
19457   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
19458   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
19459   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
19460   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
19461   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
19462   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
19463   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
19464   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
19465   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
19466   { "mips32r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R6, CPU_MIPS32R6 },
19467   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
19468   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
19469   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
19470   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
19471   { "mips64r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R6, CPU_MIPS64R6 },
19472
19473   /* MIPS I */
19474   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19475   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19476   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
19477
19478   /* MIPS II */
19479   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
19480
19481   /* MIPS III */
19482   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
19483   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
19484   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
19485   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19486   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19487   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19488   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19489   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
19490   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
19491   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19492   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19493   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19494   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19495   /* ST Microelectronics Loongson 2E and 2F cores */
19496   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19497   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
19498
19499   /* MIPS IV */
19500   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19501   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19502   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19503   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19504   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19505   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19506   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19507   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19508   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19509   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19510   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19511   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19512   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19513   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19514   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19515
19516   /* MIPS 32 */
19517   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19518   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19519   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19520   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19521
19522   /* MIPS 32 Release 2 */
19523   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19524   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19525   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19526   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19527   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19528   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19529   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19530   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19531   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19532                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19533   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19534                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19535   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19536   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19537   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19538   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19539   /* Deprecated forms of the above.  */
19540   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19541   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19542   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19543   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19544   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19545   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19546   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19547   /* Deprecated forms of the above.  */
19548   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19549   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19550   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19551   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19552   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19553   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19554   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19555   /* Deprecated forms of the above.  */
19556   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19557   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19558   /* 34Kn is a 34kc without DSP.  */
19559   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19560   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19561   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19562   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19563   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19564   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19565   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19566   /* Deprecated forms of the above.  */
19567   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19568   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19569   /* 1004K cores are multiprocessor versions of the 34K.  */
19570   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19571   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19572   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19573   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19574   /* interaptiv is the new name for 1004kf */
19575   { "interaptiv",     0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19576   /* M5100 family */
19577   { "m5100",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19578   { "m5101",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19579   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
19580   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
19581
19582   /* MIPS 64 */
19583   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19584   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19585   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19586   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19587
19588   /* Broadcom SB-1 CPU core */
19589   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19590   /* Broadcom SB-1A CPU core */
19591   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19592
19593   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
19594
19595   /* MIPS 64 Release 2 */
19596
19597   /* Cavium Networks Octeon CPU core */
19598   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19599   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19600   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19601   { "octeon3",        0, ASE_VIRT | ASE_VIRT64, ISA_MIPS64R5, CPU_OCTEON3 },
19602
19603   /* RMI Xlr */
19604   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19605
19606   /* Broadcom XLP.
19607      XLP is mostly like XLR, with the prominent exception that it is
19608      MIPS64R2 rather than MIPS64.  */
19609   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19610
19611   /* MIPS 64 Release 6 */
19612   { "i6400",          0, ASE_MSA,               ISA_MIPS64R6, CPU_MIPS64R6},
19613   { "p6600",          0, ASE_VIRT | ASE_MSA,    ISA_MIPS64R6, CPU_MIPS64R6},
19614
19615   /* End marker */
19616   { NULL, 0, 0, 0, 0 }
19617 };
19618
19619
19620 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19621    with a final "000" replaced by "k".  Ignore case.
19622
19623    Note: this function is shared between GCC and GAS.  */
19624
19625 static bfd_boolean
19626 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19627 {
19628   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19629     given++, canonical++;
19630
19631   return ((*given == 0 && *canonical == 0)
19632           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19633 }
19634
19635
19636 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19637    CPU name.  We've traditionally allowed a lot of variation here.
19638
19639    Note: this function is shared between GCC and GAS.  */
19640
19641 static bfd_boolean
19642 mips_matching_cpu_name_p (const char *canonical, const char *given)
19643 {
19644   /* First see if the name matches exactly, or with a final "000"
19645      turned into "k".  */
19646   if (mips_strict_matching_cpu_name_p (canonical, given))
19647     return TRUE;
19648
19649   /* If not, try comparing based on numerical designation alone.
19650      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19651   if (TOLOWER (*given) == 'r')
19652     given++;
19653   if (!ISDIGIT (*given))
19654     return FALSE;
19655
19656   /* Skip over some well-known prefixes in the canonical name,
19657      hoping to find a number there too.  */
19658   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19659     canonical += 2;
19660   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19661     canonical += 2;
19662   else if (TOLOWER (canonical[0]) == 'r')
19663     canonical += 1;
19664
19665   return mips_strict_matching_cpu_name_p (canonical, given);
19666 }
19667
19668
19669 /* Parse an option that takes the name of a processor as its argument.
19670    OPTION is the name of the option and CPU_STRING is the argument.
19671    Return the corresponding processor enumeration if the CPU_STRING is
19672    recognized, otherwise report an error and return null.
19673
19674    A similar function exists in GCC.  */
19675
19676 static const struct mips_cpu_info *
19677 mips_parse_cpu (const char *option, const char *cpu_string)
19678 {
19679   const struct mips_cpu_info *p;
19680
19681   /* 'from-abi' selects the most compatible architecture for the given
19682      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19683      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19684      version.  Look first at the -mgp options, if given, otherwise base
19685      the choice on MIPS_DEFAULT_64BIT.
19686
19687      Treat NO_ABI like the EABIs.  One reason to do this is that the
19688      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19689      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19690      'mips64', just as we did in the days before 'from-abi'.  */
19691   if (strcasecmp (cpu_string, "from-abi") == 0)
19692     {
19693       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19694         return mips_cpu_info_from_isa (ISA_MIPS1);
19695
19696       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19697         return mips_cpu_info_from_isa (ISA_MIPS3);
19698
19699       if (file_mips_opts.gp >= 0)
19700         return mips_cpu_info_from_isa (file_mips_opts.gp == 32
19701                                        ? ISA_MIPS1 : ISA_MIPS3);
19702
19703       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19704                                      ? ISA_MIPS3
19705                                      : ISA_MIPS1);
19706     }
19707
19708   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19709   if (strcasecmp (cpu_string, "default") == 0)
19710     return 0;
19711
19712   for (p = mips_cpu_info_table; p->name != 0; p++)
19713     if (mips_matching_cpu_name_p (p->name, cpu_string))
19714       return p;
19715
19716   as_bad (_("bad value (%s) for %s"), cpu_string, option);
19717   return 0;
19718 }
19719
19720 /* Return the canonical processor information for ISA (a member of the
19721    ISA_MIPS* enumeration).  */
19722
19723 static const struct mips_cpu_info *
19724 mips_cpu_info_from_isa (int isa)
19725 {
19726   int i;
19727
19728   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19729     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19730         && isa == mips_cpu_info_table[i].isa)
19731       return (&mips_cpu_info_table[i]);
19732
19733   return NULL;
19734 }
19735
19736 static const struct mips_cpu_info *
19737 mips_cpu_info_from_arch (int arch)
19738 {
19739   int i;
19740
19741   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19742     if (arch == mips_cpu_info_table[i].cpu)
19743       return (&mips_cpu_info_table[i]);
19744
19745   return NULL;
19746 }
19747 \f
19748 static void
19749 show (FILE *stream, const char *string, int *col_p, int *first_p)
19750 {
19751   if (*first_p)
19752     {
19753       fprintf (stream, "%24s", "");
19754       *col_p = 24;
19755     }
19756   else
19757     {
19758       fprintf (stream, ", ");
19759       *col_p += 2;
19760     }
19761
19762   if (*col_p + strlen (string) > 72)
19763     {
19764       fprintf (stream, "\n%24s", "");
19765       *col_p = 24;
19766     }
19767
19768   fprintf (stream, "%s", string);
19769   *col_p += strlen (string);
19770
19771   *first_p = 0;
19772 }
19773
19774 void
19775 md_show_usage (FILE *stream)
19776 {
19777   int column, first;
19778   size_t i;
19779
19780   fprintf (stream, _("\
19781 MIPS options:\n\
19782 -EB                     generate big endian output\n\
19783 -EL                     generate little endian output\n\
19784 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19785 -G NUM                  allow referencing objects up to NUM bytes\n\
19786                         implicitly with the gp register [default 8]\n"));
19787   fprintf (stream, _("\
19788 -mips1                  generate MIPS ISA I instructions\n\
19789 -mips2                  generate MIPS ISA II instructions\n\
19790 -mips3                  generate MIPS ISA III instructions\n\
19791 -mips4                  generate MIPS ISA IV instructions\n\
19792 -mips5                  generate MIPS ISA V instructions\n\
19793 -mips32                 generate MIPS32 ISA instructions\n\
19794 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19795 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
19796 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
19797 -mips32r6               generate MIPS32 release 6 ISA instructions\n\
19798 -mips64                 generate MIPS64 ISA instructions\n\
19799 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19800 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
19801 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
19802 -mips64r6               generate MIPS64 release 6 ISA instructions\n\
19803 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19804
19805   first = 1;
19806
19807   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19808     show (stream, mips_cpu_info_table[i].name, &column, &first);
19809   show (stream, "from-abi", &column, &first);
19810   fputc ('\n', stream);
19811
19812   fprintf (stream, _("\
19813 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19814 -no-mCPU                don't generate code specific to CPU.\n\
19815                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19816
19817   first = 1;
19818
19819   show (stream, "3900", &column, &first);
19820   show (stream, "4010", &column, &first);
19821   show (stream, "4100", &column, &first);
19822   show (stream, "4650", &column, &first);
19823   fputc ('\n', stream);
19824
19825   fprintf (stream, _("\
19826 -mips16                 generate mips16 instructions\n\
19827 -no-mips16              do not generate mips16 instructions\n"));
19828   fprintf (stream, _("\
19829 -mmicromips             generate microMIPS instructions\n\
19830 -mno-micromips          do not generate microMIPS instructions\n"));
19831   fprintf (stream, _("\
19832 -msmartmips             generate smartmips instructions\n\
19833 -mno-smartmips          do not generate smartmips instructions\n"));
19834   fprintf (stream, _("\
19835 -mdsp                   generate DSP instructions\n\
19836 -mno-dsp                do not generate DSP instructions\n"));
19837   fprintf (stream, _("\
19838 -mdspr2                 generate DSP R2 instructions\n\
19839 -mno-dspr2              do not generate DSP R2 instructions\n"));
19840   fprintf (stream, _("\
19841 -mdspr3                 generate DSP R3 instructions\n\
19842 -mno-dspr3              do not generate DSP R3 instructions\n"));
19843   fprintf (stream, _("\
19844 -mmt                    generate MT instructions\n\
19845 -mno-mt                 do not generate MT instructions\n"));
19846   fprintf (stream, _("\
19847 -mmcu                   generate MCU instructions\n\
19848 -mno-mcu                do not generate MCU instructions\n"));
19849   fprintf (stream, _("\
19850 -mmsa                   generate MSA instructions\n\
19851 -mno-msa                do not generate MSA instructions\n"));
19852   fprintf (stream, _("\
19853 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
19854 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
19855   fprintf (stream, _("\
19856 -mvirt                  generate Virtualization instructions\n\
19857 -mno-virt               do not generate Virtualization instructions\n"));
19858   fprintf (stream, _("\
19859 -minsn32                only generate 32-bit microMIPS instructions\n\
19860 -mno-insn32             generate all microMIPS instructions\n"));
19861   fprintf (stream, _("\
19862 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19863 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19864 -mfix-vr4120            work around certain VR4120 errata\n\
19865 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19866 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19867 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19868 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19869 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19870 -msym32                 assume all symbols have 32-bit values\n\
19871 -O0                     remove unneeded NOPs, do not swap branches\n\
19872 -O                      remove unneeded NOPs and swap branches\n\
19873 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19874 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19875   fprintf (stream, _("\
19876 -mhard-float            allow floating-point instructions\n\
19877 -msoft-float            do not allow floating-point instructions\n\
19878 -msingle-float          only allow 32-bit floating-point operations\n\
19879 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19880 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
19881 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
19882 -mignore-branch-isa     accept invalid branches requiring an ISA mode switch\n\
19883 -mno-ignore-branch-isa  reject invalid branches requiring an ISA mode switch\n\
19884 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
19885
19886   first = 1;
19887
19888   show (stream, "legacy", &column, &first);
19889   show (stream, "2008", &column, &first);
19890
19891   fputc ('\n', stream);
19892
19893   fprintf (stream, _("\
19894 -KPIC, -call_shared     generate SVR4 position independent code\n\
19895 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19896 -mvxworks-pic           generate VxWorks position independent code\n\
19897 -non_shared             do not generate code that can operate with DSOs\n\
19898 -xgot                   assume a 32 bit GOT\n\
19899 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19900 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19901                         position dependent (non shared) code\n\
19902 -mabi=ABI               create ABI conformant object file for:\n"));
19903
19904   first = 1;
19905
19906   show (stream, "32", &column, &first);
19907   show (stream, "o64", &column, &first);
19908   show (stream, "n32", &column, &first);
19909   show (stream, "64", &column, &first);
19910   show (stream, "eabi", &column, &first);
19911
19912   fputc ('\n', stream);
19913
19914   fprintf (stream, _("\
19915 -32                     create o32 ABI object file (default)\n\
19916 -n32                    create n32 ABI object file\n\
19917 -64                     create 64 ABI object file\n"));
19918 }
19919
19920 #ifdef TE_IRIX
19921 enum dwarf2_format
19922 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19923 {
19924   if (HAVE_64BIT_SYMBOLS)
19925     return dwarf2_format_64bit_irix;
19926   else
19927     return dwarf2_format_32bit;
19928 }
19929 #endif
19930
19931 int
19932 mips_dwarf2_addr_size (void)
19933 {
19934   if (HAVE_64BIT_OBJECTS)
19935     return 8;
19936   else
19937     return 4;
19938 }
19939
19940 /* Standard calling conventions leave the CFA at SP on entry.  */
19941 void
19942 mips_cfi_frame_initial_instructions (void)
19943 {
19944   cfi_add_CFA_def_cfa_register (SP);
19945 }
19946
19947 int
19948 tc_mips_regname_to_dw2regnum (char *regname)
19949 {
19950   unsigned int regnum = -1;
19951   unsigned int reg;
19952
19953   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19954     regnum = reg;
19955
19956   return regnum;
19957 }
19958
19959 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
19960    Given a symbolic attribute NAME, return the proper integer value.
19961    Returns -1 if the attribute is not known.  */
19962
19963 int
19964 mips_convert_symbolic_attribute (const char *name)
19965 {
19966   static const struct
19967   {
19968     const char * name;
19969     const int    tag;
19970   }
19971   attribute_table[] =
19972     {
19973 #define T(tag) {#tag, tag}
19974       T (Tag_GNU_MIPS_ABI_FP),
19975       T (Tag_GNU_MIPS_ABI_MSA),
19976 #undef T
19977     };
19978   unsigned int i;
19979
19980   if (name == NULL)
19981     return -1;
19982
19983   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
19984     if (streq (name, attribute_table[i].name))
19985       return attribute_table[i].tag;
19986
19987   return -1;
19988 }
19989
19990 void
19991 md_mips_end (void)
19992 {
19993   int fpabi = Val_GNU_MIPS_ABI_FP_ANY;
19994
19995   mips_emit_delays ();
19996   if (cur_proc_ptr)
19997     as_warn (_("missing .end at end of assembly"));
19998
19999   /* Just in case no code was emitted, do the consistency check.  */
20000   file_mips_check_options ();
20001
20002   /* Set a floating-point ABI if the user did not.  */
20003   if (obj_elf_seen_attribute (OBJ_ATTR_GNU, Tag_GNU_MIPS_ABI_FP))
20004     {
20005       /* Perform consistency checks on the floating-point ABI.  */
20006       fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20007                                         Tag_GNU_MIPS_ABI_FP);
20008       if (fpabi != Val_GNU_MIPS_ABI_FP_ANY)
20009         check_fpabi (fpabi);
20010     }
20011   else
20012     {
20013       /* Soft-float gets precedence over single-float, the two options should
20014          not be used together so this should not matter.  */
20015       if (file_mips_opts.soft_float == 1)
20016         fpabi = Val_GNU_MIPS_ABI_FP_SOFT;
20017       /* Single-float gets precedence over all double_float cases.  */
20018       else if (file_mips_opts.single_float == 1)
20019         fpabi = Val_GNU_MIPS_ABI_FP_SINGLE;
20020       else
20021         {
20022           switch (file_mips_opts.fp)
20023             {
20024             case 32:
20025               if (file_mips_opts.gp == 32)
20026                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20027               break;
20028             case 0:
20029               fpabi = Val_GNU_MIPS_ABI_FP_XX;
20030               break;
20031             case 64:
20032               if (file_mips_opts.gp == 32 && !file_mips_opts.oddspreg)
20033                 fpabi = Val_GNU_MIPS_ABI_FP_64A;
20034               else if (file_mips_opts.gp == 32)
20035                 fpabi = Val_GNU_MIPS_ABI_FP_64;
20036               else
20037                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20038               break;
20039             }
20040         }
20041
20042       bfd_elf_add_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20043                                 Tag_GNU_MIPS_ABI_FP, fpabi);
20044     }
20045 }
20046
20047 /*  Returns the relocation type required for a particular CFI encoding.  */
20048
20049 bfd_reloc_code_real_type
20050 mips_cfi_reloc_for_encoding (int encoding)
20051 {
20052   if (encoding == (DW_EH_PE_sdata4 | DW_EH_PE_pcrel))
20053     return BFD_RELOC_32_PCREL;
20054   else return BFD_RELOC_NONE;
20055 }