Ensure softfloat and singlefloat take precedence in consistency checks
[platform/upstream/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2014 Free Software Foundation, Inc.
3    Contributed by the OSF and Ralph Campbell.
4    Written by Keith Knowles and Ralph Campbell, working independently.
5    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
6    Support.
7
8    This file is part of GAS.
9
10    GAS is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3, or (at your option)
13    any later version.
14
15    GAS is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with GAS; see the file COPYING.  If not, write to the Free
22    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
23    02110-1301, USA.  */
24
25 #include "as.h"
26 #include "config.h"
27 #include "subsegs.h"
28 #include "safe-ctype.h"
29
30 #include "opcode/mips.h"
31 #include "itbl-ops.h"
32 #include "dwarf2dbg.h"
33 #include "dw2gencfi.h"
34
35 /* Check assumptions made in this file.  */
36 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
37 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
38
39 #ifdef DEBUG
40 #define DBG(x) printf x
41 #else
42 #define DBG(x)
43 #endif
44
45 #define 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 /* True if -mnan=2008, false if -mnan=legacy.  */
271 static bfd_boolean mips_flag_nan2008 = FALSE;
272
273 /* This is the struct we use to hold the module level set of options.
274    Note that we must set the isa field to ISA_UNKNOWN and the ASE, gp and
275    fp fields to -1 to indicate that they have not been initialized.  */
276
277 static struct mips_set_options file_mips_opts =
278 {
279   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
280   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
281   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
282   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
283   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
284 };
285
286 /* This is similar to file_mips_opts, but for the current set of options.  */
287
288 static struct mips_set_options mips_opts =
289 {
290   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
291   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
292   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
293   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
294   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
295 };
296
297 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
298 static unsigned int file_ase_explicit;
299
300 /* These variables are filled in with the masks of registers used.
301    The object format code reads them and puts them in the appropriate
302    place.  */
303 unsigned long mips_gprmask;
304 unsigned long mips_cprmask[4];
305
306 /* True if any MIPS16 code was produced.  */
307 static int file_ase_mips16;
308
309 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
310                               || mips_opts.isa == ISA_MIPS32R2          \
311                               || mips_opts.isa == ISA_MIPS32R3          \
312                               || mips_opts.isa == ISA_MIPS32R5          \
313                               || mips_opts.isa == ISA_MIPS64            \
314                               || mips_opts.isa == ISA_MIPS64R2          \
315                               || mips_opts.isa == ISA_MIPS64R3          \
316                               || mips_opts.isa == ISA_MIPS64R5)
317
318 /* True if any microMIPS code was produced.  */
319 static int file_ase_micromips;
320
321 /* True if we want to create R_MIPS_JALR for jalr $25.  */
322 #ifdef TE_IRIX
323 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
324 #else
325 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
326    because there's no place for any addend, the only acceptable
327    expression is a bare symbol.  */
328 #define MIPS_JALR_HINT_P(EXPR) \
329   (!HAVE_IN_PLACE_ADDENDS \
330    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
331 #endif
332
333 /* The argument of the -march= flag.  The architecture we are assembling.  */
334 static const char *mips_arch_string;
335
336 /* The argument of the -mtune= flag.  The architecture for which we
337    are optimizing.  */
338 static int mips_tune = CPU_UNKNOWN;
339 static const char *mips_tune_string;
340
341 /* True when generating 32-bit code for a 64-bit processor.  */
342 static int mips_32bitmode = 0;
343
344 /* True if the given ABI requires 32-bit registers.  */
345 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
346
347 /* Likewise 64-bit registers.  */
348 #define ABI_NEEDS_64BIT_REGS(ABI)       \
349   ((ABI) == N32_ABI                     \
350    || (ABI) == N64_ABI                  \
351    || (ABI) == O64_ABI)
352
353 /*  Return true if ISA supports 64 bit wide gp registers.  */
354 #define ISA_HAS_64BIT_REGS(ISA)         \
355   ((ISA) == ISA_MIPS3                   \
356    || (ISA) == ISA_MIPS4                \
357    || (ISA) == ISA_MIPS5                \
358    || (ISA) == ISA_MIPS64               \
359    || (ISA) == ISA_MIPS64R2             \
360    || (ISA) == ISA_MIPS64R3             \
361    || (ISA) == ISA_MIPS64R5)
362
363 /*  Return true if ISA supports 64 bit wide float registers.  */
364 #define ISA_HAS_64BIT_FPRS(ISA)         \
365   ((ISA) == ISA_MIPS3                   \
366    || (ISA) == ISA_MIPS4                \
367    || (ISA) == ISA_MIPS5                \
368    || (ISA) == ISA_MIPS32R2             \
369    || (ISA) == ISA_MIPS32R3             \
370    || (ISA) == ISA_MIPS32R5             \
371    || (ISA) == ISA_MIPS64               \
372    || (ISA) == ISA_MIPS64R2             \
373    || (ISA) == ISA_MIPS64R3             \
374    || (ISA) == ISA_MIPS64R5             )
375
376 /* Return true if ISA supports 64-bit right rotate (dror et al.)
377    instructions.  */
378 #define ISA_HAS_DROR(ISA)               \
379   ((ISA) == ISA_MIPS64R2                \
380    || (ISA) == ISA_MIPS64R3             \
381    || (ISA) == ISA_MIPS64R5             \
382    || (mips_opts.micromips              \
383        && ISA_HAS_64BIT_REGS (ISA))     \
384    )
385
386 /* Return true if ISA supports 32-bit right rotate (ror et al.)
387    instructions.  */
388 #define ISA_HAS_ROR(ISA)                \
389   ((ISA) == ISA_MIPS32R2                \
390    || (ISA) == ISA_MIPS32R3             \
391    || (ISA) == ISA_MIPS32R5             \
392    || (ISA) == ISA_MIPS64R2             \
393    || (ISA) == ISA_MIPS64R3             \
394    || (ISA) == ISA_MIPS64R5             \
395    || (mips_opts.ase & ASE_SMARTMIPS)   \
396    || mips_opts.micromips               \
397    )
398
399 /* Return true if ISA supports single-precision floats in odd registers.  */
400 #define ISA_HAS_ODD_SINGLE_FPR(ISA, CPU)\
401   (((ISA) == ISA_MIPS32                 \
402     || (ISA) == ISA_MIPS32R2            \
403     || (ISA) == ISA_MIPS32R3            \
404     || (ISA) == ISA_MIPS32R5            \
405     || (ISA) == ISA_MIPS64              \
406     || (ISA) == ISA_MIPS64R2            \
407     || (ISA) == ISA_MIPS64R3            \
408     || (ISA) == ISA_MIPS64R5            \
409     || (CPU) == CPU_R5900)              \
410    && (CPU) != CPU_LOONGSON_3A)
411
412 /* Return true if ISA supports move to/from high part of a 64-bit
413    floating-point register. */
414 #define ISA_HAS_MXHC1(ISA)              \
415   ((ISA) == ISA_MIPS32R2                \
416    || (ISA) == ISA_MIPS32R3             \
417    || (ISA) == ISA_MIPS32R5             \
418    || (ISA) == ISA_MIPS64R2             \
419    || (ISA) == ISA_MIPS64R3             \
420    || (ISA) == ISA_MIPS64R5)
421
422 #define GPR_SIZE \
423     (mips_opts.gp == 64 && !ISA_HAS_64BIT_REGS (mips_opts.isa) \
424      ? 32 \
425      : mips_opts.gp)
426
427 #define FPR_SIZE \
428     (mips_opts.fp == 64 && !ISA_HAS_64BIT_FPRS (mips_opts.isa) \
429      ? 32 \
430      : mips_opts.fp)
431
432 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
433
434 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
435
436 /* True if relocations are stored in-place.  */
437 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
438
439 /* The ABI-derived address size.  */
440 #define HAVE_64BIT_ADDRESSES \
441   (GPR_SIZE == 64 && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
442 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
443
444 /* The size of symbolic constants (i.e., expressions of the form
445    "SYMBOL" or "SYMBOL + OFFSET").  */
446 #define HAVE_32BIT_SYMBOLS \
447   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
448 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
449
450 /* Addresses are loaded in different ways, depending on the address size
451    in use.  The n32 ABI Documentation also mandates the use of additions
452    with overflow checking, but existing implementations don't follow it.  */
453 #define ADDRESS_ADD_INSN                                                \
454    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
455
456 #define ADDRESS_ADDI_INSN                                               \
457    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
458
459 #define ADDRESS_LOAD_INSN                                               \
460    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
461
462 #define ADDRESS_STORE_INSN                                              \
463    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
464
465 /* Return true if the given CPU supports the MIPS16 ASE.  */
466 #define CPU_HAS_MIPS16(cpu)                                             \
467    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
468     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
469
470 /* Return true if the given CPU supports the microMIPS ASE.  */
471 #define CPU_HAS_MICROMIPS(cpu)  0
472
473 /* True if CPU has a dror instruction.  */
474 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
475
476 /* True if CPU has a ror instruction.  */
477 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
478
479 /* True if CPU is in the Octeon family */
480 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
481
482 /* True if CPU has seq/sne and seqi/snei instructions.  */
483 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
484
485 /* True, if CPU has support for ldc1 and sdc1. */
486 #define CPU_HAS_LDC1_SDC1(CPU)  \
487    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
488
489 /* True if mflo and mfhi can be immediately followed by instructions
490    which write to the HI and LO registers.
491
492    According to MIPS specifications, MIPS ISAs I, II, and III need
493    (at least) two instructions between the reads of HI/LO and
494    instructions which write them, and later ISAs do not.  Contradicting
495    the MIPS specifications, some MIPS IV processor user manuals (e.g.
496    the UM for the NEC Vr5000) document needing the instructions between
497    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
498    MIPS64 and later ISAs to have the interlocks, plus any specific
499    earlier-ISA CPUs for which CPU documentation declares that the
500    instructions are really interlocked.  */
501 #define hilo_interlocks \
502   (mips_opts.isa == ISA_MIPS32                        \
503    || mips_opts.isa == ISA_MIPS32R2                   \
504    || mips_opts.isa == ISA_MIPS32R3                   \
505    || mips_opts.isa == ISA_MIPS32R5                   \
506    || mips_opts.isa == ISA_MIPS64                     \
507    || mips_opts.isa == ISA_MIPS64R2                   \
508    || mips_opts.isa == ISA_MIPS64R3                   \
509    || mips_opts.isa == ISA_MIPS64R5                   \
510    || mips_opts.arch == CPU_R4010                     \
511    || mips_opts.arch == CPU_R5900                     \
512    || mips_opts.arch == CPU_R10000                    \
513    || mips_opts.arch == CPU_R12000                    \
514    || mips_opts.arch == CPU_R14000                    \
515    || mips_opts.arch == CPU_R16000                    \
516    || mips_opts.arch == CPU_RM7000                    \
517    || mips_opts.arch == CPU_VR5500                    \
518    || mips_opts.micromips                             \
519    )
520
521 /* Whether the processor uses hardware interlocks to protect reads
522    from the GPRs after they are loaded from memory, and thus does not
523    require nops to be inserted.  This applies to instructions marked
524    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
525    level I and microMIPS mode instructions are always interlocked.  */
526 #define gpr_interlocks                                \
527   (mips_opts.isa != ISA_MIPS1                         \
528    || mips_opts.arch == CPU_R3900                     \
529    || mips_opts.arch == CPU_R5900                     \
530    || mips_opts.micromips                             \
531    )
532
533 /* Whether the processor uses hardware interlocks to avoid delays
534    required by coprocessor instructions, and thus does not require
535    nops to be inserted.  This applies to instructions marked
536    INSN_LOAD_COPROC, INSN_COPROC_MOVE, and to delays between
537    instructions marked INSN_WRITE_COND_CODE and ones marked
538    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
539    levels I, II, and III and microMIPS mode instructions are always
540    interlocked.  */
541 /* Itbl support may require additional care here.  */
542 #define cop_interlocks                                \
543   ((mips_opts.isa != ISA_MIPS1                        \
544     && mips_opts.isa != ISA_MIPS2                     \
545     && mips_opts.isa != ISA_MIPS3)                    \
546    || mips_opts.arch == CPU_R4300                     \
547    || mips_opts.micromips                             \
548    )
549
550 /* Whether the processor uses hardware interlocks to protect reads
551    from coprocessor registers after they are loaded from memory, and
552    thus does not require nops to be inserted.  This applies to
553    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
554    requires at MIPS ISA level I and microMIPS mode instructions are
555    always interlocked.  */
556 #define cop_mem_interlocks                            \
557   (mips_opts.isa != ISA_MIPS1                         \
558    || mips_opts.micromips                             \
559    )
560
561 /* Is this a mfhi or mflo instruction?  */
562 #define MF_HILO_INSN(PINFO) \
563   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
564
565 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
566    has been selected.  This implies, in particular, that addresses of text
567    labels have their LSB set.  */
568 #define HAVE_CODE_COMPRESSION                                           \
569   ((mips_opts.mips16 | mips_opts.micromips) != 0)
570
571 /* The minimum and maximum signed values that can be stored in a GPR.  */
572 #define GPR_SMAX ((offsetT) (((valueT) 1 << (GPR_SIZE - 1)) - 1))
573 #define GPR_SMIN (-GPR_SMAX - 1)
574
575 /* MIPS PIC level.  */
576
577 enum mips_pic_level mips_pic;
578
579 /* 1 if we should generate 32 bit offsets from the $gp register in
580    SVR4_PIC mode.  Currently has no meaning in other modes.  */
581 static int mips_big_got = 0;
582
583 /* 1 if trap instructions should used for overflow rather than break
584    instructions.  */
585 static int mips_trap = 0;
586
587 /* 1 if double width floating point constants should not be constructed
588    by assembling two single width halves into two single width floating
589    point registers which just happen to alias the double width destination
590    register.  On some architectures this aliasing can be disabled by a bit
591    in the status register, and the setting of this bit cannot be determined
592    automatically at assemble time.  */
593 static int mips_disable_float_construction;
594
595 /* Non-zero if any .set noreorder directives were used.  */
596
597 static int mips_any_noreorder;
598
599 /* Non-zero if nops should be inserted when the register referenced in
600    an mfhi/mflo instruction is read in the next two instructions.  */
601 static int mips_7000_hilo_fix;
602
603 /* The size of objects in the small data section.  */
604 static unsigned int g_switch_value = 8;
605 /* Whether the -G option was used.  */
606 static int g_switch_seen = 0;
607
608 #define N_RMASK 0xc4
609 #define N_VFP   0xd4
610
611 /* If we can determine in advance that GP optimization won't be
612    possible, we can skip the relaxation stuff that tries to produce
613    GP-relative references.  This makes delay slot optimization work
614    better.
615
616    This function can only provide a guess, but it seems to work for
617    gcc output.  It needs to guess right for gcc, otherwise gcc
618    will put what it thinks is a GP-relative instruction in a branch
619    delay slot.
620
621    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
622    fixed it for the non-PIC mode.  KR 95/04/07  */
623 static int nopic_need_relax (symbolS *, int);
624
625 /* handle of the OPCODE hash table */
626 static struct hash_control *op_hash = NULL;
627
628 /* The opcode hash table we use for the mips16.  */
629 static struct hash_control *mips16_op_hash = NULL;
630
631 /* The opcode hash table we use for the microMIPS ASE.  */
632 static struct hash_control *micromips_op_hash = NULL;
633
634 /* This array holds the chars that always start a comment.  If the
635     pre-processor is disabled, these aren't very useful */
636 const char comment_chars[] = "#";
637
638 /* This array holds the chars that only start a comment at the beginning of
639    a line.  If the line seems to have the form '# 123 filename'
640    .line and .file directives will appear in the pre-processed output */
641 /* Note that input_file.c hand checks for '#' at the beginning of the
642    first line of the input file.  This is because the compiler outputs
643    #NO_APP at the beginning of its output.  */
644 /* Also note that C style comments are always supported.  */
645 const char line_comment_chars[] = "#";
646
647 /* This array holds machine specific line separator characters.  */
648 const char line_separator_chars[] = ";";
649
650 /* Chars that can be used to separate mant from exp in floating point nums */
651 const char EXP_CHARS[] = "eE";
652
653 /* Chars that mean this number is a floating point constant */
654 /* As in 0f12.456 */
655 /* or    0d1.2345e12 */
656 const char FLT_CHARS[] = "rRsSfFdDxXpP";
657
658 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
659    changed in read.c .  Ideally it shouldn't have to know about it at all,
660    but nothing is ideal around here.
661  */
662
663 /* Types of printf format used for instruction-related error messages.
664    "I" means int ("%d") and "S" means string ("%s"). */
665 enum mips_insn_error_format {
666   ERR_FMT_PLAIN,
667   ERR_FMT_I,
668   ERR_FMT_SS,
669 };
670
671 /* Information about an error that was found while assembling the current
672    instruction.  */
673 struct mips_insn_error {
674   /* We sometimes need to match an instruction against more than one
675      opcode table entry.  Errors found during this matching are reported
676      against a particular syntactic argument rather than against the
677      instruction as a whole.  We grade these messages so that errors
678      against argument N have a greater priority than an error against
679      any argument < N, since the former implies that arguments up to N
680      were acceptable and that the opcode entry was therefore a closer match.
681      If several matches report an error against the same argument,
682      we only use that error if it is the same in all cases.
683
684      min_argnum is the minimum argument number for which an error message
685      should be accepted.  It is 0 if MSG is against the instruction as
686      a whole.  */
687   int min_argnum;
688
689   /* The printf()-style message, including its format and arguments.  */
690   enum mips_insn_error_format format;
691   const char *msg;
692   union {
693     int i;
694     const char *ss[2];
695   } u;
696 };
697
698 /* The error that should be reported for the current instruction.  */
699 static struct mips_insn_error insn_error;
700
701 static int auto_align = 1;
702
703 /* When outputting SVR4 PIC code, the assembler needs to know the
704    offset in the stack frame from which to restore the $gp register.
705    This is set by the .cprestore pseudo-op, and saved in this
706    variable.  */
707 static offsetT mips_cprestore_offset = -1;
708
709 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
710    more optimizations, it can use a register value instead of a memory-saved
711    offset and even an other register than $gp as global pointer.  */
712 static offsetT mips_cpreturn_offset = -1;
713 static int mips_cpreturn_register = -1;
714 static int mips_gp_register = GP;
715 static int mips_gprel_offset = 0;
716
717 /* Whether mips_cprestore_offset has been set in the current function
718    (or whether it has already been warned about, if not).  */
719 static int mips_cprestore_valid = 0;
720
721 /* This is the register which holds the stack frame, as set by the
722    .frame pseudo-op.  This is needed to implement .cprestore.  */
723 static int mips_frame_reg = SP;
724
725 /* Whether mips_frame_reg has been set in the current function
726    (or whether it has already been warned about, if not).  */
727 static int mips_frame_reg_valid = 0;
728
729 /* To output NOP instructions correctly, we need to keep information
730    about the previous two instructions.  */
731
732 /* Whether we are optimizing.  The default value of 2 means to remove
733    unneeded NOPs and swap branch instructions when possible.  A value
734    of 1 means to not swap branches.  A value of 0 means to always
735    insert NOPs.  */
736 static int mips_optimize = 2;
737
738 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
739    equivalent to seeing no -g option at all.  */
740 static int mips_debug = 0;
741
742 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
743 #define MAX_VR4130_NOPS 4
744
745 /* The maximum number of NOPs needed to fill delay slots.  */
746 #define MAX_DELAY_NOPS 2
747
748 /* The maximum number of NOPs needed for any purpose.  */
749 #define MAX_NOPS 4
750
751 /* A list of previous instructions, with index 0 being the most recent.
752    We need to look back MAX_NOPS instructions when filling delay slots
753    or working around processor errata.  We need to look back one
754    instruction further if we're thinking about using history[0] to
755    fill a branch delay slot.  */
756 static struct mips_cl_insn history[1 + MAX_NOPS];
757
758 /* Arrays of operands for each instruction.  */
759 #define MAX_OPERANDS 6
760 struct mips_operand_array {
761   const struct mips_operand *operand[MAX_OPERANDS];
762 };
763 static struct mips_operand_array *mips_operands;
764 static struct mips_operand_array *mips16_operands;
765 static struct mips_operand_array *micromips_operands;
766
767 /* Nop instructions used by emit_nop.  */
768 static struct mips_cl_insn nop_insn;
769 static struct mips_cl_insn mips16_nop_insn;
770 static struct mips_cl_insn micromips_nop16_insn;
771 static struct mips_cl_insn micromips_nop32_insn;
772
773 /* The appropriate nop for the current mode.  */
774 #define NOP_INSN (mips_opts.mips16                                      \
775                   ? &mips16_nop_insn                                    \
776                   : (mips_opts.micromips                                \
777                      ? (mips_opts.insn32                                \
778                         ? &micromips_nop32_insn                         \
779                         : &micromips_nop16_insn)                        \
780                      : &nop_insn))
781
782 /* The size of NOP_INSN in bytes.  */
783 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
784                         || (mips_opts.micromips && !mips_opts.insn32))  \
785                        ? 2 : 4)
786
787 /* If this is set, it points to a frag holding nop instructions which
788    were inserted before the start of a noreorder section.  If those
789    nops turn out to be unnecessary, the size of the frag can be
790    decreased.  */
791 static fragS *prev_nop_frag;
792
793 /* The number of nop instructions we created in prev_nop_frag.  */
794 static int prev_nop_frag_holds;
795
796 /* The number of nop instructions that we know we need in
797    prev_nop_frag.  */
798 static int prev_nop_frag_required;
799
800 /* The number of instructions we've seen since prev_nop_frag.  */
801 static int prev_nop_frag_since;
802
803 /* Relocations against symbols are sometimes done in two parts, with a HI
804    relocation and a LO relocation.  Each relocation has only 16 bits of
805    space to store an addend.  This means that in order for the linker to
806    handle carries correctly, it must be able to locate both the HI and
807    the LO relocation.  This means that the relocations must appear in
808    order in the relocation table.
809
810    In order to implement this, we keep track of each unmatched HI
811    relocation.  We then sort them so that they immediately precede the
812    corresponding LO relocation.  */
813
814 struct mips_hi_fixup
815 {
816   /* Next HI fixup.  */
817   struct mips_hi_fixup *next;
818   /* This fixup.  */
819   fixS *fixp;
820   /* The section this fixup is in.  */
821   segT seg;
822 };
823
824 /* The list of unmatched HI relocs.  */
825
826 static struct mips_hi_fixup *mips_hi_fixup_list;
827
828 /* The frag containing the last explicit relocation operator.
829    Null if explicit relocations have not been used.  */
830
831 static fragS *prev_reloc_op_frag;
832
833 /* Map mips16 register numbers to normal MIPS register numbers.  */
834
835 static const unsigned int mips16_to_32_reg_map[] =
836 {
837   16, 17, 2, 3, 4, 5, 6, 7
838 };
839
840 /* Map microMIPS register numbers to normal MIPS register numbers.  */
841
842 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
843
844 /* The microMIPS registers with type h.  */
845 static const unsigned int micromips_to_32_reg_h_map1[] =
846 {
847   5, 5, 6, 4, 4, 4, 4, 4
848 };
849 static const unsigned int micromips_to_32_reg_h_map2[] =
850 {
851   6, 7, 7, 21, 22, 5, 6, 7
852 };
853
854 /* The microMIPS registers with type m.  */
855 static const unsigned int micromips_to_32_reg_m_map[] =
856 {
857   0, 17, 2, 3, 16, 18, 19, 20
858 };
859
860 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
861
862 /* Classifies the kind of instructions we're interested in when
863    implementing -mfix-vr4120.  */
864 enum fix_vr4120_class
865 {
866   FIX_VR4120_MACC,
867   FIX_VR4120_DMACC,
868   FIX_VR4120_MULT,
869   FIX_VR4120_DMULT,
870   FIX_VR4120_DIV,
871   FIX_VR4120_MTHILO,
872   NUM_FIX_VR4120_CLASSES
873 };
874
875 /* ...likewise -mfix-loongson2f-jump.  */
876 static bfd_boolean mips_fix_loongson2f_jump;
877
878 /* ...likewise -mfix-loongson2f-nop.  */
879 static bfd_boolean mips_fix_loongson2f_nop;
880
881 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
882 static bfd_boolean mips_fix_loongson2f;
883
884 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
885    there must be at least one other instruction between an instruction
886    of type X and an instruction of type Y.  */
887 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
888
889 /* True if -mfix-vr4120 is in force.  */
890 static int mips_fix_vr4120;
891
892 /* ...likewise -mfix-vr4130.  */
893 static int mips_fix_vr4130;
894
895 /* ...likewise -mfix-24k.  */
896 static int mips_fix_24k;
897
898 /* ...likewise -mfix-rm7000  */
899 static int mips_fix_rm7000;
900
901 /* ...likewise -mfix-cn63xxp1 */
902 static bfd_boolean mips_fix_cn63xxp1;
903
904 /* We don't relax branches by default, since this causes us to expand
905    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
906    fail to compute the offset before expanding the macro to the most
907    efficient expansion.  */
908
909 static int mips_relax_branch;
910 \f
911 /* The expansion of many macros depends on the type of symbol that
912    they refer to.  For example, when generating position-dependent code,
913    a macro that refers to a symbol may have two different expansions,
914    one which uses GP-relative addresses and one which uses absolute
915    addresses.  When generating SVR4-style PIC, a macro may have
916    different expansions for local and global symbols.
917
918    We handle these situations by generating both sequences and putting
919    them in variant frags.  In position-dependent code, the first sequence
920    will be the GP-relative one and the second sequence will be the
921    absolute one.  In SVR4 PIC, the first sequence will be for global
922    symbols and the second will be for local symbols.
923
924    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
925    SECOND are the lengths of the two sequences in bytes.  These fields
926    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
927    the subtype has the following flags:
928
929    RELAX_USE_SECOND
930         Set if it has been decided that we should use the second
931         sequence instead of the first.
932
933    RELAX_SECOND_LONGER
934         Set in the first variant frag if the macro's second implementation
935         is longer than its first.  This refers to the macro as a whole,
936         not an individual relaxation.
937
938    RELAX_NOMACRO
939         Set in the first variant frag if the macro appeared in a .set nomacro
940         block and if one alternative requires a warning but the other does not.
941
942    RELAX_DELAY_SLOT
943         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
944         delay slot.
945
946    RELAX_DELAY_SLOT_16BIT
947         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
948         16-bit instruction.
949
950    RELAX_DELAY_SLOT_SIZE_FIRST
951         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
952         the macro is of the wrong size for the branch delay slot.
953
954    RELAX_DELAY_SLOT_SIZE_SECOND
955         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
956         the macro is of the wrong size for the branch delay slot.
957
958    The frag's "opcode" points to the first fixup for relaxable code.
959
960    Relaxable macros are generated using a sequence such as:
961
962       relax_start (SYMBOL);
963       ... generate first expansion ...
964       relax_switch ();
965       ... generate second expansion ...
966       relax_end ();
967
968    The code and fixups for the unwanted alternative are discarded
969    by md_convert_frag.  */
970 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
971
972 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
973 #define RELAX_SECOND(X) ((X) & 0xff)
974 #define RELAX_USE_SECOND 0x10000
975 #define RELAX_SECOND_LONGER 0x20000
976 #define RELAX_NOMACRO 0x40000
977 #define RELAX_DELAY_SLOT 0x80000
978 #define RELAX_DELAY_SLOT_16BIT 0x100000
979 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
980 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
981
982 /* Branch without likely bit.  If label is out of range, we turn:
983
984         beq reg1, reg2, label
985         delay slot
986
987    into
988
989         bne reg1, reg2, 0f
990         nop
991         j label
992      0: delay slot
993
994    with the following opcode replacements:
995
996         beq <-> bne
997         blez <-> bgtz
998         bltz <-> bgez
999         bc1f <-> bc1t
1000
1001         bltzal <-> bgezal  (with jal label instead of j label)
1002
1003    Even though keeping the delay slot instruction in the delay slot of
1004    the branch would be more efficient, it would be very tricky to do
1005    correctly, because we'd have to introduce a variable frag *after*
1006    the delay slot instruction, and expand that instead.  Let's do it
1007    the easy way for now, even if the branch-not-taken case now costs
1008    one additional instruction.  Out-of-range branches are not supposed
1009    to be common, anyway.
1010
1011    Branch likely.  If label is out of range, we turn:
1012
1013         beql reg1, reg2, label
1014         delay slot (annulled if branch not taken)
1015
1016    into
1017
1018         beql reg1, reg2, 1f
1019         nop
1020         beql $0, $0, 2f
1021         nop
1022      1: j[al] label
1023         delay slot (executed only if branch taken)
1024      2:
1025
1026    It would be possible to generate a shorter sequence by losing the
1027    likely bit, generating something like:
1028
1029         bne reg1, reg2, 0f
1030         nop
1031         j[al] label
1032         delay slot (executed only if branch taken)
1033      0:
1034
1035         beql -> bne
1036         bnel -> beq
1037         blezl -> bgtz
1038         bgtzl -> blez
1039         bltzl -> bgez
1040         bgezl -> bltz
1041         bc1fl -> bc1t
1042         bc1tl -> bc1f
1043
1044         bltzall -> bgezal  (with jal label instead of j label)
1045         bgezall -> bltzal  (ditto)
1046
1047
1048    but it's not clear that it would actually improve performance.  */
1049 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1050   ((relax_substateT)                                            \
1051    (0xc0000000                                                  \
1052     | ((at) & 0x1f)                                             \
1053     | ((toofar) ? 0x20 : 0)                                     \
1054     | ((link) ? 0x40 : 0)                                       \
1055     | ((likely) ? 0x80 : 0)                                     \
1056     | ((uncond) ? 0x100 : 0)))
1057 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1058 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1059 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1060 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1061 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1062 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1063
1064 /* For mips16 code, we use an entirely different form of relaxation.
1065    mips16 supports two versions of most instructions which take
1066    immediate values: a small one which takes some small value, and a
1067    larger one which takes a 16 bit value.  Since branches also follow
1068    this pattern, relaxing these values is required.
1069
1070    We can assemble both mips16 and normal MIPS code in a single
1071    object.  Therefore, we need to support this type of relaxation at
1072    the same time that we support the relaxation described above.  We
1073    use the high bit of the subtype field to distinguish these cases.
1074
1075    The information we store for this type of relaxation is the
1076    argument code found in the opcode file for this relocation, whether
1077    the user explicitly requested a small or extended form, and whether
1078    the relocation is in a jump or jal delay slot.  That tells us the
1079    size of the value, and how it should be stored.  We also store
1080    whether the fragment is considered to be extended or not.  We also
1081    store whether this is known to be a branch to a different section,
1082    whether we have tried to relax this frag yet, and whether we have
1083    ever extended a PC relative fragment because of a shift count.  */
1084 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1085   (0x80000000                                                   \
1086    | ((type) & 0xff)                                            \
1087    | ((small) ? 0x100 : 0)                                      \
1088    | ((ext) ? 0x200 : 0)                                        \
1089    | ((dslot) ? 0x400 : 0)                                      \
1090    | ((jal_dslot) ? 0x800 : 0))
1091 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1092 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1093 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1094 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1095 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1096 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1097 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1098 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1099 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1100 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1101 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1102 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1103
1104 /* For microMIPS code, we use relaxation similar to one we use for
1105    MIPS16 code.  Some instructions that take immediate values support
1106    two encodings: a small one which takes some small value, and a
1107    larger one which takes a 16 bit value.  As some branches also follow
1108    this pattern, relaxing these values is required.
1109
1110    We can assemble both microMIPS and normal MIPS code in a single
1111    object.  Therefore, we need to support this type of relaxation at
1112    the same time that we support the relaxation described above.  We
1113    use one of the high bits of the subtype field to distinguish these
1114    cases.
1115
1116    The information we store for this type of relaxation is the argument
1117    code found in the opcode file for this relocation, the register
1118    selected as the assembler temporary, whether the branch is
1119    unconditional, whether it is compact, whether it stores the link
1120    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1121    branches to a sequence of instructions is enabled, and whether the
1122    displacement of a branch is too large to fit as an immediate argument
1123    of a 16-bit and a 32-bit branch, respectively.  */
1124 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1125                                relax32, toofar16, toofar32)     \
1126   (0x40000000                                                   \
1127    | ((type) & 0xff)                                            \
1128    | (((at) & 0x1f) << 8)                                       \
1129    | ((uncond) ? 0x2000 : 0)                                    \
1130    | ((compact) ? 0x4000 : 0)                                   \
1131    | ((link) ? 0x8000 : 0)                                      \
1132    | ((relax32) ? 0x10000 : 0)                                  \
1133    | ((toofar16) ? 0x20000 : 0)                                 \
1134    | ((toofar32) ? 0x40000 : 0))
1135 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1136 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1137 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1138 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1139 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1140 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1141 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1142
1143 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1144 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1145 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1146 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1147 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1148 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1149
1150 /* Sign-extend 16-bit value X.  */
1151 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1152
1153 /* Is the given value a sign-extended 32-bit value?  */
1154 #define IS_SEXT_32BIT_NUM(x)                                            \
1155   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1156    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1157
1158 /* Is the given value a sign-extended 16-bit value?  */
1159 #define IS_SEXT_16BIT_NUM(x)                                            \
1160   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1161    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1162
1163 /* Is the given value a sign-extended 12-bit value?  */
1164 #define IS_SEXT_12BIT_NUM(x)                                            \
1165   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1166
1167 /* Is the given value a sign-extended 9-bit value?  */
1168 #define IS_SEXT_9BIT_NUM(x)                                             \
1169   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1170
1171 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1172 #define IS_ZEXT_32BIT_NUM(x)                                            \
1173   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1174    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1175
1176 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1177    SHIFT places.  */
1178 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1179   (((STRUCT) >> (SHIFT)) & (MASK))
1180
1181 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1182 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1183   (!(MICROMIPS) \
1184    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1185    : EXTRACT_BITS ((INSN).insn_opcode, \
1186                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1187 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1188   EXTRACT_BITS ((INSN).insn_opcode, \
1189                 MIPS16OP_MASK_##FIELD, \
1190                 MIPS16OP_SH_##FIELD)
1191
1192 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1193 #define MIPS16_EXTEND (0xf000U << 16)
1194 \f
1195 /* Whether or not we are emitting a branch-likely macro.  */
1196 static bfd_boolean emit_branch_likely_macro = FALSE;
1197
1198 /* Global variables used when generating relaxable macros.  See the
1199    comment above RELAX_ENCODE for more details about how relaxation
1200    is used.  */
1201 static struct {
1202   /* 0 if we're not emitting a relaxable macro.
1203      1 if we're emitting the first of the two relaxation alternatives.
1204      2 if we're emitting the second alternative.  */
1205   int sequence;
1206
1207   /* The first relaxable fixup in the current frag.  (In other words,
1208      the first fixup that refers to relaxable code.)  */
1209   fixS *first_fixup;
1210
1211   /* sizes[0] says how many bytes of the first alternative are stored in
1212      the current frag.  Likewise sizes[1] for the second alternative.  */
1213   unsigned int sizes[2];
1214
1215   /* The symbol on which the choice of sequence depends.  */
1216   symbolS *symbol;
1217 } mips_relax;
1218 \f
1219 /* Global variables used to decide whether a macro needs a warning.  */
1220 static struct {
1221   /* True if the macro is in a branch delay slot.  */
1222   bfd_boolean delay_slot_p;
1223
1224   /* Set to the length in bytes required if the macro is in a delay slot
1225      that requires a specific length of instruction, otherwise zero.  */
1226   unsigned int delay_slot_length;
1227
1228   /* For relaxable macros, sizes[0] is the length of the first alternative
1229      in bytes and sizes[1] is the length of the second alternative.
1230      For non-relaxable macros, both elements give the length of the
1231      macro in bytes.  */
1232   unsigned int sizes[2];
1233
1234   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1235      instruction of the first alternative in bytes and first_insn_sizes[1]
1236      is the length of the first instruction of the second alternative.
1237      For non-relaxable macros, both elements give the length of the first
1238      instruction in bytes.
1239
1240      Set to zero if we haven't yet seen the first instruction.  */
1241   unsigned int first_insn_sizes[2];
1242
1243   /* For relaxable macros, insns[0] is the number of instructions for the
1244      first alternative and insns[1] is the number of instructions for the
1245      second alternative.
1246
1247      For non-relaxable macros, both elements give the number of
1248      instructions for the macro.  */
1249   unsigned int insns[2];
1250
1251   /* The first variant frag for this macro.  */
1252   fragS *first_frag;
1253 } mips_macro_warning;
1254 \f
1255 /* Prototypes for static functions.  */
1256
1257 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1258
1259 static void append_insn
1260   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1261    bfd_boolean expansionp);
1262 static void mips_no_prev_insn (void);
1263 static void macro_build (expressionS *, const char *, const char *, ...);
1264 static void mips16_macro_build
1265   (expressionS *, const char *, const char *, va_list *);
1266 static void load_register (int, expressionS *, int);
1267 static void macro_start (void);
1268 static void macro_end (void);
1269 static void macro (struct mips_cl_insn *ip, char *str);
1270 static void mips16_macro (struct mips_cl_insn * ip);
1271 static void mips_ip (char *str, struct mips_cl_insn * ip);
1272 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1273 static void mips16_immed
1274   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1275    unsigned int, unsigned long *);
1276 static size_t my_getSmallExpression
1277   (expressionS *, bfd_reloc_code_real_type *, char *);
1278 static void my_getExpression (expressionS *, char *);
1279 static void s_align (int);
1280 static void s_change_sec (int);
1281 static void s_change_section (int);
1282 static void s_cons (int);
1283 static void s_float_cons (int);
1284 static void s_mips_globl (int);
1285 static void s_option (int);
1286 static void s_mipsset (int);
1287 static void s_abicalls (int);
1288 static void s_cpload (int);
1289 static void s_cpsetup (int);
1290 static void s_cplocal (int);
1291 static void s_cprestore (int);
1292 static void s_cpreturn (int);
1293 static void s_dtprelword (int);
1294 static void s_dtpreldword (int);
1295 static void s_tprelword (int);
1296 static void s_tpreldword (int);
1297 static void s_gpvalue (int);
1298 static void s_gpword (int);
1299 static void s_gpdword (int);
1300 static void s_ehword (int);
1301 static void s_cpadd (int);
1302 static void s_insn (int);
1303 static void s_nan (int);
1304 static void s_module (int);
1305 static void s_mips_ent (int);
1306 static void s_mips_end (int);
1307 static void s_mips_frame (int);
1308 static void s_mips_mask (int reg_type);
1309 static void s_mips_stab (int);
1310 static void s_mips_weakext (int);
1311 static void s_mips_file (int);
1312 static void s_mips_loc (int);
1313 static bfd_boolean pic_need_relax (symbolS *, asection *);
1314 static int relaxed_branch_length (fragS *, asection *, int);
1315 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1316 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1317 static void file_mips_check_options (void);
1318
1319 /* Table and functions used to map between CPU/ISA names, and
1320    ISA levels, and CPU numbers.  */
1321
1322 struct mips_cpu_info
1323 {
1324   const char *name;           /* CPU or ISA name.  */
1325   int flags;                  /* MIPS_CPU_* flags.  */
1326   int ase;                    /* Set of ASEs implemented by the CPU.  */
1327   int isa;                    /* ISA level.  */
1328   int cpu;                    /* CPU number (default CPU if ISA).  */
1329 };
1330
1331 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1332
1333 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1334 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1335 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1336 \f
1337 /* Command-line options.  */
1338 const char *md_shortopts = "O::g::G:";
1339
1340 enum options
1341   {
1342     OPTION_MARCH = OPTION_MD_BASE,
1343     OPTION_MTUNE,
1344     OPTION_MIPS1,
1345     OPTION_MIPS2,
1346     OPTION_MIPS3,
1347     OPTION_MIPS4,
1348     OPTION_MIPS5,
1349     OPTION_MIPS32,
1350     OPTION_MIPS64,
1351     OPTION_MIPS32R2,
1352     OPTION_MIPS32R3,
1353     OPTION_MIPS32R5,
1354     OPTION_MIPS64R2,
1355     OPTION_MIPS64R3,
1356     OPTION_MIPS64R5,
1357     OPTION_MIPS16,
1358     OPTION_NO_MIPS16,
1359     OPTION_MIPS3D,
1360     OPTION_NO_MIPS3D,
1361     OPTION_MDMX,
1362     OPTION_NO_MDMX,
1363     OPTION_DSP,
1364     OPTION_NO_DSP,
1365     OPTION_MT,
1366     OPTION_NO_MT,
1367     OPTION_VIRT,
1368     OPTION_NO_VIRT,
1369     OPTION_MSA,
1370     OPTION_NO_MSA,
1371     OPTION_SMARTMIPS,
1372     OPTION_NO_SMARTMIPS,
1373     OPTION_DSPR2,
1374     OPTION_NO_DSPR2,
1375     OPTION_EVA,
1376     OPTION_NO_EVA,
1377     OPTION_XPA,
1378     OPTION_NO_XPA,
1379     OPTION_MICROMIPS,
1380     OPTION_NO_MICROMIPS,
1381     OPTION_MCU,
1382     OPTION_NO_MCU,
1383     OPTION_COMPAT_ARCH_BASE,
1384     OPTION_M4650,
1385     OPTION_NO_M4650,
1386     OPTION_M4010,
1387     OPTION_NO_M4010,
1388     OPTION_M4100,
1389     OPTION_NO_M4100,
1390     OPTION_M3900,
1391     OPTION_NO_M3900,
1392     OPTION_M7000_HILO_FIX,
1393     OPTION_MNO_7000_HILO_FIX,
1394     OPTION_FIX_24K,
1395     OPTION_NO_FIX_24K,
1396     OPTION_FIX_RM7000,
1397     OPTION_NO_FIX_RM7000,
1398     OPTION_FIX_LOONGSON2F_JUMP,
1399     OPTION_NO_FIX_LOONGSON2F_JUMP,
1400     OPTION_FIX_LOONGSON2F_NOP,
1401     OPTION_NO_FIX_LOONGSON2F_NOP,
1402     OPTION_FIX_VR4120,
1403     OPTION_NO_FIX_VR4120,
1404     OPTION_FIX_VR4130,
1405     OPTION_NO_FIX_VR4130,
1406     OPTION_FIX_CN63XXP1,
1407     OPTION_NO_FIX_CN63XXP1,
1408     OPTION_TRAP,
1409     OPTION_BREAK,
1410     OPTION_EB,
1411     OPTION_EL,
1412     OPTION_FP32,
1413     OPTION_GP32,
1414     OPTION_CONSTRUCT_FLOATS,
1415     OPTION_NO_CONSTRUCT_FLOATS,
1416     OPTION_FP64,
1417     OPTION_FPXX,
1418     OPTION_GP64,
1419     OPTION_RELAX_BRANCH,
1420     OPTION_NO_RELAX_BRANCH,
1421     OPTION_INSN32,
1422     OPTION_NO_INSN32,
1423     OPTION_MSHARED,
1424     OPTION_MNO_SHARED,
1425     OPTION_MSYM32,
1426     OPTION_MNO_SYM32,
1427     OPTION_SOFT_FLOAT,
1428     OPTION_HARD_FLOAT,
1429     OPTION_SINGLE_FLOAT,
1430     OPTION_DOUBLE_FLOAT,
1431     OPTION_32,
1432     OPTION_CALL_SHARED,
1433     OPTION_CALL_NONPIC,
1434     OPTION_NON_SHARED,
1435     OPTION_XGOT,
1436     OPTION_MABI,
1437     OPTION_N32,
1438     OPTION_64,
1439     OPTION_MDEBUG,
1440     OPTION_NO_MDEBUG,
1441     OPTION_PDR,
1442     OPTION_NO_PDR,
1443     OPTION_MVXWORKS_PIC,
1444     OPTION_NAN,
1445     OPTION_ODD_SPREG,
1446     OPTION_NO_ODD_SPREG,
1447     OPTION_END_OF_ENUM
1448   };
1449
1450 struct option md_longopts[] =
1451 {
1452   /* Options which specify architecture.  */
1453   {"march", required_argument, NULL, OPTION_MARCH},
1454   {"mtune", required_argument, NULL, OPTION_MTUNE},
1455   {"mips0", no_argument, NULL, OPTION_MIPS1},
1456   {"mips1", no_argument, NULL, OPTION_MIPS1},
1457   {"mips2", no_argument, NULL, OPTION_MIPS2},
1458   {"mips3", no_argument, NULL, OPTION_MIPS3},
1459   {"mips4", no_argument, NULL, OPTION_MIPS4},
1460   {"mips5", no_argument, NULL, OPTION_MIPS5},
1461   {"mips32", no_argument, NULL, OPTION_MIPS32},
1462   {"mips64", no_argument, NULL, OPTION_MIPS64},
1463   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1464   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1465   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1466   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1467   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1468   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1469
1470   /* Options which specify Application Specific Extensions (ASEs).  */
1471   {"mips16", no_argument, NULL, OPTION_MIPS16},
1472   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1473   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1474   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1475   {"mdmx", no_argument, NULL, OPTION_MDMX},
1476   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1477   {"mdsp", no_argument, NULL, OPTION_DSP},
1478   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1479   {"mmt", no_argument, NULL, OPTION_MT},
1480   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1481   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1482   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1483   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1484   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1485   {"meva", no_argument, NULL, OPTION_EVA},
1486   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1487   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1488   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1489   {"mmcu", no_argument, NULL, OPTION_MCU},
1490   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1491   {"mvirt", no_argument, NULL, OPTION_VIRT},
1492   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1493   {"mmsa", no_argument, NULL, OPTION_MSA},
1494   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1495   {"mxpa", no_argument, NULL, OPTION_XPA},
1496   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1497
1498   /* Old-style architecture options.  Don't add more of these.  */
1499   {"m4650", no_argument, NULL, OPTION_M4650},
1500   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1501   {"m4010", no_argument, NULL, OPTION_M4010},
1502   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1503   {"m4100", no_argument, NULL, OPTION_M4100},
1504   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1505   {"m3900", no_argument, NULL, OPTION_M3900},
1506   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1507
1508   /* Options which enable bug fixes.  */
1509   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1510   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1511   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1512   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1513   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1514   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1515   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1516   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1517   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1518   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1519   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1520   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1521   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1522   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1523   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1524   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1525   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1526
1527   /* Miscellaneous options.  */
1528   {"trap", no_argument, NULL, OPTION_TRAP},
1529   {"no-break", no_argument, NULL, OPTION_TRAP},
1530   {"break", no_argument, NULL, OPTION_BREAK},
1531   {"no-trap", no_argument, NULL, OPTION_BREAK},
1532   {"EB", no_argument, NULL, OPTION_EB},
1533   {"EL", no_argument, NULL, OPTION_EL},
1534   {"mfp32", no_argument, NULL, OPTION_FP32},
1535   {"mgp32", no_argument, NULL, OPTION_GP32},
1536   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1537   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1538   {"mfp64", no_argument, NULL, OPTION_FP64},
1539   {"mfpxx", no_argument, NULL, OPTION_FPXX},
1540   {"mgp64", no_argument, NULL, OPTION_GP64},
1541   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1542   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1543   {"minsn32", no_argument, NULL, OPTION_INSN32},
1544   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1545   {"mshared", no_argument, NULL, OPTION_MSHARED},
1546   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1547   {"msym32", no_argument, NULL, OPTION_MSYM32},
1548   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1549   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1550   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1551   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1552   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1553   {"modd-spreg", no_argument, NULL, OPTION_ODD_SPREG},
1554   {"mno-odd-spreg", no_argument, NULL, OPTION_NO_ODD_SPREG},
1555
1556   /* Strictly speaking this next option is ELF specific,
1557      but we allow it for other ports as well in order to
1558      make testing easier.  */
1559   {"32", no_argument, NULL, OPTION_32},
1560
1561   /* ELF-specific options.  */
1562   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1563   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1564   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1565   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1566   {"xgot", no_argument, NULL, OPTION_XGOT},
1567   {"mabi", required_argument, NULL, OPTION_MABI},
1568   {"n32", no_argument, NULL, OPTION_N32},
1569   {"64", no_argument, NULL, OPTION_64},
1570   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1571   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1572   {"mpdr", no_argument, NULL, OPTION_PDR},
1573   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1574   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1575   {"mnan", required_argument, NULL, OPTION_NAN},
1576
1577   {NULL, no_argument, NULL, 0}
1578 };
1579 size_t md_longopts_size = sizeof (md_longopts);
1580 \f
1581 /* Information about either an Application Specific Extension or an
1582    optional architecture feature that, for simplicity, we treat in the
1583    same way as an ASE.  */
1584 struct mips_ase
1585 {
1586   /* The name of the ASE, used in both the command-line and .set options.  */
1587   const char *name;
1588
1589   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1590      and 64-bit architectures, the flags here refer to the subset that
1591      is available on both.  */
1592   unsigned int flags;
1593
1594   /* The ASE_* flag used for instructions that are available on 64-bit
1595      architectures but that are not included in FLAGS.  */
1596   unsigned int flags64;
1597
1598   /* The command-line options that turn the ASE on and off.  */
1599   int option_on;
1600   int option_off;
1601
1602   /* The minimum required architecture revisions for MIPS32, MIPS64,
1603      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1604   int mips32_rev;
1605   int mips64_rev;
1606   int micromips32_rev;
1607   int micromips64_rev;
1608 };
1609
1610 /* A table of all supported ASEs.  */
1611 static const struct mips_ase mips_ases[] = {
1612   { "dsp", ASE_DSP, ASE_DSP64,
1613     OPTION_DSP, OPTION_NO_DSP,
1614     2, 2, 2, 2 },
1615
1616   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1617     OPTION_DSPR2, OPTION_NO_DSPR2,
1618     2, 2, 2, 2 },
1619
1620   { "eva", ASE_EVA, 0,
1621     OPTION_EVA, OPTION_NO_EVA,
1622     2, 2, 2, 2 },
1623
1624   { "mcu", ASE_MCU, 0,
1625     OPTION_MCU, OPTION_NO_MCU,
1626     2, 2, 2, 2 },
1627
1628   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1629   { "mdmx", ASE_MDMX, 0,
1630     OPTION_MDMX, OPTION_NO_MDMX,
1631     -1, 1, -1, -1 },
1632
1633   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1634   { "mips3d", ASE_MIPS3D, 0,
1635     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1636     2, 1, -1, -1 },
1637
1638   { "mt", ASE_MT, 0,
1639     OPTION_MT, OPTION_NO_MT,
1640     2, 2, -1, -1 },
1641
1642   { "smartmips", ASE_SMARTMIPS, 0,
1643     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1644     1, -1, -1, -1 },
1645
1646   { "virt", ASE_VIRT, ASE_VIRT64,
1647     OPTION_VIRT, OPTION_NO_VIRT,
1648     2, 2, 2, 2 },
1649
1650   { "msa", ASE_MSA, ASE_MSA64,
1651     OPTION_MSA, OPTION_NO_MSA,
1652     2, 2, 2, 2 },
1653
1654   { "xpa", ASE_XPA, 0,
1655     OPTION_XPA, OPTION_NO_XPA,
1656     2, 2, -1, -1 }
1657 };
1658
1659 /* The set of ASEs that require -mfp64.  */
1660 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1661
1662 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1663 static const unsigned int mips_ase_groups[] = {
1664   ASE_DSP | ASE_DSPR2
1665 };
1666 \f
1667 /* Pseudo-op table.
1668
1669    The following pseudo-ops from the Kane and Heinrich MIPS book
1670    should be defined here, but are currently unsupported: .alias,
1671    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1672
1673    The following pseudo-ops from the Kane and Heinrich MIPS book are
1674    specific to the type of debugging information being generated, and
1675    should be defined by the object format: .aent, .begin, .bend,
1676    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1677    .vreg.
1678
1679    The following pseudo-ops from the Kane and Heinrich MIPS book are
1680    not MIPS CPU specific, but are also not specific to the object file
1681    format.  This file is probably the best place to define them, but
1682    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1683
1684 static const pseudo_typeS mips_pseudo_table[] =
1685 {
1686   /* MIPS specific pseudo-ops.  */
1687   {"option", s_option, 0},
1688   {"set", s_mipsset, 0},
1689   {"rdata", s_change_sec, 'r'},
1690   {"sdata", s_change_sec, 's'},
1691   {"livereg", s_ignore, 0},
1692   {"abicalls", s_abicalls, 0},
1693   {"cpload", s_cpload, 0},
1694   {"cpsetup", s_cpsetup, 0},
1695   {"cplocal", s_cplocal, 0},
1696   {"cprestore", s_cprestore, 0},
1697   {"cpreturn", s_cpreturn, 0},
1698   {"dtprelword", s_dtprelword, 0},
1699   {"dtpreldword", s_dtpreldword, 0},
1700   {"tprelword", s_tprelword, 0},
1701   {"tpreldword", s_tpreldword, 0},
1702   {"gpvalue", s_gpvalue, 0},
1703   {"gpword", s_gpword, 0},
1704   {"gpdword", s_gpdword, 0},
1705   {"ehword", s_ehword, 0},
1706   {"cpadd", s_cpadd, 0},
1707   {"insn", s_insn, 0},
1708   {"nan", s_nan, 0},
1709   {"module", s_module, 0},
1710
1711   /* Relatively generic pseudo-ops that happen to be used on MIPS
1712      chips.  */
1713   {"asciiz", stringer, 8 + 1},
1714   {"bss", s_change_sec, 'b'},
1715   {"err", s_err, 0},
1716   {"half", s_cons, 1},
1717   {"dword", s_cons, 3},
1718   {"weakext", s_mips_weakext, 0},
1719   {"origin", s_org, 0},
1720   {"repeat", s_rept, 0},
1721
1722   /* For MIPS this is non-standard, but we define it for consistency.  */
1723   {"sbss", s_change_sec, 'B'},
1724
1725   /* These pseudo-ops are defined in read.c, but must be overridden
1726      here for one reason or another.  */
1727   {"align", s_align, 0},
1728   {"byte", s_cons, 0},
1729   {"data", s_change_sec, 'd'},
1730   {"double", s_float_cons, 'd'},
1731   {"float", s_float_cons, 'f'},
1732   {"globl", s_mips_globl, 0},
1733   {"global", s_mips_globl, 0},
1734   {"hword", s_cons, 1},
1735   {"int", s_cons, 2},
1736   {"long", s_cons, 2},
1737   {"octa", s_cons, 4},
1738   {"quad", s_cons, 3},
1739   {"section", s_change_section, 0},
1740   {"short", s_cons, 1},
1741   {"single", s_float_cons, 'f'},
1742   {"stabd", s_mips_stab, 'd'},
1743   {"stabn", s_mips_stab, 'n'},
1744   {"stabs", s_mips_stab, 's'},
1745   {"text", s_change_sec, 't'},
1746   {"word", s_cons, 2},
1747
1748   { "extern", ecoff_directive_extern, 0},
1749
1750   { NULL, NULL, 0 },
1751 };
1752
1753 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1754 {
1755   /* These pseudo-ops should be defined by the object file format.
1756      However, a.out doesn't support them, so we have versions here.  */
1757   {"aent", s_mips_ent, 1},
1758   {"bgnb", s_ignore, 0},
1759   {"end", s_mips_end, 0},
1760   {"endb", s_ignore, 0},
1761   {"ent", s_mips_ent, 0},
1762   {"file", s_mips_file, 0},
1763   {"fmask", s_mips_mask, 'F'},
1764   {"frame", s_mips_frame, 0},
1765   {"loc", s_mips_loc, 0},
1766   {"mask", s_mips_mask, 'R'},
1767   {"verstamp", s_ignore, 0},
1768   { NULL, NULL, 0 },
1769 };
1770
1771 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1772    purpose of the `.dc.a' internal pseudo-op.  */
1773
1774 int
1775 mips_address_bytes (void)
1776 {
1777   file_mips_check_options ();
1778   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1779 }
1780
1781 extern void pop_insert (const pseudo_typeS *);
1782
1783 void
1784 mips_pop_insert (void)
1785 {
1786   pop_insert (mips_pseudo_table);
1787   if (! ECOFF_DEBUGGING)
1788     pop_insert (mips_nonecoff_pseudo_table);
1789 }
1790 \f
1791 /* Symbols labelling the current insn.  */
1792
1793 struct insn_label_list
1794 {
1795   struct insn_label_list *next;
1796   symbolS *label;
1797 };
1798
1799 static struct insn_label_list *free_insn_labels;
1800 #define label_list tc_segment_info_data.labels
1801
1802 static void mips_clear_insn_labels (void);
1803 static void mips_mark_labels (void);
1804 static void mips_compressed_mark_labels (void);
1805
1806 static inline void
1807 mips_clear_insn_labels (void)
1808 {
1809   register struct insn_label_list **pl;
1810   segment_info_type *si;
1811
1812   if (now_seg)
1813     {
1814       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1815         ;
1816       
1817       si = seg_info (now_seg);
1818       *pl = si->label_list;
1819       si->label_list = NULL;
1820     }
1821 }
1822
1823 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1824
1825 static inline void
1826 mips_mark_labels (void)
1827 {
1828   if (HAVE_CODE_COMPRESSION)
1829     mips_compressed_mark_labels ();
1830 }
1831 \f
1832 static char *expr_end;
1833
1834 /* An expression in a macro instruction.  This is set by mips_ip and
1835    mips16_ip and when populated is always an O_constant.  */
1836
1837 static expressionS imm_expr;
1838
1839 /* The relocatable field in an instruction and the relocs associated
1840    with it.  These variables are used for instructions like LUI and
1841    JAL as well as true offsets.  They are also used for address
1842    operands in macros.  */
1843
1844 static expressionS offset_expr;
1845 static bfd_reloc_code_real_type offset_reloc[3]
1846   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1847
1848 /* This is set to the resulting size of the instruction to be produced
1849    by mips16_ip if an explicit extension is used or by mips_ip if an
1850    explicit size is supplied.  */
1851
1852 static unsigned int forced_insn_length;
1853
1854 /* True if we are assembling an instruction.  All dot symbols defined during
1855    this time should be treated as code labels.  */
1856
1857 static bfd_boolean mips_assembling_insn;
1858
1859 /* The pdr segment for per procedure frame/regmask info.  Not used for
1860    ECOFF debugging.  */
1861
1862 static segT pdr_seg;
1863
1864 /* The default target format to use.  */
1865
1866 #if defined (TE_FreeBSD)
1867 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1868 #elif defined (TE_TMIPS)
1869 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1870 #else
1871 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1872 #endif
1873
1874 const char *
1875 mips_target_format (void)
1876 {
1877   switch (OUTPUT_FLAVOR)
1878     {
1879     case bfd_target_elf_flavour:
1880 #ifdef TE_VXWORKS
1881       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1882         return (target_big_endian
1883                 ? "elf32-bigmips-vxworks"
1884                 : "elf32-littlemips-vxworks");
1885 #endif
1886       return (target_big_endian
1887               ? (HAVE_64BIT_OBJECTS
1888                  ? ELF_TARGET ("elf64-", "big")
1889                  : (HAVE_NEWABI
1890                     ? ELF_TARGET ("elf32-n", "big")
1891                     : ELF_TARGET ("elf32-", "big")))
1892               : (HAVE_64BIT_OBJECTS
1893                  ? ELF_TARGET ("elf64-", "little")
1894                  : (HAVE_NEWABI
1895                     ? ELF_TARGET ("elf32-n", "little")
1896                     : ELF_TARGET ("elf32-", "little"))));
1897     default:
1898       abort ();
1899       return NULL;
1900     }
1901 }
1902
1903 /* Return the ISA revision that is currently in use, or 0 if we are
1904    generating code for MIPS V or below.  */
1905
1906 static int
1907 mips_isa_rev (void)
1908 {
1909   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1910     return 2;
1911
1912   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
1913     return 3;
1914
1915   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
1916     return 5;
1917
1918   /* microMIPS implies revision 2 or above.  */
1919   if (mips_opts.micromips)
1920     return 2;
1921
1922   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1923     return 1;
1924
1925   return 0;
1926 }
1927
1928 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1929
1930 static unsigned int
1931 mips_ase_mask (unsigned int flags)
1932 {
1933   unsigned int i;
1934
1935   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1936     if (flags & mips_ase_groups[i])
1937       flags |= mips_ase_groups[i];
1938   return flags;
1939 }
1940
1941 /* Check whether the current ISA supports ASE.  Issue a warning if
1942    appropriate.  */
1943
1944 static void
1945 mips_check_isa_supports_ase (const struct mips_ase *ase)
1946 {
1947   const char *base;
1948   int min_rev, size;
1949   static unsigned int warned_isa;
1950   static unsigned int warned_fp32;
1951
1952   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1953     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1954   else
1955     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1956   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1957       && (warned_isa & ase->flags) != ase->flags)
1958     {
1959       warned_isa |= ase->flags;
1960       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1961       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1962       if (min_rev < 0)
1963         as_warn (_("the %d-bit %s architecture does not support the"
1964                    " `%s' extension"), size, base, ase->name);
1965       else
1966         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
1967                  ase->name, base, size, min_rev);
1968     }
1969   if ((ase->flags & FP64_ASES)
1970       && mips_opts.fp != 64
1971       && (warned_fp32 & ase->flags) != ase->flags)
1972     {
1973       warned_fp32 |= ase->flags;
1974       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
1975     }
1976 }
1977
1978 /* Check all enabled ASEs to see whether they are supported by the
1979    chosen architecture.  */
1980
1981 static void
1982 mips_check_isa_supports_ases (void)
1983 {
1984   unsigned int i, mask;
1985
1986   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1987     {
1988       mask = mips_ase_mask (mips_ases[i].flags);
1989       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1990         mips_check_isa_supports_ase (&mips_ases[i]);
1991     }
1992 }
1993
1994 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1995    that were affected.  */
1996
1997 static unsigned int
1998 mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
1999               bfd_boolean enabled_p)
2000 {
2001   unsigned int mask;
2002
2003   mask = mips_ase_mask (ase->flags);
2004   opts->ase &= ~mask;
2005   if (enabled_p)
2006     opts->ase |= ase->flags;
2007   return mask;
2008 }
2009
2010 /* Return the ASE called NAME, or null if none.  */
2011
2012 static const struct mips_ase *
2013 mips_lookup_ase (const char *name)
2014 {
2015   unsigned int i;
2016
2017   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2018     if (strcmp (name, mips_ases[i].name) == 0)
2019       return &mips_ases[i];
2020   return NULL;
2021 }
2022
2023 /* Return the length of a microMIPS instruction in bytes.  If bits of
2024    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
2025    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
2026    major opcode) will require further modifications to the opcode
2027    table.  */
2028
2029 static inline unsigned int
2030 micromips_insn_length (const struct mips_opcode *mo)
2031 {
2032   return (mo->mask >> 16) == 0 ? 2 : 4;
2033 }
2034
2035 /* Return the length of MIPS16 instruction OPCODE.  */
2036
2037 static inline unsigned int
2038 mips16_opcode_length (unsigned long opcode)
2039 {
2040   return (opcode >> 16) == 0 ? 2 : 4;
2041 }
2042
2043 /* Return the length of instruction INSN.  */
2044
2045 static inline unsigned int
2046 insn_length (const struct mips_cl_insn *insn)
2047 {
2048   if (mips_opts.micromips)
2049     return micromips_insn_length (insn->insn_mo);
2050   else if (mips_opts.mips16)
2051     return mips16_opcode_length (insn->insn_opcode);
2052   else
2053     return 4;
2054 }
2055
2056 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2057
2058 static void
2059 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2060 {
2061   size_t i;
2062
2063   insn->insn_mo = mo;
2064   insn->insn_opcode = mo->match;
2065   insn->frag = NULL;
2066   insn->where = 0;
2067   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2068     insn->fixp[i] = NULL;
2069   insn->fixed_p = (mips_opts.noreorder > 0);
2070   insn->noreorder_p = (mips_opts.noreorder > 0);
2071   insn->mips16_absolute_jump_p = 0;
2072   insn->complete_p = 0;
2073   insn->cleared_p = 0;
2074 }
2075
2076 /* Get a list of all the operands in INSN.  */
2077
2078 static const struct mips_operand_array *
2079 insn_operands (const struct mips_cl_insn *insn)
2080 {
2081   if (insn->insn_mo >= &mips_opcodes[0]
2082       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2083     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2084
2085   if (insn->insn_mo >= &mips16_opcodes[0]
2086       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2087     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2088
2089   if (insn->insn_mo >= &micromips_opcodes[0]
2090       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2091     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2092
2093   abort ();
2094 }
2095
2096 /* Get a description of operand OPNO of INSN.  */
2097
2098 static const struct mips_operand *
2099 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2100 {
2101   const struct mips_operand_array *operands;
2102
2103   operands = insn_operands (insn);
2104   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2105     abort ();
2106   return operands->operand[opno];
2107 }
2108
2109 /* Install UVAL as the value of OPERAND in INSN.  */
2110
2111 static inline void
2112 insn_insert_operand (struct mips_cl_insn *insn,
2113                      const struct mips_operand *operand, unsigned int uval)
2114 {
2115   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2116 }
2117
2118 /* Extract the value of OPERAND from INSN.  */
2119
2120 static inline unsigned
2121 insn_extract_operand (const struct mips_cl_insn *insn,
2122                       const struct mips_operand *operand)
2123 {
2124   return mips_extract_operand (operand, insn->insn_opcode);
2125 }
2126
2127 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2128
2129 static void
2130 mips_record_compressed_mode (void)
2131 {
2132   segment_info_type *si;
2133
2134   si = seg_info (now_seg);
2135   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2136     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2137   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2138     si->tc_segment_info_data.micromips = mips_opts.micromips;
2139 }
2140
2141 /* Read a standard MIPS instruction from BUF.  */
2142
2143 static unsigned long
2144 read_insn (char *buf)
2145 {
2146   if (target_big_endian)
2147     return bfd_getb32 ((bfd_byte *) buf);
2148   else
2149     return bfd_getl32 ((bfd_byte *) buf);
2150 }
2151
2152 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2153    the next byte.  */
2154
2155 static char *
2156 write_insn (char *buf, unsigned int insn)
2157 {
2158   md_number_to_chars (buf, insn, 4);
2159   return buf + 4;
2160 }
2161
2162 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2163    has length LENGTH.  */
2164
2165 static unsigned long
2166 read_compressed_insn (char *buf, unsigned int length)
2167 {
2168   unsigned long insn;
2169   unsigned int i;
2170
2171   insn = 0;
2172   for (i = 0; i < length; i += 2)
2173     {
2174       insn <<= 16;
2175       if (target_big_endian)
2176         insn |= bfd_getb16 ((char *) buf);
2177       else
2178         insn |= bfd_getl16 ((char *) buf);
2179       buf += 2;
2180     }
2181   return insn;
2182 }
2183
2184 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2185    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2186
2187 static char *
2188 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2189 {
2190   unsigned int i;
2191
2192   for (i = 0; i < length; i += 2)
2193     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2194   return buf + length;
2195 }
2196
2197 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2198
2199 static void
2200 install_insn (const struct mips_cl_insn *insn)
2201 {
2202   char *f = insn->frag->fr_literal + insn->where;
2203   if (HAVE_CODE_COMPRESSION)
2204     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2205   else
2206     write_insn (f, insn->insn_opcode);
2207   mips_record_compressed_mode ();
2208 }
2209
2210 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2211    and install the opcode in the new location.  */
2212
2213 static void
2214 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2215 {
2216   size_t i;
2217
2218   insn->frag = frag;
2219   insn->where = where;
2220   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2221     if (insn->fixp[i] != NULL)
2222       {
2223         insn->fixp[i]->fx_frag = frag;
2224         insn->fixp[i]->fx_where = where;
2225       }
2226   install_insn (insn);
2227 }
2228
2229 /* Add INSN to the end of the output.  */
2230
2231 static void
2232 add_fixed_insn (struct mips_cl_insn *insn)
2233 {
2234   char *f = frag_more (insn_length (insn));
2235   move_insn (insn, frag_now, f - frag_now->fr_literal);
2236 }
2237
2238 /* Start a variant frag and move INSN to the start of the variant part,
2239    marking it as fixed.  The other arguments are as for frag_var.  */
2240
2241 static void
2242 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2243                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2244 {
2245   frag_grow (max_chars);
2246   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2247   insn->fixed_p = 1;
2248   frag_var (rs_machine_dependent, max_chars, var,
2249             subtype, symbol, offset, NULL);
2250 }
2251
2252 /* Insert N copies of INSN into the history buffer, starting at
2253    position FIRST.  Neither FIRST nor N need to be clipped.  */
2254
2255 static void
2256 insert_into_history (unsigned int first, unsigned int n,
2257                      const struct mips_cl_insn *insn)
2258 {
2259   if (mips_relax.sequence != 2)
2260     {
2261       unsigned int i;
2262
2263       for (i = ARRAY_SIZE (history); i-- > first;)
2264         if (i >= first + n)
2265           history[i] = history[i - n];
2266         else
2267           history[i] = *insn;
2268     }
2269 }
2270
2271 /* Clear the error in insn_error.  */
2272
2273 static void
2274 clear_insn_error (void)
2275 {
2276   memset (&insn_error, 0, sizeof (insn_error));
2277 }
2278
2279 /* Possibly record error message MSG for the current instruction.
2280    If the error is about a particular argument, ARGNUM is the 1-based
2281    number of that argument, otherwise it is 0.  FORMAT is the format
2282    of MSG.  Return true if MSG was used, false if the current message
2283    was kept.  */
2284
2285 static bfd_boolean
2286 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2287                        const char *msg)
2288 {
2289   if (argnum == 0)
2290     {
2291       /* Give priority to errors against specific arguments, and to
2292          the first whole-instruction message.  */
2293       if (insn_error.msg)
2294         return FALSE;
2295     }
2296   else
2297     {
2298       /* Keep insn_error if it is against a later argument.  */
2299       if (argnum < insn_error.min_argnum)
2300         return FALSE;
2301
2302       /* If both errors are against the same argument but are different,
2303          give up on reporting a specific error for this argument.
2304          See the comment about mips_insn_error for details.  */
2305       if (argnum == insn_error.min_argnum
2306           && insn_error.msg
2307           && strcmp (insn_error.msg, msg) != 0)
2308         {
2309           insn_error.msg = 0;
2310           insn_error.min_argnum += 1;
2311           return FALSE;
2312         }
2313     }
2314   insn_error.min_argnum = argnum;
2315   insn_error.format = format;
2316   insn_error.msg = msg;
2317   return TRUE;
2318 }
2319
2320 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2321    as for set_insn_error_format.  */
2322
2323 static void
2324 set_insn_error (int argnum, const char *msg)
2325 {
2326   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2327 }
2328
2329 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2330    as for set_insn_error_format.  */
2331
2332 static void
2333 set_insn_error_i (int argnum, const char *msg, int i)
2334 {
2335   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2336     insn_error.u.i = i;
2337 }
2338
2339 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2340    are as for set_insn_error_format.  */
2341
2342 static void
2343 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2344 {
2345   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2346     {
2347       insn_error.u.ss[0] = s1;
2348       insn_error.u.ss[1] = s2;
2349     }
2350 }
2351
2352 /* Report the error in insn_error, which is against assembly code STR.  */
2353
2354 static void
2355 report_insn_error (const char *str)
2356 {
2357   const char *msg;
2358
2359   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2360   switch (insn_error.format)
2361     {
2362     case ERR_FMT_PLAIN:
2363       as_bad (msg, str);
2364       break;
2365
2366     case ERR_FMT_I:
2367       as_bad (msg, insn_error.u.i, str);
2368       break;
2369
2370     case ERR_FMT_SS:
2371       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2372       break;
2373     }
2374 }
2375
2376 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2377    the idea is to make it obvious at a glance that each errata is
2378    included.  */
2379
2380 static void
2381 init_vr4120_conflicts (void)
2382 {
2383 #define CONFLICT(FIRST, SECOND) \
2384     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2385
2386   /* Errata 21 - [D]DIV[U] after [D]MACC */
2387   CONFLICT (MACC, DIV);
2388   CONFLICT (DMACC, DIV);
2389
2390   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2391   CONFLICT (DMULT, DMULT);
2392   CONFLICT (DMULT, DMACC);
2393   CONFLICT (DMACC, DMULT);
2394   CONFLICT (DMACC, DMACC);
2395
2396   /* Errata 24 - MT{LO,HI} after [D]MACC */
2397   CONFLICT (MACC, MTHILO);
2398   CONFLICT (DMACC, MTHILO);
2399
2400   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2401      instruction is executed immediately after a MACC or DMACC
2402      instruction, the result of [either instruction] is incorrect."  */
2403   CONFLICT (MACC, MULT);
2404   CONFLICT (MACC, DMULT);
2405   CONFLICT (DMACC, MULT);
2406   CONFLICT (DMACC, DMULT);
2407
2408   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2409      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2410      DDIV or DDIVU instruction, the result of the MACC or
2411      DMACC instruction is incorrect.".  */
2412   CONFLICT (DMULT, MACC);
2413   CONFLICT (DMULT, DMACC);
2414   CONFLICT (DIV, MACC);
2415   CONFLICT (DIV, DMACC);
2416
2417 #undef CONFLICT
2418 }
2419
2420 struct regname {
2421   const char *name;
2422   unsigned int num;
2423 };
2424
2425 #define RNUM_MASK       0x00000ff
2426 #define RTYPE_MASK      0x0ffff00
2427 #define RTYPE_NUM       0x0000100
2428 #define RTYPE_FPU       0x0000200
2429 #define RTYPE_FCC       0x0000400
2430 #define RTYPE_VEC       0x0000800
2431 #define RTYPE_GP        0x0001000
2432 #define RTYPE_CP0       0x0002000
2433 #define RTYPE_PC        0x0004000
2434 #define RTYPE_ACC       0x0008000
2435 #define RTYPE_CCC       0x0010000
2436 #define RTYPE_VI        0x0020000
2437 #define RTYPE_VF        0x0040000
2438 #define RTYPE_R5900_I   0x0080000
2439 #define RTYPE_R5900_Q   0x0100000
2440 #define RTYPE_R5900_R   0x0200000
2441 #define RTYPE_R5900_ACC 0x0400000
2442 #define RTYPE_MSA       0x0800000
2443 #define RWARN           0x8000000
2444
2445 #define GENERIC_REGISTER_NUMBERS \
2446     {"$0",      RTYPE_NUM | 0},  \
2447     {"$1",      RTYPE_NUM | 1},  \
2448     {"$2",      RTYPE_NUM | 2},  \
2449     {"$3",      RTYPE_NUM | 3},  \
2450     {"$4",      RTYPE_NUM | 4},  \
2451     {"$5",      RTYPE_NUM | 5},  \
2452     {"$6",      RTYPE_NUM | 6},  \
2453     {"$7",      RTYPE_NUM | 7},  \
2454     {"$8",      RTYPE_NUM | 8},  \
2455     {"$9",      RTYPE_NUM | 9},  \
2456     {"$10",     RTYPE_NUM | 10}, \
2457     {"$11",     RTYPE_NUM | 11}, \
2458     {"$12",     RTYPE_NUM | 12}, \
2459     {"$13",     RTYPE_NUM | 13}, \
2460     {"$14",     RTYPE_NUM | 14}, \
2461     {"$15",     RTYPE_NUM | 15}, \
2462     {"$16",     RTYPE_NUM | 16}, \
2463     {"$17",     RTYPE_NUM | 17}, \
2464     {"$18",     RTYPE_NUM | 18}, \
2465     {"$19",     RTYPE_NUM | 19}, \
2466     {"$20",     RTYPE_NUM | 20}, \
2467     {"$21",     RTYPE_NUM | 21}, \
2468     {"$22",     RTYPE_NUM | 22}, \
2469     {"$23",     RTYPE_NUM | 23}, \
2470     {"$24",     RTYPE_NUM | 24}, \
2471     {"$25",     RTYPE_NUM | 25}, \
2472     {"$26",     RTYPE_NUM | 26}, \
2473     {"$27",     RTYPE_NUM | 27}, \
2474     {"$28",     RTYPE_NUM | 28}, \
2475     {"$29",     RTYPE_NUM | 29}, \
2476     {"$30",     RTYPE_NUM | 30}, \
2477     {"$31",     RTYPE_NUM | 31} 
2478
2479 #define FPU_REGISTER_NAMES       \
2480     {"$f0",     RTYPE_FPU | 0},  \
2481     {"$f1",     RTYPE_FPU | 1},  \
2482     {"$f2",     RTYPE_FPU | 2},  \
2483     {"$f3",     RTYPE_FPU | 3},  \
2484     {"$f4",     RTYPE_FPU | 4},  \
2485     {"$f5",     RTYPE_FPU | 5},  \
2486     {"$f6",     RTYPE_FPU | 6},  \
2487     {"$f7",     RTYPE_FPU | 7},  \
2488     {"$f8",     RTYPE_FPU | 8},  \
2489     {"$f9",     RTYPE_FPU | 9},  \
2490     {"$f10",    RTYPE_FPU | 10}, \
2491     {"$f11",    RTYPE_FPU | 11}, \
2492     {"$f12",    RTYPE_FPU | 12}, \
2493     {"$f13",    RTYPE_FPU | 13}, \
2494     {"$f14",    RTYPE_FPU | 14}, \
2495     {"$f15",    RTYPE_FPU | 15}, \
2496     {"$f16",    RTYPE_FPU | 16}, \
2497     {"$f17",    RTYPE_FPU | 17}, \
2498     {"$f18",    RTYPE_FPU | 18}, \
2499     {"$f19",    RTYPE_FPU | 19}, \
2500     {"$f20",    RTYPE_FPU | 20}, \
2501     {"$f21",    RTYPE_FPU | 21}, \
2502     {"$f22",    RTYPE_FPU | 22}, \
2503     {"$f23",    RTYPE_FPU | 23}, \
2504     {"$f24",    RTYPE_FPU | 24}, \
2505     {"$f25",    RTYPE_FPU | 25}, \
2506     {"$f26",    RTYPE_FPU | 26}, \
2507     {"$f27",    RTYPE_FPU | 27}, \
2508     {"$f28",    RTYPE_FPU | 28}, \
2509     {"$f29",    RTYPE_FPU | 29}, \
2510     {"$f30",    RTYPE_FPU | 30}, \
2511     {"$f31",    RTYPE_FPU | 31}
2512
2513 #define FPU_CONDITION_CODE_NAMES \
2514     {"$fcc0",   RTYPE_FCC | 0},  \
2515     {"$fcc1",   RTYPE_FCC | 1},  \
2516     {"$fcc2",   RTYPE_FCC | 2},  \
2517     {"$fcc3",   RTYPE_FCC | 3},  \
2518     {"$fcc4",   RTYPE_FCC | 4},  \
2519     {"$fcc5",   RTYPE_FCC | 5},  \
2520     {"$fcc6",   RTYPE_FCC | 6},  \
2521     {"$fcc7",   RTYPE_FCC | 7}
2522
2523 #define COPROC_CONDITION_CODE_NAMES         \
2524     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2525     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2526     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2527     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2528     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2529     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2530     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2531     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2532
2533 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2534     {"$a4",     RTYPE_GP | 8},  \
2535     {"$a5",     RTYPE_GP | 9},  \
2536     {"$a6",     RTYPE_GP | 10}, \
2537     {"$a7",     RTYPE_GP | 11}, \
2538     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2539     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2540     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2541     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2542     {"$t0",     RTYPE_GP | 12}, \
2543     {"$t1",     RTYPE_GP | 13}, \
2544     {"$t2",     RTYPE_GP | 14}, \
2545     {"$t3",     RTYPE_GP | 15}
2546
2547 #define O32_SYMBOLIC_REGISTER_NAMES \
2548     {"$t0",     RTYPE_GP | 8},  \
2549     {"$t1",     RTYPE_GP | 9},  \
2550     {"$t2",     RTYPE_GP | 10}, \
2551     {"$t3",     RTYPE_GP | 11}, \
2552     {"$t4",     RTYPE_GP | 12}, \
2553     {"$t5",     RTYPE_GP | 13}, \
2554     {"$t6",     RTYPE_GP | 14}, \
2555     {"$t7",     RTYPE_GP | 15}, \
2556     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2557     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2558     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2559     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2560
2561 /* Remaining symbolic register names */
2562 #define SYMBOLIC_REGISTER_NAMES \
2563     {"$zero",   RTYPE_GP | 0},  \
2564     {"$at",     RTYPE_GP | 1},  \
2565     {"$AT",     RTYPE_GP | 1},  \
2566     {"$v0",     RTYPE_GP | 2},  \
2567     {"$v1",     RTYPE_GP | 3},  \
2568     {"$a0",     RTYPE_GP | 4},  \
2569     {"$a1",     RTYPE_GP | 5},  \
2570     {"$a2",     RTYPE_GP | 6},  \
2571     {"$a3",     RTYPE_GP | 7},  \
2572     {"$s0",     RTYPE_GP | 16}, \
2573     {"$s1",     RTYPE_GP | 17}, \
2574     {"$s2",     RTYPE_GP | 18}, \
2575     {"$s3",     RTYPE_GP | 19}, \
2576     {"$s4",     RTYPE_GP | 20}, \
2577     {"$s5",     RTYPE_GP | 21}, \
2578     {"$s6",     RTYPE_GP | 22}, \
2579     {"$s7",     RTYPE_GP | 23}, \
2580     {"$t8",     RTYPE_GP | 24}, \
2581     {"$t9",     RTYPE_GP | 25}, \
2582     {"$k0",     RTYPE_GP | 26}, \
2583     {"$kt0",    RTYPE_GP | 26}, \
2584     {"$k1",     RTYPE_GP | 27}, \
2585     {"$kt1",    RTYPE_GP | 27}, \
2586     {"$gp",     RTYPE_GP | 28}, \
2587     {"$sp",     RTYPE_GP | 29}, \
2588     {"$s8",     RTYPE_GP | 30}, \
2589     {"$fp",     RTYPE_GP | 30}, \
2590     {"$ra",     RTYPE_GP | 31}
2591
2592 #define MIPS16_SPECIAL_REGISTER_NAMES \
2593     {"$pc",     RTYPE_PC | 0}
2594
2595 #define MDMX_VECTOR_REGISTER_NAMES \
2596     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2597     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2598     {"$v2",     RTYPE_VEC | 2},  \
2599     {"$v3",     RTYPE_VEC | 3},  \
2600     {"$v4",     RTYPE_VEC | 4},  \
2601     {"$v5",     RTYPE_VEC | 5},  \
2602     {"$v6",     RTYPE_VEC | 6},  \
2603     {"$v7",     RTYPE_VEC | 7},  \
2604     {"$v8",     RTYPE_VEC | 8},  \
2605     {"$v9",     RTYPE_VEC | 9},  \
2606     {"$v10",    RTYPE_VEC | 10}, \
2607     {"$v11",    RTYPE_VEC | 11}, \
2608     {"$v12",    RTYPE_VEC | 12}, \
2609     {"$v13",    RTYPE_VEC | 13}, \
2610     {"$v14",    RTYPE_VEC | 14}, \
2611     {"$v15",    RTYPE_VEC | 15}, \
2612     {"$v16",    RTYPE_VEC | 16}, \
2613     {"$v17",    RTYPE_VEC | 17}, \
2614     {"$v18",    RTYPE_VEC | 18}, \
2615     {"$v19",    RTYPE_VEC | 19}, \
2616     {"$v20",    RTYPE_VEC | 20}, \
2617     {"$v21",    RTYPE_VEC | 21}, \
2618     {"$v22",    RTYPE_VEC | 22}, \
2619     {"$v23",    RTYPE_VEC | 23}, \
2620     {"$v24",    RTYPE_VEC | 24}, \
2621     {"$v25",    RTYPE_VEC | 25}, \
2622     {"$v26",    RTYPE_VEC | 26}, \
2623     {"$v27",    RTYPE_VEC | 27}, \
2624     {"$v28",    RTYPE_VEC | 28}, \
2625     {"$v29",    RTYPE_VEC | 29}, \
2626     {"$v30",    RTYPE_VEC | 30}, \
2627     {"$v31",    RTYPE_VEC | 31}
2628
2629 #define R5900_I_NAMES \
2630     {"$I",      RTYPE_R5900_I | 0}
2631
2632 #define R5900_Q_NAMES \
2633     {"$Q",      RTYPE_R5900_Q | 0}
2634
2635 #define R5900_R_NAMES \
2636     {"$R",      RTYPE_R5900_R | 0}
2637
2638 #define R5900_ACC_NAMES \
2639     {"$ACC",    RTYPE_R5900_ACC | 0 }
2640
2641 #define MIPS_DSP_ACCUMULATOR_NAMES \
2642     {"$ac0",    RTYPE_ACC | 0}, \
2643     {"$ac1",    RTYPE_ACC | 1}, \
2644     {"$ac2",    RTYPE_ACC | 2}, \
2645     {"$ac3",    RTYPE_ACC | 3}
2646
2647 static const struct regname reg_names[] = {
2648   GENERIC_REGISTER_NUMBERS,
2649   FPU_REGISTER_NAMES,
2650   FPU_CONDITION_CODE_NAMES,
2651   COPROC_CONDITION_CODE_NAMES,
2652
2653   /* The $txx registers depends on the abi,
2654      these will be added later into the symbol table from
2655      one of the tables below once mips_abi is set after 
2656      parsing of arguments from the command line. */
2657   SYMBOLIC_REGISTER_NAMES,
2658
2659   MIPS16_SPECIAL_REGISTER_NAMES,
2660   MDMX_VECTOR_REGISTER_NAMES,
2661   R5900_I_NAMES,
2662   R5900_Q_NAMES,
2663   R5900_R_NAMES,
2664   R5900_ACC_NAMES,
2665   MIPS_DSP_ACCUMULATOR_NAMES,
2666   {0, 0}
2667 };
2668
2669 static const struct regname reg_names_o32[] = {
2670   O32_SYMBOLIC_REGISTER_NAMES,
2671   {0, 0}
2672 };
2673
2674 static const struct regname reg_names_n32n64[] = {
2675   N32N64_SYMBOLIC_REGISTER_NAMES,
2676   {0, 0}
2677 };
2678
2679 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2680    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2681    of these register symbols, return the associated vector register,
2682    otherwise return SYMVAL itself.  */
2683
2684 static unsigned int
2685 mips_prefer_vec_regno (unsigned int symval)
2686 {
2687   if ((symval & -2) == (RTYPE_GP | 2))
2688     return RTYPE_VEC | (symval & 1);
2689   return symval;
2690 }
2691
2692 /* Return true if string [S, E) is a valid register name, storing its
2693    symbol value in *SYMVAL_PTR if so.  */
2694
2695 static bfd_boolean
2696 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2697 {
2698   char save_c;
2699   symbolS *symbol;
2700
2701   /* Terminate name.  */
2702   save_c = *e;
2703   *e = '\0';
2704
2705   /* Look up the name.  */
2706   symbol = symbol_find (s);
2707   *e = save_c;
2708
2709   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2710     return FALSE;
2711
2712   *symval_ptr = S_GET_VALUE (symbol);
2713   return TRUE;
2714 }
2715
2716 /* Return true if the string at *SPTR is a valid register name.  Allow it
2717    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2718    is nonnull.
2719
2720    When returning true, move *SPTR past the register, store the
2721    register's symbol value in *SYMVAL_PTR and the channel mask in
2722    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2723    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2724    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2725
2726 static bfd_boolean
2727 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2728                      unsigned int *channels_ptr)
2729 {
2730   char *s, *e, *m;
2731   const char *q;
2732   unsigned int channels, symval, bit;
2733
2734   /* Find end of name.  */
2735   s = e = *sptr;
2736   if (is_name_beginner (*e))
2737     ++e;
2738   while (is_part_of_name (*e))
2739     ++e;
2740
2741   channels = 0;
2742   if (!mips_parse_register_1 (s, e, &symval))
2743     {
2744       if (!channels_ptr)
2745         return FALSE;
2746
2747       /* Eat characters from the end of the string that are valid
2748          channel suffixes.  The preceding register must be $ACC or
2749          end with a digit, so there is no ambiguity.  */
2750       bit = 1;
2751       m = e;
2752       for (q = "wzyx"; *q; q++, bit <<= 1)
2753         if (m > s && m[-1] == *q)
2754           {
2755             --m;
2756             channels |= bit;
2757           }
2758
2759       if (channels == 0
2760           || !mips_parse_register_1 (s, m, &symval)
2761           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2762         return FALSE;
2763     }
2764
2765   *sptr = e;
2766   *symval_ptr = symval;
2767   if (channels_ptr)
2768     *channels_ptr = channels;
2769   return TRUE;
2770 }
2771
2772 /* Check if SPTR points at a valid register specifier according to TYPES.
2773    If so, then return 1, advance S to consume the specifier and store
2774    the register's number in REGNOP, otherwise return 0.  */
2775
2776 static int
2777 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2778 {
2779   unsigned int regno;
2780
2781   if (mips_parse_register (s, &regno, NULL))
2782     {
2783       if (types & RTYPE_VEC)
2784         regno = mips_prefer_vec_regno (regno);
2785       if (regno & types)
2786         regno &= RNUM_MASK;
2787       else
2788         regno = ~0;
2789     }
2790   else
2791     {
2792       if (types & RWARN)
2793         as_warn (_("unrecognized register name `%s'"), *s);
2794       regno = ~0;
2795     }
2796   if (regnop)
2797     *regnop = regno;
2798   return regno <= RNUM_MASK;
2799 }
2800
2801 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2802    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2803
2804 static char *
2805 mips_parse_vu0_channels (char *s, unsigned int *channels)
2806 {
2807   unsigned int i;
2808
2809   *channels = 0;
2810   for (i = 0; i < 4; i++)
2811     if (*s == "xyzw"[i])
2812       {
2813         *channels |= 1 << (3 - i);
2814         ++s;
2815       }
2816   return s;
2817 }
2818
2819 /* Token types for parsed operand lists.  */
2820 enum mips_operand_token_type {
2821   /* A plain register, e.g. $f2.  */
2822   OT_REG,
2823
2824   /* A 4-bit XYZW channel mask.  */
2825   OT_CHANNELS,
2826
2827   /* A constant vector index, e.g. [1].  */
2828   OT_INTEGER_INDEX,
2829
2830   /* A register vector index, e.g. [$2].  */
2831   OT_REG_INDEX,
2832
2833   /* A continuous range of registers, e.g. $s0-$s4.  */
2834   OT_REG_RANGE,
2835
2836   /* A (possibly relocated) expression.  */
2837   OT_INTEGER,
2838
2839   /* A floating-point value.  */
2840   OT_FLOAT,
2841
2842   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2843      before OT_REGs.  */
2844   OT_CHAR,
2845
2846   /* A doubled character, either "--" or "++".  */
2847   OT_DOUBLE_CHAR,
2848
2849   /* The end of the operand list.  */
2850   OT_END
2851 };
2852
2853 /* A parsed operand token.  */
2854 struct mips_operand_token
2855 {
2856   /* The type of token.  */
2857   enum mips_operand_token_type type;
2858   union
2859   {
2860     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2861     unsigned int regno;
2862
2863     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2864     unsigned int channels;
2865
2866     /* The integer value of an OT_INTEGER_INDEX.  */
2867     addressT index;
2868
2869     /* The two register symbol values involved in an OT_REG_RANGE.  */
2870     struct {
2871       unsigned int regno1;
2872       unsigned int regno2;
2873     } reg_range;
2874
2875     /* The value of an OT_INTEGER.  The value is represented as an
2876        expression and the relocation operators that were applied to
2877        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2878        relocation operators were used.  */
2879     struct {
2880       expressionS value;
2881       bfd_reloc_code_real_type relocs[3];
2882     } integer;
2883
2884     /* The binary data for an OT_FLOAT constant, and the number of bytes
2885        in the constant.  */
2886     struct {
2887       unsigned char data[8];
2888       int length;
2889     } flt;
2890
2891     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2892     char ch;
2893   } u;
2894 };
2895
2896 /* An obstack used to construct lists of mips_operand_tokens.  */
2897 static struct obstack mips_operand_tokens;
2898
2899 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2900
2901 static void
2902 mips_add_token (struct mips_operand_token *token,
2903                 enum mips_operand_token_type type)
2904 {
2905   token->type = type;
2906   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2907 }
2908
2909 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2910    and OT_REG tokens for them if so, and return a pointer to the first
2911    unconsumed character.  Return null otherwise.  */
2912
2913 static char *
2914 mips_parse_base_start (char *s)
2915 {
2916   struct mips_operand_token token;
2917   unsigned int regno, channels;
2918   bfd_boolean decrement_p;
2919
2920   if (*s != '(')
2921     return 0;
2922
2923   ++s;
2924   SKIP_SPACE_TABS (s);
2925
2926   /* Only match "--" as part of a base expression.  In other contexts "--X"
2927      is a double negative.  */
2928   decrement_p = (s[0] == '-' && s[1] == '-');
2929   if (decrement_p)
2930     {
2931       s += 2;
2932       SKIP_SPACE_TABS (s);
2933     }
2934
2935   /* Allow a channel specifier because that leads to better error messages
2936      than treating something like "$vf0x++" as an expression.  */
2937   if (!mips_parse_register (&s, &regno, &channels))
2938     return 0;
2939
2940   token.u.ch = '(';
2941   mips_add_token (&token, OT_CHAR);
2942
2943   if (decrement_p)
2944     {
2945       token.u.ch = '-';
2946       mips_add_token (&token, OT_DOUBLE_CHAR);
2947     }
2948
2949   token.u.regno = regno;
2950   mips_add_token (&token, OT_REG);
2951
2952   if (channels)
2953     {
2954       token.u.channels = channels;
2955       mips_add_token (&token, OT_CHANNELS);
2956     }
2957
2958   /* For consistency, only match "++" as part of base expressions too.  */
2959   SKIP_SPACE_TABS (s);
2960   if (s[0] == '+' && s[1] == '+')
2961     {
2962       s += 2;
2963       token.u.ch = '+';
2964       mips_add_token (&token, OT_DOUBLE_CHAR);
2965     }
2966
2967   return s;
2968 }
2969
2970 /* Parse one or more tokens from S.  Return a pointer to the first
2971    unconsumed character on success.  Return null if an error was found
2972    and store the error text in insn_error.  FLOAT_FORMAT is as for
2973    mips_parse_arguments.  */
2974
2975 static char *
2976 mips_parse_argument_token (char *s, char float_format)
2977 {
2978   char *end, *save_in, *err;
2979   unsigned int regno1, regno2, channels;
2980   struct mips_operand_token token;
2981
2982   /* First look for "($reg", since we want to treat that as an
2983      OT_CHAR and OT_REG rather than an expression.  */
2984   end = mips_parse_base_start (s);
2985   if (end)
2986     return end;
2987
2988   /* Handle other characters that end up as OT_CHARs.  */
2989   if (*s == ')' || *s == ',')
2990     {
2991       token.u.ch = *s;
2992       mips_add_token (&token, OT_CHAR);
2993       ++s;
2994       return s;
2995     }
2996
2997   /* Handle tokens that start with a register.  */
2998   if (mips_parse_register (&s, &regno1, &channels))
2999     {
3000       if (channels)
3001         {
3002           /* A register and a VU0 channel suffix.  */
3003           token.u.regno = regno1;
3004           mips_add_token (&token, OT_REG);
3005
3006           token.u.channels = channels;
3007           mips_add_token (&token, OT_CHANNELS);
3008           return s;
3009         }
3010
3011       SKIP_SPACE_TABS (s);
3012       if (*s == '-')
3013         {
3014           /* A register range.  */
3015           ++s;
3016           SKIP_SPACE_TABS (s);
3017           if (!mips_parse_register (&s, &regno2, NULL))
3018             {
3019               set_insn_error (0, _("invalid register range"));
3020               return 0;
3021             }
3022
3023           token.u.reg_range.regno1 = regno1;
3024           token.u.reg_range.regno2 = regno2;
3025           mips_add_token (&token, OT_REG_RANGE);
3026           return s;
3027         }
3028
3029       /* Add the register itself.  */
3030       token.u.regno = regno1;
3031       mips_add_token (&token, OT_REG);
3032
3033       /* Check for a vector index.  */
3034       if (*s == '[')
3035         {
3036           ++s;
3037           SKIP_SPACE_TABS (s);
3038           if (mips_parse_register (&s, &token.u.regno, NULL))
3039             mips_add_token (&token, OT_REG_INDEX);
3040           else
3041             {
3042               expressionS element;
3043
3044               my_getExpression (&element, s);
3045               if (element.X_op != O_constant)
3046                 {
3047                   set_insn_error (0, _("vector element must be constant"));
3048                   return 0;
3049                 }
3050               s = expr_end;
3051               token.u.index = element.X_add_number;
3052               mips_add_token (&token, OT_INTEGER_INDEX);
3053             }
3054           SKIP_SPACE_TABS (s);
3055           if (*s != ']')
3056             {
3057               set_insn_error (0, _("missing `]'"));
3058               return 0;
3059             }
3060           ++s;
3061         }
3062       return s;
3063     }
3064
3065   if (float_format)
3066     {
3067       /* First try to treat expressions as floats.  */
3068       save_in = input_line_pointer;
3069       input_line_pointer = s;
3070       err = md_atof (float_format, (char *) token.u.flt.data,
3071                      &token.u.flt.length);
3072       end = input_line_pointer;
3073       input_line_pointer = save_in;
3074       if (err && *err)
3075         {
3076           set_insn_error (0, err);
3077           return 0;
3078         }
3079       if (s != end)
3080         {
3081           mips_add_token (&token, OT_FLOAT);
3082           return end;
3083         }
3084     }
3085
3086   /* Treat everything else as an integer expression.  */
3087   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3088   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3089   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3090   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3091   s = expr_end;
3092   mips_add_token (&token, OT_INTEGER);
3093   return s;
3094 }
3095
3096 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3097    if expressions should be treated as 32-bit floating-point constants,
3098    'd' if they should be treated as 64-bit floating-point constants,
3099    or 0 if they should be treated as integer expressions (the usual case).
3100
3101    Return a list of tokens on success, otherwise return 0.  The caller
3102    must obstack_free the list after use.  */
3103
3104 static struct mips_operand_token *
3105 mips_parse_arguments (char *s, char float_format)
3106 {
3107   struct mips_operand_token token;
3108
3109   SKIP_SPACE_TABS (s);
3110   while (*s)
3111     {
3112       s = mips_parse_argument_token (s, float_format);
3113       if (!s)
3114         {
3115           obstack_free (&mips_operand_tokens,
3116                         obstack_finish (&mips_operand_tokens));
3117           return 0;
3118         }
3119       SKIP_SPACE_TABS (s);
3120     }
3121   mips_add_token (&token, OT_END);
3122   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3123 }
3124
3125 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3126    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3127
3128 static bfd_boolean
3129 is_opcode_valid (const struct mips_opcode *mo)
3130 {
3131   int isa = mips_opts.isa;
3132   int ase = mips_opts.ase;
3133   int fp_s, fp_d;
3134   unsigned int i;
3135
3136   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3137     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3138       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3139         ase |= mips_ases[i].flags64;
3140
3141   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3142     return FALSE;
3143
3144   /* Check whether the instruction or macro requires single-precision or
3145      double-precision floating-point support.  Note that this information is
3146      stored differently in the opcode table for insns and macros.  */
3147   if (mo->pinfo == INSN_MACRO)
3148     {
3149       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3150       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3151     }
3152   else
3153     {
3154       fp_s = mo->pinfo & FP_S;
3155       fp_d = mo->pinfo & FP_D;
3156     }
3157
3158   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3159     return FALSE;
3160
3161   if (fp_s && mips_opts.soft_float)
3162     return FALSE;
3163
3164   return TRUE;
3165 }
3166
3167 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3168    selected ISA and architecture.  */
3169
3170 static bfd_boolean
3171 is_opcode_valid_16 (const struct mips_opcode *mo)
3172 {
3173   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3174 }
3175
3176 /* Return TRUE if the size of the microMIPS opcode MO matches one
3177    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3178
3179 static bfd_boolean
3180 is_size_valid (const struct mips_opcode *mo)
3181 {
3182   if (!mips_opts.micromips)
3183     return TRUE;
3184
3185   if (mips_opts.insn32)
3186     {
3187       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3188         return FALSE;
3189       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3190         return FALSE;
3191     }
3192   if (!forced_insn_length)
3193     return TRUE;
3194   if (mo->pinfo == INSN_MACRO)
3195     return FALSE;
3196   return forced_insn_length == micromips_insn_length (mo);
3197 }
3198
3199 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3200    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3201
3202    We don't accept macros in 16-bit delay slots to avoid a case where
3203    a macro expansion fails because it relies on a preceding 32-bit real
3204    instruction to have matched and does not handle the operands correctly.
3205    The only macros that may expand to 16-bit instructions are JAL that
3206    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3207    and BGT (that likewise cannot be placed in a delay slot) that decay to
3208    a NOP.  In all these cases the macros precede any corresponding real
3209    instruction definitions in the opcode table, so they will match in the
3210    second pass where the size of the delay slot is ignored and therefore
3211    produce correct code.  */
3212
3213 static bfd_boolean
3214 is_delay_slot_valid (const struct mips_opcode *mo)
3215 {
3216   if (!mips_opts.micromips)
3217     return TRUE;
3218
3219   if (mo->pinfo == INSN_MACRO)
3220     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3221   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3222       && micromips_insn_length (mo) != 4)
3223     return FALSE;
3224   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3225       && micromips_insn_length (mo) != 2)
3226     return FALSE;
3227
3228   return TRUE;
3229 }
3230
3231 /* For consistency checking, verify that all bits of OPCODE are specified
3232    either by the match/mask part of the instruction definition, or by the
3233    operand list.  Also build up a list of operands in OPERANDS.
3234
3235    INSN_BITS says which bits of the instruction are significant.
3236    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3237    provides the mips_operand description of each operand.  DECODE_OPERAND
3238    is null for MIPS16 instructions.  */
3239
3240 static int
3241 validate_mips_insn (const struct mips_opcode *opcode,
3242                     unsigned long insn_bits,
3243                     const struct mips_operand *(*decode_operand) (const char *),
3244                     struct mips_operand_array *operands)
3245 {
3246   const char *s;
3247   unsigned long used_bits, doubled, undefined, opno, mask;
3248   const struct mips_operand *operand;
3249
3250   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3251   if ((mask & opcode->match) != opcode->match)
3252     {
3253       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3254               opcode->name, opcode->args);
3255       return 0;
3256     }
3257   used_bits = 0;
3258   opno = 0;
3259   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3260     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3261   for (s = opcode->args; *s; ++s)
3262     switch (*s)
3263       {
3264       case ',':
3265       case '(':
3266       case ')':
3267         break;
3268
3269       case '#':
3270         s++;
3271         break;
3272
3273       default:
3274         if (!decode_operand)
3275           operand = decode_mips16_operand (*s, FALSE);
3276         else
3277           operand = decode_operand (s);
3278         if (!operand && opcode->pinfo != INSN_MACRO)
3279           {
3280             as_bad (_("internal: unknown operand type: %s %s"),
3281                     opcode->name, opcode->args);
3282             return 0;
3283           }
3284         gas_assert (opno < MAX_OPERANDS);
3285         operands->operand[opno] = operand;
3286         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3287           {
3288             used_bits = mips_insert_operand (operand, used_bits, -1);
3289             if (operand->type == OP_MDMX_IMM_REG)
3290               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3291                  has separate entries for each format.  */
3292               used_bits &= ~(1 << (operand->lsb + 5));
3293             if (operand->type == OP_ENTRY_EXIT_LIST)
3294               used_bits &= ~(mask & 0x700);
3295           }
3296         /* Skip prefix characters.  */
3297         if (decode_operand && (*s == '+' || *s == 'm'))
3298           ++s;
3299         opno += 1;
3300         break;
3301       }
3302   doubled = used_bits & mask & insn_bits;
3303   if (doubled)
3304     {
3305       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3306                 " %s %s"), doubled, opcode->name, opcode->args);
3307       return 0;
3308     }
3309   used_bits |= mask;
3310   undefined = ~used_bits & insn_bits;
3311   if (opcode->pinfo != INSN_MACRO && undefined)
3312     {
3313       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3314               undefined, opcode->name, opcode->args);
3315       return 0;
3316     }
3317   used_bits &= ~insn_bits;
3318   if (used_bits)
3319     {
3320       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3321               used_bits, opcode->name, opcode->args);
3322       return 0;
3323     }
3324   return 1;
3325 }
3326
3327 /* The MIPS16 version of validate_mips_insn.  */
3328
3329 static int
3330 validate_mips16_insn (const struct mips_opcode *opcode,
3331                       struct mips_operand_array *operands)
3332 {
3333   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3334     {
3335       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3336          instruction.  Use TMP to describe the full instruction.  */
3337       struct mips_opcode tmp;
3338
3339       tmp = *opcode;
3340       tmp.match <<= 16;
3341       tmp.mask <<= 16;
3342       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3343     }
3344   return validate_mips_insn (opcode, 0xffff, 0, operands);
3345 }
3346
3347 /* The microMIPS version of validate_mips_insn.  */
3348
3349 static int
3350 validate_micromips_insn (const struct mips_opcode *opc,
3351                          struct mips_operand_array *operands)
3352 {
3353   unsigned long insn_bits;
3354   unsigned long major;
3355   unsigned int length;
3356
3357   if (opc->pinfo == INSN_MACRO)
3358     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3359                                operands);
3360
3361   length = micromips_insn_length (opc);
3362   if (length != 2 && length != 4)
3363     {
3364       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3365                 "%s %s"), length, opc->name, opc->args);
3366       return 0;
3367     }
3368   major = opc->match >> (10 + 8 * (length - 2));
3369   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3370       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3371     {
3372       as_bad (_("internal error: bad microMIPS opcode "
3373                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3374       return 0;
3375     }
3376
3377   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3378   insn_bits = 1 << 4 * length;
3379   insn_bits <<= 4 * length;
3380   insn_bits -= 1;
3381   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3382                              operands);
3383 }
3384
3385 /* This function is called once, at assembler startup time.  It should set up
3386    all the tables, etc. that the MD part of the assembler will need.  */
3387
3388 void
3389 md_begin (void)
3390 {
3391   const char *retval = NULL;
3392   int i = 0;
3393   int broken = 0;
3394
3395   if (mips_pic != NO_PIC)
3396     {
3397       if (g_switch_seen && g_switch_value != 0)
3398         as_bad (_("-G may not be used in position-independent code"));
3399       g_switch_value = 0;
3400     }
3401
3402   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3403     as_warn (_("could not set architecture and machine"));
3404
3405   op_hash = hash_new ();
3406
3407   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3408   for (i = 0; i < NUMOPCODES;)
3409     {
3410       const char *name = mips_opcodes[i].name;
3411
3412       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3413       if (retval != NULL)
3414         {
3415           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3416                    mips_opcodes[i].name, retval);
3417           /* Probably a memory allocation problem?  Give up now.  */
3418           as_fatal (_("broken assembler, no assembly attempted"));
3419         }
3420       do
3421         {
3422           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3423                                    decode_mips_operand, &mips_operands[i]))
3424             broken = 1;
3425           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3426             {
3427               create_insn (&nop_insn, mips_opcodes + i);
3428               if (mips_fix_loongson2f_nop)
3429                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3430               nop_insn.fixed_p = 1;
3431             }
3432           ++i;
3433         }
3434       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3435     }
3436
3437   mips16_op_hash = hash_new ();
3438   mips16_operands = XCNEWVEC (struct mips_operand_array,
3439                               bfd_mips16_num_opcodes);
3440
3441   i = 0;
3442   while (i < bfd_mips16_num_opcodes)
3443     {
3444       const char *name = mips16_opcodes[i].name;
3445
3446       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3447       if (retval != NULL)
3448         as_fatal (_("internal: can't hash `%s': %s"),
3449                   mips16_opcodes[i].name, retval);
3450       do
3451         {
3452           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3453             broken = 1;
3454           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3455             {
3456               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3457               mips16_nop_insn.fixed_p = 1;
3458             }
3459           ++i;
3460         }
3461       while (i < bfd_mips16_num_opcodes
3462              && strcmp (mips16_opcodes[i].name, name) == 0);
3463     }
3464
3465   micromips_op_hash = hash_new ();
3466   micromips_operands = XCNEWVEC (struct mips_operand_array,
3467                                  bfd_micromips_num_opcodes);
3468
3469   i = 0;
3470   while (i < bfd_micromips_num_opcodes)
3471     {
3472       const char *name = micromips_opcodes[i].name;
3473
3474       retval = hash_insert (micromips_op_hash, name,
3475                             (void *) &micromips_opcodes[i]);
3476       if (retval != NULL)
3477         as_fatal (_("internal: can't hash `%s': %s"),
3478                   micromips_opcodes[i].name, retval);
3479       do
3480         {
3481           struct mips_cl_insn *micromips_nop_insn;
3482
3483           if (!validate_micromips_insn (&micromips_opcodes[i],
3484                                         &micromips_operands[i]))
3485             broken = 1;
3486
3487           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3488             {
3489               if (micromips_insn_length (micromips_opcodes + i) == 2)
3490                 micromips_nop_insn = &micromips_nop16_insn;
3491               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3492                 micromips_nop_insn = &micromips_nop32_insn;
3493               else
3494                 continue;
3495
3496               if (micromips_nop_insn->insn_mo == NULL
3497                   && strcmp (name, "nop") == 0)
3498                 {
3499                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3500                   micromips_nop_insn->fixed_p = 1;
3501                 }
3502             }
3503         }
3504       while (++i < bfd_micromips_num_opcodes
3505              && strcmp (micromips_opcodes[i].name, name) == 0);
3506     }
3507
3508   if (broken)
3509     as_fatal (_("broken assembler, no assembly attempted"));
3510
3511   /* We add all the general register names to the symbol table.  This
3512      helps us detect invalid uses of them.  */
3513   for (i = 0; reg_names[i].name; i++) 
3514     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3515                                      reg_names[i].num, /* & RNUM_MASK, */
3516                                      &zero_address_frag));
3517   if (HAVE_NEWABI)
3518     for (i = 0; reg_names_n32n64[i].name; i++) 
3519       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3520                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3521                                        &zero_address_frag));
3522   else
3523     for (i = 0; reg_names_o32[i].name; i++) 
3524       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3525                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3526                                        &zero_address_frag));
3527
3528   for (i = 0; i < 32; i++)
3529     {
3530       char regname[7];
3531
3532       /* R5900 VU0 floating-point register.  */
3533       regname[sizeof (rename) - 1] = 0;
3534       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3535       symbol_table_insert (symbol_new (regname, reg_section,
3536                                        RTYPE_VF | i, &zero_address_frag));
3537
3538       /* R5900 VU0 integer register.  */
3539       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3540       symbol_table_insert (symbol_new (regname, reg_section,
3541                                        RTYPE_VI | i, &zero_address_frag));
3542
3543       /* MSA register.  */
3544       snprintf (regname, sizeof (regname) - 1, "$w%d", i);
3545       symbol_table_insert (symbol_new (regname, reg_section,
3546                                        RTYPE_MSA | i, &zero_address_frag));
3547     }
3548
3549   obstack_init (&mips_operand_tokens);
3550
3551   mips_no_prev_insn ();
3552
3553   mips_gprmask = 0;
3554   mips_cprmask[0] = 0;
3555   mips_cprmask[1] = 0;
3556   mips_cprmask[2] = 0;
3557   mips_cprmask[3] = 0;
3558
3559   /* set the default alignment for the text section (2**2) */
3560   record_alignment (text_section, 2);
3561
3562   bfd_set_gp_size (stdoutput, g_switch_value);
3563
3564   /* On a native system other than VxWorks, sections must be aligned
3565      to 16 byte boundaries.  When configured for an embedded ELF
3566      target, we don't bother.  */
3567   if (strncmp (TARGET_OS, "elf", 3) != 0
3568       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3569     {
3570       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3571       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3572       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3573     }
3574
3575   /* Create a .reginfo section for register masks and a .mdebug
3576      section for debugging information.  */
3577   {
3578     segT seg;
3579     subsegT subseg;
3580     flagword flags;
3581     segT sec;
3582
3583     seg = now_seg;
3584     subseg = now_subseg;
3585
3586     /* The ABI says this section should be loaded so that the
3587        running program can access it.  However, we don't load it
3588        if we are configured for an embedded target */
3589     flags = SEC_READONLY | SEC_DATA;
3590     if (strncmp (TARGET_OS, "elf", 3) != 0)
3591       flags |= SEC_ALLOC | SEC_LOAD;
3592
3593     if (mips_abi != N64_ABI)
3594       {
3595         sec = subseg_new (".reginfo", (subsegT) 0);
3596
3597         bfd_set_section_flags (stdoutput, sec, flags);
3598         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3599
3600         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3601       }
3602     else
3603       {
3604         /* The 64-bit ABI uses a .MIPS.options section rather than
3605            .reginfo section.  */
3606         sec = subseg_new (".MIPS.options", (subsegT) 0);
3607         bfd_set_section_flags (stdoutput, sec, flags);
3608         bfd_set_section_alignment (stdoutput, sec, 3);
3609
3610         /* Set up the option header.  */
3611         {
3612           Elf_Internal_Options opthdr;
3613           char *f;
3614
3615           opthdr.kind = ODK_REGINFO;
3616           opthdr.size = (sizeof (Elf_External_Options)
3617                          + sizeof (Elf64_External_RegInfo));
3618           opthdr.section = 0;
3619           opthdr.info = 0;
3620           f = frag_more (sizeof (Elf_External_Options));
3621           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3622                                          (Elf_External_Options *) f);
3623
3624           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3625         }
3626       }
3627
3628     sec = subseg_new (".MIPS.abiflags", (subsegT) 0);
3629     bfd_set_section_flags (stdoutput, sec,
3630                            SEC_READONLY | SEC_DATA | SEC_ALLOC | SEC_LOAD);
3631     bfd_set_section_alignment (stdoutput, sec, 3);
3632     mips_flags_frag = frag_more (sizeof (Elf_External_ABIFlags_v0));
3633
3634     if (ECOFF_DEBUGGING)
3635       {
3636         sec = subseg_new (".mdebug", (subsegT) 0);
3637         (void) bfd_set_section_flags (stdoutput, sec,
3638                                       SEC_HAS_CONTENTS | SEC_READONLY);
3639         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3640       }
3641     else if (mips_flag_pdr)
3642       {
3643         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3644         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3645                                       SEC_READONLY | SEC_RELOC
3646                                       | SEC_DEBUGGING);
3647         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3648       }
3649
3650     subseg_set (seg, subseg);
3651   }
3652
3653   if (mips_fix_vr4120)
3654     init_vr4120_conflicts ();
3655 }
3656
3657 static inline void
3658 fpabi_incompatible_with (int fpabi, const char *what)
3659 {
3660   as_warn (_(".gnu_attribute %d,%d is incompatible with `%s'"),
3661            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3662 }
3663
3664 static inline void
3665 fpabi_requires (int fpabi, const char *what)
3666 {
3667   as_warn (_(".gnu_attribute %d,%d requires `%s'"),
3668            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3669 }
3670
3671 /* Check -mabi and register sizes against the specified FP ABI.  */
3672 static void
3673 check_fpabi (int fpabi)
3674 {
3675   switch (fpabi)
3676     {
3677     case Val_GNU_MIPS_ABI_FP_DOUBLE:
3678       if (file_mips_opts.soft_float)
3679         fpabi_incompatible_with (fpabi, "softfloat");
3680       else if (file_mips_opts.single_float)
3681         fpabi_incompatible_with (fpabi, "singlefloat");
3682       if (file_mips_opts.gp == 64 && file_mips_opts.fp == 32)
3683         fpabi_incompatible_with (fpabi, "gp=64 fp=32");
3684       else if (file_mips_opts.gp == 32 && file_mips_opts.fp == 64)
3685         fpabi_incompatible_with (fpabi, "gp=32 fp=64");
3686       break;
3687
3688     case Val_GNU_MIPS_ABI_FP_XX:
3689       if (mips_abi != O32_ABI)
3690         fpabi_requires (fpabi, "-mabi=32");
3691       else if (file_mips_opts.soft_float)
3692         fpabi_incompatible_with (fpabi, "softfloat");
3693       else if (file_mips_opts.single_float)
3694         fpabi_incompatible_with (fpabi, "singlefloat");
3695       else if (file_mips_opts.fp != 0)
3696         fpabi_requires (fpabi, "fp=xx");
3697       break;
3698
3699     case Val_GNU_MIPS_ABI_FP_64A:
3700     case Val_GNU_MIPS_ABI_FP_64:
3701       if (mips_abi != O32_ABI)
3702         fpabi_requires (fpabi, "-mabi=32");
3703       else if (file_mips_opts.soft_float)
3704         fpabi_incompatible_with (fpabi, "softfloat");
3705       else if (file_mips_opts.single_float)
3706         fpabi_incompatible_with (fpabi, "singlefloat");
3707       else if (file_mips_opts.fp != 64)
3708         fpabi_requires (fpabi, "fp=64");
3709       else if (fpabi == Val_GNU_MIPS_ABI_FP_64 && !file_mips_opts.oddspreg)
3710         fpabi_incompatible_with (fpabi, "nooddspreg");
3711       else if (fpabi == Val_GNU_MIPS_ABI_FP_64A && file_mips_opts.oddspreg)
3712         fpabi_requires (fpabi, "nooddspreg");
3713       break;
3714
3715     case Val_GNU_MIPS_ABI_FP_SINGLE:
3716       if (file_mips_opts.soft_float)
3717         fpabi_incompatible_with (fpabi, "softfloat");
3718       else if (!file_mips_opts.single_float)
3719         fpabi_requires (fpabi, "singlefloat");
3720       break;
3721
3722     case Val_GNU_MIPS_ABI_FP_SOFT:
3723       if (!file_mips_opts.soft_float)
3724         fpabi_requires (fpabi, "softfloat");
3725       break;
3726
3727     case Val_GNU_MIPS_ABI_FP_OLD_64:
3728       as_warn (_(".gnu_attribute %d,%d is no longer supported"),
3729                Tag_GNU_MIPS_ABI_FP, fpabi);
3730       break;
3731
3732     default:
3733       as_warn (_(".gnu_attribute %d,%d is not a recognized"
3734                  " floating-point ABI"), Tag_GNU_MIPS_ABI_FP, fpabi);
3735       break;
3736     }
3737 }
3738
3739 /* Perform consistency checks on the current options.  */
3740
3741 static void
3742 mips_check_options (struct mips_set_options *opts, bfd_boolean abi_checks)
3743 {
3744   /* Check the size of integer registers agrees with the ABI and ISA.  */
3745   if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
3746     as_bad (_("`gp=64' used with a 32-bit processor"));
3747   else if (abi_checks
3748            && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
3749     as_bad (_("`gp=32' used with a 64-bit ABI"));
3750   else if (abi_checks
3751            && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
3752     as_bad (_("`gp=64' used with a 32-bit ABI"));
3753
3754   /* Check the size of the float registers agrees with the ABI and ISA.  */
3755   switch (opts->fp)
3756     {
3757     case 0:
3758       if (!CPU_HAS_LDC1_SDC1 (opts->arch))
3759         as_bad (_("`fp=xx' used with a cpu lacking ldc1/sdc1 instructions"));
3760       else if (opts->single_float == 1)
3761         as_bad (_("`fp=xx' cannot be used with `singlefloat'"));
3762       break;
3763     case 64:
3764       if (!ISA_HAS_64BIT_FPRS (opts->isa))
3765         as_bad (_("`fp=64' used with a 32-bit fpu"));
3766       else if (abi_checks
3767                && ABI_NEEDS_32BIT_REGS (mips_abi)
3768                && !ISA_HAS_MXHC1 (opts->isa))
3769         as_warn (_("`fp=64' used with a 32-bit ABI"));
3770       break;
3771     case 32:
3772       if (abi_checks
3773           && ABI_NEEDS_64BIT_REGS (mips_abi))
3774         as_warn (_("`fp=32' used with a 64-bit ABI"));
3775       break;
3776     default:
3777       as_bad (_("Unknown size of floating point registers"));
3778       break;
3779     }
3780
3781   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !opts->oddspreg)
3782     as_bad (_("`nooddspreg` cannot be used with a 64-bit ABI"));
3783
3784   if (opts->micromips == 1 && opts->mips16 == 1)
3785     as_bad (_("`mips16' cannot be used with `micromips'"));
3786 }
3787
3788 /* Perform consistency checks on the module level options exactly once.
3789    This is a deferred check that happens:
3790      at the first .set directive
3791      or, at the first pseudo op that generates code (inc .dc.a)
3792      or, at the first instruction
3793      or, at the end.  */
3794
3795 static void
3796 file_mips_check_options (void)
3797 {
3798   const struct mips_cpu_info *arch_info = 0;
3799
3800   if (file_mips_opts_checked)
3801     return;
3802
3803   /* The following code determines the register size.
3804      Similar code was added to GCC 3.3 (see override_options() in
3805      config/mips/mips.c).  The GAS and GCC code should be kept in sync
3806      as much as possible.  */
3807
3808   if (file_mips_opts.gp < 0)
3809     {
3810       /* Infer the integer register size from the ABI and processor.
3811          Restrict ourselves to 32-bit registers if that's all the
3812          processor has, or if the ABI cannot handle 64-bit registers.  */
3813       file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
3814                            || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
3815                           ? 32 : 64;
3816     }
3817
3818   if (file_mips_opts.fp < 0)
3819     {
3820       /* No user specified float register size.
3821          ??? GAS treats single-float processors as though they had 64-bit
3822          float registers (although it complains when double-precision
3823          instructions are used).  As things stand, saying they have 32-bit
3824          registers would lead to spurious "register must be even" messages.
3825          So here we assume float registers are never smaller than the
3826          integer ones.  */
3827       if (file_mips_opts.gp == 64)
3828         /* 64-bit integer registers implies 64-bit float registers.  */
3829         file_mips_opts.fp = 64;
3830       else if ((file_mips_opts.ase & FP64_ASES)
3831                && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
3832         /* Handle ASEs that require 64-bit float registers, if possible.  */
3833         file_mips_opts.fp = 64;
3834       else
3835         /* 32-bit float registers.  */
3836         file_mips_opts.fp = 32;
3837     }
3838
3839   arch_info = mips_cpu_info_from_arch (file_mips_opts.arch);
3840
3841   /* Disable operations on odd-numbered floating-point registers by default
3842      when using the FPXX ABI.  */
3843   if (file_mips_opts.oddspreg < 0)
3844     {
3845       if (file_mips_opts.fp == 0)
3846         file_mips_opts.oddspreg = 0;
3847       else
3848         file_mips_opts.oddspreg = 1;
3849     }
3850
3851   /* End of GCC-shared inference code.  */
3852
3853   /* This flag is set when we have a 64-bit capable CPU but use only
3854      32-bit wide registers.  Note that EABI does not use it.  */
3855   if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
3856       && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
3857           || mips_abi == O32_ABI))
3858     mips_32bitmode = 1;
3859
3860   if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
3861     as_bad (_("trap exception not supported at ISA 1"));
3862
3863   /* If the selected architecture includes support for ASEs, enable
3864      generation of code for them.  */
3865   if (file_mips_opts.mips16 == -1)
3866     file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
3867   if (file_mips_opts.micromips == -1)
3868     file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
3869                                 ? 1 : 0;
3870
3871   /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
3872      being selected implicitly.  */
3873   if (file_mips_opts.fp != 64)
3874     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
3875
3876   /* If the user didn't explicitly select or deselect a particular ASE,
3877      use the default setting for the CPU.  */
3878   file_mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
3879
3880   /* Set up the current options.  These may change throughout assembly.  */
3881   mips_opts = file_mips_opts;
3882
3883   mips_check_isa_supports_ases ();
3884   mips_check_options (&file_mips_opts, TRUE);
3885   file_mips_opts_checked = TRUE;
3886
3887   if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3888     as_warn (_("could not set architecture and machine"));
3889 }
3890
3891 void
3892 md_assemble (char *str)
3893 {
3894   struct mips_cl_insn insn;
3895   bfd_reloc_code_real_type unused_reloc[3]
3896     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3897
3898   file_mips_check_options ();
3899
3900   imm_expr.X_op = O_absent;
3901   offset_expr.X_op = O_absent;
3902   offset_reloc[0] = BFD_RELOC_UNUSED;
3903   offset_reloc[1] = BFD_RELOC_UNUSED;
3904   offset_reloc[2] = BFD_RELOC_UNUSED;
3905
3906   mips_mark_labels ();
3907   mips_assembling_insn = TRUE;
3908   clear_insn_error ();
3909
3910   if (mips_opts.mips16)
3911     mips16_ip (str, &insn);
3912   else
3913     {
3914       mips_ip (str, &insn);
3915       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3916             str, insn.insn_opcode));
3917     }
3918
3919   if (insn_error.msg)
3920     report_insn_error (str);
3921   else if (insn.insn_mo->pinfo == INSN_MACRO)
3922     {
3923       macro_start ();
3924       if (mips_opts.mips16)
3925         mips16_macro (&insn);
3926       else
3927         macro (&insn, str);
3928       macro_end ();
3929     }
3930   else
3931     {
3932       if (offset_expr.X_op != O_absent)
3933         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3934       else
3935         append_insn (&insn, NULL, unused_reloc, FALSE);
3936     }
3937
3938   mips_assembling_insn = FALSE;
3939 }
3940
3941 /* Convenience functions for abstracting away the differences between
3942    MIPS16 and non-MIPS16 relocations.  */
3943
3944 static inline bfd_boolean
3945 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3946 {
3947   switch (reloc)
3948     {
3949     case BFD_RELOC_MIPS16_JMP:
3950     case BFD_RELOC_MIPS16_GPREL:
3951     case BFD_RELOC_MIPS16_GOT16:
3952     case BFD_RELOC_MIPS16_CALL16:
3953     case BFD_RELOC_MIPS16_HI16_S:
3954     case BFD_RELOC_MIPS16_HI16:
3955     case BFD_RELOC_MIPS16_LO16:
3956       return TRUE;
3957
3958     default:
3959       return FALSE;
3960     }
3961 }
3962
3963 static inline bfd_boolean
3964 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3965 {
3966   switch (reloc)
3967     {
3968     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3969     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3970     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3971     case BFD_RELOC_MICROMIPS_GPREL16:
3972     case BFD_RELOC_MICROMIPS_JMP:
3973     case BFD_RELOC_MICROMIPS_HI16:
3974     case BFD_RELOC_MICROMIPS_HI16_S:
3975     case BFD_RELOC_MICROMIPS_LO16:
3976     case BFD_RELOC_MICROMIPS_LITERAL:
3977     case BFD_RELOC_MICROMIPS_GOT16:
3978     case BFD_RELOC_MICROMIPS_CALL16:
3979     case BFD_RELOC_MICROMIPS_GOT_HI16:
3980     case BFD_RELOC_MICROMIPS_GOT_LO16:
3981     case BFD_RELOC_MICROMIPS_CALL_HI16:
3982     case BFD_RELOC_MICROMIPS_CALL_LO16:
3983     case BFD_RELOC_MICROMIPS_SUB:
3984     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3985     case BFD_RELOC_MICROMIPS_GOT_OFST:
3986     case BFD_RELOC_MICROMIPS_GOT_DISP:
3987     case BFD_RELOC_MICROMIPS_HIGHEST:
3988     case BFD_RELOC_MICROMIPS_HIGHER:
3989     case BFD_RELOC_MICROMIPS_SCN_DISP:
3990     case BFD_RELOC_MICROMIPS_JALR:
3991       return TRUE;
3992
3993     default:
3994       return FALSE;
3995     }
3996 }
3997
3998 static inline bfd_boolean
3999 jmp_reloc_p (bfd_reloc_code_real_type reloc)
4000 {
4001   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
4002 }
4003
4004 static inline bfd_boolean
4005 got16_reloc_p (bfd_reloc_code_real_type reloc)
4006 {
4007   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
4008           || reloc == BFD_RELOC_MICROMIPS_GOT16);
4009 }
4010
4011 static inline bfd_boolean
4012 hi16_reloc_p (bfd_reloc_code_real_type reloc)
4013 {
4014   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
4015           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
4016 }
4017
4018 static inline bfd_boolean
4019 lo16_reloc_p (bfd_reloc_code_real_type reloc)
4020 {
4021   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
4022           || reloc == BFD_RELOC_MICROMIPS_LO16);
4023 }
4024
4025 static inline bfd_boolean
4026 jalr_reloc_p (bfd_reloc_code_real_type reloc)
4027 {
4028   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
4029 }
4030
4031 static inline bfd_boolean
4032 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
4033 {
4034   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
4035           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
4036 }
4037
4038 /* Return true if RELOC is a PC-relative relocation that does not have
4039    full address range.  */
4040
4041 static inline bfd_boolean
4042 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
4043 {
4044   switch (reloc)
4045     {
4046     case BFD_RELOC_16_PCREL_S2:
4047     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4048     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4049     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4050       return TRUE;
4051
4052     case BFD_RELOC_32_PCREL:
4053       return HAVE_64BIT_ADDRESSES;
4054
4055     default:
4056       return FALSE;
4057     }
4058 }
4059
4060 /* Return true if the given relocation might need a matching %lo().
4061    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
4062    need a matching %lo() when applied to local symbols.  */
4063
4064 static inline bfd_boolean
4065 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
4066 {
4067   return (HAVE_IN_PLACE_ADDENDS
4068           && (hi16_reloc_p (reloc)
4069               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
4070                  all GOT16 relocations evaluate to "G".  */
4071               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
4072 }
4073
4074 /* Return the type of %lo() reloc needed by RELOC, given that
4075    reloc_needs_lo_p.  */
4076
4077 static inline bfd_reloc_code_real_type
4078 matching_lo_reloc (bfd_reloc_code_real_type reloc)
4079 {
4080   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
4081           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
4082              : BFD_RELOC_LO16));
4083 }
4084
4085 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
4086    relocation.  */
4087
4088 static inline bfd_boolean
4089 fixup_has_matching_lo_p (fixS *fixp)
4090 {
4091   return (fixp->fx_next != NULL
4092           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
4093           && fixp->fx_addsy == fixp->fx_next->fx_addsy
4094           && fixp->fx_offset == fixp->fx_next->fx_offset);
4095 }
4096
4097 /* Move all labels in LABELS to the current insertion point.  TEXT_P
4098    says whether the labels refer to text or data.  */
4099
4100 static void
4101 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
4102 {
4103   struct insn_label_list *l;
4104   valueT val;
4105
4106   for (l = labels; l != NULL; l = l->next)
4107     {
4108       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
4109       symbol_set_frag (l->label, frag_now);
4110       val = (valueT) frag_now_fix ();
4111       /* MIPS16/microMIPS text labels are stored as odd.  */
4112       if (text_p && HAVE_CODE_COMPRESSION)
4113         ++val;
4114       S_SET_VALUE (l->label, val);
4115     }
4116 }
4117
4118 /* Move all labels in insn_labels to the current insertion point
4119    and treat them as text labels.  */
4120
4121 static void
4122 mips_move_text_labels (void)
4123 {
4124   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
4125 }
4126
4127 static bfd_boolean
4128 s_is_linkonce (symbolS *sym, segT from_seg)
4129 {
4130   bfd_boolean linkonce = FALSE;
4131   segT symseg = S_GET_SEGMENT (sym);
4132
4133   if (symseg != from_seg && !S_IS_LOCAL (sym))
4134     {
4135       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
4136         linkonce = TRUE;
4137       /* The GNU toolchain uses an extension for ELF: a section
4138          beginning with the magic string .gnu.linkonce is a
4139          linkonce section.  */
4140       if (strncmp (segment_name (symseg), ".gnu.linkonce",
4141                    sizeof ".gnu.linkonce" - 1) == 0)
4142         linkonce = TRUE;
4143     }
4144   return linkonce;
4145 }
4146
4147 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4148    linker to handle them specially, such as generating jalx instructions
4149    when needed.  We also make them odd for the duration of the assembly,
4150    in order to generate the right sort of code.  We will make them even
4151    in the adjust_symtab routine, while leaving them marked.  This is
4152    convenient for the debugger and the disassembler.  The linker knows
4153    to make them odd again.  */
4154
4155 static void
4156 mips_compressed_mark_label (symbolS *label)
4157 {
4158   gas_assert (HAVE_CODE_COMPRESSION);
4159
4160   if (mips_opts.mips16)
4161     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4162   else
4163     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4164   if ((S_GET_VALUE (label) & 1) == 0
4165       /* Don't adjust the address if the label is global or weak, or
4166          in a link-once section, since we'll be emitting symbol reloc
4167          references to it which will be patched up by the linker, and
4168          the final value of the symbol may or may not be MIPS16/microMIPS.  */
4169       && !S_IS_WEAK (label)
4170       && !S_IS_EXTERNAL (label)
4171       && !s_is_linkonce (label, now_seg))
4172     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4173 }
4174
4175 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
4176
4177 static void
4178 mips_compressed_mark_labels (void)
4179 {
4180   struct insn_label_list *l;
4181
4182   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4183     mips_compressed_mark_label (l->label);
4184 }
4185
4186 /* End the current frag.  Make it a variant frag and record the
4187    relaxation info.  */
4188
4189 static void
4190 relax_close_frag (void)
4191 {
4192   mips_macro_warning.first_frag = frag_now;
4193   frag_var (rs_machine_dependent, 0, 0,
4194             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
4195             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4196
4197   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4198   mips_relax.first_fixup = 0;
4199 }
4200
4201 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
4202    See the comment above RELAX_ENCODE for more details.  */
4203
4204 static void
4205 relax_start (symbolS *symbol)
4206 {
4207   gas_assert (mips_relax.sequence == 0);
4208   mips_relax.sequence = 1;
4209   mips_relax.symbol = symbol;
4210 }
4211
4212 /* Start generating the second version of a relaxable sequence.
4213    See the comment above RELAX_ENCODE for more details.  */
4214
4215 static void
4216 relax_switch (void)
4217 {
4218   gas_assert (mips_relax.sequence == 1);
4219   mips_relax.sequence = 2;
4220 }
4221
4222 /* End the current relaxable sequence.  */
4223
4224 static void
4225 relax_end (void)
4226 {
4227   gas_assert (mips_relax.sequence == 2);
4228   relax_close_frag ();
4229   mips_relax.sequence = 0;
4230 }
4231
4232 /* Return true if IP is a delayed branch or jump.  */
4233
4234 static inline bfd_boolean
4235 delayed_branch_p (const struct mips_cl_insn *ip)
4236 {
4237   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4238                                 | INSN_COND_BRANCH_DELAY
4239                                 | INSN_COND_BRANCH_LIKELY)) != 0;
4240 }
4241
4242 /* Return true if IP is a compact branch or jump.  */
4243
4244 static inline bfd_boolean
4245 compact_branch_p (const struct mips_cl_insn *ip)
4246 {
4247   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4248                                  | INSN2_COND_BRANCH)) != 0;
4249 }
4250
4251 /* Return true if IP is an unconditional branch or jump.  */
4252
4253 static inline bfd_boolean
4254 uncond_branch_p (const struct mips_cl_insn *ip)
4255 {
4256   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4257           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4258 }
4259
4260 /* Return true if IP is a branch-likely instruction.  */
4261
4262 static inline bfd_boolean
4263 branch_likely_p (const struct mips_cl_insn *ip)
4264 {
4265   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4266 }
4267
4268 /* Return the type of nop that should be used to fill the delay slot
4269    of delayed branch IP.  */
4270
4271 static struct mips_cl_insn *
4272 get_delay_slot_nop (const struct mips_cl_insn *ip)
4273 {
4274   if (mips_opts.micromips
4275       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4276     return &micromips_nop32_insn;
4277   return NOP_INSN;
4278 }
4279
4280 /* Return a mask that has bit N set if OPCODE reads the register(s)
4281    in operand N.  */
4282
4283 static unsigned int
4284 insn_read_mask (const struct mips_opcode *opcode)
4285 {
4286   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4287 }
4288
4289 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4290    in operand N.  */
4291
4292 static unsigned int
4293 insn_write_mask (const struct mips_opcode *opcode)
4294 {
4295   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4296 }
4297
4298 /* Return a mask of the registers specified by operand OPERAND of INSN.
4299    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4300    is set.  */
4301
4302 static unsigned int
4303 operand_reg_mask (const struct mips_cl_insn *insn,
4304                   const struct mips_operand *operand,
4305                   unsigned int type_mask)
4306 {
4307   unsigned int uval, vsel;
4308
4309   switch (operand->type)
4310     {
4311     case OP_INT:
4312     case OP_MAPPED_INT:
4313     case OP_MSB:
4314     case OP_PCREL:
4315     case OP_PERF_REG:
4316     case OP_ADDIUSP_INT:
4317     case OP_ENTRY_EXIT_LIST:
4318     case OP_REPEAT_DEST_REG:
4319     case OP_REPEAT_PREV_REG:
4320     case OP_PC:
4321     case OP_VU0_SUFFIX:
4322     case OP_VU0_MATCH_SUFFIX:
4323     case OP_IMM_INDEX:
4324       abort ();
4325
4326     case OP_REG:
4327     case OP_OPTIONAL_REG:
4328       {
4329         const struct mips_reg_operand *reg_op;
4330
4331         reg_op = (const struct mips_reg_operand *) operand;
4332         if (!(type_mask & (1 << reg_op->reg_type)))
4333           return 0;
4334         uval = insn_extract_operand (insn, operand);
4335         return 1 << mips_decode_reg_operand (reg_op, uval);
4336       }
4337
4338     case OP_REG_PAIR:
4339       {
4340         const struct mips_reg_pair_operand *pair_op;
4341
4342         pair_op = (const struct mips_reg_pair_operand *) operand;
4343         if (!(type_mask & (1 << pair_op->reg_type)))
4344           return 0;
4345         uval = insn_extract_operand (insn, operand);
4346         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4347       }
4348
4349     case OP_CLO_CLZ_DEST:
4350       if (!(type_mask & (1 << OP_REG_GP)))
4351         return 0;
4352       uval = insn_extract_operand (insn, operand);
4353       return (1 << (uval & 31)) | (1 << (uval >> 5));
4354
4355     case OP_LWM_SWM_LIST:
4356       abort ();
4357
4358     case OP_SAVE_RESTORE_LIST:
4359       abort ();
4360
4361     case OP_MDMX_IMM_REG:
4362       if (!(type_mask & (1 << OP_REG_VEC)))
4363         return 0;
4364       uval = insn_extract_operand (insn, operand);
4365       vsel = uval >> 5;
4366       if ((vsel & 0x18) == 0x18)
4367         return 0;
4368       return 1 << (uval & 31);
4369
4370     case OP_REG_INDEX:
4371       if (!(type_mask & (1 << OP_REG_GP)))
4372         return 0;
4373       return 1 << insn_extract_operand (insn, operand);
4374     }
4375   abort ();
4376 }
4377
4378 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4379    where bit N of OPNO_MASK is set if operand N should be included.
4380    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4381    is set.  */
4382
4383 static unsigned int
4384 insn_reg_mask (const struct mips_cl_insn *insn,
4385                unsigned int type_mask, unsigned int opno_mask)
4386 {
4387   unsigned int opno, reg_mask;
4388
4389   opno = 0;
4390   reg_mask = 0;
4391   while (opno_mask != 0)
4392     {
4393       if (opno_mask & 1)
4394         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4395       opno_mask >>= 1;
4396       opno += 1;
4397     }
4398   return reg_mask;
4399 }
4400
4401 /* Return the mask of core registers that IP reads.  */
4402
4403 static unsigned int
4404 gpr_read_mask (const struct mips_cl_insn *ip)
4405 {
4406   unsigned long pinfo, pinfo2;
4407   unsigned int mask;
4408
4409   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4410   pinfo = ip->insn_mo->pinfo;
4411   pinfo2 = ip->insn_mo->pinfo2;
4412   if (pinfo & INSN_UDI)
4413     {
4414       /* UDI instructions have traditionally been assumed to read RS
4415          and RT.  */
4416       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4417       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4418     }
4419   if (pinfo & INSN_READ_GPR_24)
4420     mask |= 1 << 24;
4421   if (pinfo2 & INSN2_READ_GPR_16)
4422     mask |= 1 << 16;
4423   if (pinfo2 & INSN2_READ_SP)
4424     mask |= 1 << SP;
4425   if (pinfo2 & INSN2_READ_GPR_31)
4426     mask |= 1 << 31;
4427   /* Don't include register 0.  */
4428   return mask & ~1;
4429 }
4430
4431 /* Return the mask of core registers that IP writes.  */
4432
4433 static unsigned int
4434 gpr_write_mask (const struct mips_cl_insn *ip)
4435 {
4436   unsigned long pinfo, pinfo2;
4437   unsigned int mask;
4438
4439   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4440   pinfo = ip->insn_mo->pinfo;
4441   pinfo2 = ip->insn_mo->pinfo2;
4442   if (pinfo & INSN_WRITE_GPR_24)
4443     mask |= 1 << 24;
4444   if (pinfo & INSN_WRITE_GPR_31)
4445     mask |= 1 << 31;
4446   if (pinfo & INSN_UDI)
4447     /* UDI instructions have traditionally been assumed to write to RD.  */
4448     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4449   if (pinfo2 & INSN2_WRITE_SP)
4450     mask |= 1 << SP;
4451   /* Don't include register 0.  */
4452   return mask & ~1;
4453 }
4454
4455 /* Return the mask of floating-point registers that IP reads.  */
4456
4457 static unsigned int
4458 fpr_read_mask (const struct mips_cl_insn *ip)
4459 {
4460   unsigned long pinfo;
4461   unsigned int mask;
4462
4463   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4464                              | (1 << OP_REG_MSA)),
4465                         insn_read_mask (ip->insn_mo));
4466   pinfo = ip->insn_mo->pinfo;
4467   /* Conservatively treat all operands to an FP_D instruction are doubles.
4468      (This is overly pessimistic for things like cvt.d.s.)  */
4469   if (FPR_SIZE != 64 && (pinfo & FP_D))
4470     mask |= mask << 1;
4471   return mask;
4472 }
4473
4474 /* Return the mask of floating-point registers that IP writes.  */
4475
4476 static unsigned int
4477 fpr_write_mask (const struct mips_cl_insn *ip)
4478 {
4479   unsigned long pinfo;
4480   unsigned int mask;
4481
4482   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4483                              | (1 << OP_REG_MSA)),
4484                         insn_write_mask (ip->insn_mo));
4485   pinfo = ip->insn_mo->pinfo;
4486   /* Conservatively treat all operands to an FP_D instruction are doubles.
4487      (This is overly pessimistic for things like cvt.s.d.)  */
4488   if (FPR_SIZE != 64 && (pinfo & FP_D))
4489     mask |= mask << 1;
4490   return mask;
4491 }
4492
4493 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4494    Check whether that is allowed.  */
4495
4496 static bfd_boolean
4497 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4498 {
4499   const char *s = insn->name;
4500   bfd_boolean oddspreg = (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa, mips_opts.arch)
4501                           || FPR_SIZE == 64)
4502                          && mips_opts.oddspreg;
4503
4504   if (insn->pinfo == INSN_MACRO)
4505     /* Let a macro pass, we'll catch it later when it is expanded.  */
4506     return TRUE;
4507
4508   /* Single-precision coprocessor loads and moves are OK for 32-bit registers,
4509      otherwise it depends on oddspreg.  */
4510   if ((insn->pinfo & FP_S)
4511       && (insn->pinfo & (INSN_LOAD_MEMORY | INSN_STORE_MEMORY
4512                          | INSN_LOAD_COPROC | INSN_COPROC_MOVE)))
4513     return FPR_SIZE == 32 || oddspreg;
4514
4515   /* Allow odd registers for single-precision ops and double-precision if the
4516      floating-point registers are 64-bit wide.  */
4517   switch (insn->pinfo & (FP_S | FP_D))
4518     {
4519     case FP_S:
4520     case 0:
4521       return oddspreg;
4522     case FP_D:
4523       return FPR_SIZE == 64;
4524     default:
4525       break;
4526     }
4527
4528   /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4529   s = strchr (insn->name, '.');
4530   if (s != NULL && opnum == 2)
4531     s = strchr (s + 1, '.');
4532   if (s != NULL && (s[1] == 'w' || s[1] == 's'))
4533     return oddspreg;
4534
4535   return FPR_SIZE == 64;
4536 }
4537
4538 /* Information about an instruction argument that we're trying to match.  */
4539 struct mips_arg_info
4540 {
4541   /* The instruction so far.  */
4542   struct mips_cl_insn *insn;
4543
4544   /* The first unconsumed operand token.  */
4545   struct mips_operand_token *token;
4546
4547   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4548   int opnum;
4549
4550   /* The 1-based argument number, for error reporting.  This does not
4551      count elided optional registers, etc..  */
4552   int argnum;
4553
4554   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4555   unsigned int last_regno;
4556
4557   /* If the first operand was an OP_REG, this is the register that it
4558      specified, otherwise it is ILLEGAL_REG.  */
4559   unsigned int dest_regno;
4560
4561   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4562      where it gives the lsb position.  */
4563   unsigned int last_op_int;
4564
4565   /* If true, match routines should assume that no later instruction
4566      alternative matches and should therefore be as accomodating as
4567      possible.  Match routines should not report errors if something
4568      is only invalid for !LAX_MATCH.  */
4569   bfd_boolean lax_match;
4570
4571   /* True if a reference to the current AT register was seen.  */
4572   bfd_boolean seen_at;
4573 };
4574
4575 /* Record that the argument is out of range.  */
4576
4577 static void
4578 match_out_of_range (struct mips_arg_info *arg)
4579 {
4580   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4581 }
4582
4583 /* Record that the argument isn't constant but needs to be.  */
4584
4585 static void
4586 match_not_constant (struct mips_arg_info *arg)
4587 {
4588   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4589                     arg->argnum);
4590 }
4591
4592 /* Try to match an OT_CHAR token for character CH.  Consume the token
4593    and return true on success, otherwise return false.  */
4594
4595 static bfd_boolean
4596 match_char (struct mips_arg_info *arg, char ch)
4597 {
4598   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4599     {
4600       ++arg->token;
4601       if (ch == ',')
4602         arg->argnum += 1;
4603       return TRUE;
4604     }
4605   return FALSE;
4606 }
4607
4608 /* Try to get an expression from the next tokens in ARG.  Consume the
4609    tokens and return true on success, storing the expression value in
4610    VALUE and relocation types in R.  */
4611
4612 static bfd_boolean
4613 match_expression (struct mips_arg_info *arg, expressionS *value,
4614                   bfd_reloc_code_real_type *r)
4615 {
4616   /* If the next token is a '(' that was parsed as being part of a base
4617      expression, assume we have an elided offset.  The later match will fail
4618      if this turns out to be wrong.  */
4619   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4620     {
4621       value->X_op = O_constant;
4622       value->X_add_number = 0;
4623       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4624       return TRUE;
4625     }
4626
4627   /* Reject register-based expressions such as "0+$2" and "(($2))".
4628      For plain registers the default error seems more appropriate.  */
4629   if (arg->token->type == OT_INTEGER
4630       && arg->token->u.integer.value.X_op == O_register)
4631     {
4632       set_insn_error (arg->argnum, _("register value used as expression"));
4633       return FALSE;
4634     }
4635
4636   if (arg->token->type == OT_INTEGER)
4637     {
4638       *value = arg->token->u.integer.value;
4639       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4640       ++arg->token;
4641       return TRUE;
4642     }
4643
4644   set_insn_error_i
4645     (arg->argnum, _("operand %d must be an immediate expression"),
4646      arg->argnum);
4647   return FALSE;
4648 }
4649
4650 /* Try to get a constant expression from the next tokens in ARG.  Consume
4651    the tokens and return return true on success, storing the constant value
4652    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4653    error.  */
4654
4655 static bfd_boolean
4656 match_const_int (struct mips_arg_info *arg, offsetT *value)
4657 {
4658   expressionS ex;
4659   bfd_reloc_code_real_type r[3];
4660
4661   if (!match_expression (arg, &ex, r))
4662     return FALSE;
4663
4664   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4665     *value = ex.X_add_number;
4666   else
4667     {
4668       match_not_constant (arg);
4669       return FALSE;
4670     }
4671   return TRUE;
4672 }
4673
4674 /* Return the RTYPE_* flags for a register operand of type TYPE that
4675    appears in instruction OPCODE.  */
4676
4677 static unsigned int
4678 convert_reg_type (const struct mips_opcode *opcode,
4679                   enum mips_reg_operand_type type)
4680 {
4681   switch (type)
4682     {
4683     case OP_REG_GP:
4684       return RTYPE_NUM | RTYPE_GP;
4685
4686     case OP_REG_FP:
4687       /* Allow vector register names for MDMX if the instruction is a 64-bit
4688          FPR load, store or move (including moves to and from GPRs).  */
4689       if ((mips_opts.ase & ASE_MDMX)
4690           && (opcode->pinfo & FP_D)
4691           && (opcode->pinfo & (INSN_COPROC_MOVE
4692                                | INSN_COPROC_MEMORY_DELAY
4693                                | INSN_LOAD_COPROC
4694                                | INSN_LOAD_MEMORY
4695                                | INSN_STORE_MEMORY)))
4696         return RTYPE_FPU | RTYPE_VEC;
4697       return RTYPE_FPU;
4698
4699     case OP_REG_CCC:
4700       if (opcode->pinfo & (FP_D | FP_S))
4701         return RTYPE_CCC | RTYPE_FCC;
4702       return RTYPE_CCC;
4703
4704     case OP_REG_VEC:
4705       if (opcode->membership & INSN_5400)
4706         return RTYPE_FPU;
4707       return RTYPE_FPU | RTYPE_VEC;
4708
4709     case OP_REG_ACC:
4710       return RTYPE_ACC;
4711
4712     case OP_REG_COPRO:
4713       if (opcode->name[strlen (opcode->name) - 1] == '0')
4714         return RTYPE_NUM | RTYPE_CP0;
4715       return RTYPE_NUM;
4716
4717     case OP_REG_HW:
4718       return RTYPE_NUM;
4719
4720     case OP_REG_VI:
4721       return RTYPE_NUM | RTYPE_VI;
4722
4723     case OP_REG_VF:
4724       return RTYPE_NUM | RTYPE_VF;
4725
4726     case OP_REG_R5900_I:
4727       return RTYPE_R5900_I;
4728
4729     case OP_REG_R5900_Q:
4730       return RTYPE_R5900_Q;
4731
4732     case OP_REG_R5900_R:
4733       return RTYPE_R5900_R;
4734
4735     case OP_REG_R5900_ACC:
4736       return RTYPE_R5900_ACC;
4737
4738     case OP_REG_MSA:
4739       return RTYPE_MSA;
4740
4741     case OP_REG_MSA_CTRL:
4742       return RTYPE_NUM;
4743     }
4744   abort ();
4745 }
4746
4747 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4748
4749 static void
4750 check_regno (struct mips_arg_info *arg,
4751              enum mips_reg_operand_type type, unsigned int regno)
4752 {
4753   if (AT && type == OP_REG_GP && regno == AT)
4754     arg->seen_at = TRUE;
4755
4756   if (type == OP_REG_FP
4757       && (regno & 1) != 0
4758       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4759     {
4760       /* This was a warning prior to introducing O32 FPXX and FP64 support
4761          so maintain a warning for FP32 but raise an error for the new
4762          cases.  */
4763       if (FPR_SIZE == 32)
4764         as_warn (_("float register should be even, was %d"), regno);
4765       else
4766         as_bad (_("float register should be even, was %d"), regno);
4767     }
4768
4769   if (type == OP_REG_CCC)
4770     {
4771       const char *name;
4772       size_t length;
4773
4774       name = arg->insn->insn_mo->name;
4775       length = strlen (name);
4776       if ((regno & 1) != 0
4777           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4778               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4779         as_warn (_("condition code register should be even for %s, was %d"),
4780                  name, regno);
4781
4782       if ((regno & 3) != 0
4783           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4784         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4785                  name, regno);
4786     }
4787 }
4788
4789 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4790    a register of type TYPE.  Return true on success, storing the register
4791    number in *REGNO and warning about any dubious uses.  */
4792
4793 static bfd_boolean
4794 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4795              unsigned int symval, unsigned int *regno)
4796 {
4797   if (type == OP_REG_VEC)
4798     symval = mips_prefer_vec_regno (symval);
4799   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4800     return FALSE;
4801
4802   *regno = symval & RNUM_MASK;
4803   check_regno (arg, type, *regno);
4804   return TRUE;
4805 }
4806
4807 /* Try to interpret the next token in ARG as a register of type TYPE.
4808    Consume the token and return true on success, storing the register
4809    number in *REGNO.  Return false on failure.  */
4810
4811 static bfd_boolean
4812 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4813            unsigned int *regno)
4814 {
4815   if (arg->token->type == OT_REG
4816       && match_regno (arg, type, arg->token->u.regno, regno))
4817     {
4818       ++arg->token;
4819       return TRUE;
4820     }
4821   return FALSE;
4822 }
4823
4824 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4825    Consume the token and return true on success, storing the register numbers
4826    in *REGNO1 and *REGNO2.  Return false on failure.  */
4827
4828 static bfd_boolean
4829 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4830                  unsigned int *regno1, unsigned int *regno2)
4831 {
4832   if (match_reg (arg, type, regno1))
4833     {
4834       *regno2 = *regno1;
4835       return TRUE;
4836     }
4837   if (arg->token->type == OT_REG_RANGE
4838       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4839       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4840       && *regno1 <= *regno2)
4841     {
4842       ++arg->token;
4843       return TRUE;
4844     }
4845   return FALSE;
4846 }
4847
4848 /* OP_INT matcher.  */
4849
4850 static bfd_boolean
4851 match_int_operand (struct mips_arg_info *arg,
4852                    const struct mips_operand *operand_base)
4853 {
4854   const struct mips_int_operand *operand;
4855   unsigned int uval;
4856   int min_val, max_val, factor;
4857   offsetT sval;
4858
4859   operand = (const struct mips_int_operand *) operand_base;
4860   factor = 1 << operand->shift;
4861   min_val = mips_int_operand_min (operand);
4862   max_val = mips_int_operand_max (operand);
4863
4864   if (operand_base->lsb == 0
4865       && operand_base->size == 16
4866       && operand->shift == 0
4867       && operand->bias == 0
4868       && (operand->max_val == 32767 || operand->max_val == 65535))
4869     {
4870       /* The operand can be relocated.  */
4871       if (!match_expression (arg, &offset_expr, offset_reloc))
4872         return FALSE;
4873
4874       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4875         /* Relocation operators were used.  Accept the arguent and
4876            leave the relocation value in offset_expr and offset_relocs
4877            for the caller to process.  */
4878         return TRUE;
4879
4880       if (offset_expr.X_op != O_constant)
4881         {
4882           /* Accept non-constant operands if no later alternative matches,
4883              leaving it for the caller to process.  */
4884           if (!arg->lax_match)
4885             return FALSE;
4886           offset_reloc[0] = BFD_RELOC_LO16;
4887           return TRUE;
4888         }
4889
4890       /* Clear the global state; we're going to install the operand
4891          ourselves.  */
4892       sval = offset_expr.X_add_number;
4893       offset_expr.X_op = O_absent;
4894
4895       /* For compatibility with older assemblers, we accept
4896          0x8000-0xffff as signed 16-bit numbers when only
4897          signed numbers are allowed.  */
4898       if (sval > max_val)
4899         {
4900           max_val = ((1 << operand_base->size) - 1) << operand->shift;
4901           if (!arg->lax_match && sval <= max_val)
4902             return FALSE;
4903         }
4904     }
4905   else
4906     {
4907       if (!match_const_int (arg, &sval))
4908         return FALSE;
4909     }
4910
4911   arg->last_op_int = sval;
4912
4913   if (sval < min_val || sval > max_val || sval % factor)
4914     {
4915       match_out_of_range (arg);
4916       return FALSE;
4917     }
4918
4919   uval = (unsigned int) sval >> operand->shift;
4920   uval -= operand->bias;
4921
4922   /* Handle -mfix-cn63xxp1.  */
4923   if (arg->opnum == 1
4924       && mips_fix_cn63xxp1
4925       && !mips_opts.micromips
4926       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4927     switch (uval)
4928       {
4929       case 5:
4930       case 25:
4931       case 26:
4932       case 27:
4933       case 28:
4934       case 29:
4935       case 30:
4936       case 31:
4937         /* These are ok.  */
4938         break;
4939
4940       default:
4941         /* The rest must be changed to 28.  */
4942         uval = 28;
4943         break;
4944       }
4945
4946   insn_insert_operand (arg->insn, operand_base, uval);
4947   return TRUE;
4948 }
4949
4950 /* OP_MAPPED_INT matcher.  */
4951
4952 static bfd_boolean
4953 match_mapped_int_operand (struct mips_arg_info *arg,
4954                           const struct mips_operand *operand_base)
4955 {
4956   const struct mips_mapped_int_operand *operand;
4957   unsigned int uval, num_vals;
4958   offsetT sval;
4959
4960   operand = (const struct mips_mapped_int_operand *) operand_base;
4961   if (!match_const_int (arg, &sval))
4962     return FALSE;
4963
4964   num_vals = 1 << operand_base->size;
4965   for (uval = 0; uval < num_vals; uval++)
4966     if (operand->int_map[uval] == sval)
4967       break;
4968   if (uval == num_vals)
4969     {
4970       match_out_of_range (arg);
4971       return FALSE;
4972     }
4973
4974   insn_insert_operand (arg->insn, operand_base, uval);
4975   return TRUE;
4976 }
4977
4978 /* OP_MSB matcher.  */
4979
4980 static bfd_boolean
4981 match_msb_operand (struct mips_arg_info *arg,
4982                    const struct mips_operand *operand_base)
4983 {
4984   const struct mips_msb_operand *operand;
4985   int min_val, max_val, max_high;
4986   offsetT size, sval, high;
4987
4988   operand = (const struct mips_msb_operand *) operand_base;
4989   min_val = operand->bias;
4990   max_val = min_val + (1 << operand_base->size) - 1;
4991   max_high = operand->opsize;
4992
4993   if (!match_const_int (arg, &size))
4994     return FALSE;
4995
4996   high = size + arg->last_op_int;
4997   sval = operand->add_lsb ? high : size;
4998
4999   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
5000     {
5001       match_out_of_range (arg);
5002       return FALSE;
5003     }
5004   insn_insert_operand (arg->insn, operand_base, sval - min_val);
5005   return TRUE;
5006 }
5007
5008 /* OP_REG matcher.  */
5009
5010 static bfd_boolean
5011 match_reg_operand (struct mips_arg_info *arg,
5012                    const struct mips_operand *operand_base)
5013 {
5014   const struct mips_reg_operand *operand;
5015   unsigned int regno, uval, num_vals;
5016
5017   operand = (const struct mips_reg_operand *) operand_base;
5018   if (!match_reg (arg, operand->reg_type, &regno))
5019     return FALSE;
5020
5021   if (operand->reg_map)
5022     {
5023       num_vals = 1 << operand->root.size;
5024       for (uval = 0; uval < num_vals; uval++)
5025         if (operand->reg_map[uval] == regno)
5026           break;
5027       if (num_vals == uval)
5028         return FALSE;
5029     }
5030   else
5031     uval = regno;
5032
5033   arg->last_regno = regno;
5034   if (arg->opnum == 1)
5035     arg->dest_regno = regno;
5036   insn_insert_operand (arg->insn, operand_base, uval);
5037   return TRUE;
5038 }
5039
5040 /* OP_REG_PAIR matcher.  */
5041
5042 static bfd_boolean
5043 match_reg_pair_operand (struct mips_arg_info *arg,
5044                         const struct mips_operand *operand_base)
5045 {
5046   const struct mips_reg_pair_operand *operand;
5047   unsigned int regno1, regno2, uval, num_vals;
5048
5049   operand = (const struct mips_reg_pair_operand *) operand_base;
5050   if (!match_reg (arg, operand->reg_type, &regno1)
5051       || !match_char (arg, ',')
5052       || !match_reg (arg, operand->reg_type, &regno2))
5053     return FALSE;
5054
5055   num_vals = 1 << operand_base->size;
5056   for (uval = 0; uval < num_vals; uval++)
5057     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
5058       break;
5059   if (uval == num_vals)
5060     return FALSE;
5061
5062   insn_insert_operand (arg->insn, operand_base, uval);
5063   return TRUE;
5064 }
5065
5066 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
5067
5068 static bfd_boolean
5069 match_pcrel_operand (struct mips_arg_info *arg)
5070 {
5071   bfd_reloc_code_real_type r[3];
5072
5073   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
5074 }
5075
5076 /* OP_PERF_REG matcher.  */
5077
5078 static bfd_boolean
5079 match_perf_reg_operand (struct mips_arg_info *arg,
5080                         const struct mips_operand *operand)
5081 {
5082   offsetT sval;
5083
5084   if (!match_const_int (arg, &sval))
5085     return FALSE;
5086
5087   if (sval != 0
5088       && (sval != 1
5089           || (mips_opts.arch == CPU_R5900
5090               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
5091                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
5092     {
5093       set_insn_error (arg->argnum, _("invalid performance register"));
5094       return FALSE;
5095     }
5096
5097   insn_insert_operand (arg->insn, operand, sval);
5098   return TRUE;
5099 }
5100
5101 /* OP_ADDIUSP matcher.  */
5102
5103 static bfd_boolean
5104 match_addiusp_operand (struct mips_arg_info *arg,
5105                        const struct mips_operand *operand)
5106 {
5107   offsetT sval;
5108   unsigned int uval;
5109
5110   if (!match_const_int (arg, &sval))
5111     return FALSE;
5112
5113   if (sval % 4)
5114     {
5115       match_out_of_range (arg);
5116       return FALSE;
5117     }
5118
5119   sval /= 4;
5120   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
5121     {
5122       match_out_of_range (arg);
5123       return FALSE;
5124     }
5125
5126   uval = (unsigned int) sval;
5127   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
5128   insn_insert_operand (arg->insn, operand, uval);
5129   return TRUE;
5130 }
5131
5132 /* OP_CLO_CLZ_DEST matcher.  */
5133
5134 static bfd_boolean
5135 match_clo_clz_dest_operand (struct mips_arg_info *arg,
5136                             const struct mips_operand *operand)
5137 {
5138   unsigned int regno;
5139
5140   if (!match_reg (arg, OP_REG_GP, &regno))
5141     return FALSE;
5142
5143   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5144   return TRUE;
5145 }
5146
5147 /* OP_LWM_SWM_LIST matcher.  */
5148
5149 static bfd_boolean
5150 match_lwm_swm_list_operand (struct mips_arg_info *arg,
5151                             const struct mips_operand *operand)
5152 {
5153   unsigned int reglist, sregs, ra, regno1, regno2;
5154   struct mips_arg_info reset;
5155
5156   reglist = 0;
5157   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5158     return FALSE;
5159   do
5160     {
5161       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5162         {
5163           reglist |= 1 << FP;
5164           regno2 = S7;
5165         }
5166       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5167       reset = *arg;
5168     }
5169   while (match_char (arg, ',')
5170          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5171   *arg = reset;
5172
5173   if (operand->size == 2)
5174     {
5175       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5176
5177          s0, ra
5178          s0, s1, ra, s2, s3
5179          s0-s2, ra
5180
5181          and any permutations of these.  */
5182       if ((reglist & 0xfff1ffff) != 0x80010000)
5183         return FALSE;
5184
5185       sregs = (reglist >> 17) & 7;
5186       ra = 0;
5187     }
5188   else
5189     {
5190       /* The list must include at least one of ra and s0-sN,
5191          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5192          which are $23 and $30 respectively.)  E.g.:
5193
5194          ra
5195          s0
5196          ra, s0, s1, s2
5197          s0-s8
5198          s0-s5, ra
5199
5200          and any permutations of these.  */
5201       if ((reglist & 0x3f00ffff) != 0)
5202         return FALSE;
5203
5204       ra = (reglist >> 27) & 0x10;
5205       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5206     }
5207   sregs += 1;
5208   if ((sregs & -sregs) != sregs)
5209     return FALSE;
5210
5211   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5212   return TRUE;
5213 }
5214
5215 /* OP_ENTRY_EXIT_LIST matcher.  */
5216
5217 static unsigned int
5218 match_entry_exit_operand (struct mips_arg_info *arg,
5219                           const struct mips_operand *operand)
5220 {
5221   unsigned int mask;
5222   bfd_boolean is_exit;
5223
5224   /* The format is the same for both ENTRY and EXIT, but the constraints
5225      are different.  */
5226   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5227   mask = (is_exit ? 7 << 3 : 0);
5228   do
5229     {
5230       unsigned int regno1, regno2;
5231       bfd_boolean is_freg;
5232
5233       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5234         is_freg = FALSE;
5235       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5236         is_freg = TRUE;
5237       else
5238         return FALSE;
5239
5240       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5241         {
5242           mask &= ~(7 << 3);
5243           mask |= (5 + regno2) << 3;
5244         }
5245       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5246         mask |= (regno2 - 3) << 3;
5247       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5248         mask |= (regno2 - 15) << 1;
5249       else if (regno1 == RA && regno2 == RA)
5250         mask |= 1;
5251       else
5252         return FALSE;
5253     }
5254   while (match_char (arg, ','));
5255
5256   insn_insert_operand (arg->insn, operand, mask);
5257   return TRUE;
5258 }
5259
5260 /* OP_SAVE_RESTORE_LIST matcher.  */
5261
5262 static bfd_boolean
5263 match_save_restore_list_operand (struct mips_arg_info *arg)
5264 {
5265   unsigned int opcode, args, statics, sregs;
5266   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5267   offsetT frame_size;
5268
5269   opcode = arg->insn->insn_opcode;
5270   frame_size = 0;
5271   num_frame_sizes = 0;
5272   args = 0;
5273   statics = 0;
5274   sregs = 0;
5275   do
5276     {
5277       unsigned int regno1, regno2;
5278
5279       if (arg->token->type == OT_INTEGER)
5280         {
5281           /* Handle the frame size.  */
5282           if (!match_const_int (arg, &frame_size))
5283             return FALSE;
5284           num_frame_sizes += 1;
5285         }
5286       else
5287         {
5288           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5289             return FALSE;
5290
5291           while (regno1 <= regno2)
5292             {
5293               if (regno1 >= 4 && regno1 <= 7)
5294                 {
5295                   if (num_frame_sizes == 0)
5296                     /* args $a0-$a3 */
5297                     args |= 1 << (regno1 - 4);
5298                   else
5299                     /* statics $a0-$a3 */
5300                     statics |= 1 << (regno1 - 4);
5301                 }
5302               else if (regno1 >= 16 && regno1 <= 23)
5303                 /* $s0-$s7 */
5304                 sregs |= 1 << (regno1 - 16);
5305               else if (regno1 == 30)
5306                 /* $s8 */
5307                 sregs |= 1 << 8;
5308               else if (regno1 == 31)
5309                 /* Add $ra to insn.  */
5310                 opcode |= 0x40;
5311               else
5312                 return FALSE;
5313               regno1 += 1;
5314               if (regno1 == 24)
5315                 regno1 = 30;
5316             }
5317         }
5318     }
5319   while (match_char (arg, ','));
5320
5321   /* Encode args/statics combination.  */
5322   if (args & statics)
5323     return FALSE;
5324   else if (args == 0xf)
5325     /* All $a0-$a3 are args.  */
5326     opcode |= MIPS16_ALL_ARGS << 16;
5327   else if (statics == 0xf)
5328     /* All $a0-$a3 are statics.  */
5329     opcode |= MIPS16_ALL_STATICS << 16;
5330   else
5331     {
5332       /* Count arg registers.  */
5333       num_args = 0;
5334       while (args & 0x1)
5335         {
5336           args >>= 1;
5337           num_args += 1;
5338         }
5339       if (args != 0)
5340         return FALSE;
5341
5342       /* Count static registers.  */
5343       num_statics = 0;
5344       while (statics & 0x8)
5345         {
5346           statics = (statics << 1) & 0xf;
5347           num_statics += 1;
5348         }
5349       if (statics != 0)
5350         return FALSE;
5351
5352       /* Encode args/statics.  */
5353       opcode |= ((num_args << 2) | num_statics) << 16;
5354     }
5355
5356   /* Encode $s0/$s1.  */
5357   if (sregs & (1 << 0))         /* $s0 */
5358     opcode |= 0x20;
5359   if (sregs & (1 << 1))         /* $s1 */
5360     opcode |= 0x10;
5361   sregs >>= 2;
5362
5363   /* Encode $s2-$s8. */
5364   num_sregs = 0;
5365   while (sregs & 1)
5366     {
5367       sregs >>= 1;
5368       num_sregs += 1;
5369     }
5370   if (sregs != 0)
5371     return FALSE;
5372   opcode |= num_sregs << 24;
5373
5374   /* Encode frame size.  */
5375   if (num_frame_sizes == 0)
5376     {
5377       set_insn_error (arg->argnum, _("missing frame size"));
5378       return FALSE;
5379     }
5380   if (num_frame_sizes > 1)
5381     {
5382       set_insn_error (arg->argnum, _("frame size specified twice"));
5383       return FALSE;
5384     }
5385   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5386     {
5387       set_insn_error (arg->argnum, _("invalid frame size"));
5388       return FALSE;
5389     }
5390   if (frame_size != 128 || (opcode >> 16) != 0)
5391     {
5392       frame_size /= 8;
5393       opcode |= (((frame_size & 0xf0) << 16)
5394                  | (frame_size & 0x0f));
5395     }
5396
5397   /* Finally build the instruction.  */
5398   if ((opcode >> 16) != 0 || frame_size == 0)
5399     opcode |= MIPS16_EXTEND;
5400   arg->insn->insn_opcode = opcode;
5401   return TRUE;
5402 }
5403
5404 /* OP_MDMX_IMM_REG matcher.  */
5405
5406 static bfd_boolean
5407 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5408                             const struct mips_operand *operand)
5409 {
5410   unsigned int regno, uval;
5411   bfd_boolean is_qh;
5412   const struct mips_opcode *opcode;
5413
5414   /* The mips_opcode records whether this is an octobyte or quadhalf
5415      instruction.  Start out with that bit in place.  */
5416   opcode = arg->insn->insn_mo;
5417   uval = mips_extract_operand (operand, opcode->match);
5418   is_qh = (uval != 0);
5419
5420   if (arg->token->type == OT_REG)
5421     {
5422       if ((opcode->membership & INSN_5400)
5423           && strcmp (opcode->name, "rzu.ob") == 0)
5424         {
5425           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5426                             arg->argnum);
5427           return FALSE;
5428         }
5429
5430       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5431         return FALSE;
5432       ++arg->token;
5433
5434       /* Check whether this is a vector register or a broadcast of
5435          a single element.  */
5436       if (arg->token->type == OT_INTEGER_INDEX)
5437         {
5438           if (arg->token->u.index > (is_qh ? 3 : 7))
5439             {
5440               set_insn_error (arg->argnum, _("invalid element selector"));
5441               return FALSE;
5442             }
5443           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5444           ++arg->token;
5445         }
5446       else
5447         {
5448           /* A full vector.  */
5449           if ((opcode->membership & INSN_5400)
5450               && (strcmp (opcode->name, "sll.ob") == 0
5451                   || strcmp (opcode->name, "srl.ob") == 0))
5452             {
5453               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5454                                 arg->argnum);
5455               return FALSE;
5456             }
5457
5458           if (is_qh)
5459             uval |= MDMX_FMTSEL_VEC_QH << 5;
5460           else
5461             uval |= MDMX_FMTSEL_VEC_OB << 5;
5462         }
5463       uval |= regno;
5464     }
5465   else
5466     {
5467       offsetT sval;
5468
5469       if (!match_const_int (arg, &sval))
5470         return FALSE;
5471       if (sval < 0 || sval > 31)
5472         {
5473           match_out_of_range (arg);
5474           return FALSE;
5475         }
5476       uval |= (sval & 31);
5477       if (is_qh)
5478         uval |= MDMX_FMTSEL_IMM_QH << 5;
5479       else
5480         uval |= MDMX_FMTSEL_IMM_OB << 5;
5481     }
5482   insn_insert_operand (arg->insn, operand, uval);
5483   return TRUE;
5484 }
5485
5486 /* OP_IMM_INDEX matcher.  */
5487
5488 static bfd_boolean
5489 match_imm_index_operand (struct mips_arg_info *arg,
5490                          const struct mips_operand *operand)
5491 {
5492   unsigned int max_val;
5493
5494   if (arg->token->type != OT_INTEGER_INDEX)
5495     return FALSE;
5496
5497   max_val = (1 << operand->size) - 1;
5498   if (arg->token->u.index > max_val)
5499     {
5500       match_out_of_range (arg);
5501       return FALSE;
5502     }
5503   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5504   ++arg->token;
5505   return TRUE;
5506 }
5507
5508 /* OP_REG_INDEX matcher.  */
5509
5510 static bfd_boolean
5511 match_reg_index_operand (struct mips_arg_info *arg,
5512                          const struct mips_operand *operand)
5513 {
5514   unsigned int regno;
5515
5516   if (arg->token->type != OT_REG_INDEX)
5517     return FALSE;
5518
5519   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5520     return FALSE;
5521
5522   insn_insert_operand (arg->insn, operand, regno);
5523   ++arg->token;
5524   return TRUE;
5525 }
5526
5527 /* OP_PC matcher.  */
5528
5529 static bfd_boolean
5530 match_pc_operand (struct mips_arg_info *arg)
5531 {
5532   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5533     {
5534       ++arg->token;
5535       return TRUE;
5536     }
5537   return FALSE;
5538 }
5539
5540 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5541    register that we need to match.  */
5542
5543 static bfd_boolean
5544 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5545 {
5546   unsigned int regno;
5547
5548   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5549 }
5550
5551 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5552    the length of the value in bytes (4 for float, 8 for double) and
5553    USING_GPRS says whether the destination is a GPR rather than an FPR.
5554
5555    Return the constant in IMM and OFFSET as follows:
5556
5557    - If the constant should be loaded via memory, set IMM to O_absent and
5558      OFFSET to the memory address.
5559
5560    - Otherwise, if the constant should be loaded into two 32-bit registers,
5561      set IMM to the O_constant to load into the high register and OFFSET
5562      to the corresponding value for the low register.
5563
5564    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5565
5566    These constants only appear as the last operand in an instruction,
5567    and every instruction that accepts them in any variant accepts them
5568    in all variants.  This means we don't have to worry about backing out
5569    any changes if the instruction does not match.  We just match
5570    unconditionally and report an error if the constant is invalid.  */
5571
5572 static bfd_boolean
5573 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5574                       expressionS *offset, int length, bfd_boolean using_gprs)
5575 {
5576   char *p;
5577   segT seg, new_seg;
5578   subsegT subseg;
5579   const char *newname;
5580   unsigned char *data;
5581
5582   /* Where the constant is placed is based on how the MIPS assembler
5583      does things:
5584
5585      length == 4 && using_gprs  -- immediate value only
5586      length == 8 && using_gprs  -- .rdata or immediate value
5587      length == 4 && !using_gprs -- .lit4 or immediate value
5588      length == 8 && !using_gprs -- .lit8 or immediate value
5589
5590      The .lit4 and .lit8 sections are only used if permitted by the
5591      -G argument.  */
5592   if (arg->token->type != OT_FLOAT)
5593     {
5594       set_insn_error (arg->argnum, _("floating-point expression required"));
5595       return FALSE;
5596     }
5597
5598   gas_assert (arg->token->u.flt.length == length);
5599   data = arg->token->u.flt.data;
5600   ++arg->token;
5601
5602   /* Handle 32-bit constants for which an immediate value is best.  */
5603   if (length == 4
5604       && (using_gprs
5605           || g_switch_value < 4
5606           || (data[0] == 0 && data[1] == 0)
5607           || (data[2] == 0 && data[3] == 0)))
5608     {
5609       imm->X_op = O_constant;
5610       if (!target_big_endian)
5611         imm->X_add_number = bfd_getl32 (data);
5612       else
5613         imm->X_add_number = bfd_getb32 (data);
5614       offset->X_op = O_absent;
5615       return TRUE;
5616     }
5617
5618   /* Handle 64-bit constants for which an immediate value is best.  */
5619   if (length == 8
5620       && !mips_disable_float_construction
5621       /* Constants can only be constructed in GPRs and copied to FPRs if the
5622          GPRs are at least as wide as the FPRs or MTHC1 is available.
5623          Unlike most tests for 32-bit floating-point registers this check
5624          specifically looks for GPR_SIZE == 32 as the FPXX ABI does not
5625          permit 64-bit moves without MXHC1.
5626          Force the constant into memory otherwise.  */
5627       && (using_gprs
5628           || GPR_SIZE == 64
5629           || ISA_HAS_MXHC1 (mips_opts.isa)
5630           || FPR_SIZE == 32)
5631       && ((data[0] == 0 && data[1] == 0)
5632           || (data[2] == 0 && data[3] == 0))
5633       && ((data[4] == 0 && data[5] == 0)
5634           || (data[6] == 0 && data[7] == 0)))
5635     {
5636       /* The value is simple enough to load with a couple of instructions.
5637          If using 32-bit registers, set IMM to the high order 32 bits and
5638          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5639          64 bit constant.  */
5640       if (GPR_SIZE == 32 || (!using_gprs && FPR_SIZE != 64))
5641         {
5642           imm->X_op = O_constant;
5643           offset->X_op = O_constant;
5644           if (!target_big_endian)
5645             {
5646               imm->X_add_number = bfd_getl32 (data + 4);
5647               offset->X_add_number = bfd_getl32 (data);
5648             }
5649           else
5650             {
5651               imm->X_add_number = bfd_getb32 (data);
5652               offset->X_add_number = bfd_getb32 (data + 4);
5653             }
5654           if (offset->X_add_number == 0)
5655             offset->X_op = O_absent;
5656         }
5657       else
5658         {
5659           imm->X_op = O_constant;
5660           if (!target_big_endian)
5661             imm->X_add_number = bfd_getl64 (data);
5662           else
5663             imm->X_add_number = bfd_getb64 (data);
5664           offset->X_op = O_absent;
5665         }
5666       return TRUE;
5667     }
5668
5669   /* Switch to the right section.  */
5670   seg = now_seg;
5671   subseg = now_subseg;
5672   if (length == 4)
5673     {
5674       gas_assert (!using_gprs && g_switch_value >= 4);
5675       newname = ".lit4";
5676     }
5677   else
5678     {
5679       if (using_gprs || g_switch_value < 8)
5680         newname = RDATA_SECTION_NAME;
5681       else
5682         newname = ".lit8";
5683     }
5684
5685   new_seg = subseg_new (newname, (subsegT) 0);
5686   bfd_set_section_flags (stdoutput, new_seg,
5687                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5688   frag_align (length == 4 ? 2 : 3, 0, 0);
5689   if (strncmp (TARGET_OS, "elf", 3) != 0)
5690     record_alignment (new_seg, 4);
5691   else
5692     record_alignment (new_seg, length == 4 ? 2 : 3);
5693   if (seg == now_seg)
5694     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5695
5696   /* Set the argument to the current address in the section.  */
5697   imm->X_op = O_absent;
5698   offset->X_op = O_symbol;
5699   offset->X_add_symbol = symbol_temp_new_now ();
5700   offset->X_add_number = 0;
5701
5702   /* Put the floating point number into the section.  */
5703   p = frag_more (length);
5704   memcpy (p, data, length);
5705
5706   /* Switch back to the original section.  */
5707   subseg_set (seg, subseg);
5708   return TRUE;
5709 }
5710
5711 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5712    them.  */
5713
5714 static bfd_boolean
5715 match_vu0_suffix_operand (struct mips_arg_info *arg,
5716                           const struct mips_operand *operand,
5717                           bfd_boolean match_p)
5718 {
5719   unsigned int uval;
5720
5721   /* The operand can be an XYZW mask or a single 2-bit channel index
5722      (with X being 0).  */
5723   gas_assert (operand->size == 2 || operand->size == 4);
5724
5725   /* The suffix can be omitted when it is already part of the opcode.  */
5726   if (arg->token->type != OT_CHANNELS)
5727     return match_p;
5728
5729   uval = arg->token->u.channels;
5730   if (operand->size == 2)
5731     {
5732       /* Check that a single bit is set and convert it into a 2-bit index.  */
5733       if ((uval & -uval) != uval)
5734         return FALSE;
5735       uval = 4 - ffs (uval);
5736     }
5737
5738   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5739     return FALSE;
5740
5741   ++arg->token;
5742   if (!match_p)
5743     insn_insert_operand (arg->insn, operand, uval);
5744   return TRUE;
5745 }
5746
5747 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5748    of the argument text if the match is successful, otherwise return null.  */
5749
5750 static bfd_boolean
5751 match_operand (struct mips_arg_info *arg,
5752                const struct mips_operand *operand)
5753 {
5754   switch (operand->type)
5755     {
5756     case OP_INT:
5757       return match_int_operand (arg, operand);
5758
5759     case OP_MAPPED_INT:
5760       return match_mapped_int_operand (arg, operand);
5761
5762     case OP_MSB:
5763       return match_msb_operand (arg, operand);
5764
5765     case OP_REG:
5766     case OP_OPTIONAL_REG:
5767       return match_reg_operand (arg, operand);
5768
5769     case OP_REG_PAIR:
5770       return match_reg_pair_operand (arg, operand);
5771
5772     case OP_PCREL:
5773       return match_pcrel_operand (arg);
5774
5775     case OP_PERF_REG:
5776       return match_perf_reg_operand (arg, operand);
5777
5778     case OP_ADDIUSP_INT:
5779       return match_addiusp_operand (arg, operand);
5780
5781     case OP_CLO_CLZ_DEST:
5782       return match_clo_clz_dest_operand (arg, operand);
5783
5784     case OP_LWM_SWM_LIST:
5785       return match_lwm_swm_list_operand (arg, operand);
5786
5787     case OP_ENTRY_EXIT_LIST:
5788       return match_entry_exit_operand (arg, operand);
5789
5790     case OP_SAVE_RESTORE_LIST:
5791       return match_save_restore_list_operand (arg);
5792
5793     case OP_MDMX_IMM_REG:
5794       return match_mdmx_imm_reg_operand (arg, operand);
5795
5796     case OP_REPEAT_DEST_REG:
5797       return match_tied_reg_operand (arg, arg->dest_regno);
5798
5799     case OP_REPEAT_PREV_REG:
5800       return match_tied_reg_operand (arg, arg->last_regno);
5801
5802     case OP_PC:
5803       return match_pc_operand (arg);
5804
5805     case OP_VU0_SUFFIX:
5806       return match_vu0_suffix_operand (arg, operand, FALSE);
5807
5808     case OP_VU0_MATCH_SUFFIX:
5809       return match_vu0_suffix_operand (arg, operand, TRUE);
5810
5811     case OP_IMM_INDEX:
5812       return match_imm_index_operand (arg, operand);
5813
5814     case OP_REG_INDEX:
5815       return match_reg_index_operand (arg, operand);
5816     }
5817   abort ();
5818 }
5819
5820 /* ARG is the state after successfully matching an instruction.
5821    Issue any queued-up warnings.  */
5822
5823 static void
5824 check_completed_insn (struct mips_arg_info *arg)
5825 {
5826   if (arg->seen_at)
5827     {
5828       if (AT == ATREG)
5829         as_warn (_("used $at without \".set noat\""));
5830       else
5831         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
5832     }
5833 }
5834
5835 /* Return true if modifying general-purpose register REG needs a delay.  */
5836
5837 static bfd_boolean
5838 reg_needs_delay (unsigned int reg)
5839 {
5840   unsigned long prev_pinfo;
5841
5842   prev_pinfo = history[0].insn_mo->pinfo;
5843   if (!mips_opts.noreorder
5844       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
5845           || ((prev_pinfo & INSN_LOAD_COPROC) && !cop_interlocks))
5846       && (gpr_write_mask (&history[0]) & (1 << reg)))
5847     return TRUE;
5848
5849   return FALSE;
5850 }
5851
5852 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5853    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5854    by VR4120 errata.  */
5855
5856 static unsigned int
5857 classify_vr4120_insn (const char *name)
5858 {
5859   if (strncmp (name, "macc", 4) == 0)
5860     return FIX_VR4120_MACC;
5861   if (strncmp (name, "dmacc", 5) == 0)
5862     return FIX_VR4120_DMACC;
5863   if (strncmp (name, "mult", 4) == 0)
5864     return FIX_VR4120_MULT;
5865   if (strncmp (name, "dmult", 5) == 0)
5866     return FIX_VR4120_DMULT;
5867   if (strstr (name, "div"))
5868     return FIX_VR4120_DIV;
5869   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5870     return FIX_VR4120_MTHILO;
5871   return NUM_FIX_VR4120_CLASSES;
5872 }
5873
5874 #define INSN_ERET       0x42000018
5875 #define INSN_DERET      0x4200001f
5876 #define INSN_DMULT      0x1c
5877 #define INSN_DMULTU     0x1d
5878
5879 /* Return the number of instructions that must separate INSN1 and INSN2,
5880    where INSN1 is the earlier instruction.  Return the worst-case value
5881    for any INSN2 if INSN2 is null.  */
5882
5883 static unsigned int
5884 insns_between (const struct mips_cl_insn *insn1,
5885                const struct mips_cl_insn *insn2)
5886 {
5887   unsigned long pinfo1, pinfo2;
5888   unsigned int mask;
5889
5890   /* If INFO2 is null, pessimistically assume that all flags are set for
5891      the second instruction.  */
5892   pinfo1 = insn1->insn_mo->pinfo;
5893   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5894
5895   /* For most targets, write-after-read dependencies on the HI and LO
5896      registers must be separated by at least two instructions.  */
5897   if (!hilo_interlocks)
5898     {
5899       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5900         return 2;
5901       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5902         return 2;
5903     }
5904
5905   /* If we're working around r7000 errata, there must be two instructions
5906      between an mfhi or mflo and any instruction that uses the result.  */
5907   if (mips_7000_hilo_fix
5908       && !mips_opts.micromips
5909       && MF_HILO_INSN (pinfo1)
5910       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5911     return 2;
5912
5913   /* If we're working around 24K errata, one instruction is required
5914      if an ERET or DERET is followed by a branch instruction.  */
5915   if (mips_fix_24k && !mips_opts.micromips)
5916     {
5917       if (insn1->insn_opcode == INSN_ERET
5918           || insn1->insn_opcode == INSN_DERET)
5919         {
5920           if (insn2 == NULL
5921               || insn2->insn_opcode == INSN_ERET
5922               || insn2->insn_opcode == INSN_DERET
5923               || delayed_branch_p (insn2))
5924             return 1;
5925         }
5926     }
5927
5928   /* If we're working around PMC RM7000 errata, there must be three
5929      nops between a dmult and a load instruction.  */
5930   if (mips_fix_rm7000 && !mips_opts.micromips)
5931     {
5932       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
5933           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
5934         {
5935           if (pinfo2 & INSN_LOAD_MEMORY)
5936            return 3;
5937         }
5938     }
5939
5940   /* If working around VR4120 errata, check for combinations that need
5941      a single intervening instruction.  */
5942   if (mips_fix_vr4120 && !mips_opts.micromips)
5943     {
5944       unsigned int class1, class2;
5945
5946       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5947       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5948         {
5949           if (insn2 == NULL)
5950             return 1;
5951           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5952           if (vr4120_conflicts[class1] & (1 << class2))
5953             return 1;
5954         }
5955     }
5956
5957   if (!HAVE_CODE_COMPRESSION)
5958     {
5959       /* Check for GPR or coprocessor load delays.  All such delays
5960          are on the RT register.  */
5961       /* Itbl support may require additional care here.  */
5962       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
5963           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC)))
5964         {
5965           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5966             return 1;
5967         }
5968
5969       /* Check for generic coprocessor hazards.
5970
5971          This case is not handled very well.  There is no special
5972          knowledge of CP0 handling, and the coprocessors other than
5973          the floating point unit are not distinguished at all.  */
5974       /* Itbl support may require additional care here. FIXME!
5975          Need to modify this to include knowledge about
5976          user specified delays!  */
5977       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE))
5978                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5979         {
5980           /* Handle cases where INSN1 writes to a known general coprocessor
5981              register.  There must be a one instruction delay before INSN2
5982              if INSN2 reads that register, otherwise no delay is needed.  */
5983           mask = fpr_write_mask (insn1);
5984           if (mask != 0)
5985             {
5986               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5987                 return 1;
5988             }
5989           else
5990             {
5991               /* Read-after-write dependencies on the control registers
5992                  require a two-instruction gap.  */
5993               if ((pinfo1 & INSN_WRITE_COND_CODE)
5994                   && (pinfo2 & INSN_READ_COND_CODE))
5995                 return 2;
5996
5997               /* We don't know exactly what INSN1 does.  If INSN2 is
5998                  also a coprocessor instruction, assume there must be
5999                  a one instruction gap.  */
6000               if (pinfo2 & INSN_COP)
6001                 return 1;
6002             }
6003         }
6004
6005       /* Check for read-after-write dependencies on the coprocessor
6006          control registers in cases where INSN1 does not need a general
6007          coprocessor delay.  This means that INSN1 is a floating point
6008          comparison instruction.  */
6009       /* Itbl support may require additional care here.  */
6010       else if (!cop_interlocks
6011                && (pinfo1 & INSN_WRITE_COND_CODE)
6012                && (pinfo2 & INSN_READ_COND_CODE))
6013         return 1;
6014     }
6015
6016   return 0;
6017 }
6018
6019 /* Return the number of nops that would be needed to work around the
6020    VR4130 mflo/mfhi errata if instruction INSN immediately followed
6021    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
6022    that are contained within the first IGNORE instructions of HIST.  */
6023
6024 static int
6025 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
6026                  const struct mips_cl_insn *insn)
6027 {
6028   int i, j;
6029   unsigned int mask;
6030
6031   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
6032      are not affected by the errata.  */
6033   if (insn != 0
6034       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
6035           || strcmp (insn->insn_mo->name, "mtlo") == 0
6036           || strcmp (insn->insn_mo->name, "mthi") == 0))
6037     return 0;
6038
6039   /* Search for the first MFLO or MFHI.  */
6040   for (i = 0; i < MAX_VR4130_NOPS; i++)
6041     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
6042       {
6043         /* Extract the destination register.  */
6044         mask = gpr_write_mask (&hist[i]);
6045
6046         /* No nops are needed if INSN reads that register.  */
6047         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
6048           return 0;
6049
6050         /* ...or if any of the intervening instructions do.  */
6051         for (j = 0; j < i; j++)
6052           if (gpr_read_mask (&hist[j]) & mask)
6053             return 0;
6054
6055         if (i >= ignore)
6056           return MAX_VR4130_NOPS - i;
6057       }
6058   return 0;
6059 }
6060
6061 #define BASE_REG_EQ(INSN1, INSN2)       \
6062   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
6063       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
6064
6065 /* Return the minimum alignment for this store instruction.  */
6066
6067 static int
6068 fix_24k_align_to (const struct mips_opcode *mo)
6069 {
6070   if (strcmp (mo->name, "sh") == 0)
6071     return 2;
6072
6073   if (strcmp (mo->name, "swc1") == 0
6074       || strcmp (mo->name, "swc2") == 0
6075       || strcmp (mo->name, "sw") == 0
6076       || strcmp (mo->name, "sc") == 0
6077       || strcmp (mo->name, "s.s") == 0)
6078     return 4;
6079
6080   if (strcmp (mo->name, "sdc1") == 0
6081       || strcmp (mo->name, "sdc2") == 0
6082       || strcmp (mo->name, "s.d") == 0)
6083     return 8;
6084
6085   /* sb, swl, swr */
6086   return 1;
6087 }
6088
6089 struct fix_24k_store_info
6090   {
6091     /* Immediate offset, if any, for this store instruction.  */
6092     short off;
6093     /* Alignment required by this store instruction.  */
6094     int align_to;
6095     /* True for register offsets.  */
6096     int register_offset;
6097   };
6098
6099 /* Comparison function used by qsort.  */
6100
6101 static int
6102 fix_24k_sort (const void *a, const void *b)
6103 {
6104   const struct fix_24k_store_info *pos1 = a;
6105   const struct fix_24k_store_info *pos2 = b;
6106
6107   return (pos1->off - pos2->off);
6108 }
6109
6110 /* INSN is a store instruction.  Try to record the store information
6111    in STINFO.  Return false if the information isn't known.  */
6112
6113 static bfd_boolean
6114 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
6115                            const struct mips_cl_insn *insn)
6116 {
6117   /* The instruction must have a known offset.  */
6118   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
6119     return FALSE;
6120
6121   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
6122   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
6123   return TRUE;
6124 }
6125
6126 /* Return the number of nops that would be needed to work around the 24k
6127    "lost data on stores during refill" errata if instruction INSN
6128    immediately followed the 2 instructions described by HIST.
6129    Ignore hazards that are contained within the first IGNORE
6130    instructions of HIST.
6131
6132    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6133    for the data cache refills and store data. The following describes
6134    the scenario where the store data could be lost.
6135
6136    * A data cache miss, due to either a load or a store, causing fill
6137      data to be supplied by the memory subsystem
6138    * The first three doublewords of fill data are returned and written
6139      into the cache
6140    * A sequence of four stores occurs in consecutive cycles around the
6141      final doubleword of the fill:
6142    * Store A
6143    * Store B
6144    * Store C
6145    * Zero, One or more instructions
6146    * Store D
6147
6148    The four stores A-D must be to different doublewords of the line that
6149    is being filled. The fourth instruction in the sequence above permits
6150    the fill of the final doubleword to be transferred from the FSB into
6151    the cache. In the sequence above, the stores may be either integer
6152    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6153    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6154    different doublewords on the line. If the floating point unit is
6155    running in 1:2 mode, it is not possible to create the sequence above
6156    using only floating point store instructions.
6157
6158    In this case, the cache line being filled is incorrectly marked
6159    invalid, thereby losing the data from any store to the line that
6160    occurs between the original miss and the completion of the five
6161    cycle sequence shown above.
6162
6163    The workarounds are:
6164
6165    * Run the data cache in write-through mode.
6166    * Insert a non-store instruction between
6167      Store A and Store B or Store B and Store C.  */
6168   
6169 static int
6170 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6171               const struct mips_cl_insn *insn)
6172 {
6173   struct fix_24k_store_info pos[3];
6174   int align, i, base_offset;
6175
6176   if (ignore >= 2)
6177     return 0;
6178
6179   /* If the previous instruction wasn't a store, there's nothing to
6180      worry about.  */
6181   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6182     return 0;
6183
6184   /* If the instructions after the previous one are unknown, we have
6185      to assume the worst.  */
6186   if (!insn)
6187     return 1;
6188
6189   /* Check whether we are dealing with three consecutive stores.  */
6190   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6191       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6192     return 0;
6193
6194   /* If we don't know the relationship between the store addresses,
6195      assume the worst.  */
6196   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6197       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6198     return 1;
6199
6200   if (!fix_24k_record_store_info (&pos[0], insn)
6201       || !fix_24k_record_store_info (&pos[1], &hist[0])
6202       || !fix_24k_record_store_info (&pos[2], &hist[1]))
6203     return 1;
6204
6205   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6206
6207   /* Pick a value of ALIGN and X such that all offsets are adjusted by
6208      X bytes and such that the base register + X is known to be aligned
6209      to align bytes.  */
6210
6211   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6212     align = 8;
6213   else
6214     {
6215       align = pos[0].align_to;
6216       base_offset = pos[0].off;
6217       for (i = 1; i < 3; i++)
6218         if (align < pos[i].align_to)
6219           {
6220             align = pos[i].align_to;
6221             base_offset = pos[i].off;
6222           }
6223       for (i = 0; i < 3; i++)
6224         pos[i].off -= base_offset;
6225     }
6226
6227   pos[0].off &= ~align + 1;
6228   pos[1].off &= ~align + 1;
6229   pos[2].off &= ~align + 1;
6230
6231   /* If any two stores write to the same chunk, they also write to the
6232      same doubleword.  The offsets are still sorted at this point.  */
6233   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6234     return 0;
6235
6236   /* A range of at least 9 bytes is needed for the stores to be in
6237      non-overlapping doublewords.  */
6238   if (pos[2].off - pos[0].off <= 8)
6239     return 0;
6240
6241   if (pos[2].off - pos[1].off >= 24
6242       || pos[1].off - pos[0].off >= 24
6243       || pos[2].off - pos[0].off >= 32)
6244     return 0;
6245
6246   return 1;
6247 }
6248
6249 /* Return the number of nops that would be needed if instruction INSN
6250    immediately followed the MAX_NOPS instructions given by HIST,
6251    where HIST[0] is the most recent instruction.  Ignore hazards
6252    between INSN and the first IGNORE instructions in HIST.
6253
6254    If INSN is null, return the worse-case number of nops for any
6255    instruction.  */
6256
6257 static int
6258 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6259                const struct mips_cl_insn *insn)
6260 {
6261   int i, nops, tmp_nops;
6262
6263   nops = 0;
6264   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6265     {
6266       tmp_nops = insns_between (hist + i, insn) - i;
6267       if (tmp_nops > nops)
6268         nops = tmp_nops;
6269     }
6270
6271   if (mips_fix_vr4130 && !mips_opts.micromips)
6272     {
6273       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6274       if (tmp_nops > nops)
6275         nops = tmp_nops;
6276     }
6277
6278   if (mips_fix_24k && !mips_opts.micromips)
6279     {
6280       tmp_nops = nops_for_24k (ignore, hist, insn);
6281       if (tmp_nops > nops)
6282         nops = tmp_nops;
6283     }
6284
6285   return nops;
6286 }
6287
6288 /* The variable arguments provide NUM_INSNS extra instructions that
6289    might be added to HIST.  Return the largest number of nops that
6290    would be needed after the extended sequence, ignoring hazards
6291    in the first IGNORE instructions.  */
6292
6293 static int
6294 nops_for_sequence (int num_insns, int ignore,
6295                    const struct mips_cl_insn *hist, ...)
6296 {
6297   va_list args;
6298   struct mips_cl_insn buffer[MAX_NOPS];
6299   struct mips_cl_insn *cursor;
6300   int nops;
6301
6302   va_start (args, hist);
6303   cursor = buffer + num_insns;
6304   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6305   while (cursor > buffer)
6306     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6307
6308   nops = nops_for_insn (ignore, buffer, NULL);
6309   va_end (args);
6310   return nops;
6311 }
6312
6313 /* Like nops_for_insn, but if INSN is a branch, take into account the
6314    worst-case delay for the branch target.  */
6315
6316 static int
6317 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6318                          const struct mips_cl_insn *insn)
6319 {
6320   int nops, tmp_nops;
6321
6322   nops = nops_for_insn (ignore, hist, insn);
6323   if (delayed_branch_p (insn))
6324     {
6325       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6326                                     hist, insn, get_delay_slot_nop (insn));
6327       if (tmp_nops > nops)
6328         nops = tmp_nops;
6329     }
6330   else if (compact_branch_p (insn))
6331     {
6332       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6333       if (tmp_nops > nops)
6334         nops = tmp_nops;
6335     }
6336   return nops;
6337 }
6338
6339 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6340
6341 static void
6342 fix_loongson2f_nop (struct mips_cl_insn * ip)
6343 {
6344   gas_assert (!HAVE_CODE_COMPRESSION);
6345   if (strcmp (ip->insn_mo->name, "nop") == 0)
6346     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6347 }
6348
6349 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6350                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6351
6352 static void
6353 fix_loongson2f_jump (struct mips_cl_insn * ip)
6354 {
6355   gas_assert (!HAVE_CODE_COMPRESSION);
6356   if (strcmp (ip->insn_mo->name, "j") == 0
6357       || strcmp (ip->insn_mo->name, "jr") == 0
6358       || strcmp (ip->insn_mo->name, "jalr") == 0)
6359     {
6360       int sreg;
6361       expressionS ep;
6362
6363       if (! mips_opts.at)
6364         return;
6365
6366       sreg = EXTRACT_OPERAND (0, RS, *ip);
6367       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6368         return;
6369
6370       ep.X_op = O_constant;
6371       ep.X_add_number = 0xcfff0000;
6372       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6373       ep.X_add_number = 0xffff;
6374       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6375       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6376     }
6377 }
6378
6379 static void
6380 fix_loongson2f (struct mips_cl_insn * ip)
6381 {
6382   if (mips_fix_loongson2f_nop)
6383     fix_loongson2f_nop (ip);
6384
6385   if (mips_fix_loongson2f_jump)
6386     fix_loongson2f_jump (ip);
6387 }
6388
6389 /* IP is a branch that has a delay slot, and we need to fill it
6390    automatically.   Return true if we can do that by swapping IP
6391    with the previous instruction.
6392    ADDRESS_EXPR is an operand of the instruction to be used with
6393    RELOC_TYPE.  */
6394
6395 static bfd_boolean
6396 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6397                    bfd_reloc_code_real_type *reloc_type)
6398 {
6399   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6400   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6401   unsigned int fpr_read, prev_fpr_write;
6402
6403   /* -O2 and above is required for this optimization.  */
6404   if (mips_optimize < 2)
6405     return FALSE;
6406
6407   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6408   if (mips_opts.nomove)
6409     return FALSE;
6410
6411   /* We can't swap if the previous instruction's position is fixed.  */
6412   if (history[0].fixed_p)
6413     return FALSE;
6414
6415   /* If the previous previous insn was in a .set noreorder, we can't
6416      swap.  Actually, the MIPS assembler will swap in this situation.
6417      However, gcc configured -with-gnu-as will generate code like
6418
6419         .set    noreorder
6420         lw      $4,XXX
6421         .set    reorder
6422         INSN
6423         bne     $4,$0,foo
6424
6425      in which we can not swap the bne and INSN.  If gcc is not configured
6426      -with-gnu-as, it does not output the .set pseudo-ops.  */
6427   if (history[1].noreorder_p)
6428     return FALSE;
6429
6430   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6431      This means that the previous instruction was a 4-byte one anyhow.  */
6432   if (mips_opts.mips16 && history[0].fixp[0])
6433     return FALSE;
6434
6435   /* If the branch is itself the target of a branch, we can not swap.
6436      We cheat on this; all we check for is whether there is a label on
6437      this instruction.  If there are any branches to anything other than
6438      a label, users must use .set noreorder.  */
6439   if (seg_info (now_seg)->label_list)
6440     return FALSE;
6441
6442   /* If the previous instruction is in a variant frag other than this
6443      branch's one, we cannot do the swap.  This does not apply to
6444      MIPS16 code, which uses variant frags for different purposes.  */
6445   if (!mips_opts.mips16
6446       && history[0].frag
6447       && history[0].frag->fr_type == rs_machine_dependent)
6448     return FALSE;
6449
6450   /* We do not swap with instructions that cannot architecturally
6451      be placed in a branch delay slot, such as SYNC or ERET.  We
6452      also refrain from swapping with a trap instruction, since it
6453      complicates trap handlers to have the trap instruction be in
6454      a delay slot.  */
6455   prev_pinfo = history[0].insn_mo->pinfo;
6456   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6457     return FALSE;
6458
6459   /* Check for conflicts between the branch and the instructions
6460      before the candidate delay slot.  */
6461   if (nops_for_insn (0, history + 1, ip) > 0)
6462     return FALSE;
6463
6464   /* Check for conflicts between the swapped sequence and the
6465      target of the branch.  */
6466   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6467     return FALSE;
6468
6469   /* If the branch reads a register that the previous
6470      instruction sets, we can not swap.  */
6471   gpr_read = gpr_read_mask (ip);
6472   prev_gpr_write = gpr_write_mask (&history[0]);
6473   if (gpr_read & prev_gpr_write)
6474     return FALSE;
6475
6476   fpr_read = fpr_read_mask (ip);
6477   prev_fpr_write = fpr_write_mask (&history[0]);
6478   if (fpr_read & prev_fpr_write)
6479     return FALSE;
6480
6481   /* If the branch writes a register that the previous
6482      instruction sets, we can not swap.  */
6483   gpr_write = gpr_write_mask (ip);
6484   if (gpr_write & prev_gpr_write)
6485     return FALSE;
6486
6487   /* If the branch writes a register that the previous
6488      instruction reads, we can not swap.  */
6489   prev_gpr_read = gpr_read_mask (&history[0]);
6490   if (gpr_write & prev_gpr_read)
6491     return FALSE;
6492
6493   /* If one instruction sets a condition code and the
6494      other one uses a condition code, we can not swap.  */
6495   pinfo = ip->insn_mo->pinfo;
6496   if ((pinfo & INSN_READ_COND_CODE)
6497       && (prev_pinfo & INSN_WRITE_COND_CODE))
6498     return FALSE;
6499   if ((pinfo & INSN_WRITE_COND_CODE)
6500       && (prev_pinfo & INSN_READ_COND_CODE))
6501     return FALSE;
6502
6503   /* If the previous instruction uses the PC, we can not swap.  */
6504   prev_pinfo2 = history[0].insn_mo->pinfo2;
6505   if (prev_pinfo2 & INSN2_READ_PC)
6506     return FALSE;
6507
6508   /* If the previous instruction has an incorrect size for a fixed
6509      branch delay slot in microMIPS mode, we cannot swap.  */
6510   pinfo2 = ip->insn_mo->pinfo2;
6511   if (mips_opts.micromips
6512       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6513       && insn_length (history) != 2)
6514     return FALSE;
6515   if (mips_opts.micromips
6516       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6517       && insn_length (history) != 4)
6518     return FALSE;
6519
6520   /* On R5900 short loops need to be fixed by inserting a nop in
6521      the branch delay slots.
6522      A short loop can be terminated too early.  */
6523   if (mips_opts.arch == CPU_R5900
6524       /* Check if instruction has a parameter, ignore "j $31". */
6525       && (address_expr != NULL)
6526       /* Parameter must be 16 bit. */
6527       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6528       /* Branch to same segment. */
6529       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6530       /* Branch to same code fragment. */
6531       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6532       /* Can only calculate branch offset if value is known. */
6533       && symbol_constant_p(address_expr->X_add_symbol)
6534       /* Check if branch is really conditional. */
6535       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6536         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6537         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6538     {
6539       int distance;
6540       /* Check if loop is shorter than 6 instructions including
6541          branch and delay slot.  */
6542       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6543       if (distance <= 20)
6544         {
6545           int i;
6546           int rv;
6547
6548           rv = FALSE;
6549           /* When the loop includes branches or jumps,
6550              it is not a short loop. */
6551           for (i = 0; i < (distance / 4); i++)
6552             {
6553               if ((history[i].cleared_p)
6554                   || delayed_branch_p(&history[i]))
6555                 {
6556                   rv = TRUE;
6557                   break;
6558                 }
6559             }
6560           if (rv == FALSE)
6561             {
6562               /* Insert nop after branch to fix short loop. */
6563               return FALSE;
6564             }
6565         }
6566     }
6567
6568   return TRUE;
6569 }
6570
6571 /* Decide how we should add IP to the instruction stream.
6572    ADDRESS_EXPR is an operand of the instruction to be used with
6573    RELOC_TYPE.  */
6574
6575 static enum append_method
6576 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6577                    bfd_reloc_code_real_type *reloc_type)
6578 {
6579   /* The relaxed version of a macro sequence must be inherently
6580      hazard-free.  */
6581   if (mips_relax.sequence == 2)
6582     return APPEND_ADD;
6583
6584   /* We must not dabble with instructions in a ".set norerorder" block.  */
6585   if (mips_opts.noreorder)
6586     return APPEND_ADD;
6587
6588   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6589   if (delayed_branch_p (ip))
6590     {
6591       if (!branch_likely_p (ip)
6592           && can_swap_branch_p (ip, address_expr, reloc_type))
6593         return APPEND_SWAP;
6594
6595       if (mips_opts.mips16
6596           && ISA_SUPPORTS_MIPS16E
6597           && gpr_read_mask (ip) != 0)
6598         return APPEND_ADD_COMPACT;
6599
6600       return APPEND_ADD_WITH_NOP;
6601     }
6602
6603   return APPEND_ADD;
6604 }
6605
6606 /* IP is a MIPS16 instruction whose opcode we have just changed.
6607    Point IP->insn_mo to the new opcode's definition.  */
6608
6609 static void
6610 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6611 {
6612   const struct mips_opcode *mo, *end;
6613
6614   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6615   for (mo = ip->insn_mo; mo < end; mo++)
6616     if ((ip->insn_opcode & mo->mask) == mo->match)
6617       {
6618         ip->insn_mo = mo;
6619         return;
6620       }
6621   abort ();
6622 }
6623
6624 /* For microMIPS macros, we need to generate a local number label
6625    as the target of branches.  */
6626 #define MICROMIPS_LABEL_CHAR            '\037'
6627 static unsigned long micromips_target_label;
6628 static char micromips_target_name[32];
6629
6630 static char *
6631 micromips_label_name (void)
6632 {
6633   char *p = micromips_target_name;
6634   char symbol_name_temporary[24];
6635   unsigned long l;
6636   int i;
6637
6638   if (*p)
6639     return p;
6640
6641   i = 0;
6642   l = micromips_target_label;
6643 #ifdef LOCAL_LABEL_PREFIX
6644   *p++ = LOCAL_LABEL_PREFIX;
6645 #endif
6646   *p++ = 'L';
6647   *p++ = MICROMIPS_LABEL_CHAR;
6648   do
6649     {
6650       symbol_name_temporary[i++] = l % 10 + '0';
6651       l /= 10;
6652     }
6653   while (l != 0);
6654   while (i > 0)
6655     *p++ = symbol_name_temporary[--i];
6656   *p = '\0';
6657
6658   return micromips_target_name;
6659 }
6660
6661 static void
6662 micromips_label_expr (expressionS *label_expr)
6663 {
6664   label_expr->X_op = O_symbol;
6665   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6666   label_expr->X_add_number = 0;
6667 }
6668
6669 static void
6670 micromips_label_inc (void)
6671 {
6672   micromips_target_label++;
6673   *micromips_target_name = '\0';
6674 }
6675
6676 static void
6677 micromips_add_label (void)
6678 {
6679   symbolS *s;
6680
6681   s = colon (micromips_label_name ());
6682   micromips_label_inc ();
6683   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6684 }
6685
6686 /* If assembling microMIPS code, then return the microMIPS reloc
6687    corresponding to the requested one if any.  Otherwise return
6688    the reloc unchanged.  */
6689
6690 static bfd_reloc_code_real_type
6691 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6692 {
6693   static const bfd_reloc_code_real_type relocs[][2] =
6694     {
6695       /* Keep sorted incrementally by the left-hand key.  */
6696       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6697       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6698       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6699       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6700       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6701       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6702       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6703       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6704       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6705       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6706       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6707       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6708       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6709       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6710       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6711       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6712       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6713       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6714       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6715       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6716       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6717       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6718       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6719       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6720       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6721       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6722       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6723     };
6724   bfd_reloc_code_real_type r;
6725   size_t i;
6726
6727   if (!mips_opts.micromips)
6728     return reloc;
6729   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6730     {
6731       r = relocs[i][0];
6732       if (r > reloc)
6733         return reloc;
6734       if (r == reloc)
6735         return relocs[i][1];
6736     }
6737   return reloc;
6738 }
6739
6740 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6741    Return true on success, storing the resolved value in RESULT.  */
6742
6743 static bfd_boolean
6744 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6745                  offsetT *result)
6746 {
6747   switch (reloc)
6748     {
6749     case BFD_RELOC_MIPS_HIGHEST:
6750     case BFD_RELOC_MICROMIPS_HIGHEST:
6751       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6752       return TRUE;
6753
6754     case BFD_RELOC_MIPS_HIGHER:
6755     case BFD_RELOC_MICROMIPS_HIGHER:
6756       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6757       return TRUE;
6758
6759     case BFD_RELOC_HI16_S:
6760     case BFD_RELOC_MICROMIPS_HI16_S:
6761     case BFD_RELOC_MIPS16_HI16_S:
6762       *result = ((operand + 0x8000) >> 16) & 0xffff;
6763       return TRUE;
6764
6765     case BFD_RELOC_HI16:
6766     case BFD_RELOC_MICROMIPS_HI16:
6767     case BFD_RELOC_MIPS16_HI16:
6768       *result = (operand >> 16) & 0xffff;
6769       return TRUE;
6770
6771     case BFD_RELOC_LO16:
6772     case BFD_RELOC_MICROMIPS_LO16:
6773     case BFD_RELOC_MIPS16_LO16:
6774       *result = operand & 0xffff;
6775       return TRUE;
6776
6777     case BFD_RELOC_UNUSED:
6778       *result = operand;
6779       return TRUE;
6780
6781     default:
6782       return FALSE;
6783     }
6784 }
6785
6786 /* Output an instruction.  IP is the instruction information.
6787    ADDRESS_EXPR is an operand of the instruction to be used with
6788    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6789    a macro expansion.  */
6790
6791 static void
6792 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6793              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6794 {
6795   unsigned long prev_pinfo2, pinfo;
6796   bfd_boolean relaxed_branch = FALSE;
6797   enum append_method method;
6798   bfd_boolean relax32;
6799   int branch_disp;
6800
6801   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6802     fix_loongson2f (ip);
6803
6804   file_ase_mips16 |= mips_opts.mips16;
6805   file_ase_micromips |= mips_opts.micromips;
6806
6807   prev_pinfo2 = history[0].insn_mo->pinfo2;
6808   pinfo = ip->insn_mo->pinfo;
6809
6810   if (mips_opts.micromips
6811       && !expansionp
6812       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6813            && micromips_insn_length (ip->insn_mo) != 2)
6814           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6815               && micromips_insn_length (ip->insn_mo) != 4)))
6816     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
6817              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6818
6819   if (address_expr == NULL)
6820     ip->complete_p = 1;
6821   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6822            && reloc_type[1] == BFD_RELOC_UNUSED
6823            && reloc_type[2] == BFD_RELOC_UNUSED
6824            && address_expr->X_op == O_constant)
6825     {
6826       switch (*reloc_type)
6827         {
6828         case BFD_RELOC_MIPS_JMP:
6829           {
6830             int shift;
6831
6832             shift = mips_opts.micromips ? 1 : 2;
6833             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6834               as_bad (_("jump to misaligned address (0x%lx)"),
6835                       (unsigned long) address_expr->X_add_number);
6836             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6837                                 & 0x3ffffff);
6838             ip->complete_p = 1;
6839           }
6840           break;
6841
6842         case BFD_RELOC_MIPS16_JMP:
6843           if ((address_expr->X_add_number & 3) != 0)
6844             as_bad (_("jump to misaligned address (0x%lx)"),
6845                     (unsigned long) address_expr->X_add_number);
6846           ip->insn_opcode |=
6847             (((address_expr->X_add_number & 0x7c0000) << 3)
6848                | ((address_expr->X_add_number & 0xf800000) >> 7)
6849                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6850           ip->complete_p = 1;
6851           break;
6852
6853         case BFD_RELOC_16_PCREL_S2:
6854           {
6855             int shift;
6856
6857             shift = mips_opts.micromips ? 1 : 2;
6858             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6859               as_bad (_("branch to misaligned address (0x%lx)"),
6860                       (unsigned long) address_expr->X_add_number);
6861             if (!mips_relax_branch)
6862               {
6863                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6864                     & ~((1 << (shift + 16)) - 1))
6865                   as_bad (_("branch address range overflow (0x%lx)"),
6866                           (unsigned long) address_expr->X_add_number);
6867                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6868                                     & 0xffff);
6869               }
6870           }
6871           break;
6872
6873         default:
6874           {
6875             offsetT value;
6876
6877             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6878                                  &value))
6879               {
6880                 ip->insn_opcode |= value & 0xffff;
6881                 ip->complete_p = 1;
6882               }
6883           }
6884           break;
6885         }
6886     }
6887
6888   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6889     {
6890       /* There are a lot of optimizations we could do that we don't.
6891          In particular, we do not, in general, reorder instructions.
6892          If you use gcc with optimization, it will reorder
6893          instructions and generally do much more optimization then we
6894          do here; repeating all that work in the assembler would only
6895          benefit hand written assembly code, and does not seem worth
6896          it.  */
6897       int nops = (mips_optimize == 0
6898                   ? nops_for_insn (0, history, NULL)
6899                   : nops_for_insn_or_target (0, history, ip));
6900       if (nops > 0)
6901         {
6902           fragS *old_frag;
6903           unsigned long old_frag_offset;
6904           int i;
6905
6906           old_frag = frag_now;
6907           old_frag_offset = frag_now_fix ();
6908
6909           for (i = 0; i < nops; i++)
6910             add_fixed_insn (NOP_INSN);
6911           insert_into_history (0, nops, NOP_INSN);
6912
6913           if (listing)
6914             {
6915               listing_prev_line ();
6916               /* We may be at the start of a variant frag.  In case we
6917                  are, make sure there is enough space for the frag
6918                  after the frags created by listing_prev_line.  The
6919                  argument to frag_grow here must be at least as large
6920                  as the argument to all other calls to frag_grow in
6921                  this file.  We don't have to worry about being in the
6922                  middle of a variant frag, because the variants insert
6923                  all needed nop instructions themselves.  */
6924               frag_grow (40);
6925             }
6926
6927           mips_move_text_labels ();
6928
6929 #ifndef NO_ECOFF_DEBUGGING
6930           if (ECOFF_DEBUGGING)
6931             ecoff_fix_loc (old_frag, old_frag_offset);
6932 #endif
6933         }
6934     }
6935   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6936     {
6937       int nops;
6938
6939       /* Work out how many nops in prev_nop_frag are needed by IP,
6940          ignoring hazards generated by the first prev_nop_frag_since
6941          instructions.  */
6942       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6943       gas_assert (nops <= prev_nop_frag_holds);
6944
6945       /* Enforce NOPS as a minimum.  */
6946       if (nops > prev_nop_frag_required)
6947         prev_nop_frag_required = nops;
6948
6949       if (prev_nop_frag_holds == prev_nop_frag_required)
6950         {
6951           /* Settle for the current number of nops.  Update the history
6952              accordingly (for the benefit of any future .set reorder code).  */
6953           prev_nop_frag = NULL;
6954           insert_into_history (prev_nop_frag_since,
6955                                prev_nop_frag_holds, NOP_INSN);
6956         }
6957       else
6958         {
6959           /* Allow this instruction to replace one of the nops that was
6960              tentatively added to prev_nop_frag.  */
6961           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6962           prev_nop_frag_holds--;
6963           prev_nop_frag_since++;
6964         }
6965     }
6966
6967   method = get_append_method (ip, address_expr, reloc_type);
6968   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6969
6970   dwarf2_emit_insn (0);
6971   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6972      so "move" the instruction address accordingly.
6973
6974      Also, it doesn't seem appropriate for the assembler to reorder .loc
6975      entries.  If this instruction is a branch that we are going to swap
6976      with the previous instruction, the two instructions should be
6977      treated as a unit, and the debug information for both instructions
6978      should refer to the start of the branch sequence.  Using the
6979      current position is certainly wrong when swapping a 32-bit branch
6980      and a 16-bit delay slot, since the current position would then be
6981      in the middle of a branch.  */
6982   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6983
6984   relax32 = (mips_relax_branch
6985              /* Don't try branch relaxation within .set nomacro, or within
6986                 .set noat if we use $at for PIC computations.  If it turns
6987                 out that the branch was out-of-range, we'll get an error.  */
6988              && !mips_opts.warn_about_macros
6989              && (mips_opts.at || mips_pic == NO_PIC)
6990              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6991                 as they have no complementing branches.  */
6992              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6993
6994   if (!HAVE_CODE_COMPRESSION
6995       && address_expr
6996       && relax32
6997       && *reloc_type == BFD_RELOC_16_PCREL_S2
6998       && delayed_branch_p (ip))
6999     {
7000       relaxed_branch = TRUE;
7001       add_relaxed_insn (ip, (relaxed_branch_length
7002                              (NULL, NULL,
7003                               uncond_branch_p (ip) ? -1
7004                               : branch_likely_p (ip) ? 1
7005                               : 0)), 4,
7006                         RELAX_BRANCH_ENCODE
7007                         (AT,
7008                          uncond_branch_p (ip),
7009                          branch_likely_p (ip),
7010                          pinfo & INSN_WRITE_GPR_31,
7011                          0),
7012                         address_expr->X_add_symbol,
7013                         address_expr->X_add_number);
7014       *reloc_type = BFD_RELOC_UNUSED;
7015     }
7016   else if (mips_opts.micromips
7017            && address_expr
7018            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
7019                || *reloc_type > BFD_RELOC_UNUSED)
7020            && (delayed_branch_p (ip) || compact_branch_p (ip))
7021            /* Don't try branch relaxation when users specify
7022               16-bit/32-bit instructions.  */
7023            && !forced_insn_length)
7024     {
7025       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
7026       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
7027       int uncond = uncond_branch_p (ip) ? -1 : 0;
7028       int compact = compact_branch_p (ip);
7029       int al = pinfo & INSN_WRITE_GPR_31;
7030       int length32;
7031
7032       gas_assert (address_expr != NULL);
7033       gas_assert (!mips_relax.sequence);
7034
7035       relaxed_branch = TRUE;
7036       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
7037       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
7038                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
7039                                                 relax32, 0, 0),
7040                         address_expr->X_add_symbol,
7041                         address_expr->X_add_number);
7042       *reloc_type = BFD_RELOC_UNUSED;
7043     }
7044   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
7045     {
7046       /* We need to set up a variant frag.  */
7047       gas_assert (address_expr != NULL);
7048       add_relaxed_insn (ip, 4, 0,
7049                         RELAX_MIPS16_ENCODE
7050                         (*reloc_type - BFD_RELOC_UNUSED,
7051                          forced_insn_length == 2, forced_insn_length == 4,
7052                          delayed_branch_p (&history[0]),
7053                          history[0].mips16_absolute_jump_p),
7054                         make_expr_symbol (address_expr), 0);
7055     }
7056   else if (mips_opts.mips16 && insn_length (ip) == 2)
7057     {
7058       if (!delayed_branch_p (ip))
7059         /* Make sure there is enough room to swap this instruction with
7060            a following jump instruction.  */
7061         frag_grow (6);
7062       add_fixed_insn (ip);
7063     }
7064   else
7065     {
7066       if (mips_opts.mips16
7067           && mips_opts.noreorder
7068           && delayed_branch_p (&history[0]))
7069         as_warn (_("extended instruction in delay slot"));
7070
7071       if (mips_relax.sequence)
7072         {
7073           /* If we've reached the end of this frag, turn it into a variant
7074              frag and record the information for the instructions we've
7075              written so far.  */
7076           if (frag_room () < 4)
7077             relax_close_frag ();
7078           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
7079         }
7080
7081       if (mips_relax.sequence != 2)
7082         {
7083           if (mips_macro_warning.first_insn_sizes[0] == 0)
7084             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
7085           mips_macro_warning.sizes[0] += insn_length (ip);
7086           mips_macro_warning.insns[0]++;
7087         }
7088       if (mips_relax.sequence != 1)
7089         {
7090           if (mips_macro_warning.first_insn_sizes[1] == 0)
7091             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
7092           mips_macro_warning.sizes[1] += insn_length (ip);
7093           mips_macro_warning.insns[1]++;
7094         }
7095
7096       if (mips_opts.mips16)
7097         {
7098           ip->fixed_p = 1;
7099           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
7100         }
7101       add_fixed_insn (ip);
7102     }
7103
7104   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
7105     {
7106       bfd_reloc_code_real_type final_type[3];
7107       reloc_howto_type *howto0;
7108       reloc_howto_type *howto;
7109       int i;
7110
7111       /* Perform any necessary conversion to microMIPS relocations
7112          and find out how many relocations there actually are.  */
7113       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
7114         final_type[i] = micromips_map_reloc (reloc_type[i]);
7115
7116       /* In a compound relocation, it is the final (outermost)
7117          operator that determines the relocated field.  */
7118       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
7119       if (!howto)
7120         abort ();
7121
7122       if (i > 1)
7123         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
7124       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
7125                                  bfd_get_reloc_size (howto),
7126                                  address_expr,
7127                                  howto0 && howto0->pc_relative,
7128                                  final_type[0]);
7129
7130       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
7131       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
7132         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7133
7134       /* These relocations can have an addend that won't fit in
7135          4 octets for 64bit assembly.  */
7136       if (GPR_SIZE == 64
7137           && ! howto->partial_inplace
7138           && (reloc_type[0] == BFD_RELOC_16
7139               || reloc_type[0] == BFD_RELOC_32
7140               || reloc_type[0] == BFD_RELOC_MIPS_JMP
7141               || reloc_type[0] == BFD_RELOC_GPREL16
7142               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
7143               || reloc_type[0] == BFD_RELOC_GPREL32
7144               || reloc_type[0] == BFD_RELOC_64
7145               || reloc_type[0] == BFD_RELOC_CTOR
7146               || reloc_type[0] == BFD_RELOC_MIPS_SUB
7147               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
7148               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
7149               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
7150               || reloc_type[0] == BFD_RELOC_MIPS_REL16
7151               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
7152               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
7153               || hi16_reloc_p (reloc_type[0])
7154               || lo16_reloc_p (reloc_type[0])))
7155         ip->fixp[0]->fx_no_overflow = 1;
7156
7157       /* These relocations can have an addend that won't fit in 2 octets.  */
7158       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
7159           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
7160         ip->fixp[0]->fx_no_overflow = 1;
7161
7162       if (mips_relax.sequence)
7163         {
7164           if (mips_relax.first_fixup == 0)
7165             mips_relax.first_fixup = ip->fixp[0];
7166         }
7167       else if (reloc_needs_lo_p (*reloc_type))
7168         {
7169           struct mips_hi_fixup *hi_fixup;
7170
7171           /* Reuse the last entry if it already has a matching %lo.  */
7172           hi_fixup = mips_hi_fixup_list;
7173           if (hi_fixup == 0
7174               || !fixup_has_matching_lo_p (hi_fixup->fixp))
7175             {
7176               hi_fixup = ((struct mips_hi_fixup *)
7177                           xmalloc (sizeof (struct mips_hi_fixup)));
7178               hi_fixup->next = mips_hi_fixup_list;
7179               mips_hi_fixup_list = hi_fixup;
7180             }
7181           hi_fixup->fixp = ip->fixp[0];
7182           hi_fixup->seg = now_seg;
7183         }
7184
7185       /* Add fixups for the second and third relocations, if given.
7186          Note that the ABI allows the second relocation to be
7187          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
7188          moment we only use RSS_UNDEF, but we could add support
7189          for the others if it ever becomes necessary.  */
7190       for (i = 1; i < 3; i++)
7191         if (reloc_type[i] != BFD_RELOC_UNUSED)
7192           {
7193             ip->fixp[i] = fix_new (ip->frag, ip->where,
7194                                    ip->fixp[0]->fx_size, NULL, 0,
7195                                    FALSE, final_type[i]);
7196
7197             /* Use fx_tcbit to mark compound relocs.  */
7198             ip->fixp[0]->fx_tcbit = 1;
7199             ip->fixp[i]->fx_tcbit = 1;
7200           }
7201     }
7202   install_insn (ip);
7203
7204   /* Update the register mask information.  */
7205   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
7206   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
7207
7208   switch (method)
7209     {
7210     case APPEND_ADD:
7211       insert_into_history (0, 1, ip);
7212       break;
7213
7214     case APPEND_ADD_WITH_NOP:
7215       {
7216         struct mips_cl_insn *nop;
7217
7218         insert_into_history (0, 1, ip);
7219         nop = get_delay_slot_nop (ip);
7220         add_fixed_insn (nop);
7221         insert_into_history (0, 1, nop);
7222         if (mips_relax.sequence)
7223           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
7224       }
7225       break;
7226
7227     case APPEND_ADD_COMPACT:
7228       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
7229       gas_assert (mips_opts.mips16);
7230       ip->insn_opcode |= 0x0080;
7231       find_altered_mips16_opcode (ip);
7232       install_insn (ip);
7233       insert_into_history (0, 1, ip);
7234       break;
7235
7236     case APPEND_SWAP:
7237       {
7238         struct mips_cl_insn delay = history[0];
7239         if (mips_opts.mips16)
7240           {
7241             know (delay.frag == ip->frag);
7242             move_insn (ip, delay.frag, delay.where);
7243             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
7244           }
7245         else if (relaxed_branch || delay.frag != ip->frag)
7246           {
7247             /* Add the delay slot instruction to the end of the
7248                current frag and shrink the fixed part of the
7249                original frag.  If the branch occupies the tail of
7250                the latter, move it backwards to cover the gap.  */
7251             delay.frag->fr_fix -= branch_disp;
7252             if (delay.frag == ip->frag)
7253               move_insn (ip, ip->frag, ip->where - branch_disp);
7254             add_fixed_insn (&delay);
7255           }
7256         else
7257           {
7258             move_insn (&delay, ip->frag,
7259                        ip->where - branch_disp + insn_length (ip));
7260             move_insn (ip, history[0].frag, history[0].where);
7261           }
7262         history[0] = *ip;
7263         delay.fixed_p = 1;
7264         insert_into_history (0, 1, &delay);
7265       }
7266       break;
7267     }
7268
7269   /* If we have just completed an unconditional branch, clear the history.  */
7270   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7271       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7272     {
7273       unsigned int i;
7274
7275       mips_no_prev_insn ();
7276
7277       for (i = 0; i < ARRAY_SIZE (history); i++)
7278         history[i].cleared_p = 1;
7279     }
7280
7281   /* We need to emit a label at the end of branch-likely macros.  */
7282   if (emit_branch_likely_macro)
7283     {
7284       emit_branch_likely_macro = FALSE;
7285       micromips_add_label ();
7286     }
7287
7288   /* We just output an insn, so the next one doesn't have a label.  */
7289   mips_clear_insn_labels ();
7290 }
7291
7292 /* Forget that there was any previous instruction or label.
7293    When BRANCH is true, the branch history is also flushed.  */
7294
7295 static void
7296 mips_no_prev_insn (void)
7297 {
7298   prev_nop_frag = NULL;
7299   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7300   mips_clear_insn_labels ();
7301 }
7302
7303 /* This function must be called before we emit something other than
7304    instructions.  It is like mips_no_prev_insn except that it inserts
7305    any NOPS that might be needed by previous instructions.  */
7306
7307 void
7308 mips_emit_delays (void)
7309 {
7310   if (! mips_opts.noreorder)
7311     {
7312       int nops = nops_for_insn (0, history, NULL);
7313       if (nops > 0)
7314         {
7315           while (nops-- > 0)
7316             add_fixed_insn (NOP_INSN);
7317           mips_move_text_labels ();
7318         }
7319     }
7320   mips_no_prev_insn ();
7321 }
7322
7323 /* Start a (possibly nested) noreorder block.  */
7324
7325 static void
7326 start_noreorder (void)
7327 {
7328   if (mips_opts.noreorder == 0)
7329     {
7330       unsigned int i;
7331       int nops;
7332
7333       /* None of the instructions before the .set noreorder can be moved.  */
7334       for (i = 0; i < ARRAY_SIZE (history); i++)
7335         history[i].fixed_p = 1;
7336
7337       /* Insert any nops that might be needed between the .set noreorder
7338          block and the previous instructions.  We will later remove any
7339          nops that turn out not to be needed.  */
7340       nops = nops_for_insn (0, history, NULL);
7341       if (nops > 0)
7342         {
7343           if (mips_optimize != 0)
7344             {
7345               /* Record the frag which holds the nop instructions, so
7346                  that we can remove them if we don't need them.  */
7347               frag_grow (nops * NOP_INSN_SIZE);
7348               prev_nop_frag = frag_now;
7349               prev_nop_frag_holds = nops;
7350               prev_nop_frag_required = 0;
7351               prev_nop_frag_since = 0;
7352             }
7353
7354           for (; nops > 0; --nops)
7355             add_fixed_insn (NOP_INSN);
7356
7357           /* Move on to a new frag, so that it is safe to simply
7358              decrease the size of prev_nop_frag.  */
7359           frag_wane (frag_now);
7360           frag_new (0);
7361           mips_move_text_labels ();
7362         }
7363       mips_mark_labels ();
7364       mips_clear_insn_labels ();
7365     }
7366   mips_opts.noreorder++;
7367   mips_any_noreorder = 1;
7368 }
7369
7370 /* End a nested noreorder block.  */
7371
7372 static void
7373 end_noreorder (void)
7374 {
7375   mips_opts.noreorder--;
7376   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7377     {
7378       /* Commit to inserting prev_nop_frag_required nops and go back to
7379          handling nop insertion the .set reorder way.  */
7380       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7381                                 * NOP_INSN_SIZE);
7382       insert_into_history (prev_nop_frag_since,
7383                            prev_nop_frag_required, NOP_INSN);
7384       prev_nop_frag = NULL;
7385     }
7386 }
7387
7388 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7389    higher bits unset.  */
7390
7391 static void
7392 normalize_constant_expr (expressionS *ex)
7393 {
7394   if (ex->X_op == O_constant
7395       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7396     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7397                         - 0x80000000);
7398 }
7399
7400 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7401    all higher bits unset.  */
7402
7403 static void
7404 normalize_address_expr (expressionS *ex)
7405 {
7406   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7407         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7408       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7409     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7410                         - 0x80000000);
7411 }
7412
7413 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7414    Return true if the match was successful.
7415
7416    OPCODE_EXTRA is a value that should be ORed into the opcode
7417    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7418    there are more alternatives after OPCODE and SOFT_MATCH is
7419    as for mips_arg_info.  */
7420
7421 static bfd_boolean
7422 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7423             struct mips_operand_token *tokens, unsigned int opcode_extra,
7424             bfd_boolean lax_match, bfd_boolean complete_p)
7425 {
7426   const char *args;
7427   struct mips_arg_info arg;
7428   const struct mips_operand *operand;
7429   char c;
7430
7431   imm_expr.X_op = O_absent;
7432   offset_expr.X_op = O_absent;
7433   offset_reloc[0] = BFD_RELOC_UNUSED;
7434   offset_reloc[1] = BFD_RELOC_UNUSED;
7435   offset_reloc[2] = BFD_RELOC_UNUSED;
7436
7437   create_insn (insn, opcode);
7438   /* When no opcode suffix is specified, assume ".xyzw". */
7439   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7440     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7441   else
7442     insn->insn_opcode |= opcode_extra;
7443   memset (&arg, 0, sizeof (arg));
7444   arg.insn = insn;
7445   arg.token = tokens;
7446   arg.argnum = 1;
7447   arg.last_regno = ILLEGAL_REG;
7448   arg.dest_regno = ILLEGAL_REG;
7449   arg.lax_match = lax_match;
7450   for (args = opcode->args;; ++args)
7451     {
7452       if (arg.token->type == OT_END)
7453         {
7454           /* Handle unary instructions in which only one operand is given.
7455              The source is then the same as the destination.  */
7456           if (arg.opnum == 1 && *args == ',')
7457             {
7458               operand = (mips_opts.micromips
7459                          ? decode_micromips_operand (args + 1)
7460                          : decode_mips_operand (args + 1));
7461               if (operand && mips_optional_operand_p (operand))
7462                 {
7463                   arg.token = tokens;
7464                   arg.argnum = 1;
7465                   continue;
7466                 }
7467             }
7468
7469           /* Treat elided base registers as $0.  */
7470           if (strcmp (args, "(b)") == 0)
7471             args += 3;
7472
7473           if (args[0] == '+')
7474             switch (args[1])
7475               {
7476               case 'K':
7477               case 'N':
7478                 /* The register suffix is optional. */
7479                 args += 2;
7480                 break;
7481               }
7482
7483           /* Fail the match if there were too few operands.  */
7484           if (*args)
7485             return FALSE;
7486
7487           /* Successful match.  */
7488           if (!complete_p)
7489             return TRUE;
7490           clear_insn_error ();
7491           if (arg.dest_regno == arg.last_regno
7492               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7493             {
7494               if (arg.opnum == 2)
7495                 set_insn_error
7496                   (0, _("source and destination must be different"));
7497               else if (arg.last_regno == 31)
7498                 set_insn_error
7499                   (0, _("a destination register must be supplied"));
7500             }
7501           else if (arg.last_regno == 31
7502                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7503                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7504             set_insn_error (0, _("the source register must not be $31"));
7505           check_completed_insn (&arg);
7506           return TRUE;
7507         }
7508
7509       /* Fail the match if the line has too many operands.   */
7510       if (*args == 0)
7511         return FALSE;
7512
7513       /* Handle characters that need to match exactly.  */
7514       if (*args == '(' || *args == ')' || *args == ',')
7515         {
7516           if (match_char (&arg, *args))
7517             continue;
7518           return FALSE;
7519         }
7520       if (*args == '#')
7521         {
7522           ++args;
7523           if (arg.token->type == OT_DOUBLE_CHAR
7524               && arg.token->u.ch == *args)
7525             {
7526               ++arg.token;
7527               continue;
7528             }
7529           return FALSE;
7530         }
7531
7532       /* Handle special macro operands.  Work out the properties of
7533          other operands.  */
7534       arg.opnum += 1;
7535       switch (*args)
7536         {
7537         case '+':
7538           switch (args[1])
7539             {
7540             case 'i':
7541               *offset_reloc = BFD_RELOC_MIPS_JMP;
7542               break;
7543             }
7544           break;
7545
7546         case 'I':
7547           if (!match_const_int (&arg, &imm_expr.X_add_number))
7548             return FALSE;
7549           imm_expr.X_op = O_constant;
7550           if (GPR_SIZE == 32)
7551             normalize_constant_expr (&imm_expr);
7552           continue;
7553
7554         case 'A':
7555           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7556             {
7557               /* Assume that the offset has been elided and that what
7558                  we saw was a base register.  The match will fail later
7559                  if that assumption turns out to be wrong.  */
7560               offset_expr.X_op = O_constant;
7561               offset_expr.X_add_number = 0;
7562             }
7563           else
7564             {
7565               if (!match_expression (&arg, &offset_expr, offset_reloc))
7566                 return FALSE;
7567               normalize_address_expr (&offset_expr);
7568             }
7569           continue;
7570
7571         case 'F':
7572           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7573                                      8, TRUE))
7574             return FALSE;
7575           continue;
7576
7577         case 'L':
7578           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7579                                      8, FALSE))
7580             return FALSE;
7581           continue;
7582
7583         case 'f':
7584           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7585                                      4, TRUE))
7586             return FALSE;
7587           continue;
7588
7589         case 'l':
7590           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7591                                      4, FALSE))
7592             return FALSE;
7593           continue;
7594
7595         case 'p':
7596           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7597           break;
7598
7599         case 'a':
7600           *offset_reloc = BFD_RELOC_MIPS_JMP;
7601           break;
7602
7603         case 'm':
7604           gas_assert (mips_opts.micromips);
7605           c = args[1];
7606           switch (c)
7607             {
7608             case 'D':
7609             case 'E':
7610               if (!forced_insn_length)
7611                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7612               else if (c == 'D')
7613                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7614               else
7615                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7616               break;
7617             }
7618           break;
7619         }
7620
7621       operand = (mips_opts.micromips
7622                  ? decode_micromips_operand (args)
7623                  : decode_mips_operand (args));
7624       if (!operand)
7625         abort ();
7626
7627       /* Skip prefixes.  */
7628       if (*args == '+' || *args == 'm')
7629         args++;
7630
7631       if (mips_optional_operand_p (operand)
7632           && args[1] == ','
7633           && (arg.token[0].type != OT_REG
7634               || arg.token[1].type == OT_END))
7635         {
7636           /* Assume that the register has been elided and is the
7637              same as the first operand.  */
7638           arg.token = tokens;
7639           arg.argnum = 1;
7640         }
7641
7642       if (!match_operand (&arg, operand))
7643         return FALSE;
7644     }
7645 }
7646
7647 /* Like match_insn, but for MIPS16.  */
7648
7649 static bfd_boolean
7650 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7651                    struct mips_operand_token *tokens)
7652 {
7653   const char *args;
7654   const struct mips_operand *operand;
7655   const struct mips_operand *ext_operand;
7656   struct mips_arg_info arg;
7657   int relax_char;
7658
7659   create_insn (insn, opcode);
7660   imm_expr.X_op = O_absent;
7661   offset_expr.X_op = O_absent;
7662   offset_reloc[0] = BFD_RELOC_UNUSED;
7663   offset_reloc[1] = BFD_RELOC_UNUSED;
7664   offset_reloc[2] = BFD_RELOC_UNUSED;
7665   relax_char = 0;
7666
7667   memset (&arg, 0, sizeof (arg));
7668   arg.insn = insn;
7669   arg.token = tokens;
7670   arg.argnum = 1;
7671   arg.last_regno = ILLEGAL_REG;
7672   arg.dest_regno = ILLEGAL_REG;
7673   relax_char = 0;
7674   for (args = opcode->args;; ++args)
7675     {
7676       int c;
7677
7678       if (arg.token->type == OT_END)
7679         {
7680           offsetT value;
7681
7682           /* Handle unary instructions in which only one operand is given.
7683              The source is then the same as the destination.  */
7684           if (arg.opnum == 1 && *args == ',')
7685             {
7686               operand = decode_mips16_operand (args[1], FALSE);
7687               if (operand && mips_optional_operand_p (operand))
7688                 {
7689                   arg.token = tokens;
7690                   arg.argnum = 1;
7691                   continue;
7692                 }
7693             }
7694
7695           /* Fail the match if there were too few operands.  */
7696           if (*args)
7697             return FALSE;
7698
7699           /* Successful match.  Stuff the immediate value in now, if
7700              we can.  */
7701           clear_insn_error ();
7702           if (opcode->pinfo == INSN_MACRO)
7703             {
7704               gas_assert (relax_char == 0 || relax_char == 'p');
7705               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7706             }
7707           else if (relax_char
7708                    && offset_expr.X_op == O_constant
7709                    && calculate_reloc (*offset_reloc,
7710                                        offset_expr.X_add_number,
7711                                        &value))
7712             {
7713               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7714                             forced_insn_length, &insn->insn_opcode);
7715               offset_expr.X_op = O_absent;
7716               *offset_reloc = BFD_RELOC_UNUSED;
7717             }
7718           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7719             {
7720               if (forced_insn_length == 2)
7721                 set_insn_error (0, _("invalid unextended operand value"));
7722               forced_insn_length = 4;
7723               insn->insn_opcode |= MIPS16_EXTEND;
7724             }
7725           else if (relax_char)
7726             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7727
7728           check_completed_insn (&arg);
7729           return TRUE;
7730         }
7731
7732       /* Fail the match if the line has too many operands.   */
7733       if (*args == 0)
7734         return FALSE;
7735
7736       /* Handle characters that need to match exactly.  */
7737       if (*args == '(' || *args == ')' || *args == ',')
7738         {
7739           if (match_char (&arg, *args))
7740             continue;
7741           return FALSE;
7742         }
7743
7744       arg.opnum += 1;
7745       c = *args;
7746       switch (c)
7747         {
7748         case 'p':
7749         case 'q':
7750         case 'A':
7751         case 'B':
7752         case 'E':
7753           relax_char = c;
7754           break;
7755
7756         case 'I':
7757           if (!match_const_int (&arg, &imm_expr.X_add_number))
7758             return FALSE;
7759           imm_expr.X_op = O_constant;
7760           if (GPR_SIZE == 32)
7761             normalize_constant_expr (&imm_expr);
7762           continue;
7763
7764         case 'a':
7765         case 'i':
7766           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7767           insn->insn_opcode <<= 16;
7768           break;
7769         }
7770
7771       operand = decode_mips16_operand (c, FALSE);
7772       if (!operand)
7773         abort ();
7774
7775       /* '6' is a special case.  It is used for BREAK and SDBBP,
7776          whose operands are only meaningful to the software that decodes
7777          them.  This means that there is no architectural reason why
7778          they cannot be prefixed by EXTEND, but in practice,
7779          exception handlers will only look at the instruction
7780          itself.  We therefore allow '6' to be extended when
7781          disassembling but not when assembling.  */
7782       if (operand->type != OP_PCREL && c != '6')
7783         {
7784           ext_operand = decode_mips16_operand (c, TRUE);
7785           if (operand != ext_operand)
7786             {
7787               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7788                 {
7789                   offset_expr.X_op = O_constant;
7790                   offset_expr.X_add_number = 0;
7791                   relax_char = c;
7792                   continue;
7793                 }
7794
7795               /* We need the OT_INTEGER check because some MIPS16
7796                  immediate variants are listed before the register ones.  */
7797               if (arg.token->type != OT_INTEGER
7798                   || !match_expression (&arg, &offset_expr, offset_reloc))
7799                 return FALSE;
7800
7801               /* '8' is used for SLTI(U) and has traditionally not
7802                  been allowed to take relocation operators.  */
7803               if (offset_reloc[0] != BFD_RELOC_UNUSED
7804                   && (ext_operand->size != 16 || c == '8'))
7805                 return FALSE;
7806
7807               relax_char = c;
7808               continue;
7809             }
7810         }
7811
7812       if (mips_optional_operand_p (operand)
7813           && args[1] == ','
7814           && (arg.token[0].type != OT_REG
7815               || arg.token[1].type == OT_END))
7816         {
7817           /* Assume that the register has been elided and is the
7818              same as the first operand.  */
7819           arg.token = tokens;
7820           arg.argnum = 1;
7821         }
7822
7823       if (!match_operand (&arg, operand))
7824         return FALSE;
7825     }
7826 }
7827
7828 /* Record that the current instruction is invalid for the current ISA.  */
7829
7830 static void
7831 match_invalid_for_isa (void)
7832 {
7833   set_insn_error_ss
7834     (0, _("opcode not supported on this processor: %s (%s)"),
7835      mips_cpu_info_from_arch (mips_opts.arch)->name,
7836      mips_cpu_info_from_isa (mips_opts.isa)->name);
7837 }
7838
7839 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
7840    Return true if a definite match or failure was found, storing any match
7841    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
7842    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
7843    tried and failed to match under normal conditions and now want to try a
7844    more relaxed match.  */
7845
7846 static bfd_boolean
7847 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7848              const struct mips_opcode *past, struct mips_operand_token *tokens,
7849              int opcode_extra, bfd_boolean lax_match)
7850 {
7851   const struct mips_opcode *opcode;
7852   const struct mips_opcode *invalid_delay_slot;
7853   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
7854
7855   /* Search for a match, ignoring alternatives that don't satisfy the
7856      current ISA or forced_length.  */
7857   invalid_delay_slot = 0;
7858   seen_valid_for_isa = FALSE;
7859   seen_valid_for_size = FALSE;
7860   opcode = first;
7861   do
7862     {
7863       gas_assert (strcmp (opcode->name, first->name) == 0);
7864       if (is_opcode_valid (opcode))
7865         {
7866           seen_valid_for_isa = TRUE;
7867           if (is_size_valid (opcode))
7868             {
7869               bfd_boolean delay_slot_ok;
7870
7871               seen_valid_for_size = TRUE;
7872               delay_slot_ok = is_delay_slot_valid (opcode);
7873               if (match_insn (insn, opcode, tokens, opcode_extra,
7874                               lax_match, delay_slot_ok))
7875                 {
7876                   if (!delay_slot_ok)
7877                     {
7878                       if (!invalid_delay_slot)
7879                         invalid_delay_slot = opcode;
7880                     }
7881                   else
7882                     return TRUE;
7883                 }
7884             }
7885         }
7886       ++opcode;
7887     }
7888   while (opcode < past && strcmp (opcode->name, first->name) == 0);
7889
7890   /* If the only matches we found had the wrong length for the delay slot,
7891      pick the first such match.  We'll issue an appropriate warning later.  */
7892   if (invalid_delay_slot)
7893     {
7894       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
7895                       lax_match, TRUE))
7896         return TRUE;
7897       abort ();
7898     }
7899
7900   /* Handle the case where we didn't try to match an instruction because
7901      all the alternatives were incompatible with the current ISA.  */
7902   if (!seen_valid_for_isa)
7903     {
7904       match_invalid_for_isa ();
7905       return TRUE;
7906     }
7907
7908   /* Handle the case where we didn't try to match an instruction because
7909      all the alternatives were of the wrong size.  */
7910   if (!seen_valid_for_size)
7911     {
7912       if (mips_opts.insn32)
7913         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
7914       else
7915         set_insn_error_i
7916           (0, _("unrecognized %d-bit version of microMIPS opcode"),
7917            8 * forced_insn_length);
7918       return TRUE;
7919     }
7920
7921   return FALSE;
7922 }
7923
7924 /* Like match_insns, but for MIPS16.  */
7925
7926 static bfd_boolean
7927 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7928                     struct mips_operand_token *tokens)
7929 {
7930   const struct mips_opcode *opcode;
7931   bfd_boolean seen_valid_for_isa;
7932
7933   /* Search for a match, ignoring alternatives that don't satisfy the
7934      current ISA.  There are no separate entries for extended forms so
7935      we deal with forced_length later.  */
7936   seen_valid_for_isa = FALSE;
7937   opcode = first;
7938   do
7939     {
7940       gas_assert (strcmp (opcode->name, first->name) == 0);
7941       if (is_opcode_valid_16 (opcode))
7942         {
7943           seen_valid_for_isa = TRUE;
7944           if (match_mips16_insn (insn, opcode, tokens))
7945             return TRUE;
7946         }
7947       ++opcode;
7948     }
7949   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
7950          && strcmp (opcode->name, first->name) == 0);
7951
7952   /* Handle the case where we didn't try to match an instruction because
7953      all the alternatives were incompatible with the current ISA.  */
7954   if (!seen_valid_for_isa)
7955     {
7956       match_invalid_for_isa ();
7957       return TRUE;
7958     }
7959
7960   return FALSE;
7961 }
7962
7963 /* Set up global variables for the start of a new macro.  */
7964
7965 static void
7966 macro_start (void)
7967 {
7968   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7969   memset (&mips_macro_warning.first_insn_sizes, 0,
7970           sizeof (mips_macro_warning.first_insn_sizes));
7971   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7972   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7973                                      && delayed_branch_p (&history[0]));
7974   switch (history[0].insn_mo->pinfo2
7975           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7976     {
7977     case INSN2_BRANCH_DELAY_32BIT:
7978       mips_macro_warning.delay_slot_length = 4;
7979       break;
7980     case INSN2_BRANCH_DELAY_16BIT:
7981       mips_macro_warning.delay_slot_length = 2;
7982       break;
7983     default:
7984       mips_macro_warning.delay_slot_length = 0;
7985       break;
7986     }
7987   mips_macro_warning.first_frag = NULL;
7988 }
7989
7990 /* Given that a macro is longer than one instruction or of the wrong size,
7991    return the appropriate warning for it.  Return null if no warning is
7992    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7993    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7994    and RELAX_NOMACRO.  */
7995
7996 static const char *
7997 macro_warning (relax_substateT subtype)
7998 {
7999   if (subtype & RELAX_DELAY_SLOT)
8000     return _("macro instruction expanded into multiple instructions"
8001              " in a branch delay slot");
8002   else if (subtype & RELAX_NOMACRO)
8003     return _("macro instruction expanded into multiple instructions");
8004   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
8005                       | RELAX_DELAY_SLOT_SIZE_SECOND))
8006     return ((subtype & RELAX_DELAY_SLOT_16BIT)
8007             ? _("macro instruction expanded into a wrong size instruction"
8008                 " in a 16-bit branch delay slot")
8009             : _("macro instruction expanded into a wrong size instruction"
8010                 " in a 32-bit branch delay slot"));
8011   else
8012     return 0;
8013 }
8014
8015 /* Finish up a macro.  Emit warnings as appropriate.  */
8016
8017 static void
8018 macro_end (void)
8019 {
8020   /* Relaxation warning flags.  */
8021   relax_substateT subtype = 0;
8022
8023   /* Check delay slot size requirements.  */
8024   if (mips_macro_warning.delay_slot_length == 2)
8025     subtype |= RELAX_DELAY_SLOT_16BIT;
8026   if (mips_macro_warning.delay_slot_length != 0)
8027     {
8028       if (mips_macro_warning.delay_slot_length
8029           != mips_macro_warning.first_insn_sizes[0])
8030         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
8031       if (mips_macro_warning.delay_slot_length
8032           != mips_macro_warning.first_insn_sizes[1])
8033         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
8034     }
8035
8036   /* Check instruction count requirements.  */
8037   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
8038     {
8039       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
8040         subtype |= RELAX_SECOND_LONGER;
8041       if (mips_opts.warn_about_macros)
8042         subtype |= RELAX_NOMACRO;
8043       if (mips_macro_warning.delay_slot_p)
8044         subtype |= RELAX_DELAY_SLOT;
8045     }
8046
8047   /* If both alternatives fail to fill a delay slot correctly,
8048      emit the warning now.  */
8049   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
8050       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
8051     {
8052       relax_substateT s;
8053       const char *msg;
8054
8055       s = subtype & (RELAX_DELAY_SLOT_16BIT
8056                      | RELAX_DELAY_SLOT_SIZE_FIRST
8057                      | RELAX_DELAY_SLOT_SIZE_SECOND);
8058       msg = macro_warning (s);
8059       if (msg != NULL)
8060         as_warn ("%s", msg);
8061       subtype &= ~s;
8062     }
8063
8064   /* If both implementations are longer than 1 instruction, then emit the
8065      warning now.  */
8066   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
8067     {
8068       relax_substateT s;
8069       const char *msg;
8070
8071       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
8072       msg = macro_warning (s);
8073       if (msg != NULL)
8074         as_warn ("%s", msg);
8075       subtype &= ~s;
8076     }
8077
8078   /* If any flags still set, then one implementation might need a warning
8079      and the other either will need one of a different kind or none at all.
8080      Pass any remaining flags over to relaxation.  */
8081   if (mips_macro_warning.first_frag != NULL)
8082     mips_macro_warning.first_frag->fr_subtype |= subtype;
8083 }
8084
8085 /* Instruction operand formats used in macros that vary between
8086    standard MIPS and microMIPS code.  */
8087
8088 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
8089 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
8090 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
8091 static const char * const lui_fmt[2] = { "t,u", "s,u" };
8092 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
8093 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
8094 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
8095 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
8096
8097 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
8098 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
8099 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
8100 #define LUI_FMT (lui_fmt[mips_opts.micromips])
8101 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
8102 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
8103 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
8104 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
8105
8106 /* Read a macro's relocation codes from *ARGS and store them in *R.
8107    The first argument in *ARGS will be either the code for a single
8108    relocation or -1 followed by the three codes that make up a
8109    composite relocation.  */
8110
8111 static void
8112 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
8113 {
8114   int i, next;
8115
8116   next = va_arg (*args, int);
8117   if (next >= 0)
8118     r[0] = (bfd_reloc_code_real_type) next;
8119   else
8120     {
8121       for (i = 0; i < 3; i++)
8122         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
8123       /* This function is only used for 16-bit relocation fields.
8124          To make the macro code simpler, treat an unrelocated value
8125          in the same way as BFD_RELOC_LO16.  */
8126       if (r[0] == BFD_RELOC_UNUSED)
8127         r[0] = BFD_RELOC_LO16;
8128     }
8129 }
8130
8131 /* Build an instruction created by a macro expansion.  This is passed
8132    a pointer to the count of instructions created so far, an
8133    expression, the name of the instruction to build, an operand format
8134    string, and corresponding arguments.  */
8135
8136 static void
8137 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
8138 {
8139   const struct mips_opcode *mo = NULL;
8140   bfd_reloc_code_real_type r[3];
8141   const struct mips_opcode *amo;
8142   const struct mips_operand *operand;
8143   struct hash_control *hash;
8144   struct mips_cl_insn insn;
8145   va_list args;
8146   unsigned int uval;
8147
8148   va_start (args, fmt);
8149
8150   if (mips_opts.mips16)
8151     {
8152       mips16_macro_build (ep, name, fmt, &args);
8153       va_end (args);
8154       return;
8155     }
8156
8157   r[0] = BFD_RELOC_UNUSED;
8158   r[1] = BFD_RELOC_UNUSED;
8159   r[2] = BFD_RELOC_UNUSED;
8160   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
8161   amo = (struct mips_opcode *) hash_find (hash, name);
8162   gas_assert (amo);
8163   gas_assert (strcmp (name, amo->name) == 0);
8164
8165   do
8166     {
8167       /* Search until we get a match for NAME.  It is assumed here that
8168          macros will never generate MDMX, MIPS-3D, or MT instructions.
8169          We try to match an instruction that fulfils the branch delay
8170          slot instruction length requirement (if any) of the previous
8171          instruction.  While doing this we record the first instruction
8172          seen that matches all the other conditions and use it anyway
8173          if the requirement cannot be met; we will issue an appropriate
8174          warning later on.  */
8175       if (strcmp (fmt, amo->args) == 0
8176           && amo->pinfo != INSN_MACRO
8177           && is_opcode_valid (amo)
8178           && is_size_valid (amo))
8179         {
8180           if (is_delay_slot_valid (amo))
8181             {
8182               mo = amo;
8183               break;
8184             }
8185           else if (!mo)
8186             mo = amo;
8187         }
8188
8189       ++amo;
8190       gas_assert (amo->name);
8191     }
8192   while (strcmp (name, amo->name) == 0);
8193
8194   gas_assert (mo);
8195   create_insn (&insn, mo);
8196   for (; *fmt; ++fmt)
8197     {
8198       switch (*fmt)
8199         {
8200         case ',':
8201         case '(':
8202         case ')':
8203         case 'z':
8204           break;
8205
8206         case 'i':
8207         case 'j':
8208           macro_read_relocs (&args, r);
8209           gas_assert (*r == BFD_RELOC_GPREL16
8210                       || *r == BFD_RELOC_MIPS_HIGHER
8211                       || *r == BFD_RELOC_HI16_S
8212                       || *r == BFD_RELOC_LO16
8213                       || *r == BFD_RELOC_MIPS_GOT_OFST);
8214           break;
8215
8216         case 'o':
8217           macro_read_relocs (&args, r);
8218           break;
8219
8220         case 'u':
8221           macro_read_relocs (&args, r);
8222           gas_assert (ep != NULL
8223                       && (ep->X_op == O_constant
8224                           || (ep->X_op == O_symbol
8225                               && (*r == BFD_RELOC_MIPS_HIGHEST
8226                                   || *r == BFD_RELOC_HI16_S
8227                                   || *r == BFD_RELOC_HI16
8228                                   || *r == BFD_RELOC_GPREL16
8229                                   || *r == BFD_RELOC_MIPS_GOT_HI16
8230                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
8231           break;
8232
8233         case 'p':
8234           gas_assert (ep != NULL);
8235
8236           /*
8237            * This allows macro() to pass an immediate expression for
8238            * creating short branches without creating a symbol.
8239            *
8240            * We don't allow branch relaxation for these branches, as
8241            * they should only appear in ".set nomacro" anyway.
8242            */
8243           if (ep->X_op == O_constant)
8244             {
8245               /* For microMIPS we always use relocations for branches.
8246                  So we should not resolve immediate values.  */
8247               gas_assert (!mips_opts.micromips);
8248
8249               if ((ep->X_add_number & 3) != 0)
8250                 as_bad (_("branch to misaligned address (0x%lx)"),
8251                         (unsigned long) ep->X_add_number);
8252               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
8253                 as_bad (_("branch address range overflow (0x%lx)"),
8254                         (unsigned long) ep->X_add_number);
8255               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8256               ep = NULL;
8257             }
8258           else
8259             *r = BFD_RELOC_16_PCREL_S2;
8260           break;
8261
8262         case 'a':
8263           gas_assert (ep != NULL);
8264           *r = BFD_RELOC_MIPS_JMP;
8265           break;
8266
8267         default:
8268           operand = (mips_opts.micromips
8269                      ? decode_micromips_operand (fmt)
8270                      : decode_mips_operand (fmt));
8271           if (!operand)
8272             abort ();
8273
8274           uval = va_arg (args, int);
8275           if (operand->type == OP_CLO_CLZ_DEST)
8276             uval |= (uval << 5);
8277           insn_insert_operand (&insn, operand, uval);
8278
8279           if (*fmt == '+' || *fmt == 'm')
8280             ++fmt;
8281           break;
8282         }
8283     }
8284   va_end (args);
8285   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8286
8287   append_insn (&insn, ep, r, TRUE);
8288 }
8289
8290 static void
8291 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8292                     va_list *args)
8293 {
8294   struct mips_opcode *mo;
8295   struct mips_cl_insn insn;
8296   const struct mips_operand *operand;
8297   bfd_reloc_code_real_type r[3]
8298     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8299
8300   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8301   gas_assert (mo);
8302   gas_assert (strcmp (name, mo->name) == 0);
8303
8304   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8305     {
8306       ++mo;
8307       gas_assert (mo->name);
8308       gas_assert (strcmp (name, mo->name) == 0);
8309     }
8310
8311   create_insn (&insn, mo);
8312   for (; *fmt; ++fmt)
8313     {
8314       int c;
8315
8316       c = *fmt;
8317       switch (c)
8318         {
8319         case ',':
8320         case '(':
8321         case ')':
8322           break;
8323
8324         case '0':
8325         case 'S':
8326         case 'P':
8327         case 'R':
8328           break;
8329
8330         case '<':
8331         case '>':
8332         case '4':
8333         case '5':
8334         case 'H':
8335         case 'W':
8336         case 'D':
8337         case 'j':
8338         case '8':
8339         case 'V':
8340         case 'C':
8341         case 'U':
8342         case 'k':
8343         case 'K':
8344         case 'p':
8345         case 'q':
8346           {
8347             offsetT value;
8348
8349             gas_assert (ep != NULL);
8350
8351             if (ep->X_op != O_constant)
8352               *r = (int) BFD_RELOC_UNUSED + c;
8353             else if (calculate_reloc (*r, ep->X_add_number, &value))
8354               {
8355                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8356                 ep = NULL;
8357                 *r = BFD_RELOC_UNUSED;
8358               }
8359           }
8360           break;
8361
8362         default:
8363           operand = decode_mips16_operand (c, FALSE);
8364           if (!operand)
8365             abort ();
8366
8367           insn_insert_operand (&insn, operand, va_arg (*args, int));
8368           break;
8369         }
8370     }
8371
8372   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8373
8374   append_insn (&insn, ep, r, TRUE);
8375 }
8376
8377 /*
8378  * Generate a "jalr" instruction with a relocation hint to the called
8379  * function.  This occurs in NewABI PIC code.
8380  */
8381 static void
8382 macro_build_jalr (expressionS *ep, int cprestore)
8383 {
8384   static const bfd_reloc_code_real_type jalr_relocs[2]
8385     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8386   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8387   const char *jalr;
8388   char *f = NULL;
8389
8390   if (MIPS_JALR_HINT_P (ep))
8391     {
8392       frag_grow (8);
8393       f = frag_more (0);
8394     }
8395   if (mips_opts.micromips)
8396     {
8397       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8398               ? "jalr" : "jalrs");
8399       if (MIPS_JALR_HINT_P (ep)
8400           || mips_opts.insn32
8401           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8402         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8403       else
8404         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8405     }
8406   else
8407     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8408   if (MIPS_JALR_HINT_P (ep))
8409     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8410 }
8411
8412 /*
8413  * Generate a "lui" instruction.
8414  */
8415 static void
8416 macro_build_lui (expressionS *ep, int regnum)
8417 {
8418   gas_assert (! mips_opts.mips16);
8419
8420   if (ep->X_op != O_constant)
8421     {
8422       gas_assert (ep->X_op == O_symbol);
8423       /* _gp_disp is a special case, used from s_cpload.
8424          __gnu_local_gp is used if mips_no_shared.  */
8425       gas_assert (mips_pic == NO_PIC
8426               || (! HAVE_NEWABI
8427                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8428               || (! mips_in_shared
8429                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8430                              "__gnu_local_gp") == 0));
8431     }
8432
8433   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8434 }
8435
8436 /* Generate a sequence of instructions to do a load or store from a constant
8437    offset off of a base register (breg) into/from a target register (treg),
8438    using AT if necessary.  */
8439 static void
8440 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8441                               int treg, int breg, int dbl)
8442 {
8443   gas_assert (ep->X_op == O_constant);
8444
8445   /* Sign-extending 32-bit constants makes their handling easier.  */
8446   if (!dbl)
8447     normalize_constant_expr (ep);
8448
8449   /* Right now, this routine can only handle signed 32-bit constants.  */
8450   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8451     as_warn (_("operand overflow"));
8452
8453   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8454     {
8455       /* Signed 16-bit offset will fit in the op.  Easy!  */
8456       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8457     }
8458   else
8459     {
8460       /* 32-bit offset, need multiple instructions and AT, like:
8461            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8462            addu     $tempreg,$tempreg,$breg
8463            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8464          to handle the complete offset.  */
8465       macro_build_lui (ep, AT);
8466       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8467       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8468
8469       if (!mips_opts.at)
8470         as_bad (_("macro used $at after \".set noat\""));
8471     }
8472 }
8473
8474 /*                      set_at()
8475  * Generates code to set the $at register to true (one)
8476  * if reg is less than the immediate expression.
8477  */
8478 static void
8479 set_at (int reg, int unsignedp)
8480 {
8481   if (imm_expr.X_add_number >= -0x8000
8482       && imm_expr.X_add_number < 0x8000)
8483     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8484                  AT, reg, BFD_RELOC_LO16);
8485   else
8486     {
8487       load_register (AT, &imm_expr, GPR_SIZE == 64);
8488       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8489     }
8490 }
8491
8492 /* Count the leading zeroes by performing a binary chop. This is a
8493    bulky bit of source, but performance is a LOT better for the
8494    majority of values than a simple loop to count the bits:
8495        for (lcnt = 0; (lcnt < 32); lcnt++)
8496          if ((v) & (1 << (31 - lcnt)))
8497            break;
8498   However it is not code size friendly, and the gain will drop a bit
8499   on certain cached systems.
8500 */
8501 #define COUNT_TOP_ZEROES(v)             \
8502   (((v) & ~0xffff) == 0                 \
8503    ? ((v) & ~0xff) == 0                 \
8504      ? ((v) & ~0xf) == 0                \
8505        ? ((v) & ~0x3) == 0              \
8506          ? ((v) & ~0x1) == 0            \
8507            ? !(v)                       \
8508              ? 32                       \
8509              : 31                       \
8510            : 30                         \
8511          : ((v) & ~0x7) == 0            \
8512            ? 29                         \
8513            : 28                         \
8514        : ((v) & ~0x3f) == 0             \
8515          ? ((v) & ~0x1f) == 0           \
8516            ? 27                         \
8517            : 26                         \
8518          : ((v) & ~0x7f) == 0           \
8519            ? 25                         \
8520            : 24                         \
8521      : ((v) & ~0xfff) == 0              \
8522        ? ((v) & ~0x3ff) == 0            \
8523          ? ((v) & ~0x1ff) == 0          \
8524            ? 23                         \
8525            : 22                         \
8526          : ((v) & ~0x7ff) == 0          \
8527            ? 21                         \
8528            : 20                         \
8529        : ((v) & ~0x3fff) == 0           \
8530          ? ((v) & ~0x1fff) == 0         \
8531            ? 19                         \
8532            : 18                         \
8533          : ((v) & ~0x7fff) == 0         \
8534            ? 17                         \
8535            : 16                         \
8536    : ((v) & ~0xffffff) == 0             \
8537      ? ((v) & ~0xfffff) == 0            \
8538        ? ((v) & ~0x3ffff) == 0          \
8539          ? ((v) & ~0x1ffff) == 0        \
8540            ? 15                         \
8541            : 14                         \
8542          : ((v) & ~0x7ffff) == 0        \
8543            ? 13                         \
8544            : 12                         \
8545        : ((v) & ~0x3fffff) == 0         \
8546          ? ((v) & ~0x1fffff) == 0       \
8547            ? 11                         \
8548            : 10                         \
8549          : ((v) & ~0x7fffff) == 0       \
8550            ? 9                          \
8551            : 8                          \
8552      : ((v) & ~0xfffffff) == 0          \
8553        ? ((v) & ~0x3ffffff) == 0        \
8554          ? ((v) & ~0x1ffffff) == 0      \
8555            ? 7                          \
8556            : 6                          \
8557          : ((v) & ~0x7ffffff) == 0      \
8558            ? 5                          \
8559            : 4                          \
8560        : ((v) & ~0x3fffffff) == 0       \
8561          ? ((v) & ~0x1fffffff) == 0     \
8562            ? 3                          \
8563            : 2                          \
8564          : ((v) & ~0x7fffffff) == 0     \
8565            ? 1                          \
8566            : 0)
8567
8568 /*                      load_register()
8569  *  This routine generates the least number of instructions necessary to load
8570  *  an absolute expression value into a register.
8571  */
8572 static void
8573 load_register (int reg, expressionS *ep, int dbl)
8574 {
8575   int freg;
8576   expressionS hi32, lo32;
8577
8578   if (ep->X_op != O_big)
8579     {
8580       gas_assert (ep->X_op == O_constant);
8581
8582       /* Sign-extending 32-bit constants makes their handling easier.  */
8583       if (!dbl)
8584         normalize_constant_expr (ep);
8585
8586       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8587         {
8588           /* We can handle 16 bit signed values with an addiu to
8589              $zero.  No need to ever use daddiu here, since $zero and
8590              the result are always correct in 32 bit mode.  */
8591           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8592           return;
8593         }
8594       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8595         {
8596           /* We can handle 16 bit unsigned values with an ori to
8597              $zero.  */
8598           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8599           return;
8600         }
8601       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8602         {
8603           /* 32 bit values require an lui.  */
8604           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8605           if ((ep->X_add_number & 0xffff) != 0)
8606             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8607           return;
8608         }
8609     }
8610
8611   /* The value is larger than 32 bits.  */
8612
8613   if (!dbl || GPR_SIZE == 32)
8614     {
8615       char value[32];
8616
8617       sprintf_vma (value, ep->X_add_number);
8618       as_bad (_("number (0x%s) larger than 32 bits"), value);
8619       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8620       return;
8621     }
8622
8623   if (ep->X_op != O_big)
8624     {
8625       hi32 = *ep;
8626       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8627       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8628       hi32.X_add_number &= 0xffffffff;
8629       lo32 = *ep;
8630       lo32.X_add_number &= 0xffffffff;
8631     }
8632   else
8633     {
8634       gas_assert (ep->X_add_number > 2);
8635       if (ep->X_add_number == 3)
8636         generic_bignum[3] = 0;
8637       else if (ep->X_add_number > 4)
8638         as_bad (_("number larger than 64 bits"));
8639       lo32.X_op = O_constant;
8640       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8641       hi32.X_op = O_constant;
8642       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8643     }
8644
8645   if (hi32.X_add_number == 0)
8646     freg = 0;
8647   else
8648     {
8649       int shift, bit;
8650       unsigned long hi, lo;
8651
8652       if (hi32.X_add_number == (offsetT) 0xffffffff)
8653         {
8654           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8655             {
8656               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8657               return;
8658             }
8659           if (lo32.X_add_number & 0x80000000)
8660             {
8661               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8662               if (lo32.X_add_number & 0xffff)
8663                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8664               return;
8665             }
8666         }
8667
8668       /* Check for 16bit shifted constant.  We know that hi32 is
8669          non-zero, so start the mask on the first bit of the hi32
8670          value.  */
8671       shift = 17;
8672       do
8673         {
8674           unsigned long himask, lomask;
8675
8676           if (shift < 32)
8677             {
8678               himask = 0xffff >> (32 - shift);
8679               lomask = (0xffff << shift) & 0xffffffff;
8680             }
8681           else
8682             {
8683               himask = 0xffff << (shift - 32);
8684               lomask = 0;
8685             }
8686           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8687               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8688             {
8689               expressionS tmp;
8690
8691               tmp.X_op = O_constant;
8692               if (shift < 32)
8693                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8694                                     | (lo32.X_add_number >> shift));
8695               else
8696                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8697               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8698               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8699                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8700               return;
8701             }
8702           ++shift;
8703         }
8704       while (shift <= (64 - 16));
8705
8706       /* Find the bit number of the lowest one bit, and store the
8707          shifted value in hi/lo.  */
8708       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8709       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8710       if (lo != 0)
8711         {
8712           bit = 0;
8713           while ((lo & 1) == 0)
8714             {
8715               lo >>= 1;
8716               ++bit;
8717             }
8718           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8719           hi >>= bit;
8720         }
8721       else
8722         {
8723           bit = 32;
8724           while ((hi & 1) == 0)
8725             {
8726               hi >>= 1;
8727               ++bit;
8728             }
8729           lo = hi;
8730           hi = 0;
8731         }
8732
8733       /* Optimize if the shifted value is a (power of 2) - 1.  */
8734       if ((hi == 0 && ((lo + 1) & lo) == 0)
8735           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8736         {
8737           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8738           if (shift != 0)
8739             {
8740               expressionS tmp;
8741
8742               /* This instruction will set the register to be all
8743                  ones.  */
8744               tmp.X_op = O_constant;
8745               tmp.X_add_number = (offsetT) -1;
8746               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8747               if (bit != 0)
8748                 {
8749                   bit += shift;
8750                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8751                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8752                 }
8753               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8754                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8755               return;
8756             }
8757         }
8758
8759       /* Sign extend hi32 before calling load_register, because we can
8760          generally get better code when we load a sign extended value.  */
8761       if ((hi32.X_add_number & 0x80000000) != 0)
8762         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8763       load_register (reg, &hi32, 0);
8764       freg = reg;
8765     }
8766   if ((lo32.X_add_number & 0xffff0000) == 0)
8767     {
8768       if (freg != 0)
8769         {
8770           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8771           freg = reg;
8772         }
8773     }
8774   else
8775     {
8776       expressionS mid16;
8777
8778       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8779         {
8780           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8781           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8782           return;
8783         }
8784
8785       if (freg != 0)
8786         {
8787           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8788           freg = reg;
8789         }
8790       mid16 = lo32;
8791       mid16.X_add_number >>= 16;
8792       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8793       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8794       freg = reg;
8795     }
8796   if ((lo32.X_add_number & 0xffff) != 0)
8797     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8798 }
8799
8800 static inline void
8801 load_delay_nop (void)
8802 {
8803   if (!gpr_interlocks)
8804     macro_build (NULL, "nop", "");
8805 }
8806
8807 /* Load an address into a register.  */
8808
8809 static void
8810 load_address (int reg, expressionS *ep, int *used_at)
8811 {
8812   if (ep->X_op != O_constant
8813       && ep->X_op != O_symbol)
8814     {
8815       as_bad (_("expression too complex"));
8816       ep->X_op = O_constant;
8817     }
8818
8819   if (ep->X_op == O_constant)
8820     {
8821       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8822       return;
8823     }
8824
8825   if (mips_pic == NO_PIC)
8826     {
8827       /* If this is a reference to a GP relative symbol, we want
8828            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8829          Otherwise we want
8830            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8831            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8832          If we have an addend, we always use the latter form.
8833
8834          With 64bit address space and a usable $at we want
8835            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8836            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8837            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8838            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8839            dsll32       $reg,0
8840            daddu        $reg,$reg,$at
8841
8842          If $at is already in use, we use a path which is suboptimal
8843          on superscalar processors.
8844            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8845            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8846            dsll         $reg,16
8847            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8848            dsll         $reg,16
8849            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8850
8851          For GP relative symbols in 64bit address space we can use
8852          the same sequence as in 32bit address space.  */
8853       if (HAVE_64BIT_SYMBOLS)
8854         {
8855           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8856               && !nopic_need_relax (ep->X_add_symbol, 1))
8857             {
8858               relax_start (ep->X_add_symbol);
8859               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8860                            mips_gp_register, BFD_RELOC_GPREL16);
8861               relax_switch ();
8862             }
8863
8864           if (*used_at == 0 && mips_opts.at)
8865             {
8866               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8867               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8868               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8869                            BFD_RELOC_MIPS_HIGHER);
8870               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8871               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8872               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8873               *used_at = 1;
8874             }
8875           else
8876             {
8877               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8878               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8879                            BFD_RELOC_MIPS_HIGHER);
8880               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8881               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8882               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8883               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8884             }
8885
8886           if (mips_relax.sequence)
8887             relax_end ();
8888         }
8889       else
8890         {
8891           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8892               && !nopic_need_relax (ep->X_add_symbol, 1))
8893             {
8894               relax_start (ep->X_add_symbol);
8895               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8896                            mips_gp_register, BFD_RELOC_GPREL16);
8897               relax_switch ();
8898             }
8899           macro_build_lui (ep, reg);
8900           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8901                        reg, reg, BFD_RELOC_LO16);
8902           if (mips_relax.sequence)
8903             relax_end ();
8904         }
8905     }
8906   else if (!mips_big_got)
8907     {
8908       expressionS ex;
8909
8910       /* If this is a reference to an external symbol, we want
8911            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8912          Otherwise we want
8913            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8914            nop
8915            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8916          If there is a constant, it must be added in after.
8917
8918          If we have NewABI, we want
8919            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8920          unless we're referencing a global symbol with a non-zero
8921          offset, in which case cst must be added separately.  */
8922       if (HAVE_NEWABI)
8923         {
8924           if (ep->X_add_number)
8925             {
8926               ex.X_add_number = ep->X_add_number;
8927               ep->X_add_number = 0;
8928               relax_start (ep->X_add_symbol);
8929               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8930                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8931               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8932                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8933               ex.X_op = O_constant;
8934               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8935                            reg, reg, BFD_RELOC_LO16);
8936               ep->X_add_number = ex.X_add_number;
8937               relax_switch ();
8938             }
8939           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8940                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8941           if (mips_relax.sequence)
8942             relax_end ();
8943         }
8944       else
8945         {
8946           ex.X_add_number = ep->X_add_number;
8947           ep->X_add_number = 0;
8948           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8949                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8950           load_delay_nop ();
8951           relax_start (ep->X_add_symbol);
8952           relax_switch ();
8953           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8954                        BFD_RELOC_LO16);
8955           relax_end ();
8956
8957           if (ex.X_add_number != 0)
8958             {
8959               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8960                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8961               ex.X_op = O_constant;
8962               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8963                            reg, reg, BFD_RELOC_LO16);
8964             }
8965         }
8966     }
8967   else if (mips_big_got)
8968     {
8969       expressionS ex;
8970
8971       /* This is the large GOT case.  If this is a reference to an
8972          external symbol, we want
8973            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8974            addu         $reg,$reg,$gp
8975            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8976
8977          Otherwise, for a reference to a local symbol in old ABI, we want
8978            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8979            nop
8980            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8981          If there is a constant, it must be added in after.
8982
8983          In the NewABI, for local symbols, with or without offsets, we want:
8984            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8985            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8986       */
8987       if (HAVE_NEWABI)
8988         {
8989           ex.X_add_number = ep->X_add_number;
8990           ep->X_add_number = 0;
8991           relax_start (ep->X_add_symbol);
8992           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8993           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8994                        reg, reg, mips_gp_register);
8995           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8996                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8997           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8998             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8999           else if (ex.X_add_number)
9000             {
9001               ex.X_op = O_constant;
9002               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9003                            BFD_RELOC_LO16);
9004             }
9005
9006           ep->X_add_number = ex.X_add_number;
9007           relax_switch ();
9008           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9009                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9010           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9011                        BFD_RELOC_MIPS_GOT_OFST);
9012           relax_end ();
9013         }
9014       else
9015         {
9016           ex.X_add_number = ep->X_add_number;
9017           ep->X_add_number = 0;
9018           relax_start (ep->X_add_symbol);
9019           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9020           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9021                        reg, reg, mips_gp_register);
9022           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9023                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9024           relax_switch ();
9025           if (reg_needs_delay (mips_gp_register))
9026             {
9027               /* We need a nop before loading from $gp.  This special
9028                  check is required because the lui which starts the main
9029                  instruction stream does not refer to $gp, and so will not
9030                  insert the nop which may be required.  */
9031               macro_build (NULL, "nop", "");
9032             }
9033           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9034                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9035           load_delay_nop ();
9036           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9037                        BFD_RELOC_LO16);
9038           relax_end ();
9039
9040           if (ex.X_add_number != 0)
9041             {
9042               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9043                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9044               ex.X_op = O_constant;
9045               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9046                            BFD_RELOC_LO16);
9047             }
9048         }
9049     }
9050   else
9051     abort ();
9052
9053   if (!mips_opts.at && *used_at == 1)
9054     as_bad (_("macro used $at after \".set noat\""));
9055 }
9056
9057 /* Move the contents of register SOURCE into register DEST.  */
9058
9059 static void
9060 move_register (int dest, int source)
9061 {
9062   /* Prefer to use a 16-bit microMIPS instruction unless the previous
9063      instruction specifically requires a 32-bit one.  */
9064   if (mips_opts.micromips
9065       && !mips_opts.insn32
9066       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9067     macro_build (NULL, "move", "mp,mj", dest, source);
9068   else
9069     macro_build (NULL, GPR_SIZE == 32 ? "addu" : "daddu", "d,v,t",
9070                  dest, source, 0);
9071 }
9072
9073 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
9074    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
9075    The two alternatives are:
9076
9077    Global symbol                Local sybmol
9078    -------------                ------------
9079    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
9080    ...                          ...
9081    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
9082
9083    load_got_offset emits the first instruction and add_got_offset
9084    emits the second for a 16-bit offset or add_got_offset_hilo emits
9085    a sequence to add a 32-bit offset using a scratch register.  */
9086
9087 static void
9088 load_got_offset (int dest, expressionS *local)
9089 {
9090   expressionS global;
9091
9092   global = *local;
9093   global.X_add_number = 0;
9094
9095   relax_start (local->X_add_symbol);
9096   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9097                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9098   relax_switch ();
9099   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9100                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9101   relax_end ();
9102 }
9103
9104 static void
9105 add_got_offset (int dest, expressionS *local)
9106 {
9107   expressionS global;
9108
9109   global.X_op = O_constant;
9110   global.X_op_symbol = NULL;
9111   global.X_add_symbol = NULL;
9112   global.X_add_number = local->X_add_number;
9113
9114   relax_start (local->X_add_symbol);
9115   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
9116                dest, dest, BFD_RELOC_LO16);
9117   relax_switch ();
9118   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
9119   relax_end ();
9120 }
9121
9122 static void
9123 add_got_offset_hilo (int dest, expressionS *local, int tmp)
9124 {
9125   expressionS global;
9126   int hold_mips_optimize;
9127
9128   global.X_op = O_constant;
9129   global.X_op_symbol = NULL;
9130   global.X_add_symbol = NULL;
9131   global.X_add_number = local->X_add_number;
9132
9133   relax_start (local->X_add_symbol);
9134   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
9135   relax_switch ();
9136   /* Set mips_optimize around the lui instruction to avoid
9137      inserting an unnecessary nop after the lw.  */
9138   hold_mips_optimize = mips_optimize;
9139   mips_optimize = 2;
9140   macro_build_lui (&global, tmp);
9141   mips_optimize = hold_mips_optimize;
9142   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
9143   relax_end ();
9144
9145   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
9146 }
9147
9148 /* Emit a sequence of instructions to emulate a branch likely operation.
9149    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
9150    is its complementing branch with the original condition negated.
9151    CALL is set if the original branch specified the link operation.
9152    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
9153
9154    Code like this is produced in the noreorder mode:
9155
9156         BRNEG   <args>, 1f
9157          nop
9158         b       <sym>
9159          delay slot (executed only if branch taken)
9160     1:
9161
9162    or, if CALL is set:
9163
9164         BRNEG   <args>, 1f
9165          nop
9166         bal     <sym>
9167          delay slot (executed only if branch taken)
9168     1:
9169
9170    In the reorder mode the delay slot would be filled with a nop anyway,
9171    so code produced is simply:
9172
9173         BR      <args>, <sym>
9174          nop
9175
9176    This function is used when producing code for the microMIPS ASE that
9177    does not implement branch likely instructions in hardware.  */
9178
9179 static void
9180 macro_build_branch_likely (const char *br, const char *brneg,
9181                            int call, expressionS *ep, const char *fmt,
9182                            unsigned int sreg, unsigned int treg)
9183 {
9184   int noreorder = mips_opts.noreorder;
9185   expressionS expr1;
9186
9187   gas_assert (mips_opts.micromips);
9188   start_noreorder ();
9189   if (noreorder)
9190     {
9191       micromips_label_expr (&expr1);
9192       macro_build (&expr1, brneg, fmt, sreg, treg);
9193       macro_build (NULL, "nop", "");
9194       macro_build (ep, call ? "bal" : "b", "p");
9195
9196       /* Set to true so that append_insn adds a label.  */
9197       emit_branch_likely_macro = TRUE;
9198     }
9199   else
9200     {
9201       macro_build (ep, br, fmt, sreg, treg);
9202       macro_build (NULL, "nop", "");
9203     }
9204   end_noreorder ();
9205 }
9206
9207 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
9208    the condition code tested.  EP specifies the branch target.  */
9209
9210 static void
9211 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
9212 {
9213   const int call = 0;
9214   const char *brneg;
9215   const char *br;
9216
9217   switch (type)
9218     {
9219     case M_BC1FL:
9220       br = "bc1f";
9221       brneg = "bc1t";
9222       break;
9223     case M_BC1TL:
9224       br = "bc1t";
9225       brneg = "bc1f";
9226       break;
9227     case M_BC2FL:
9228       br = "bc2f";
9229       brneg = "bc2t";
9230       break;
9231     case M_BC2TL:
9232       br = "bc2t";
9233       brneg = "bc2f";
9234       break;
9235     default:
9236       abort ();
9237     }
9238   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
9239 }
9240
9241 /* Emit a two-argument branch macro specified by TYPE, using SREG as
9242    the register tested.  EP specifies the branch target.  */
9243
9244 static void
9245 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
9246 {
9247   const char *brneg = NULL;
9248   const char *br;
9249   int call = 0;
9250
9251   switch (type)
9252     {
9253     case M_BGEZ:
9254       br = "bgez";
9255       break;
9256     case M_BGEZL:
9257       br = mips_opts.micromips ? "bgez" : "bgezl";
9258       brneg = "bltz";
9259       break;
9260     case M_BGEZALL:
9261       gas_assert (mips_opts.micromips);
9262       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9263       brneg = "bltz";
9264       call = 1;
9265       break;
9266     case M_BGTZ:
9267       br = "bgtz";
9268       break;
9269     case M_BGTZL:
9270       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9271       brneg = "blez";
9272       break;
9273     case M_BLEZ:
9274       br = "blez";
9275       break;
9276     case M_BLEZL:
9277       br = mips_opts.micromips ? "blez" : "blezl";
9278       brneg = "bgtz";
9279       break;
9280     case M_BLTZ:
9281       br = "bltz";
9282       break;
9283     case M_BLTZL:
9284       br = mips_opts.micromips ? "bltz" : "bltzl";
9285       brneg = "bgez";
9286       break;
9287     case M_BLTZALL:
9288       gas_assert (mips_opts.micromips);
9289       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9290       brneg = "bgez";
9291       call = 1;
9292       break;
9293     default:
9294       abort ();
9295     }
9296   if (mips_opts.micromips && brneg)
9297     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9298   else
9299     macro_build (ep, br, "s,p", sreg);
9300 }
9301
9302 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9303    TREG as the registers tested.  EP specifies the branch target.  */
9304
9305 static void
9306 macro_build_branch_rsrt (int type, expressionS *ep,
9307                          unsigned int sreg, unsigned int treg)
9308 {
9309   const char *brneg = NULL;
9310   const int call = 0;
9311   const char *br;
9312
9313   switch (type)
9314     {
9315     case M_BEQ:
9316     case M_BEQ_I:
9317       br = "beq";
9318       break;
9319     case M_BEQL:
9320     case M_BEQL_I:
9321       br = mips_opts.micromips ? "beq" : "beql";
9322       brneg = "bne";
9323       break;
9324     case M_BNE:
9325     case M_BNE_I:
9326       br = "bne";
9327       break;
9328     case M_BNEL:
9329     case M_BNEL_I:
9330       br = mips_opts.micromips ? "bne" : "bnel";
9331       brneg = "beq";
9332       break;
9333     default:
9334       abort ();
9335     }
9336   if (mips_opts.micromips && brneg)
9337     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9338   else
9339     macro_build (ep, br, "s,t,p", sreg, treg);
9340 }
9341
9342 /* Return the high part that should be loaded in order to make the low
9343    part of VALUE accessible using an offset of OFFBITS bits.  */
9344
9345 static offsetT
9346 offset_high_part (offsetT value, unsigned int offbits)
9347 {
9348   offsetT bias;
9349   addressT low_mask;
9350
9351   if (offbits == 0)
9352     return value;
9353   bias = 1 << (offbits - 1);
9354   low_mask = bias * 2 - 1;
9355   return (value + bias) & ~low_mask;
9356 }
9357
9358 /* Return true if the value stored in offset_expr and offset_reloc
9359    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9360    amount that the caller wants to add without inducing overflow
9361    and ALIGN is the known alignment of the value in bytes.  */
9362
9363 static bfd_boolean
9364 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9365 {
9366   if (offbits == 16)
9367     {
9368       /* Accept any relocation operator if overflow isn't a concern.  */
9369       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9370         return TRUE;
9371
9372       /* These relocations are guaranteed not to overflow in correct links.  */
9373       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9374           || gprel16_reloc_p (*offset_reloc))
9375         return TRUE;
9376     }
9377   if (offset_expr.X_op == O_constant
9378       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9379       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9380     return TRUE;
9381   return FALSE;
9382 }
9383
9384 /*
9385  *                      Build macros
9386  *   This routine implements the seemingly endless macro or synthesized
9387  * instructions and addressing modes in the mips assembly language. Many
9388  * of these macros are simple and are similar to each other. These could
9389  * probably be handled by some kind of table or grammar approach instead of
9390  * this verbose method. Others are not simple macros but are more like
9391  * optimizing code generation.
9392  *   One interesting optimization is when several store macros appear
9393  * consecutively that would load AT with the upper half of the same address.
9394  * The ensuing load upper instructions are ommited. This implies some kind
9395  * of global optimization. We currently only optimize within a single macro.
9396  *   For many of the load and store macros if the address is specified as a
9397  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9398  * first load register 'at' with zero and use it as the base register. The
9399  * mips assembler simply uses register $zero. Just one tiny optimization
9400  * we're missing.
9401  */
9402 static void
9403 macro (struct mips_cl_insn *ip, char *str)
9404 {
9405   const struct mips_operand_array *operands;
9406   unsigned int breg, i;
9407   unsigned int tempreg;
9408   int mask;
9409   int used_at = 0;
9410   expressionS label_expr;
9411   expressionS expr1;
9412   expressionS *ep;
9413   const char *s;
9414   const char *s2;
9415   const char *fmt;
9416   int likely = 0;
9417   int coproc = 0;
9418   int offbits = 16;
9419   int call = 0;
9420   int jals = 0;
9421   int dbl = 0;
9422   int imm = 0;
9423   int ust = 0;
9424   int lp = 0;
9425   bfd_boolean large_offset;
9426   int off;
9427   int hold_mips_optimize;
9428   unsigned int align;
9429   unsigned int op[MAX_OPERANDS];
9430
9431   gas_assert (! mips_opts.mips16);
9432
9433   operands = insn_operands (ip);
9434   for (i = 0; i < MAX_OPERANDS; i++)
9435     if (operands->operand[i])
9436       op[i] = insn_extract_operand (ip, operands->operand[i]);
9437     else
9438       op[i] = -1;
9439
9440   mask = ip->insn_mo->mask;
9441
9442   label_expr.X_op = O_constant;
9443   label_expr.X_op_symbol = NULL;
9444   label_expr.X_add_symbol = NULL;
9445   label_expr.X_add_number = 0;
9446
9447   expr1.X_op = O_constant;
9448   expr1.X_op_symbol = NULL;
9449   expr1.X_add_symbol = NULL;
9450   expr1.X_add_number = 1;
9451   align = 1;
9452
9453   switch (mask)
9454     {
9455     case M_DABS:
9456       dbl = 1;
9457     case M_ABS:
9458       /*    bgez    $a0,1f
9459             move    v0,$a0
9460             sub     v0,$zero,$a0
9461          1:
9462        */
9463
9464       start_noreorder ();
9465
9466       if (mips_opts.micromips)
9467         micromips_label_expr (&label_expr);
9468       else
9469         label_expr.X_add_number = 8;
9470       macro_build (&label_expr, "bgez", "s,p", op[1]);
9471       if (op[0] == op[1])
9472         macro_build (NULL, "nop", "");
9473       else
9474         move_register (op[0], op[1]);
9475       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9476       if (mips_opts.micromips)
9477         micromips_add_label ();
9478
9479       end_noreorder ();
9480       break;
9481
9482     case M_ADD_I:
9483       s = "addi";
9484       s2 = "add";
9485       goto do_addi;
9486     case M_ADDU_I:
9487       s = "addiu";
9488       s2 = "addu";
9489       goto do_addi;
9490     case M_DADD_I:
9491       dbl = 1;
9492       s = "daddi";
9493       s2 = "dadd";
9494       if (!mips_opts.micromips)
9495         goto do_addi;
9496       if (imm_expr.X_add_number >= -0x200
9497           && imm_expr.X_add_number < 0x200)
9498         {
9499           macro_build (NULL, s, "t,r,.", op[0], op[1],
9500                        (int) imm_expr.X_add_number);
9501           break;
9502         }
9503       goto do_addi_i;
9504     case M_DADDU_I:
9505       dbl = 1;
9506       s = "daddiu";
9507       s2 = "daddu";
9508     do_addi:
9509       if (imm_expr.X_add_number >= -0x8000
9510           && imm_expr.X_add_number < 0x8000)
9511         {
9512           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9513           break;
9514         }
9515     do_addi_i:
9516       used_at = 1;
9517       load_register (AT, &imm_expr, dbl);
9518       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9519       break;
9520
9521     case M_AND_I:
9522       s = "andi";
9523       s2 = "and";
9524       goto do_bit;
9525     case M_OR_I:
9526       s = "ori";
9527       s2 = "or";
9528       goto do_bit;
9529     case M_NOR_I:
9530       s = "";
9531       s2 = "nor";
9532       goto do_bit;
9533     case M_XOR_I:
9534       s = "xori";
9535       s2 = "xor";
9536     do_bit:
9537       if (imm_expr.X_add_number >= 0
9538           && imm_expr.X_add_number < 0x10000)
9539         {
9540           if (mask != M_NOR_I)
9541             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9542           else
9543             {
9544               macro_build (&imm_expr, "ori", "t,r,i",
9545                            op[0], op[1], BFD_RELOC_LO16);
9546               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9547             }
9548           break;
9549         }
9550
9551       used_at = 1;
9552       load_register (AT, &imm_expr, GPR_SIZE == 64);
9553       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9554       break;
9555
9556     case M_BALIGN:
9557       switch (imm_expr.X_add_number)
9558         {
9559         case 0:
9560           macro_build (NULL, "nop", "");
9561           break;
9562         case 2:
9563           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9564           break;
9565         case 1:
9566         case 3:
9567           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9568                        (int) imm_expr.X_add_number);
9569           break;
9570         default:
9571           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9572                   (unsigned long) imm_expr.X_add_number);
9573           break;
9574         }
9575       break;
9576
9577     case M_BC1FL:
9578     case M_BC1TL:
9579     case M_BC2FL:
9580     case M_BC2TL:
9581       gas_assert (mips_opts.micromips);
9582       macro_build_branch_ccl (mask, &offset_expr,
9583                               EXTRACT_OPERAND (1, BCC, *ip));
9584       break;
9585
9586     case M_BEQ_I:
9587     case M_BEQL_I:
9588     case M_BNE_I:
9589     case M_BNEL_I:
9590       if (imm_expr.X_add_number == 0)
9591         op[1] = 0;
9592       else
9593         {
9594           op[1] = AT;
9595           used_at = 1;
9596           load_register (op[1], &imm_expr, GPR_SIZE == 64);
9597         }
9598       /* Fall through.  */
9599     case M_BEQL:
9600     case M_BNEL:
9601       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9602       break;
9603
9604     case M_BGEL:
9605       likely = 1;
9606     case M_BGE:
9607       if (op[1] == 0)
9608         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9609       else if (op[0] == 0)
9610         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9611       else
9612         {
9613           used_at = 1;
9614           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9615           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9616                                    &offset_expr, AT, ZERO);
9617         }
9618       break;
9619
9620     case M_BGEZL:
9621     case M_BGEZALL:
9622     case M_BGTZL:
9623     case M_BLEZL:
9624     case M_BLTZL:
9625     case M_BLTZALL:
9626       macro_build_branch_rs (mask, &offset_expr, op[0]);
9627       break;
9628
9629     case M_BGTL_I:
9630       likely = 1;
9631     case M_BGT_I:
9632       /* Check for > max integer.  */
9633       if (imm_expr.X_add_number >= GPR_SMAX)
9634         {
9635         do_false:
9636           /* Result is always false.  */
9637           if (! likely)
9638             macro_build (NULL, "nop", "");
9639           else
9640             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9641           break;
9642         }
9643       ++imm_expr.X_add_number;
9644       /* FALLTHROUGH */
9645     case M_BGE_I:
9646     case M_BGEL_I:
9647       if (mask == M_BGEL_I)
9648         likely = 1;
9649       if (imm_expr.X_add_number == 0)
9650         {
9651           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9652                                  &offset_expr, op[0]);
9653           break;
9654         }
9655       if (imm_expr.X_add_number == 1)
9656         {
9657           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9658                                  &offset_expr, op[0]);
9659           break;
9660         }
9661       if (imm_expr.X_add_number <= GPR_SMIN)
9662         {
9663         do_true:
9664           /* result is always true */
9665           as_warn (_("branch %s is always true"), ip->insn_mo->name);
9666           macro_build (&offset_expr, "b", "p");
9667           break;
9668         }
9669       used_at = 1;
9670       set_at (op[0], 0);
9671       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9672                                &offset_expr, AT, ZERO);
9673       break;
9674
9675     case M_BGEUL:
9676       likely = 1;
9677     case M_BGEU:
9678       if (op[1] == 0)
9679         goto do_true;
9680       else if (op[0] == 0)
9681         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9682                                  &offset_expr, ZERO, op[1]);
9683       else
9684         {
9685           used_at = 1;
9686           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9687           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9688                                    &offset_expr, AT, ZERO);
9689         }
9690       break;
9691
9692     case M_BGTUL_I:
9693       likely = 1;
9694     case M_BGTU_I:
9695       if (op[0] == 0
9696           || (GPR_SIZE == 32
9697               && imm_expr.X_add_number == -1))
9698         goto do_false;
9699       ++imm_expr.X_add_number;
9700       /* FALLTHROUGH */
9701     case M_BGEU_I:
9702     case M_BGEUL_I:
9703       if (mask == M_BGEUL_I)
9704         likely = 1;
9705       if (imm_expr.X_add_number == 0)
9706         goto do_true;
9707       else if (imm_expr.X_add_number == 1)
9708         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9709                                  &offset_expr, op[0], ZERO);
9710       else
9711         {
9712           used_at = 1;
9713           set_at (op[0], 1);
9714           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9715                                    &offset_expr, AT, ZERO);
9716         }
9717       break;
9718
9719     case M_BGTL:
9720       likely = 1;
9721     case M_BGT:
9722       if (op[1] == 0)
9723         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9724       else if (op[0] == 0)
9725         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9726       else
9727         {
9728           used_at = 1;
9729           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9730           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9731                                    &offset_expr, AT, ZERO);
9732         }
9733       break;
9734
9735     case M_BGTUL:
9736       likely = 1;
9737     case M_BGTU:
9738       if (op[1] == 0)
9739         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9740                                  &offset_expr, op[0], ZERO);
9741       else if (op[0] == 0)
9742         goto do_false;
9743       else
9744         {
9745           used_at = 1;
9746           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9747           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9748                                    &offset_expr, AT, ZERO);
9749         }
9750       break;
9751
9752     case M_BLEL:
9753       likely = 1;
9754     case M_BLE:
9755       if (op[1] == 0)
9756         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9757       else if (op[0] == 0)
9758         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9759       else
9760         {
9761           used_at = 1;
9762           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9763           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9764                                    &offset_expr, AT, ZERO);
9765         }
9766       break;
9767
9768     case M_BLEL_I:
9769       likely = 1;
9770     case M_BLE_I:
9771       if (imm_expr.X_add_number >= GPR_SMAX)
9772         goto do_true;
9773       ++imm_expr.X_add_number;
9774       /* FALLTHROUGH */
9775     case M_BLT_I:
9776     case M_BLTL_I:
9777       if (mask == M_BLTL_I)
9778         likely = 1;
9779       if (imm_expr.X_add_number == 0)
9780         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9781       else if (imm_expr.X_add_number == 1)
9782         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9783       else
9784         {
9785           used_at = 1;
9786           set_at (op[0], 0);
9787           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9788                                    &offset_expr, AT, ZERO);
9789         }
9790       break;
9791
9792     case M_BLEUL:
9793       likely = 1;
9794     case M_BLEU:
9795       if (op[1] == 0)
9796         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9797                                  &offset_expr, op[0], ZERO);
9798       else if (op[0] == 0)
9799         goto do_true;
9800       else
9801         {
9802           used_at = 1;
9803           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9804           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9805                                    &offset_expr, AT, ZERO);
9806         }
9807       break;
9808
9809     case M_BLEUL_I:
9810       likely = 1;
9811     case M_BLEU_I:
9812       if (op[0] == 0
9813           || (GPR_SIZE == 32
9814               && imm_expr.X_add_number == -1))
9815         goto do_true;
9816       ++imm_expr.X_add_number;
9817       /* FALLTHROUGH */
9818     case M_BLTU_I:
9819     case M_BLTUL_I:
9820       if (mask == M_BLTUL_I)
9821         likely = 1;
9822       if (imm_expr.X_add_number == 0)
9823         goto do_false;
9824       else if (imm_expr.X_add_number == 1)
9825         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9826                                  &offset_expr, op[0], ZERO);
9827       else
9828         {
9829           used_at = 1;
9830           set_at (op[0], 1);
9831           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9832                                    &offset_expr, AT, ZERO);
9833         }
9834       break;
9835
9836     case M_BLTL:
9837       likely = 1;
9838     case M_BLT:
9839       if (op[1] == 0)
9840         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9841       else if (op[0] == 0)
9842         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9843       else
9844         {
9845           used_at = 1;
9846           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9847           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9848                                    &offset_expr, AT, ZERO);
9849         }
9850       break;
9851
9852     case M_BLTUL:
9853       likely = 1;
9854     case M_BLTU:
9855       if (op[1] == 0)
9856         goto do_false;
9857       else if (op[0] == 0)
9858         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9859                                  &offset_expr, ZERO, op[1]);
9860       else
9861         {
9862           used_at = 1;
9863           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9864           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9865                                    &offset_expr, AT, ZERO);
9866         }
9867       break;
9868
9869     case M_DDIV_3:
9870       dbl = 1;
9871     case M_DIV_3:
9872       s = "mflo";
9873       goto do_div3;
9874     case M_DREM_3:
9875       dbl = 1;
9876     case M_REM_3:
9877       s = "mfhi";
9878     do_div3:
9879       if (op[2] == 0)
9880         {
9881           as_warn (_("divide by zero"));
9882           if (mips_trap)
9883             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9884           else
9885             macro_build (NULL, "break", BRK_FMT, 7);
9886           break;
9887         }
9888
9889       start_noreorder ();
9890       if (mips_trap)
9891         {
9892           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9893           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9894         }
9895       else
9896         {
9897           if (mips_opts.micromips)
9898             micromips_label_expr (&label_expr);
9899           else
9900             label_expr.X_add_number = 8;
9901           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9902           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9903           macro_build (NULL, "break", BRK_FMT, 7);
9904           if (mips_opts.micromips)
9905             micromips_add_label ();
9906         }
9907       expr1.X_add_number = -1;
9908       used_at = 1;
9909       load_register (AT, &expr1, dbl);
9910       if (mips_opts.micromips)
9911         micromips_label_expr (&label_expr);
9912       else
9913         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9914       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9915       if (dbl)
9916         {
9917           expr1.X_add_number = 1;
9918           load_register (AT, &expr1, dbl);
9919           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9920         }
9921       else
9922         {
9923           expr1.X_add_number = 0x80000000;
9924           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9925         }
9926       if (mips_trap)
9927         {
9928           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9929           /* We want to close the noreorder block as soon as possible, so
9930              that later insns are available for delay slot filling.  */
9931           end_noreorder ();
9932         }
9933       else
9934         {
9935           if (mips_opts.micromips)
9936             micromips_label_expr (&label_expr);
9937           else
9938             label_expr.X_add_number = 8;
9939           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9940           macro_build (NULL, "nop", "");
9941
9942           /* We want to close the noreorder block as soon as possible, so
9943              that later insns are available for delay slot filling.  */
9944           end_noreorder ();
9945
9946           macro_build (NULL, "break", BRK_FMT, 6);
9947         }
9948       if (mips_opts.micromips)
9949         micromips_add_label ();
9950       macro_build (NULL, s, MFHL_FMT, op[0]);
9951       break;
9952
9953     case M_DIV_3I:
9954       s = "div";
9955       s2 = "mflo";
9956       goto do_divi;
9957     case M_DIVU_3I:
9958       s = "divu";
9959       s2 = "mflo";
9960       goto do_divi;
9961     case M_REM_3I:
9962       s = "div";
9963       s2 = "mfhi";
9964       goto do_divi;
9965     case M_REMU_3I:
9966       s = "divu";
9967       s2 = "mfhi";
9968       goto do_divi;
9969     case M_DDIV_3I:
9970       dbl = 1;
9971       s = "ddiv";
9972       s2 = "mflo";
9973       goto do_divi;
9974     case M_DDIVU_3I:
9975       dbl = 1;
9976       s = "ddivu";
9977       s2 = "mflo";
9978       goto do_divi;
9979     case M_DREM_3I:
9980       dbl = 1;
9981       s = "ddiv";
9982       s2 = "mfhi";
9983       goto do_divi;
9984     case M_DREMU_3I:
9985       dbl = 1;
9986       s = "ddivu";
9987       s2 = "mfhi";
9988     do_divi:
9989       if (imm_expr.X_add_number == 0)
9990         {
9991           as_warn (_("divide by zero"));
9992           if (mips_trap)
9993             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9994           else
9995             macro_build (NULL, "break", BRK_FMT, 7);
9996           break;
9997         }
9998       if (imm_expr.X_add_number == 1)
9999         {
10000           if (strcmp (s2, "mflo") == 0)
10001             move_register (op[0], op[1]);
10002           else
10003             move_register (op[0], ZERO);
10004           break;
10005         }
10006       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
10007         {
10008           if (strcmp (s2, "mflo") == 0)
10009             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
10010           else
10011             move_register (op[0], ZERO);
10012           break;
10013         }
10014
10015       used_at = 1;
10016       load_register (AT, &imm_expr, dbl);
10017       macro_build (NULL, s, "z,s,t", op[1], AT);
10018       macro_build (NULL, s2, MFHL_FMT, op[0]);
10019       break;
10020
10021     case M_DIVU_3:
10022       s = "divu";
10023       s2 = "mflo";
10024       goto do_divu3;
10025     case M_REMU_3:
10026       s = "divu";
10027       s2 = "mfhi";
10028       goto do_divu3;
10029     case M_DDIVU_3:
10030       s = "ddivu";
10031       s2 = "mflo";
10032       goto do_divu3;
10033     case M_DREMU_3:
10034       s = "ddivu";
10035       s2 = "mfhi";
10036     do_divu3:
10037       start_noreorder ();
10038       if (mips_trap)
10039         {
10040           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10041           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10042           /* We want to close the noreorder block as soon as possible, so
10043              that later insns are available for delay slot filling.  */
10044           end_noreorder ();
10045         }
10046       else
10047         {
10048           if (mips_opts.micromips)
10049             micromips_label_expr (&label_expr);
10050           else
10051             label_expr.X_add_number = 8;
10052           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10053           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10054
10055           /* We want to close the noreorder block as soon as possible, so
10056              that later insns are available for delay slot filling.  */
10057           end_noreorder ();
10058           macro_build (NULL, "break", BRK_FMT, 7);
10059           if (mips_opts.micromips)
10060             micromips_add_label ();
10061         }
10062       macro_build (NULL, s2, MFHL_FMT, op[0]);
10063       break;
10064
10065     case M_DLCA_AB:
10066       dbl = 1;
10067     case M_LCA_AB:
10068       call = 1;
10069       goto do_la;
10070     case M_DLA_AB:
10071       dbl = 1;
10072     case M_LA_AB:
10073     do_la:
10074       /* Load the address of a symbol into a register.  If breg is not
10075          zero, we then add a base register to it.  */
10076
10077       breg = op[2];
10078       if (dbl && GPR_SIZE == 32)
10079         as_warn (_("dla used to load 32-bit register"));
10080
10081       if (!dbl && HAVE_64BIT_OBJECTS)
10082         as_warn (_("la used to load 64-bit address"));
10083
10084       if (small_offset_p (0, align, 16))
10085         {
10086           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
10087                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10088           break;
10089         }
10090
10091       if (mips_opts.at && (op[0] == breg))
10092         {
10093           tempreg = AT;
10094           used_at = 1;
10095         }
10096       else
10097         tempreg = op[0];
10098
10099       if (offset_expr.X_op != O_symbol
10100           && offset_expr.X_op != O_constant)
10101         {
10102           as_bad (_("expression too complex"));
10103           offset_expr.X_op = O_constant;
10104         }
10105
10106       if (offset_expr.X_op == O_constant)
10107         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
10108       else if (mips_pic == NO_PIC)
10109         {
10110           /* If this is a reference to a GP relative symbol, we want
10111                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
10112              Otherwise we want
10113                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10114                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10115              If we have a constant, we need two instructions anyhow,
10116              so we may as well always use the latter form.
10117
10118              With 64bit address space and a usable $at we want
10119                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10120                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10121                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10122                daddiu   $at,<sym>               (BFD_RELOC_LO16)
10123                dsll32   $tempreg,0
10124                daddu    $tempreg,$tempreg,$at
10125
10126              If $at is already in use, we use a path which is suboptimal
10127              on superscalar processors.
10128                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10129                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10130                dsll     $tempreg,16
10131                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10132                dsll     $tempreg,16
10133                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
10134
10135              For GP relative symbols in 64bit address space we can use
10136              the same sequence as in 32bit address space.  */
10137           if (HAVE_64BIT_SYMBOLS)
10138             {
10139               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10140                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10141                 {
10142                   relax_start (offset_expr.X_add_symbol);
10143                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10144                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10145                   relax_switch ();
10146                 }
10147
10148               if (used_at == 0 && mips_opts.at)
10149                 {
10150                   macro_build (&offset_expr, "lui", LUI_FMT,
10151                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10152                   macro_build (&offset_expr, "lui", LUI_FMT,
10153                                AT, BFD_RELOC_HI16_S);
10154                   macro_build (&offset_expr, "daddiu", "t,r,j",
10155                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10156                   macro_build (&offset_expr, "daddiu", "t,r,j",
10157                                AT, AT, BFD_RELOC_LO16);
10158                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10159                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10160                   used_at = 1;
10161                 }
10162               else
10163                 {
10164                   macro_build (&offset_expr, "lui", LUI_FMT,
10165                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10166                   macro_build (&offset_expr, "daddiu", "t,r,j",
10167                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10168                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10169                   macro_build (&offset_expr, "daddiu", "t,r,j",
10170                                tempreg, tempreg, BFD_RELOC_HI16_S);
10171                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10172                   macro_build (&offset_expr, "daddiu", "t,r,j",
10173                                tempreg, tempreg, BFD_RELOC_LO16);
10174                 }
10175
10176               if (mips_relax.sequence)
10177                 relax_end ();
10178             }
10179           else
10180             {
10181               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10182                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10183                 {
10184                   relax_start (offset_expr.X_add_symbol);
10185                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10186                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10187                   relax_switch ();
10188                 }
10189               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10190                 as_bad (_("offset too large"));
10191               macro_build_lui (&offset_expr, tempreg);
10192               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10193                            tempreg, tempreg, BFD_RELOC_LO16);
10194               if (mips_relax.sequence)
10195                 relax_end ();
10196             }
10197         }
10198       else if (!mips_big_got && !HAVE_NEWABI)
10199         {
10200           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10201
10202           /* If this is a reference to an external symbol, and there
10203              is no constant, we want
10204                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10205              or for lca or if tempreg is PIC_CALL_REG
10206                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10207              For a local symbol, we want
10208                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10209                nop
10210                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10211
10212              If we have a small constant, and this is a reference to
10213              an external symbol, we want
10214                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10215                nop
10216                addiu    $tempreg,$tempreg,<constant>
10217              For a local symbol, we want the same instruction
10218              sequence, but we output a BFD_RELOC_LO16 reloc on the
10219              addiu instruction.
10220
10221              If we have a large constant, and this is a reference to
10222              an external symbol, we want
10223                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10224                lui      $at,<hiconstant>
10225                addiu    $at,$at,<loconstant>
10226                addu     $tempreg,$tempreg,$at
10227              For a local symbol, we want the same instruction
10228              sequence, but we output a BFD_RELOC_LO16 reloc on the
10229              addiu instruction.
10230            */
10231
10232           if (offset_expr.X_add_number == 0)
10233             {
10234               if (mips_pic == SVR4_PIC
10235                   && breg == 0
10236                   && (call || tempreg == PIC_CALL_REG))
10237                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
10238
10239               relax_start (offset_expr.X_add_symbol);
10240               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10241                            lw_reloc_type, mips_gp_register);
10242               if (breg != 0)
10243                 {
10244                   /* We're going to put in an addu instruction using
10245                      tempreg, so we may as well insert the nop right
10246                      now.  */
10247                   load_delay_nop ();
10248                 }
10249               relax_switch ();
10250               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10251                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
10252               load_delay_nop ();
10253               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10254                            tempreg, tempreg, BFD_RELOC_LO16);
10255               relax_end ();
10256               /* FIXME: If breg == 0, and the next instruction uses
10257                  $tempreg, then if this variant case is used an extra
10258                  nop will be generated.  */
10259             }
10260           else if (offset_expr.X_add_number >= -0x8000
10261                    && offset_expr.X_add_number < 0x8000)
10262             {
10263               load_got_offset (tempreg, &offset_expr);
10264               load_delay_nop ();
10265               add_got_offset (tempreg, &offset_expr);
10266             }
10267           else
10268             {
10269               expr1.X_add_number = offset_expr.X_add_number;
10270               offset_expr.X_add_number =
10271                 SEXT_16BIT (offset_expr.X_add_number);
10272               load_got_offset (tempreg, &offset_expr);
10273               offset_expr.X_add_number = expr1.X_add_number;
10274               /* If we are going to add in a base register, and the
10275                  target register and the base register are the same,
10276                  then we are using AT as a temporary register.  Since
10277                  we want to load the constant into AT, we add our
10278                  current AT (from the global offset table) and the
10279                  register into the register now, and pretend we were
10280                  not using a base register.  */
10281               if (breg == op[0])
10282                 {
10283                   load_delay_nop ();
10284                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10285                                op[0], AT, breg);
10286                   breg = 0;
10287                   tempreg = op[0];
10288                 }
10289               add_got_offset_hilo (tempreg, &offset_expr, AT);
10290               used_at = 1;
10291             }
10292         }
10293       else if (!mips_big_got && HAVE_NEWABI)
10294         {
10295           int add_breg_early = 0;
10296
10297           /* If this is a reference to an external, and there is no
10298              constant, or local symbol (*), with or without a
10299              constant, we want
10300                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10301              or for lca or if tempreg is PIC_CALL_REG
10302                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10303
10304              If we have a small constant, and this is a reference to
10305              an external symbol, we want
10306                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10307                addiu    $tempreg,$tempreg,<constant>
10308
10309              If we have a large constant, and this is a reference to
10310              an external symbol, we want
10311                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10312                lui      $at,<hiconstant>
10313                addiu    $at,$at,<loconstant>
10314                addu     $tempreg,$tempreg,$at
10315
10316              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10317              local symbols, even though it introduces an additional
10318              instruction.  */
10319
10320           if (offset_expr.X_add_number)
10321             {
10322               expr1.X_add_number = offset_expr.X_add_number;
10323               offset_expr.X_add_number = 0;
10324
10325               relax_start (offset_expr.X_add_symbol);
10326               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10327                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10328
10329               if (expr1.X_add_number >= -0x8000
10330                   && expr1.X_add_number < 0x8000)
10331                 {
10332                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10333                                tempreg, tempreg, BFD_RELOC_LO16);
10334                 }
10335               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10336                 {
10337                   unsigned int dreg;
10338
10339                   /* If we are going to add in a base register, and the
10340                      target register and the base register are the same,
10341                      then we are using AT as a temporary register.  Since
10342                      we want to load the constant into AT, we add our
10343                      current AT (from the global offset table) and the
10344                      register into the register now, and pretend we were
10345                      not using a base register.  */
10346                   if (breg != op[0])
10347                     dreg = tempreg;
10348                   else
10349                     {
10350                       gas_assert (tempreg == AT);
10351                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10352                                    op[0], AT, breg);
10353                       dreg = op[0];
10354                       add_breg_early = 1;
10355                     }
10356
10357                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10358                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10359                                dreg, dreg, AT);
10360
10361                   used_at = 1;
10362                 }
10363               else
10364                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10365
10366               relax_switch ();
10367               offset_expr.X_add_number = expr1.X_add_number;
10368
10369               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10370                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10371               if (add_breg_early)
10372                 {
10373                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10374                                op[0], tempreg, breg);
10375                   breg = 0;
10376                   tempreg = op[0];
10377                 }
10378               relax_end ();
10379             }
10380           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10381             {
10382               relax_start (offset_expr.X_add_symbol);
10383               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10384                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10385               relax_switch ();
10386               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10387                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10388               relax_end ();
10389             }
10390           else
10391             {
10392               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10393                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10394             }
10395         }
10396       else if (mips_big_got && !HAVE_NEWABI)
10397         {
10398           int gpdelay;
10399           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10400           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10401           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10402
10403           /* This is the large GOT case.  If this is a reference to an
10404              external symbol, and there is no constant, we want
10405                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10406                addu     $tempreg,$tempreg,$gp
10407                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10408              or for lca or if tempreg is PIC_CALL_REG
10409                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10410                addu     $tempreg,$tempreg,$gp
10411                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10412              For a local symbol, we want
10413                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10414                nop
10415                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10416
10417              If we have a small constant, and this is a reference to
10418              an external symbol, we want
10419                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10420                addu     $tempreg,$tempreg,$gp
10421                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10422                nop
10423                addiu    $tempreg,$tempreg,<constant>
10424              For a local symbol, we want
10425                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10426                nop
10427                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10428
10429              If we have a large constant, and this is a reference to
10430              an external symbol, we want
10431                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10432                addu     $tempreg,$tempreg,$gp
10433                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10434                lui      $at,<hiconstant>
10435                addiu    $at,$at,<loconstant>
10436                addu     $tempreg,$tempreg,$at
10437              For a local symbol, we want
10438                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10439                lui      $at,<hiconstant>
10440                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10441                addu     $tempreg,$tempreg,$at
10442           */
10443
10444           expr1.X_add_number = offset_expr.X_add_number;
10445           offset_expr.X_add_number = 0;
10446           relax_start (offset_expr.X_add_symbol);
10447           gpdelay = reg_needs_delay (mips_gp_register);
10448           if (expr1.X_add_number == 0 && breg == 0
10449               && (call || tempreg == PIC_CALL_REG))
10450             {
10451               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10452               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10453             }
10454           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10455           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10456                        tempreg, tempreg, mips_gp_register);
10457           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10458                        tempreg, lw_reloc_type, tempreg);
10459           if (expr1.X_add_number == 0)
10460             {
10461               if (breg != 0)
10462                 {
10463                   /* We're going to put in an addu instruction using
10464                      tempreg, so we may as well insert the nop right
10465                      now.  */
10466                   load_delay_nop ();
10467                 }
10468             }
10469           else if (expr1.X_add_number >= -0x8000
10470                    && expr1.X_add_number < 0x8000)
10471             {
10472               load_delay_nop ();
10473               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10474                            tempreg, tempreg, BFD_RELOC_LO16);
10475             }
10476           else
10477             {
10478               unsigned int dreg;
10479
10480               /* If we are going to add in a base register, and the
10481                  target register and the base register are the same,
10482                  then we are using AT as a temporary register.  Since
10483                  we want to load the constant into AT, we add our
10484                  current AT (from the global offset table) and the
10485                  register into the register now, and pretend we were
10486                  not using a base register.  */
10487               if (breg != op[0])
10488                 dreg = tempreg;
10489               else
10490                 {
10491                   gas_assert (tempreg == AT);
10492                   load_delay_nop ();
10493                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10494                                op[0], AT, breg);
10495                   dreg = op[0];
10496                 }
10497
10498               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10499               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10500
10501               used_at = 1;
10502             }
10503           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10504           relax_switch ();
10505
10506           if (gpdelay)
10507             {
10508               /* This is needed because this instruction uses $gp, but
10509                  the first instruction on the main stream does not.  */
10510               macro_build (NULL, "nop", "");
10511             }
10512
10513           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10514                        local_reloc_type, mips_gp_register);
10515           if (expr1.X_add_number >= -0x8000
10516               && expr1.X_add_number < 0x8000)
10517             {
10518               load_delay_nop ();
10519               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10520                            tempreg, tempreg, BFD_RELOC_LO16);
10521               /* FIXME: If add_number is 0, and there was no base
10522                  register, the external symbol case ended with a load,
10523                  so if the symbol turns out to not be external, and
10524                  the next instruction uses tempreg, an unnecessary nop
10525                  will be inserted.  */
10526             }
10527           else
10528             {
10529               if (breg == op[0])
10530                 {
10531                   /* We must add in the base register now, as in the
10532                      external symbol case.  */
10533                   gas_assert (tempreg == AT);
10534                   load_delay_nop ();
10535                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10536                                op[0], AT, breg);
10537                   tempreg = op[0];
10538                   /* We set breg to 0 because we have arranged to add
10539                      it in in both cases.  */
10540                   breg = 0;
10541                 }
10542
10543               macro_build_lui (&expr1, AT);
10544               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10545                            AT, AT, BFD_RELOC_LO16);
10546               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10547                            tempreg, tempreg, AT);
10548               used_at = 1;
10549             }
10550           relax_end ();
10551         }
10552       else if (mips_big_got && HAVE_NEWABI)
10553         {
10554           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10555           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10556           int add_breg_early = 0;
10557
10558           /* This is the large GOT case.  If this is a reference to an
10559              external symbol, and there is no constant, we want
10560                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10561                add      $tempreg,$tempreg,$gp
10562                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10563              or for lca or if tempreg is PIC_CALL_REG
10564                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10565                add      $tempreg,$tempreg,$gp
10566                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10567
10568              If we have a small constant, and this is a reference to
10569              an external symbol, we want
10570                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10571                add      $tempreg,$tempreg,$gp
10572                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10573                addi     $tempreg,$tempreg,<constant>
10574
10575              If we have a large constant, and this is a reference to
10576              an external symbol, we want
10577                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10578                addu     $tempreg,$tempreg,$gp
10579                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10580                lui      $at,<hiconstant>
10581                addi     $at,$at,<loconstant>
10582                add      $tempreg,$tempreg,$at
10583
10584              If we have NewABI, and we know it's a local symbol, we want
10585                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10586                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10587              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10588
10589           relax_start (offset_expr.X_add_symbol);
10590
10591           expr1.X_add_number = offset_expr.X_add_number;
10592           offset_expr.X_add_number = 0;
10593
10594           if (expr1.X_add_number == 0 && breg == 0
10595               && (call || tempreg == PIC_CALL_REG))
10596             {
10597               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10598               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10599             }
10600           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10601           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10602                        tempreg, tempreg, mips_gp_register);
10603           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10604                        tempreg, lw_reloc_type, tempreg);
10605
10606           if (expr1.X_add_number == 0)
10607             ;
10608           else if (expr1.X_add_number >= -0x8000
10609                    && expr1.X_add_number < 0x8000)
10610             {
10611               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10612                            tempreg, tempreg, BFD_RELOC_LO16);
10613             }
10614           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10615             {
10616               unsigned int dreg;
10617
10618               /* If we are going to add in a base register, and the
10619                  target register and the base register are the same,
10620                  then we are using AT as a temporary register.  Since
10621                  we want to load the constant into AT, we add our
10622                  current AT (from the global offset table) and the
10623                  register into the register now, and pretend we were
10624                  not using a base register.  */
10625               if (breg != op[0])
10626                 dreg = tempreg;
10627               else
10628                 {
10629                   gas_assert (tempreg == AT);
10630                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10631                                op[0], AT, breg);
10632                   dreg = op[0];
10633                   add_breg_early = 1;
10634                 }
10635
10636               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10637               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10638
10639               used_at = 1;
10640             }
10641           else
10642             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10643
10644           relax_switch ();
10645           offset_expr.X_add_number = expr1.X_add_number;
10646           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10647                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10648           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10649                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10650           if (add_breg_early)
10651             {
10652               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10653                            op[0], tempreg, breg);
10654               breg = 0;
10655               tempreg = op[0];
10656             }
10657           relax_end ();
10658         }
10659       else
10660         abort ();
10661
10662       if (breg != 0)
10663         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10664       break;
10665
10666     case M_MSGSND:
10667       gas_assert (!mips_opts.micromips);
10668       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10669       break;
10670
10671     case M_MSGLD:
10672       gas_assert (!mips_opts.micromips);
10673       macro_build (NULL, "c2", "C", 0x02);
10674       break;
10675
10676     case M_MSGLD_T:
10677       gas_assert (!mips_opts.micromips);
10678       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10679       break;
10680
10681     case M_MSGWAIT:
10682       gas_assert (!mips_opts.micromips);
10683       macro_build (NULL, "c2", "C", 3);
10684       break;
10685
10686     case M_MSGWAIT_T:
10687       gas_assert (!mips_opts.micromips);
10688       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10689       break;
10690
10691     case M_J_A:
10692       /* The j instruction may not be used in PIC code, since it
10693          requires an absolute address.  We convert it to a b
10694          instruction.  */
10695       if (mips_pic == NO_PIC)
10696         macro_build (&offset_expr, "j", "a");
10697       else
10698         macro_build (&offset_expr, "b", "p");
10699       break;
10700
10701       /* The jal instructions must be handled as macros because when
10702          generating PIC code they expand to multi-instruction
10703          sequences.  Normally they are simple instructions.  */
10704     case M_JALS_1:
10705       op[1] = op[0];
10706       op[0] = RA;
10707       /* Fall through.  */
10708     case M_JALS_2:
10709       gas_assert (mips_opts.micromips);
10710       if (mips_opts.insn32)
10711         {
10712           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10713           break;
10714         }
10715       jals = 1;
10716       goto jal;
10717     case M_JAL_1:
10718       op[1] = op[0];
10719       op[0] = RA;
10720       /* Fall through.  */
10721     case M_JAL_2:
10722     jal:
10723       if (mips_pic == NO_PIC)
10724         {
10725           s = jals ? "jalrs" : "jalr";
10726           if (mips_opts.micromips
10727               && !mips_opts.insn32
10728               && op[0] == RA
10729               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10730             macro_build (NULL, s, "mj", op[1]);
10731           else
10732             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10733         }
10734       else
10735         {
10736           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10737                            && mips_cprestore_offset >= 0);
10738
10739           if (op[1] != PIC_CALL_REG)
10740             as_warn (_("MIPS PIC call to register other than $25"));
10741
10742           s = ((mips_opts.micromips
10743                 && !mips_opts.insn32
10744                 && (!mips_opts.noreorder || cprestore))
10745                ? "jalrs" : "jalr");
10746           if (mips_opts.micromips
10747               && !mips_opts.insn32
10748               && op[0] == RA
10749               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10750             macro_build (NULL, s, "mj", op[1]);
10751           else
10752             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10753           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10754             {
10755               if (mips_cprestore_offset < 0)
10756                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10757               else
10758                 {
10759                   if (!mips_frame_reg_valid)
10760                     {
10761                       as_warn (_("no .frame pseudo-op used in PIC code"));
10762                       /* Quiet this warning.  */
10763                       mips_frame_reg_valid = 1;
10764                     }
10765                   if (!mips_cprestore_valid)
10766                     {
10767                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10768                       /* Quiet this warning.  */
10769                       mips_cprestore_valid = 1;
10770                     }
10771                   if (mips_opts.noreorder)
10772                     macro_build (NULL, "nop", "");
10773                   expr1.X_add_number = mips_cprestore_offset;
10774                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10775                                                 mips_gp_register,
10776                                                 mips_frame_reg,
10777                                                 HAVE_64BIT_ADDRESSES);
10778                 }
10779             }
10780         }
10781
10782       break;
10783
10784     case M_JALS_A:
10785       gas_assert (mips_opts.micromips);
10786       if (mips_opts.insn32)
10787         {
10788           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10789           break;
10790         }
10791       jals = 1;
10792       /* Fall through.  */
10793     case M_JAL_A:
10794       if (mips_pic == NO_PIC)
10795         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10796       else if (mips_pic == SVR4_PIC)
10797         {
10798           /* If this is a reference to an external symbol, and we are
10799              using a small GOT, we want
10800                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10801                nop
10802                jalr     $ra,$25
10803                nop
10804                lw       $gp,cprestore($sp)
10805              The cprestore value is set using the .cprestore
10806              pseudo-op.  If we are using a big GOT, we want
10807                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10808                addu     $25,$25,$gp
10809                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10810                nop
10811                jalr     $ra,$25
10812                nop
10813                lw       $gp,cprestore($sp)
10814              If the symbol is not external, we want
10815                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10816                nop
10817                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10818                jalr     $ra,$25
10819                nop
10820                lw $gp,cprestore($sp)
10821
10822              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10823              sequences above, minus nops, unless the symbol is local,
10824              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10825              GOT_DISP.  */
10826           if (HAVE_NEWABI)
10827             {
10828               if (!mips_big_got)
10829                 {
10830                   relax_start (offset_expr.X_add_symbol);
10831                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10832                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10833                                mips_gp_register);
10834                   relax_switch ();
10835                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10836                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10837                                mips_gp_register);
10838                   relax_end ();
10839                 }
10840               else
10841                 {
10842                   relax_start (offset_expr.X_add_symbol);
10843                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10844                                BFD_RELOC_MIPS_CALL_HI16);
10845                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10846                                PIC_CALL_REG, mips_gp_register);
10847                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10848                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10849                                PIC_CALL_REG);
10850                   relax_switch ();
10851                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10852                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10853                                mips_gp_register);
10854                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10855                                PIC_CALL_REG, PIC_CALL_REG,
10856                                BFD_RELOC_MIPS_GOT_OFST);
10857                   relax_end ();
10858                 }
10859
10860               macro_build_jalr (&offset_expr, 0);
10861             }
10862           else
10863             {
10864               relax_start (offset_expr.X_add_symbol);
10865               if (!mips_big_got)
10866                 {
10867                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10868                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10869                                mips_gp_register);
10870                   load_delay_nop ();
10871                   relax_switch ();
10872                 }
10873               else
10874                 {
10875                   int gpdelay;
10876
10877                   gpdelay = reg_needs_delay (mips_gp_register);
10878                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10879                                BFD_RELOC_MIPS_CALL_HI16);
10880                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10881                                PIC_CALL_REG, mips_gp_register);
10882                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10883                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10884                                PIC_CALL_REG);
10885                   load_delay_nop ();
10886                   relax_switch ();
10887                   if (gpdelay)
10888                     macro_build (NULL, "nop", "");
10889                 }
10890               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10891                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10892                            mips_gp_register);
10893               load_delay_nop ();
10894               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10895                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10896               relax_end ();
10897               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10898
10899               if (mips_cprestore_offset < 0)
10900                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10901               else
10902                 {
10903                   if (!mips_frame_reg_valid)
10904                     {
10905                       as_warn (_("no .frame pseudo-op used in PIC code"));
10906                       /* Quiet this warning.  */
10907                       mips_frame_reg_valid = 1;
10908                     }
10909                   if (!mips_cprestore_valid)
10910                     {
10911                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10912                       /* Quiet this warning.  */
10913                       mips_cprestore_valid = 1;
10914                     }
10915                   if (mips_opts.noreorder)
10916                     macro_build (NULL, "nop", "");
10917                   expr1.X_add_number = mips_cprestore_offset;
10918                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10919                                                 mips_gp_register,
10920                                                 mips_frame_reg,
10921                                                 HAVE_64BIT_ADDRESSES);
10922                 }
10923             }
10924         }
10925       else if (mips_pic == VXWORKS_PIC)
10926         as_bad (_("non-PIC jump used in PIC library"));
10927       else
10928         abort ();
10929
10930       break;
10931
10932     case M_LBUE_AB:
10933       s = "lbue";
10934       fmt = "t,+j(b)";
10935       offbits = 9;
10936       goto ld_st;
10937     case M_LHUE_AB:
10938       s = "lhue";
10939       fmt = "t,+j(b)";
10940       offbits = 9;
10941       goto ld_st;
10942     case M_LBE_AB:
10943       s = "lbe";
10944       fmt = "t,+j(b)";
10945       offbits = 9;
10946       goto ld_st;
10947     case M_LHE_AB:
10948       s = "lhe";
10949       fmt = "t,+j(b)";
10950       offbits = 9;
10951       goto ld_st;
10952     case M_LLE_AB:
10953       s = "lle";
10954       fmt = "t,+j(b)";
10955       offbits = 9;
10956       goto ld_st;
10957     case M_LWE_AB:
10958       s = "lwe";
10959       fmt = "t,+j(b)";
10960       offbits = 9;
10961       goto ld_st;
10962     case M_LWLE_AB:
10963       s = "lwle";
10964       fmt = "t,+j(b)";
10965       offbits = 9;
10966       goto ld_st;
10967     case M_LWRE_AB:
10968       s = "lwre";
10969       fmt = "t,+j(b)";
10970       offbits = 9;
10971       goto ld_st;
10972     case M_SBE_AB:
10973       s = "sbe";
10974       fmt = "t,+j(b)";
10975       offbits = 9;
10976       goto ld_st;
10977     case M_SCE_AB:
10978       s = "sce";
10979       fmt = "t,+j(b)";
10980       offbits = 9;
10981       goto ld_st;
10982     case M_SHE_AB:
10983       s = "she";
10984       fmt = "t,+j(b)";
10985       offbits = 9;
10986       goto ld_st;
10987     case M_SWE_AB:
10988       s = "swe";
10989       fmt = "t,+j(b)";
10990       offbits = 9;
10991       goto ld_st;
10992     case M_SWLE_AB:
10993       s = "swle";
10994       fmt = "t,+j(b)";
10995       offbits = 9;
10996       goto ld_st;
10997     case M_SWRE_AB:
10998       s = "swre";
10999       fmt = "t,+j(b)";
11000       offbits = 9;
11001       goto ld_st;
11002     case M_ACLR_AB:
11003       s = "aclr";
11004       fmt = "\\,~(b)";
11005       offbits = 12;
11006       goto ld_st;
11007     case M_ASET_AB:
11008       s = "aset";
11009       fmt = "\\,~(b)";
11010       offbits = 12;
11011       goto ld_st;
11012     case M_LB_AB:
11013       s = "lb";
11014       fmt = "t,o(b)";
11015       goto ld;
11016     case M_LBU_AB:
11017       s = "lbu";
11018       fmt = "t,o(b)";
11019       goto ld;
11020     case M_LH_AB:
11021       s = "lh";
11022       fmt = "t,o(b)";
11023       goto ld;
11024     case M_LHU_AB:
11025       s = "lhu";
11026       fmt = "t,o(b)";
11027       goto ld;
11028     case M_LW_AB:
11029       s = "lw";
11030       fmt = "t,o(b)";
11031       goto ld;
11032     case M_LWC0_AB:
11033       gas_assert (!mips_opts.micromips);
11034       s = "lwc0";
11035       fmt = "E,o(b)";
11036       /* Itbl support may require additional care here.  */
11037       coproc = 1;
11038       goto ld_st;
11039     case M_LWC1_AB:
11040       s = "lwc1";
11041       fmt = "T,o(b)";
11042       /* Itbl support may require additional care here.  */
11043       coproc = 1;
11044       goto ld_st;
11045     case M_LWC2_AB:
11046       s = "lwc2";
11047       fmt = COP12_FMT;
11048       offbits = (mips_opts.micromips ? 12 : 16);
11049       /* Itbl support may require additional care here.  */
11050       coproc = 1;
11051       goto ld_st;
11052     case M_LWC3_AB:
11053       gas_assert (!mips_opts.micromips);
11054       s = "lwc3";
11055       fmt = "E,o(b)";
11056       /* Itbl support may require additional care here.  */
11057       coproc = 1;
11058       goto ld_st;
11059     case M_LWL_AB:
11060       s = "lwl";
11061       fmt = MEM12_FMT;
11062       offbits = (mips_opts.micromips ? 12 : 16);
11063       goto ld_st;
11064     case M_LWR_AB:
11065       s = "lwr";
11066       fmt = MEM12_FMT;
11067       offbits = (mips_opts.micromips ? 12 : 16);
11068       goto ld_st;
11069     case M_LDC1_AB:
11070       s = "ldc1";
11071       fmt = "T,o(b)";
11072       /* Itbl support may require additional care here.  */
11073       coproc = 1;
11074       goto ld_st;
11075     case M_LDC2_AB:
11076       s = "ldc2";
11077       fmt = COP12_FMT;
11078       offbits = (mips_opts.micromips ? 12 : 16);
11079       /* Itbl support may require additional care here.  */
11080       coproc = 1;
11081       goto ld_st;
11082     case M_LQC2_AB:
11083       s = "lqc2";
11084       fmt = "+7,o(b)";
11085       /* Itbl support may require additional care here.  */
11086       coproc = 1;
11087       goto ld_st;
11088     case M_LDC3_AB:
11089       s = "ldc3";
11090       fmt = "E,o(b)";
11091       /* Itbl support may require additional care here.  */
11092       coproc = 1;
11093       goto ld_st;
11094     case M_LDL_AB:
11095       s = "ldl";
11096       fmt = MEM12_FMT;
11097       offbits = (mips_opts.micromips ? 12 : 16);
11098       goto ld_st;
11099     case M_LDR_AB:
11100       s = "ldr";
11101       fmt = MEM12_FMT;
11102       offbits = (mips_opts.micromips ? 12 : 16);
11103       goto ld_st;
11104     case M_LL_AB:
11105       s = "ll";
11106       fmt = MEM12_FMT;
11107       offbits = (mips_opts.micromips ? 12 : 16);
11108       goto ld;
11109     case M_LLD_AB:
11110       s = "lld";
11111       fmt = MEM12_FMT;
11112       offbits = (mips_opts.micromips ? 12 : 16);
11113       goto ld;
11114     case M_LWU_AB:
11115       s = "lwu";
11116       fmt = MEM12_FMT;
11117       offbits = (mips_opts.micromips ? 12 : 16);
11118       goto ld;
11119     case M_LWP_AB:
11120       gas_assert (mips_opts.micromips);
11121       s = "lwp";
11122       fmt = "t,~(b)";
11123       offbits = 12;
11124       lp = 1;
11125       goto ld;
11126     case M_LDP_AB:
11127       gas_assert (mips_opts.micromips);
11128       s = "ldp";
11129       fmt = "t,~(b)";
11130       offbits = 12;
11131       lp = 1;
11132       goto ld;
11133     case M_LWM_AB:
11134       gas_assert (mips_opts.micromips);
11135       s = "lwm";
11136       fmt = "n,~(b)";
11137       offbits = 12;
11138       goto ld_st;
11139     case M_LDM_AB:
11140       gas_assert (mips_opts.micromips);
11141       s = "ldm";
11142       fmt = "n,~(b)";
11143       offbits = 12;
11144       goto ld_st;
11145
11146     ld:
11147       /* We don't want to use $0 as tempreg.  */
11148       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
11149         goto ld_st;
11150       else
11151         tempreg = op[0] + lp;
11152       goto ld_noat;
11153
11154     case M_SB_AB:
11155       s = "sb";
11156       fmt = "t,o(b)";
11157       goto ld_st;
11158     case M_SH_AB:
11159       s = "sh";
11160       fmt = "t,o(b)";
11161       goto ld_st;
11162     case M_SW_AB:
11163       s = "sw";
11164       fmt = "t,o(b)";
11165       goto ld_st;
11166     case M_SWC0_AB:
11167       gas_assert (!mips_opts.micromips);
11168       s = "swc0";
11169       fmt = "E,o(b)";
11170       /* Itbl support may require additional care here.  */
11171       coproc = 1;
11172       goto ld_st;
11173     case M_SWC1_AB:
11174       s = "swc1";
11175       fmt = "T,o(b)";
11176       /* Itbl support may require additional care here.  */
11177       coproc = 1;
11178       goto ld_st;
11179     case M_SWC2_AB:
11180       s = "swc2";
11181       fmt = COP12_FMT;
11182       offbits = (mips_opts.micromips ? 12 : 16);
11183       /* Itbl support may require additional care here.  */
11184       coproc = 1;
11185       goto ld_st;
11186     case M_SWC3_AB:
11187       gas_assert (!mips_opts.micromips);
11188       s = "swc3";
11189       fmt = "E,o(b)";
11190       /* Itbl support may require additional care here.  */
11191       coproc = 1;
11192       goto ld_st;
11193     case M_SWL_AB:
11194       s = "swl";
11195       fmt = MEM12_FMT;
11196       offbits = (mips_opts.micromips ? 12 : 16);
11197       goto ld_st;
11198     case M_SWR_AB:
11199       s = "swr";
11200       fmt = MEM12_FMT;
11201       offbits = (mips_opts.micromips ? 12 : 16);
11202       goto ld_st;
11203     case M_SC_AB:
11204       s = "sc";
11205       fmt = MEM12_FMT;
11206       offbits = (mips_opts.micromips ? 12 : 16);
11207       goto ld_st;
11208     case M_SCD_AB:
11209       s = "scd";
11210       fmt = MEM12_FMT;
11211       offbits = (mips_opts.micromips ? 12 : 16);
11212       goto ld_st;
11213     case M_CACHE_AB:
11214       s = "cache";
11215       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
11216       offbits = (mips_opts.micromips ? 12 : 16);
11217       goto ld_st;
11218     case M_CACHEE_AB:
11219       s = "cachee";
11220       fmt = "k,+j(b)";
11221       offbits = 9;
11222       goto ld_st;
11223     case M_PREF_AB:
11224       s = "pref";
11225       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
11226       offbits = (mips_opts.micromips ? 12 : 16);
11227       goto ld_st;
11228     case M_PREFE_AB:
11229       s = "prefe";
11230       fmt = "k,+j(b)";
11231       offbits = 9;
11232       goto ld_st;
11233     case M_SDC1_AB:
11234       s = "sdc1";
11235       fmt = "T,o(b)";
11236       coproc = 1;
11237       /* Itbl support may require additional care here.  */
11238       goto ld_st;
11239     case M_SDC2_AB:
11240       s = "sdc2";
11241       fmt = COP12_FMT;
11242       offbits = (mips_opts.micromips ? 12 : 16);
11243       /* Itbl support may require additional care here.  */
11244       coproc = 1;
11245       goto ld_st;
11246     case M_SQC2_AB:
11247       s = "sqc2";
11248       fmt = "+7,o(b)";
11249       /* Itbl support may require additional care here.  */
11250       coproc = 1;
11251       goto ld_st;
11252     case M_SDC3_AB:
11253       gas_assert (!mips_opts.micromips);
11254       s = "sdc3";
11255       fmt = "E,o(b)";
11256       /* Itbl support may require additional care here.  */
11257       coproc = 1;
11258       goto ld_st;
11259     case M_SDL_AB:
11260       s = "sdl";
11261       fmt = MEM12_FMT;
11262       offbits = (mips_opts.micromips ? 12 : 16);
11263       goto ld_st;
11264     case M_SDR_AB:
11265       s = "sdr";
11266       fmt = MEM12_FMT;
11267       offbits = (mips_opts.micromips ? 12 : 16);
11268       goto ld_st;
11269     case M_SWP_AB:
11270       gas_assert (mips_opts.micromips);
11271       s = "swp";
11272       fmt = "t,~(b)";
11273       offbits = 12;
11274       goto ld_st;
11275     case M_SDP_AB:
11276       gas_assert (mips_opts.micromips);
11277       s = "sdp";
11278       fmt = "t,~(b)";
11279       offbits = 12;
11280       goto ld_st;
11281     case M_SWM_AB:
11282       gas_assert (mips_opts.micromips);
11283       s = "swm";
11284       fmt = "n,~(b)";
11285       offbits = 12;
11286       goto ld_st;
11287     case M_SDM_AB:
11288       gas_assert (mips_opts.micromips);
11289       s = "sdm";
11290       fmt = "n,~(b)";
11291       offbits = 12;
11292
11293     ld_st:
11294       tempreg = AT;
11295     ld_noat:
11296       breg = op[2];
11297       if (small_offset_p (0, align, 16))
11298         {
11299           /* The first case exists for M_LD_AB and M_SD_AB, which are
11300              macros for o32 but which should act like normal instructions
11301              otherwise.  */
11302           if (offbits == 16)
11303             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
11304                          offset_reloc[1], offset_reloc[2], breg);
11305           else if (small_offset_p (0, align, offbits))
11306             {
11307               if (offbits == 0)
11308                 macro_build (NULL, s, fmt, op[0], breg);
11309               else
11310                 macro_build (NULL, s, fmt, op[0],
11311                              (int) offset_expr.X_add_number, breg);
11312             }
11313           else
11314             {
11315               if (tempreg == AT)
11316                 used_at = 1;
11317               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11318                            tempreg, breg, -1, offset_reloc[0],
11319                            offset_reloc[1], offset_reloc[2]);
11320               if (offbits == 0)
11321                 macro_build (NULL, s, fmt, op[0], tempreg);
11322               else
11323                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11324             }
11325           break;
11326         }
11327
11328       if (tempreg == AT)
11329         used_at = 1;
11330
11331       if (offset_expr.X_op != O_constant
11332           && offset_expr.X_op != O_symbol)
11333         {
11334           as_bad (_("expression too complex"));
11335           offset_expr.X_op = O_constant;
11336         }
11337
11338       if (HAVE_32BIT_ADDRESSES
11339           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11340         {
11341           char value [32];
11342
11343           sprintf_vma (value, offset_expr.X_add_number);
11344           as_bad (_("number (0x%s) larger than 32 bits"), value);
11345         }
11346
11347       /* A constant expression in PIC code can be handled just as it
11348          is in non PIC code.  */
11349       if (offset_expr.X_op == O_constant)
11350         {
11351           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11352                                                  offbits == 0 ? 16 : offbits);
11353           offset_expr.X_add_number -= expr1.X_add_number;
11354
11355           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11356           if (breg != 0)
11357             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11358                          tempreg, tempreg, breg);
11359           if (offbits == 0)
11360             {
11361               if (offset_expr.X_add_number != 0)
11362                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11363                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11364               macro_build (NULL, s, fmt, op[0], tempreg);
11365             }
11366           else if (offbits == 16)
11367             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11368           else
11369             macro_build (NULL, s, fmt, op[0],
11370                          (int) offset_expr.X_add_number, tempreg);
11371         }
11372       else if (offbits != 16)
11373         {
11374           /* The offset field is too narrow to be used for a low-part
11375              relocation, so load the whole address into the auxillary
11376              register.  */
11377           load_address (tempreg, &offset_expr, &used_at);
11378           if (breg != 0)
11379             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11380                          tempreg, tempreg, breg);
11381           if (offbits == 0)
11382             macro_build (NULL, s, fmt, op[0], tempreg);
11383           else
11384             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11385         }
11386       else if (mips_pic == NO_PIC)
11387         {
11388           /* If this is a reference to a GP relative symbol, and there
11389              is no base register, we want
11390                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11391              Otherwise, if there is no base register, we want
11392                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11393                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11394              If we have a constant, we need two instructions anyhow,
11395              so we always use the latter form.
11396
11397              If we have a base register, and this is a reference to a
11398              GP relative symbol, we want
11399                addu     $tempreg,$breg,$gp
11400                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11401              Otherwise we want
11402                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11403                addu     $tempreg,$tempreg,$breg
11404                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11405              With a constant we always use the latter case.
11406
11407              With 64bit address space and no base register and $at usable,
11408              we want
11409                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11410                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11411                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11412                dsll32   $tempreg,0
11413                daddu    $tempreg,$at
11414                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11415              If we have a base register, we want
11416                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11417                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11418                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11419                daddu    $at,$breg
11420                dsll32   $tempreg,0
11421                daddu    $tempreg,$at
11422                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11423
11424              Without $at we can't generate the optimal path for superscalar
11425              processors here since this would require two temporary registers.
11426                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11427                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11428                dsll     $tempreg,16
11429                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11430                dsll     $tempreg,16
11431                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11432              If we have a base register, we want
11433                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11434                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11435                dsll     $tempreg,16
11436                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11437                dsll     $tempreg,16
11438                daddu    $tempreg,$tempreg,$breg
11439                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11440
11441              For GP relative symbols in 64bit address space we can use
11442              the same sequence as in 32bit address space.  */
11443           if (HAVE_64BIT_SYMBOLS)
11444             {
11445               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11446                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11447                 {
11448                   relax_start (offset_expr.X_add_symbol);
11449                   if (breg == 0)
11450                     {
11451                       macro_build (&offset_expr, s, fmt, op[0],
11452                                    BFD_RELOC_GPREL16, mips_gp_register);
11453                     }
11454                   else
11455                     {
11456                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11457                                    tempreg, breg, mips_gp_register);
11458                       macro_build (&offset_expr, s, fmt, op[0],
11459                                    BFD_RELOC_GPREL16, tempreg);
11460                     }
11461                   relax_switch ();
11462                 }
11463
11464               if (used_at == 0 && mips_opts.at)
11465                 {
11466                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11467                                BFD_RELOC_MIPS_HIGHEST);
11468                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11469                                BFD_RELOC_HI16_S);
11470                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11471                                tempreg, BFD_RELOC_MIPS_HIGHER);
11472                   if (breg != 0)
11473                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11474                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11475                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11476                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11477                                tempreg);
11478                   used_at = 1;
11479                 }
11480               else
11481                 {
11482                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11483                                BFD_RELOC_MIPS_HIGHEST);
11484                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11485                                tempreg, BFD_RELOC_MIPS_HIGHER);
11486                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11487                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11488                                tempreg, BFD_RELOC_HI16_S);
11489                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11490                   if (breg != 0)
11491                     macro_build (NULL, "daddu", "d,v,t",
11492                                  tempreg, tempreg, breg);
11493                   macro_build (&offset_expr, s, fmt, op[0],
11494                                BFD_RELOC_LO16, tempreg);
11495                 }
11496
11497               if (mips_relax.sequence)
11498                 relax_end ();
11499               break;
11500             }
11501
11502           if (breg == 0)
11503             {
11504               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11505                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11506                 {
11507                   relax_start (offset_expr.X_add_symbol);
11508                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11509                                mips_gp_register);
11510                   relax_switch ();
11511                 }
11512               macro_build_lui (&offset_expr, tempreg);
11513               macro_build (&offset_expr, s, fmt, op[0],
11514                            BFD_RELOC_LO16, tempreg);
11515               if (mips_relax.sequence)
11516                 relax_end ();
11517             }
11518           else
11519             {
11520               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11521                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11522                 {
11523                   relax_start (offset_expr.X_add_symbol);
11524                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11525                                tempreg, breg, mips_gp_register);
11526                   macro_build (&offset_expr, s, fmt, op[0],
11527                                BFD_RELOC_GPREL16, tempreg);
11528                   relax_switch ();
11529                 }
11530               macro_build_lui (&offset_expr, tempreg);
11531               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11532                            tempreg, tempreg, breg);
11533               macro_build (&offset_expr, s, fmt, op[0],
11534                            BFD_RELOC_LO16, tempreg);
11535               if (mips_relax.sequence)
11536                 relax_end ();
11537             }
11538         }
11539       else if (!mips_big_got)
11540         {
11541           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11542
11543           /* If this is a reference to an external symbol, we want
11544                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11545                nop
11546                <op>     op[0],0($tempreg)
11547              Otherwise we want
11548                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11549                nop
11550                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11551                <op>     op[0],0($tempreg)
11552
11553              For NewABI, we want
11554                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11555                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11556
11557              If there is a base register, we add it to $tempreg before
11558              the <op>.  If there is a constant, we stick it in the
11559              <op> instruction.  We don't handle constants larger than
11560              16 bits, because we have no way to load the upper 16 bits
11561              (actually, we could handle them for the subset of cases
11562              in which we are not using $at).  */
11563           gas_assert (offset_expr.X_op == O_symbol);
11564           if (HAVE_NEWABI)
11565             {
11566               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11567                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11568               if (breg != 0)
11569                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11570                              tempreg, tempreg, breg);
11571               macro_build (&offset_expr, s, fmt, op[0],
11572                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11573               break;
11574             }
11575           expr1.X_add_number = offset_expr.X_add_number;
11576           offset_expr.X_add_number = 0;
11577           if (expr1.X_add_number < -0x8000
11578               || expr1.X_add_number >= 0x8000)
11579             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11580           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11581                        lw_reloc_type, mips_gp_register);
11582           load_delay_nop ();
11583           relax_start (offset_expr.X_add_symbol);
11584           relax_switch ();
11585           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11586                        tempreg, BFD_RELOC_LO16);
11587           relax_end ();
11588           if (breg != 0)
11589             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11590                          tempreg, tempreg, breg);
11591           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11592         }
11593       else if (mips_big_got && !HAVE_NEWABI)
11594         {
11595           int gpdelay;
11596
11597           /* If this is a reference to an external symbol, we want
11598                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11599                addu     $tempreg,$tempreg,$gp
11600                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11601                <op>     op[0],0($tempreg)
11602              Otherwise we want
11603                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11604                nop
11605                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11606                <op>     op[0],0($tempreg)
11607              If there is a base register, we add it to $tempreg before
11608              the <op>.  If there is a constant, we stick it in the
11609              <op> instruction.  We don't handle constants larger than
11610              16 bits, because we have no way to load the upper 16 bits
11611              (actually, we could handle them for the subset of cases
11612              in which we are not using $at).  */
11613           gas_assert (offset_expr.X_op == O_symbol);
11614           expr1.X_add_number = offset_expr.X_add_number;
11615           offset_expr.X_add_number = 0;
11616           if (expr1.X_add_number < -0x8000
11617               || expr1.X_add_number >= 0x8000)
11618             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11619           gpdelay = reg_needs_delay (mips_gp_register);
11620           relax_start (offset_expr.X_add_symbol);
11621           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11622                        BFD_RELOC_MIPS_GOT_HI16);
11623           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11624                        mips_gp_register);
11625           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11626                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11627           relax_switch ();
11628           if (gpdelay)
11629             macro_build (NULL, "nop", "");
11630           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11631                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11632           load_delay_nop ();
11633           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11634                        tempreg, BFD_RELOC_LO16);
11635           relax_end ();
11636
11637           if (breg != 0)
11638             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11639                          tempreg, tempreg, breg);
11640           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11641         }
11642       else if (mips_big_got && HAVE_NEWABI)
11643         {
11644           /* If this is a reference to an external symbol, we want
11645                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11646                add      $tempreg,$tempreg,$gp
11647                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11648                <op>     op[0],<ofst>($tempreg)
11649              Otherwise, for local symbols, we want:
11650                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11651                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11652           gas_assert (offset_expr.X_op == O_symbol);
11653           expr1.X_add_number = offset_expr.X_add_number;
11654           offset_expr.X_add_number = 0;
11655           if (expr1.X_add_number < -0x8000
11656               || expr1.X_add_number >= 0x8000)
11657             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11658           relax_start (offset_expr.X_add_symbol);
11659           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11660                        BFD_RELOC_MIPS_GOT_HI16);
11661           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11662                        mips_gp_register);
11663           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11664                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11665           if (breg != 0)
11666             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11667                          tempreg, tempreg, breg);
11668           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11669
11670           relax_switch ();
11671           offset_expr.X_add_number = expr1.X_add_number;
11672           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11673                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11674           if (breg != 0)
11675             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11676                          tempreg, tempreg, breg);
11677           macro_build (&offset_expr, s, fmt, op[0],
11678                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11679           relax_end ();
11680         }
11681       else
11682         abort ();
11683
11684       break;
11685
11686     case M_JRADDIUSP:
11687       gas_assert (mips_opts.micromips);
11688       gas_assert (mips_opts.insn32);
11689       start_noreorder ();
11690       macro_build (NULL, "jr", "s", RA);
11691       expr1.X_add_number = op[0] << 2;
11692       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11693       end_noreorder ();
11694       break;
11695
11696     case M_JRC:
11697       gas_assert (mips_opts.micromips);
11698       gas_assert (mips_opts.insn32);
11699       macro_build (NULL, "jr", "s", op[0]);
11700       if (mips_opts.noreorder)
11701         macro_build (NULL, "nop", "");
11702       break;
11703
11704     case M_LI:
11705     case M_LI_S:
11706       load_register (op[0], &imm_expr, 0);
11707       break;
11708
11709     case M_DLI:
11710       load_register (op[0], &imm_expr, 1);
11711       break;
11712
11713     case M_LI_SS:
11714       if (imm_expr.X_op == O_constant)
11715         {
11716           used_at = 1;
11717           load_register (AT, &imm_expr, 0);
11718           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11719           break;
11720         }
11721       else
11722         {
11723           gas_assert (imm_expr.X_op == O_absent
11724                       && offset_expr.X_op == O_symbol
11725                       && strcmp (segment_name (S_GET_SEGMENT
11726                                                (offset_expr.X_add_symbol)),
11727                                  ".lit4") == 0
11728                       && offset_expr.X_add_number == 0);
11729           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11730                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11731           break;
11732         }
11733
11734     case M_LI_D:
11735       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11736          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11737          order 32 bits of the value and the low order 32 bits are either
11738          zero or in OFFSET_EXPR.  */
11739       if (imm_expr.X_op == O_constant)
11740         {
11741           if (GPR_SIZE == 64)
11742             load_register (op[0], &imm_expr, 1);
11743           else
11744             {
11745               int hreg, lreg;
11746
11747               if (target_big_endian)
11748                 {
11749                   hreg = op[0];
11750                   lreg = op[0] + 1;
11751                 }
11752               else
11753                 {
11754                   hreg = op[0] + 1;
11755                   lreg = op[0];
11756                 }
11757
11758               if (hreg <= 31)
11759                 load_register (hreg, &imm_expr, 0);
11760               if (lreg <= 31)
11761                 {
11762                   if (offset_expr.X_op == O_absent)
11763                     move_register (lreg, 0);
11764                   else
11765                     {
11766                       gas_assert (offset_expr.X_op == O_constant);
11767                       load_register (lreg, &offset_expr, 0);
11768                     }
11769                 }
11770             }
11771           break;
11772         }
11773       gas_assert (imm_expr.X_op == O_absent);
11774
11775       /* We know that sym is in the .rdata section.  First we get the
11776          upper 16 bits of the address.  */
11777       if (mips_pic == NO_PIC)
11778         {
11779           macro_build_lui (&offset_expr, AT);
11780           used_at = 1;
11781         }
11782       else
11783         {
11784           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11785                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11786           used_at = 1;
11787         }
11788
11789       /* Now we load the register(s).  */
11790       if (GPR_SIZE == 64)
11791         {
11792           used_at = 1;
11793           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11794                        BFD_RELOC_LO16, AT);
11795         }
11796       else
11797         {
11798           used_at = 1;
11799           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11800                        BFD_RELOC_LO16, AT);
11801           if (op[0] != RA)
11802             {
11803               /* FIXME: How in the world do we deal with the possible
11804                  overflow here?  */
11805               offset_expr.X_add_number += 4;
11806               macro_build (&offset_expr, "lw", "t,o(b)",
11807                            op[0] + 1, BFD_RELOC_LO16, AT);
11808             }
11809         }
11810       break;
11811
11812     case M_LI_DD:
11813       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11814          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11815          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11816          the value and the low order 32 bits are either zero or in
11817          OFFSET_EXPR.  */
11818       if (imm_expr.X_op == O_constant)
11819         {
11820           used_at = 1;
11821           load_register (AT, &imm_expr, FPR_SIZE == 64);
11822           if (FPR_SIZE == 64 && GPR_SIZE == 64)
11823             macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11824           else
11825             {
11826               if (ISA_HAS_MXHC1 (mips_opts.isa))
11827                 macro_build (NULL, "mthc1", "t,G", AT, op[0]);
11828               else if (FPR_SIZE != 32)
11829                 as_bad (_("Unable to generate `%s' compliant code "
11830                           "without mthc1"),
11831                         (FPR_SIZE == 64) ? "fp64" : "fpxx");
11832               else
11833                 macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11834               if (offset_expr.X_op == O_absent)
11835                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11836               else
11837                 {
11838                   gas_assert (offset_expr.X_op == O_constant);
11839                   load_register (AT, &offset_expr, 0);
11840                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11841                 }
11842             }
11843           break;
11844         }
11845
11846       gas_assert (imm_expr.X_op == O_absent
11847                   && offset_expr.X_op == O_symbol
11848                   && offset_expr.X_add_number == 0);
11849       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11850       if (strcmp (s, ".lit8") == 0)
11851         {
11852           op[2] = mips_gp_register;
11853           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11854           offset_reloc[1] = BFD_RELOC_UNUSED;
11855           offset_reloc[2] = BFD_RELOC_UNUSED;
11856         }
11857       else
11858         {
11859           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11860           used_at = 1;
11861           if (mips_pic != NO_PIC)
11862             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11863                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11864           else
11865             {
11866               /* FIXME: This won't work for a 64 bit address.  */
11867               macro_build_lui (&offset_expr, AT);
11868             }
11869
11870           op[2] = AT;
11871           offset_reloc[0] = BFD_RELOC_LO16;
11872           offset_reloc[1] = BFD_RELOC_UNUSED;
11873           offset_reloc[2] = BFD_RELOC_UNUSED;
11874         }
11875       align = 8;
11876       /* Fall through */
11877
11878     case M_L_DAB:
11879       /*
11880        * The MIPS assembler seems to check for X_add_number not
11881        * being double aligned and generating:
11882        *        lui     at,%hi(foo+1)
11883        *        addu    at,at,v1
11884        *        addiu   at,at,%lo(foo+1)
11885        *        lwc1    f2,0(at)
11886        *        lwc1    f3,4(at)
11887        * But, the resulting address is the same after relocation so why
11888        * generate the extra instruction?
11889        */
11890       /* Itbl support may require additional care here.  */
11891       coproc = 1;
11892       fmt = "T,o(b)";
11893       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11894         {
11895           s = "ldc1";
11896           goto ld_st;
11897         }
11898       s = "lwc1";
11899       goto ldd_std;
11900
11901     case M_S_DAB:
11902       gas_assert (!mips_opts.micromips);
11903       /* Itbl support may require additional care here.  */
11904       coproc = 1;
11905       fmt = "T,o(b)";
11906       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11907         {
11908           s = "sdc1";
11909           goto ld_st;
11910         }
11911       s = "swc1";
11912       goto ldd_std;
11913
11914     case M_LQ_AB:
11915       fmt = "t,o(b)";
11916       s = "lq";
11917       goto ld;
11918
11919     case M_SQ_AB:
11920       fmt = "t,o(b)";
11921       s = "sq";
11922       goto ld_st;
11923
11924     case M_LD_AB:
11925       fmt = "t,o(b)";
11926       if (GPR_SIZE == 64)
11927         {
11928           s = "ld";
11929           goto ld;
11930         }
11931       s = "lw";
11932       goto ldd_std;
11933
11934     case M_SD_AB:
11935       fmt = "t,o(b)";
11936       if (GPR_SIZE == 64)
11937         {
11938           s = "sd";
11939           goto ld_st;
11940         }
11941       s = "sw";
11942
11943     ldd_std:
11944       /* Even on a big endian machine $fn comes before $fn+1.  We have
11945          to adjust when loading from memory.  We set coproc if we must
11946          load $fn+1 first.  */
11947       /* Itbl support may require additional care here.  */
11948       if (!target_big_endian)
11949         coproc = 0;
11950
11951       breg = op[2];
11952       if (small_offset_p (0, align, 16))
11953         {
11954           ep = &offset_expr;
11955           if (!small_offset_p (4, align, 16))
11956             {
11957               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11958                            -1, offset_reloc[0], offset_reloc[1],
11959                            offset_reloc[2]);
11960               expr1.X_add_number = 0;
11961               ep = &expr1;
11962               breg = AT;
11963               used_at = 1;
11964               offset_reloc[0] = BFD_RELOC_LO16;
11965               offset_reloc[1] = BFD_RELOC_UNUSED;
11966               offset_reloc[2] = BFD_RELOC_UNUSED;
11967             }
11968           if (strcmp (s, "lw") == 0 && op[0] == breg)
11969             {
11970               ep->X_add_number += 4;
11971               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11972                            offset_reloc[1], offset_reloc[2], breg);
11973               ep->X_add_number -= 4;
11974               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11975                            offset_reloc[1], offset_reloc[2], breg);
11976             }
11977           else
11978             {
11979               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11980                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11981                            breg);
11982               ep->X_add_number += 4;
11983               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11984                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11985                            breg);
11986             }
11987           break;
11988         }
11989
11990       if (offset_expr.X_op != O_symbol
11991           && offset_expr.X_op != O_constant)
11992         {
11993           as_bad (_("expression too complex"));
11994           offset_expr.X_op = O_constant;
11995         }
11996
11997       if (HAVE_32BIT_ADDRESSES
11998           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11999         {
12000           char value [32];
12001
12002           sprintf_vma (value, offset_expr.X_add_number);
12003           as_bad (_("number (0x%s) larger than 32 bits"), value);
12004         }
12005
12006       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
12007         {
12008           /* If this is a reference to a GP relative symbol, we want
12009                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12010                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
12011              If we have a base register, we use this
12012                addu     $at,$breg,$gp
12013                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
12014                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
12015              If this is not a GP relative symbol, we want
12016                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12017                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12018                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12019              If there is a base register, we add it to $at after the
12020              lui instruction.  If there is a constant, we always use
12021              the last case.  */
12022           if (offset_expr.X_op == O_symbol
12023               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12024               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12025             {
12026               relax_start (offset_expr.X_add_symbol);
12027               if (breg == 0)
12028                 {
12029                   tempreg = mips_gp_register;
12030                 }
12031               else
12032                 {
12033                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12034                                AT, breg, mips_gp_register);
12035                   tempreg = AT;
12036                   used_at = 1;
12037                 }
12038
12039               /* Itbl support may require additional care here.  */
12040               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12041                            BFD_RELOC_GPREL16, tempreg);
12042               offset_expr.X_add_number += 4;
12043
12044               /* Set mips_optimize to 2 to avoid inserting an
12045                  undesired nop.  */
12046               hold_mips_optimize = mips_optimize;
12047               mips_optimize = 2;
12048               /* Itbl support may require additional care here.  */
12049               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12050                            BFD_RELOC_GPREL16, tempreg);
12051               mips_optimize = hold_mips_optimize;
12052
12053               relax_switch ();
12054
12055               offset_expr.X_add_number -= 4;
12056             }
12057           used_at = 1;
12058           if (offset_high_part (offset_expr.X_add_number, 16)
12059               != offset_high_part (offset_expr.X_add_number + 4, 16))
12060             {
12061               load_address (AT, &offset_expr, &used_at);
12062               offset_expr.X_op = O_constant;
12063               offset_expr.X_add_number = 0;
12064             }
12065           else
12066             macro_build_lui (&offset_expr, AT);
12067           if (breg != 0)
12068             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12069           /* Itbl support may require additional care here.  */
12070           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12071                        BFD_RELOC_LO16, AT);
12072           /* FIXME: How do we handle overflow here?  */
12073           offset_expr.X_add_number += 4;
12074           /* Itbl support may require additional care here.  */
12075           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12076                        BFD_RELOC_LO16, AT);
12077           if (mips_relax.sequence)
12078             relax_end ();
12079         }
12080       else if (!mips_big_got)
12081         {
12082           /* If this is a reference to an external symbol, we want
12083                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12084                nop
12085                <op>     op[0],0($at)
12086                <op>     op[0]+1,4($at)
12087              Otherwise we want
12088                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12089                nop
12090                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12091                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12092              If there is a base register we add it to $at before the
12093              lwc1 instructions.  If there is a constant we include it
12094              in the lwc1 instructions.  */
12095           used_at = 1;
12096           expr1.X_add_number = offset_expr.X_add_number;
12097           if (expr1.X_add_number < -0x8000
12098               || expr1.X_add_number >= 0x8000 - 4)
12099             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12100           load_got_offset (AT, &offset_expr);
12101           load_delay_nop ();
12102           if (breg != 0)
12103             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12104
12105           /* Set mips_optimize to 2 to avoid inserting an undesired
12106              nop.  */
12107           hold_mips_optimize = mips_optimize;
12108           mips_optimize = 2;
12109
12110           /* Itbl support may require additional care here.  */
12111           relax_start (offset_expr.X_add_symbol);
12112           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12113                        BFD_RELOC_LO16, AT);
12114           expr1.X_add_number += 4;
12115           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12116                        BFD_RELOC_LO16, AT);
12117           relax_switch ();
12118           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12119                        BFD_RELOC_LO16, AT);
12120           offset_expr.X_add_number += 4;
12121           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12122                        BFD_RELOC_LO16, AT);
12123           relax_end ();
12124
12125           mips_optimize = hold_mips_optimize;
12126         }
12127       else if (mips_big_got)
12128         {
12129           int gpdelay;
12130
12131           /* If this is a reference to an external symbol, we want
12132                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
12133                addu     $at,$at,$gp
12134                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
12135                nop
12136                <op>     op[0],0($at)
12137                <op>     op[0]+1,4($at)
12138              Otherwise we want
12139                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12140                nop
12141                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12142                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12143              If there is a base register we add it to $at before the
12144              lwc1 instructions.  If there is a constant we include it
12145              in the lwc1 instructions.  */
12146           used_at = 1;
12147           expr1.X_add_number = offset_expr.X_add_number;
12148           offset_expr.X_add_number = 0;
12149           if (expr1.X_add_number < -0x8000
12150               || expr1.X_add_number >= 0x8000 - 4)
12151             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12152           gpdelay = reg_needs_delay (mips_gp_register);
12153           relax_start (offset_expr.X_add_symbol);
12154           macro_build (&offset_expr, "lui", LUI_FMT,
12155                        AT, BFD_RELOC_MIPS_GOT_HI16);
12156           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12157                        AT, AT, mips_gp_register);
12158           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
12159                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
12160           load_delay_nop ();
12161           if (breg != 0)
12162             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12163           /* Itbl support may require additional care here.  */
12164           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12165                        BFD_RELOC_LO16, AT);
12166           expr1.X_add_number += 4;
12167
12168           /* Set mips_optimize to 2 to avoid inserting an undesired
12169              nop.  */
12170           hold_mips_optimize = mips_optimize;
12171           mips_optimize = 2;
12172           /* Itbl support may require additional care here.  */
12173           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12174                        BFD_RELOC_LO16, AT);
12175           mips_optimize = hold_mips_optimize;
12176           expr1.X_add_number -= 4;
12177
12178           relax_switch ();
12179           offset_expr.X_add_number = expr1.X_add_number;
12180           if (gpdelay)
12181             macro_build (NULL, "nop", "");
12182           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12183                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12184           load_delay_nop ();
12185           if (breg != 0)
12186             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12187           /* Itbl support may require additional care here.  */
12188           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12189                        BFD_RELOC_LO16, AT);
12190           offset_expr.X_add_number += 4;
12191
12192           /* Set mips_optimize to 2 to avoid inserting an undesired
12193              nop.  */
12194           hold_mips_optimize = mips_optimize;
12195           mips_optimize = 2;
12196           /* Itbl support may require additional care here.  */
12197           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12198                        BFD_RELOC_LO16, AT);
12199           mips_optimize = hold_mips_optimize;
12200           relax_end ();
12201         }
12202       else
12203         abort ();
12204
12205       break;
12206         
12207     case M_SAA_AB:
12208       s = "saa";
12209       goto saa_saad;
12210     case M_SAAD_AB:
12211       s = "saad";
12212     saa_saad:
12213       gas_assert (!mips_opts.micromips);
12214       offbits = 0;
12215       fmt = "t,(b)";
12216       goto ld_st;
12217
12218    /* New code added to support COPZ instructions.
12219       This code builds table entries out of the macros in mip_opcodes.
12220       R4000 uses interlocks to handle coproc delays.
12221       Other chips (like the R3000) require nops to be inserted for delays.
12222
12223       FIXME: Currently, we require that the user handle delays.
12224       In order to fill delay slots for non-interlocked chips,
12225       we must have a way to specify delays based on the coprocessor.
12226       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
12227       What are the side-effects of the cop instruction?
12228       What cache support might we have and what are its effects?
12229       Both coprocessor & memory require delays. how long???
12230       What registers are read/set/modified?
12231
12232       If an itbl is provided to interpret cop instructions,
12233       this knowledge can be encoded in the itbl spec.  */
12234
12235     case M_COP0:
12236       s = "c0";
12237       goto copz;
12238     case M_COP1:
12239       s = "c1";
12240       goto copz;
12241     case M_COP2:
12242       s = "c2";
12243       goto copz;
12244     case M_COP3:
12245       s = "c3";
12246     copz:
12247       gas_assert (!mips_opts.micromips);
12248       /* For now we just do C (same as Cz).  The parameter will be
12249          stored in insn_opcode by mips_ip.  */
12250       macro_build (NULL, s, "C", (int) ip->insn_opcode);
12251       break;
12252
12253     case M_MOVE:
12254       move_register (op[0], op[1]);
12255       break;
12256
12257     case M_MOVEP:
12258       gas_assert (mips_opts.micromips);
12259       gas_assert (mips_opts.insn32);
12260       move_register (micromips_to_32_reg_h_map1[op[0]],
12261                      micromips_to_32_reg_m_map[op[1]]);
12262       move_register (micromips_to_32_reg_h_map2[op[0]],
12263                      micromips_to_32_reg_n_map[op[2]]);
12264       break;
12265
12266     case M_DMUL:
12267       dbl = 1;
12268     case M_MUL:
12269       if (mips_opts.arch == CPU_R5900)
12270         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
12271                      op[2]);
12272       else
12273         {
12274           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
12275           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12276         }
12277       break;
12278
12279     case M_DMUL_I:
12280       dbl = 1;
12281     case M_MUL_I:
12282       /* The MIPS assembler some times generates shifts and adds.  I'm
12283          not trying to be that fancy. GCC should do this for us
12284          anyway.  */
12285       used_at = 1;
12286       load_register (AT, &imm_expr, dbl);
12287       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
12288       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12289       break;
12290
12291     case M_DMULO_I:
12292       dbl = 1;
12293     case M_MULO_I:
12294       imm = 1;
12295       goto do_mulo;
12296
12297     case M_DMULO:
12298       dbl = 1;
12299     case M_MULO:
12300     do_mulo:
12301       start_noreorder ();
12302       used_at = 1;
12303       if (imm)
12304         load_register (AT, &imm_expr, dbl);
12305       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
12306                    op[1], imm ? AT : op[2]);
12307       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12308       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12309       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12310       if (mips_trap)
12311         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12312       else
12313         {
12314           if (mips_opts.micromips)
12315             micromips_label_expr (&label_expr);
12316           else
12317             label_expr.X_add_number = 8;
12318           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12319           macro_build (NULL, "nop", "");
12320           macro_build (NULL, "break", BRK_FMT, 6);
12321           if (mips_opts.micromips)
12322             micromips_add_label ();
12323         }
12324       end_noreorder ();
12325       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12326       break;
12327
12328     case M_DMULOU_I:
12329       dbl = 1;
12330     case M_MULOU_I:
12331       imm = 1;
12332       goto do_mulou;
12333
12334     case M_DMULOU:
12335       dbl = 1;
12336     case M_MULOU:
12337     do_mulou:
12338       start_noreorder ();
12339       used_at = 1;
12340       if (imm)
12341         load_register (AT, &imm_expr, dbl);
12342       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12343                    op[1], imm ? AT : op[2]);
12344       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12345       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12346       if (mips_trap)
12347         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12348       else
12349         {
12350           if (mips_opts.micromips)
12351             micromips_label_expr (&label_expr);
12352           else
12353             label_expr.X_add_number = 8;
12354           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12355           macro_build (NULL, "nop", "");
12356           macro_build (NULL, "break", BRK_FMT, 6);
12357           if (mips_opts.micromips)
12358             micromips_add_label ();
12359         }
12360       end_noreorder ();
12361       break;
12362
12363     case M_DROL:
12364       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12365         {
12366           if (op[0] == op[1])
12367             {
12368               tempreg = AT;
12369               used_at = 1;
12370             }
12371           else
12372             tempreg = op[0];
12373           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12374           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12375           break;
12376         }
12377       used_at = 1;
12378       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12379       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12380       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12381       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12382       break;
12383
12384     case M_ROL:
12385       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12386         {
12387           if (op[0] == op[1])
12388             {
12389               tempreg = AT;
12390               used_at = 1;
12391             }
12392           else
12393             tempreg = op[0];
12394           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12395           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12396           break;
12397         }
12398       used_at = 1;
12399       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12400       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12401       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12402       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12403       break;
12404
12405     case M_DROL_I:
12406       {
12407         unsigned int rot;
12408         char *l;
12409         char *rr;
12410
12411         rot = imm_expr.X_add_number & 0x3f;
12412         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12413           {
12414             rot = (64 - rot) & 0x3f;
12415             if (rot >= 32)
12416               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12417             else
12418               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12419             break;
12420           }
12421         if (rot == 0)
12422           {
12423             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12424             break;
12425           }
12426         l = (rot < 0x20) ? "dsll" : "dsll32";
12427         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12428         rot &= 0x1f;
12429         used_at = 1;
12430         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12431         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12432         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12433       }
12434       break;
12435
12436     case M_ROL_I:
12437       {
12438         unsigned int rot;
12439
12440         rot = imm_expr.X_add_number & 0x1f;
12441         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12442           {
12443             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12444                          (32 - rot) & 0x1f);
12445             break;
12446           }
12447         if (rot == 0)
12448           {
12449             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12450             break;
12451           }
12452         used_at = 1;
12453         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12454         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12455         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12456       }
12457       break;
12458
12459     case M_DROR:
12460       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12461         {
12462           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12463           break;
12464         }
12465       used_at = 1;
12466       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12467       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12468       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12469       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12470       break;
12471
12472     case M_ROR:
12473       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12474         {
12475           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12476           break;
12477         }
12478       used_at = 1;
12479       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12480       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12481       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12482       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12483       break;
12484
12485     case M_DROR_I:
12486       {
12487         unsigned int rot;
12488         char *l;
12489         char *rr;
12490
12491         rot = imm_expr.X_add_number & 0x3f;
12492         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12493           {
12494             if (rot >= 32)
12495               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12496             else
12497               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12498             break;
12499           }
12500         if (rot == 0)
12501           {
12502             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12503             break;
12504           }
12505         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12506         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12507         rot &= 0x1f;
12508         used_at = 1;
12509         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12510         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12511         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12512       }
12513       break;
12514
12515     case M_ROR_I:
12516       {
12517         unsigned int rot;
12518
12519         rot = imm_expr.X_add_number & 0x1f;
12520         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12521           {
12522             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12523             break;
12524           }
12525         if (rot == 0)
12526           {
12527             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12528             break;
12529           }
12530         used_at = 1;
12531         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12532         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12533         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12534       }
12535       break;
12536
12537     case M_SEQ:
12538       if (op[1] == 0)
12539         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12540       else if (op[2] == 0)
12541         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12542       else
12543         {
12544           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12545           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12546         }
12547       break;
12548
12549     case M_SEQ_I:
12550       if (imm_expr.X_add_number == 0)
12551         {
12552           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12553           break;
12554         }
12555       if (op[1] == 0)
12556         {
12557           as_warn (_("instruction %s: result is always false"),
12558                    ip->insn_mo->name);
12559           move_register (op[0], 0);
12560           break;
12561         }
12562       if (CPU_HAS_SEQ (mips_opts.arch)
12563           && -512 <= imm_expr.X_add_number
12564           && imm_expr.X_add_number < 512)
12565         {
12566           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12567                        (int) imm_expr.X_add_number);
12568           break;
12569         }
12570       if (imm_expr.X_add_number >= 0
12571           && imm_expr.X_add_number < 0x10000)
12572         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12573       else if (imm_expr.X_add_number > -0x8000
12574                && imm_expr.X_add_number < 0)
12575         {
12576           imm_expr.X_add_number = -imm_expr.X_add_number;
12577           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
12578                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12579         }
12580       else if (CPU_HAS_SEQ (mips_opts.arch))
12581         {
12582           used_at = 1;
12583           load_register (AT, &imm_expr, GPR_SIZE == 64);
12584           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12585           break;
12586         }
12587       else
12588         {
12589           load_register (AT, &imm_expr, GPR_SIZE == 64);
12590           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12591           used_at = 1;
12592         }
12593       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12594       break;
12595
12596     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12597       s = "slt";
12598       goto sge;
12599     case M_SGEU:
12600       s = "sltu";
12601     sge:
12602       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12603       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12604       break;
12605
12606     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12607     case M_SGEU_I:
12608       if (imm_expr.X_add_number >= -0x8000
12609           && imm_expr.X_add_number < 0x8000)
12610         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12611                      op[0], op[1], BFD_RELOC_LO16);
12612       else
12613         {
12614           load_register (AT, &imm_expr, GPR_SIZE == 64);
12615           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12616                        op[0], op[1], AT);
12617           used_at = 1;
12618         }
12619       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12620       break;
12621
12622     case M_SGT:         /* X > Y  <==>  Y < X */
12623       s = "slt";
12624       goto sgt;
12625     case M_SGTU:
12626       s = "sltu";
12627     sgt:
12628       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12629       break;
12630
12631     case M_SGT_I:       /* X > I  <==>  I < X */
12632       s = "slt";
12633       goto sgti;
12634     case M_SGTU_I:
12635       s = "sltu";
12636     sgti:
12637       used_at = 1;
12638       load_register (AT, &imm_expr, GPR_SIZE == 64);
12639       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12640       break;
12641
12642     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12643       s = "slt";
12644       goto sle;
12645     case M_SLEU:
12646       s = "sltu";
12647     sle:
12648       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12649       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12650       break;
12651
12652     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12653       s = "slt";
12654       goto slei;
12655     case M_SLEU_I:
12656       s = "sltu";
12657     slei:
12658       used_at = 1;
12659       load_register (AT, &imm_expr, GPR_SIZE == 64);
12660       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12661       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12662       break;
12663
12664     case M_SLT_I:
12665       if (imm_expr.X_add_number >= -0x8000
12666           && imm_expr.X_add_number < 0x8000)
12667         {
12668           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12669                        BFD_RELOC_LO16);
12670           break;
12671         }
12672       used_at = 1;
12673       load_register (AT, &imm_expr, GPR_SIZE == 64);
12674       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12675       break;
12676
12677     case M_SLTU_I:
12678       if (imm_expr.X_add_number >= -0x8000
12679           && imm_expr.X_add_number < 0x8000)
12680         {
12681           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12682                        BFD_RELOC_LO16);
12683           break;
12684         }
12685       used_at = 1;
12686       load_register (AT, &imm_expr, GPR_SIZE == 64);
12687       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12688       break;
12689
12690     case M_SNE:
12691       if (op[1] == 0)
12692         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12693       else if (op[2] == 0)
12694         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12695       else
12696         {
12697           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12698           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12699         }
12700       break;
12701
12702     case M_SNE_I:
12703       if (imm_expr.X_add_number == 0)
12704         {
12705           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12706           break;
12707         }
12708       if (op[1] == 0)
12709         {
12710           as_warn (_("instruction %s: result is always true"),
12711                    ip->insn_mo->name);
12712           macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
12713                        op[0], 0, BFD_RELOC_LO16);
12714           break;
12715         }
12716       if (CPU_HAS_SEQ (mips_opts.arch)
12717           && -512 <= imm_expr.X_add_number
12718           && imm_expr.X_add_number < 512)
12719         {
12720           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12721                        (int) imm_expr.X_add_number);
12722           break;
12723         }
12724       if (imm_expr.X_add_number >= 0
12725           && imm_expr.X_add_number < 0x10000)
12726         {
12727           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12728                        BFD_RELOC_LO16);
12729         }
12730       else if (imm_expr.X_add_number > -0x8000
12731                && imm_expr.X_add_number < 0)
12732         {
12733           imm_expr.X_add_number = -imm_expr.X_add_number;
12734           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
12735                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12736         }
12737       else if (CPU_HAS_SEQ (mips_opts.arch))
12738         {
12739           used_at = 1;
12740           load_register (AT, &imm_expr, GPR_SIZE == 64);
12741           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12742           break;
12743         }
12744       else
12745         {
12746           load_register (AT, &imm_expr, GPR_SIZE == 64);
12747           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12748           used_at = 1;
12749         }
12750       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12751       break;
12752
12753     case M_SUB_I:
12754       s = "addi";
12755       s2 = "sub";
12756       goto do_subi;
12757     case M_SUBU_I:
12758       s = "addiu";
12759       s2 = "subu";
12760       goto do_subi;
12761     case M_DSUB_I:
12762       dbl = 1;
12763       s = "daddi";
12764       s2 = "dsub";
12765       if (!mips_opts.micromips)
12766         goto do_subi;
12767       if (imm_expr.X_add_number > -0x200
12768           && imm_expr.X_add_number <= 0x200)
12769         {
12770           macro_build (NULL, s, "t,r,.", op[0], op[1],
12771                        (int) -imm_expr.X_add_number);
12772           break;
12773         }
12774       goto do_subi_i;
12775     case M_DSUBU_I:
12776       dbl = 1;
12777       s = "daddiu";
12778       s2 = "dsubu";
12779     do_subi:
12780       if (imm_expr.X_add_number > -0x8000
12781           && imm_expr.X_add_number <= 0x8000)
12782         {
12783           imm_expr.X_add_number = -imm_expr.X_add_number;
12784           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12785           break;
12786         }
12787     do_subi_i:
12788       used_at = 1;
12789       load_register (AT, &imm_expr, dbl);
12790       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12791       break;
12792
12793     case M_TEQ_I:
12794       s = "teq";
12795       goto trap;
12796     case M_TGE_I:
12797       s = "tge";
12798       goto trap;
12799     case M_TGEU_I:
12800       s = "tgeu";
12801       goto trap;
12802     case M_TLT_I:
12803       s = "tlt";
12804       goto trap;
12805     case M_TLTU_I:
12806       s = "tltu";
12807       goto trap;
12808     case M_TNE_I:
12809       s = "tne";
12810     trap:
12811       used_at = 1;
12812       load_register (AT, &imm_expr, GPR_SIZE == 64);
12813       macro_build (NULL, s, "s,t", op[0], AT);
12814       break;
12815
12816     case M_TRUNCWS:
12817     case M_TRUNCWD:
12818       gas_assert (!mips_opts.micromips);
12819       gas_assert (mips_opts.isa == ISA_MIPS1);
12820       used_at = 1;
12821
12822       /*
12823        * Is the double cfc1 instruction a bug in the mips assembler;
12824        * or is there a reason for it?
12825        */
12826       start_noreorder ();
12827       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12828       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12829       macro_build (NULL, "nop", "");
12830       expr1.X_add_number = 3;
12831       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12832       expr1.X_add_number = 2;
12833       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12834       macro_build (NULL, "ctc1", "t,G", AT, RA);
12835       macro_build (NULL, "nop", "");
12836       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12837                    op[0], op[1]);
12838       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12839       macro_build (NULL, "nop", "");
12840       end_noreorder ();
12841       break;
12842
12843     case M_ULH_AB:
12844       s = "lb";
12845       s2 = "lbu";
12846       off = 1;
12847       goto uld_st;
12848     case M_ULHU_AB:
12849       s = "lbu";
12850       s2 = "lbu";
12851       off = 1;
12852       goto uld_st;
12853     case M_ULW_AB:
12854       s = "lwl";
12855       s2 = "lwr";
12856       offbits = (mips_opts.micromips ? 12 : 16);
12857       off = 3;
12858       goto uld_st;
12859     case M_ULD_AB:
12860       s = "ldl";
12861       s2 = "ldr";
12862       offbits = (mips_opts.micromips ? 12 : 16);
12863       off = 7;
12864       goto uld_st;
12865     case M_USH_AB:
12866       s = "sb";
12867       s2 = "sb";
12868       off = 1;
12869       ust = 1;
12870       goto uld_st;
12871     case M_USW_AB:
12872       s = "swl";
12873       s2 = "swr";
12874       offbits = (mips_opts.micromips ? 12 : 16);
12875       off = 3;
12876       ust = 1;
12877       goto uld_st;
12878     case M_USD_AB:
12879       s = "sdl";
12880       s2 = "sdr";
12881       offbits = (mips_opts.micromips ? 12 : 16);
12882       off = 7;
12883       ust = 1;
12884
12885     uld_st:
12886       breg = op[2];
12887       large_offset = !small_offset_p (off, align, offbits);
12888       ep = &offset_expr;
12889       expr1.X_add_number = 0;
12890       if (large_offset)
12891         {
12892           used_at = 1;
12893           tempreg = AT;
12894           if (small_offset_p (0, align, 16))
12895             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12896                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12897           else
12898             {
12899               load_address (tempreg, ep, &used_at);
12900               if (breg != 0)
12901                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12902                              tempreg, tempreg, breg);
12903             }
12904           offset_reloc[0] = BFD_RELOC_LO16;
12905           offset_reloc[1] = BFD_RELOC_UNUSED;
12906           offset_reloc[2] = BFD_RELOC_UNUSED;
12907           breg = tempreg;
12908           tempreg = op[0];
12909           ep = &expr1;
12910         }
12911       else if (!ust && op[0] == breg)
12912         {
12913           used_at = 1;
12914           tempreg = AT;
12915         }
12916       else
12917         tempreg = op[0];
12918
12919       if (off == 1)
12920         goto ulh_sh;
12921
12922       if (!target_big_endian)
12923         ep->X_add_number += off;
12924       if (offbits == 12)
12925         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12926       else
12927         macro_build (ep, s, "t,o(b)", tempreg, -1,
12928                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12929
12930       if (!target_big_endian)
12931         ep->X_add_number -= off;
12932       else
12933         ep->X_add_number += off;
12934       if (offbits == 12)
12935         macro_build (NULL, s2, "t,~(b)",
12936                      tempreg, (int) ep->X_add_number, breg);
12937       else
12938         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12939                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12940
12941       /* If necessary, move the result in tempreg to the final destination.  */
12942       if (!ust && op[0] != tempreg)
12943         {
12944           /* Protect second load's delay slot.  */
12945           load_delay_nop ();
12946           move_register (op[0], tempreg);
12947         }
12948       break;
12949
12950     ulh_sh:
12951       used_at = 1;
12952       if (target_big_endian == ust)
12953         ep->X_add_number += off;
12954       tempreg = ust || large_offset ? op[0] : AT;
12955       macro_build (ep, s, "t,o(b)", tempreg, -1,
12956                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12957
12958       /* For halfword transfers we need a temporary register to shuffle
12959          bytes.  Unfortunately for M_USH_A we have none available before
12960          the next store as AT holds the base address.  We deal with this
12961          case by clobbering TREG and then restoring it as with ULH.  */
12962       tempreg = ust == large_offset ? op[0] : AT;
12963       if (ust)
12964         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12965
12966       if (target_big_endian == ust)
12967         ep->X_add_number -= off;
12968       else
12969         ep->X_add_number += off;
12970       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12971                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12972
12973       /* For M_USH_A re-retrieve the LSB.  */
12974       if (ust && large_offset)
12975         {
12976           if (target_big_endian)
12977             ep->X_add_number += off;
12978           else
12979             ep->X_add_number -= off;
12980           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12981                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12982         }
12983       /* For ULH and M_USH_A OR the LSB in.  */
12984       if (!ust || large_offset)
12985         {
12986           tempreg = !large_offset ? AT : op[0];
12987           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12988           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12989         }
12990       break;
12991
12992     default:
12993       /* FIXME: Check if this is one of the itbl macros, since they
12994          are added dynamically.  */
12995       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
12996       break;
12997     }
12998   if (!mips_opts.at && used_at)
12999     as_bad (_("macro used $at after \".set noat\""));
13000 }
13001
13002 /* Implement macros in mips16 mode.  */
13003
13004 static void
13005 mips16_macro (struct mips_cl_insn *ip)
13006 {
13007   const struct mips_operand_array *operands;
13008   int mask;
13009   int tmp;
13010   expressionS expr1;
13011   int dbl;
13012   const char *s, *s2, *s3;
13013   unsigned int op[MAX_OPERANDS];
13014   unsigned int i;
13015
13016   mask = ip->insn_mo->mask;
13017
13018   operands = insn_operands (ip);
13019   for (i = 0; i < MAX_OPERANDS; i++)
13020     if (operands->operand[i])
13021       op[i] = insn_extract_operand (ip, operands->operand[i]);
13022     else
13023       op[i] = -1;
13024
13025   expr1.X_op = O_constant;
13026   expr1.X_op_symbol = NULL;
13027   expr1.X_add_symbol = NULL;
13028   expr1.X_add_number = 1;
13029
13030   dbl = 0;
13031
13032   switch (mask)
13033     {
13034     default:
13035       abort ();
13036
13037     case M_DDIV_3:
13038       dbl = 1;
13039     case M_DIV_3:
13040       s = "mflo";
13041       goto do_div3;
13042     case M_DREM_3:
13043       dbl = 1;
13044     case M_REM_3:
13045       s = "mfhi";
13046     do_div3:
13047       start_noreorder ();
13048       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
13049       expr1.X_add_number = 2;
13050       macro_build (&expr1, "bnez", "x,p", op[2]);
13051       macro_build (NULL, "break", "6", 7);
13052
13053       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
13054          since that causes an overflow.  We should do that as well,
13055          but I don't see how to do the comparisons without a temporary
13056          register.  */
13057       end_noreorder ();
13058       macro_build (NULL, s, "x", op[0]);
13059       break;
13060
13061     case M_DIVU_3:
13062       s = "divu";
13063       s2 = "mflo";
13064       goto do_divu3;
13065     case M_REMU_3:
13066       s = "divu";
13067       s2 = "mfhi";
13068       goto do_divu3;
13069     case M_DDIVU_3:
13070       s = "ddivu";
13071       s2 = "mflo";
13072       goto do_divu3;
13073     case M_DREMU_3:
13074       s = "ddivu";
13075       s2 = "mfhi";
13076     do_divu3:
13077       start_noreorder ();
13078       macro_build (NULL, s, "0,x,y", op[1], op[2]);
13079       expr1.X_add_number = 2;
13080       macro_build (&expr1, "bnez", "x,p", op[2]);
13081       macro_build (NULL, "break", "6", 7);
13082       end_noreorder ();
13083       macro_build (NULL, s2, "x", op[0]);
13084       break;
13085
13086     case M_DMUL:
13087       dbl = 1;
13088     case M_MUL:
13089       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
13090       macro_build (NULL, "mflo", "x", op[0]);
13091       break;
13092
13093     case M_DSUBU_I:
13094       dbl = 1;
13095       goto do_subu;
13096     case M_SUBU_I:
13097     do_subu:
13098       imm_expr.X_add_number = -imm_expr.X_add_number;
13099       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
13100       break;
13101
13102     case M_SUBU_I_2:
13103       imm_expr.X_add_number = -imm_expr.X_add_number;
13104       macro_build (&imm_expr, "addiu", "x,k", op[0]);
13105       break;
13106
13107     case M_DSUBU_I_2:
13108       imm_expr.X_add_number = -imm_expr.X_add_number;
13109       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
13110       break;
13111
13112     case M_BEQ:
13113       s = "cmp";
13114       s2 = "bteqz";
13115       goto do_branch;
13116     case M_BNE:
13117       s = "cmp";
13118       s2 = "btnez";
13119       goto do_branch;
13120     case M_BLT:
13121       s = "slt";
13122       s2 = "btnez";
13123       goto do_branch;
13124     case M_BLTU:
13125       s = "sltu";
13126       s2 = "btnez";
13127       goto do_branch;
13128     case M_BLE:
13129       s = "slt";
13130       s2 = "bteqz";
13131       goto do_reverse_branch;
13132     case M_BLEU:
13133       s = "sltu";
13134       s2 = "bteqz";
13135       goto do_reverse_branch;
13136     case M_BGE:
13137       s = "slt";
13138       s2 = "bteqz";
13139       goto do_branch;
13140     case M_BGEU:
13141       s = "sltu";
13142       s2 = "bteqz";
13143       goto do_branch;
13144     case M_BGT:
13145       s = "slt";
13146       s2 = "btnez";
13147       goto do_reverse_branch;
13148     case M_BGTU:
13149       s = "sltu";
13150       s2 = "btnez";
13151
13152     do_reverse_branch:
13153       tmp = op[1];
13154       op[1] = op[0];
13155       op[0] = tmp;
13156
13157     do_branch:
13158       macro_build (NULL, s, "x,y", op[0], op[1]);
13159       macro_build (&offset_expr, s2, "p");
13160       break;
13161
13162     case M_BEQ_I:
13163       s = "cmpi";
13164       s2 = "bteqz";
13165       s3 = "x,U";
13166       goto do_branch_i;
13167     case M_BNE_I:
13168       s = "cmpi";
13169       s2 = "btnez";
13170       s3 = "x,U";
13171       goto do_branch_i;
13172     case M_BLT_I:
13173       s = "slti";
13174       s2 = "btnez";
13175       s3 = "x,8";
13176       goto do_branch_i;
13177     case M_BLTU_I:
13178       s = "sltiu";
13179       s2 = "btnez";
13180       s3 = "x,8";
13181       goto do_branch_i;
13182     case M_BLE_I:
13183       s = "slti";
13184       s2 = "btnez";
13185       s3 = "x,8";
13186       goto do_addone_branch_i;
13187     case M_BLEU_I:
13188       s = "sltiu";
13189       s2 = "btnez";
13190       s3 = "x,8";
13191       goto do_addone_branch_i;
13192     case M_BGE_I:
13193       s = "slti";
13194       s2 = "bteqz";
13195       s3 = "x,8";
13196       goto do_branch_i;
13197     case M_BGEU_I:
13198       s = "sltiu";
13199       s2 = "bteqz";
13200       s3 = "x,8";
13201       goto do_branch_i;
13202     case M_BGT_I:
13203       s = "slti";
13204       s2 = "bteqz";
13205       s3 = "x,8";
13206       goto do_addone_branch_i;
13207     case M_BGTU_I:
13208       s = "sltiu";
13209       s2 = "bteqz";
13210       s3 = "x,8";
13211
13212     do_addone_branch_i:
13213       ++imm_expr.X_add_number;
13214
13215     do_branch_i:
13216       macro_build (&imm_expr, s, s3, op[0]);
13217       macro_build (&offset_expr, s2, "p");
13218       break;
13219
13220     case M_ABS:
13221       expr1.X_add_number = 0;
13222       macro_build (&expr1, "slti", "x,8", op[1]);
13223       if (op[0] != op[1])
13224         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
13225       expr1.X_add_number = 2;
13226       macro_build (&expr1, "bteqz", "p");
13227       macro_build (NULL, "neg", "x,w", op[0], op[0]);
13228       break;
13229     }
13230 }
13231
13232 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
13233    opcode bits in *OPCODE_EXTRA.  */
13234
13235 static struct mips_opcode *
13236 mips_lookup_insn (struct hash_control *hash, const char *start,
13237                   ssize_t length, unsigned int *opcode_extra)
13238 {
13239   char *name, *dot, *p;
13240   unsigned int mask, suffix;
13241   ssize_t opend;
13242   struct mips_opcode *insn;
13243
13244   /* Make a copy of the instruction so that we can fiddle with it.  */
13245   name = alloca (length + 1);
13246   memcpy (name, start, length);
13247   name[length] = '\0';
13248
13249   /* Look up the instruction as-is.  */
13250   insn = (struct mips_opcode *) hash_find (hash, name);
13251   if (insn)
13252     return insn;
13253
13254   dot = strchr (name, '.');
13255   if (dot && dot[1])
13256     {
13257       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
13258       p = mips_parse_vu0_channels (dot + 1, &mask);
13259       if (*p == 0 && mask != 0)
13260         {
13261           *dot = 0;
13262           insn = (struct mips_opcode *) hash_find (hash, name);
13263           *dot = '.';
13264           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
13265             {
13266               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
13267               return insn;
13268             }
13269         }
13270     }
13271
13272   if (mips_opts.micromips)
13273     {
13274       /* See if there's an instruction size override suffix,
13275          either `16' or `32', at the end of the mnemonic proper,
13276          that defines the operation, i.e. before the first `.'
13277          character if any.  Strip it and retry.  */
13278       opend = dot != NULL ? dot - name : length;
13279       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
13280         suffix = 2;
13281       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
13282         suffix = 4;
13283       else
13284         suffix = 0;
13285       if (suffix)
13286         {
13287           memcpy (name + opend - 2, name + opend, length - opend + 1);
13288           insn = (struct mips_opcode *) hash_find (hash, name);
13289           if (insn)
13290             {
13291               forced_insn_length = suffix;
13292               return insn;
13293             }
13294         }
13295     }
13296
13297   return NULL;
13298 }
13299
13300 /* Assemble an instruction into its binary format.  If the instruction
13301    is a macro, set imm_expr and offset_expr to the values associated
13302    with "I" and "A" operands respectively.  Otherwise store the value
13303    of the relocatable field (if any) in offset_expr.  In both cases
13304    set offset_reloc to the relocation operators applied to offset_expr.  */
13305
13306 static void
13307 mips_ip (char *str, struct mips_cl_insn *insn)
13308 {
13309   const struct mips_opcode *first, *past;
13310   struct hash_control *hash;
13311   char format;
13312   size_t end;
13313   struct mips_operand_token *tokens;
13314   unsigned int opcode_extra;
13315
13316   if (mips_opts.micromips)
13317     {
13318       hash = micromips_op_hash;
13319       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13320     }
13321   else
13322     {
13323       hash = op_hash;
13324       past = &mips_opcodes[NUMOPCODES];
13325     }
13326   forced_insn_length = 0;
13327   opcode_extra = 0;
13328
13329   /* We first try to match an instruction up to a space or to the end.  */
13330   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13331     continue;
13332
13333   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13334   if (first == NULL)
13335     {
13336       set_insn_error (0, _("unrecognized opcode"));
13337       return;
13338     }
13339
13340   if (strcmp (first->name, "li.s") == 0)
13341     format = 'f';
13342   else if (strcmp (first->name, "li.d") == 0)
13343     format = 'd';
13344   else
13345     format = 0;
13346   tokens = mips_parse_arguments (str + end, format);
13347   if (!tokens)
13348     return;
13349
13350   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13351       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13352     set_insn_error (0, _("invalid operands"));
13353
13354   obstack_free (&mips_operand_tokens, tokens);
13355 }
13356
13357 /* As for mips_ip, but used when assembling MIPS16 code.
13358    Also set forced_insn_length to the resulting instruction size in
13359    bytes if the user explicitly requested a small or extended instruction.  */
13360
13361 static void
13362 mips16_ip (char *str, struct mips_cl_insn *insn)
13363 {
13364   char *end, *s, c;
13365   struct mips_opcode *first;
13366   struct mips_operand_token *tokens;
13367
13368   forced_insn_length = 0;
13369
13370   for (s = str; ISLOWER (*s); ++s)
13371     ;
13372   end = s;
13373   c = *end;
13374   switch (c)
13375     {
13376     case '\0':
13377       break;
13378
13379     case ' ':
13380       s++;
13381       break;
13382
13383     case '.':
13384       if (s[1] == 't' && s[2] == ' ')
13385         {
13386           forced_insn_length = 2;
13387           s += 3;
13388           break;
13389         }
13390       else if (s[1] == 'e' && s[2] == ' ')
13391         {
13392           forced_insn_length = 4;
13393           s += 3;
13394           break;
13395         }
13396       /* Fall through.  */
13397     default:
13398       set_insn_error (0, _("unrecognized opcode"));
13399       return;
13400     }
13401
13402   if (mips_opts.noautoextend && !forced_insn_length)
13403     forced_insn_length = 2;
13404
13405   *end = 0;
13406   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13407   *end = c;
13408
13409   if (!first)
13410     {
13411       set_insn_error (0, _("unrecognized opcode"));
13412       return;
13413     }
13414
13415   tokens = mips_parse_arguments (s, 0);
13416   if (!tokens)
13417     return;
13418
13419   if (!match_mips16_insns (insn, first, tokens))
13420     set_insn_error (0, _("invalid operands"));
13421
13422   obstack_free (&mips_operand_tokens, tokens);
13423 }
13424
13425 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13426    NBITS is the number of significant bits in VAL.  */
13427
13428 static unsigned long
13429 mips16_immed_extend (offsetT val, unsigned int nbits)
13430 {
13431   int extval;
13432   if (nbits == 16)
13433     {
13434       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13435       val &= 0x1f;
13436     }
13437   else if (nbits == 15)
13438     {
13439       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13440       val &= 0xf;
13441     }
13442   else
13443     {
13444       extval = ((val & 0x1f) << 6) | (val & 0x20);
13445       val = 0;
13446     }
13447   return (extval << 16) | val;
13448 }
13449
13450 /* Like decode_mips16_operand, but require the operand to be defined and
13451    require it to be an integer.  */
13452
13453 static const struct mips_int_operand *
13454 mips16_immed_operand (int type, bfd_boolean extended_p)
13455 {
13456   const struct mips_operand *operand;
13457
13458   operand = decode_mips16_operand (type, extended_p);
13459   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13460     abort ();
13461   return (const struct mips_int_operand *) operand;
13462 }
13463
13464 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13465
13466 static bfd_boolean
13467 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13468                          bfd_reloc_code_real_type reloc, offsetT sval)
13469 {
13470   int min_val, max_val;
13471
13472   min_val = mips_int_operand_min (operand);
13473   max_val = mips_int_operand_max (operand);
13474   if (reloc != BFD_RELOC_UNUSED)
13475     {
13476       if (min_val < 0)
13477         sval = SEXT_16BIT (sval);
13478       else
13479         sval &= 0xffff;
13480     }
13481
13482   return (sval >= min_val
13483           && sval <= max_val
13484           && (sval & ((1 << operand->shift) - 1)) == 0);
13485 }
13486
13487 /* Install immediate value VAL into MIPS16 instruction *INSN,
13488    extending it if necessary.  The instruction in *INSN may
13489    already be extended.
13490
13491    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13492    if none.  In the former case, VAL is a 16-bit number with no
13493    defined signedness.
13494
13495    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13496    is the length that the user requested, or 0 if none.  */
13497
13498 static void
13499 mips16_immed (char *file, unsigned int line, int type,
13500               bfd_reloc_code_real_type reloc, offsetT val,
13501               unsigned int user_insn_length, unsigned long *insn)
13502 {
13503   const struct mips_int_operand *operand;
13504   unsigned int uval, length;
13505
13506   operand = mips16_immed_operand (type, FALSE);
13507   if (!mips16_immed_in_range_p (operand, reloc, val))
13508     {
13509       /* We need an extended instruction.  */
13510       if (user_insn_length == 2)
13511         as_bad_where (file, line, _("invalid unextended operand value"));
13512       else
13513         *insn |= MIPS16_EXTEND;
13514     }
13515   else if (user_insn_length == 4)
13516     {
13517       /* The operand doesn't force an unextended instruction to be extended.
13518          Warn if the user wanted an extended instruction anyway.  */
13519       *insn |= MIPS16_EXTEND;
13520       as_warn_where (file, line,
13521                      _("extended operand requested but not required"));
13522     }
13523
13524   length = mips16_opcode_length (*insn);
13525   if (length == 4)
13526     {
13527       operand = mips16_immed_operand (type, TRUE);
13528       if (!mips16_immed_in_range_p (operand, reloc, val))
13529         as_bad_where (file, line,
13530                       _("operand value out of range for instruction"));
13531     }
13532   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13533   if (length == 2)
13534     *insn = mips_insert_operand (&operand->root, *insn, uval);
13535   else
13536     *insn |= mips16_immed_extend (uval, operand->root.size);
13537 }
13538 \f
13539 struct percent_op_match
13540 {
13541   const char *str;
13542   bfd_reloc_code_real_type reloc;
13543 };
13544
13545 static const struct percent_op_match mips_percent_op[] =
13546 {
13547   {"%lo", BFD_RELOC_LO16},
13548   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13549   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13550   {"%call16", BFD_RELOC_MIPS_CALL16},
13551   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13552   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13553   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13554   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13555   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13556   {"%got", BFD_RELOC_MIPS_GOT16},
13557   {"%gp_rel", BFD_RELOC_GPREL16},
13558   {"%half", BFD_RELOC_16},
13559   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13560   {"%higher", BFD_RELOC_MIPS_HIGHER},
13561   {"%neg", BFD_RELOC_MIPS_SUB},
13562   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13563   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13564   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13565   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13566   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13567   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13568   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13569   {"%hi", BFD_RELOC_HI16_S}
13570 };
13571
13572 static const struct percent_op_match mips16_percent_op[] =
13573 {
13574   {"%lo", BFD_RELOC_MIPS16_LO16},
13575   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13576   {"%got", BFD_RELOC_MIPS16_GOT16},
13577   {"%call16", BFD_RELOC_MIPS16_CALL16},
13578   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13579   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13580   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13581   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13582   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13583   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13584   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13585   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13586 };
13587
13588
13589 /* Return true if *STR points to a relocation operator.  When returning true,
13590    move *STR over the operator and store its relocation code in *RELOC.
13591    Leave both *STR and *RELOC alone when returning false.  */
13592
13593 static bfd_boolean
13594 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13595 {
13596   const struct percent_op_match *percent_op;
13597   size_t limit, i;
13598
13599   if (mips_opts.mips16)
13600     {
13601       percent_op = mips16_percent_op;
13602       limit = ARRAY_SIZE (mips16_percent_op);
13603     }
13604   else
13605     {
13606       percent_op = mips_percent_op;
13607       limit = ARRAY_SIZE (mips_percent_op);
13608     }
13609
13610   for (i = 0; i < limit; i++)
13611     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13612       {
13613         int len = strlen (percent_op[i].str);
13614
13615         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13616           continue;
13617
13618         *str += strlen (percent_op[i].str);
13619         *reloc = percent_op[i].reloc;
13620
13621         /* Check whether the output BFD supports this relocation.
13622            If not, issue an error and fall back on something safe.  */
13623         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13624           {
13625             as_bad (_("relocation %s isn't supported by the current ABI"),
13626                     percent_op[i].str);
13627             *reloc = BFD_RELOC_UNUSED;
13628           }
13629         return TRUE;
13630       }
13631   return FALSE;
13632 }
13633
13634
13635 /* Parse string STR as a 16-bit relocatable operand.  Store the
13636    expression in *EP and the relocations in the array starting
13637    at RELOC.  Return the number of relocation operators used.
13638
13639    On exit, EXPR_END points to the first character after the expression.  */
13640
13641 static size_t
13642 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13643                        char *str)
13644 {
13645   bfd_reloc_code_real_type reversed_reloc[3];
13646   size_t reloc_index, i;
13647   int crux_depth, str_depth;
13648   char *crux;
13649
13650   /* Search for the start of the main expression, recoding relocations
13651      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13652      of the main expression and with CRUX_DEPTH containing the number
13653      of open brackets at that point.  */
13654   reloc_index = -1;
13655   str_depth = 0;
13656   do
13657     {
13658       reloc_index++;
13659       crux = str;
13660       crux_depth = str_depth;
13661
13662       /* Skip over whitespace and brackets, keeping count of the number
13663          of brackets.  */
13664       while (*str == ' ' || *str == '\t' || *str == '(')
13665         if (*str++ == '(')
13666           str_depth++;
13667     }
13668   while (*str == '%'
13669          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13670          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13671
13672   my_getExpression (ep, crux);
13673   str = expr_end;
13674
13675   /* Match every open bracket.  */
13676   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13677     if (*str++ == ')')
13678       crux_depth--;
13679
13680   if (crux_depth > 0)
13681     as_bad (_("unclosed '('"));
13682
13683   expr_end = str;
13684
13685   if (reloc_index != 0)
13686     {
13687       prev_reloc_op_frag = frag_now;
13688       for (i = 0; i < reloc_index; i++)
13689         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13690     }
13691
13692   return reloc_index;
13693 }
13694
13695 static void
13696 my_getExpression (expressionS *ep, char *str)
13697 {
13698   char *save_in;
13699
13700   save_in = input_line_pointer;
13701   input_line_pointer = str;
13702   expression (ep);
13703   expr_end = input_line_pointer;
13704   input_line_pointer = save_in;
13705 }
13706
13707 char *
13708 md_atof (int type, char *litP, int *sizeP)
13709 {
13710   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13711 }
13712
13713 void
13714 md_number_to_chars (char *buf, valueT val, int n)
13715 {
13716   if (target_big_endian)
13717     number_to_chars_bigendian (buf, val, n);
13718   else
13719     number_to_chars_littleendian (buf, val, n);
13720 }
13721 \f
13722 static int support_64bit_objects(void)
13723 {
13724   const char **list, **l;
13725   int yes;
13726
13727   list = bfd_target_list ();
13728   for (l = list; *l != NULL; l++)
13729     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13730         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13731       break;
13732   yes = (*l != NULL);
13733   free (list);
13734   return yes;
13735 }
13736
13737 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13738    NEW_VALUE.  Warn if another value was already specified.  Note:
13739    we have to defer parsing the -march and -mtune arguments in order
13740    to handle 'from-abi' correctly, since the ABI might be specified
13741    in a later argument.  */
13742
13743 static void
13744 mips_set_option_string (const char **string_ptr, const char *new_value)
13745 {
13746   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13747     as_warn (_("a different %s was already specified, is now %s"),
13748              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13749              new_value);
13750
13751   *string_ptr = new_value;
13752 }
13753
13754 int
13755 md_parse_option (int c, char *arg)
13756 {
13757   unsigned int i;
13758
13759   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13760     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13761       {
13762         file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
13763                                            c == mips_ases[i].option_on);
13764         return 1;
13765       }
13766
13767   switch (c)
13768     {
13769     case OPTION_CONSTRUCT_FLOATS:
13770       mips_disable_float_construction = 0;
13771       break;
13772
13773     case OPTION_NO_CONSTRUCT_FLOATS:
13774       mips_disable_float_construction = 1;
13775       break;
13776
13777     case OPTION_TRAP:
13778       mips_trap = 1;
13779       break;
13780
13781     case OPTION_BREAK:
13782       mips_trap = 0;
13783       break;
13784
13785     case OPTION_EB:
13786       target_big_endian = 1;
13787       break;
13788
13789     case OPTION_EL:
13790       target_big_endian = 0;
13791       break;
13792
13793     case 'O':
13794       if (arg == NULL)
13795         mips_optimize = 1;
13796       else if (arg[0] == '0')
13797         mips_optimize = 0;
13798       else if (arg[0] == '1')
13799         mips_optimize = 1;
13800       else
13801         mips_optimize = 2;
13802       break;
13803
13804     case 'g':
13805       if (arg == NULL)
13806         mips_debug = 2;
13807       else
13808         mips_debug = atoi (arg);
13809       break;
13810
13811     case OPTION_MIPS1:
13812       file_mips_opts.isa = ISA_MIPS1;
13813       break;
13814
13815     case OPTION_MIPS2:
13816       file_mips_opts.isa = ISA_MIPS2;
13817       break;
13818
13819     case OPTION_MIPS3:
13820       file_mips_opts.isa = ISA_MIPS3;
13821       break;
13822
13823     case OPTION_MIPS4:
13824       file_mips_opts.isa = ISA_MIPS4;
13825       break;
13826
13827     case OPTION_MIPS5:
13828       file_mips_opts.isa = ISA_MIPS5;
13829       break;
13830
13831     case OPTION_MIPS32:
13832       file_mips_opts.isa = ISA_MIPS32;
13833       break;
13834
13835     case OPTION_MIPS32R2:
13836       file_mips_opts.isa = ISA_MIPS32R2;
13837       break;
13838
13839     case OPTION_MIPS32R3:
13840       file_mips_opts.isa = ISA_MIPS32R3;
13841       break;
13842
13843     case OPTION_MIPS32R5:
13844       file_mips_opts.isa = ISA_MIPS32R5;
13845       break;
13846
13847     case OPTION_MIPS64R2:
13848       file_mips_opts.isa = ISA_MIPS64R2;
13849       break;
13850
13851     case OPTION_MIPS64R3:
13852       file_mips_opts.isa = ISA_MIPS64R3;
13853       break;
13854
13855     case OPTION_MIPS64R5:
13856       file_mips_opts.isa = ISA_MIPS64R5;
13857       break;
13858
13859     case OPTION_MIPS64:
13860       file_mips_opts.isa = ISA_MIPS64;
13861       break;
13862
13863     case OPTION_MTUNE:
13864       mips_set_option_string (&mips_tune_string, arg);
13865       break;
13866
13867     case OPTION_MARCH:
13868       mips_set_option_string (&mips_arch_string, arg);
13869       break;
13870
13871     case OPTION_M4650:
13872       mips_set_option_string (&mips_arch_string, "4650");
13873       mips_set_option_string (&mips_tune_string, "4650");
13874       break;
13875
13876     case OPTION_NO_M4650:
13877       break;
13878
13879     case OPTION_M4010:
13880       mips_set_option_string (&mips_arch_string, "4010");
13881       mips_set_option_string (&mips_tune_string, "4010");
13882       break;
13883
13884     case OPTION_NO_M4010:
13885       break;
13886
13887     case OPTION_M4100:
13888       mips_set_option_string (&mips_arch_string, "4100");
13889       mips_set_option_string (&mips_tune_string, "4100");
13890       break;
13891
13892     case OPTION_NO_M4100:
13893       break;
13894
13895     case OPTION_M3900:
13896       mips_set_option_string (&mips_arch_string, "3900");
13897       mips_set_option_string (&mips_tune_string, "3900");
13898       break;
13899
13900     case OPTION_NO_M3900:
13901       break;
13902
13903     case OPTION_MICROMIPS:
13904       if (file_mips_opts.mips16 == 1)
13905         {
13906           as_bad (_("-mmicromips cannot be used with -mips16"));
13907           return 0;
13908         }
13909       file_mips_opts.micromips = 1;
13910       mips_no_prev_insn ();
13911       break;
13912
13913     case OPTION_NO_MICROMIPS:
13914       file_mips_opts.micromips = 0;
13915       mips_no_prev_insn ();
13916       break;
13917
13918     case OPTION_MIPS16:
13919       if (file_mips_opts.micromips == 1)
13920         {
13921           as_bad (_("-mips16 cannot be used with -micromips"));
13922           return 0;
13923         }
13924       file_mips_opts.mips16 = 1;
13925       mips_no_prev_insn ();
13926       break;
13927
13928     case OPTION_NO_MIPS16:
13929       file_mips_opts.mips16 = 0;
13930       mips_no_prev_insn ();
13931       break;
13932
13933     case OPTION_FIX_24K:
13934       mips_fix_24k = 1;
13935       break;
13936
13937     case OPTION_NO_FIX_24K:
13938       mips_fix_24k = 0;
13939       break;
13940
13941     case OPTION_FIX_RM7000:
13942       mips_fix_rm7000 = 1;
13943       break;
13944
13945     case OPTION_NO_FIX_RM7000:
13946       mips_fix_rm7000 = 0;
13947       break;
13948
13949     case OPTION_FIX_LOONGSON2F_JUMP:
13950       mips_fix_loongson2f_jump = TRUE;
13951       break;
13952
13953     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13954       mips_fix_loongson2f_jump = FALSE;
13955       break;
13956
13957     case OPTION_FIX_LOONGSON2F_NOP:
13958       mips_fix_loongson2f_nop = TRUE;
13959       break;
13960
13961     case OPTION_NO_FIX_LOONGSON2F_NOP:
13962       mips_fix_loongson2f_nop = FALSE;
13963       break;
13964
13965     case OPTION_FIX_VR4120:
13966       mips_fix_vr4120 = 1;
13967       break;
13968
13969     case OPTION_NO_FIX_VR4120:
13970       mips_fix_vr4120 = 0;
13971       break;
13972
13973     case OPTION_FIX_VR4130:
13974       mips_fix_vr4130 = 1;
13975       break;
13976
13977     case OPTION_NO_FIX_VR4130:
13978       mips_fix_vr4130 = 0;
13979       break;
13980
13981     case OPTION_FIX_CN63XXP1:
13982       mips_fix_cn63xxp1 = TRUE;
13983       break;
13984
13985     case OPTION_NO_FIX_CN63XXP1:
13986       mips_fix_cn63xxp1 = FALSE;
13987       break;
13988
13989     case OPTION_RELAX_BRANCH:
13990       mips_relax_branch = 1;
13991       break;
13992
13993     case OPTION_NO_RELAX_BRANCH:
13994       mips_relax_branch = 0;
13995       break;
13996
13997     case OPTION_INSN32:
13998       file_mips_opts.insn32 = TRUE;
13999       break;
14000
14001     case OPTION_NO_INSN32:
14002       file_mips_opts.insn32 = FALSE;
14003       break;
14004
14005     case OPTION_MSHARED:
14006       mips_in_shared = TRUE;
14007       break;
14008
14009     case OPTION_MNO_SHARED:
14010       mips_in_shared = FALSE;
14011       break;
14012
14013     case OPTION_MSYM32:
14014       file_mips_opts.sym32 = TRUE;
14015       break;
14016
14017     case OPTION_MNO_SYM32:
14018       file_mips_opts.sym32 = FALSE;
14019       break;
14020
14021       /* When generating ELF code, we permit -KPIC and -call_shared to
14022          select SVR4_PIC, and -non_shared to select no PIC.  This is
14023          intended to be compatible with Irix 5.  */
14024     case OPTION_CALL_SHARED:
14025       mips_pic = SVR4_PIC;
14026       mips_abicalls = TRUE;
14027       break;
14028
14029     case OPTION_CALL_NONPIC:
14030       mips_pic = NO_PIC;
14031       mips_abicalls = TRUE;
14032       break;
14033
14034     case OPTION_NON_SHARED:
14035       mips_pic = NO_PIC;
14036       mips_abicalls = FALSE;
14037       break;
14038
14039       /* The -xgot option tells the assembler to use 32 bit offsets
14040          when accessing the got in SVR4_PIC mode.  It is for Irix
14041          compatibility.  */
14042     case OPTION_XGOT:
14043       mips_big_got = 1;
14044       break;
14045
14046     case 'G':
14047       g_switch_value = atoi (arg);
14048       g_switch_seen = 1;
14049       break;
14050
14051       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14052          and -mabi=64.  */
14053     case OPTION_32:
14054       mips_abi = O32_ABI;
14055       break;
14056
14057     case OPTION_N32:
14058       mips_abi = N32_ABI;
14059       break;
14060
14061     case OPTION_64:
14062       mips_abi = N64_ABI;
14063       if (!support_64bit_objects())
14064         as_fatal (_("no compiled in support for 64 bit object file format"));
14065       break;
14066
14067     case OPTION_GP32:
14068       file_mips_opts.gp = 32;
14069       break;
14070
14071     case OPTION_GP64:
14072       file_mips_opts.gp = 64;
14073       break;
14074
14075     case OPTION_FP32:
14076       file_mips_opts.fp = 32;
14077       break;
14078
14079     case OPTION_FPXX:
14080       file_mips_opts.fp = 0;
14081       break;
14082
14083     case OPTION_FP64:
14084       file_mips_opts.fp = 64;
14085       break;
14086
14087     case OPTION_ODD_SPREG:
14088       file_mips_opts.oddspreg = 1;
14089       break;
14090
14091     case OPTION_NO_ODD_SPREG:
14092       file_mips_opts.oddspreg = 0;
14093       break;
14094
14095     case OPTION_SINGLE_FLOAT:
14096       file_mips_opts.single_float = 1;
14097       break;
14098
14099     case OPTION_DOUBLE_FLOAT:
14100       file_mips_opts.single_float = 0;
14101       break;
14102
14103     case OPTION_SOFT_FLOAT:
14104       file_mips_opts.soft_float = 1;
14105       break;
14106
14107     case OPTION_HARD_FLOAT:
14108       file_mips_opts.soft_float = 0;
14109       break;
14110
14111     case OPTION_MABI:
14112       if (strcmp (arg, "32") == 0)
14113         mips_abi = O32_ABI;
14114       else if (strcmp (arg, "o64") == 0)
14115         mips_abi = O64_ABI;
14116       else if (strcmp (arg, "n32") == 0)
14117         mips_abi = N32_ABI;
14118       else if (strcmp (arg, "64") == 0)
14119         {
14120           mips_abi = N64_ABI;
14121           if (! support_64bit_objects())
14122             as_fatal (_("no compiled in support for 64 bit object file "
14123                         "format"));
14124         }
14125       else if (strcmp (arg, "eabi") == 0)
14126         mips_abi = EABI_ABI;
14127       else
14128         {
14129           as_fatal (_("invalid abi -mabi=%s"), arg);
14130           return 0;
14131         }
14132       break;
14133
14134     case OPTION_M7000_HILO_FIX:
14135       mips_7000_hilo_fix = TRUE;
14136       break;
14137
14138     case OPTION_MNO_7000_HILO_FIX:
14139       mips_7000_hilo_fix = FALSE;
14140       break;
14141
14142     case OPTION_MDEBUG:
14143       mips_flag_mdebug = TRUE;
14144       break;
14145
14146     case OPTION_NO_MDEBUG:
14147       mips_flag_mdebug = FALSE;
14148       break;
14149
14150     case OPTION_PDR:
14151       mips_flag_pdr = TRUE;
14152       break;
14153
14154     case OPTION_NO_PDR:
14155       mips_flag_pdr = FALSE;
14156       break;
14157
14158     case OPTION_MVXWORKS_PIC:
14159       mips_pic = VXWORKS_PIC;
14160       break;
14161
14162     case OPTION_NAN:
14163       if (strcmp (arg, "2008") == 0)
14164         mips_flag_nan2008 = TRUE;
14165       else if (strcmp (arg, "legacy") == 0)
14166         mips_flag_nan2008 = FALSE;
14167       else
14168         {
14169           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
14170           return 0;
14171         }
14172       break;
14173
14174     default:
14175       return 0;
14176     }
14177
14178     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14179
14180   return 1;
14181 }
14182 \f
14183 /* Set up globals to tune for the ISA or processor described by INFO.  */
14184
14185 static void
14186 mips_set_tune (const struct mips_cpu_info *info)
14187 {
14188   if (info != 0)
14189     mips_tune = info->cpu;
14190 }
14191
14192
14193 void
14194 mips_after_parse_args (void)
14195 {
14196   const struct mips_cpu_info *arch_info = 0;
14197   const struct mips_cpu_info *tune_info = 0;
14198
14199   /* GP relative stuff not working for PE */
14200   if (strncmp (TARGET_OS, "pe", 2) == 0)
14201     {
14202       if (g_switch_seen && g_switch_value != 0)
14203         as_bad (_("-G not supported in this configuration"));
14204       g_switch_value = 0;
14205     }
14206
14207   if (mips_abi == NO_ABI)
14208     mips_abi = MIPS_DEFAULT_ABI;
14209
14210   /* The following code determines the architecture.
14211      Similar code was added to GCC 3.3 (see override_options() in
14212      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14213      as much as possible.  */
14214
14215   if (mips_arch_string != 0)
14216     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14217
14218   if (file_mips_opts.isa != ISA_UNKNOWN)
14219     {
14220       /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
14221          ISA level specified by -mipsN, while arch_info->isa contains
14222          the -march selection (if any).  */
14223       if (arch_info != 0)
14224         {
14225           /* -march takes precedence over -mipsN, since it is more descriptive.
14226              There's no harm in specifying both as long as the ISA levels
14227              are the same.  */
14228           if (file_mips_opts.isa != arch_info->isa)
14229             as_bad (_("-%s conflicts with the other architecture options,"
14230                       " which imply -%s"),
14231                     mips_cpu_info_from_isa (file_mips_opts.isa)->name,
14232                     mips_cpu_info_from_isa (arch_info->isa)->name);
14233         }
14234       else
14235         arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
14236     }
14237
14238   if (arch_info == 0)
14239     {
14240       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14241       gas_assert (arch_info);
14242     }
14243
14244   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14245     as_bad (_("-march=%s is not compatible with the selected ABI"),
14246             arch_info->name);
14247
14248   file_mips_opts.arch = arch_info->cpu;
14249   file_mips_opts.isa = arch_info->isa;
14250
14251   /* Set up initial mips_opts state.  */
14252   mips_opts = file_mips_opts;
14253
14254   /* The register size inference code is now placed in
14255      file_mips_check_options.  */
14256
14257   /* Optimize for file_mips_opts.arch, unless -mtune selects a different
14258      processor.  */
14259   if (mips_tune_string != 0)
14260     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14261
14262   if (tune_info == 0)
14263     mips_set_tune (arch_info);
14264   else
14265     mips_set_tune (tune_info);
14266
14267   if (mips_flag_mdebug < 0)
14268     mips_flag_mdebug = 0;
14269 }
14270 \f
14271 void
14272 mips_init_after_args (void)
14273 {
14274   /* initialize opcodes */
14275   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14276   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14277 }
14278
14279 long
14280 md_pcrel_from (fixS *fixP)
14281 {
14282   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14283   switch (fixP->fx_r_type)
14284     {
14285     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14286     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14287       /* Return the address of the delay slot.  */
14288       return addr + 2;
14289
14290     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14291     case BFD_RELOC_MICROMIPS_JMP:
14292     case BFD_RELOC_16_PCREL_S2:
14293     case BFD_RELOC_MIPS_JMP:
14294       /* Return the address of the delay slot.  */
14295       return addr + 4;
14296
14297     default:
14298       return addr;
14299     }
14300 }
14301
14302 /* This is called before the symbol table is processed.  In order to
14303    work with gcc when using mips-tfile, we must keep all local labels.
14304    However, in other cases, we want to discard them.  If we were
14305    called with -g, but we didn't see any debugging information, it may
14306    mean that gcc is smuggling debugging information through to
14307    mips-tfile, in which case we must generate all local labels.  */
14308
14309 void
14310 mips_frob_file_before_adjust (void)
14311 {
14312 #ifndef NO_ECOFF_DEBUGGING
14313   if (ECOFF_DEBUGGING
14314       && mips_debug != 0
14315       && ! ecoff_debugging_seen)
14316     flag_keep_locals = 1;
14317 #endif
14318 }
14319
14320 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14321    the corresponding LO16 reloc.  This is called before md_apply_fix and
14322    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14323    relocation operators.
14324
14325    For our purposes, a %lo() expression matches a %got() or %hi()
14326    expression if:
14327
14328       (a) it refers to the same symbol; and
14329       (b) the offset applied in the %lo() expression is no lower than
14330           the offset applied in the %got() or %hi().
14331
14332    (b) allows us to cope with code like:
14333
14334         lui     $4,%hi(foo)
14335         lh      $4,%lo(foo+2)($4)
14336
14337    ...which is legal on RELA targets, and has a well-defined behaviour
14338    if the user knows that adding 2 to "foo" will not induce a carry to
14339    the high 16 bits.
14340
14341    When several %lo()s match a particular %got() or %hi(), we use the
14342    following rules to distinguish them:
14343
14344      (1) %lo()s with smaller offsets are a better match than %lo()s with
14345          higher offsets.
14346
14347      (2) %lo()s with no matching %got() or %hi() are better than those
14348          that already have a matching %got() or %hi().
14349
14350      (3) later %lo()s are better than earlier %lo()s.
14351
14352    These rules are applied in order.
14353
14354    (1) means, among other things, that %lo()s with identical offsets are
14355    chosen if they exist.
14356
14357    (2) means that we won't associate several high-part relocations with
14358    the same low-part relocation unless there's no alternative.  Having
14359    several high parts for the same low part is a GNU extension; this rule
14360    allows careful users to avoid it.
14361
14362    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14363    with the last high-part relocation being at the front of the list.
14364    It therefore makes sense to choose the last matching low-part
14365    relocation, all other things being equal.  It's also easier
14366    to code that way.  */
14367
14368 void
14369 mips_frob_file (void)
14370 {
14371   struct mips_hi_fixup *l;
14372   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14373
14374   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14375     {
14376       segment_info_type *seginfo;
14377       bfd_boolean matched_lo_p;
14378       fixS **hi_pos, **lo_pos, **pos;
14379
14380       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14381
14382       /* If a GOT16 relocation turns out to be against a global symbol,
14383          there isn't supposed to be a matching LO.  Ignore %gots against
14384          constants; we'll report an error for those later.  */
14385       if (got16_reloc_p (l->fixp->fx_r_type)
14386           && !(l->fixp->fx_addsy
14387                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14388         continue;
14389
14390       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14391       if (fixup_has_matching_lo_p (l->fixp))
14392         continue;
14393
14394       seginfo = seg_info (l->seg);
14395
14396       /* Set HI_POS to the position of this relocation in the chain.
14397          Set LO_POS to the position of the chosen low-part relocation.
14398          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14399          relocation that matches an immediately-preceding high-part
14400          relocation.  */
14401       hi_pos = NULL;
14402       lo_pos = NULL;
14403       matched_lo_p = FALSE;
14404       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14405
14406       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14407         {
14408           if (*pos == l->fixp)
14409             hi_pos = pos;
14410
14411           if ((*pos)->fx_r_type == looking_for_rtype
14412               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14413               && (*pos)->fx_offset >= l->fixp->fx_offset
14414               && (lo_pos == NULL
14415                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14416                   || (!matched_lo_p
14417                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14418             lo_pos = pos;
14419
14420           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14421                           && fixup_has_matching_lo_p (*pos));
14422         }
14423
14424       /* If we found a match, remove the high-part relocation from its
14425          current position and insert it before the low-part relocation.
14426          Make the offsets match so that fixup_has_matching_lo_p()
14427          will return true.
14428
14429          We don't warn about unmatched high-part relocations since some
14430          versions of gcc have been known to emit dead "lui ...%hi(...)"
14431          instructions.  */
14432       if (lo_pos != NULL)
14433         {
14434           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14435           if (l->fixp->fx_next != *lo_pos)
14436             {
14437               *hi_pos = l->fixp->fx_next;
14438               l->fixp->fx_next = *lo_pos;
14439               *lo_pos = l->fixp;
14440             }
14441         }
14442     }
14443 }
14444
14445 int
14446 mips_force_relocation (fixS *fixp)
14447 {
14448   if (generic_force_reloc (fixp))
14449     return 1;
14450
14451   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14452      so that the linker relaxation can update targets.  */
14453   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14454       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14455       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14456     return 1;
14457
14458   return 0;
14459 }
14460
14461 /* Read the instruction associated with RELOC from BUF.  */
14462
14463 static unsigned int
14464 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14465 {
14466   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14467     return read_compressed_insn (buf, 4);
14468   else
14469     return read_insn (buf);
14470 }
14471
14472 /* Write instruction INSN to BUF, given that it has been relocated
14473    by RELOC.  */
14474
14475 static void
14476 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14477                   unsigned long insn)
14478 {
14479   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14480     write_compressed_insn (buf, insn, 4);
14481   else
14482     write_insn (buf, insn);
14483 }
14484
14485 /* Apply a fixup to the object file.  */
14486
14487 void
14488 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14489 {
14490   char *buf;
14491   unsigned long insn;
14492   reloc_howto_type *howto;
14493
14494   if (fixP->fx_pcrel)
14495     switch (fixP->fx_r_type)
14496       {
14497       case BFD_RELOC_16_PCREL_S2:
14498       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14499       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14500       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14501       case BFD_RELOC_32_PCREL:
14502         break;
14503
14504       case BFD_RELOC_32:
14505         fixP->fx_r_type = BFD_RELOC_32_PCREL;
14506         break;
14507
14508       default:
14509         as_bad_where (fixP->fx_file, fixP->fx_line,
14510                       _("PC-relative reference to a different section"));
14511         break;
14512       }
14513
14514   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
14515      that have no MIPS ELF equivalent.  */
14516   if (fixP->fx_r_type != BFD_RELOC_8)
14517     {
14518       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14519       if (!howto)
14520         return;
14521     }
14522
14523   gas_assert (fixP->fx_size == 2
14524               || fixP->fx_size == 4
14525               || fixP->fx_r_type == BFD_RELOC_8
14526               || fixP->fx_r_type == BFD_RELOC_16
14527               || fixP->fx_r_type == BFD_RELOC_64
14528               || fixP->fx_r_type == BFD_RELOC_CTOR
14529               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14530               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14531               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14532               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14533               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14534
14535   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14536
14537   /* Don't treat parts of a composite relocation as done.  There are two
14538      reasons for this:
14539
14540      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14541          should nevertheless be emitted if the first part is.
14542
14543      (2) In normal usage, composite relocations are never assembly-time
14544          constants.  The easiest way of dealing with the pathological
14545          exceptions is to generate a relocation against STN_UNDEF and
14546          leave everything up to the linker.  */
14547   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14548     fixP->fx_done = 1;
14549
14550   switch (fixP->fx_r_type)
14551     {
14552     case BFD_RELOC_MIPS_TLS_GD:
14553     case BFD_RELOC_MIPS_TLS_LDM:
14554     case BFD_RELOC_MIPS_TLS_DTPREL32:
14555     case BFD_RELOC_MIPS_TLS_DTPREL64:
14556     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14557     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14558     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14559     case BFD_RELOC_MIPS_TLS_TPREL32:
14560     case BFD_RELOC_MIPS_TLS_TPREL64:
14561     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14562     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14563     case BFD_RELOC_MICROMIPS_TLS_GD:
14564     case BFD_RELOC_MICROMIPS_TLS_LDM:
14565     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14566     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14567     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14568     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14569     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14570     case BFD_RELOC_MIPS16_TLS_GD:
14571     case BFD_RELOC_MIPS16_TLS_LDM:
14572     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14573     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14574     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14575     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14576     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14577       if (!fixP->fx_addsy)
14578         {
14579           as_bad_where (fixP->fx_file, fixP->fx_line,
14580                         _("TLS relocation against a constant"));
14581           break;
14582         }
14583       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14584       /* fall through */
14585
14586     case BFD_RELOC_MIPS_JMP:
14587     case BFD_RELOC_MIPS_SHIFT5:
14588     case BFD_RELOC_MIPS_SHIFT6:
14589     case BFD_RELOC_MIPS_GOT_DISP:
14590     case BFD_RELOC_MIPS_GOT_PAGE:
14591     case BFD_RELOC_MIPS_GOT_OFST:
14592     case BFD_RELOC_MIPS_SUB:
14593     case BFD_RELOC_MIPS_INSERT_A:
14594     case BFD_RELOC_MIPS_INSERT_B:
14595     case BFD_RELOC_MIPS_DELETE:
14596     case BFD_RELOC_MIPS_HIGHEST:
14597     case BFD_RELOC_MIPS_HIGHER:
14598     case BFD_RELOC_MIPS_SCN_DISP:
14599     case BFD_RELOC_MIPS_REL16:
14600     case BFD_RELOC_MIPS_RELGOT:
14601     case BFD_RELOC_MIPS_JALR:
14602     case BFD_RELOC_HI16:
14603     case BFD_RELOC_HI16_S:
14604     case BFD_RELOC_LO16:
14605     case BFD_RELOC_GPREL16:
14606     case BFD_RELOC_MIPS_LITERAL:
14607     case BFD_RELOC_MIPS_CALL16:
14608     case BFD_RELOC_MIPS_GOT16:
14609     case BFD_RELOC_GPREL32:
14610     case BFD_RELOC_MIPS_GOT_HI16:
14611     case BFD_RELOC_MIPS_GOT_LO16:
14612     case BFD_RELOC_MIPS_CALL_HI16:
14613     case BFD_RELOC_MIPS_CALL_LO16:
14614     case BFD_RELOC_MIPS16_GPREL:
14615     case BFD_RELOC_MIPS16_GOT16:
14616     case BFD_RELOC_MIPS16_CALL16:
14617     case BFD_RELOC_MIPS16_HI16:
14618     case BFD_RELOC_MIPS16_HI16_S:
14619     case BFD_RELOC_MIPS16_LO16:
14620     case BFD_RELOC_MIPS16_JMP:
14621     case BFD_RELOC_MICROMIPS_JMP:
14622     case BFD_RELOC_MICROMIPS_GOT_DISP:
14623     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14624     case BFD_RELOC_MICROMIPS_GOT_OFST:
14625     case BFD_RELOC_MICROMIPS_SUB:
14626     case BFD_RELOC_MICROMIPS_HIGHEST:
14627     case BFD_RELOC_MICROMIPS_HIGHER:
14628     case BFD_RELOC_MICROMIPS_SCN_DISP:
14629     case BFD_RELOC_MICROMIPS_JALR:
14630     case BFD_RELOC_MICROMIPS_HI16:
14631     case BFD_RELOC_MICROMIPS_HI16_S:
14632     case BFD_RELOC_MICROMIPS_LO16:
14633     case BFD_RELOC_MICROMIPS_GPREL16:
14634     case BFD_RELOC_MICROMIPS_LITERAL:
14635     case BFD_RELOC_MICROMIPS_CALL16:
14636     case BFD_RELOC_MICROMIPS_GOT16:
14637     case BFD_RELOC_MICROMIPS_GOT_HI16:
14638     case BFD_RELOC_MICROMIPS_GOT_LO16:
14639     case BFD_RELOC_MICROMIPS_CALL_HI16:
14640     case BFD_RELOC_MICROMIPS_CALL_LO16:
14641     case BFD_RELOC_MIPS_EH:
14642       if (fixP->fx_done)
14643         {
14644           offsetT value;
14645
14646           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14647             {
14648               insn = read_reloc_insn (buf, fixP->fx_r_type);
14649               if (mips16_reloc_p (fixP->fx_r_type))
14650                 insn |= mips16_immed_extend (value, 16);
14651               else
14652                 insn |= (value & 0xffff);
14653               write_reloc_insn (buf, fixP->fx_r_type, insn);
14654             }
14655           else
14656             as_bad_where (fixP->fx_file, fixP->fx_line,
14657                           _("unsupported constant in relocation"));
14658         }
14659       break;
14660
14661     case BFD_RELOC_64:
14662       /* This is handled like BFD_RELOC_32, but we output a sign
14663          extended value if we are only 32 bits.  */
14664       if (fixP->fx_done)
14665         {
14666           if (8 <= sizeof (valueT))
14667             md_number_to_chars (buf, *valP, 8);
14668           else
14669             {
14670               valueT hiv;
14671
14672               if ((*valP & 0x80000000) != 0)
14673                 hiv = 0xffffffff;
14674               else
14675                 hiv = 0;
14676               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14677               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14678             }
14679         }
14680       break;
14681
14682     case BFD_RELOC_RVA:
14683     case BFD_RELOC_32:
14684     case BFD_RELOC_32_PCREL:
14685     case BFD_RELOC_16:
14686     case BFD_RELOC_8:
14687       /* If we are deleting this reloc entry, we must fill in the
14688          value now.  This can happen if we have a .word which is not
14689          resolved when it appears but is later defined.  */
14690       if (fixP->fx_done)
14691         md_number_to_chars (buf, *valP, fixP->fx_size);
14692       break;
14693
14694     case BFD_RELOC_16_PCREL_S2:
14695       if ((*valP & 0x3) != 0)
14696         as_bad_where (fixP->fx_file, fixP->fx_line,
14697                       _("branch to misaligned address (%lx)"), (long) *valP);
14698
14699       /* We need to save the bits in the instruction since fixup_segment()
14700          might be deleting the relocation entry (i.e., a branch within
14701          the current segment).  */
14702       if (! fixP->fx_done)
14703         break;
14704
14705       /* Update old instruction data.  */
14706       insn = read_insn (buf);
14707
14708       if (*valP + 0x20000 <= 0x3ffff)
14709         {
14710           insn |= (*valP >> 2) & 0xffff;
14711           write_insn (buf, insn);
14712         }
14713       else if (mips_pic == NO_PIC
14714                && fixP->fx_done
14715                && fixP->fx_frag->fr_address >= text_section->vma
14716                && (fixP->fx_frag->fr_address
14717                    < text_section->vma + bfd_get_section_size (text_section))
14718                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14719                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14720                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14721         {
14722           /* The branch offset is too large.  If this is an
14723              unconditional branch, and we are not generating PIC code,
14724              we can convert it to an absolute jump instruction.  */
14725           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14726             insn = 0x0c000000;  /* jal */
14727           else
14728             insn = 0x08000000;  /* j */
14729           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14730           fixP->fx_done = 0;
14731           fixP->fx_addsy = section_symbol (text_section);
14732           *valP += md_pcrel_from (fixP);
14733           write_insn (buf, insn);
14734         }
14735       else
14736         {
14737           /* If we got here, we have branch-relaxation disabled,
14738              and there's nothing we can do to fix this instruction
14739              without turning it into a longer sequence.  */
14740           as_bad_where (fixP->fx_file, fixP->fx_line,
14741                         _("branch out of range"));
14742         }
14743       break;
14744
14745     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14746     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14747     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14748       /* We adjust the offset back to even.  */
14749       if ((*valP & 0x1) != 0)
14750         --(*valP);
14751
14752       if (! fixP->fx_done)
14753         break;
14754
14755       /* Should never visit here, because we keep the relocation.  */
14756       abort ();
14757       break;
14758
14759     case BFD_RELOC_VTABLE_INHERIT:
14760       fixP->fx_done = 0;
14761       if (fixP->fx_addsy
14762           && !S_IS_DEFINED (fixP->fx_addsy)
14763           && !S_IS_WEAK (fixP->fx_addsy))
14764         S_SET_WEAK (fixP->fx_addsy);
14765       break;
14766
14767     case BFD_RELOC_VTABLE_ENTRY:
14768       fixP->fx_done = 0;
14769       break;
14770
14771     default:
14772       abort ();
14773     }
14774
14775   /* Remember value for tc_gen_reloc.  */
14776   fixP->fx_addnumber = *valP;
14777 }
14778
14779 static symbolS *
14780 get_symbol (void)
14781 {
14782   int c;
14783   char *name;
14784   symbolS *p;
14785
14786   name = input_line_pointer;
14787   c = get_symbol_end ();
14788   p = (symbolS *) symbol_find_or_make (name);
14789   *input_line_pointer = c;
14790   return p;
14791 }
14792
14793 /* Align the current frag to a given power of two.  If a particular
14794    fill byte should be used, FILL points to an integer that contains
14795    that byte, otherwise FILL is null.
14796
14797    This function used to have the comment:
14798
14799       The MIPS assembler also automatically adjusts any preceding label.
14800
14801    The implementation therefore applied the adjustment to a maximum of
14802    one label.  However, other label adjustments are applied to batches
14803    of labels, and adjusting just one caused problems when new labels
14804    were added for the sake of debugging or unwind information.
14805    We therefore adjust all preceding labels (given as LABELS) instead.  */
14806
14807 static void
14808 mips_align (int to, int *fill, struct insn_label_list *labels)
14809 {
14810   mips_emit_delays ();
14811   mips_record_compressed_mode ();
14812   if (fill == NULL && subseg_text_p (now_seg))
14813     frag_align_code (to, 0);
14814   else
14815     frag_align (to, fill ? *fill : 0, 0);
14816   record_alignment (now_seg, to);
14817   mips_move_labels (labels, FALSE);
14818 }
14819
14820 /* Align to a given power of two.  .align 0 turns off the automatic
14821    alignment used by the data creating pseudo-ops.  */
14822
14823 static void
14824 s_align (int x ATTRIBUTE_UNUSED)
14825 {
14826   int temp, fill_value, *fill_ptr;
14827   long max_alignment = 28;
14828
14829   /* o Note that the assembler pulls down any immediately preceding label
14830        to the aligned address.
14831      o It's not documented but auto alignment is reinstated by
14832        a .align pseudo instruction.
14833      o Note also that after auto alignment is turned off the mips assembler
14834        issues an error on attempt to assemble an improperly aligned data item.
14835        We don't.  */
14836
14837   temp = get_absolute_expression ();
14838   if (temp > max_alignment)
14839     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
14840   else if (temp < 0)
14841     {
14842       as_warn (_("alignment negative, 0 assumed"));
14843       temp = 0;
14844     }
14845   if (*input_line_pointer == ',')
14846     {
14847       ++input_line_pointer;
14848       fill_value = get_absolute_expression ();
14849       fill_ptr = &fill_value;
14850     }
14851   else
14852     fill_ptr = 0;
14853   if (temp)
14854     {
14855       segment_info_type *si = seg_info (now_seg);
14856       struct insn_label_list *l = si->label_list;
14857       /* Auto alignment should be switched on by next section change.  */
14858       auto_align = 1;
14859       mips_align (temp, fill_ptr, l);
14860     }
14861   else
14862     {
14863       auto_align = 0;
14864     }
14865
14866   demand_empty_rest_of_line ();
14867 }
14868
14869 static void
14870 s_change_sec (int sec)
14871 {
14872   segT seg;
14873
14874   /* The ELF backend needs to know that we are changing sections, so
14875      that .previous works correctly.  We could do something like check
14876      for an obj_section_change_hook macro, but that might be confusing
14877      as it would not be appropriate to use it in the section changing
14878      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14879      This should be cleaner, somehow.  */
14880   obj_elf_section_change_hook ();
14881
14882   mips_emit_delays ();
14883
14884   switch (sec)
14885     {
14886     case 't':
14887       s_text (0);
14888       break;
14889     case 'd':
14890       s_data (0);
14891       break;
14892     case 'b':
14893       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14894       demand_empty_rest_of_line ();
14895       break;
14896
14897     case 'r':
14898       seg = subseg_new (RDATA_SECTION_NAME,
14899                         (subsegT) get_absolute_expression ());
14900       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14901                                               | SEC_READONLY | SEC_RELOC
14902                                               | SEC_DATA));
14903       if (strncmp (TARGET_OS, "elf", 3) != 0)
14904         record_alignment (seg, 4);
14905       demand_empty_rest_of_line ();
14906       break;
14907
14908     case 's':
14909       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14910       bfd_set_section_flags (stdoutput, seg,
14911                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14912       if (strncmp (TARGET_OS, "elf", 3) != 0)
14913         record_alignment (seg, 4);
14914       demand_empty_rest_of_line ();
14915       break;
14916
14917     case 'B':
14918       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14919       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14920       if (strncmp (TARGET_OS, "elf", 3) != 0)
14921         record_alignment (seg, 4);
14922       demand_empty_rest_of_line ();
14923       break;
14924     }
14925
14926   auto_align = 1;
14927 }
14928
14929 void
14930 s_change_section (int ignore ATTRIBUTE_UNUSED)
14931 {
14932   char *section_name;
14933   char c;
14934   char next_c = 0;
14935   int section_type;
14936   int section_flag;
14937   int section_entry_size;
14938   int section_alignment;
14939
14940   section_name = input_line_pointer;
14941   c = get_symbol_end ();
14942   if (c)
14943     next_c = *(input_line_pointer + 1);
14944
14945   /* Do we have .section Name<,"flags">?  */
14946   if (c != ',' || (c == ',' && next_c == '"'))
14947     {
14948       /* just after name is now '\0'.  */
14949       *input_line_pointer = c;
14950       input_line_pointer = section_name;
14951       obj_elf_section (ignore);
14952       return;
14953     }
14954   input_line_pointer++;
14955
14956   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14957   if (c == ',')
14958     section_type = get_absolute_expression ();
14959   else
14960     section_type = 0;
14961   if (*input_line_pointer++ == ',')
14962     section_flag = get_absolute_expression ();
14963   else
14964     section_flag = 0;
14965   if (*input_line_pointer++ == ',')
14966     section_entry_size = get_absolute_expression ();
14967   else
14968     section_entry_size = 0;
14969   if (*input_line_pointer++ == ',')
14970     section_alignment = get_absolute_expression ();
14971   else
14972     section_alignment = 0;
14973   /* FIXME: really ignore?  */
14974   (void) section_alignment;
14975
14976   section_name = xstrdup (section_name);
14977
14978   /* When using the generic form of .section (as implemented by obj-elf.c),
14979      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14980      traditionally had to fall back on the more common @progbits instead.
14981
14982      There's nothing really harmful in this, since bfd will correct
14983      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14984      means that, for backwards compatibility, the special_section entries
14985      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14986
14987      Even so, we shouldn't force users of the MIPS .section syntax to
14988      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14989      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14990      generic type-checking code.  */
14991   if (section_type == SHT_MIPS_DWARF)
14992     section_type = SHT_PROGBITS;
14993
14994   obj_elf_change_section (section_name, section_type, section_flag,
14995                           section_entry_size, 0, 0, 0);
14996
14997   if (now_seg->name != section_name)
14998     free (section_name);
14999 }
15000
15001 void
15002 mips_enable_auto_align (void)
15003 {
15004   auto_align = 1;
15005 }
15006
15007 static void
15008 s_cons (int log_size)
15009 {
15010   segment_info_type *si = seg_info (now_seg);
15011   struct insn_label_list *l = si->label_list;
15012
15013   mips_emit_delays ();
15014   if (log_size > 0 && auto_align)
15015     mips_align (log_size, 0, l);
15016   cons (1 << log_size);
15017   mips_clear_insn_labels ();
15018 }
15019
15020 static void
15021 s_float_cons (int type)
15022 {
15023   segment_info_type *si = seg_info (now_seg);
15024   struct insn_label_list *l = si->label_list;
15025
15026   mips_emit_delays ();
15027
15028   if (auto_align)
15029     {
15030       if (type == 'd')
15031         mips_align (3, 0, l);
15032       else
15033         mips_align (2, 0, l);
15034     }
15035
15036   float_cons (type);
15037   mips_clear_insn_labels ();
15038 }
15039
15040 /* Handle .globl.  We need to override it because on Irix 5 you are
15041    permitted to say
15042        .globl foo .text
15043    where foo is an undefined symbol, to mean that foo should be
15044    considered to be the address of a function.  */
15045
15046 static void
15047 s_mips_globl (int x ATTRIBUTE_UNUSED)
15048 {
15049   char *name;
15050   int c;
15051   symbolS *symbolP;
15052   flagword flag;
15053
15054   do
15055     {
15056       name = input_line_pointer;
15057       c = get_symbol_end ();
15058       symbolP = symbol_find_or_make (name);
15059       S_SET_EXTERNAL (symbolP);
15060
15061       *input_line_pointer = c;
15062       SKIP_WHITESPACE ();
15063
15064       /* On Irix 5, every global symbol that is not explicitly labelled as
15065          being a function is apparently labelled as being an object.  */
15066       flag = BSF_OBJECT;
15067
15068       if (!is_end_of_line[(unsigned char) *input_line_pointer]
15069           && (*input_line_pointer != ','))
15070         {
15071           char *secname;
15072           asection *sec;
15073
15074           secname = input_line_pointer;
15075           c = get_symbol_end ();
15076           sec = bfd_get_section_by_name (stdoutput, secname);
15077           if (sec == NULL)
15078             as_bad (_("%s: no such section"), secname);
15079           *input_line_pointer = c;
15080
15081           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
15082             flag = BSF_FUNCTION;
15083         }
15084
15085       symbol_get_bfdsym (symbolP)->flags |= flag;
15086
15087       c = *input_line_pointer;
15088       if (c == ',')
15089         {
15090           input_line_pointer++;
15091           SKIP_WHITESPACE ();
15092           if (is_end_of_line[(unsigned char) *input_line_pointer])
15093             c = '\n';
15094         }
15095     }
15096   while (c == ',');
15097
15098   demand_empty_rest_of_line ();
15099 }
15100
15101 static void
15102 s_option (int x ATTRIBUTE_UNUSED)
15103 {
15104   char *opt;
15105   char c;
15106
15107   opt = input_line_pointer;
15108   c = get_symbol_end ();
15109
15110   if (*opt == 'O')
15111     {
15112       /* FIXME: What does this mean?  */
15113     }
15114   else if (strncmp (opt, "pic", 3) == 0)
15115     {
15116       int i;
15117
15118       i = atoi (opt + 3);
15119       if (i == 0)
15120         mips_pic = NO_PIC;
15121       else if (i == 2)
15122         {
15123           mips_pic = SVR4_PIC;
15124           mips_abicalls = TRUE;
15125         }
15126       else
15127         as_bad (_(".option pic%d not supported"), i);
15128
15129       if (mips_pic == SVR4_PIC)
15130         {
15131           if (g_switch_seen && g_switch_value != 0)
15132             as_warn (_("-G may not be used with SVR4 PIC code"));
15133           g_switch_value = 0;
15134           bfd_set_gp_size (stdoutput, 0);
15135         }
15136     }
15137   else
15138     as_warn (_("unrecognized option \"%s\""), opt);
15139
15140   *input_line_pointer = c;
15141   demand_empty_rest_of_line ();
15142 }
15143
15144 /* This structure is used to hold a stack of .set values.  */
15145
15146 struct mips_option_stack
15147 {
15148   struct mips_option_stack *next;
15149   struct mips_set_options options;
15150 };
15151
15152 static struct mips_option_stack *mips_opts_stack;
15153
15154 static bfd_boolean
15155 parse_code_option (char * name)
15156 {
15157   const struct mips_ase *ase;
15158   if (strncmp (name, "at=", 3) == 0)
15159     {
15160       char *s = name + 3;
15161
15162       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
15163         as_bad (_("unrecognized register name `%s'"), s);
15164     }
15165   else if (strcmp (name, "at") == 0)
15166     mips_opts.at = ATREG;
15167   else if (strcmp (name, "noat") == 0)
15168     mips_opts.at = ZERO;
15169   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
15170     mips_opts.nomove = 0;
15171   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
15172     mips_opts.nomove = 1;
15173   else if (strcmp (name, "bopt") == 0)
15174     mips_opts.nobopt = 0;
15175   else if (strcmp (name, "nobopt") == 0)
15176     mips_opts.nobopt = 1;
15177   else if (strcmp (name, "gp=32") == 0)
15178     mips_opts.gp = 32;
15179   else if (strcmp (name, "gp=64") == 0)
15180     mips_opts.gp = 64;
15181   else if (strcmp (name, "fp=32") == 0)
15182     mips_opts.fp = 32;
15183   else if (strcmp (name, "fp=xx") == 0)
15184     mips_opts.fp = 0;
15185   else if (strcmp (name, "fp=64") == 0)
15186     mips_opts.fp = 64;
15187   else if (strcmp (name, "softfloat") == 0)
15188     mips_opts.soft_float = 1;
15189   else if (strcmp (name, "hardfloat") == 0)
15190     mips_opts.soft_float = 0;
15191   else if (strcmp (name, "singlefloat") == 0)
15192     mips_opts.single_float = 1;
15193   else if (strcmp (name, "doublefloat") == 0)
15194     mips_opts.single_float = 0;
15195   else if (strcmp (name, "nooddspreg") == 0)
15196     mips_opts.oddspreg = 0;
15197   else if (strcmp (name, "oddspreg") == 0)
15198     mips_opts.oddspreg = 1;
15199   else if (strcmp (name, "mips16") == 0
15200            || strcmp (name, "MIPS-16") == 0)
15201     mips_opts.mips16 = 1;
15202   else if (strcmp (name, "nomips16") == 0
15203            || strcmp (name, "noMIPS-16") == 0)
15204     mips_opts.mips16 = 0;
15205   else if (strcmp (name, "micromips") == 0)
15206     mips_opts.micromips = 1;
15207   else if (strcmp (name, "nomicromips") == 0)
15208     mips_opts.micromips = 0;
15209   else if (name[0] == 'n'
15210            && name[1] == 'o'
15211            && (ase = mips_lookup_ase (name + 2)))
15212     mips_set_ase (ase, &mips_opts, FALSE);
15213   else if ((ase = mips_lookup_ase (name)))
15214     mips_set_ase (ase, &mips_opts, TRUE);
15215   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15216     {
15217       /* Permit the user to change the ISA and architecture on the fly.
15218          Needless to say, misuse can cause serious problems.  */
15219       if (strncmp (name, "arch=", 5) == 0)
15220         {
15221           const struct mips_cpu_info *p;
15222
15223           p = mips_parse_cpu ("internal use", name + 5);
15224           if (!p)
15225             as_bad (_("unknown architecture %s"), name + 5);
15226           else
15227             {
15228               mips_opts.arch = p->cpu;
15229               mips_opts.isa = p->isa;
15230             }
15231         }
15232       else if (strncmp (name, "mips", 4) == 0)
15233         {
15234           const struct mips_cpu_info *p;
15235
15236           p = mips_parse_cpu ("internal use", name);
15237           if (!p)
15238             as_bad (_("unknown ISA level %s"), name + 4);
15239           else
15240             {
15241               mips_opts.arch = p->cpu;
15242               mips_opts.isa = p->isa;
15243             }
15244         }
15245       else
15246         as_bad (_("unknown ISA or architecture %s"), name);
15247     }
15248   else if (strcmp (name, "autoextend") == 0)
15249     mips_opts.noautoextend = 0;
15250   else if (strcmp (name, "noautoextend") == 0)
15251     mips_opts.noautoextend = 1;
15252   else if (strcmp (name, "insn32") == 0)
15253     mips_opts.insn32 = TRUE;
15254   else if (strcmp (name, "noinsn32") == 0)
15255     mips_opts.insn32 = FALSE;
15256   else if (strcmp (name, "sym32") == 0)
15257     mips_opts.sym32 = TRUE;
15258   else if (strcmp (name, "nosym32") == 0)
15259     mips_opts.sym32 = FALSE;
15260   else
15261     return FALSE;
15262   return TRUE;
15263 }
15264
15265 /* Handle the .set pseudo-op.  */
15266
15267 static void
15268 s_mipsset (int x ATTRIBUTE_UNUSED)
15269 {
15270   char *name = input_line_pointer, ch;
15271   int prev_isa = mips_opts.isa;
15272
15273   file_mips_check_options ();
15274
15275   while (!is_end_of_line[(unsigned char) *input_line_pointer])
15276     ++input_line_pointer;
15277   ch = *input_line_pointer;
15278   *input_line_pointer = '\0';
15279
15280   if (strchr (name, ','))
15281     {
15282       /* Generic ".set" directive; use the generic handler.  */
15283       *input_line_pointer = ch;
15284       input_line_pointer = name;
15285       s_set (0);
15286       return;
15287     }
15288
15289   if (strcmp (name, "reorder") == 0)
15290     {
15291       if (mips_opts.noreorder)
15292         end_noreorder ();
15293     }
15294   else if (strcmp (name, "noreorder") == 0)
15295     {
15296       if (!mips_opts.noreorder)
15297         start_noreorder ();
15298     }
15299   else if (strcmp (name, "macro") == 0)
15300     mips_opts.warn_about_macros = 0;
15301   else if (strcmp (name, "nomacro") == 0)
15302     {
15303       if (mips_opts.noreorder == 0)
15304         as_bad (_("`noreorder' must be set before `nomacro'"));
15305       mips_opts.warn_about_macros = 1;
15306     }
15307   else if (strcmp (name, "gp=default") == 0)
15308     mips_opts.gp = file_mips_opts.gp;
15309   else if (strcmp (name, "fp=default") == 0)
15310     mips_opts.fp = file_mips_opts.fp;
15311   else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
15312     {
15313       mips_opts.isa = file_mips_opts.isa;
15314       mips_opts.arch = file_mips_opts.arch;
15315       mips_opts.gp = file_mips_opts.gp;
15316       mips_opts.fp = file_mips_opts.fp;
15317     }
15318   else if (strcmp (name, "push") == 0)
15319     {
15320       struct mips_option_stack *s;
15321
15322       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15323       s->next = mips_opts_stack;
15324       s->options = mips_opts;
15325       mips_opts_stack = s;
15326     }
15327   else if (strcmp (name, "pop") == 0)
15328     {
15329       struct mips_option_stack *s;
15330
15331       s = mips_opts_stack;
15332       if (s == NULL)
15333         as_bad (_(".set pop with no .set push"));
15334       else
15335         {
15336           /* If we're changing the reorder mode we need to handle
15337              delay slots correctly.  */
15338           if (s->options.noreorder && ! mips_opts.noreorder)
15339             start_noreorder ();
15340           else if (! s->options.noreorder && mips_opts.noreorder)
15341             end_noreorder ();
15342
15343           mips_opts = s->options;
15344           mips_opts_stack = s->next;
15345           free (s);
15346         }
15347     }
15348   else if (!parse_code_option (name))
15349     as_warn (_("tried to set unrecognized symbol: %s\n"), name);
15350
15351   /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
15352      registers based on what is supported by the arch/cpu.  */
15353   if (mips_opts.isa != prev_isa)
15354     {
15355       switch (mips_opts.isa)
15356         {
15357         case 0:
15358           break;
15359         case ISA_MIPS1:
15360           /* MIPS I cannot support FPXX.  */
15361           mips_opts.fp = 32;
15362           /* fall-through.  */
15363         case ISA_MIPS2:
15364         case ISA_MIPS32:
15365         case ISA_MIPS32R2:
15366         case ISA_MIPS32R3:
15367         case ISA_MIPS32R5:
15368           mips_opts.gp = 32;
15369           if (mips_opts.fp != 0)
15370             mips_opts.fp = 32;
15371           break;
15372         case ISA_MIPS3:
15373         case ISA_MIPS4:
15374         case ISA_MIPS5:
15375         case ISA_MIPS64:
15376         case ISA_MIPS64R2:
15377         case ISA_MIPS64R3:
15378         case ISA_MIPS64R5:
15379           mips_opts.gp = 64;
15380           if (mips_opts.fp != 0)
15381             {
15382               if (mips_opts.arch == CPU_R5900)
15383                 mips_opts.fp = 32;
15384               else
15385                 mips_opts.fp = 64;
15386             }
15387           break;
15388         default:
15389           as_bad (_("unknown ISA level %s"), name + 4);
15390           break;
15391         }
15392     }
15393
15394   mips_check_options (&mips_opts, FALSE);
15395
15396   mips_check_isa_supports_ases ();
15397   *input_line_pointer = ch;
15398   demand_empty_rest_of_line ();
15399 }
15400
15401 /* Handle the .module pseudo-op.  */
15402
15403 static void
15404 s_module (int ignore ATTRIBUTE_UNUSED)
15405 {
15406   char *name = input_line_pointer, ch;
15407
15408   while (!is_end_of_line[(unsigned char) *input_line_pointer])
15409     ++input_line_pointer;
15410   ch = *input_line_pointer;
15411   *input_line_pointer = '\0';
15412
15413   if (!file_mips_opts_checked)
15414     {
15415       if (!parse_code_option (name))
15416         as_bad (_(".module used with unrecognized symbol: %s\n"), name);
15417
15418       /* Update module level settings from mips_opts.  */
15419       file_mips_opts = mips_opts;
15420     }
15421   else
15422     as_bad (_(".module is not permitted after generating code"));
15423
15424   *input_line_pointer = ch;
15425   demand_empty_rest_of_line ();
15426 }
15427
15428 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15429    .option pic2.  It means to generate SVR4 PIC calls.  */
15430
15431 static void
15432 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15433 {
15434   mips_pic = SVR4_PIC;
15435   mips_abicalls = TRUE;
15436
15437   if (g_switch_seen && g_switch_value != 0)
15438     as_warn (_("-G may not be used with SVR4 PIC code"));
15439   g_switch_value = 0;
15440
15441   bfd_set_gp_size (stdoutput, 0);
15442   demand_empty_rest_of_line ();
15443 }
15444
15445 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15446    PIC code.  It sets the $gp register for the function based on the
15447    function address, which is in the register named in the argument.
15448    This uses a relocation against _gp_disp, which is handled specially
15449    by the linker.  The result is:
15450         lui     $gp,%hi(_gp_disp)
15451         addiu   $gp,$gp,%lo(_gp_disp)
15452         addu    $gp,$gp,.cpload argument
15453    The .cpload argument is normally $25 == $t9.
15454
15455    The -mno-shared option changes this to:
15456         lui     $gp,%hi(__gnu_local_gp)
15457         addiu   $gp,$gp,%lo(__gnu_local_gp)
15458    and the argument is ignored.  This saves an instruction, but the
15459    resulting code is not position independent; it uses an absolute
15460    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15461    can go into an ordinary executable, but not into a shared library.  */
15462
15463 static void
15464 s_cpload (int ignore ATTRIBUTE_UNUSED)
15465 {
15466   expressionS ex;
15467   int reg;
15468   int in_shared;
15469
15470   file_mips_check_options ();
15471
15472   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15473      .cpload is ignored.  */
15474   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15475     {
15476       s_ignore (0);
15477       return;
15478     }
15479
15480   if (mips_opts.mips16)
15481     {
15482       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15483       ignore_rest_of_line ();
15484       return;
15485     }
15486
15487   /* .cpload should be in a .set noreorder section.  */
15488   if (mips_opts.noreorder == 0)
15489     as_warn (_(".cpload not in noreorder section"));
15490
15491   reg = tc_get_register (0);
15492
15493   /* If we need to produce a 64-bit address, we are better off using
15494      the default instruction sequence.  */
15495   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15496
15497   ex.X_op = O_symbol;
15498   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15499                                          "__gnu_local_gp");
15500   ex.X_op_symbol = NULL;
15501   ex.X_add_number = 0;
15502
15503   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15504   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15505
15506   mips_mark_labels ();
15507   mips_assembling_insn = TRUE;
15508
15509   macro_start ();
15510   macro_build_lui (&ex, mips_gp_register);
15511   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15512                mips_gp_register, BFD_RELOC_LO16);
15513   if (in_shared)
15514     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15515                  mips_gp_register, reg);
15516   macro_end ();
15517
15518   mips_assembling_insn = FALSE;
15519   demand_empty_rest_of_line ();
15520 }
15521
15522 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15523      .cpsetup $reg1, offset|$reg2, label
15524
15525    If offset is given, this results in:
15526      sd         $gp, offset($sp)
15527      lui        $gp, %hi(%neg(%gp_rel(label)))
15528      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15529      daddu      $gp, $gp, $reg1
15530
15531    If $reg2 is given, this results in:
15532      daddu      $reg2, $gp, $0
15533      lui        $gp, %hi(%neg(%gp_rel(label)))
15534      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15535      daddu      $gp, $gp, $reg1
15536    $reg1 is normally $25 == $t9.
15537
15538    The -mno-shared option replaces the last three instructions with
15539         lui     $gp,%hi(_gp)
15540         addiu   $gp,$gp,%lo(_gp)  */
15541
15542 static void
15543 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15544 {
15545   expressionS ex_off;
15546   expressionS ex_sym;
15547   int reg1;
15548
15549   file_mips_check_options ();
15550
15551   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15552      We also need NewABI support.  */
15553   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15554     {
15555       s_ignore (0);
15556       return;
15557     }
15558
15559   if (mips_opts.mips16)
15560     {
15561       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15562       ignore_rest_of_line ();
15563       return;
15564     }
15565
15566   reg1 = tc_get_register (0);
15567   SKIP_WHITESPACE ();
15568   if (*input_line_pointer != ',')
15569     {
15570       as_bad (_("missing argument separator ',' for .cpsetup"));
15571       return;
15572     }
15573   else
15574     ++input_line_pointer;
15575   SKIP_WHITESPACE ();
15576   if (*input_line_pointer == '$')
15577     {
15578       mips_cpreturn_register = tc_get_register (0);
15579       mips_cpreturn_offset = -1;
15580     }
15581   else
15582     {
15583       mips_cpreturn_offset = get_absolute_expression ();
15584       mips_cpreturn_register = -1;
15585     }
15586   SKIP_WHITESPACE ();
15587   if (*input_line_pointer != ',')
15588     {
15589       as_bad (_("missing argument separator ',' for .cpsetup"));
15590       return;
15591     }
15592   else
15593     ++input_line_pointer;
15594   SKIP_WHITESPACE ();
15595   expression (&ex_sym);
15596
15597   mips_mark_labels ();
15598   mips_assembling_insn = TRUE;
15599
15600   macro_start ();
15601   if (mips_cpreturn_register == -1)
15602     {
15603       ex_off.X_op = O_constant;
15604       ex_off.X_add_symbol = NULL;
15605       ex_off.X_op_symbol = NULL;
15606       ex_off.X_add_number = mips_cpreturn_offset;
15607
15608       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15609                    BFD_RELOC_LO16, SP);
15610     }
15611   else
15612     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15613                  mips_gp_register, 0);
15614
15615   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15616     {
15617       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15618                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15619                    BFD_RELOC_HI16_S);
15620
15621       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15622                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15623                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15624
15625       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15626                    mips_gp_register, reg1);
15627     }
15628   else
15629     {
15630       expressionS ex;
15631
15632       ex.X_op = O_symbol;
15633       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15634       ex.X_op_symbol = NULL;
15635       ex.X_add_number = 0;
15636
15637       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15638       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15639
15640       macro_build_lui (&ex, mips_gp_register);
15641       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15642                    mips_gp_register, BFD_RELOC_LO16);
15643     }
15644
15645   macro_end ();
15646
15647   mips_assembling_insn = FALSE;
15648   demand_empty_rest_of_line ();
15649 }
15650
15651 static void
15652 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15653 {
15654   file_mips_check_options ();
15655
15656   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15657      .cplocal is ignored.  */
15658   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15659     {
15660       s_ignore (0);
15661       return;
15662     }
15663
15664   if (mips_opts.mips16)
15665     {
15666       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15667       ignore_rest_of_line ();
15668       return;
15669     }
15670
15671   mips_gp_register = tc_get_register (0);
15672   demand_empty_rest_of_line ();
15673 }
15674
15675 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15676    offset from $sp.  The offset is remembered, and after making a PIC
15677    call $gp is restored from that location.  */
15678
15679 static void
15680 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15681 {
15682   expressionS ex;
15683
15684   file_mips_check_options ();
15685
15686   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15687      .cprestore is ignored.  */
15688   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15689     {
15690       s_ignore (0);
15691       return;
15692     }
15693
15694   if (mips_opts.mips16)
15695     {
15696       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15697       ignore_rest_of_line ();
15698       return;
15699     }
15700
15701   mips_cprestore_offset = get_absolute_expression ();
15702   mips_cprestore_valid = 1;
15703
15704   ex.X_op = O_constant;
15705   ex.X_add_symbol = NULL;
15706   ex.X_op_symbol = NULL;
15707   ex.X_add_number = mips_cprestore_offset;
15708
15709   mips_mark_labels ();
15710   mips_assembling_insn = TRUE;
15711
15712   macro_start ();
15713   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15714                                 SP, HAVE_64BIT_ADDRESSES);
15715   macro_end ();
15716
15717   mips_assembling_insn = FALSE;
15718   demand_empty_rest_of_line ();
15719 }
15720
15721 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15722    was given in the preceding .cpsetup, it results in:
15723      ld         $gp, offset($sp)
15724
15725    If a register $reg2 was given there, it results in:
15726      daddu      $gp, $reg2, $0  */
15727
15728 static void
15729 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15730 {
15731   expressionS ex;
15732
15733   file_mips_check_options ();
15734
15735   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15736      We also need NewABI support.  */
15737   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15738     {
15739       s_ignore (0);
15740       return;
15741     }
15742
15743   if (mips_opts.mips16)
15744     {
15745       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15746       ignore_rest_of_line ();
15747       return;
15748     }
15749
15750   mips_mark_labels ();
15751   mips_assembling_insn = TRUE;
15752
15753   macro_start ();
15754   if (mips_cpreturn_register == -1)
15755     {
15756       ex.X_op = O_constant;
15757       ex.X_add_symbol = NULL;
15758       ex.X_op_symbol = NULL;
15759       ex.X_add_number = mips_cpreturn_offset;
15760
15761       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15762     }
15763   else
15764     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15765                  mips_cpreturn_register, 0);
15766   macro_end ();
15767
15768   mips_assembling_insn = FALSE;
15769   demand_empty_rest_of_line ();
15770 }
15771
15772 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15773    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15774    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15775    debug information or MIPS16 TLS.  */
15776
15777 static void
15778 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15779                      bfd_reloc_code_real_type rtype)
15780 {
15781   expressionS ex;
15782   char *p;
15783
15784   expression (&ex);
15785
15786   if (ex.X_op != O_symbol)
15787     {
15788       as_bad (_("unsupported use of %s"), dirstr);
15789       ignore_rest_of_line ();
15790     }
15791
15792   p = frag_more (bytes);
15793   md_number_to_chars (p, 0, bytes);
15794   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15795   demand_empty_rest_of_line ();
15796   mips_clear_insn_labels ();
15797 }
15798
15799 /* Handle .dtprelword.  */
15800
15801 static void
15802 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15803 {
15804   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15805 }
15806
15807 /* Handle .dtpreldword.  */
15808
15809 static void
15810 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15811 {
15812   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15813 }
15814
15815 /* Handle .tprelword.  */
15816
15817 static void
15818 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15819 {
15820   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15821 }
15822
15823 /* Handle .tpreldword.  */
15824
15825 static void
15826 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15827 {
15828   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15829 }
15830
15831 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15832    code.  It sets the offset to use in gp_rel relocations.  */
15833
15834 static void
15835 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15836 {
15837   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15838      We also need NewABI support.  */
15839   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15840     {
15841       s_ignore (0);
15842       return;
15843     }
15844
15845   mips_gprel_offset = get_absolute_expression ();
15846
15847   demand_empty_rest_of_line ();
15848 }
15849
15850 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15851    code.  It generates a 32 bit GP relative reloc.  */
15852
15853 static void
15854 s_gpword (int ignore ATTRIBUTE_UNUSED)
15855 {
15856   segment_info_type *si;
15857   struct insn_label_list *l;
15858   expressionS ex;
15859   char *p;
15860
15861   /* When not generating PIC code, this is treated as .word.  */
15862   if (mips_pic != SVR4_PIC)
15863     {
15864       s_cons (2);
15865       return;
15866     }
15867
15868   si = seg_info (now_seg);
15869   l = si->label_list;
15870   mips_emit_delays ();
15871   if (auto_align)
15872     mips_align (2, 0, l);
15873
15874   expression (&ex);
15875   mips_clear_insn_labels ();
15876
15877   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15878     {
15879       as_bad (_("unsupported use of .gpword"));
15880       ignore_rest_of_line ();
15881     }
15882
15883   p = frag_more (4);
15884   md_number_to_chars (p, 0, 4);
15885   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15886                BFD_RELOC_GPREL32);
15887
15888   demand_empty_rest_of_line ();
15889 }
15890
15891 static void
15892 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15893 {
15894   segment_info_type *si;
15895   struct insn_label_list *l;
15896   expressionS ex;
15897   char *p;
15898
15899   /* When not generating PIC code, this is treated as .dword.  */
15900   if (mips_pic != SVR4_PIC)
15901     {
15902       s_cons (3);
15903       return;
15904     }
15905
15906   si = seg_info (now_seg);
15907   l = si->label_list;
15908   mips_emit_delays ();
15909   if (auto_align)
15910     mips_align (3, 0, l);
15911
15912   expression (&ex);
15913   mips_clear_insn_labels ();
15914
15915   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15916     {
15917       as_bad (_("unsupported use of .gpdword"));
15918       ignore_rest_of_line ();
15919     }
15920
15921   p = frag_more (8);
15922   md_number_to_chars (p, 0, 8);
15923   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15924                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15925
15926   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15927   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15928            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15929
15930   demand_empty_rest_of_line ();
15931 }
15932
15933 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15934    tables.  It generates a R_MIPS_EH reloc.  */
15935
15936 static void
15937 s_ehword (int ignore ATTRIBUTE_UNUSED)
15938 {
15939   expressionS ex;
15940   char *p;
15941
15942   mips_emit_delays ();
15943
15944   expression (&ex);
15945   mips_clear_insn_labels ();
15946
15947   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15948     {
15949       as_bad (_("unsupported use of .ehword"));
15950       ignore_rest_of_line ();
15951     }
15952
15953   p = frag_more (4);
15954   md_number_to_chars (p, 0, 4);
15955   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15956                BFD_RELOC_MIPS_EH);
15957
15958   demand_empty_rest_of_line ();
15959 }
15960
15961 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15962    tables in SVR4 PIC code.  */
15963
15964 static void
15965 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15966 {
15967   int reg;
15968
15969   file_mips_check_options ();
15970
15971   /* This is ignored when not generating SVR4 PIC code.  */
15972   if (mips_pic != SVR4_PIC)
15973     {
15974       s_ignore (0);
15975       return;
15976     }
15977
15978   mips_mark_labels ();
15979   mips_assembling_insn = TRUE;
15980
15981   /* Add $gp to the register named as an argument.  */
15982   macro_start ();
15983   reg = tc_get_register (0);
15984   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15985   macro_end ();
15986
15987   mips_assembling_insn = FALSE;
15988   demand_empty_rest_of_line ();
15989 }
15990
15991 /* Handle the .insn pseudo-op.  This marks instruction labels in
15992    mips16/micromips mode.  This permits the linker to handle them specially,
15993    such as generating jalx instructions when needed.  We also make
15994    them odd for the duration of the assembly, in order to generate the
15995    right sort of code.  We will make them even in the adjust_symtab
15996    routine, while leaving them marked.  This is convenient for the
15997    debugger and the disassembler.  The linker knows to make them odd
15998    again.  */
15999
16000 static void
16001 s_insn (int ignore ATTRIBUTE_UNUSED)
16002 {
16003   mips_mark_labels ();
16004
16005   demand_empty_rest_of_line ();
16006 }
16007
16008 /* Handle the .nan pseudo-op.  */
16009
16010 static void
16011 s_nan (int ignore ATTRIBUTE_UNUSED)
16012 {
16013   static const char str_legacy[] = "legacy";
16014   static const char str_2008[] = "2008";
16015   size_t i;
16016
16017   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
16018
16019   if (i == sizeof (str_2008) - 1
16020       && memcmp (input_line_pointer, str_2008, i) == 0)
16021     mips_flag_nan2008 = TRUE;
16022   else if (i == sizeof (str_legacy) - 1
16023            && memcmp (input_line_pointer, str_legacy, i) == 0)
16024     mips_flag_nan2008 = FALSE;
16025   else
16026     as_bad (_("bad .nan directive"));
16027
16028   input_line_pointer += i;
16029   demand_empty_rest_of_line ();
16030 }
16031
16032 /* Handle a .stab[snd] directive.  Ideally these directives would be
16033    implemented in a transparent way, so that removing them would not
16034    have any effect on the generated instructions.  However, s_stab
16035    internally changes the section, so in practice we need to decide
16036    now whether the preceding label marks compressed code.  We do not
16037    support changing the compression mode of a label after a .stab*
16038    directive, such as in:
16039
16040    foo:
16041         .stabs ...
16042         .set mips16
16043
16044    so the current mode wins.  */
16045
16046 static void
16047 s_mips_stab (int type)
16048 {
16049   mips_mark_labels ();
16050   s_stab (type);
16051 }
16052
16053 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
16054
16055 static void
16056 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
16057 {
16058   char *name;
16059   int c;
16060   symbolS *symbolP;
16061   expressionS exp;
16062
16063   name = input_line_pointer;
16064   c = get_symbol_end ();
16065   symbolP = symbol_find_or_make (name);
16066   S_SET_WEAK (symbolP);
16067   *input_line_pointer = c;
16068
16069   SKIP_WHITESPACE ();
16070
16071   if (! is_end_of_line[(unsigned char) *input_line_pointer])
16072     {
16073       if (S_IS_DEFINED (symbolP))
16074         {
16075           as_bad (_("ignoring attempt to redefine symbol %s"),
16076                   S_GET_NAME (symbolP));
16077           ignore_rest_of_line ();
16078           return;
16079         }
16080
16081       if (*input_line_pointer == ',')
16082         {
16083           ++input_line_pointer;
16084           SKIP_WHITESPACE ();
16085         }
16086
16087       expression (&exp);
16088       if (exp.X_op != O_symbol)
16089         {
16090           as_bad (_("bad .weakext directive"));
16091           ignore_rest_of_line ();
16092           return;
16093         }
16094       symbol_set_value_expression (symbolP, &exp);
16095     }
16096
16097   demand_empty_rest_of_line ();
16098 }
16099
16100 /* Parse a register string into a number.  Called from the ECOFF code
16101    to parse .frame.  The argument is non-zero if this is the frame
16102    register, so that we can record it in mips_frame_reg.  */
16103
16104 int
16105 tc_get_register (int frame)
16106 {
16107   unsigned int reg;
16108
16109   SKIP_WHITESPACE ();
16110   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
16111     reg = 0;
16112   if (frame)
16113     {
16114       mips_frame_reg = reg != 0 ? reg : SP;
16115       mips_frame_reg_valid = 1;
16116       mips_cprestore_valid = 0;
16117     }
16118   return reg;
16119 }
16120
16121 valueT
16122 md_section_align (asection *seg, valueT addr)
16123 {
16124   int align = bfd_get_section_alignment (stdoutput, seg);
16125
16126   /* We don't need to align ELF sections to the full alignment.
16127      However, Irix 5 may prefer that we align them at least to a 16
16128      byte boundary.  We don't bother to align the sections if we
16129      are targeted for an embedded system.  */
16130   if (strncmp (TARGET_OS, "elf", 3) == 0)
16131     return addr;
16132   if (align > 4)
16133     align = 4;
16134
16135   return ((addr + (1 << align) - 1) & (-1 << align));
16136 }
16137
16138 /* Utility routine, called from above as well.  If called while the
16139    input file is still being read, it's only an approximation.  (For
16140    example, a symbol may later become defined which appeared to be
16141    undefined earlier.)  */
16142
16143 static int
16144 nopic_need_relax (symbolS *sym, int before_relaxing)
16145 {
16146   if (sym == 0)
16147     return 0;
16148
16149   if (g_switch_value > 0)
16150     {
16151       const char *symname;
16152       int change;
16153
16154       /* Find out whether this symbol can be referenced off the $gp
16155          register.  It can be if it is smaller than the -G size or if
16156          it is in the .sdata or .sbss section.  Certain symbols can
16157          not be referenced off the $gp, although it appears as though
16158          they can.  */
16159       symname = S_GET_NAME (sym);
16160       if (symname != (const char *) NULL
16161           && (strcmp (symname, "eprol") == 0
16162               || strcmp (symname, "etext") == 0
16163               || strcmp (symname, "_gp") == 0
16164               || strcmp (symname, "edata") == 0
16165               || strcmp (symname, "_fbss") == 0
16166               || strcmp (symname, "_fdata") == 0
16167               || strcmp (symname, "_ftext") == 0
16168               || strcmp (symname, "end") == 0
16169               || strcmp (symname, "_gp_disp") == 0))
16170         change = 1;
16171       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
16172                && (0
16173 #ifndef NO_ECOFF_DEBUGGING
16174                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
16175                        && (symbol_get_obj (sym)->ecoff_extern_size
16176                            <= g_switch_value))
16177 #endif
16178                    /* We must defer this decision until after the whole
16179                       file has been read, since there might be a .extern
16180                       after the first use of this symbol.  */
16181                    || (before_relaxing
16182 #ifndef NO_ECOFF_DEBUGGING
16183                        && symbol_get_obj (sym)->ecoff_extern_size == 0
16184 #endif
16185                        && S_GET_VALUE (sym) == 0)
16186                    || (S_GET_VALUE (sym) != 0
16187                        && S_GET_VALUE (sym) <= g_switch_value)))
16188         change = 0;
16189       else
16190         {
16191           const char *segname;
16192
16193           segname = segment_name (S_GET_SEGMENT (sym));
16194           gas_assert (strcmp (segname, ".lit8") != 0
16195                   && strcmp (segname, ".lit4") != 0);
16196           change = (strcmp (segname, ".sdata") != 0
16197                     && strcmp (segname, ".sbss") != 0
16198                     && strncmp (segname, ".sdata.", 7) != 0
16199                     && strncmp (segname, ".sbss.", 6) != 0
16200                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
16201                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
16202         }
16203       return change;
16204     }
16205   else
16206     /* We are not optimizing for the $gp register.  */
16207     return 1;
16208 }
16209
16210
16211 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
16212
16213 static bfd_boolean
16214 pic_need_relax (symbolS *sym, asection *segtype)
16215 {
16216   asection *symsec;
16217
16218   /* Handle the case of a symbol equated to another symbol.  */
16219   while (symbol_equated_reloc_p (sym))
16220     {
16221       symbolS *n;
16222
16223       /* It's possible to get a loop here in a badly written program.  */
16224       n = symbol_get_value_expression (sym)->X_add_symbol;
16225       if (n == sym)
16226         break;
16227       sym = n;
16228     }
16229
16230   if (symbol_section_p (sym))
16231     return TRUE;
16232
16233   symsec = S_GET_SEGMENT (sym);
16234
16235   /* This must duplicate the test in adjust_reloc_syms.  */
16236   return (!bfd_is_und_section (symsec)
16237           && !bfd_is_abs_section (symsec)
16238           && !bfd_is_com_section (symsec)
16239           && !s_is_linkonce (sym, segtype)
16240           /* A global or weak symbol is treated as external.  */
16241           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
16242 }
16243
16244
16245 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
16246    extended opcode.  SEC is the section the frag is in.  */
16247
16248 static int
16249 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
16250 {
16251   int type;
16252   const struct mips_int_operand *operand;
16253   offsetT val;
16254   segT symsec;
16255   fragS *sym_frag;
16256
16257   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16258     return 0;
16259   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16260     return 1;
16261
16262   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16263   operand = mips16_immed_operand (type, FALSE);
16264
16265   sym_frag = symbol_get_frag (fragp->fr_symbol);
16266   val = S_GET_VALUE (fragp->fr_symbol);
16267   symsec = S_GET_SEGMENT (fragp->fr_symbol);
16268
16269   if (operand->root.type == OP_PCREL)
16270     {
16271       const struct mips_pcrel_operand *pcrel_op;
16272       addressT addr;
16273       offsetT maxtiny;
16274
16275       /* We won't have the section when we are called from
16276          mips_relax_frag.  However, we will always have been called
16277          from md_estimate_size_before_relax first.  If this is a
16278          branch to a different section, we mark it as such.  If SEC is
16279          NULL, and the frag is not marked, then it must be a branch to
16280          the same section.  */
16281       pcrel_op = (const struct mips_pcrel_operand *) operand;
16282       if (sec == NULL)
16283         {
16284           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16285             return 1;
16286         }
16287       else
16288         {
16289           /* Must have been called from md_estimate_size_before_relax.  */
16290           if (symsec != sec)
16291             {
16292               fragp->fr_subtype =
16293                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16294
16295               /* FIXME: We should support this, and let the linker
16296                  catch branches and loads that are out of range.  */
16297               as_bad_where (fragp->fr_file, fragp->fr_line,
16298                             _("unsupported PC relative reference to different section"));
16299
16300               return 1;
16301             }
16302           if (fragp != sym_frag && sym_frag->fr_address == 0)
16303             /* Assume non-extended on the first relaxation pass.
16304                The address we have calculated will be bogus if this is
16305                a forward branch to another frag, as the forward frag
16306                will have fr_address == 0.  */
16307             return 0;
16308         }
16309
16310       /* In this case, we know for sure that the symbol fragment is in
16311          the same section.  If the relax_marker of the symbol fragment
16312          differs from the relax_marker of this fragment, we have not
16313          yet adjusted the symbol fragment fr_address.  We want to add
16314          in STRETCH in order to get a better estimate of the address.
16315          This particularly matters because of the shift bits.  */
16316       if (stretch != 0
16317           && sym_frag->relax_marker != fragp->relax_marker)
16318         {
16319           fragS *f;
16320
16321           /* Adjust stretch for any alignment frag.  Note that if have
16322              been expanding the earlier code, the symbol may be
16323              defined in what appears to be an earlier frag.  FIXME:
16324              This doesn't handle the fr_subtype field, which specifies
16325              a maximum number of bytes to skip when doing an
16326              alignment.  */
16327           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16328             {
16329               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16330                 {
16331                   if (stretch < 0)
16332                     stretch = - ((- stretch)
16333                                  & ~ ((1 << (int) f->fr_offset) - 1));
16334                   else
16335                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16336                   if (stretch == 0)
16337                     break;
16338                 }
16339             }
16340           if (f != NULL)
16341             val += stretch;
16342         }
16343
16344       addr = fragp->fr_address + fragp->fr_fix;
16345
16346       /* The base address rules are complicated.  The base address of
16347          a branch is the following instruction.  The base address of a
16348          PC relative load or add is the instruction itself, but if it
16349          is in a delay slot (in which case it can not be extended) use
16350          the address of the instruction whose delay slot it is in.  */
16351       if (pcrel_op->include_isa_bit)
16352         {
16353           addr += 2;
16354
16355           /* If we are currently assuming that this frag should be
16356              extended, then, the current address is two bytes
16357              higher.  */
16358           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16359             addr += 2;
16360
16361           /* Ignore the low bit in the target, since it will be set
16362              for a text label.  */
16363           val &= -2;
16364         }
16365       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16366         addr -= 4;
16367       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16368         addr -= 2;
16369
16370       val -= addr & -(1 << pcrel_op->align_log2);
16371
16372       /* If any of the shifted bits are set, we must use an extended
16373          opcode.  If the address depends on the size of this
16374          instruction, this can lead to a loop, so we arrange to always
16375          use an extended opcode.  We only check this when we are in
16376          the main relaxation loop, when SEC is NULL.  */
16377       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16378         {
16379           fragp->fr_subtype =
16380             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16381           return 1;
16382         }
16383
16384       /* If we are about to mark a frag as extended because the value
16385          is precisely the next value above maxtiny, then there is a
16386          chance of an infinite loop as in the following code:
16387              la $4,foo
16388              .skip      1020
16389              .align     2
16390            foo:
16391          In this case when the la is extended, foo is 0x3fc bytes
16392          away, so the la can be shrunk, but then foo is 0x400 away, so
16393          the la must be extended.  To avoid this loop, we mark the
16394          frag as extended if it was small, and is about to become
16395          extended with the next value above maxtiny.  */
16396       maxtiny = mips_int_operand_max (operand);
16397       if (val == maxtiny + (1 << operand->shift)
16398           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16399           && sec == NULL)
16400         {
16401           fragp->fr_subtype =
16402             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16403           return 1;
16404         }
16405     }
16406   else if (symsec != absolute_section && sec != NULL)
16407     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16408
16409   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16410 }
16411
16412 /* Compute the length of a branch sequence, and adjust the
16413    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16414    worst-case length is computed, with UPDATE being used to indicate
16415    whether an unconditional (-1), branch-likely (+1) or regular (0)
16416    branch is to be computed.  */
16417 static int
16418 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16419 {
16420   bfd_boolean toofar;
16421   int length;
16422
16423   if (fragp
16424       && S_IS_DEFINED (fragp->fr_symbol)
16425       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16426     {
16427       addressT addr;
16428       offsetT val;
16429
16430       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16431
16432       addr = fragp->fr_address + fragp->fr_fix + 4;
16433
16434       val -= addr;
16435
16436       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16437     }
16438   else if (fragp)
16439     /* If the symbol is not defined or it's in a different segment,
16440        assume the user knows what's going on and emit a short
16441        branch.  */
16442     toofar = FALSE;
16443   else
16444     toofar = TRUE;
16445
16446   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16447     fragp->fr_subtype
16448       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16449                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16450                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16451                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16452                              toofar);
16453
16454   length = 4;
16455   if (toofar)
16456     {
16457       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16458         length += 8;
16459
16460       if (mips_pic != NO_PIC)
16461         {
16462           /* Additional space for PIC loading of target address.  */
16463           length += 8;
16464           if (mips_opts.isa == ISA_MIPS1)
16465             /* Additional space for $at-stabilizing nop.  */
16466             length += 4;
16467         }
16468
16469       /* If branch is conditional.  */
16470       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16471         length += 8;
16472     }
16473
16474   return length;
16475 }
16476
16477 /* Compute the length of a branch sequence, and adjust the
16478    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16479    worst-case length is computed, with UPDATE being used to indicate
16480    whether an unconditional (-1), or regular (0) branch is to be
16481    computed.  */
16482
16483 static int
16484 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16485 {
16486   bfd_boolean toofar;
16487   int length;
16488
16489   if (fragp
16490       && S_IS_DEFINED (fragp->fr_symbol)
16491       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16492     {
16493       addressT addr;
16494       offsetT val;
16495
16496       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16497       /* Ignore the low bit in the target, since it will be set
16498          for a text label.  */
16499       if ((val & 1) != 0)
16500         --val;
16501
16502       addr = fragp->fr_address + fragp->fr_fix + 4;
16503
16504       val -= addr;
16505
16506       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16507     }
16508   else if (fragp)
16509     /* If the symbol is not defined or it's in a different segment,
16510        assume the user knows what's going on and emit a short
16511        branch.  */
16512     toofar = FALSE;
16513   else
16514     toofar = TRUE;
16515
16516   if (fragp && update
16517       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16518     fragp->fr_subtype = (toofar
16519                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16520                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16521
16522   length = 4;
16523   if (toofar)
16524     {
16525       bfd_boolean compact_known = fragp != NULL;
16526       bfd_boolean compact = FALSE;
16527       bfd_boolean uncond;
16528
16529       if (compact_known)
16530         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16531       if (fragp)
16532         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16533       else
16534         uncond = update < 0;
16535
16536       /* If label is out of range, we turn branch <br>:
16537
16538                 <br>    label                   # 4 bytes
16539             0:
16540
16541          into:
16542
16543                 j       label                   # 4 bytes
16544                 nop                             # 2 bytes if compact && !PIC
16545             0:
16546        */
16547       if (mips_pic == NO_PIC && (!compact_known || compact))
16548         length += 2;
16549
16550       /* If assembling PIC code, we further turn:
16551
16552                         j       label                   # 4 bytes
16553
16554          into:
16555
16556                         lw/ld   at, %got(label)(gp)     # 4 bytes
16557                         d/addiu at, %lo(label)          # 4 bytes
16558                         jr/c    at                      # 2 bytes
16559        */
16560       if (mips_pic != NO_PIC)
16561         length += 6;
16562
16563       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16564
16565                         <brneg> 0f                      # 4 bytes
16566                         nop                             # 2 bytes if !compact
16567        */
16568       if (!uncond)
16569         length += (compact_known && compact) ? 4 : 6;
16570     }
16571
16572   return length;
16573 }
16574
16575 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16576    bit accordingly.  */
16577
16578 static int
16579 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16580 {
16581   bfd_boolean toofar;
16582
16583   if (fragp
16584       && S_IS_DEFINED (fragp->fr_symbol)
16585       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16586     {
16587       addressT addr;
16588       offsetT val;
16589       int type;
16590
16591       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16592       /* Ignore the low bit in the target, since it will be set
16593          for a text label.  */
16594       if ((val & 1) != 0)
16595         --val;
16596
16597       /* Assume this is a 2-byte branch.  */
16598       addr = fragp->fr_address + fragp->fr_fix + 2;
16599
16600       /* We try to avoid the infinite loop by not adding 2 more bytes for
16601          long branches.  */
16602
16603       val -= addr;
16604
16605       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16606       if (type == 'D')
16607         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16608       else if (type == 'E')
16609         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16610       else
16611         abort ();
16612     }
16613   else
16614     /* If the symbol is not defined or it's in a different segment,
16615        we emit a normal 32-bit branch.  */
16616     toofar = TRUE;
16617
16618   if (fragp && update
16619       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16620     fragp->fr_subtype
16621       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16622                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16623
16624   if (toofar)
16625     return 4;
16626
16627   return 2;
16628 }
16629
16630 /* Estimate the size of a frag before relaxing.  Unless this is the
16631    mips16, we are not really relaxing here, and the final size is
16632    encoded in the subtype information.  For the mips16, we have to
16633    decide whether we are using an extended opcode or not.  */
16634
16635 int
16636 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16637 {
16638   int change;
16639
16640   if (RELAX_BRANCH_P (fragp->fr_subtype))
16641     {
16642
16643       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16644
16645       return fragp->fr_var;
16646     }
16647
16648   if (RELAX_MIPS16_P (fragp->fr_subtype))
16649     /* We don't want to modify the EXTENDED bit here; it might get us
16650        into infinite loops.  We change it only in mips_relax_frag().  */
16651     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16652
16653   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16654     {
16655       int length = 4;
16656
16657       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16658         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16659       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16660         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16661       fragp->fr_var = length;
16662
16663       return length;
16664     }
16665
16666   if (mips_pic == NO_PIC)
16667     change = nopic_need_relax (fragp->fr_symbol, 0);
16668   else if (mips_pic == SVR4_PIC)
16669     change = pic_need_relax (fragp->fr_symbol, segtype);
16670   else if (mips_pic == VXWORKS_PIC)
16671     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16672     change = 0;
16673   else
16674     abort ();
16675
16676   if (change)
16677     {
16678       fragp->fr_subtype |= RELAX_USE_SECOND;
16679       return -RELAX_FIRST (fragp->fr_subtype);
16680     }
16681   else
16682     return -RELAX_SECOND (fragp->fr_subtype);
16683 }
16684
16685 /* This is called to see whether a reloc against a defined symbol
16686    should be converted into a reloc against a section.  */
16687
16688 int
16689 mips_fix_adjustable (fixS *fixp)
16690 {
16691   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16692       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16693     return 0;
16694
16695   if (fixp->fx_addsy == NULL)
16696     return 1;
16697
16698   /* If symbol SYM is in a mergeable section, relocations of the form
16699      SYM + 0 can usually be made section-relative.  The mergeable data
16700      is then identified by the section offset rather than by the symbol.
16701
16702      However, if we're generating REL LO16 relocations, the offset is split
16703      between the LO16 and parterning high part relocation.  The linker will
16704      need to recalculate the complete offset in order to correctly identify
16705      the merge data.
16706
16707      The linker has traditionally not looked for the parterning high part
16708      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16709      placed anywhere.  Rather than break backwards compatibility by changing
16710      this, it seems better not to force the issue, and instead keep the
16711      original symbol.  This will work with either linker behavior.  */
16712   if ((lo16_reloc_p (fixp->fx_r_type)
16713        || reloc_needs_lo_p (fixp->fx_r_type))
16714       && HAVE_IN_PLACE_ADDENDS
16715       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16716     return 0;
16717
16718   /* There is no place to store an in-place offset for JALR relocations.
16719      Likewise an in-range offset of limited PC-relative relocations may
16720      overflow the in-place relocatable field if recalculated against the
16721      start address of the symbol's containing section.  */
16722   if (HAVE_IN_PLACE_ADDENDS
16723       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16724           || jalr_reloc_p (fixp->fx_r_type)))
16725     return 0;
16726
16727   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16728      to a floating-point stub.  The same is true for non-R_MIPS16_26
16729      relocations against MIPS16 functions; in this case, the stub becomes
16730      the function's canonical address.
16731
16732      Floating-point stubs are stored in unique .mips16.call.* or
16733      .mips16.fn.* sections.  If a stub T for function F is in section S,
16734      the first relocation in section S must be against F; this is how the
16735      linker determines the target function.  All relocations that might
16736      resolve to T must also be against F.  We therefore have the following
16737      restrictions, which are given in an intentionally-redundant way:
16738
16739        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16740           symbols.
16741
16742        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16743           if that stub might be used.
16744
16745        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16746           symbols.
16747
16748        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16749           that stub might be used.
16750
16751      There is a further restriction:
16752
16753        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16754           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16755           targets with in-place addends; the relocation field cannot
16756           encode the low bit.
16757
16758      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16759      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16760      such relocations on REL targets.
16761
16762      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16763      relocation against some symbol R, no relocation against R may be
16764      reduced.  (Note that this deals with (2) as well as (1) because
16765      relocations against global symbols will never be reduced on ELF
16766      targets.)  This approach is a little simpler than trying to detect
16767      stub sections, and gives the "all or nothing" per-symbol consistency
16768      that we have for MIPS16 symbols.  */
16769   if (fixp->fx_subsy == NULL
16770       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16771           || *symbol_get_tc (fixp->fx_addsy)
16772           || (HAVE_IN_PLACE_ADDENDS
16773               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16774               && jmp_reloc_p (fixp->fx_r_type))))
16775     return 0;
16776
16777   return 1;
16778 }
16779
16780 /* Translate internal representation of relocation info to BFD target
16781    format.  */
16782
16783 arelent **
16784 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16785 {
16786   static arelent *retval[4];
16787   arelent *reloc;
16788   bfd_reloc_code_real_type code;
16789
16790   memset (retval, 0, sizeof(retval));
16791   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16792   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16793   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16794   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16795
16796   if (fixp->fx_pcrel)
16797     {
16798       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16799                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16800                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16801                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16802                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16803
16804       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16805          Relocations want only the symbol offset.  */
16806       reloc->addend = fixp->fx_addnumber + reloc->address;
16807     }
16808   else
16809     reloc->addend = fixp->fx_addnumber;
16810
16811   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16812      entry to be used in the relocation's section offset.  */
16813   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16814     {
16815       reloc->address = reloc->addend;
16816       reloc->addend = 0;
16817     }
16818
16819   code = fixp->fx_r_type;
16820
16821   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16822   if (reloc->howto == NULL)
16823     {
16824       as_bad_where (fixp->fx_file, fixp->fx_line,
16825                     _("cannot represent %s relocation in this object file"
16826                       " format"),
16827                     bfd_get_reloc_code_name (code));
16828       retval[0] = NULL;
16829     }
16830
16831   return retval;
16832 }
16833
16834 /* Relax a machine dependent frag.  This returns the amount by which
16835    the current size of the frag should change.  */
16836
16837 int
16838 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16839 {
16840   if (RELAX_BRANCH_P (fragp->fr_subtype))
16841     {
16842       offsetT old_var = fragp->fr_var;
16843
16844       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16845
16846       return fragp->fr_var - old_var;
16847     }
16848
16849   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16850     {
16851       offsetT old_var = fragp->fr_var;
16852       offsetT new_var = 4;
16853
16854       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16855         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16856       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16857         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16858       fragp->fr_var = new_var;
16859
16860       return new_var - old_var;
16861     }
16862
16863   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16864     return 0;
16865
16866   if (mips16_extended_frag (fragp, NULL, stretch))
16867     {
16868       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16869         return 0;
16870       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16871       return 2;
16872     }
16873   else
16874     {
16875       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16876         return 0;
16877       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16878       return -2;
16879     }
16880
16881   return 0;
16882 }
16883
16884 /* Convert a machine dependent frag.  */
16885
16886 void
16887 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16888 {
16889   if (RELAX_BRANCH_P (fragp->fr_subtype))
16890     {
16891       char *buf;
16892       unsigned long insn;
16893       expressionS exp;
16894       fixS *fixp;
16895
16896       buf = fragp->fr_literal + fragp->fr_fix;
16897       insn = read_insn (buf);
16898
16899       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16900         {
16901           /* We generate a fixup instead of applying it right now
16902              because, if there are linker relaxations, we're going to
16903              need the relocations.  */
16904           exp.X_op = O_symbol;
16905           exp.X_add_symbol = fragp->fr_symbol;
16906           exp.X_add_number = fragp->fr_offset;
16907
16908           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16909                               BFD_RELOC_16_PCREL_S2);
16910           fixp->fx_file = fragp->fr_file;
16911           fixp->fx_line = fragp->fr_line;
16912
16913           buf = write_insn (buf, insn);
16914         }
16915       else
16916         {
16917           int i;
16918
16919           as_warn_where (fragp->fr_file, fragp->fr_line,
16920                          _("relaxed out-of-range branch into a jump"));
16921
16922           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16923             goto uncond;
16924
16925           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16926             {
16927               /* Reverse the branch.  */
16928               switch ((insn >> 28) & 0xf)
16929                 {
16930                 case 4:
16931                   if ((insn & 0xff000000) == 0x47000000
16932                       || (insn & 0xff600000) == 0x45600000)
16933                     {
16934                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
16935                          reversed by tweaking bit 23.  */
16936                       insn ^= 0x00800000;
16937                     }
16938                   else
16939                     {
16940                       /* bc[0-3][tf]l? instructions can have the condition
16941                          reversed by tweaking a single TF bit, and their
16942                          opcodes all have 0x4???????.  */
16943                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
16944                       insn ^= 0x00010000;
16945                     }
16946                   break;
16947
16948                 case 0:
16949                   /* bltz       0x04000000      bgez    0x04010000
16950                      bltzal     0x04100000      bgezal  0x04110000  */
16951                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16952                   insn ^= 0x00010000;
16953                   break;
16954
16955                 case 1:
16956                   /* beq        0x10000000      bne     0x14000000
16957                      blez       0x18000000      bgtz    0x1c000000  */
16958                   insn ^= 0x04000000;
16959                   break;
16960
16961                 default:
16962                   abort ();
16963                 }
16964             }
16965
16966           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16967             {
16968               /* Clear the and-link bit.  */
16969               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16970
16971               /* bltzal         0x04100000      bgezal  0x04110000
16972                  bltzall        0x04120000      bgezall 0x04130000  */
16973               insn &= ~0x00100000;
16974             }
16975
16976           /* Branch over the branch (if the branch was likely) or the
16977              full jump (not likely case).  Compute the offset from the
16978              current instruction to branch to.  */
16979           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16980             i = 16;
16981           else
16982             {
16983               /* How many bytes in instructions we've already emitted?  */
16984               i = buf - fragp->fr_literal - fragp->fr_fix;
16985               /* How many bytes in instructions from here to the end?  */
16986               i = fragp->fr_var - i;
16987             }
16988           /* Convert to instruction count.  */
16989           i >>= 2;
16990           /* Branch counts from the next instruction.  */
16991           i--;
16992           insn |= i;
16993           /* Branch over the jump.  */
16994           buf = write_insn (buf, insn);
16995
16996           /* nop */
16997           buf = write_insn (buf, 0);
16998
16999           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17000             {
17001               /* beql $0, $0, 2f */
17002               insn = 0x50000000;
17003               /* Compute the PC offset from the current instruction to
17004                  the end of the variable frag.  */
17005               /* How many bytes in instructions we've already emitted?  */
17006               i = buf - fragp->fr_literal - fragp->fr_fix;
17007               /* How many bytes in instructions from here to the end?  */
17008               i = fragp->fr_var - i;
17009               /* Convert to instruction count.  */
17010               i >>= 2;
17011               /* Don't decrement i, because we want to branch over the
17012                  delay slot.  */
17013               insn |= i;
17014
17015               buf = write_insn (buf, insn);
17016               buf = write_insn (buf, 0);
17017             }
17018
17019         uncond:
17020           if (mips_pic == NO_PIC)
17021             {
17022               /* j or jal.  */
17023               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
17024                       ? 0x0c000000 : 0x08000000);
17025               exp.X_op = O_symbol;
17026               exp.X_add_symbol = fragp->fr_symbol;
17027               exp.X_add_number = fragp->fr_offset;
17028
17029               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17030                                   FALSE, BFD_RELOC_MIPS_JMP);
17031               fixp->fx_file = fragp->fr_file;
17032               fixp->fx_line = fragp->fr_line;
17033
17034               buf = write_insn (buf, insn);
17035             }
17036           else
17037             {
17038               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
17039
17040               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
17041               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
17042               insn |= at << OP_SH_RT;
17043               exp.X_op = O_symbol;
17044               exp.X_add_symbol = fragp->fr_symbol;
17045               exp.X_add_number = fragp->fr_offset;
17046
17047               if (fragp->fr_offset)
17048                 {
17049                   exp.X_add_symbol = make_expr_symbol (&exp);
17050                   exp.X_add_number = 0;
17051                 }
17052
17053               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17054                                   FALSE, BFD_RELOC_MIPS_GOT16);
17055               fixp->fx_file = fragp->fr_file;
17056               fixp->fx_line = fragp->fr_line;
17057
17058               buf = write_insn (buf, insn);
17059
17060               if (mips_opts.isa == ISA_MIPS1)
17061                 /* nop */
17062                 buf = write_insn (buf, 0);
17063
17064               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
17065               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
17066               insn |= at << OP_SH_RS | at << OP_SH_RT;
17067
17068               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17069                                   FALSE, BFD_RELOC_LO16);
17070               fixp->fx_file = fragp->fr_file;
17071               fixp->fx_line = fragp->fr_line;
17072
17073               buf = write_insn (buf, insn);
17074
17075               /* j(al)r $at.  */
17076               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17077                 insn = 0x0000f809;
17078               else
17079                 insn = 0x00000008;
17080               insn |= at << OP_SH_RS;
17081
17082               buf = write_insn (buf, insn);
17083             }
17084         }
17085
17086       fragp->fr_fix += fragp->fr_var;
17087       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17088       return;
17089     }
17090
17091   /* Relax microMIPS branches.  */
17092   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17093     {
17094       char *buf = fragp->fr_literal + fragp->fr_fix;
17095       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17096       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17097       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17098       bfd_boolean short_ds;
17099       unsigned long insn;
17100       expressionS exp;
17101       fixS *fixp;
17102
17103       exp.X_op = O_symbol;
17104       exp.X_add_symbol = fragp->fr_symbol;
17105       exp.X_add_number = fragp->fr_offset;
17106
17107       fragp->fr_fix += fragp->fr_var;
17108
17109       /* Handle 16-bit branches that fit or are forced to fit.  */
17110       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17111         {
17112           /* We generate a fixup instead of applying it right now,
17113              because if there is linker relaxation, we're going to
17114              need the relocations.  */
17115           if (type == 'D')
17116             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
17117                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
17118           else if (type == 'E')
17119             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
17120                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
17121           else
17122             abort ();
17123
17124           fixp->fx_file = fragp->fr_file;
17125           fixp->fx_line = fragp->fr_line;
17126
17127           /* These relocations can have an addend that won't fit in
17128              2 octets.  */
17129           fixp->fx_no_overflow = 1;
17130
17131           return;
17132         }
17133
17134       /* Handle 32-bit branches that fit or are forced to fit.  */
17135       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17136           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17137         {
17138           /* We generate a fixup instead of applying it right now,
17139              because if there is linker relaxation, we're going to
17140              need the relocations.  */
17141           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
17142                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
17143           fixp->fx_file = fragp->fr_file;
17144           fixp->fx_line = fragp->fr_line;
17145
17146           if (type == 0)
17147             return;
17148         }
17149
17150       /* Relax 16-bit branches to 32-bit branches.  */
17151       if (type != 0)
17152         {
17153           insn = read_compressed_insn (buf, 2);
17154
17155           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
17156             insn = 0x94000000;                          /* beq  */
17157           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
17158             {
17159               unsigned long regno;
17160
17161               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
17162               regno = micromips_to_32_reg_d_map [regno];
17163               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
17164               insn |= regno << MICROMIPSOP_SH_RS;
17165             }
17166           else
17167             abort ();
17168
17169           /* Nothing else to do, just write it out.  */
17170           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17171               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17172             {
17173               buf = write_compressed_insn (buf, insn, 4);
17174               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17175               return;
17176             }
17177         }
17178       else
17179         insn = read_compressed_insn (buf, 4);
17180
17181       /* Relax 32-bit branches to a sequence of instructions.  */
17182       as_warn_where (fragp->fr_file, fragp->fr_line,
17183                      _("relaxed out-of-range branch into a jump"));
17184
17185       /* Set the short-delay-slot bit.  */
17186       short_ds = al && (insn & 0x02000000) != 0;
17187
17188       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
17189         {
17190           symbolS *l;
17191
17192           /* Reverse the branch.  */
17193           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
17194               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
17195             insn ^= 0x20000000;
17196           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
17197                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
17198                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
17199                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
17200                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
17201                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
17202                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
17203                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
17204                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
17205                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
17206             insn ^= 0x00400000;
17207           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
17208                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
17209                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
17210                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
17211             insn ^= 0x00200000;
17212           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
17213                                                                    BNZ.df  */
17214                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
17215                                                                    BNZ.V */
17216             insn ^= 0x00800000;
17217           else
17218             abort ();
17219
17220           if (al)
17221             {
17222               /* Clear the and-link and short-delay-slot bits.  */
17223               gas_assert ((insn & 0xfda00000) == 0x40200000);
17224
17225               /* bltzal  0x40200000     bgezal  0x40600000  */
17226               /* bltzals 0x42200000     bgezals 0x42600000  */
17227               insn &= ~0x02200000;
17228             }
17229
17230           /* Make a label at the end for use with the branch.  */
17231           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
17232           micromips_label_inc ();
17233           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
17234
17235           /* Refer to it.  */
17236           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
17237                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
17238           fixp->fx_file = fragp->fr_file;
17239           fixp->fx_line = fragp->fr_line;
17240
17241           /* Branch over the jump.  */
17242           buf = write_compressed_insn (buf, insn, 4);
17243           if (!compact)
17244             /* nop */
17245             buf = write_compressed_insn (buf, 0x0c00, 2);
17246         }
17247
17248       if (mips_pic == NO_PIC)
17249         {
17250           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
17251
17252           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
17253           insn = al ? jal : 0xd4000000;
17254
17255           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17256                               BFD_RELOC_MICROMIPS_JMP);
17257           fixp->fx_file = fragp->fr_file;
17258           fixp->fx_line = fragp->fr_line;
17259
17260           buf = write_compressed_insn (buf, insn, 4);
17261           if (compact)
17262             /* nop */
17263             buf = write_compressed_insn (buf, 0x0c00, 2);
17264         }
17265       else
17266         {
17267           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
17268           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
17269           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
17270
17271           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
17272           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
17273           insn |= at << MICROMIPSOP_SH_RT;
17274
17275           if (exp.X_add_number)
17276             {
17277               exp.X_add_symbol = make_expr_symbol (&exp);
17278               exp.X_add_number = 0;
17279             }
17280
17281           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17282                               BFD_RELOC_MICROMIPS_GOT16);
17283           fixp->fx_file = fragp->fr_file;
17284           fixp->fx_line = fragp->fr_line;
17285
17286           buf = write_compressed_insn (buf, insn, 4);
17287
17288           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
17289           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
17290           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
17291
17292           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17293                               BFD_RELOC_MICROMIPS_LO16);
17294           fixp->fx_file = fragp->fr_file;
17295           fixp->fx_line = fragp->fr_line;
17296
17297           buf = write_compressed_insn (buf, insn, 4);
17298
17299           /* jr/jrc/jalr/jalrs $at  */
17300           insn = al ? jalr : jr;
17301           insn |= at << MICROMIPSOP_SH_MJ;
17302
17303           buf = write_compressed_insn (buf, insn, 2);
17304         }
17305
17306       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17307       return;
17308     }
17309
17310   if (RELAX_MIPS16_P (fragp->fr_subtype))
17311     {
17312       int type;
17313       const struct mips_int_operand *operand;
17314       offsetT val;
17315       char *buf;
17316       unsigned int user_length, length;
17317       unsigned long insn;
17318       bfd_boolean ext;
17319
17320       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17321       operand = mips16_immed_operand (type, FALSE);
17322
17323       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
17324       val = resolve_symbol_value (fragp->fr_symbol);
17325       if (operand->root.type == OP_PCREL)
17326         {
17327           const struct mips_pcrel_operand *pcrel_op;
17328           addressT addr;
17329
17330           pcrel_op = (const struct mips_pcrel_operand *) operand;
17331           addr = fragp->fr_address + fragp->fr_fix;
17332
17333           /* The rules for the base address of a PC relative reloc are
17334              complicated; see mips16_extended_frag.  */
17335           if (pcrel_op->include_isa_bit)
17336             {
17337               addr += 2;
17338               if (ext)
17339                 addr += 2;
17340               /* Ignore the low bit in the target, since it will be
17341                  set for a text label.  */
17342               val &= -2;
17343             }
17344           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17345             addr -= 4;
17346           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17347             addr -= 2;
17348
17349           addr &= -(1 << pcrel_op->align_log2);
17350           val -= addr;
17351
17352           /* Make sure the section winds up with the alignment we have
17353              assumed.  */
17354           if (operand->shift > 0)
17355             record_alignment (asec, operand->shift);
17356         }
17357
17358       if (ext
17359           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17360               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17361         as_warn_where (fragp->fr_file, fragp->fr_line,
17362                        _("extended instruction in delay slot"));
17363
17364       buf = fragp->fr_literal + fragp->fr_fix;
17365
17366       insn = read_compressed_insn (buf, 2);
17367       if (ext)
17368         insn |= MIPS16_EXTEND;
17369
17370       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17371         user_length = 4;
17372       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17373         user_length = 2;
17374       else
17375         user_length = 0;
17376
17377       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17378                     BFD_RELOC_UNUSED, val, user_length, &insn);
17379
17380       length = (ext ? 4 : 2);
17381       gas_assert (mips16_opcode_length (insn) == length);
17382       write_compressed_insn (buf, insn, length);
17383       fragp->fr_fix += length;
17384     }
17385   else
17386     {
17387       relax_substateT subtype = fragp->fr_subtype;
17388       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17389       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17390       int first, second;
17391       fixS *fixp;
17392
17393       first = RELAX_FIRST (subtype);
17394       second = RELAX_SECOND (subtype);
17395       fixp = (fixS *) fragp->fr_opcode;
17396
17397       /* If the delay slot chosen does not match the size of the instruction,
17398          then emit a warning.  */
17399       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17400            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17401         {
17402           relax_substateT s;
17403           const char *msg;
17404
17405           s = subtype & (RELAX_DELAY_SLOT_16BIT
17406                          | RELAX_DELAY_SLOT_SIZE_FIRST
17407                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17408           msg = macro_warning (s);
17409           if (msg != NULL)
17410             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17411           subtype &= ~s;
17412         }
17413
17414       /* Possibly emit a warning if we've chosen the longer option.  */
17415       if (use_second == second_longer)
17416         {
17417           relax_substateT s;
17418           const char *msg;
17419
17420           s = (subtype
17421                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17422           msg = macro_warning (s);
17423           if (msg != NULL)
17424             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17425           subtype &= ~s;
17426         }
17427
17428       /* Go through all the fixups for the first sequence.  Disable them
17429          (by marking them as done) if we're going to use the second
17430          sequence instead.  */
17431       while (fixp
17432              && fixp->fx_frag == fragp
17433              && fixp->fx_where < fragp->fr_fix - second)
17434         {
17435           if (subtype & RELAX_USE_SECOND)
17436             fixp->fx_done = 1;
17437           fixp = fixp->fx_next;
17438         }
17439
17440       /* Go through the fixups for the second sequence.  Disable them if
17441          we're going to use the first sequence, otherwise adjust their
17442          addresses to account for the relaxation.  */
17443       while (fixp && fixp->fx_frag == fragp)
17444         {
17445           if (subtype & RELAX_USE_SECOND)
17446             fixp->fx_where -= first;
17447           else
17448             fixp->fx_done = 1;
17449           fixp = fixp->fx_next;
17450         }
17451
17452       /* Now modify the frag contents.  */
17453       if (subtype & RELAX_USE_SECOND)
17454         {
17455           char *start;
17456
17457           start = fragp->fr_literal + fragp->fr_fix - first - second;
17458           memmove (start, start + first, second);
17459           fragp->fr_fix -= first;
17460         }
17461       else
17462         fragp->fr_fix -= second;
17463     }
17464 }
17465
17466 /* This function is called after the relocs have been generated.
17467    We've been storing mips16 text labels as odd.  Here we convert them
17468    back to even for the convenience of the debugger.  */
17469
17470 void
17471 mips_frob_file_after_relocs (void)
17472 {
17473   asymbol **syms;
17474   unsigned int count, i;
17475
17476   syms = bfd_get_outsymbols (stdoutput);
17477   count = bfd_get_symcount (stdoutput);
17478   for (i = 0; i < count; i++, syms++)
17479     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17480         && ((*syms)->value & 1) != 0)
17481       {
17482         (*syms)->value &= ~1;
17483         /* If the symbol has an odd size, it was probably computed
17484            incorrectly, so adjust that as well.  */
17485         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17486           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17487       }
17488 }
17489
17490 /* This function is called whenever a label is defined, including fake
17491    labels instantiated off the dot special symbol.  It is used when
17492    handling branch delays; if a branch has a label, we assume we cannot
17493    move it.  This also bumps the value of the symbol by 1 in compressed
17494    code.  */
17495
17496 static void
17497 mips_record_label (symbolS *sym)
17498 {
17499   segment_info_type *si = seg_info (now_seg);
17500   struct insn_label_list *l;
17501
17502   if (free_insn_labels == NULL)
17503     l = (struct insn_label_list *) xmalloc (sizeof *l);
17504   else
17505     {
17506       l = free_insn_labels;
17507       free_insn_labels = l->next;
17508     }
17509
17510   l->label = sym;
17511   l->next = si->label_list;
17512   si->label_list = l;
17513 }
17514
17515 /* This function is called as tc_frob_label() whenever a label is defined
17516    and adds a DWARF-2 record we only want for true labels.  */
17517
17518 void
17519 mips_define_label (symbolS *sym)
17520 {
17521   mips_record_label (sym);
17522   dwarf2_emit_label (sym);
17523 }
17524
17525 /* This function is called by tc_new_dot_label whenever a new dot symbol
17526    is defined.  */
17527
17528 void
17529 mips_add_dot_label (symbolS *sym)
17530 {
17531   mips_record_label (sym);
17532   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17533     mips_compressed_mark_label (sym);
17534 }
17535 \f
17536 /* Converting ASE flags from internal to .MIPS.abiflags values.  */
17537 static unsigned int
17538 mips_convert_ase_flags (int ase)
17539 {
17540   unsigned int ext_ases = 0;
17541
17542   if (ase & ASE_DSP)
17543     ext_ases |= AFL_ASE_DSP;
17544   if (ase & ASE_DSPR2)
17545     ext_ases |= AFL_ASE_DSPR2;
17546   if (ase & ASE_EVA)
17547     ext_ases |= AFL_ASE_EVA;
17548   if (ase & ASE_MCU)
17549     ext_ases |= AFL_ASE_MCU;
17550   if (ase & ASE_MDMX)
17551     ext_ases |= AFL_ASE_MDMX;
17552   if (ase & ASE_MIPS3D)
17553     ext_ases |= AFL_ASE_MIPS3D;
17554   if (ase & ASE_MT)
17555     ext_ases |= AFL_ASE_MT;
17556   if (ase & ASE_SMARTMIPS)
17557     ext_ases |= AFL_ASE_SMARTMIPS;
17558   if (ase & ASE_VIRT)
17559     ext_ases |= AFL_ASE_VIRT;
17560   if (ase & ASE_MSA)
17561     ext_ases |= AFL_ASE_MSA;
17562   if (ase & ASE_XPA)
17563     ext_ases |= AFL_ASE_XPA;
17564
17565   return ext_ases;
17566 }
17567 /* Some special processing for a MIPS ELF file.  */
17568
17569 void
17570 mips_elf_final_processing (void)
17571 {
17572   int fpabi;
17573   Elf_Internal_ABIFlags_v0 flags;
17574
17575   flags.version = 0;
17576   flags.isa_rev = 0;
17577   switch (file_mips_opts.isa)
17578     {
17579     case INSN_ISA1:
17580       flags.isa_level = 1;
17581       break;
17582     case INSN_ISA2:
17583       flags.isa_level = 2;
17584       break;
17585     case INSN_ISA3:
17586       flags.isa_level = 3;
17587       break;
17588     case INSN_ISA4:
17589       flags.isa_level = 4;
17590       break;
17591     case INSN_ISA5:
17592       flags.isa_level = 5;
17593       break;
17594     case INSN_ISA32:
17595       flags.isa_level = 32;
17596       flags.isa_rev = 1;
17597       break;
17598     case INSN_ISA32R2:
17599       flags.isa_level = 32;
17600       flags.isa_rev = 2;
17601       break;
17602     case INSN_ISA32R3:
17603       flags.isa_level = 32;
17604       flags.isa_rev = 3;
17605       break;
17606     case INSN_ISA32R5:
17607       flags.isa_level = 32;
17608       flags.isa_rev = 5;
17609       break;
17610     case INSN_ISA64:
17611       flags.isa_level = 64;
17612       flags.isa_rev = 1;
17613       break;
17614     case INSN_ISA64R2:
17615       flags.isa_level = 64;
17616       flags.isa_rev = 2;
17617       break;
17618     case INSN_ISA64R3:
17619       flags.isa_level = 64;
17620       flags.isa_rev = 3;
17621       break;
17622     case INSN_ISA64R5:
17623       flags.isa_level = 64;
17624       flags.isa_rev = 5;
17625       break;
17626     }
17627
17628   flags.gpr_size = file_mips_opts.gp == 32 ? AFL_REG_32 : AFL_REG_64;
17629   flags.cpr1_size = file_mips_opts.soft_float ? AFL_REG_NONE
17630                     : (file_mips_opts.ase & ASE_MSA) ? AFL_REG_128
17631                     : (file_mips_opts.fp == 64) ? AFL_REG_64
17632                     : AFL_REG_32;
17633   flags.cpr2_size = AFL_REG_NONE;
17634   flags.fp_abi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
17635                                            Tag_GNU_MIPS_ABI_FP);
17636   flags.isa_ext = bfd_mips_isa_ext (stdoutput);
17637   flags.ases = mips_convert_ase_flags (file_mips_opts.ase);
17638   if (file_ase_mips16)
17639     flags.ases |= AFL_ASE_MIPS16;
17640   if (file_ase_micromips)
17641     flags.ases |= AFL_ASE_MICROMIPS;
17642   flags.flags1 = 0;
17643   if ((ISA_HAS_ODD_SINGLE_FPR (file_mips_opts.isa, file_mips_opts.arch)
17644        || file_mips_opts.fp == 64)
17645       && file_mips_opts.oddspreg)
17646     flags.flags1 |= AFL_FLAGS1_ODDSPREG;
17647   flags.flags2 = 0;
17648
17649   bfd_mips_elf_swap_abiflags_v0_out (stdoutput, &flags,
17650                                      ((Elf_External_ABIFlags_v0 *)
17651                                      mips_flags_frag));
17652
17653   /* Write out the register information.  */
17654   if (mips_abi != N64_ABI)
17655     {
17656       Elf32_RegInfo s;
17657
17658       s.ri_gprmask = mips_gprmask;
17659       s.ri_cprmask[0] = mips_cprmask[0];
17660       s.ri_cprmask[1] = mips_cprmask[1];
17661       s.ri_cprmask[2] = mips_cprmask[2];
17662       s.ri_cprmask[3] = mips_cprmask[3];
17663       /* The gp_value field is set by the MIPS ELF backend.  */
17664
17665       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17666                                        ((Elf32_External_RegInfo *)
17667                                         mips_regmask_frag));
17668     }
17669   else
17670     {
17671       Elf64_Internal_RegInfo s;
17672
17673       s.ri_gprmask = mips_gprmask;
17674       s.ri_pad = 0;
17675       s.ri_cprmask[0] = mips_cprmask[0];
17676       s.ri_cprmask[1] = mips_cprmask[1];
17677       s.ri_cprmask[2] = mips_cprmask[2];
17678       s.ri_cprmask[3] = mips_cprmask[3];
17679       /* The gp_value field is set by the MIPS ELF backend.  */
17680
17681       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17682                                        ((Elf64_External_RegInfo *)
17683                                         mips_regmask_frag));
17684     }
17685
17686   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17687      sort of BFD interface for this.  */
17688   if (mips_any_noreorder)
17689     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17690   if (mips_pic != NO_PIC)
17691     {
17692       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17693       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17694     }
17695   if (mips_abicalls)
17696     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17697
17698   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17699      defined at present; this might need to change in future.  */
17700   if (file_ase_mips16)
17701     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17702   if (file_ase_micromips)
17703     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17704   if (file_mips_opts.ase & ASE_MDMX)
17705     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17706
17707   /* Set the MIPS ELF ABI flags.  */
17708   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17709     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17710   else if (mips_abi == O64_ABI)
17711     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17712   else if (mips_abi == EABI_ABI)
17713     {
17714       if (file_mips_opts.gp == 64)
17715         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17716       else
17717         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17718     }
17719   else if (mips_abi == N32_ABI)
17720     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17721
17722   /* Nothing to do for N64_ABI.  */
17723
17724   if (mips_32bitmode)
17725     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17726
17727   if (mips_flag_nan2008)
17728     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17729
17730   /* 32 bit code with 64 bit FP registers.  */
17731   fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
17732                                     Tag_GNU_MIPS_ABI_FP);
17733   if (fpabi == Val_GNU_MIPS_ABI_FP_OLD_64)
17734     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
17735 }
17736 \f
17737 typedef struct proc {
17738   symbolS *func_sym;
17739   symbolS *func_end_sym;
17740   unsigned long reg_mask;
17741   unsigned long reg_offset;
17742   unsigned long fpreg_mask;
17743   unsigned long fpreg_offset;
17744   unsigned long frame_offset;
17745   unsigned long frame_reg;
17746   unsigned long pc_reg;
17747 } procS;
17748
17749 static procS cur_proc;
17750 static procS *cur_proc_ptr;
17751 static int numprocs;
17752
17753 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17754    as "2", and a normal nop as "0".  */
17755
17756 #define NOP_OPCODE_MIPS         0
17757 #define NOP_OPCODE_MIPS16       1
17758 #define NOP_OPCODE_MICROMIPS    2
17759
17760 char
17761 mips_nop_opcode (void)
17762 {
17763   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17764     return NOP_OPCODE_MICROMIPS;
17765   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17766     return NOP_OPCODE_MIPS16;
17767   else
17768     return NOP_OPCODE_MIPS;
17769 }
17770
17771 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17772    32-bit microMIPS NOPs here (if applicable).  */
17773
17774 void
17775 mips_handle_align (fragS *fragp)
17776 {
17777   char nop_opcode;
17778   char *p;
17779   int bytes, size, excess;
17780   valueT opcode;
17781
17782   if (fragp->fr_type != rs_align_code)
17783     return;
17784
17785   p = fragp->fr_literal + fragp->fr_fix;
17786   nop_opcode = *p;
17787   switch (nop_opcode)
17788     {
17789     case NOP_OPCODE_MICROMIPS:
17790       opcode = micromips_nop32_insn.insn_opcode;
17791       size = 4;
17792       break;
17793     case NOP_OPCODE_MIPS16:
17794       opcode = mips16_nop_insn.insn_opcode;
17795       size = 2;
17796       break;
17797     case NOP_OPCODE_MIPS:
17798     default:
17799       opcode = nop_insn.insn_opcode;
17800       size = 4;
17801       break;
17802     }
17803
17804   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17805   excess = bytes % size;
17806
17807   /* Handle the leading part if we're not inserting a whole number of
17808      instructions, and make it the end of the fixed part of the frag.
17809      Try to fit in a short microMIPS NOP if applicable and possible,
17810      and use zeroes otherwise.  */
17811   gas_assert (excess < 4);
17812   fragp->fr_fix += excess;
17813   switch (excess)
17814     {
17815     case 3:
17816       *p++ = '\0';
17817       /* Fall through.  */
17818     case 2:
17819       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17820         {
17821           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17822           break;
17823         }
17824       *p++ = '\0';
17825       /* Fall through.  */
17826     case 1:
17827       *p++ = '\0';
17828       /* Fall through.  */
17829     case 0:
17830       break;
17831     }
17832
17833   md_number_to_chars (p, opcode, size);
17834   fragp->fr_var = size;
17835 }
17836
17837 static long
17838 get_number (void)
17839 {
17840   int negative = 0;
17841   long val = 0;
17842
17843   if (*input_line_pointer == '-')
17844     {
17845       ++input_line_pointer;
17846       negative = 1;
17847     }
17848   if (!ISDIGIT (*input_line_pointer))
17849     as_bad (_("expected simple number"));
17850   if (input_line_pointer[0] == '0')
17851     {
17852       if (input_line_pointer[1] == 'x')
17853         {
17854           input_line_pointer += 2;
17855           while (ISXDIGIT (*input_line_pointer))
17856             {
17857               val <<= 4;
17858               val |= hex_value (*input_line_pointer++);
17859             }
17860           return negative ? -val : val;
17861         }
17862       else
17863         {
17864           ++input_line_pointer;
17865           while (ISDIGIT (*input_line_pointer))
17866             {
17867               val <<= 3;
17868               val |= *input_line_pointer++ - '0';
17869             }
17870           return negative ? -val : val;
17871         }
17872     }
17873   if (!ISDIGIT (*input_line_pointer))
17874     {
17875       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17876               *input_line_pointer, *input_line_pointer);
17877       as_warn (_("invalid number"));
17878       return -1;
17879     }
17880   while (ISDIGIT (*input_line_pointer))
17881     {
17882       val *= 10;
17883       val += *input_line_pointer++ - '0';
17884     }
17885   return negative ? -val : val;
17886 }
17887
17888 /* The .file directive; just like the usual .file directive, but there
17889    is an initial number which is the ECOFF file index.  In the non-ECOFF
17890    case .file implies DWARF-2.  */
17891
17892 static void
17893 s_mips_file (int x ATTRIBUTE_UNUSED)
17894 {
17895   static int first_file_directive = 0;
17896
17897   if (ECOFF_DEBUGGING)
17898     {
17899       get_number ();
17900       s_app_file (0);
17901     }
17902   else
17903     {
17904       char *filename;
17905
17906       filename = dwarf2_directive_file (0);
17907
17908       /* Versions of GCC up to 3.1 start files with a ".file"
17909          directive even for stabs output.  Make sure that this
17910          ".file" is handled.  Note that you need a version of GCC
17911          after 3.1 in order to support DWARF-2 on MIPS.  */
17912       if (filename != NULL && ! first_file_directive)
17913         {
17914           (void) new_logical_line (filename, -1);
17915           s_app_file_string (filename, 0);
17916         }
17917       first_file_directive = 1;
17918     }
17919 }
17920
17921 /* The .loc directive, implying DWARF-2.  */
17922
17923 static void
17924 s_mips_loc (int x ATTRIBUTE_UNUSED)
17925 {
17926   if (!ECOFF_DEBUGGING)
17927     dwarf2_directive_loc (0);
17928 }
17929
17930 /* The .end directive.  */
17931
17932 static void
17933 s_mips_end (int x ATTRIBUTE_UNUSED)
17934 {
17935   symbolS *p;
17936
17937   /* Following functions need their own .frame and .cprestore directives.  */
17938   mips_frame_reg_valid = 0;
17939   mips_cprestore_valid = 0;
17940
17941   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17942     {
17943       p = get_symbol ();
17944       demand_empty_rest_of_line ();
17945     }
17946   else
17947     p = NULL;
17948
17949   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17950     as_warn (_(".end not in text section"));
17951
17952   if (!cur_proc_ptr)
17953     {
17954       as_warn (_(".end directive without a preceding .ent directive"));
17955       demand_empty_rest_of_line ();
17956       return;
17957     }
17958
17959   if (p != NULL)
17960     {
17961       gas_assert (S_GET_NAME (p));
17962       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17963         as_warn (_(".end symbol does not match .ent symbol"));
17964
17965       if (debug_type == DEBUG_STABS)
17966         stabs_generate_asm_endfunc (S_GET_NAME (p),
17967                                     S_GET_NAME (p));
17968     }
17969   else
17970     as_warn (_(".end directive missing or unknown symbol"));
17971
17972   /* Create an expression to calculate the size of the function.  */
17973   if (p && cur_proc_ptr)
17974     {
17975       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17976       expressionS *exp = xmalloc (sizeof (expressionS));
17977
17978       obj->size = exp;
17979       exp->X_op = O_subtract;
17980       exp->X_add_symbol = symbol_temp_new_now ();
17981       exp->X_op_symbol = p;
17982       exp->X_add_number = 0;
17983
17984       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17985     }
17986
17987   /* Generate a .pdr section.  */
17988   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17989     {
17990       segT saved_seg = now_seg;
17991       subsegT saved_subseg = now_subseg;
17992       expressionS exp;
17993       char *fragp;
17994
17995 #ifdef md_flush_pending_output
17996       md_flush_pending_output ();
17997 #endif
17998
17999       gas_assert (pdr_seg);
18000       subseg_set (pdr_seg, 0);
18001
18002       /* Write the symbol.  */
18003       exp.X_op = O_symbol;
18004       exp.X_add_symbol = p;
18005       exp.X_add_number = 0;
18006       emit_expr (&exp, 4);
18007
18008       fragp = frag_more (7 * 4);
18009
18010       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
18011       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
18012       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
18013       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
18014       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
18015       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
18016       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
18017
18018       subseg_set (saved_seg, saved_subseg);
18019     }
18020
18021   cur_proc_ptr = NULL;
18022 }
18023
18024 /* The .aent and .ent directives.  */
18025
18026 static void
18027 s_mips_ent (int aent)
18028 {
18029   symbolS *symbolP;
18030
18031   symbolP = get_symbol ();
18032   if (*input_line_pointer == ',')
18033     ++input_line_pointer;
18034   SKIP_WHITESPACE ();
18035   if (ISDIGIT (*input_line_pointer)
18036       || *input_line_pointer == '-')
18037     get_number ();
18038
18039   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18040     as_warn (_(".ent or .aent not in text section"));
18041
18042   if (!aent && cur_proc_ptr)
18043     as_warn (_("missing .end"));
18044
18045   if (!aent)
18046     {
18047       /* This function needs its own .frame and .cprestore directives.  */
18048       mips_frame_reg_valid = 0;
18049       mips_cprestore_valid = 0;
18050
18051       cur_proc_ptr = &cur_proc;
18052       memset (cur_proc_ptr, '\0', sizeof (procS));
18053
18054       cur_proc_ptr->func_sym = symbolP;
18055
18056       ++numprocs;
18057
18058       if (debug_type == DEBUG_STABS)
18059         stabs_generate_asm_func (S_GET_NAME (symbolP),
18060                                  S_GET_NAME (symbolP));
18061     }
18062
18063   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
18064
18065   demand_empty_rest_of_line ();
18066 }
18067
18068 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
18069    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
18070    s_mips_frame is used so that we can set the PDR information correctly.
18071    We can't use the ecoff routines because they make reference to the ecoff
18072    symbol table (in the mdebug section).  */
18073
18074 static void
18075 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
18076 {
18077   if (ECOFF_DEBUGGING)
18078     s_ignore (ignore);
18079   else
18080     {
18081       long val;
18082
18083       if (cur_proc_ptr == (procS *) NULL)
18084         {
18085           as_warn (_(".frame outside of .ent"));
18086           demand_empty_rest_of_line ();
18087           return;
18088         }
18089
18090       cur_proc_ptr->frame_reg = tc_get_register (1);
18091
18092       SKIP_WHITESPACE ();
18093       if (*input_line_pointer++ != ','
18094           || get_absolute_expression_and_terminator (&val) != ',')
18095         {
18096           as_warn (_("bad .frame directive"));
18097           --input_line_pointer;
18098           demand_empty_rest_of_line ();
18099           return;
18100         }
18101
18102       cur_proc_ptr->frame_offset = val;
18103       cur_proc_ptr->pc_reg = tc_get_register (0);
18104
18105       demand_empty_rest_of_line ();
18106     }
18107 }
18108
18109 /* The .fmask and .mask directives. If the mdebug section is present
18110    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
18111    embedded targets, s_mips_mask is used so that we can set the PDR
18112    information correctly. We can't use the ecoff routines because they
18113    make reference to the ecoff symbol table (in the mdebug section).  */
18114
18115 static void
18116 s_mips_mask (int reg_type)
18117 {
18118   if (ECOFF_DEBUGGING)
18119     s_ignore (reg_type);
18120   else
18121     {
18122       long mask, off;
18123
18124       if (cur_proc_ptr == (procS *) NULL)
18125         {
18126           as_warn (_(".mask/.fmask outside of .ent"));
18127           demand_empty_rest_of_line ();
18128           return;
18129         }
18130
18131       if (get_absolute_expression_and_terminator (&mask) != ',')
18132         {
18133           as_warn (_("bad .mask/.fmask directive"));
18134           --input_line_pointer;
18135           demand_empty_rest_of_line ();
18136           return;
18137         }
18138
18139       off = get_absolute_expression ();
18140
18141       if (reg_type == 'F')
18142         {
18143           cur_proc_ptr->fpreg_mask = mask;
18144           cur_proc_ptr->fpreg_offset = off;
18145         }
18146       else
18147         {
18148           cur_proc_ptr->reg_mask = mask;
18149           cur_proc_ptr->reg_offset = off;
18150         }
18151
18152       demand_empty_rest_of_line ();
18153     }
18154 }
18155
18156 /* A table describing all the processors gas knows about.  Names are
18157    matched in the order listed.
18158
18159    To ease comparison, please keep this table in the same order as
18160    gcc's mips_cpu_info_table[].  */
18161 static const struct mips_cpu_info mips_cpu_info_table[] =
18162 {
18163   /* Entries for generic ISAs */
18164   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
18165   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
18166   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
18167   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
18168   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
18169   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
18170   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
18171   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
18172   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
18173   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
18174   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
18175   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
18176   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
18177
18178   /* MIPS I */
18179   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
18180   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
18181   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
18182
18183   /* MIPS II */
18184   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
18185
18186   /* MIPS III */
18187   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
18188   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
18189   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
18190   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
18191   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
18192   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
18193   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
18194   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
18195   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
18196   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
18197   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
18198   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
18199   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
18200   /* ST Microelectronics Loongson 2E and 2F cores */
18201   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
18202   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
18203
18204   /* MIPS IV */
18205   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
18206   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
18207   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
18208   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
18209   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
18210   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18211   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
18212   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
18213   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18214   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18215   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18216   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18217   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18218   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
18219   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
18220
18221   /* MIPS 32 */
18222   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
18223   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
18224   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
18225   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
18226
18227   /* MIPS 32 Release 2 */
18228   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18229   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18230   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18231   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
18232   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18233   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18234   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
18235   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
18236   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
18237                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
18238   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
18239                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
18240   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18241   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18242   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18243   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18244   /* Deprecated forms of the above.  */
18245   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18246   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18247   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
18248   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18249   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18250   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18251   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18252   /* Deprecated forms of the above.  */
18253   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18254   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18255   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
18256   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18257   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18258   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18259   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18260   /* Deprecated forms of the above.  */
18261   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18262   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18263   /* 34Kn is a 34kc without DSP.  */
18264   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
18265   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
18266   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18267   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18268   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18269   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18270   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18271   /* Deprecated forms of the above.  */
18272   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18273   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18274   /* 1004K cores are multiprocessor versions of the 34K.  */
18275   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18276   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18277   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18278   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18279   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
18280   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
18281
18282   /* MIPS 64 */
18283   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
18284   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
18285   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
18286   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
18287
18288   /* Broadcom SB-1 CPU core */
18289   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
18290   /* Broadcom SB-1A CPU core */
18291   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
18292   
18293   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
18294
18295   /* MIPS 64 Release 2 */
18296
18297   /* Cavium Networks Octeon CPU core */
18298   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
18299   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
18300   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
18301
18302   /* RMI Xlr */
18303   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
18304
18305   /* Broadcom XLP.
18306      XLP is mostly like XLR, with the prominent exception that it is
18307      MIPS64R2 rather than MIPS64.  */
18308   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
18309
18310   /* End marker */
18311   { NULL, 0, 0, 0, 0 }
18312 };
18313
18314
18315 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
18316    with a final "000" replaced by "k".  Ignore case.
18317
18318    Note: this function is shared between GCC and GAS.  */
18319
18320 static bfd_boolean
18321 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
18322 {
18323   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
18324     given++, canonical++;
18325
18326   return ((*given == 0 && *canonical == 0)
18327           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
18328 }
18329
18330
18331 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
18332    CPU name.  We've traditionally allowed a lot of variation here.
18333
18334    Note: this function is shared between GCC and GAS.  */
18335
18336 static bfd_boolean
18337 mips_matching_cpu_name_p (const char *canonical, const char *given)
18338 {
18339   /* First see if the name matches exactly, or with a final "000"
18340      turned into "k".  */
18341   if (mips_strict_matching_cpu_name_p (canonical, given))
18342     return TRUE;
18343
18344   /* If not, try comparing based on numerical designation alone.
18345      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
18346   if (TOLOWER (*given) == 'r')
18347     given++;
18348   if (!ISDIGIT (*given))
18349     return FALSE;
18350
18351   /* Skip over some well-known prefixes in the canonical name,
18352      hoping to find a number there too.  */
18353   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
18354     canonical += 2;
18355   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
18356     canonical += 2;
18357   else if (TOLOWER (canonical[0]) == 'r')
18358     canonical += 1;
18359
18360   return mips_strict_matching_cpu_name_p (canonical, given);
18361 }
18362
18363
18364 /* Parse an option that takes the name of a processor as its argument.
18365    OPTION is the name of the option and CPU_STRING is the argument.
18366    Return the corresponding processor enumeration if the CPU_STRING is
18367    recognized, otherwise report an error and return null.
18368
18369    A similar function exists in GCC.  */
18370
18371 static const struct mips_cpu_info *
18372 mips_parse_cpu (const char *option, const char *cpu_string)
18373 {
18374   const struct mips_cpu_info *p;
18375
18376   /* 'from-abi' selects the most compatible architecture for the given
18377      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
18378      EABIs, we have to decide whether we're using the 32-bit or 64-bit
18379      version.  Look first at the -mgp options, if given, otherwise base
18380      the choice on MIPS_DEFAULT_64BIT.
18381
18382      Treat NO_ABI like the EABIs.  One reason to do this is that the
18383      plain 'mips' and 'mips64' configs have 'from-abi' as their default
18384      architecture.  This code picks MIPS I for 'mips' and MIPS III for
18385      'mips64', just as we did in the days before 'from-abi'.  */
18386   if (strcasecmp (cpu_string, "from-abi") == 0)
18387     {
18388       if (ABI_NEEDS_32BIT_REGS (mips_abi))
18389         return mips_cpu_info_from_isa (ISA_MIPS1);
18390
18391       if (ABI_NEEDS_64BIT_REGS (mips_abi))
18392         return mips_cpu_info_from_isa (ISA_MIPS3);
18393
18394       if (file_mips_opts.gp >= 0)
18395         return mips_cpu_info_from_isa (file_mips_opts.gp == 32
18396                                        ? ISA_MIPS1 : ISA_MIPS3);
18397
18398       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
18399                                      ? ISA_MIPS3
18400                                      : ISA_MIPS1);
18401     }
18402
18403   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
18404   if (strcasecmp (cpu_string, "default") == 0)
18405     return 0;
18406
18407   for (p = mips_cpu_info_table; p->name != 0; p++)
18408     if (mips_matching_cpu_name_p (p->name, cpu_string))
18409       return p;
18410
18411   as_bad (_("bad value (%s) for %s"), cpu_string, option);
18412   return 0;
18413 }
18414
18415 /* Return the canonical processor information for ISA (a member of the
18416    ISA_MIPS* enumeration).  */
18417
18418 static const struct mips_cpu_info *
18419 mips_cpu_info_from_isa (int isa)
18420 {
18421   int i;
18422
18423   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18424     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
18425         && isa == mips_cpu_info_table[i].isa)
18426       return (&mips_cpu_info_table[i]);
18427
18428   return NULL;
18429 }
18430
18431 static const struct mips_cpu_info *
18432 mips_cpu_info_from_arch (int arch)
18433 {
18434   int i;
18435
18436   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18437     if (arch == mips_cpu_info_table[i].cpu)
18438       return (&mips_cpu_info_table[i]);
18439
18440   return NULL;
18441 }
18442 \f
18443 static void
18444 show (FILE *stream, const char *string, int *col_p, int *first_p)
18445 {
18446   if (*first_p)
18447     {
18448       fprintf (stream, "%24s", "");
18449       *col_p = 24;
18450     }
18451   else
18452     {
18453       fprintf (stream, ", ");
18454       *col_p += 2;
18455     }
18456
18457   if (*col_p + strlen (string) > 72)
18458     {
18459       fprintf (stream, "\n%24s", "");
18460       *col_p = 24;
18461     }
18462
18463   fprintf (stream, "%s", string);
18464   *col_p += strlen (string);
18465
18466   *first_p = 0;
18467 }
18468
18469 void
18470 md_show_usage (FILE *stream)
18471 {
18472   int column, first;
18473   size_t i;
18474
18475   fprintf (stream, _("\
18476 MIPS options:\n\
18477 -EB                     generate big endian output\n\
18478 -EL                     generate little endian output\n\
18479 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18480 -G NUM                  allow referencing objects up to NUM bytes\n\
18481                         implicitly with the gp register [default 8]\n"));
18482   fprintf (stream, _("\
18483 -mips1                  generate MIPS ISA I instructions\n\
18484 -mips2                  generate MIPS ISA II instructions\n\
18485 -mips3                  generate MIPS ISA III instructions\n\
18486 -mips4                  generate MIPS ISA IV instructions\n\
18487 -mips5                  generate MIPS ISA V instructions\n\
18488 -mips32                 generate MIPS32 ISA instructions\n\
18489 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18490 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
18491 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
18492 -mips64                 generate MIPS64 ISA instructions\n\
18493 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18494 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
18495 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
18496 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18497
18498   first = 1;
18499
18500   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18501     show (stream, mips_cpu_info_table[i].name, &column, &first);
18502   show (stream, "from-abi", &column, &first);
18503   fputc ('\n', stream);
18504
18505   fprintf (stream, _("\
18506 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18507 -no-mCPU                don't generate code specific to CPU.\n\
18508                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18509
18510   first = 1;
18511
18512   show (stream, "3900", &column, &first);
18513   show (stream, "4010", &column, &first);
18514   show (stream, "4100", &column, &first);
18515   show (stream, "4650", &column, &first);
18516   fputc ('\n', stream);
18517
18518   fprintf (stream, _("\
18519 -mips16                 generate mips16 instructions\n\
18520 -no-mips16              do not generate mips16 instructions\n"));
18521   fprintf (stream, _("\
18522 -mmicromips             generate microMIPS instructions\n\
18523 -mno-micromips          do not generate microMIPS instructions\n"));
18524   fprintf (stream, _("\
18525 -msmartmips             generate smartmips instructions\n\
18526 -mno-smartmips          do not generate smartmips instructions\n"));  
18527   fprintf (stream, _("\
18528 -mdsp                   generate DSP instructions\n\
18529 -mno-dsp                do not generate DSP instructions\n"));
18530   fprintf (stream, _("\
18531 -mdspr2                 generate DSP R2 instructions\n\
18532 -mno-dspr2              do not generate DSP R2 instructions\n"));
18533   fprintf (stream, _("\
18534 -mmt                    generate MT instructions\n\
18535 -mno-mt                 do not generate MT instructions\n"));
18536   fprintf (stream, _("\
18537 -mmcu                   generate MCU instructions\n\
18538 -mno-mcu                do not generate MCU instructions\n"));
18539   fprintf (stream, _("\
18540 -mmsa                   generate MSA instructions\n\
18541 -mno-msa                do not generate MSA instructions\n"));
18542   fprintf (stream, _("\
18543 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
18544 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
18545   fprintf (stream, _("\
18546 -mvirt                  generate Virtualization instructions\n\
18547 -mno-virt               do not generate Virtualization instructions\n"));
18548   fprintf (stream, _("\
18549 -minsn32                only generate 32-bit microMIPS instructions\n\
18550 -mno-insn32             generate all microMIPS instructions\n"));
18551   fprintf (stream, _("\
18552 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18553 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18554 -mfix-vr4120            work around certain VR4120 errata\n\
18555 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18556 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18557 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18558 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18559 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18560 -msym32                 assume all symbols have 32-bit values\n\
18561 -O0                     remove unneeded NOPs, do not swap branches\n\
18562 -O                      remove unneeded NOPs and swap branches\n\
18563 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18564 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18565   fprintf (stream, _("\
18566 -mhard-float            allow floating-point instructions\n\
18567 -msoft-float            do not allow floating-point instructions\n\
18568 -msingle-float          only allow 32-bit floating-point operations\n\
18569 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18570 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18571 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18572 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18573
18574   first = 1;
18575
18576   show (stream, "legacy", &column, &first);
18577   show (stream, "2008", &column, &first);
18578
18579   fputc ('\n', stream);
18580
18581   fprintf (stream, _("\
18582 -KPIC, -call_shared     generate SVR4 position independent code\n\
18583 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18584 -mvxworks-pic           generate VxWorks position independent code\n\
18585 -non_shared             do not generate code that can operate with DSOs\n\
18586 -xgot                   assume a 32 bit GOT\n\
18587 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18588 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18589                         position dependent (non shared) code\n\
18590 -mabi=ABI               create ABI conformant object file for:\n"));
18591
18592   first = 1;
18593
18594   show (stream, "32", &column, &first);
18595   show (stream, "o64", &column, &first);
18596   show (stream, "n32", &column, &first);
18597   show (stream, "64", &column, &first);
18598   show (stream, "eabi", &column, &first);
18599
18600   fputc ('\n', stream);
18601
18602   fprintf (stream, _("\
18603 -32                     create o32 ABI object file (default)\n\
18604 -n32                    create n32 ABI object file\n\
18605 -64                     create 64 ABI object file\n"));
18606 }
18607
18608 #ifdef TE_IRIX
18609 enum dwarf2_format
18610 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18611 {
18612   if (HAVE_64BIT_SYMBOLS)
18613     return dwarf2_format_64bit_irix;
18614   else
18615     return dwarf2_format_32bit;
18616 }
18617 #endif
18618
18619 int
18620 mips_dwarf2_addr_size (void)
18621 {
18622   if (HAVE_64BIT_OBJECTS)
18623     return 8;
18624   else
18625     return 4;
18626 }
18627
18628 /* Standard calling conventions leave the CFA at SP on entry.  */
18629 void
18630 mips_cfi_frame_initial_instructions (void)
18631 {
18632   cfi_add_CFA_def_cfa_register (SP);
18633 }
18634
18635 int
18636 tc_mips_regname_to_dw2regnum (char *regname)
18637 {
18638   unsigned int regnum = -1;
18639   unsigned int reg;
18640
18641   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18642     regnum = reg;
18643
18644   return regnum;
18645 }
18646
18647 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
18648    Given a symbolic attribute NAME, return the proper integer value.
18649    Returns -1 if the attribute is not known.  */
18650
18651 int
18652 mips_convert_symbolic_attribute (const char *name)
18653 {
18654   static const struct
18655   {
18656     const char * name;
18657     const int    tag;
18658   }
18659   attribute_table[] =
18660     {
18661 #define T(tag) {#tag, tag}
18662       T (Tag_GNU_MIPS_ABI_FP),
18663       T (Tag_GNU_MIPS_ABI_MSA),
18664 #undef T
18665     };
18666   unsigned int i;
18667
18668   if (name == NULL)
18669     return -1;
18670
18671   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
18672     if (streq (name, attribute_table[i].name))
18673       return attribute_table[i].tag;
18674
18675   return -1;
18676 }
18677
18678 void
18679 md_mips_end (void)
18680 {
18681   int fpabi = Val_GNU_MIPS_ABI_FP_ANY;
18682
18683   mips_emit_delays ();
18684   if (cur_proc_ptr)
18685     as_warn (_("missing .end at end of assembly"));
18686
18687   /* Just in case no code was emitted, do the consistency check.  */
18688   file_mips_check_options ();
18689
18690   /* Set a floating-point ABI if the user did not.  */
18691   if (obj_elf_seen_attribute (OBJ_ATTR_GNU, Tag_GNU_MIPS_ABI_FP))
18692     {
18693       /* Perform consistency checks on the floating-point ABI.  */
18694       fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
18695                                         Tag_GNU_MIPS_ABI_FP);
18696       if (fpabi != Val_GNU_MIPS_ABI_FP_ANY)
18697         check_fpabi (fpabi);
18698     }
18699   else
18700     {
18701       /* Soft-float gets precedence over single-float, the two options should
18702          not be used together so this should not matter.  */
18703       if (file_mips_opts.soft_float == 1)
18704         fpabi = Val_GNU_MIPS_ABI_FP_SOFT;
18705       /* Single-float gets precedence over all double_float cases.  */
18706       else if (file_mips_opts.single_float == 1)
18707         fpabi = Val_GNU_MIPS_ABI_FP_SINGLE;
18708       else
18709         {
18710           switch (file_mips_opts.fp)
18711             {
18712             case 32:
18713               if (file_mips_opts.gp == 32)
18714                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
18715               break;
18716             case 0:
18717               fpabi = Val_GNU_MIPS_ABI_FP_XX;
18718               break;
18719             case 64:
18720               if (file_mips_opts.gp == 32 && !file_mips_opts.oddspreg)
18721                 fpabi = Val_GNU_MIPS_ABI_FP_64A;
18722               else if (file_mips_opts.gp == 32)
18723                 fpabi = Val_GNU_MIPS_ABI_FP_64;
18724               else
18725                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
18726               break;
18727             }
18728         }
18729
18730       bfd_elf_add_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
18731                                 Tag_GNU_MIPS_ABI_FP, fpabi);
18732     }
18733 }