Implement CONVERT_SYMBOLIC_ATTRIBUTE for MIPS.
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2014 Free Software Foundation, Inc.
3    Contributed by the OSF and Ralph Campbell.
4    Written by Keith Knowles and Ralph Campbell, working independently.
5    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
6    Support.
7
8    This file is part of GAS.
9
10    GAS is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3, or (at your option)
13    any later version.
14
15    GAS is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with GAS; see the file COPYING.  If not, write to the Free
22    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
23    02110-1301, USA.  */
24
25 #include "as.h"
26 #include "config.h"
27 #include "subsegs.h"
28 #include "safe-ctype.h"
29
30 #include "opcode/mips.h"
31 #include "itbl-ops.h"
32 #include "dwarf2dbg.h"
33 #include "dw2gencfi.h"
34
35 /* Check assumptions made in this file.  */
36 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
37 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
38
39 #ifdef DEBUG
40 #define DBG(x) printf x
41 #else
42 #define DBG(x)
43 #endif
44
45 #define 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
93 #define ZERO 0
94 #define ATREG 1
95 #define S0  16
96 #define S7  23
97 #define TREG 24
98 #define PIC_CALL_REG 25
99 #define KT0 26
100 #define KT1 27
101 #define GP  28
102 #define SP  29
103 #define FP  30
104 #define RA  31
105
106 #define ILLEGAL_REG (32)
107
108 #define AT  mips_opts.at
109
110 extern int target_big_endian;
111
112 /* The name of the readonly data section.  */
113 #define RDATA_SECTION_NAME ".rodata"
114
115 /* Ways in which an instruction can be "appended" to the output.  */
116 enum append_method {
117   /* Just add it normally.  */
118   APPEND_ADD,
119
120   /* Add it normally and then add a nop.  */
121   APPEND_ADD_WITH_NOP,
122
123   /* Turn an instruction with a delay slot into a "compact" version.  */
124   APPEND_ADD_COMPACT,
125
126   /* Insert the instruction before the last one.  */
127   APPEND_SWAP
128 };
129
130 /* Information about an instruction, including its format, operands
131    and fixups.  */
132 struct mips_cl_insn
133 {
134   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
135   const struct mips_opcode *insn_mo;
136
137   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
138      a copy of INSN_MO->match with the operands filled in.  If we have
139      decided to use an extended MIPS16 instruction, this includes the
140      extension.  */
141   unsigned long insn_opcode;
142
143   /* The frag that contains the instruction.  */
144   struct frag *frag;
145
146   /* The offset into FRAG of the first instruction byte.  */
147   long where;
148
149   /* The relocs associated with the instruction, if any.  */
150   fixS *fixp[3];
151
152   /* True if this entry cannot be moved from its current position.  */
153   unsigned int fixed_p : 1;
154
155   /* True if this instruction occurred in a .set noreorder block.  */
156   unsigned int noreorder_p : 1;
157
158   /* True for mips16 instructions that jump to an absolute address.  */
159   unsigned int mips16_absolute_jump_p : 1;
160
161   /* True if this instruction is complete.  */
162   unsigned int complete_p : 1;
163
164   /* True if this instruction is cleared from history by unconditional
165      branch.  */
166   unsigned int cleared_p : 1;
167 };
168
169 /* The ABI to use.  */
170 enum mips_abi_level
171 {
172   NO_ABI = 0,
173   O32_ABI,
174   O64_ABI,
175   N32_ABI,
176   N64_ABI,
177   EABI_ABI
178 };
179
180 /* MIPS ABI we are using for this output file.  */
181 static enum mips_abi_level mips_abi = NO_ABI;
182
183 /* Whether or not we have code that can call pic code.  */
184 int mips_abicalls = FALSE;
185
186 /* Whether or not we have code which can be put into a shared
187    library.  */
188 static bfd_boolean mips_in_shared = TRUE;
189
190 /* This is the set of options which may be modified by the .set
191    pseudo-op.  We use a struct so that .set push and .set pop are more
192    reliable.  */
193
194 struct mips_set_options
195 {
196   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
197      if it has not been initialized.  Changed by `.set mipsN', and the
198      -mipsN command line option, and the default CPU.  */
199   int isa;
200   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
201      <asename>', by command line options, and based on the default
202      architecture.  */
203   int ase;
204   /* Whether we are assembling for the mips16 processor.  0 if we are
205      not, 1 if we are, and -1 if the value has not been initialized.
206      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
207      -nomips16 command line options, and the default CPU.  */
208   int mips16;
209   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
210      1 if we are, and -1 if the value has not been initialized.  Changed
211      by `.set micromips' and `.set nomicromips', and the -mmicromips
212      and -mno-micromips command line options, and the default CPU.  */
213   int micromips;
214   /* Non-zero if we should not reorder instructions.  Changed by `.set
215      reorder' and `.set noreorder'.  */
216   int noreorder;
217   /* Non-zero if we should not permit the register designated "assembler
218      temporary" to be used in instructions.  The value is the register
219      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
220      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
221   unsigned int at;
222   /* Non-zero if we should warn when a macro instruction expands into
223      more than one machine instruction.  Changed by `.set nomacro' and
224      `.set macro'.  */
225   int warn_about_macros;
226   /* Non-zero if we should not move instructions.  Changed by `.set
227      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
228   int nomove;
229   /* Non-zero if we should not optimize branches by moving the target
230      of the branch into the delay slot.  Actually, we don't perform
231      this optimization anyhow.  Changed by `.set bopt' and `.set
232      nobopt'.  */
233   int nobopt;
234   /* Non-zero if we should not autoextend mips16 instructions.
235      Changed by `.set autoextend' and `.set noautoextend'.  */
236   int noautoextend;
237   /* True if we should only emit 32-bit microMIPS instructions.
238      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
239      and -mno-insn32 command line options.  */
240   bfd_boolean insn32;
241   /* Restrict general purpose registers and floating point registers
242      to 32 bit.  This is initially determined when -mgp32 or -mfp32
243      is passed but can changed if the assembler code uses .set mipsN.  */
244   int gp32;
245   int fp32;
246   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
247      command line option, and the default CPU.  */
248   int arch;
249   /* True if ".set sym32" is in effect.  */
250   bfd_boolean sym32;
251   /* True if floating-point operations are not allowed.  Changed by .set
252      softfloat or .set hardfloat, by command line options -msoft-float or
253      -mhard-float.  The default is false.  */
254   bfd_boolean soft_float;
255
256   /* True if only single-precision floating-point operations are allowed.
257      Changed by .set singlefloat or .set doublefloat, command-line options
258      -msingle-float or -mdouble-float.  The default is false.  */
259   bfd_boolean single_float;
260 };
261
262 /* This is the struct we use to hold the current set of options.  Note
263    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
264    -1 to indicate that they have not been initialized.  */
265
266 /* True if -mgp32 was passed.  */
267 static int file_mips_gp32 = -1;
268
269 /* True if -mfp32 was passed.  */
270 static int file_mips_fp32 = -1;
271
272 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
273 static int file_mips_soft_float = 0;
274
275 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
276 static int file_mips_single_float = 0;
277
278 /* True if -mnan=2008, false if -mnan=legacy.  */
279 static bfd_boolean mips_flag_nan2008 = FALSE;
280
281 static struct mips_set_options mips_opts =
282 {
283   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
284   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
285   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
286   /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
287   /* soft_float */ FALSE, /* single_float */ FALSE
288 };
289
290 /* The set of ASEs that were selected on the command line, either
291    explicitly via ASE options or implicitly through things like -march.  */
292 static unsigned int file_ase;
293
294 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
295 static unsigned int file_ase_explicit;
296
297 /* These variables are filled in with the masks of registers used.
298    The object format code reads them and puts them in the appropriate
299    place.  */
300 unsigned long mips_gprmask;
301 unsigned long mips_cprmask[4];
302
303 /* MIPS ISA we are using for this output file.  */
304 static int file_mips_isa = ISA_UNKNOWN;
305
306 /* True if any MIPS16 code was produced.  */
307 static int file_ase_mips16;
308
309 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
310                               || mips_opts.isa == ISA_MIPS32R2          \
311                               || mips_opts.isa == ISA_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 int file_mips_arch = CPU_UNKNOWN;
335 static const char *mips_arch_string;
336
337 /* The argument of the -mtune= flag.  The architecture for which we
338    are optimizing.  */
339 static int mips_tune = CPU_UNKNOWN;
340 static const char *mips_tune_string;
341
342 /* True when generating 32-bit code for a 64-bit processor.  */
343 static int mips_32bitmode = 0;
344
345 /* True if the given ABI requires 32-bit registers.  */
346 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
347
348 /* Likewise 64-bit registers.  */
349 #define ABI_NEEDS_64BIT_REGS(ABI)       \
350   ((ABI) == N32_ABI                     \
351    || (ABI) == N64_ABI                  \
352    || (ABI) == O64_ABI)
353
354 /*  Return true if ISA supports 64 bit wide gp registers.  */
355 #define ISA_HAS_64BIT_REGS(ISA)         \
356   ((ISA) == ISA_MIPS3                   \
357    || (ISA) == ISA_MIPS4                \
358    || (ISA) == ISA_MIPS5                \
359    || (ISA) == ISA_MIPS64               \
360    || (ISA) == ISA_MIPS64R2             \
361    || (ISA) == ISA_MIPS64R3             \
362    || (ISA) == ISA_MIPS64R5)
363
364 /*  Return true if ISA supports 64 bit wide float registers.  */
365 #define ISA_HAS_64BIT_FPRS(ISA)         \
366   ((ISA) == ISA_MIPS3                   \
367    || (ISA) == ISA_MIPS4                \
368    || (ISA) == ISA_MIPS5                \
369    || (ISA) == ISA_MIPS32R2             \
370    || (ISA) == ISA_MIPS32R3             \
371    || (ISA) == ISA_MIPS32R5             \
372    || (ISA) == ISA_MIPS64               \
373    || (ISA) == ISA_MIPS64R2             \
374    || (ISA) == ISA_MIPS64R3             \
375    || (ISA) == ISA_MIPS64R5             )
376
377 /* Return true if ISA supports 64-bit right rotate (dror et al.)
378    instructions.  */
379 #define ISA_HAS_DROR(ISA)               \
380   ((ISA) == ISA_MIPS64R2                \
381    || (ISA) == ISA_MIPS64R3             \
382    || (ISA) == ISA_MIPS64R5             \
383    || (mips_opts.micromips              \
384        && ISA_HAS_64BIT_REGS (ISA))     \
385    )
386
387 /* Return true if ISA supports 32-bit right rotate (ror et al.)
388    instructions.  */
389 #define ISA_HAS_ROR(ISA)                \
390   ((ISA) == ISA_MIPS32R2                \
391    || (ISA) == ISA_MIPS32R3             \
392    || (ISA) == ISA_MIPS32R5             \
393    || (ISA) == ISA_MIPS64R2             \
394    || (ISA) == ISA_MIPS64R3             \
395    || (ISA) == ISA_MIPS64R5             \
396    || (mips_opts.ase & ASE_SMARTMIPS)   \
397    || mips_opts.micromips               \
398    )
399
400 /* Return true if ISA supports single-precision floats in odd registers.  */
401 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
402   ((ISA) == ISA_MIPS32                  \
403    || (ISA) == ISA_MIPS32R2             \
404    || (ISA) == ISA_MIPS32R3             \
405    || (ISA) == ISA_MIPS32R5             \
406    || (ISA) == ISA_MIPS64               \
407    || (ISA) == ISA_MIPS64R2             \
408    || (ISA) == ISA_MIPS64R3             \
409    || (ISA) == ISA_MIPS64R5)
410
411 /* Return true if ISA supports move to/from high part of a 64-bit
412    floating-point register. */
413 #define ISA_HAS_MXHC1(ISA)              \
414   ((ISA) == ISA_MIPS32R2                \
415    || (ISA) == ISA_MIPS32R3             \
416    || (ISA) == ISA_MIPS32R5             \
417    || (ISA) == ISA_MIPS64R2             \
418    || (ISA) == ISA_MIPS64R3             \
419    || (ISA) == ISA_MIPS64R5)
420
421 #define HAVE_32BIT_GPRS                            \
422     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
423
424 #define HAVE_32BIT_FPRS                            \
425     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
426
427 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
428 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
429
430 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
431
432 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
433
434 /* True if relocations are stored in-place.  */
435 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
436
437 /* The ABI-derived address size.  */
438 #define HAVE_64BIT_ADDRESSES \
439   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
440 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
441
442 /* The size of symbolic constants (i.e., expressions of the form
443    "SYMBOL" or "SYMBOL + OFFSET").  */
444 #define HAVE_32BIT_SYMBOLS \
445   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
446 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
447
448 /* Addresses are loaded in different ways, depending on the address size
449    in use.  The n32 ABI Documentation also mandates the use of additions
450    with overflow checking, but existing implementations don't follow it.  */
451 #define ADDRESS_ADD_INSN                                                \
452    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
453
454 #define ADDRESS_ADDI_INSN                                               \
455    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
456
457 #define ADDRESS_LOAD_INSN                                               \
458    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
459
460 #define ADDRESS_STORE_INSN                                              \
461    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
462
463 /* Return true if the given CPU supports the MIPS16 ASE.  */
464 #define CPU_HAS_MIPS16(cpu)                                             \
465    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
466     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
467
468 /* Return true if the given CPU supports the microMIPS ASE.  */
469 #define CPU_HAS_MICROMIPS(cpu)  0
470
471 /* True if CPU has a dror instruction.  */
472 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
473
474 /* True if CPU has a ror instruction.  */
475 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
476
477 /* True if CPU is in the Octeon family */
478 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
479
480 /* True if CPU has seq/sne and seqi/snei instructions.  */
481 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
482
483 /* True, if CPU has support for ldc1 and sdc1. */
484 #define CPU_HAS_LDC1_SDC1(CPU)  \
485    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
486
487 /* True if mflo and mfhi can be immediately followed by instructions
488    which write to the HI and LO registers.
489
490    According to MIPS specifications, MIPS ISAs I, II, and III need
491    (at least) two instructions between the reads of HI/LO and
492    instructions which write them, and later ISAs do not.  Contradicting
493    the MIPS specifications, some MIPS IV processor user manuals (e.g.
494    the UM for the NEC Vr5000) document needing the instructions between
495    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
496    MIPS64 and later ISAs to have the interlocks, plus any specific
497    earlier-ISA CPUs for which CPU documentation declares that the
498    instructions are really interlocked.  */
499 #define hilo_interlocks \
500   (mips_opts.isa == ISA_MIPS32                        \
501    || mips_opts.isa == ISA_MIPS32R2                   \
502    || mips_opts.isa == ISA_MIPS32R3                   \
503    || mips_opts.isa == ISA_MIPS32R5                   \
504    || mips_opts.isa == ISA_MIPS64                     \
505    || mips_opts.isa == ISA_MIPS64R2                   \
506    || mips_opts.isa == ISA_MIPS64R3                   \
507    || mips_opts.isa == ISA_MIPS64R5                   \
508    || mips_opts.arch == CPU_R4010                     \
509    || mips_opts.arch == CPU_R5900                     \
510    || mips_opts.arch == CPU_R10000                    \
511    || mips_opts.arch == CPU_R12000                    \
512    || mips_opts.arch == CPU_R14000                    \
513    || mips_opts.arch == CPU_R16000                    \
514    || mips_opts.arch == CPU_RM7000                    \
515    || mips_opts.arch == CPU_VR5500                    \
516    || mips_opts.micromips                             \
517    )
518
519 /* Whether the processor uses hardware interlocks to protect reads
520    from the GPRs after they are loaded from memory, and thus does not
521    require nops to be inserted.  This applies to instructions marked
522    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
523    level I and microMIPS mode instructions are always interlocked.  */
524 #define gpr_interlocks                                \
525   (mips_opts.isa != ISA_MIPS1                         \
526    || mips_opts.arch == CPU_R3900                     \
527    || mips_opts.arch == CPU_R5900                     \
528    || mips_opts.micromips                             \
529    )
530
531 /* Whether the processor uses hardware interlocks to avoid delays
532    required by coprocessor instructions, and thus does not require
533    nops to be inserted.  This applies to instructions marked
534    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
535    between instructions marked INSN_WRITE_COND_CODE and ones marked
536    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
537    levels I, II, and III and microMIPS mode instructions are always
538    interlocked.  */
539 /* Itbl support may require additional care here.  */
540 #define cop_interlocks                                \
541   ((mips_opts.isa != ISA_MIPS1                        \
542     && mips_opts.isa != ISA_MIPS2                     \
543     && mips_opts.isa != ISA_MIPS3)                    \
544    || mips_opts.arch == CPU_R4300                     \
545    || mips_opts.micromips                             \
546    )
547
548 /* Whether the processor uses hardware interlocks to protect reads
549    from coprocessor registers after they are loaded from memory, and
550    thus does not require nops to be inserted.  This applies to
551    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
552    requires at MIPS ISA level I and microMIPS mode instructions are
553    always interlocked.  */
554 #define cop_mem_interlocks                            \
555   (mips_opts.isa != ISA_MIPS1                         \
556    || mips_opts.micromips                             \
557    )
558
559 /* Is this a mfhi or mflo instruction?  */
560 #define MF_HILO_INSN(PINFO) \
561   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
562
563 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
564    has been selected.  This implies, in particular, that addresses of text
565    labels have their LSB set.  */
566 #define HAVE_CODE_COMPRESSION                                           \
567   ((mips_opts.mips16 | mips_opts.micromips) != 0)
568
569 /* The minimum and maximum signed values that can be stored in a GPR.  */
570 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
571 #define GPR_SMIN (-GPR_SMAX - 1)
572
573 /* MIPS PIC level.  */
574
575 enum mips_pic_level mips_pic;
576
577 /* 1 if we should generate 32 bit offsets from the $gp register in
578    SVR4_PIC mode.  Currently has no meaning in other modes.  */
579 static int mips_big_got = 0;
580
581 /* 1 if trap instructions should used for overflow rather than break
582    instructions.  */
583 static int mips_trap = 0;
584
585 /* 1 if double width floating point constants should not be constructed
586    by assembling two single width halves into two single width floating
587    point registers which just happen to alias the double width destination
588    register.  On some architectures this aliasing can be disabled by a bit
589    in the status register, and the setting of this bit cannot be determined
590    automatically at assemble time.  */
591 static int mips_disable_float_construction;
592
593 /* Non-zero if any .set noreorder directives were used.  */
594
595 static int mips_any_noreorder;
596
597 /* Non-zero if nops should be inserted when the register referenced in
598    an mfhi/mflo instruction is read in the next two instructions.  */
599 static int mips_7000_hilo_fix;
600
601 /* The size of objects in the small data section.  */
602 static unsigned int g_switch_value = 8;
603 /* Whether the -G option was used.  */
604 static int g_switch_seen = 0;
605
606 #define N_RMASK 0xc4
607 #define N_VFP   0xd4
608
609 /* If we can determine in advance that GP optimization won't be
610    possible, we can skip the relaxation stuff that tries to produce
611    GP-relative references.  This makes delay slot optimization work
612    better.
613
614    This function can only provide a guess, but it seems to work for
615    gcc output.  It needs to guess right for gcc, otherwise gcc
616    will put what it thinks is a GP-relative instruction in a branch
617    delay slot.
618
619    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
620    fixed it for the non-PIC mode.  KR 95/04/07  */
621 static int nopic_need_relax (symbolS *, int);
622
623 /* handle of the OPCODE hash table */
624 static struct hash_control *op_hash = NULL;
625
626 /* The opcode hash table we use for the mips16.  */
627 static struct hash_control *mips16_op_hash = NULL;
628
629 /* The opcode hash table we use for the microMIPS ASE.  */
630 static struct hash_control *micromips_op_hash = NULL;
631
632 /* This array holds the chars that always start a comment.  If the
633     pre-processor is disabled, these aren't very useful */
634 const char comment_chars[] = "#";
635
636 /* This array holds the chars that only start a comment at the beginning of
637    a line.  If the line seems to have the form '# 123 filename'
638    .line and .file directives will appear in the pre-processed output */
639 /* Note that input_file.c hand checks for '#' at the beginning of the
640    first line of the input file.  This is because the compiler outputs
641    #NO_APP at the beginning of its output.  */
642 /* Also note that C style comments are always supported.  */
643 const char line_comment_chars[] = "#";
644
645 /* This array holds machine specific line separator characters.  */
646 const char line_separator_chars[] = ";";
647
648 /* Chars that can be used to separate mant from exp in floating point nums */
649 const char EXP_CHARS[] = "eE";
650
651 /* Chars that mean this number is a floating point constant */
652 /* As in 0f12.456 */
653 /* or    0d1.2345e12 */
654 const char FLT_CHARS[] = "rRsSfFdDxXpP";
655
656 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
657    changed in read.c .  Ideally it shouldn't have to know about it at all,
658    but nothing is ideal around here.
659  */
660
661 /* Types of printf format used for instruction-related error messages.
662    "I" means int ("%d") and "S" means string ("%s"). */
663 enum mips_insn_error_format {
664   ERR_FMT_PLAIN,
665   ERR_FMT_I,
666   ERR_FMT_SS,
667 };
668
669 /* Information about an error that was found while assembling the current
670    instruction.  */
671 struct mips_insn_error {
672   /* We sometimes need to match an instruction against more than one
673      opcode table entry.  Errors found during this matching are reported
674      against a particular syntactic argument rather than against the
675      instruction as a whole.  We grade these messages so that errors
676      against argument N have a greater priority than an error against
677      any argument < N, since the former implies that arguments up to N
678      were acceptable and that the opcode entry was therefore a closer match.
679      If several matches report an error against the same argument,
680      we only use that error if it is the same in all cases.
681
682      min_argnum is the minimum argument number for which an error message
683      should be accepted.  It is 0 if MSG is against the instruction as
684      a whole.  */
685   int min_argnum;
686
687   /* The printf()-style message, including its format and arguments.  */
688   enum mips_insn_error_format format;
689   const char *msg;
690   union {
691     int i;
692     const char *ss[2];
693   } u;
694 };
695
696 /* The error that should be reported for the current instruction.  */
697 static struct mips_insn_error insn_error;
698
699 static int auto_align = 1;
700
701 /* When outputting SVR4 PIC code, the assembler needs to know the
702    offset in the stack frame from which to restore the $gp register.
703    This is set by the .cprestore pseudo-op, and saved in this
704    variable.  */
705 static offsetT mips_cprestore_offset = -1;
706
707 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
708    more optimizations, it can use a register value instead of a memory-saved
709    offset and even an other register than $gp as global pointer.  */
710 static offsetT mips_cpreturn_offset = -1;
711 static int mips_cpreturn_register = -1;
712 static int mips_gp_register = GP;
713 static int mips_gprel_offset = 0;
714
715 /* Whether mips_cprestore_offset has been set in the current function
716    (or whether it has already been warned about, if not).  */
717 static int mips_cprestore_valid = 0;
718
719 /* This is the register which holds the stack frame, as set by the
720    .frame pseudo-op.  This is needed to implement .cprestore.  */
721 static int mips_frame_reg = SP;
722
723 /* Whether mips_frame_reg has been set in the current function
724    (or whether it has already been warned about, if not).  */
725 static int mips_frame_reg_valid = 0;
726
727 /* To output NOP instructions correctly, we need to keep information
728    about the previous two instructions.  */
729
730 /* Whether we are optimizing.  The default value of 2 means to remove
731    unneeded NOPs and swap branch instructions when possible.  A value
732    of 1 means to not swap branches.  A value of 0 means to always
733    insert NOPs.  */
734 static int mips_optimize = 2;
735
736 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
737    equivalent to seeing no -g option at all.  */
738 static int mips_debug = 0;
739
740 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
741 #define MAX_VR4130_NOPS 4
742
743 /* The maximum number of NOPs needed to fill delay slots.  */
744 #define MAX_DELAY_NOPS 2
745
746 /* The maximum number of NOPs needed for any purpose.  */
747 #define MAX_NOPS 4
748
749 /* A list of previous instructions, with index 0 being the most recent.
750    We need to look back MAX_NOPS instructions when filling delay slots
751    or working around processor errata.  We need to look back one
752    instruction further if we're thinking about using history[0] to
753    fill a branch delay slot.  */
754 static struct mips_cl_insn history[1 + MAX_NOPS];
755
756 /* Arrays of operands for each instruction.  */
757 #define MAX_OPERANDS 6
758 struct mips_operand_array {
759   const struct mips_operand *operand[MAX_OPERANDS];
760 };
761 static struct mips_operand_array *mips_operands;
762 static struct mips_operand_array *mips16_operands;
763 static struct mips_operand_array *micromips_operands;
764
765 /* Nop instructions used by emit_nop.  */
766 static struct mips_cl_insn nop_insn;
767 static struct mips_cl_insn mips16_nop_insn;
768 static struct mips_cl_insn micromips_nop16_insn;
769 static struct mips_cl_insn micromips_nop32_insn;
770
771 /* The appropriate nop for the current mode.  */
772 #define NOP_INSN (mips_opts.mips16                                      \
773                   ? &mips16_nop_insn                                    \
774                   : (mips_opts.micromips                                \
775                      ? (mips_opts.insn32                                \
776                         ? &micromips_nop32_insn                         \
777                         : &micromips_nop16_insn)                        \
778                      : &nop_insn))
779
780 /* The size of NOP_INSN in bytes.  */
781 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
782                         || (mips_opts.micromips && !mips_opts.insn32))  \
783                        ? 2 : 4)
784
785 /* If this is set, it points to a frag holding nop instructions which
786    were inserted before the start of a noreorder section.  If those
787    nops turn out to be unnecessary, the size of the frag can be
788    decreased.  */
789 static fragS *prev_nop_frag;
790
791 /* The number of nop instructions we created in prev_nop_frag.  */
792 static int prev_nop_frag_holds;
793
794 /* The number of nop instructions that we know we need in
795    prev_nop_frag.  */
796 static int prev_nop_frag_required;
797
798 /* The number of instructions we've seen since prev_nop_frag.  */
799 static int prev_nop_frag_since;
800
801 /* Relocations against symbols are sometimes done in two parts, with a HI
802    relocation and a LO relocation.  Each relocation has only 16 bits of
803    space to store an addend.  This means that in order for the linker to
804    handle carries correctly, it must be able to locate both the HI and
805    the LO relocation.  This means that the relocations must appear in
806    order in the relocation table.
807
808    In order to implement this, we keep track of each unmatched HI
809    relocation.  We then sort them so that they immediately precede the
810    corresponding LO relocation.  */
811
812 struct mips_hi_fixup
813 {
814   /* Next HI fixup.  */
815   struct mips_hi_fixup *next;
816   /* This fixup.  */
817   fixS *fixp;
818   /* The section this fixup is in.  */
819   segT seg;
820 };
821
822 /* The list of unmatched HI relocs.  */
823
824 static struct mips_hi_fixup *mips_hi_fixup_list;
825
826 /* The frag containing the last explicit relocation operator.
827    Null if explicit relocations have not been used.  */
828
829 static fragS *prev_reloc_op_frag;
830
831 /* Map mips16 register numbers to normal MIPS register numbers.  */
832
833 static const unsigned int mips16_to_32_reg_map[] =
834 {
835   16, 17, 2, 3, 4, 5, 6, 7
836 };
837
838 /* Map microMIPS register numbers to normal MIPS register numbers.  */
839
840 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
841
842 /* The microMIPS registers with type h.  */
843 static const unsigned int micromips_to_32_reg_h_map1[] =
844 {
845   5, 5, 6, 4, 4, 4, 4, 4
846 };
847 static const unsigned int micromips_to_32_reg_h_map2[] =
848 {
849   6, 7, 7, 21, 22, 5, 6, 7
850 };
851
852 /* The microMIPS registers with type m.  */
853 static const unsigned int micromips_to_32_reg_m_map[] =
854 {
855   0, 17, 2, 3, 16, 18, 19, 20
856 };
857
858 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
859
860 /* Classifies the kind of instructions we're interested in when
861    implementing -mfix-vr4120.  */
862 enum fix_vr4120_class
863 {
864   FIX_VR4120_MACC,
865   FIX_VR4120_DMACC,
866   FIX_VR4120_MULT,
867   FIX_VR4120_DMULT,
868   FIX_VR4120_DIV,
869   FIX_VR4120_MTHILO,
870   NUM_FIX_VR4120_CLASSES
871 };
872
873 /* ...likewise -mfix-loongson2f-jump.  */
874 static bfd_boolean mips_fix_loongson2f_jump;
875
876 /* ...likewise -mfix-loongson2f-nop.  */
877 static bfd_boolean mips_fix_loongson2f_nop;
878
879 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
880 static bfd_boolean mips_fix_loongson2f;
881
882 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
883    there must be at least one other instruction between an instruction
884    of type X and an instruction of type Y.  */
885 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
886
887 /* True if -mfix-vr4120 is in force.  */
888 static int mips_fix_vr4120;
889
890 /* ...likewise -mfix-vr4130.  */
891 static int mips_fix_vr4130;
892
893 /* ...likewise -mfix-24k.  */
894 static int mips_fix_24k;
895
896 /* ...likewise -mfix-rm7000  */
897 static int mips_fix_rm7000;
898
899 /* ...likewise -mfix-cn63xxp1 */
900 static bfd_boolean mips_fix_cn63xxp1;
901
902 /* We don't relax branches by default, since this causes us to expand
903    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
904    fail to compute the offset before expanding the macro to the most
905    efficient expansion.  */
906
907 static int mips_relax_branch;
908 \f
909 /* The expansion of many macros depends on the type of symbol that
910    they refer to.  For example, when generating position-dependent code,
911    a macro that refers to a symbol may have two different expansions,
912    one which uses GP-relative addresses and one which uses absolute
913    addresses.  When generating SVR4-style PIC, a macro may have
914    different expansions for local and global symbols.
915
916    We handle these situations by generating both sequences and putting
917    them in variant frags.  In position-dependent code, the first sequence
918    will be the GP-relative one and the second sequence will be the
919    absolute one.  In SVR4 PIC, the first sequence will be for global
920    symbols and the second will be for local symbols.
921
922    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
923    SECOND are the lengths of the two sequences in bytes.  These fields
924    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
925    the subtype has the following flags:
926
927    RELAX_USE_SECOND
928         Set if it has been decided that we should use the second
929         sequence instead of the first.
930
931    RELAX_SECOND_LONGER
932         Set in the first variant frag if the macro's second implementation
933         is longer than its first.  This refers to the macro as a whole,
934         not an individual relaxation.
935
936    RELAX_NOMACRO
937         Set in the first variant frag if the macro appeared in a .set nomacro
938         block and if one alternative requires a warning but the other does not.
939
940    RELAX_DELAY_SLOT
941         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
942         delay slot.
943
944    RELAX_DELAY_SLOT_16BIT
945         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
946         16-bit instruction.
947
948    RELAX_DELAY_SLOT_SIZE_FIRST
949         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
950         the macro is of the wrong size for the branch delay slot.
951
952    RELAX_DELAY_SLOT_SIZE_SECOND
953         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
954         the macro is of the wrong size for the branch delay slot.
955
956    The frag's "opcode" points to the first fixup for relaxable code.
957
958    Relaxable macros are generated using a sequence such as:
959
960       relax_start (SYMBOL);
961       ... generate first expansion ...
962       relax_switch ();
963       ... generate second expansion ...
964       relax_end ();
965
966    The code and fixups for the unwanted alternative are discarded
967    by md_convert_frag.  */
968 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
969
970 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
971 #define RELAX_SECOND(X) ((X) & 0xff)
972 #define RELAX_USE_SECOND 0x10000
973 #define RELAX_SECOND_LONGER 0x20000
974 #define RELAX_NOMACRO 0x40000
975 #define RELAX_DELAY_SLOT 0x80000
976 #define RELAX_DELAY_SLOT_16BIT 0x100000
977 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
978 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
979
980 /* Branch without likely bit.  If label is out of range, we turn:
981
982         beq reg1, reg2, label
983         delay slot
984
985    into
986
987         bne reg1, reg2, 0f
988         nop
989         j label
990      0: delay slot
991
992    with the following opcode replacements:
993
994         beq <-> bne
995         blez <-> bgtz
996         bltz <-> bgez
997         bc1f <-> bc1t
998
999         bltzal <-> bgezal  (with jal label instead of j label)
1000
1001    Even though keeping the delay slot instruction in the delay slot of
1002    the branch would be more efficient, it would be very tricky to do
1003    correctly, because we'd have to introduce a variable frag *after*
1004    the delay slot instruction, and expand that instead.  Let's do it
1005    the easy way for now, even if the branch-not-taken case now costs
1006    one additional instruction.  Out-of-range branches are not supposed
1007    to be common, anyway.
1008
1009    Branch likely.  If label is out of range, we turn:
1010
1011         beql reg1, reg2, label
1012         delay slot (annulled if branch not taken)
1013
1014    into
1015
1016         beql reg1, reg2, 1f
1017         nop
1018         beql $0, $0, 2f
1019         nop
1020      1: j[al] label
1021         delay slot (executed only if branch taken)
1022      2:
1023
1024    It would be possible to generate a shorter sequence by losing the
1025    likely bit, generating something like:
1026
1027         bne reg1, reg2, 0f
1028         nop
1029         j[al] label
1030         delay slot (executed only if branch taken)
1031      0:
1032
1033         beql -> bne
1034         bnel -> beq
1035         blezl -> bgtz
1036         bgtzl -> blez
1037         bltzl -> bgez
1038         bgezl -> bltz
1039         bc1fl -> bc1t
1040         bc1tl -> bc1f
1041
1042         bltzall -> bgezal  (with jal label instead of j label)
1043         bgezall -> bltzal  (ditto)
1044
1045
1046    but it's not clear that it would actually improve performance.  */
1047 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1048   ((relax_substateT)                                            \
1049    (0xc0000000                                                  \
1050     | ((at) & 0x1f)                                             \
1051     | ((toofar) ? 0x20 : 0)                                     \
1052     | ((link) ? 0x40 : 0)                                       \
1053     | ((likely) ? 0x80 : 0)                                     \
1054     | ((uncond) ? 0x100 : 0)))
1055 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1056 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1057 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1058 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1059 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1060 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1061
1062 /* For mips16 code, we use an entirely different form of relaxation.
1063    mips16 supports two versions of most instructions which take
1064    immediate values: a small one which takes some small value, and a
1065    larger one which takes a 16 bit value.  Since branches also follow
1066    this pattern, relaxing these values is required.
1067
1068    We can assemble both mips16 and normal MIPS code in a single
1069    object.  Therefore, we need to support this type of relaxation at
1070    the same time that we support the relaxation described above.  We
1071    use the high bit of the subtype field to distinguish these cases.
1072
1073    The information we store for this type of relaxation is the
1074    argument code found in the opcode file for this relocation, whether
1075    the user explicitly requested a small or extended form, and whether
1076    the relocation is in a jump or jal delay slot.  That tells us the
1077    size of the value, and how it should be stored.  We also store
1078    whether the fragment is considered to be extended or not.  We also
1079    store whether this is known to be a branch to a different section,
1080    whether we have tried to relax this frag yet, and whether we have
1081    ever extended a PC relative fragment because of a shift count.  */
1082 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1083   (0x80000000                                                   \
1084    | ((type) & 0xff)                                            \
1085    | ((small) ? 0x100 : 0)                                      \
1086    | ((ext) ? 0x200 : 0)                                        \
1087    | ((dslot) ? 0x400 : 0)                                      \
1088    | ((jal_dslot) ? 0x800 : 0))
1089 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1090 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1091 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1092 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1093 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1094 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1095 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1096 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1097 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1098 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1099 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1100 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1101
1102 /* For microMIPS code, we use relaxation similar to one we use for
1103    MIPS16 code.  Some instructions that take immediate values support
1104    two encodings: a small one which takes some small value, and a
1105    larger one which takes a 16 bit value.  As some branches also follow
1106    this pattern, relaxing these values is required.
1107
1108    We can assemble both microMIPS and normal MIPS code in a single
1109    object.  Therefore, we need to support this type of relaxation at
1110    the same time that we support the relaxation described above.  We
1111    use one of the high bits of the subtype field to distinguish these
1112    cases.
1113
1114    The information we store for this type of relaxation is the argument
1115    code found in the opcode file for this relocation, the register
1116    selected as the assembler temporary, whether the branch is
1117    unconditional, whether it is compact, whether it stores the link
1118    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1119    branches to a sequence of instructions is enabled, and whether the
1120    displacement of a branch is too large to fit as an immediate argument
1121    of a 16-bit and a 32-bit branch, respectively.  */
1122 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1123                                relax32, toofar16, toofar32)     \
1124   (0x40000000                                                   \
1125    | ((type) & 0xff)                                            \
1126    | (((at) & 0x1f) << 8)                                       \
1127    | ((uncond) ? 0x2000 : 0)                                    \
1128    | ((compact) ? 0x4000 : 0)                                   \
1129    | ((link) ? 0x8000 : 0)                                      \
1130    | ((relax32) ? 0x10000 : 0)                                  \
1131    | ((toofar16) ? 0x20000 : 0)                                 \
1132    | ((toofar32) ? 0x40000 : 0))
1133 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1134 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1135 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1136 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1137 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1138 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1139 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1140
1141 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1142 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1143 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1144 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1145 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1146 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1147
1148 /* Sign-extend 16-bit value X.  */
1149 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1150
1151 /* Is the given value a sign-extended 32-bit value?  */
1152 #define IS_SEXT_32BIT_NUM(x)                                            \
1153   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1154    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1155
1156 /* Is the given value a sign-extended 16-bit value?  */
1157 #define IS_SEXT_16BIT_NUM(x)                                            \
1158   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1159    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1160
1161 /* Is the given value a sign-extended 12-bit value?  */
1162 #define IS_SEXT_12BIT_NUM(x)                                            \
1163   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1164
1165 /* Is the given value a sign-extended 9-bit value?  */
1166 #define IS_SEXT_9BIT_NUM(x)                                             \
1167   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1168
1169 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1170 #define IS_ZEXT_32BIT_NUM(x)                                            \
1171   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1172    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1173
1174 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1175    SHIFT places.  */
1176 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1177   (((STRUCT) >> (SHIFT)) & (MASK))
1178
1179 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1180 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1181   (!(MICROMIPS) \
1182    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1183    : EXTRACT_BITS ((INSN).insn_opcode, \
1184                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1185 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1186   EXTRACT_BITS ((INSN).insn_opcode, \
1187                 MIPS16OP_MASK_##FIELD, \
1188                 MIPS16OP_SH_##FIELD)
1189
1190 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1191 #define MIPS16_EXTEND (0xf000U << 16)
1192 \f
1193 /* Whether or not we are emitting a branch-likely macro.  */
1194 static bfd_boolean emit_branch_likely_macro = FALSE;
1195
1196 /* Global variables used when generating relaxable macros.  See the
1197    comment above RELAX_ENCODE for more details about how relaxation
1198    is used.  */
1199 static struct {
1200   /* 0 if we're not emitting a relaxable macro.
1201      1 if we're emitting the first of the two relaxation alternatives.
1202      2 if we're emitting the second alternative.  */
1203   int sequence;
1204
1205   /* The first relaxable fixup in the current frag.  (In other words,
1206      the first fixup that refers to relaxable code.)  */
1207   fixS *first_fixup;
1208
1209   /* sizes[0] says how many bytes of the first alternative are stored in
1210      the current frag.  Likewise sizes[1] for the second alternative.  */
1211   unsigned int sizes[2];
1212
1213   /* The symbol on which the choice of sequence depends.  */
1214   symbolS *symbol;
1215 } mips_relax;
1216 \f
1217 /* Global variables used to decide whether a macro needs a warning.  */
1218 static struct {
1219   /* True if the macro is in a branch delay slot.  */
1220   bfd_boolean delay_slot_p;
1221
1222   /* Set to the length in bytes required if the macro is in a delay slot
1223      that requires a specific length of instruction, otherwise zero.  */
1224   unsigned int delay_slot_length;
1225
1226   /* For relaxable macros, sizes[0] is the length of the first alternative
1227      in bytes and sizes[1] is the length of the second alternative.
1228      For non-relaxable macros, both elements give the length of the
1229      macro in bytes.  */
1230   unsigned int sizes[2];
1231
1232   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1233      instruction of the first alternative in bytes and first_insn_sizes[1]
1234      is the length of the first instruction of the second alternative.
1235      For non-relaxable macros, both elements give the length of the first
1236      instruction in bytes.
1237
1238      Set to zero if we haven't yet seen the first instruction.  */
1239   unsigned int first_insn_sizes[2];
1240
1241   /* For relaxable macros, insns[0] is the number of instructions for the
1242      first alternative and insns[1] is the number of instructions for the
1243      second alternative.
1244
1245      For non-relaxable macros, both elements give the number of
1246      instructions for the macro.  */
1247   unsigned int insns[2];
1248
1249   /* The first variant frag for this macro.  */
1250   fragS *first_frag;
1251 } mips_macro_warning;
1252 \f
1253 /* Prototypes for static functions.  */
1254
1255 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1256
1257 static void append_insn
1258   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1259    bfd_boolean expansionp);
1260 static void mips_no_prev_insn (void);
1261 static void macro_build (expressionS *, const char *, const char *, ...);
1262 static void mips16_macro_build
1263   (expressionS *, const char *, const char *, va_list *);
1264 static void load_register (int, expressionS *, int);
1265 static void macro_start (void);
1266 static void macro_end (void);
1267 static void macro (struct mips_cl_insn *ip, char *str);
1268 static void mips16_macro (struct mips_cl_insn * ip);
1269 static void mips_ip (char *str, struct mips_cl_insn * ip);
1270 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1271 static void mips16_immed
1272   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1273    unsigned int, unsigned long *);
1274 static size_t my_getSmallExpression
1275   (expressionS *, bfd_reloc_code_real_type *, char *);
1276 static void my_getExpression (expressionS *, char *);
1277 static void s_align (int);
1278 static void s_change_sec (int);
1279 static void s_change_section (int);
1280 static void s_cons (int);
1281 static void s_float_cons (int);
1282 static void s_mips_globl (int);
1283 static void s_option (int);
1284 static void s_mipsset (int);
1285 static void s_abicalls (int);
1286 static void s_cpload (int);
1287 static void s_cpsetup (int);
1288 static void s_cplocal (int);
1289 static void s_cprestore (int);
1290 static void s_cpreturn (int);
1291 static void s_dtprelword (int);
1292 static void s_dtpreldword (int);
1293 static void s_tprelword (int);
1294 static void s_tpreldword (int);
1295 static void s_gpvalue (int);
1296 static void s_gpword (int);
1297 static void s_gpdword (int);
1298 static void s_ehword (int);
1299 static void s_cpadd (int);
1300 static void s_insn (int);
1301 static void s_nan (int);
1302 static void md_obj_begin (void);
1303 static void md_obj_end (void);
1304 static void s_mips_ent (int);
1305 static void s_mips_end (int);
1306 static void s_mips_frame (int);
1307 static void s_mips_mask (int reg_type);
1308 static void s_mips_stab (int);
1309 static void s_mips_weakext (int);
1310 static void s_mips_file (int);
1311 static void s_mips_loc (int);
1312 static bfd_boolean pic_need_relax (symbolS *, asection *);
1313 static int relaxed_branch_length (fragS *, asection *, int);
1314 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1315 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1316
1317 /* Table and functions used to map between CPU/ISA names, and
1318    ISA levels, and CPU numbers.  */
1319
1320 struct mips_cpu_info
1321 {
1322   const char *name;           /* CPU or ISA name.  */
1323   int flags;                  /* MIPS_CPU_* flags.  */
1324   int ase;                    /* Set of ASEs implemented by the CPU.  */
1325   int isa;                    /* ISA level.  */
1326   int cpu;                    /* CPU number (default CPU if ISA).  */
1327 };
1328
1329 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1330
1331 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1332 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1333 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1334 \f
1335 /* Command-line options.  */
1336 const char *md_shortopts = "O::g::G:";
1337
1338 enum options
1339   {
1340     OPTION_MARCH = OPTION_MD_BASE,
1341     OPTION_MTUNE,
1342     OPTION_MIPS1,
1343     OPTION_MIPS2,
1344     OPTION_MIPS3,
1345     OPTION_MIPS4,
1346     OPTION_MIPS5,
1347     OPTION_MIPS32,
1348     OPTION_MIPS64,
1349     OPTION_MIPS32R2,
1350     OPTION_MIPS32R3,
1351     OPTION_MIPS32R5,
1352     OPTION_MIPS64R2,
1353     OPTION_MIPS64R3,
1354     OPTION_MIPS64R5,
1355     OPTION_MIPS16,
1356     OPTION_NO_MIPS16,
1357     OPTION_MIPS3D,
1358     OPTION_NO_MIPS3D,
1359     OPTION_MDMX,
1360     OPTION_NO_MDMX,
1361     OPTION_DSP,
1362     OPTION_NO_DSP,
1363     OPTION_MT,
1364     OPTION_NO_MT,
1365     OPTION_VIRT,
1366     OPTION_NO_VIRT,
1367     OPTION_MSA,
1368     OPTION_NO_MSA,
1369     OPTION_SMARTMIPS,
1370     OPTION_NO_SMARTMIPS,
1371     OPTION_DSPR2,
1372     OPTION_NO_DSPR2,
1373     OPTION_EVA,
1374     OPTION_NO_EVA,
1375     OPTION_XPA,
1376     OPTION_NO_XPA,
1377     OPTION_MICROMIPS,
1378     OPTION_NO_MICROMIPS,
1379     OPTION_MCU,
1380     OPTION_NO_MCU,
1381     OPTION_COMPAT_ARCH_BASE,
1382     OPTION_M4650,
1383     OPTION_NO_M4650,
1384     OPTION_M4010,
1385     OPTION_NO_M4010,
1386     OPTION_M4100,
1387     OPTION_NO_M4100,
1388     OPTION_M3900,
1389     OPTION_NO_M3900,
1390     OPTION_M7000_HILO_FIX,
1391     OPTION_MNO_7000_HILO_FIX,
1392     OPTION_FIX_24K,
1393     OPTION_NO_FIX_24K,
1394     OPTION_FIX_RM7000,
1395     OPTION_NO_FIX_RM7000,
1396     OPTION_FIX_LOONGSON2F_JUMP,
1397     OPTION_NO_FIX_LOONGSON2F_JUMP,
1398     OPTION_FIX_LOONGSON2F_NOP,
1399     OPTION_NO_FIX_LOONGSON2F_NOP,
1400     OPTION_FIX_VR4120,
1401     OPTION_NO_FIX_VR4120,
1402     OPTION_FIX_VR4130,
1403     OPTION_NO_FIX_VR4130,
1404     OPTION_FIX_CN63XXP1,
1405     OPTION_NO_FIX_CN63XXP1,
1406     OPTION_TRAP,
1407     OPTION_BREAK,
1408     OPTION_EB,
1409     OPTION_EL,
1410     OPTION_FP32,
1411     OPTION_GP32,
1412     OPTION_CONSTRUCT_FLOATS,
1413     OPTION_NO_CONSTRUCT_FLOATS,
1414     OPTION_FP64,
1415     OPTION_GP64,
1416     OPTION_RELAX_BRANCH,
1417     OPTION_NO_RELAX_BRANCH,
1418     OPTION_INSN32,
1419     OPTION_NO_INSN32,
1420     OPTION_MSHARED,
1421     OPTION_MNO_SHARED,
1422     OPTION_MSYM32,
1423     OPTION_MNO_SYM32,
1424     OPTION_SOFT_FLOAT,
1425     OPTION_HARD_FLOAT,
1426     OPTION_SINGLE_FLOAT,
1427     OPTION_DOUBLE_FLOAT,
1428     OPTION_32,
1429     OPTION_CALL_SHARED,
1430     OPTION_CALL_NONPIC,
1431     OPTION_NON_SHARED,
1432     OPTION_XGOT,
1433     OPTION_MABI,
1434     OPTION_N32,
1435     OPTION_64,
1436     OPTION_MDEBUG,
1437     OPTION_NO_MDEBUG,
1438     OPTION_PDR,
1439     OPTION_NO_PDR,
1440     OPTION_MVXWORKS_PIC,
1441     OPTION_NAN,
1442     OPTION_END_OF_ENUM
1443   };
1444
1445 struct option md_longopts[] =
1446 {
1447   /* Options which specify architecture.  */
1448   {"march", required_argument, NULL, OPTION_MARCH},
1449   {"mtune", required_argument, NULL, OPTION_MTUNE},
1450   {"mips0", no_argument, NULL, OPTION_MIPS1},
1451   {"mips1", no_argument, NULL, OPTION_MIPS1},
1452   {"mips2", no_argument, NULL, OPTION_MIPS2},
1453   {"mips3", no_argument, NULL, OPTION_MIPS3},
1454   {"mips4", no_argument, NULL, OPTION_MIPS4},
1455   {"mips5", no_argument, NULL, OPTION_MIPS5},
1456   {"mips32", no_argument, NULL, OPTION_MIPS32},
1457   {"mips64", no_argument, NULL, OPTION_MIPS64},
1458   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1459   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1460   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1461   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1462   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1463   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1464
1465   /* Options which specify Application Specific Extensions (ASEs).  */
1466   {"mips16", no_argument, NULL, OPTION_MIPS16},
1467   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1468   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1469   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1470   {"mdmx", no_argument, NULL, OPTION_MDMX},
1471   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1472   {"mdsp", no_argument, NULL, OPTION_DSP},
1473   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1474   {"mmt", no_argument, NULL, OPTION_MT},
1475   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1476   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1477   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1478   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1479   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1480   {"meva", no_argument, NULL, OPTION_EVA},
1481   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1482   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1483   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1484   {"mmcu", no_argument, NULL, OPTION_MCU},
1485   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1486   {"mvirt", no_argument, NULL, OPTION_VIRT},
1487   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1488   {"mmsa", no_argument, NULL, OPTION_MSA},
1489   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1490   {"mxpa", no_argument, NULL, OPTION_XPA},
1491   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1492
1493   /* Old-style architecture options.  Don't add more of these.  */
1494   {"m4650", no_argument, NULL, OPTION_M4650},
1495   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1496   {"m4010", no_argument, NULL, OPTION_M4010},
1497   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1498   {"m4100", no_argument, NULL, OPTION_M4100},
1499   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1500   {"m3900", no_argument, NULL, OPTION_M3900},
1501   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1502
1503   /* Options which enable bug fixes.  */
1504   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1505   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1506   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1507   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1508   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1509   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1510   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1511   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1512   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1513   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1514   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1515   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1516   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1517   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1518   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1519   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1520   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1521
1522   /* Miscellaneous options.  */
1523   {"trap", no_argument, NULL, OPTION_TRAP},
1524   {"no-break", no_argument, NULL, OPTION_TRAP},
1525   {"break", no_argument, NULL, OPTION_BREAK},
1526   {"no-trap", no_argument, NULL, OPTION_BREAK},
1527   {"EB", no_argument, NULL, OPTION_EB},
1528   {"EL", no_argument, NULL, OPTION_EL},
1529   {"mfp32", no_argument, NULL, OPTION_FP32},
1530   {"mgp32", no_argument, NULL, OPTION_GP32},
1531   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1532   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1533   {"mfp64", no_argument, NULL, OPTION_FP64},
1534   {"mgp64", no_argument, NULL, OPTION_GP64},
1535   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1536   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1537   {"minsn32", no_argument, NULL, OPTION_INSN32},
1538   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1539   {"mshared", no_argument, NULL, OPTION_MSHARED},
1540   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1541   {"msym32", no_argument, NULL, OPTION_MSYM32},
1542   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1543   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1544   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1545   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1546   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1547
1548   /* Strictly speaking this next option is ELF specific,
1549      but we allow it for other ports as well in order to
1550      make testing easier.  */
1551   {"32", no_argument, NULL, OPTION_32},
1552
1553   /* ELF-specific options.  */
1554   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1555   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1556   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1557   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1558   {"xgot", no_argument, NULL, OPTION_XGOT},
1559   {"mabi", required_argument, NULL, OPTION_MABI},
1560   {"n32", no_argument, NULL, OPTION_N32},
1561   {"64", no_argument, NULL, OPTION_64},
1562   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1563   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1564   {"mpdr", no_argument, NULL, OPTION_PDR},
1565   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1566   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1567   {"mnan", required_argument, NULL, OPTION_NAN},
1568
1569   {NULL, no_argument, NULL, 0}
1570 };
1571 size_t md_longopts_size = sizeof (md_longopts);
1572 \f
1573 /* Information about either an Application Specific Extension or an
1574    optional architecture feature that, for simplicity, we treat in the
1575    same way as an ASE.  */
1576 struct mips_ase
1577 {
1578   /* The name of the ASE, used in both the command-line and .set options.  */
1579   const char *name;
1580
1581   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1582      and 64-bit architectures, the flags here refer to the subset that
1583      is available on both.  */
1584   unsigned int flags;
1585
1586   /* The ASE_* flag used for instructions that are available on 64-bit
1587      architectures but that are not included in FLAGS.  */
1588   unsigned int flags64;
1589
1590   /* The command-line options that turn the ASE on and off.  */
1591   int option_on;
1592   int option_off;
1593
1594   /* The minimum required architecture revisions for MIPS32, MIPS64,
1595      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1596   int mips32_rev;
1597   int mips64_rev;
1598   int micromips32_rev;
1599   int micromips64_rev;
1600 };
1601
1602 /* A table of all supported ASEs.  */
1603 static const struct mips_ase mips_ases[] = {
1604   { "dsp", ASE_DSP, ASE_DSP64,
1605     OPTION_DSP, OPTION_NO_DSP,
1606     2, 2, 2, 2 },
1607
1608   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1609     OPTION_DSPR2, OPTION_NO_DSPR2,
1610     2, 2, 2, 2 },
1611
1612   { "eva", ASE_EVA, 0,
1613     OPTION_EVA, OPTION_NO_EVA,
1614     2, 2, 2, 2 },
1615
1616   { "mcu", ASE_MCU, 0,
1617     OPTION_MCU, OPTION_NO_MCU,
1618     2, 2, 2, 2 },
1619
1620   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1621   { "mdmx", ASE_MDMX, 0,
1622     OPTION_MDMX, OPTION_NO_MDMX,
1623     -1, 1, -1, -1 },
1624
1625   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1626   { "mips3d", ASE_MIPS3D, 0,
1627     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1628     2, 1, -1, -1 },
1629
1630   { "mt", ASE_MT, 0,
1631     OPTION_MT, OPTION_NO_MT,
1632     2, 2, -1, -1 },
1633
1634   { "smartmips", ASE_SMARTMIPS, 0,
1635     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1636     1, -1, -1, -1 },
1637
1638   { "virt", ASE_VIRT, ASE_VIRT64,
1639     OPTION_VIRT, OPTION_NO_VIRT,
1640     2, 2, 2, 2 },
1641
1642   { "msa", ASE_MSA, ASE_MSA64,
1643     OPTION_MSA, OPTION_NO_MSA,
1644     2, 2, 2, 2 },
1645
1646   { "xpa", ASE_XPA, 0,
1647     OPTION_XPA, OPTION_NO_XPA,
1648     2, 2, -1, -1 }
1649 };
1650
1651 /* The set of ASEs that require -mfp64.  */
1652 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1653
1654 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1655 static const unsigned int mips_ase_groups[] = {
1656   ASE_DSP | ASE_DSPR2
1657 };
1658 \f
1659 /* Pseudo-op table.
1660
1661    The following pseudo-ops from the Kane and Heinrich MIPS book
1662    should be defined here, but are currently unsupported: .alias,
1663    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1664
1665    The following pseudo-ops from the Kane and Heinrich MIPS book are
1666    specific to the type of debugging information being generated, and
1667    should be defined by the object format: .aent, .begin, .bend,
1668    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1669    .vreg.
1670
1671    The following pseudo-ops from the Kane and Heinrich MIPS book are
1672    not MIPS CPU specific, but are also not specific to the object file
1673    format.  This file is probably the best place to define them, but
1674    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1675
1676 static const pseudo_typeS mips_pseudo_table[] =
1677 {
1678   /* MIPS specific pseudo-ops.  */
1679   {"option", s_option, 0},
1680   {"set", s_mipsset, 0},
1681   {"rdata", s_change_sec, 'r'},
1682   {"sdata", s_change_sec, 's'},
1683   {"livereg", s_ignore, 0},
1684   {"abicalls", s_abicalls, 0},
1685   {"cpload", s_cpload, 0},
1686   {"cpsetup", s_cpsetup, 0},
1687   {"cplocal", s_cplocal, 0},
1688   {"cprestore", s_cprestore, 0},
1689   {"cpreturn", s_cpreturn, 0},
1690   {"dtprelword", s_dtprelword, 0},
1691   {"dtpreldword", s_dtpreldword, 0},
1692   {"tprelword", s_tprelword, 0},
1693   {"tpreldword", s_tpreldword, 0},
1694   {"gpvalue", s_gpvalue, 0},
1695   {"gpword", s_gpword, 0},
1696   {"gpdword", s_gpdword, 0},
1697   {"ehword", s_ehword, 0},
1698   {"cpadd", s_cpadd, 0},
1699   {"insn", s_insn, 0},
1700   {"nan", s_nan, 0},
1701
1702   /* Relatively generic pseudo-ops that happen to be used on MIPS
1703      chips.  */
1704   {"asciiz", stringer, 8 + 1},
1705   {"bss", s_change_sec, 'b'},
1706   {"err", s_err, 0},
1707   {"half", s_cons, 1},
1708   {"dword", s_cons, 3},
1709   {"weakext", s_mips_weakext, 0},
1710   {"origin", s_org, 0},
1711   {"repeat", s_rept, 0},
1712
1713   /* For MIPS this is non-standard, but we define it for consistency.  */
1714   {"sbss", s_change_sec, 'B'},
1715
1716   /* These pseudo-ops are defined in read.c, but must be overridden
1717      here for one reason or another.  */
1718   {"align", s_align, 0},
1719   {"byte", s_cons, 0},
1720   {"data", s_change_sec, 'd'},
1721   {"double", s_float_cons, 'd'},
1722   {"float", s_float_cons, 'f'},
1723   {"globl", s_mips_globl, 0},
1724   {"global", s_mips_globl, 0},
1725   {"hword", s_cons, 1},
1726   {"int", s_cons, 2},
1727   {"long", s_cons, 2},
1728   {"octa", s_cons, 4},
1729   {"quad", s_cons, 3},
1730   {"section", s_change_section, 0},
1731   {"short", s_cons, 1},
1732   {"single", s_float_cons, 'f'},
1733   {"stabd", s_mips_stab, 'd'},
1734   {"stabn", s_mips_stab, 'n'},
1735   {"stabs", s_mips_stab, 's'},
1736   {"text", s_change_sec, 't'},
1737   {"word", s_cons, 2},
1738
1739   { "extern", ecoff_directive_extern, 0},
1740
1741   { NULL, NULL, 0 },
1742 };
1743
1744 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1745 {
1746   /* These pseudo-ops should be defined by the object file format.
1747      However, a.out doesn't support them, so we have versions here.  */
1748   {"aent", s_mips_ent, 1},
1749   {"bgnb", s_ignore, 0},
1750   {"end", s_mips_end, 0},
1751   {"endb", s_ignore, 0},
1752   {"ent", s_mips_ent, 0},
1753   {"file", s_mips_file, 0},
1754   {"fmask", s_mips_mask, 'F'},
1755   {"frame", s_mips_frame, 0},
1756   {"loc", s_mips_loc, 0},
1757   {"mask", s_mips_mask, 'R'},
1758   {"verstamp", s_ignore, 0},
1759   { NULL, NULL, 0 },
1760 };
1761
1762 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1763    purpose of the `.dc.a' internal pseudo-op.  */
1764
1765 int
1766 mips_address_bytes (void)
1767 {
1768   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1769 }
1770
1771 extern void pop_insert (const pseudo_typeS *);
1772
1773 void
1774 mips_pop_insert (void)
1775 {
1776   pop_insert (mips_pseudo_table);
1777   if (! ECOFF_DEBUGGING)
1778     pop_insert (mips_nonecoff_pseudo_table);
1779 }
1780 \f
1781 /* Symbols labelling the current insn.  */
1782
1783 struct insn_label_list
1784 {
1785   struct insn_label_list *next;
1786   symbolS *label;
1787 };
1788
1789 static struct insn_label_list *free_insn_labels;
1790 #define label_list tc_segment_info_data.labels
1791
1792 static void mips_clear_insn_labels (void);
1793 static void mips_mark_labels (void);
1794 static void mips_compressed_mark_labels (void);
1795
1796 static inline void
1797 mips_clear_insn_labels (void)
1798 {
1799   register struct insn_label_list **pl;
1800   segment_info_type *si;
1801
1802   if (now_seg)
1803     {
1804       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1805         ;
1806       
1807       si = seg_info (now_seg);
1808       *pl = si->label_list;
1809       si->label_list = NULL;
1810     }
1811 }
1812
1813 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1814
1815 static inline void
1816 mips_mark_labels (void)
1817 {
1818   if (HAVE_CODE_COMPRESSION)
1819     mips_compressed_mark_labels ();
1820 }
1821 \f
1822 static char *expr_end;
1823
1824 /* An expression in a macro instruction.  This is set by mips_ip and
1825    mips16_ip and when populated is always an O_constant.  */
1826
1827 static expressionS imm_expr;
1828
1829 /* The relocatable field in an instruction and the relocs associated
1830    with it.  These variables are used for instructions like LUI and
1831    JAL as well as true offsets.  They are also used for address
1832    operands in macros.  */
1833
1834 static expressionS offset_expr;
1835 static bfd_reloc_code_real_type offset_reloc[3]
1836   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1837
1838 /* This is set to the resulting size of the instruction to be produced
1839    by mips16_ip if an explicit extension is used or by mips_ip if an
1840    explicit size is supplied.  */
1841
1842 static unsigned int forced_insn_length;
1843
1844 /* True if we are assembling an instruction.  All dot symbols defined during
1845    this time should be treated as code labels.  */
1846
1847 static bfd_boolean mips_assembling_insn;
1848
1849 /* The pdr segment for per procedure frame/regmask info.  Not used for
1850    ECOFF debugging.  */
1851
1852 static segT pdr_seg;
1853
1854 /* The default target format to use.  */
1855
1856 #if defined (TE_FreeBSD)
1857 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1858 #elif defined (TE_TMIPS)
1859 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1860 #else
1861 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1862 #endif
1863
1864 const char *
1865 mips_target_format (void)
1866 {
1867   switch (OUTPUT_FLAVOR)
1868     {
1869     case bfd_target_elf_flavour:
1870 #ifdef TE_VXWORKS
1871       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1872         return (target_big_endian
1873                 ? "elf32-bigmips-vxworks"
1874                 : "elf32-littlemips-vxworks");
1875 #endif
1876       return (target_big_endian
1877               ? (HAVE_64BIT_OBJECTS
1878                  ? ELF_TARGET ("elf64-", "big")
1879                  : (HAVE_NEWABI
1880                     ? ELF_TARGET ("elf32-n", "big")
1881                     : ELF_TARGET ("elf32-", "big")))
1882               : (HAVE_64BIT_OBJECTS
1883                  ? ELF_TARGET ("elf64-", "little")
1884                  : (HAVE_NEWABI
1885                     ? ELF_TARGET ("elf32-n", "little")
1886                     : ELF_TARGET ("elf32-", "little"))));
1887     default:
1888       abort ();
1889       return NULL;
1890     }
1891 }
1892
1893 /* Return the ISA revision that is currently in use, or 0 if we are
1894    generating code for MIPS V or below.  */
1895
1896 static int
1897 mips_isa_rev (void)
1898 {
1899   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1900     return 2;
1901
1902   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
1903     return 3;
1904
1905   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
1906     return 5;
1907
1908   /* microMIPS implies revision 2 or above.  */
1909   if (mips_opts.micromips)
1910     return 2;
1911
1912   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1913     return 1;
1914
1915   return 0;
1916 }
1917
1918 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1919
1920 static unsigned int
1921 mips_ase_mask (unsigned int flags)
1922 {
1923   unsigned int i;
1924
1925   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1926     if (flags & mips_ase_groups[i])
1927       flags |= mips_ase_groups[i];
1928   return flags;
1929 }
1930
1931 /* Check whether the current ISA supports ASE.  Issue a warning if
1932    appropriate.  */
1933
1934 static void
1935 mips_check_isa_supports_ase (const struct mips_ase *ase)
1936 {
1937   const char *base;
1938   int min_rev, size;
1939   static unsigned int warned_isa;
1940   static unsigned int warned_fp32;
1941
1942   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1943     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1944   else
1945     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1946   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1947       && (warned_isa & ase->flags) != ase->flags)
1948     {
1949       warned_isa |= ase->flags;
1950       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1951       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1952       if (min_rev < 0)
1953         as_warn (_("the %d-bit %s architecture does not support the"
1954                    " `%s' extension"), size, base, ase->name);
1955       else
1956         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
1957                  ase->name, base, size, min_rev);
1958     }
1959   if ((ase->flags & FP64_ASES)
1960       && mips_opts.fp32
1961       && (warned_fp32 & ase->flags) != ase->flags)
1962     {
1963       warned_fp32 |= ase->flags;
1964       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
1965     }
1966 }
1967
1968 /* Check all enabled ASEs to see whether they are supported by the
1969    chosen architecture.  */
1970
1971 static void
1972 mips_check_isa_supports_ases (void)
1973 {
1974   unsigned int i, mask;
1975
1976   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1977     {
1978       mask = mips_ase_mask (mips_ases[i].flags);
1979       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1980         mips_check_isa_supports_ase (&mips_ases[i]);
1981     }
1982 }
1983
1984 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1985    that were affected.  */
1986
1987 static unsigned int
1988 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1989 {
1990   unsigned int mask;
1991
1992   mask = mips_ase_mask (ase->flags);
1993   mips_opts.ase &= ~mask;
1994   if (enabled_p)
1995     mips_opts.ase |= ase->flags;
1996   return mask;
1997 }
1998
1999 /* Return the ASE called NAME, or null if none.  */
2000
2001 static const struct mips_ase *
2002 mips_lookup_ase (const char *name)
2003 {
2004   unsigned int i;
2005
2006   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2007     if (strcmp (name, mips_ases[i].name) == 0)
2008       return &mips_ases[i];
2009   return NULL;
2010 }
2011
2012 /* Return the length of a microMIPS instruction in bytes.  If bits of
2013    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
2014    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
2015    major opcode) will require further modifications to the opcode
2016    table.  */
2017
2018 static inline unsigned int
2019 micromips_insn_length (const struct mips_opcode *mo)
2020 {
2021   return (mo->mask >> 16) == 0 ? 2 : 4;
2022 }
2023
2024 /* Return the length of MIPS16 instruction OPCODE.  */
2025
2026 static inline unsigned int
2027 mips16_opcode_length (unsigned long opcode)
2028 {
2029   return (opcode >> 16) == 0 ? 2 : 4;
2030 }
2031
2032 /* Return the length of instruction INSN.  */
2033
2034 static inline unsigned int
2035 insn_length (const struct mips_cl_insn *insn)
2036 {
2037   if (mips_opts.micromips)
2038     return micromips_insn_length (insn->insn_mo);
2039   else if (mips_opts.mips16)
2040     return mips16_opcode_length (insn->insn_opcode);
2041   else
2042     return 4;
2043 }
2044
2045 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2046
2047 static void
2048 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2049 {
2050   size_t i;
2051
2052   insn->insn_mo = mo;
2053   insn->insn_opcode = mo->match;
2054   insn->frag = NULL;
2055   insn->where = 0;
2056   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2057     insn->fixp[i] = NULL;
2058   insn->fixed_p = (mips_opts.noreorder > 0);
2059   insn->noreorder_p = (mips_opts.noreorder > 0);
2060   insn->mips16_absolute_jump_p = 0;
2061   insn->complete_p = 0;
2062   insn->cleared_p = 0;
2063 }
2064
2065 /* Get a list of all the operands in INSN.  */
2066
2067 static const struct mips_operand_array *
2068 insn_operands (const struct mips_cl_insn *insn)
2069 {
2070   if (insn->insn_mo >= &mips_opcodes[0]
2071       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2072     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2073
2074   if (insn->insn_mo >= &mips16_opcodes[0]
2075       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2076     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2077
2078   if (insn->insn_mo >= &micromips_opcodes[0]
2079       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2080     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2081
2082   abort ();
2083 }
2084
2085 /* Get a description of operand OPNO of INSN.  */
2086
2087 static const struct mips_operand *
2088 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2089 {
2090   const struct mips_operand_array *operands;
2091
2092   operands = insn_operands (insn);
2093   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2094     abort ();
2095   return operands->operand[opno];
2096 }
2097
2098 /* Install UVAL as the value of OPERAND in INSN.  */
2099
2100 static inline void
2101 insn_insert_operand (struct mips_cl_insn *insn,
2102                      const struct mips_operand *operand, unsigned int uval)
2103 {
2104   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2105 }
2106
2107 /* Extract the value of OPERAND from INSN.  */
2108
2109 static inline unsigned
2110 insn_extract_operand (const struct mips_cl_insn *insn,
2111                       const struct mips_operand *operand)
2112 {
2113   return mips_extract_operand (operand, insn->insn_opcode);
2114 }
2115
2116 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2117
2118 static void
2119 mips_record_compressed_mode (void)
2120 {
2121   segment_info_type *si;
2122
2123   si = seg_info (now_seg);
2124   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2125     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2126   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2127     si->tc_segment_info_data.micromips = mips_opts.micromips;
2128 }
2129
2130 /* Read a standard MIPS instruction from BUF.  */
2131
2132 static unsigned long
2133 read_insn (char *buf)
2134 {
2135   if (target_big_endian)
2136     return bfd_getb32 ((bfd_byte *) buf);
2137   else
2138     return bfd_getl32 ((bfd_byte *) buf);
2139 }
2140
2141 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2142    the next byte.  */
2143
2144 static char *
2145 write_insn (char *buf, unsigned int insn)
2146 {
2147   md_number_to_chars (buf, insn, 4);
2148   return buf + 4;
2149 }
2150
2151 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2152    has length LENGTH.  */
2153
2154 static unsigned long
2155 read_compressed_insn (char *buf, unsigned int length)
2156 {
2157   unsigned long insn;
2158   unsigned int i;
2159
2160   insn = 0;
2161   for (i = 0; i < length; i += 2)
2162     {
2163       insn <<= 16;
2164       if (target_big_endian)
2165         insn |= bfd_getb16 ((char *) buf);
2166       else
2167         insn |= bfd_getl16 ((char *) buf);
2168       buf += 2;
2169     }
2170   return insn;
2171 }
2172
2173 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2174    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2175
2176 static char *
2177 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2178 {
2179   unsigned int i;
2180
2181   for (i = 0; i < length; i += 2)
2182     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2183   return buf + length;
2184 }
2185
2186 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2187
2188 static void
2189 install_insn (const struct mips_cl_insn *insn)
2190 {
2191   char *f = insn->frag->fr_literal + insn->where;
2192   if (HAVE_CODE_COMPRESSION)
2193     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2194   else
2195     write_insn (f, insn->insn_opcode);
2196   mips_record_compressed_mode ();
2197 }
2198
2199 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2200    and install the opcode in the new location.  */
2201
2202 static void
2203 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2204 {
2205   size_t i;
2206
2207   insn->frag = frag;
2208   insn->where = where;
2209   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2210     if (insn->fixp[i] != NULL)
2211       {
2212         insn->fixp[i]->fx_frag = frag;
2213         insn->fixp[i]->fx_where = where;
2214       }
2215   install_insn (insn);
2216 }
2217
2218 /* Add INSN to the end of the output.  */
2219
2220 static void
2221 add_fixed_insn (struct mips_cl_insn *insn)
2222 {
2223   char *f = frag_more (insn_length (insn));
2224   move_insn (insn, frag_now, f - frag_now->fr_literal);
2225 }
2226
2227 /* Start a variant frag and move INSN to the start of the variant part,
2228    marking it as fixed.  The other arguments are as for frag_var.  */
2229
2230 static void
2231 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2232                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2233 {
2234   frag_grow (max_chars);
2235   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2236   insn->fixed_p = 1;
2237   frag_var (rs_machine_dependent, max_chars, var,
2238             subtype, symbol, offset, NULL);
2239 }
2240
2241 /* Insert N copies of INSN into the history buffer, starting at
2242    position FIRST.  Neither FIRST nor N need to be clipped.  */
2243
2244 static void
2245 insert_into_history (unsigned int first, unsigned int n,
2246                      const struct mips_cl_insn *insn)
2247 {
2248   if (mips_relax.sequence != 2)
2249     {
2250       unsigned int i;
2251
2252       for (i = ARRAY_SIZE (history); i-- > first;)
2253         if (i >= first + n)
2254           history[i] = history[i - n];
2255         else
2256           history[i] = *insn;
2257     }
2258 }
2259
2260 /* Clear the error in insn_error.  */
2261
2262 static void
2263 clear_insn_error (void)
2264 {
2265   memset (&insn_error, 0, sizeof (insn_error));
2266 }
2267
2268 /* Possibly record error message MSG for the current instruction.
2269    If the error is about a particular argument, ARGNUM is the 1-based
2270    number of that argument, otherwise it is 0.  FORMAT is the format
2271    of MSG.  Return true if MSG was used, false if the current message
2272    was kept.  */
2273
2274 static bfd_boolean
2275 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2276                        const char *msg)
2277 {
2278   if (argnum == 0)
2279     {
2280       /* Give priority to errors against specific arguments, and to
2281          the first whole-instruction message.  */
2282       if (insn_error.msg)
2283         return FALSE;
2284     }
2285   else
2286     {
2287       /* Keep insn_error if it is against a later argument.  */
2288       if (argnum < insn_error.min_argnum)
2289         return FALSE;
2290
2291       /* If both errors are against the same argument but are different,
2292          give up on reporting a specific error for this argument.
2293          See the comment about mips_insn_error for details.  */
2294       if (argnum == insn_error.min_argnum
2295           && insn_error.msg
2296           && strcmp (insn_error.msg, msg) != 0)
2297         {
2298           insn_error.msg = 0;
2299           insn_error.min_argnum += 1;
2300           return FALSE;
2301         }
2302     }
2303   insn_error.min_argnum = argnum;
2304   insn_error.format = format;
2305   insn_error.msg = msg;
2306   return TRUE;
2307 }
2308
2309 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2310    as for set_insn_error_format.  */
2311
2312 static void
2313 set_insn_error (int argnum, const char *msg)
2314 {
2315   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2316 }
2317
2318 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2319    as for set_insn_error_format.  */
2320
2321 static void
2322 set_insn_error_i (int argnum, const char *msg, int i)
2323 {
2324   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2325     insn_error.u.i = i;
2326 }
2327
2328 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2329    are as for set_insn_error_format.  */
2330
2331 static void
2332 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2333 {
2334   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2335     {
2336       insn_error.u.ss[0] = s1;
2337       insn_error.u.ss[1] = s2;
2338     }
2339 }
2340
2341 /* Report the error in insn_error, which is against assembly code STR.  */
2342
2343 static void
2344 report_insn_error (const char *str)
2345 {
2346   const char *msg;
2347
2348   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2349   switch (insn_error.format)
2350     {
2351     case ERR_FMT_PLAIN:
2352       as_bad (msg, str);
2353       break;
2354
2355     case ERR_FMT_I:
2356       as_bad (msg, insn_error.u.i, str);
2357       break;
2358
2359     case ERR_FMT_SS:
2360       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2361       break;
2362     }
2363 }
2364
2365 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2366    the idea is to make it obvious at a glance that each errata is
2367    included.  */
2368
2369 static void
2370 init_vr4120_conflicts (void)
2371 {
2372 #define CONFLICT(FIRST, SECOND) \
2373     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2374
2375   /* Errata 21 - [D]DIV[U] after [D]MACC */
2376   CONFLICT (MACC, DIV);
2377   CONFLICT (DMACC, DIV);
2378
2379   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2380   CONFLICT (DMULT, DMULT);
2381   CONFLICT (DMULT, DMACC);
2382   CONFLICT (DMACC, DMULT);
2383   CONFLICT (DMACC, DMACC);
2384
2385   /* Errata 24 - MT{LO,HI} after [D]MACC */
2386   CONFLICT (MACC, MTHILO);
2387   CONFLICT (DMACC, MTHILO);
2388
2389   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2390      instruction is executed immediately after a MACC or DMACC
2391      instruction, the result of [either instruction] is incorrect."  */
2392   CONFLICT (MACC, MULT);
2393   CONFLICT (MACC, DMULT);
2394   CONFLICT (DMACC, MULT);
2395   CONFLICT (DMACC, DMULT);
2396
2397   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2398      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2399      DDIV or DDIVU instruction, the result of the MACC or
2400      DMACC instruction is incorrect.".  */
2401   CONFLICT (DMULT, MACC);
2402   CONFLICT (DMULT, DMACC);
2403   CONFLICT (DIV, MACC);
2404   CONFLICT (DIV, DMACC);
2405
2406 #undef CONFLICT
2407 }
2408
2409 struct regname {
2410   const char *name;
2411   unsigned int num;
2412 };
2413
2414 #define RNUM_MASK       0x00000ff
2415 #define RTYPE_MASK      0x0ffff00
2416 #define RTYPE_NUM       0x0000100
2417 #define RTYPE_FPU       0x0000200
2418 #define RTYPE_FCC       0x0000400
2419 #define RTYPE_VEC       0x0000800
2420 #define RTYPE_GP        0x0001000
2421 #define RTYPE_CP0       0x0002000
2422 #define RTYPE_PC        0x0004000
2423 #define RTYPE_ACC       0x0008000
2424 #define RTYPE_CCC       0x0010000
2425 #define RTYPE_VI        0x0020000
2426 #define RTYPE_VF        0x0040000
2427 #define RTYPE_R5900_I   0x0080000
2428 #define RTYPE_R5900_Q   0x0100000
2429 #define RTYPE_R5900_R   0x0200000
2430 #define RTYPE_R5900_ACC 0x0400000
2431 #define RTYPE_MSA       0x0800000
2432 #define RWARN           0x8000000
2433
2434 #define GENERIC_REGISTER_NUMBERS \
2435     {"$0",      RTYPE_NUM | 0},  \
2436     {"$1",      RTYPE_NUM | 1},  \
2437     {"$2",      RTYPE_NUM | 2},  \
2438     {"$3",      RTYPE_NUM | 3},  \
2439     {"$4",      RTYPE_NUM | 4},  \
2440     {"$5",      RTYPE_NUM | 5},  \
2441     {"$6",      RTYPE_NUM | 6},  \
2442     {"$7",      RTYPE_NUM | 7},  \
2443     {"$8",      RTYPE_NUM | 8},  \
2444     {"$9",      RTYPE_NUM | 9},  \
2445     {"$10",     RTYPE_NUM | 10}, \
2446     {"$11",     RTYPE_NUM | 11}, \
2447     {"$12",     RTYPE_NUM | 12}, \
2448     {"$13",     RTYPE_NUM | 13}, \
2449     {"$14",     RTYPE_NUM | 14}, \
2450     {"$15",     RTYPE_NUM | 15}, \
2451     {"$16",     RTYPE_NUM | 16}, \
2452     {"$17",     RTYPE_NUM | 17}, \
2453     {"$18",     RTYPE_NUM | 18}, \
2454     {"$19",     RTYPE_NUM | 19}, \
2455     {"$20",     RTYPE_NUM | 20}, \
2456     {"$21",     RTYPE_NUM | 21}, \
2457     {"$22",     RTYPE_NUM | 22}, \
2458     {"$23",     RTYPE_NUM | 23}, \
2459     {"$24",     RTYPE_NUM | 24}, \
2460     {"$25",     RTYPE_NUM | 25}, \
2461     {"$26",     RTYPE_NUM | 26}, \
2462     {"$27",     RTYPE_NUM | 27}, \
2463     {"$28",     RTYPE_NUM | 28}, \
2464     {"$29",     RTYPE_NUM | 29}, \
2465     {"$30",     RTYPE_NUM | 30}, \
2466     {"$31",     RTYPE_NUM | 31} 
2467
2468 #define FPU_REGISTER_NAMES       \
2469     {"$f0",     RTYPE_FPU | 0},  \
2470     {"$f1",     RTYPE_FPU | 1},  \
2471     {"$f2",     RTYPE_FPU | 2},  \
2472     {"$f3",     RTYPE_FPU | 3},  \
2473     {"$f4",     RTYPE_FPU | 4},  \
2474     {"$f5",     RTYPE_FPU | 5},  \
2475     {"$f6",     RTYPE_FPU | 6},  \
2476     {"$f7",     RTYPE_FPU | 7},  \
2477     {"$f8",     RTYPE_FPU | 8},  \
2478     {"$f9",     RTYPE_FPU | 9},  \
2479     {"$f10",    RTYPE_FPU | 10}, \
2480     {"$f11",    RTYPE_FPU | 11}, \
2481     {"$f12",    RTYPE_FPU | 12}, \
2482     {"$f13",    RTYPE_FPU | 13}, \
2483     {"$f14",    RTYPE_FPU | 14}, \
2484     {"$f15",    RTYPE_FPU | 15}, \
2485     {"$f16",    RTYPE_FPU | 16}, \
2486     {"$f17",    RTYPE_FPU | 17}, \
2487     {"$f18",    RTYPE_FPU | 18}, \
2488     {"$f19",    RTYPE_FPU | 19}, \
2489     {"$f20",    RTYPE_FPU | 20}, \
2490     {"$f21",    RTYPE_FPU | 21}, \
2491     {"$f22",    RTYPE_FPU | 22}, \
2492     {"$f23",    RTYPE_FPU | 23}, \
2493     {"$f24",    RTYPE_FPU | 24}, \
2494     {"$f25",    RTYPE_FPU | 25}, \
2495     {"$f26",    RTYPE_FPU | 26}, \
2496     {"$f27",    RTYPE_FPU | 27}, \
2497     {"$f28",    RTYPE_FPU | 28}, \
2498     {"$f29",    RTYPE_FPU | 29}, \
2499     {"$f30",    RTYPE_FPU | 30}, \
2500     {"$f31",    RTYPE_FPU | 31}
2501
2502 #define FPU_CONDITION_CODE_NAMES \
2503     {"$fcc0",   RTYPE_FCC | 0},  \
2504     {"$fcc1",   RTYPE_FCC | 1},  \
2505     {"$fcc2",   RTYPE_FCC | 2},  \
2506     {"$fcc3",   RTYPE_FCC | 3},  \
2507     {"$fcc4",   RTYPE_FCC | 4},  \
2508     {"$fcc5",   RTYPE_FCC | 5},  \
2509     {"$fcc6",   RTYPE_FCC | 6},  \
2510     {"$fcc7",   RTYPE_FCC | 7}
2511
2512 #define COPROC_CONDITION_CODE_NAMES         \
2513     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2514     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2515     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2516     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2517     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2518     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2519     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2520     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2521
2522 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2523     {"$a4",     RTYPE_GP | 8},  \
2524     {"$a5",     RTYPE_GP | 9},  \
2525     {"$a6",     RTYPE_GP | 10}, \
2526     {"$a7",     RTYPE_GP | 11}, \
2527     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2528     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2529     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2530     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2531     {"$t0",     RTYPE_GP | 12}, \
2532     {"$t1",     RTYPE_GP | 13}, \
2533     {"$t2",     RTYPE_GP | 14}, \
2534     {"$t3",     RTYPE_GP | 15}
2535
2536 #define O32_SYMBOLIC_REGISTER_NAMES \
2537     {"$t0",     RTYPE_GP | 8},  \
2538     {"$t1",     RTYPE_GP | 9},  \
2539     {"$t2",     RTYPE_GP | 10}, \
2540     {"$t3",     RTYPE_GP | 11}, \
2541     {"$t4",     RTYPE_GP | 12}, \
2542     {"$t5",     RTYPE_GP | 13}, \
2543     {"$t6",     RTYPE_GP | 14}, \
2544     {"$t7",     RTYPE_GP | 15}, \
2545     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2546     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2547     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2548     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2549
2550 /* Remaining symbolic register names */
2551 #define SYMBOLIC_REGISTER_NAMES \
2552     {"$zero",   RTYPE_GP | 0},  \
2553     {"$at",     RTYPE_GP | 1},  \
2554     {"$AT",     RTYPE_GP | 1},  \
2555     {"$v0",     RTYPE_GP | 2},  \
2556     {"$v1",     RTYPE_GP | 3},  \
2557     {"$a0",     RTYPE_GP | 4},  \
2558     {"$a1",     RTYPE_GP | 5},  \
2559     {"$a2",     RTYPE_GP | 6},  \
2560     {"$a3",     RTYPE_GP | 7},  \
2561     {"$s0",     RTYPE_GP | 16}, \
2562     {"$s1",     RTYPE_GP | 17}, \
2563     {"$s2",     RTYPE_GP | 18}, \
2564     {"$s3",     RTYPE_GP | 19}, \
2565     {"$s4",     RTYPE_GP | 20}, \
2566     {"$s5",     RTYPE_GP | 21}, \
2567     {"$s6",     RTYPE_GP | 22}, \
2568     {"$s7",     RTYPE_GP | 23}, \
2569     {"$t8",     RTYPE_GP | 24}, \
2570     {"$t9",     RTYPE_GP | 25}, \
2571     {"$k0",     RTYPE_GP | 26}, \
2572     {"$kt0",    RTYPE_GP | 26}, \
2573     {"$k1",     RTYPE_GP | 27}, \
2574     {"$kt1",    RTYPE_GP | 27}, \
2575     {"$gp",     RTYPE_GP | 28}, \
2576     {"$sp",     RTYPE_GP | 29}, \
2577     {"$s8",     RTYPE_GP | 30}, \
2578     {"$fp",     RTYPE_GP | 30}, \
2579     {"$ra",     RTYPE_GP | 31}
2580
2581 #define MIPS16_SPECIAL_REGISTER_NAMES \
2582     {"$pc",     RTYPE_PC | 0}
2583
2584 #define MDMX_VECTOR_REGISTER_NAMES \
2585     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2586     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2587     {"$v2",     RTYPE_VEC | 2},  \
2588     {"$v3",     RTYPE_VEC | 3},  \
2589     {"$v4",     RTYPE_VEC | 4},  \
2590     {"$v5",     RTYPE_VEC | 5},  \
2591     {"$v6",     RTYPE_VEC | 6},  \
2592     {"$v7",     RTYPE_VEC | 7},  \
2593     {"$v8",     RTYPE_VEC | 8},  \
2594     {"$v9",     RTYPE_VEC | 9},  \
2595     {"$v10",    RTYPE_VEC | 10}, \
2596     {"$v11",    RTYPE_VEC | 11}, \
2597     {"$v12",    RTYPE_VEC | 12}, \
2598     {"$v13",    RTYPE_VEC | 13}, \
2599     {"$v14",    RTYPE_VEC | 14}, \
2600     {"$v15",    RTYPE_VEC | 15}, \
2601     {"$v16",    RTYPE_VEC | 16}, \
2602     {"$v17",    RTYPE_VEC | 17}, \
2603     {"$v18",    RTYPE_VEC | 18}, \
2604     {"$v19",    RTYPE_VEC | 19}, \
2605     {"$v20",    RTYPE_VEC | 20}, \
2606     {"$v21",    RTYPE_VEC | 21}, \
2607     {"$v22",    RTYPE_VEC | 22}, \
2608     {"$v23",    RTYPE_VEC | 23}, \
2609     {"$v24",    RTYPE_VEC | 24}, \
2610     {"$v25",    RTYPE_VEC | 25}, \
2611     {"$v26",    RTYPE_VEC | 26}, \
2612     {"$v27",    RTYPE_VEC | 27}, \
2613     {"$v28",    RTYPE_VEC | 28}, \
2614     {"$v29",    RTYPE_VEC | 29}, \
2615     {"$v30",    RTYPE_VEC | 30}, \
2616     {"$v31",    RTYPE_VEC | 31}
2617
2618 #define R5900_I_NAMES \
2619     {"$I",      RTYPE_R5900_I | 0}
2620
2621 #define R5900_Q_NAMES \
2622     {"$Q",      RTYPE_R5900_Q | 0}
2623
2624 #define R5900_R_NAMES \
2625     {"$R",      RTYPE_R5900_R | 0}
2626
2627 #define R5900_ACC_NAMES \
2628     {"$ACC",    RTYPE_R5900_ACC | 0 }
2629
2630 #define MIPS_DSP_ACCUMULATOR_NAMES \
2631     {"$ac0",    RTYPE_ACC | 0}, \
2632     {"$ac1",    RTYPE_ACC | 1}, \
2633     {"$ac2",    RTYPE_ACC | 2}, \
2634     {"$ac3",    RTYPE_ACC | 3}
2635
2636 static const struct regname reg_names[] = {
2637   GENERIC_REGISTER_NUMBERS,
2638   FPU_REGISTER_NAMES,
2639   FPU_CONDITION_CODE_NAMES,
2640   COPROC_CONDITION_CODE_NAMES,
2641
2642   /* The $txx registers depends on the abi,
2643      these will be added later into the symbol table from
2644      one of the tables below once mips_abi is set after 
2645      parsing of arguments from the command line. */
2646   SYMBOLIC_REGISTER_NAMES,
2647
2648   MIPS16_SPECIAL_REGISTER_NAMES,
2649   MDMX_VECTOR_REGISTER_NAMES,
2650   R5900_I_NAMES,
2651   R5900_Q_NAMES,
2652   R5900_R_NAMES,
2653   R5900_ACC_NAMES,
2654   MIPS_DSP_ACCUMULATOR_NAMES,
2655   {0, 0}
2656 };
2657
2658 static const struct regname reg_names_o32[] = {
2659   O32_SYMBOLIC_REGISTER_NAMES,
2660   {0, 0}
2661 };
2662
2663 static const struct regname reg_names_n32n64[] = {
2664   N32N64_SYMBOLIC_REGISTER_NAMES,
2665   {0, 0}
2666 };
2667
2668 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2669    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2670    of these register symbols, return the associated vector register,
2671    otherwise return SYMVAL itself.  */
2672
2673 static unsigned int
2674 mips_prefer_vec_regno (unsigned int symval)
2675 {
2676   if ((symval & -2) == (RTYPE_GP | 2))
2677     return RTYPE_VEC | (symval & 1);
2678   return symval;
2679 }
2680
2681 /* Return true if string [S, E) is a valid register name, storing its
2682    symbol value in *SYMVAL_PTR if so.  */
2683
2684 static bfd_boolean
2685 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2686 {
2687   char save_c;
2688   symbolS *symbol;
2689
2690   /* Terminate name.  */
2691   save_c = *e;
2692   *e = '\0';
2693
2694   /* Look up the name.  */
2695   symbol = symbol_find (s);
2696   *e = save_c;
2697
2698   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2699     return FALSE;
2700
2701   *symval_ptr = S_GET_VALUE (symbol);
2702   return TRUE;
2703 }
2704
2705 /* Return true if the string at *SPTR is a valid register name.  Allow it
2706    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2707    is nonnull.
2708
2709    When returning true, move *SPTR past the register, store the
2710    register's symbol value in *SYMVAL_PTR and the channel mask in
2711    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2712    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2713    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2714
2715 static bfd_boolean
2716 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2717                      unsigned int *channels_ptr)
2718 {
2719   char *s, *e, *m;
2720   const char *q;
2721   unsigned int channels, symval, bit;
2722
2723   /* Find end of name.  */
2724   s = e = *sptr;
2725   if (is_name_beginner (*e))
2726     ++e;
2727   while (is_part_of_name (*e))
2728     ++e;
2729
2730   channels = 0;
2731   if (!mips_parse_register_1 (s, e, &symval))
2732     {
2733       if (!channels_ptr)
2734         return FALSE;
2735
2736       /* Eat characters from the end of the string that are valid
2737          channel suffixes.  The preceding register must be $ACC or
2738          end with a digit, so there is no ambiguity.  */
2739       bit = 1;
2740       m = e;
2741       for (q = "wzyx"; *q; q++, bit <<= 1)
2742         if (m > s && m[-1] == *q)
2743           {
2744             --m;
2745             channels |= bit;
2746           }
2747
2748       if (channels == 0
2749           || !mips_parse_register_1 (s, m, &symval)
2750           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2751         return FALSE;
2752     }
2753
2754   *sptr = e;
2755   *symval_ptr = symval;
2756   if (channels_ptr)
2757     *channels_ptr = channels;
2758   return TRUE;
2759 }
2760
2761 /* Check if SPTR points at a valid register specifier according to TYPES.
2762    If so, then return 1, advance S to consume the specifier and store
2763    the register's number in REGNOP, otherwise return 0.  */
2764
2765 static int
2766 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2767 {
2768   unsigned int regno;
2769
2770   if (mips_parse_register (s, &regno, NULL))
2771     {
2772       if (types & RTYPE_VEC)
2773         regno = mips_prefer_vec_regno (regno);
2774       if (regno & types)
2775         regno &= RNUM_MASK;
2776       else
2777         regno = ~0;
2778     }
2779   else
2780     {
2781       if (types & RWARN)
2782         as_warn (_("unrecognized register name `%s'"), *s);
2783       regno = ~0;
2784     }
2785   if (regnop)
2786     *regnop = regno;
2787   return regno <= RNUM_MASK;
2788 }
2789
2790 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2791    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2792
2793 static char *
2794 mips_parse_vu0_channels (char *s, unsigned int *channels)
2795 {
2796   unsigned int i;
2797
2798   *channels = 0;
2799   for (i = 0; i < 4; i++)
2800     if (*s == "xyzw"[i])
2801       {
2802         *channels |= 1 << (3 - i);
2803         ++s;
2804       }
2805   return s;
2806 }
2807
2808 /* Token types for parsed operand lists.  */
2809 enum mips_operand_token_type {
2810   /* A plain register, e.g. $f2.  */
2811   OT_REG,
2812
2813   /* A 4-bit XYZW channel mask.  */
2814   OT_CHANNELS,
2815
2816   /* A constant vector index, e.g. [1].  */
2817   OT_INTEGER_INDEX,
2818
2819   /* A register vector index, e.g. [$2].  */
2820   OT_REG_INDEX,
2821
2822   /* A continuous range of registers, e.g. $s0-$s4.  */
2823   OT_REG_RANGE,
2824
2825   /* A (possibly relocated) expression.  */
2826   OT_INTEGER,
2827
2828   /* A floating-point value.  */
2829   OT_FLOAT,
2830
2831   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2832      before OT_REGs.  */
2833   OT_CHAR,
2834
2835   /* A doubled character, either "--" or "++".  */
2836   OT_DOUBLE_CHAR,
2837
2838   /* The end of the operand list.  */
2839   OT_END
2840 };
2841
2842 /* A parsed operand token.  */
2843 struct mips_operand_token
2844 {
2845   /* The type of token.  */
2846   enum mips_operand_token_type type;
2847   union
2848   {
2849     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2850     unsigned int regno;
2851
2852     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2853     unsigned int channels;
2854
2855     /* The integer value of an OT_INTEGER_INDEX.  */
2856     addressT index;
2857
2858     /* The two register symbol values involved in an OT_REG_RANGE.  */
2859     struct {
2860       unsigned int regno1;
2861       unsigned int regno2;
2862     } reg_range;
2863
2864     /* The value of an OT_INTEGER.  The value is represented as an
2865        expression and the relocation operators that were applied to
2866        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2867        relocation operators were used.  */
2868     struct {
2869       expressionS value;
2870       bfd_reloc_code_real_type relocs[3];
2871     } integer;
2872
2873     /* The binary data for an OT_FLOAT constant, and the number of bytes
2874        in the constant.  */
2875     struct {
2876       unsigned char data[8];
2877       int length;
2878     } flt;
2879
2880     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2881     char ch;
2882   } u;
2883 };
2884
2885 /* An obstack used to construct lists of mips_operand_tokens.  */
2886 static struct obstack mips_operand_tokens;
2887
2888 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2889
2890 static void
2891 mips_add_token (struct mips_operand_token *token,
2892                 enum mips_operand_token_type type)
2893 {
2894   token->type = type;
2895   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2896 }
2897
2898 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2899    and OT_REG tokens for them if so, and return a pointer to the first
2900    unconsumed character.  Return null otherwise.  */
2901
2902 static char *
2903 mips_parse_base_start (char *s)
2904 {
2905   struct mips_operand_token token;
2906   unsigned int regno, channels;
2907   bfd_boolean decrement_p;
2908
2909   if (*s != '(')
2910     return 0;
2911
2912   ++s;
2913   SKIP_SPACE_TABS (s);
2914
2915   /* Only match "--" as part of a base expression.  In other contexts "--X"
2916      is a double negative.  */
2917   decrement_p = (s[0] == '-' && s[1] == '-');
2918   if (decrement_p)
2919     {
2920       s += 2;
2921       SKIP_SPACE_TABS (s);
2922     }
2923
2924   /* Allow a channel specifier because that leads to better error messages
2925      than treating something like "$vf0x++" as an expression.  */
2926   if (!mips_parse_register (&s, &regno, &channels))
2927     return 0;
2928
2929   token.u.ch = '(';
2930   mips_add_token (&token, OT_CHAR);
2931
2932   if (decrement_p)
2933     {
2934       token.u.ch = '-';
2935       mips_add_token (&token, OT_DOUBLE_CHAR);
2936     }
2937
2938   token.u.regno = regno;
2939   mips_add_token (&token, OT_REG);
2940
2941   if (channels)
2942     {
2943       token.u.channels = channels;
2944       mips_add_token (&token, OT_CHANNELS);
2945     }
2946
2947   /* For consistency, only match "++" as part of base expressions too.  */
2948   SKIP_SPACE_TABS (s);
2949   if (s[0] == '+' && s[1] == '+')
2950     {
2951       s += 2;
2952       token.u.ch = '+';
2953       mips_add_token (&token, OT_DOUBLE_CHAR);
2954     }
2955
2956   return s;
2957 }
2958
2959 /* Parse one or more tokens from S.  Return a pointer to the first
2960    unconsumed character on success.  Return null if an error was found
2961    and store the error text in insn_error.  FLOAT_FORMAT is as for
2962    mips_parse_arguments.  */
2963
2964 static char *
2965 mips_parse_argument_token (char *s, char float_format)
2966 {
2967   char *end, *save_in, *err;
2968   unsigned int regno1, regno2, channels;
2969   struct mips_operand_token token;
2970
2971   /* First look for "($reg", since we want to treat that as an
2972      OT_CHAR and OT_REG rather than an expression.  */
2973   end = mips_parse_base_start (s);
2974   if (end)
2975     return end;
2976
2977   /* Handle other characters that end up as OT_CHARs.  */
2978   if (*s == ')' || *s == ',')
2979     {
2980       token.u.ch = *s;
2981       mips_add_token (&token, OT_CHAR);
2982       ++s;
2983       return s;
2984     }
2985
2986   /* Handle tokens that start with a register.  */
2987   if (mips_parse_register (&s, &regno1, &channels))
2988     {
2989       if (channels)
2990         {
2991           /* A register and a VU0 channel suffix.  */
2992           token.u.regno = regno1;
2993           mips_add_token (&token, OT_REG);
2994
2995           token.u.channels = channels;
2996           mips_add_token (&token, OT_CHANNELS);
2997           return s;
2998         }
2999
3000       SKIP_SPACE_TABS (s);
3001       if (*s == '-')
3002         {
3003           /* A register range.  */
3004           ++s;
3005           SKIP_SPACE_TABS (s);
3006           if (!mips_parse_register (&s, &regno2, NULL))
3007             {
3008               set_insn_error (0, _("invalid register range"));
3009               return 0;
3010             }
3011
3012           token.u.reg_range.regno1 = regno1;
3013           token.u.reg_range.regno2 = regno2;
3014           mips_add_token (&token, OT_REG_RANGE);
3015           return s;
3016         }
3017
3018       /* Add the register itself.  */
3019       token.u.regno = regno1;
3020       mips_add_token (&token, OT_REG);
3021
3022       /* Check for a vector index.  */
3023       if (*s == '[')
3024         {
3025           ++s;
3026           SKIP_SPACE_TABS (s);
3027           if (mips_parse_register (&s, &token.u.regno, NULL))
3028             mips_add_token (&token, OT_REG_INDEX);
3029           else
3030             {
3031               expressionS element;
3032
3033               my_getExpression (&element, s);
3034               if (element.X_op != O_constant)
3035                 {
3036                   set_insn_error (0, _("vector element must be constant"));
3037                   return 0;
3038                 }
3039               s = expr_end;
3040               token.u.index = element.X_add_number;
3041               mips_add_token (&token, OT_INTEGER_INDEX);
3042             }
3043           SKIP_SPACE_TABS (s);
3044           if (*s != ']')
3045             {
3046               set_insn_error (0, _("missing `]'"));
3047               return 0;
3048             }
3049           ++s;
3050         }
3051       return s;
3052     }
3053
3054   if (float_format)
3055     {
3056       /* First try to treat expressions as floats.  */
3057       save_in = input_line_pointer;
3058       input_line_pointer = s;
3059       err = md_atof (float_format, (char *) token.u.flt.data,
3060                      &token.u.flt.length);
3061       end = input_line_pointer;
3062       input_line_pointer = save_in;
3063       if (err && *err)
3064         {
3065           set_insn_error (0, err);
3066           return 0;
3067         }
3068       if (s != end)
3069         {
3070           mips_add_token (&token, OT_FLOAT);
3071           return end;
3072         }
3073     }
3074
3075   /* Treat everything else as an integer expression.  */
3076   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3077   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3078   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3079   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3080   s = expr_end;
3081   mips_add_token (&token, OT_INTEGER);
3082   return s;
3083 }
3084
3085 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3086    if expressions should be treated as 32-bit floating-point constants,
3087    'd' if they should be treated as 64-bit floating-point constants,
3088    or 0 if they should be treated as integer expressions (the usual case).
3089
3090    Return a list of tokens on success, otherwise return 0.  The caller
3091    must obstack_free the list after use.  */
3092
3093 static struct mips_operand_token *
3094 mips_parse_arguments (char *s, char float_format)
3095 {
3096   struct mips_operand_token token;
3097
3098   SKIP_SPACE_TABS (s);
3099   while (*s)
3100     {
3101       s = mips_parse_argument_token (s, float_format);
3102       if (!s)
3103         {
3104           obstack_free (&mips_operand_tokens,
3105                         obstack_finish (&mips_operand_tokens));
3106           return 0;
3107         }
3108       SKIP_SPACE_TABS (s);
3109     }
3110   mips_add_token (&token, OT_END);
3111   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3112 }
3113
3114 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3115    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3116
3117 static bfd_boolean
3118 is_opcode_valid (const struct mips_opcode *mo)
3119 {
3120   int isa = mips_opts.isa;
3121   int ase = mips_opts.ase;
3122   int fp_s, fp_d;
3123   unsigned int i;
3124
3125   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3126     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3127       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3128         ase |= mips_ases[i].flags64;
3129
3130   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3131     return FALSE;
3132
3133   /* Check whether the instruction or macro requires single-precision or
3134      double-precision floating-point support.  Note that this information is
3135      stored differently in the opcode table for insns and macros.  */
3136   if (mo->pinfo == INSN_MACRO)
3137     {
3138       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3139       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3140     }
3141   else
3142     {
3143       fp_s = mo->pinfo & FP_S;
3144       fp_d = mo->pinfo & FP_D;
3145     }
3146
3147   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3148     return FALSE;
3149
3150   if (fp_s && mips_opts.soft_float)
3151     return FALSE;
3152
3153   return TRUE;
3154 }
3155
3156 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3157    selected ISA and architecture.  */
3158
3159 static bfd_boolean
3160 is_opcode_valid_16 (const struct mips_opcode *mo)
3161 {
3162   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3163 }
3164
3165 /* Return TRUE if the size of the microMIPS opcode MO matches one
3166    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3167
3168 static bfd_boolean
3169 is_size_valid (const struct mips_opcode *mo)
3170 {
3171   if (!mips_opts.micromips)
3172     return TRUE;
3173
3174   if (mips_opts.insn32)
3175     {
3176       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3177         return FALSE;
3178       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3179         return FALSE;
3180     }
3181   if (!forced_insn_length)
3182     return TRUE;
3183   if (mo->pinfo == INSN_MACRO)
3184     return FALSE;
3185   return forced_insn_length == micromips_insn_length (mo);
3186 }
3187
3188 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3189    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3190
3191    We don't accept macros in 16-bit delay slots to avoid a case where
3192    a macro expansion fails because it relies on a preceding 32-bit real
3193    instruction to have matched and does not handle the operands correctly.
3194    The only macros that may expand to 16-bit instructions are JAL that
3195    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3196    and BGT (that likewise cannot be placed in a delay slot) that decay to
3197    a NOP.  In all these cases the macros precede any corresponding real
3198    instruction definitions in the opcode table, so they will match in the
3199    second pass where the size of the delay slot is ignored and therefore
3200    produce correct code.  */
3201
3202 static bfd_boolean
3203 is_delay_slot_valid (const struct mips_opcode *mo)
3204 {
3205   if (!mips_opts.micromips)
3206     return TRUE;
3207
3208   if (mo->pinfo == INSN_MACRO)
3209     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3210   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3211       && micromips_insn_length (mo) != 4)
3212     return FALSE;
3213   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3214       && micromips_insn_length (mo) != 2)
3215     return FALSE;
3216
3217   return TRUE;
3218 }
3219
3220 /* For consistency checking, verify that all bits of OPCODE are specified
3221    either by the match/mask part of the instruction definition, or by the
3222    operand list.  Also build up a list of operands in OPERANDS.
3223
3224    INSN_BITS says which bits of the instruction are significant.
3225    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3226    provides the mips_operand description of each operand.  DECODE_OPERAND
3227    is null for MIPS16 instructions.  */
3228
3229 static int
3230 validate_mips_insn (const struct mips_opcode *opcode,
3231                     unsigned long insn_bits,
3232                     const struct mips_operand *(*decode_operand) (const char *),
3233                     struct mips_operand_array *operands)
3234 {
3235   const char *s;
3236   unsigned long used_bits, doubled, undefined, opno, mask;
3237   const struct mips_operand *operand;
3238
3239   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3240   if ((mask & opcode->match) != opcode->match)
3241     {
3242       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3243               opcode->name, opcode->args);
3244       return 0;
3245     }
3246   used_bits = 0;
3247   opno = 0;
3248   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3249     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3250   for (s = opcode->args; *s; ++s)
3251     switch (*s)
3252       {
3253       case ',':
3254       case '(':
3255       case ')':
3256         break;
3257
3258       case '#':
3259         s++;
3260         break;
3261
3262       default:
3263         if (!decode_operand)
3264           operand = decode_mips16_operand (*s, FALSE);
3265         else
3266           operand = decode_operand (s);
3267         if (!operand && opcode->pinfo != INSN_MACRO)
3268           {
3269             as_bad (_("internal: unknown operand type: %s %s"),
3270                     opcode->name, opcode->args);
3271             return 0;
3272           }
3273         gas_assert (opno < MAX_OPERANDS);
3274         operands->operand[opno] = operand;
3275         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3276           {
3277             used_bits = mips_insert_operand (operand, used_bits, -1);
3278             if (operand->type == OP_MDMX_IMM_REG)
3279               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3280                  has separate entries for each format.  */
3281               used_bits &= ~(1 << (operand->lsb + 5));
3282             if (operand->type == OP_ENTRY_EXIT_LIST)
3283               used_bits &= ~(mask & 0x700);
3284           }
3285         /* Skip prefix characters.  */
3286         if (decode_operand && (*s == '+' || *s == 'm'))
3287           ++s;
3288         opno += 1;
3289         break;
3290       }
3291   doubled = used_bits & mask & insn_bits;
3292   if (doubled)
3293     {
3294       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3295                 " %s %s"), doubled, opcode->name, opcode->args);
3296       return 0;
3297     }
3298   used_bits |= mask;
3299   undefined = ~used_bits & insn_bits;
3300   if (opcode->pinfo != INSN_MACRO && undefined)
3301     {
3302       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3303               undefined, opcode->name, opcode->args);
3304       return 0;
3305     }
3306   used_bits &= ~insn_bits;
3307   if (used_bits)
3308     {
3309       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3310               used_bits, opcode->name, opcode->args);
3311       return 0;
3312     }
3313   return 1;
3314 }
3315
3316 /* The MIPS16 version of validate_mips_insn.  */
3317
3318 static int
3319 validate_mips16_insn (const struct mips_opcode *opcode,
3320                       struct mips_operand_array *operands)
3321 {
3322   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3323     {
3324       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3325          instruction.  Use TMP to describe the full instruction.  */
3326       struct mips_opcode tmp;
3327
3328       tmp = *opcode;
3329       tmp.match <<= 16;
3330       tmp.mask <<= 16;
3331       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3332     }
3333   return validate_mips_insn (opcode, 0xffff, 0, operands);
3334 }
3335
3336 /* The microMIPS version of validate_mips_insn.  */
3337
3338 static int
3339 validate_micromips_insn (const struct mips_opcode *opc,
3340                          struct mips_operand_array *operands)
3341 {
3342   unsigned long insn_bits;
3343   unsigned long major;
3344   unsigned int length;
3345
3346   if (opc->pinfo == INSN_MACRO)
3347     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3348                                operands);
3349
3350   length = micromips_insn_length (opc);
3351   if (length != 2 && length != 4)
3352     {
3353       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3354                 "%s %s"), length, opc->name, opc->args);
3355       return 0;
3356     }
3357   major = opc->match >> (10 + 8 * (length - 2));
3358   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3359       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3360     {
3361       as_bad (_("internal error: bad microMIPS opcode "
3362                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3363       return 0;
3364     }
3365
3366   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3367   insn_bits = 1 << 4 * length;
3368   insn_bits <<= 4 * length;
3369   insn_bits -= 1;
3370   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3371                              operands);
3372 }
3373
3374 /* This function is called once, at assembler startup time.  It should set up
3375    all the tables, etc. that the MD part of the assembler will need.  */
3376
3377 void
3378 md_begin (void)
3379 {
3380   const char *retval = NULL;
3381   int i = 0;
3382   int broken = 0;
3383
3384   if (mips_pic != NO_PIC)
3385     {
3386       if (g_switch_seen && g_switch_value != 0)
3387         as_bad (_("-G may not be used in position-independent code"));
3388       g_switch_value = 0;
3389     }
3390
3391   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
3392     as_warn (_("could not set architecture and machine"));
3393
3394   op_hash = hash_new ();
3395
3396   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3397   for (i = 0; i < NUMOPCODES;)
3398     {
3399       const char *name = mips_opcodes[i].name;
3400
3401       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3402       if (retval != NULL)
3403         {
3404           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3405                    mips_opcodes[i].name, retval);
3406           /* Probably a memory allocation problem?  Give up now.  */
3407           as_fatal (_("broken assembler, no assembly attempted"));
3408         }
3409       do
3410         {
3411           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3412                                    decode_mips_operand, &mips_operands[i]))
3413             broken = 1;
3414           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3415             {
3416               create_insn (&nop_insn, mips_opcodes + i);
3417               if (mips_fix_loongson2f_nop)
3418                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3419               nop_insn.fixed_p = 1;
3420             }
3421           ++i;
3422         }
3423       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3424     }
3425
3426   mips16_op_hash = hash_new ();
3427   mips16_operands = XCNEWVEC (struct mips_operand_array,
3428                               bfd_mips16_num_opcodes);
3429
3430   i = 0;
3431   while (i < bfd_mips16_num_opcodes)
3432     {
3433       const char *name = mips16_opcodes[i].name;
3434
3435       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3436       if (retval != NULL)
3437         as_fatal (_("internal: can't hash `%s': %s"),
3438                   mips16_opcodes[i].name, retval);
3439       do
3440         {
3441           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3442             broken = 1;
3443           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3444             {
3445               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3446               mips16_nop_insn.fixed_p = 1;
3447             }
3448           ++i;
3449         }
3450       while (i < bfd_mips16_num_opcodes
3451              && strcmp (mips16_opcodes[i].name, name) == 0);
3452     }
3453
3454   micromips_op_hash = hash_new ();
3455   micromips_operands = XCNEWVEC (struct mips_operand_array,
3456                                  bfd_micromips_num_opcodes);
3457
3458   i = 0;
3459   while (i < bfd_micromips_num_opcodes)
3460     {
3461       const char *name = micromips_opcodes[i].name;
3462
3463       retval = hash_insert (micromips_op_hash, name,
3464                             (void *) &micromips_opcodes[i]);
3465       if (retval != NULL)
3466         as_fatal (_("internal: can't hash `%s': %s"),
3467                   micromips_opcodes[i].name, retval);
3468       do
3469         {
3470           struct mips_cl_insn *micromips_nop_insn;
3471
3472           if (!validate_micromips_insn (&micromips_opcodes[i],
3473                                         &micromips_operands[i]))
3474             broken = 1;
3475
3476           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3477             {
3478               if (micromips_insn_length (micromips_opcodes + i) == 2)
3479                 micromips_nop_insn = &micromips_nop16_insn;
3480               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3481                 micromips_nop_insn = &micromips_nop32_insn;
3482               else
3483                 continue;
3484
3485               if (micromips_nop_insn->insn_mo == NULL
3486                   && strcmp (name, "nop") == 0)
3487                 {
3488                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3489                   micromips_nop_insn->fixed_p = 1;
3490                 }
3491             }
3492         }
3493       while (++i < bfd_micromips_num_opcodes
3494              && strcmp (micromips_opcodes[i].name, name) == 0);
3495     }
3496
3497   if (broken)
3498     as_fatal (_("broken assembler, no assembly attempted"));
3499
3500   /* We add all the general register names to the symbol table.  This
3501      helps us detect invalid uses of them.  */
3502   for (i = 0; reg_names[i].name; i++) 
3503     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3504                                      reg_names[i].num, /* & RNUM_MASK, */
3505                                      &zero_address_frag));
3506   if (HAVE_NEWABI)
3507     for (i = 0; reg_names_n32n64[i].name; i++) 
3508       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3509                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3510                                        &zero_address_frag));
3511   else
3512     for (i = 0; reg_names_o32[i].name; i++) 
3513       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3514                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3515                                        &zero_address_frag));
3516
3517   for (i = 0; i < 32; i++)
3518     {
3519       char regname[7];
3520
3521       /* R5900 VU0 floating-point register.  */
3522       regname[sizeof (rename) - 1] = 0;
3523       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3524       symbol_table_insert (symbol_new (regname, reg_section,
3525                                        RTYPE_VF | i, &zero_address_frag));
3526
3527       /* R5900 VU0 integer register.  */
3528       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3529       symbol_table_insert (symbol_new (regname, reg_section,
3530                                        RTYPE_VI | i, &zero_address_frag));
3531
3532       /* MSA register.  */
3533       snprintf (regname, sizeof (regname) - 1, "$w%d", i);
3534       symbol_table_insert (symbol_new (regname, reg_section,
3535                                        RTYPE_MSA | i, &zero_address_frag));
3536     }
3537
3538   obstack_init (&mips_operand_tokens);
3539
3540   mips_no_prev_insn ();
3541
3542   mips_gprmask = 0;
3543   mips_cprmask[0] = 0;
3544   mips_cprmask[1] = 0;
3545   mips_cprmask[2] = 0;
3546   mips_cprmask[3] = 0;
3547
3548   /* set the default alignment for the text section (2**2) */
3549   record_alignment (text_section, 2);
3550
3551   bfd_set_gp_size (stdoutput, g_switch_value);
3552
3553   /* On a native system other than VxWorks, sections must be aligned
3554      to 16 byte boundaries.  When configured for an embedded ELF
3555      target, we don't bother.  */
3556   if (strncmp (TARGET_OS, "elf", 3) != 0
3557       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3558     {
3559       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3560       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3561       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3562     }
3563
3564   /* Create a .reginfo section for register masks and a .mdebug
3565      section for debugging information.  */
3566   {
3567     segT seg;
3568     subsegT subseg;
3569     flagword flags;
3570     segT sec;
3571
3572     seg = now_seg;
3573     subseg = now_subseg;
3574
3575     /* The ABI says this section should be loaded so that the
3576        running program can access it.  However, we don't load it
3577        if we are configured for an embedded target */
3578     flags = SEC_READONLY | SEC_DATA;
3579     if (strncmp (TARGET_OS, "elf", 3) != 0)
3580       flags |= SEC_ALLOC | SEC_LOAD;
3581
3582     if (mips_abi != N64_ABI)
3583       {
3584         sec = subseg_new (".reginfo", (subsegT) 0);
3585
3586         bfd_set_section_flags (stdoutput, sec, flags);
3587         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3588
3589         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3590       }
3591     else
3592       {
3593         /* The 64-bit ABI uses a .MIPS.options section rather than
3594            .reginfo section.  */
3595         sec = subseg_new (".MIPS.options", (subsegT) 0);
3596         bfd_set_section_flags (stdoutput, sec, flags);
3597         bfd_set_section_alignment (stdoutput, sec, 3);
3598
3599         /* Set up the option header.  */
3600         {
3601           Elf_Internal_Options opthdr;
3602           char *f;
3603
3604           opthdr.kind = ODK_REGINFO;
3605           opthdr.size = (sizeof (Elf_External_Options)
3606                          + sizeof (Elf64_External_RegInfo));
3607           opthdr.section = 0;
3608           opthdr.info = 0;
3609           f = frag_more (sizeof (Elf_External_Options));
3610           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3611                                          (Elf_External_Options *) f);
3612
3613           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3614         }
3615       }
3616
3617     if (ECOFF_DEBUGGING)
3618       {
3619         sec = subseg_new (".mdebug", (subsegT) 0);
3620         (void) bfd_set_section_flags (stdoutput, sec,
3621                                       SEC_HAS_CONTENTS | SEC_READONLY);
3622         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3623       }
3624     else if (mips_flag_pdr)
3625       {
3626         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3627         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3628                                       SEC_READONLY | SEC_RELOC
3629                                       | SEC_DEBUGGING);
3630         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3631       }
3632
3633     subseg_set (seg, subseg);
3634   }
3635
3636   if (! ECOFF_DEBUGGING)
3637     md_obj_begin ();
3638
3639   if (mips_fix_vr4120)
3640     init_vr4120_conflicts ();
3641 }
3642
3643 void
3644 md_mips_end (void)
3645 {
3646   mips_emit_delays ();
3647   if (! ECOFF_DEBUGGING)
3648     md_obj_end ();
3649 }
3650
3651 void
3652 md_assemble (char *str)
3653 {
3654   struct mips_cl_insn insn;
3655   bfd_reloc_code_real_type unused_reloc[3]
3656     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3657
3658   imm_expr.X_op = O_absent;
3659   offset_expr.X_op = O_absent;
3660   offset_reloc[0] = BFD_RELOC_UNUSED;
3661   offset_reloc[1] = BFD_RELOC_UNUSED;
3662   offset_reloc[2] = BFD_RELOC_UNUSED;
3663
3664   mips_mark_labels ();
3665   mips_assembling_insn = TRUE;
3666   clear_insn_error ();
3667
3668   if (mips_opts.mips16)
3669     mips16_ip (str, &insn);
3670   else
3671     {
3672       mips_ip (str, &insn);
3673       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3674             str, insn.insn_opcode));
3675     }
3676
3677   if (insn_error.msg)
3678     report_insn_error (str);
3679   else if (insn.insn_mo->pinfo == INSN_MACRO)
3680     {
3681       macro_start ();
3682       if (mips_opts.mips16)
3683         mips16_macro (&insn);
3684       else
3685         macro (&insn, str);
3686       macro_end ();
3687     }
3688   else
3689     {
3690       if (offset_expr.X_op != O_absent)
3691         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3692       else
3693         append_insn (&insn, NULL, unused_reloc, FALSE);
3694     }
3695
3696   mips_assembling_insn = FALSE;
3697 }
3698
3699 /* Convenience functions for abstracting away the differences between
3700    MIPS16 and non-MIPS16 relocations.  */
3701
3702 static inline bfd_boolean
3703 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3704 {
3705   switch (reloc)
3706     {
3707     case BFD_RELOC_MIPS16_JMP:
3708     case BFD_RELOC_MIPS16_GPREL:
3709     case BFD_RELOC_MIPS16_GOT16:
3710     case BFD_RELOC_MIPS16_CALL16:
3711     case BFD_RELOC_MIPS16_HI16_S:
3712     case BFD_RELOC_MIPS16_HI16:
3713     case BFD_RELOC_MIPS16_LO16:
3714       return TRUE;
3715
3716     default:
3717       return FALSE;
3718     }
3719 }
3720
3721 static inline bfd_boolean
3722 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3723 {
3724   switch (reloc)
3725     {
3726     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3727     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3728     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3729     case BFD_RELOC_MICROMIPS_GPREL16:
3730     case BFD_RELOC_MICROMIPS_JMP:
3731     case BFD_RELOC_MICROMIPS_HI16:
3732     case BFD_RELOC_MICROMIPS_HI16_S:
3733     case BFD_RELOC_MICROMIPS_LO16:
3734     case BFD_RELOC_MICROMIPS_LITERAL:
3735     case BFD_RELOC_MICROMIPS_GOT16:
3736     case BFD_RELOC_MICROMIPS_CALL16:
3737     case BFD_RELOC_MICROMIPS_GOT_HI16:
3738     case BFD_RELOC_MICROMIPS_GOT_LO16:
3739     case BFD_RELOC_MICROMIPS_CALL_HI16:
3740     case BFD_RELOC_MICROMIPS_CALL_LO16:
3741     case BFD_RELOC_MICROMIPS_SUB:
3742     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3743     case BFD_RELOC_MICROMIPS_GOT_OFST:
3744     case BFD_RELOC_MICROMIPS_GOT_DISP:
3745     case BFD_RELOC_MICROMIPS_HIGHEST:
3746     case BFD_RELOC_MICROMIPS_HIGHER:
3747     case BFD_RELOC_MICROMIPS_SCN_DISP:
3748     case BFD_RELOC_MICROMIPS_JALR:
3749       return TRUE;
3750
3751     default:
3752       return FALSE;
3753     }
3754 }
3755
3756 static inline bfd_boolean
3757 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3758 {
3759   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3760 }
3761
3762 static inline bfd_boolean
3763 got16_reloc_p (bfd_reloc_code_real_type reloc)
3764 {
3765   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3766           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3767 }
3768
3769 static inline bfd_boolean
3770 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3771 {
3772   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3773           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3774 }
3775
3776 static inline bfd_boolean
3777 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3778 {
3779   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3780           || reloc == BFD_RELOC_MICROMIPS_LO16);
3781 }
3782
3783 static inline bfd_boolean
3784 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3785 {
3786   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3787 }
3788
3789 static inline bfd_boolean
3790 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3791 {
3792   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3793           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3794 }
3795
3796 /* Return true if RELOC is a PC-relative relocation that does not have
3797    full address range.  */
3798
3799 static inline bfd_boolean
3800 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3801 {
3802   switch (reloc)
3803     {
3804     case BFD_RELOC_16_PCREL_S2:
3805     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3806     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3807     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3808       return TRUE;
3809
3810     case BFD_RELOC_32_PCREL:
3811       return HAVE_64BIT_ADDRESSES;
3812
3813     default:
3814       return FALSE;
3815     }
3816 }
3817
3818 /* Return true if the given relocation might need a matching %lo().
3819    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3820    need a matching %lo() when applied to local symbols.  */
3821
3822 static inline bfd_boolean
3823 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3824 {
3825   return (HAVE_IN_PLACE_ADDENDS
3826           && (hi16_reloc_p (reloc)
3827               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3828                  all GOT16 relocations evaluate to "G".  */
3829               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3830 }
3831
3832 /* Return the type of %lo() reloc needed by RELOC, given that
3833    reloc_needs_lo_p.  */
3834
3835 static inline bfd_reloc_code_real_type
3836 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3837 {
3838   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3839           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3840              : BFD_RELOC_LO16));
3841 }
3842
3843 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3844    relocation.  */
3845
3846 static inline bfd_boolean
3847 fixup_has_matching_lo_p (fixS *fixp)
3848 {
3849   return (fixp->fx_next != NULL
3850           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3851           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3852           && fixp->fx_offset == fixp->fx_next->fx_offset);
3853 }
3854
3855 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3856    says whether the labels refer to text or data.  */
3857
3858 static void
3859 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3860 {
3861   struct insn_label_list *l;
3862   valueT val;
3863
3864   for (l = labels; l != NULL; l = l->next)
3865     {
3866       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3867       symbol_set_frag (l->label, frag_now);
3868       val = (valueT) frag_now_fix ();
3869       /* MIPS16/microMIPS text labels are stored as odd.  */
3870       if (text_p && HAVE_CODE_COMPRESSION)
3871         ++val;
3872       S_SET_VALUE (l->label, val);
3873     }
3874 }
3875
3876 /* Move all labels in insn_labels to the current insertion point
3877    and treat them as text labels.  */
3878
3879 static void
3880 mips_move_text_labels (void)
3881 {
3882   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3883 }
3884
3885 static bfd_boolean
3886 s_is_linkonce (symbolS *sym, segT from_seg)
3887 {
3888   bfd_boolean linkonce = FALSE;
3889   segT symseg = S_GET_SEGMENT (sym);
3890
3891   if (symseg != from_seg && !S_IS_LOCAL (sym))
3892     {
3893       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3894         linkonce = TRUE;
3895       /* The GNU toolchain uses an extension for ELF: a section
3896          beginning with the magic string .gnu.linkonce is a
3897          linkonce section.  */
3898       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3899                    sizeof ".gnu.linkonce" - 1) == 0)
3900         linkonce = TRUE;
3901     }
3902   return linkonce;
3903 }
3904
3905 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3906    linker to handle them specially, such as generating jalx instructions
3907    when needed.  We also make them odd for the duration of the assembly,
3908    in order to generate the right sort of code.  We will make them even
3909    in the adjust_symtab routine, while leaving them marked.  This is
3910    convenient for the debugger and the disassembler.  The linker knows
3911    to make them odd again.  */
3912
3913 static void
3914 mips_compressed_mark_label (symbolS *label)
3915 {
3916   gas_assert (HAVE_CODE_COMPRESSION);
3917
3918   if (mips_opts.mips16)
3919     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3920   else
3921     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3922   if ((S_GET_VALUE (label) & 1) == 0
3923       /* Don't adjust the address if the label is global or weak, or
3924          in a link-once section, since we'll be emitting symbol reloc
3925          references to it which will be patched up by the linker, and
3926          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3927       && !S_IS_WEAK (label)
3928       && !S_IS_EXTERNAL (label)
3929       && !s_is_linkonce (label, now_seg))
3930     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3931 }
3932
3933 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3934
3935 static void
3936 mips_compressed_mark_labels (void)
3937 {
3938   struct insn_label_list *l;
3939
3940   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3941     mips_compressed_mark_label (l->label);
3942 }
3943
3944 /* End the current frag.  Make it a variant frag and record the
3945    relaxation info.  */
3946
3947 static void
3948 relax_close_frag (void)
3949 {
3950   mips_macro_warning.first_frag = frag_now;
3951   frag_var (rs_machine_dependent, 0, 0,
3952             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3953             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3954
3955   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3956   mips_relax.first_fixup = 0;
3957 }
3958
3959 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3960    See the comment above RELAX_ENCODE for more details.  */
3961
3962 static void
3963 relax_start (symbolS *symbol)
3964 {
3965   gas_assert (mips_relax.sequence == 0);
3966   mips_relax.sequence = 1;
3967   mips_relax.symbol = symbol;
3968 }
3969
3970 /* Start generating the second version of a relaxable sequence.
3971    See the comment above RELAX_ENCODE for more details.  */
3972
3973 static void
3974 relax_switch (void)
3975 {
3976   gas_assert (mips_relax.sequence == 1);
3977   mips_relax.sequence = 2;
3978 }
3979
3980 /* End the current relaxable sequence.  */
3981
3982 static void
3983 relax_end (void)
3984 {
3985   gas_assert (mips_relax.sequence == 2);
3986   relax_close_frag ();
3987   mips_relax.sequence = 0;
3988 }
3989
3990 /* Return true if IP is a delayed branch or jump.  */
3991
3992 static inline bfd_boolean
3993 delayed_branch_p (const struct mips_cl_insn *ip)
3994 {
3995   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3996                                 | INSN_COND_BRANCH_DELAY
3997                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3998 }
3999
4000 /* Return true if IP is a compact branch or jump.  */
4001
4002 static inline bfd_boolean
4003 compact_branch_p (const struct mips_cl_insn *ip)
4004 {
4005   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4006                                  | INSN2_COND_BRANCH)) != 0;
4007 }
4008
4009 /* Return true if IP is an unconditional branch or jump.  */
4010
4011 static inline bfd_boolean
4012 uncond_branch_p (const struct mips_cl_insn *ip)
4013 {
4014   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4015           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4016 }
4017
4018 /* Return true if IP is a branch-likely instruction.  */
4019
4020 static inline bfd_boolean
4021 branch_likely_p (const struct mips_cl_insn *ip)
4022 {
4023   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4024 }
4025
4026 /* Return the type of nop that should be used to fill the delay slot
4027    of delayed branch IP.  */
4028
4029 static struct mips_cl_insn *
4030 get_delay_slot_nop (const struct mips_cl_insn *ip)
4031 {
4032   if (mips_opts.micromips
4033       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4034     return &micromips_nop32_insn;
4035   return NOP_INSN;
4036 }
4037
4038 /* Return a mask that has bit N set if OPCODE reads the register(s)
4039    in operand N.  */
4040
4041 static unsigned int
4042 insn_read_mask (const struct mips_opcode *opcode)
4043 {
4044   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4045 }
4046
4047 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4048    in operand N.  */
4049
4050 static unsigned int
4051 insn_write_mask (const struct mips_opcode *opcode)
4052 {
4053   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4054 }
4055
4056 /* Return a mask of the registers specified by operand OPERAND of INSN.
4057    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4058    is set.  */
4059
4060 static unsigned int
4061 operand_reg_mask (const struct mips_cl_insn *insn,
4062                   const struct mips_operand *operand,
4063                   unsigned int type_mask)
4064 {
4065   unsigned int uval, vsel;
4066
4067   switch (operand->type)
4068     {
4069     case OP_INT:
4070     case OP_MAPPED_INT:
4071     case OP_MSB:
4072     case OP_PCREL:
4073     case OP_PERF_REG:
4074     case OP_ADDIUSP_INT:
4075     case OP_ENTRY_EXIT_LIST:
4076     case OP_REPEAT_DEST_REG:
4077     case OP_REPEAT_PREV_REG:
4078     case OP_PC:
4079     case OP_VU0_SUFFIX:
4080     case OP_VU0_MATCH_SUFFIX:
4081     case OP_IMM_INDEX:
4082       abort ();
4083
4084     case OP_REG:
4085     case OP_OPTIONAL_REG:
4086       {
4087         const struct mips_reg_operand *reg_op;
4088
4089         reg_op = (const struct mips_reg_operand *) operand;
4090         if (!(type_mask & (1 << reg_op->reg_type)))
4091           return 0;
4092         uval = insn_extract_operand (insn, operand);
4093         return 1 << mips_decode_reg_operand (reg_op, uval);
4094       }
4095
4096     case OP_REG_PAIR:
4097       {
4098         const struct mips_reg_pair_operand *pair_op;
4099
4100         pair_op = (const struct mips_reg_pair_operand *) operand;
4101         if (!(type_mask & (1 << pair_op->reg_type)))
4102           return 0;
4103         uval = insn_extract_operand (insn, operand);
4104         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4105       }
4106
4107     case OP_CLO_CLZ_DEST:
4108       if (!(type_mask & (1 << OP_REG_GP)))
4109         return 0;
4110       uval = insn_extract_operand (insn, operand);
4111       return (1 << (uval & 31)) | (1 << (uval >> 5));
4112
4113     case OP_LWM_SWM_LIST:
4114       abort ();
4115
4116     case OP_SAVE_RESTORE_LIST:
4117       abort ();
4118
4119     case OP_MDMX_IMM_REG:
4120       if (!(type_mask & (1 << OP_REG_VEC)))
4121         return 0;
4122       uval = insn_extract_operand (insn, operand);
4123       vsel = uval >> 5;
4124       if ((vsel & 0x18) == 0x18)
4125         return 0;
4126       return 1 << (uval & 31);
4127
4128     case OP_REG_INDEX:
4129       if (!(type_mask & (1 << OP_REG_GP)))
4130         return 0;
4131       return 1 << insn_extract_operand (insn, operand);
4132     }
4133   abort ();
4134 }
4135
4136 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4137    where bit N of OPNO_MASK is set if operand N should be included.
4138    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4139    is set.  */
4140
4141 static unsigned int
4142 insn_reg_mask (const struct mips_cl_insn *insn,
4143                unsigned int type_mask, unsigned int opno_mask)
4144 {
4145   unsigned int opno, reg_mask;
4146
4147   opno = 0;
4148   reg_mask = 0;
4149   while (opno_mask != 0)
4150     {
4151       if (opno_mask & 1)
4152         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4153       opno_mask >>= 1;
4154       opno += 1;
4155     }
4156   return reg_mask;
4157 }
4158
4159 /* Return the mask of core registers that IP reads.  */
4160
4161 static unsigned int
4162 gpr_read_mask (const struct mips_cl_insn *ip)
4163 {
4164   unsigned long pinfo, pinfo2;
4165   unsigned int mask;
4166
4167   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4168   pinfo = ip->insn_mo->pinfo;
4169   pinfo2 = ip->insn_mo->pinfo2;
4170   if (pinfo & INSN_UDI)
4171     {
4172       /* UDI instructions have traditionally been assumed to read RS
4173          and RT.  */
4174       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4175       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4176     }
4177   if (pinfo & INSN_READ_GPR_24)
4178     mask |= 1 << 24;
4179   if (pinfo2 & INSN2_READ_GPR_16)
4180     mask |= 1 << 16;
4181   if (pinfo2 & INSN2_READ_SP)
4182     mask |= 1 << SP;
4183   if (pinfo2 & INSN2_READ_GPR_31)
4184     mask |= 1 << 31;
4185   /* Don't include register 0.  */
4186   return mask & ~1;
4187 }
4188
4189 /* Return the mask of core registers that IP writes.  */
4190
4191 static unsigned int
4192 gpr_write_mask (const struct mips_cl_insn *ip)
4193 {
4194   unsigned long pinfo, pinfo2;
4195   unsigned int mask;
4196
4197   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4198   pinfo = ip->insn_mo->pinfo;
4199   pinfo2 = ip->insn_mo->pinfo2;
4200   if (pinfo & INSN_WRITE_GPR_24)
4201     mask |= 1 << 24;
4202   if (pinfo & INSN_WRITE_GPR_31)
4203     mask |= 1 << 31;
4204   if (pinfo & INSN_UDI)
4205     /* UDI instructions have traditionally been assumed to write to RD.  */
4206     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4207   if (pinfo2 & INSN2_WRITE_SP)
4208     mask |= 1 << SP;
4209   /* Don't include register 0.  */
4210   return mask & ~1;
4211 }
4212
4213 /* Return the mask of floating-point registers that IP reads.  */
4214
4215 static unsigned int
4216 fpr_read_mask (const struct mips_cl_insn *ip)
4217 {
4218   unsigned long pinfo;
4219   unsigned int mask;
4220
4221   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4222                              | (1 << OP_REG_MSA)),
4223                         insn_read_mask (ip->insn_mo));
4224   pinfo = ip->insn_mo->pinfo;
4225   /* Conservatively treat all operands to an FP_D instruction are doubles.
4226      (This is overly pessimistic for things like cvt.d.s.)  */
4227   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4228     mask |= mask << 1;
4229   return mask;
4230 }
4231
4232 /* Return the mask of floating-point registers that IP writes.  */
4233
4234 static unsigned int
4235 fpr_write_mask (const struct mips_cl_insn *ip)
4236 {
4237   unsigned long pinfo;
4238   unsigned int mask;
4239
4240   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4241                              | (1 << OP_REG_MSA)),
4242                         insn_write_mask (ip->insn_mo));
4243   pinfo = ip->insn_mo->pinfo;
4244   /* Conservatively treat all operands to an FP_D instruction are doubles.
4245      (This is overly pessimistic for things like cvt.s.d.)  */
4246   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4247     mask |= mask << 1;
4248   return mask;
4249 }
4250
4251 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4252    Check whether that is allowed.  */
4253
4254 static bfd_boolean
4255 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4256 {
4257   const char *s = insn->name;
4258
4259   if (insn->pinfo == INSN_MACRO)
4260     /* Let a macro pass, we'll catch it later when it is expanded.  */
4261     return TRUE;
4262
4263   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4264     {
4265       /* Allow odd registers for single-precision ops.  */
4266       switch (insn->pinfo & (FP_S | FP_D))
4267         {
4268         case FP_S:
4269         case 0:
4270           return TRUE;
4271         case FP_D:
4272           return FALSE;
4273         default:
4274           break;
4275         }
4276
4277       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4278       s = strchr (insn->name, '.');
4279       if (s != NULL && opnum == 2)
4280         s = strchr (s + 1, '.');
4281       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4282     }
4283
4284   /* Single-precision coprocessor loads and moves are OK too.  */
4285   if ((insn->pinfo & FP_S)
4286       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4287                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4288     return TRUE;
4289
4290   return FALSE;
4291 }
4292
4293 /* Information about an instruction argument that we're trying to match.  */
4294 struct mips_arg_info
4295 {
4296   /* The instruction so far.  */
4297   struct mips_cl_insn *insn;
4298
4299   /* The first unconsumed operand token.  */
4300   struct mips_operand_token *token;
4301
4302   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4303   int opnum;
4304
4305   /* The 1-based argument number, for error reporting.  This does not
4306      count elided optional registers, etc..  */
4307   int argnum;
4308
4309   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4310   unsigned int last_regno;
4311
4312   /* If the first operand was an OP_REG, this is the register that it
4313      specified, otherwise it is ILLEGAL_REG.  */
4314   unsigned int dest_regno;
4315
4316   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4317      where it gives the lsb position.  */
4318   unsigned int last_op_int;
4319
4320   /* If true, match routines should assume that no later instruction
4321      alternative matches and should therefore be as accomodating as
4322      possible.  Match routines should not report errors if something
4323      is only invalid for !LAX_MATCH.  */
4324   bfd_boolean lax_match;
4325
4326   /* True if a reference to the current AT register was seen.  */
4327   bfd_boolean seen_at;
4328 };
4329
4330 /* Record that the argument is out of range.  */
4331
4332 static void
4333 match_out_of_range (struct mips_arg_info *arg)
4334 {
4335   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4336 }
4337
4338 /* Record that the argument isn't constant but needs to be.  */
4339
4340 static void
4341 match_not_constant (struct mips_arg_info *arg)
4342 {
4343   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4344                     arg->argnum);
4345 }
4346
4347 /* Try to match an OT_CHAR token for character CH.  Consume the token
4348    and return true on success, otherwise return false.  */
4349
4350 static bfd_boolean
4351 match_char (struct mips_arg_info *arg, char ch)
4352 {
4353   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4354     {
4355       ++arg->token;
4356       if (ch == ',')
4357         arg->argnum += 1;
4358       return TRUE;
4359     }
4360   return FALSE;
4361 }
4362
4363 /* Try to get an expression from the next tokens in ARG.  Consume the
4364    tokens and return true on success, storing the expression value in
4365    VALUE and relocation types in R.  */
4366
4367 static bfd_boolean
4368 match_expression (struct mips_arg_info *arg, expressionS *value,
4369                   bfd_reloc_code_real_type *r)
4370 {
4371   /* If the next token is a '(' that was parsed as being part of a base
4372      expression, assume we have an elided offset.  The later match will fail
4373      if this turns out to be wrong.  */
4374   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4375     {
4376       value->X_op = O_constant;
4377       value->X_add_number = 0;
4378       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4379       return TRUE;
4380     }
4381
4382   /* Reject register-based expressions such as "0+$2" and "(($2))".
4383      For plain registers the default error seems more appropriate.  */
4384   if (arg->token->type == OT_INTEGER
4385       && arg->token->u.integer.value.X_op == O_register)
4386     {
4387       set_insn_error (arg->argnum, _("register value used as expression"));
4388       return FALSE;
4389     }
4390
4391   if (arg->token->type == OT_INTEGER)
4392     {
4393       *value = arg->token->u.integer.value;
4394       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4395       ++arg->token;
4396       return TRUE;
4397     }
4398
4399   set_insn_error_i
4400     (arg->argnum, _("operand %d must be an immediate expression"),
4401      arg->argnum);
4402   return FALSE;
4403 }
4404
4405 /* Try to get a constant expression from the next tokens in ARG.  Consume
4406    the tokens and return return true on success, storing the constant value
4407    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4408    error.  */
4409
4410 static bfd_boolean
4411 match_const_int (struct mips_arg_info *arg, offsetT *value)
4412 {
4413   expressionS ex;
4414   bfd_reloc_code_real_type r[3];
4415
4416   if (!match_expression (arg, &ex, r))
4417     return FALSE;
4418
4419   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4420     *value = ex.X_add_number;
4421   else
4422     {
4423       match_not_constant (arg);
4424       return FALSE;
4425     }
4426   return TRUE;
4427 }
4428
4429 /* Return the RTYPE_* flags for a register operand of type TYPE that
4430    appears in instruction OPCODE.  */
4431
4432 static unsigned int
4433 convert_reg_type (const struct mips_opcode *opcode,
4434                   enum mips_reg_operand_type type)
4435 {
4436   switch (type)
4437     {
4438     case OP_REG_GP:
4439       return RTYPE_NUM | RTYPE_GP;
4440
4441     case OP_REG_FP:
4442       /* Allow vector register names for MDMX if the instruction is a 64-bit
4443          FPR load, store or move (including moves to and from GPRs).  */
4444       if ((mips_opts.ase & ASE_MDMX)
4445           && (opcode->pinfo & FP_D)
4446           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4447                                | INSN_COPROC_MEMORY_DELAY
4448                                | INSN_LOAD_COPROC_DELAY
4449                                | INSN_LOAD_MEMORY
4450                                | INSN_STORE_MEMORY)))
4451         return RTYPE_FPU | RTYPE_VEC;
4452       return RTYPE_FPU;
4453
4454     case OP_REG_CCC:
4455       if (opcode->pinfo & (FP_D | FP_S))
4456         return RTYPE_CCC | RTYPE_FCC;
4457       return RTYPE_CCC;
4458
4459     case OP_REG_VEC:
4460       if (opcode->membership & INSN_5400)
4461         return RTYPE_FPU;
4462       return RTYPE_FPU | RTYPE_VEC;
4463
4464     case OP_REG_ACC:
4465       return RTYPE_ACC;
4466
4467     case OP_REG_COPRO:
4468       if (opcode->name[strlen (opcode->name) - 1] == '0')
4469         return RTYPE_NUM | RTYPE_CP0;
4470       return RTYPE_NUM;
4471
4472     case OP_REG_HW:
4473       return RTYPE_NUM;
4474
4475     case OP_REG_VI:
4476       return RTYPE_NUM | RTYPE_VI;
4477
4478     case OP_REG_VF:
4479       return RTYPE_NUM | RTYPE_VF;
4480
4481     case OP_REG_R5900_I:
4482       return RTYPE_R5900_I;
4483
4484     case OP_REG_R5900_Q:
4485       return RTYPE_R5900_Q;
4486
4487     case OP_REG_R5900_R:
4488       return RTYPE_R5900_R;
4489
4490     case OP_REG_R5900_ACC:
4491       return RTYPE_R5900_ACC;
4492
4493     case OP_REG_MSA:
4494       return RTYPE_MSA;
4495
4496     case OP_REG_MSA_CTRL:
4497       return RTYPE_NUM;
4498     }
4499   abort ();
4500 }
4501
4502 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4503
4504 static void
4505 check_regno (struct mips_arg_info *arg,
4506              enum mips_reg_operand_type type, unsigned int regno)
4507 {
4508   if (AT && type == OP_REG_GP && regno == AT)
4509     arg->seen_at = TRUE;
4510
4511   if (type == OP_REG_FP
4512       && (regno & 1) != 0
4513       && HAVE_32BIT_FPRS
4514       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4515     as_warn (_("float register should be even, was %d"), regno);
4516
4517   if (type == OP_REG_CCC)
4518     {
4519       const char *name;
4520       size_t length;
4521
4522       name = arg->insn->insn_mo->name;
4523       length = strlen (name);
4524       if ((regno & 1) != 0
4525           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4526               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4527         as_warn (_("condition code register should be even for %s, was %d"),
4528                  name, regno);
4529
4530       if ((regno & 3) != 0
4531           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4532         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4533                  name, regno);
4534     }
4535 }
4536
4537 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4538    a register of type TYPE.  Return true on success, storing the register
4539    number in *REGNO and warning about any dubious uses.  */
4540
4541 static bfd_boolean
4542 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4543              unsigned int symval, unsigned int *regno)
4544 {
4545   if (type == OP_REG_VEC)
4546     symval = mips_prefer_vec_regno (symval);
4547   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4548     return FALSE;
4549
4550   *regno = symval & RNUM_MASK;
4551   check_regno (arg, type, *regno);
4552   return TRUE;
4553 }
4554
4555 /* Try to interpret the next token in ARG as a register of type TYPE.
4556    Consume the token and return true on success, storing the register
4557    number in *REGNO.  Return false on failure.  */
4558
4559 static bfd_boolean
4560 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4561            unsigned int *regno)
4562 {
4563   if (arg->token->type == OT_REG
4564       && match_regno (arg, type, arg->token->u.regno, regno))
4565     {
4566       ++arg->token;
4567       return TRUE;
4568     }
4569   return FALSE;
4570 }
4571
4572 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4573    Consume the token and return true on success, storing the register numbers
4574    in *REGNO1 and *REGNO2.  Return false on failure.  */
4575
4576 static bfd_boolean
4577 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4578                  unsigned int *regno1, unsigned int *regno2)
4579 {
4580   if (match_reg (arg, type, regno1))
4581     {
4582       *regno2 = *regno1;
4583       return TRUE;
4584     }
4585   if (arg->token->type == OT_REG_RANGE
4586       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4587       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4588       && *regno1 <= *regno2)
4589     {
4590       ++arg->token;
4591       return TRUE;
4592     }
4593   return FALSE;
4594 }
4595
4596 /* OP_INT matcher.  */
4597
4598 static bfd_boolean
4599 match_int_operand (struct mips_arg_info *arg,
4600                    const struct mips_operand *operand_base)
4601 {
4602   const struct mips_int_operand *operand;
4603   unsigned int uval;
4604   int min_val, max_val, factor;
4605   offsetT sval;
4606
4607   operand = (const struct mips_int_operand *) operand_base;
4608   factor = 1 << operand->shift;
4609   min_val = mips_int_operand_min (operand);
4610   max_val = mips_int_operand_max (operand);
4611
4612   if (operand_base->lsb == 0
4613       && operand_base->size == 16
4614       && operand->shift == 0
4615       && operand->bias == 0
4616       && (operand->max_val == 32767 || operand->max_val == 65535))
4617     {
4618       /* The operand can be relocated.  */
4619       if (!match_expression (arg, &offset_expr, offset_reloc))
4620         return FALSE;
4621
4622       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4623         /* Relocation operators were used.  Accept the arguent and
4624            leave the relocation value in offset_expr and offset_relocs
4625            for the caller to process.  */
4626         return TRUE;
4627
4628       if (offset_expr.X_op != O_constant)
4629         {
4630           /* Accept non-constant operands if no later alternative matches,
4631              leaving it for the caller to process.  */
4632           if (!arg->lax_match)
4633             return FALSE;
4634           offset_reloc[0] = BFD_RELOC_LO16;
4635           return TRUE;
4636         }
4637
4638       /* Clear the global state; we're going to install the operand
4639          ourselves.  */
4640       sval = offset_expr.X_add_number;
4641       offset_expr.X_op = O_absent;
4642
4643       /* For compatibility with older assemblers, we accept
4644          0x8000-0xffff as signed 16-bit numbers when only
4645          signed numbers are allowed.  */
4646       if (sval > max_val)
4647         {
4648           max_val = ((1 << operand_base->size) - 1) << operand->shift;
4649           if (!arg->lax_match && sval <= max_val)
4650             return FALSE;
4651         }
4652     }
4653   else
4654     {
4655       if (!match_const_int (arg, &sval))
4656         return FALSE;
4657     }
4658
4659   arg->last_op_int = sval;
4660
4661   if (sval < min_val || sval > max_val || sval % factor)
4662     {
4663       match_out_of_range (arg);
4664       return FALSE;
4665     }
4666
4667   uval = (unsigned int) sval >> operand->shift;
4668   uval -= operand->bias;
4669
4670   /* Handle -mfix-cn63xxp1.  */
4671   if (arg->opnum == 1
4672       && mips_fix_cn63xxp1
4673       && !mips_opts.micromips
4674       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4675     switch (uval)
4676       {
4677       case 5:
4678       case 25:
4679       case 26:
4680       case 27:
4681       case 28:
4682       case 29:
4683       case 30:
4684       case 31:
4685         /* These are ok.  */
4686         break;
4687
4688       default:
4689         /* The rest must be changed to 28.  */
4690         uval = 28;
4691         break;
4692       }
4693
4694   insn_insert_operand (arg->insn, operand_base, uval);
4695   return TRUE;
4696 }
4697
4698 /* OP_MAPPED_INT matcher.  */
4699
4700 static bfd_boolean
4701 match_mapped_int_operand (struct mips_arg_info *arg,
4702                           const struct mips_operand *operand_base)
4703 {
4704   const struct mips_mapped_int_operand *operand;
4705   unsigned int uval, num_vals;
4706   offsetT sval;
4707
4708   operand = (const struct mips_mapped_int_operand *) operand_base;
4709   if (!match_const_int (arg, &sval))
4710     return FALSE;
4711
4712   num_vals = 1 << operand_base->size;
4713   for (uval = 0; uval < num_vals; uval++)
4714     if (operand->int_map[uval] == sval)
4715       break;
4716   if (uval == num_vals)
4717     {
4718       match_out_of_range (arg);
4719       return FALSE;
4720     }
4721
4722   insn_insert_operand (arg->insn, operand_base, uval);
4723   return TRUE;
4724 }
4725
4726 /* OP_MSB matcher.  */
4727
4728 static bfd_boolean
4729 match_msb_operand (struct mips_arg_info *arg,
4730                    const struct mips_operand *operand_base)
4731 {
4732   const struct mips_msb_operand *operand;
4733   int min_val, max_val, max_high;
4734   offsetT size, sval, high;
4735
4736   operand = (const struct mips_msb_operand *) operand_base;
4737   min_val = operand->bias;
4738   max_val = min_val + (1 << operand_base->size) - 1;
4739   max_high = operand->opsize;
4740
4741   if (!match_const_int (arg, &size))
4742     return FALSE;
4743
4744   high = size + arg->last_op_int;
4745   sval = operand->add_lsb ? high : size;
4746
4747   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4748     {
4749       match_out_of_range (arg);
4750       return FALSE;
4751     }
4752   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4753   return TRUE;
4754 }
4755
4756 /* OP_REG matcher.  */
4757
4758 static bfd_boolean
4759 match_reg_operand (struct mips_arg_info *arg,
4760                    const struct mips_operand *operand_base)
4761 {
4762   const struct mips_reg_operand *operand;
4763   unsigned int regno, uval, num_vals;
4764
4765   operand = (const struct mips_reg_operand *) operand_base;
4766   if (!match_reg (arg, operand->reg_type, &regno))
4767     return FALSE;
4768
4769   if (operand->reg_map)
4770     {
4771       num_vals = 1 << operand->root.size;
4772       for (uval = 0; uval < num_vals; uval++)
4773         if (operand->reg_map[uval] == regno)
4774           break;
4775       if (num_vals == uval)
4776         return FALSE;
4777     }
4778   else
4779     uval = regno;
4780
4781   arg->last_regno = regno;
4782   if (arg->opnum == 1)
4783     arg->dest_regno = regno;
4784   insn_insert_operand (arg->insn, operand_base, uval);
4785   return TRUE;
4786 }
4787
4788 /* OP_REG_PAIR matcher.  */
4789
4790 static bfd_boolean
4791 match_reg_pair_operand (struct mips_arg_info *arg,
4792                         const struct mips_operand *operand_base)
4793 {
4794   const struct mips_reg_pair_operand *operand;
4795   unsigned int regno1, regno2, uval, num_vals;
4796
4797   operand = (const struct mips_reg_pair_operand *) operand_base;
4798   if (!match_reg (arg, operand->reg_type, &regno1)
4799       || !match_char (arg, ',')
4800       || !match_reg (arg, operand->reg_type, &regno2))
4801     return FALSE;
4802
4803   num_vals = 1 << operand_base->size;
4804   for (uval = 0; uval < num_vals; uval++)
4805     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4806       break;
4807   if (uval == num_vals)
4808     return FALSE;
4809
4810   insn_insert_operand (arg->insn, operand_base, uval);
4811   return TRUE;
4812 }
4813
4814 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4815
4816 static bfd_boolean
4817 match_pcrel_operand (struct mips_arg_info *arg)
4818 {
4819   bfd_reloc_code_real_type r[3];
4820
4821   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4822 }
4823
4824 /* OP_PERF_REG matcher.  */
4825
4826 static bfd_boolean
4827 match_perf_reg_operand (struct mips_arg_info *arg,
4828                         const struct mips_operand *operand)
4829 {
4830   offsetT sval;
4831
4832   if (!match_const_int (arg, &sval))
4833     return FALSE;
4834
4835   if (sval != 0
4836       && (sval != 1
4837           || (mips_opts.arch == CPU_R5900
4838               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4839                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4840     {
4841       set_insn_error (arg->argnum, _("invalid performance register"));
4842       return FALSE;
4843     }
4844
4845   insn_insert_operand (arg->insn, operand, sval);
4846   return TRUE;
4847 }
4848
4849 /* OP_ADDIUSP matcher.  */
4850
4851 static bfd_boolean
4852 match_addiusp_operand (struct mips_arg_info *arg,
4853                        const struct mips_operand *operand)
4854 {
4855   offsetT sval;
4856   unsigned int uval;
4857
4858   if (!match_const_int (arg, &sval))
4859     return FALSE;
4860
4861   if (sval % 4)
4862     {
4863       match_out_of_range (arg);
4864       return FALSE;
4865     }
4866
4867   sval /= 4;
4868   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4869     {
4870       match_out_of_range (arg);
4871       return FALSE;
4872     }
4873
4874   uval = (unsigned int) sval;
4875   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4876   insn_insert_operand (arg->insn, operand, uval);
4877   return TRUE;
4878 }
4879
4880 /* OP_CLO_CLZ_DEST matcher.  */
4881
4882 static bfd_boolean
4883 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4884                             const struct mips_operand *operand)
4885 {
4886   unsigned int regno;
4887
4888   if (!match_reg (arg, OP_REG_GP, &regno))
4889     return FALSE;
4890
4891   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4892   return TRUE;
4893 }
4894
4895 /* OP_LWM_SWM_LIST matcher.  */
4896
4897 static bfd_boolean
4898 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4899                             const struct mips_operand *operand)
4900 {
4901   unsigned int reglist, sregs, ra, regno1, regno2;
4902   struct mips_arg_info reset;
4903
4904   reglist = 0;
4905   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4906     return FALSE;
4907   do
4908     {
4909       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
4910         {
4911           reglist |= 1 << FP;
4912           regno2 = S7;
4913         }
4914       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
4915       reset = *arg;
4916     }
4917   while (match_char (arg, ',')
4918          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
4919   *arg = reset;
4920
4921   if (operand->size == 2)
4922     {
4923       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4924
4925          s0, ra
4926          s0, s1, ra, s2, s3
4927          s0-s2, ra
4928
4929          and any permutations of these.  */
4930       if ((reglist & 0xfff1ffff) != 0x80010000)
4931         return FALSE;
4932
4933       sregs = (reglist >> 17) & 7;
4934       ra = 0;
4935     }
4936   else
4937     {
4938       /* The list must include at least one of ra and s0-sN,
4939          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4940          which are $23 and $30 respectively.)  E.g.:
4941
4942          ra
4943          s0
4944          ra, s0, s1, s2
4945          s0-s8
4946          s0-s5, ra
4947
4948          and any permutations of these.  */
4949       if ((reglist & 0x3f00ffff) != 0)
4950         return FALSE;
4951
4952       ra = (reglist >> 27) & 0x10;
4953       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4954     }
4955   sregs += 1;
4956   if ((sregs & -sregs) != sregs)
4957     return FALSE;
4958
4959   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4960   return TRUE;
4961 }
4962
4963 /* OP_ENTRY_EXIT_LIST matcher.  */
4964
4965 static unsigned int
4966 match_entry_exit_operand (struct mips_arg_info *arg,
4967                           const struct mips_operand *operand)
4968 {
4969   unsigned int mask;
4970   bfd_boolean is_exit;
4971
4972   /* The format is the same for both ENTRY and EXIT, but the constraints
4973      are different.  */
4974   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4975   mask = (is_exit ? 7 << 3 : 0);
4976   do
4977     {
4978       unsigned int regno1, regno2;
4979       bfd_boolean is_freg;
4980
4981       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4982         is_freg = FALSE;
4983       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
4984         is_freg = TRUE;
4985       else
4986         return FALSE;
4987
4988       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4989         {
4990           mask &= ~(7 << 3);
4991           mask |= (5 + regno2) << 3;
4992         }
4993       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4994         mask |= (regno2 - 3) << 3;
4995       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4996         mask |= (regno2 - 15) << 1;
4997       else if (regno1 == RA && regno2 == RA)
4998         mask |= 1;
4999       else
5000         return FALSE;
5001     }
5002   while (match_char (arg, ','));
5003
5004   insn_insert_operand (arg->insn, operand, mask);
5005   return TRUE;
5006 }
5007
5008 /* OP_SAVE_RESTORE_LIST matcher.  */
5009
5010 static bfd_boolean
5011 match_save_restore_list_operand (struct mips_arg_info *arg)
5012 {
5013   unsigned int opcode, args, statics, sregs;
5014   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5015   offsetT frame_size;
5016
5017   opcode = arg->insn->insn_opcode;
5018   frame_size = 0;
5019   num_frame_sizes = 0;
5020   args = 0;
5021   statics = 0;
5022   sregs = 0;
5023   do
5024     {
5025       unsigned int regno1, regno2;
5026
5027       if (arg->token->type == OT_INTEGER)
5028         {
5029           /* Handle the frame size.  */
5030           if (!match_const_int (arg, &frame_size))
5031             return FALSE;
5032           num_frame_sizes += 1;
5033         }
5034       else
5035         {
5036           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5037             return FALSE;
5038
5039           while (regno1 <= regno2)
5040             {
5041               if (regno1 >= 4 && regno1 <= 7)
5042                 {
5043                   if (num_frame_sizes == 0)
5044                     /* args $a0-$a3 */
5045                     args |= 1 << (regno1 - 4);
5046                   else
5047                     /* statics $a0-$a3 */
5048                     statics |= 1 << (regno1 - 4);
5049                 }
5050               else if (regno1 >= 16 && regno1 <= 23)
5051                 /* $s0-$s7 */
5052                 sregs |= 1 << (regno1 - 16);
5053               else if (regno1 == 30)
5054                 /* $s8 */
5055                 sregs |= 1 << 8;
5056               else if (regno1 == 31)
5057                 /* Add $ra to insn.  */
5058                 opcode |= 0x40;
5059               else
5060                 return FALSE;
5061               regno1 += 1;
5062               if (regno1 == 24)
5063                 regno1 = 30;
5064             }
5065         }
5066     }
5067   while (match_char (arg, ','));
5068
5069   /* Encode args/statics combination.  */
5070   if (args & statics)
5071     return FALSE;
5072   else if (args == 0xf)
5073     /* All $a0-$a3 are args.  */
5074     opcode |= MIPS16_ALL_ARGS << 16;
5075   else if (statics == 0xf)
5076     /* All $a0-$a3 are statics.  */
5077     opcode |= MIPS16_ALL_STATICS << 16;
5078   else
5079     {
5080       /* Count arg registers.  */
5081       num_args = 0;
5082       while (args & 0x1)
5083         {
5084           args >>= 1;
5085           num_args += 1;
5086         }
5087       if (args != 0)
5088         return FALSE;
5089
5090       /* Count static registers.  */
5091       num_statics = 0;
5092       while (statics & 0x8)
5093         {
5094           statics = (statics << 1) & 0xf;
5095           num_statics += 1;
5096         }
5097       if (statics != 0)
5098         return FALSE;
5099
5100       /* Encode args/statics.  */
5101       opcode |= ((num_args << 2) | num_statics) << 16;
5102     }
5103
5104   /* Encode $s0/$s1.  */
5105   if (sregs & (1 << 0))         /* $s0 */
5106     opcode |= 0x20;
5107   if (sregs & (1 << 1))         /* $s1 */
5108     opcode |= 0x10;
5109   sregs >>= 2;
5110
5111   /* Encode $s2-$s8. */
5112   num_sregs = 0;
5113   while (sregs & 1)
5114     {
5115       sregs >>= 1;
5116       num_sregs += 1;
5117     }
5118   if (sregs != 0)
5119     return FALSE;
5120   opcode |= num_sregs << 24;
5121
5122   /* Encode frame size.  */
5123   if (num_frame_sizes == 0)
5124     {
5125       set_insn_error (arg->argnum, _("missing frame size"));
5126       return FALSE;
5127     }
5128   if (num_frame_sizes > 1)
5129     {
5130       set_insn_error (arg->argnum, _("frame size specified twice"));
5131       return FALSE;
5132     }
5133   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5134     {
5135       set_insn_error (arg->argnum, _("invalid frame size"));
5136       return FALSE;
5137     }
5138   if (frame_size != 128 || (opcode >> 16) != 0)
5139     {
5140       frame_size /= 8;
5141       opcode |= (((frame_size & 0xf0) << 16)
5142                  | (frame_size & 0x0f));
5143     }
5144
5145   /* Finally build the instruction.  */
5146   if ((opcode >> 16) != 0 || frame_size == 0)
5147     opcode |= MIPS16_EXTEND;
5148   arg->insn->insn_opcode = opcode;
5149   return TRUE;
5150 }
5151
5152 /* OP_MDMX_IMM_REG matcher.  */
5153
5154 static bfd_boolean
5155 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5156                             const struct mips_operand *operand)
5157 {
5158   unsigned int regno, uval;
5159   bfd_boolean is_qh;
5160   const struct mips_opcode *opcode;
5161
5162   /* The mips_opcode records whether this is an octobyte or quadhalf
5163      instruction.  Start out with that bit in place.  */
5164   opcode = arg->insn->insn_mo;
5165   uval = mips_extract_operand (operand, opcode->match);
5166   is_qh = (uval != 0);
5167
5168   if (arg->token->type == OT_REG)
5169     {
5170       if ((opcode->membership & INSN_5400)
5171           && strcmp (opcode->name, "rzu.ob") == 0)
5172         {
5173           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5174                             arg->argnum);
5175           return FALSE;
5176         }
5177
5178       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5179         return FALSE;
5180       ++arg->token;
5181
5182       /* Check whether this is a vector register or a broadcast of
5183          a single element.  */
5184       if (arg->token->type == OT_INTEGER_INDEX)
5185         {
5186           if (arg->token->u.index > (is_qh ? 3 : 7))
5187             {
5188               set_insn_error (arg->argnum, _("invalid element selector"));
5189               return FALSE;
5190             }
5191           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5192           ++arg->token;
5193         }
5194       else
5195         {
5196           /* A full vector.  */
5197           if ((opcode->membership & INSN_5400)
5198               && (strcmp (opcode->name, "sll.ob") == 0
5199                   || strcmp (opcode->name, "srl.ob") == 0))
5200             {
5201               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5202                                 arg->argnum);
5203               return FALSE;
5204             }
5205
5206           if (is_qh)
5207             uval |= MDMX_FMTSEL_VEC_QH << 5;
5208           else
5209             uval |= MDMX_FMTSEL_VEC_OB << 5;
5210         }
5211       uval |= regno;
5212     }
5213   else
5214     {
5215       offsetT sval;
5216
5217       if (!match_const_int (arg, &sval))
5218         return FALSE;
5219       if (sval < 0 || sval > 31)
5220         {
5221           match_out_of_range (arg);
5222           return FALSE;
5223         }
5224       uval |= (sval & 31);
5225       if (is_qh)
5226         uval |= MDMX_FMTSEL_IMM_QH << 5;
5227       else
5228         uval |= MDMX_FMTSEL_IMM_OB << 5;
5229     }
5230   insn_insert_operand (arg->insn, operand, uval);
5231   return TRUE;
5232 }
5233
5234 /* OP_IMM_INDEX matcher.  */
5235
5236 static bfd_boolean
5237 match_imm_index_operand (struct mips_arg_info *arg,
5238                          const struct mips_operand *operand)
5239 {
5240   unsigned int max_val;
5241
5242   if (arg->token->type != OT_INTEGER_INDEX)
5243     return FALSE;
5244
5245   max_val = (1 << operand->size) - 1;
5246   if (arg->token->u.index > max_val)
5247     {
5248       match_out_of_range (arg);
5249       return FALSE;
5250     }
5251   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5252   ++arg->token;
5253   return TRUE;
5254 }
5255
5256 /* OP_REG_INDEX matcher.  */
5257
5258 static bfd_boolean
5259 match_reg_index_operand (struct mips_arg_info *arg,
5260                          const struct mips_operand *operand)
5261 {
5262   unsigned int regno;
5263
5264   if (arg->token->type != OT_REG_INDEX)
5265     return FALSE;
5266
5267   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5268     return FALSE;
5269
5270   insn_insert_operand (arg->insn, operand, regno);
5271   ++arg->token;
5272   return TRUE;
5273 }
5274
5275 /* OP_PC matcher.  */
5276
5277 static bfd_boolean
5278 match_pc_operand (struct mips_arg_info *arg)
5279 {
5280   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5281     {
5282       ++arg->token;
5283       return TRUE;
5284     }
5285   return FALSE;
5286 }
5287
5288 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5289    register that we need to match.  */
5290
5291 static bfd_boolean
5292 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5293 {
5294   unsigned int regno;
5295
5296   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5297 }
5298
5299 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5300    the length of the value in bytes (4 for float, 8 for double) and
5301    USING_GPRS says whether the destination is a GPR rather than an FPR.
5302
5303    Return the constant in IMM and OFFSET as follows:
5304
5305    - If the constant should be loaded via memory, set IMM to O_absent and
5306      OFFSET to the memory address.
5307
5308    - Otherwise, if the constant should be loaded into two 32-bit registers,
5309      set IMM to the O_constant to load into the high register and OFFSET
5310      to the corresponding value for the low register.
5311
5312    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5313
5314    These constants only appear as the last operand in an instruction,
5315    and every instruction that accepts them in any variant accepts them
5316    in all variants.  This means we don't have to worry about backing out
5317    any changes if the instruction does not match.  We just match
5318    unconditionally and report an error if the constant is invalid.  */
5319
5320 static bfd_boolean
5321 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5322                       expressionS *offset, int length, bfd_boolean using_gprs)
5323 {
5324   char *p;
5325   segT seg, new_seg;
5326   subsegT subseg;
5327   const char *newname;
5328   unsigned char *data;
5329
5330   /* Where the constant is placed is based on how the MIPS assembler
5331      does things:
5332
5333      length == 4 && using_gprs  -- immediate value only
5334      length == 8 && using_gprs  -- .rdata or immediate value
5335      length == 4 && !using_gprs -- .lit4 or immediate value
5336      length == 8 && !using_gprs -- .lit8 or immediate value
5337
5338      The .lit4 and .lit8 sections are only used if permitted by the
5339      -G argument.  */
5340   if (arg->token->type != OT_FLOAT)
5341     {
5342       set_insn_error (arg->argnum, _("floating-point expression required"));
5343       return FALSE;
5344     }
5345
5346   gas_assert (arg->token->u.flt.length == length);
5347   data = arg->token->u.flt.data;
5348   ++arg->token;
5349
5350   /* Handle 32-bit constants for which an immediate value is best.  */
5351   if (length == 4
5352       && (using_gprs
5353           || g_switch_value < 4
5354           || (data[0] == 0 && data[1] == 0)
5355           || (data[2] == 0 && data[3] == 0)))
5356     {
5357       imm->X_op = O_constant;
5358       if (!target_big_endian)
5359         imm->X_add_number = bfd_getl32 (data);
5360       else
5361         imm->X_add_number = bfd_getb32 (data);
5362       offset->X_op = O_absent;
5363       return TRUE;
5364     }
5365
5366   /* Handle 64-bit constants for which an immediate value is best.  */
5367   if (length == 8
5368       && !mips_disable_float_construction
5369       /* Constants can only be constructed in GPRs and copied
5370          to FPRs if the GPRs are at least as wide as the FPRs.
5371          Force the constant into memory if we are using 64-bit FPRs
5372          but the GPRs are only 32 bits wide.  */
5373       /* ??? No longer true with the addition of MTHC1, but this
5374          is legacy code...  */
5375       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
5376       && ((data[0] == 0 && data[1] == 0)
5377           || (data[2] == 0 && data[3] == 0))
5378       && ((data[4] == 0 && data[5] == 0)
5379           || (data[6] == 0 && data[7] == 0)))
5380     {
5381       /* The value is simple enough to load with a couple of instructions.
5382          If using 32-bit registers, set IMM to the high order 32 bits and
5383          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5384          64 bit constant.  */
5385       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
5386         {
5387           imm->X_op = O_constant;
5388           offset->X_op = O_constant;
5389           if (!target_big_endian)
5390             {
5391               imm->X_add_number = bfd_getl32 (data + 4);
5392               offset->X_add_number = bfd_getl32 (data);
5393             }
5394           else
5395             {
5396               imm->X_add_number = bfd_getb32 (data);
5397               offset->X_add_number = bfd_getb32 (data + 4);
5398             }
5399           if (offset->X_add_number == 0)
5400             offset->X_op = O_absent;
5401         }
5402       else
5403         {
5404           imm->X_op = O_constant;
5405           if (!target_big_endian)
5406             imm->X_add_number = bfd_getl64 (data);
5407           else
5408             imm->X_add_number = bfd_getb64 (data);
5409           offset->X_op = O_absent;
5410         }
5411       return TRUE;
5412     }
5413
5414   /* Switch to the right section.  */
5415   seg = now_seg;
5416   subseg = now_subseg;
5417   if (length == 4)
5418     {
5419       gas_assert (!using_gprs && g_switch_value >= 4);
5420       newname = ".lit4";
5421     }
5422   else
5423     {
5424       if (using_gprs || g_switch_value < 8)
5425         newname = RDATA_SECTION_NAME;
5426       else
5427         newname = ".lit8";
5428     }
5429
5430   new_seg = subseg_new (newname, (subsegT) 0);
5431   bfd_set_section_flags (stdoutput, new_seg,
5432                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5433   frag_align (length == 4 ? 2 : 3, 0, 0);
5434   if (strncmp (TARGET_OS, "elf", 3) != 0)
5435     record_alignment (new_seg, 4);
5436   else
5437     record_alignment (new_seg, length == 4 ? 2 : 3);
5438   if (seg == now_seg)
5439     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5440
5441   /* Set the argument to the current address in the section.  */
5442   imm->X_op = O_absent;
5443   offset->X_op = O_symbol;
5444   offset->X_add_symbol = symbol_temp_new_now ();
5445   offset->X_add_number = 0;
5446
5447   /* Put the floating point number into the section.  */
5448   p = frag_more (length);
5449   memcpy (p, data, length);
5450
5451   /* Switch back to the original section.  */
5452   subseg_set (seg, subseg);
5453   return TRUE;
5454 }
5455
5456 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5457    them.  */
5458
5459 static bfd_boolean
5460 match_vu0_suffix_operand (struct mips_arg_info *arg,
5461                           const struct mips_operand *operand,
5462                           bfd_boolean match_p)
5463 {
5464   unsigned int uval;
5465
5466   /* The operand can be an XYZW mask or a single 2-bit channel index
5467      (with X being 0).  */
5468   gas_assert (operand->size == 2 || operand->size == 4);
5469
5470   /* The suffix can be omitted when it is already part of the opcode.  */
5471   if (arg->token->type != OT_CHANNELS)
5472     return match_p;
5473
5474   uval = arg->token->u.channels;
5475   if (operand->size == 2)
5476     {
5477       /* Check that a single bit is set and convert it into a 2-bit index.  */
5478       if ((uval & -uval) != uval)
5479         return FALSE;
5480       uval = 4 - ffs (uval);
5481     }
5482
5483   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5484     return FALSE;
5485
5486   ++arg->token;
5487   if (!match_p)
5488     insn_insert_operand (arg->insn, operand, uval);
5489   return TRUE;
5490 }
5491
5492 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5493    of the argument text if the match is successful, otherwise return null.  */
5494
5495 static bfd_boolean
5496 match_operand (struct mips_arg_info *arg,
5497                const struct mips_operand *operand)
5498 {
5499   switch (operand->type)
5500     {
5501     case OP_INT:
5502       return match_int_operand (arg, operand);
5503
5504     case OP_MAPPED_INT:
5505       return match_mapped_int_operand (arg, operand);
5506
5507     case OP_MSB:
5508       return match_msb_operand (arg, operand);
5509
5510     case OP_REG:
5511     case OP_OPTIONAL_REG:
5512       return match_reg_operand (arg, operand);
5513
5514     case OP_REG_PAIR:
5515       return match_reg_pair_operand (arg, operand);
5516
5517     case OP_PCREL:
5518       return match_pcrel_operand (arg);
5519
5520     case OP_PERF_REG:
5521       return match_perf_reg_operand (arg, operand);
5522
5523     case OP_ADDIUSP_INT:
5524       return match_addiusp_operand (arg, operand);
5525
5526     case OP_CLO_CLZ_DEST:
5527       return match_clo_clz_dest_operand (arg, operand);
5528
5529     case OP_LWM_SWM_LIST:
5530       return match_lwm_swm_list_operand (arg, operand);
5531
5532     case OP_ENTRY_EXIT_LIST:
5533       return match_entry_exit_operand (arg, operand);
5534
5535     case OP_SAVE_RESTORE_LIST:
5536       return match_save_restore_list_operand (arg);
5537
5538     case OP_MDMX_IMM_REG:
5539       return match_mdmx_imm_reg_operand (arg, operand);
5540
5541     case OP_REPEAT_DEST_REG:
5542       return match_tied_reg_operand (arg, arg->dest_regno);
5543
5544     case OP_REPEAT_PREV_REG:
5545       return match_tied_reg_operand (arg, arg->last_regno);
5546
5547     case OP_PC:
5548       return match_pc_operand (arg);
5549
5550     case OP_VU0_SUFFIX:
5551       return match_vu0_suffix_operand (arg, operand, FALSE);
5552
5553     case OP_VU0_MATCH_SUFFIX:
5554       return match_vu0_suffix_operand (arg, operand, TRUE);
5555
5556     case OP_IMM_INDEX:
5557       return match_imm_index_operand (arg, operand);
5558
5559     case OP_REG_INDEX:
5560       return match_reg_index_operand (arg, operand);
5561     }
5562   abort ();
5563 }
5564
5565 /* ARG is the state after successfully matching an instruction.
5566    Issue any queued-up warnings.  */
5567
5568 static void
5569 check_completed_insn (struct mips_arg_info *arg)
5570 {
5571   if (arg->seen_at)
5572     {
5573       if (AT == ATREG)
5574         as_warn (_("used $at without \".set noat\""));
5575       else
5576         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
5577     }
5578 }
5579
5580 /* Return true if modifying general-purpose register REG needs a delay.  */
5581
5582 static bfd_boolean
5583 reg_needs_delay (unsigned int reg)
5584 {
5585   unsigned long prev_pinfo;
5586
5587   prev_pinfo = history[0].insn_mo->pinfo;
5588   if (!mips_opts.noreorder
5589       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
5590           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5591       && (gpr_write_mask (&history[0]) & (1 << reg)))
5592     return TRUE;
5593
5594   return FALSE;
5595 }
5596
5597 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5598    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5599    by VR4120 errata.  */
5600
5601 static unsigned int
5602 classify_vr4120_insn (const char *name)
5603 {
5604   if (strncmp (name, "macc", 4) == 0)
5605     return FIX_VR4120_MACC;
5606   if (strncmp (name, "dmacc", 5) == 0)
5607     return FIX_VR4120_DMACC;
5608   if (strncmp (name, "mult", 4) == 0)
5609     return FIX_VR4120_MULT;
5610   if (strncmp (name, "dmult", 5) == 0)
5611     return FIX_VR4120_DMULT;
5612   if (strstr (name, "div"))
5613     return FIX_VR4120_DIV;
5614   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5615     return FIX_VR4120_MTHILO;
5616   return NUM_FIX_VR4120_CLASSES;
5617 }
5618
5619 #define INSN_ERET       0x42000018
5620 #define INSN_DERET      0x4200001f
5621 #define INSN_DMULT      0x1c
5622 #define INSN_DMULTU     0x1d
5623
5624 /* Return the number of instructions that must separate INSN1 and INSN2,
5625    where INSN1 is the earlier instruction.  Return the worst-case value
5626    for any INSN2 if INSN2 is null.  */
5627
5628 static unsigned int
5629 insns_between (const struct mips_cl_insn *insn1,
5630                const struct mips_cl_insn *insn2)
5631 {
5632   unsigned long pinfo1, pinfo2;
5633   unsigned int mask;
5634
5635   /* If INFO2 is null, pessimistically assume that all flags are set for
5636      the second instruction.  */
5637   pinfo1 = insn1->insn_mo->pinfo;
5638   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5639
5640   /* For most targets, write-after-read dependencies on the HI and LO
5641      registers must be separated by at least two instructions.  */
5642   if (!hilo_interlocks)
5643     {
5644       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5645         return 2;
5646       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5647         return 2;
5648     }
5649
5650   /* If we're working around r7000 errata, there must be two instructions
5651      between an mfhi or mflo and any instruction that uses the result.  */
5652   if (mips_7000_hilo_fix
5653       && !mips_opts.micromips
5654       && MF_HILO_INSN (pinfo1)
5655       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5656     return 2;
5657
5658   /* If we're working around 24K errata, one instruction is required
5659      if an ERET or DERET is followed by a branch instruction.  */
5660   if (mips_fix_24k && !mips_opts.micromips)
5661     {
5662       if (insn1->insn_opcode == INSN_ERET
5663           || insn1->insn_opcode == INSN_DERET)
5664         {
5665           if (insn2 == NULL
5666               || insn2->insn_opcode == INSN_ERET
5667               || insn2->insn_opcode == INSN_DERET
5668               || delayed_branch_p (insn2))
5669             return 1;
5670         }
5671     }
5672
5673   /* If we're working around PMC RM7000 errata, there must be three
5674      nops between a dmult and a load instruction.  */
5675   if (mips_fix_rm7000 && !mips_opts.micromips)
5676     {
5677       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
5678           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
5679         {
5680           if (pinfo2 & INSN_LOAD_MEMORY)
5681            return 3;
5682         }
5683     }
5684
5685   /* If working around VR4120 errata, check for combinations that need
5686      a single intervening instruction.  */
5687   if (mips_fix_vr4120 && !mips_opts.micromips)
5688     {
5689       unsigned int class1, class2;
5690
5691       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5692       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5693         {
5694           if (insn2 == NULL)
5695             return 1;
5696           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5697           if (vr4120_conflicts[class1] & (1 << class2))
5698             return 1;
5699         }
5700     }
5701
5702   if (!HAVE_CODE_COMPRESSION)
5703     {
5704       /* Check for GPR or coprocessor load delays.  All such delays
5705          are on the RT register.  */
5706       /* Itbl support may require additional care here.  */
5707       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
5708           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5709         {
5710           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5711             return 1;
5712         }
5713
5714       /* Check for generic coprocessor hazards.
5715
5716          This case is not handled very well.  There is no special
5717          knowledge of CP0 handling, and the coprocessors other than
5718          the floating point unit are not distinguished at all.  */
5719       /* Itbl support may require additional care here. FIXME!
5720          Need to modify this to include knowledge about
5721          user specified delays!  */
5722       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5723                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5724         {
5725           /* Handle cases where INSN1 writes to a known general coprocessor
5726              register.  There must be a one instruction delay before INSN2
5727              if INSN2 reads that register, otherwise no delay is needed.  */
5728           mask = fpr_write_mask (insn1);
5729           if (mask != 0)
5730             {
5731               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5732                 return 1;
5733             }
5734           else
5735             {
5736               /* Read-after-write dependencies on the control registers
5737                  require a two-instruction gap.  */
5738               if ((pinfo1 & INSN_WRITE_COND_CODE)
5739                   && (pinfo2 & INSN_READ_COND_CODE))
5740                 return 2;
5741
5742               /* We don't know exactly what INSN1 does.  If INSN2 is
5743                  also a coprocessor instruction, assume there must be
5744                  a one instruction gap.  */
5745               if (pinfo2 & INSN_COP)
5746                 return 1;
5747             }
5748         }
5749
5750       /* Check for read-after-write dependencies on the coprocessor
5751          control registers in cases where INSN1 does not need a general
5752          coprocessor delay.  This means that INSN1 is a floating point
5753          comparison instruction.  */
5754       /* Itbl support may require additional care here.  */
5755       else if (!cop_interlocks
5756                && (pinfo1 & INSN_WRITE_COND_CODE)
5757                && (pinfo2 & INSN_READ_COND_CODE))
5758         return 1;
5759     }
5760
5761   return 0;
5762 }
5763
5764 /* Return the number of nops that would be needed to work around the
5765    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5766    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5767    that are contained within the first IGNORE instructions of HIST.  */
5768
5769 static int
5770 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5771                  const struct mips_cl_insn *insn)
5772 {
5773   int i, j;
5774   unsigned int mask;
5775
5776   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5777      are not affected by the errata.  */
5778   if (insn != 0
5779       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5780           || strcmp (insn->insn_mo->name, "mtlo") == 0
5781           || strcmp (insn->insn_mo->name, "mthi") == 0))
5782     return 0;
5783
5784   /* Search for the first MFLO or MFHI.  */
5785   for (i = 0; i < MAX_VR4130_NOPS; i++)
5786     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5787       {
5788         /* Extract the destination register.  */
5789         mask = gpr_write_mask (&hist[i]);
5790
5791         /* No nops are needed if INSN reads that register.  */
5792         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5793           return 0;
5794
5795         /* ...or if any of the intervening instructions do.  */
5796         for (j = 0; j < i; j++)
5797           if (gpr_read_mask (&hist[j]) & mask)
5798             return 0;
5799
5800         if (i >= ignore)
5801           return MAX_VR4130_NOPS - i;
5802       }
5803   return 0;
5804 }
5805
5806 #define BASE_REG_EQ(INSN1, INSN2)       \
5807   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5808       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5809
5810 /* Return the minimum alignment for this store instruction.  */
5811
5812 static int
5813 fix_24k_align_to (const struct mips_opcode *mo)
5814 {
5815   if (strcmp (mo->name, "sh") == 0)
5816     return 2;
5817
5818   if (strcmp (mo->name, "swc1") == 0
5819       || strcmp (mo->name, "swc2") == 0
5820       || strcmp (mo->name, "sw") == 0
5821       || strcmp (mo->name, "sc") == 0
5822       || strcmp (mo->name, "s.s") == 0)
5823     return 4;
5824
5825   if (strcmp (mo->name, "sdc1") == 0
5826       || strcmp (mo->name, "sdc2") == 0
5827       || strcmp (mo->name, "s.d") == 0)
5828     return 8;
5829
5830   /* sb, swl, swr */
5831   return 1;
5832 }
5833
5834 struct fix_24k_store_info
5835   {
5836     /* Immediate offset, if any, for this store instruction.  */
5837     short off;
5838     /* Alignment required by this store instruction.  */
5839     int align_to;
5840     /* True for register offsets.  */
5841     int register_offset;
5842   };
5843
5844 /* Comparison function used by qsort.  */
5845
5846 static int
5847 fix_24k_sort (const void *a, const void *b)
5848 {
5849   const struct fix_24k_store_info *pos1 = a;
5850   const struct fix_24k_store_info *pos2 = b;
5851
5852   return (pos1->off - pos2->off);
5853 }
5854
5855 /* INSN is a store instruction.  Try to record the store information
5856    in STINFO.  Return false if the information isn't known.  */
5857
5858 static bfd_boolean
5859 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5860                            const struct mips_cl_insn *insn)
5861 {
5862   /* The instruction must have a known offset.  */
5863   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5864     return FALSE;
5865
5866   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5867   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5868   return TRUE;
5869 }
5870
5871 /* Return the number of nops that would be needed to work around the 24k
5872    "lost data on stores during refill" errata if instruction INSN
5873    immediately followed the 2 instructions described by HIST.
5874    Ignore hazards that are contained within the first IGNORE
5875    instructions of HIST.
5876
5877    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5878    for the data cache refills and store data. The following describes
5879    the scenario where the store data could be lost.
5880
5881    * A data cache miss, due to either a load or a store, causing fill
5882      data to be supplied by the memory subsystem
5883    * The first three doublewords of fill data are returned and written
5884      into the cache
5885    * A sequence of four stores occurs in consecutive cycles around the
5886      final doubleword of the fill:
5887    * Store A
5888    * Store B
5889    * Store C
5890    * Zero, One or more instructions
5891    * Store D
5892
5893    The four stores A-D must be to different doublewords of the line that
5894    is being filled. The fourth instruction in the sequence above permits
5895    the fill of the final doubleword to be transferred from the FSB into
5896    the cache. In the sequence above, the stores may be either integer
5897    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5898    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5899    different doublewords on the line. If the floating point unit is
5900    running in 1:2 mode, it is not possible to create the sequence above
5901    using only floating point store instructions.
5902
5903    In this case, the cache line being filled is incorrectly marked
5904    invalid, thereby losing the data from any store to the line that
5905    occurs between the original miss and the completion of the five
5906    cycle sequence shown above.
5907
5908    The workarounds are:
5909
5910    * Run the data cache in write-through mode.
5911    * Insert a non-store instruction between
5912      Store A and Store B or Store B and Store C.  */
5913   
5914 static int
5915 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5916               const struct mips_cl_insn *insn)
5917 {
5918   struct fix_24k_store_info pos[3];
5919   int align, i, base_offset;
5920
5921   if (ignore >= 2)
5922     return 0;
5923
5924   /* If the previous instruction wasn't a store, there's nothing to
5925      worry about.  */
5926   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5927     return 0;
5928
5929   /* If the instructions after the previous one are unknown, we have
5930      to assume the worst.  */
5931   if (!insn)
5932     return 1;
5933
5934   /* Check whether we are dealing with three consecutive stores.  */
5935   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5936       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5937     return 0;
5938
5939   /* If we don't know the relationship between the store addresses,
5940      assume the worst.  */
5941   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5942       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5943     return 1;
5944
5945   if (!fix_24k_record_store_info (&pos[0], insn)
5946       || !fix_24k_record_store_info (&pos[1], &hist[0])
5947       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5948     return 1;
5949
5950   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5951
5952   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5953      X bytes and such that the base register + X is known to be aligned
5954      to align bytes.  */
5955
5956   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5957     align = 8;
5958   else
5959     {
5960       align = pos[0].align_to;
5961       base_offset = pos[0].off;
5962       for (i = 1; i < 3; i++)
5963         if (align < pos[i].align_to)
5964           {
5965             align = pos[i].align_to;
5966             base_offset = pos[i].off;
5967           }
5968       for (i = 0; i < 3; i++)
5969         pos[i].off -= base_offset;
5970     }
5971
5972   pos[0].off &= ~align + 1;
5973   pos[1].off &= ~align + 1;
5974   pos[2].off &= ~align + 1;
5975
5976   /* If any two stores write to the same chunk, they also write to the
5977      same doubleword.  The offsets are still sorted at this point.  */
5978   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5979     return 0;
5980
5981   /* A range of at least 9 bytes is needed for the stores to be in
5982      non-overlapping doublewords.  */
5983   if (pos[2].off - pos[0].off <= 8)
5984     return 0;
5985
5986   if (pos[2].off - pos[1].off >= 24
5987       || pos[1].off - pos[0].off >= 24
5988       || pos[2].off - pos[0].off >= 32)
5989     return 0;
5990
5991   return 1;
5992 }
5993
5994 /* Return the number of nops that would be needed if instruction INSN
5995    immediately followed the MAX_NOPS instructions given by HIST,
5996    where HIST[0] is the most recent instruction.  Ignore hazards
5997    between INSN and the first IGNORE instructions in HIST.
5998
5999    If INSN is null, return the worse-case number of nops for any
6000    instruction.  */
6001
6002 static int
6003 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6004                const struct mips_cl_insn *insn)
6005 {
6006   int i, nops, tmp_nops;
6007
6008   nops = 0;
6009   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6010     {
6011       tmp_nops = insns_between (hist + i, insn) - i;
6012       if (tmp_nops > nops)
6013         nops = tmp_nops;
6014     }
6015
6016   if (mips_fix_vr4130 && !mips_opts.micromips)
6017     {
6018       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6019       if (tmp_nops > nops)
6020         nops = tmp_nops;
6021     }
6022
6023   if (mips_fix_24k && !mips_opts.micromips)
6024     {
6025       tmp_nops = nops_for_24k (ignore, hist, insn);
6026       if (tmp_nops > nops)
6027         nops = tmp_nops;
6028     }
6029
6030   return nops;
6031 }
6032
6033 /* The variable arguments provide NUM_INSNS extra instructions that
6034    might be added to HIST.  Return the largest number of nops that
6035    would be needed after the extended sequence, ignoring hazards
6036    in the first IGNORE instructions.  */
6037
6038 static int
6039 nops_for_sequence (int num_insns, int ignore,
6040                    const struct mips_cl_insn *hist, ...)
6041 {
6042   va_list args;
6043   struct mips_cl_insn buffer[MAX_NOPS];
6044   struct mips_cl_insn *cursor;
6045   int nops;
6046
6047   va_start (args, hist);
6048   cursor = buffer + num_insns;
6049   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6050   while (cursor > buffer)
6051     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6052
6053   nops = nops_for_insn (ignore, buffer, NULL);
6054   va_end (args);
6055   return nops;
6056 }
6057
6058 /* Like nops_for_insn, but if INSN is a branch, take into account the
6059    worst-case delay for the branch target.  */
6060
6061 static int
6062 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6063                          const struct mips_cl_insn *insn)
6064 {
6065   int nops, tmp_nops;
6066
6067   nops = nops_for_insn (ignore, hist, insn);
6068   if (delayed_branch_p (insn))
6069     {
6070       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6071                                     hist, insn, get_delay_slot_nop (insn));
6072       if (tmp_nops > nops)
6073         nops = tmp_nops;
6074     }
6075   else if (compact_branch_p (insn))
6076     {
6077       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6078       if (tmp_nops > nops)
6079         nops = tmp_nops;
6080     }
6081   return nops;
6082 }
6083
6084 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6085
6086 static void
6087 fix_loongson2f_nop (struct mips_cl_insn * ip)
6088 {
6089   gas_assert (!HAVE_CODE_COMPRESSION);
6090   if (strcmp (ip->insn_mo->name, "nop") == 0)
6091     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6092 }
6093
6094 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6095                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6096
6097 static void
6098 fix_loongson2f_jump (struct mips_cl_insn * ip)
6099 {
6100   gas_assert (!HAVE_CODE_COMPRESSION);
6101   if (strcmp (ip->insn_mo->name, "j") == 0
6102       || strcmp (ip->insn_mo->name, "jr") == 0
6103       || strcmp (ip->insn_mo->name, "jalr") == 0)
6104     {
6105       int sreg;
6106       expressionS ep;
6107
6108       if (! mips_opts.at)
6109         return;
6110
6111       sreg = EXTRACT_OPERAND (0, RS, *ip);
6112       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6113         return;
6114
6115       ep.X_op = O_constant;
6116       ep.X_add_number = 0xcfff0000;
6117       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6118       ep.X_add_number = 0xffff;
6119       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6120       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6121     }
6122 }
6123
6124 static void
6125 fix_loongson2f (struct mips_cl_insn * ip)
6126 {
6127   if (mips_fix_loongson2f_nop)
6128     fix_loongson2f_nop (ip);
6129
6130   if (mips_fix_loongson2f_jump)
6131     fix_loongson2f_jump (ip);
6132 }
6133
6134 /* IP is a branch that has a delay slot, and we need to fill it
6135    automatically.   Return true if we can do that by swapping IP
6136    with the previous instruction.
6137    ADDRESS_EXPR is an operand of the instruction to be used with
6138    RELOC_TYPE.  */
6139
6140 static bfd_boolean
6141 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6142                    bfd_reloc_code_real_type *reloc_type)
6143 {
6144   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6145   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6146   unsigned int fpr_read, prev_fpr_write;
6147
6148   /* -O2 and above is required for this optimization.  */
6149   if (mips_optimize < 2)
6150     return FALSE;
6151
6152   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6153   if (mips_opts.nomove)
6154     return FALSE;
6155
6156   /* We can't swap if the previous instruction's position is fixed.  */
6157   if (history[0].fixed_p)
6158     return FALSE;
6159
6160   /* If the previous previous insn was in a .set noreorder, we can't
6161      swap.  Actually, the MIPS assembler will swap in this situation.
6162      However, gcc configured -with-gnu-as will generate code like
6163
6164         .set    noreorder
6165         lw      $4,XXX
6166         .set    reorder
6167         INSN
6168         bne     $4,$0,foo
6169
6170      in which we can not swap the bne and INSN.  If gcc is not configured
6171      -with-gnu-as, it does not output the .set pseudo-ops.  */
6172   if (history[1].noreorder_p)
6173     return FALSE;
6174
6175   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6176      This means that the previous instruction was a 4-byte one anyhow.  */
6177   if (mips_opts.mips16 && history[0].fixp[0])
6178     return FALSE;
6179
6180   /* If the branch is itself the target of a branch, we can not swap.
6181      We cheat on this; all we check for is whether there is a label on
6182      this instruction.  If there are any branches to anything other than
6183      a label, users must use .set noreorder.  */
6184   if (seg_info (now_seg)->label_list)
6185     return FALSE;
6186
6187   /* If the previous instruction is in a variant frag other than this
6188      branch's one, we cannot do the swap.  This does not apply to
6189      MIPS16 code, which uses variant frags for different purposes.  */
6190   if (!mips_opts.mips16
6191       && history[0].frag
6192       && history[0].frag->fr_type == rs_machine_dependent)
6193     return FALSE;
6194
6195   /* We do not swap with instructions that cannot architecturally
6196      be placed in a branch delay slot, such as SYNC or ERET.  We
6197      also refrain from swapping with a trap instruction, since it
6198      complicates trap handlers to have the trap instruction be in
6199      a delay slot.  */
6200   prev_pinfo = history[0].insn_mo->pinfo;
6201   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6202     return FALSE;
6203
6204   /* Check for conflicts between the branch and the instructions
6205      before the candidate delay slot.  */
6206   if (nops_for_insn (0, history + 1, ip) > 0)
6207     return FALSE;
6208
6209   /* Check for conflicts between the swapped sequence and the
6210      target of the branch.  */
6211   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6212     return FALSE;
6213
6214   /* If the branch reads a register that the previous
6215      instruction sets, we can not swap.  */
6216   gpr_read = gpr_read_mask (ip);
6217   prev_gpr_write = gpr_write_mask (&history[0]);
6218   if (gpr_read & prev_gpr_write)
6219     return FALSE;
6220
6221   fpr_read = fpr_read_mask (ip);
6222   prev_fpr_write = fpr_write_mask (&history[0]);
6223   if (fpr_read & prev_fpr_write)
6224     return FALSE;
6225
6226   /* If the branch writes a register that the previous
6227      instruction sets, we can not swap.  */
6228   gpr_write = gpr_write_mask (ip);
6229   if (gpr_write & prev_gpr_write)
6230     return FALSE;
6231
6232   /* If the branch writes a register that the previous
6233      instruction reads, we can not swap.  */
6234   prev_gpr_read = gpr_read_mask (&history[0]);
6235   if (gpr_write & prev_gpr_read)
6236     return FALSE;
6237
6238   /* If one instruction sets a condition code and the
6239      other one uses a condition code, we can not swap.  */
6240   pinfo = ip->insn_mo->pinfo;
6241   if ((pinfo & INSN_READ_COND_CODE)
6242       && (prev_pinfo & INSN_WRITE_COND_CODE))
6243     return FALSE;
6244   if ((pinfo & INSN_WRITE_COND_CODE)
6245       && (prev_pinfo & INSN_READ_COND_CODE))
6246     return FALSE;
6247
6248   /* If the previous instruction uses the PC, we can not swap.  */
6249   prev_pinfo2 = history[0].insn_mo->pinfo2;
6250   if (prev_pinfo2 & INSN2_READ_PC)
6251     return FALSE;
6252
6253   /* If the previous instruction has an incorrect size for a fixed
6254      branch delay slot in microMIPS mode, we cannot swap.  */
6255   pinfo2 = ip->insn_mo->pinfo2;
6256   if (mips_opts.micromips
6257       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6258       && insn_length (history) != 2)
6259     return FALSE;
6260   if (mips_opts.micromips
6261       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6262       && insn_length (history) != 4)
6263     return FALSE;
6264
6265   /* On R5900 short loops need to be fixed by inserting a nop in
6266      the branch delay slots.
6267      A short loop can be terminated too early.  */
6268   if (mips_opts.arch == CPU_R5900
6269       /* Check if instruction has a parameter, ignore "j $31". */
6270       && (address_expr != NULL)
6271       /* Parameter must be 16 bit. */
6272       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6273       /* Branch to same segment. */
6274       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6275       /* Branch to same code fragment. */
6276       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6277       /* Can only calculate branch offset if value is known. */
6278       && symbol_constant_p(address_expr->X_add_symbol)
6279       /* Check if branch is really conditional. */
6280       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6281         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6282         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6283     {
6284       int distance;
6285       /* Check if loop is shorter than 6 instructions including
6286          branch and delay slot.  */
6287       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6288       if (distance <= 20)
6289         {
6290           int i;
6291           int rv;
6292
6293           rv = FALSE;
6294           /* When the loop includes branches or jumps,
6295              it is not a short loop. */
6296           for (i = 0; i < (distance / 4); i++)
6297             {
6298               if ((history[i].cleared_p)
6299                   || delayed_branch_p(&history[i]))
6300                 {
6301                   rv = TRUE;
6302                   break;
6303                 }
6304             }
6305           if (rv == FALSE)
6306             {
6307               /* Insert nop after branch to fix short loop. */
6308               return FALSE;
6309             }
6310         }
6311     }
6312
6313   return TRUE;
6314 }
6315
6316 /* Decide how we should add IP to the instruction stream.
6317    ADDRESS_EXPR is an operand of the instruction to be used with
6318    RELOC_TYPE.  */
6319
6320 static enum append_method
6321 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6322                    bfd_reloc_code_real_type *reloc_type)
6323 {
6324   /* The relaxed version of a macro sequence must be inherently
6325      hazard-free.  */
6326   if (mips_relax.sequence == 2)
6327     return APPEND_ADD;
6328
6329   /* We must not dabble with instructions in a ".set norerorder" block.  */
6330   if (mips_opts.noreorder)
6331     return APPEND_ADD;
6332
6333   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6334   if (delayed_branch_p (ip))
6335     {
6336       if (!branch_likely_p (ip)
6337           && can_swap_branch_p (ip, address_expr, reloc_type))
6338         return APPEND_SWAP;
6339
6340       if (mips_opts.mips16
6341           && ISA_SUPPORTS_MIPS16E
6342           && gpr_read_mask (ip) != 0)
6343         return APPEND_ADD_COMPACT;
6344
6345       return APPEND_ADD_WITH_NOP;
6346     }
6347
6348   return APPEND_ADD;
6349 }
6350
6351 /* IP is a MIPS16 instruction whose opcode we have just changed.
6352    Point IP->insn_mo to the new opcode's definition.  */
6353
6354 static void
6355 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6356 {
6357   const struct mips_opcode *mo, *end;
6358
6359   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6360   for (mo = ip->insn_mo; mo < end; mo++)
6361     if ((ip->insn_opcode & mo->mask) == mo->match)
6362       {
6363         ip->insn_mo = mo;
6364         return;
6365       }
6366   abort ();
6367 }
6368
6369 /* For microMIPS macros, we need to generate a local number label
6370    as the target of branches.  */
6371 #define MICROMIPS_LABEL_CHAR            '\037'
6372 static unsigned long micromips_target_label;
6373 static char micromips_target_name[32];
6374
6375 static char *
6376 micromips_label_name (void)
6377 {
6378   char *p = micromips_target_name;
6379   char symbol_name_temporary[24];
6380   unsigned long l;
6381   int i;
6382
6383   if (*p)
6384     return p;
6385
6386   i = 0;
6387   l = micromips_target_label;
6388 #ifdef LOCAL_LABEL_PREFIX
6389   *p++ = LOCAL_LABEL_PREFIX;
6390 #endif
6391   *p++ = 'L';
6392   *p++ = MICROMIPS_LABEL_CHAR;
6393   do
6394     {
6395       symbol_name_temporary[i++] = l % 10 + '0';
6396       l /= 10;
6397     }
6398   while (l != 0);
6399   while (i > 0)
6400     *p++ = symbol_name_temporary[--i];
6401   *p = '\0';
6402
6403   return micromips_target_name;
6404 }
6405
6406 static void
6407 micromips_label_expr (expressionS *label_expr)
6408 {
6409   label_expr->X_op = O_symbol;
6410   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6411   label_expr->X_add_number = 0;
6412 }
6413
6414 static void
6415 micromips_label_inc (void)
6416 {
6417   micromips_target_label++;
6418   *micromips_target_name = '\0';
6419 }
6420
6421 static void
6422 micromips_add_label (void)
6423 {
6424   symbolS *s;
6425
6426   s = colon (micromips_label_name ());
6427   micromips_label_inc ();
6428   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6429 }
6430
6431 /* If assembling microMIPS code, then return the microMIPS reloc
6432    corresponding to the requested one if any.  Otherwise return
6433    the reloc unchanged.  */
6434
6435 static bfd_reloc_code_real_type
6436 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6437 {
6438   static const bfd_reloc_code_real_type relocs[][2] =
6439     {
6440       /* Keep sorted incrementally by the left-hand key.  */
6441       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6442       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6443       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6444       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6445       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6446       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6447       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6448       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6449       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6450       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6451       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6452       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6453       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6454       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6455       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6456       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6457       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6458       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6459       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6460       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6461       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6462       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6463       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6464       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6465       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6466       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6467       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6468     };
6469   bfd_reloc_code_real_type r;
6470   size_t i;
6471
6472   if (!mips_opts.micromips)
6473     return reloc;
6474   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6475     {
6476       r = relocs[i][0];
6477       if (r > reloc)
6478         return reloc;
6479       if (r == reloc)
6480         return relocs[i][1];
6481     }
6482   return reloc;
6483 }
6484
6485 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6486    Return true on success, storing the resolved value in RESULT.  */
6487
6488 static bfd_boolean
6489 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6490                  offsetT *result)
6491 {
6492   switch (reloc)
6493     {
6494     case BFD_RELOC_MIPS_HIGHEST:
6495     case BFD_RELOC_MICROMIPS_HIGHEST:
6496       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6497       return TRUE;
6498
6499     case BFD_RELOC_MIPS_HIGHER:
6500     case BFD_RELOC_MICROMIPS_HIGHER:
6501       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6502       return TRUE;
6503
6504     case BFD_RELOC_HI16_S:
6505     case BFD_RELOC_MICROMIPS_HI16_S:
6506     case BFD_RELOC_MIPS16_HI16_S:
6507       *result = ((operand + 0x8000) >> 16) & 0xffff;
6508       return TRUE;
6509
6510     case BFD_RELOC_HI16:
6511     case BFD_RELOC_MICROMIPS_HI16:
6512     case BFD_RELOC_MIPS16_HI16:
6513       *result = (operand >> 16) & 0xffff;
6514       return TRUE;
6515
6516     case BFD_RELOC_LO16:
6517     case BFD_RELOC_MICROMIPS_LO16:
6518     case BFD_RELOC_MIPS16_LO16:
6519       *result = operand & 0xffff;
6520       return TRUE;
6521
6522     case BFD_RELOC_UNUSED:
6523       *result = operand;
6524       return TRUE;
6525
6526     default:
6527       return FALSE;
6528     }
6529 }
6530
6531 /* Output an instruction.  IP is the instruction information.
6532    ADDRESS_EXPR is an operand of the instruction to be used with
6533    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6534    a macro expansion.  */
6535
6536 static void
6537 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6538              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6539 {
6540   unsigned long prev_pinfo2, pinfo;
6541   bfd_boolean relaxed_branch = FALSE;
6542   enum append_method method;
6543   bfd_boolean relax32;
6544   int branch_disp;
6545
6546   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6547     fix_loongson2f (ip);
6548
6549   file_ase_mips16 |= mips_opts.mips16;
6550   file_ase_micromips |= mips_opts.micromips;
6551
6552   prev_pinfo2 = history[0].insn_mo->pinfo2;
6553   pinfo = ip->insn_mo->pinfo;
6554
6555   if (mips_opts.micromips
6556       && !expansionp
6557       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6558            && micromips_insn_length (ip->insn_mo) != 2)
6559           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6560               && micromips_insn_length (ip->insn_mo) != 4)))
6561     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
6562              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6563
6564   if (address_expr == NULL)
6565     ip->complete_p = 1;
6566   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6567            && reloc_type[1] == BFD_RELOC_UNUSED
6568            && reloc_type[2] == BFD_RELOC_UNUSED
6569            && address_expr->X_op == O_constant)
6570     {
6571       switch (*reloc_type)
6572         {
6573         case BFD_RELOC_MIPS_JMP:
6574           {
6575             int shift;
6576
6577             shift = mips_opts.micromips ? 1 : 2;
6578             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6579               as_bad (_("jump to misaligned address (0x%lx)"),
6580                       (unsigned long) address_expr->X_add_number);
6581             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6582                                 & 0x3ffffff);
6583             ip->complete_p = 1;
6584           }
6585           break;
6586
6587         case BFD_RELOC_MIPS16_JMP:
6588           if ((address_expr->X_add_number & 3) != 0)
6589             as_bad (_("jump to misaligned address (0x%lx)"),
6590                     (unsigned long) address_expr->X_add_number);
6591           ip->insn_opcode |=
6592             (((address_expr->X_add_number & 0x7c0000) << 3)
6593                | ((address_expr->X_add_number & 0xf800000) >> 7)
6594                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6595           ip->complete_p = 1;
6596           break;
6597
6598         case BFD_RELOC_16_PCREL_S2:
6599           {
6600             int shift;
6601
6602             shift = mips_opts.micromips ? 1 : 2;
6603             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6604               as_bad (_("branch to misaligned address (0x%lx)"),
6605                       (unsigned long) address_expr->X_add_number);
6606             if (!mips_relax_branch)
6607               {
6608                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6609                     & ~((1 << (shift + 16)) - 1))
6610                   as_bad (_("branch address range overflow (0x%lx)"),
6611                           (unsigned long) address_expr->X_add_number);
6612                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6613                                     & 0xffff);
6614               }
6615           }
6616           break;
6617
6618         default:
6619           {
6620             offsetT value;
6621
6622             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6623                                  &value))
6624               {
6625                 ip->insn_opcode |= value & 0xffff;
6626                 ip->complete_p = 1;
6627               }
6628           }
6629           break;
6630         }
6631     }
6632
6633   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6634     {
6635       /* There are a lot of optimizations we could do that we don't.
6636          In particular, we do not, in general, reorder instructions.
6637          If you use gcc with optimization, it will reorder
6638          instructions and generally do much more optimization then we
6639          do here; repeating all that work in the assembler would only
6640          benefit hand written assembly code, and does not seem worth
6641          it.  */
6642       int nops = (mips_optimize == 0
6643                   ? nops_for_insn (0, history, NULL)
6644                   : nops_for_insn_or_target (0, history, ip));
6645       if (nops > 0)
6646         {
6647           fragS *old_frag;
6648           unsigned long old_frag_offset;
6649           int i;
6650
6651           old_frag = frag_now;
6652           old_frag_offset = frag_now_fix ();
6653
6654           for (i = 0; i < nops; i++)
6655             add_fixed_insn (NOP_INSN);
6656           insert_into_history (0, nops, NOP_INSN);
6657
6658           if (listing)
6659             {
6660               listing_prev_line ();
6661               /* We may be at the start of a variant frag.  In case we
6662                  are, make sure there is enough space for the frag
6663                  after the frags created by listing_prev_line.  The
6664                  argument to frag_grow here must be at least as large
6665                  as the argument to all other calls to frag_grow in
6666                  this file.  We don't have to worry about being in the
6667                  middle of a variant frag, because the variants insert
6668                  all needed nop instructions themselves.  */
6669               frag_grow (40);
6670             }
6671
6672           mips_move_text_labels ();
6673
6674 #ifndef NO_ECOFF_DEBUGGING
6675           if (ECOFF_DEBUGGING)
6676             ecoff_fix_loc (old_frag, old_frag_offset);
6677 #endif
6678         }
6679     }
6680   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6681     {
6682       int nops;
6683
6684       /* Work out how many nops in prev_nop_frag are needed by IP,
6685          ignoring hazards generated by the first prev_nop_frag_since
6686          instructions.  */
6687       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6688       gas_assert (nops <= prev_nop_frag_holds);
6689
6690       /* Enforce NOPS as a minimum.  */
6691       if (nops > prev_nop_frag_required)
6692         prev_nop_frag_required = nops;
6693
6694       if (prev_nop_frag_holds == prev_nop_frag_required)
6695         {
6696           /* Settle for the current number of nops.  Update the history
6697              accordingly (for the benefit of any future .set reorder code).  */
6698           prev_nop_frag = NULL;
6699           insert_into_history (prev_nop_frag_since,
6700                                prev_nop_frag_holds, NOP_INSN);
6701         }
6702       else
6703         {
6704           /* Allow this instruction to replace one of the nops that was
6705              tentatively added to prev_nop_frag.  */
6706           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6707           prev_nop_frag_holds--;
6708           prev_nop_frag_since++;
6709         }
6710     }
6711
6712   method = get_append_method (ip, address_expr, reloc_type);
6713   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6714
6715   dwarf2_emit_insn (0);
6716   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6717      so "move" the instruction address accordingly.
6718
6719      Also, it doesn't seem appropriate for the assembler to reorder .loc
6720      entries.  If this instruction is a branch that we are going to swap
6721      with the previous instruction, the two instructions should be
6722      treated as a unit, and the debug information for both instructions
6723      should refer to the start of the branch sequence.  Using the
6724      current position is certainly wrong when swapping a 32-bit branch
6725      and a 16-bit delay slot, since the current position would then be
6726      in the middle of a branch.  */
6727   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6728
6729   relax32 = (mips_relax_branch
6730              /* Don't try branch relaxation within .set nomacro, or within
6731                 .set noat if we use $at for PIC computations.  If it turns
6732                 out that the branch was out-of-range, we'll get an error.  */
6733              && !mips_opts.warn_about_macros
6734              && (mips_opts.at || mips_pic == NO_PIC)
6735              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6736                 as they have no complementing branches.  */
6737              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6738
6739   if (!HAVE_CODE_COMPRESSION
6740       && address_expr
6741       && relax32
6742       && *reloc_type == BFD_RELOC_16_PCREL_S2
6743       && delayed_branch_p (ip))
6744     {
6745       relaxed_branch = TRUE;
6746       add_relaxed_insn (ip, (relaxed_branch_length
6747                              (NULL, NULL,
6748                               uncond_branch_p (ip) ? -1
6749                               : branch_likely_p (ip) ? 1
6750                               : 0)), 4,
6751                         RELAX_BRANCH_ENCODE
6752                         (AT,
6753                          uncond_branch_p (ip),
6754                          branch_likely_p (ip),
6755                          pinfo & INSN_WRITE_GPR_31,
6756                          0),
6757                         address_expr->X_add_symbol,
6758                         address_expr->X_add_number);
6759       *reloc_type = BFD_RELOC_UNUSED;
6760     }
6761   else if (mips_opts.micromips
6762            && address_expr
6763            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6764                || *reloc_type > BFD_RELOC_UNUSED)
6765            && (delayed_branch_p (ip) || compact_branch_p (ip))
6766            /* Don't try branch relaxation when users specify
6767               16-bit/32-bit instructions.  */
6768            && !forced_insn_length)
6769     {
6770       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6771       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6772       int uncond = uncond_branch_p (ip) ? -1 : 0;
6773       int compact = compact_branch_p (ip);
6774       int al = pinfo & INSN_WRITE_GPR_31;
6775       int length32;
6776
6777       gas_assert (address_expr != NULL);
6778       gas_assert (!mips_relax.sequence);
6779
6780       relaxed_branch = TRUE;
6781       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6782       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6783                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6784                                                 relax32, 0, 0),
6785                         address_expr->X_add_symbol,
6786                         address_expr->X_add_number);
6787       *reloc_type = BFD_RELOC_UNUSED;
6788     }
6789   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6790     {
6791       /* We need to set up a variant frag.  */
6792       gas_assert (address_expr != NULL);
6793       add_relaxed_insn (ip, 4, 0,
6794                         RELAX_MIPS16_ENCODE
6795                         (*reloc_type - BFD_RELOC_UNUSED,
6796                          forced_insn_length == 2, forced_insn_length == 4,
6797                          delayed_branch_p (&history[0]),
6798                          history[0].mips16_absolute_jump_p),
6799                         make_expr_symbol (address_expr), 0);
6800     }
6801   else if (mips_opts.mips16 && insn_length (ip) == 2)
6802     {
6803       if (!delayed_branch_p (ip))
6804         /* Make sure there is enough room to swap this instruction with
6805            a following jump instruction.  */
6806         frag_grow (6);
6807       add_fixed_insn (ip);
6808     }
6809   else
6810     {
6811       if (mips_opts.mips16
6812           && mips_opts.noreorder
6813           && delayed_branch_p (&history[0]))
6814         as_warn (_("extended instruction in delay slot"));
6815
6816       if (mips_relax.sequence)
6817         {
6818           /* If we've reached the end of this frag, turn it into a variant
6819              frag and record the information for the instructions we've
6820              written so far.  */
6821           if (frag_room () < 4)
6822             relax_close_frag ();
6823           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6824         }
6825
6826       if (mips_relax.sequence != 2)
6827         {
6828           if (mips_macro_warning.first_insn_sizes[0] == 0)
6829             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6830           mips_macro_warning.sizes[0] += insn_length (ip);
6831           mips_macro_warning.insns[0]++;
6832         }
6833       if (mips_relax.sequence != 1)
6834         {
6835           if (mips_macro_warning.first_insn_sizes[1] == 0)
6836             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6837           mips_macro_warning.sizes[1] += insn_length (ip);
6838           mips_macro_warning.insns[1]++;
6839         }
6840
6841       if (mips_opts.mips16)
6842         {
6843           ip->fixed_p = 1;
6844           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6845         }
6846       add_fixed_insn (ip);
6847     }
6848
6849   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6850     {
6851       bfd_reloc_code_real_type final_type[3];
6852       reloc_howto_type *howto0;
6853       reloc_howto_type *howto;
6854       int i;
6855
6856       /* Perform any necessary conversion to microMIPS relocations
6857          and find out how many relocations there actually are.  */
6858       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6859         final_type[i] = micromips_map_reloc (reloc_type[i]);
6860
6861       /* In a compound relocation, it is the final (outermost)
6862          operator that determines the relocated field.  */
6863       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6864       if (!howto)
6865         abort ();
6866
6867       if (i > 1)
6868         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6869       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6870                                  bfd_get_reloc_size (howto),
6871                                  address_expr,
6872                                  howto0 && howto0->pc_relative,
6873                                  final_type[0]);
6874
6875       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6876       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6877         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6878
6879       /* These relocations can have an addend that won't fit in
6880          4 octets for 64bit assembly.  */
6881       if (HAVE_64BIT_GPRS
6882           && ! howto->partial_inplace
6883           && (reloc_type[0] == BFD_RELOC_16
6884               || reloc_type[0] == BFD_RELOC_32
6885               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6886               || reloc_type[0] == BFD_RELOC_GPREL16
6887               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6888               || reloc_type[0] == BFD_RELOC_GPREL32
6889               || reloc_type[0] == BFD_RELOC_64
6890               || reloc_type[0] == BFD_RELOC_CTOR
6891               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6892               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6893               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6894               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6895               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6896               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6897               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6898               || hi16_reloc_p (reloc_type[0])
6899               || lo16_reloc_p (reloc_type[0])))
6900         ip->fixp[0]->fx_no_overflow = 1;
6901
6902       /* These relocations can have an addend that won't fit in 2 octets.  */
6903       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6904           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6905         ip->fixp[0]->fx_no_overflow = 1;
6906
6907       if (mips_relax.sequence)
6908         {
6909           if (mips_relax.first_fixup == 0)
6910             mips_relax.first_fixup = ip->fixp[0];
6911         }
6912       else if (reloc_needs_lo_p (*reloc_type))
6913         {
6914           struct mips_hi_fixup *hi_fixup;
6915
6916           /* Reuse the last entry if it already has a matching %lo.  */
6917           hi_fixup = mips_hi_fixup_list;
6918           if (hi_fixup == 0
6919               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6920             {
6921               hi_fixup = ((struct mips_hi_fixup *)
6922                           xmalloc (sizeof (struct mips_hi_fixup)));
6923               hi_fixup->next = mips_hi_fixup_list;
6924               mips_hi_fixup_list = hi_fixup;
6925             }
6926           hi_fixup->fixp = ip->fixp[0];
6927           hi_fixup->seg = now_seg;
6928         }
6929
6930       /* Add fixups for the second and third relocations, if given.
6931          Note that the ABI allows the second relocation to be
6932          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6933          moment we only use RSS_UNDEF, but we could add support
6934          for the others if it ever becomes necessary.  */
6935       for (i = 1; i < 3; i++)
6936         if (reloc_type[i] != BFD_RELOC_UNUSED)
6937           {
6938             ip->fixp[i] = fix_new (ip->frag, ip->where,
6939                                    ip->fixp[0]->fx_size, NULL, 0,
6940                                    FALSE, final_type[i]);
6941
6942             /* Use fx_tcbit to mark compound relocs.  */
6943             ip->fixp[0]->fx_tcbit = 1;
6944             ip->fixp[i]->fx_tcbit = 1;
6945           }
6946     }
6947   install_insn (ip);
6948
6949   /* Update the register mask information.  */
6950   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6951   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6952
6953   switch (method)
6954     {
6955     case APPEND_ADD:
6956       insert_into_history (0, 1, ip);
6957       break;
6958
6959     case APPEND_ADD_WITH_NOP:
6960       {
6961         struct mips_cl_insn *nop;
6962
6963         insert_into_history (0, 1, ip);
6964         nop = get_delay_slot_nop (ip);
6965         add_fixed_insn (nop);
6966         insert_into_history (0, 1, nop);
6967         if (mips_relax.sequence)
6968           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6969       }
6970       break;
6971
6972     case APPEND_ADD_COMPACT:
6973       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6974       gas_assert (mips_opts.mips16);
6975       ip->insn_opcode |= 0x0080;
6976       find_altered_mips16_opcode (ip);
6977       install_insn (ip);
6978       insert_into_history (0, 1, ip);
6979       break;
6980
6981     case APPEND_SWAP:
6982       {
6983         struct mips_cl_insn delay = history[0];
6984         if (mips_opts.mips16)
6985           {
6986             know (delay.frag == ip->frag);
6987             move_insn (ip, delay.frag, delay.where);
6988             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6989           }
6990         else if (relaxed_branch || delay.frag != ip->frag)
6991           {
6992             /* Add the delay slot instruction to the end of the
6993                current frag and shrink the fixed part of the
6994                original frag.  If the branch occupies the tail of
6995                the latter, move it backwards to cover the gap.  */
6996             delay.frag->fr_fix -= branch_disp;
6997             if (delay.frag == ip->frag)
6998               move_insn (ip, ip->frag, ip->where - branch_disp);
6999             add_fixed_insn (&delay);
7000           }
7001         else
7002           {
7003             move_insn (&delay, ip->frag,
7004                        ip->where - branch_disp + insn_length (ip));
7005             move_insn (ip, history[0].frag, history[0].where);
7006           }
7007         history[0] = *ip;
7008         delay.fixed_p = 1;
7009         insert_into_history (0, 1, &delay);
7010       }
7011       break;
7012     }
7013
7014   /* If we have just completed an unconditional branch, clear the history.  */
7015   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7016       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7017     {
7018       unsigned int i;
7019
7020       mips_no_prev_insn ();
7021
7022       for (i = 0; i < ARRAY_SIZE (history); i++)
7023         history[i].cleared_p = 1;
7024     }
7025
7026   /* We need to emit a label at the end of branch-likely macros.  */
7027   if (emit_branch_likely_macro)
7028     {
7029       emit_branch_likely_macro = FALSE;
7030       micromips_add_label ();
7031     }
7032
7033   /* We just output an insn, so the next one doesn't have a label.  */
7034   mips_clear_insn_labels ();
7035 }
7036
7037 /* Forget that there was any previous instruction or label.
7038    When BRANCH is true, the branch history is also flushed.  */
7039
7040 static void
7041 mips_no_prev_insn (void)
7042 {
7043   prev_nop_frag = NULL;
7044   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7045   mips_clear_insn_labels ();
7046 }
7047
7048 /* This function must be called before we emit something other than
7049    instructions.  It is like mips_no_prev_insn except that it inserts
7050    any NOPS that might be needed by previous instructions.  */
7051
7052 void
7053 mips_emit_delays (void)
7054 {
7055   if (! mips_opts.noreorder)
7056     {
7057       int nops = nops_for_insn (0, history, NULL);
7058       if (nops > 0)
7059         {
7060           while (nops-- > 0)
7061             add_fixed_insn (NOP_INSN);
7062           mips_move_text_labels ();
7063         }
7064     }
7065   mips_no_prev_insn ();
7066 }
7067
7068 /* Start a (possibly nested) noreorder block.  */
7069
7070 static void
7071 start_noreorder (void)
7072 {
7073   if (mips_opts.noreorder == 0)
7074     {
7075       unsigned int i;
7076       int nops;
7077
7078       /* None of the instructions before the .set noreorder can be moved.  */
7079       for (i = 0; i < ARRAY_SIZE (history); i++)
7080         history[i].fixed_p = 1;
7081
7082       /* Insert any nops that might be needed between the .set noreorder
7083          block and the previous instructions.  We will later remove any
7084          nops that turn out not to be needed.  */
7085       nops = nops_for_insn (0, history, NULL);
7086       if (nops > 0)
7087         {
7088           if (mips_optimize != 0)
7089             {
7090               /* Record the frag which holds the nop instructions, so
7091                  that we can remove them if we don't need them.  */
7092               frag_grow (nops * NOP_INSN_SIZE);
7093               prev_nop_frag = frag_now;
7094               prev_nop_frag_holds = nops;
7095               prev_nop_frag_required = 0;
7096               prev_nop_frag_since = 0;
7097             }
7098
7099           for (; nops > 0; --nops)
7100             add_fixed_insn (NOP_INSN);
7101
7102           /* Move on to a new frag, so that it is safe to simply
7103              decrease the size of prev_nop_frag.  */
7104           frag_wane (frag_now);
7105           frag_new (0);
7106           mips_move_text_labels ();
7107         }
7108       mips_mark_labels ();
7109       mips_clear_insn_labels ();
7110     }
7111   mips_opts.noreorder++;
7112   mips_any_noreorder = 1;
7113 }
7114
7115 /* End a nested noreorder block.  */
7116
7117 static void
7118 end_noreorder (void)
7119 {
7120   mips_opts.noreorder--;
7121   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7122     {
7123       /* Commit to inserting prev_nop_frag_required nops and go back to
7124          handling nop insertion the .set reorder way.  */
7125       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7126                                 * NOP_INSN_SIZE);
7127       insert_into_history (prev_nop_frag_since,
7128                            prev_nop_frag_required, NOP_INSN);
7129       prev_nop_frag = NULL;
7130     }
7131 }
7132
7133 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7134    higher bits unset.  */
7135
7136 static void
7137 normalize_constant_expr (expressionS *ex)
7138 {
7139   if (ex->X_op == O_constant
7140       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7141     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7142                         - 0x80000000);
7143 }
7144
7145 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7146    all higher bits unset.  */
7147
7148 static void
7149 normalize_address_expr (expressionS *ex)
7150 {
7151   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7152         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7153       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7154     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7155                         - 0x80000000);
7156 }
7157
7158 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7159    Return true if the match was successful.
7160
7161    OPCODE_EXTRA is a value that should be ORed into the opcode
7162    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7163    there are more alternatives after OPCODE and SOFT_MATCH is
7164    as for mips_arg_info.  */
7165
7166 static bfd_boolean
7167 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7168             struct mips_operand_token *tokens, unsigned int opcode_extra,
7169             bfd_boolean lax_match, bfd_boolean complete_p)
7170 {
7171   const char *args;
7172   struct mips_arg_info arg;
7173   const struct mips_operand *operand;
7174   char c;
7175
7176   imm_expr.X_op = O_absent;
7177   offset_expr.X_op = O_absent;
7178   offset_reloc[0] = BFD_RELOC_UNUSED;
7179   offset_reloc[1] = BFD_RELOC_UNUSED;
7180   offset_reloc[2] = BFD_RELOC_UNUSED;
7181
7182   create_insn (insn, opcode);
7183   /* When no opcode suffix is specified, assume ".xyzw". */
7184   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7185     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7186   else
7187     insn->insn_opcode |= opcode_extra;
7188   memset (&arg, 0, sizeof (arg));
7189   arg.insn = insn;
7190   arg.token = tokens;
7191   arg.argnum = 1;
7192   arg.last_regno = ILLEGAL_REG;
7193   arg.dest_regno = ILLEGAL_REG;
7194   arg.lax_match = lax_match;
7195   for (args = opcode->args;; ++args)
7196     {
7197       if (arg.token->type == OT_END)
7198         {
7199           /* Handle unary instructions in which only one operand is given.
7200              The source is then the same as the destination.  */
7201           if (arg.opnum == 1 && *args == ',')
7202             {
7203               operand = (mips_opts.micromips
7204                          ? decode_micromips_operand (args + 1)
7205                          : decode_mips_operand (args + 1));
7206               if (operand && mips_optional_operand_p (operand))
7207                 {
7208                   arg.token = tokens;
7209                   arg.argnum = 1;
7210                   continue;
7211                 }
7212             }
7213
7214           /* Treat elided base registers as $0.  */
7215           if (strcmp (args, "(b)") == 0)
7216             args += 3;
7217
7218           if (args[0] == '+')
7219             switch (args[1])
7220               {
7221               case 'K':
7222               case 'N':
7223                 /* The register suffix is optional. */
7224                 args += 2;
7225                 break;
7226               }
7227
7228           /* Fail the match if there were too few operands.  */
7229           if (*args)
7230             return FALSE;
7231
7232           /* Successful match.  */
7233           if (!complete_p)
7234             return TRUE;
7235           clear_insn_error ();
7236           if (arg.dest_regno == arg.last_regno
7237               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7238             {
7239               if (arg.opnum == 2)
7240                 set_insn_error
7241                   (0, _("source and destination must be different"));
7242               else if (arg.last_regno == 31)
7243                 set_insn_error
7244                   (0, _("a destination register must be supplied"));
7245             }
7246           else if (arg.last_regno == 31
7247                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7248                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7249             set_insn_error (0, _("the source register must not be $31"));
7250           check_completed_insn (&arg);
7251           return TRUE;
7252         }
7253
7254       /* Fail the match if the line has too many operands.   */
7255       if (*args == 0)
7256         return FALSE;
7257
7258       /* Handle characters that need to match exactly.  */
7259       if (*args == '(' || *args == ')' || *args == ',')
7260         {
7261           if (match_char (&arg, *args))
7262             continue;
7263           return FALSE;
7264         }
7265       if (*args == '#')
7266         {
7267           ++args;
7268           if (arg.token->type == OT_DOUBLE_CHAR
7269               && arg.token->u.ch == *args)
7270             {
7271               ++arg.token;
7272               continue;
7273             }
7274           return FALSE;
7275         }
7276
7277       /* Handle special macro operands.  Work out the properties of
7278          other operands.  */
7279       arg.opnum += 1;
7280       switch (*args)
7281         {
7282         case '+':
7283           switch (args[1])
7284             {
7285             case 'i':
7286               *offset_reloc = BFD_RELOC_MIPS_JMP;
7287               break;
7288             }
7289           break;
7290
7291         case 'I':
7292           if (!match_const_int (&arg, &imm_expr.X_add_number))
7293             return FALSE;
7294           imm_expr.X_op = O_constant;
7295           if (HAVE_32BIT_GPRS)
7296             normalize_constant_expr (&imm_expr);
7297           continue;
7298
7299         case 'A':
7300           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7301             {
7302               /* Assume that the offset has been elided and that what
7303                  we saw was a base register.  The match will fail later
7304                  if that assumption turns out to be wrong.  */
7305               offset_expr.X_op = O_constant;
7306               offset_expr.X_add_number = 0;
7307             }
7308           else
7309             {
7310               if (!match_expression (&arg, &offset_expr, offset_reloc))
7311                 return FALSE;
7312               normalize_address_expr (&offset_expr);
7313             }
7314           continue;
7315
7316         case 'F':
7317           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7318                                      8, TRUE))
7319             return FALSE;
7320           continue;
7321
7322         case 'L':
7323           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7324                                      8, FALSE))
7325             return FALSE;
7326           continue;
7327
7328         case 'f':
7329           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7330                                      4, TRUE))
7331             return FALSE;
7332           continue;
7333
7334         case 'l':
7335           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7336                                      4, FALSE))
7337             return FALSE;
7338           continue;
7339
7340         case 'p':
7341           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7342           break;
7343
7344         case 'a':
7345           *offset_reloc = BFD_RELOC_MIPS_JMP;
7346           break;
7347
7348         case 'm':
7349           gas_assert (mips_opts.micromips);
7350           c = args[1];
7351           switch (c)
7352             {
7353             case 'D':
7354             case 'E':
7355               if (!forced_insn_length)
7356                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7357               else if (c == 'D')
7358                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7359               else
7360                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7361               break;
7362             }
7363           break;
7364         }
7365
7366       operand = (mips_opts.micromips
7367                  ? decode_micromips_operand (args)
7368                  : decode_mips_operand (args));
7369       if (!operand)
7370         abort ();
7371
7372       /* Skip prefixes.  */
7373       if (*args == '+' || *args == 'm')
7374         args++;
7375
7376       if (mips_optional_operand_p (operand)
7377           && args[1] == ','
7378           && (arg.token[0].type != OT_REG
7379               || arg.token[1].type == OT_END))
7380         {
7381           /* Assume that the register has been elided and is the
7382              same as the first operand.  */
7383           arg.token = tokens;
7384           arg.argnum = 1;
7385         }
7386
7387       if (!match_operand (&arg, operand))
7388         return FALSE;
7389     }
7390 }
7391
7392 /* Like match_insn, but for MIPS16.  */
7393
7394 static bfd_boolean
7395 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7396                    struct mips_operand_token *tokens)
7397 {
7398   const char *args;
7399   const struct mips_operand *operand;
7400   const struct mips_operand *ext_operand;
7401   struct mips_arg_info arg;
7402   int relax_char;
7403
7404   create_insn (insn, opcode);
7405   imm_expr.X_op = O_absent;
7406   offset_expr.X_op = O_absent;
7407   offset_reloc[0] = BFD_RELOC_UNUSED;
7408   offset_reloc[1] = BFD_RELOC_UNUSED;
7409   offset_reloc[2] = BFD_RELOC_UNUSED;
7410   relax_char = 0;
7411
7412   memset (&arg, 0, sizeof (arg));
7413   arg.insn = insn;
7414   arg.token = tokens;
7415   arg.argnum = 1;
7416   arg.last_regno = ILLEGAL_REG;
7417   arg.dest_regno = ILLEGAL_REG;
7418   relax_char = 0;
7419   for (args = opcode->args;; ++args)
7420     {
7421       int c;
7422
7423       if (arg.token->type == OT_END)
7424         {
7425           offsetT value;
7426
7427           /* Handle unary instructions in which only one operand is given.
7428              The source is then the same as the destination.  */
7429           if (arg.opnum == 1 && *args == ',')
7430             {
7431               operand = decode_mips16_operand (args[1], FALSE);
7432               if (operand && mips_optional_operand_p (operand))
7433                 {
7434                   arg.token = tokens;
7435                   arg.argnum = 1;
7436                   continue;
7437                 }
7438             }
7439
7440           /* Fail the match if there were too few operands.  */
7441           if (*args)
7442             return FALSE;
7443
7444           /* Successful match.  Stuff the immediate value in now, if
7445              we can.  */
7446           clear_insn_error ();
7447           if (opcode->pinfo == INSN_MACRO)
7448             {
7449               gas_assert (relax_char == 0 || relax_char == 'p');
7450               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7451             }
7452           else if (relax_char
7453                    && offset_expr.X_op == O_constant
7454                    && calculate_reloc (*offset_reloc,
7455                                        offset_expr.X_add_number,
7456                                        &value))
7457             {
7458               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7459                             forced_insn_length, &insn->insn_opcode);
7460               offset_expr.X_op = O_absent;
7461               *offset_reloc = BFD_RELOC_UNUSED;
7462             }
7463           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7464             {
7465               if (forced_insn_length == 2)
7466                 set_insn_error (0, _("invalid unextended operand value"));
7467               forced_insn_length = 4;
7468               insn->insn_opcode |= MIPS16_EXTEND;
7469             }
7470           else if (relax_char)
7471             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7472
7473           check_completed_insn (&arg);
7474           return TRUE;
7475         }
7476
7477       /* Fail the match if the line has too many operands.   */
7478       if (*args == 0)
7479         return FALSE;
7480
7481       /* Handle characters that need to match exactly.  */
7482       if (*args == '(' || *args == ')' || *args == ',')
7483         {
7484           if (match_char (&arg, *args))
7485             continue;
7486           return FALSE;
7487         }
7488
7489       arg.opnum += 1;
7490       c = *args;
7491       switch (c)
7492         {
7493         case 'p':
7494         case 'q':
7495         case 'A':
7496         case 'B':
7497         case 'E':
7498           relax_char = c;
7499           break;
7500
7501         case 'I':
7502           if (!match_const_int (&arg, &imm_expr.X_add_number))
7503             return FALSE;
7504           imm_expr.X_op = O_constant;
7505           if (HAVE_32BIT_GPRS)
7506             normalize_constant_expr (&imm_expr);
7507           continue;
7508
7509         case 'a':
7510         case 'i':
7511           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7512           insn->insn_opcode <<= 16;
7513           break;
7514         }
7515
7516       operand = decode_mips16_operand (c, FALSE);
7517       if (!operand)
7518         abort ();
7519
7520       /* '6' is a special case.  It is used for BREAK and SDBBP,
7521          whose operands are only meaningful to the software that decodes
7522          them.  This means that there is no architectural reason why
7523          they cannot be prefixed by EXTEND, but in practice,
7524          exception handlers will only look at the instruction
7525          itself.  We therefore allow '6' to be extended when
7526          disassembling but not when assembling.  */
7527       if (operand->type != OP_PCREL && c != '6')
7528         {
7529           ext_operand = decode_mips16_operand (c, TRUE);
7530           if (operand != ext_operand)
7531             {
7532               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7533                 {
7534                   offset_expr.X_op = O_constant;
7535                   offset_expr.X_add_number = 0;
7536                   relax_char = c;
7537                   continue;
7538                 }
7539
7540               /* We need the OT_INTEGER check because some MIPS16
7541                  immediate variants are listed before the register ones.  */
7542               if (arg.token->type != OT_INTEGER
7543                   || !match_expression (&arg, &offset_expr, offset_reloc))
7544                 return FALSE;
7545
7546               /* '8' is used for SLTI(U) and has traditionally not
7547                  been allowed to take relocation operators.  */
7548               if (offset_reloc[0] != BFD_RELOC_UNUSED
7549                   && (ext_operand->size != 16 || c == '8'))
7550                 return FALSE;
7551
7552               relax_char = c;
7553               continue;
7554             }
7555         }
7556
7557       if (mips_optional_operand_p (operand)
7558           && args[1] == ','
7559           && (arg.token[0].type != OT_REG
7560               || arg.token[1].type == OT_END))
7561         {
7562           /* Assume that the register has been elided and is the
7563              same as the first operand.  */
7564           arg.token = tokens;
7565           arg.argnum = 1;
7566         }
7567
7568       if (!match_operand (&arg, operand))
7569         return FALSE;
7570     }
7571 }
7572
7573 /* Record that the current instruction is invalid for the current ISA.  */
7574
7575 static void
7576 match_invalid_for_isa (void)
7577 {
7578   set_insn_error_ss
7579     (0, _("opcode not supported on this processor: %s (%s)"),
7580      mips_cpu_info_from_arch (mips_opts.arch)->name,
7581      mips_cpu_info_from_isa (mips_opts.isa)->name);
7582 }
7583
7584 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
7585    Return true if a definite match or failure was found, storing any match
7586    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
7587    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
7588    tried and failed to match under normal conditions and now want to try a
7589    more relaxed match.  */
7590
7591 static bfd_boolean
7592 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7593              const struct mips_opcode *past, struct mips_operand_token *tokens,
7594              int opcode_extra, bfd_boolean lax_match)
7595 {
7596   const struct mips_opcode *opcode;
7597   const struct mips_opcode *invalid_delay_slot;
7598   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
7599
7600   /* Search for a match, ignoring alternatives that don't satisfy the
7601      current ISA or forced_length.  */
7602   invalid_delay_slot = 0;
7603   seen_valid_for_isa = FALSE;
7604   seen_valid_for_size = FALSE;
7605   opcode = first;
7606   do
7607     {
7608       gas_assert (strcmp (opcode->name, first->name) == 0);
7609       if (is_opcode_valid (opcode))
7610         {
7611           seen_valid_for_isa = TRUE;
7612           if (is_size_valid (opcode))
7613             {
7614               bfd_boolean delay_slot_ok;
7615
7616               seen_valid_for_size = TRUE;
7617               delay_slot_ok = is_delay_slot_valid (opcode);
7618               if (match_insn (insn, opcode, tokens, opcode_extra,
7619                               lax_match, delay_slot_ok))
7620                 {
7621                   if (!delay_slot_ok)
7622                     {
7623                       if (!invalid_delay_slot)
7624                         invalid_delay_slot = opcode;
7625                     }
7626                   else
7627                     return TRUE;
7628                 }
7629             }
7630         }
7631       ++opcode;
7632     }
7633   while (opcode < past && strcmp (opcode->name, first->name) == 0);
7634
7635   /* If the only matches we found had the wrong length for the delay slot,
7636      pick the first such match.  We'll issue an appropriate warning later.  */
7637   if (invalid_delay_slot)
7638     {
7639       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
7640                       lax_match, TRUE))
7641         return TRUE;
7642       abort ();
7643     }
7644
7645   /* Handle the case where we didn't try to match an instruction because
7646      all the alternatives were incompatible with the current ISA.  */
7647   if (!seen_valid_for_isa)
7648     {
7649       match_invalid_for_isa ();
7650       return TRUE;
7651     }
7652
7653   /* Handle the case where we didn't try to match an instruction because
7654      all the alternatives were of the wrong size.  */
7655   if (!seen_valid_for_size)
7656     {
7657       if (mips_opts.insn32)
7658         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
7659       else
7660         set_insn_error_i
7661           (0, _("unrecognized %d-bit version of microMIPS opcode"),
7662            8 * forced_insn_length);
7663       return TRUE;
7664     }
7665
7666   return FALSE;
7667 }
7668
7669 /* Like match_insns, but for MIPS16.  */
7670
7671 static bfd_boolean
7672 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7673                     struct mips_operand_token *tokens)
7674 {
7675   const struct mips_opcode *opcode;
7676   bfd_boolean seen_valid_for_isa;
7677
7678   /* Search for a match, ignoring alternatives that don't satisfy the
7679      current ISA.  There are no separate entries for extended forms so
7680      we deal with forced_length later.  */
7681   seen_valid_for_isa = FALSE;
7682   opcode = first;
7683   do
7684     {
7685       gas_assert (strcmp (opcode->name, first->name) == 0);
7686       if (is_opcode_valid_16 (opcode))
7687         {
7688           seen_valid_for_isa = TRUE;
7689           if (match_mips16_insn (insn, opcode, tokens))
7690             return TRUE;
7691         }
7692       ++opcode;
7693     }
7694   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
7695          && strcmp (opcode->name, first->name) == 0);
7696
7697   /* Handle the case where we didn't try to match an instruction because
7698      all the alternatives were incompatible with the current ISA.  */
7699   if (!seen_valid_for_isa)
7700     {
7701       match_invalid_for_isa ();
7702       return TRUE;
7703     }
7704
7705   return FALSE;
7706 }
7707
7708 /* Set up global variables for the start of a new macro.  */
7709
7710 static void
7711 macro_start (void)
7712 {
7713   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7714   memset (&mips_macro_warning.first_insn_sizes, 0,
7715           sizeof (mips_macro_warning.first_insn_sizes));
7716   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7717   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7718                                      && delayed_branch_p (&history[0]));
7719   switch (history[0].insn_mo->pinfo2
7720           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7721     {
7722     case INSN2_BRANCH_DELAY_32BIT:
7723       mips_macro_warning.delay_slot_length = 4;
7724       break;
7725     case INSN2_BRANCH_DELAY_16BIT:
7726       mips_macro_warning.delay_slot_length = 2;
7727       break;
7728     default:
7729       mips_macro_warning.delay_slot_length = 0;
7730       break;
7731     }
7732   mips_macro_warning.first_frag = NULL;
7733 }
7734
7735 /* Given that a macro is longer than one instruction or of the wrong size,
7736    return the appropriate warning for it.  Return null if no warning is
7737    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7738    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7739    and RELAX_NOMACRO.  */
7740
7741 static const char *
7742 macro_warning (relax_substateT subtype)
7743 {
7744   if (subtype & RELAX_DELAY_SLOT)
7745     return _("macro instruction expanded into multiple instructions"
7746              " in a branch delay slot");
7747   else if (subtype & RELAX_NOMACRO)
7748     return _("macro instruction expanded into multiple instructions");
7749   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
7750                       | RELAX_DELAY_SLOT_SIZE_SECOND))
7751     return ((subtype & RELAX_DELAY_SLOT_16BIT)
7752             ? _("macro instruction expanded into a wrong size instruction"
7753                 " in a 16-bit branch delay slot")
7754             : _("macro instruction expanded into a wrong size instruction"
7755                 " in a 32-bit branch delay slot"));
7756   else
7757     return 0;
7758 }
7759
7760 /* Finish up a macro.  Emit warnings as appropriate.  */
7761
7762 static void
7763 macro_end (void)
7764 {
7765   /* Relaxation warning flags.  */
7766   relax_substateT subtype = 0;
7767
7768   /* Check delay slot size requirements.  */
7769   if (mips_macro_warning.delay_slot_length == 2)
7770     subtype |= RELAX_DELAY_SLOT_16BIT;
7771   if (mips_macro_warning.delay_slot_length != 0)
7772     {
7773       if (mips_macro_warning.delay_slot_length
7774           != mips_macro_warning.first_insn_sizes[0])
7775         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
7776       if (mips_macro_warning.delay_slot_length
7777           != mips_macro_warning.first_insn_sizes[1])
7778         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
7779     }
7780
7781   /* Check instruction count requirements.  */
7782   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
7783     {
7784       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
7785         subtype |= RELAX_SECOND_LONGER;
7786       if (mips_opts.warn_about_macros)
7787         subtype |= RELAX_NOMACRO;
7788       if (mips_macro_warning.delay_slot_p)
7789         subtype |= RELAX_DELAY_SLOT;
7790     }
7791
7792   /* If both alternatives fail to fill a delay slot correctly,
7793      emit the warning now.  */
7794   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
7795       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
7796     {
7797       relax_substateT s;
7798       const char *msg;
7799
7800       s = subtype & (RELAX_DELAY_SLOT_16BIT
7801                      | RELAX_DELAY_SLOT_SIZE_FIRST
7802                      | RELAX_DELAY_SLOT_SIZE_SECOND);
7803       msg = macro_warning (s);
7804       if (msg != NULL)
7805         as_warn ("%s", msg);
7806       subtype &= ~s;
7807     }
7808
7809   /* If both implementations are longer than 1 instruction, then emit the
7810      warning now.  */
7811   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
7812     {
7813       relax_substateT s;
7814       const char *msg;
7815
7816       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
7817       msg = macro_warning (s);
7818       if (msg != NULL)
7819         as_warn ("%s", msg);
7820       subtype &= ~s;
7821     }
7822
7823   /* If any flags still set, then one implementation might need a warning
7824      and the other either will need one of a different kind or none at all.
7825      Pass any remaining flags over to relaxation.  */
7826   if (mips_macro_warning.first_frag != NULL)
7827     mips_macro_warning.first_frag->fr_subtype |= subtype;
7828 }
7829
7830 /* Instruction operand formats used in macros that vary between
7831    standard MIPS and microMIPS code.  */
7832
7833 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7834 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7835 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7836 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7837 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7838 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7839 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7840 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7841
7842 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7843 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7844 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7845 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7846 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7847 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7848 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7849 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7850
7851 /* Read a macro's relocation codes from *ARGS and store them in *R.
7852    The first argument in *ARGS will be either the code for a single
7853    relocation or -1 followed by the three codes that make up a
7854    composite relocation.  */
7855
7856 static void
7857 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7858 {
7859   int i, next;
7860
7861   next = va_arg (*args, int);
7862   if (next >= 0)
7863     r[0] = (bfd_reloc_code_real_type) next;
7864   else
7865     {
7866       for (i = 0; i < 3; i++)
7867         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7868       /* This function is only used for 16-bit relocation fields.
7869          To make the macro code simpler, treat an unrelocated value
7870          in the same way as BFD_RELOC_LO16.  */
7871       if (r[0] == BFD_RELOC_UNUSED)
7872         r[0] = BFD_RELOC_LO16;
7873     }
7874 }
7875
7876 /* Build an instruction created by a macro expansion.  This is passed
7877    a pointer to the count of instructions created so far, an
7878    expression, the name of the instruction to build, an operand format
7879    string, and corresponding arguments.  */
7880
7881 static void
7882 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
7883 {
7884   const struct mips_opcode *mo = NULL;
7885   bfd_reloc_code_real_type r[3];
7886   const struct mips_opcode *amo;
7887   const struct mips_operand *operand;
7888   struct hash_control *hash;
7889   struct mips_cl_insn insn;
7890   va_list args;
7891   unsigned int uval;
7892
7893   va_start (args, fmt);
7894
7895   if (mips_opts.mips16)
7896     {
7897       mips16_macro_build (ep, name, fmt, &args);
7898       va_end (args);
7899       return;
7900     }
7901
7902   r[0] = BFD_RELOC_UNUSED;
7903   r[1] = BFD_RELOC_UNUSED;
7904   r[2] = BFD_RELOC_UNUSED;
7905   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
7906   amo = (struct mips_opcode *) hash_find (hash, name);
7907   gas_assert (amo);
7908   gas_assert (strcmp (name, amo->name) == 0);
7909
7910   do
7911     {
7912       /* Search until we get a match for NAME.  It is assumed here that
7913          macros will never generate MDMX, MIPS-3D, or MT instructions.
7914          We try to match an instruction that fulfils the branch delay
7915          slot instruction length requirement (if any) of the previous
7916          instruction.  While doing this we record the first instruction
7917          seen that matches all the other conditions and use it anyway
7918          if the requirement cannot be met; we will issue an appropriate
7919          warning later on.  */
7920       if (strcmp (fmt, amo->args) == 0
7921           && amo->pinfo != INSN_MACRO
7922           && is_opcode_valid (amo)
7923           && is_size_valid (amo))
7924         {
7925           if (is_delay_slot_valid (amo))
7926             {
7927               mo = amo;
7928               break;
7929             }
7930           else if (!mo)
7931             mo = amo;
7932         }
7933
7934       ++amo;
7935       gas_assert (amo->name);
7936     }
7937   while (strcmp (name, amo->name) == 0);
7938
7939   gas_assert (mo);
7940   create_insn (&insn, mo);
7941   for (; *fmt; ++fmt)
7942     {
7943       switch (*fmt)
7944         {
7945         case ',':
7946         case '(':
7947         case ')':
7948         case 'z':
7949           break;
7950
7951         case 'i':
7952         case 'j':
7953           macro_read_relocs (&args, r);
7954           gas_assert (*r == BFD_RELOC_GPREL16
7955                       || *r == BFD_RELOC_MIPS_HIGHER
7956                       || *r == BFD_RELOC_HI16_S
7957                       || *r == BFD_RELOC_LO16
7958                       || *r == BFD_RELOC_MIPS_GOT_OFST);
7959           break;
7960
7961         case 'o':
7962           macro_read_relocs (&args, r);
7963           break;
7964
7965         case 'u':
7966           macro_read_relocs (&args, r);
7967           gas_assert (ep != NULL
7968                       && (ep->X_op == O_constant
7969                           || (ep->X_op == O_symbol
7970                               && (*r == BFD_RELOC_MIPS_HIGHEST
7971                                   || *r == BFD_RELOC_HI16_S
7972                                   || *r == BFD_RELOC_HI16
7973                                   || *r == BFD_RELOC_GPREL16
7974                                   || *r == BFD_RELOC_MIPS_GOT_HI16
7975                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
7976           break;
7977
7978         case 'p':
7979           gas_assert (ep != NULL);
7980
7981           /*
7982            * This allows macro() to pass an immediate expression for
7983            * creating short branches without creating a symbol.
7984            *
7985            * We don't allow branch relaxation for these branches, as
7986            * they should only appear in ".set nomacro" anyway.
7987            */
7988           if (ep->X_op == O_constant)
7989             {
7990               /* For microMIPS we always use relocations for branches.
7991                  So we should not resolve immediate values.  */
7992               gas_assert (!mips_opts.micromips);
7993
7994               if ((ep->X_add_number & 3) != 0)
7995                 as_bad (_("branch to misaligned address (0x%lx)"),
7996                         (unsigned long) ep->X_add_number);
7997               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
7998                 as_bad (_("branch address range overflow (0x%lx)"),
7999                         (unsigned long) ep->X_add_number);
8000               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8001               ep = NULL;
8002             }
8003           else
8004             *r = BFD_RELOC_16_PCREL_S2;
8005           break;
8006
8007         case 'a':
8008           gas_assert (ep != NULL);
8009           *r = BFD_RELOC_MIPS_JMP;
8010           break;
8011
8012         default:
8013           operand = (mips_opts.micromips
8014                      ? decode_micromips_operand (fmt)
8015                      : decode_mips_operand (fmt));
8016           if (!operand)
8017             abort ();
8018
8019           uval = va_arg (args, int);
8020           if (operand->type == OP_CLO_CLZ_DEST)
8021             uval |= (uval << 5);
8022           insn_insert_operand (&insn, operand, uval);
8023
8024           if (*fmt == '+' || *fmt == 'm')
8025             ++fmt;
8026           break;
8027         }
8028     }
8029   va_end (args);
8030   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8031
8032   append_insn (&insn, ep, r, TRUE);
8033 }
8034
8035 static void
8036 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8037                     va_list *args)
8038 {
8039   struct mips_opcode *mo;
8040   struct mips_cl_insn insn;
8041   const struct mips_operand *operand;
8042   bfd_reloc_code_real_type r[3]
8043     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8044
8045   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8046   gas_assert (mo);
8047   gas_assert (strcmp (name, mo->name) == 0);
8048
8049   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8050     {
8051       ++mo;
8052       gas_assert (mo->name);
8053       gas_assert (strcmp (name, mo->name) == 0);
8054     }
8055
8056   create_insn (&insn, mo);
8057   for (; *fmt; ++fmt)
8058     {
8059       int c;
8060
8061       c = *fmt;
8062       switch (c)
8063         {
8064         case ',':
8065         case '(':
8066         case ')':
8067           break;
8068
8069         case '0':
8070         case 'S':
8071         case 'P':
8072         case 'R':
8073           break;
8074
8075         case '<':
8076         case '>':
8077         case '4':
8078         case '5':
8079         case 'H':
8080         case 'W':
8081         case 'D':
8082         case 'j':
8083         case '8':
8084         case 'V':
8085         case 'C':
8086         case 'U':
8087         case 'k':
8088         case 'K':
8089         case 'p':
8090         case 'q':
8091           {
8092             offsetT value;
8093
8094             gas_assert (ep != NULL);
8095
8096             if (ep->X_op != O_constant)
8097               *r = (int) BFD_RELOC_UNUSED + c;
8098             else if (calculate_reloc (*r, ep->X_add_number, &value))
8099               {
8100                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8101                 ep = NULL;
8102                 *r = BFD_RELOC_UNUSED;
8103               }
8104           }
8105           break;
8106
8107         default:
8108           operand = decode_mips16_operand (c, FALSE);
8109           if (!operand)
8110             abort ();
8111
8112           insn_insert_operand (&insn, operand, va_arg (*args, int));
8113           break;
8114         }
8115     }
8116
8117   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8118
8119   append_insn (&insn, ep, r, TRUE);
8120 }
8121
8122 /*
8123  * Generate a "jalr" instruction with a relocation hint to the called
8124  * function.  This occurs in NewABI PIC code.
8125  */
8126 static void
8127 macro_build_jalr (expressionS *ep, int cprestore)
8128 {
8129   static const bfd_reloc_code_real_type jalr_relocs[2]
8130     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8131   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8132   const char *jalr;
8133   char *f = NULL;
8134
8135   if (MIPS_JALR_HINT_P (ep))
8136     {
8137       frag_grow (8);
8138       f = frag_more (0);
8139     }
8140   if (mips_opts.micromips)
8141     {
8142       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8143               ? "jalr" : "jalrs");
8144       if (MIPS_JALR_HINT_P (ep)
8145           || mips_opts.insn32
8146           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8147         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8148       else
8149         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8150     }
8151   else
8152     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8153   if (MIPS_JALR_HINT_P (ep))
8154     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8155 }
8156
8157 /*
8158  * Generate a "lui" instruction.
8159  */
8160 static void
8161 macro_build_lui (expressionS *ep, int regnum)
8162 {
8163   gas_assert (! mips_opts.mips16);
8164
8165   if (ep->X_op != O_constant)
8166     {
8167       gas_assert (ep->X_op == O_symbol);
8168       /* _gp_disp is a special case, used from s_cpload.
8169          __gnu_local_gp is used if mips_no_shared.  */
8170       gas_assert (mips_pic == NO_PIC
8171               || (! HAVE_NEWABI
8172                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8173               || (! mips_in_shared
8174                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8175                              "__gnu_local_gp") == 0));
8176     }
8177
8178   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8179 }
8180
8181 /* Generate a sequence of instructions to do a load or store from a constant
8182    offset off of a base register (breg) into/from a target register (treg),
8183    using AT if necessary.  */
8184 static void
8185 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8186                               int treg, int breg, int dbl)
8187 {
8188   gas_assert (ep->X_op == O_constant);
8189
8190   /* Sign-extending 32-bit constants makes their handling easier.  */
8191   if (!dbl)
8192     normalize_constant_expr (ep);
8193
8194   /* Right now, this routine can only handle signed 32-bit constants.  */
8195   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8196     as_warn (_("operand overflow"));
8197
8198   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8199     {
8200       /* Signed 16-bit offset will fit in the op.  Easy!  */
8201       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8202     }
8203   else
8204     {
8205       /* 32-bit offset, need multiple instructions and AT, like:
8206            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8207            addu     $tempreg,$tempreg,$breg
8208            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8209          to handle the complete offset.  */
8210       macro_build_lui (ep, AT);
8211       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8212       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8213
8214       if (!mips_opts.at)
8215         as_bad (_("macro used $at after \".set noat\""));
8216     }
8217 }
8218
8219 /*                      set_at()
8220  * Generates code to set the $at register to true (one)
8221  * if reg is less than the immediate expression.
8222  */
8223 static void
8224 set_at (int reg, int unsignedp)
8225 {
8226   if (imm_expr.X_add_number >= -0x8000
8227       && imm_expr.X_add_number < 0x8000)
8228     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8229                  AT, reg, BFD_RELOC_LO16);
8230   else
8231     {
8232       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
8233       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8234     }
8235 }
8236
8237 /* Count the leading zeroes by performing a binary chop. This is a
8238    bulky bit of source, but performance is a LOT better for the
8239    majority of values than a simple loop to count the bits:
8240        for (lcnt = 0; (lcnt < 32); lcnt++)
8241          if ((v) & (1 << (31 - lcnt)))
8242            break;
8243   However it is not code size friendly, and the gain will drop a bit
8244   on certain cached systems.
8245 */
8246 #define COUNT_TOP_ZEROES(v)             \
8247   (((v) & ~0xffff) == 0                 \
8248    ? ((v) & ~0xff) == 0                 \
8249      ? ((v) & ~0xf) == 0                \
8250        ? ((v) & ~0x3) == 0              \
8251          ? ((v) & ~0x1) == 0            \
8252            ? !(v)                       \
8253              ? 32                       \
8254              : 31                       \
8255            : 30                         \
8256          : ((v) & ~0x7) == 0            \
8257            ? 29                         \
8258            : 28                         \
8259        : ((v) & ~0x3f) == 0             \
8260          ? ((v) & ~0x1f) == 0           \
8261            ? 27                         \
8262            : 26                         \
8263          : ((v) & ~0x7f) == 0           \
8264            ? 25                         \
8265            : 24                         \
8266      : ((v) & ~0xfff) == 0              \
8267        ? ((v) & ~0x3ff) == 0            \
8268          ? ((v) & ~0x1ff) == 0          \
8269            ? 23                         \
8270            : 22                         \
8271          : ((v) & ~0x7ff) == 0          \
8272            ? 21                         \
8273            : 20                         \
8274        : ((v) & ~0x3fff) == 0           \
8275          ? ((v) & ~0x1fff) == 0         \
8276            ? 19                         \
8277            : 18                         \
8278          : ((v) & ~0x7fff) == 0         \
8279            ? 17                         \
8280            : 16                         \
8281    : ((v) & ~0xffffff) == 0             \
8282      ? ((v) & ~0xfffff) == 0            \
8283        ? ((v) & ~0x3ffff) == 0          \
8284          ? ((v) & ~0x1ffff) == 0        \
8285            ? 15                         \
8286            : 14                         \
8287          : ((v) & ~0x7ffff) == 0        \
8288            ? 13                         \
8289            : 12                         \
8290        : ((v) & ~0x3fffff) == 0         \
8291          ? ((v) & ~0x1fffff) == 0       \
8292            ? 11                         \
8293            : 10                         \
8294          : ((v) & ~0x7fffff) == 0       \
8295            ? 9                          \
8296            : 8                          \
8297      : ((v) & ~0xfffffff) == 0          \
8298        ? ((v) & ~0x3ffffff) == 0        \
8299          ? ((v) & ~0x1ffffff) == 0      \
8300            ? 7                          \
8301            : 6                          \
8302          : ((v) & ~0x7ffffff) == 0      \
8303            ? 5                          \
8304            : 4                          \
8305        : ((v) & ~0x3fffffff) == 0       \
8306          ? ((v) & ~0x1fffffff) == 0     \
8307            ? 3                          \
8308            : 2                          \
8309          : ((v) & ~0x7fffffff) == 0     \
8310            ? 1                          \
8311            : 0)
8312
8313 /*                      load_register()
8314  *  This routine generates the least number of instructions necessary to load
8315  *  an absolute expression value into a register.
8316  */
8317 static void
8318 load_register (int reg, expressionS *ep, int dbl)
8319 {
8320   int freg;
8321   expressionS hi32, lo32;
8322
8323   if (ep->X_op != O_big)
8324     {
8325       gas_assert (ep->X_op == O_constant);
8326
8327       /* Sign-extending 32-bit constants makes their handling easier.  */
8328       if (!dbl)
8329         normalize_constant_expr (ep);
8330
8331       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8332         {
8333           /* We can handle 16 bit signed values with an addiu to
8334              $zero.  No need to ever use daddiu here, since $zero and
8335              the result are always correct in 32 bit mode.  */
8336           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8337           return;
8338         }
8339       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8340         {
8341           /* We can handle 16 bit unsigned values with an ori to
8342              $zero.  */
8343           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8344           return;
8345         }
8346       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8347         {
8348           /* 32 bit values require an lui.  */
8349           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8350           if ((ep->X_add_number & 0xffff) != 0)
8351             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8352           return;
8353         }
8354     }
8355
8356   /* The value is larger than 32 bits.  */
8357
8358   if (!dbl || HAVE_32BIT_GPRS)
8359     {
8360       char value[32];
8361
8362       sprintf_vma (value, ep->X_add_number);
8363       as_bad (_("number (0x%s) larger than 32 bits"), value);
8364       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8365       return;
8366     }
8367
8368   if (ep->X_op != O_big)
8369     {
8370       hi32 = *ep;
8371       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8372       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8373       hi32.X_add_number &= 0xffffffff;
8374       lo32 = *ep;
8375       lo32.X_add_number &= 0xffffffff;
8376     }
8377   else
8378     {
8379       gas_assert (ep->X_add_number > 2);
8380       if (ep->X_add_number == 3)
8381         generic_bignum[3] = 0;
8382       else if (ep->X_add_number > 4)
8383         as_bad (_("number larger than 64 bits"));
8384       lo32.X_op = O_constant;
8385       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8386       hi32.X_op = O_constant;
8387       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8388     }
8389
8390   if (hi32.X_add_number == 0)
8391     freg = 0;
8392   else
8393     {
8394       int shift, bit;
8395       unsigned long hi, lo;
8396
8397       if (hi32.X_add_number == (offsetT) 0xffffffff)
8398         {
8399           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8400             {
8401               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8402               return;
8403             }
8404           if (lo32.X_add_number & 0x80000000)
8405             {
8406               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8407               if (lo32.X_add_number & 0xffff)
8408                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8409               return;
8410             }
8411         }
8412
8413       /* Check for 16bit shifted constant.  We know that hi32 is
8414          non-zero, so start the mask on the first bit of the hi32
8415          value.  */
8416       shift = 17;
8417       do
8418         {
8419           unsigned long himask, lomask;
8420
8421           if (shift < 32)
8422             {
8423               himask = 0xffff >> (32 - shift);
8424               lomask = (0xffff << shift) & 0xffffffff;
8425             }
8426           else
8427             {
8428               himask = 0xffff << (shift - 32);
8429               lomask = 0;
8430             }
8431           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8432               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8433             {
8434               expressionS tmp;
8435
8436               tmp.X_op = O_constant;
8437               if (shift < 32)
8438                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8439                                     | (lo32.X_add_number >> shift));
8440               else
8441                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8442               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8443               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8444                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8445               return;
8446             }
8447           ++shift;
8448         }
8449       while (shift <= (64 - 16));
8450
8451       /* Find the bit number of the lowest one bit, and store the
8452          shifted value in hi/lo.  */
8453       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8454       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8455       if (lo != 0)
8456         {
8457           bit = 0;
8458           while ((lo & 1) == 0)
8459             {
8460               lo >>= 1;
8461               ++bit;
8462             }
8463           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8464           hi >>= bit;
8465         }
8466       else
8467         {
8468           bit = 32;
8469           while ((hi & 1) == 0)
8470             {
8471               hi >>= 1;
8472               ++bit;
8473             }
8474           lo = hi;
8475           hi = 0;
8476         }
8477
8478       /* Optimize if the shifted value is a (power of 2) - 1.  */
8479       if ((hi == 0 && ((lo + 1) & lo) == 0)
8480           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8481         {
8482           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8483           if (shift != 0)
8484             {
8485               expressionS tmp;
8486
8487               /* This instruction will set the register to be all
8488                  ones.  */
8489               tmp.X_op = O_constant;
8490               tmp.X_add_number = (offsetT) -1;
8491               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8492               if (bit != 0)
8493                 {
8494                   bit += shift;
8495                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8496                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8497                 }
8498               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8499                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8500               return;
8501             }
8502         }
8503
8504       /* Sign extend hi32 before calling load_register, because we can
8505          generally get better code when we load a sign extended value.  */
8506       if ((hi32.X_add_number & 0x80000000) != 0)
8507         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8508       load_register (reg, &hi32, 0);
8509       freg = reg;
8510     }
8511   if ((lo32.X_add_number & 0xffff0000) == 0)
8512     {
8513       if (freg != 0)
8514         {
8515           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8516           freg = reg;
8517         }
8518     }
8519   else
8520     {
8521       expressionS mid16;
8522
8523       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8524         {
8525           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8526           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8527           return;
8528         }
8529
8530       if (freg != 0)
8531         {
8532           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8533           freg = reg;
8534         }
8535       mid16 = lo32;
8536       mid16.X_add_number >>= 16;
8537       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8538       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8539       freg = reg;
8540     }
8541   if ((lo32.X_add_number & 0xffff) != 0)
8542     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8543 }
8544
8545 static inline void
8546 load_delay_nop (void)
8547 {
8548   if (!gpr_interlocks)
8549     macro_build (NULL, "nop", "");
8550 }
8551
8552 /* Load an address into a register.  */
8553
8554 static void
8555 load_address (int reg, expressionS *ep, int *used_at)
8556 {
8557   if (ep->X_op != O_constant
8558       && ep->X_op != O_symbol)
8559     {
8560       as_bad (_("expression too complex"));
8561       ep->X_op = O_constant;
8562     }
8563
8564   if (ep->X_op == O_constant)
8565     {
8566       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8567       return;
8568     }
8569
8570   if (mips_pic == NO_PIC)
8571     {
8572       /* If this is a reference to a GP relative symbol, we want
8573            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8574          Otherwise we want
8575            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8576            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8577          If we have an addend, we always use the latter form.
8578
8579          With 64bit address space and a usable $at we want
8580            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8581            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8582            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8583            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8584            dsll32       $reg,0
8585            daddu        $reg,$reg,$at
8586
8587          If $at is already in use, we use a path which is suboptimal
8588          on superscalar processors.
8589            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8590            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8591            dsll         $reg,16
8592            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8593            dsll         $reg,16
8594            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8595
8596          For GP relative symbols in 64bit address space we can use
8597          the same sequence as in 32bit address space.  */
8598       if (HAVE_64BIT_SYMBOLS)
8599         {
8600           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8601               && !nopic_need_relax (ep->X_add_symbol, 1))
8602             {
8603               relax_start (ep->X_add_symbol);
8604               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8605                            mips_gp_register, BFD_RELOC_GPREL16);
8606               relax_switch ();
8607             }
8608
8609           if (*used_at == 0 && mips_opts.at)
8610             {
8611               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8612               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8613               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8614                            BFD_RELOC_MIPS_HIGHER);
8615               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8616               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8617               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8618               *used_at = 1;
8619             }
8620           else
8621             {
8622               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8623               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8624                            BFD_RELOC_MIPS_HIGHER);
8625               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8626               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8627               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8628               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8629             }
8630
8631           if (mips_relax.sequence)
8632             relax_end ();
8633         }
8634       else
8635         {
8636           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8637               && !nopic_need_relax (ep->X_add_symbol, 1))
8638             {
8639               relax_start (ep->X_add_symbol);
8640               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8641                            mips_gp_register, BFD_RELOC_GPREL16);
8642               relax_switch ();
8643             }
8644           macro_build_lui (ep, reg);
8645           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8646                        reg, reg, BFD_RELOC_LO16);
8647           if (mips_relax.sequence)
8648             relax_end ();
8649         }
8650     }
8651   else if (!mips_big_got)
8652     {
8653       expressionS ex;
8654
8655       /* If this is a reference to an external symbol, we want
8656            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8657          Otherwise we want
8658            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8659            nop
8660            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8661          If there is a constant, it must be added in after.
8662
8663          If we have NewABI, we want
8664            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8665          unless we're referencing a global symbol with a non-zero
8666          offset, in which case cst must be added separately.  */
8667       if (HAVE_NEWABI)
8668         {
8669           if (ep->X_add_number)
8670             {
8671               ex.X_add_number = ep->X_add_number;
8672               ep->X_add_number = 0;
8673               relax_start (ep->X_add_symbol);
8674               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8675                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8676               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8677                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8678               ex.X_op = O_constant;
8679               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8680                            reg, reg, BFD_RELOC_LO16);
8681               ep->X_add_number = ex.X_add_number;
8682               relax_switch ();
8683             }
8684           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8685                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8686           if (mips_relax.sequence)
8687             relax_end ();
8688         }
8689       else
8690         {
8691           ex.X_add_number = ep->X_add_number;
8692           ep->X_add_number = 0;
8693           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8694                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8695           load_delay_nop ();
8696           relax_start (ep->X_add_symbol);
8697           relax_switch ();
8698           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8699                        BFD_RELOC_LO16);
8700           relax_end ();
8701
8702           if (ex.X_add_number != 0)
8703             {
8704               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8705                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8706               ex.X_op = O_constant;
8707               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8708                            reg, reg, BFD_RELOC_LO16);
8709             }
8710         }
8711     }
8712   else if (mips_big_got)
8713     {
8714       expressionS ex;
8715
8716       /* This is the large GOT case.  If this is a reference to an
8717          external symbol, we want
8718            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8719            addu         $reg,$reg,$gp
8720            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8721
8722          Otherwise, for a reference to a local symbol in old ABI, we want
8723            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8724            nop
8725            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8726          If there is a constant, it must be added in after.
8727
8728          In the NewABI, for local symbols, with or without offsets, we want:
8729            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8730            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8731       */
8732       if (HAVE_NEWABI)
8733         {
8734           ex.X_add_number = ep->X_add_number;
8735           ep->X_add_number = 0;
8736           relax_start (ep->X_add_symbol);
8737           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8738           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8739                        reg, reg, mips_gp_register);
8740           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8741                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8742           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8743             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8744           else if (ex.X_add_number)
8745             {
8746               ex.X_op = O_constant;
8747               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8748                            BFD_RELOC_LO16);
8749             }
8750
8751           ep->X_add_number = ex.X_add_number;
8752           relax_switch ();
8753           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8754                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8755           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8756                        BFD_RELOC_MIPS_GOT_OFST);
8757           relax_end ();
8758         }
8759       else
8760         {
8761           ex.X_add_number = ep->X_add_number;
8762           ep->X_add_number = 0;
8763           relax_start (ep->X_add_symbol);
8764           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8765           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8766                        reg, reg, mips_gp_register);
8767           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8768                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8769           relax_switch ();
8770           if (reg_needs_delay (mips_gp_register))
8771             {
8772               /* We need a nop before loading from $gp.  This special
8773                  check is required because the lui which starts the main
8774                  instruction stream does not refer to $gp, and so will not
8775                  insert the nop which may be required.  */
8776               macro_build (NULL, "nop", "");
8777             }
8778           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8779                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8780           load_delay_nop ();
8781           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8782                        BFD_RELOC_LO16);
8783           relax_end ();
8784
8785           if (ex.X_add_number != 0)
8786             {
8787               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8788                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8789               ex.X_op = O_constant;
8790               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8791                            BFD_RELOC_LO16);
8792             }
8793         }
8794     }
8795   else
8796     abort ();
8797
8798   if (!mips_opts.at && *used_at == 1)
8799     as_bad (_("macro used $at after \".set noat\""));
8800 }
8801
8802 /* Move the contents of register SOURCE into register DEST.  */
8803
8804 static void
8805 move_register (int dest, int source)
8806 {
8807   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8808      instruction specifically requires a 32-bit one.  */
8809   if (mips_opts.micromips
8810       && !mips_opts.insn32
8811       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8812     macro_build (NULL, "move", "mp,mj", dest, source);
8813   else
8814     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
8815                  dest, source, 0);
8816 }
8817
8818 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8819    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8820    The two alternatives are:
8821
8822    Global symbol                Local sybmol
8823    -------------                ------------
8824    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8825    ...                          ...
8826    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8827
8828    load_got_offset emits the first instruction and add_got_offset
8829    emits the second for a 16-bit offset or add_got_offset_hilo emits
8830    a sequence to add a 32-bit offset using a scratch register.  */
8831
8832 static void
8833 load_got_offset (int dest, expressionS *local)
8834 {
8835   expressionS global;
8836
8837   global = *local;
8838   global.X_add_number = 0;
8839
8840   relax_start (local->X_add_symbol);
8841   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8842                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8843   relax_switch ();
8844   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8845                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8846   relax_end ();
8847 }
8848
8849 static void
8850 add_got_offset (int dest, expressionS *local)
8851 {
8852   expressionS global;
8853
8854   global.X_op = O_constant;
8855   global.X_op_symbol = NULL;
8856   global.X_add_symbol = NULL;
8857   global.X_add_number = local->X_add_number;
8858
8859   relax_start (local->X_add_symbol);
8860   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8861                dest, dest, BFD_RELOC_LO16);
8862   relax_switch ();
8863   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8864   relax_end ();
8865 }
8866
8867 static void
8868 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8869 {
8870   expressionS global;
8871   int hold_mips_optimize;
8872
8873   global.X_op = O_constant;
8874   global.X_op_symbol = NULL;
8875   global.X_add_symbol = NULL;
8876   global.X_add_number = local->X_add_number;
8877
8878   relax_start (local->X_add_symbol);
8879   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
8880   relax_switch ();
8881   /* Set mips_optimize around the lui instruction to avoid
8882      inserting an unnecessary nop after the lw.  */
8883   hold_mips_optimize = mips_optimize;
8884   mips_optimize = 2;
8885   macro_build_lui (&global, tmp);
8886   mips_optimize = hold_mips_optimize;
8887   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
8888   relax_end ();
8889
8890   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
8891 }
8892
8893 /* Emit a sequence of instructions to emulate a branch likely operation.
8894    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
8895    is its complementing branch with the original condition negated.
8896    CALL is set if the original branch specified the link operation.
8897    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
8898
8899    Code like this is produced in the noreorder mode:
8900
8901         BRNEG   <args>, 1f
8902          nop
8903         b       <sym>
8904          delay slot (executed only if branch taken)
8905     1:
8906
8907    or, if CALL is set:
8908
8909         BRNEG   <args>, 1f
8910          nop
8911         bal     <sym>
8912          delay slot (executed only if branch taken)
8913     1:
8914
8915    In the reorder mode the delay slot would be filled with a nop anyway,
8916    so code produced is simply:
8917
8918         BR      <args>, <sym>
8919          nop
8920
8921    This function is used when producing code for the microMIPS ASE that
8922    does not implement branch likely instructions in hardware.  */
8923
8924 static void
8925 macro_build_branch_likely (const char *br, const char *brneg,
8926                            int call, expressionS *ep, const char *fmt,
8927                            unsigned int sreg, unsigned int treg)
8928 {
8929   int noreorder = mips_opts.noreorder;
8930   expressionS expr1;
8931
8932   gas_assert (mips_opts.micromips);
8933   start_noreorder ();
8934   if (noreorder)
8935     {
8936       micromips_label_expr (&expr1);
8937       macro_build (&expr1, brneg, fmt, sreg, treg);
8938       macro_build (NULL, "nop", "");
8939       macro_build (ep, call ? "bal" : "b", "p");
8940
8941       /* Set to true so that append_insn adds a label.  */
8942       emit_branch_likely_macro = TRUE;
8943     }
8944   else
8945     {
8946       macro_build (ep, br, fmt, sreg, treg);
8947       macro_build (NULL, "nop", "");
8948     }
8949   end_noreorder ();
8950 }
8951
8952 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
8953    the condition code tested.  EP specifies the branch target.  */
8954
8955 static void
8956 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
8957 {
8958   const int call = 0;
8959   const char *brneg;
8960   const char *br;
8961
8962   switch (type)
8963     {
8964     case M_BC1FL:
8965       br = "bc1f";
8966       brneg = "bc1t";
8967       break;
8968     case M_BC1TL:
8969       br = "bc1t";
8970       brneg = "bc1f";
8971       break;
8972     case M_BC2FL:
8973       br = "bc2f";
8974       brneg = "bc2t";
8975       break;
8976     case M_BC2TL:
8977       br = "bc2t";
8978       brneg = "bc2f";
8979       break;
8980     default:
8981       abort ();
8982     }
8983   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
8984 }
8985
8986 /* Emit a two-argument branch macro specified by TYPE, using SREG as
8987    the register tested.  EP specifies the branch target.  */
8988
8989 static void
8990 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
8991 {
8992   const char *brneg = NULL;
8993   const char *br;
8994   int call = 0;
8995
8996   switch (type)
8997     {
8998     case M_BGEZ:
8999       br = "bgez";
9000       break;
9001     case M_BGEZL:
9002       br = mips_opts.micromips ? "bgez" : "bgezl";
9003       brneg = "bltz";
9004       break;
9005     case M_BGEZALL:
9006       gas_assert (mips_opts.micromips);
9007       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9008       brneg = "bltz";
9009       call = 1;
9010       break;
9011     case M_BGTZ:
9012       br = "bgtz";
9013       break;
9014     case M_BGTZL:
9015       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9016       brneg = "blez";
9017       break;
9018     case M_BLEZ:
9019       br = "blez";
9020       break;
9021     case M_BLEZL:
9022       br = mips_opts.micromips ? "blez" : "blezl";
9023       brneg = "bgtz";
9024       break;
9025     case M_BLTZ:
9026       br = "bltz";
9027       break;
9028     case M_BLTZL:
9029       br = mips_opts.micromips ? "bltz" : "bltzl";
9030       brneg = "bgez";
9031       break;
9032     case M_BLTZALL:
9033       gas_assert (mips_opts.micromips);
9034       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9035       brneg = "bgez";
9036       call = 1;
9037       break;
9038     default:
9039       abort ();
9040     }
9041   if (mips_opts.micromips && brneg)
9042     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9043   else
9044     macro_build (ep, br, "s,p", sreg);
9045 }
9046
9047 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9048    TREG as the registers tested.  EP specifies the branch target.  */
9049
9050 static void
9051 macro_build_branch_rsrt (int type, expressionS *ep,
9052                          unsigned int sreg, unsigned int treg)
9053 {
9054   const char *brneg = NULL;
9055   const int call = 0;
9056   const char *br;
9057
9058   switch (type)
9059     {
9060     case M_BEQ:
9061     case M_BEQ_I:
9062       br = "beq";
9063       break;
9064     case M_BEQL:
9065     case M_BEQL_I:
9066       br = mips_opts.micromips ? "beq" : "beql";
9067       brneg = "bne";
9068       break;
9069     case M_BNE:
9070     case M_BNE_I:
9071       br = "bne";
9072       break;
9073     case M_BNEL:
9074     case M_BNEL_I:
9075       br = mips_opts.micromips ? "bne" : "bnel";
9076       brneg = "beq";
9077       break;
9078     default:
9079       abort ();
9080     }
9081   if (mips_opts.micromips && brneg)
9082     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9083   else
9084     macro_build (ep, br, "s,t,p", sreg, treg);
9085 }
9086
9087 /* Return the high part that should be loaded in order to make the low
9088    part of VALUE accessible using an offset of OFFBITS bits.  */
9089
9090 static offsetT
9091 offset_high_part (offsetT value, unsigned int offbits)
9092 {
9093   offsetT bias;
9094   addressT low_mask;
9095
9096   if (offbits == 0)
9097     return value;
9098   bias = 1 << (offbits - 1);
9099   low_mask = bias * 2 - 1;
9100   return (value + bias) & ~low_mask;
9101 }
9102
9103 /* Return true if the value stored in offset_expr and offset_reloc
9104    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9105    amount that the caller wants to add without inducing overflow
9106    and ALIGN is the known alignment of the value in bytes.  */
9107
9108 static bfd_boolean
9109 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9110 {
9111   if (offbits == 16)
9112     {
9113       /* Accept any relocation operator if overflow isn't a concern.  */
9114       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9115         return TRUE;
9116
9117       /* These relocations are guaranteed not to overflow in correct links.  */
9118       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9119           || gprel16_reloc_p (*offset_reloc))
9120         return TRUE;
9121     }
9122   if (offset_expr.X_op == O_constant
9123       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9124       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9125     return TRUE;
9126   return FALSE;
9127 }
9128
9129 /*
9130  *                      Build macros
9131  *   This routine implements the seemingly endless macro or synthesized
9132  * instructions and addressing modes in the mips assembly language. Many
9133  * of these macros are simple and are similar to each other. These could
9134  * probably be handled by some kind of table or grammar approach instead of
9135  * this verbose method. Others are not simple macros but are more like
9136  * optimizing code generation.
9137  *   One interesting optimization is when several store macros appear
9138  * consecutively that would load AT with the upper half of the same address.
9139  * The ensuing load upper instructions are ommited. This implies some kind
9140  * of global optimization. We currently only optimize within a single macro.
9141  *   For many of the load and store macros if the address is specified as a
9142  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9143  * first load register 'at' with zero and use it as the base register. The
9144  * mips assembler simply uses register $zero. Just one tiny optimization
9145  * we're missing.
9146  */
9147 static void
9148 macro (struct mips_cl_insn *ip, char *str)
9149 {
9150   const struct mips_operand_array *operands;
9151   unsigned int breg, i;
9152   unsigned int tempreg;
9153   int mask;
9154   int used_at = 0;
9155   expressionS label_expr;
9156   expressionS expr1;
9157   expressionS *ep;
9158   const char *s;
9159   const char *s2;
9160   const char *fmt;
9161   int likely = 0;
9162   int coproc = 0;
9163   int offbits = 16;
9164   int call = 0;
9165   int jals = 0;
9166   int dbl = 0;
9167   int imm = 0;
9168   int ust = 0;
9169   int lp = 0;
9170   bfd_boolean large_offset;
9171   int off;
9172   int hold_mips_optimize;
9173   unsigned int align;
9174   unsigned int op[MAX_OPERANDS];
9175
9176   gas_assert (! mips_opts.mips16);
9177
9178   operands = insn_operands (ip);
9179   for (i = 0; i < MAX_OPERANDS; i++)
9180     if (operands->operand[i])
9181       op[i] = insn_extract_operand (ip, operands->operand[i]);
9182     else
9183       op[i] = -1;
9184
9185   mask = ip->insn_mo->mask;
9186
9187   label_expr.X_op = O_constant;
9188   label_expr.X_op_symbol = NULL;
9189   label_expr.X_add_symbol = NULL;
9190   label_expr.X_add_number = 0;
9191
9192   expr1.X_op = O_constant;
9193   expr1.X_op_symbol = NULL;
9194   expr1.X_add_symbol = NULL;
9195   expr1.X_add_number = 1;
9196   align = 1;
9197
9198   switch (mask)
9199     {
9200     case M_DABS:
9201       dbl = 1;
9202     case M_ABS:
9203       /*    bgez    $a0,1f
9204             move    v0,$a0
9205             sub     v0,$zero,$a0
9206          1:
9207        */
9208
9209       start_noreorder ();
9210
9211       if (mips_opts.micromips)
9212         micromips_label_expr (&label_expr);
9213       else
9214         label_expr.X_add_number = 8;
9215       macro_build (&label_expr, "bgez", "s,p", op[1]);
9216       if (op[0] == op[1])
9217         macro_build (NULL, "nop", "");
9218       else
9219         move_register (op[0], op[1]);
9220       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9221       if (mips_opts.micromips)
9222         micromips_add_label ();
9223
9224       end_noreorder ();
9225       break;
9226
9227     case M_ADD_I:
9228       s = "addi";
9229       s2 = "add";
9230       goto do_addi;
9231     case M_ADDU_I:
9232       s = "addiu";
9233       s2 = "addu";
9234       goto do_addi;
9235     case M_DADD_I:
9236       dbl = 1;
9237       s = "daddi";
9238       s2 = "dadd";
9239       if (!mips_opts.micromips)
9240         goto do_addi;
9241       if (imm_expr.X_add_number >= -0x200
9242           && imm_expr.X_add_number < 0x200)
9243         {
9244           macro_build (NULL, s, "t,r,.", op[0], op[1],
9245                        (int) imm_expr.X_add_number);
9246           break;
9247         }
9248       goto do_addi_i;
9249     case M_DADDU_I:
9250       dbl = 1;
9251       s = "daddiu";
9252       s2 = "daddu";
9253     do_addi:
9254       if (imm_expr.X_add_number >= -0x8000
9255           && imm_expr.X_add_number < 0x8000)
9256         {
9257           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9258           break;
9259         }
9260     do_addi_i:
9261       used_at = 1;
9262       load_register (AT, &imm_expr, dbl);
9263       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9264       break;
9265
9266     case M_AND_I:
9267       s = "andi";
9268       s2 = "and";
9269       goto do_bit;
9270     case M_OR_I:
9271       s = "ori";
9272       s2 = "or";
9273       goto do_bit;
9274     case M_NOR_I:
9275       s = "";
9276       s2 = "nor";
9277       goto do_bit;
9278     case M_XOR_I:
9279       s = "xori";
9280       s2 = "xor";
9281     do_bit:
9282       if (imm_expr.X_add_number >= 0
9283           && imm_expr.X_add_number < 0x10000)
9284         {
9285           if (mask != M_NOR_I)
9286             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9287           else
9288             {
9289               macro_build (&imm_expr, "ori", "t,r,i",
9290                            op[0], op[1], BFD_RELOC_LO16);
9291               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9292             }
9293           break;
9294         }
9295
9296       used_at = 1;
9297       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9298       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9299       break;
9300
9301     case M_BALIGN:
9302       switch (imm_expr.X_add_number)
9303         {
9304         case 0:
9305           macro_build (NULL, "nop", "");
9306           break;
9307         case 2:
9308           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9309           break;
9310         case 1:
9311         case 3:
9312           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9313                        (int) imm_expr.X_add_number);
9314           break;
9315         default:
9316           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9317                   (unsigned long) imm_expr.X_add_number);
9318           break;
9319         }
9320       break;
9321
9322     case M_BC1FL:
9323     case M_BC1TL:
9324     case M_BC2FL:
9325     case M_BC2TL:
9326       gas_assert (mips_opts.micromips);
9327       macro_build_branch_ccl (mask, &offset_expr,
9328                               EXTRACT_OPERAND (1, BCC, *ip));
9329       break;
9330
9331     case M_BEQ_I:
9332     case M_BEQL_I:
9333     case M_BNE_I:
9334     case M_BNEL_I:
9335       if (imm_expr.X_add_number == 0)
9336         op[1] = 0;
9337       else
9338         {
9339           op[1] = AT;
9340           used_at = 1;
9341           load_register (op[1], &imm_expr, HAVE_64BIT_GPRS);
9342         }
9343       /* Fall through.  */
9344     case M_BEQL:
9345     case M_BNEL:
9346       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9347       break;
9348
9349     case M_BGEL:
9350       likely = 1;
9351     case M_BGE:
9352       if (op[1] == 0)
9353         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9354       else if (op[0] == 0)
9355         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9356       else
9357         {
9358           used_at = 1;
9359           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9360           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9361                                    &offset_expr, AT, ZERO);
9362         }
9363       break;
9364
9365     case M_BGEZL:
9366     case M_BGEZALL:
9367     case M_BGTZL:
9368     case M_BLEZL:
9369     case M_BLTZL:
9370     case M_BLTZALL:
9371       macro_build_branch_rs (mask, &offset_expr, op[0]);
9372       break;
9373
9374     case M_BGTL_I:
9375       likely = 1;
9376     case M_BGT_I:
9377       /* Check for > max integer.  */
9378       if (imm_expr.X_add_number >= GPR_SMAX)
9379         {
9380         do_false:
9381           /* Result is always false.  */
9382           if (! likely)
9383             macro_build (NULL, "nop", "");
9384           else
9385             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9386           break;
9387         }
9388       ++imm_expr.X_add_number;
9389       /* FALLTHROUGH */
9390     case M_BGE_I:
9391     case M_BGEL_I:
9392       if (mask == M_BGEL_I)
9393         likely = 1;
9394       if (imm_expr.X_add_number == 0)
9395         {
9396           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9397                                  &offset_expr, op[0]);
9398           break;
9399         }
9400       if (imm_expr.X_add_number == 1)
9401         {
9402           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9403                                  &offset_expr, op[0]);
9404           break;
9405         }
9406       if (imm_expr.X_add_number <= GPR_SMIN)
9407         {
9408         do_true:
9409           /* result is always true */
9410           as_warn (_("branch %s is always true"), ip->insn_mo->name);
9411           macro_build (&offset_expr, "b", "p");
9412           break;
9413         }
9414       used_at = 1;
9415       set_at (op[0], 0);
9416       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9417                                &offset_expr, AT, ZERO);
9418       break;
9419
9420     case M_BGEUL:
9421       likely = 1;
9422     case M_BGEU:
9423       if (op[1] == 0)
9424         goto do_true;
9425       else if (op[0] == 0)
9426         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9427                                  &offset_expr, ZERO, op[1]);
9428       else
9429         {
9430           used_at = 1;
9431           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9432           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9433                                    &offset_expr, AT, ZERO);
9434         }
9435       break;
9436
9437     case M_BGTUL_I:
9438       likely = 1;
9439     case M_BGTU_I:
9440       if (op[0] == 0
9441           || (HAVE_32BIT_GPRS
9442               && imm_expr.X_add_number == -1))
9443         goto do_false;
9444       ++imm_expr.X_add_number;
9445       /* FALLTHROUGH */
9446     case M_BGEU_I:
9447     case M_BGEUL_I:
9448       if (mask == M_BGEUL_I)
9449         likely = 1;
9450       if (imm_expr.X_add_number == 0)
9451         goto do_true;
9452       else if (imm_expr.X_add_number == 1)
9453         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9454                                  &offset_expr, op[0], ZERO);
9455       else
9456         {
9457           used_at = 1;
9458           set_at (op[0], 1);
9459           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9460                                    &offset_expr, AT, ZERO);
9461         }
9462       break;
9463
9464     case M_BGTL:
9465       likely = 1;
9466     case M_BGT:
9467       if (op[1] == 0)
9468         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9469       else if (op[0] == 0)
9470         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9471       else
9472         {
9473           used_at = 1;
9474           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9475           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9476                                    &offset_expr, AT, ZERO);
9477         }
9478       break;
9479
9480     case M_BGTUL:
9481       likely = 1;
9482     case M_BGTU:
9483       if (op[1] == 0)
9484         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9485                                  &offset_expr, op[0], ZERO);
9486       else if (op[0] == 0)
9487         goto do_false;
9488       else
9489         {
9490           used_at = 1;
9491           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9492           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9493                                    &offset_expr, AT, ZERO);
9494         }
9495       break;
9496
9497     case M_BLEL:
9498       likely = 1;
9499     case M_BLE:
9500       if (op[1] == 0)
9501         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9502       else if (op[0] == 0)
9503         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9504       else
9505         {
9506           used_at = 1;
9507           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9508           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9509                                    &offset_expr, AT, ZERO);
9510         }
9511       break;
9512
9513     case M_BLEL_I:
9514       likely = 1;
9515     case M_BLE_I:
9516       if (imm_expr.X_add_number >= GPR_SMAX)
9517         goto do_true;
9518       ++imm_expr.X_add_number;
9519       /* FALLTHROUGH */
9520     case M_BLT_I:
9521     case M_BLTL_I:
9522       if (mask == M_BLTL_I)
9523         likely = 1;
9524       if (imm_expr.X_add_number == 0)
9525         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9526       else if (imm_expr.X_add_number == 1)
9527         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9528       else
9529         {
9530           used_at = 1;
9531           set_at (op[0], 0);
9532           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9533                                    &offset_expr, AT, ZERO);
9534         }
9535       break;
9536
9537     case M_BLEUL:
9538       likely = 1;
9539     case M_BLEU:
9540       if (op[1] == 0)
9541         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9542                                  &offset_expr, op[0], ZERO);
9543       else if (op[0] == 0)
9544         goto do_true;
9545       else
9546         {
9547           used_at = 1;
9548           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9549           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9550                                    &offset_expr, AT, ZERO);
9551         }
9552       break;
9553
9554     case M_BLEUL_I:
9555       likely = 1;
9556     case M_BLEU_I:
9557       if (op[0] == 0
9558           || (HAVE_32BIT_GPRS
9559               && imm_expr.X_add_number == -1))
9560         goto do_true;
9561       ++imm_expr.X_add_number;
9562       /* FALLTHROUGH */
9563     case M_BLTU_I:
9564     case M_BLTUL_I:
9565       if (mask == M_BLTUL_I)
9566         likely = 1;
9567       if (imm_expr.X_add_number == 0)
9568         goto do_false;
9569       else if (imm_expr.X_add_number == 1)
9570         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9571                                  &offset_expr, op[0], ZERO);
9572       else
9573         {
9574           used_at = 1;
9575           set_at (op[0], 1);
9576           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9577                                    &offset_expr, AT, ZERO);
9578         }
9579       break;
9580
9581     case M_BLTL:
9582       likely = 1;
9583     case M_BLT:
9584       if (op[1] == 0)
9585         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9586       else if (op[0] == 0)
9587         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9588       else
9589         {
9590           used_at = 1;
9591           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9592           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9593                                    &offset_expr, AT, ZERO);
9594         }
9595       break;
9596
9597     case M_BLTUL:
9598       likely = 1;
9599     case M_BLTU:
9600       if (op[1] == 0)
9601         goto do_false;
9602       else if (op[0] == 0)
9603         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9604                                  &offset_expr, ZERO, op[1]);
9605       else
9606         {
9607           used_at = 1;
9608           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9609           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9610                                    &offset_expr, AT, ZERO);
9611         }
9612       break;
9613
9614     case M_DDIV_3:
9615       dbl = 1;
9616     case M_DIV_3:
9617       s = "mflo";
9618       goto do_div3;
9619     case M_DREM_3:
9620       dbl = 1;
9621     case M_REM_3:
9622       s = "mfhi";
9623     do_div3:
9624       if (op[2] == 0)
9625         {
9626           as_warn (_("divide by zero"));
9627           if (mips_trap)
9628             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9629           else
9630             macro_build (NULL, "break", BRK_FMT, 7);
9631           break;
9632         }
9633
9634       start_noreorder ();
9635       if (mips_trap)
9636         {
9637           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9638           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9639         }
9640       else
9641         {
9642           if (mips_opts.micromips)
9643             micromips_label_expr (&label_expr);
9644           else
9645             label_expr.X_add_number = 8;
9646           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9647           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9648           macro_build (NULL, "break", BRK_FMT, 7);
9649           if (mips_opts.micromips)
9650             micromips_add_label ();
9651         }
9652       expr1.X_add_number = -1;
9653       used_at = 1;
9654       load_register (AT, &expr1, dbl);
9655       if (mips_opts.micromips)
9656         micromips_label_expr (&label_expr);
9657       else
9658         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9659       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9660       if (dbl)
9661         {
9662           expr1.X_add_number = 1;
9663           load_register (AT, &expr1, dbl);
9664           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9665         }
9666       else
9667         {
9668           expr1.X_add_number = 0x80000000;
9669           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9670         }
9671       if (mips_trap)
9672         {
9673           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9674           /* We want to close the noreorder block as soon as possible, so
9675              that later insns are available for delay slot filling.  */
9676           end_noreorder ();
9677         }
9678       else
9679         {
9680           if (mips_opts.micromips)
9681             micromips_label_expr (&label_expr);
9682           else
9683             label_expr.X_add_number = 8;
9684           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9685           macro_build (NULL, "nop", "");
9686
9687           /* We want to close the noreorder block as soon as possible, so
9688              that later insns are available for delay slot filling.  */
9689           end_noreorder ();
9690
9691           macro_build (NULL, "break", BRK_FMT, 6);
9692         }
9693       if (mips_opts.micromips)
9694         micromips_add_label ();
9695       macro_build (NULL, s, MFHL_FMT, op[0]);
9696       break;
9697
9698     case M_DIV_3I:
9699       s = "div";
9700       s2 = "mflo";
9701       goto do_divi;
9702     case M_DIVU_3I:
9703       s = "divu";
9704       s2 = "mflo";
9705       goto do_divi;
9706     case M_REM_3I:
9707       s = "div";
9708       s2 = "mfhi";
9709       goto do_divi;
9710     case M_REMU_3I:
9711       s = "divu";
9712       s2 = "mfhi";
9713       goto do_divi;
9714     case M_DDIV_3I:
9715       dbl = 1;
9716       s = "ddiv";
9717       s2 = "mflo";
9718       goto do_divi;
9719     case M_DDIVU_3I:
9720       dbl = 1;
9721       s = "ddivu";
9722       s2 = "mflo";
9723       goto do_divi;
9724     case M_DREM_3I:
9725       dbl = 1;
9726       s = "ddiv";
9727       s2 = "mfhi";
9728       goto do_divi;
9729     case M_DREMU_3I:
9730       dbl = 1;
9731       s = "ddivu";
9732       s2 = "mfhi";
9733     do_divi:
9734       if (imm_expr.X_add_number == 0)
9735         {
9736           as_warn (_("divide by zero"));
9737           if (mips_trap)
9738             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9739           else
9740             macro_build (NULL, "break", BRK_FMT, 7);
9741           break;
9742         }
9743       if (imm_expr.X_add_number == 1)
9744         {
9745           if (strcmp (s2, "mflo") == 0)
9746             move_register (op[0], op[1]);
9747           else
9748             move_register (op[0], ZERO);
9749           break;
9750         }
9751       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
9752         {
9753           if (strcmp (s2, "mflo") == 0)
9754             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9755           else
9756             move_register (op[0], ZERO);
9757           break;
9758         }
9759
9760       used_at = 1;
9761       load_register (AT, &imm_expr, dbl);
9762       macro_build (NULL, s, "z,s,t", op[1], AT);
9763       macro_build (NULL, s2, MFHL_FMT, op[0]);
9764       break;
9765
9766     case M_DIVU_3:
9767       s = "divu";
9768       s2 = "mflo";
9769       goto do_divu3;
9770     case M_REMU_3:
9771       s = "divu";
9772       s2 = "mfhi";
9773       goto do_divu3;
9774     case M_DDIVU_3:
9775       s = "ddivu";
9776       s2 = "mflo";
9777       goto do_divu3;
9778     case M_DREMU_3:
9779       s = "ddivu";
9780       s2 = "mfhi";
9781     do_divu3:
9782       start_noreorder ();
9783       if (mips_trap)
9784         {
9785           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9786           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9787           /* We want to close the noreorder block as soon as possible, so
9788              that later insns are available for delay slot filling.  */
9789           end_noreorder ();
9790         }
9791       else
9792         {
9793           if (mips_opts.micromips)
9794             micromips_label_expr (&label_expr);
9795           else
9796             label_expr.X_add_number = 8;
9797           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9798           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9799
9800           /* We want to close the noreorder block as soon as possible, so
9801              that later insns are available for delay slot filling.  */
9802           end_noreorder ();
9803           macro_build (NULL, "break", BRK_FMT, 7);
9804           if (mips_opts.micromips)
9805             micromips_add_label ();
9806         }
9807       macro_build (NULL, s2, MFHL_FMT, op[0]);
9808       break;
9809
9810     case M_DLCA_AB:
9811       dbl = 1;
9812     case M_LCA_AB:
9813       call = 1;
9814       goto do_la;
9815     case M_DLA_AB:
9816       dbl = 1;
9817     case M_LA_AB:
9818     do_la:
9819       /* Load the address of a symbol into a register.  If breg is not
9820          zero, we then add a base register to it.  */
9821
9822       breg = op[2];
9823       if (dbl && HAVE_32BIT_GPRS)
9824         as_warn (_("dla used to load 32-bit register"));
9825
9826       if (!dbl && HAVE_64BIT_OBJECTS)
9827         as_warn (_("la used to load 64-bit address"));
9828
9829       if (small_offset_p (0, align, 16))
9830         {
9831           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9832                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9833           break;
9834         }
9835
9836       if (mips_opts.at && (op[0] == breg))
9837         {
9838           tempreg = AT;
9839           used_at = 1;
9840         }
9841       else
9842         tempreg = op[0];
9843
9844       if (offset_expr.X_op != O_symbol
9845           && offset_expr.X_op != O_constant)
9846         {
9847           as_bad (_("expression too complex"));
9848           offset_expr.X_op = O_constant;
9849         }
9850
9851       if (offset_expr.X_op == O_constant)
9852         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9853       else if (mips_pic == NO_PIC)
9854         {
9855           /* If this is a reference to a GP relative symbol, we want
9856                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9857              Otherwise we want
9858                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9859                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9860              If we have a constant, we need two instructions anyhow,
9861              so we may as well always use the latter form.
9862
9863              With 64bit address space and a usable $at we want
9864                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9865                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9866                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9867                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9868                dsll32   $tempreg,0
9869                daddu    $tempreg,$tempreg,$at
9870
9871              If $at is already in use, we use a path which is suboptimal
9872              on superscalar processors.
9873                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9874                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9875                dsll     $tempreg,16
9876                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9877                dsll     $tempreg,16
9878                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
9879
9880              For GP relative symbols in 64bit address space we can use
9881              the same sequence as in 32bit address space.  */
9882           if (HAVE_64BIT_SYMBOLS)
9883             {
9884               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9885                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9886                 {
9887                   relax_start (offset_expr.X_add_symbol);
9888                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9889                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9890                   relax_switch ();
9891                 }
9892
9893               if (used_at == 0 && mips_opts.at)
9894                 {
9895                   macro_build (&offset_expr, "lui", LUI_FMT,
9896                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9897                   macro_build (&offset_expr, "lui", LUI_FMT,
9898                                AT, BFD_RELOC_HI16_S);
9899                   macro_build (&offset_expr, "daddiu", "t,r,j",
9900                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9901                   macro_build (&offset_expr, "daddiu", "t,r,j",
9902                                AT, AT, BFD_RELOC_LO16);
9903                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9904                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9905                   used_at = 1;
9906                 }
9907               else
9908                 {
9909                   macro_build (&offset_expr, "lui", LUI_FMT,
9910                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9911                   macro_build (&offset_expr, "daddiu", "t,r,j",
9912                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9913                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9914                   macro_build (&offset_expr, "daddiu", "t,r,j",
9915                                tempreg, tempreg, BFD_RELOC_HI16_S);
9916                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9917                   macro_build (&offset_expr, "daddiu", "t,r,j",
9918                                tempreg, tempreg, BFD_RELOC_LO16);
9919                 }
9920
9921               if (mips_relax.sequence)
9922                 relax_end ();
9923             }
9924           else
9925             {
9926               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9927                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9928                 {
9929                   relax_start (offset_expr.X_add_symbol);
9930                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9931                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9932                   relax_switch ();
9933                 }
9934               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9935                 as_bad (_("offset too large"));
9936               macro_build_lui (&offset_expr, tempreg);
9937               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9938                            tempreg, tempreg, BFD_RELOC_LO16);
9939               if (mips_relax.sequence)
9940                 relax_end ();
9941             }
9942         }
9943       else if (!mips_big_got && !HAVE_NEWABI)
9944         {
9945           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9946
9947           /* If this is a reference to an external symbol, and there
9948              is no constant, we want
9949                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9950              or for lca or if tempreg is PIC_CALL_REG
9951                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9952              For a local symbol, we want
9953                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9954                nop
9955                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9956
9957              If we have a small constant, and this is a reference to
9958              an external symbol, we want
9959                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9960                nop
9961                addiu    $tempreg,$tempreg,<constant>
9962              For a local symbol, we want the same instruction
9963              sequence, but we output a BFD_RELOC_LO16 reloc on the
9964              addiu instruction.
9965
9966              If we have a large constant, and this is a reference to
9967              an external symbol, we want
9968                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9969                lui      $at,<hiconstant>
9970                addiu    $at,$at,<loconstant>
9971                addu     $tempreg,$tempreg,$at
9972              For a local symbol, we want the same instruction
9973              sequence, but we output a BFD_RELOC_LO16 reloc on the
9974              addiu instruction.
9975            */
9976
9977           if (offset_expr.X_add_number == 0)
9978             {
9979               if (mips_pic == SVR4_PIC
9980                   && breg == 0
9981                   && (call || tempreg == PIC_CALL_REG))
9982                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
9983
9984               relax_start (offset_expr.X_add_symbol);
9985               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9986                            lw_reloc_type, mips_gp_register);
9987               if (breg != 0)
9988                 {
9989                   /* We're going to put in an addu instruction using
9990                      tempreg, so we may as well insert the nop right
9991                      now.  */
9992                   load_delay_nop ();
9993                 }
9994               relax_switch ();
9995               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9996                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
9997               load_delay_nop ();
9998               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9999                            tempreg, tempreg, BFD_RELOC_LO16);
10000               relax_end ();
10001               /* FIXME: If breg == 0, and the next instruction uses
10002                  $tempreg, then if this variant case is used an extra
10003                  nop will be generated.  */
10004             }
10005           else if (offset_expr.X_add_number >= -0x8000
10006                    && offset_expr.X_add_number < 0x8000)
10007             {
10008               load_got_offset (tempreg, &offset_expr);
10009               load_delay_nop ();
10010               add_got_offset (tempreg, &offset_expr);
10011             }
10012           else
10013             {
10014               expr1.X_add_number = offset_expr.X_add_number;
10015               offset_expr.X_add_number =
10016                 SEXT_16BIT (offset_expr.X_add_number);
10017               load_got_offset (tempreg, &offset_expr);
10018               offset_expr.X_add_number = expr1.X_add_number;
10019               /* If we are going to add in a base register, and the
10020                  target register and the base register are the same,
10021                  then we are using AT as a temporary register.  Since
10022                  we want to load the constant into AT, we add our
10023                  current AT (from the global offset table) and the
10024                  register into the register now, and pretend we were
10025                  not using a base register.  */
10026               if (breg == op[0])
10027                 {
10028                   load_delay_nop ();
10029                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10030                                op[0], AT, breg);
10031                   breg = 0;
10032                   tempreg = op[0];
10033                 }
10034               add_got_offset_hilo (tempreg, &offset_expr, AT);
10035               used_at = 1;
10036             }
10037         }
10038       else if (!mips_big_got && HAVE_NEWABI)
10039         {
10040           int add_breg_early = 0;
10041
10042           /* If this is a reference to an external, and there is no
10043              constant, or local symbol (*), with or without a
10044              constant, we want
10045                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10046              or for lca or if tempreg is PIC_CALL_REG
10047                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10048
10049              If we have a small constant, and this is a reference to
10050              an external symbol, we want
10051                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10052                addiu    $tempreg,$tempreg,<constant>
10053
10054              If we have a large constant, and this is a reference to
10055              an external symbol, we want
10056                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10057                lui      $at,<hiconstant>
10058                addiu    $at,$at,<loconstant>
10059                addu     $tempreg,$tempreg,$at
10060
10061              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10062              local symbols, even though it introduces an additional
10063              instruction.  */
10064
10065           if (offset_expr.X_add_number)
10066             {
10067               expr1.X_add_number = offset_expr.X_add_number;
10068               offset_expr.X_add_number = 0;
10069
10070               relax_start (offset_expr.X_add_symbol);
10071               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10072                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10073
10074               if (expr1.X_add_number >= -0x8000
10075                   && expr1.X_add_number < 0x8000)
10076                 {
10077                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10078                                tempreg, tempreg, BFD_RELOC_LO16);
10079                 }
10080               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10081                 {
10082                   unsigned int dreg;
10083
10084                   /* If we are going to add in a base register, and the
10085                      target register and the base register are the same,
10086                      then we are using AT as a temporary register.  Since
10087                      we want to load the constant into AT, we add our
10088                      current AT (from the global offset table) and the
10089                      register into the register now, and pretend we were
10090                      not using a base register.  */
10091                   if (breg != op[0])
10092                     dreg = tempreg;
10093                   else
10094                     {
10095                       gas_assert (tempreg == AT);
10096                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10097                                    op[0], AT, breg);
10098                       dreg = op[0];
10099                       add_breg_early = 1;
10100                     }
10101
10102                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10103                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10104                                dreg, dreg, AT);
10105
10106                   used_at = 1;
10107                 }
10108               else
10109                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10110
10111               relax_switch ();
10112               offset_expr.X_add_number = expr1.X_add_number;
10113
10114               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10115                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10116               if (add_breg_early)
10117                 {
10118                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10119                                op[0], tempreg, breg);
10120                   breg = 0;
10121                   tempreg = op[0];
10122                 }
10123               relax_end ();
10124             }
10125           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10126             {
10127               relax_start (offset_expr.X_add_symbol);
10128               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10129                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10130               relax_switch ();
10131               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10132                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10133               relax_end ();
10134             }
10135           else
10136             {
10137               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10138                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10139             }
10140         }
10141       else if (mips_big_got && !HAVE_NEWABI)
10142         {
10143           int gpdelay;
10144           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10145           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10146           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10147
10148           /* This is the large GOT case.  If this is a reference to an
10149              external symbol, and there is no constant, we want
10150                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10151                addu     $tempreg,$tempreg,$gp
10152                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10153              or for lca or if tempreg is PIC_CALL_REG
10154                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10155                addu     $tempreg,$tempreg,$gp
10156                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10157              For a local symbol, we want
10158                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10159                nop
10160                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10161
10162              If we have a small constant, and this is a reference to
10163              an external symbol, we want
10164                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10165                addu     $tempreg,$tempreg,$gp
10166                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10167                nop
10168                addiu    $tempreg,$tempreg,<constant>
10169              For a local symbol, we want
10170                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10171                nop
10172                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10173
10174              If we have a large constant, and this is a reference to
10175              an external symbol, we want
10176                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10177                addu     $tempreg,$tempreg,$gp
10178                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10179                lui      $at,<hiconstant>
10180                addiu    $at,$at,<loconstant>
10181                addu     $tempreg,$tempreg,$at
10182              For a local symbol, we want
10183                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10184                lui      $at,<hiconstant>
10185                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10186                addu     $tempreg,$tempreg,$at
10187           */
10188
10189           expr1.X_add_number = offset_expr.X_add_number;
10190           offset_expr.X_add_number = 0;
10191           relax_start (offset_expr.X_add_symbol);
10192           gpdelay = reg_needs_delay (mips_gp_register);
10193           if (expr1.X_add_number == 0 && breg == 0
10194               && (call || tempreg == PIC_CALL_REG))
10195             {
10196               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10197               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10198             }
10199           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10200           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10201                        tempreg, tempreg, mips_gp_register);
10202           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10203                        tempreg, lw_reloc_type, tempreg);
10204           if (expr1.X_add_number == 0)
10205             {
10206               if (breg != 0)
10207                 {
10208                   /* We're going to put in an addu instruction using
10209                      tempreg, so we may as well insert the nop right
10210                      now.  */
10211                   load_delay_nop ();
10212                 }
10213             }
10214           else if (expr1.X_add_number >= -0x8000
10215                    && expr1.X_add_number < 0x8000)
10216             {
10217               load_delay_nop ();
10218               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10219                            tempreg, tempreg, BFD_RELOC_LO16);
10220             }
10221           else
10222             {
10223               unsigned int dreg;
10224
10225               /* If we are going to add in a base register, and the
10226                  target register and the base register are the same,
10227                  then we are using AT as a temporary register.  Since
10228                  we want to load the constant into AT, we add our
10229                  current AT (from the global offset table) and the
10230                  register into the register now, and pretend we were
10231                  not using a base register.  */
10232               if (breg != op[0])
10233                 dreg = tempreg;
10234               else
10235                 {
10236                   gas_assert (tempreg == AT);
10237                   load_delay_nop ();
10238                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10239                                op[0], AT, breg);
10240                   dreg = op[0];
10241                 }
10242
10243               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10244               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10245
10246               used_at = 1;
10247             }
10248           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10249           relax_switch ();
10250
10251           if (gpdelay)
10252             {
10253               /* This is needed because this instruction uses $gp, but
10254                  the first instruction on the main stream does not.  */
10255               macro_build (NULL, "nop", "");
10256             }
10257
10258           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10259                        local_reloc_type, mips_gp_register);
10260           if (expr1.X_add_number >= -0x8000
10261               && expr1.X_add_number < 0x8000)
10262             {
10263               load_delay_nop ();
10264               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10265                            tempreg, tempreg, BFD_RELOC_LO16);
10266               /* FIXME: If add_number is 0, and there was no base
10267                  register, the external symbol case ended with a load,
10268                  so if the symbol turns out to not be external, and
10269                  the next instruction uses tempreg, an unnecessary nop
10270                  will be inserted.  */
10271             }
10272           else
10273             {
10274               if (breg == op[0])
10275                 {
10276                   /* We must add in the base register now, as in the
10277                      external symbol case.  */
10278                   gas_assert (tempreg == AT);
10279                   load_delay_nop ();
10280                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10281                                op[0], AT, breg);
10282                   tempreg = op[0];
10283                   /* We set breg to 0 because we have arranged to add
10284                      it in in both cases.  */
10285                   breg = 0;
10286                 }
10287
10288               macro_build_lui (&expr1, AT);
10289               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10290                            AT, AT, BFD_RELOC_LO16);
10291               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10292                            tempreg, tempreg, AT);
10293               used_at = 1;
10294             }
10295           relax_end ();
10296         }
10297       else if (mips_big_got && HAVE_NEWABI)
10298         {
10299           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10300           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10301           int add_breg_early = 0;
10302
10303           /* This is the large GOT case.  If this is a reference to an
10304              external symbol, and there is no constant, we want
10305                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10306                add      $tempreg,$tempreg,$gp
10307                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10308              or for lca or if tempreg is PIC_CALL_REG
10309                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10310                add      $tempreg,$tempreg,$gp
10311                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10312
10313              If we have a small constant, and this is a reference to
10314              an external symbol, we want
10315                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10316                add      $tempreg,$tempreg,$gp
10317                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10318                addi     $tempreg,$tempreg,<constant>
10319
10320              If we have a large constant, and this is a reference to
10321              an external symbol, we want
10322                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10323                addu     $tempreg,$tempreg,$gp
10324                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10325                lui      $at,<hiconstant>
10326                addi     $at,$at,<loconstant>
10327                add      $tempreg,$tempreg,$at
10328
10329              If we have NewABI, and we know it's a local symbol, we want
10330                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10331                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10332              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10333
10334           relax_start (offset_expr.X_add_symbol);
10335
10336           expr1.X_add_number = offset_expr.X_add_number;
10337           offset_expr.X_add_number = 0;
10338
10339           if (expr1.X_add_number == 0 && breg == 0
10340               && (call || tempreg == PIC_CALL_REG))
10341             {
10342               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10343               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10344             }
10345           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10346           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10347                        tempreg, tempreg, mips_gp_register);
10348           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10349                        tempreg, lw_reloc_type, tempreg);
10350
10351           if (expr1.X_add_number == 0)
10352             ;
10353           else if (expr1.X_add_number >= -0x8000
10354                    && expr1.X_add_number < 0x8000)
10355             {
10356               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10357                            tempreg, tempreg, BFD_RELOC_LO16);
10358             }
10359           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10360             {
10361               unsigned int dreg;
10362
10363               /* If we are going to add in a base register, and the
10364                  target register and the base register are the same,
10365                  then we are using AT as a temporary register.  Since
10366                  we want to load the constant into AT, we add our
10367                  current AT (from the global offset table) and the
10368                  register into the register now, and pretend we were
10369                  not using a base register.  */
10370               if (breg != op[0])
10371                 dreg = tempreg;
10372               else
10373                 {
10374                   gas_assert (tempreg == AT);
10375                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10376                                op[0], AT, breg);
10377                   dreg = op[0];
10378                   add_breg_early = 1;
10379                 }
10380
10381               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10382               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10383
10384               used_at = 1;
10385             }
10386           else
10387             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10388
10389           relax_switch ();
10390           offset_expr.X_add_number = expr1.X_add_number;
10391           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10392                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10393           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10394                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10395           if (add_breg_early)
10396             {
10397               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10398                            op[0], tempreg, breg);
10399               breg = 0;
10400               tempreg = op[0];
10401             }
10402           relax_end ();
10403         }
10404       else
10405         abort ();
10406
10407       if (breg != 0)
10408         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10409       break;
10410
10411     case M_MSGSND:
10412       gas_assert (!mips_opts.micromips);
10413       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10414       break;
10415
10416     case M_MSGLD:
10417       gas_assert (!mips_opts.micromips);
10418       macro_build (NULL, "c2", "C", 0x02);
10419       break;
10420
10421     case M_MSGLD_T:
10422       gas_assert (!mips_opts.micromips);
10423       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10424       break;
10425
10426     case M_MSGWAIT:
10427       gas_assert (!mips_opts.micromips);
10428       macro_build (NULL, "c2", "C", 3);
10429       break;
10430
10431     case M_MSGWAIT_T:
10432       gas_assert (!mips_opts.micromips);
10433       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10434       break;
10435
10436     case M_J_A:
10437       /* The j instruction may not be used in PIC code, since it
10438          requires an absolute address.  We convert it to a b
10439          instruction.  */
10440       if (mips_pic == NO_PIC)
10441         macro_build (&offset_expr, "j", "a");
10442       else
10443         macro_build (&offset_expr, "b", "p");
10444       break;
10445
10446       /* The jal instructions must be handled as macros because when
10447          generating PIC code they expand to multi-instruction
10448          sequences.  Normally they are simple instructions.  */
10449     case M_JALS_1:
10450       op[1] = op[0];
10451       op[0] = RA;
10452       /* Fall through.  */
10453     case M_JALS_2:
10454       gas_assert (mips_opts.micromips);
10455       if (mips_opts.insn32)
10456         {
10457           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10458           break;
10459         }
10460       jals = 1;
10461       goto jal;
10462     case M_JAL_1:
10463       op[1] = op[0];
10464       op[0] = RA;
10465       /* Fall through.  */
10466     case M_JAL_2:
10467     jal:
10468       if (mips_pic == NO_PIC)
10469         {
10470           s = jals ? "jalrs" : "jalr";
10471           if (mips_opts.micromips
10472               && !mips_opts.insn32
10473               && op[0] == RA
10474               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10475             macro_build (NULL, s, "mj", op[1]);
10476           else
10477             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10478         }
10479       else
10480         {
10481           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10482                            && mips_cprestore_offset >= 0);
10483
10484           if (op[1] != PIC_CALL_REG)
10485             as_warn (_("MIPS PIC call to register other than $25"));
10486
10487           s = ((mips_opts.micromips
10488                 && !mips_opts.insn32
10489                 && (!mips_opts.noreorder || cprestore))
10490                ? "jalrs" : "jalr");
10491           if (mips_opts.micromips
10492               && !mips_opts.insn32
10493               && op[0] == RA
10494               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10495             macro_build (NULL, s, "mj", op[1]);
10496           else
10497             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10498           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10499             {
10500               if (mips_cprestore_offset < 0)
10501                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10502               else
10503                 {
10504                   if (!mips_frame_reg_valid)
10505                     {
10506                       as_warn (_("no .frame pseudo-op used in PIC code"));
10507                       /* Quiet this warning.  */
10508                       mips_frame_reg_valid = 1;
10509                     }
10510                   if (!mips_cprestore_valid)
10511                     {
10512                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10513                       /* Quiet this warning.  */
10514                       mips_cprestore_valid = 1;
10515                     }
10516                   if (mips_opts.noreorder)
10517                     macro_build (NULL, "nop", "");
10518                   expr1.X_add_number = mips_cprestore_offset;
10519                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10520                                                 mips_gp_register,
10521                                                 mips_frame_reg,
10522                                                 HAVE_64BIT_ADDRESSES);
10523                 }
10524             }
10525         }
10526
10527       break;
10528
10529     case M_JALS_A:
10530       gas_assert (mips_opts.micromips);
10531       if (mips_opts.insn32)
10532         {
10533           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10534           break;
10535         }
10536       jals = 1;
10537       /* Fall through.  */
10538     case M_JAL_A:
10539       if (mips_pic == NO_PIC)
10540         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10541       else if (mips_pic == SVR4_PIC)
10542         {
10543           /* If this is a reference to an external symbol, and we are
10544              using a small GOT, we want
10545                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10546                nop
10547                jalr     $ra,$25
10548                nop
10549                lw       $gp,cprestore($sp)
10550              The cprestore value is set using the .cprestore
10551              pseudo-op.  If we are using a big GOT, we want
10552                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10553                addu     $25,$25,$gp
10554                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10555                nop
10556                jalr     $ra,$25
10557                nop
10558                lw       $gp,cprestore($sp)
10559              If the symbol is not external, we want
10560                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10561                nop
10562                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10563                jalr     $ra,$25
10564                nop
10565                lw $gp,cprestore($sp)
10566
10567              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10568              sequences above, minus nops, unless the symbol is local,
10569              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10570              GOT_DISP.  */
10571           if (HAVE_NEWABI)
10572             {
10573               if (!mips_big_got)
10574                 {
10575                   relax_start (offset_expr.X_add_symbol);
10576                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10577                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10578                                mips_gp_register);
10579                   relax_switch ();
10580                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10581                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10582                                mips_gp_register);
10583                   relax_end ();
10584                 }
10585               else
10586                 {
10587                   relax_start (offset_expr.X_add_symbol);
10588                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10589                                BFD_RELOC_MIPS_CALL_HI16);
10590                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10591                                PIC_CALL_REG, mips_gp_register);
10592                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10593                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10594                                PIC_CALL_REG);
10595                   relax_switch ();
10596                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10597                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10598                                mips_gp_register);
10599                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10600                                PIC_CALL_REG, PIC_CALL_REG,
10601                                BFD_RELOC_MIPS_GOT_OFST);
10602                   relax_end ();
10603                 }
10604
10605               macro_build_jalr (&offset_expr, 0);
10606             }
10607           else
10608             {
10609               relax_start (offset_expr.X_add_symbol);
10610               if (!mips_big_got)
10611                 {
10612                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10613                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10614                                mips_gp_register);
10615                   load_delay_nop ();
10616                   relax_switch ();
10617                 }
10618               else
10619                 {
10620                   int gpdelay;
10621
10622                   gpdelay = reg_needs_delay (mips_gp_register);
10623                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10624                                BFD_RELOC_MIPS_CALL_HI16);
10625                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10626                                PIC_CALL_REG, mips_gp_register);
10627                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10628                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10629                                PIC_CALL_REG);
10630                   load_delay_nop ();
10631                   relax_switch ();
10632                   if (gpdelay)
10633                     macro_build (NULL, "nop", "");
10634                 }
10635               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10636                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10637                            mips_gp_register);
10638               load_delay_nop ();
10639               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10640                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10641               relax_end ();
10642               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10643
10644               if (mips_cprestore_offset < 0)
10645                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10646               else
10647                 {
10648                   if (!mips_frame_reg_valid)
10649                     {
10650                       as_warn (_("no .frame pseudo-op used in PIC code"));
10651                       /* Quiet this warning.  */
10652                       mips_frame_reg_valid = 1;
10653                     }
10654                   if (!mips_cprestore_valid)
10655                     {
10656                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10657                       /* Quiet this warning.  */
10658                       mips_cprestore_valid = 1;
10659                     }
10660                   if (mips_opts.noreorder)
10661                     macro_build (NULL, "nop", "");
10662                   expr1.X_add_number = mips_cprestore_offset;
10663                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10664                                                 mips_gp_register,
10665                                                 mips_frame_reg,
10666                                                 HAVE_64BIT_ADDRESSES);
10667                 }
10668             }
10669         }
10670       else if (mips_pic == VXWORKS_PIC)
10671         as_bad (_("non-PIC jump used in PIC library"));
10672       else
10673         abort ();
10674
10675       break;
10676
10677     case M_LBUE_AB:
10678       s = "lbue";
10679       fmt = "t,+j(b)";
10680       offbits = 9;
10681       goto ld_st;
10682     case M_LHUE_AB:
10683       s = "lhue";
10684       fmt = "t,+j(b)";
10685       offbits = 9;
10686       goto ld_st;
10687     case M_LBE_AB:
10688       s = "lbe";
10689       fmt = "t,+j(b)";
10690       offbits = 9;
10691       goto ld_st;
10692     case M_LHE_AB:
10693       s = "lhe";
10694       fmt = "t,+j(b)";
10695       offbits = 9;
10696       goto ld_st;
10697     case M_LLE_AB:
10698       s = "lle";
10699       fmt = "t,+j(b)";
10700       offbits = 9;
10701       goto ld_st;
10702     case M_LWE_AB:
10703       s = "lwe";
10704       fmt = "t,+j(b)";
10705       offbits = 9;
10706       goto ld_st;
10707     case M_LWLE_AB:
10708       s = "lwle";
10709       fmt = "t,+j(b)";
10710       offbits = 9;
10711       goto ld_st;
10712     case M_LWRE_AB:
10713       s = "lwre";
10714       fmt = "t,+j(b)";
10715       offbits = 9;
10716       goto ld_st;
10717     case M_SBE_AB:
10718       s = "sbe";
10719       fmt = "t,+j(b)";
10720       offbits = 9;
10721       goto ld_st;
10722     case M_SCE_AB:
10723       s = "sce";
10724       fmt = "t,+j(b)";
10725       offbits = 9;
10726       goto ld_st;
10727     case M_SHE_AB:
10728       s = "she";
10729       fmt = "t,+j(b)";
10730       offbits = 9;
10731       goto ld_st;
10732     case M_SWE_AB:
10733       s = "swe";
10734       fmt = "t,+j(b)";
10735       offbits = 9;
10736       goto ld_st;
10737     case M_SWLE_AB:
10738       s = "swle";
10739       fmt = "t,+j(b)";
10740       offbits = 9;
10741       goto ld_st;
10742     case M_SWRE_AB:
10743       s = "swre";
10744       fmt = "t,+j(b)";
10745       offbits = 9;
10746       goto ld_st;
10747     case M_ACLR_AB:
10748       s = "aclr";
10749       fmt = "\\,~(b)";
10750       offbits = 12;
10751       goto ld_st;
10752     case M_ASET_AB:
10753       s = "aset";
10754       fmt = "\\,~(b)";
10755       offbits = 12;
10756       goto ld_st;
10757     case M_LB_AB:
10758       s = "lb";
10759       fmt = "t,o(b)";
10760       goto ld;
10761     case M_LBU_AB:
10762       s = "lbu";
10763       fmt = "t,o(b)";
10764       goto ld;
10765     case M_LH_AB:
10766       s = "lh";
10767       fmt = "t,o(b)";
10768       goto ld;
10769     case M_LHU_AB:
10770       s = "lhu";
10771       fmt = "t,o(b)";
10772       goto ld;
10773     case M_LW_AB:
10774       s = "lw";
10775       fmt = "t,o(b)";
10776       goto ld;
10777     case M_LWC0_AB:
10778       gas_assert (!mips_opts.micromips);
10779       s = "lwc0";
10780       fmt = "E,o(b)";
10781       /* Itbl support may require additional care here.  */
10782       coproc = 1;
10783       goto ld_st;
10784     case M_LWC1_AB:
10785       s = "lwc1";
10786       fmt = "T,o(b)";
10787       /* Itbl support may require additional care here.  */
10788       coproc = 1;
10789       goto ld_st;
10790     case M_LWC2_AB:
10791       s = "lwc2";
10792       fmt = COP12_FMT;
10793       offbits = (mips_opts.micromips ? 12 : 16);
10794       /* Itbl support may require additional care here.  */
10795       coproc = 1;
10796       goto ld_st;
10797     case M_LWC3_AB:
10798       gas_assert (!mips_opts.micromips);
10799       s = "lwc3";
10800       fmt = "E,o(b)";
10801       /* Itbl support may require additional care here.  */
10802       coproc = 1;
10803       goto ld_st;
10804     case M_LWL_AB:
10805       s = "lwl";
10806       fmt = MEM12_FMT;
10807       offbits = (mips_opts.micromips ? 12 : 16);
10808       goto ld_st;
10809     case M_LWR_AB:
10810       s = "lwr";
10811       fmt = MEM12_FMT;
10812       offbits = (mips_opts.micromips ? 12 : 16);
10813       goto ld_st;
10814     case M_LDC1_AB:
10815       s = "ldc1";
10816       fmt = "T,o(b)";
10817       /* Itbl support may require additional care here.  */
10818       coproc = 1;
10819       goto ld_st;
10820     case M_LDC2_AB:
10821       s = "ldc2";
10822       fmt = COP12_FMT;
10823       offbits = (mips_opts.micromips ? 12 : 16);
10824       /* Itbl support may require additional care here.  */
10825       coproc = 1;
10826       goto ld_st;
10827     case M_LQC2_AB:
10828       s = "lqc2";
10829       fmt = "+7,o(b)";
10830       /* Itbl support may require additional care here.  */
10831       coproc = 1;
10832       goto ld_st;
10833     case M_LDC3_AB:
10834       s = "ldc3";
10835       fmt = "E,o(b)";
10836       /* Itbl support may require additional care here.  */
10837       coproc = 1;
10838       goto ld_st;
10839     case M_LDL_AB:
10840       s = "ldl";
10841       fmt = MEM12_FMT;
10842       offbits = (mips_opts.micromips ? 12 : 16);
10843       goto ld_st;
10844     case M_LDR_AB:
10845       s = "ldr";
10846       fmt = MEM12_FMT;
10847       offbits = (mips_opts.micromips ? 12 : 16);
10848       goto ld_st;
10849     case M_LL_AB:
10850       s = "ll";
10851       fmt = MEM12_FMT;
10852       offbits = (mips_opts.micromips ? 12 : 16);
10853       goto ld;
10854     case M_LLD_AB:
10855       s = "lld";
10856       fmt = MEM12_FMT;
10857       offbits = (mips_opts.micromips ? 12 : 16);
10858       goto ld;
10859     case M_LWU_AB:
10860       s = "lwu";
10861       fmt = MEM12_FMT;
10862       offbits = (mips_opts.micromips ? 12 : 16);
10863       goto ld;
10864     case M_LWP_AB:
10865       gas_assert (mips_opts.micromips);
10866       s = "lwp";
10867       fmt = "t,~(b)";
10868       offbits = 12;
10869       lp = 1;
10870       goto ld;
10871     case M_LDP_AB:
10872       gas_assert (mips_opts.micromips);
10873       s = "ldp";
10874       fmt = "t,~(b)";
10875       offbits = 12;
10876       lp = 1;
10877       goto ld;
10878     case M_LWM_AB:
10879       gas_assert (mips_opts.micromips);
10880       s = "lwm";
10881       fmt = "n,~(b)";
10882       offbits = 12;
10883       goto ld_st;
10884     case M_LDM_AB:
10885       gas_assert (mips_opts.micromips);
10886       s = "ldm";
10887       fmt = "n,~(b)";
10888       offbits = 12;
10889       goto ld_st;
10890
10891     ld:
10892       /* We don't want to use $0 as tempreg.  */
10893       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
10894         goto ld_st;
10895       else
10896         tempreg = op[0] + lp;
10897       goto ld_noat;
10898
10899     case M_SB_AB:
10900       s = "sb";
10901       fmt = "t,o(b)";
10902       goto ld_st;
10903     case M_SH_AB:
10904       s = "sh";
10905       fmt = "t,o(b)";
10906       goto ld_st;
10907     case M_SW_AB:
10908       s = "sw";
10909       fmt = "t,o(b)";
10910       goto ld_st;
10911     case M_SWC0_AB:
10912       gas_assert (!mips_opts.micromips);
10913       s = "swc0";
10914       fmt = "E,o(b)";
10915       /* Itbl support may require additional care here.  */
10916       coproc = 1;
10917       goto ld_st;
10918     case M_SWC1_AB:
10919       s = "swc1";
10920       fmt = "T,o(b)";
10921       /* Itbl support may require additional care here.  */
10922       coproc = 1;
10923       goto ld_st;
10924     case M_SWC2_AB:
10925       s = "swc2";
10926       fmt = COP12_FMT;
10927       offbits = (mips_opts.micromips ? 12 : 16);
10928       /* Itbl support may require additional care here.  */
10929       coproc = 1;
10930       goto ld_st;
10931     case M_SWC3_AB:
10932       gas_assert (!mips_opts.micromips);
10933       s = "swc3";
10934       fmt = "E,o(b)";
10935       /* Itbl support may require additional care here.  */
10936       coproc = 1;
10937       goto ld_st;
10938     case M_SWL_AB:
10939       s = "swl";
10940       fmt = MEM12_FMT;
10941       offbits = (mips_opts.micromips ? 12 : 16);
10942       goto ld_st;
10943     case M_SWR_AB:
10944       s = "swr";
10945       fmt = MEM12_FMT;
10946       offbits = (mips_opts.micromips ? 12 : 16);
10947       goto ld_st;
10948     case M_SC_AB:
10949       s = "sc";
10950       fmt = MEM12_FMT;
10951       offbits = (mips_opts.micromips ? 12 : 16);
10952       goto ld_st;
10953     case M_SCD_AB:
10954       s = "scd";
10955       fmt = MEM12_FMT;
10956       offbits = (mips_opts.micromips ? 12 : 16);
10957       goto ld_st;
10958     case M_CACHE_AB:
10959       s = "cache";
10960       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
10961       offbits = (mips_opts.micromips ? 12 : 16);
10962       goto ld_st;
10963     case M_CACHEE_AB:
10964       s = "cachee";
10965       fmt = "k,+j(b)";
10966       offbits = 9;
10967       goto ld_st;
10968     case M_PREF_AB:
10969       s = "pref";
10970       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
10971       offbits = (mips_opts.micromips ? 12 : 16);
10972       goto ld_st;
10973     case M_PREFE_AB:
10974       s = "prefe";
10975       fmt = "k,+j(b)";
10976       offbits = 9;
10977       goto ld_st;
10978     case M_SDC1_AB:
10979       s = "sdc1";
10980       fmt = "T,o(b)";
10981       coproc = 1;
10982       /* Itbl support may require additional care here.  */
10983       goto ld_st;
10984     case M_SDC2_AB:
10985       s = "sdc2";
10986       fmt = COP12_FMT;
10987       offbits = (mips_opts.micromips ? 12 : 16);
10988       /* Itbl support may require additional care here.  */
10989       coproc = 1;
10990       goto ld_st;
10991     case M_SQC2_AB:
10992       s = "sqc2";
10993       fmt = "+7,o(b)";
10994       /* Itbl support may require additional care here.  */
10995       coproc = 1;
10996       goto ld_st;
10997     case M_SDC3_AB:
10998       gas_assert (!mips_opts.micromips);
10999       s = "sdc3";
11000       fmt = "E,o(b)";
11001       /* Itbl support may require additional care here.  */
11002       coproc = 1;
11003       goto ld_st;
11004     case M_SDL_AB:
11005       s = "sdl";
11006       fmt = MEM12_FMT;
11007       offbits = (mips_opts.micromips ? 12 : 16);
11008       goto ld_st;
11009     case M_SDR_AB:
11010       s = "sdr";
11011       fmt = MEM12_FMT;
11012       offbits = (mips_opts.micromips ? 12 : 16);
11013       goto ld_st;
11014     case M_SWP_AB:
11015       gas_assert (mips_opts.micromips);
11016       s = "swp";
11017       fmt = "t,~(b)";
11018       offbits = 12;
11019       goto ld_st;
11020     case M_SDP_AB:
11021       gas_assert (mips_opts.micromips);
11022       s = "sdp";
11023       fmt = "t,~(b)";
11024       offbits = 12;
11025       goto ld_st;
11026     case M_SWM_AB:
11027       gas_assert (mips_opts.micromips);
11028       s = "swm";
11029       fmt = "n,~(b)";
11030       offbits = 12;
11031       goto ld_st;
11032     case M_SDM_AB:
11033       gas_assert (mips_opts.micromips);
11034       s = "sdm";
11035       fmt = "n,~(b)";
11036       offbits = 12;
11037
11038     ld_st:
11039       tempreg = AT;
11040     ld_noat:
11041       breg = op[2];
11042       if (small_offset_p (0, align, 16))
11043         {
11044           /* The first case exists for M_LD_AB and M_SD_AB, which are
11045              macros for o32 but which should act like normal instructions
11046              otherwise.  */
11047           if (offbits == 16)
11048             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
11049                          offset_reloc[1], offset_reloc[2], breg);
11050           else if (small_offset_p (0, align, offbits))
11051             {
11052               if (offbits == 0)
11053                 macro_build (NULL, s, fmt, op[0], breg);
11054               else
11055                 macro_build (NULL, s, fmt, op[0],
11056                              (int) offset_expr.X_add_number, breg);
11057             }
11058           else
11059             {
11060               if (tempreg == AT)
11061                 used_at = 1;
11062               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11063                            tempreg, breg, -1, offset_reloc[0],
11064                            offset_reloc[1], offset_reloc[2]);
11065               if (offbits == 0)
11066                 macro_build (NULL, s, fmt, op[0], tempreg);
11067               else
11068                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11069             }
11070           break;
11071         }
11072
11073       if (tempreg == AT)
11074         used_at = 1;
11075
11076       if (offset_expr.X_op != O_constant
11077           && offset_expr.X_op != O_symbol)
11078         {
11079           as_bad (_("expression too complex"));
11080           offset_expr.X_op = O_constant;
11081         }
11082
11083       if (HAVE_32BIT_ADDRESSES
11084           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11085         {
11086           char value [32];
11087
11088           sprintf_vma (value, offset_expr.X_add_number);
11089           as_bad (_("number (0x%s) larger than 32 bits"), value);
11090         }
11091
11092       /* A constant expression in PIC code can be handled just as it
11093          is in non PIC code.  */
11094       if (offset_expr.X_op == O_constant)
11095         {
11096           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11097                                                  offbits == 0 ? 16 : offbits);
11098           offset_expr.X_add_number -= expr1.X_add_number;
11099
11100           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11101           if (breg != 0)
11102             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11103                          tempreg, tempreg, breg);
11104           if (offbits == 0)
11105             {
11106               if (offset_expr.X_add_number != 0)
11107                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11108                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11109               macro_build (NULL, s, fmt, op[0], tempreg);
11110             }
11111           else if (offbits == 16)
11112             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11113           else
11114             macro_build (NULL, s, fmt, op[0],
11115                          (int) offset_expr.X_add_number, tempreg);
11116         }
11117       else if (offbits != 16)
11118         {
11119           /* The offset field is too narrow to be used for a low-part
11120              relocation, so load the whole address into the auxillary
11121              register.  */
11122           load_address (tempreg, &offset_expr, &used_at);
11123           if (breg != 0)
11124             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11125                          tempreg, tempreg, breg);
11126           if (offbits == 0)
11127             macro_build (NULL, s, fmt, op[0], tempreg);
11128           else
11129             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11130         }
11131       else if (mips_pic == NO_PIC)
11132         {
11133           /* If this is a reference to a GP relative symbol, and there
11134              is no base register, we want
11135                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11136              Otherwise, if there is no base register, we want
11137                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11138                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11139              If we have a constant, we need two instructions anyhow,
11140              so we always use the latter form.
11141
11142              If we have a base register, and this is a reference to a
11143              GP relative symbol, we want
11144                addu     $tempreg,$breg,$gp
11145                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11146              Otherwise we want
11147                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11148                addu     $tempreg,$tempreg,$breg
11149                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11150              With a constant we always use the latter case.
11151
11152              With 64bit address space and no base register and $at usable,
11153              we want
11154                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11155                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11156                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11157                dsll32   $tempreg,0
11158                daddu    $tempreg,$at
11159                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11160              If we have a base register, we want
11161                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11162                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11163                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11164                daddu    $at,$breg
11165                dsll32   $tempreg,0
11166                daddu    $tempreg,$at
11167                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11168
11169              Without $at we can't generate the optimal path for superscalar
11170              processors here since this would require two temporary registers.
11171                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11172                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11173                dsll     $tempreg,16
11174                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11175                dsll     $tempreg,16
11176                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11177              If we have a base register, we want
11178                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11179                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11180                dsll     $tempreg,16
11181                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11182                dsll     $tempreg,16
11183                daddu    $tempreg,$tempreg,$breg
11184                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11185
11186              For GP relative symbols in 64bit address space we can use
11187              the same sequence as in 32bit address space.  */
11188           if (HAVE_64BIT_SYMBOLS)
11189             {
11190               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11191                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11192                 {
11193                   relax_start (offset_expr.X_add_symbol);
11194                   if (breg == 0)
11195                     {
11196                       macro_build (&offset_expr, s, fmt, op[0],
11197                                    BFD_RELOC_GPREL16, mips_gp_register);
11198                     }
11199                   else
11200                     {
11201                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11202                                    tempreg, breg, mips_gp_register);
11203                       macro_build (&offset_expr, s, fmt, op[0],
11204                                    BFD_RELOC_GPREL16, tempreg);
11205                     }
11206                   relax_switch ();
11207                 }
11208
11209               if (used_at == 0 && mips_opts.at)
11210                 {
11211                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11212                                BFD_RELOC_MIPS_HIGHEST);
11213                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11214                                BFD_RELOC_HI16_S);
11215                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11216                                tempreg, BFD_RELOC_MIPS_HIGHER);
11217                   if (breg != 0)
11218                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11219                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11220                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11221                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11222                                tempreg);
11223                   used_at = 1;
11224                 }
11225               else
11226                 {
11227                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11228                                BFD_RELOC_MIPS_HIGHEST);
11229                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11230                                tempreg, BFD_RELOC_MIPS_HIGHER);
11231                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11232                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11233                                tempreg, BFD_RELOC_HI16_S);
11234                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11235                   if (breg != 0)
11236                     macro_build (NULL, "daddu", "d,v,t",
11237                                  tempreg, tempreg, breg);
11238                   macro_build (&offset_expr, s, fmt, op[0],
11239                                BFD_RELOC_LO16, tempreg);
11240                 }
11241
11242               if (mips_relax.sequence)
11243                 relax_end ();
11244               break;
11245             }
11246
11247           if (breg == 0)
11248             {
11249               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11250                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11251                 {
11252                   relax_start (offset_expr.X_add_symbol);
11253                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11254                                mips_gp_register);
11255                   relax_switch ();
11256                 }
11257               macro_build_lui (&offset_expr, tempreg);
11258               macro_build (&offset_expr, s, fmt, op[0],
11259                            BFD_RELOC_LO16, tempreg);
11260               if (mips_relax.sequence)
11261                 relax_end ();
11262             }
11263           else
11264             {
11265               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11266                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11267                 {
11268                   relax_start (offset_expr.X_add_symbol);
11269                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11270                                tempreg, breg, mips_gp_register);
11271                   macro_build (&offset_expr, s, fmt, op[0],
11272                                BFD_RELOC_GPREL16, tempreg);
11273                   relax_switch ();
11274                 }
11275               macro_build_lui (&offset_expr, tempreg);
11276               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11277                            tempreg, tempreg, breg);
11278               macro_build (&offset_expr, s, fmt, op[0],
11279                            BFD_RELOC_LO16, tempreg);
11280               if (mips_relax.sequence)
11281                 relax_end ();
11282             }
11283         }
11284       else if (!mips_big_got)
11285         {
11286           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11287
11288           /* If this is a reference to an external symbol, we want
11289                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11290                nop
11291                <op>     op[0],0($tempreg)
11292              Otherwise we want
11293                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11294                nop
11295                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11296                <op>     op[0],0($tempreg)
11297
11298              For NewABI, we want
11299                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11300                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11301
11302              If there is a base register, we add it to $tempreg before
11303              the <op>.  If there is a constant, we stick it in the
11304              <op> instruction.  We don't handle constants larger than
11305              16 bits, because we have no way to load the upper 16 bits
11306              (actually, we could handle them for the subset of cases
11307              in which we are not using $at).  */
11308           gas_assert (offset_expr.X_op == O_symbol);
11309           if (HAVE_NEWABI)
11310             {
11311               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11312                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11313               if (breg != 0)
11314                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11315                              tempreg, tempreg, breg);
11316               macro_build (&offset_expr, s, fmt, op[0],
11317                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11318               break;
11319             }
11320           expr1.X_add_number = offset_expr.X_add_number;
11321           offset_expr.X_add_number = 0;
11322           if (expr1.X_add_number < -0x8000
11323               || expr1.X_add_number >= 0x8000)
11324             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11325           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11326                        lw_reloc_type, mips_gp_register);
11327           load_delay_nop ();
11328           relax_start (offset_expr.X_add_symbol);
11329           relax_switch ();
11330           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11331                        tempreg, BFD_RELOC_LO16);
11332           relax_end ();
11333           if (breg != 0)
11334             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11335                          tempreg, tempreg, breg);
11336           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11337         }
11338       else if (mips_big_got && !HAVE_NEWABI)
11339         {
11340           int gpdelay;
11341
11342           /* If this is a reference to an external symbol, we want
11343                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11344                addu     $tempreg,$tempreg,$gp
11345                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11346                <op>     op[0],0($tempreg)
11347              Otherwise we want
11348                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11349                nop
11350                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11351                <op>     op[0],0($tempreg)
11352              If there is a base register, we add it to $tempreg before
11353              the <op>.  If there is a constant, we stick it in the
11354              <op> instruction.  We don't handle constants larger than
11355              16 bits, because we have no way to load the upper 16 bits
11356              (actually, we could handle them for the subset of cases
11357              in which we are not using $at).  */
11358           gas_assert (offset_expr.X_op == O_symbol);
11359           expr1.X_add_number = offset_expr.X_add_number;
11360           offset_expr.X_add_number = 0;
11361           if (expr1.X_add_number < -0x8000
11362               || expr1.X_add_number >= 0x8000)
11363             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11364           gpdelay = reg_needs_delay (mips_gp_register);
11365           relax_start (offset_expr.X_add_symbol);
11366           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11367                        BFD_RELOC_MIPS_GOT_HI16);
11368           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11369                        mips_gp_register);
11370           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11371                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11372           relax_switch ();
11373           if (gpdelay)
11374             macro_build (NULL, "nop", "");
11375           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11376                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11377           load_delay_nop ();
11378           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11379                        tempreg, BFD_RELOC_LO16);
11380           relax_end ();
11381
11382           if (breg != 0)
11383             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11384                          tempreg, tempreg, breg);
11385           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11386         }
11387       else if (mips_big_got && HAVE_NEWABI)
11388         {
11389           /* If this is a reference to an external symbol, we want
11390                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11391                add      $tempreg,$tempreg,$gp
11392                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11393                <op>     op[0],<ofst>($tempreg)
11394              Otherwise, for local symbols, we want:
11395                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11396                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11397           gas_assert (offset_expr.X_op == O_symbol);
11398           expr1.X_add_number = offset_expr.X_add_number;
11399           offset_expr.X_add_number = 0;
11400           if (expr1.X_add_number < -0x8000
11401               || expr1.X_add_number >= 0x8000)
11402             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11403           relax_start (offset_expr.X_add_symbol);
11404           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11405                        BFD_RELOC_MIPS_GOT_HI16);
11406           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11407                        mips_gp_register);
11408           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11409                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11410           if (breg != 0)
11411             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11412                          tempreg, tempreg, breg);
11413           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11414
11415           relax_switch ();
11416           offset_expr.X_add_number = expr1.X_add_number;
11417           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11418                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11419           if (breg != 0)
11420             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11421                          tempreg, tempreg, breg);
11422           macro_build (&offset_expr, s, fmt, op[0],
11423                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11424           relax_end ();
11425         }
11426       else
11427         abort ();
11428
11429       break;
11430
11431     case M_JRADDIUSP:
11432       gas_assert (mips_opts.micromips);
11433       gas_assert (mips_opts.insn32);
11434       start_noreorder ();
11435       macro_build (NULL, "jr", "s", RA);
11436       expr1.X_add_number = op[0] << 2;
11437       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11438       end_noreorder ();
11439       break;
11440
11441     case M_JRC:
11442       gas_assert (mips_opts.micromips);
11443       gas_assert (mips_opts.insn32);
11444       macro_build (NULL, "jr", "s", op[0]);
11445       if (mips_opts.noreorder)
11446         macro_build (NULL, "nop", "");
11447       break;
11448
11449     case M_LI:
11450     case M_LI_S:
11451       load_register (op[0], &imm_expr, 0);
11452       break;
11453
11454     case M_DLI:
11455       load_register (op[0], &imm_expr, 1);
11456       break;
11457
11458     case M_LI_SS:
11459       if (imm_expr.X_op == O_constant)
11460         {
11461           used_at = 1;
11462           load_register (AT, &imm_expr, 0);
11463           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11464           break;
11465         }
11466       else
11467         {
11468           gas_assert (imm_expr.X_op == O_absent
11469                       && offset_expr.X_op == O_symbol
11470                       && strcmp (segment_name (S_GET_SEGMENT
11471                                                (offset_expr.X_add_symbol)),
11472                                  ".lit4") == 0
11473                       && offset_expr.X_add_number == 0);
11474           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11475                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11476           break;
11477         }
11478
11479     case M_LI_D:
11480       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11481          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11482          order 32 bits of the value and the low order 32 bits are either
11483          zero or in OFFSET_EXPR.  */
11484       if (imm_expr.X_op == O_constant)
11485         {
11486           if (HAVE_64BIT_GPRS)
11487             load_register (op[0], &imm_expr, 1);
11488           else
11489             {
11490               int hreg, lreg;
11491
11492               if (target_big_endian)
11493                 {
11494                   hreg = op[0];
11495                   lreg = op[0] + 1;
11496                 }
11497               else
11498                 {
11499                   hreg = op[0] + 1;
11500                   lreg = op[0];
11501                 }
11502
11503               if (hreg <= 31)
11504                 load_register (hreg, &imm_expr, 0);
11505               if (lreg <= 31)
11506                 {
11507                   if (offset_expr.X_op == O_absent)
11508                     move_register (lreg, 0);
11509                   else
11510                     {
11511                       gas_assert (offset_expr.X_op == O_constant);
11512                       load_register (lreg, &offset_expr, 0);
11513                     }
11514                 }
11515             }
11516           break;
11517         }
11518       gas_assert (imm_expr.X_op == O_absent);
11519
11520       /* We know that sym is in the .rdata section.  First we get the
11521          upper 16 bits of the address.  */
11522       if (mips_pic == NO_PIC)
11523         {
11524           macro_build_lui (&offset_expr, AT);
11525           used_at = 1;
11526         }
11527       else
11528         {
11529           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11530                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11531           used_at = 1;
11532         }
11533
11534       /* Now we load the register(s).  */
11535       if (HAVE_64BIT_GPRS)
11536         {
11537           used_at = 1;
11538           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11539                        BFD_RELOC_LO16, AT);
11540         }
11541       else
11542         {
11543           used_at = 1;
11544           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11545                        BFD_RELOC_LO16, AT);
11546           if (op[0] != RA)
11547             {
11548               /* FIXME: How in the world do we deal with the possible
11549                  overflow here?  */
11550               offset_expr.X_add_number += 4;
11551               macro_build (&offset_expr, "lw", "t,o(b)",
11552                            op[0] + 1, BFD_RELOC_LO16, AT);
11553             }
11554         }
11555       break;
11556
11557     case M_LI_DD:
11558       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11559          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11560          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11561          the value and the low order 32 bits are either zero or in
11562          OFFSET_EXPR.  */
11563       if (imm_expr.X_op == O_constant)
11564         {
11565           used_at = 1;
11566           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
11567           if (HAVE_64BIT_FPRS)
11568             {
11569               gas_assert (HAVE_64BIT_GPRS);
11570               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11571             }
11572           else
11573             {
11574               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11575               if (offset_expr.X_op == O_absent)
11576                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11577               else
11578                 {
11579                   gas_assert (offset_expr.X_op == O_constant);
11580                   load_register (AT, &offset_expr, 0);
11581                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11582                 }
11583             }
11584           break;
11585         }
11586
11587       gas_assert (imm_expr.X_op == O_absent
11588                   && offset_expr.X_op == O_symbol
11589                   && offset_expr.X_add_number == 0);
11590       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11591       if (strcmp (s, ".lit8") == 0)
11592         {
11593           op[2] = mips_gp_register;
11594           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11595           offset_reloc[1] = BFD_RELOC_UNUSED;
11596           offset_reloc[2] = BFD_RELOC_UNUSED;
11597         }
11598       else
11599         {
11600           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11601           used_at = 1;
11602           if (mips_pic != NO_PIC)
11603             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11604                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11605           else
11606             {
11607               /* FIXME: This won't work for a 64 bit address.  */
11608               macro_build_lui (&offset_expr, AT);
11609             }
11610
11611           op[2] = AT;
11612           offset_reloc[0] = BFD_RELOC_LO16;
11613           offset_reloc[1] = BFD_RELOC_UNUSED;
11614           offset_reloc[2] = BFD_RELOC_UNUSED;
11615         }
11616       align = 8;
11617       /* Fall through */
11618
11619     case M_L_DAB:
11620       /*
11621        * The MIPS assembler seems to check for X_add_number not
11622        * being double aligned and generating:
11623        *        lui     at,%hi(foo+1)
11624        *        addu    at,at,v1
11625        *        addiu   at,at,%lo(foo+1)
11626        *        lwc1    f2,0(at)
11627        *        lwc1    f3,4(at)
11628        * But, the resulting address is the same after relocation so why
11629        * generate the extra instruction?
11630        */
11631       /* Itbl support may require additional care here.  */
11632       coproc = 1;
11633       fmt = "T,o(b)";
11634       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11635         {
11636           s = "ldc1";
11637           goto ld_st;
11638         }
11639       s = "lwc1";
11640       goto ldd_std;
11641
11642     case M_S_DAB:
11643       gas_assert (!mips_opts.micromips);
11644       /* Itbl support may require additional care here.  */
11645       coproc = 1;
11646       fmt = "T,o(b)";
11647       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11648         {
11649           s = "sdc1";
11650           goto ld_st;
11651         }
11652       s = "swc1";
11653       goto ldd_std;
11654
11655     case M_LQ_AB:
11656       fmt = "t,o(b)";
11657       s = "lq";
11658       goto ld;
11659
11660     case M_SQ_AB:
11661       fmt = "t,o(b)";
11662       s = "sq";
11663       goto ld_st;
11664
11665     case M_LD_AB:
11666       fmt = "t,o(b)";
11667       if (HAVE_64BIT_GPRS)
11668         {
11669           s = "ld";
11670           goto ld;
11671         }
11672       s = "lw";
11673       goto ldd_std;
11674
11675     case M_SD_AB:
11676       fmt = "t,o(b)";
11677       if (HAVE_64BIT_GPRS)
11678         {
11679           s = "sd";
11680           goto ld_st;
11681         }
11682       s = "sw";
11683
11684     ldd_std:
11685       /* Even on a big endian machine $fn comes before $fn+1.  We have
11686          to adjust when loading from memory.  We set coproc if we must
11687          load $fn+1 first.  */
11688       /* Itbl support may require additional care here.  */
11689       if (!target_big_endian)
11690         coproc = 0;
11691
11692       breg = op[2];
11693       if (small_offset_p (0, align, 16))
11694         {
11695           ep = &offset_expr;
11696           if (!small_offset_p (4, align, 16))
11697             {
11698               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11699                            -1, offset_reloc[0], offset_reloc[1],
11700                            offset_reloc[2]);
11701               expr1.X_add_number = 0;
11702               ep = &expr1;
11703               breg = AT;
11704               used_at = 1;
11705               offset_reloc[0] = BFD_RELOC_LO16;
11706               offset_reloc[1] = BFD_RELOC_UNUSED;
11707               offset_reloc[2] = BFD_RELOC_UNUSED;
11708             }
11709           if (strcmp (s, "lw") == 0 && op[0] == breg)
11710             {
11711               ep->X_add_number += 4;
11712               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11713                            offset_reloc[1], offset_reloc[2], breg);
11714               ep->X_add_number -= 4;
11715               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11716                            offset_reloc[1], offset_reloc[2], breg);
11717             }
11718           else
11719             {
11720               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11721                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11722                            breg);
11723               ep->X_add_number += 4;
11724               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11725                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11726                            breg);
11727             }
11728           break;
11729         }
11730
11731       if (offset_expr.X_op != O_symbol
11732           && offset_expr.X_op != O_constant)
11733         {
11734           as_bad (_("expression too complex"));
11735           offset_expr.X_op = O_constant;
11736         }
11737
11738       if (HAVE_32BIT_ADDRESSES
11739           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11740         {
11741           char value [32];
11742
11743           sprintf_vma (value, offset_expr.X_add_number);
11744           as_bad (_("number (0x%s) larger than 32 bits"), value);
11745         }
11746
11747       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11748         {
11749           /* If this is a reference to a GP relative symbol, we want
11750                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11751                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11752              If we have a base register, we use this
11753                addu     $at,$breg,$gp
11754                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11755                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11756              If this is not a GP relative symbol, we want
11757                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11758                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11759                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11760              If there is a base register, we add it to $at after the
11761              lui instruction.  If there is a constant, we always use
11762              the last case.  */
11763           if (offset_expr.X_op == O_symbol
11764               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11765               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11766             {
11767               relax_start (offset_expr.X_add_symbol);
11768               if (breg == 0)
11769                 {
11770                   tempreg = mips_gp_register;
11771                 }
11772               else
11773                 {
11774                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11775                                AT, breg, mips_gp_register);
11776                   tempreg = AT;
11777                   used_at = 1;
11778                 }
11779
11780               /* Itbl support may require additional care here.  */
11781               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11782                            BFD_RELOC_GPREL16, tempreg);
11783               offset_expr.X_add_number += 4;
11784
11785               /* Set mips_optimize to 2 to avoid inserting an
11786                  undesired nop.  */
11787               hold_mips_optimize = mips_optimize;
11788               mips_optimize = 2;
11789               /* Itbl support may require additional care here.  */
11790               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11791                            BFD_RELOC_GPREL16, tempreg);
11792               mips_optimize = hold_mips_optimize;
11793
11794               relax_switch ();
11795
11796               offset_expr.X_add_number -= 4;
11797             }
11798           used_at = 1;
11799           if (offset_high_part (offset_expr.X_add_number, 16)
11800               != offset_high_part (offset_expr.X_add_number + 4, 16))
11801             {
11802               load_address (AT, &offset_expr, &used_at);
11803               offset_expr.X_op = O_constant;
11804               offset_expr.X_add_number = 0;
11805             }
11806           else
11807             macro_build_lui (&offset_expr, AT);
11808           if (breg != 0)
11809             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11810           /* Itbl support may require additional care here.  */
11811           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11812                        BFD_RELOC_LO16, AT);
11813           /* FIXME: How do we handle overflow here?  */
11814           offset_expr.X_add_number += 4;
11815           /* Itbl support may require additional care here.  */
11816           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11817                        BFD_RELOC_LO16, AT);
11818           if (mips_relax.sequence)
11819             relax_end ();
11820         }
11821       else if (!mips_big_got)
11822         {
11823           /* If this is a reference to an external symbol, we want
11824                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11825                nop
11826                <op>     op[0],0($at)
11827                <op>     op[0]+1,4($at)
11828              Otherwise we want
11829                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11830                nop
11831                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11832                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11833              If there is a base register we add it to $at before the
11834              lwc1 instructions.  If there is a constant we include it
11835              in the lwc1 instructions.  */
11836           used_at = 1;
11837           expr1.X_add_number = offset_expr.X_add_number;
11838           if (expr1.X_add_number < -0x8000
11839               || expr1.X_add_number >= 0x8000 - 4)
11840             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11841           load_got_offset (AT, &offset_expr);
11842           load_delay_nop ();
11843           if (breg != 0)
11844             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11845
11846           /* Set mips_optimize to 2 to avoid inserting an undesired
11847              nop.  */
11848           hold_mips_optimize = mips_optimize;
11849           mips_optimize = 2;
11850
11851           /* Itbl support may require additional care here.  */
11852           relax_start (offset_expr.X_add_symbol);
11853           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11854                        BFD_RELOC_LO16, AT);
11855           expr1.X_add_number += 4;
11856           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11857                        BFD_RELOC_LO16, AT);
11858           relax_switch ();
11859           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11860                        BFD_RELOC_LO16, AT);
11861           offset_expr.X_add_number += 4;
11862           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11863                        BFD_RELOC_LO16, AT);
11864           relax_end ();
11865
11866           mips_optimize = hold_mips_optimize;
11867         }
11868       else if (mips_big_got)
11869         {
11870           int gpdelay;
11871
11872           /* If this is a reference to an external symbol, we want
11873                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11874                addu     $at,$at,$gp
11875                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11876                nop
11877                <op>     op[0],0($at)
11878                <op>     op[0]+1,4($at)
11879              Otherwise we want
11880                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11881                nop
11882                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11883                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11884              If there is a base register we add it to $at before the
11885              lwc1 instructions.  If there is a constant we include it
11886              in the lwc1 instructions.  */
11887           used_at = 1;
11888           expr1.X_add_number = offset_expr.X_add_number;
11889           offset_expr.X_add_number = 0;
11890           if (expr1.X_add_number < -0x8000
11891               || expr1.X_add_number >= 0x8000 - 4)
11892             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11893           gpdelay = reg_needs_delay (mips_gp_register);
11894           relax_start (offset_expr.X_add_symbol);
11895           macro_build (&offset_expr, "lui", LUI_FMT,
11896                        AT, BFD_RELOC_MIPS_GOT_HI16);
11897           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11898                        AT, AT, mips_gp_register);
11899           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11900                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
11901           load_delay_nop ();
11902           if (breg != 0)
11903             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11904           /* Itbl support may require additional care here.  */
11905           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11906                        BFD_RELOC_LO16, AT);
11907           expr1.X_add_number += 4;
11908
11909           /* Set mips_optimize to 2 to avoid inserting an undesired
11910              nop.  */
11911           hold_mips_optimize = mips_optimize;
11912           mips_optimize = 2;
11913           /* Itbl support may require additional care here.  */
11914           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11915                        BFD_RELOC_LO16, AT);
11916           mips_optimize = hold_mips_optimize;
11917           expr1.X_add_number -= 4;
11918
11919           relax_switch ();
11920           offset_expr.X_add_number = expr1.X_add_number;
11921           if (gpdelay)
11922             macro_build (NULL, "nop", "");
11923           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11924                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11925           load_delay_nop ();
11926           if (breg != 0)
11927             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11928           /* Itbl support may require additional care here.  */
11929           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11930                        BFD_RELOC_LO16, AT);
11931           offset_expr.X_add_number += 4;
11932
11933           /* Set mips_optimize to 2 to avoid inserting an undesired
11934              nop.  */
11935           hold_mips_optimize = mips_optimize;
11936           mips_optimize = 2;
11937           /* Itbl support may require additional care here.  */
11938           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11939                        BFD_RELOC_LO16, AT);
11940           mips_optimize = hold_mips_optimize;
11941           relax_end ();
11942         }
11943       else
11944         abort ();
11945
11946       break;
11947         
11948     case M_SAA_AB:
11949       s = "saa";
11950       offbits = 0;
11951       fmt = "t,(b)";
11952       goto ld_st;
11953     case M_SAAD_AB:
11954       s = "saad";
11955       offbits = 0;
11956       fmt = "t,(b)";
11957       goto ld_st;
11958
11959    /* New code added to support COPZ instructions.
11960       This code builds table entries out of the macros in mip_opcodes.
11961       R4000 uses interlocks to handle coproc delays.
11962       Other chips (like the R3000) require nops to be inserted for delays.
11963
11964       FIXME: Currently, we require that the user handle delays.
11965       In order to fill delay slots for non-interlocked chips,
11966       we must have a way to specify delays based on the coprocessor.
11967       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
11968       What are the side-effects of the cop instruction?
11969       What cache support might we have and what are its effects?
11970       Both coprocessor & memory require delays. how long???
11971       What registers are read/set/modified?
11972
11973       If an itbl is provided to interpret cop instructions,
11974       this knowledge can be encoded in the itbl spec.  */
11975
11976     case M_COP0:
11977       s = "c0";
11978       goto copz;
11979     case M_COP1:
11980       s = "c1";
11981       goto copz;
11982     case M_COP2:
11983       s = "c2";
11984       goto copz;
11985     case M_COP3:
11986       s = "c3";
11987     copz:
11988       gas_assert (!mips_opts.micromips);
11989       /* For now we just do C (same as Cz).  The parameter will be
11990          stored in insn_opcode by mips_ip.  */
11991       macro_build (NULL, s, "C", (int) ip->insn_opcode);
11992       break;
11993
11994     case M_MOVE:
11995       move_register (op[0], op[1]);
11996       break;
11997
11998     case M_MOVEP:
11999       gas_assert (mips_opts.micromips);
12000       gas_assert (mips_opts.insn32);
12001       move_register (micromips_to_32_reg_h_map1[op[0]],
12002                      micromips_to_32_reg_m_map[op[1]]);
12003       move_register (micromips_to_32_reg_h_map2[op[0]],
12004                      micromips_to_32_reg_n_map[op[2]]);
12005       break;
12006
12007     case M_DMUL:
12008       dbl = 1;
12009     case M_MUL:
12010       if (mips_opts.arch == CPU_R5900)
12011         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
12012                      op[2]);
12013       else
12014         {
12015           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
12016           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12017         }
12018       break;
12019
12020     case M_DMUL_I:
12021       dbl = 1;
12022     case M_MUL_I:
12023       /* The MIPS assembler some times generates shifts and adds.  I'm
12024          not trying to be that fancy. GCC should do this for us
12025          anyway.  */
12026       used_at = 1;
12027       load_register (AT, &imm_expr, dbl);
12028       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
12029       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12030       break;
12031
12032     case M_DMULO_I:
12033       dbl = 1;
12034     case M_MULO_I:
12035       imm = 1;
12036       goto do_mulo;
12037
12038     case M_DMULO:
12039       dbl = 1;
12040     case M_MULO:
12041     do_mulo:
12042       start_noreorder ();
12043       used_at = 1;
12044       if (imm)
12045         load_register (AT, &imm_expr, dbl);
12046       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
12047                    op[1], imm ? AT : op[2]);
12048       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12049       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12050       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12051       if (mips_trap)
12052         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12053       else
12054         {
12055           if (mips_opts.micromips)
12056             micromips_label_expr (&label_expr);
12057           else
12058             label_expr.X_add_number = 8;
12059           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12060           macro_build (NULL, "nop", "");
12061           macro_build (NULL, "break", BRK_FMT, 6);
12062           if (mips_opts.micromips)
12063             micromips_add_label ();
12064         }
12065       end_noreorder ();
12066       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12067       break;
12068
12069     case M_DMULOU_I:
12070       dbl = 1;
12071     case M_MULOU_I:
12072       imm = 1;
12073       goto do_mulou;
12074
12075     case M_DMULOU:
12076       dbl = 1;
12077     case M_MULOU:
12078     do_mulou:
12079       start_noreorder ();
12080       used_at = 1;
12081       if (imm)
12082         load_register (AT, &imm_expr, dbl);
12083       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12084                    op[1], imm ? AT : op[2]);
12085       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12086       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12087       if (mips_trap)
12088         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12089       else
12090         {
12091           if (mips_opts.micromips)
12092             micromips_label_expr (&label_expr);
12093           else
12094             label_expr.X_add_number = 8;
12095           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12096           macro_build (NULL, "nop", "");
12097           macro_build (NULL, "break", BRK_FMT, 6);
12098           if (mips_opts.micromips)
12099             micromips_add_label ();
12100         }
12101       end_noreorder ();
12102       break;
12103
12104     case M_DROL:
12105       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12106         {
12107           if (op[0] == op[1])
12108             {
12109               tempreg = AT;
12110               used_at = 1;
12111             }
12112           else
12113             tempreg = op[0];
12114           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12115           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12116           break;
12117         }
12118       used_at = 1;
12119       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12120       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12121       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12122       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12123       break;
12124
12125     case M_ROL:
12126       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12127         {
12128           if (op[0] == op[1])
12129             {
12130               tempreg = AT;
12131               used_at = 1;
12132             }
12133           else
12134             tempreg = op[0];
12135           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12136           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12137           break;
12138         }
12139       used_at = 1;
12140       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12141       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12142       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12143       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12144       break;
12145
12146     case M_DROL_I:
12147       {
12148         unsigned int rot;
12149         char *l;
12150         char *rr;
12151
12152         rot = imm_expr.X_add_number & 0x3f;
12153         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12154           {
12155             rot = (64 - rot) & 0x3f;
12156             if (rot >= 32)
12157               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12158             else
12159               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12160             break;
12161           }
12162         if (rot == 0)
12163           {
12164             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12165             break;
12166           }
12167         l = (rot < 0x20) ? "dsll" : "dsll32";
12168         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12169         rot &= 0x1f;
12170         used_at = 1;
12171         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12172         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12173         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12174       }
12175       break;
12176
12177     case M_ROL_I:
12178       {
12179         unsigned int rot;
12180
12181         rot = imm_expr.X_add_number & 0x1f;
12182         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12183           {
12184             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12185                          (32 - rot) & 0x1f);
12186             break;
12187           }
12188         if (rot == 0)
12189           {
12190             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12191             break;
12192           }
12193         used_at = 1;
12194         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12195         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12196         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12197       }
12198       break;
12199
12200     case M_DROR:
12201       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12202         {
12203           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12204           break;
12205         }
12206       used_at = 1;
12207       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12208       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12209       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12210       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12211       break;
12212
12213     case M_ROR:
12214       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12215         {
12216           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12217           break;
12218         }
12219       used_at = 1;
12220       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12221       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12222       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12223       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12224       break;
12225
12226     case M_DROR_I:
12227       {
12228         unsigned int rot;
12229         char *l;
12230         char *rr;
12231
12232         rot = imm_expr.X_add_number & 0x3f;
12233         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12234           {
12235             if (rot >= 32)
12236               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12237             else
12238               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12239             break;
12240           }
12241         if (rot == 0)
12242           {
12243             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12244             break;
12245           }
12246         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12247         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12248         rot &= 0x1f;
12249         used_at = 1;
12250         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12251         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12252         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12253       }
12254       break;
12255
12256     case M_ROR_I:
12257       {
12258         unsigned int rot;
12259
12260         rot = imm_expr.X_add_number & 0x1f;
12261         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12262           {
12263             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12264             break;
12265           }
12266         if (rot == 0)
12267           {
12268             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12269             break;
12270           }
12271         used_at = 1;
12272         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12273         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12274         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12275       }
12276       break;
12277
12278     case M_SEQ:
12279       if (op[1] == 0)
12280         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12281       else if (op[2] == 0)
12282         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12283       else
12284         {
12285           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12286           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12287         }
12288       break;
12289
12290     case M_SEQ_I:
12291       if (imm_expr.X_add_number == 0)
12292         {
12293           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12294           break;
12295         }
12296       if (op[1] == 0)
12297         {
12298           as_warn (_("instruction %s: result is always false"),
12299                    ip->insn_mo->name);
12300           move_register (op[0], 0);
12301           break;
12302         }
12303       if (CPU_HAS_SEQ (mips_opts.arch)
12304           && -512 <= imm_expr.X_add_number
12305           && imm_expr.X_add_number < 512)
12306         {
12307           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12308                        (int) imm_expr.X_add_number);
12309           break;
12310         }
12311       if (imm_expr.X_add_number >= 0
12312           && imm_expr.X_add_number < 0x10000)
12313         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12314       else if (imm_expr.X_add_number > -0x8000
12315                && imm_expr.X_add_number < 0)
12316         {
12317           imm_expr.X_add_number = -imm_expr.X_add_number;
12318           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12319                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12320         }
12321       else if (CPU_HAS_SEQ (mips_opts.arch))
12322         {
12323           used_at = 1;
12324           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12325           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12326           break;
12327         }
12328       else
12329         {
12330           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12331           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12332           used_at = 1;
12333         }
12334       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12335       break;
12336
12337     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12338       s = "slt";
12339       goto sge;
12340     case M_SGEU:
12341       s = "sltu";
12342     sge:
12343       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12344       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12345       break;
12346
12347     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12348     case M_SGEU_I:
12349       if (imm_expr.X_add_number >= -0x8000
12350           && imm_expr.X_add_number < 0x8000)
12351         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12352                      op[0], op[1], BFD_RELOC_LO16);
12353       else
12354         {
12355           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12356           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12357                        op[0], op[1], AT);
12358           used_at = 1;
12359         }
12360       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12361       break;
12362
12363     case M_SGT:         /* X > Y  <==>  Y < X */
12364       s = "slt";
12365       goto sgt;
12366     case M_SGTU:
12367       s = "sltu";
12368     sgt:
12369       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12370       break;
12371
12372     case M_SGT_I:       /* X > I  <==>  I < X */
12373       s = "slt";
12374       goto sgti;
12375     case M_SGTU_I:
12376       s = "sltu";
12377     sgti:
12378       used_at = 1;
12379       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12380       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12381       break;
12382
12383     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12384       s = "slt";
12385       goto sle;
12386     case M_SLEU:
12387       s = "sltu";
12388     sle:
12389       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12390       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12391       break;
12392
12393     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12394       s = "slt";
12395       goto slei;
12396     case M_SLEU_I:
12397       s = "sltu";
12398     slei:
12399       used_at = 1;
12400       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12401       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12402       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12403       break;
12404
12405     case M_SLT_I:
12406       if (imm_expr.X_add_number >= -0x8000
12407           && imm_expr.X_add_number < 0x8000)
12408         {
12409           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12410                        BFD_RELOC_LO16);
12411           break;
12412         }
12413       used_at = 1;
12414       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12415       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12416       break;
12417
12418     case M_SLTU_I:
12419       if (imm_expr.X_add_number >= -0x8000
12420           && imm_expr.X_add_number < 0x8000)
12421         {
12422           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12423                        BFD_RELOC_LO16);
12424           break;
12425         }
12426       used_at = 1;
12427       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12428       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12429       break;
12430
12431     case M_SNE:
12432       if (op[1] == 0)
12433         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12434       else if (op[2] == 0)
12435         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12436       else
12437         {
12438           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12439           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12440         }
12441       break;
12442
12443     case M_SNE_I:
12444       if (imm_expr.X_add_number == 0)
12445         {
12446           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12447           break;
12448         }
12449       if (op[1] == 0)
12450         {
12451           as_warn (_("instruction %s: result is always true"),
12452                    ip->insn_mo->name);
12453           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
12454                        op[0], 0, BFD_RELOC_LO16);
12455           break;
12456         }
12457       if (CPU_HAS_SEQ (mips_opts.arch)
12458           && -512 <= imm_expr.X_add_number
12459           && imm_expr.X_add_number < 512)
12460         {
12461           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12462                        (int) imm_expr.X_add_number);
12463           break;
12464         }
12465       if (imm_expr.X_add_number >= 0
12466           && imm_expr.X_add_number < 0x10000)
12467         {
12468           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12469                        BFD_RELOC_LO16);
12470         }
12471       else if (imm_expr.X_add_number > -0x8000
12472                && imm_expr.X_add_number < 0)
12473         {
12474           imm_expr.X_add_number = -imm_expr.X_add_number;
12475           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12476                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12477         }
12478       else if (CPU_HAS_SEQ (mips_opts.arch))
12479         {
12480           used_at = 1;
12481           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12482           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12483           break;
12484         }
12485       else
12486         {
12487           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12488           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12489           used_at = 1;
12490         }
12491       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12492       break;
12493
12494     case M_SUB_I:
12495       s = "addi";
12496       s2 = "sub";
12497       goto do_subi;
12498     case M_SUBU_I:
12499       s = "addiu";
12500       s2 = "subu";
12501       goto do_subi;
12502     case M_DSUB_I:
12503       dbl = 1;
12504       s = "daddi";
12505       s2 = "dsub";
12506       if (!mips_opts.micromips)
12507         goto do_subi;
12508       if (imm_expr.X_add_number > -0x200
12509           && imm_expr.X_add_number <= 0x200)
12510         {
12511           macro_build (NULL, s, "t,r,.", op[0], op[1],
12512                        (int) -imm_expr.X_add_number);
12513           break;
12514         }
12515       goto do_subi_i;
12516     case M_DSUBU_I:
12517       dbl = 1;
12518       s = "daddiu";
12519       s2 = "dsubu";
12520     do_subi:
12521       if (imm_expr.X_add_number > -0x8000
12522           && imm_expr.X_add_number <= 0x8000)
12523         {
12524           imm_expr.X_add_number = -imm_expr.X_add_number;
12525           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12526           break;
12527         }
12528     do_subi_i:
12529       used_at = 1;
12530       load_register (AT, &imm_expr, dbl);
12531       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12532       break;
12533
12534     case M_TEQ_I:
12535       s = "teq";
12536       goto trap;
12537     case M_TGE_I:
12538       s = "tge";
12539       goto trap;
12540     case M_TGEU_I:
12541       s = "tgeu";
12542       goto trap;
12543     case M_TLT_I:
12544       s = "tlt";
12545       goto trap;
12546     case M_TLTU_I:
12547       s = "tltu";
12548       goto trap;
12549     case M_TNE_I:
12550       s = "tne";
12551     trap:
12552       used_at = 1;
12553       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12554       macro_build (NULL, s, "s,t", op[0], AT);
12555       break;
12556
12557     case M_TRUNCWS:
12558     case M_TRUNCWD:
12559       gas_assert (!mips_opts.micromips);
12560       gas_assert (mips_opts.isa == ISA_MIPS1);
12561       used_at = 1;
12562
12563       /*
12564        * Is the double cfc1 instruction a bug in the mips assembler;
12565        * or is there a reason for it?
12566        */
12567       start_noreorder ();
12568       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12569       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12570       macro_build (NULL, "nop", "");
12571       expr1.X_add_number = 3;
12572       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12573       expr1.X_add_number = 2;
12574       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12575       macro_build (NULL, "ctc1", "t,G", AT, RA);
12576       macro_build (NULL, "nop", "");
12577       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12578                    op[0], op[1]);
12579       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12580       macro_build (NULL, "nop", "");
12581       end_noreorder ();
12582       break;
12583
12584     case M_ULH_AB:
12585       s = "lb";
12586       s2 = "lbu";
12587       off = 1;
12588       goto uld_st;
12589     case M_ULHU_AB:
12590       s = "lbu";
12591       s2 = "lbu";
12592       off = 1;
12593       goto uld_st;
12594     case M_ULW_AB:
12595       s = "lwl";
12596       s2 = "lwr";
12597       offbits = (mips_opts.micromips ? 12 : 16);
12598       off = 3;
12599       goto uld_st;
12600     case M_ULD_AB:
12601       s = "ldl";
12602       s2 = "ldr";
12603       offbits = (mips_opts.micromips ? 12 : 16);
12604       off = 7;
12605       goto uld_st;
12606     case M_USH_AB:
12607       s = "sb";
12608       s2 = "sb";
12609       off = 1;
12610       ust = 1;
12611       goto uld_st;
12612     case M_USW_AB:
12613       s = "swl";
12614       s2 = "swr";
12615       offbits = (mips_opts.micromips ? 12 : 16);
12616       off = 3;
12617       ust = 1;
12618       goto uld_st;
12619     case M_USD_AB:
12620       s = "sdl";
12621       s2 = "sdr";
12622       offbits = (mips_opts.micromips ? 12 : 16);
12623       off = 7;
12624       ust = 1;
12625
12626     uld_st:
12627       breg = op[2];
12628       large_offset = !small_offset_p (off, align, offbits);
12629       ep = &offset_expr;
12630       expr1.X_add_number = 0;
12631       if (large_offset)
12632         {
12633           used_at = 1;
12634           tempreg = AT;
12635           if (small_offset_p (0, align, 16))
12636             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12637                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12638           else
12639             {
12640               load_address (tempreg, ep, &used_at);
12641               if (breg != 0)
12642                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12643                              tempreg, tempreg, breg);
12644             }
12645           offset_reloc[0] = BFD_RELOC_LO16;
12646           offset_reloc[1] = BFD_RELOC_UNUSED;
12647           offset_reloc[2] = BFD_RELOC_UNUSED;
12648           breg = tempreg;
12649           tempreg = op[0];
12650           ep = &expr1;
12651         }
12652       else if (!ust && op[0] == breg)
12653         {
12654           used_at = 1;
12655           tempreg = AT;
12656         }
12657       else
12658         tempreg = op[0];
12659
12660       if (off == 1)
12661         goto ulh_sh;
12662
12663       if (!target_big_endian)
12664         ep->X_add_number += off;
12665       if (offbits == 12)
12666         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12667       else
12668         macro_build (ep, s, "t,o(b)", tempreg, -1,
12669                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12670
12671       if (!target_big_endian)
12672         ep->X_add_number -= off;
12673       else
12674         ep->X_add_number += off;
12675       if (offbits == 12)
12676         macro_build (NULL, s2, "t,~(b)",
12677                      tempreg, (int) ep->X_add_number, breg);
12678       else
12679         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12680                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12681
12682       /* If necessary, move the result in tempreg to the final destination.  */
12683       if (!ust && op[0] != tempreg)
12684         {
12685           /* Protect second load's delay slot.  */
12686           load_delay_nop ();
12687           move_register (op[0], tempreg);
12688         }
12689       break;
12690
12691     ulh_sh:
12692       used_at = 1;
12693       if (target_big_endian == ust)
12694         ep->X_add_number += off;
12695       tempreg = ust || large_offset ? op[0] : AT;
12696       macro_build (ep, s, "t,o(b)", tempreg, -1,
12697                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12698
12699       /* For halfword transfers we need a temporary register to shuffle
12700          bytes.  Unfortunately for M_USH_A we have none available before
12701          the next store as AT holds the base address.  We deal with this
12702          case by clobbering TREG and then restoring it as with ULH.  */
12703       tempreg = ust == large_offset ? op[0] : AT;
12704       if (ust)
12705         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12706
12707       if (target_big_endian == ust)
12708         ep->X_add_number -= off;
12709       else
12710         ep->X_add_number += off;
12711       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12712                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12713
12714       /* For M_USH_A re-retrieve the LSB.  */
12715       if (ust && large_offset)
12716         {
12717           if (target_big_endian)
12718             ep->X_add_number += off;
12719           else
12720             ep->X_add_number -= off;
12721           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12722                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12723         }
12724       /* For ULH and M_USH_A OR the LSB in.  */
12725       if (!ust || large_offset)
12726         {
12727           tempreg = !large_offset ? AT : op[0];
12728           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12729           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12730         }
12731       break;
12732
12733     default:
12734       /* FIXME: Check if this is one of the itbl macros, since they
12735          are added dynamically.  */
12736       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
12737       break;
12738     }
12739   if (!mips_opts.at && used_at)
12740     as_bad (_("macro used $at after \".set noat\""));
12741 }
12742
12743 /* Implement macros in mips16 mode.  */
12744
12745 static void
12746 mips16_macro (struct mips_cl_insn *ip)
12747 {
12748   const struct mips_operand_array *operands;
12749   int mask;
12750   int tmp;
12751   expressionS expr1;
12752   int dbl;
12753   const char *s, *s2, *s3;
12754   unsigned int op[MAX_OPERANDS];
12755   unsigned int i;
12756
12757   mask = ip->insn_mo->mask;
12758
12759   operands = insn_operands (ip);
12760   for (i = 0; i < MAX_OPERANDS; i++)
12761     if (operands->operand[i])
12762       op[i] = insn_extract_operand (ip, operands->operand[i]);
12763     else
12764       op[i] = -1;
12765
12766   expr1.X_op = O_constant;
12767   expr1.X_op_symbol = NULL;
12768   expr1.X_add_symbol = NULL;
12769   expr1.X_add_number = 1;
12770
12771   dbl = 0;
12772
12773   switch (mask)
12774     {
12775     default:
12776       abort ();
12777
12778     case M_DDIV_3:
12779       dbl = 1;
12780     case M_DIV_3:
12781       s = "mflo";
12782       goto do_div3;
12783     case M_DREM_3:
12784       dbl = 1;
12785     case M_REM_3:
12786       s = "mfhi";
12787     do_div3:
12788       start_noreorder ();
12789       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12790       expr1.X_add_number = 2;
12791       macro_build (&expr1, "bnez", "x,p", op[2]);
12792       macro_build (NULL, "break", "6", 7);
12793
12794       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12795          since that causes an overflow.  We should do that as well,
12796          but I don't see how to do the comparisons without a temporary
12797          register.  */
12798       end_noreorder ();
12799       macro_build (NULL, s, "x", op[0]);
12800       break;
12801
12802     case M_DIVU_3:
12803       s = "divu";
12804       s2 = "mflo";
12805       goto do_divu3;
12806     case M_REMU_3:
12807       s = "divu";
12808       s2 = "mfhi";
12809       goto do_divu3;
12810     case M_DDIVU_3:
12811       s = "ddivu";
12812       s2 = "mflo";
12813       goto do_divu3;
12814     case M_DREMU_3:
12815       s = "ddivu";
12816       s2 = "mfhi";
12817     do_divu3:
12818       start_noreorder ();
12819       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12820       expr1.X_add_number = 2;
12821       macro_build (&expr1, "bnez", "x,p", op[2]);
12822       macro_build (NULL, "break", "6", 7);
12823       end_noreorder ();
12824       macro_build (NULL, s2, "x", op[0]);
12825       break;
12826
12827     case M_DMUL:
12828       dbl = 1;
12829     case M_MUL:
12830       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12831       macro_build (NULL, "mflo", "x", op[0]);
12832       break;
12833
12834     case M_DSUBU_I:
12835       dbl = 1;
12836       goto do_subu;
12837     case M_SUBU_I:
12838     do_subu:
12839       imm_expr.X_add_number = -imm_expr.X_add_number;
12840       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12841       break;
12842
12843     case M_SUBU_I_2:
12844       imm_expr.X_add_number = -imm_expr.X_add_number;
12845       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12846       break;
12847
12848     case M_DSUBU_I_2:
12849       imm_expr.X_add_number = -imm_expr.X_add_number;
12850       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12851       break;
12852
12853     case M_BEQ:
12854       s = "cmp";
12855       s2 = "bteqz";
12856       goto do_branch;
12857     case M_BNE:
12858       s = "cmp";
12859       s2 = "btnez";
12860       goto do_branch;
12861     case M_BLT:
12862       s = "slt";
12863       s2 = "btnez";
12864       goto do_branch;
12865     case M_BLTU:
12866       s = "sltu";
12867       s2 = "btnez";
12868       goto do_branch;
12869     case M_BLE:
12870       s = "slt";
12871       s2 = "bteqz";
12872       goto do_reverse_branch;
12873     case M_BLEU:
12874       s = "sltu";
12875       s2 = "bteqz";
12876       goto do_reverse_branch;
12877     case M_BGE:
12878       s = "slt";
12879       s2 = "bteqz";
12880       goto do_branch;
12881     case M_BGEU:
12882       s = "sltu";
12883       s2 = "bteqz";
12884       goto do_branch;
12885     case M_BGT:
12886       s = "slt";
12887       s2 = "btnez";
12888       goto do_reverse_branch;
12889     case M_BGTU:
12890       s = "sltu";
12891       s2 = "btnez";
12892
12893     do_reverse_branch:
12894       tmp = op[1];
12895       op[1] = op[0];
12896       op[0] = tmp;
12897
12898     do_branch:
12899       macro_build (NULL, s, "x,y", op[0], op[1]);
12900       macro_build (&offset_expr, s2, "p");
12901       break;
12902
12903     case M_BEQ_I:
12904       s = "cmpi";
12905       s2 = "bteqz";
12906       s3 = "x,U";
12907       goto do_branch_i;
12908     case M_BNE_I:
12909       s = "cmpi";
12910       s2 = "btnez";
12911       s3 = "x,U";
12912       goto do_branch_i;
12913     case M_BLT_I:
12914       s = "slti";
12915       s2 = "btnez";
12916       s3 = "x,8";
12917       goto do_branch_i;
12918     case M_BLTU_I:
12919       s = "sltiu";
12920       s2 = "btnez";
12921       s3 = "x,8";
12922       goto do_branch_i;
12923     case M_BLE_I:
12924       s = "slti";
12925       s2 = "btnez";
12926       s3 = "x,8";
12927       goto do_addone_branch_i;
12928     case M_BLEU_I:
12929       s = "sltiu";
12930       s2 = "btnez";
12931       s3 = "x,8";
12932       goto do_addone_branch_i;
12933     case M_BGE_I:
12934       s = "slti";
12935       s2 = "bteqz";
12936       s3 = "x,8";
12937       goto do_branch_i;
12938     case M_BGEU_I:
12939       s = "sltiu";
12940       s2 = "bteqz";
12941       s3 = "x,8";
12942       goto do_branch_i;
12943     case M_BGT_I:
12944       s = "slti";
12945       s2 = "bteqz";
12946       s3 = "x,8";
12947       goto do_addone_branch_i;
12948     case M_BGTU_I:
12949       s = "sltiu";
12950       s2 = "bteqz";
12951       s3 = "x,8";
12952
12953     do_addone_branch_i:
12954       ++imm_expr.X_add_number;
12955
12956     do_branch_i:
12957       macro_build (&imm_expr, s, s3, op[0]);
12958       macro_build (&offset_expr, s2, "p");
12959       break;
12960
12961     case M_ABS:
12962       expr1.X_add_number = 0;
12963       macro_build (&expr1, "slti", "x,8", op[1]);
12964       if (op[0] != op[1])
12965         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
12966       expr1.X_add_number = 2;
12967       macro_build (&expr1, "bteqz", "p");
12968       macro_build (NULL, "neg", "x,w", op[0], op[0]);
12969       break;
12970     }
12971 }
12972
12973 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
12974    opcode bits in *OPCODE_EXTRA.  */
12975
12976 static struct mips_opcode *
12977 mips_lookup_insn (struct hash_control *hash, const char *start,
12978                   ssize_t length, unsigned int *opcode_extra)
12979 {
12980   char *name, *dot, *p;
12981   unsigned int mask, suffix;
12982   ssize_t opend;
12983   struct mips_opcode *insn;
12984
12985   /* Make a copy of the instruction so that we can fiddle with it.  */
12986   name = alloca (length + 1);
12987   memcpy (name, start, length);
12988   name[length] = '\0';
12989
12990   /* Look up the instruction as-is.  */
12991   insn = (struct mips_opcode *) hash_find (hash, name);
12992   if (insn)
12993     return insn;
12994
12995   dot = strchr (name, '.');
12996   if (dot && dot[1])
12997     {
12998       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
12999       p = mips_parse_vu0_channels (dot + 1, &mask);
13000       if (*p == 0 && mask != 0)
13001         {
13002           *dot = 0;
13003           insn = (struct mips_opcode *) hash_find (hash, name);
13004           *dot = '.';
13005           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
13006             {
13007               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
13008               return insn;
13009             }
13010         }
13011     }
13012
13013   if (mips_opts.micromips)
13014     {
13015       /* See if there's an instruction size override suffix,
13016          either `16' or `32', at the end of the mnemonic proper,
13017          that defines the operation, i.e. before the first `.'
13018          character if any.  Strip it and retry.  */
13019       opend = dot != NULL ? dot - name : length;
13020       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
13021         suffix = 2;
13022       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
13023         suffix = 4;
13024       else
13025         suffix = 0;
13026       if (suffix)
13027         {
13028           memcpy (name + opend - 2, name + opend, length - opend + 1);
13029           insn = (struct mips_opcode *) hash_find (hash, name);
13030           if (insn)
13031             {
13032               forced_insn_length = suffix;
13033               return insn;
13034             }
13035         }
13036     }
13037
13038   return NULL;
13039 }
13040
13041 /* Assemble an instruction into its binary format.  If the instruction
13042    is a macro, set imm_expr and offset_expr to the values associated
13043    with "I" and "A" operands respectively.  Otherwise store the value
13044    of the relocatable field (if any) in offset_expr.  In both cases
13045    set offset_reloc to the relocation operators applied to offset_expr.  */
13046
13047 static void
13048 mips_ip (char *str, struct mips_cl_insn *insn)
13049 {
13050   const struct mips_opcode *first, *past;
13051   struct hash_control *hash;
13052   char format;
13053   size_t end;
13054   struct mips_operand_token *tokens;
13055   unsigned int opcode_extra;
13056
13057   if (mips_opts.micromips)
13058     {
13059       hash = micromips_op_hash;
13060       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13061     }
13062   else
13063     {
13064       hash = op_hash;
13065       past = &mips_opcodes[NUMOPCODES];
13066     }
13067   forced_insn_length = 0;
13068   opcode_extra = 0;
13069
13070   /* We first try to match an instruction up to a space or to the end.  */
13071   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13072     continue;
13073
13074   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13075   if (first == NULL)
13076     {
13077       set_insn_error (0, _("unrecognized opcode"));
13078       return;
13079     }
13080
13081   if (strcmp (first->name, "li.s") == 0)
13082     format = 'f';
13083   else if (strcmp (first->name, "li.d") == 0)
13084     format = 'd';
13085   else
13086     format = 0;
13087   tokens = mips_parse_arguments (str + end, format);
13088   if (!tokens)
13089     return;
13090
13091   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13092       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13093     set_insn_error (0, _("invalid operands"));
13094
13095   obstack_free (&mips_operand_tokens, tokens);
13096 }
13097
13098 /* As for mips_ip, but used when assembling MIPS16 code.
13099    Also set forced_insn_length to the resulting instruction size in
13100    bytes if the user explicitly requested a small or extended instruction.  */
13101
13102 static void
13103 mips16_ip (char *str, struct mips_cl_insn *insn)
13104 {
13105   char *end, *s, c;
13106   struct mips_opcode *first;
13107   struct mips_operand_token *tokens;
13108
13109   forced_insn_length = 0;
13110
13111   for (s = str; ISLOWER (*s); ++s)
13112     ;
13113   end = s;
13114   c = *end;
13115   switch (c)
13116     {
13117     case '\0':
13118       break;
13119
13120     case ' ':
13121       s++;
13122       break;
13123
13124     case '.':
13125       if (s[1] == 't' && s[2] == ' ')
13126         {
13127           forced_insn_length = 2;
13128           s += 3;
13129           break;
13130         }
13131       else if (s[1] == 'e' && s[2] == ' ')
13132         {
13133           forced_insn_length = 4;
13134           s += 3;
13135           break;
13136         }
13137       /* Fall through.  */
13138     default:
13139       set_insn_error (0, _("unrecognized opcode"));
13140       return;
13141     }
13142
13143   if (mips_opts.noautoextend && !forced_insn_length)
13144     forced_insn_length = 2;
13145
13146   *end = 0;
13147   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13148   *end = c;
13149
13150   if (!first)
13151     {
13152       set_insn_error (0, _("unrecognized opcode"));
13153       return;
13154     }
13155
13156   tokens = mips_parse_arguments (s, 0);
13157   if (!tokens)
13158     return;
13159
13160   if (!match_mips16_insns (insn, first, tokens))
13161     set_insn_error (0, _("invalid operands"));
13162
13163   obstack_free (&mips_operand_tokens, tokens);
13164 }
13165
13166 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13167    NBITS is the number of significant bits in VAL.  */
13168
13169 static unsigned long
13170 mips16_immed_extend (offsetT val, unsigned int nbits)
13171 {
13172   int extval;
13173   if (nbits == 16)
13174     {
13175       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13176       val &= 0x1f;
13177     }
13178   else if (nbits == 15)
13179     {
13180       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13181       val &= 0xf;
13182     }
13183   else
13184     {
13185       extval = ((val & 0x1f) << 6) | (val & 0x20);
13186       val = 0;
13187     }
13188   return (extval << 16) | val;
13189 }
13190
13191 /* Like decode_mips16_operand, but require the operand to be defined and
13192    require it to be an integer.  */
13193
13194 static const struct mips_int_operand *
13195 mips16_immed_operand (int type, bfd_boolean extended_p)
13196 {
13197   const struct mips_operand *operand;
13198
13199   operand = decode_mips16_operand (type, extended_p);
13200   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13201     abort ();
13202   return (const struct mips_int_operand *) operand;
13203 }
13204
13205 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13206
13207 static bfd_boolean
13208 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13209                          bfd_reloc_code_real_type reloc, offsetT sval)
13210 {
13211   int min_val, max_val;
13212
13213   min_val = mips_int_operand_min (operand);
13214   max_val = mips_int_operand_max (operand);
13215   if (reloc != BFD_RELOC_UNUSED)
13216     {
13217       if (min_val < 0)
13218         sval = SEXT_16BIT (sval);
13219       else
13220         sval &= 0xffff;
13221     }
13222
13223   return (sval >= min_val
13224           && sval <= max_val
13225           && (sval & ((1 << operand->shift) - 1)) == 0);
13226 }
13227
13228 /* Install immediate value VAL into MIPS16 instruction *INSN,
13229    extending it if necessary.  The instruction in *INSN may
13230    already be extended.
13231
13232    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13233    if none.  In the former case, VAL is a 16-bit number with no
13234    defined signedness.
13235
13236    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13237    is the length that the user requested, or 0 if none.  */
13238
13239 static void
13240 mips16_immed (char *file, unsigned int line, int type,
13241               bfd_reloc_code_real_type reloc, offsetT val,
13242               unsigned int user_insn_length, unsigned long *insn)
13243 {
13244   const struct mips_int_operand *operand;
13245   unsigned int uval, length;
13246
13247   operand = mips16_immed_operand (type, FALSE);
13248   if (!mips16_immed_in_range_p (operand, reloc, val))
13249     {
13250       /* We need an extended instruction.  */
13251       if (user_insn_length == 2)
13252         as_bad_where (file, line, _("invalid unextended operand value"));
13253       else
13254         *insn |= MIPS16_EXTEND;
13255     }
13256   else if (user_insn_length == 4)
13257     {
13258       /* The operand doesn't force an unextended instruction to be extended.
13259          Warn if the user wanted an extended instruction anyway.  */
13260       *insn |= MIPS16_EXTEND;
13261       as_warn_where (file, line,
13262                      _("extended operand requested but not required"));
13263     }
13264
13265   length = mips16_opcode_length (*insn);
13266   if (length == 4)
13267     {
13268       operand = mips16_immed_operand (type, TRUE);
13269       if (!mips16_immed_in_range_p (operand, reloc, val))
13270         as_bad_where (file, line,
13271                       _("operand value out of range for instruction"));
13272     }
13273   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13274   if (length == 2)
13275     *insn = mips_insert_operand (&operand->root, *insn, uval);
13276   else
13277     *insn |= mips16_immed_extend (uval, operand->root.size);
13278 }
13279 \f
13280 struct percent_op_match
13281 {
13282   const char *str;
13283   bfd_reloc_code_real_type reloc;
13284 };
13285
13286 static const struct percent_op_match mips_percent_op[] =
13287 {
13288   {"%lo", BFD_RELOC_LO16},
13289   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13290   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13291   {"%call16", BFD_RELOC_MIPS_CALL16},
13292   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13293   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13294   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13295   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13296   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13297   {"%got", BFD_RELOC_MIPS_GOT16},
13298   {"%gp_rel", BFD_RELOC_GPREL16},
13299   {"%half", BFD_RELOC_16},
13300   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13301   {"%higher", BFD_RELOC_MIPS_HIGHER},
13302   {"%neg", BFD_RELOC_MIPS_SUB},
13303   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13304   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13305   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13306   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13307   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13308   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13309   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13310   {"%hi", BFD_RELOC_HI16_S}
13311 };
13312
13313 static const struct percent_op_match mips16_percent_op[] =
13314 {
13315   {"%lo", BFD_RELOC_MIPS16_LO16},
13316   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13317   {"%got", BFD_RELOC_MIPS16_GOT16},
13318   {"%call16", BFD_RELOC_MIPS16_CALL16},
13319   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13320   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13321   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13322   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13323   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13324   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13325   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13326   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13327 };
13328
13329
13330 /* Return true if *STR points to a relocation operator.  When returning true,
13331    move *STR over the operator and store its relocation code in *RELOC.
13332    Leave both *STR and *RELOC alone when returning false.  */
13333
13334 static bfd_boolean
13335 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13336 {
13337   const struct percent_op_match *percent_op;
13338   size_t limit, i;
13339
13340   if (mips_opts.mips16)
13341     {
13342       percent_op = mips16_percent_op;
13343       limit = ARRAY_SIZE (mips16_percent_op);
13344     }
13345   else
13346     {
13347       percent_op = mips_percent_op;
13348       limit = ARRAY_SIZE (mips_percent_op);
13349     }
13350
13351   for (i = 0; i < limit; i++)
13352     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13353       {
13354         int len = strlen (percent_op[i].str);
13355
13356         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13357           continue;
13358
13359         *str += strlen (percent_op[i].str);
13360         *reloc = percent_op[i].reloc;
13361
13362         /* Check whether the output BFD supports this relocation.
13363            If not, issue an error and fall back on something safe.  */
13364         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13365           {
13366             as_bad (_("relocation %s isn't supported by the current ABI"),
13367                     percent_op[i].str);
13368             *reloc = BFD_RELOC_UNUSED;
13369           }
13370         return TRUE;
13371       }
13372   return FALSE;
13373 }
13374
13375
13376 /* Parse string STR as a 16-bit relocatable operand.  Store the
13377    expression in *EP and the relocations in the array starting
13378    at RELOC.  Return the number of relocation operators used.
13379
13380    On exit, EXPR_END points to the first character after the expression.  */
13381
13382 static size_t
13383 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13384                        char *str)
13385 {
13386   bfd_reloc_code_real_type reversed_reloc[3];
13387   size_t reloc_index, i;
13388   int crux_depth, str_depth;
13389   char *crux;
13390
13391   /* Search for the start of the main expression, recoding relocations
13392      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13393      of the main expression and with CRUX_DEPTH containing the number
13394      of open brackets at that point.  */
13395   reloc_index = -1;
13396   str_depth = 0;
13397   do
13398     {
13399       reloc_index++;
13400       crux = str;
13401       crux_depth = str_depth;
13402
13403       /* Skip over whitespace and brackets, keeping count of the number
13404          of brackets.  */
13405       while (*str == ' ' || *str == '\t' || *str == '(')
13406         if (*str++ == '(')
13407           str_depth++;
13408     }
13409   while (*str == '%'
13410          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13411          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13412
13413   my_getExpression (ep, crux);
13414   str = expr_end;
13415
13416   /* Match every open bracket.  */
13417   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13418     if (*str++ == ')')
13419       crux_depth--;
13420
13421   if (crux_depth > 0)
13422     as_bad (_("unclosed '('"));
13423
13424   expr_end = str;
13425
13426   if (reloc_index != 0)
13427     {
13428       prev_reloc_op_frag = frag_now;
13429       for (i = 0; i < reloc_index; i++)
13430         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13431     }
13432
13433   return reloc_index;
13434 }
13435
13436 static void
13437 my_getExpression (expressionS *ep, char *str)
13438 {
13439   char *save_in;
13440
13441   save_in = input_line_pointer;
13442   input_line_pointer = str;
13443   expression (ep);
13444   expr_end = input_line_pointer;
13445   input_line_pointer = save_in;
13446 }
13447
13448 char *
13449 md_atof (int type, char *litP, int *sizeP)
13450 {
13451   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13452 }
13453
13454 void
13455 md_number_to_chars (char *buf, valueT val, int n)
13456 {
13457   if (target_big_endian)
13458     number_to_chars_bigendian (buf, val, n);
13459   else
13460     number_to_chars_littleendian (buf, val, n);
13461 }
13462 \f
13463 static int support_64bit_objects(void)
13464 {
13465   const char **list, **l;
13466   int yes;
13467
13468   list = bfd_target_list ();
13469   for (l = list; *l != NULL; l++)
13470     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13471         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13472       break;
13473   yes = (*l != NULL);
13474   free (list);
13475   return yes;
13476 }
13477
13478 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13479    NEW_VALUE.  Warn if another value was already specified.  Note:
13480    we have to defer parsing the -march and -mtune arguments in order
13481    to handle 'from-abi' correctly, since the ABI might be specified
13482    in a later argument.  */
13483
13484 static void
13485 mips_set_option_string (const char **string_ptr, const char *new_value)
13486 {
13487   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13488     as_warn (_("a different %s was already specified, is now %s"),
13489              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13490              new_value);
13491
13492   *string_ptr = new_value;
13493 }
13494
13495 int
13496 md_parse_option (int c, char *arg)
13497 {
13498   unsigned int i;
13499
13500   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13501     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13502       {
13503         file_ase_explicit |= mips_set_ase (&mips_ases[i],
13504                                            c == mips_ases[i].option_on);
13505         return 1;
13506       }
13507
13508   switch (c)
13509     {
13510     case OPTION_CONSTRUCT_FLOATS:
13511       mips_disable_float_construction = 0;
13512       break;
13513
13514     case OPTION_NO_CONSTRUCT_FLOATS:
13515       mips_disable_float_construction = 1;
13516       break;
13517
13518     case OPTION_TRAP:
13519       mips_trap = 1;
13520       break;
13521
13522     case OPTION_BREAK:
13523       mips_trap = 0;
13524       break;
13525
13526     case OPTION_EB:
13527       target_big_endian = 1;
13528       break;
13529
13530     case OPTION_EL:
13531       target_big_endian = 0;
13532       break;
13533
13534     case 'O':
13535       if (arg == NULL)
13536         mips_optimize = 1;
13537       else if (arg[0] == '0')
13538         mips_optimize = 0;
13539       else if (arg[0] == '1')
13540         mips_optimize = 1;
13541       else
13542         mips_optimize = 2;
13543       break;
13544
13545     case 'g':
13546       if (arg == NULL)
13547         mips_debug = 2;
13548       else
13549         mips_debug = atoi (arg);
13550       break;
13551
13552     case OPTION_MIPS1:
13553       file_mips_isa = ISA_MIPS1;
13554       break;
13555
13556     case OPTION_MIPS2:
13557       file_mips_isa = ISA_MIPS2;
13558       break;
13559
13560     case OPTION_MIPS3:
13561       file_mips_isa = ISA_MIPS3;
13562       break;
13563
13564     case OPTION_MIPS4:
13565       file_mips_isa = ISA_MIPS4;
13566       break;
13567
13568     case OPTION_MIPS5:
13569       file_mips_isa = ISA_MIPS5;
13570       break;
13571
13572     case OPTION_MIPS32:
13573       file_mips_isa = ISA_MIPS32;
13574       break;
13575
13576     case OPTION_MIPS32R2:
13577       file_mips_isa = ISA_MIPS32R2;
13578       break;
13579
13580     case OPTION_MIPS32R3:
13581       file_mips_isa = ISA_MIPS32R3;
13582       break;
13583
13584     case OPTION_MIPS32R5:
13585       file_mips_isa = ISA_MIPS32R5;
13586       break;
13587
13588     case OPTION_MIPS64R2:
13589       file_mips_isa = ISA_MIPS64R2;
13590       break;
13591
13592     case OPTION_MIPS64R3:
13593       file_mips_isa = ISA_MIPS64R3;
13594       break;
13595
13596     case OPTION_MIPS64R5:
13597       file_mips_isa = ISA_MIPS64R5;
13598       break;
13599
13600     case OPTION_MIPS64:
13601       file_mips_isa = ISA_MIPS64;
13602       break;
13603
13604     case OPTION_MTUNE:
13605       mips_set_option_string (&mips_tune_string, arg);
13606       break;
13607
13608     case OPTION_MARCH:
13609       mips_set_option_string (&mips_arch_string, arg);
13610       break;
13611
13612     case OPTION_M4650:
13613       mips_set_option_string (&mips_arch_string, "4650");
13614       mips_set_option_string (&mips_tune_string, "4650");
13615       break;
13616
13617     case OPTION_NO_M4650:
13618       break;
13619
13620     case OPTION_M4010:
13621       mips_set_option_string (&mips_arch_string, "4010");
13622       mips_set_option_string (&mips_tune_string, "4010");
13623       break;
13624
13625     case OPTION_NO_M4010:
13626       break;
13627
13628     case OPTION_M4100:
13629       mips_set_option_string (&mips_arch_string, "4100");
13630       mips_set_option_string (&mips_tune_string, "4100");
13631       break;
13632
13633     case OPTION_NO_M4100:
13634       break;
13635
13636     case OPTION_M3900:
13637       mips_set_option_string (&mips_arch_string, "3900");
13638       mips_set_option_string (&mips_tune_string, "3900");
13639       break;
13640
13641     case OPTION_NO_M3900:
13642       break;
13643
13644     case OPTION_MICROMIPS:
13645       if (mips_opts.mips16 == 1)
13646         {
13647           as_bad (_("-mmicromips cannot be used with -mips16"));
13648           return 0;
13649         }
13650       mips_opts.micromips = 1;
13651       mips_no_prev_insn ();
13652       break;
13653
13654     case OPTION_NO_MICROMIPS:
13655       mips_opts.micromips = 0;
13656       mips_no_prev_insn ();
13657       break;
13658
13659     case OPTION_MIPS16:
13660       if (mips_opts.micromips == 1)
13661         {
13662           as_bad (_("-mips16 cannot be used with -micromips"));
13663           return 0;
13664         }
13665       mips_opts.mips16 = 1;
13666       mips_no_prev_insn ();
13667       break;
13668
13669     case OPTION_NO_MIPS16:
13670       mips_opts.mips16 = 0;
13671       mips_no_prev_insn ();
13672       break;
13673
13674     case OPTION_FIX_24K:
13675       mips_fix_24k = 1;
13676       break;
13677
13678     case OPTION_NO_FIX_24K:
13679       mips_fix_24k = 0;
13680       break;
13681
13682     case OPTION_FIX_RM7000:
13683       mips_fix_rm7000 = 1;
13684       break;
13685
13686     case OPTION_NO_FIX_RM7000:
13687       mips_fix_rm7000 = 0;
13688       break;
13689
13690     case OPTION_FIX_LOONGSON2F_JUMP:
13691       mips_fix_loongson2f_jump = TRUE;
13692       break;
13693
13694     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13695       mips_fix_loongson2f_jump = FALSE;
13696       break;
13697
13698     case OPTION_FIX_LOONGSON2F_NOP:
13699       mips_fix_loongson2f_nop = TRUE;
13700       break;
13701
13702     case OPTION_NO_FIX_LOONGSON2F_NOP:
13703       mips_fix_loongson2f_nop = FALSE;
13704       break;
13705
13706     case OPTION_FIX_VR4120:
13707       mips_fix_vr4120 = 1;
13708       break;
13709
13710     case OPTION_NO_FIX_VR4120:
13711       mips_fix_vr4120 = 0;
13712       break;
13713
13714     case OPTION_FIX_VR4130:
13715       mips_fix_vr4130 = 1;
13716       break;
13717
13718     case OPTION_NO_FIX_VR4130:
13719       mips_fix_vr4130 = 0;
13720       break;
13721
13722     case OPTION_FIX_CN63XXP1:
13723       mips_fix_cn63xxp1 = TRUE;
13724       break;
13725
13726     case OPTION_NO_FIX_CN63XXP1:
13727       mips_fix_cn63xxp1 = FALSE;
13728       break;
13729
13730     case OPTION_RELAX_BRANCH:
13731       mips_relax_branch = 1;
13732       break;
13733
13734     case OPTION_NO_RELAX_BRANCH:
13735       mips_relax_branch = 0;
13736       break;
13737
13738     case OPTION_INSN32:
13739       mips_opts.insn32 = TRUE;
13740       break;
13741
13742     case OPTION_NO_INSN32:
13743       mips_opts.insn32 = FALSE;
13744       break;
13745
13746     case OPTION_MSHARED:
13747       mips_in_shared = TRUE;
13748       break;
13749
13750     case OPTION_MNO_SHARED:
13751       mips_in_shared = FALSE;
13752       break;
13753
13754     case OPTION_MSYM32:
13755       mips_opts.sym32 = TRUE;
13756       break;
13757
13758     case OPTION_MNO_SYM32:
13759       mips_opts.sym32 = FALSE;
13760       break;
13761
13762       /* When generating ELF code, we permit -KPIC and -call_shared to
13763          select SVR4_PIC, and -non_shared to select no PIC.  This is
13764          intended to be compatible with Irix 5.  */
13765     case OPTION_CALL_SHARED:
13766       mips_pic = SVR4_PIC;
13767       mips_abicalls = TRUE;
13768       break;
13769
13770     case OPTION_CALL_NONPIC:
13771       mips_pic = NO_PIC;
13772       mips_abicalls = TRUE;
13773       break;
13774
13775     case OPTION_NON_SHARED:
13776       mips_pic = NO_PIC;
13777       mips_abicalls = FALSE;
13778       break;
13779
13780       /* The -xgot option tells the assembler to use 32 bit offsets
13781          when accessing the got in SVR4_PIC mode.  It is for Irix
13782          compatibility.  */
13783     case OPTION_XGOT:
13784       mips_big_got = 1;
13785       break;
13786
13787     case 'G':
13788       g_switch_value = atoi (arg);
13789       g_switch_seen = 1;
13790       break;
13791
13792       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13793          and -mabi=64.  */
13794     case OPTION_32:
13795       mips_abi = O32_ABI;
13796       break;
13797
13798     case OPTION_N32:
13799       mips_abi = N32_ABI;
13800       break;
13801
13802     case OPTION_64:
13803       mips_abi = N64_ABI;
13804       if (!support_64bit_objects())
13805         as_fatal (_("no compiled in support for 64 bit object file format"));
13806       break;
13807
13808     case OPTION_GP32:
13809       file_mips_gp32 = 1;
13810       break;
13811
13812     case OPTION_GP64:
13813       file_mips_gp32 = 0;
13814       break;
13815
13816     case OPTION_FP32:
13817       file_mips_fp32 = 1;
13818       break;
13819
13820     case OPTION_FP64:
13821       file_mips_fp32 = 0;
13822       break;
13823
13824     case OPTION_SINGLE_FLOAT:
13825       file_mips_single_float = 1;
13826       break;
13827
13828     case OPTION_DOUBLE_FLOAT:
13829       file_mips_single_float = 0;
13830       break;
13831
13832     case OPTION_SOFT_FLOAT:
13833       file_mips_soft_float = 1;
13834       break;
13835
13836     case OPTION_HARD_FLOAT:
13837       file_mips_soft_float = 0;
13838       break;
13839
13840     case OPTION_MABI:
13841       if (strcmp (arg, "32") == 0)
13842         mips_abi = O32_ABI;
13843       else if (strcmp (arg, "o64") == 0)
13844         mips_abi = O64_ABI;
13845       else if (strcmp (arg, "n32") == 0)
13846         mips_abi = N32_ABI;
13847       else if (strcmp (arg, "64") == 0)
13848         {
13849           mips_abi = N64_ABI;
13850           if (! support_64bit_objects())
13851             as_fatal (_("no compiled in support for 64 bit object file "
13852                         "format"));
13853         }
13854       else if (strcmp (arg, "eabi") == 0)
13855         mips_abi = EABI_ABI;
13856       else
13857         {
13858           as_fatal (_("invalid abi -mabi=%s"), arg);
13859           return 0;
13860         }
13861       break;
13862
13863     case OPTION_M7000_HILO_FIX:
13864       mips_7000_hilo_fix = TRUE;
13865       break;
13866
13867     case OPTION_MNO_7000_HILO_FIX:
13868       mips_7000_hilo_fix = FALSE;
13869       break;
13870
13871     case OPTION_MDEBUG:
13872       mips_flag_mdebug = TRUE;
13873       break;
13874
13875     case OPTION_NO_MDEBUG:
13876       mips_flag_mdebug = FALSE;
13877       break;
13878
13879     case OPTION_PDR:
13880       mips_flag_pdr = TRUE;
13881       break;
13882
13883     case OPTION_NO_PDR:
13884       mips_flag_pdr = FALSE;
13885       break;
13886
13887     case OPTION_MVXWORKS_PIC:
13888       mips_pic = VXWORKS_PIC;
13889       break;
13890
13891     case OPTION_NAN:
13892       if (strcmp (arg, "2008") == 0)
13893         mips_flag_nan2008 = TRUE;
13894       else if (strcmp (arg, "legacy") == 0)
13895         mips_flag_nan2008 = FALSE;
13896       else
13897         {
13898           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
13899           return 0;
13900         }
13901       break;
13902
13903     default:
13904       return 0;
13905     }
13906
13907     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13908
13909   return 1;
13910 }
13911 \f
13912 /* Set up globals to generate code for the ISA or processor
13913    described by INFO.  */
13914
13915 static void
13916 mips_set_architecture (const struct mips_cpu_info *info)
13917 {
13918   if (info != 0)
13919     {
13920       file_mips_arch = info->cpu;
13921       mips_opts.arch = info->cpu;
13922       mips_opts.isa = info->isa;
13923     }
13924 }
13925
13926
13927 /* Likewise for tuning.  */
13928
13929 static void
13930 mips_set_tune (const struct mips_cpu_info *info)
13931 {
13932   if (info != 0)
13933     mips_tune = info->cpu;
13934 }
13935
13936
13937 void
13938 mips_after_parse_args (void)
13939 {
13940   const struct mips_cpu_info *arch_info = 0;
13941   const struct mips_cpu_info *tune_info = 0;
13942
13943   /* GP relative stuff not working for PE */
13944   if (strncmp (TARGET_OS, "pe", 2) == 0)
13945     {
13946       if (g_switch_seen && g_switch_value != 0)
13947         as_bad (_("-G not supported in this configuration"));
13948       g_switch_value = 0;
13949     }
13950
13951   if (mips_abi == NO_ABI)
13952     mips_abi = MIPS_DEFAULT_ABI;
13953
13954   /* The following code determines the architecture and register size.
13955      Similar code was added to GCC 3.3 (see override_options() in
13956      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13957      as much as possible.  */
13958
13959   if (mips_arch_string != 0)
13960     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13961
13962   if (file_mips_isa != ISA_UNKNOWN)
13963     {
13964       /* Handle -mipsN.  At this point, file_mips_isa contains the
13965          ISA level specified by -mipsN, while arch_info->isa contains
13966          the -march selection (if any).  */
13967       if (arch_info != 0)
13968         {
13969           /* -march takes precedence over -mipsN, since it is more descriptive.
13970              There's no harm in specifying both as long as the ISA levels
13971              are the same.  */
13972           if (file_mips_isa != arch_info->isa)
13973             as_bad (_("-%s conflicts with the other architecture options,"
13974                       " which imply -%s"),
13975                     mips_cpu_info_from_isa (file_mips_isa)->name,
13976                     mips_cpu_info_from_isa (arch_info->isa)->name);
13977         }
13978       else
13979         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13980     }
13981
13982   if (arch_info == 0)
13983     {
13984       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13985       gas_assert (arch_info);
13986     }
13987
13988   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13989     as_bad (_("-march=%s is not compatible with the selected ABI"),
13990             arch_info->name);
13991
13992   mips_set_architecture (arch_info);
13993
13994   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13995   if (mips_tune_string != 0)
13996     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13997
13998   if (tune_info == 0)
13999     mips_set_tune (arch_info);
14000   else
14001     mips_set_tune (tune_info);
14002
14003   if (file_mips_gp32 >= 0)
14004     {
14005       /* The user specified the size of the integer registers.  Make sure
14006          it agrees with the ABI and ISA.  */
14007       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
14008         as_bad (_("-mgp64 used with a 32-bit processor"));
14009       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
14010         as_bad (_("-mgp32 used with a 64-bit ABI"));
14011       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
14012         as_bad (_("-mgp64 used with a 32-bit ABI"));
14013     }
14014   else
14015     {
14016       /* Infer the integer register size from the ABI and processor.
14017          Restrict ourselves to 32-bit registers if that's all the
14018          processor has, or if the ABI cannot handle 64-bit registers.  */
14019       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
14020                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
14021     }
14022
14023   switch (file_mips_fp32)
14024     {
14025     default:
14026     case -1:
14027       /* No user specified float register size.
14028          ??? GAS treats single-float processors as though they had 64-bit
14029          float registers (although it complains when double-precision
14030          instructions are used).  As things stand, saying they have 32-bit
14031          registers would lead to spurious "register must be even" messages.
14032          So here we assume float registers are never smaller than the
14033          integer ones.  */
14034       if (file_mips_gp32 == 0)
14035         /* 64-bit integer registers implies 64-bit float registers.  */
14036         file_mips_fp32 = 0;
14037       else if ((mips_opts.ase & FP64_ASES)
14038                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
14039         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
14040         file_mips_fp32 = 0;
14041       else
14042         /* 32-bit float registers.  */
14043         file_mips_fp32 = 1;
14044       break;
14045
14046     /* The user specified the size of the float registers.  Check if it
14047        agrees with the ABI and ISA.  */
14048     case 0:
14049       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14050         as_bad (_("-mfp64 used with a 32-bit fpu"));
14051       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
14052                && !ISA_HAS_MXHC1 (mips_opts.isa))
14053         as_warn (_("-mfp64 used with a 32-bit ABI"));
14054       break;
14055     case 1:
14056       if (ABI_NEEDS_64BIT_REGS (mips_abi))
14057         as_warn (_("-mfp32 used with a 64-bit ABI"));
14058       break;
14059     }
14060
14061   /* End of GCC-shared inference code.  */
14062
14063   /* This flag is set when we have a 64-bit capable CPU but use only
14064      32-bit wide registers.  Note that EABI does not use it.  */
14065   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
14066       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
14067           || mips_abi == O32_ABI))
14068     mips_32bitmode = 1;
14069
14070   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
14071     as_bad (_("trap exception not supported at ISA 1"));
14072
14073   /* If the selected architecture includes support for ASEs, enable
14074      generation of code for them.  */
14075   if (mips_opts.mips16 == -1)
14076     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
14077   if (mips_opts.micromips == -1)
14078     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
14079
14080   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
14081      ASEs from being selected implicitly.  */
14082   if (file_mips_fp32 == 1)
14083     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
14084
14085   /* If the user didn't explicitly select or deselect a particular ASE,
14086      use the default setting for the CPU.  */
14087   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
14088
14089   file_mips_isa = mips_opts.isa;
14090   file_ase = mips_opts.ase;
14091   mips_opts.gp32 = file_mips_gp32;
14092   mips_opts.fp32 = file_mips_fp32;
14093   mips_opts.soft_float = file_mips_soft_float;
14094   mips_opts.single_float = file_mips_single_float;
14095
14096   mips_check_isa_supports_ases ();
14097
14098   if (mips_flag_mdebug < 0)
14099     mips_flag_mdebug = 0;
14100 }
14101 \f
14102 void
14103 mips_init_after_args (void)
14104 {
14105   /* initialize opcodes */
14106   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14107   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14108 }
14109
14110 long
14111 md_pcrel_from (fixS *fixP)
14112 {
14113   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14114   switch (fixP->fx_r_type)
14115     {
14116     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14117     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14118       /* Return the address of the delay slot.  */
14119       return addr + 2;
14120
14121     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14122     case BFD_RELOC_MICROMIPS_JMP:
14123     case BFD_RELOC_16_PCREL_S2:
14124     case BFD_RELOC_MIPS_JMP:
14125       /* Return the address of the delay slot.  */
14126       return addr + 4;
14127
14128     default:
14129       return addr;
14130     }
14131 }
14132
14133 /* This is called before the symbol table is processed.  In order to
14134    work with gcc when using mips-tfile, we must keep all local labels.
14135    However, in other cases, we want to discard them.  If we were
14136    called with -g, but we didn't see any debugging information, it may
14137    mean that gcc is smuggling debugging information through to
14138    mips-tfile, in which case we must generate all local labels.  */
14139
14140 void
14141 mips_frob_file_before_adjust (void)
14142 {
14143 #ifndef NO_ECOFF_DEBUGGING
14144   if (ECOFF_DEBUGGING
14145       && mips_debug != 0
14146       && ! ecoff_debugging_seen)
14147     flag_keep_locals = 1;
14148 #endif
14149 }
14150
14151 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14152    the corresponding LO16 reloc.  This is called before md_apply_fix and
14153    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14154    relocation operators.
14155
14156    For our purposes, a %lo() expression matches a %got() or %hi()
14157    expression if:
14158
14159       (a) it refers to the same symbol; and
14160       (b) the offset applied in the %lo() expression is no lower than
14161           the offset applied in the %got() or %hi().
14162
14163    (b) allows us to cope with code like:
14164
14165         lui     $4,%hi(foo)
14166         lh      $4,%lo(foo+2)($4)
14167
14168    ...which is legal on RELA targets, and has a well-defined behaviour
14169    if the user knows that adding 2 to "foo" will not induce a carry to
14170    the high 16 bits.
14171
14172    When several %lo()s match a particular %got() or %hi(), we use the
14173    following rules to distinguish them:
14174
14175      (1) %lo()s with smaller offsets are a better match than %lo()s with
14176          higher offsets.
14177
14178      (2) %lo()s with no matching %got() or %hi() are better than those
14179          that already have a matching %got() or %hi().
14180
14181      (3) later %lo()s are better than earlier %lo()s.
14182
14183    These rules are applied in order.
14184
14185    (1) means, among other things, that %lo()s with identical offsets are
14186    chosen if they exist.
14187
14188    (2) means that we won't associate several high-part relocations with
14189    the same low-part relocation unless there's no alternative.  Having
14190    several high parts for the same low part is a GNU extension; this rule
14191    allows careful users to avoid it.
14192
14193    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14194    with the last high-part relocation being at the front of the list.
14195    It therefore makes sense to choose the last matching low-part
14196    relocation, all other things being equal.  It's also easier
14197    to code that way.  */
14198
14199 void
14200 mips_frob_file (void)
14201 {
14202   struct mips_hi_fixup *l;
14203   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14204
14205   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14206     {
14207       segment_info_type *seginfo;
14208       bfd_boolean matched_lo_p;
14209       fixS **hi_pos, **lo_pos, **pos;
14210
14211       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14212
14213       /* If a GOT16 relocation turns out to be against a global symbol,
14214          there isn't supposed to be a matching LO.  Ignore %gots against
14215          constants; we'll report an error for those later.  */
14216       if (got16_reloc_p (l->fixp->fx_r_type)
14217           && !(l->fixp->fx_addsy
14218                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14219         continue;
14220
14221       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14222       if (fixup_has_matching_lo_p (l->fixp))
14223         continue;
14224
14225       seginfo = seg_info (l->seg);
14226
14227       /* Set HI_POS to the position of this relocation in the chain.
14228          Set LO_POS to the position of the chosen low-part relocation.
14229          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14230          relocation that matches an immediately-preceding high-part
14231          relocation.  */
14232       hi_pos = NULL;
14233       lo_pos = NULL;
14234       matched_lo_p = FALSE;
14235       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14236
14237       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14238         {
14239           if (*pos == l->fixp)
14240             hi_pos = pos;
14241
14242           if ((*pos)->fx_r_type == looking_for_rtype
14243               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14244               && (*pos)->fx_offset >= l->fixp->fx_offset
14245               && (lo_pos == NULL
14246                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14247                   || (!matched_lo_p
14248                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14249             lo_pos = pos;
14250
14251           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14252                           && fixup_has_matching_lo_p (*pos));
14253         }
14254
14255       /* If we found a match, remove the high-part relocation from its
14256          current position and insert it before the low-part relocation.
14257          Make the offsets match so that fixup_has_matching_lo_p()
14258          will return true.
14259
14260          We don't warn about unmatched high-part relocations since some
14261          versions of gcc have been known to emit dead "lui ...%hi(...)"
14262          instructions.  */
14263       if (lo_pos != NULL)
14264         {
14265           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14266           if (l->fixp->fx_next != *lo_pos)
14267             {
14268               *hi_pos = l->fixp->fx_next;
14269               l->fixp->fx_next = *lo_pos;
14270               *lo_pos = l->fixp;
14271             }
14272         }
14273     }
14274 }
14275
14276 int
14277 mips_force_relocation (fixS *fixp)
14278 {
14279   if (generic_force_reloc (fixp))
14280     return 1;
14281
14282   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14283      so that the linker relaxation can update targets.  */
14284   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14285       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14286       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14287     return 1;
14288
14289   return 0;
14290 }
14291
14292 /* Read the instruction associated with RELOC from BUF.  */
14293
14294 static unsigned int
14295 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14296 {
14297   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14298     return read_compressed_insn (buf, 4);
14299   else
14300     return read_insn (buf);
14301 }
14302
14303 /* Write instruction INSN to BUF, given that it has been relocated
14304    by RELOC.  */
14305
14306 static void
14307 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14308                   unsigned long insn)
14309 {
14310   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14311     write_compressed_insn (buf, insn, 4);
14312   else
14313     write_insn (buf, insn);
14314 }
14315
14316 /* Apply a fixup to the object file.  */
14317
14318 void
14319 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14320 {
14321   char *buf;
14322   unsigned long insn;
14323   reloc_howto_type *howto;
14324
14325   if (fixP->fx_pcrel)
14326     switch (fixP->fx_r_type)
14327       {
14328       case BFD_RELOC_16_PCREL_S2:
14329       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14330       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14331       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14332       case BFD_RELOC_32_PCREL:
14333         break;
14334
14335       case BFD_RELOC_32:
14336         fixP->fx_r_type = BFD_RELOC_32_PCREL;
14337         break;
14338
14339       default:
14340         as_bad_where (fixP->fx_file, fixP->fx_line,
14341                       _("PC-relative reference to a different section"));
14342         break;
14343       }
14344
14345   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
14346      that have no MIPS ELF equivalent.  */
14347   if (fixP->fx_r_type != BFD_RELOC_8)
14348     {
14349       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14350       if (!howto)
14351         return;
14352     }
14353
14354   gas_assert (fixP->fx_size == 2
14355               || fixP->fx_size == 4
14356               || fixP->fx_r_type == BFD_RELOC_8
14357               || fixP->fx_r_type == BFD_RELOC_16
14358               || fixP->fx_r_type == BFD_RELOC_64
14359               || fixP->fx_r_type == BFD_RELOC_CTOR
14360               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14361               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14362               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14363               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14364               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14365
14366   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14367
14368   /* Don't treat parts of a composite relocation as done.  There are two
14369      reasons for this:
14370
14371      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14372          should nevertheless be emitted if the first part is.
14373
14374      (2) In normal usage, composite relocations are never assembly-time
14375          constants.  The easiest way of dealing with the pathological
14376          exceptions is to generate a relocation against STN_UNDEF and
14377          leave everything up to the linker.  */
14378   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14379     fixP->fx_done = 1;
14380
14381   switch (fixP->fx_r_type)
14382     {
14383     case BFD_RELOC_MIPS_TLS_GD:
14384     case BFD_RELOC_MIPS_TLS_LDM:
14385     case BFD_RELOC_MIPS_TLS_DTPREL32:
14386     case BFD_RELOC_MIPS_TLS_DTPREL64:
14387     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14388     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14389     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14390     case BFD_RELOC_MIPS_TLS_TPREL32:
14391     case BFD_RELOC_MIPS_TLS_TPREL64:
14392     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14393     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14394     case BFD_RELOC_MICROMIPS_TLS_GD:
14395     case BFD_RELOC_MICROMIPS_TLS_LDM:
14396     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14397     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14398     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14399     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14400     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14401     case BFD_RELOC_MIPS16_TLS_GD:
14402     case BFD_RELOC_MIPS16_TLS_LDM:
14403     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14404     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14405     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14406     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14407     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14408       if (!fixP->fx_addsy)
14409         {
14410           as_bad_where (fixP->fx_file, fixP->fx_line,
14411                         _("TLS relocation against a constant"));
14412           break;
14413         }
14414       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14415       /* fall through */
14416
14417     case BFD_RELOC_MIPS_JMP:
14418     case BFD_RELOC_MIPS_SHIFT5:
14419     case BFD_RELOC_MIPS_SHIFT6:
14420     case BFD_RELOC_MIPS_GOT_DISP:
14421     case BFD_RELOC_MIPS_GOT_PAGE:
14422     case BFD_RELOC_MIPS_GOT_OFST:
14423     case BFD_RELOC_MIPS_SUB:
14424     case BFD_RELOC_MIPS_INSERT_A:
14425     case BFD_RELOC_MIPS_INSERT_B:
14426     case BFD_RELOC_MIPS_DELETE:
14427     case BFD_RELOC_MIPS_HIGHEST:
14428     case BFD_RELOC_MIPS_HIGHER:
14429     case BFD_RELOC_MIPS_SCN_DISP:
14430     case BFD_RELOC_MIPS_REL16:
14431     case BFD_RELOC_MIPS_RELGOT:
14432     case BFD_RELOC_MIPS_JALR:
14433     case BFD_RELOC_HI16:
14434     case BFD_RELOC_HI16_S:
14435     case BFD_RELOC_LO16:
14436     case BFD_RELOC_GPREL16:
14437     case BFD_RELOC_MIPS_LITERAL:
14438     case BFD_RELOC_MIPS_CALL16:
14439     case BFD_RELOC_MIPS_GOT16:
14440     case BFD_RELOC_GPREL32:
14441     case BFD_RELOC_MIPS_GOT_HI16:
14442     case BFD_RELOC_MIPS_GOT_LO16:
14443     case BFD_RELOC_MIPS_CALL_HI16:
14444     case BFD_RELOC_MIPS_CALL_LO16:
14445     case BFD_RELOC_MIPS16_GPREL:
14446     case BFD_RELOC_MIPS16_GOT16:
14447     case BFD_RELOC_MIPS16_CALL16:
14448     case BFD_RELOC_MIPS16_HI16:
14449     case BFD_RELOC_MIPS16_HI16_S:
14450     case BFD_RELOC_MIPS16_LO16:
14451     case BFD_RELOC_MIPS16_JMP:
14452     case BFD_RELOC_MICROMIPS_JMP:
14453     case BFD_RELOC_MICROMIPS_GOT_DISP:
14454     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14455     case BFD_RELOC_MICROMIPS_GOT_OFST:
14456     case BFD_RELOC_MICROMIPS_SUB:
14457     case BFD_RELOC_MICROMIPS_HIGHEST:
14458     case BFD_RELOC_MICROMIPS_HIGHER:
14459     case BFD_RELOC_MICROMIPS_SCN_DISP:
14460     case BFD_RELOC_MICROMIPS_JALR:
14461     case BFD_RELOC_MICROMIPS_HI16:
14462     case BFD_RELOC_MICROMIPS_HI16_S:
14463     case BFD_RELOC_MICROMIPS_LO16:
14464     case BFD_RELOC_MICROMIPS_GPREL16:
14465     case BFD_RELOC_MICROMIPS_LITERAL:
14466     case BFD_RELOC_MICROMIPS_CALL16:
14467     case BFD_RELOC_MICROMIPS_GOT16:
14468     case BFD_RELOC_MICROMIPS_GOT_HI16:
14469     case BFD_RELOC_MICROMIPS_GOT_LO16:
14470     case BFD_RELOC_MICROMIPS_CALL_HI16:
14471     case BFD_RELOC_MICROMIPS_CALL_LO16:
14472     case BFD_RELOC_MIPS_EH:
14473       if (fixP->fx_done)
14474         {
14475           offsetT value;
14476
14477           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14478             {
14479               insn = read_reloc_insn (buf, fixP->fx_r_type);
14480               if (mips16_reloc_p (fixP->fx_r_type))
14481                 insn |= mips16_immed_extend (value, 16);
14482               else
14483                 insn |= (value & 0xffff);
14484               write_reloc_insn (buf, fixP->fx_r_type, insn);
14485             }
14486           else
14487             as_bad_where (fixP->fx_file, fixP->fx_line,
14488                           _("unsupported constant in relocation"));
14489         }
14490       break;
14491
14492     case BFD_RELOC_64:
14493       /* This is handled like BFD_RELOC_32, but we output a sign
14494          extended value if we are only 32 bits.  */
14495       if (fixP->fx_done)
14496         {
14497           if (8 <= sizeof (valueT))
14498             md_number_to_chars (buf, *valP, 8);
14499           else
14500             {
14501               valueT hiv;
14502
14503               if ((*valP & 0x80000000) != 0)
14504                 hiv = 0xffffffff;
14505               else
14506                 hiv = 0;
14507               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14508               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14509             }
14510         }
14511       break;
14512
14513     case BFD_RELOC_RVA:
14514     case BFD_RELOC_32:
14515     case BFD_RELOC_32_PCREL:
14516     case BFD_RELOC_16:
14517     case BFD_RELOC_8:
14518       /* If we are deleting this reloc entry, we must fill in the
14519          value now.  This can happen if we have a .word which is not
14520          resolved when it appears but is later defined.  */
14521       if (fixP->fx_done)
14522         md_number_to_chars (buf, *valP, fixP->fx_size);
14523       break;
14524
14525     case BFD_RELOC_16_PCREL_S2:
14526       if ((*valP & 0x3) != 0)
14527         as_bad_where (fixP->fx_file, fixP->fx_line,
14528                       _("branch to misaligned address (%lx)"), (long) *valP);
14529
14530       /* We need to save the bits in the instruction since fixup_segment()
14531          might be deleting the relocation entry (i.e., a branch within
14532          the current segment).  */
14533       if (! fixP->fx_done)
14534         break;
14535
14536       /* Update old instruction data.  */
14537       insn = read_insn (buf);
14538
14539       if (*valP + 0x20000 <= 0x3ffff)
14540         {
14541           insn |= (*valP >> 2) & 0xffff;
14542           write_insn (buf, insn);
14543         }
14544       else if (mips_pic == NO_PIC
14545                && fixP->fx_done
14546                && fixP->fx_frag->fr_address >= text_section->vma
14547                && (fixP->fx_frag->fr_address
14548                    < text_section->vma + bfd_get_section_size (text_section))
14549                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14550                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14551                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14552         {
14553           /* The branch offset is too large.  If this is an
14554              unconditional branch, and we are not generating PIC code,
14555              we can convert it to an absolute jump instruction.  */
14556           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14557             insn = 0x0c000000;  /* jal */
14558           else
14559             insn = 0x08000000;  /* j */
14560           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14561           fixP->fx_done = 0;
14562           fixP->fx_addsy = section_symbol (text_section);
14563           *valP += md_pcrel_from (fixP);
14564           write_insn (buf, insn);
14565         }
14566       else
14567         {
14568           /* If we got here, we have branch-relaxation disabled,
14569              and there's nothing we can do to fix this instruction
14570              without turning it into a longer sequence.  */
14571           as_bad_where (fixP->fx_file, fixP->fx_line,
14572                         _("branch out of range"));
14573         }
14574       break;
14575
14576     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14577     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14578     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14579       /* We adjust the offset back to even.  */
14580       if ((*valP & 0x1) != 0)
14581         --(*valP);
14582
14583       if (! fixP->fx_done)
14584         break;
14585
14586       /* Should never visit here, because we keep the relocation.  */
14587       abort ();
14588       break;
14589
14590     case BFD_RELOC_VTABLE_INHERIT:
14591       fixP->fx_done = 0;
14592       if (fixP->fx_addsy
14593           && !S_IS_DEFINED (fixP->fx_addsy)
14594           && !S_IS_WEAK (fixP->fx_addsy))
14595         S_SET_WEAK (fixP->fx_addsy);
14596       break;
14597
14598     case BFD_RELOC_VTABLE_ENTRY:
14599       fixP->fx_done = 0;
14600       break;
14601
14602     default:
14603       abort ();
14604     }
14605
14606   /* Remember value for tc_gen_reloc.  */
14607   fixP->fx_addnumber = *valP;
14608 }
14609
14610 static symbolS *
14611 get_symbol (void)
14612 {
14613   int c;
14614   char *name;
14615   symbolS *p;
14616
14617   name = input_line_pointer;
14618   c = get_symbol_end ();
14619   p = (symbolS *) symbol_find_or_make (name);
14620   *input_line_pointer = c;
14621   return p;
14622 }
14623
14624 /* Align the current frag to a given power of two.  If a particular
14625    fill byte should be used, FILL points to an integer that contains
14626    that byte, otherwise FILL is null.
14627
14628    This function used to have the comment:
14629
14630       The MIPS assembler also automatically adjusts any preceding label.
14631
14632    The implementation therefore applied the adjustment to a maximum of
14633    one label.  However, other label adjustments are applied to batches
14634    of labels, and adjusting just one caused problems when new labels
14635    were added for the sake of debugging or unwind information.
14636    We therefore adjust all preceding labels (given as LABELS) instead.  */
14637
14638 static void
14639 mips_align (int to, int *fill, struct insn_label_list *labels)
14640 {
14641   mips_emit_delays ();
14642   mips_record_compressed_mode ();
14643   if (fill == NULL && subseg_text_p (now_seg))
14644     frag_align_code (to, 0);
14645   else
14646     frag_align (to, fill ? *fill : 0, 0);
14647   record_alignment (now_seg, to);
14648   mips_move_labels (labels, FALSE);
14649 }
14650
14651 /* Align to a given power of two.  .align 0 turns off the automatic
14652    alignment used by the data creating pseudo-ops.  */
14653
14654 static void
14655 s_align (int x ATTRIBUTE_UNUSED)
14656 {
14657   int temp, fill_value, *fill_ptr;
14658   long max_alignment = 28;
14659
14660   /* o Note that the assembler pulls down any immediately preceding label
14661        to the aligned address.
14662      o It's not documented but auto alignment is reinstated by
14663        a .align pseudo instruction.
14664      o Note also that after auto alignment is turned off the mips assembler
14665        issues an error on attempt to assemble an improperly aligned data item.
14666        We don't.  */
14667
14668   temp = get_absolute_expression ();
14669   if (temp > max_alignment)
14670     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
14671   else if (temp < 0)
14672     {
14673       as_warn (_("alignment negative, 0 assumed"));
14674       temp = 0;
14675     }
14676   if (*input_line_pointer == ',')
14677     {
14678       ++input_line_pointer;
14679       fill_value = get_absolute_expression ();
14680       fill_ptr = &fill_value;
14681     }
14682   else
14683     fill_ptr = 0;
14684   if (temp)
14685     {
14686       segment_info_type *si = seg_info (now_seg);
14687       struct insn_label_list *l = si->label_list;
14688       /* Auto alignment should be switched on by next section change.  */
14689       auto_align = 1;
14690       mips_align (temp, fill_ptr, l);
14691     }
14692   else
14693     {
14694       auto_align = 0;
14695     }
14696
14697   demand_empty_rest_of_line ();
14698 }
14699
14700 static void
14701 s_change_sec (int sec)
14702 {
14703   segT seg;
14704
14705   /* The ELF backend needs to know that we are changing sections, so
14706      that .previous works correctly.  We could do something like check
14707      for an obj_section_change_hook macro, but that might be confusing
14708      as it would not be appropriate to use it in the section changing
14709      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14710      This should be cleaner, somehow.  */
14711   obj_elf_section_change_hook ();
14712
14713   mips_emit_delays ();
14714
14715   switch (sec)
14716     {
14717     case 't':
14718       s_text (0);
14719       break;
14720     case 'd':
14721       s_data (0);
14722       break;
14723     case 'b':
14724       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14725       demand_empty_rest_of_line ();
14726       break;
14727
14728     case 'r':
14729       seg = subseg_new (RDATA_SECTION_NAME,
14730                         (subsegT) get_absolute_expression ());
14731       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14732                                               | SEC_READONLY | SEC_RELOC
14733                                               | SEC_DATA));
14734       if (strncmp (TARGET_OS, "elf", 3) != 0)
14735         record_alignment (seg, 4);
14736       demand_empty_rest_of_line ();
14737       break;
14738
14739     case 's':
14740       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14741       bfd_set_section_flags (stdoutput, seg,
14742                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14743       if (strncmp (TARGET_OS, "elf", 3) != 0)
14744         record_alignment (seg, 4);
14745       demand_empty_rest_of_line ();
14746       break;
14747
14748     case 'B':
14749       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14750       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14751       if (strncmp (TARGET_OS, "elf", 3) != 0)
14752         record_alignment (seg, 4);
14753       demand_empty_rest_of_line ();
14754       break;
14755     }
14756
14757   auto_align = 1;
14758 }
14759
14760 void
14761 s_change_section (int ignore ATTRIBUTE_UNUSED)
14762 {
14763   char *section_name;
14764   char c;
14765   char next_c = 0;
14766   int section_type;
14767   int section_flag;
14768   int section_entry_size;
14769   int section_alignment;
14770
14771   section_name = input_line_pointer;
14772   c = get_symbol_end ();
14773   if (c)
14774     next_c = *(input_line_pointer + 1);
14775
14776   /* Do we have .section Name<,"flags">?  */
14777   if (c != ',' || (c == ',' && next_c == '"'))
14778     {
14779       /* just after name is now '\0'.  */
14780       *input_line_pointer = c;
14781       input_line_pointer = section_name;
14782       obj_elf_section (ignore);
14783       return;
14784     }
14785   input_line_pointer++;
14786
14787   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14788   if (c == ',')
14789     section_type = get_absolute_expression ();
14790   else
14791     section_type = 0;
14792   if (*input_line_pointer++ == ',')
14793     section_flag = get_absolute_expression ();
14794   else
14795     section_flag = 0;
14796   if (*input_line_pointer++ == ',')
14797     section_entry_size = get_absolute_expression ();
14798   else
14799     section_entry_size = 0;
14800   if (*input_line_pointer++ == ',')
14801     section_alignment = get_absolute_expression ();
14802   else
14803     section_alignment = 0;
14804   /* FIXME: really ignore?  */
14805   (void) section_alignment;
14806
14807   section_name = xstrdup (section_name);
14808
14809   /* When using the generic form of .section (as implemented by obj-elf.c),
14810      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14811      traditionally had to fall back on the more common @progbits instead.
14812
14813      There's nothing really harmful in this, since bfd will correct
14814      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14815      means that, for backwards compatibility, the special_section entries
14816      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14817
14818      Even so, we shouldn't force users of the MIPS .section syntax to
14819      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14820      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14821      generic type-checking code.  */
14822   if (section_type == SHT_MIPS_DWARF)
14823     section_type = SHT_PROGBITS;
14824
14825   obj_elf_change_section (section_name, section_type, section_flag,
14826                           section_entry_size, 0, 0, 0);
14827
14828   if (now_seg->name != section_name)
14829     free (section_name);
14830 }
14831
14832 void
14833 mips_enable_auto_align (void)
14834 {
14835   auto_align = 1;
14836 }
14837
14838 static void
14839 s_cons (int log_size)
14840 {
14841   segment_info_type *si = seg_info (now_seg);
14842   struct insn_label_list *l = si->label_list;
14843
14844   mips_emit_delays ();
14845   if (log_size > 0 && auto_align)
14846     mips_align (log_size, 0, l);
14847   cons (1 << log_size);
14848   mips_clear_insn_labels ();
14849 }
14850
14851 static void
14852 s_float_cons (int type)
14853 {
14854   segment_info_type *si = seg_info (now_seg);
14855   struct insn_label_list *l = si->label_list;
14856
14857   mips_emit_delays ();
14858
14859   if (auto_align)
14860     {
14861       if (type == 'd')
14862         mips_align (3, 0, l);
14863       else
14864         mips_align (2, 0, l);
14865     }
14866
14867   float_cons (type);
14868   mips_clear_insn_labels ();
14869 }
14870
14871 /* Handle .globl.  We need to override it because on Irix 5 you are
14872    permitted to say
14873        .globl foo .text
14874    where foo is an undefined symbol, to mean that foo should be
14875    considered to be the address of a function.  */
14876
14877 static void
14878 s_mips_globl (int x ATTRIBUTE_UNUSED)
14879 {
14880   char *name;
14881   int c;
14882   symbolS *symbolP;
14883   flagword flag;
14884
14885   do
14886     {
14887       name = input_line_pointer;
14888       c = get_symbol_end ();
14889       symbolP = symbol_find_or_make (name);
14890       S_SET_EXTERNAL (symbolP);
14891
14892       *input_line_pointer = c;
14893       SKIP_WHITESPACE ();
14894
14895       /* On Irix 5, every global symbol that is not explicitly labelled as
14896          being a function is apparently labelled as being an object.  */
14897       flag = BSF_OBJECT;
14898
14899       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14900           && (*input_line_pointer != ','))
14901         {
14902           char *secname;
14903           asection *sec;
14904
14905           secname = input_line_pointer;
14906           c = get_symbol_end ();
14907           sec = bfd_get_section_by_name (stdoutput, secname);
14908           if (sec == NULL)
14909             as_bad (_("%s: no such section"), secname);
14910           *input_line_pointer = c;
14911
14912           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14913             flag = BSF_FUNCTION;
14914         }
14915
14916       symbol_get_bfdsym (symbolP)->flags |= flag;
14917
14918       c = *input_line_pointer;
14919       if (c == ',')
14920         {
14921           input_line_pointer++;
14922           SKIP_WHITESPACE ();
14923           if (is_end_of_line[(unsigned char) *input_line_pointer])
14924             c = '\n';
14925         }
14926     }
14927   while (c == ',');
14928
14929   demand_empty_rest_of_line ();
14930 }
14931
14932 static void
14933 s_option (int x ATTRIBUTE_UNUSED)
14934 {
14935   char *opt;
14936   char c;
14937
14938   opt = input_line_pointer;
14939   c = get_symbol_end ();
14940
14941   if (*opt == 'O')
14942     {
14943       /* FIXME: What does this mean?  */
14944     }
14945   else if (strncmp (opt, "pic", 3) == 0)
14946     {
14947       int i;
14948
14949       i = atoi (opt + 3);
14950       if (i == 0)
14951         mips_pic = NO_PIC;
14952       else if (i == 2)
14953         {
14954           mips_pic = SVR4_PIC;
14955           mips_abicalls = TRUE;
14956         }
14957       else
14958         as_bad (_(".option pic%d not supported"), i);
14959
14960       if (mips_pic == SVR4_PIC)
14961         {
14962           if (g_switch_seen && g_switch_value != 0)
14963             as_warn (_("-G may not be used with SVR4 PIC code"));
14964           g_switch_value = 0;
14965           bfd_set_gp_size (stdoutput, 0);
14966         }
14967     }
14968   else
14969     as_warn (_("unrecognized option \"%s\""), opt);
14970
14971   *input_line_pointer = c;
14972   demand_empty_rest_of_line ();
14973 }
14974
14975 /* This structure is used to hold a stack of .set values.  */
14976
14977 struct mips_option_stack
14978 {
14979   struct mips_option_stack *next;
14980   struct mips_set_options options;
14981 };
14982
14983 static struct mips_option_stack *mips_opts_stack;
14984
14985 /* Handle the .set pseudo-op.  */
14986
14987 static void
14988 s_mipsset (int x ATTRIBUTE_UNUSED)
14989 {
14990   char *name = input_line_pointer, ch;
14991   const struct mips_ase *ase;
14992
14993   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14994     ++input_line_pointer;
14995   ch = *input_line_pointer;
14996   *input_line_pointer = '\0';
14997
14998   if (strcmp (name, "reorder") == 0)
14999     {
15000       if (mips_opts.noreorder)
15001         end_noreorder ();
15002     }
15003   else if (strcmp (name, "noreorder") == 0)
15004     {
15005       if (!mips_opts.noreorder)
15006         start_noreorder ();
15007     }
15008   else if (strncmp (name, "at=", 3) == 0)
15009     {
15010       char *s = name + 3;
15011
15012       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
15013         as_bad (_("unrecognized register name `%s'"), s);
15014     }
15015   else if (strcmp (name, "at") == 0)
15016     {
15017       mips_opts.at = ATREG;
15018     }
15019   else if (strcmp (name, "noat") == 0)
15020     {
15021       mips_opts.at = ZERO;
15022     }
15023   else if (strcmp (name, "macro") == 0)
15024     {
15025       mips_opts.warn_about_macros = 0;
15026     }
15027   else if (strcmp (name, "nomacro") == 0)
15028     {
15029       if (mips_opts.noreorder == 0)
15030         as_bad (_("`noreorder' must be set before `nomacro'"));
15031       mips_opts.warn_about_macros = 1;
15032     }
15033   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
15034     {
15035       mips_opts.nomove = 0;
15036     }
15037   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
15038     {
15039       mips_opts.nomove = 1;
15040     }
15041   else if (strcmp (name, "bopt") == 0)
15042     {
15043       mips_opts.nobopt = 0;
15044     }
15045   else if (strcmp (name, "nobopt") == 0)
15046     {
15047       mips_opts.nobopt = 1;
15048     }
15049   else if (strcmp (name, "gp=default") == 0)
15050     mips_opts.gp32 = file_mips_gp32;
15051   else if (strcmp (name, "gp=32") == 0)
15052     mips_opts.gp32 = 1;
15053   else if (strcmp (name, "gp=64") == 0)
15054     {
15055       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
15056         as_warn (_("%s isa does not support 64-bit registers"),
15057                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15058       mips_opts.gp32 = 0;
15059     }
15060   else if (strcmp (name, "fp=default") == 0)
15061     mips_opts.fp32 = file_mips_fp32;
15062   else if (strcmp (name, "fp=32") == 0)
15063     mips_opts.fp32 = 1;
15064   else if (strcmp (name, "fp=64") == 0)
15065     {
15066       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15067         as_warn (_("%s isa does not support 64-bit floating point registers"),
15068                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15069       mips_opts.fp32 = 0;
15070     }
15071   else if (strcmp (name, "softfloat") == 0)
15072     mips_opts.soft_float = 1;
15073   else if (strcmp (name, "hardfloat") == 0)
15074     mips_opts.soft_float = 0;
15075   else if (strcmp (name, "singlefloat") == 0)
15076     mips_opts.single_float = 1;
15077   else if (strcmp (name, "doublefloat") == 0)
15078     mips_opts.single_float = 0;
15079   else if (strcmp (name, "mips16") == 0
15080            || strcmp (name, "MIPS-16") == 0)
15081     {
15082       if (mips_opts.micromips == 1)
15083         as_fatal (_("`mips16' cannot be used with `micromips'"));
15084       mips_opts.mips16 = 1;
15085     }
15086   else if (strcmp (name, "nomips16") == 0
15087            || strcmp (name, "noMIPS-16") == 0)
15088     mips_opts.mips16 = 0;
15089   else if (strcmp (name, "micromips") == 0)
15090     {
15091       if (mips_opts.mips16 == 1)
15092         as_fatal (_("`micromips' cannot be used with `mips16'"));
15093       mips_opts.micromips = 1;
15094     }
15095   else if (strcmp (name, "nomicromips") == 0)
15096     mips_opts.micromips = 0;
15097   else if (name[0] == 'n'
15098            && name[1] == 'o'
15099            && (ase = mips_lookup_ase (name + 2)))
15100     mips_set_ase (ase, FALSE);
15101   else if ((ase = mips_lookup_ase (name)))
15102     mips_set_ase (ase, TRUE);
15103   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15104     {
15105       int reset = 0;
15106
15107       /* Permit the user to change the ISA and architecture on the fly.
15108          Needless to say, misuse can cause serious problems.  */
15109       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
15110         {
15111           reset = 1;
15112           mips_opts.isa = file_mips_isa;
15113           mips_opts.arch = file_mips_arch;
15114         }
15115       else if (strncmp (name, "arch=", 5) == 0)
15116         {
15117           const struct mips_cpu_info *p;
15118
15119           p = mips_parse_cpu("internal use", name + 5);
15120           if (!p)
15121             as_bad (_("unknown architecture %s"), name + 5);
15122           else
15123             {
15124               mips_opts.arch = p->cpu;
15125               mips_opts.isa = p->isa;
15126             }
15127         }
15128       else if (strncmp (name, "mips", 4) == 0)
15129         {
15130           const struct mips_cpu_info *p;
15131
15132           p = mips_parse_cpu("internal use", name);
15133           if (!p)
15134             as_bad (_("unknown ISA level %s"), name + 4);
15135           else
15136             {
15137               mips_opts.arch = p->cpu;
15138               mips_opts.isa = p->isa;
15139             }
15140         }
15141       else
15142         as_bad (_("unknown ISA or architecture %s"), name);
15143
15144       switch (mips_opts.isa)
15145         {
15146         case  0:
15147           break;
15148         case ISA_MIPS1:
15149         case ISA_MIPS2:
15150         case ISA_MIPS32:
15151         case ISA_MIPS32R2:
15152         case ISA_MIPS32R3:
15153         case ISA_MIPS32R5:
15154           mips_opts.gp32 = 1;
15155           mips_opts.fp32 = 1;
15156           break;
15157         case ISA_MIPS3:
15158         case ISA_MIPS4:
15159         case ISA_MIPS5:
15160         case ISA_MIPS64:
15161         case ISA_MIPS64R2:
15162         case ISA_MIPS64R3:
15163         case ISA_MIPS64R5:
15164           mips_opts.gp32 = 0;
15165           if (mips_opts.arch == CPU_R5900)
15166             {
15167                 mips_opts.fp32 = 1;
15168             }
15169           else
15170             {
15171           mips_opts.fp32 = 0;
15172             }
15173           break;
15174         default:
15175           as_bad (_("unknown ISA level %s"), name + 4);
15176           break;
15177         }
15178       if (reset)
15179         {
15180           mips_opts.gp32 = file_mips_gp32;
15181           mips_opts.fp32 = file_mips_fp32;
15182         }
15183     }
15184   else if (strcmp (name, "autoextend") == 0)
15185     mips_opts.noautoextend = 0;
15186   else if (strcmp (name, "noautoextend") == 0)
15187     mips_opts.noautoextend = 1;
15188   else if (strcmp (name, "insn32") == 0)
15189     mips_opts.insn32 = TRUE;
15190   else if (strcmp (name, "noinsn32") == 0)
15191     mips_opts.insn32 = FALSE;
15192   else if (strcmp (name, "push") == 0)
15193     {
15194       struct mips_option_stack *s;
15195
15196       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15197       s->next = mips_opts_stack;
15198       s->options = mips_opts;
15199       mips_opts_stack = s;
15200     }
15201   else if (strcmp (name, "pop") == 0)
15202     {
15203       struct mips_option_stack *s;
15204
15205       s = mips_opts_stack;
15206       if (s == NULL)
15207         as_bad (_(".set pop with no .set push"));
15208       else
15209         {
15210           /* If we're changing the reorder mode we need to handle
15211              delay slots correctly.  */
15212           if (s->options.noreorder && ! mips_opts.noreorder)
15213             start_noreorder ();
15214           else if (! s->options.noreorder && mips_opts.noreorder)
15215             end_noreorder ();
15216
15217           mips_opts = s->options;
15218           mips_opts_stack = s->next;
15219           free (s);
15220         }
15221     }
15222   else if (strcmp (name, "sym32") == 0)
15223     mips_opts.sym32 = TRUE;
15224   else if (strcmp (name, "nosym32") == 0)
15225     mips_opts.sym32 = FALSE;
15226   else if (strchr (name, ','))
15227     {
15228       /* Generic ".set" directive; use the generic handler.  */
15229       *input_line_pointer = ch;
15230       input_line_pointer = name;
15231       s_set (0);
15232       return;
15233     }
15234   else
15235     {
15236       as_warn (_("tried to set unrecognized symbol: %s\n"), name);
15237     }
15238   mips_check_isa_supports_ases ();
15239   *input_line_pointer = ch;
15240   demand_empty_rest_of_line ();
15241 }
15242
15243 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15244    .option pic2.  It means to generate SVR4 PIC calls.  */
15245
15246 static void
15247 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15248 {
15249   mips_pic = SVR4_PIC;
15250   mips_abicalls = TRUE;
15251
15252   if (g_switch_seen && g_switch_value != 0)
15253     as_warn (_("-G may not be used with SVR4 PIC code"));
15254   g_switch_value = 0;
15255
15256   bfd_set_gp_size (stdoutput, 0);
15257   demand_empty_rest_of_line ();
15258 }
15259
15260 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15261    PIC code.  It sets the $gp register for the function based on the
15262    function address, which is in the register named in the argument.
15263    This uses a relocation against _gp_disp, which is handled specially
15264    by the linker.  The result is:
15265         lui     $gp,%hi(_gp_disp)
15266         addiu   $gp,$gp,%lo(_gp_disp)
15267         addu    $gp,$gp,.cpload argument
15268    The .cpload argument is normally $25 == $t9.
15269
15270    The -mno-shared option changes this to:
15271         lui     $gp,%hi(__gnu_local_gp)
15272         addiu   $gp,$gp,%lo(__gnu_local_gp)
15273    and the argument is ignored.  This saves an instruction, but the
15274    resulting code is not position independent; it uses an absolute
15275    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15276    can go into an ordinary executable, but not into a shared library.  */
15277
15278 static void
15279 s_cpload (int ignore ATTRIBUTE_UNUSED)
15280 {
15281   expressionS ex;
15282   int reg;
15283   int in_shared;
15284
15285   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15286      .cpload is ignored.  */
15287   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15288     {
15289       s_ignore (0);
15290       return;
15291     }
15292
15293   if (mips_opts.mips16)
15294     {
15295       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15296       ignore_rest_of_line ();
15297       return;
15298     }
15299
15300   /* .cpload should be in a .set noreorder section.  */
15301   if (mips_opts.noreorder == 0)
15302     as_warn (_(".cpload not in noreorder section"));
15303
15304   reg = tc_get_register (0);
15305
15306   /* If we need to produce a 64-bit address, we are better off using
15307      the default instruction sequence.  */
15308   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15309
15310   ex.X_op = O_symbol;
15311   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15312                                          "__gnu_local_gp");
15313   ex.X_op_symbol = NULL;
15314   ex.X_add_number = 0;
15315
15316   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15317   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15318
15319   mips_mark_labels ();
15320   mips_assembling_insn = TRUE;
15321
15322   macro_start ();
15323   macro_build_lui (&ex, mips_gp_register);
15324   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15325                mips_gp_register, BFD_RELOC_LO16);
15326   if (in_shared)
15327     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15328                  mips_gp_register, reg);
15329   macro_end ();
15330
15331   mips_assembling_insn = FALSE;
15332   demand_empty_rest_of_line ();
15333 }
15334
15335 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15336      .cpsetup $reg1, offset|$reg2, label
15337
15338    If offset is given, this results in:
15339      sd         $gp, offset($sp)
15340      lui        $gp, %hi(%neg(%gp_rel(label)))
15341      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15342      daddu      $gp, $gp, $reg1
15343
15344    If $reg2 is given, this results in:
15345      daddu      $reg2, $gp, $0
15346      lui        $gp, %hi(%neg(%gp_rel(label)))
15347      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15348      daddu      $gp, $gp, $reg1
15349    $reg1 is normally $25 == $t9.
15350
15351    The -mno-shared option replaces the last three instructions with
15352         lui     $gp,%hi(_gp)
15353         addiu   $gp,$gp,%lo(_gp)  */
15354
15355 static void
15356 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15357 {
15358   expressionS ex_off;
15359   expressionS ex_sym;
15360   int reg1;
15361
15362   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15363      We also need NewABI support.  */
15364   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15365     {
15366       s_ignore (0);
15367       return;
15368     }
15369
15370   if (mips_opts.mips16)
15371     {
15372       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15373       ignore_rest_of_line ();
15374       return;
15375     }
15376
15377   reg1 = tc_get_register (0);
15378   SKIP_WHITESPACE ();
15379   if (*input_line_pointer != ',')
15380     {
15381       as_bad (_("missing argument separator ',' for .cpsetup"));
15382       return;
15383     }
15384   else
15385     ++input_line_pointer;
15386   SKIP_WHITESPACE ();
15387   if (*input_line_pointer == '$')
15388     {
15389       mips_cpreturn_register = tc_get_register (0);
15390       mips_cpreturn_offset = -1;
15391     }
15392   else
15393     {
15394       mips_cpreturn_offset = get_absolute_expression ();
15395       mips_cpreturn_register = -1;
15396     }
15397   SKIP_WHITESPACE ();
15398   if (*input_line_pointer != ',')
15399     {
15400       as_bad (_("missing argument separator ',' for .cpsetup"));
15401       return;
15402     }
15403   else
15404     ++input_line_pointer;
15405   SKIP_WHITESPACE ();
15406   expression (&ex_sym);
15407
15408   mips_mark_labels ();
15409   mips_assembling_insn = TRUE;
15410
15411   macro_start ();
15412   if (mips_cpreturn_register == -1)
15413     {
15414       ex_off.X_op = O_constant;
15415       ex_off.X_add_symbol = NULL;
15416       ex_off.X_op_symbol = NULL;
15417       ex_off.X_add_number = mips_cpreturn_offset;
15418
15419       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15420                    BFD_RELOC_LO16, SP);
15421     }
15422   else
15423     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15424                  mips_gp_register, 0);
15425
15426   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15427     {
15428       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15429                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15430                    BFD_RELOC_HI16_S);
15431
15432       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15433                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15434                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15435
15436       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15437                    mips_gp_register, reg1);
15438     }
15439   else
15440     {
15441       expressionS ex;
15442
15443       ex.X_op = O_symbol;
15444       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15445       ex.X_op_symbol = NULL;
15446       ex.X_add_number = 0;
15447
15448       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15449       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15450
15451       macro_build_lui (&ex, mips_gp_register);
15452       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15453                    mips_gp_register, BFD_RELOC_LO16);
15454     }
15455
15456   macro_end ();
15457
15458   mips_assembling_insn = FALSE;
15459   demand_empty_rest_of_line ();
15460 }
15461
15462 static void
15463 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15464 {
15465   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15466      .cplocal is ignored.  */
15467   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15468     {
15469       s_ignore (0);
15470       return;
15471     }
15472
15473   if (mips_opts.mips16)
15474     {
15475       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15476       ignore_rest_of_line ();
15477       return;
15478     }
15479
15480   mips_gp_register = tc_get_register (0);
15481   demand_empty_rest_of_line ();
15482 }
15483
15484 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15485    offset from $sp.  The offset is remembered, and after making a PIC
15486    call $gp is restored from that location.  */
15487
15488 static void
15489 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15490 {
15491   expressionS ex;
15492
15493   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15494      .cprestore is ignored.  */
15495   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15496     {
15497       s_ignore (0);
15498       return;
15499     }
15500
15501   if (mips_opts.mips16)
15502     {
15503       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15504       ignore_rest_of_line ();
15505       return;
15506     }
15507
15508   mips_cprestore_offset = get_absolute_expression ();
15509   mips_cprestore_valid = 1;
15510
15511   ex.X_op = O_constant;
15512   ex.X_add_symbol = NULL;
15513   ex.X_op_symbol = NULL;
15514   ex.X_add_number = mips_cprestore_offset;
15515
15516   mips_mark_labels ();
15517   mips_assembling_insn = TRUE;
15518
15519   macro_start ();
15520   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15521                                 SP, HAVE_64BIT_ADDRESSES);
15522   macro_end ();
15523
15524   mips_assembling_insn = FALSE;
15525   demand_empty_rest_of_line ();
15526 }
15527
15528 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15529    was given in the preceding .cpsetup, it results in:
15530      ld         $gp, offset($sp)
15531
15532    If a register $reg2 was given there, it results in:
15533      daddu      $gp, $reg2, $0  */
15534
15535 static void
15536 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15537 {
15538   expressionS ex;
15539
15540   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15541      We also need NewABI support.  */
15542   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15543     {
15544       s_ignore (0);
15545       return;
15546     }
15547
15548   if (mips_opts.mips16)
15549     {
15550       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15551       ignore_rest_of_line ();
15552       return;
15553     }
15554
15555   mips_mark_labels ();
15556   mips_assembling_insn = TRUE;
15557
15558   macro_start ();
15559   if (mips_cpreturn_register == -1)
15560     {
15561       ex.X_op = O_constant;
15562       ex.X_add_symbol = NULL;
15563       ex.X_op_symbol = NULL;
15564       ex.X_add_number = mips_cpreturn_offset;
15565
15566       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15567     }
15568   else
15569     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15570                  mips_cpreturn_register, 0);
15571   macro_end ();
15572
15573   mips_assembling_insn = FALSE;
15574   demand_empty_rest_of_line ();
15575 }
15576
15577 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15578    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15579    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15580    debug information or MIPS16 TLS.  */
15581
15582 static void
15583 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15584                      bfd_reloc_code_real_type rtype)
15585 {
15586   expressionS ex;
15587   char *p;
15588
15589   expression (&ex);
15590
15591   if (ex.X_op != O_symbol)
15592     {
15593       as_bad (_("unsupported use of %s"), dirstr);
15594       ignore_rest_of_line ();
15595     }
15596
15597   p = frag_more (bytes);
15598   md_number_to_chars (p, 0, bytes);
15599   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15600   demand_empty_rest_of_line ();
15601   mips_clear_insn_labels ();
15602 }
15603
15604 /* Handle .dtprelword.  */
15605
15606 static void
15607 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15608 {
15609   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15610 }
15611
15612 /* Handle .dtpreldword.  */
15613
15614 static void
15615 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15616 {
15617   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15618 }
15619
15620 /* Handle .tprelword.  */
15621
15622 static void
15623 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15624 {
15625   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15626 }
15627
15628 /* Handle .tpreldword.  */
15629
15630 static void
15631 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15632 {
15633   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15634 }
15635
15636 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15637    code.  It sets the offset to use in gp_rel relocations.  */
15638
15639 static void
15640 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15641 {
15642   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15643      We also need NewABI support.  */
15644   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15645     {
15646       s_ignore (0);
15647       return;
15648     }
15649
15650   mips_gprel_offset = get_absolute_expression ();
15651
15652   demand_empty_rest_of_line ();
15653 }
15654
15655 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15656    code.  It generates a 32 bit GP relative reloc.  */
15657
15658 static void
15659 s_gpword (int ignore ATTRIBUTE_UNUSED)
15660 {
15661   segment_info_type *si;
15662   struct insn_label_list *l;
15663   expressionS ex;
15664   char *p;
15665
15666   /* When not generating PIC code, this is treated as .word.  */
15667   if (mips_pic != SVR4_PIC)
15668     {
15669       s_cons (2);
15670       return;
15671     }
15672
15673   si = seg_info (now_seg);
15674   l = si->label_list;
15675   mips_emit_delays ();
15676   if (auto_align)
15677     mips_align (2, 0, l);
15678
15679   expression (&ex);
15680   mips_clear_insn_labels ();
15681
15682   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15683     {
15684       as_bad (_("unsupported use of .gpword"));
15685       ignore_rest_of_line ();
15686     }
15687
15688   p = frag_more (4);
15689   md_number_to_chars (p, 0, 4);
15690   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15691                BFD_RELOC_GPREL32);
15692
15693   demand_empty_rest_of_line ();
15694 }
15695
15696 static void
15697 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15698 {
15699   segment_info_type *si;
15700   struct insn_label_list *l;
15701   expressionS ex;
15702   char *p;
15703
15704   /* When not generating PIC code, this is treated as .dword.  */
15705   if (mips_pic != SVR4_PIC)
15706     {
15707       s_cons (3);
15708       return;
15709     }
15710
15711   si = seg_info (now_seg);
15712   l = si->label_list;
15713   mips_emit_delays ();
15714   if (auto_align)
15715     mips_align (3, 0, l);
15716
15717   expression (&ex);
15718   mips_clear_insn_labels ();
15719
15720   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15721     {
15722       as_bad (_("unsupported use of .gpdword"));
15723       ignore_rest_of_line ();
15724     }
15725
15726   p = frag_more (8);
15727   md_number_to_chars (p, 0, 8);
15728   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15729                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15730
15731   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15732   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15733            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15734
15735   demand_empty_rest_of_line ();
15736 }
15737
15738 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15739    tables.  It generates a R_MIPS_EH reloc.  */
15740
15741 static void
15742 s_ehword (int ignore ATTRIBUTE_UNUSED)
15743 {
15744   expressionS ex;
15745   char *p;
15746
15747   mips_emit_delays ();
15748
15749   expression (&ex);
15750   mips_clear_insn_labels ();
15751
15752   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15753     {
15754       as_bad (_("unsupported use of .ehword"));
15755       ignore_rest_of_line ();
15756     }
15757
15758   p = frag_more (4);
15759   md_number_to_chars (p, 0, 4);
15760   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15761                BFD_RELOC_MIPS_EH);
15762
15763   demand_empty_rest_of_line ();
15764 }
15765
15766 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15767    tables in SVR4 PIC code.  */
15768
15769 static void
15770 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15771 {
15772   int reg;
15773
15774   /* This is ignored when not generating SVR4 PIC code.  */
15775   if (mips_pic != SVR4_PIC)
15776     {
15777       s_ignore (0);
15778       return;
15779     }
15780
15781   mips_mark_labels ();
15782   mips_assembling_insn = TRUE;
15783
15784   /* Add $gp to the register named as an argument.  */
15785   macro_start ();
15786   reg = tc_get_register (0);
15787   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15788   macro_end ();
15789
15790   mips_assembling_insn = FALSE;
15791   demand_empty_rest_of_line ();
15792 }
15793
15794 /* Handle the .insn pseudo-op.  This marks instruction labels in
15795    mips16/micromips mode.  This permits the linker to handle them specially,
15796    such as generating jalx instructions when needed.  We also make
15797    them odd for the duration of the assembly, in order to generate the
15798    right sort of code.  We will make them even in the adjust_symtab
15799    routine, while leaving them marked.  This is convenient for the
15800    debugger and the disassembler.  The linker knows to make them odd
15801    again.  */
15802
15803 static void
15804 s_insn (int ignore ATTRIBUTE_UNUSED)
15805 {
15806   mips_mark_labels ();
15807
15808   demand_empty_rest_of_line ();
15809 }
15810
15811 /* Handle the .nan pseudo-op.  */
15812
15813 static void
15814 s_nan (int ignore ATTRIBUTE_UNUSED)
15815 {
15816   static const char str_legacy[] = "legacy";
15817   static const char str_2008[] = "2008";
15818   size_t i;
15819
15820   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15821
15822   if (i == sizeof (str_2008) - 1
15823       && memcmp (input_line_pointer, str_2008, i) == 0)
15824     mips_flag_nan2008 = TRUE;
15825   else if (i == sizeof (str_legacy) - 1
15826            && memcmp (input_line_pointer, str_legacy, i) == 0)
15827     mips_flag_nan2008 = FALSE;
15828   else
15829     as_bad (_("bad .nan directive"));
15830
15831   input_line_pointer += i;
15832   demand_empty_rest_of_line ();
15833 }
15834
15835 /* Handle a .stab[snd] directive.  Ideally these directives would be
15836    implemented in a transparent way, so that removing them would not
15837    have any effect on the generated instructions.  However, s_stab
15838    internally changes the section, so in practice we need to decide
15839    now whether the preceding label marks compressed code.  We do not
15840    support changing the compression mode of a label after a .stab*
15841    directive, such as in:
15842
15843    foo:
15844         .stabs ...
15845         .set mips16
15846
15847    so the current mode wins.  */
15848
15849 static void
15850 s_mips_stab (int type)
15851 {
15852   mips_mark_labels ();
15853   s_stab (type);
15854 }
15855
15856 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15857
15858 static void
15859 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15860 {
15861   char *name;
15862   int c;
15863   symbolS *symbolP;
15864   expressionS exp;
15865
15866   name = input_line_pointer;
15867   c = get_symbol_end ();
15868   symbolP = symbol_find_or_make (name);
15869   S_SET_WEAK (symbolP);
15870   *input_line_pointer = c;
15871
15872   SKIP_WHITESPACE ();
15873
15874   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15875     {
15876       if (S_IS_DEFINED (symbolP))
15877         {
15878           as_bad (_("ignoring attempt to redefine symbol %s"),
15879                   S_GET_NAME (symbolP));
15880           ignore_rest_of_line ();
15881           return;
15882         }
15883
15884       if (*input_line_pointer == ',')
15885         {
15886           ++input_line_pointer;
15887           SKIP_WHITESPACE ();
15888         }
15889
15890       expression (&exp);
15891       if (exp.X_op != O_symbol)
15892         {
15893           as_bad (_("bad .weakext directive"));
15894           ignore_rest_of_line ();
15895           return;
15896         }
15897       symbol_set_value_expression (symbolP, &exp);
15898     }
15899
15900   demand_empty_rest_of_line ();
15901 }
15902
15903 /* Parse a register string into a number.  Called from the ECOFF code
15904    to parse .frame.  The argument is non-zero if this is the frame
15905    register, so that we can record it in mips_frame_reg.  */
15906
15907 int
15908 tc_get_register (int frame)
15909 {
15910   unsigned int reg;
15911
15912   SKIP_WHITESPACE ();
15913   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15914     reg = 0;
15915   if (frame)
15916     {
15917       mips_frame_reg = reg != 0 ? reg : SP;
15918       mips_frame_reg_valid = 1;
15919       mips_cprestore_valid = 0;
15920     }
15921   return reg;
15922 }
15923
15924 valueT
15925 md_section_align (asection *seg, valueT addr)
15926 {
15927   int align = bfd_get_section_alignment (stdoutput, seg);
15928
15929   /* We don't need to align ELF sections to the full alignment.
15930      However, Irix 5 may prefer that we align them at least to a 16
15931      byte boundary.  We don't bother to align the sections if we
15932      are targeted for an embedded system.  */
15933   if (strncmp (TARGET_OS, "elf", 3) == 0)
15934     return addr;
15935   if (align > 4)
15936     align = 4;
15937
15938   return ((addr + (1 << align) - 1) & (-1 << align));
15939 }
15940
15941 /* Utility routine, called from above as well.  If called while the
15942    input file is still being read, it's only an approximation.  (For
15943    example, a symbol may later become defined which appeared to be
15944    undefined earlier.)  */
15945
15946 static int
15947 nopic_need_relax (symbolS *sym, int before_relaxing)
15948 {
15949   if (sym == 0)
15950     return 0;
15951
15952   if (g_switch_value > 0)
15953     {
15954       const char *symname;
15955       int change;
15956
15957       /* Find out whether this symbol can be referenced off the $gp
15958          register.  It can be if it is smaller than the -G size or if
15959          it is in the .sdata or .sbss section.  Certain symbols can
15960          not be referenced off the $gp, although it appears as though
15961          they can.  */
15962       symname = S_GET_NAME (sym);
15963       if (symname != (const char *) NULL
15964           && (strcmp (symname, "eprol") == 0
15965               || strcmp (symname, "etext") == 0
15966               || strcmp (symname, "_gp") == 0
15967               || strcmp (symname, "edata") == 0
15968               || strcmp (symname, "_fbss") == 0
15969               || strcmp (symname, "_fdata") == 0
15970               || strcmp (symname, "_ftext") == 0
15971               || strcmp (symname, "end") == 0
15972               || strcmp (symname, "_gp_disp") == 0))
15973         change = 1;
15974       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15975                && (0
15976 #ifndef NO_ECOFF_DEBUGGING
15977                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15978                        && (symbol_get_obj (sym)->ecoff_extern_size
15979                            <= g_switch_value))
15980 #endif
15981                    /* We must defer this decision until after the whole
15982                       file has been read, since there might be a .extern
15983                       after the first use of this symbol.  */
15984                    || (before_relaxing
15985 #ifndef NO_ECOFF_DEBUGGING
15986                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15987 #endif
15988                        && S_GET_VALUE (sym) == 0)
15989                    || (S_GET_VALUE (sym) != 0
15990                        && S_GET_VALUE (sym) <= g_switch_value)))
15991         change = 0;
15992       else
15993         {
15994           const char *segname;
15995
15996           segname = segment_name (S_GET_SEGMENT (sym));
15997           gas_assert (strcmp (segname, ".lit8") != 0
15998                   && strcmp (segname, ".lit4") != 0);
15999           change = (strcmp (segname, ".sdata") != 0
16000                     && strcmp (segname, ".sbss") != 0
16001                     && strncmp (segname, ".sdata.", 7) != 0
16002                     && strncmp (segname, ".sbss.", 6) != 0
16003                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
16004                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
16005         }
16006       return change;
16007     }
16008   else
16009     /* We are not optimizing for the $gp register.  */
16010     return 1;
16011 }
16012
16013
16014 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
16015
16016 static bfd_boolean
16017 pic_need_relax (symbolS *sym, asection *segtype)
16018 {
16019   asection *symsec;
16020
16021   /* Handle the case of a symbol equated to another symbol.  */
16022   while (symbol_equated_reloc_p (sym))
16023     {
16024       symbolS *n;
16025
16026       /* It's possible to get a loop here in a badly written program.  */
16027       n = symbol_get_value_expression (sym)->X_add_symbol;
16028       if (n == sym)
16029         break;
16030       sym = n;
16031     }
16032
16033   if (symbol_section_p (sym))
16034     return TRUE;
16035
16036   symsec = S_GET_SEGMENT (sym);
16037
16038   /* This must duplicate the test in adjust_reloc_syms.  */
16039   return (!bfd_is_und_section (symsec)
16040           && !bfd_is_abs_section (symsec)
16041           && !bfd_is_com_section (symsec)
16042           && !s_is_linkonce (sym, segtype)
16043           /* A global or weak symbol is treated as external.  */
16044           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
16045 }
16046
16047
16048 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
16049    extended opcode.  SEC is the section the frag is in.  */
16050
16051 static int
16052 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
16053 {
16054   int type;
16055   const struct mips_int_operand *operand;
16056   offsetT val;
16057   segT symsec;
16058   fragS *sym_frag;
16059
16060   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16061     return 0;
16062   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16063     return 1;
16064
16065   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16066   operand = mips16_immed_operand (type, FALSE);
16067
16068   sym_frag = symbol_get_frag (fragp->fr_symbol);
16069   val = S_GET_VALUE (fragp->fr_symbol);
16070   symsec = S_GET_SEGMENT (fragp->fr_symbol);
16071
16072   if (operand->root.type == OP_PCREL)
16073     {
16074       const struct mips_pcrel_operand *pcrel_op;
16075       addressT addr;
16076       offsetT maxtiny;
16077
16078       /* We won't have the section when we are called from
16079          mips_relax_frag.  However, we will always have been called
16080          from md_estimate_size_before_relax first.  If this is a
16081          branch to a different section, we mark it as such.  If SEC is
16082          NULL, and the frag is not marked, then it must be a branch to
16083          the same section.  */
16084       pcrel_op = (const struct mips_pcrel_operand *) operand;
16085       if (sec == NULL)
16086         {
16087           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16088             return 1;
16089         }
16090       else
16091         {
16092           /* Must have been called from md_estimate_size_before_relax.  */
16093           if (symsec != sec)
16094             {
16095               fragp->fr_subtype =
16096                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16097
16098               /* FIXME: We should support this, and let the linker
16099                  catch branches and loads that are out of range.  */
16100               as_bad_where (fragp->fr_file, fragp->fr_line,
16101                             _("unsupported PC relative reference to different section"));
16102
16103               return 1;
16104             }
16105           if (fragp != sym_frag && sym_frag->fr_address == 0)
16106             /* Assume non-extended on the first relaxation pass.
16107                The address we have calculated will be bogus if this is
16108                a forward branch to another frag, as the forward frag
16109                will have fr_address == 0.  */
16110             return 0;
16111         }
16112
16113       /* In this case, we know for sure that the symbol fragment is in
16114          the same section.  If the relax_marker of the symbol fragment
16115          differs from the relax_marker of this fragment, we have not
16116          yet adjusted the symbol fragment fr_address.  We want to add
16117          in STRETCH in order to get a better estimate of the address.
16118          This particularly matters because of the shift bits.  */
16119       if (stretch != 0
16120           && sym_frag->relax_marker != fragp->relax_marker)
16121         {
16122           fragS *f;
16123
16124           /* Adjust stretch for any alignment frag.  Note that if have
16125              been expanding the earlier code, the symbol may be
16126              defined in what appears to be an earlier frag.  FIXME:
16127              This doesn't handle the fr_subtype field, which specifies
16128              a maximum number of bytes to skip when doing an
16129              alignment.  */
16130           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16131             {
16132               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16133                 {
16134                   if (stretch < 0)
16135                     stretch = - ((- stretch)
16136                                  & ~ ((1 << (int) f->fr_offset) - 1));
16137                   else
16138                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16139                   if (stretch == 0)
16140                     break;
16141                 }
16142             }
16143           if (f != NULL)
16144             val += stretch;
16145         }
16146
16147       addr = fragp->fr_address + fragp->fr_fix;
16148
16149       /* The base address rules are complicated.  The base address of
16150          a branch is the following instruction.  The base address of a
16151          PC relative load or add is the instruction itself, but if it
16152          is in a delay slot (in which case it can not be extended) use
16153          the address of the instruction whose delay slot it is in.  */
16154       if (pcrel_op->include_isa_bit)
16155         {
16156           addr += 2;
16157
16158           /* If we are currently assuming that this frag should be
16159              extended, then, the current address is two bytes
16160              higher.  */
16161           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16162             addr += 2;
16163
16164           /* Ignore the low bit in the target, since it will be set
16165              for a text label.  */
16166           val &= -2;
16167         }
16168       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16169         addr -= 4;
16170       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16171         addr -= 2;
16172
16173       val -= addr & -(1 << pcrel_op->align_log2);
16174
16175       /* If any of the shifted bits are set, we must use an extended
16176          opcode.  If the address depends on the size of this
16177          instruction, this can lead to a loop, so we arrange to always
16178          use an extended opcode.  We only check this when we are in
16179          the main relaxation loop, when SEC is NULL.  */
16180       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16181         {
16182           fragp->fr_subtype =
16183             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16184           return 1;
16185         }
16186
16187       /* If we are about to mark a frag as extended because the value
16188          is precisely the next value above maxtiny, then there is a
16189          chance of an infinite loop as in the following code:
16190              la $4,foo
16191              .skip      1020
16192              .align     2
16193            foo:
16194          In this case when the la is extended, foo is 0x3fc bytes
16195          away, so the la can be shrunk, but then foo is 0x400 away, so
16196          the la must be extended.  To avoid this loop, we mark the
16197          frag as extended if it was small, and is about to become
16198          extended with the next value above maxtiny.  */
16199       maxtiny = mips_int_operand_max (operand);
16200       if (val == maxtiny + (1 << operand->shift)
16201           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16202           && sec == NULL)
16203         {
16204           fragp->fr_subtype =
16205             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16206           return 1;
16207         }
16208     }
16209   else if (symsec != absolute_section && sec != NULL)
16210     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16211
16212   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16213 }
16214
16215 /* Compute the length of a branch sequence, and adjust the
16216    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16217    worst-case length is computed, with UPDATE being used to indicate
16218    whether an unconditional (-1), branch-likely (+1) or regular (0)
16219    branch is to be computed.  */
16220 static int
16221 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16222 {
16223   bfd_boolean toofar;
16224   int length;
16225
16226   if (fragp
16227       && S_IS_DEFINED (fragp->fr_symbol)
16228       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16229     {
16230       addressT addr;
16231       offsetT val;
16232
16233       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16234
16235       addr = fragp->fr_address + fragp->fr_fix + 4;
16236
16237       val -= addr;
16238
16239       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16240     }
16241   else if (fragp)
16242     /* If the symbol is not defined or it's in a different segment,
16243        assume the user knows what's going on and emit a short
16244        branch.  */
16245     toofar = FALSE;
16246   else
16247     toofar = TRUE;
16248
16249   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16250     fragp->fr_subtype
16251       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16252                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16253                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16254                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16255                              toofar);
16256
16257   length = 4;
16258   if (toofar)
16259     {
16260       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16261         length += 8;
16262
16263       if (mips_pic != NO_PIC)
16264         {
16265           /* Additional space for PIC loading of target address.  */
16266           length += 8;
16267           if (mips_opts.isa == ISA_MIPS1)
16268             /* Additional space for $at-stabilizing nop.  */
16269             length += 4;
16270         }
16271
16272       /* If branch is conditional.  */
16273       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16274         length += 8;
16275     }
16276
16277   return length;
16278 }
16279
16280 /* Compute the length of a branch sequence, and adjust the
16281    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16282    worst-case length is computed, with UPDATE being used to indicate
16283    whether an unconditional (-1), or regular (0) branch is to be
16284    computed.  */
16285
16286 static int
16287 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16288 {
16289   bfd_boolean toofar;
16290   int length;
16291
16292   if (fragp
16293       && S_IS_DEFINED (fragp->fr_symbol)
16294       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16295     {
16296       addressT addr;
16297       offsetT val;
16298
16299       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16300       /* Ignore the low bit in the target, since it will be set
16301          for a text label.  */
16302       if ((val & 1) != 0)
16303         --val;
16304
16305       addr = fragp->fr_address + fragp->fr_fix + 4;
16306
16307       val -= addr;
16308
16309       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16310     }
16311   else if (fragp)
16312     /* If the symbol is not defined or it's in a different segment,
16313        assume the user knows what's going on and emit a short
16314        branch.  */
16315     toofar = FALSE;
16316   else
16317     toofar = TRUE;
16318
16319   if (fragp && update
16320       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16321     fragp->fr_subtype = (toofar
16322                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16323                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16324
16325   length = 4;
16326   if (toofar)
16327     {
16328       bfd_boolean compact_known = fragp != NULL;
16329       bfd_boolean compact = FALSE;
16330       bfd_boolean uncond;
16331
16332       if (compact_known)
16333         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16334       if (fragp)
16335         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16336       else
16337         uncond = update < 0;
16338
16339       /* If label is out of range, we turn branch <br>:
16340
16341                 <br>    label                   # 4 bytes
16342             0:
16343
16344          into:
16345
16346                 j       label                   # 4 bytes
16347                 nop                             # 2 bytes if compact && !PIC
16348             0:
16349        */
16350       if (mips_pic == NO_PIC && (!compact_known || compact))
16351         length += 2;
16352
16353       /* If assembling PIC code, we further turn:
16354
16355                         j       label                   # 4 bytes
16356
16357          into:
16358
16359                         lw/ld   at, %got(label)(gp)     # 4 bytes
16360                         d/addiu at, %lo(label)          # 4 bytes
16361                         jr/c    at                      # 2 bytes
16362        */
16363       if (mips_pic != NO_PIC)
16364         length += 6;
16365
16366       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16367
16368                         <brneg> 0f                      # 4 bytes
16369                         nop                             # 2 bytes if !compact
16370        */
16371       if (!uncond)
16372         length += (compact_known && compact) ? 4 : 6;
16373     }
16374
16375   return length;
16376 }
16377
16378 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16379    bit accordingly.  */
16380
16381 static int
16382 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16383 {
16384   bfd_boolean toofar;
16385
16386   if (fragp
16387       && S_IS_DEFINED (fragp->fr_symbol)
16388       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16389     {
16390       addressT addr;
16391       offsetT val;
16392       int type;
16393
16394       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16395       /* Ignore the low bit in the target, since it will be set
16396          for a text label.  */
16397       if ((val & 1) != 0)
16398         --val;
16399
16400       /* Assume this is a 2-byte branch.  */
16401       addr = fragp->fr_address + fragp->fr_fix + 2;
16402
16403       /* We try to avoid the infinite loop by not adding 2 more bytes for
16404          long branches.  */
16405
16406       val -= addr;
16407
16408       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16409       if (type == 'D')
16410         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16411       else if (type == 'E')
16412         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16413       else
16414         abort ();
16415     }
16416   else
16417     /* If the symbol is not defined or it's in a different segment,
16418        we emit a normal 32-bit branch.  */
16419     toofar = TRUE;
16420
16421   if (fragp && update
16422       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16423     fragp->fr_subtype
16424       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16425                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16426
16427   if (toofar)
16428     return 4;
16429
16430   return 2;
16431 }
16432
16433 /* Estimate the size of a frag before relaxing.  Unless this is the
16434    mips16, we are not really relaxing here, and the final size is
16435    encoded in the subtype information.  For the mips16, we have to
16436    decide whether we are using an extended opcode or not.  */
16437
16438 int
16439 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16440 {
16441   int change;
16442
16443   if (RELAX_BRANCH_P (fragp->fr_subtype))
16444     {
16445
16446       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16447
16448       return fragp->fr_var;
16449     }
16450
16451   if (RELAX_MIPS16_P (fragp->fr_subtype))
16452     /* We don't want to modify the EXTENDED bit here; it might get us
16453        into infinite loops.  We change it only in mips_relax_frag().  */
16454     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16455
16456   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16457     {
16458       int length = 4;
16459
16460       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16461         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16462       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16463         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16464       fragp->fr_var = length;
16465
16466       return length;
16467     }
16468
16469   if (mips_pic == NO_PIC)
16470     change = nopic_need_relax (fragp->fr_symbol, 0);
16471   else if (mips_pic == SVR4_PIC)
16472     change = pic_need_relax (fragp->fr_symbol, segtype);
16473   else if (mips_pic == VXWORKS_PIC)
16474     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16475     change = 0;
16476   else
16477     abort ();
16478
16479   if (change)
16480     {
16481       fragp->fr_subtype |= RELAX_USE_SECOND;
16482       return -RELAX_FIRST (fragp->fr_subtype);
16483     }
16484   else
16485     return -RELAX_SECOND (fragp->fr_subtype);
16486 }
16487
16488 /* This is called to see whether a reloc against a defined symbol
16489    should be converted into a reloc against a section.  */
16490
16491 int
16492 mips_fix_adjustable (fixS *fixp)
16493 {
16494   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16495       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16496     return 0;
16497
16498   if (fixp->fx_addsy == NULL)
16499     return 1;
16500
16501   /* If symbol SYM is in a mergeable section, relocations of the form
16502      SYM + 0 can usually be made section-relative.  The mergeable data
16503      is then identified by the section offset rather than by the symbol.
16504
16505      However, if we're generating REL LO16 relocations, the offset is split
16506      between the LO16 and parterning high part relocation.  The linker will
16507      need to recalculate the complete offset in order to correctly identify
16508      the merge data.
16509
16510      The linker has traditionally not looked for the parterning high part
16511      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16512      placed anywhere.  Rather than break backwards compatibility by changing
16513      this, it seems better not to force the issue, and instead keep the
16514      original symbol.  This will work with either linker behavior.  */
16515   if ((lo16_reloc_p (fixp->fx_r_type)
16516        || reloc_needs_lo_p (fixp->fx_r_type))
16517       && HAVE_IN_PLACE_ADDENDS
16518       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16519     return 0;
16520
16521   /* There is no place to store an in-place offset for JALR relocations.
16522      Likewise an in-range offset of limited PC-relative relocations may
16523      overflow the in-place relocatable field if recalculated against the
16524      start address of the symbol's containing section.  */
16525   if (HAVE_IN_PLACE_ADDENDS
16526       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16527           || jalr_reloc_p (fixp->fx_r_type)))
16528     return 0;
16529
16530   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16531      to a floating-point stub.  The same is true for non-R_MIPS16_26
16532      relocations against MIPS16 functions; in this case, the stub becomes
16533      the function's canonical address.
16534
16535      Floating-point stubs are stored in unique .mips16.call.* or
16536      .mips16.fn.* sections.  If a stub T for function F is in section S,
16537      the first relocation in section S must be against F; this is how the
16538      linker determines the target function.  All relocations that might
16539      resolve to T must also be against F.  We therefore have the following
16540      restrictions, which are given in an intentionally-redundant way:
16541
16542        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16543           symbols.
16544
16545        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16546           if that stub might be used.
16547
16548        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16549           symbols.
16550
16551        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16552           that stub might be used.
16553
16554      There is a further restriction:
16555
16556        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16557           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16558           targets with in-place addends; the relocation field cannot
16559           encode the low bit.
16560
16561      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16562      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16563      such relocations on REL targets.
16564
16565      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16566      relocation against some symbol R, no relocation against R may be
16567      reduced.  (Note that this deals with (2) as well as (1) because
16568      relocations against global symbols will never be reduced on ELF
16569      targets.)  This approach is a little simpler than trying to detect
16570      stub sections, and gives the "all or nothing" per-symbol consistency
16571      that we have for MIPS16 symbols.  */
16572   if (fixp->fx_subsy == NULL
16573       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16574           || *symbol_get_tc (fixp->fx_addsy)
16575           || (HAVE_IN_PLACE_ADDENDS
16576               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16577               && jmp_reloc_p (fixp->fx_r_type))))
16578     return 0;
16579
16580   return 1;
16581 }
16582
16583 /* Translate internal representation of relocation info to BFD target
16584    format.  */
16585
16586 arelent **
16587 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16588 {
16589   static arelent *retval[4];
16590   arelent *reloc;
16591   bfd_reloc_code_real_type code;
16592
16593   memset (retval, 0, sizeof(retval));
16594   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16595   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16596   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16597   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16598
16599   if (fixp->fx_pcrel)
16600     {
16601       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16602                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16603                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16604                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16605                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16606
16607       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16608          Relocations want only the symbol offset.  */
16609       reloc->addend = fixp->fx_addnumber + reloc->address;
16610     }
16611   else
16612     reloc->addend = fixp->fx_addnumber;
16613
16614   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16615      entry to be used in the relocation's section offset.  */
16616   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16617     {
16618       reloc->address = reloc->addend;
16619       reloc->addend = 0;
16620     }
16621
16622   code = fixp->fx_r_type;
16623
16624   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16625   if (reloc->howto == NULL)
16626     {
16627       as_bad_where (fixp->fx_file, fixp->fx_line,
16628                     _("cannot represent %s relocation in this object file"
16629                       " format"),
16630                     bfd_get_reloc_code_name (code));
16631       retval[0] = NULL;
16632     }
16633
16634   return retval;
16635 }
16636
16637 /* Relax a machine dependent frag.  This returns the amount by which
16638    the current size of the frag should change.  */
16639
16640 int
16641 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16642 {
16643   if (RELAX_BRANCH_P (fragp->fr_subtype))
16644     {
16645       offsetT old_var = fragp->fr_var;
16646
16647       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16648
16649       return fragp->fr_var - old_var;
16650     }
16651
16652   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16653     {
16654       offsetT old_var = fragp->fr_var;
16655       offsetT new_var = 4;
16656
16657       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16658         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16659       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16660         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16661       fragp->fr_var = new_var;
16662
16663       return new_var - old_var;
16664     }
16665
16666   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16667     return 0;
16668
16669   if (mips16_extended_frag (fragp, NULL, stretch))
16670     {
16671       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16672         return 0;
16673       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16674       return 2;
16675     }
16676   else
16677     {
16678       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16679         return 0;
16680       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16681       return -2;
16682     }
16683
16684   return 0;
16685 }
16686
16687 /* Convert a machine dependent frag.  */
16688
16689 void
16690 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16691 {
16692   if (RELAX_BRANCH_P (fragp->fr_subtype))
16693     {
16694       char *buf;
16695       unsigned long insn;
16696       expressionS exp;
16697       fixS *fixp;
16698
16699       buf = fragp->fr_literal + fragp->fr_fix;
16700       insn = read_insn (buf);
16701
16702       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16703         {
16704           /* We generate a fixup instead of applying it right now
16705              because, if there are linker relaxations, we're going to
16706              need the relocations.  */
16707           exp.X_op = O_symbol;
16708           exp.X_add_symbol = fragp->fr_symbol;
16709           exp.X_add_number = fragp->fr_offset;
16710
16711           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16712                               BFD_RELOC_16_PCREL_S2);
16713           fixp->fx_file = fragp->fr_file;
16714           fixp->fx_line = fragp->fr_line;
16715
16716           buf = write_insn (buf, insn);
16717         }
16718       else
16719         {
16720           int i;
16721
16722           as_warn_where (fragp->fr_file, fragp->fr_line,
16723                          _("relaxed out-of-range branch into a jump"));
16724
16725           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16726             goto uncond;
16727
16728           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16729             {
16730               /* Reverse the branch.  */
16731               switch ((insn >> 28) & 0xf)
16732                 {
16733                 case 4:
16734                   if ((insn & 0xff000000) == 0x47000000
16735                       || (insn & 0xff600000) == 0x45600000)
16736                     {
16737                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
16738                          reversed by tweaking bit 23.  */
16739                       insn ^= 0x00800000;
16740                     }
16741                   else
16742                     {
16743                       /* bc[0-3][tf]l? instructions can have the condition
16744                          reversed by tweaking a single TF bit, and their
16745                          opcodes all have 0x4???????.  */
16746                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
16747                       insn ^= 0x00010000;
16748                     }
16749                   break;
16750
16751                 case 0:
16752                   /* bltz       0x04000000      bgez    0x04010000
16753                      bltzal     0x04100000      bgezal  0x04110000  */
16754                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16755                   insn ^= 0x00010000;
16756                   break;
16757
16758                 case 1:
16759                   /* beq        0x10000000      bne     0x14000000
16760                      blez       0x18000000      bgtz    0x1c000000  */
16761                   insn ^= 0x04000000;
16762                   break;
16763
16764                 default:
16765                   abort ();
16766                 }
16767             }
16768
16769           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16770             {
16771               /* Clear the and-link bit.  */
16772               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16773
16774               /* bltzal         0x04100000      bgezal  0x04110000
16775                  bltzall        0x04120000      bgezall 0x04130000  */
16776               insn &= ~0x00100000;
16777             }
16778
16779           /* Branch over the branch (if the branch was likely) or the
16780              full jump (not likely case).  Compute the offset from the
16781              current instruction to branch to.  */
16782           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16783             i = 16;
16784           else
16785             {
16786               /* How many bytes in instructions we've already emitted?  */
16787               i = buf - fragp->fr_literal - fragp->fr_fix;
16788               /* How many bytes in instructions from here to the end?  */
16789               i = fragp->fr_var - i;
16790             }
16791           /* Convert to instruction count.  */
16792           i >>= 2;
16793           /* Branch counts from the next instruction.  */
16794           i--;
16795           insn |= i;
16796           /* Branch over the jump.  */
16797           buf = write_insn (buf, insn);
16798
16799           /* nop */
16800           buf = write_insn (buf, 0);
16801
16802           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16803             {
16804               /* beql $0, $0, 2f */
16805               insn = 0x50000000;
16806               /* Compute the PC offset from the current instruction to
16807                  the end of the variable frag.  */
16808               /* How many bytes in instructions we've already emitted?  */
16809               i = buf - fragp->fr_literal - fragp->fr_fix;
16810               /* How many bytes in instructions from here to the end?  */
16811               i = fragp->fr_var - i;
16812               /* Convert to instruction count.  */
16813               i >>= 2;
16814               /* Don't decrement i, because we want to branch over the
16815                  delay slot.  */
16816               insn |= i;
16817
16818               buf = write_insn (buf, insn);
16819               buf = write_insn (buf, 0);
16820             }
16821
16822         uncond:
16823           if (mips_pic == NO_PIC)
16824             {
16825               /* j or jal.  */
16826               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16827                       ? 0x0c000000 : 0x08000000);
16828               exp.X_op = O_symbol;
16829               exp.X_add_symbol = fragp->fr_symbol;
16830               exp.X_add_number = fragp->fr_offset;
16831
16832               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16833                                   FALSE, BFD_RELOC_MIPS_JMP);
16834               fixp->fx_file = fragp->fr_file;
16835               fixp->fx_line = fragp->fr_line;
16836
16837               buf = write_insn (buf, insn);
16838             }
16839           else
16840             {
16841               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16842
16843               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16844               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16845               insn |= at << OP_SH_RT;
16846               exp.X_op = O_symbol;
16847               exp.X_add_symbol = fragp->fr_symbol;
16848               exp.X_add_number = fragp->fr_offset;
16849
16850               if (fragp->fr_offset)
16851                 {
16852                   exp.X_add_symbol = make_expr_symbol (&exp);
16853                   exp.X_add_number = 0;
16854                 }
16855
16856               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16857                                   FALSE, BFD_RELOC_MIPS_GOT16);
16858               fixp->fx_file = fragp->fr_file;
16859               fixp->fx_line = fragp->fr_line;
16860
16861               buf = write_insn (buf, insn);
16862
16863               if (mips_opts.isa == ISA_MIPS1)
16864                 /* nop */
16865                 buf = write_insn (buf, 0);
16866
16867               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16868               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16869               insn |= at << OP_SH_RS | at << OP_SH_RT;
16870
16871               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16872                                   FALSE, BFD_RELOC_LO16);
16873               fixp->fx_file = fragp->fr_file;
16874               fixp->fx_line = fragp->fr_line;
16875
16876               buf = write_insn (buf, insn);
16877
16878               /* j(al)r $at.  */
16879               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16880                 insn = 0x0000f809;
16881               else
16882                 insn = 0x00000008;
16883               insn |= at << OP_SH_RS;
16884
16885               buf = write_insn (buf, insn);
16886             }
16887         }
16888
16889       fragp->fr_fix += fragp->fr_var;
16890       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16891       return;
16892     }
16893
16894   /* Relax microMIPS branches.  */
16895   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16896     {
16897       char *buf = fragp->fr_literal + fragp->fr_fix;
16898       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16899       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16900       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16901       bfd_boolean short_ds;
16902       unsigned long insn;
16903       expressionS exp;
16904       fixS *fixp;
16905
16906       exp.X_op = O_symbol;
16907       exp.X_add_symbol = fragp->fr_symbol;
16908       exp.X_add_number = fragp->fr_offset;
16909
16910       fragp->fr_fix += fragp->fr_var;
16911
16912       /* Handle 16-bit branches that fit or are forced to fit.  */
16913       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16914         {
16915           /* We generate a fixup instead of applying it right now,
16916              because if there is linker relaxation, we're going to
16917              need the relocations.  */
16918           if (type == 'D')
16919             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16920                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16921           else if (type == 'E')
16922             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16923                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16924           else
16925             abort ();
16926
16927           fixp->fx_file = fragp->fr_file;
16928           fixp->fx_line = fragp->fr_line;
16929
16930           /* These relocations can have an addend that won't fit in
16931              2 octets.  */
16932           fixp->fx_no_overflow = 1;
16933
16934           return;
16935         }
16936
16937       /* Handle 32-bit branches that fit or are forced to fit.  */
16938       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16939           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16940         {
16941           /* We generate a fixup instead of applying it right now,
16942              because if there is linker relaxation, we're going to
16943              need the relocations.  */
16944           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16945                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16946           fixp->fx_file = fragp->fr_file;
16947           fixp->fx_line = fragp->fr_line;
16948
16949           if (type == 0)
16950             return;
16951         }
16952
16953       /* Relax 16-bit branches to 32-bit branches.  */
16954       if (type != 0)
16955         {
16956           insn = read_compressed_insn (buf, 2);
16957
16958           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16959             insn = 0x94000000;                          /* beq  */
16960           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16961             {
16962               unsigned long regno;
16963
16964               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16965               regno = micromips_to_32_reg_d_map [regno];
16966               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16967               insn |= regno << MICROMIPSOP_SH_RS;
16968             }
16969           else
16970             abort ();
16971
16972           /* Nothing else to do, just write it out.  */
16973           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16974               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16975             {
16976               buf = write_compressed_insn (buf, insn, 4);
16977               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16978               return;
16979             }
16980         }
16981       else
16982         insn = read_compressed_insn (buf, 4);
16983
16984       /* Relax 32-bit branches to a sequence of instructions.  */
16985       as_warn_where (fragp->fr_file, fragp->fr_line,
16986                      _("relaxed out-of-range branch into a jump"));
16987
16988       /* Set the short-delay-slot bit.  */
16989       short_ds = al && (insn & 0x02000000) != 0;
16990
16991       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16992         {
16993           symbolS *l;
16994
16995           /* Reverse the branch.  */
16996           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16997               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16998             insn ^= 0x20000000;
16999           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
17000                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
17001                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
17002                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
17003                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
17004                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
17005                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
17006                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
17007                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
17008                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
17009             insn ^= 0x00400000;
17010           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
17011                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
17012                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
17013                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
17014             insn ^= 0x00200000;
17015           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
17016                                                                    BNZ.df  */
17017                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
17018                                                                    BNZ.V */
17019             insn ^= 0x00800000;
17020           else
17021             abort ();
17022
17023           if (al)
17024             {
17025               /* Clear the and-link and short-delay-slot bits.  */
17026               gas_assert ((insn & 0xfda00000) == 0x40200000);
17027
17028               /* bltzal  0x40200000     bgezal  0x40600000  */
17029               /* bltzals 0x42200000     bgezals 0x42600000  */
17030               insn &= ~0x02200000;
17031             }
17032
17033           /* Make a label at the end for use with the branch.  */
17034           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
17035           micromips_label_inc ();
17036           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
17037
17038           /* Refer to it.  */
17039           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
17040                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
17041           fixp->fx_file = fragp->fr_file;
17042           fixp->fx_line = fragp->fr_line;
17043
17044           /* Branch over the jump.  */
17045           buf = write_compressed_insn (buf, insn, 4);
17046           if (!compact)
17047             /* nop */
17048             buf = write_compressed_insn (buf, 0x0c00, 2);
17049         }
17050
17051       if (mips_pic == NO_PIC)
17052         {
17053           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
17054
17055           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
17056           insn = al ? jal : 0xd4000000;
17057
17058           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17059                               BFD_RELOC_MICROMIPS_JMP);
17060           fixp->fx_file = fragp->fr_file;
17061           fixp->fx_line = fragp->fr_line;
17062
17063           buf = write_compressed_insn (buf, insn, 4);
17064           if (compact)
17065             /* nop */
17066             buf = write_compressed_insn (buf, 0x0c00, 2);
17067         }
17068       else
17069         {
17070           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
17071           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
17072           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
17073
17074           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
17075           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
17076           insn |= at << MICROMIPSOP_SH_RT;
17077
17078           if (exp.X_add_number)
17079             {
17080               exp.X_add_symbol = make_expr_symbol (&exp);
17081               exp.X_add_number = 0;
17082             }
17083
17084           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17085                               BFD_RELOC_MICROMIPS_GOT16);
17086           fixp->fx_file = fragp->fr_file;
17087           fixp->fx_line = fragp->fr_line;
17088
17089           buf = write_compressed_insn (buf, insn, 4);
17090
17091           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
17092           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
17093           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
17094
17095           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17096                               BFD_RELOC_MICROMIPS_LO16);
17097           fixp->fx_file = fragp->fr_file;
17098           fixp->fx_line = fragp->fr_line;
17099
17100           buf = write_compressed_insn (buf, insn, 4);
17101
17102           /* jr/jrc/jalr/jalrs $at  */
17103           insn = al ? jalr : jr;
17104           insn |= at << MICROMIPSOP_SH_MJ;
17105
17106           buf = write_compressed_insn (buf, insn, 2);
17107         }
17108
17109       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17110       return;
17111     }
17112
17113   if (RELAX_MIPS16_P (fragp->fr_subtype))
17114     {
17115       int type;
17116       const struct mips_int_operand *operand;
17117       offsetT val;
17118       char *buf;
17119       unsigned int user_length, length;
17120       unsigned long insn;
17121       bfd_boolean ext;
17122
17123       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17124       operand = mips16_immed_operand (type, FALSE);
17125
17126       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
17127       val = resolve_symbol_value (fragp->fr_symbol);
17128       if (operand->root.type == OP_PCREL)
17129         {
17130           const struct mips_pcrel_operand *pcrel_op;
17131           addressT addr;
17132
17133           pcrel_op = (const struct mips_pcrel_operand *) operand;
17134           addr = fragp->fr_address + fragp->fr_fix;
17135
17136           /* The rules for the base address of a PC relative reloc are
17137              complicated; see mips16_extended_frag.  */
17138           if (pcrel_op->include_isa_bit)
17139             {
17140               addr += 2;
17141               if (ext)
17142                 addr += 2;
17143               /* Ignore the low bit in the target, since it will be
17144                  set for a text label.  */
17145               val &= -2;
17146             }
17147           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17148             addr -= 4;
17149           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17150             addr -= 2;
17151
17152           addr &= -(1 << pcrel_op->align_log2);
17153           val -= addr;
17154
17155           /* Make sure the section winds up with the alignment we have
17156              assumed.  */
17157           if (operand->shift > 0)
17158             record_alignment (asec, operand->shift);
17159         }
17160
17161       if (ext
17162           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17163               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17164         as_warn_where (fragp->fr_file, fragp->fr_line,
17165                        _("extended instruction in delay slot"));
17166
17167       buf = fragp->fr_literal + fragp->fr_fix;
17168
17169       insn = read_compressed_insn (buf, 2);
17170       if (ext)
17171         insn |= MIPS16_EXTEND;
17172
17173       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17174         user_length = 4;
17175       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17176         user_length = 2;
17177       else
17178         user_length = 0;
17179
17180       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17181                     BFD_RELOC_UNUSED, val, user_length, &insn);
17182
17183       length = (ext ? 4 : 2);
17184       gas_assert (mips16_opcode_length (insn) == length);
17185       write_compressed_insn (buf, insn, length);
17186       fragp->fr_fix += length;
17187     }
17188   else
17189     {
17190       relax_substateT subtype = fragp->fr_subtype;
17191       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17192       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17193       int first, second;
17194       fixS *fixp;
17195
17196       first = RELAX_FIRST (subtype);
17197       second = RELAX_SECOND (subtype);
17198       fixp = (fixS *) fragp->fr_opcode;
17199
17200       /* If the delay slot chosen does not match the size of the instruction,
17201          then emit a warning.  */
17202       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17203            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17204         {
17205           relax_substateT s;
17206           const char *msg;
17207
17208           s = subtype & (RELAX_DELAY_SLOT_16BIT
17209                          | RELAX_DELAY_SLOT_SIZE_FIRST
17210                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17211           msg = macro_warning (s);
17212           if (msg != NULL)
17213             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17214           subtype &= ~s;
17215         }
17216
17217       /* Possibly emit a warning if we've chosen the longer option.  */
17218       if (use_second == second_longer)
17219         {
17220           relax_substateT s;
17221           const char *msg;
17222
17223           s = (subtype
17224                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17225           msg = macro_warning (s);
17226           if (msg != NULL)
17227             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17228           subtype &= ~s;
17229         }
17230
17231       /* Go through all the fixups for the first sequence.  Disable them
17232          (by marking them as done) if we're going to use the second
17233          sequence instead.  */
17234       while (fixp
17235              && fixp->fx_frag == fragp
17236              && fixp->fx_where < fragp->fr_fix - second)
17237         {
17238           if (subtype & RELAX_USE_SECOND)
17239             fixp->fx_done = 1;
17240           fixp = fixp->fx_next;
17241         }
17242
17243       /* Go through the fixups for the second sequence.  Disable them if
17244          we're going to use the first sequence, otherwise adjust their
17245          addresses to account for the relaxation.  */
17246       while (fixp && fixp->fx_frag == fragp)
17247         {
17248           if (subtype & RELAX_USE_SECOND)
17249             fixp->fx_where -= first;
17250           else
17251             fixp->fx_done = 1;
17252           fixp = fixp->fx_next;
17253         }
17254
17255       /* Now modify the frag contents.  */
17256       if (subtype & RELAX_USE_SECOND)
17257         {
17258           char *start;
17259
17260           start = fragp->fr_literal + fragp->fr_fix - first - second;
17261           memmove (start, start + first, second);
17262           fragp->fr_fix -= first;
17263         }
17264       else
17265         fragp->fr_fix -= second;
17266     }
17267 }
17268
17269 /* This function is called after the relocs have been generated.
17270    We've been storing mips16 text labels as odd.  Here we convert them
17271    back to even for the convenience of the debugger.  */
17272
17273 void
17274 mips_frob_file_after_relocs (void)
17275 {
17276   asymbol **syms;
17277   unsigned int count, i;
17278
17279   syms = bfd_get_outsymbols (stdoutput);
17280   count = bfd_get_symcount (stdoutput);
17281   for (i = 0; i < count; i++, syms++)
17282     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17283         && ((*syms)->value & 1) != 0)
17284       {
17285         (*syms)->value &= ~1;
17286         /* If the symbol has an odd size, it was probably computed
17287            incorrectly, so adjust that as well.  */
17288         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17289           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17290       }
17291 }
17292
17293 /* This function is called whenever a label is defined, including fake
17294    labels instantiated off the dot special symbol.  It is used when
17295    handling branch delays; if a branch has a label, we assume we cannot
17296    move it.  This also bumps the value of the symbol by 1 in compressed
17297    code.  */
17298
17299 static void
17300 mips_record_label (symbolS *sym)
17301 {
17302   segment_info_type *si = seg_info (now_seg);
17303   struct insn_label_list *l;
17304
17305   if (free_insn_labels == NULL)
17306     l = (struct insn_label_list *) xmalloc (sizeof *l);
17307   else
17308     {
17309       l = free_insn_labels;
17310       free_insn_labels = l->next;
17311     }
17312
17313   l->label = sym;
17314   l->next = si->label_list;
17315   si->label_list = l;
17316 }
17317
17318 /* This function is called as tc_frob_label() whenever a label is defined
17319    and adds a DWARF-2 record we only want for true labels.  */
17320
17321 void
17322 mips_define_label (symbolS *sym)
17323 {
17324   mips_record_label (sym);
17325   dwarf2_emit_label (sym);
17326 }
17327
17328 /* This function is called by tc_new_dot_label whenever a new dot symbol
17329    is defined.  */
17330
17331 void
17332 mips_add_dot_label (symbolS *sym)
17333 {
17334   mips_record_label (sym);
17335   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17336     mips_compressed_mark_label (sym);
17337 }
17338 \f
17339 /* Some special processing for a MIPS ELF file.  */
17340
17341 void
17342 mips_elf_final_processing (void)
17343 {
17344   /* Write out the register information.  */
17345   if (mips_abi != N64_ABI)
17346     {
17347       Elf32_RegInfo s;
17348
17349       s.ri_gprmask = mips_gprmask;
17350       s.ri_cprmask[0] = mips_cprmask[0];
17351       s.ri_cprmask[1] = mips_cprmask[1];
17352       s.ri_cprmask[2] = mips_cprmask[2];
17353       s.ri_cprmask[3] = mips_cprmask[3];
17354       /* The gp_value field is set by the MIPS ELF backend.  */
17355
17356       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17357                                        ((Elf32_External_RegInfo *)
17358                                         mips_regmask_frag));
17359     }
17360   else
17361     {
17362       Elf64_Internal_RegInfo s;
17363
17364       s.ri_gprmask = mips_gprmask;
17365       s.ri_pad = 0;
17366       s.ri_cprmask[0] = mips_cprmask[0];
17367       s.ri_cprmask[1] = mips_cprmask[1];
17368       s.ri_cprmask[2] = mips_cprmask[2];
17369       s.ri_cprmask[3] = mips_cprmask[3];
17370       /* The gp_value field is set by the MIPS ELF backend.  */
17371
17372       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17373                                        ((Elf64_External_RegInfo *)
17374                                         mips_regmask_frag));
17375     }
17376
17377   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17378      sort of BFD interface for this.  */
17379   if (mips_any_noreorder)
17380     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17381   if (mips_pic != NO_PIC)
17382     {
17383       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17384       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17385     }
17386   if (mips_abicalls)
17387     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17388
17389   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17390      defined at present; this might need to change in future.  */
17391   if (file_ase_mips16)
17392     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17393   if (file_ase_micromips)
17394     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17395   if (file_ase & ASE_MDMX)
17396     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17397
17398   /* Set the MIPS ELF ABI flags.  */
17399   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17400     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17401   else if (mips_abi == O64_ABI)
17402     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17403   else if (mips_abi == EABI_ABI)
17404     {
17405       if (!file_mips_gp32)
17406         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17407       else
17408         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17409     }
17410   else if (mips_abi == N32_ABI)
17411     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17412
17413   /* Nothing to do for N64_ABI.  */
17414
17415   if (mips_32bitmode)
17416     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17417
17418   if (mips_flag_nan2008)
17419     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17420
17421   /* 32 bit code with 64 bit FP registers.  */
17422   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
17423     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
17424 }
17425 \f
17426 typedef struct proc {
17427   symbolS *func_sym;
17428   symbolS *func_end_sym;
17429   unsigned long reg_mask;
17430   unsigned long reg_offset;
17431   unsigned long fpreg_mask;
17432   unsigned long fpreg_offset;
17433   unsigned long frame_offset;
17434   unsigned long frame_reg;
17435   unsigned long pc_reg;
17436 } procS;
17437
17438 static procS cur_proc;
17439 static procS *cur_proc_ptr;
17440 static int numprocs;
17441
17442 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17443    as "2", and a normal nop as "0".  */
17444
17445 #define NOP_OPCODE_MIPS         0
17446 #define NOP_OPCODE_MIPS16       1
17447 #define NOP_OPCODE_MICROMIPS    2
17448
17449 char
17450 mips_nop_opcode (void)
17451 {
17452   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17453     return NOP_OPCODE_MICROMIPS;
17454   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17455     return NOP_OPCODE_MIPS16;
17456   else
17457     return NOP_OPCODE_MIPS;
17458 }
17459
17460 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17461    32-bit microMIPS NOPs here (if applicable).  */
17462
17463 void
17464 mips_handle_align (fragS *fragp)
17465 {
17466   char nop_opcode;
17467   char *p;
17468   int bytes, size, excess;
17469   valueT opcode;
17470
17471   if (fragp->fr_type != rs_align_code)
17472     return;
17473
17474   p = fragp->fr_literal + fragp->fr_fix;
17475   nop_opcode = *p;
17476   switch (nop_opcode)
17477     {
17478     case NOP_OPCODE_MICROMIPS:
17479       opcode = micromips_nop32_insn.insn_opcode;
17480       size = 4;
17481       break;
17482     case NOP_OPCODE_MIPS16:
17483       opcode = mips16_nop_insn.insn_opcode;
17484       size = 2;
17485       break;
17486     case NOP_OPCODE_MIPS:
17487     default:
17488       opcode = nop_insn.insn_opcode;
17489       size = 4;
17490       break;
17491     }
17492
17493   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17494   excess = bytes % size;
17495
17496   /* Handle the leading part if we're not inserting a whole number of
17497      instructions, and make it the end of the fixed part of the frag.
17498      Try to fit in a short microMIPS NOP if applicable and possible,
17499      and use zeroes otherwise.  */
17500   gas_assert (excess < 4);
17501   fragp->fr_fix += excess;
17502   switch (excess)
17503     {
17504     case 3:
17505       *p++ = '\0';
17506       /* Fall through.  */
17507     case 2:
17508       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17509         {
17510           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17511           break;
17512         }
17513       *p++ = '\0';
17514       /* Fall through.  */
17515     case 1:
17516       *p++ = '\0';
17517       /* Fall through.  */
17518     case 0:
17519       break;
17520     }
17521
17522   md_number_to_chars (p, opcode, size);
17523   fragp->fr_var = size;
17524 }
17525
17526 static void
17527 md_obj_begin (void)
17528 {
17529 }
17530
17531 static void
17532 md_obj_end (void)
17533 {
17534   /* Check for premature end, nesting errors, etc.  */
17535   if (cur_proc_ptr)
17536     as_warn (_("missing .end at end of assembly"));
17537 }
17538
17539 static long
17540 get_number (void)
17541 {
17542   int negative = 0;
17543   long val = 0;
17544
17545   if (*input_line_pointer == '-')
17546     {
17547       ++input_line_pointer;
17548       negative = 1;
17549     }
17550   if (!ISDIGIT (*input_line_pointer))
17551     as_bad (_("expected simple number"));
17552   if (input_line_pointer[0] == '0')
17553     {
17554       if (input_line_pointer[1] == 'x')
17555         {
17556           input_line_pointer += 2;
17557           while (ISXDIGIT (*input_line_pointer))
17558             {
17559               val <<= 4;
17560               val |= hex_value (*input_line_pointer++);
17561             }
17562           return negative ? -val : val;
17563         }
17564       else
17565         {
17566           ++input_line_pointer;
17567           while (ISDIGIT (*input_line_pointer))
17568             {
17569               val <<= 3;
17570               val |= *input_line_pointer++ - '0';
17571             }
17572           return negative ? -val : val;
17573         }
17574     }
17575   if (!ISDIGIT (*input_line_pointer))
17576     {
17577       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17578               *input_line_pointer, *input_line_pointer);
17579       as_warn (_("invalid number"));
17580       return -1;
17581     }
17582   while (ISDIGIT (*input_line_pointer))
17583     {
17584       val *= 10;
17585       val += *input_line_pointer++ - '0';
17586     }
17587   return negative ? -val : val;
17588 }
17589
17590 /* The .file directive; just like the usual .file directive, but there
17591    is an initial number which is the ECOFF file index.  In the non-ECOFF
17592    case .file implies DWARF-2.  */
17593
17594 static void
17595 s_mips_file (int x ATTRIBUTE_UNUSED)
17596 {
17597   static int first_file_directive = 0;
17598
17599   if (ECOFF_DEBUGGING)
17600     {
17601       get_number ();
17602       s_app_file (0);
17603     }
17604   else
17605     {
17606       char *filename;
17607
17608       filename = dwarf2_directive_file (0);
17609
17610       /* Versions of GCC up to 3.1 start files with a ".file"
17611          directive even for stabs output.  Make sure that this
17612          ".file" is handled.  Note that you need a version of GCC
17613          after 3.1 in order to support DWARF-2 on MIPS.  */
17614       if (filename != NULL && ! first_file_directive)
17615         {
17616           (void) new_logical_line (filename, -1);
17617           s_app_file_string (filename, 0);
17618         }
17619       first_file_directive = 1;
17620     }
17621 }
17622
17623 /* The .loc directive, implying DWARF-2.  */
17624
17625 static void
17626 s_mips_loc (int x ATTRIBUTE_UNUSED)
17627 {
17628   if (!ECOFF_DEBUGGING)
17629     dwarf2_directive_loc (0);
17630 }
17631
17632 /* The .end directive.  */
17633
17634 static void
17635 s_mips_end (int x ATTRIBUTE_UNUSED)
17636 {
17637   symbolS *p;
17638
17639   /* Following functions need their own .frame and .cprestore directives.  */
17640   mips_frame_reg_valid = 0;
17641   mips_cprestore_valid = 0;
17642
17643   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17644     {
17645       p = get_symbol ();
17646       demand_empty_rest_of_line ();
17647     }
17648   else
17649     p = NULL;
17650
17651   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17652     as_warn (_(".end not in text section"));
17653
17654   if (!cur_proc_ptr)
17655     {
17656       as_warn (_(".end directive without a preceding .ent directive"));
17657       demand_empty_rest_of_line ();
17658       return;
17659     }
17660
17661   if (p != NULL)
17662     {
17663       gas_assert (S_GET_NAME (p));
17664       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17665         as_warn (_(".end symbol does not match .ent symbol"));
17666
17667       if (debug_type == DEBUG_STABS)
17668         stabs_generate_asm_endfunc (S_GET_NAME (p),
17669                                     S_GET_NAME (p));
17670     }
17671   else
17672     as_warn (_(".end directive missing or unknown symbol"));
17673
17674   /* Create an expression to calculate the size of the function.  */
17675   if (p && cur_proc_ptr)
17676     {
17677       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17678       expressionS *exp = xmalloc (sizeof (expressionS));
17679
17680       obj->size = exp;
17681       exp->X_op = O_subtract;
17682       exp->X_add_symbol = symbol_temp_new_now ();
17683       exp->X_op_symbol = p;
17684       exp->X_add_number = 0;
17685
17686       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17687     }
17688
17689   /* Generate a .pdr section.  */
17690   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17691     {
17692       segT saved_seg = now_seg;
17693       subsegT saved_subseg = now_subseg;
17694       expressionS exp;
17695       char *fragp;
17696
17697 #ifdef md_flush_pending_output
17698       md_flush_pending_output ();
17699 #endif
17700
17701       gas_assert (pdr_seg);
17702       subseg_set (pdr_seg, 0);
17703
17704       /* Write the symbol.  */
17705       exp.X_op = O_symbol;
17706       exp.X_add_symbol = p;
17707       exp.X_add_number = 0;
17708       emit_expr (&exp, 4);
17709
17710       fragp = frag_more (7 * 4);
17711
17712       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17713       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17714       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17715       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17716       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17717       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17718       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17719
17720       subseg_set (saved_seg, saved_subseg);
17721     }
17722
17723   cur_proc_ptr = NULL;
17724 }
17725
17726 /* The .aent and .ent directives.  */
17727
17728 static void
17729 s_mips_ent (int aent)
17730 {
17731   symbolS *symbolP;
17732
17733   symbolP = get_symbol ();
17734   if (*input_line_pointer == ',')
17735     ++input_line_pointer;
17736   SKIP_WHITESPACE ();
17737   if (ISDIGIT (*input_line_pointer)
17738       || *input_line_pointer == '-')
17739     get_number ();
17740
17741   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17742     as_warn (_(".ent or .aent not in text section"));
17743
17744   if (!aent && cur_proc_ptr)
17745     as_warn (_("missing .end"));
17746
17747   if (!aent)
17748     {
17749       /* This function needs its own .frame and .cprestore directives.  */
17750       mips_frame_reg_valid = 0;
17751       mips_cprestore_valid = 0;
17752
17753       cur_proc_ptr = &cur_proc;
17754       memset (cur_proc_ptr, '\0', sizeof (procS));
17755
17756       cur_proc_ptr->func_sym = symbolP;
17757
17758       ++numprocs;
17759
17760       if (debug_type == DEBUG_STABS)
17761         stabs_generate_asm_func (S_GET_NAME (symbolP),
17762                                  S_GET_NAME (symbolP));
17763     }
17764
17765   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17766
17767   demand_empty_rest_of_line ();
17768 }
17769
17770 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17771    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17772    s_mips_frame is used so that we can set the PDR information correctly.
17773    We can't use the ecoff routines because they make reference to the ecoff
17774    symbol table (in the mdebug section).  */
17775
17776 static void
17777 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17778 {
17779   if (ECOFF_DEBUGGING)
17780     s_ignore (ignore);
17781   else
17782     {
17783       long val;
17784
17785       if (cur_proc_ptr == (procS *) NULL)
17786         {
17787           as_warn (_(".frame outside of .ent"));
17788           demand_empty_rest_of_line ();
17789           return;
17790         }
17791
17792       cur_proc_ptr->frame_reg = tc_get_register (1);
17793
17794       SKIP_WHITESPACE ();
17795       if (*input_line_pointer++ != ','
17796           || get_absolute_expression_and_terminator (&val) != ',')
17797         {
17798           as_warn (_("bad .frame directive"));
17799           --input_line_pointer;
17800           demand_empty_rest_of_line ();
17801           return;
17802         }
17803
17804       cur_proc_ptr->frame_offset = val;
17805       cur_proc_ptr->pc_reg = tc_get_register (0);
17806
17807       demand_empty_rest_of_line ();
17808     }
17809 }
17810
17811 /* The .fmask and .mask directives. If the mdebug section is present
17812    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17813    embedded targets, s_mips_mask is used so that we can set the PDR
17814    information correctly. We can't use the ecoff routines because they
17815    make reference to the ecoff symbol table (in the mdebug section).  */
17816
17817 static void
17818 s_mips_mask (int reg_type)
17819 {
17820   if (ECOFF_DEBUGGING)
17821     s_ignore (reg_type);
17822   else
17823     {
17824       long mask, off;
17825
17826       if (cur_proc_ptr == (procS *) NULL)
17827         {
17828           as_warn (_(".mask/.fmask outside of .ent"));
17829           demand_empty_rest_of_line ();
17830           return;
17831         }
17832
17833       if (get_absolute_expression_and_terminator (&mask) != ',')
17834         {
17835           as_warn (_("bad .mask/.fmask directive"));
17836           --input_line_pointer;
17837           demand_empty_rest_of_line ();
17838           return;
17839         }
17840
17841       off = get_absolute_expression ();
17842
17843       if (reg_type == 'F')
17844         {
17845           cur_proc_ptr->fpreg_mask = mask;
17846           cur_proc_ptr->fpreg_offset = off;
17847         }
17848       else
17849         {
17850           cur_proc_ptr->reg_mask = mask;
17851           cur_proc_ptr->reg_offset = off;
17852         }
17853
17854       demand_empty_rest_of_line ();
17855     }
17856 }
17857
17858 /* A table describing all the processors gas knows about.  Names are
17859    matched in the order listed.
17860
17861    To ease comparison, please keep this table in the same order as
17862    gcc's mips_cpu_info_table[].  */
17863 static const struct mips_cpu_info mips_cpu_info_table[] =
17864 {
17865   /* Entries for generic ISAs */
17866   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17867   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17868   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17869   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17870   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17871   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17872   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17873   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
17874   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
17875   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17876   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17877   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
17878   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
17879
17880   /* MIPS I */
17881   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17882   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17883   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17884
17885   /* MIPS II */
17886   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17887
17888   /* MIPS III */
17889   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17890   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17891   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17892   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17893   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17894   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17895   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17896   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17897   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17898   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17899   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17900   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17901   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17902   /* ST Microelectronics Loongson 2E and 2F cores */
17903   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17904   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17905
17906   /* MIPS IV */
17907   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17908   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17909   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17910   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17911   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17912   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17913   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17914   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17915   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17916   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17917   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17918   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17919   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17920   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17921   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17922
17923   /* MIPS 32 */
17924   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17925   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17926   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17927   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17928
17929   /* MIPS 32 Release 2 */
17930   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17931   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17932   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17933   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17934   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17935   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17936   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17937   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17938   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17939                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17940   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17941                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17942   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17943   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17944   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17945   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17946   /* Deprecated forms of the above.  */
17947   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17948   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17949   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17950   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17951   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17952   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17953   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17954   /* Deprecated forms of the above.  */
17955   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17956   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17957   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17958   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17959   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17960   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17961   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17962   /* Deprecated forms of the above.  */
17963   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17964   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17965   /* 34Kn is a 34kc without DSP.  */
17966   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17967   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17968   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17969   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17970   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17971   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17972   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17973   /* Deprecated forms of the above.  */
17974   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17975   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17976   /* 1004K cores are multiprocessor versions of the 34K.  */
17977   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17978   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17979   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17980   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17981   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
17982   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
17983
17984   /* MIPS 64 */
17985   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17986   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17987   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17988   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17989
17990   /* Broadcom SB-1 CPU core */
17991   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17992   /* Broadcom SB-1A CPU core */
17993   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17994   
17995   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
17996
17997   /* MIPS 64 Release 2 */
17998
17999   /* Cavium Networks Octeon CPU core */
18000   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
18001   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
18002   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
18003
18004   /* RMI Xlr */
18005   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
18006
18007   /* Broadcom XLP.
18008      XLP is mostly like XLR, with the prominent exception that it is
18009      MIPS64R2 rather than MIPS64.  */
18010   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
18011
18012   /* End marker */
18013   { NULL, 0, 0, 0, 0 }
18014 };
18015
18016
18017 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
18018    with a final "000" replaced by "k".  Ignore case.
18019
18020    Note: this function is shared between GCC and GAS.  */
18021
18022 static bfd_boolean
18023 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
18024 {
18025   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
18026     given++, canonical++;
18027
18028   return ((*given == 0 && *canonical == 0)
18029           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
18030 }
18031
18032
18033 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
18034    CPU name.  We've traditionally allowed a lot of variation here.
18035
18036    Note: this function is shared between GCC and GAS.  */
18037
18038 static bfd_boolean
18039 mips_matching_cpu_name_p (const char *canonical, const char *given)
18040 {
18041   /* First see if the name matches exactly, or with a final "000"
18042      turned into "k".  */
18043   if (mips_strict_matching_cpu_name_p (canonical, given))
18044     return TRUE;
18045
18046   /* If not, try comparing based on numerical designation alone.
18047      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
18048   if (TOLOWER (*given) == 'r')
18049     given++;
18050   if (!ISDIGIT (*given))
18051     return FALSE;
18052
18053   /* Skip over some well-known prefixes in the canonical name,
18054      hoping to find a number there too.  */
18055   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
18056     canonical += 2;
18057   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
18058     canonical += 2;
18059   else if (TOLOWER (canonical[0]) == 'r')
18060     canonical += 1;
18061
18062   return mips_strict_matching_cpu_name_p (canonical, given);
18063 }
18064
18065
18066 /* Parse an option that takes the name of a processor as its argument.
18067    OPTION is the name of the option and CPU_STRING is the argument.
18068    Return the corresponding processor enumeration if the CPU_STRING is
18069    recognized, otherwise report an error and return null.
18070
18071    A similar function exists in GCC.  */
18072
18073 static const struct mips_cpu_info *
18074 mips_parse_cpu (const char *option, const char *cpu_string)
18075 {
18076   const struct mips_cpu_info *p;
18077
18078   /* 'from-abi' selects the most compatible architecture for the given
18079      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
18080      EABIs, we have to decide whether we're using the 32-bit or 64-bit
18081      version.  Look first at the -mgp options, if given, otherwise base
18082      the choice on MIPS_DEFAULT_64BIT.
18083
18084      Treat NO_ABI like the EABIs.  One reason to do this is that the
18085      plain 'mips' and 'mips64' configs have 'from-abi' as their default
18086      architecture.  This code picks MIPS I for 'mips' and MIPS III for
18087      'mips64', just as we did in the days before 'from-abi'.  */
18088   if (strcasecmp (cpu_string, "from-abi") == 0)
18089     {
18090       if (ABI_NEEDS_32BIT_REGS (mips_abi))
18091         return mips_cpu_info_from_isa (ISA_MIPS1);
18092
18093       if (ABI_NEEDS_64BIT_REGS (mips_abi))
18094         return mips_cpu_info_from_isa (ISA_MIPS3);
18095
18096       if (file_mips_gp32 >= 0)
18097         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
18098
18099       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
18100                                      ? ISA_MIPS3
18101                                      : ISA_MIPS1);
18102     }
18103
18104   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
18105   if (strcasecmp (cpu_string, "default") == 0)
18106     return 0;
18107
18108   for (p = mips_cpu_info_table; p->name != 0; p++)
18109     if (mips_matching_cpu_name_p (p->name, cpu_string))
18110       return p;
18111
18112   as_bad (_("bad value (%s) for %s"), cpu_string, option);
18113   return 0;
18114 }
18115
18116 /* Return the canonical processor information for ISA (a member of the
18117    ISA_MIPS* enumeration).  */
18118
18119 static const struct mips_cpu_info *
18120 mips_cpu_info_from_isa (int isa)
18121 {
18122   int i;
18123
18124   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18125     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
18126         && isa == mips_cpu_info_table[i].isa)
18127       return (&mips_cpu_info_table[i]);
18128
18129   return NULL;
18130 }
18131
18132 static const struct mips_cpu_info *
18133 mips_cpu_info_from_arch (int arch)
18134 {
18135   int i;
18136
18137   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18138     if (arch == mips_cpu_info_table[i].cpu)
18139       return (&mips_cpu_info_table[i]);
18140
18141   return NULL;
18142 }
18143 \f
18144 static void
18145 show (FILE *stream, const char *string, int *col_p, int *first_p)
18146 {
18147   if (*first_p)
18148     {
18149       fprintf (stream, "%24s", "");
18150       *col_p = 24;
18151     }
18152   else
18153     {
18154       fprintf (stream, ", ");
18155       *col_p += 2;
18156     }
18157
18158   if (*col_p + strlen (string) > 72)
18159     {
18160       fprintf (stream, "\n%24s", "");
18161       *col_p = 24;
18162     }
18163
18164   fprintf (stream, "%s", string);
18165   *col_p += strlen (string);
18166
18167   *first_p = 0;
18168 }
18169
18170 void
18171 md_show_usage (FILE *stream)
18172 {
18173   int column, first;
18174   size_t i;
18175
18176   fprintf (stream, _("\
18177 MIPS options:\n\
18178 -EB                     generate big endian output\n\
18179 -EL                     generate little endian output\n\
18180 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18181 -G NUM                  allow referencing objects up to NUM bytes\n\
18182                         implicitly with the gp register [default 8]\n"));
18183   fprintf (stream, _("\
18184 -mips1                  generate MIPS ISA I instructions\n\
18185 -mips2                  generate MIPS ISA II instructions\n\
18186 -mips3                  generate MIPS ISA III instructions\n\
18187 -mips4                  generate MIPS ISA IV instructions\n\
18188 -mips5                  generate MIPS ISA V instructions\n\
18189 -mips32                 generate MIPS32 ISA instructions\n\
18190 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18191 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
18192 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
18193 -mips64                 generate MIPS64 ISA instructions\n\
18194 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18195 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
18196 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
18197 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18198
18199   first = 1;
18200
18201   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18202     show (stream, mips_cpu_info_table[i].name, &column, &first);
18203   show (stream, "from-abi", &column, &first);
18204   fputc ('\n', stream);
18205
18206   fprintf (stream, _("\
18207 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18208 -no-mCPU                don't generate code specific to CPU.\n\
18209                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18210
18211   first = 1;
18212
18213   show (stream, "3900", &column, &first);
18214   show (stream, "4010", &column, &first);
18215   show (stream, "4100", &column, &first);
18216   show (stream, "4650", &column, &first);
18217   fputc ('\n', stream);
18218
18219   fprintf (stream, _("\
18220 -mips16                 generate mips16 instructions\n\
18221 -no-mips16              do not generate mips16 instructions\n"));
18222   fprintf (stream, _("\
18223 -mmicromips             generate microMIPS instructions\n\
18224 -mno-micromips          do not generate microMIPS instructions\n"));
18225   fprintf (stream, _("\
18226 -msmartmips             generate smartmips instructions\n\
18227 -mno-smartmips          do not generate smartmips instructions\n"));  
18228   fprintf (stream, _("\
18229 -mdsp                   generate DSP instructions\n\
18230 -mno-dsp                do not generate DSP instructions\n"));
18231   fprintf (stream, _("\
18232 -mdspr2                 generate DSP R2 instructions\n\
18233 -mno-dspr2              do not generate DSP R2 instructions\n"));
18234   fprintf (stream, _("\
18235 -mmt                    generate MT instructions\n\
18236 -mno-mt                 do not generate MT instructions\n"));
18237   fprintf (stream, _("\
18238 -mmcu                   generate MCU instructions\n\
18239 -mno-mcu                do not generate MCU instructions\n"));
18240   fprintf (stream, _("\
18241 -mmsa                   generate MSA instructions\n\
18242 -mno-msa                do not generate MSA instructions\n"));
18243   fprintf (stream, _("\
18244 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
18245 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
18246   fprintf (stream, _("\
18247 -mvirt                  generate Virtualization instructions\n\
18248 -mno-virt               do not generate Virtualization instructions\n"));
18249   fprintf (stream, _("\
18250 -minsn32                only generate 32-bit microMIPS instructions\n\
18251 -mno-insn32             generate all microMIPS instructions\n"));
18252   fprintf (stream, _("\
18253 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18254 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18255 -mfix-vr4120            work around certain VR4120 errata\n\
18256 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18257 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18258 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18259 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18260 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18261 -msym32                 assume all symbols have 32-bit values\n\
18262 -O0                     remove unneeded NOPs, do not swap branches\n\
18263 -O                      remove unneeded NOPs and swap branches\n\
18264 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18265 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18266   fprintf (stream, _("\
18267 -mhard-float            allow floating-point instructions\n\
18268 -msoft-float            do not allow floating-point instructions\n\
18269 -msingle-float          only allow 32-bit floating-point operations\n\
18270 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18271 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18272 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18273 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18274
18275   first = 1;
18276
18277   show (stream, "legacy", &column, &first);
18278   show (stream, "2008", &column, &first);
18279
18280   fputc ('\n', stream);
18281
18282   fprintf (stream, _("\
18283 -KPIC, -call_shared     generate SVR4 position independent code\n\
18284 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18285 -mvxworks-pic           generate VxWorks position independent code\n\
18286 -non_shared             do not generate code that can operate with DSOs\n\
18287 -xgot                   assume a 32 bit GOT\n\
18288 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18289 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18290                         position dependent (non shared) code\n\
18291 -mabi=ABI               create ABI conformant object file for:\n"));
18292
18293   first = 1;
18294
18295   show (stream, "32", &column, &first);
18296   show (stream, "o64", &column, &first);
18297   show (stream, "n32", &column, &first);
18298   show (stream, "64", &column, &first);
18299   show (stream, "eabi", &column, &first);
18300
18301   fputc ('\n', stream);
18302
18303   fprintf (stream, _("\
18304 -32                     create o32 ABI object file (default)\n\
18305 -n32                    create n32 ABI object file\n\
18306 -64                     create 64 ABI object file\n"));
18307 }
18308
18309 #ifdef TE_IRIX
18310 enum dwarf2_format
18311 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18312 {
18313   if (HAVE_64BIT_SYMBOLS)
18314     return dwarf2_format_64bit_irix;
18315   else
18316     return dwarf2_format_32bit;
18317 }
18318 #endif
18319
18320 int
18321 mips_dwarf2_addr_size (void)
18322 {
18323   if (HAVE_64BIT_OBJECTS)
18324     return 8;
18325   else
18326     return 4;
18327 }
18328
18329 /* Standard calling conventions leave the CFA at SP on entry.  */
18330 void
18331 mips_cfi_frame_initial_instructions (void)
18332 {
18333   cfi_add_CFA_def_cfa_register (SP);
18334 }
18335
18336 int
18337 tc_mips_regname_to_dw2regnum (char *regname)
18338 {
18339   unsigned int regnum = -1;
18340   unsigned int reg;
18341
18342   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18343     regnum = reg;
18344
18345   return regnum;
18346 }
18347
18348 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
18349    Given a symbolic attribute NAME, return the proper integer value.
18350    Returns -1 if the attribute is not known.  */
18351
18352 int
18353 mips_convert_symbolic_attribute (const char *name)
18354 {
18355   static const struct
18356   {
18357     const char * name;
18358     const int    tag;
18359   }
18360   attribute_table[] =
18361     {
18362 #define T(tag) {#tag, tag}
18363       T (Tag_GNU_MIPS_ABI_FP),
18364       T (Tag_GNU_MIPS_ABI_MSA),
18365 #undef T
18366     };
18367   unsigned int i;
18368
18369   if (name == NULL)
18370     return -1;
18371
18372   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
18373     if (streq (name, attribute_table[i].name))
18374       return attribute_table[i].tag;
18375
18376   return -1;
18377 }