ff861653fa8c17093ca7dfd413e17bf58b541908
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
4    Free Software Foundation, Inc.
5    Contributed by the OSF and Ralph Campbell.
6    Written by Keith Knowles and Ralph Campbell, working independently.
7    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
8    Support.
9
10    This file is part of GAS.
11
12    GAS is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3, or (at your option)
15    any later version.
16
17    GAS is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with GAS; see the file COPYING.  If not, write to the Free
24    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
25    02110-1301, USA.  */
26
27 #include "as.h"
28 #include "config.h"
29 #include "subsegs.h"
30 #include "safe-ctype.h"
31
32 #include "opcode/mips.h"
33 #include "itbl-ops.h"
34 #include "dwarf2dbg.h"
35 #include "dw2gencfi.h"
36
37 /* Check assumptions made in this file.  */
38 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
39 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
40
41 #ifdef DEBUG
42 #define DBG(x) printf x
43 #else
44 #define DBG(x)
45 #endif
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_MIPS64            \
312                               || mips_opts.isa == ISA_MIPS64R2)
313
314 /* True if any microMIPS code was produced.  */
315 static int file_ase_micromips;
316
317 /* True if we want to create R_MIPS_JALR for jalr $25.  */
318 #ifdef TE_IRIX
319 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
320 #else
321 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
322    because there's no place for any addend, the only acceptable
323    expression is a bare symbol.  */
324 #define MIPS_JALR_HINT_P(EXPR) \
325   (!HAVE_IN_PLACE_ADDENDS \
326    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
327 #endif
328
329 /* The argument of the -march= flag.  The architecture we are assembling.  */
330 static int file_mips_arch = CPU_UNKNOWN;
331 static const char *mips_arch_string;
332
333 /* The argument of the -mtune= flag.  The architecture for which we
334    are optimizing.  */
335 static int mips_tune = CPU_UNKNOWN;
336 static const char *mips_tune_string;
337
338 /* True when generating 32-bit code for a 64-bit processor.  */
339 static int mips_32bitmode = 0;
340
341 /* True if the given ABI requires 32-bit registers.  */
342 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
343
344 /* Likewise 64-bit registers.  */
345 #define ABI_NEEDS_64BIT_REGS(ABI)       \
346   ((ABI) == N32_ABI                     \
347    || (ABI) == N64_ABI                  \
348    || (ABI) == O64_ABI)
349
350 /*  Return true if ISA supports 64 bit wide gp registers.  */
351 #define ISA_HAS_64BIT_REGS(ISA)         \
352   ((ISA) == ISA_MIPS3                   \
353    || (ISA) == ISA_MIPS4                \
354    || (ISA) == ISA_MIPS5                \
355    || (ISA) == ISA_MIPS64               \
356    || (ISA) == ISA_MIPS64R2)
357
358 /*  Return true if ISA supports 64 bit wide float registers.  */
359 #define ISA_HAS_64BIT_FPRS(ISA)         \
360   ((ISA) == ISA_MIPS3                   \
361    || (ISA) == ISA_MIPS4                \
362    || (ISA) == ISA_MIPS5                \
363    || (ISA) == ISA_MIPS32R2             \
364    || (ISA) == ISA_MIPS64               \
365    || (ISA) == ISA_MIPS64R2)
366
367 /* Return true if ISA supports 64-bit right rotate (dror et al.)
368    instructions.  */
369 #define ISA_HAS_DROR(ISA)               \
370   ((ISA) == ISA_MIPS64R2                \
371    || (mips_opts.micromips              \
372        && ISA_HAS_64BIT_REGS (ISA))     \
373    )
374
375 /* Return true if ISA supports 32-bit right rotate (ror et al.)
376    instructions.  */
377 #define ISA_HAS_ROR(ISA)                \
378   ((ISA) == ISA_MIPS32R2                \
379    || (ISA) == ISA_MIPS64R2             \
380    || (mips_opts.ase & ASE_SMARTMIPS)   \
381    || mips_opts.micromips               \
382    )
383
384 /* Return true if ISA supports single-precision floats in odd registers.  */
385 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
386   ((ISA) == ISA_MIPS32                  \
387    || (ISA) == ISA_MIPS32R2             \
388    || (ISA) == ISA_MIPS64               \
389    || (ISA) == ISA_MIPS64R2)
390
391 /* Return true if ISA supports move to/from high part of a 64-bit
392    floating-point register. */
393 #define ISA_HAS_MXHC1(ISA)              \
394   ((ISA) == ISA_MIPS32R2                \
395    || (ISA) == ISA_MIPS64R2)
396
397 #define HAVE_32BIT_GPRS                            \
398     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
399
400 #define HAVE_32BIT_FPRS                            \
401     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
402
403 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
404 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
405
406 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
407
408 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
409
410 /* True if relocations are stored in-place.  */
411 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
412
413 /* The ABI-derived address size.  */
414 #define HAVE_64BIT_ADDRESSES \
415   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
416 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
417
418 /* The size of symbolic constants (i.e., expressions of the form
419    "SYMBOL" or "SYMBOL + OFFSET").  */
420 #define HAVE_32BIT_SYMBOLS \
421   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
422 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
423
424 /* Addresses are loaded in different ways, depending on the address size
425    in use.  The n32 ABI Documentation also mandates the use of additions
426    with overflow checking, but existing implementations don't follow it.  */
427 #define ADDRESS_ADD_INSN                                                \
428    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
429
430 #define ADDRESS_ADDI_INSN                                               \
431    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
432
433 #define ADDRESS_LOAD_INSN                                               \
434    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
435
436 #define ADDRESS_STORE_INSN                                              \
437    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
438
439 /* Return true if the given CPU supports the MIPS16 ASE.  */
440 #define CPU_HAS_MIPS16(cpu)                                             \
441    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
442     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
443
444 /* Return true if the given CPU supports the microMIPS ASE.  */
445 #define CPU_HAS_MICROMIPS(cpu)  0
446
447 /* True if CPU has a dror instruction.  */
448 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
449
450 /* True if CPU has a ror instruction.  */
451 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
452
453 /* True if CPU is in the Octeon family */
454 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
455
456 /* True if CPU has seq/sne and seqi/snei instructions.  */
457 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
458
459 /* True, if CPU has support for ldc1 and sdc1. */
460 #define CPU_HAS_LDC1_SDC1(CPU)  \
461    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
462
463 /* True if mflo and mfhi can be immediately followed by instructions
464    which write to the HI and LO registers.
465
466    According to MIPS specifications, MIPS ISAs I, II, and III need
467    (at least) two instructions between the reads of HI/LO and
468    instructions which write them, and later ISAs do not.  Contradicting
469    the MIPS specifications, some MIPS IV processor user manuals (e.g.
470    the UM for the NEC Vr5000) document needing the instructions between
471    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
472    MIPS64 and later ISAs to have the interlocks, plus any specific
473    earlier-ISA CPUs for which CPU documentation declares that the
474    instructions are really interlocked.  */
475 #define hilo_interlocks \
476   (mips_opts.isa == ISA_MIPS32                        \
477    || mips_opts.isa == ISA_MIPS32R2                   \
478    || mips_opts.isa == ISA_MIPS64                     \
479    || mips_opts.isa == ISA_MIPS64R2                   \
480    || mips_opts.arch == CPU_R4010                     \
481    || mips_opts.arch == CPU_R5900                     \
482    || mips_opts.arch == CPU_R10000                    \
483    || mips_opts.arch == CPU_R12000                    \
484    || mips_opts.arch == CPU_R14000                    \
485    || mips_opts.arch == CPU_R16000                    \
486    || mips_opts.arch == CPU_RM7000                    \
487    || mips_opts.arch == CPU_VR5500                    \
488    || mips_opts.micromips                             \
489    )
490
491 /* Whether the processor uses hardware interlocks to protect reads
492    from the GPRs after they are loaded from memory, and thus does not
493    require nops to be inserted.  This applies to instructions marked
494    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
495    level I and microMIPS mode instructions are always interlocked.  */
496 #define gpr_interlocks                                \
497   (mips_opts.isa != ISA_MIPS1                         \
498    || mips_opts.arch == CPU_R3900                     \
499    || mips_opts.arch == CPU_R5900                     \
500    || mips_opts.micromips                             \
501    )
502
503 /* Whether the processor uses hardware interlocks to avoid delays
504    required by coprocessor instructions, and thus does not require
505    nops to be inserted.  This applies to instructions marked
506    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
507    between instructions marked INSN_WRITE_COND_CODE and ones marked
508    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
509    levels I, II, and III and microMIPS mode instructions are always
510    interlocked.  */
511 /* Itbl support may require additional care here.  */
512 #define cop_interlocks                                \
513   ((mips_opts.isa != ISA_MIPS1                        \
514     && mips_opts.isa != ISA_MIPS2                     \
515     && mips_opts.isa != ISA_MIPS3)                    \
516    || mips_opts.arch == CPU_R4300                     \
517    || mips_opts.micromips                             \
518    )
519
520 /* Whether the processor uses hardware interlocks to protect reads
521    from coprocessor registers after they are loaded from memory, and
522    thus does not require nops to be inserted.  This applies to
523    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
524    requires at MIPS ISA level I and microMIPS mode instructions are
525    always interlocked.  */
526 #define cop_mem_interlocks                            \
527   (mips_opts.isa != ISA_MIPS1                         \
528    || mips_opts.micromips                             \
529    )
530
531 /* Is this a mfhi or mflo instruction?  */
532 #define MF_HILO_INSN(PINFO) \
533   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
534
535 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
536    has been selected.  This implies, in particular, that addresses of text
537    labels have their LSB set.  */
538 #define HAVE_CODE_COMPRESSION                                           \
539   ((mips_opts.mips16 | mips_opts.micromips) != 0)
540
541 /* The minimum and maximum signed values that can be stored in a GPR.  */
542 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
543 #define GPR_SMIN (-GPR_SMAX - 1)
544
545 /* MIPS PIC level.  */
546
547 enum mips_pic_level mips_pic;
548
549 /* 1 if we should generate 32 bit offsets from the $gp register in
550    SVR4_PIC mode.  Currently has no meaning in other modes.  */
551 static int mips_big_got = 0;
552
553 /* 1 if trap instructions should used for overflow rather than break
554    instructions.  */
555 static int mips_trap = 0;
556
557 /* 1 if double width floating point constants should not be constructed
558    by assembling two single width halves into two single width floating
559    point registers which just happen to alias the double width destination
560    register.  On some architectures this aliasing can be disabled by a bit
561    in the status register, and the setting of this bit cannot be determined
562    automatically at assemble time.  */
563 static int mips_disable_float_construction;
564
565 /* Non-zero if any .set noreorder directives were used.  */
566
567 static int mips_any_noreorder;
568
569 /* Non-zero if nops should be inserted when the register referenced in
570    an mfhi/mflo instruction is read in the next two instructions.  */
571 static int mips_7000_hilo_fix;
572
573 /* The size of objects in the small data section.  */
574 static unsigned int g_switch_value = 8;
575 /* Whether the -G option was used.  */
576 static int g_switch_seen = 0;
577
578 #define N_RMASK 0xc4
579 #define N_VFP   0xd4
580
581 /* If we can determine in advance that GP optimization won't be
582    possible, we can skip the relaxation stuff that tries to produce
583    GP-relative references.  This makes delay slot optimization work
584    better.
585
586    This function can only provide a guess, but it seems to work for
587    gcc output.  It needs to guess right for gcc, otherwise gcc
588    will put what it thinks is a GP-relative instruction in a branch
589    delay slot.
590
591    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
592    fixed it for the non-PIC mode.  KR 95/04/07  */
593 static int nopic_need_relax (symbolS *, int);
594
595 /* handle of the OPCODE hash table */
596 static struct hash_control *op_hash = NULL;
597
598 /* The opcode hash table we use for the mips16.  */
599 static struct hash_control *mips16_op_hash = NULL;
600
601 /* The opcode hash table we use for the microMIPS ASE.  */
602 static struct hash_control *micromips_op_hash = NULL;
603
604 /* This array holds the chars that always start a comment.  If the
605     pre-processor is disabled, these aren't very useful */
606 const char comment_chars[] = "#";
607
608 /* This array holds the chars that only start a comment at the beginning of
609    a line.  If the line seems to have the form '# 123 filename'
610    .line and .file directives will appear in the pre-processed output */
611 /* Note that input_file.c hand checks for '#' at the beginning of the
612    first line of the input file.  This is because the compiler outputs
613    #NO_APP at the beginning of its output.  */
614 /* Also note that C style comments are always supported.  */
615 const char line_comment_chars[] = "#";
616
617 /* This array holds machine specific line separator characters.  */
618 const char line_separator_chars[] = ";";
619
620 /* Chars that can be used to separate mant from exp in floating point nums */
621 const char EXP_CHARS[] = "eE";
622
623 /* Chars that mean this number is a floating point constant */
624 /* As in 0f12.456 */
625 /* or    0d1.2345e12 */
626 const char FLT_CHARS[] = "rRsSfFdDxXpP";
627
628 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
629    changed in read.c .  Ideally it shouldn't have to know about it at all,
630    but nothing is ideal around here.
631  */
632
633 static char *insn_error;
634
635 static int auto_align = 1;
636
637 /* When outputting SVR4 PIC code, the assembler needs to know the
638    offset in the stack frame from which to restore the $gp register.
639    This is set by the .cprestore pseudo-op, and saved in this
640    variable.  */
641 static offsetT mips_cprestore_offset = -1;
642
643 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
644    more optimizations, it can use a register value instead of a memory-saved
645    offset and even an other register than $gp as global pointer.  */
646 static offsetT mips_cpreturn_offset = -1;
647 static int mips_cpreturn_register = -1;
648 static int mips_gp_register = GP;
649 static int mips_gprel_offset = 0;
650
651 /* Whether mips_cprestore_offset has been set in the current function
652    (or whether it has already been warned about, if not).  */
653 static int mips_cprestore_valid = 0;
654
655 /* This is the register which holds the stack frame, as set by the
656    .frame pseudo-op.  This is needed to implement .cprestore.  */
657 static int mips_frame_reg = SP;
658
659 /* Whether mips_frame_reg has been set in the current function
660    (or whether it has already been warned about, if not).  */
661 static int mips_frame_reg_valid = 0;
662
663 /* To output NOP instructions correctly, we need to keep information
664    about the previous two instructions.  */
665
666 /* Whether we are optimizing.  The default value of 2 means to remove
667    unneeded NOPs and swap branch instructions when possible.  A value
668    of 1 means to not swap branches.  A value of 0 means to always
669    insert NOPs.  */
670 static int mips_optimize = 2;
671
672 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
673    equivalent to seeing no -g option at all.  */
674 static int mips_debug = 0;
675
676 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
677 #define MAX_VR4130_NOPS 4
678
679 /* The maximum number of NOPs needed to fill delay slots.  */
680 #define MAX_DELAY_NOPS 2
681
682 /* The maximum number of NOPs needed for any purpose.  */
683 #define MAX_NOPS 4
684
685 /* A list of previous instructions, with index 0 being the most recent.
686    We need to look back MAX_NOPS instructions when filling delay slots
687    or working around processor errata.  We need to look back one
688    instruction further if we're thinking about using history[0] to
689    fill a branch delay slot.  */
690 static struct mips_cl_insn history[1 + MAX_NOPS];
691
692 /* Nop instructions used by emit_nop.  */
693 static struct mips_cl_insn nop_insn;
694 static struct mips_cl_insn mips16_nop_insn;
695 static struct mips_cl_insn micromips_nop16_insn;
696 static struct mips_cl_insn micromips_nop32_insn;
697
698 /* The appropriate nop for the current mode.  */
699 #define NOP_INSN (mips_opts.mips16                                      \
700                   ? &mips16_nop_insn                                    \
701                   : (mips_opts.micromips                                \
702                      ? (mips_opts.insn32                                \
703                         ? &micromips_nop32_insn                         \
704                         : &micromips_nop16_insn)                        \
705                      : &nop_insn))
706
707 /* The size of NOP_INSN in bytes.  */
708 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
709                         || (mips_opts.micromips && !mips_opts.insn32))  \
710                        ? 2 : 4)
711
712 /* If this is set, it points to a frag holding nop instructions which
713    were inserted before the start of a noreorder section.  If those
714    nops turn out to be unnecessary, the size of the frag can be
715    decreased.  */
716 static fragS *prev_nop_frag;
717
718 /* The number of nop instructions we created in prev_nop_frag.  */
719 static int prev_nop_frag_holds;
720
721 /* The number of nop instructions that we know we need in
722    prev_nop_frag.  */
723 static int prev_nop_frag_required;
724
725 /* The number of instructions we've seen since prev_nop_frag.  */
726 static int prev_nop_frag_since;
727
728 /* Relocations against symbols are sometimes done in two parts, with a HI
729    relocation and a LO relocation.  Each relocation has only 16 bits of
730    space to store an addend.  This means that in order for the linker to
731    handle carries correctly, it must be able to locate both the HI and
732    the LO relocation.  This means that the relocations must appear in
733    order in the relocation table.
734
735    In order to implement this, we keep track of each unmatched HI
736    relocation.  We then sort them so that they immediately precede the
737    corresponding LO relocation.  */
738
739 struct mips_hi_fixup
740 {
741   /* Next HI fixup.  */
742   struct mips_hi_fixup *next;
743   /* This fixup.  */
744   fixS *fixp;
745   /* The section this fixup is in.  */
746   segT seg;
747 };
748
749 /* The list of unmatched HI relocs.  */
750
751 static struct mips_hi_fixup *mips_hi_fixup_list;
752
753 /* The frag containing the last explicit relocation operator.
754    Null if explicit relocations have not been used.  */
755
756 static fragS *prev_reloc_op_frag;
757
758 /* Map mips16 register numbers to normal MIPS register numbers.  */
759
760 static const unsigned int mips16_to_32_reg_map[] =
761 {
762   16, 17, 2, 3, 4, 5, 6, 7
763 };
764
765 /* Map microMIPS register numbers to normal MIPS register numbers.  */
766
767 #define micromips_to_32_reg_b_map       mips16_to_32_reg_map
768 #define micromips_to_32_reg_c_map       mips16_to_32_reg_map
769 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
770 #define micromips_to_32_reg_e_map       mips16_to_32_reg_map
771 #define micromips_to_32_reg_f_map       mips16_to_32_reg_map
772 #define micromips_to_32_reg_g_map       mips16_to_32_reg_map
773
774 /* The microMIPS registers with type h.  */
775 static const unsigned int micromips_to_32_reg_h_map1[] =
776 {
777   5, 5, 6, 4, 4, 4, 4, 4
778 };
779 static const unsigned int micromips_to_32_reg_h_map2[] =
780 {
781   6, 7, 7, 21, 22, 5, 6, 7
782 };
783
784 #define micromips_to_32_reg_l_map       mips16_to_32_reg_map
785
786 /* The microMIPS registers with type m.  */
787 static const unsigned int micromips_to_32_reg_m_map[] =
788 {
789   0, 17, 2, 3, 16, 18, 19, 20
790 };
791
792 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
793
794 /* The microMIPS registers with type q.  */
795 static const unsigned int micromips_to_32_reg_q_map[] =
796 {
797   0, 17, 2, 3, 4, 5, 6, 7
798 };
799
800 /* Classifies the kind of instructions we're interested in when
801    implementing -mfix-vr4120.  */
802 enum fix_vr4120_class
803 {
804   FIX_VR4120_MACC,
805   FIX_VR4120_DMACC,
806   FIX_VR4120_MULT,
807   FIX_VR4120_DMULT,
808   FIX_VR4120_DIV,
809   FIX_VR4120_MTHILO,
810   NUM_FIX_VR4120_CLASSES
811 };
812
813 /* ...likewise -mfix-loongson2f-jump.  */
814 static bfd_boolean mips_fix_loongson2f_jump;
815
816 /* ...likewise -mfix-loongson2f-nop.  */
817 static bfd_boolean mips_fix_loongson2f_nop;
818
819 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
820 static bfd_boolean mips_fix_loongson2f;
821
822 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
823    there must be at least one other instruction between an instruction
824    of type X and an instruction of type Y.  */
825 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
826
827 /* True if -mfix-vr4120 is in force.  */
828 static int mips_fix_vr4120;
829
830 /* ...likewise -mfix-vr4130.  */
831 static int mips_fix_vr4130;
832
833 /* ...likewise -mfix-24k.  */
834 static int mips_fix_24k;
835
836 /* ...likewise -mfix-cn63xxp1 */
837 static bfd_boolean mips_fix_cn63xxp1;
838
839 /* We don't relax branches by default, since this causes us to expand
840    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
841    fail to compute the offset before expanding the macro to the most
842    efficient expansion.  */
843
844 static int mips_relax_branch;
845 \f
846 /* The expansion of many macros depends on the type of symbol that
847    they refer to.  For example, when generating position-dependent code,
848    a macro that refers to a symbol may have two different expansions,
849    one which uses GP-relative addresses and one which uses absolute
850    addresses.  When generating SVR4-style PIC, a macro may have
851    different expansions for local and global symbols.
852
853    We handle these situations by generating both sequences and putting
854    them in variant frags.  In position-dependent code, the first sequence
855    will be the GP-relative one and the second sequence will be the
856    absolute one.  In SVR4 PIC, the first sequence will be for global
857    symbols and the second will be for local symbols.
858
859    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
860    SECOND are the lengths of the two sequences in bytes.  These fields
861    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
862    the subtype has the following flags:
863
864    RELAX_USE_SECOND
865         Set if it has been decided that we should use the second
866         sequence instead of the first.
867
868    RELAX_SECOND_LONGER
869         Set in the first variant frag if the macro's second implementation
870         is longer than its first.  This refers to the macro as a whole,
871         not an individual relaxation.
872
873    RELAX_NOMACRO
874         Set in the first variant frag if the macro appeared in a .set nomacro
875         block and if one alternative requires a warning but the other does not.
876
877    RELAX_DELAY_SLOT
878         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
879         delay slot.
880
881    RELAX_DELAY_SLOT_16BIT
882         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
883         16-bit instruction.
884
885    RELAX_DELAY_SLOT_SIZE_FIRST
886         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
887         the macro is of the wrong size for the branch delay slot.
888
889    RELAX_DELAY_SLOT_SIZE_SECOND
890         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
891         the macro is of the wrong size for the branch delay slot.
892
893    The frag's "opcode" points to the first fixup for relaxable code.
894
895    Relaxable macros are generated using a sequence such as:
896
897       relax_start (SYMBOL);
898       ... generate first expansion ...
899       relax_switch ();
900       ... generate second expansion ...
901       relax_end ();
902
903    The code and fixups for the unwanted alternative are discarded
904    by md_convert_frag.  */
905 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
906
907 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
908 #define RELAX_SECOND(X) ((X) & 0xff)
909 #define RELAX_USE_SECOND 0x10000
910 #define RELAX_SECOND_LONGER 0x20000
911 #define RELAX_NOMACRO 0x40000
912 #define RELAX_DELAY_SLOT 0x80000
913 #define RELAX_DELAY_SLOT_16BIT 0x100000
914 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
915 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
916
917 /* Branch without likely bit.  If label is out of range, we turn:
918
919         beq reg1, reg2, label
920         delay slot
921
922    into
923
924         bne reg1, reg2, 0f
925         nop
926         j label
927      0: delay slot
928
929    with the following opcode replacements:
930
931         beq <-> bne
932         blez <-> bgtz
933         bltz <-> bgez
934         bc1f <-> bc1t
935
936         bltzal <-> bgezal  (with jal label instead of j label)
937
938    Even though keeping the delay slot instruction in the delay slot of
939    the branch would be more efficient, it would be very tricky to do
940    correctly, because we'd have to introduce a variable frag *after*
941    the delay slot instruction, and expand that instead.  Let's do it
942    the easy way for now, even if the branch-not-taken case now costs
943    one additional instruction.  Out-of-range branches are not supposed
944    to be common, anyway.
945
946    Branch likely.  If label is out of range, we turn:
947
948         beql reg1, reg2, label
949         delay slot (annulled if branch not taken)
950
951    into
952
953         beql reg1, reg2, 1f
954         nop
955         beql $0, $0, 2f
956         nop
957      1: j[al] label
958         delay slot (executed only if branch taken)
959      2:
960
961    It would be possible to generate a shorter sequence by losing the
962    likely bit, generating something like:
963
964         bne reg1, reg2, 0f
965         nop
966         j[al] label
967         delay slot (executed only if branch taken)
968      0:
969
970         beql -> bne
971         bnel -> beq
972         blezl -> bgtz
973         bgtzl -> blez
974         bltzl -> bgez
975         bgezl -> bltz
976         bc1fl -> bc1t
977         bc1tl -> bc1f
978
979         bltzall -> bgezal  (with jal label instead of j label)
980         bgezall -> bltzal  (ditto)
981
982
983    but it's not clear that it would actually improve performance.  */
984 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
985   ((relax_substateT)                                            \
986    (0xc0000000                                                  \
987     | ((at) & 0x1f)                                             \
988     | ((toofar) ? 0x20 : 0)                                     \
989     | ((link) ? 0x40 : 0)                                       \
990     | ((likely) ? 0x80 : 0)                                     \
991     | ((uncond) ? 0x100 : 0)))
992 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
993 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
994 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
995 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
996 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
997 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
998
999 /* For mips16 code, we use an entirely different form of relaxation.
1000    mips16 supports two versions of most instructions which take
1001    immediate values: a small one which takes some small value, and a
1002    larger one which takes a 16 bit value.  Since branches also follow
1003    this pattern, relaxing these values is required.
1004
1005    We can assemble both mips16 and normal MIPS code in a single
1006    object.  Therefore, we need to support this type of relaxation at
1007    the same time that we support the relaxation described above.  We
1008    use the high bit of the subtype field to distinguish these cases.
1009
1010    The information we store for this type of relaxation is the
1011    argument code found in the opcode file for this relocation, whether
1012    the user explicitly requested a small or extended form, and whether
1013    the relocation is in a jump or jal delay slot.  That tells us the
1014    size of the value, and how it should be stored.  We also store
1015    whether the fragment is considered to be extended or not.  We also
1016    store whether this is known to be a branch to a different section,
1017    whether we have tried to relax this frag yet, and whether we have
1018    ever extended a PC relative fragment because of a shift count.  */
1019 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1020   (0x80000000                                                   \
1021    | ((type) & 0xff)                                            \
1022    | ((small) ? 0x100 : 0)                                      \
1023    | ((ext) ? 0x200 : 0)                                        \
1024    | ((dslot) ? 0x400 : 0)                                      \
1025    | ((jal_dslot) ? 0x800 : 0))
1026 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1027 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1028 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1029 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1030 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1031 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1032 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1033 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1034 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1035 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1036 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1037 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1038
1039 /* For microMIPS code, we use relaxation similar to one we use for
1040    MIPS16 code.  Some instructions that take immediate values support
1041    two encodings: a small one which takes some small value, and a
1042    larger one which takes a 16 bit value.  As some branches also follow
1043    this pattern, relaxing these values is required.
1044
1045    We can assemble both microMIPS and normal MIPS code in a single
1046    object.  Therefore, we need to support this type of relaxation at
1047    the same time that we support the relaxation described above.  We
1048    use one of the high bits of the subtype field to distinguish these
1049    cases.
1050
1051    The information we store for this type of relaxation is the argument
1052    code found in the opcode file for this relocation, the register
1053    selected as the assembler temporary, whether the branch is
1054    unconditional, whether it is compact, whether it stores the link
1055    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1056    branches to a sequence of instructions is enabled, and whether the
1057    displacement of a branch is too large to fit as an immediate argument
1058    of a 16-bit and a 32-bit branch, respectively.  */
1059 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1060                                relax32, toofar16, toofar32)     \
1061   (0x40000000                                                   \
1062    | ((type) & 0xff)                                            \
1063    | (((at) & 0x1f) << 8)                                       \
1064    | ((uncond) ? 0x2000 : 0)                                    \
1065    | ((compact) ? 0x4000 : 0)                                   \
1066    | ((link) ? 0x8000 : 0)                                      \
1067    | ((relax32) ? 0x10000 : 0)                                  \
1068    | ((toofar16) ? 0x20000 : 0)                                 \
1069    | ((toofar32) ? 0x40000 : 0))
1070 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1071 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1072 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1073 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1074 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1075 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1076 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1077
1078 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1079 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1080 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1081 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1082 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1083 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1084
1085 /* Sign-extend 16-bit value X.  */
1086 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1087
1088 /* Is the given value a sign-extended 32-bit value?  */
1089 #define IS_SEXT_32BIT_NUM(x)                                            \
1090   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1091    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1092
1093 /* Is the given value a sign-extended 16-bit value?  */
1094 #define IS_SEXT_16BIT_NUM(x)                                            \
1095   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1096    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1097
1098 /* Is the given value a sign-extended 12-bit value?  */
1099 #define IS_SEXT_12BIT_NUM(x)                                            \
1100   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1101
1102 /* Is the given value a sign-extended 9-bit value?  */
1103 #define IS_SEXT_9BIT_NUM(x)                                             \
1104   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1105
1106 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1107 #define IS_ZEXT_32BIT_NUM(x)                                            \
1108   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1109    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1110
1111 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
1112    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
1113 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
1114   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
1115               | (((VALUE) & (MASK)) << (SHIFT)))
1116
1117 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1118    SHIFT places.  */
1119 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1120   (((STRUCT) >> (SHIFT)) & (MASK))
1121
1122 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
1123    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
1124
1125    include/opcode/mips.h specifies operand fields using the macros
1126    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
1127    with "MIPS16OP" instead of "OP".  */
1128 #define INSERT_OPERAND(MICROMIPS, FIELD, INSN, VALUE) \
1129   do \
1130     if (!(MICROMIPS)) \
1131       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1132                    OP_MASK_##FIELD, OP_SH_##FIELD); \
1133     else \
1134       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1135                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD); \
1136   while (0)
1137 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
1138   INSERT_BITS ((INSN).insn_opcode, VALUE, \
1139                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
1140
1141 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1142 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1143   (!(MICROMIPS) \
1144    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1145    : EXTRACT_BITS ((INSN).insn_opcode, \
1146                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1147 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1148   EXTRACT_BITS ((INSN).insn_opcode, \
1149                 MIPS16OP_MASK_##FIELD, \
1150                 MIPS16OP_SH_##FIELD)
1151
1152 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1153 #define MIPS16_EXTEND (0xf000U << 16)
1154 \f
1155 /* Whether or not we are emitting a branch-likely macro.  */
1156 static bfd_boolean emit_branch_likely_macro = FALSE;
1157
1158 /* Global variables used when generating relaxable macros.  See the
1159    comment above RELAX_ENCODE for more details about how relaxation
1160    is used.  */
1161 static struct {
1162   /* 0 if we're not emitting a relaxable macro.
1163      1 if we're emitting the first of the two relaxation alternatives.
1164      2 if we're emitting the second alternative.  */
1165   int sequence;
1166
1167   /* The first relaxable fixup in the current frag.  (In other words,
1168      the first fixup that refers to relaxable code.)  */
1169   fixS *first_fixup;
1170
1171   /* sizes[0] says how many bytes of the first alternative are stored in
1172      the current frag.  Likewise sizes[1] for the second alternative.  */
1173   unsigned int sizes[2];
1174
1175   /* The symbol on which the choice of sequence depends.  */
1176   symbolS *symbol;
1177 } mips_relax;
1178 \f
1179 /* Global variables used to decide whether a macro needs a warning.  */
1180 static struct {
1181   /* True if the macro is in a branch delay slot.  */
1182   bfd_boolean delay_slot_p;
1183
1184   /* Set to the length in bytes required if the macro is in a delay slot
1185      that requires a specific length of instruction, otherwise zero.  */
1186   unsigned int delay_slot_length;
1187
1188   /* For relaxable macros, sizes[0] is the length of the first alternative
1189      in bytes and sizes[1] is the length of the second alternative.
1190      For non-relaxable macros, both elements give the length of the
1191      macro in bytes.  */
1192   unsigned int sizes[2];
1193
1194   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1195      instruction of the first alternative in bytes and first_insn_sizes[1]
1196      is the length of the first instruction of the second alternative.
1197      For non-relaxable macros, both elements give the length of the first
1198      instruction in bytes.
1199
1200      Set to zero if we haven't yet seen the first instruction.  */
1201   unsigned int first_insn_sizes[2];
1202
1203   /* For relaxable macros, insns[0] is the number of instructions for the
1204      first alternative and insns[1] is the number of instructions for the
1205      second alternative.
1206
1207      For non-relaxable macros, both elements give the number of
1208      instructions for the macro.  */
1209   unsigned int insns[2];
1210
1211   /* The first variant frag for this macro.  */
1212   fragS *first_frag;
1213 } mips_macro_warning;
1214 \f
1215 /* Prototypes for static functions.  */
1216
1217 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1218
1219 static void append_insn
1220   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1221    bfd_boolean expansionp);
1222 static void mips_no_prev_insn (void);
1223 static void macro_build (expressionS *, const char *, const char *, ...);
1224 static void mips16_macro_build
1225   (expressionS *, const char *, const char *, va_list *);
1226 static void load_register (int, expressionS *, int);
1227 static void macro_start (void);
1228 static void macro_end (void);
1229 static void macro (struct mips_cl_insn *ip, char *str);
1230 static void mips16_macro (struct mips_cl_insn * ip);
1231 static void mips_ip (char *str, struct mips_cl_insn * ip);
1232 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1233 static void mips16_immed
1234   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1235    unsigned int, unsigned long *);
1236 static size_t my_getSmallExpression
1237   (expressionS *, bfd_reloc_code_real_type *, char *);
1238 static void my_getExpression (expressionS *, char *);
1239 static void s_align (int);
1240 static void s_change_sec (int);
1241 static void s_change_section (int);
1242 static void s_cons (int);
1243 static void s_float_cons (int);
1244 static void s_mips_globl (int);
1245 static void s_option (int);
1246 static void s_mipsset (int);
1247 static void s_abicalls (int);
1248 static void s_cpload (int);
1249 static void s_cpsetup (int);
1250 static void s_cplocal (int);
1251 static void s_cprestore (int);
1252 static void s_cpreturn (int);
1253 static void s_dtprelword (int);
1254 static void s_dtpreldword (int);
1255 static void s_tprelword (int);
1256 static void s_tpreldword (int);
1257 static void s_gpvalue (int);
1258 static void s_gpword (int);
1259 static void s_gpdword (int);
1260 static void s_ehword (int);
1261 static void s_cpadd (int);
1262 static void s_insn (int);
1263 static void s_nan (int);
1264 static void md_obj_begin (void);
1265 static void md_obj_end (void);
1266 static void s_mips_ent (int);
1267 static void s_mips_end (int);
1268 static void s_mips_frame (int);
1269 static void s_mips_mask (int reg_type);
1270 static void s_mips_stab (int);
1271 static void s_mips_weakext (int);
1272 static void s_mips_file (int);
1273 static void s_mips_loc (int);
1274 static bfd_boolean pic_need_relax (symbolS *, asection *);
1275 static int relaxed_branch_length (fragS *, asection *, int);
1276 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1277 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1278
1279 /* Table and functions used to map between CPU/ISA names, and
1280    ISA levels, and CPU numbers.  */
1281
1282 struct mips_cpu_info
1283 {
1284   const char *name;           /* CPU or ISA name.  */
1285   int flags;                  /* MIPS_CPU_* flags.  */
1286   int ase;                    /* Set of ASEs implemented by the CPU.  */
1287   int isa;                    /* ISA level.  */
1288   int cpu;                    /* CPU number (default CPU if ISA).  */
1289 };
1290
1291 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1292
1293 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1294 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1295 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1296 \f
1297 /* Command-line options.  */
1298 const char *md_shortopts = "O::g::G:";
1299
1300 enum options
1301   {
1302     OPTION_MARCH = OPTION_MD_BASE,
1303     OPTION_MTUNE,
1304     OPTION_MIPS1,
1305     OPTION_MIPS2,
1306     OPTION_MIPS3,
1307     OPTION_MIPS4,
1308     OPTION_MIPS5,
1309     OPTION_MIPS32,
1310     OPTION_MIPS64,
1311     OPTION_MIPS32R2,
1312     OPTION_MIPS64R2,
1313     OPTION_MIPS16,
1314     OPTION_NO_MIPS16,
1315     OPTION_MIPS3D,
1316     OPTION_NO_MIPS3D,
1317     OPTION_MDMX,
1318     OPTION_NO_MDMX,
1319     OPTION_DSP,
1320     OPTION_NO_DSP,
1321     OPTION_MT,
1322     OPTION_NO_MT,
1323     OPTION_VIRT,
1324     OPTION_NO_VIRT,
1325     OPTION_SMARTMIPS,
1326     OPTION_NO_SMARTMIPS,
1327     OPTION_DSPR2,
1328     OPTION_NO_DSPR2,
1329     OPTION_EVA,
1330     OPTION_NO_EVA,
1331     OPTION_MICROMIPS,
1332     OPTION_NO_MICROMIPS,
1333     OPTION_MCU,
1334     OPTION_NO_MCU,
1335     OPTION_COMPAT_ARCH_BASE,
1336     OPTION_M4650,
1337     OPTION_NO_M4650,
1338     OPTION_M4010,
1339     OPTION_NO_M4010,
1340     OPTION_M4100,
1341     OPTION_NO_M4100,
1342     OPTION_M3900,
1343     OPTION_NO_M3900,
1344     OPTION_M7000_HILO_FIX,
1345     OPTION_MNO_7000_HILO_FIX,
1346     OPTION_FIX_24K,
1347     OPTION_NO_FIX_24K,
1348     OPTION_FIX_LOONGSON2F_JUMP,
1349     OPTION_NO_FIX_LOONGSON2F_JUMP,
1350     OPTION_FIX_LOONGSON2F_NOP,
1351     OPTION_NO_FIX_LOONGSON2F_NOP,
1352     OPTION_FIX_VR4120,
1353     OPTION_NO_FIX_VR4120,
1354     OPTION_FIX_VR4130,
1355     OPTION_NO_FIX_VR4130,
1356     OPTION_FIX_CN63XXP1,
1357     OPTION_NO_FIX_CN63XXP1,
1358     OPTION_TRAP,
1359     OPTION_BREAK,
1360     OPTION_EB,
1361     OPTION_EL,
1362     OPTION_FP32,
1363     OPTION_GP32,
1364     OPTION_CONSTRUCT_FLOATS,
1365     OPTION_NO_CONSTRUCT_FLOATS,
1366     OPTION_FP64,
1367     OPTION_GP64,
1368     OPTION_RELAX_BRANCH,
1369     OPTION_NO_RELAX_BRANCH,
1370     OPTION_INSN32,
1371     OPTION_NO_INSN32,
1372     OPTION_MSHARED,
1373     OPTION_MNO_SHARED,
1374     OPTION_MSYM32,
1375     OPTION_MNO_SYM32,
1376     OPTION_SOFT_FLOAT,
1377     OPTION_HARD_FLOAT,
1378     OPTION_SINGLE_FLOAT,
1379     OPTION_DOUBLE_FLOAT,
1380     OPTION_32,
1381     OPTION_CALL_SHARED,
1382     OPTION_CALL_NONPIC,
1383     OPTION_NON_SHARED,
1384     OPTION_XGOT,
1385     OPTION_MABI,
1386     OPTION_N32,
1387     OPTION_64,
1388     OPTION_MDEBUG,
1389     OPTION_NO_MDEBUG,
1390     OPTION_PDR,
1391     OPTION_NO_PDR,
1392     OPTION_MVXWORKS_PIC,
1393     OPTION_NAN,
1394     OPTION_END_OF_ENUM
1395   };
1396
1397 struct option md_longopts[] =
1398 {
1399   /* Options which specify architecture.  */
1400   {"march", required_argument, NULL, OPTION_MARCH},
1401   {"mtune", required_argument, NULL, OPTION_MTUNE},
1402   {"mips0", no_argument, NULL, OPTION_MIPS1},
1403   {"mips1", no_argument, NULL, OPTION_MIPS1},
1404   {"mips2", no_argument, NULL, OPTION_MIPS2},
1405   {"mips3", no_argument, NULL, OPTION_MIPS3},
1406   {"mips4", no_argument, NULL, OPTION_MIPS4},
1407   {"mips5", no_argument, NULL, OPTION_MIPS5},
1408   {"mips32", no_argument, NULL, OPTION_MIPS32},
1409   {"mips64", no_argument, NULL, OPTION_MIPS64},
1410   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1411   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1412
1413   /* Options which specify Application Specific Extensions (ASEs).  */
1414   {"mips16", no_argument, NULL, OPTION_MIPS16},
1415   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1416   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1417   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1418   {"mdmx", no_argument, NULL, OPTION_MDMX},
1419   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1420   {"mdsp", no_argument, NULL, OPTION_DSP},
1421   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1422   {"mmt", no_argument, NULL, OPTION_MT},
1423   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1424   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1425   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1426   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1427   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1428   {"meva", no_argument, NULL, OPTION_EVA},
1429   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1430   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1431   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1432   {"mmcu", no_argument, NULL, OPTION_MCU},
1433   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1434   {"mvirt", no_argument, NULL, OPTION_VIRT},
1435   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1436
1437   /* Old-style architecture options.  Don't add more of these.  */
1438   {"m4650", no_argument, NULL, OPTION_M4650},
1439   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1440   {"m4010", no_argument, NULL, OPTION_M4010},
1441   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1442   {"m4100", no_argument, NULL, OPTION_M4100},
1443   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1444   {"m3900", no_argument, NULL, OPTION_M3900},
1445   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1446
1447   /* Options which enable bug fixes.  */
1448   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1449   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1450   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1451   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1452   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1453   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1454   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1455   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1456   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1457   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1458   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1459   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1460   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1461   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1462   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1463
1464   /* Miscellaneous options.  */
1465   {"trap", no_argument, NULL, OPTION_TRAP},
1466   {"no-break", no_argument, NULL, OPTION_TRAP},
1467   {"break", no_argument, NULL, OPTION_BREAK},
1468   {"no-trap", no_argument, NULL, OPTION_BREAK},
1469   {"EB", no_argument, NULL, OPTION_EB},
1470   {"EL", no_argument, NULL, OPTION_EL},
1471   {"mfp32", no_argument, NULL, OPTION_FP32},
1472   {"mgp32", no_argument, NULL, OPTION_GP32},
1473   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1474   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1475   {"mfp64", no_argument, NULL, OPTION_FP64},
1476   {"mgp64", no_argument, NULL, OPTION_GP64},
1477   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1478   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1479   {"minsn32", no_argument, NULL, OPTION_INSN32},
1480   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1481   {"mshared", no_argument, NULL, OPTION_MSHARED},
1482   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1483   {"msym32", no_argument, NULL, OPTION_MSYM32},
1484   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1485   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1486   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1487   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1488   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1489
1490   /* Strictly speaking this next option is ELF specific,
1491      but we allow it for other ports as well in order to
1492      make testing easier.  */
1493   {"32", no_argument, NULL, OPTION_32},
1494
1495   /* ELF-specific options.  */
1496   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1497   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1498   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1499   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1500   {"xgot", no_argument, NULL, OPTION_XGOT},
1501   {"mabi", required_argument, NULL, OPTION_MABI},
1502   {"n32", no_argument, NULL, OPTION_N32},
1503   {"64", no_argument, NULL, OPTION_64},
1504   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1505   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1506   {"mpdr", no_argument, NULL, OPTION_PDR},
1507   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1508   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1509   {"mnan", required_argument, NULL, OPTION_NAN},
1510
1511   {NULL, no_argument, NULL, 0}
1512 };
1513 size_t md_longopts_size = sizeof (md_longopts);
1514 \f
1515 /* Information about either an Application Specific Extension or an
1516    optional architecture feature that, for simplicity, we treat in the
1517    same way as an ASE.  */
1518 struct mips_ase
1519 {
1520   /* The name of the ASE, used in both the command-line and .set options.  */
1521   const char *name;
1522
1523   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1524      and 64-bit architectures, the flags here refer to the subset that
1525      is available on both.  */
1526   unsigned int flags;
1527
1528   /* The ASE_* flag used for instructions that are available on 64-bit
1529      architectures but that are not included in FLAGS.  */
1530   unsigned int flags64;
1531
1532   /* The command-line options that turn the ASE on and off.  */
1533   int option_on;
1534   int option_off;
1535
1536   /* The minimum required architecture revisions for MIPS32, MIPS64,
1537      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1538   int mips32_rev;
1539   int mips64_rev;
1540   int micromips32_rev;
1541   int micromips64_rev;
1542 };
1543
1544 /* A table of all supported ASEs.  */
1545 static const struct mips_ase mips_ases[] = {
1546   { "dsp", ASE_DSP, ASE_DSP64,
1547     OPTION_DSP, OPTION_NO_DSP,
1548     2, 2, 2, 2 },
1549
1550   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1551     OPTION_DSPR2, OPTION_NO_DSPR2,
1552     2, 2, 2, 2 },
1553
1554   { "eva", ASE_EVA, 0,
1555     OPTION_EVA, OPTION_NO_EVA,
1556     2, 2, 2, 2 },
1557
1558   { "mcu", ASE_MCU, 0,
1559     OPTION_MCU, OPTION_NO_MCU,
1560     2, 2, 2, 2 },
1561
1562   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1563   { "mdmx", ASE_MDMX, 0,
1564     OPTION_MDMX, OPTION_NO_MDMX,
1565     -1, 1, -1, -1 },
1566
1567   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1568   { "mips3d", ASE_MIPS3D, 0,
1569     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1570     2, 1, -1, -1 },
1571
1572   { "mt", ASE_MT, 0,
1573     OPTION_MT, OPTION_NO_MT,
1574     2, 2, -1, -1 },
1575
1576   { "smartmips", ASE_SMARTMIPS, 0,
1577     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1578     1, -1, -1, -1 },
1579
1580   { "virt", ASE_VIRT, ASE_VIRT64,
1581     OPTION_VIRT, OPTION_NO_VIRT,
1582     2, 2, 2, 2 }
1583 };
1584
1585 /* The set of ASEs that require -mfp64.  */
1586 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1587
1588 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1589 static const unsigned int mips_ase_groups[] = {
1590   ASE_DSP | ASE_DSPR2
1591 };
1592 \f
1593 /* Pseudo-op table.
1594
1595    The following pseudo-ops from the Kane and Heinrich MIPS book
1596    should be defined here, but are currently unsupported: .alias,
1597    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1598
1599    The following pseudo-ops from the Kane and Heinrich MIPS book are
1600    specific to the type of debugging information being generated, and
1601    should be defined by the object format: .aent, .begin, .bend,
1602    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1603    .vreg.
1604
1605    The following pseudo-ops from the Kane and Heinrich MIPS book are
1606    not MIPS CPU specific, but are also not specific to the object file
1607    format.  This file is probably the best place to define them, but
1608    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1609
1610 static const pseudo_typeS mips_pseudo_table[] =
1611 {
1612   /* MIPS specific pseudo-ops.  */
1613   {"option", s_option, 0},
1614   {"set", s_mipsset, 0},
1615   {"rdata", s_change_sec, 'r'},
1616   {"sdata", s_change_sec, 's'},
1617   {"livereg", s_ignore, 0},
1618   {"abicalls", s_abicalls, 0},
1619   {"cpload", s_cpload, 0},
1620   {"cpsetup", s_cpsetup, 0},
1621   {"cplocal", s_cplocal, 0},
1622   {"cprestore", s_cprestore, 0},
1623   {"cpreturn", s_cpreturn, 0},
1624   {"dtprelword", s_dtprelword, 0},
1625   {"dtpreldword", s_dtpreldword, 0},
1626   {"tprelword", s_tprelword, 0},
1627   {"tpreldword", s_tpreldword, 0},
1628   {"gpvalue", s_gpvalue, 0},
1629   {"gpword", s_gpword, 0},
1630   {"gpdword", s_gpdword, 0},
1631   {"ehword", s_ehword, 0},
1632   {"cpadd", s_cpadd, 0},
1633   {"insn", s_insn, 0},
1634   {"nan", s_nan, 0},
1635
1636   /* Relatively generic pseudo-ops that happen to be used on MIPS
1637      chips.  */
1638   {"asciiz", stringer, 8 + 1},
1639   {"bss", s_change_sec, 'b'},
1640   {"err", s_err, 0},
1641   {"half", s_cons, 1},
1642   {"dword", s_cons, 3},
1643   {"weakext", s_mips_weakext, 0},
1644   {"origin", s_org, 0},
1645   {"repeat", s_rept, 0},
1646
1647   /* For MIPS this is non-standard, but we define it for consistency.  */
1648   {"sbss", s_change_sec, 'B'},
1649
1650   /* These pseudo-ops are defined in read.c, but must be overridden
1651      here for one reason or another.  */
1652   {"align", s_align, 0},
1653   {"byte", s_cons, 0},
1654   {"data", s_change_sec, 'd'},
1655   {"double", s_float_cons, 'd'},
1656   {"float", s_float_cons, 'f'},
1657   {"globl", s_mips_globl, 0},
1658   {"global", s_mips_globl, 0},
1659   {"hword", s_cons, 1},
1660   {"int", s_cons, 2},
1661   {"long", s_cons, 2},
1662   {"octa", s_cons, 4},
1663   {"quad", s_cons, 3},
1664   {"section", s_change_section, 0},
1665   {"short", s_cons, 1},
1666   {"single", s_float_cons, 'f'},
1667   {"stabd", s_mips_stab, 'd'},
1668   {"stabn", s_mips_stab, 'n'},
1669   {"stabs", s_mips_stab, 's'},
1670   {"text", s_change_sec, 't'},
1671   {"word", s_cons, 2},
1672
1673   { "extern", ecoff_directive_extern, 0},
1674
1675   { NULL, NULL, 0 },
1676 };
1677
1678 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1679 {
1680   /* These pseudo-ops should be defined by the object file format.
1681      However, a.out doesn't support them, so we have versions here.  */
1682   {"aent", s_mips_ent, 1},
1683   {"bgnb", s_ignore, 0},
1684   {"end", s_mips_end, 0},
1685   {"endb", s_ignore, 0},
1686   {"ent", s_mips_ent, 0},
1687   {"file", s_mips_file, 0},
1688   {"fmask", s_mips_mask, 'F'},
1689   {"frame", s_mips_frame, 0},
1690   {"loc", s_mips_loc, 0},
1691   {"mask", s_mips_mask, 'R'},
1692   {"verstamp", s_ignore, 0},
1693   { NULL, NULL, 0 },
1694 };
1695
1696 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1697    purpose of the `.dc.a' internal pseudo-op.  */
1698
1699 int
1700 mips_address_bytes (void)
1701 {
1702   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1703 }
1704
1705 extern void pop_insert (const pseudo_typeS *);
1706
1707 void
1708 mips_pop_insert (void)
1709 {
1710   pop_insert (mips_pseudo_table);
1711   if (! ECOFF_DEBUGGING)
1712     pop_insert (mips_nonecoff_pseudo_table);
1713 }
1714 \f
1715 /* Symbols labelling the current insn.  */
1716
1717 struct insn_label_list
1718 {
1719   struct insn_label_list *next;
1720   symbolS *label;
1721 };
1722
1723 static struct insn_label_list *free_insn_labels;
1724 #define label_list tc_segment_info_data.labels
1725
1726 static void mips_clear_insn_labels (void);
1727 static void mips_mark_labels (void);
1728 static void mips_compressed_mark_labels (void);
1729
1730 static inline void
1731 mips_clear_insn_labels (void)
1732 {
1733   register struct insn_label_list **pl;
1734   segment_info_type *si;
1735
1736   if (now_seg)
1737     {
1738       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1739         ;
1740       
1741       si = seg_info (now_seg);
1742       *pl = si->label_list;
1743       si->label_list = NULL;
1744     }
1745 }
1746
1747 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1748
1749 static inline void
1750 mips_mark_labels (void)
1751 {
1752   if (HAVE_CODE_COMPRESSION)
1753     mips_compressed_mark_labels ();
1754 }
1755 \f
1756 static char *expr_end;
1757
1758 /* Expressions which appear in macro instructions.  These are set by
1759    mips_ip and read by macro.  */
1760
1761 static expressionS imm_expr;
1762 static expressionS imm2_expr;
1763
1764 /* The relocatable field in an instruction and the relocs associated
1765    with it.  These variables are used for instructions like LUI and
1766    JAL as well as true offsets.  They are also used for address
1767    operands in macros.  */
1768
1769 static expressionS offset_expr;
1770 static bfd_reloc_code_real_type offset_reloc[3]
1771   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1772
1773 /* This is set to the resulting size of the instruction to be produced
1774    by mips16_ip if an explicit extension is used or by mips_ip if an
1775    explicit size is supplied.  */
1776
1777 static unsigned int forced_insn_length;
1778
1779 /* True if we are assembling an instruction.  All dot symbols defined during
1780    this time should be treated as code labels.  */
1781
1782 static bfd_boolean mips_assembling_insn;
1783
1784 /* The pdr segment for per procedure frame/regmask info.  Not used for
1785    ECOFF debugging.  */
1786
1787 static segT pdr_seg;
1788
1789 /* The default target format to use.  */
1790
1791 #if defined (TE_FreeBSD)
1792 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1793 #elif defined (TE_TMIPS)
1794 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1795 #else
1796 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1797 #endif
1798
1799 const char *
1800 mips_target_format (void)
1801 {
1802   switch (OUTPUT_FLAVOR)
1803     {
1804     case bfd_target_elf_flavour:
1805 #ifdef TE_VXWORKS
1806       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1807         return (target_big_endian
1808                 ? "elf32-bigmips-vxworks"
1809                 : "elf32-littlemips-vxworks");
1810 #endif
1811       return (target_big_endian
1812               ? (HAVE_64BIT_OBJECTS
1813                  ? ELF_TARGET ("elf64-", "big")
1814                  : (HAVE_NEWABI
1815                     ? ELF_TARGET ("elf32-n", "big")
1816                     : ELF_TARGET ("elf32-", "big")))
1817               : (HAVE_64BIT_OBJECTS
1818                  ? ELF_TARGET ("elf64-", "little")
1819                  : (HAVE_NEWABI
1820                     ? ELF_TARGET ("elf32-n", "little")
1821                     : ELF_TARGET ("elf32-", "little"))));
1822     default:
1823       abort ();
1824       return NULL;
1825     }
1826 }
1827
1828 /* Return the ISA revision that is currently in use, or 0 if we are
1829    generating code for MIPS V or below.  */
1830
1831 static int
1832 mips_isa_rev (void)
1833 {
1834   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1835     return 2;
1836
1837   /* microMIPS implies revision 2 or above.  */
1838   if (mips_opts.micromips)
1839     return 2;
1840
1841   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1842     return 1;
1843
1844   return 0;
1845 }
1846
1847 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1848
1849 static unsigned int
1850 mips_ase_mask (unsigned int flags)
1851 {
1852   unsigned int i;
1853
1854   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1855     if (flags & mips_ase_groups[i])
1856       flags |= mips_ase_groups[i];
1857   return flags;
1858 }
1859
1860 /* Check whether the current ISA supports ASE.  Issue a warning if
1861    appropriate.  */
1862
1863 static void
1864 mips_check_isa_supports_ase (const struct mips_ase *ase)
1865 {
1866   const char *base;
1867   int min_rev, size;
1868   static unsigned int warned_isa;
1869   static unsigned int warned_fp32;
1870
1871   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1872     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1873   else
1874     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1875   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1876       && (warned_isa & ase->flags) != ase->flags)
1877     {
1878       warned_isa |= ase->flags;
1879       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1880       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1881       if (min_rev < 0)
1882         as_warn (_("The %d-bit %s architecture does not support the"
1883                    " `%s' extension"), size, base, ase->name);
1884       else
1885         as_warn (_("The `%s' extension requires %s%d revision %d or greater"),
1886                  ase->name, base, size, min_rev);
1887     }
1888   if ((ase->flags & FP64_ASES)
1889       && mips_opts.fp32
1890       && (warned_fp32 & ase->flags) != ase->flags)
1891     {
1892       warned_fp32 |= ase->flags;
1893       as_warn (_("The `%s' extension requires 64-bit FPRs"), ase->name);
1894     }
1895 }
1896
1897 /* Check all enabled ASEs to see whether they are supported by the
1898    chosen architecture.  */
1899
1900 static void
1901 mips_check_isa_supports_ases (void)
1902 {
1903   unsigned int i, mask;
1904
1905   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1906     {
1907       mask = mips_ase_mask (mips_ases[i].flags);
1908       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1909         mips_check_isa_supports_ase (&mips_ases[i]);
1910     }
1911 }
1912
1913 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1914    that were affected.  */
1915
1916 static unsigned int
1917 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1918 {
1919   unsigned int mask;
1920
1921   mask = mips_ase_mask (ase->flags);
1922   mips_opts.ase &= ~mask;
1923   if (enabled_p)
1924     mips_opts.ase |= ase->flags;
1925   return mask;
1926 }
1927
1928 /* Return the ASE called NAME, or null if none.  */
1929
1930 static const struct mips_ase *
1931 mips_lookup_ase (const char *name)
1932 {
1933   unsigned int i;
1934
1935   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1936     if (strcmp (name, mips_ases[i].name) == 0)
1937       return &mips_ases[i];
1938   return NULL;
1939 }
1940
1941 /* Return the length of a microMIPS instruction in bytes.  If bits of
1942    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1943    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1944    major opcode) will require further modifications to the opcode
1945    table.  */
1946
1947 static inline unsigned int
1948 micromips_insn_length (const struct mips_opcode *mo)
1949 {
1950   return (mo->mask >> 16) == 0 ? 2 : 4;
1951 }
1952
1953 /* Return the length of MIPS16 instruction OPCODE.  */
1954
1955 static inline unsigned int
1956 mips16_opcode_length (unsigned long opcode)
1957 {
1958   return (opcode >> 16) == 0 ? 2 : 4;
1959 }
1960
1961 /* Return the length of instruction INSN.  */
1962
1963 static inline unsigned int
1964 insn_length (const struct mips_cl_insn *insn)
1965 {
1966   if (mips_opts.micromips)
1967     return micromips_insn_length (insn->insn_mo);
1968   else if (mips_opts.mips16)
1969     return mips16_opcode_length (insn->insn_opcode);
1970   else
1971     return 4;
1972 }
1973
1974 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1975
1976 static void
1977 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1978 {
1979   size_t i;
1980
1981   insn->insn_mo = mo;
1982   insn->insn_opcode = mo->match;
1983   insn->frag = NULL;
1984   insn->where = 0;
1985   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1986     insn->fixp[i] = NULL;
1987   insn->fixed_p = (mips_opts.noreorder > 0);
1988   insn->noreorder_p = (mips_opts.noreorder > 0);
1989   insn->mips16_absolute_jump_p = 0;
1990   insn->complete_p = 0;
1991   insn->cleared_p = 0;
1992 }
1993
1994 /* Install UVAL as the value of OPERAND in INSN.  */
1995
1996 static inline void
1997 insn_insert_operand (struct mips_cl_insn *insn,
1998                      const struct mips_operand *operand, unsigned int uval)
1999 {
2000   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2001 }
2002
2003 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2004
2005 static void
2006 mips_record_compressed_mode (void)
2007 {
2008   segment_info_type *si;
2009
2010   si = seg_info (now_seg);
2011   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2012     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2013   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2014     si->tc_segment_info_data.micromips = mips_opts.micromips;
2015 }
2016
2017 /* Read a standard MIPS instruction from BUF.  */
2018
2019 static unsigned long
2020 read_insn (char *buf)
2021 {
2022   if (target_big_endian)
2023     return bfd_getb32 ((bfd_byte *) buf);
2024   else
2025     return bfd_getl32 ((bfd_byte *) buf);
2026 }
2027
2028 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2029    the next byte.  */
2030
2031 static char *
2032 write_insn (char *buf, unsigned int insn)
2033 {
2034   md_number_to_chars (buf, insn, 4);
2035   return buf + 4;
2036 }
2037
2038 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2039    has length LENGTH.  */
2040
2041 static unsigned long
2042 read_compressed_insn (char *buf, unsigned int length)
2043 {
2044   unsigned long insn;
2045   unsigned int i;
2046
2047   insn = 0;
2048   for (i = 0; i < length; i += 2)
2049     {
2050       insn <<= 16;
2051       if (target_big_endian)
2052         insn |= bfd_getb16 ((char *) buf);
2053       else
2054         insn |= bfd_getl16 ((char *) buf);
2055       buf += 2;
2056     }
2057   return insn;
2058 }
2059
2060 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2061    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2062
2063 static char *
2064 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2065 {
2066   unsigned int i;
2067
2068   for (i = 0; i < length; i += 2)
2069     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2070   return buf + length;
2071 }
2072
2073 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2074
2075 static void
2076 install_insn (const struct mips_cl_insn *insn)
2077 {
2078   char *f = insn->frag->fr_literal + insn->where;
2079   if (HAVE_CODE_COMPRESSION)
2080     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2081   else
2082     write_insn (f, insn->insn_opcode);
2083   mips_record_compressed_mode ();
2084 }
2085
2086 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2087    and install the opcode in the new location.  */
2088
2089 static void
2090 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2091 {
2092   size_t i;
2093
2094   insn->frag = frag;
2095   insn->where = where;
2096   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2097     if (insn->fixp[i] != NULL)
2098       {
2099         insn->fixp[i]->fx_frag = frag;
2100         insn->fixp[i]->fx_where = where;
2101       }
2102   install_insn (insn);
2103 }
2104
2105 /* Add INSN to the end of the output.  */
2106
2107 static void
2108 add_fixed_insn (struct mips_cl_insn *insn)
2109 {
2110   char *f = frag_more (insn_length (insn));
2111   move_insn (insn, frag_now, f - frag_now->fr_literal);
2112 }
2113
2114 /* Start a variant frag and move INSN to the start of the variant part,
2115    marking it as fixed.  The other arguments are as for frag_var.  */
2116
2117 static void
2118 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2119                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2120 {
2121   frag_grow (max_chars);
2122   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2123   insn->fixed_p = 1;
2124   frag_var (rs_machine_dependent, max_chars, var,
2125             subtype, symbol, offset, NULL);
2126 }
2127
2128 /* Insert N copies of INSN into the history buffer, starting at
2129    position FIRST.  Neither FIRST nor N need to be clipped.  */
2130
2131 static void
2132 insert_into_history (unsigned int first, unsigned int n,
2133                      const struct mips_cl_insn *insn)
2134 {
2135   if (mips_relax.sequence != 2)
2136     {
2137       unsigned int i;
2138
2139       for (i = ARRAY_SIZE (history); i-- > first;)
2140         if (i >= first + n)
2141           history[i] = history[i - n];
2142         else
2143           history[i] = *insn;
2144     }
2145 }
2146
2147 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2148    the idea is to make it obvious at a glance that each errata is
2149    included.  */
2150
2151 static void
2152 init_vr4120_conflicts (void)
2153 {
2154 #define CONFLICT(FIRST, SECOND) \
2155     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2156
2157   /* Errata 21 - [D]DIV[U] after [D]MACC */
2158   CONFLICT (MACC, DIV);
2159   CONFLICT (DMACC, DIV);
2160
2161   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2162   CONFLICT (DMULT, DMULT);
2163   CONFLICT (DMULT, DMACC);
2164   CONFLICT (DMACC, DMULT);
2165   CONFLICT (DMACC, DMACC);
2166
2167   /* Errata 24 - MT{LO,HI} after [D]MACC */
2168   CONFLICT (MACC, MTHILO);
2169   CONFLICT (DMACC, MTHILO);
2170
2171   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2172      instruction is executed immediately after a MACC or DMACC
2173      instruction, the result of [either instruction] is incorrect."  */
2174   CONFLICT (MACC, MULT);
2175   CONFLICT (MACC, DMULT);
2176   CONFLICT (DMACC, MULT);
2177   CONFLICT (DMACC, DMULT);
2178
2179   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2180      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2181      DDIV or DDIVU instruction, the result of the MACC or
2182      DMACC instruction is incorrect.".  */
2183   CONFLICT (DMULT, MACC);
2184   CONFLICT (DMULT, DMACC);
2185   CONFLICT (DIV, MACC);
2186   CONFLICT (DIV, DMACC);
2187
2188 #undef CONFLICT
2189 }
2190
2191 struct regname {
2192   const char *name;
2193   unsigned int num;
2194 };
2195
2196 #define RTYPE_MASK      0x1ff00
2197 #define RTYPE_NUM       0x00100
2198 #define RTYPE_FPU       0x00200
2199 #define RTYPE_FCC       0x00400
2200 #define RTYPE_VEC       0x00800
2201 #define RTYPE_GP        0x01000
2202 #define RTYPE_CP0       0x02000
2203 #define RTYPE_PC        0x04000
2204 #define RTYPE_ACC       0x08000
2205 #define RTYPE_CCC       0x10000
2206 #define RNUM_MASK       0x000ff
2207 #define RWARN           0x80000
2208
2209 #define GENERIC_REGISTER_NUMBERS \
2210     {"$0",      RTYPE_NUM | 0},  \
2211     {"$1",      RTYPE_NUM | 1},  \
2212     {"$2",      RTYPE_NUM | 2},  \
2213     {"$3",      RTYPE_NUM | 3},  \
2214     {"$4",      RTYPE_NUM | 4},  \
2215     {"$5",      RTYPE_NUM | 5},  \
2216     {"$6",      RTYPE_NUM | 6},  \
2217     {"$7",      RTYPE_NUM | 7},  \
2218     {"$8",      RTYPE_NUM | 8},  \
2219     {"$9",      RTYPE_NUM | 9},  \
2220     {"$10",     RTYPE_NUM | 10}, \
2221     {"$11",     RTYPE_NUM | 11}, \
2222     {"$12",     RTYPE_NUM | 12}, \
2223     {"$13",     RTYPE_NUM | 13}, \
2224     {"$14",     RTYPE_NUM | 14}, \
2225     {"$15",     RTYPE_NUM | 15}, \
2226     {"$16",     RTYPE_NUM | 16}, \
2227     {"$17",     RTYPE_NUM | 17}, \
2228     {"$18",     RTYPE_NUM | 18}, \
2229     {"$19",     RTYPE_NUM | 19}, \
2230     {"$20",     RTYPE_NUM | 20}, \
2231     {"$21",     RTYPE_NUM | 21}, \
2232     {"$22",     RTYPE_NUM | 22}, \
2233     {"$23",     RTYPE_NUM | 23}, \
2234     {"$24",     RTYPE_NUM | 24}, \
2235     {"$25",     RTYPE_NUM | 25}, \
2236     {"$26",     RTYPE_NUM | 26}, \
2237     {"$27",     RTYPE_NUM | 27}, \
2238     {"$28",     RTYPE_NUM | 28}, \
2239     {"$29",     RTYPE_NUM | 29}, \
2240     {"$30",     RTYPE_NUM | 30}, \
2241     {"$31",     RTYPE_NUM | 31} 
2242
2243 #define FPU_REGISTER_NAMES       \
2244     {"$f0",     RTYPE_FPU | 0},  \
2245     {"$f1",     RTYPE_FPU | 1},  \
2246     {"$f2",     RTYPE_FPU | 2},  \
2247     {"$f3",     RTYPE_FPU | 3},  \
2248     {"$f4",     RTYPE_FPU | 4},  \
2249     {"$f5",     RTYPE_FPU | 5},  \
2250     {"$f6",     RTYPE_FPU | 6},  \
2251     {"$f7",     RTYPE_FPU | 7},  \
2252     {"$f8",     RTYPE_FPU | 8},  \
2253     {"$f9",     RTYPE_FPU | 9},  \
2254     {"$f10",    RTYPE_FPU | 10}, \
2255     {"$f11",    RTYPE_FPU | 11}, \
2256     {"$f12",    RTYPE_FPU | 12}, \
2257     {"$f13",    RTYPE_FPU | 13}, \
2258     {"$f14",    RTYPE_FPU | 14}, \
2259     {"$f15",    RTYPE_FPU | 15}, \
2260     {"$f16",    RTYPE_FPU | 16}, \
2261     {"$f17",    RTYPE_FPU | 17}, \
2262     {"$f18",    RTYPE_FPU | 18}, \
2263     {"$f19",    RTYPE_FPU | 19}, \
2264     {"$f20",    RTYPE_FPU | 20}, \
2265     {"$f21",    RTYPE_FPU | 21}, \
2266     {"$f22",    RTYPE_FPU | 22}, \
2267     {"$f23",    RTYPE_FPU | 23}, \
2268     {"$f24",    RTYPE_FPU | 24}, \
2269     {"$f25",    RTYPE_FPU | 25}, \
2270     {"$f26",    RTYPE_FPU | 26}, \
2271     {"$f27",    RTYPE_FPU | 27}, \
2272     {"$f28",    RTYPE_FPU | 28}, \
2273     {"$f29",    RTYPE_FPU | 29}, \
2274     {"$f30",    RTYPE_FPU | 30}, \
2275     {"$f31",    RTYPE_FPU | 31}
2276
2277 #define FPU_CONDITION_CODE_NAMES \
2278     {"$fcc0",   RTYPE_FCC | 0},  \
2279     {"$fcc1",   RTYPE_FCC | 1},  \
2280     {"$fcc2",   RTYPE_FCC | 2},  \
2281     {"$fcc3",   RTYPE_FCC | 3},  \
2282     {"$fcc4",   RTYPE_FCC | 4},  \
2283     {"$fcc5",   RTYPE_FCC | 5},  \
2284     {"$fcc6",   RTYPE_FCC | 6},  \
2285     {"$fcc7",   RTYPE_FCC | 7}
2286
2287 #define COPROC_CONDITION_CODE_NAMES         \
2288     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2289     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2290     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2291     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2292     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2293     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2294     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2295     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2296
2297 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2298     {"$a4",     RTYPE_GP | 8},  \
2299     {"$a5",     RTYPE_GP | 9},  \
2300     {"$a6",     RTYPE_GP | 10}, \
2301     {"$a7",     RTYPE_GP | 11}, \
2302     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2303     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2304     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2305     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2306     {"$t0",     RTYPE_GP | 12}, \
2307     {"$t1",     RTYPE_GP | 13}, \
2308     {"$t2",     RTYPE_GP | 14}, \
2309     {"$t3",     RTYPE_GP | 15}
2310
2311 #define O32_SYMBOLIC_REGISTER_NAMES \
2312     {"$t0",     RTYPE_GP | 8},  \
2313     {"$t1",     RTYPE_GP | 9},  \
2314     {"$t2",     RTYPE_GP | 10}, \
2315     {"$t3",     RTYPE_GP | 11}, \
2316     {"$t4",     RTYPE_GP | 12}, \
2317     {"$t5",     RTYPE_GP | 13}, \
2318     {"$t6",     RTYPE_GP | 14}, \
2319     {"$t7",     RTYPE_GP | 15}, \
2320     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2321     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2322     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2323     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2324
2325 /* Remaining symbolic register names */
2326 #define SYMBOLIC_REGISTER_NAMES \
2327     {"$zero",   RTYPE_GP | 0},  \
2328     {"$at",     RTYPE_GP | 1},  \
2329     {"$AT",     RTYPE_GP | 1},  \
2330     {"$v0",     RTYPE_GP | 2},  \
2331     {"$v1",     RTYPE_GP | 3},  \
2332     {"$a0",     RTYPE_GP | 4},  \
2333     {"$a1",     RTYPE_GP | 5},  \
2334     {"$a2",     RTYPE_GP | 6},  \
2335     {"$a3",     RTYPE_GP | 7},  \
2336     {"$s0",     RTYPE_GP | 16}, \
2337     {"$s1",     RTYPE_GP | 17}, \
2338     {"$s2",     RTYPE_GP | 18}, \
2339     {"$s3",     RTYPE_GP | 19}, \
2340     {"$s4",     RTYPE_GP | 20}, \
2341     {"$s5",     RTYPE_GP | 21}, \
2342     {"$s6",     RTYPE_GP | 22}, \
2343     {"$s7",     RTYPE_GP | 23}, \
2344     {"$t8",     RTYPE_GP | 24}, \
2345     {"$t9",     RTYPE_GP | 25}, \
2346     {"$k0",     RTYPE_GP | 26}, \
2347     {"$kt0",    RTYPE_GP | 26}, \
2348     {"$k1",     RTYPE_GP | 27}, \
2349     {"$kt1",    RTYPE_GP | 27}, \
2350     {"$gp",     RTYPE_GP | 28}, \
2351     {"$sp",     RTYPE_GP | 29}, \
2352     {"$s8",     RTYPE_GP | 30}, \
2353     {"$fp",     RTYPE_GP | 30}, \
2354     {"$ra",     RTYPE_GP | 31}
2355
2356 #define MIPS16_SPECIAL_REGISTER_NAMES \
2357     {"$pc",     RTYPE_PC | 0}
2358
2359 #define MDMX_VECTOR_REGISTER_NAMES \
2360     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2361     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2362     {"$v2",     RTYPE_VEC | 2},  \
2363     {"$v3",     RTYPE_VEC | 3},  \
2364     {"$v4",     RTYPE_VEC | 4},  \
2365     {"$v5",     RTYPE_VEC | 5},  \
2366     {"$v6",     RTYPE_VEC | 6},  \
2367     {"$v7",     RTYPE_VEC | 7},  \
2368     {"$v8",     RTYPE_VEC | 8},  \
2369     {"$v9",     RTYPE_VEC | 9},  \
2370     {"$v10",    RTYPE_VEC | 10}, \
2371     {"$v11",    RTYPE_VEC | 11}, \
2372     {"$v12",    RTYPE_VEC | 12}, \
2373     {"$v13",    RTYPE_VEC | 13}, \
2374     {"$v14",    RTYPE_VEC | 14}, \
2375     {"$v15",    RTYPE_VEC | 15}, \
2376     {"$v16",    RTYPE_VEC | 16}, \
2377     {"$v17",    RTYPE_VEC | 17}, \
2378     {"$v18",    RTYPE_VEC | 18}, \
2379     {"$v19",    RTYPE_VEC | 19}, \
2380     {"$v20",    RTYPE_VEC | 20}, \
2381     {"$v21",    RTYPE_VEC | 21}, \
2382     {"$v22",    RTYPE_VEC | 22}, \
2383     {"$v23",    RTYPE_VEC | 23}, \
2384     {"$v24",    RTYPE_VEC | 24}, \
2385     {"$v25",    RTYPE_VEC | 25}, \
2386     {"$v26",    RTYPE_VEC | 26}, \
2387     {"$v27",    RTYPE_VEC | 27}, \
2388     {"$v28",    RTYPE_VEC | 28}, \
2389     {"$v29",    RTYPE_VEC | 29}, \
2390     {"$v30",    RTYPE_VEC | 30}, \
2391     {"$v31",    RTYPE_VEC | 31}
2392
2393 #define MIPS_DSP_ACCUMULATOR_NAMES \
2394     {"$ac0",    RTYPE_ACC | 0}, \
2395     {"$ac1",    RTYPE_ACC | 1}, \
2396     {"$ac2",    RTYPE_ACC | 2}, \
2397     {"$ac3",    RTYPE_ACC | 3}
2398
2399 static const struct regname reg_names[] = {
2400   GENERIC_REGISTER_NUMBERS,
2401   FPU_REGISTER_NAMES,
2402   FPU_CONDITION_CODE_NAMES,
2403   COPROC_CONDITION_CODE_NAMES,
2404
2405   /* The $txx registers depends on the abi,
2406      these will be added later into the symbol table from
2407      one of the tables below once mips_abi is set after 
2408      parsing of arguments from the command line. */
2409   SYMBOLIC_REGISTER_NAMES,
2410
2411   MIPS16_SPECIAL_REGISTER_NAMES,
2412   MDMX_VECTOR_REGISTER_NAMES,
2413   MIPS_DSP_ACCUMULATOR_NAMES,
2414   {0, 0}
2415 };
2416
2417 static const struct regname reg_names_o32[] = {
2418   O32_SYMBOLIC_REGISTER_NAMES,
2419   {0, 0}
2420 };
2421
2422 static const struct regname reg_names_n32n64[] = {
2423   N32N64_SYMBOLIC_REGISTER_NAMES,
2424   {0, 0}
2425 };
2426
2427 /* Check if S points at a valid register specifier according to TYPES.
2428    If so, then return 1, advance S to consume the specifier and store
2429    the register's number in REGNOP, otherwise return 0.  */
2430
2431 static int
2432 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2433 {
2434   symbolS *symbolP;
2435   char *e;
2436   char save_c;
2437   int reg = -1;
2438
2439   /* Find end of name.  */
2440   e = *s;
2441   if (is_name_beginner (*e))
2442     ++e;
2443   while (is_part_of_name (*e))
2444     ++e;
2445
2446   /* Terminate name.  */
2447   save_c = *e;
2448   *e = '\0';
2449
2450   /* Look for a register symbol.  */
2451   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2452     {
2453       int r = S_GET_VALUE (symbolP);
2454       if (r & types)
2455         reg = r & RNUM_MASK;
2456       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2457         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2458         reg = (r & RNUM_MASK) - 2;
2459     }
2460   /* Else see if this is a register defined in an itbl entry.  */
2461   else if ((types & RTYPE_GP) && itbl_have_entries)
2462     {
2463       char *n = *s;
2464       unsigned long r;
2465
2466       if (*n == '$')
2467         ++n;
2468       if (itbl_get_reg_val (n, &r))
2469         reg = r & RNUM_MASK;
2470     }
2471
2472   /* Advance to next token if a register was recognised.  */
2473   if (reg >= 0)
2474     *s = e;
2475   else if (types & RWARN)
2476     as_warn (_("Unrecognized register name `%s'"), *s);
2477
2478   *e = save_c;
2479   if (regnop)
2480     *regnop = reg;
2481   return reg >= 0;
2482 }
2483
2484 /* Check if S points at a valid register list according to TYPES.
2485    If so, then return 1, advance S to consume the list and store
2486    the registers present on the list as a bitmask of ones in REGLISTP,
2487    otherwise return 0.  A valid list comprises a comma-separated
2488    enumeration of valid single registers and/or dash-separated
2489    contiguous register ranges as determined by their numbers.
2490
2491    As a special exception if one of s0-s7 registers is specified as
2492    the range's lower delimiter and s8 (fp) is its upper one, then no
2493    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2494    are selected; they have to be listed separately if needed.  */
2495
2496 static int
2497 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2498 {
2499   unsigned int reglist = 0;
2500   unsigned int lastregno;
2501   bfd_boolean ok = TRUE;
2502   unsigned int regmask;
2503   char *s_endlist = *s;
2504   char *s_reset = *s;
2505   unsigned int regno;
2506
2507   while (reg_lookup (s, types, &regno))
2508     {
2509       lastregno = regno;
2510       if (**s == '-')
2511         {
2512           (*s)++;
2513           ok = reg_lookup (s, types, &lastregno);
2514           if (ok && lastregno < regno)
2515             ok = FALSE;
2516           if (!ok)
2517             break;
2518         }
2519
2520       if (lastregno == FP && regno >= S0 && regno <= S7)
2521         {
2522           lastregno = S7;
2523           reglist |= 1 << FP;
2524         }
2525       regmask = 1 << lastregno;
2526       regmask = (regmask << 1) - 1;
2527       regmask ^= (1 << regno) - 1;
2528       reglist |= regmask;
2529
2530       s_endlist = *s;
2531       if (**s != ',')
2532         break;
2533       (*s)++;
2534     }
2535
2536   if (ok)
2537     *s = s_endlist;
2538   else
2539     *s = s_reset;
2540   if (reglistp)
2541     *reglistp = reglist;
2542   return ok && reglist != 0;
2543 }
2544
2545 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
2546    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2547
2548 static bfd_boolean
2549 is_opcode_valid (const struct mips_opcode *mo)
2550 {
2551   int isa = mips_opts.isa;
2552   int ase = mips_opts.ase;
2553   int fp_s, fp_d;
2554   unsigned int i;
2555
2556   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2557     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2558       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
2559         ase |= mips_ases[i].flags64;
2560
2561   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
2562     return FALSE;
2563
2564   /* Check whether the instruction or macro requires single-precision or
2565      double-precision floating-point support.  Note that this information is
2566      stored differently in the opcode table for insns and macros.  */
2567   if (mo->pinfo == INSN_MACRO)
2568     {
2569       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2570       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2571     }
2572   else
2573     {
2574       fp_s = mo->pinfo & FP_S;
2575       fp_d = mo->pinfo & FP_D;
2576     }
2577
2578   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2579     return FALSE;
2580
2581   if (fp_s && mips_opts.soft_float)
2582     return FALSE;
2583
2584   return TRUE;
2585 }
2586
2587 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2588    selected ISA and architecture.  */
2589
2590 static bfd_boolean
2591 is_opcode_valid_16 (const struct mips_opcode *mo)
2592 {
2593   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
2594 }
2595
2596 /* Return TRUE if the size of the microMIPS opcode MO matches one
2597    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2598
2599 static bfd_boolean
2600 is_size_valid (const struct mips_opcode *mo)
2601 {
2602   if (!mips_opts.micromips)
2603     return TRUE;
2604
2605   if (mips_opts.insn32)
2606     {
2607       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
2608         return FALSE;
2609       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
2610         return FALSE;
2611     }
2612   if (!forced_insn_length)
2613     return TRUE;
2614   if (mo->pinfo == INSN_MACRO)
2615     return FALSE;
2616   return forced_insn_length == micromips_insn_length (mo);
2617 }
2618
2619 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2620    of the preceding instruction.  Always TRUE in the standard MIPS mode.
2621
2622    We don't accept macros in 16-bit delay slots to avoid a case where
2623    a macro expansion fails because it relies on a preceding 32-bit real
2624    instruction to have matched and does not handle the operands correctly.
2625    The only macros that may expand to 16-bit instructions are JAL that
2626    cannot be placed in a delay slot anyway, and corner cases of BALIGN
2627    and BGT (that likewise cannot be placed in a delay slot) that decay to
2628    a NOP.  In all these cases the macros precede any corresponding real
2629    instruction definitions in the opcode table, so they will match in the
2630    second pass where the size of the delay slot is ignored and therefore
2631    produce correct code.  */
2632
2633 static bfd_boolean
2634 is_delay_slot_valid (const struct mips_opcode *mo)
2635 {
2636   if (!mips_opts.micromips)
2637     return TRUE;
2638
2639   if (mo->pinfo == INSN_MACRO)
2640     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
2641   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2642       && micromips_insn_length (mo) != 4)
2643     return FALSE;
2644   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2645       && micromips_insn_length (mo) != 2)
2646     return FALSE;
2647
2648   return TRUE;
2649 }
2650
2651 /* For consistency checking, verify that all bits of OPCODE are
2652    specified either by the match/mask part of the instruction
2653    definition, or by the operand list.  INSN_BITS says which
2654    bits of the instruction are significant and DECODE_OPERAND
2655    provides the mips_operand description of each operand.  */
2656
2657 static int
2658 validate_mips_insn (const struct mips_opcode *opcode,
2659                     unsigned long insn_bits,
2660                     const struct mips_operand *(*decode_operand) (const char *))
2661 {
2662   const char *s;
2663   unsigned long used_bits, doubled, undefined;
2664   const struct mips_operand *operand;
2665
2666   if ((opcode->mask & opcode->match) != opcode->match)
2667     {
2668       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
2669               opcode->name, opcode->args);
2670       return 0;
2671     }
2672   used_bits = 0;
2673   for (s = opcode->args; *s; ++s)
2674     switch (*s)
2675       {
2676       case ',':
2677       case '(':
2678       case ')':
2679         break;
2680
2681       default:
2682         operand = decode_operand (s);
2683         if (!operand)
2684           {
2685             as_bad (_("internal: unknown operand type: %s %s"),
2686                     opcode->name, opcode->args);
2687             return 0;
2688           }
2689         used_bits |= ((1 << operand->size) - 1) << operand->lsb;
2690         if (operand->type == OP_MDMX_IMM_REG)
2691           /* Bit 5 is the format selector (OB vs QH).  The opcode table
2692              has separate entries for each format.  */
2693           used_bits &= ~(1 << (operand->lsb + 5));
2694         /* Skip prefix characters.  */
2695         if (*s == '+' || *s == 'm')
2696           ++s;
2697         break;
2698       }
2699   doubled = used_bits & opcode->mask & insn_bits;
2700   if (doubled)
2701     {
2702       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
2703                 " %s %s"), doubled, opcode->name, opcode->args);
2704       return 0;
2705     }
2706   used_bits |= opcode->mask;
2707   undefined = ~used_bits & insn_bits;
2708   if (undefined)
2709     {
2710       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
2711               undefined, opcode->name, opcode->args);
2712       return 0;
2713     }
2714   used_bits &= ~insn_bits;
2715   if (used_bits)
2716     {
2717       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
2718               used_bits, opcode->name, opcode->args);
2719       return 0;
2720     }
2721   return 1;
2722 }
2723
2724 /* The microMIPS version of validate_mips_insn.  */
2725
2726 static int
2727 validate_micromips_insn (const struct mips_opcode *opc)
2728 {
2729   unsigned long insn_bits;
2730   unsigned long major;
2731   unsigned int length;
2732
2733   length = micromips_insn_length (opc);
2734   if (length != 2 && length != 4)
2735     {
2736       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
2737                 "%s %s"), length, opc->name, opc->args);
2738       return 0;
2739     }
2740   major = opc->match >> (10 + 8 * (length - 2));
2741   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
2742       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
2743     {
2744       as_bad (_("Internal error: bad microMIPS opcode "
2745                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
2746       return 0;
2747     }
2748
2749   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
2750   insn_bits = 1 << 4 * length;
2751   insn_bits <<= 4 * length;
2752   insn_bits -= 1;
2753   return validate_mips_insn (opc, insn_bits, decode_micromips_operand);
2754 }
2755
2756 /* This function is called once, at assembler startup time.  It should set up
2757    all the tables, etc. that the MD part of the assembler will need.  */
2758
2759 void
2760 md_begin (void)
2761 {
2762   const char *retval = NULL;
2763   int i = 0;
2764   int broken = 0;
2765
2766   if (mips_pic != NO_PIC)
2767     {
2768       if (g_switch_seen && g_switch_value != 0)
2769         as_bad (_("-G may not be used in position-independent code"));
2770       g_switch_value = 0;
2771     }
2772
2773   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2774     as_warn (_("Could not set architecture and machine"));
2775
2776   op_hash = hash_new ();
2777
2778   for (i = 0; i < NUMOPCODES;)
2779     {
2780       const char *name = mips_opcodes[i].name;
2781
2782       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2783       if (retval != NULL)
2784         {
2785           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2786                    mips_opcodes[i].name, retval);
2787           /* Probably a memory allocation problem?  Give up now.  */
2788           as_fatal (_("Broken assembler.  No assembly attempted."));
2789         }
2790       do
2791         {
2792           if (mips_opcodes[i].pinfo != INSN_MACRO)
2793             {
2794               if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
2795                                        decode_mips_operand))
2796                 broken = 1;
2797               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2798                 {
2799                   create_insn (&nop_insn, mips_opcodes + i);
2800                   if (mips_fix_loongson2f_nop)
2801                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2802                   nop_insn.fixed_p = 1;
2803                 }
2804             }
2805           ++i;
2806         }
2807       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2808     }
2809
2810   mips16_op_hash = hash_new ();
2811
2812   i = 0;
2813   while (i < bfd_mips16_num_opcodes)
2814     {
2815       const char *name = mips16_opcodes[i].name;
2816
2817       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2818       if (retval != NULL)
2819         as_fatal (_("internal: can't hash `%s': %s"),
2820                   mips16_opcodes[i].name, retval);
2821       do
2822         {
2823           if (mips16_opcodes[i].pinfo != INSN_MACRO
2824               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2825                   != mips16_opcodes[i].match))
2826             {
2827               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2828                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2829               broken = 1;
2830             }
2831           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2832             {
2833               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2834               mips16_nop_insn.fixed_p = 1;
2835             }
2836           ++i;
2837         }
2838       while (i < bfd_mips16_num_opcodes
2839              && strcmp (mips16_opcodes[i].name, name) == 0);
2840     }
2841
2842   micromips_op_hash = hash_new ();
2843
2844   i = 0;
2845   while (i < bfd_micromips_num_opcodes)
2846     {
2847       const char *name = micromips_opcodes[i].name;
2848
2849       retval = hash_insert (micromips_op_hash, name,
2850                             (void *) &micromips_opcodes[i]);
2851       if (retval != NULL)
2852         as_fatal (_("internal: can't hash `%s': %s"),
2853                   micromips_opcodes[i].name, retval);
2854       do
2855         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2856           {
2857             struct mips_cl_insn *micromips_nop_insn;
2858
2859             if (!validate_micromips_insn (&micromips_opcodes[i]))
2860               broken = 1;
2861
2862             if (micromips_insn_length (micromips_opcodes + i) == 2)
2863               micromips_nop_insn = &micromips_nop16_insn;
2864             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2865               micromips_nop_insn = &micromips_nop32_insn;
2866             else
2867               continue;
2868
2869             if (micromips_nop_insn->insn_mo == NULL
2870                 && strcmp (name, "nop") == 0)
2871               {
2872                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2873                 micromips_nop_insn->fixed_p = 1;
2874               }
2875           }
2876       while (++i < bfd_micromips_num_opcodes
2877              && strcmp (micromips_opcodes[i].name, name) == 0);
2878     }
2879
2880   if (broken)
2881     as_fatal (_("Broken assembler.  No assembly attempted."));
2882
2883   /* We add all the general register names to the symbol table.  This
2884      helps us detect invalid uses of them.  */
2885   for (i = 0; reg_names[i].name; i++) 
2886     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2887                                      reg_names[i].num, /* & RNUM_MASK, */
2888                                      &zero_address_frag));
2889   if (HAVE_NEWABI)
2890     for (i = 0; reg_names_n32n64[i].name; i++) 
2891       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2892                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2893                                        &zero_address_frag));
2894   else
2895     for (i = 0; reg_names_o32[i].name; i++) 
2896       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2897                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2898                                        &zero_address_frag));
2899
2900   mips_no_prev_insn ();
2901
2902   mips_gprmask = 0;
2903   mips_cprmask[0] = 0;
2904   mips_cprmask[1] = 0;
2905   mips_cprmask[2] = 0;
2906   mips_cprmask[3] = 0;
2907
2908   /* set the default alignment for the text section (2**2) */
2909   record_alignment (text_section, 2);
2910
2911   bfd_set_gp_size (stdoutput, g_switch_value);
2912
2913   /* On a native system other than VxWorks, sections must be aligned
2914      to 16 byte boundaries.  When configured for an embedded ELF
2915      target, we don't bother.  */
2916   if (strncmp (TARGET_OS, "elf", 3) != 0
2917       && strncmp (TARGET_OS, "vxworks", 7) != 0)
2918     {
2919       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2920       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2921       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2922     }
2923
2924   /* Create a .reginfo section for register masks and a .mdebug
2925      section for debugging information.  */
2926   {
2927     segT seg;
2928     subsegT subseg;
2929     flagword flags;
2930     segT sec;
2931
2932     seg = now_seg;
2933     subseg = now_subseg;
2934
2935     /* The ABI says this section should be loaded so that the
2936        running program can access it.  However, we don't load it
2937        if we are configured for an embedded target */
2938     flags = SEC_READONLY | SEC_DATA;
2939     if (strncmp (TARGET_OS, "elf", 3) != 0)
2940       flags |= SEC_ALLOC | SEC_LOAD;
2941
2942     if (mips_abi != N64_ABI)
2943       {
2944         sec = subseg_new (".reginfo", (subsegT) 0);
2945
2946         bfd_set_section_flags (stdoutput, sec, flags);
2947         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
2948
2949         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
2950       }
2951     else
2952       {
2953         /* The 64-bit ABI uses a .MIPS.options section rather than
2954            .reginfo section.  */
2955         sec = subseg_new (".MIPS.options", (subsegT) 0);
2956         bfd_set_section_flags (stdoutput, sec, flags);
2957         bfd_set_section_alignment (stdoutput, sec, 3);
2958
2959         /* Set up the option header.  */
2960         {
2961           Elf_Internal_Options opthdr;
2962           char *f;
2963
2964           opthdr.kind = ODK_REGINFO;
2965           opthdr.size = (sizeof (Elf_External_Options)
2966                          + sizeof (Elf64_External_RegInfo));
2967           opthdr.section = 0;
2968           opthdr.info = 0;
2969           f = frag_more (sizeof (Elf_External_Options));
2970           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
2971                                          (Elf_External_Options *) f);
2972
2973           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
2974         }
2975       }
2976
2977     if (ECOFF_DEBUGGING)
2978       {
2979         sec = subseg_new (".mdebug", (subsegT) 0);
2980         (void) bfd_set_section_flags (stdoutput, sec,
2981                                       SEC_HAS_CONTENTS | SEC_READONLY);
2982         (void) bfd_set_section_alignment (stdoutput, sec, 2);
2983       }
2984     else if (mips_flag_pdr)
2985       {
2986         pdr_seg = subseg_new (".pdr", (subsegT) 0);
2987         (void) bfd_set_section_flags (stdoutput, pdr_seg,
2988                                       SEC_READONLY | SEC_RELOC
2989                                       | SEC_DEBUGGING);
2990         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
2991       }
2992
2993     subseg_set (seg, subseg);
2994   }
2995
2996   if (! ECOFF_DEBUGGING)
2997     md_obj_begin ();
2998
2999   if (mips_fix_vr4120)
3000     init_vr4120_conflicts ();
3001 }
3002
3003 void
3004 md_mips_end (void)
3005 {
3006   mips_emit_delays ();
3007   if (! ECOFF_DEBUGGING)
3008     md_obj_end ();
3009 }
3010
3011 void
3012 md_assemble (char *str)
3013 {
3014   struct mips_cl_insn insn;
3015   bfd_reloc_code_real_type unused_reloc[3]
3016     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3017
3018   imm_expr.X_op = O_absent;
3019   imm2_expr.X_op = O_absent;
3020   offset_expr.X_op = O_absent;
3021   offset_reloc[0] = BFD_RELOC_UNUSED;
3022   offset_reloc[1] = BFD_RELOC_UNUSED;
3023   offset_reloc[2] = BFD_RELOC_UNUSED;
3024
3025   mips_mark_labels ();
3026   mips_assembling_insn = TRUE;
3027
3028   if (mips_opts.mips16)
3029     mips16_ip (str, &insn);
3030   else
3031     {
3032       mips_ip (str, &insn);
3033       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3034             str, insn.insn_opcode));
3035     }
3036
3037   if (insn_error)
3038     as_bad ("%s `%s'", insn_error, str);
3039   else if (insn.insn_mo->pinfo == INSN_MACRO)
3040     {
3041       macro_start ();
3042       if (mips_opts.mips16)
3043         mips16_macro (&insn);
3044       else
3045         macro (&insn, str);
3046       macro_end ();
3047     }
3048   else
3049     {
3050       if (offset_expr.X_op != O_absent)
3051         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3052       else
3053         append_insn (&insn, NULL, unused_reloc, FALSE);
3054     }
3055
3056   mips_assembling_insn = FALSE;
3057 }
3058
3059 /* Convenience functions for abstracting away the differences between
3060    MIPS16 and non-MIPS16 relocations.  */
3061
3062 static inline bfd_boolean
3063 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3064 {
3065   switch (reloc)
3066     {
3067     case BFD_RELOC_MIPS16_JMP:
3068     case BFD_RELOC_MIPS16_GPREL:
3069     case BFD_RELOC_MIPS16_GOT16:
3070     case BFD_RELOC_MIPS16_CALL16:
3071     case BFD_RELOC_MIPS16_HI16_S:
3072     case BFD_RELOC_MIPS16_HI16:
3073     case BFD_RELOC_MIPS16_LO16:
3074       return TRUE;
3075
3076     default:
3077       return FALSE;
3078     }
3079 }
3080
3081 static inline bfd_boolean
3082 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3083 {
3084   switch (reloc)
3085     {
3086     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3087     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3088     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3089     case BFD_RELOC_MICROMIPS_GPREL16:
3090     case BFD_RELOC_MICROMIPS_JMP:
3091     case BFD_RELOC_MICROMIPS_HI16:
3092     case BFD_RELOC_MICROMIPS_HI16_S:
3093     case BFD_RELOC_MICROMIPS_LO16:
3094     case BFD_RELOC_MICROMIPS_LITERAL:
3095     case BFD_RELOC_MICROMIPS_GOT16:
3096     case BFD_RELOC_MICROMIPS_CALL16:
3097     case BFD_RELOC_MICROMIPS_GOT_HI16:
3098     case BFD_RELOC_MICROMIPS_GOT_LO16:
3099     case BFD_RELOC_MICROMIPS_CALL_HI16:
3100     case BFD_RELOC_MICROMIPS_CALL_LO16:
3101     case BFD_RELOC_MICROMIPS_SUB:
3102     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3103     case BFD_RELOC_MICROMIPS_GOT_OFST:
3104     case BFD_RELOC_MICROMIPS_GOT_DISP:
3105     case BFD_RELOC_MICROMIPS_HIGHEST:
3106     case BFD_RELOC_MICROMIPS_HIGHER:
3107     case BFD_RELOC_MICROMIPS_SCN_DISP:
3108     case BFD_RELOC_MICROMIPS_JALR:
3109       return TRUE;
3110
3111     default:
3112       return FALSE;
3113     }
3114 }
3115
3116 static inline bfd_boolean
3117 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3118 {
3119   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3120 }
3121
3122 static inline bfd_boolean
3123 got16_reloc_p (bfd_reloc_code_real_type reloc)
3124 {
3125   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3126           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3127 }
3128
3129 static inline bfd_boolean
3130 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3131 {
3132   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3133           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3134 }
3135
3136 static inline bfd_boolean
3137 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3138 {
3139   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3140           || reloc == BFD_RELOC_MICROMIPS_LO16);
3141 }
3142
3143 static inline bfd_boolean
3144 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3145 {
3146   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3147 }
3148
3149 static inline bfd_boolean
3150 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3151 {
3152   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3153           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3154 }
3155
3156 /* Return true if RELOC is a PC-relative relocation that does not have
3157    full address range.  */
3158
3159 static inline bfd_boolean
3160 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3161 {
3162   switch (reloc)
3163     {
3164     case BFD_RELOC_16_PCREL_S2:
3165     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3166     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3167     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3168       return TRUE;
3169
3170     case BFD_RELOC_32_PCREL:
3171       return HAVE_64BIT_ADDRESSES;
3172
3173     default:
3174       return FALSE;
3175     }
3176 }
3177
3178 /* Return true if the given relocation might need a matching %lo().
3179    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3180    need a matching %lo() when applied to local symbols.  */
3181
3182 static inline bfd_boolean
3183 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3184 {
3185   return (HAVE_IN_PLACE_ADDENDS
3186           && (hi16_reloc_p (reloc)
3187               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3188                  all GOT16 relocations evaluate to "G".  */
3189               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3190 }
3191
3192 /* Return the type of %lo() reloc needed by RELOC, given that
3193    reloc_needs_lo_p.  */
3194
3195 static inline bfd_reloc_code_real_type
3196 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3197 {
3198   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3199           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3200              : BFD_RELOC_LO16));
3201 }
3202
3203 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3204    relocation.  */
3205
3206 static inline bfd_boolean
3207 fixup_has_matching_lo_p (fixS *fixp)
3208 {
3209   return (fixp->fx_next != NULL
3210           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3211           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3212           && fixp->fx_offset == fixp->fx_next->fx_offset);
3213 }
3214
3215 /* This function returns true if modifying a register requires a
3216    delay.  */
3217
3218 static int
3219 reg_needs_delay (unsigned int reg)
3220 {
3221   unsigned long prev_pinfo;
3222
3223   prev_pinfo = history[0].insn_mo->pinfo;
3224   if (! mips_opts.noreorder
3225       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
3226            && ! gpr_interlocks)
3227           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
3228               && ! cop_interlocks)))
3229     {
3230       /* A load from a coprocessor or from memory.  All load delays
3231          delay the use of general register rt for one instruction.  */
3232       /* Itbl support may require additional care here.  */
3233       know (prev_pinfo & INSN_WRITE_GPR_T);
3234       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
3235         return 1;
3236     }
3237
3238   return 0;
3239 }
3240
3241 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3242    says whether the labels refer to text or data.  */
3243
3244 static void
3245 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3246 {
3247   struct insn_label_list *l;
3248   valueT val;
3249
3250   for (l = labels; l != NULL; l = l->next)
3251     {
3252       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3253       symbol_set_frag (l->label, frag_now);
3254       val = (valueT) frag_now_fix ();
3255       /* MIPS16/microMIPS text labels are stored as odd.  */
3256       if (text_p && HAVE_CODE_COMPRESSION)
3257         ++val;
3258       S_SET_VALUE (l->label, val);
3259     }
3260 }
3261
3262 /* Move all labels in insn_labels to the current insertion point
3263    and treat them as text labels.  */
3264
3265 static void
3266 mips_move_text_labels (void)
3267 {
3268   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3269 }
3270
3271 static bfd_boolean
3272 s_is_linkonce (symbolS *sym, segT from_seg)
3273 {
3274   bfd_boolean linkonce = FALSE;
3275   segT symseg = S_GET_SEGMENT (sym);
3276
3277   if (symseg != from_seg && !S_IS_LOCAL (sym))
3278     {
3279       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3280         linkonce = TRUE;
3281       /* The GNU toolchain uses an extension for ELF: a section
3282          beginning with the magic string .gnu.linkonce is a
3283          linkonce section.  */
3284       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3285                    sizeof ".gnu.linkonce" - 1) == 0)
3286         linkonce = TRUE;
3287     }
3288   return linkonce;
3289 }
3290
3291 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3292    linker to handle them specially, such as generating jalx instructions
3293    when needed.  We also make them odd for the duration of the assembly,
3294    in order to generate the right sort of code.  We will make them even
3295    in the adjust_symtab routine, while leaving them marked.  This is
3296    convenient for the debugger and the disassembler.  The linker knows
3297    to make them odd again.  */
3298
3299 static void
3300 mips_compressed_mark_label (symbolS *label)
3301 {
3302   gas_assert (HAVE_CODE_COMPRESSION);
3303
3304   if (mips_opts.mips16)
3305     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3306   else
3307     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3308   if ((S_GET_VALUE (label) & 1) == 0
3309       /* Don't adjust the address if the label is global or weak, or
3310          in a link-once section, since we'll be emitting symbol reloc
3311          references to it which will be patched up by the linker, and
3312          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3313       && !S_IS_WEAK (label)
3314       && !S_IS_EXTERNAL (label)
3315       && !s_is_linkonce (label, now_seg))
3316     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3317 }
3318
3319 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3320
3321 static void
3322 mips_compressed_mark_labels (void)
3323 {
3324   struct insn_label_list *l;
3325
3326   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3327     mips_compressed_mark_label (l->label);
3328 }
3329
3330 /* End the current frag.  Make it a variant frag and record the
3331    relaxation info.  */
3332
3333 static void
3334 relax_close_frag (void)
3335 {
3336   mips_macro_warning.first_frag = frag_now;
3337   frag_var (rs_machine_dependent, 0, 0,
3338             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3339             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3340
3341   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3342   mips_relax.first_fixup = 0;
3343 }
3344
3345 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3346    See the comment above RELAX_ENCODE for more details.  */
3347
3348 static void
3349 relax_start (symbolS *symbol)
3350 {
3351   gas_assert (mips_relax.sequence == 0);
3352   mips_relax.sequence = 1;
3353   mips_relax.symbol = symbol;
3354 }
3355
3356 /* Start generating the second version of a relaxable sequence.
3357    See the comment above RELAX_ENCODE for more details.  */
3358
3359 static void
3360 relax_switch (void)
3361 {
3362   gas_assert (mips_relax.sequence == 1);
3363   mips_relax.sequence = 2;
3364 }
3365
3366 /* End the current relaxable sequence.  */
3367
3368 static void
3369 relax_end (void)
3370 {
3371   gas_assert (mips_relax.sequence == 2);
3372   relax_close_frag ();
3373   mips_relax.sequence = 0;
3374 }
3375
3376 /* Return true if IP is a delayed branch or jump.  */
3377
3378 static inline bfd_boolean
3379 delayed_branch_p (const struct mips_cl_insn *ip)
3380 {
3381   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3382                                 | INSN_COND_BRANCH_DELAY
3383                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3384 }
3385
3386 /* Return true if IP is a compact branch or jump.  */
3387
3388 static inline bfd_boolean
3389 compact_branch_p (const struct mips_cl_insn *ip)
3390 {
3391   if (mips_opts.mips16)
3392     return (ip->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
3393                                   | MIPS16_INSN_COND_BRANCH)) != 0;
3394   else
3395     return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3396                                    | INSN2_COND_BRANCH)) != 0;
3397 }
3398
3399 /* Return true if IP is an unconditional branch or jump.  */
3400
3401 static inline bfd_boolean
3402 uncond_branch_p (const struct mips_cl_insn *ip)
3403 {
3404   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3405           || (mips_opts.mips16
3406               ? (ip->insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH) != 0
3407               : (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0));
3408 }
3409
3410 /* Return true if IP is a branch-likely instruction.  */
3411
3412 static inline bfd_boolean
3413 branch_likely_p (const struct mips_cl_insn *ip)
3414 {
3415   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3416 }
3417
3418 /* Return the type of nop that should be used to fill the delay slot
3419    of delayed branch IP.  */
3420
3421 static struct mips_cl_insn *
3422 get_delay_slot_nop (const struct mips_cl_insn *ip)
3423 {
3424   if (mips_opts.micromips
3425       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3426     return &micromips_nop32_insn;
3427   return NOP_INSN;
3428 }
3429
3430 /* Return the mask of core registers that IP reads or writes.  */
3431
3432 static unsigned int
3433 gpr_mod_mask (const struct mips_cl_insn *ip)
3434 {
3435   unsigned long pinfo2;
3436   unsigned int mask;
3437
3438   mask = 0;
3439   pinfo2 = ip->insn_mo->pinfo2;
3440   if (mips_opts.micromips)
3441     {
3442       if (pinfo2 & INSN2_MOD_GPR_MD)
3443         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
3444       if (pinfo2 & INSN2_MOD_GPR_MF)
3445         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
3446       if (pinfo2 & INSN2_MOD_SP)
3447         mask |= 1 << SP;
3448     }
3449   return mask;
3450 }
3451
3452 /* Return the mask of core registers that IP reads.  */
3453
3454 static unsigned int
3455 gpr_read_mask (const struct mips_cl_insn *ip)
3456 {
3457   unsigned long pinfo, pinfo2;
3458   unsigned int mask;
3459
3460   mask = gpr_mod_mask (ip);
3461   pinfo = ip->insn_mo->pinfo;
3462   pinfo2 = ip->insn_mo->pinfo2;
3463   if (mips_opts.mips16)
3464     {
3465       if (pinfo & MIPS16_INSN_READ_X)
3466         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3467       if (pinfo & MIPS16_INSN_READ_Y)
3468         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3469       if (pinfo & MIPS16_INSN_READ_T)
3470         mask |= 1 << TREG;
3471       if (pinfo & MIPS16_INSN_READ_SP)
3472         mask |= 1 << SP;
3473       if (pinfo & MIPS16_INSN_READ_31)
3474         mask |= 1 << RA;
3475       if (pinfo & MIPS16_INSN_READ_Z)
3476         mask |= 1 << (mips16_to_32_reg_map
3477                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
3478       if (pinfo & MIPS16_INSN_READ_GPR_X)
3479         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3480     }
3481   else
3482     {
3483       if (pinfo2 & INSN2_READ_GPR_D)
3484         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3485       if (pinfo & INSN_READ_GPR_T)
3486         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3487       if (pinfo & INSN_READ_GPR_S)
3488         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3489       if (pinfo2 & INSN2_READ_GP)
3490         mask |= 1 << GP;
3491       if (pinfo2 & INSN2_READ_GPR_31)
3492         mask |= 1 << RA;
3493       if (pinfo2 & INSN2_READ_GPR_Z)
3494         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3495     }
3496   if (mips_opts.micromips)
3497     {
3498       if (pinfo2 & INSN2_READ_GPR_MC)
3499         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
3500       if (pinfo2 & INSN2_READ_GPR_ME)
3501         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
3502       if (pinfo2 & INSN2_READ_GPR_MG)
3503         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
3504       if (pinfo2 & INSN2_READ_GPR_MJ)
3505         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3506       if (pinfo2 & INSN2_READ_GPR_MMN)
3507         {
3508           mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
3509           mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
3510         }
3511       if (pinfo2 & INSN2_READ_GPR_MP)
3512         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3513       if (pinfo2 & INSN2_READ_GPR_MQ)
3514         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
3515     }
3516   /* Don't include register 0.  */
3517   return mask & ~1;
3518 }
3519
3520 /* Return the mask of core registers that IP writes.  */
3521
3522 static unsigned int
3523 gpr_write_mask (const struct mips_cl_insn *ip)
3524 {
3525   unsigned long pinfo, pinfo2;
3526   unsigned int mask;
3527
3528   mask = gpr_mod_mask (ip);
3529   pinfo = ip->insn_mo->pinfo;
3530   pinfo2 = ip->insn_mo->pinfo2;
3531   if (mips_opts.mips16)
3532     {
3533       if (pinfo & MIPS16_INSN_WRITE_X)
3534         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3535       if (pinfo & MIPS16_INSN_WRITE_Y)
3536         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3537       if (pinfo & MIPS16_INSN_WRITE_Z)
3538         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3539       if (pinfo & MIPS16_INSN_WRITE_T)
3540         mask |= 1 << TREG;
3541       if (pinfo & MIPS16_INSN_WRITE_SP)
3542         mask |= 1 << SP;
3543       if (pinfo & MIPS16_INSN_WRITE_31)
3544         mask |= 1 << RA;
3545       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3546         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3547     }
3548   else
3549     {
3550       if (pinfo & INSN_WRITE_GPR_D)
3551         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3552       if (pinfo & INSN_WRITE_GPR_T)
3553         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3554       if (pinfo & INSN_WRITE_GPR_S)
3555         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3556       if (pinfo & INSN_WRITE_GPR_31)
3557         mask |= 1 << RA;
3558       if (pinfo2 & INSN2_WRITE_GPR_Z)
3559         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3560     }
3561   if (mips_opts.micromips)
3562     {
3563       if (pinfo2 & INSN2_WRITE_GPR_MB)
3564         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
3565       if (pinfo2 & INSN2_WRITE_GPR_MH)
3566         {
3567           mask |= 1 << micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
3568           mask |= 1 << micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
3569         }
3570       if (pinfo2 & INSN2_WRITE_GPR_MJ)
3571         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3572       if (pinfo2 & INSN2_WRITE_GPR_MP)
3573         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3574     }
3575   /* Don't include register 0.  */
3576   return mask & ~1;
3577 }
3578
3579 /* Return the mask of floating-point registers that IP reads.  */
3580
3581 static unsigned int
3582 fpr_read_mask (const struct mips_cl_insn *ip)
3583 {
3584   unsigned long pinfo, pinfo2;
3585   unsigned int mask;
3586
3587   mask = 0;
3588   pinfo = ip->insn_mo->pinfo;
3589   pinfo2 = ip->insn_mo->pinfo2;
3590   if (!mips_opts.mips16)
3591     {
3592       if (pinfo2 & INSN2_READ_FPR_D)
3593         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3594       if (pinfo & INSN_READ_FPR_S)
3595         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3596       if (pinfo & INSN_READ_FPR_T)
3597         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3598       if (pinfo & INSN_READ_FPR_R)
3599         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3600       if (pinfo2 & INSN2_READ_FPR_Z)
3601         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3602     }
3603   /* Conservatively treat all operands to an FP_D instruction are doubles.
3604      (This is overly pessimistic for things like cvt.d.s.)  */
3605   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3606     mask |= mask << 1;
3607   return mask;
3608 }
3609
3610 /* Return the mask of floating-point registers that IP writes.  */
3611
3612 static unsigned int
3613 fpr_write_mask (const struct mips_cl_insn *ip)
3614 {
3615   unsigned long pinfo, pinfo2;
3616   unsigned int mask;
3617
3618   mask = 0;
3619   pinfo = ip->insn_mo->pinfo;
3620   pinfo2 = ip->insn_mo->pinfo2;
3621   if (!mips_opts.mips16)
3622     {
3623       if (pinfo & INSN_WRITE_FPR_D)
3624         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3625       if (pinfo & INSN_WRITE_FPR_S)
3626         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3627       if (pinfo & INSN_WRITE_FPR_T)
3628         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3629       if (pinfo2 & INSN2_WRITE_FPR_Z)
3630         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3631     }
3632   /* Conservatively treat all operands to an FP_D instruction are doubles.
3633      (This is overly pessimistic for things like cvt.s.d.)  */
3634   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3635     mask |= mask << 1;
3636   return mask;
3637 }
3638
3639 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
3640    Check whether that is allowed.  */
3641
3642 static bfd_boolean
3643 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
3644 {
3645   const char *s = insn->name;
3646
3647   if (insn->pinfo == INSN_MACRO)
3648     /* Let a macro pass, we'll catch it later when it is expanded.  */
3649     return TRUE;
3650
3651   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
3652     {
3653       /* Allow odd registers for single-precision ops.  */
3654       switch (insn->pinfo & (FP_S | FP_D))
3655         {
3656         case FP_S:
3657         case 0:
3658           return TRUE;
3659         case FP_D:
3660           return FALSE;
3661         default:
3662           break;
3663         }
3664
3665       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
3666       s = strchr (insn->name, '.');
3667       if (s != NULL && opnum == 2)
3668         s = strchr (s + 1, '.');
3669       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
3670     }
3671
3672   /* Single-precision coprocessor loads and moves are OK too.  */
3673   if ((insn->pinfo & FP_S)
3674       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
3675                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
3676     return TRUE;
3677
3678   return FALSE;
3679 }
3680
3681 /* Report that user-supplied argument ARGNUM for INSN was VAL, but should
3682    have been in the range [MIN_VAL, MAX_VAL].  PRINT_HEX says whether
3683    this operand is normally printed in hex or decimal.  */
3684
3685 static void
3686 report_bad_range (struct mips_cl_insn *insn, int argnum,
3687                   offsetT val, int min_val, int max_val,
3688                   bfd_boolean print_hex)
3689 {
3690   if (print_hex && val >= 0)
3691     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
3692               " was 0x%lx."),
3693             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3694   else if (print_hex)
3695     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
3696               " was %ld."),
3697             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3698   else
3699     as_bad (_("Operand %d of `%s' must be in the range [%d, %d],"
3700               " was %ld."),
3701             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3702 }
3703
3704 /* Report an invalid combination of position and size operands for a bitfield
3705    operation.  POS and SIZE are the values that were given.  */
3706
3707 static void
3708 report_bad_field (offsetT pos, offsetT size)
3709 {
3710   as_bad (_("Invalid field specification (position %ld, size %ld)"),
3711           (unsigned long) pos, (unsigned long) size);
3712 }
3713
3714 /* Information about an instruction argument that we're trying to match.  */
3715 struct mips_arg_info
3716 {
3717   /* The instruction so far.  */
3718   struct mips_cl_insn *insn;
3719
3720   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
3721   int opnum;
3722
3723   /* The 1-based argument number, for error reporting.  This does not
3724      count elided optional registers, etc..  */
3725   int argnum;
3726
3727   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
3728   unsigned int last_regno;
3729
3730   /* If the first operand was an OP_REG, this is the register that it
3731      specified, otherwise it is ILLEGAL_REG.  */
3732   unsigned int dest_regno;
3733
3734   /* The value of the last OP_INT operand.  Only used for OP_MSB,
3735      where it gives the lsb position.  */
3736   unsigned int last_op_int;
3737
3738   /* If true, match routines should silently reject invalid arguments.
3739      If false, match routines can accept invalid arguments as long as
3740      they report an appropriate error.  They still have the option of
3741      silently rejecting arguments, in which case a generic "Invalid operands"
3742      style of error will be used instead.  */
3743   bfd_boolean soft_match;
3744
3745   /* If true, the OP_INT match routine should treat plain symbolic operands
3746      as if a relocation operator like %lo(...) had been used.  This is only
3747      ever true if the operand can be relocated.  */
3748   bfd_boolean allow_nonconst;
3749
3750   /* When true, the OP_INT match routine should allow unsigned N-bit
3751      arguments to be used where a signed N-bit operand is expected.  */
3752   bfd_boolean lax_max;
3753
3754   /* When true, the OP_REG match routine should assume that another operand
3755      appears after this one.  It should fail the match if the register it
3756      sees is at the end of the argument list.  */
3757   bfd_boolean optional_reg;
3758
3759   /* True if a reference to the current AT register was seen.  */
3760   bfd_boolean seen_at;
3761 };
3762
3763 /* Match a constant integer at S for ARG.  Return null if the match failed.
3764    Otherwise return the end of the matched string and store the constant value
3765    in *VALUE.  In the latter case, use FALLBACK as the value if the match
3766    succeeded with an error.  */
3767
3768 static char *
3769 match_const_int (struct mips_arg_info *arg, char *s, offsetT *value,
3770                  offsetT fallback)
3771 {
3772   expressionS ex;
3773   bfd_reloc_code_real_type r[3];
3774   int num_relocs;
3775
3776   num_relocs = my_getSmallExpression (&ex, r, s);
3777   if (*s == '(' && ex.X_op == O_register)
3778     {
3779       /* Assume that the constant has been elided and that S is a base
3780          register.  The rest of the match will fail if the assumption
3781          turns out to be wrong.  */
3782       *value = 0;
3783       return s;
3784     }
3785
3786   if (num_relocs == 0 && ex.X_op == O_constant)
3787     *value = ex.X_add_number;
3788   else
3789     {
3790       /* If we got a register rather than an expression, the default
3791          "Invalid operands" style of error seems more appropriate.  */
3792       if (arg->soft_match || ex.X_op == O_register)
3793         return 0;
3794       as_bad (_("Operand %d of `%s' must be constant"),
3795               arg->argnum, arg->insn->insn_mo->name);
3796       *value = fallback;
3797     }
3798   return expr_end;
3799 }
3800
3801 /* Return the RTYPE_* flags for a register operand of type TYPE that
3802    appears in instruction OPCODE.  */
3803
3804 static unsigned int
3805 convert_reg_type (const struct mips_opcode *opcode,
3806                   enum mips_reg_operand_type type)
3807 {
3808   switch (type)
3809     {
3810     case OP_REG_GP:
3811       return RTYPE_NUM | RTYPE_GP;
3812
3813     case OP_REG_FP:
3814       /* Allow vector register names for MDMX if the instruction is a 64-bit
3815          FPR load, store or move (including moves to and from GPRs).  */
3816       if ((mips_opts.ase & ASE_MDMX)
3817           && (opcode->pinfo & FP_D)
3818           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
3819                                | INSN_COPROC_MEMORY_DELAY
3820                                | INSN_LOAD_COPROC_DELAY
3821                                | INSN_LOAD_MEMORY_DELAY
3822                                | INSN_STORE_MEMORY)))
3823         return RTYPE_FPU | RTYPE_VEC;
3824       return RTYPE_FPU;
3825
3826     case OP_REG_CCC:
3827       if (opcode->pinfo & (FP_D | FP_S))
3828         return RTYPE_CCC | RTYPE_FCC;
3829       return RTYPE_CCC;
3830
3831     case OP_REG_VEC:
3832       if (opcode->membership & INSN_5400)
3833         return RTYPE_FPU;
3834       return RTYPE_FPU | RTYPE_VEC;
3835
3836     case OP_REG_ACC:
3837       return RTYPE_ACC;
3838
3839     case OP_REG_COPRO:
3840       if (opcode->name[strlen (opcode->name) - 1] == '0')
3841         return RTYPE_NUM | RTYPE_CP0;
3842       return RTYPE_NUM;
3843
3844     case OP_REG_HW:
3845       return RTYPE_NUM;
3846     }
3847   abort ();
3848 }
3849
3850 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
3851
3852 static void
3853 check_regno (struct mips_arg_info *arg,
3854              enum mips_reg_operand_type type, unsigned int regno)
3855 {
3856   if (AT && type == OP_REG_GP && regno == AT)
3857     arg->seen_at = TRUE;
3858
3859   if (type == OP_REG_FP
3860       && (regno & 1) != 0
3861       && HAVE_32BIT_FPRS
3862       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
3863     as_warn (_("Float register should be even, was %d"), regno);
3864
3865   if (type == OP_REG_CCC)
3866     {
3867       const char *name;
3868       size_t length;
3869
3870       name = arg->insn->insn_mo->name;
3871       length = strlen (name);
3872       if ((regno & 1) != 0
3873           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
3874               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
3875         as_warn (_("Condition code register should be even for %s, was %d"),
3876                  name, regno);
3877
3878       if ((regno & 3) != 0
3879           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
3880         as_warn (_("Condition code register should be 0 or 4 for %s, was %d"),
3881                  name, regno);
3882     }
3883 }
3884
3885 /* OP_INT matcher.  */
3886
3887 static char *
3888 match_int_operand (struct mips_arg_info *arg,
3889                    const struct mips_operand *operand_base, char *s)
3890 {
3891   const struct mips_int_operand *operand;
3892   unsigned int uval, mask;
3893   int min_val, max_val, factor;
3894   offsetT sval;
3895   bfd_boolean print_hex;
3896
3897   operand = (const struct mips_int_operand *) operand_base;
3898   factor = 1 << operand->shift;
3899   mask = (1 << operand_base->size) - 1;
3900   max_val = (operand->max_val + operand->bias) << operand->shift;
3901   min_val = max_val - (mask << operand->shift);
3902   if (arg->lax_max)
3903     max_val = mask << operand->shift;
3904
3905   if (operand_base->lsb == 0
3906       && operand_base->size == 16
3907       && operand->shift == 0
3908       && operand->bias == 0
3909       && (operand->max_val == 32767 || operand->max_val == 65535))
3910     {
3911       /* The operand can be relocated.  */
3912       offset_reloc[0] = BFD_RELOC_LO16;
3913       offset_reloc[1] = BFD_RELOC_UNUSED;
3914       offset_reloc[2] = BFD_RELOC_UNUSED;
3915       if (my_getSmallExpression (&offset_expr, offset_reloc, s) > 0)
3916         /* Relocation operators were used.  Accept the arguent and
3917            leave the relocation value in offset_expr and offset_relocs
3918            for the caller to process.  */
3919         return expr_end;
3920       if (*s == '(' && offset_expr.X_op == O_register)
3921         /* Assume that the constant has been elided and that S is a base
3922            register.  The rest of the match will fail if the assumption
3923            turns out to be wrong.  */
3924         sval = 0;
3925       else
3926         {
3927           s = expr_end;
3928           if (offset_expr.X_op != O_constant)
3929             /* If non-constant operands are allowed then leave them for
3930                the caller to process, otherwise fail the match.  */
3931             return arg->allow_nonconst ? s : 0;
3932           sval = offset_expr.X_add_number;
3933         }
3934       /* Clear the global state; we're going to install the operand
3935          ourselves.  */
3936       offset_reloc[0] = BFD_RELOC_UNUSED;
3937       offset_expr.X_op = O_absent;
3938     }
3939   else
3940     {
3941       s = match_const_int (arg, s, &sval, min_val);
3942       if (!s)
3943         return 0;
3944     }
3945
3946   arg->last_op_int = sval;
3947
3948   /* Check the range.  If there's a problem, record the lowest acceptable
3949      value in arg->last_op_int in order to prevent an unhelpful error
3950      from OP_MSB too.
3951
3952      Bit counts have traditionally been printed in hex by the disassembler
3953      but printed as decimal in error messages.  Only resort to hex if
3954      the operand is bigger than 6 bits.  */
3955   print_hex = operand->print_hex && operand_base->size > 6;
3956   if (sval < min_val || sval > max_val)
3957     {
3958       if (arg->soft_match)
3959         return 0;
3960       report_bad_range (arg->insn, arg->argnum, sval, min_val, max_val,
3961                         print_hex);
3962       arg->last_op_int = min_val;
3963     }
3964   else if (sval % factor)
3965     {
3966       if (arg->soft_match)
3967         return 0;
3968       as_bad (print_hex && sval >= 0
3969               ? _("Operand %d of `%s' must be a factor of %d, was 0x%lx.")
3970               : _("Operand %d of `%s' must be a factor of %d, was %ld."),
3971               arg->argnum, arg->insn->insn_mo->name, factor,
3972               (unsigned long) sval);
3973       arg->last_op_int = min_val;
3974     }
3975
3976   uval = (unsigned int) sval >> operand->shift;
3977   uval -= operand->bias;
3978
3979   /* Handle -mfix-cn63xxp1.  */
3980   if (arg->opnum == 1
3981       && mips_fix_cn63xxp1
3982       && !mips_opts.micromips
3983       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
3984     switch (uval)
3985       {
3986       case 5:
3987       case 25:
3988       case 26:
3989       case 27:
3990       case 28:
3991       case 29:
3992       case 30:
3993       case 31:
3994         /* These are ok.  */
3995         break;
3996
3997       default:
3998         /* The rest must be changed to 28.  */
3999         uval = 28;
4000         break;
4001       }
4002
4003   insn_insert_operand (arg->insn, operand_base, uval);
4004   return s;
4005 }
4006
4007 /* OP_MAPPED_INT matcher.  */
4008
4009 static char *
4010 match_mapped_int_operand (struct mips_arg_info *arg,
4011                           const struct mips_operand *operand_base, char *s)
4012 {
4013   const struct mips_mapped_int_operand *operand;
4014   unsigned int uval, num_vals;
4015   offsetT sval;
4016
4017   operand = (const struct mips_mapped_int_operand *) operand_base;
4018   s = match_const_int (arg, s, &sval, operand->int_map[0]);
4019   if (!s)
4020     return 0;
4021
4022   num_vals = 1 << operand_base->size;
4023   for (uval = 0; uval < num_vals; uval++)
4024     if (operand->int_map[uval] == sval)
4025       break;
4026   if (uval == num_vals)
4027     return 0;
4028
4029   insn_insert_operand (arg->insn, operand_base, uval);
4030   return s;
4031 }
4032
4033 /* OP_MSB matcher.  */
4034
4035 static char *
4036 match_msb_operand (struct mips_arg_info *arg,
4037                    const struct mips_operand *operand_base, char *s)
4038 {
4039   const struct mips_msb_operand *operand;
4040   int min_val, max_val, max_high;
4041   offsetT size, sval, high;
4042
4043   operand = (const struct mips_msb_operand *) operand_base;
4044   min_val = operand->bias;
4045   max_val = min_val + (1 << operand_base->size) - 1;
4046   max_high = operand->opsize;
4047
4048   s = match_const_int (arg, s, &size, 1);
4049   if (!s)
4050     return 0;
4051
4052   high = size + arg->last_op_int;
4053   sval = operand->add_lsb ? high : size;
4054
4055   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4056     {
4057       if (arg->soft_match)
4058         return 0;
4059       report_bad_field (arg->last_op_int, size);
4060       sval = min_val;
4061     }
4062   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4063   return s;
4064 }
4065
4066 /* OP_REG matcher.  */
4067
4068 static char *
4069 match_reg_operand (struct mips_arg_info *arg,
4070                    const struct mips_operand *operand_base, char *s)
4071 {
4072   const struct mips_reg_operand *operand;
4073   unsigned int regno, uval, num_vals, types;
4074
4075   operand = (const struct mips_reg_operand *) operand_base;
4076   types = convert_reg_type (arg->insn->insn_mo, operand->reg_type);
4077   if (!reg_lookup (&s, types, &regno))
4078     return 0;
4079
4080   SKIP_SPACE_TABS (s);
4081   if (arg->optional_reg && *s == 0)
4082     return 0;
4083
4084   if (operand->reg_map)
4085     {
4086       num_vals = 1 << operand->root.size;
4087       for (uval = 0; uval < num_vals; uval++)
4088         if (operand->reg_map[uval] == regno)
4089           break;
4090       if (num_vals == uval)
4091         return 0;
4092     }
4093   else
4094     uval = regno;
4095
4096   check_regno (arg, operand->reg_type, regno);
4097   arg->last_regno = regno;
4098   if (arg->opnum == 1)
4099     arg->dest_regno = regno;
4100   insn_insert_operand (arg->insn, operand_base, uval);
4101   return s;
4102 }
4103
4104 /* OP_REG_PAIR matcher.  */
4105
4106 static char *
4107 match_reg_pair_operand (struct mips_arg_info *arg,
4108                         const struct mips_operand *operand_base, char *s)
4109 {
4110   const struct mips_reg_pair_operand *operand;
4111   unsigned int regno1, regno2, uval, num_vals, types;
4112
4113   operand = (const struct mips_reg_pair_operand *) operand_base;
4114   types = convert_reg_type (arg->insn->insn_mo, operand->reg_type);
4115
4116   if (!reg_lookup (&s, types, &regno1))
4117     return 0;
4118
4119   SKIP_SPACE_TABS (s);
4120   if (*s++ != ',')
4121     return 0;
4122   arg->argnum += 1;
4123
4124   if (!reg_lookup (&s, types, &regno2))
4125     return 0;
4126
4127   num_vals = 1 << operand_base->size;
4128   for (uval = 0; uval < num_vals; uval++)
4129     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4130       break;
4131   if (uval == num_vals)
4132     return 0;
4133
4134   check_regno (arg, operand->reg_type, regno1);
4135   check_regno (arg, operand->reg_type, regno2);
4136   insn_insert_operand (arg->insn, operand_base, uval);
4137   return s;
4138 }
4139
4140 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4141
4142 static char *
4143 match_pcrel_operand (char *s)
4144 {
4145   my_getExpression (&offset_expr, s);
4146   return expr_end;
4147 }
4148
4149 /* OP_PERF_REG matcher.  */
4150
4151 static char *
4152 match_perf_reg_operand (struct mips_arg_info *arg,
4153                         const struct mips_operand *operand, char *s)
4154 {
4155   offsetT sval;
4156
4157   s = match_const_int (arg, s, &sval, 0);
4158   if (!s)
4159     return 0;
4160
4161   if (sval != 0
4162       && (sval != 1
4163           || (mips_opts.arch == CPU_R5900
4164               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4165                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4166     {
4167       if (arg->soft_match)
4168         return 0;
4169       as_bad (_("Invalid performance register (%ld)"), (unsigned long) sval);
4170     }
4171
4172   insn_insert_operand (arg->insn, operand, sval);
4173   return s;
4174 }
4175
4176 /* OP_ADDIUSP matcher.  */
4177
4178 static char *
4179 match_addiusp_operand (struct mips_arg_info *arg,
4180                        const struct mips_operand *operand, char *s)
4181 {
4182   offsetT sval;
4183   unsigned int uval;
4184
4185   s = match_const_int (arg, s, &sval, -256);
4186   if (!s)
4187     return 0;
4188
4189   if (sval % 4)
4190     return 0;
4191
4192   sval /= 4;
4193   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4194     return 0;
4195
4196   uval = (unsigned int) sval;
4197   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4198   insn_insert_operand (arg->insn, operand, uval);
4199   return s;
4200 }
4201
4202 /* OP_CLO_CLZ_DEST matcher.  */
4203
4204 static char *
4205 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4206                             const struct mips_operand *operand, char *s)
4207 {
4208   unsigned int regno;
4209
4210   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
4211     return 0;
4212
4213   check_regno (arg, OP_REG_GP, regno);
4214   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4215   return s;
4216 }
4217
4218 /* OP_LWM_SWM_LIST matcher.  */
4219
4220 static char *
4221 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4222                             const struct mips_operand *operand, char *s)
4223 {
4224   unsigned int reglist, sregs, ra;
4225
4226   if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
4227     return 0;
4228
4229   if (operand->size == 2)
4230     {
4231       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4232
4233          s0, ra
4234          s0, s1, ra, s2, s3
4235          s0-s2, ra
4236
4237          and any permutations of these.  */
4238       if ((reglist & 0xfff1ffff) != 0x80010000)
4239         return 0;
4240
4241       sregs = (reglist >> 17) & 7;
4242       ra = 0;
4243     }
4244   else
4245     {
4246       /* The list must include at least one of ra and s0-sN,
4247          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4248          which are $23 and $30 respectively.)  E.g.:
4249
4250          ra
4251          s0
4252          ra, s0, s1, s2
4253          s0-s8
4254          s0-s5, ra
4255
4256          and any permutations of these.  */
4257       if ((reglist & 0x3f00ffff) != 0)
4258         return 0;
4259
4260       ra = (reglist >> 27) & 0x10;
4261       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4262     }
4263   sregs += 1;
4264   if ((sregs & -sregs) != sregs)
4265     return 0;
4266
4267   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4268   return s;
4269 }
4270
4271 /* OP_ENTRY_EXIT_LIST matcher.  */
4272
4273 static char *
4274 match_entry_exit_operand (struct mips_arg_info *arg,
4275                           const struct mips_operand *operand, char *s)
4276 {
4277   unsigned int mask;
4278   bfd_boolean is_exit;
4279
4280   /* The format is the same for both ENTRY and EXIT, but the constraints
4281      are different.  */
4282   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4283   mask = (is_exit ? 7 << 3 : 0);
4284   for (;;)
4285     {
4286       unsigned int regno1, regno2;
4287       bfd_boolean is_freg;
4288
4289       if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &regno1))
4290         is_freg = FALSE;
4291       else if (reg_lookup (&s, RTYPE_FPU, &regno1))
4292         is_freg = TRUE;
4293       else
4294         return 0;
4295
4296       SKIP_SPACE_TABS (s);
4297       if (*s == '-')
4298         {
4299           ++s;
4300           SKIP_SPACE_TABS (s);
4301           if (!reg_lookup (&s, (is_freg ? RTYPE_FPU
4302                                 : RTYPE_GP | RTYPE_NUM), &regno2))
4303             return 0;
4304           SKIP_SPACE_TABS (s);
4305         }
4306       else
4307         regno2 = regno1;
4308
4309       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4310         {
4311           mask &= ~(7 << 3);
4312           mask |= (5 + regno2) << 3;
4313         }
4314       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4315         mask |= (regno2 - 3) << 3;
4316       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4317         mask |= (regno2 - 15) << 1;
4318       else if (regno1 == RA && regno2 == RA)
4319         mask |= 1;
4320       else
4321         return 0;
4322
4323       if (!*s)
4324         break;
4325       if (*s != ',')
4326         return 0;
4327       arg->argnum += 1;
4328       ++s;
4329       SKIP_SPACE_TABS (s);
4330     }
4331   insn_insert_operand (arg->insn, operand, mask);
4332   return s;
4333 }
4334
4335 /* OP_SAVE_RESTORE_LIST matcher.  */
4336
4337 static char *
4338 match_save_restore_list_operand (struct mips_arg_info *arg, char *s)
4339 {
4340   unsigned int opcode, args, statics, sregs;
4341   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4342   expressionS value;
4343   offsetT frame_size;
4344   const char *error;
4345
4346   error = 0;
4347   opcode = arg->insn->insn_opcode;
4348   frame_size = 0;
4349   num_frame_sizes = 0;
4350   args = 0;
4351   statics = 0;
4352   sregs = 0;
4353   for (;;)
4354     {
4355       unsigned int regno1, regno2;
4356
4357       my_getExpression (&value, s);
4358       if (value.X_op == O_constant)
4359         {
4360           /* Handle the frame size.  */
4361           num_frame_sizes += 1;
4362           frame_size = value.X_add_number;
4363           s = expr_end;
4364           SKIP_SPACE_TABS (s);
4365         }
4366       else
4367         {
4368           if (!reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &regno1))
4369             return 0;
4370
4371           SKIP_SPACE_TABS (s);
4372           if (*s == '-')
4373             {
4374               ++s;
4375               SKIP_SPACE_TABS (s);
4376               if (!reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &regno2)
4377                   || regno2 < regno1)
4378                 return 0;
4379               SKIP_SPACE_TABS (s);
4380             }
4381           else
4382             regno2 = regno1;
4383
4384           while (regno1 <= regno2)
4385             {
4386               if (regno1 >= 4 && regno1 <= 7)
4387                 {
4388                   if (num_frame_sizes == 0)
4389                     /* args $a0-$a3 */
4390                     args |= 1 << (regno1 - 4);
4391                   else
4392                     /* statics $a0-$a3 */
4393                     statics |= 1 << (regno1 - 4);
4394                 }
4395               else if (regno1 >= 16 && regno1 <= 23)
4396                 /* $s0-$s7 */
4397                 sregs |= 1 << (regno1 - 16);
4398               else if (regno1 == 30)
4399                 /* $s8 */
4400                 sregs |= 1 << 8;
4401               else if (regno1 == 31)
4402                 /* Add $ra to insn.  */
4403                 opcode |= 0x40;
4404               else
4405                 return 0;
4406               regno1 += 1;
4407               if (regno1 == 24)
4408                 regno1 = 30;
4409             }
4410         }
4411       if (!*s)
4412         break;
4413       if (*s != ',')
4414         return 0;
4415       arg->argnum += 1;
4416       ++s;
4417       SKIP_SPACE_TABS (s);
4418     }
4419
4420   /* Encode args/statics combination.  */
4421   if (args & statics)
4422     return 0;
4423   else if (args == 0xf)
4424     /* All $a0-$a3 are args.  */
4425     opcode |= MIPS16_ALL_ARGS << 16;
4426   else if (statics == 0xf)
4427     /* All $a0-$a3 are statics.  */
4428     opcode |= MIPS16_ALL_STATICS << 16;
4429   else
4430     {
4431       /* Count arg registers.  */
4432       num_args = 0;
4433       while (args & 0x1)
4434         {
4435           args >>= 1;
4436           num_args += 1;
4437         }
4438       if (args != 0)
4439         return 0;
4440
4441       /* Count static registers.  */
4442       num_statics = 0;
4443       while (statics & 0x8)
4444         {
4445           statics = (statics << 1) & 0xf;
4446           num_statics += 1;
4447         }
4448       if (statics != 0)
4449         return 0;
4450
4451       /* Encode args/statics.  */
4452       opcode |= ((num_args << 2) | num_statics) << 16;
4453     }
4454
4455   /* Encode $s0/$s1.  */
4456   if (sregs & (1 << 0))         /* $s0 */
4457     opcode |= 0x20;
4458   if (sregs & (1 << 1))         /* $s1 */
4459     opcode |= 0x10;
4460   sregs >>= 2;
4461
4462   /* Encode $s2-$s8. */
4463   num_sregs = 0;
4464   while (sregs & 1)
4465     {
4466       sregs >>= 1;
4467       num_sregs += 1;
4468     }
4469   if (sregs != 0)
4470     return 0;
4471   opcode |= num_sregs << 24;
4472
4473   /* Encode frame size.  */
4474   if (num_frame_sizes == 0)
4475     error = _("Missing frame size");
4476   else if (num_frame_sizes > 1)
4477     error = _("Frame size specified twice");
4478   else if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
4479     error = _("Invalid frame size");
4480   else if (frame_size != 128 || (opcode >> 16) != 0)
4481     {
4482       frame_size /= 8;
4483       opcode |= (((frame_size & 0xf0) << 16)
4484                  | (frame_size & 0x0f));
4485     }
4486
4487   if (error)
4488     {
4489       if (arg->soft_match)
4490         return 0;
4491       as_bad (error);
4492     }
4493
4494   /* Finally build the instruction.  */
4495   if ((opcode >> 16) != 0 || frame_size == 0)
4496     opcode |= MIPS16_EXTEND;
4497   arg->insn->insn_opcode = opcode;
4498   return s;
4499 }
4500
4501 /* OP_MDMX_IMM_REG matcher.  */
4502
4503 static char *
4504 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
4505                             const struct mips_operand *operand, char *s)
4506 {
4507   unsigned int regno, uval, types;
4508   bfd_boolean is_qh;
4509   const struct mips_opcode *opcode;
4510
4511   /* The mips_opcode records whether this is an octobyte or quadhalf
4512      instruction.  Start out with that bit in place.  */
4513   opcode = arg->insn->insn_mo;
4514   uval = mips_extract_operand (operand, opcode->match);
4515   is_qh = (uval != 0);
4516
4517   types = convert_reg_type (arg->insn->insn_mo, OP_REG_VEC);
4518   if (reg_lookup (&s, types, &regno))
4519     {
4520       if ((opcode->membership & INSN_5400)
4521           && strcmp (opcode->name, "rzu.ob") == 0)
4522         {
4523           if (arg->soft_match)
4524             return 0;
4525           as_bad (_("Operand %d of `%s' must be an immediate"),
4526                   arg->argnum, opcode->name);
4527         }
4528
4529       /* Check whether this is a vector register or a broadcast of
4530          a single element.  */
4531       SKIP_SPACE_TABS (s);
4532       if (*s == '[')
4533         {
4534           /* Read the element number.  */
4535           expressionS value;
4536
4537           ++s;
4538           SKIP_SPACE_TABS (s);
4539           my_getExpression (&value, s);
4540           s = expr_end;
4541           if (value.X_op != O_constant
4542               || value.X_add_number < 0
4543               || value.X_add_number > (is_qh ? 3 : 7))
4544             {
4545               if (arg->soft_match)
4546                 return 0;
4547               as_bad (_("Invalid element selector"));
4548               value.X_add_number = 0;
4549             }
4550           uval |= (unsigned int) value.X_add_number << (is_qh ? 2 : 1) << 5;
4551           SKIP_SPACE_TABS (s);
4552           if (*s == ']')
4553             ++s;
4554           else
4555             {
4556               if (arg->soft_match)
4557                 return 0;
4558               as_bad (_("Expecting ']' found '%s'"), s);
4559             }
4560         }
4561       else
4562         {
4563           /* A full vector.  */
4564           if ((opcode->membership & INSN_5400)
4565               && (strcmp (opcode->name, "sll.ob") == 0
4566                   || strcmp (opcode->name, "srl.ob") == 0))
4567             {
4568               if (arg->soft_match)
4569                 return 0;
4570               as_bad (_("Operand %d of `%s' must be scalar"),
4571                       arg->argnum, opcode->name);
4572             }
4573
4574           if (is_qh)
4575             uval |= MDMX_FMTSEL_VEC_QH << 5;
4576           else
4577             uval |= MDMX_FMTSEL_VEC_OB << 5;
4578         }
4579       check_regno (arg, OP_REG_FP, regno);
4580       uval |= regno;
4581     }
4582   else
4583     {
4584       offsetT sval;
4585
4586       s = match_const_int (arg, s, &sval, 0);
4587       if (!s)
4588         return 0;
4589       if (sval < 0 || sval > 31)
4590         {
4591           if (arg->soft_match)
4592             return 0;
4593           report_bad_range (arg->insn, arg->argnum, sval, 0, 31, FALSE);
4594         }
4595       uval |= (sval & 31);
4596       if (is_qh)
4597         uval |= MDMX_FMTSEL_IMM_QH << 5;
4598       else
4599         uval |= MDMX_FMTSEL_IMM_OB << 5;
4600     }
4601   insn_insert_operand (arg->insn, operand, uval);
4602   return s;
4603 }
4604
4605 /* OP_PC matcher.  */
4606
4607 static char *
4608 match_pc_operand (char *s)
4609 {
4610   if (strncmp (s, "$pc", 3) != 0)
4611     return 0;
4612   s += 3;
4613   SKIP_SPACE_TABS (s);
4614   return s;
4615 }
4616
4617 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
4618    register that we need to match.  */
4619
4620 static char *
4621 match_tied_reg_operand (struct mips_arg_info *arg, char *s,
4622                         unsigned int other_regno)
4623 {
4624   unsigned int regno;
4625
4626   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno)
4627       || regno != other_regno)
4628     return 0;
4629   SKIP_SPACE_TABS (s);
4630   if (arg->optional_reg && *s == 0)
4631     return 0;
4632   return s;
4633 }
4634
4635 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
4636    of the argument text if the match is successful, otherwise return null.  */
4637
4638 static char *
4639 match_operand (struct mips_arg_info *arg,
4640                const struct mips_operand *operand, char *s)
4641 {
4642   switch (operand->type)
4643     {
4644     case OP_INT:
4645       return match_int_operand (arg, operand, s);
4646
4647     case OP_MAPPED_INT:
4648       return match_mapped_int_operand (arg, operand, s);
4649
4650     case OP_MSB:
4651       return match_msb_operand (arg, operand, s);
4652
4653     case OP_REG:
4654       return match_reg_operand (arg, operand, s);
4655
4656     case OP_REG_PAIR:
4657       return match_reg_pair_operand (arg, operand, s);
4658
4659     case OP_PCREL:
4660       return match_pcrel_operand (s);
4661
4662     case OP_PERF_REG:
4663       return match_perf_reg_operand (arg, operand, s);
4664
4665     case OP_ADDIUSP_INT:
4666       return match_addiusp_operand (arg, operand, s);
4667
4668     case OP_CLO_CLZ_DEST:
4669       return match_clo_clz_dest_operand (arg, operand, s);
4670
4671     case OP_LWM_SWM_LIST:
4672       return match_lwm_swm_list_operand (arg, operand, s);
4673
4674     case OP_ENTRY_EXIT_LIST:
4675       return match_entry_exit_operand (arg, operand, s);
4676
4677     case OP_SAVE_RESTORE_LIST:
4678       return match_save_restore_list_operand (arg, s);
4679
4680     case OP_MDMX_IMM_REG:
4681       return match_mdmx_imm_reg_operand (arg, operand, s);
4682
4683     case OP_REPEAT_DEST_REG:
4684       return match_tied_reg_operand (arg, s, arg->dest_regno);
4685
4686     case OP_REPEAT_PREV_REG:
4687       return match_tied_reg_operand (arg, s, arg->last_regno);
4688
4689     case OP_PC:
4690       return match_pc_operand (s);
4691     }
4692   abort ();
4693 }
4694
4695 /* ARG is the state after successfully matching an instruction.
4696    Issue any queued-up warnings.  */
4697
4698 static void
4699 check_completed_insn (struct mips_arg_info *arg)
4700 {
4701   if (arg->seen_at)
4702     {
4703       if (AT == ATREG)
4704         as_warn (_("Used $at without \".set noat\""));
4705       else
4706         as_warn (_("Used $%u with \".set at=$%u\""), AT, AT);
4707     }
4708 }
4709
4710 /* Classify an instruction according to the FIX_VR4120_* enumeration.
4711    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
4712    by VR4120 errata.  */
4713
4714 static unsigned int
4715 classify_vr4120_insn (const char *name)
4716 {
4717   if (strncmp (name, "macc", 4) == 0)
4718     return FIX_VR4120_MACC;
4719   if (strncmp (name, "dmacc", 5) == 0)
4720     return FIX_VR4120_DMACC;
4721   if (strncmp (name, "mult", 4) == 0)
4722     return FIX_VR4120_MULT;
4723   if (strncmp (name, "dmult", 5) == 0)
4724     return FIX_VR4120_DMULT;
4725   if (strstr (name, "div"))
4726     return FIX_VR4120_DIV;
4727   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
4728     return FIX_VR4120_MTHILO;
4729   return NUM_FIX_VR4120_CLASSES;
4730 }
4731
4732 #define INSN_ERET  0x42000018
4733 #define INSN_DERET 0x4200001f
4734
4735 /* Return the number of instructions that must separate INSN1 and INSN2,
4736    where INSN1 is the earlier instruction.  Return the worst-case value
4737    for any INSN2 if INSN2 is null.  */
4738
4739 static unsigned int
4740 insns_between (const struct mips_cl_insn *insn1,
4741                const struct mips_cl_insn *insn2)
4742 {
4743   unsigned long pinfo1, pinfo2;
4744   unsigned int mask;
4745
4746   /* This function needs to know which pinfo flags are set for INSN2
4747      and which registers INSN2 uses.  The former is stored in PINFO2 and
4748      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
4749      will have every flag set and INSN2_USES_GPR will always return true.  */
4750   pinfo1 = insn1->insn_mo->pinfo;
4751   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
4752
4753 #define INSN2_USES_GPR(REG) \
4754   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
4755
4756   /* For most targets, write-after-read dependencies on the HI and LO
4757      registers must be separated by at least two instructions.  */
4758   if (!hilo_interlocks)
4759     {
4760       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
4761         return 2;
4762       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
4763         return 2;
4764     }
4765
4766   /* If we're working around r7000 errata, there must be two instructions
4767      between an mfhi or mflo and any instruction that uses the result.  */
4768   if (mips_7000_hilo_fix
4769       && !mips_opts.micromips
4770       && MF_HILO_INSN (pinfo1)
4771       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
4772     return 2;
4773
4774   /* If we're working around 24K errata, one instruction is required
4775      if an ERET or DERET is followed by a branch instruction.  */
4776   if (mips_fix_24k && !mips_opts.micromips)
4777     {
4778       if (insn1->insn_opcode == INSN_ERET
4779           || insn1->insn_opcode == INSN_DERET)
4780         {
4781           if (insn2 == NULL
4782               || insn2->insn_opcode == INSN_ERET
4783               || insn2->insn_opcode == INSN_DERET
4784               || delayed_branch_p (insn2))
4785             return 1;
4786         }
4787     }
4788
4789   /* If working around VR4120 errata, check for combinations that need
4790      a single intervening instruction.  */
4791   if (mips_fix_vr4120 && !mips_opts.micromips)
4792     {
4793       unsigned int class1, class2;
4794
4795       class1 = classify_vr4120_insn (insn1->insn_mo->name);
4796       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
4797         {
4798           if (insn2 == NULL)
4799             return 1;
4800           class2 = classify_vr4120_insn (insn2->insn_mo->name);
4801           if (vr4120_conflicts[class1] & (1 << class2))
4802             return 1;
4803         }
4804     }
4805
4806   if (!HAVE_CODE_COMPRESSION)
4807     {
4808       /* Check for GPR or coprocessor load delays.  All such delays
4809          are on the RT register.  */
4810       /* Itbl support may require additional care here.  */
4811       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
4812           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
4813         {
4814           know (pinfo1 & INSN_WRITE_GPR_T);
4815           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
4816             return 1;
4817         }
4818
4819       /* Check for generic coprocessor hazards.
4820
4821          This case is not handled very well.  There is no special
4822          knowledge of CP0 handling, and the coprocessors other than
4823          the floating point unit are not distinguished at all.  */
4824       /* Itbl support may require additional care here. FIXME!
4825          Need to modify this to include knowledge about
4826          user specified delays!  */
4827       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
4828                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
4829         {
4830           /* Handle cases where INSN1 writes to a known general coprocessor
4831              register.  There must be a one instruction delay before INSN2
4832              if INSN2 reads that register, otherwise no delay is needed.  */
4833           mask = fpr_write_mask (insn1);
4834           if (mask != 0)
4835             {
4836               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
4837                 return 1;
4838             }
4839           else
4840             {
4841               /* Read-after-write dependencies on the control registers
4842                  require a two-instruction gap.  */
4843               if ((pinfo1 & INSN_WRITE_COND_CODE)
4844                   && (pinfo2 & INSN_READ_COND_CODE))
4845                 return 2;
4846
4847               /* We don't know exactly what INSN1 does.  If INSN2 is
4848                  also a coprocessor instruction, assume there must be
4849                  a one instruction gap.  */
4850               if (pinfo2 & INSN_COP)
4851                 return 1;
4852             }
4853         }
4854
4855       /* Check for read-after-write dependencies on the coprocessor
4856          control registers in cases where INSN1 does not need a general
4857          coprocessor delay.  This means that INSN1 is a floating point
4858          comparison instruction.  */
4859       /* Itbl support may require additional care here.  */
4860       else if (!cop_interlocks
4861                && (pinfo1 & INSN_WRITE_COND_CODE)
4862                && (pinfo2 & INSN_READ_COND_CODE))
4863         return 1;
4864     }
4865
4866 #undef INSN2_USES_GPR
4867
4868   return 0;
4869 }
4870
4871 /* Return the number of nops that would be needed to work around the
4872    VR4130 mflo/mfhi errata if instruction INSN immediately followed
4873    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
4874    that are contained within the first IGNORE instructions of HIST.  */
4875
4876 static int
4877 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
4878                  const struct mips_cl_insn *insn)
4879 {
4880   int i, j;
4881   unsigned int mask;
4882
4883   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
4884      are not affected by the errata.  */
4885   if (insn != 0
4886       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
4887           || strcmp (insn->insn_mo->name, "mtlo") == 0
4888           || strcmp (insn->insn_mo->name, "mthi") == 0))
4889     return 0;
4890
4891   /* Search for the first MFLO or MFHI.  */
4892   for (i = 0; i < MAX_VR4130_NOPS; i++)
4893     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
4894       {
4895         /* Extract the destination register.  */
4896         mask = gpr_write_mask (&hist[i]);
4897
4898         /* No nops are needed if INSN reads that register.  */
4899         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
4900           return 0;
4901
4902         /* ...or if any of the intervening instructions do.  */
4903         for (j = 0; j < i; j++)
4904           if (gpr_read_mask (&hist[j]) & mask)
4905             return 0;
4906
4907         if (i >= ignore)
4908           return MAX_VR4130_NOPS - i;
4909       }
4910   return 0;
4911 }
4912
4913 #define BASE_REG_EQ(INSN1, INSN2)       \
4914   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
4915       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
4916
4917 /* Return the minimum alignment for this store instruction.  */
4918
4919 static int
4920 fix_24k_align_to (const struct mips_opcode *mo)
4921 {
4922   if (strcmp (mo->name, "sh") == 0)
4923     return 2;
4924
4925   if (strcmp (mo->name, "swc1") == 0
4926       || strcmp (mo->name, "swc2") == 0
4927       || strcmp (mo->name, "sw") == 0
4928       || strcmp (mo->name, "sc") == 0
4929       || strcmp (mo->name, "s.s") == 0)
4930     return 4;
4931
4932   if (strcmp (mo->name, "sdc1") == 0
4933       || strcmp (mo->name, "sdc2") == 0
4934       || strcmp (mo->name, "s.d") == 0)
4935     return 8;
4936
4937   /* sb, swl, swr */
4938   return 1;
4939 }
4940
4941 struct fix_24k_store_info
4942   {
4943     /* Immediate offset, if any, for this store instruction.  */
4944     short off;
4945     /* Alignment required by this store instruction.  */
4946     int align_to;
4947     /* True for register offsets.  */
4948     int register_offset;
4949   };
4950
4951 /* Comparison function used by qsort.  */
4952
4953 static int
4954 fix_24k_sort (const void *a, const void *b)
4955 {
4956   const struct fix_24k_store_info *pos1 = a;
4957   const struct fix_24k_store_info *pos2 = b;
4958
4959   return (pos1->off - pos2->off);
4960 }
4961
4962 /* INSN is a store instruction.  Try to record the store information
4963    in STINFO.  Return false if the information isn't known.  */
4964
4965 static bfd_boolean
4966 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
4967                            const struct mips_cl_insn *insn)
4968 {
4969   /* The instruction must have a known offset.  */
4970   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
4971     return FALSE;
4972
4973   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
4974   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
4975   return TRUE;
4976 }
4977
4978 /* Return the number of nops that would be needed to work around the 24k
4979    "lost data on stores during refill" errata if instruction INSN
4980    immediately followed the 2 instructions described by HIST.
4981    Ignore hazards that are contained within the first IGNORE
4982    instructions of HIST.
4983
4984    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
4985    for the data cache refills and store data. The following describes
4986    the scenario where the store data could be lost.
4987
4988    * A data cache miss, due to either a load or a store, causing fill
4989      data to be supplied by the memory subsystem
4990    * The first three doublewords of fill data are returned and written
4991      into the cache
4992    * A sequence of four stores occurs in consecutive cycles around the
4993      final doubleword of the fill:
4994    * Store A
4995    * Store B
4996    * Store C
4997    * Zero, One or more instructions
4998    * Store D
4999
5000    The four stores A-D must be to different doublewords of the line that
5001    is being filled. The fourth instruction in the sequence above permits
5002    the fill of the final doubleword to be transferred from the FSB into
5003    the cache. In the sequence above, the stores may be either integer
5004    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5005    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5006    different doublewords on the line. If the floating point unit is
5007    running in 1:2 mode, it is not possible to create the sequence above
5008    using only floating point store instructions.
5009
5010    In this case, the cache line being filled is incorrectly marked
5011    invalid, thereby losing the data from any store to the line that
5012    occurs between the original miss and the completion of the five
5013    cycle sequence shown above.
5014
5015    The workarounds are:
5016
5017    * Run the data cache in write-through mode.
5018    * Insert a non-store instruction between
5019      Store A and Store B or Store B and Store C.  */
5020   
5021 static int
5022 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5023               const struct mips_cl_insn *insn)
5024 {
5025   struct fix_24k_store_info pos[3];
5026   int align, i, base_offset;
5027
5028   if (ignore >= 2)
5029     return 0;
5030
5031   /* If the previous instruction wasn't a store, there's nothing to
5032      worry about.  */
5033   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5034     return 0;
5035
5036   /* If the instructions after the previous one are unknown, we have
5037      to assume the worst.  */
5038   if (!insn)
5039     return 1;
5040
5041   /* Check whether we are dealing with three consecutive stores.  */
5042   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5043       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5044     return 0;
5045
5046   /* If we don't know the relationship between the store addresses,
5047      assume the worst.  */
5048   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5049       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5050     return 1;
5051
5052   if (!fix_24k_record_store_info (&pos[0], insn)
5053       || !fix_24k_record_store_info (&pos[1], &hist[0])
5054       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5055     return 1;
5056
5057   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5058
5059   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5060      X bytes and such that the base register + X is known to be aligned
5061      to align bytes.  */
5062
5063   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5064     align = 8;
5065   else
5066     {
5067       align = pos[0].align_to;
5068       base_offset = pos[0].off;
5069       for (i = 1; i < 3; i++)
5070         if (align < pos[i].align_to)
5071           {
5072             align = pos[i].align_to;
5073             base_offset = pos[i].off;
5074           }
5075       for (i = 0; i < 3; i++)
5076         pos[i].off -= base_offset;
5077     }
5078
5079   pos[0].off &= ~align + 1;
5080   pos[1].off &= ~align + 1;
5081   pos[2].off &= ~align + 1;
5082
5083   /* If any two stores write to the same chunk, they also write to the
5084      same doubleword.  The offsets are still sorted at this point.  */
5085   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5086     return 0;
5087
5088   /* A range of at least 9 bytes is needed for the stores to be in
5089      non-overlapping doublewords.  */
5090   if (pos[2].off - pos[0].off <= 8)
5091     return 0;
5092
5093   if (pos[2].off - pos[1].off >= 24
5094       || pos[1].off - pos[0].off >= 24
5095       || pos[2].off - pos[0].off >= 32)
5096     return 0;
5097
5098   return 1;
5099 }
5100
5101 /* Return the number of nops that would be needed if instruction INSN
5102    immediately followed the MAX_NOPS instructions given by HIST,
5103    where HIST[0] is the most recent instruction.  Ignore hazards
5104    between INSN and the first IGNORE instructions in HIST.
5105
5106    If INSN is null, return the worse-case number of nops for any
5107    instruction.  */
5108
5109 static int
5110 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5111                const struct mips_cl_insn *insn)
5112 {
5113   int i, nops, tmp_nops;
5114
5115   nops = 0;
5116   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5117     {
5118       tmp_nops = insns_between (hist + i, insn) - i;
5119       if (tmp_nops > nops)
5120         nops = tmp_nops;
5121     }
5122
5123   if (mips_fix_vr4130 && !mips_opts.micromips)
5124     {
5125       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5126       if (tmp_nops > nops)
5127         nops = tmp_nops;
5128     }
5129
5130   if (mips_fix_24k && !mips_opts.micromips)
5131     {
5132       tmp_nops = nops_for_24k (ignore, hist, insn);
5133       if (tmp_nops > nops)
5134         nops = tmp_nops;
5135     }
5136
5137   return nops;
5138 }
5139
5140 /* The variable arguments provide NUM_INSNS extra instructions that
5141    might be added to HIST.  Return the largest number of nops that
5142    would be needed after the extended sequence, ignoring hazards
5143    in the first IGNORE instructions.  */
5144
5145 static int
5146 nops_for_sequence (int num_insns, int ignore,
5147                    const struct mips_cl_insn *hist, ...)
5148 {
5149   va_list args;
5150   struct mips_cl_insn buffer[MAX_NOPS];
5151   struct mips_cl_insn *cursor;
5152   int nops;
5153
5154   va_start (args, hist);
5155   cursor = buffer + num_insns;
5156   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
5157   while (cursor > buffer)
5158     *--cursor = *va_arg (args, const struct mips_cl_insn *);
5159
5160   nops = nops_for_insn (ignore, buffer, NULL);
5161   va_end (args);
5162   return nops;
5163 }
5164
5165 /* Like nops_for_insn, but if INSN is a branch, take into account the
5166    worst-case delay for the branch target.  */
5167
5168 static int
5169 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
5170                          const struct mips_cl_insn *insn)
5171 {
5172   int nops, tmp_nops;
5173
5174   nops = nops_for_insn (ignore, hist, insn);
5175   if (delayed_branch_p (insn))
5176     {
5177       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
5178                                     hist, insn, get_delay_slot_nop (insn));
5179       if (tmp_nops > nops)
5180         nops = tmp_nops;
5181     }
5182   else if (compact_branch_p (insn))
5183     {
5184       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
5185       if (tmp_nops > nops)
5186         nops = tmp_nops;
5187     }
5188   return nops;
5189 }
5190
5191 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
5192
5193 static void
5194 fix_loongson2f_nop (struct mips_cl_insn * ip)
5195 {
5196   gas_assert (!HAVE_CODE_COMPRESSION);
5197   if (strcmp (ip->insn_mo->name, "nop") == 0)
5198     ip->insn_opcode = LOONGSON2F_NOP_INSN;
5199 }
5200
5201 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
5202                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
5203
5204 static void
5205 fix_loongson2f_jump (struct mips_cl_insn * ip)
5206 {
5207   gas_assert (!HAVE_CODE_COMPRESSION);
5208   if (strcmp (ip->insn_mo->name, "j") == 0
5209       || strcmp (ip->insn_mo->name, "jr") == 0
5210       || strcmp (ip->insn_mo->name, "jalr") == 0)
5211     {
5212       int sreg;
5213       expressionS ep;
5214
5215       if (! mips_opts.at)
5216         return;
5217
5218       sreg = EXTRACT_OPERAND (0, RS, *ip);
5219       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
5220         return;
5221
5222       ep.X_op = O_constant;
5223       ep.X_add_number = 0xcfff0000;
5224       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
5225       ep.X_add_number = 0xffff;
5226       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
5227       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
5228     }
5229 }
5230
5231 static void
5232 fix_loongson2f (struct mips_cl_insn * ip)
5233 {
5234   if (mips_fix_loongson2f_nop)
5235     fix_loongson2f_nop (ip);
5236
5237   if (mips_fix_loongson2f_jump)
5238     fix_loongson2f_jump (ip);
5239 }
5240
5241 /* IP is a branch that has a delay slot, and we need to fill it
5242    automatically.   Return true if we can do that by swapping IP
5243    with the previous instruction.
5244    ADDRESS_EXPR is an operand of the instruction to be used with
5245    RELOC_TYPE.  */
5246
5247 static bfd_boolean
5248 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
5249   bfd_reloc_code_real_type *reloc_type)
5250 {
5251   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
5252   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
5253
5254   /* -O2 and above is required for this optimization.  */
5255   if (mips_optimize < 2)
5256     return FALSE;
5257
5258   /* If we have seen .set volatile or .set nomove, don't optimize.  */
5259   if (mips_opts.nomove)
5260     return FALSE;
5261
5262   /* We can't swap if the previous instruction's position is fixed.  */
5263   if (history[0].fixed_p)
5264     return FALSE;
5265
5266   /* If the previous previous insn was in a .set noreorder, we can't
5267      swap.  Actually, the MIPS assembler will swap in this situation.
5268      However, gcc configured -with-gnu-as will generate code like
5269
5270         .set    noreorder
5271         lw      $4,XXX
5272         .set    reorder
5273         INSN
5274         bne     $4,$0,foo
5275
5276      in which we can not swap the bne and INSN.  If gcc is not configured
5277      -with-gnu-as, it does not output the .set pseudo-ops.  */
5278   if (history[1].noreorder_p)
5279     return FALSE;
5280
5281   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
5282      This means that the previous instruction was a 4-byte one anyhow.  */
5283   if (mips_opts.mips16 && history[0].fixp[0])
5284     return FALSE;
5285
5286   /* If the branch is itself the target of a branch, we can not swap.
5287      We cheat on this; all we check for is whether there is a label on
5288      this instruction.  If there are any branches to anything other than
5289      a label, users must use .set noreorder.  */
5290   if (seg_info (now_seg)->label_list)
5291     return FALSE;
5292
5293   /* If the previous instruction is in a variant frag other than this
5294      branch's one, we cannot do the swap.  This does not apply to
5295      MIPS16 code, which uses variant frags for different purposes.  */
5296   if (!mips_opts.mips16
5297       && history[0].frag
5298       && history[0].frag->fr_type == rs_machine_dependent)
5299     return FALSE;
5300
5301   /* We do not swap with instructions that cannot architecturally
5302      be placed in a branch delay slot, such as SYNC or ERET.  We
5303      also refrain from swapping with a trap instruction, since it
5304      complicates trap handlers to have the trap instruction be in
5305      a delay slot.  */
5306   prev_pinfo = history[0].insn_mo->pinfo;
5307   if (prev_pinfo & INSN_NO_DELAY_SLOT)
5308     return FALSE;
5309
5310   /* Check for conflicts between the branch and the instructions
5311      before the candidate delay slot.  */
5312   if (nops_for_insn (0, history + 1, ip) > 0)
5313     return FALSE;
5314
5315   /* Check for conflicts between the swapped sequence and the
5316      target of the branch.  */
5317   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
5318     return FALSE;
5319
5320   /* If the branch reads a register that the previous
5321      instruction sets, we can not swap.  */
5322   gpr_read = gpr_read_mask (ip);
5323   prev_gpr_write = gpr_write_mask (&history[0]);
5324   if (gpr_read & prev_gpr_write)
5325     return FALSE;
5326
5327   /* If the branch writes a register that the previous
5328      instruction sets, we can not swap.  */
5329   gpr_write = gpr_write_mask (ip);
5330   if (gpr_write & prev_gpr_write)
5331     return FALSE;
5332
5333   /* If the branch writes a register that the previous
5334      instruction reads, we can not swap.  */
5335   prev_gpr_read = gpr_read_mask (&history[0]);
5336   if (gpr_write & prev_gpr_read)
5337     return FALSE;
5338
5339   /* If one instruction sets a condition code and the
5340      other one uses a condition code, we can not swap.  */
5341   pinfo = ip->insn_mo->pinfo;
5342   if ((pinfo & INSN_READ_COND_CODE)
5343       && (prev_pinfo & INSN_WRITE_COND_CODE))
5344     return FALSE;
5345   if ((pinfo & INSN_WRITE_COND_CODE)
5346       && (prev_pinfo & INSN_READ_COND_CODE))
5347     return FALSE;
5348
5349   /* If the previous instruction uses the PC, we can not swap.  */
5350   prev_pinfo2 = history[0].insn_mo->pinfo2;
5351   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
5352     return FALSE;
5353   if (mips_opts.micromips && (prev_pinfo2 & INSN2_READ_PC))
5354     return FALSE;
5355
5356   /* If the previous instruction has an incorrect size for a fixed
5357      branch delay slot in microMIPS mode, we cannot swap.  */
5358   pinfo2 = ip->insn_mo->pinfo2;
5359   if (mips_opts.micromips
5360       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
5361       && insn_length (history) != 2)
5362     return FALSE;
5363   if (mips_opts.micromips
5364       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
5365       && insn_length (history) != 4)
5366     return FALSE;
5367
5368   /* On R5900 short loops need to be fixed by inserting a nop in
5369      the branch delay slots.
5370      A short loop can be terminated too early.  */
5371   if (mips_opts.arch == CPU_R5900
5372       /* Check if instruction has a parameter, ignore "j $31". */
5373       && (address_expr != NULL)
5374       /* Parameter must be 16 bit. */
5375       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
5376       /* Branch to same segment. */
5377       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
5378       /* Branch to same code fragment. */
5379       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
5380       /* Can only calculate branch offset if value is known. */
5381       && symbol_constant_p(address_expr->X_add_symbol)
5382       /* Check if branch is really conditional. */
5383       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
5384         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
5385         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
5386     {
5387       int distance;
5388       /* Check if loop is shorter than 6 instructions including
5389          branch and delay slot.  */
5390       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
5391       if (distance <= 20)
5392         {
5393           int i;
5394           int rv;
5395
5396           rv = FALSE;
5397           /* When the loop includes branches or jumps,
5398              it is not a short loop. */
5399           for (i = 0; i < (distance / 4); i++)
5400             {
5401               if ((history[i].cleared_p)
5402                   || delayed_branch_p(&history[i]))
5403                 {
5404                   rv = TRUE;
5405                   break;
5406                 }
5407             }
5408           if (rv == FALSE)
5409             {
5410               /* Insert nop after branch to fix short loop. */
5411               return FALSE;
5412             }
5413         }
5414     }
5415
5416   return TRUE;
5417 }
5418
5419 /* Decide how we should add IP to the instruction stream.
5420    ADDRESS_EXPR is an operand of the instruction to be used with
5421    RELOC_TYPE.  */
5422
5423 static enum append_method
5424 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
5425   bfd_reloc_code_real_type *reloc_type)
5426 {
5427   unsigned long pinfo;
5428
5429   /* The relaxed version of a macro sequence must be inherently
5430      hazard-free.  */
5431   if (mips_relax.sequence == 2)
5432     return APPEND_ADD;
5433
5434   /* We must not dabble with instructions in a ".set norerorder" block.  */
5435   if (mips_opts.noreorder)
5436     return APPEND_ADD;
5437
5438   /* Otherwise, it's our responsibility to fill branch delay slots.  */
5439   if (delayed_branch_p (ip))
5440     {
5441       if (!branch_likely_p (ip)
5442           && can_swap_branch_p (ip, address_expr, reloc_type))
5443         return APPEND_SWAP;
5444
5445       pinfo = ip->insn_mo->pinfo;
5446       if (mips_opts.mips16
5447           && ISA_SUPPORTS_MIPS16E
5448           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
5449         return APPEND_ADD_COMPACT;
5450
5451       return APPEND_ADD_WITH_NOP;
5452     }
5453
5454   return APPEND_ADD;
5455 }
5456
5457 /* IP is a MIPS16 instruction whose opcode we have just changed.
5458    Point IP->insn_mo to the new opcode's definition.  */
5459
5460 static void
5461 find_altered_mips16_opcode (struct mips_cl_insn *ip)
5462 {
5463   const struct mips_opcode *mo, *end;
5464
5465   end = &mips16_opcodes[bfd_mips16_num_opcodes];
5466   for (mo = ip->insn_mo; mo < end; mo++)
5467     if ((ip->insn_opcode & mo->mask) == mo->match)
5468       {
5469         ip->insn_mo = mo;
5470         return;
5471       }
5472   abort ();
5473 }
5474
5475 /* For microMIPS macros, we need to generate a local number label
5476    as the target of branches.  */
5477 #define MICROMIPS_LABEL_CHAR            '\037'
5478 static unsigned long micromips_target_label;
5479 static char micromips_target_name[32];
5480
5481 static char *
5482 micromips_label_name (void)
5483 {
5484   char *p = micromips_target_name;
5485   char symbol_name_temporary[24];
5486   unsigned long l;
5487   int i;
5488
5489   if (*p)
5490     return p;
5491
5492   i = 0;
5493   l = micromips_target_label;
5494 #ifdef LOCAL_LABEL_PREFIX
5495   *p++ = LOCAL_LABEL_PREFIX;
5496 #endif
5497   *p++ = 'L';
5498   *p++ = MICROMIPS_LABEL_CHAR;
5499   do
5500     {
5501       symbol_name_temporary[i++] = l % 10 + '0';
5502       l /= 10;
5503     }
5504   while (l != 0);
5505   while (i > 0)
5506     *p++ = symbol_name_temporary[--i];
5507   *p = '\0';
5508
5509   return micromips_target_name;
5510 }
5511
5512 static void
5513 micromips_label_expr (expressionS *label_expr)
5514 {
5515   label_expr->X_op = O_symbol;
5516   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
5517   label_expr->X_add_number = 0;
5518 }
5519
5520 static void
5521 micromips_label_inc (void)
5522 {
5523   micromips_target_label++;
5524   *micromips_target_name = '\0';
5525 }
5526
5527 static void
5528 micromips_add_label (void)
5529 {
5530   symbolS *s;
5531
5532   s = colon (micromips_label_name ());
5533   micromips_label_inc ();
5534   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
5535 }
5536
5537 /* If assembling microMIPS code, then return the microMIPS reloc
5538    corresponding to the requested one if any.  Otherwise return
5539    the reloc unchanged.  */
5540
5541 static bfd_reloc_code_real_type
5542 micromips_map_reloc (bfd_reloc_code_real_type reloc)
5543 {
5544   static const bfd_reloc_code_real_type relocs[][2] =
5545     {
5546       /* Keep sorted incrementally by the left-hand key.  */
5547       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
5548       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
5549       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
5550       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
5551       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
5552       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
5553       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
5554       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
5555       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
5556       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
5557       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
5558       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
5559       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
5560       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
5561       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
5562       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
5563       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
5564       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
5565       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
5566       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
5567       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
5568       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
5569       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
5570       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
5571       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
5572       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
5573       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
5574     };
5575   bfd_reloc_code_real_type r;
5576   size_t i;
5577
5578   if (!mips_opts.micromips)
5579     return reloc;
5580   for (i = 0; i < ARRAY_SIZE (relocs); i++)
5581     {
5582       r = relocs[i][0];
5583       if (r > reloc)
5584         return reloc;
5585       if (r == reloc)
5586         return relocs[i][1];
5587     }
5588   return reloc;
5589 }
5590
5591 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
5592    Return true on success, storing the resolved value in RESULT.  */
5593
5594 static bfd_boolean
5595 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
5596                  offsetT *result)
5597 {
5598   switch (reloc)
5599     {
5600     case BFD_RELOC_MIPS_HIGHEST:
5601     case BFD_RELOC_MICROMIPS_HIGHEST:
5602       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
5603       return TRUE;
5604
5605     case BFD_RELOC_MIPS_HIGHER:
5606     case BFD_RELOC_MICROMIPS_HIGHER:
5607       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
5608       return TRUE;
5609
5610     case BFD_RELOC_HI16_S:
5611     case BFD_RELOC_MICROMIPS_HI16_S:
5612     case BFD_RELOC_MIPS16_HI16_S:
5613       *result = ((operand + 0x8000) >> 16) & 0xffff;
5614       return TRUE;
5615
5616     case BFD_RELOC_HI16:
5617     case BFD_RELOC_MICROMIPS_HI16:
5618     case BFD_RELOC_MIPS16_HI16:
5619       *result = (operand >> 16) & 0xffff;
5620       return TRUE;
5621
5622     case BFD_RELOC_LO16:
5623     case BFD_RELOC_MICROMIPS_LO16:
5624     case BFD_RELOC_MIPS16_LO16:
5625       *result = operand & 0xffff;
5626       return TRUE;
5627
5628     case BFD_RELOC_UNUSED:
5629       *result = operand;
5630       return TRUE;
5631
5632     default:
5633       return FALSE;
5634     }
5635 }
5636
5637 /* Output an instruction.  IP is the instruction information.
5638    ADDRESS_EXPR is an operand of the instruction to be used with
5639    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
5640    a macro expansion.  */
5641
5642 static void
5643 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
5644              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
5645 {
5646   unsigned long prev_pinfo2, pinfo;
5647   bfd_boolean relaxed_branch = FALSE;
5648   enum append_method method;
5649   bfd_boolean relax32;
5650   int branch_disp;
5651
5652   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
5653     fix_loongson2f (ip);
5654
5655   file_ase_mips16 |= mips_opts.mips16;
5656   file_ase_micromips |= mips_opts.micromips;
5657
5658   prev_pinfo2 = history[0].insn_mo->pinfo2;
5659   pinfo = ip->insn_mo->pinfo;
5660
5661   if (mips_opts.micromips
5662       && !expansionp
5663       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
5664            && micromips_insn_length (ip->insn_mo) != 2)
5665           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
5666               && micromips_insn_length (ip->insn_mo) != 4)))
5667     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
5668              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
5669
5670   if (address_expr == NULL)
5671     ip->complete_p = 1;
5672   else if (reloc_type[0] <= BFD_RELOC_UNUSED
5673            && reloc_type[1] == BFD_RELOC_UNUSED
5674            && reloc_type[2] == BFD_RELOC_UNUSED
5675            && address_expr->X_op == O_constant)
5676     {
5677       switch (*reloc_type)
5678         {
5679         case BFD_RELOC_MIPS_JMP:
5680           {
5681             int shift;
5682
5683             shift = mips_opts.micromips ? 1 : 2;
5684             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
5685               as_bad (_("jump to misaligned address (0x%lx)"),
5686                       (unsigned long) address_expr->X_add_number);
5687             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
5688                                 & 0x3ffffff);
5689             ip->complete_p = 1;
5690           }
5691           break;
5692
5693         case BFD_RELOC_MIPS16_JMP:
5694           if ((address_expr->X_add_number & 3) != 0)
5695             as_bad (_("jump to misaligned address (0x%lx)"),
5696                     (unsigned long) address_expr->X_add_number);
5697           ip->insn_opcode |=
5698             (((address_expr->X_add_number & 0x7c0000) << 3)
5699                | ((address_expr->X_add_number & 0xf800000) >> 7)
5700                | ((address_expr->X_add_number & 0x3fffc) >> 2));
5701           ip->complete_p = 1;
5702           break;
5703
5704         case BFD_RELOC_16_PCREL_S2:
5705           {
5706             int shift;
5707
5708             shift = mips_opts.micromips ? 1 : 2;
5709             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
5710               as_bad (_("branch to misaligned address (0x%lx)"),
5711                       (unsigned long) address_expr->X_add_number);
5712             if (!mips_relax_branch)
5713               {
5714                 if ((address_expr->X_add_number + (1 << (shift + 15)))
5715                     & ~((1 << (shift + 16)) - 1))
5716                   as_bad (_("branch address range overflow (0x%lx)"),
5717                           (unsigned long) address_expr->X_add_number);
5718                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
5719                                     & 0xffff);
5720               }
5721           }
5722           break;
5723
5724         default:
5725           {
5726             offsetT value;
5727
5728             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
5729                                  &value))
5730               {
5731                 ip->insn_opcode |= value & 0xffff;
5732                 ip->complete_p = 1;
5733               }
5734           }
5735           break;
5736         }
5737     }
5738
5739   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
5740     {
5741       /* There are a lot of optimizations we could do that we don't.
5742          In particular, we do not, in general, reorder instructions.
5743          If you use gcc with optimization, it will reorder
5744          instructions and generally do much more optimization then we
5745          do here; repeating all that work in the assembler would only
5746          benefit hand written assembly code, and does not seem worth
5747          it.  */
5748       int nops = (mips_optimize == 0
5749                   ? nops_for_insn (0, history, NULL)
5750                   : nops_for_insn_or_target (0, history, ip));
5751       if (nops > 0)
5752         {
5753           fragS *old_frag;
5754           unsigned long old_frag_offset;
5755           int i;
5756
5757           old_frag = frag_now;
5758           old_frag_offset = frag_now_fix ();
5759
5760           for (i = 0; i < nops; i++)
5761             add_fixed_insn (NOP_INSN);
5762           insert_into_history (0, nops, NOP_INSN);
5763
5764           if (listing)
5765             {
5766               listing_prev_line ();
5767               /* We may be at the start of a variant frag.  In case we
5768                  are, make sure there is enough space for the frag
5769                  after the frags created by listing_prev_line.  The
5770                  argument to frag_grow here must be at least as large
5771                  as the argument to all other calls to frag_grow in
5772                  this file.  We don't have to worry about being in the
5773                  middle of a variant frag, because the variants insert
5774                  all needed nop instructions themselves.  */
5775               frag_grow (40);
5776             }
5777
5778           mips_move_text_labels ();
5779
5780 #ifndef NO_ECOFF_DEBUGGING
5781           if (ECOFF_DEBUGGING)
5782             ecoff_fix_loc (old_frag, old_frag_offset);
5783 #endif
5784         }
5785     }
5786   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
5787     {
5788       int nops;
5789
5790       /* Work out how many nops in prev_nop_frag are needed by IP,
5791          ignoring hazards generated by the first prev_nop_frag_since
5792          instructions.  */
5793       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
5794       gas_assert (nops <= prev_nop_frag_holds);
5795
5796       /* Enforce NOPS as a minimum.  */
5797       if (nops > prev_nop_frag_required)
5798         prev_nop_frag_required = nops;
5799
5800       if (prev_nop_frag_holds == prev_nop_frag_required)
5801         {
5802           /* Settle for the current number of nops.  Update the history
5803              accordingly (for the benefit of any future .set reorder code).  */
5804           prev_nop_frag = NULL;
5805           insert_into_history (prev_nop_frag_since,
5806                                prev_nop_frag_holds, NOP_INSN);
5807         }
5808       else
5809         {
5810           /* Allow this instruction to replace one of the nops that was
5811              tentatively added to prev_nop_frag.  */
5812           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
5813           prev_nop_frag_holds--;
5814           prev_nop_frag_since++;
5815         }
5816     }
5817
5818   method = get_append_method (ip, address_expr, reloc_type);
5819   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
5820
5821   dwarf2_emit_insn (0);
5822   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
5823      so "move" the instruction address accordingly.
5824
5825      Also, it doesn't seem appropriate for the assembler to reorder .loc
5826      entries.  If this instruction is a branch that we are going to swap
5827      with the previous instruction, the two instructions should be
5828      treated as a unit, and the debug information for both instructions
5829      should refer to the start of the branch sequence.  Using the
5830      current position is certainly wrong when swapping a 32-bit branch
5831      and a 16-bit delay slot, since the current position would then be
5832      in the middle of a branch.  */
5833   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
5834
5835   relax32 = (mips_relax_branch
5836              /* Don't try branch relaxation within .set nomacro, or within
5837                 .set noat if we use $at for PIC computations.  If it turns
5838                 out that the branch was out-of-range, we'll get an error.  */
5839              && !mips_opts.warn_about_macros
5840              && (mips_opts.at || mips_pic == NO_PIC)
5841              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
5842                 as they have no complementing branches.  */
5843              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
5844
5845   if (!HAVE_CODE_COMPRESSION
5846       && address_expr
5847       && relax32
5848       && *reloc_type == BFD_RELOC_16_PCREL_S2
5849       && delayed_branch_p (ip))
5850     {
5851       relaxed_branch = TRUE;
5852       add_relaxed_insn (ip, (relaxed_branch_length
5853                              (NULL, NULL,
5854                               uncond_branch_p (ip) ? -1
5855                               : branch_likely_p (ip) ? 1
5856                               : 0)), 4,
5857                         RELAX_BRANCH_ENCODE
5858                         (AT,
5859                          uncond_branch_p (ip),
5860                          branch_likely_p (ip),
5861                          pinfo & INSN_WRITE_GPR_31,
5862                          0),
5863                         address_expr->X_add_symbol,
5864                         address_expr->X_add_number);
5865       *reloc_type = BFD_RELOC_UNUSED;
5866     }
5867   else if (mips_opts.micromips
5868            && address_expr
5869            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
5870                || *reloc_type > BFD_RELOC_UNUSED)
5871            && (delayed_branch_p (ip) || compact_branch_p (ip))
5872            /* Don't try branch relaxation when users specify
5873               16-bit/32-bit instructions.  */
5874            && !forced_insn_length)
5875     {
5876       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
5877       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
5878       int uncond = uncond_branch_p (ip) ? -1 : 0;
5879       int compact = compact_branch_p (ip);
5880       int al = pinfo & INSN_WRITE_GPR_31;
5881       int length32;
5882
5883       gas_assert (address_expr != NULL);
5884       gas_assert (!mips_relax.sequence);
5885
5886       relaxed_branch = TRUE;
5887       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
5888       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
5889                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
5890                                                 relax32, 0, 0),
5891                         address_expr->X_add_symbol,
5892                         address_expr->X_add_number);
5893       *reloc_type = BFD_RELOC_UNUSED;
5894     }
5895   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
5896     {
5897       /* We need to set up a variant frag.  */
5898       gas_assert (address_expr != NULL);
5899       add_relaxed_insn (ip, 4, 0,
5900                         RELAX_MIPS16_ENCODE
5901                         (*reloc_type - BFD_RELOC_UNUSED,
5902                          forced_insn_length == 2, forced_insn_length == 4,
5903                          delayed_branch_p (&history[0]),
5904                          history[0].mips16_absolute_jump_p),
5905                         make_expr_symbol (address_expr), 0);
5906     }
5907   else if (mips_opts.mips16 && insn_length (ip) == 2)
5908     {
5909       if (!delayed_branch_p (ip))
5910         /* Make sure there is enough room to swap this instruction with
5911            a following jump instruction.  */
5912         frag_grow (6);
5913       add_fixed_insn (ip);
5914     }
5915   else
5916     {
5917       if (mips_opts.mips16
5918           && mips_opts.noreorder
5919           && delayed_branch_p (&history[0]))
5920         as_warn (_("extended instruction in delay slot"));
5921
5922       if (mips_relax.sequence)
5923         {
5924           /* If we've reached the end of this frag, turn it into a variant
5925              frag and record the information for the instructions we've
5926              written so far.  */
5927           if (frag_room () < 4)
5928             relax_close_frag ();
5929           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
5930         }
5931
5932       if (mips_relax.sequence != 2)
5933         {
5934           if (mips_macro_warning.first_insn_sizes[0] == 0)
5935             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
5936           mips_macro_warning.sizes[0] += insn_length (ip);
5937           mips_macro_warning.insns[0]++;
5938         }
5939       if (mips_relax.sequence != 1)
5940         {
5941           if (mips_macro_warning.first_insn_sizes[1] == 0)
5942             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
5943           mips_macro_warning.sizes[1] += insn_length (ip);
5944           mips_macro_warning.insns[1]++;
5945         }
5946
5947       if (mips_opts.mips16)
5948         {
5949           ip->fixed_p = 1;
5950           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
5951         }
5952       add_fixed_insn (ip);
5953     }
5954
5955   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
5956     {
5957       bfd_reloc_code_real_type final_type[3];
5958       reloc_howto_type *howto0;
5959       reloc_howto_type *howto;
5960       int i;
5961
5962       /* Perform any necessary conversion to microMIPS relocations
5963          and find out how many relocations there actually are.  */
5964       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
5965         final_type[i] = micromips_map_reloc (reloc_type[i]);
5966
5967       /* In a compound relocation, it is the final (outermost)
5968          operator that determines the relocated field.  */
5969       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
5970       if (!howto)
5971         abort ();
5972
5973       if (i > 1)
5974         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
5975       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
5976                                  bfd_get_reloc_size (howto),
5977                                  address_expr,
5978                                  howto0 && howto0->pc_relative,
5979                                  final_type[0]);
5980
5981       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
5982       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
5983         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
5984
5985       /* These relocations can have an addend that won't fit in
5986          4 octets for 64bit assembly.  */
5987       if (HAVE_64BIT_GPRS
5988           && ! howto->partial_inplace
5989           && (reloc_type[0] == BFD_RELOC_16
5990               || reloc_type[0] == BFD_RELOC_32
5991               || reloc_type[0] == BFD_RELOC_MIPS_JMP
5992               || reloc_type[0] == BFD_RELOC_GPREL16
5993               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
5994               || reloc_type[0] == BFD_RELOC_GPREL32
5995               || reloc_type[0] == BFD_RELOC_64
5996               || reloc_type[0] == BFD_RELOC_CTOR
5997               || reloc_type[0] == BFD_RELOC_MIPS_SUB
5998               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
5999               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6000               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6001               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6002               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6003               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6004               || hi16_reloc_p (reloc_type[0])
6005               || lo16_reloc_p (reloc_type[0])))
6006         ip->fixp[0]->fx_no_overflow = 1;
6007
6008       /* These relocations can have an addend that won't fit in 2 octets.  */
6009       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6010           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6011         ip->fixp[0]->fx_no_overflow = 1;
6012
6013       if (mips_relax.sequence)
6014         {
6015           if (mips_relax.first_fixup == 0)
6016             mips_relax.first_fixup = ip->fixp[0];
6017         }
6018       else if (reloc_needs_lo_p (*reloc_type))
6019         {
6020           struct mips_hi_fixup *hi_fixup;
6021
6022           /* Reuse the last entry if it already has a matching %lo.  */
6023           hi_fixup = mips_hi_fixup_list;
6024           if (hi_fixup == 0
6025               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6026             {
6027               hi_fixup = ((struct mips_hi_fixup *)
6028                           xmalloc (sizeof (struct mips_hi_fixup)));
6029               hi_fixup->next = mips_hi_fixup_list;
6030               mips_hi_fixup_list = hi_fixup;
6031             }
6032           hi_fixup->fixp = ip->fixp[0];
6033           hi_fixup->seg = now_seg;
6034         }
6035
6036       /* Add fixups for the second and third relocations, if given.
6037          Note that the ABI allows the second relocation to be
6038          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6039          moment we only use RSS_UNDEF, but we could add support
6040          for the others if it ever becomes necessary.  */
6041       for (i = 1; i < 3; i++)
6042         if (reloc_type[i] != BFD_RELOC_UNUSED)
6043           {
6044             ip->fixp[i] = fix_new (ip->frag, ip->where,
6045                                    ip->fixp[0]->fx_size, NULL, 0,
6046                                    FALSE, final_type[i]);
6047
6048             /* Use fx_tcbit to mark compound relocs.  */
6049             ip->fixp[0]->fx_tcbit = 1;
6050             ip->fixp[i]->fx_tcbit = 1;
6051           }
6052     }
6053   install_insn (ip);
6054
6055   /* Update the register mask information.  */
6056   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6057   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6058
6059   switch (method)
6060     {
6061     case APPEND_ADD:
6062       insert_into_history (0, 1, ip);
6063       break;
6064
6065     case APPEND_ADD_WITH_NOP:
6066       {
6067         struct mips_cl_insn *nop;
6068
6069         insert_into_history (0, 1, ip);
6070         nop = get_delay_slot_nop (ip);
6071         add_fixed_insn (nop);
6072         insert_into_history (0, 1, nop);
6073         if (mips_relax.sequence)
6074           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6075       }
6076       break;
6077
6078     case APPEND_ADD_COMPACT:
6079       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6080       gas_assert (mips_opts.mips16);
6081       ip->insn_opcode |= 0x0080;
6082       find_altered_mips16_opcode (ip);
6083       install_insn (ip);
6084       insert_into_history (0, 1, ip);
6085       break;
6086
6087     case APPEND_SWAP:
6088       {
6089         struct mips_cl_insn delay = history[0];
6090         if (mips_opts.mips16)
6091           {
6092             know (delay.frag == ip->frag);
6093             move_insn (ip, delay.frag, delay.where);
6094             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6095           }
6096         else if (relaxed_branch || delay.frag != ip->frag)
6097           {
6098             /* Add the delay slot instruction to the end of the
6099                current frag and shrink the fixed part of the
6100                original frag.  If the branch occupies the tail of
6101                the latter, move it backwards to cover the gap.  */
6102             delay.frag->fr_fix -= branch_disp;
6103             if (delay.frag == ip->frag)
6104               move_insn (ip, ip->frag, ip->where - branch_disp);
6105             add_fixed_insn (&delay);
6106           }
6107         else
6108           {
6109             move_insn (&delay, ip->frag,
6110                        ip->where - branch_disp + insn_length (ip));
6111             move_insn (ip, history[0].frag, history[0].where);
6112           }
6113         history[0] = *ip;
6114         delay.fixed_p = 1;
6115         insert_into_history (0, 1, &delay);
6116       }
6117       break;
6118     }
6119
6120   /* If we have just completed an unconditional branch, clear the history.  */
6121   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6122       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6123     {
6124       unsigned int i;
6125
6126       mips_no_prev_insn ();
6127
6128       for (i = 0; i < ARRAY_SIZE (history); i++)
6129         history[i].cleared_p = 1;
6130     }
6131
6132   /* We need to emit a label at the end of branch-likely macros.  */
6133   if (emit_branch_likely_macro)
6134     {
6135       emit_branch_likely_macro = FALSE;
6136       micromips_add_label ();
6137     }
6138
6139   /* We just output an insn, so the next one doesn't have a label.  */
6140   mips_clear_insn_labels ();
6141 }
6142
6143 /* Forget that there was any previous instruction or label.
6144    When BRANCH is true, the branch history is also flushed.  */
6145
6146 static void
6147 mips_no_prev_insn (void)
6148 {
6149   prev_nop_frag = NULL;
6150   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6151   mips_clear_insn_labels ();
6152 }
6153
6154 /* This function must be called before we emit something other than
6155    instructions.  It is like mips_no_prev_insn except that it inserts
6156    any NOPS that might be needed by previous instructions.  */
6157
6158 void
6159 mips_emit_delays (void)
6160 {
6161   if (! mips_opts.noreorder)
6162     {
6163       int nops = nops_for_insn (0, history, NULL);
6164       if (nops > 0)
6165         {
6166           while (nops-- > 0)
6167             add_fixed_insn (NOP_INSN);
6168           mips_move_text_labels ();
6169         }
6170     }
6171   mips_no_prev_insn ();
6172 }
6173
6174 /* Start a (possibly nested) noreorder block.  */
6175
6176 static void
6177 start_noreorder (void)
6178 {
6179   if (mips_opts.noreorder == 0)
6180     {
6181       unsigned int i;
6182       int nops;
6183
6184       /* None of the instructions before the .set noreorder can be moved.  */
6185       for (i = 0; i < ARRAY_SIZE (history); i++)
6186         history[i].fixed_p = 1;
6187
6188       /* Insert any nops that might be needed between the .set noreorder
6189          block and the previous instructions.  We will later remove any
6190          nops that turn out not to be needed.  */
6191       nops = nops_for_insn (0, history, NULL);
6192       if (nops > 0)
6193         {
6194           if (mips_optimize != 0)
6195             {
6196               /* Record the frag which holds the nop instructions, so
6197                  that we can remove them if we don't need them.  */
6198               frag_grow (nops * NOP_INSN_SIZE);
6199               prev_nop_frag = frag_now;
6200               prev_nop_frag_holds = nops;
6201               prev_nop_frag_required = 0;
6202               prev_nop_frag_since = 0;
6203             }
6204
6205           for (; nops > 0; --nops)
6206             add_fixed_insn (NOP_INSN);
6207
6208           /* Move on to a new frag, so that it is safe to simply
6209              decrease the size of prev_nop_frag.  */
6210           frag_wane (frag_now);
6211           frag_new (0);
6212           mips_move_text_labels ();
6213         }
6214       mips_mark_labels ();
6215       mips_clear_insn_labels ();
6216     }
6217   mips_opts.noreorder++;
6218   mips_any_noreorder = 1;
6219 }
6220
6221 /* End a nested noreorder block.  */
6222
6223 static void
6224 end_noreorder (void)
6225 {
6226   mips_opts.noreorder--;
6227   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
6228     {
6229       /* Commit to inserting prev_nop_frag_required nops and go back to
6230          handling nop insertion the .set reorder way.  */
6231       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
6232                                 * NOP_INSN_SIZE);
6233       insert_into_history (prev_nop_frag_since,
6234                            prev_nop_frag_required, NOP_INSN);
6235       prev_nop_frag = NULL;
6236     }
6237 }
6238
6239 /* Set up global variables for the start of a new macro.  */
6240
6241 static void
6242 macro_start (void)
6243 {
6244   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
6245   memset (&mips_macro_warning.first_insn_sizes, 0,
6246           sizeof (mips_macro_warning.first_insn_sizes));
6247   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
6248   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
6249                                      && delayed_branch_p (&history[0]));
6250   switch (history[0].insn_mo->pinfo2
6251           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
6252     {
6253     case INSN2_BRANCH_DELAY_32BIT:
6254       mips_macro_warning.delay_slot_length = 4;
6255       break;
6256     case INSN2_BRANCH_DELAY_16BIT:
6257       mips_macro_warning.delay_slot_length = 2;
6258       break;
6259     default:
6260       mips_macro_warning.delay_slot_length = 0;
6261       break;
6262     }
6263   mips_macro_warning.first_frag = NULL;
6264 }
6265
6266 /* Given that a macro is longer than one instruction or of the wrong size,
6267    return the appropriate warning for it.  Return null if no warning is
6268    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
6269    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
6270    and RELAX_NOMACRO.  */
6271
6272 static const char *
6273 macro_warning (relax_substateT subtype)
6274 {
6275   if (subtype & RELAX_DELAY_SLOT)
6276     return _("Macro instruction expanded into multiple instructions"
6277              " in a branch delay slot");
6278   else if (subtype & RELAX_NOMACRO)
6279     return _("Macro instruction expanded into multiple instructions");
6280   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
6281                       | RELAX_DELAY_SLOT_SIZE_SECOND))
6282     return ((subtype & RELAX_DELAY_SLOT_16BIT)
6283             ? _("Macro instruction expanded into a wrong size instruction"
6284                 " in a 16-bit branch delay slot")
6285             : _("Macro instruction expanded into a wrong size instruction"
6286                 " in a 32-bit branch delay slot"));
6287   else
6288     return 0;
6289 }
6290
6291 /* Finish up a macro.  Emit warnings as appropriate.  */
6292
6293 static void
6294 macro_end (void)
6295 {
6296   /* Relaxation warning flags.  */
6297   relax_substateT subtype = 0;
6298
6299   /* Check delay slot size requirements.  */
6300   if (mips_macro_warning.delay_slot_length == 2)
6301     subtype |= RELAX_DELAY_SLOT_16BIT;
6302   if (mips_macro_warning.delay_slot_length != 0)
6303     {
6304       if (mips_macro_warning.delay_slot_length
6305           != mips_macro_warning.first_insn_sizes[0])
6306         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
6307       if (mips_macro_warning.delay_slot_length
6308           != mips_macro_warning.first_insn_sizes[1])
6309         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
6310     }
6311
6312   /* Check instruction count requirements.  */
6313   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
6314     {
6315       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
6316         subtype |= RELAX_SECOND_LONGER;
6317       if (mips_opts.warn_about_macros)
6318         subtype |= RELAX_NOMACRO;
6319       if (mips_macro_warning.delay_slot_p)
6320         subtype |= RELAX_DELAY_SLOT;
6321     }
6322
6323   /* If both alternatives fail to fill a delay slot correctly,
6324      emit the warning now.  */
6325   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
6326       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
6327     {
6328       relax_substateT s;
6329       const char *msg;
6330
6331       s = subtype & (RELAX_DELAY_SLOT_16BIT
6332                      | RELAX_DELAY_SLOT_SIZE_FIRST
6333                      | RELAX_DELAY_SLOT_SIZE_SECOND);
6334       msg = macro_warning (s);
6335       if (msg != NULL)
6336         as_warn ("%s", msg);
6337       subtype &= ~s;
6338     }
6339
6340   /* If both implementations are longer than 1 instruction, then emit the
6341      warning now.  */
6342   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
6343     {
6344       relax_substateT s;
6345       const char *msg;
6346
6347       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
6348       msg = macro_warning (s);
6349       if (msg != NULL)
6350         as_warn ("%s", msg);
6351       subtype &= ~s;
6352     }
6353
6354   /* If any flags still set, then one implementation might need a warning
6355      and the other either will need one of a different kind or none at all.
6356      Pass any remaining flags over to relaxation.  */
6357   if (mips_macro_warning.first_frag != NULL)
6358     mips_macro_warning.first_frag->fr_subtype |= subtype;
6359 }
6360
6361 /* Instruction operand formats used in macros that vary between
6362    standard MIPS and microMIPS code.  */
6363
6364 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
6365 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
6366 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
6367 static const char * const lui_fmt[2] = { "t,u", "s,u" };
6368 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
6369 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
6370 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
6371 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
6372
6373 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
6374 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
6375 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
6376 #define LUI_FMT (lui_fmt[mips_opts.micromips])
6377 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
6378 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
6379 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
6380 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
6381
6382 /* Read a macro's relocation codes from *ARGS and store them in *R.
6383    The first argument in *ARGS will be either the code for a single
6384    relocation or -1 followed by the three codes that make up a
6385    composite relocation.  */
6386
6387 static void
6388 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
6389 {
6390   int i, next;
6391
6392   next = va_arg (*args, int);
6393   if (next >= 0)
6394     r[0] = (bfd_reloc_code_real_type) next;
6395   else
6396     {
6397       for (i = 0; i < 3; i++)
6398         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
6399       /* This function is only used for 16-bit relocation fields.
6400          To make the macro code simpler, treat an unrelocated value
6401          in the same way as BFD_RELOC_LO16.  */
6402       if (r[0] == BFD_RELOC_UNUSED)
6403         r[0] = BFD_RELOC_LO16;
6404     }
6405 }
6406
6407 /* Build an instruction created by a macro expansion.  This is passed
6408    a pointer to the count of instructions created so far, an
6409    expression, the name of the instruction to build, an operand format
6410    string, and corresponding arguments.  */
6411
6412 static void
6413 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
6414 {
6415   const struct mips_opcode *mo = NULL;
6416   bfd_reloc_code_real_type r[3];
6417   const struct mips_opcode *amo;
6418   const struct mips_operand *operand;
6419   struct hash_control *hash;
6420   struct mips_cl_insn insn;
6421   va_list args;
6422   unsigned int uval;
6423
6424   va_start (args, fmt);
6425
6426   if (mips_opts.mips16)
6427     {
6428       mips16_macro_build (ep, name, fmt, &args);
6429       va_end (args);
6430       return;
6431     }
6432
6433   r[0] = BFD_RELOC_UNUSED;
6434   r[1] = BFD_RELOC_UNUSED;
6435   r[2] = BFD_RELOC_UNUSED;
6436   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
6437   amo = (struct mips_opcode *) hash_find (hash, name);
6438   gas_assert (amo);
6439   gas_assert (strcmp (name, amo->name) == 0);
6440
6441   do
6442     {
6443       /* Search until we get a match for NAME.  It is assumed here that
6444          macros will never generate MDMX, MIPS-3D, or MT instructions.
6445          We try to match an instruction that fulfils the branch delay
6446          slot instruction length requirement (if any) of the previous
6447          instruction.  While doing this we record the first instruction
6448          seen that matches all the other conditions and use it anyway
6449          if the requirement cannot be met; we will issue an appropriate
6450          warning later on.  */
6451       if (strcmp (fmt, amo->args) == 0
6452           && amo->pinfo != INSN_MACRO
6453           && is_opcode_valid (amo)
6454           && is_size_valid (amo))
6455         {
6456           if (is_delay_slot_valid (amo))
6457             {
6458               mo = amo;
6459               break;
6460             }
6461           else if (!mo)
6462             mo = amo;
6463         }
6464
6465       ++amo;
6466       gas_assert (amo->name);
6467     }
6468   while (strcmp (name, amo->name) == 0);
6469
6470   gas_assert (mo);
6471   create_insn (&insn, mo);
6472   for (; *fmt; ++fmt)
6473     {
6474       switch (*fmt)
6475         {
6476         case ',':
6477         case '(':
6478         case ')':
6479         case 'z':
6480           break;
6481
6482         case 'i':
6483         case 'j':
6484           macro_read_relocs (&args, r);
6485           gas_assert (*r == BFD_RELOC_GPREL16
6486                       || *r == BFD_RELOC_MIPS_HIGHER
6487                       || *r == BFD_RELOC_HI16_S
6488                       || *r == BFD_RELOC_LO16
6489                       || *r == BFD_RELOC_MIPS_GOT_OFST);
6490           break;
6491
6492         case 'o':
6493           macro_read_relocs (&args, r);
6494           break;
6495
6496         case 'u':
6497           macro_read_relocs (&args, r);
6498           gas_assert (ep != NULL
6499                       && (ep->X_op == O_constant
6500                           || (ep->X_op == O_symbol
6501                               && (*r == BFD_RELOC_MIPS_HIGHEST
6502                                   || *r == BFD_RELOC_HI16_S
6503                                   || *r == BFD_RELOC_HI16
6504                                   || *r == BFD_RELOC_GPREL16
6505                                   || *r == BFD_RELOC_MIPS_GOT_HI16
6506                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
6507           break;
6508
6509         case 'p':
6510           gas_assert (ep != NULL);
6511
6512           /*
6513            * This allows macro() to pass an immediate expression for
6514            * creating short branches without creating a symbol.
6515            *
6516            * We don't allow branch relaxation for these branches, as
6517            * they should only appear in ".set nomacro" anyway.
6518            */
6519           if (ep->X_op == O_constant)
6520             {
6521               /* For microMIPS we always use relocations for branches.
6522                  So we should not resolve immediate values.  */
6523               gas_assert (!mips_opts.micromips);
6524
6525               if ((ep->X_add_number & 3) != 0)
6526                 as_bad (_("branch to misaligned address (0x%lx)"),
6527                         (unsigned long) ep->X_add_number);
6528               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
6529                 as_bad (_("branch address range overflow (0x%lx)"),
6530                         (unsigned long) ep->X_add_number);
6531               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
6532               ep = NULL;
6533             }
6534           else
6535             *r = BFD_RELOC_16_PCREL_S2;
6536           break;
6537
6538         case 'a':
6539           gas_assert (ep != NULL);
6540           *r = BFD_RELOC_MIPS_JMP;
6541           break;
6542
6543         default:
6544           operand = (mips_opts.micromips
6545                      ? decode_micromips_operand (fmt)
6546                      : decode_mips_operand (fmt));
6547           if (!operand)
6548             abort ();
6549
6550           uval = va_arg (args, int);
6551           if (operand->type == OP_CLO_CLZ_DEST)
6552             uval |= (uval << 5);
6553           insn_insert_operand (&insn, operand, uval);
6554
6555           if (*fmt == '+' || *fmt == 'm')
6556             ++fmt;
6557           break;
6558         }
6559     }
6560   va_end (args);
6561   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
6562
6563   append_insn (&insn, ep, r, TRUE);
6564 }
6565
6566 static void
6567 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
6568                     va_list *args)
6569 {
6570   struct mips_opcode *mo;
6571   struct mips_cl_insn insn;
6572   const struct mips_operand *operand;
6573   bfd_reloc_code_real_type r[3]
6574     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
6575
6576   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
6577   gas_assert (mo);
6578   gas_assert (strcmp (name, mo->name) == 0);
6579
6580   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
6581     {
6582       ++mo;
6583       gas_assert (mo->name);
6584       gas_assert (strcmp (name, mo->name) == 0);
6585     }
6586
6587   create_insn (&insn, mo);
6588   for (; *fmt; ++fmt)
6589     {
6590       int c;
6591
6592       c = *fmt;
6593       switch (c)
6594         {
6595         case ',':
6596         case '(':
6597         case ')':
6598           break;
6599
6600         case '0':
6601         case 'S':
6602         case 'P':
6603         case 'R':
6604           break;
6605
6606         case '<':
6607         case '>':
6608         case '4':
6609         case '5':
6610         case 'H':
6611         case 'W':
6612         case 'D':
6613         case 'j':
6614         case '8':
6615         case 'V':
6616         case 'C':
6617         case 'U':
6618         case 'k':
6619         case 'K':
6620         case 'p':
6621         case 'q':
6622           {
6623             offsetT value;
6624
6625             gas_assert (ep != NULL);
6626
6627             if (ep->X_op != O_constant)
6628               *r = (int) BFD_RELOC_UNUSED + c;
6629             else if (calculate_reloc (*r, ep->X_add_number, &value))
6630               {
6631                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
6632                 ep = NULL;
6633                 *r = BFD_RELOC_UNUSED;
6634               }
6635           }
6636           break;
6637
6638         default:
6639           operand = decode_mips16_operand (c, FALSE);
6640           if (!operand)
6641             abort ();
6642
6643           insn_insert_operand (&insn, operand, va_arg (args, int));
6644           break;
6645         }
6646     }
6647
6648   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
6649
6650   append_insn (&insn, ep, r, TRUE);
6651 }
6652
6653 /*
6654  * Sign-extend 32-bit mode constants that have bit 31 set and all
6655  * higher bits unset.
6656  */
6657 static void
6658 normalize_constant_expr (expressionS *ex)
6659 {
6660   if (ex->X_op == O_constant
6661       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6662     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6663                         - 0x80000000);
6664 }
6665
6666 /*
6667  * Sign-extend 32-bit mode address offsets that have bit 31 set and
6668  * all higher bits unset.
6669  */
6670 static void
6671 normalize_address_expr (expressionS *ex)
6672 {
6673   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
6674         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
6675       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6676     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6677                         - 0x80000000);
6678 }
6679
6680 /*
6681  * Generate a "jalr" instruction with a relocation hint to the called
6682  * function.  This occurs in NewABI PIC code.
6683  */
6684 static void
6685 macro_build_jalr (expressionS *ep, int cprestore)
6686 {
6687   static const bfd_reloc_code_real_type jalr_relocs[2]
6688     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
6689   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
6690   const char *jalr;
6691   char *f = NULL;
6692
6693   if (MIPS_JALR_HINT_P (ep))
6694     {
6695       frag_grow (8);
6696       f = frag_more (0);
6697     }
6698   if (mips_opts.micromips)
6699     {
6700       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
6701               ? "jalr" : "jalrs");
6702       if (MIPS_JALR_HINT_P (ep)
6703           || mips_opts.insn32
6704           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
6705         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
6706       else
6707         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
6708     }
6709   else
6710     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
6711   if (MIPS_JALR_HINT_P (ep))
6712     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
6713 }
6714
6715 /*
6716  * Generate a "lui" instruction.
6717  */
6718 static void
6719 macro_build_lui (expressionS *ep, int regnum)
6720 {
6721   gas_assert (! mips_opts.mips16);
6722
6723   if (ep->X_op != O_constant)
6724     {
6725       gas_assert (ep->X_op == O_symbol);
6726       /* _gp_disp is a special case, used from s_cpload.
6727          __gnu_local_gp is used if mips_no_shared.  */
6728       gas_assert (mips_pic == NO_PIC
6729               || (! HAVE_NEWABI
6730                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
6731               || (! mips_in_shared
6732                   && strcmp (S_GET_NAME (ep->X_add_symbol),
6733                              "__gnu_local_gp") == 0));
6734     }
6735
6736   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
6737 }
6738
6739 /* Generate a sequence of instructions to do a load or store from a constant
6740    offset off of a base register (breg) into/from a target register (treg),
6741    using AT if necessary.  */
6742 static void
6743 macro_build_ldst_constoffset (expressionS *ep, const char *op,
6744                               int treg, int breg, int dbl)
6745 {
6746   gas_assert (ep->X_op == O_constant);
6747
6748   /* Sign-extending 32-bit constants makes their handling easier.  */
6749   if (!dbl)
6750     normalize_constant_expr (ep);
6751
6752   /* Right now, this routine can only handle signed 32-bit constants.  */
6753   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
6754     as_warn (_("operand overflow"));
6755
6756   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
6757     {
6758       /* Signed 16-bit offset will fit in the op.  Easy!  */
6759       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
6760     }
6761   else
6762     {
6763       /* 32-bit offset, need multiple instructions and AT, like:
6764            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
6765            addu     $tempreg,$tempreg,$breg
6766            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
6767          to handle the complete offset.  */
6768       macro_build_lui (ep, AT);
6769       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
6770       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
6771
6772       if (!mips_opts.at)
6773         as_bad (_("Macro used $at after \".set noat\""));
6774     }
6775 }
6776
6777 /*                      set_at()
6778  * Generates code to set the $at register to true (one)
6779  * if reg is less than the immediate expression.
6780  */
6781 static void
6782 set_at (int reg, int unsignedp)
6783 {
6784   if (imm_expr.X_op == O_constant
6785       && imm_expr.X_add_number >= -0x8000
6786       && imm_expr.X_add_number < 0x8000)
6787     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
6788                  AT, reg, BFD_RELOC_LO16);
6789   else
6790     {
6791       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6792       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
6793     }
6794 }
6795
6796 /* Count the leading zeroes by performing a binary chop. This is a
6797    bulky bit of source, but performance is a LOT better for the
6798    majority of values than a simple loop to count the bits:
6799        for (lcnt = 0; (lcnt < 32); lcnt++)
6800          if ((v) & (1 << (31 - lcnt)))
6801            break;
6802   However it is not code size friendly, and the gain will drop a bit
6803   on certain cached systems.
6804 */
6805 #define COUNT_TOP_ZEROES(v)             \
6806   (((v) & ~0xffff) == 0                 \
6807    ? ((v) & ~0xff) == 0                 \
6808      ? ((v) & ~0xf) == 0                \
6809        ? ((v) & ~0x3) == 0              \
6810          ? ((v) & ~0x1) == 0            \
6811            ? !(v)                       \
6812              ? 32                       \
6813              : 31                       \
6814            : 30                         \
6815          : ((v) & ~0x7) == 0            \
6816            ? 29                         \
6817            : 28                         \
6818        : ((v) & ~0x3f) == 0             \
6819          ? ((v) & ~0x1f) == 0           \
6820            ? 27                         \
6821            : 26                         \
6822          : ((v) & ~0x7f) == 0           \
6823            ? 25                         \
6824            : 24                         \
6825      : ((v) & ~0xfff) == 0              \
6826        ? ((v) & ~0x3ff) == 0            \
6827          ? ((v) & ~0x1ff) == 0          \
6828            ? 23                         \
6829            : 22                         \
6830          : ((v) & ~0x7ff) == 0          \
6831            ? 21                         \
6832            : 20                         \
6833        : ((v) & ~0x3fff) == 0           \
6834          ? ((v) & ~0x1fff) == 0         \
6835            ? 19                         \
6836            : 18                         \
6837          : ((v) & ~0x7fff) == 0         \
6838            ? 17                         \
6839            : 16                         \
6840    : ((v) & ~0xffffff) == 0             \
6841      ? ((v) & ~0xfffff) == 0            \
6842        ? ((v) & ~0x3ffff) == 0          \
6843          ? ((v) & ~0x1ffff) == 0        \
6844            ? 15                         \
6845            : 14                         \
6846          : ((v) & ~0x7ffff) == 0        \
6847            ? 13                         \
6848            : 12                         \
6849        : ((v) & ~0x3fffff) == 0         \
6850          ? ((v) & ~0x1fffff) == 0       \
6851            ? 11                         \
6852            : 10                         \
6853          : ((v) & ~0x7fffff) == 0       \
6854            ? 9                          \
6855            : 8                          \
6856      : ((v) & ~0xfffffff) == 0          \
6857        ? ((v) & ~0x3ffffff) == 0        \
6858          ? ((v) & ~0x1ffffff) == 0      \
6859            ? 7                          \
6860            : 6                          \
6861          : ((v) & ~0x7ffffff) == 0      \
6862            ? 5                          \
6863            : 4                          \
6864        : ((v) & ~0x3fffffff) == 0       \
6865          ? ((v) & ~0x1fffffff) == 0     \
6866            ? 3                          \
6867            : 2                          \
6868          : ((v) & ~0x7fffffff) == 0     \
6869            ? 1                          \
6870            : 0)
6871
6872 /*                      load_register()
6873  *  This routine generates the least number of instructions necessary to load
6874  *  an absolute expression value into a register.
6875  */
6876 static void
6877 load_register (int reg, expressionS *ep, int dbl)
6878 {
6879   int freg;
6880   expressionS hi32, lo32;
6881
6882   if (ep->X_op != O_big)
6883     {
6884       gas_assert (ep->X_op == O_constant);
6885
6886       /* Sign-extending 32-bit constants makes their handling easier.  */
6887       if (!dbl)
6888         normalize_constant_expr (ep);
6889
6890       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
6891         {
6892           /* We can handle 16 bit signed values with an addiu to
6893              $zero.  No need to ever use daddiu here, since $zero and
6894              the result are always correct in 32 bit mode.  */
6895           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6896           return;
6897         }
6898       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
6899         {
6900           /* We can handle 16 bit unsigned values with an ori to
6901              $zero.  */
6902           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6903           return;
6904         }
6905       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
6906         {
6907           /* 32 bit values require an lui.  */
6908           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6909           if ((ep->X_add_number & 0xffff) != 0)
6910             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6911           return;
6912         }
6913     }
6914
6915   /* The value is larger than 32 bits.  */
6916
6917   if (!dbl || HAVE_32BIT_GPRS)
6918     {
6919       char value[32];
6920
6921       sprintf_vma (value, ep->X_add_number);
6922       as_bad (_("Number (0x%s) larger than 32 bits"), value);
6923       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6924       return;
6925     }
6926
6927   if (ep->X_op != O_big)
6928     {
6929       hi32 = *ep;
6930       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6931       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6932       hi32.X_add_number &= 0xffffffff;
6933       lo32 = *ep;
6934       lo32.X_add_number &= 0xffffffff;
6935     }
6936   else
6937     {
6938       gas_assert (ep->X_add_number > 2);
6939       if (ep->X_add_number == 3)
6940         generic_bignum[3] = 0;
6941       else if (ep->X_add_number > 4)
6942         as_bad (_("Number larger than 64 bits"));
6943       lo32.X_op = O_constant;
6944       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
6945       hi32.X_op = O_constant;
6946       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
6947     }
6948
6949   if (hi32.X_add_number == 0)
6950     freg = 0;
6951   else
6952     {
6953       int shift, bit;
6954       unsigned long hi, lo;
6955
6956       if (hi32.X_add_number == (offsetT) 0xffffffff)
6957         {
6958           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
6959             {
6960               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6961               return;
6962             }
6963           if (lo32.X_add_number & 0x80000000)
6964             {
6965               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6966               if (lo32.X_add_number & 0xffff)
6967                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6968               return;
6969             }
6970         }
6971
6972       /* Check for 16bit shifted constant.  We know that hi32 is
6973          non-zero, so start the mask on the first bit of the hi32
6974          value.  */
6975       shift = 17;
6976       do
6977         {
6978           unsigned long himask, lomask;
6979
6980           if (shift < 32)
6981             {
6982               himask = 0xffff >> (32 - shift);
6983               lomask = (0xffff << shift) & 0xffffffff;
6984             }
6985           else
6986             {
6987               himask = 0xffff << (shift - 32);
6988               lomask = 0;
6989             }
6990           if ((hi32.X_add_number & ~(offsetT) himask) == 0
6991               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
6992             {
6993               expressionS tmp;
6994
6995               tmp.X_op = O_constant;
6996               if (shift < 32)
6997                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
6998                                     | (lo32.X_add_number >> shift));
6999               else
7000                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
7001               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
7002               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
7003                            reg, reg, (shift >= 32) ? shift - 32 : shift);
7004               return;
7005             }
7006           ++shift;
7007         }
7008       while (shift <= (64 - 16));
7009
7010       /* Find the bit number of the lowest one bit, and store the
7011          shifted value in hi/lo.  */
7012       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
7013       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
7014       if (lo != 0)
7015         {
7016           bit = 0;
7017           while ((lo & 1) == 0)
7018             {
7019               lo >>= 1;
7020               ++bit;
7021             }
7022           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
7023           hi >>= bit;
7024         }
7025       else
7026         {
7027           bit = 32;
7028           while ((hi & 1) == 0)
7029             {
7030               hi >>= 1;
7031               ++bit;
7032             }
7033           lo = hi;
7034           hi = 0;
7035         }
7036
7037       /* Optimize if the shifted value is a (power of 2) - 1.  */
7038       if ((hi == 0 && ((lo + 1) & lo) == 0)
7039           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
7040         {
7041           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
7042           if (shift != 0)
7043             {
7044               expressionS tmp;
7045
7046               /* This instruction will set the register to be all
7047                  ones.  */
7048               tmp.X_op = O_constant;
7049               tmp.X_add_number = (offsetT) -1;
7050               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7051               if (bit != 0)
7052                 {
7053                   bit += shift;
7054                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
7055                                reg, reg, (bit >= 32) ? bit - 32 : bit);
7056                 }
7057               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
7058                            reg, reg, (shift >= 32) ? shift - 32 : shift);
7059               return;
7060             }
7061         }
7062
7063       /* Sign extend hi32 before calling load_register, because we can
7064          generally get better code when we load a sign extended value.  */
7065       if ((hi32.X_add_number & 0x80000000) != 0)
7066         hi32.X_add_number |= ~(offsetT) 0xffffffff;
7067       load_register (reg, &hi32, 0);
7068       freg = reg;
7069     }
7070   if ((lo32.X_add_number & 0xffff0000) == 0)
7071     {
7072       if (freg != 0)
7073         {
7074           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
7075           freg = reg;
7076         }
7077     }
7078   else
7079     {
7080       expressionS mid16;
7081
7082       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
7083         {
7084           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
7085           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
7086           return;
7087         }
7088
7089       if (freg != 0)
7090         {
7091           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
7092           freg = reg;
7093         }
7094       mid16 = lo32;
7095       mid16.X_add_number >>= 16;
7096       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
7097       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7098       freg = reg;
7099     }
7100   if ((lo32.X_add_number & 0xffff) != 0)
7101     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
7102 }
7103
7104 static inline void
7105 load_delay_nop (void)
7106 {
7107   if (!gpr_interlocks)
7108     macro_build (NULL, "nop", "");
7109 }
7110
7111 /* Load an address into a register.  */
7112
7113 static void
7114 load_address (int reg, expressionS *ep, int *used_at)
7115 {
7116   if (ep->X_op != O_constant
7117       && ep->X_op != O_symbol)
7118     {
7119       as_bad (_("expression too complex"));
7120       ep->X_op = O_constant;
7121     }
7122
7123   if (ep->X_op == O_constant)
7124     {
7125       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
7126       return;
7127     }
7128
7129   if (mips_pic == NO_PIC)
7130     {
7131       /* If this is a reference to a GP relative symbol, we want
7132            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
7133          Otherwise we want
7134            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
7135            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7136          If we have an addend, we always use the latter form.
7137
7138          With 64bit address space and a usable $at we want
7139            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7140            lui          $at,<sym>               (BFD_RELOC_HI16_S)
7141            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7142            daddiu       $at,<sym>               (BFD_RELOC_LO16)
7143            dsll32       $reg,0
7144            daddu        $reg,$reg,$at
7145
7146          If $at is already in use, we use a path which is suboptimal
7147          on superscalar processors.
7148            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7149            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7150            dsll         $reg,16
7151            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
7152            dsll         $reg,16
7153            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
7154
7155          For GP relative symbols in 64bit address space we can use
7156          the same sequence as in 32bit address space.  */
7157       if (HAVE_64BIT_SYMBOLS)
7158         {
7159           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7160               && !nopic_need_relax (ep->X_add_symbol, 1))
7161             {
7162               relax_start (ep->X_add_symbol);
7163               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7164                            mips_gp_register, BFD_RELOC_GPREL16);
7165               relax_switch ();
7166             }
7167
7168           if (*used_at == 0 && mips_opts.at)
7169             {
7170               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7171               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
7172               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7173                            BFD_RELOC_MIPS_HIGHER);
7174               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
7175               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
7176               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
7177               *used_at = 1;
7178             }
7179           else
7180             {
7181               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7182               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7183                            BFD_RELOC_MIPS_HIGHER);
7184               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7185               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
7186               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7187               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
7188             }
7189
7190           if (mips_relax.sequence)
7191             relax_end ();
7192         }
7193       else
7194         {
7195           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7196               && !nopic_need_relax (ep->X_add_symbol, 1))
7197             {
7198               relax_start (ep->X_add_symbol);
7199               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7200                            mips_gp_register, BFD_RELOC_GPREL16);
7201               relax_switch ();
7202             }
7203           macro_build_lui (ep, reg);
7204           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
7205                        reg, reg, BFD_RELOC_LO16);
7206           if (mips_relax.sequence)
7207             relax_end ();
7208         }
7209     }
7210   else if (!mips_big_got)
7211     {
7212       expressionS ex;
7213
7214       /* If this is a reference to an external symbol, we want
7215            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7216          Otherwise we want
7217            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7218            nop
7219            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7220          If there is a constant, it must be added in after.
7221
7222          If we have NewABI, we want
7223            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7224          unless we're referencing a global symbol with a non-zero
7225          offset, in which case cst must be added separately.  */
7226       if (HAVE_NEWABI)
7227         {
7228           if (ep->X_add_number)
7229             {
7230               ex.X_add_number = ep->X_add_number;
7231               ep->X_add_number = 0;
7232               relax_start (ep->X_add_symbol);
7233               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7234                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7235               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7236                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7237               ex.X_op = O_constant;
7238               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7239                            reg, reg, BFD_RELOC_LO16);
7240               ep->X_add_number = ex.X_add_number;
7241               relax_switch ();
7242             }
7243           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7244                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7245           if (mips_relax.sequence)
7246             relax_end ();
7247         }
7248       else
7249         {
7250           ex.X_add_number = ep->X_add_number;
7251           ep->X_add_number = 0;
7252           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7253                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7254           load_delay_nop ();
7255           relax_start (ep->X_add_symbol);
7256           relax_switch ();
7257           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7258                        BFD_RELOC_LO16);
7259           relax_end ();
7260
7261           if (ex.X_add_number != 0)
7262             {
7263               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7264                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7265               ex.X_op = O_constant;
7266               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7267                            reg, reg, BFD_RELOC_LO16);
7268             }
7269         }
7270     }
7271   else if (mips_big_got)
7272     {
7273       expressionS ex;
7274
7275       /* This is the large GOT case.  If this is a reference to an
7276          external symbol, we want
7277            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
7278            addu         $reg,$reg,$gp
7279            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
7280
7281          Otherwise, for a reference to a local symbol in old ABI, we want
7282            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7283            nop
7284            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7285          If there is a constant, it must be added in after.
7286
7287          In the NewABI, for local symbols, with or without offsets, we want:
7288            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
7289            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
7290       */
7291       if (HAVE_NEWABI)
7292         {
7293           ex.X_add_number = ep->X_add_number;
7294           ep->X_add_number = 0;
7295           relax_start (ep->X_add_symbol);
7296           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7297           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7298                        reg, reg, mips_gp_register);
7299           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7300                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7301           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7302             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7303           else if (ex.X_add_number)
7304             {
7305               ex.X_op = O_constant;
7306               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7307                            BFD_RELOC_LO16);
7308             }
7309
7310           ep->X_add_number = ex.X_add_number;
7311           relax_switch ();
7312           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7313                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
7314           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7315                        BFD_RELOC_MIPS_GOT_OFST);
7316           relax_end ();
7317         }
7318       else
7319         {
7320           ex.X_add_number = ep->X_add_number;
7321           ep->X_add_number = 0;
7322           relax_start (ep->X_add_symbol);
7323           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7324           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7325                        reg, reg, mips_gp_register);
7326           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7327                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7328           relax_switch ();
7329           if (reg_needs_delay (mips_gp_register))
7330             {
7331               /* We need a nop before loading from $gp.  This special
7332                  check is required because the lui which starts the main
7333                  instruction stream does not refer to $gp, and so will not
7334                  insert the nop which may be required.  */
7335               macro_build (NULL, "nop", "");
7336             }
7337           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7338                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7339           load_delay_nop ();
7340           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7341                        BFD_RELOC_LO16);
7342           relax_end ();
7343
7344           if (ex.X_add_number != 0)
7345             {
7346               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7347                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7348               ex.X_op = O_constant;
7349               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7350                            BFD_RELOC_LO16);
7351             }
7352         }
7353     }
7354   else
7355     abort ();
7356
7357   if (!mips_opts.at && *used_at == 1)
7358     as_bad (_("Macro used $at after \".set noat\""));
7359 }
7360
7361 /* Move the contents of register SOURCE into register DEST.  */
7362
7363 static void
7364 move_register (int dest, int source)
7365 {
7366   /* Prefer to use a 16-bit microMIPS instruction unless the previous
7367      instruction specifically requires a 32-bit one.  */
7368   if (mips_opts.micromips
7369       && !mips_opts.insn32
7370       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
7371     macro_build (NULL, "move", "mp,mj", dest, source);
7372   else
7373     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
7374                  dest, source, 0);
7375 }
7376
7377 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
7378    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
7379    The two alternatives are:
7380
7381    Global symbol                Local sybmol
7382    -------------                ------------
7383    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
7384    ...                          ...
7385    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
7386
7387    load_got_offset emits the first instruction and add_got_offset
7388    emits the second for a 16-bit offset or add_got_offset_hilo emits
7389    a sequence to add a 32-bit offset using a scratch register.  */
7390
7391 static void
7392 load_got_offset (int dest, expressionS *local)
7393 {
7394   expressionS global;
7395
7396   global = *local;
7397   global.X_add_number = 0;
7398
7399   relax_start (local->X_add_symbol);
7400   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
7401                BFD_RELOC_MIPS_GOT16, mips_gp_register);
7402   relax_switch ();
7403   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
7404                BFD_RELOC_MIPS_GOT16, mips_gp_register);
7405   relax_end ();
7406 }
7407
7408 static void
7409 add_got_offset (int dest, expressionS *local)
7410 {
7411   expressionS global;
7412
7413   global.X_op = O_constant;
7414   global.X_op_symbol = NULL;
7415   global.X_add_symbol = NULL;
7416   global.X_add_number = local->X_add_number;
7417
7418   relax_start (local->X_add_symbol);
7419   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
7420                dest, dest, BFD_RELOC_LO16);
7421   relax_switch ();
7422   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
7423   relax_end ();
7424 }
7425
7426 static void
7427 add_got_offset_hilo (int dest, expressionS *local, int tmp)
7428 {
7429   expressionS global;
7430   int hold_mips_optimize;
7431
7432   global.X_op = O_constant;
7433   global.X_op_symbol = NULL;
7434   global.X_add_symbol = NULL;
7435   global.X_add_number = local->X_add_number;
7436
7437   relax_start (local->X_add_symbol);
7438   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
7439   relax_switch ();
7440   /* Set mips_optimize around the lui instruction to avoid
7441      inserting an unnecessary nop after the lw.  */
7442   hold_mips_optimize = mips_optimize;
7443   mips_optimize = 2;
7444   macro_build_lui (&global, tmp);
7445   mips_optimize = hold_mips_optimize;
7446   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
7447   relax_end ();
7448
7449   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
7450 }
7451
7452 /* Emit a sequence of instructions to emulate a branch likely operation.
7453    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
7454    is its complementing branch with the original condition negated.
7455    CALL is set if the original branch specified the link operation.
7456    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
7457
7458    Code like this is produced in the noreorder mode:
7459
7460         BRNEG   <args>, 1f
7461          nop
7462         b       <sym>
7463          delay slot (executed only if branch taken)
7464     1:
7465
7466    or, if CALL is set:
7467
7468         BRNEG   <args>, 1f
7469          nop
7470         bal     <sym>
7471          delay slot (executed only if branch taken)
7472     1:
7473
7474    In the reorder mode the delay slot would be filled with a nop anyway,
7475    so code produced is simply:
7476
7477         BR      <args>, <sym>
7478          nop
7479
7480    This function is used when producing code for the microMIPS ASE that
7481    does not implement branch likely instructions in hardware.  */
7482
7483 static void
7484 macro_build_branch_likely (const char *br, const char *brneg,
7485                            int call, expressionS *ep, const char *fmt,
7486                            unsigned int sreg, unsigned int treg)
7487 {
7488   int noreorder = mips_opts.noreorder;
7489   expressionS expr1;
7490
7491   gas_assert (mips_opts.micromips);
7492   start_noreorder ();
7493   if (noreorder)
7494     {
7495       micromips_label_expr (&expr1);
7496       macro_build (&expr1, brneg, fmt, sreg, treg);
7497       macro_build (NULL, "nop", "");
7498       macro_build (ep, call ? "bal" : "b", "p");
7499
7500       /* Set to true so that append_insn adds a label.  */
7501       emit_branch_likely_macro = TRUE;
7502     }
7503   else
7504     {
7505       macro_build (ep, br, fmt, sreg, treg);
7506       macro_build (NULL, "nop", "");
7507     }
7508   end_noreorder ();
7509 }
7510
7511 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
7512    the condition code tested.  EP specifies the branch target.  */
7513
7514 static void
7515 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
7516 {
7517   const int call = 0;
7518   const char *brneg;
7519   const char *br;
7520
7521   switch (type)
7522     {
7523     case M_BC1FL:
7524       br = "bc1f";
7525       brneg = "bc1t";
7526       break;
7527     case M_BC1TL:
7528       br = "bc1t";
7529       brneg = "bc1f";
7530       break;
7531     case M_BC2FL:
7532       br = "bc2f";
7533       brneg = "bc2t";
7534       break;
7535     case M_BC2TL:
7536       br = "bc2t";
7537       brneg = "bc2f";
7538       break;
7539     default:
7540       abort ();
7541     }
7542   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
7543 }
7544
7545 /* Emit a two-argument branch macro specified by TYPE, using SREG as
7546    the register tested.  EP specifies the branch target.  */
7547
7548 static void
7549 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
7550 {
7551   const char *brneg = NULL;
7552   const char *br;
7553   int call = 0;
7554
7555   switch (type)
7556     {
7557     case M_BGEZ:
7558       br = "bgez";
7559       break;
7560     case M_BGEZL:
7561       br = mips_opts.micromips ? "bgez" : "bgezl";
7562       brneg = "bltz";
7563       break;
7564     case M_BGEZALL:
7565       gas_assert (mips_opts.micromips);
7566       br = mips_opts.insn32 ? "bgezal" : "bgezals";
7567       brneg = "bltz";
7568       call = 1;
7569       break;
7570     case M_BGTZ:
7571       br = "bgtz";
7572       break;
7573     case M_BGTZL:
7574       br = mips_opts.micromips ? "bgtz" : "bgtzl";
7575       brneg = "blez";
7576       break;
7577     case M_BLEZ:
7578       br = "blez";
7579       break;
7580     case M_BLEZL:
7581       br = mips_opts.micromips ? "blez" : "blezl";
7582       brneg = "bgtz";
7583       break;
7584     case M_BLTZ:
7585       br = "bltz";
7586       break;
7587     case M_BLTZL:
7588       br = mips_opts.micromips ? "bltz" : "bltzl";
7589       brneg = "bgez";
7590       break;
7591     case M_BLTZALL:
7592       gas_assert (mips_opts.micromips);
7593       br = mips_opts.insn32 ? "bltzal" : "bltzals";
7594       brneg = "bgez";
7595       call = 1;
7596       break;
7597     default:
7598       abort ();
7599     }
7600   if (mips_opts.micromips && brneg)
7601     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
7602   else
7603     macro_build (ep, br, "s,p", sreg);
7604 }
7605
7606 /* Emit a three-argument branch macro specified by TYPE, using SREG and
7607    TREG as the registers tested.  EP specifies the branch target.  */
7608
7609 static void
7610 macro_build_branch_rsrt (int type, expressionS *ep,
7611                          unsigned int sreg, unsigned int treg)
7612 {
7613   const char *brneg = NULL;
7614   const int call = 0;
7615   const char *br;
7616
7617   switch (type)
7618     {
7619     case M_BEQ:
7620     case M_BEQ_I:
7621       br = "beq";
7622       break;
7623     case M_BEQL:
7624     case M_BEQL_I:
7625       br = mips_opts.micromips ? "beq" : "beql";
7626       brneg = "bne";
7627       break;
7628     case M_BNE:
7629     case M_BNE_I:
7630       br = "bne";
7631       break;
7632     case M_BNEL:
7633     case M_BNEL_I:
7634       br = mips_opts.micromips ? "bne" : "bnel";
7635       brneg = "beq";
7636       break;
7637     default:
7638       abort ();
7639     }
7640   if (mips_opts.micromips && brneg)
7641     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
7642   else
7643     macro_build (ep, br, "s,t,p", sreg, treg);
7644 }
7645
7646 /* Return the high part that should be loaded in order to make the low
7647    part of VALUE accessible using an offset of OFFBITS bits.  */
7648
7649 static offsetT
7650 offset_high_part (offsetT value, unsigned int offbits)
7651 {
7652   offsetT bias;
7653   addressT low_mask;
7654
7655   if (offbits == 0)
7656     return value;
7657   bias = 1 << (offbits - 1);
7658   low_mask = bias * 2 - 1;
7659   return (value + bias) & ~low_mask;
7660 }
7661
7662 /* Return true if the value stored in offset_expr and offset_reloc
7663    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
7664    amount that the caller wants to add without inducing overflow
7665    and ALIGN is the known alignment of the value in bytes.  */
7666
7667 static bfd_boolean
7668 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
7669 {
7670   if (offbits == 16)
7671     {
7672       /* Accept any relocation operator if overflow isn't a concern.  */
7673       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
7674         return TRUE;
7675
7676       /* These relocations are guaranteed not to overflow in correct links.  */
7677       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
7678           || gprel16_reloc_p (*offset_reloc))
7679         return TRUE;
7680     }
7681   if (offset_expr.X_op == O_constant
7682       && offset_high_part (offset_expr.X_add_number, offbits) == 0
7683       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
7684     return TRUE;
7685   return FALSE;
7686 }
7687
7688 /*
7689  *                      Build macros
7690  *   This routine implements the seemingly endless macro or synthesized
7691  * instructions and addressing modes in the mips assembly language. Many
7692  * of these macros are simple and are similar to each other. These could
7693  * probably be handled by some kind of table or grammar approach instead of
7694  * this verbose method. Others are not simple macros but are more like
7695  * optimizing code generation.
7696  *   One interesting optimization is when several store macros appear
7697  * consecutively that would load AT with the upper half of the same address.
7698  * The ensuing load upper instructions are ommited. This implies some kind
7699  * of global optimization. We currently only optimize within a single macro.
7700  *   For many of the load and store macros if the address is specified as a
7701  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
7702  * first load register 'at' with zero and use it as the base register. The
7703  * mips assembler simply uses register $zero. Just one tiny optimization
7704  * we're missing.
7705  */
7706 static void
7707 macro (struct mips_cl_insn *ip, char *str)
7708 {
7709   unsigned int treg, sreg, dreg, breg;
7710   unsigned int tempreg;
7711   int mask;
7712   int used_at = 0;
7713   expressionS label_expr;
7714   expressionS expr1;
7715   expressionS *ep;
7716   const char *s;
7717   const char *s2;
7718   const char *fmt;
7719   int likely = 0;
7720   int coproc = 0;
7721   int offbits = 16;
7722   int call = 0;
7723   int jals = 0;
7724   int dbl = 0;
7725   int imm = 0;
7726   int ust = 0;
7727   int lp = 0;
7728   bfd_boolean large_offset;
7729   int off;
7730   int hold_mips_optimize;
7731   unsigned int align;
7732
7733   gas_assert (! mips_opts.mips16);
7734
7735   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
7736   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
7737   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
7738   mask = ip->insn_mo->mask;
7739
7740   label_expr.X_op = O_constant;
7741   label_expr.X_op_symbol = NULL;
7742   label_expr.X_add_symbol = NULL;
7743   label_expr.X_add_number = 0;
7744
7745   expr1.X_op = O_constant;
7746   expr1.X_op_symbol = NULL;
7747   expr1.X_add_symbol = NULL;
7748   expr1.X_add_number = 1;
7749   align = 1;
7750
7751   switch (mask)
7752     {
7753     case M_DABS:
7754       dbl = 1;
7755     case M_ABS:
7756       /*    bgez    $a0,1f
7757             move    v0,$a0
7758             sub     v0,$zero,$a0
7759          1:
7760        */
7761
7762       start_noreorder ();
7763
7764       if (mips_opts.micromips)
7765         micromips_label_expr (&label_expr);
7766       else
7767         label_expr.X_add_number = 8;
7768       macro_build (&label_expr, "bgez", "s,p", sreg);
7769       if (dreg == sreg)
7770         macro_build (NULL, "nop", "");
7771       else
7772         move_register (dreg, sreg);
7773       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
7774       if (mips_opts.micromips)
7775         micromips_add_label ();
7776
7777       end_noreorder ();
7778       break;
7779
7780     case M_ADD_I:
7781       s = "addi";
7782       s2 = "add";
7783       goto do_addi;
7784     case M_ADDU_I:
7785       s = "addiu";
7786       s2 = "addu";
7787       goto do_addi;
7788     case M_DADD_I:
7789       dbl = 1;
7790       s = "daddi";
7791       s2 = "dadd";
7792       if (!mips_opts.micromips)
7793         goto do_addi;
7794       if (imm_expr.X_op == O_constant
7795           && imm_expr.X_add_number >= -0x200
7796           && imm_expr.X_add_number < 0x200)
7797         {
7798           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
7799           break;
7800         }
7801       goto do_addi_i;
7802     case M_DADDU_I:
7803       dbl = 1;
7804       s = "daddiu";
7805       s2 = "daddu";
7806     do_addi:
7807       if (imm_expr.X_op == O_constant
7808           && imm_expr.X_add_number >= -0x8000
7809           && imm_expr.X_add_number < 0x8000)
7810         {
7811           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
7812           break;
7813         }
7814     do_addi_i:
7815       used_at = 1;
7816       load_register (AT, &imm_expr, dbl);
7817       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7818       break;
7819
7820     case M_AND_I:
7821       s = "andi";
7822       s2 = "and";
7823       goto do_bit;
7824     case M_OR_I:
7825       s = "ori";
7826       s2 = "or";
7827       goto do_bit;
7828     case M_NOR_I:
7829       s = "";
7830       s2 = "nor";
7831       goto do_bit;
7832     case M_XOR_I:
7833       s = "xori";
7834       s2 = "xor";
7835     do_bit:
7836       if (imm_expr.X_op == O_constant
7837           && imm_expr.X_add_number >= 0
7838           && imm_expr.X_add_number < 0x10000)
7839         {
7840           if (mask != M_NOR_I)
7841             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
7842           else
7843             {
7844               macro_build (&imm_expr, "ori", "t,r,i",
7845                            treg, sreg, BFD_RELOC_LO16);
7846               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
7847             }
7848           break;
7849         }
7850
7851       used_at = 1;
7852       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7853       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7854       break;
7855
7856     case M_BALIGN:
7857       switch (imm_expr.X_add_number)
7858         {
7859         case 0:
7860           macro_build (NULL, "nop", "");
7861           break;
7862         case 2:
7863           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
7864           break;
7865         case 1:
7866         case 3:
7867           macro_build (NULL, "balign", "t,s,2", treg, sreg,
7868                        (int) imm_expr.X_add_number);
7869           break;
7870         default:
7871           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
7872                   (unsigned long) imm_expr.X_add_number);
7873           break;
7874         }
7875       break;
7876
7877     case M_BC1FL:
7878     case M_BC1TL:
7879     case M_BC2FL:
7880     case M_BC2TL:
7881       gas_assert (mips_opts.micromips);
7882       macro_build_branch_ccl (mask, &offset_expr,
7883                               EXTRACT_OPERAND (1, BCC, *ip));
7884       break;
7885
7886     case M_BEQ_I:
7887     case M_BEQL_I:
7888     case M_BNE_I:
7889     case M_BNEL_I:
7890       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7891         treg = 0;
7892       else
7893         {
7894           treg = AT;
7895           used_at = 1;
7896           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
7897         }
7898       /* Fall through.  */
7899     case M_BEQL:
7900     case M_BNEL:
7901       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
7902       break;
7903
7904     case M_BGEL:
7905       likely = 1;
7906     case M_BGE:
7907       if (treg == 0)
7908         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
7909       else if (sreg == 0)
7910         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
7911       else
7912         {
7913           used_at = 1;
7914           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
7915           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7916                                    &offset_expr, AT, ZERO);
7917         }
7918       break;
7919
7920     case M_BGEZL:
7921     case M_BGEZALL:
7922     case M_BGTZL:
7923     case M_BLEZL:
7924     case M_BLTZL:
7925     case M_BLTZALL:
7926       macro_build_branch_rs (mask, &offset_expr, sreg);
7927       break;
7928
7929     case M_BGTL_I:
7930       likely = 1;
7931     case M_BGT_I:
7932       /* Check for > max integer.  */
7933       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
7934         {
7935         do_false:
7936           /* Result is always false.  */
7937           if (! likely)
7938             macro_build (NULL, "nop", "");
7939           else
7940             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
7941           break;
7942         }
7943       if (imm_expr.X_op != O_constant)
7944         as_bad (_("Unsupported large constant"));
7945       ++imm_expr.X_add_number;
7946       /* FALLTHROUGH */
7947     case M_BGE_I:
7948     case M_BGEL_I:
7949       if (mask == M_BGEL_I)
7950         likely = 1;
7951       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7952         {
7953           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
7954                                  &offset_expr, sreg);
7955           break;
7956         }
7957       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7958         {
7959           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
7960                                  &offset_expr, sreg);
7961           break;
7962         }
7963       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
7964         {
7965         do_true:
7966           /* result is always true */
7967           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
7968           macro_build (&offset_expr, "b", "p");
7969           break;
7970         }
7971       used_at = 1;
7972       set_at (sreg, 0);
7973       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7974                                &offset_expr, AT, ZERO);
7975       break;
7976
7977     case M_BGEUL:
7978       likely = 1;
7979     case M_BGEU:
7980       if (treg == 0)
7981         goto do_true;
7982       else if (sreg == 0)
7983         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7984                                  &offset_expr, ZERO, treg);
7985       else
7986         {
7987           used_at = 1;
7988           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
7989           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7990                                    &offset_expr, AT, ZERO);
7991         }
7992       break;
7993
7994     case M_BGTUL_I:
7995       likely = 1;
7996     case M_BGTU_I:
7997       if (sreg == 0
7998           || (HAVE_32BIT_GPRS
7999               && imm_expr.X_op == O_constant
8000               && imm_expr.X_add_number == -1))
8001         goto do_false;
8002       if (imm_expr.X_op != O_constant)
8003         as_bad (_("Unsupported large constant"));
8004       ++imm_expr.X_add_number;
8005       /* FALLTHROUGH */
8006     case M_BGEU_I:
8007     case M_BGEUL_I:
8008       if (mask == M_BGEUL_I)
8009         likely = 1;
8010       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8011         goto do_true;
8012       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8013         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8014                                  &offset_expr, sreg, ZERO);
8015       else
8016         {
8017           used_at = 1;
8018           set_at (sreg, 1);
8019           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8020                                    &offset_expr, AT, ZERO);
8021         }
8022       break;
8023
8024     case M_BGTL:
8025       likely = 1;
8026     case M_BGT:
8027       if (treg == 0)
8028         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
8029       else if (sreg == 0)
8030         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
8031       else
8032         {
8033           used_at = 1;
8034           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
8035           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8036                                    &offset_expr, AT, ZERO);
8037         }
8038       break;
8039
8040     case M_BGTUL:
8041       likely = 1;
8042     case M_BGTU:
8043       if (treg == 0)
8044         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8045                                  &offset_expr, sreg, ZERO);
8046       else if (sreg == 0)
8047         goto do_false;
8048       else
8049         {
8050           used_at = 1;
8051           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
8052           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8053                                    &offset_expr, AT, ZERO);
8054         }
8055       break;
8056
8057     case M_BLEL:
8058       likely = 1;
8059     case M_BLE:
8060       if (treg == 0)
8061         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
8062       else if (sreg == 0)
8063         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
8064       else
8065         {
8066           used_at = 1;
8067           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
8068           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8069                                    &offset_expr, AT, ZERO);
8070         }
8071       break;
8072
8073     case M_BLEL_I:
8074       likely = 1;
8075     case M_BLE_I:
8076       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
8077         goto do_true;
8078       if (imm_expr.X_op != O_constant)
8079         as_bad (_("Unsupported large constant"));
8080       ++imm_expr.X_add_number;
8081       /* FALLTHROUGH */
8082     case M_BLT_I:
8083     case M_BLTL_I:
8084       if (mask == M_BLTL_I)
8085         likely = 1;
8086       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8087         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
8088       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8089         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
8090       else
8091         {
8092           used_at = 1;
8093           set_at (sreg, 0);
8094           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8095                                    &offset_expr, AT, ZERO);
8096         }
8097       break;
8098
8099     case M_BLEUL:
8100       likely = 1;
8101     case M_BLEU:
8102       if (treg == 0)
8103         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8104                                  &offset_expr, sreg, ZERO);
8105       else if (sreg == 0)
8106         goto do_true;
8107       else
8108         {
8109           used_at = 1;
8110           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
8111           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8112                                    &offset_expr, AT, ZERO);
8113         }
8114       break;
8115
8116     case M_BLEUL_I:
8117       likely = 1;
8118     case M_BLEU_I:
8119       if (sreg == 0
8120           || (HAVE_32BIT_GPRS
8121               && imm_expr.X_op == O_constant
8122               && imm_expr.X_add_number == -1))
8123         goto do_true;
8124       if (imm_expr.X_op != O_constant)
8125         as_bad (_("Unsupported large constant"));
8126       ++imm_expr.X_add_number;
8127       /* FALLTHROUGH */
8128     case M_BLTU_I:
8129     case M_BLTUL_I:
8130       if (mask == M_BLTUL_I)
8131         likely = 1;
8132       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8133         goto do_false;
8134       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8135         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8136                                  &offset_expr, sreg, ZERO);
8137       else
8138         {
8139           used_at = 1;
8140           set_at (sreg, 1);
8141           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8142                                    &offset_expr, AT, ZERO);
8143         }
8144       break;
8145
8146     case M_BLTL:
8147       likely = 1;
8148     case M_BLT:
8149       if (treg == 0)
8150         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
8151       else if (sreg == 0)
8152         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
8153       else
8154         {
8155           used_at = 1;
8156           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
8157           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8158                                    &offset_expr, AT, ZERO);
8159         }
8160       break;
8161
8162     case M_BLTUL:
8163       likely = 1;
8164     case M_BLTU:
8165       if (treg == 0)
8166         goto do_false;
8167       else if (sreg == 0)
8168         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8169                                  &offset_expr, ZERO, treg);
8170       else
8171         {
8172           used_at = 1;
8173           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
8174           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8175                                    &offset_expr, AT, ZERO);
8176         }
8177       break;
8178
8179     case M_DEXT:
8180       {
8181         /* Use unsigned arithmetic.  */
8182         addressT pos;
8183         addressT size;
8184
8185         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8186           {
8187             as_bad (_("Unsupported large constant"));
8188             pos = size = 1;
8189           }
8190         else
8191           {
8192             pos = imm_expr.X_add_number;
8193             size = imm2_expr.X_add_number;
8194           }
8195
8196         if (pos > 63)
8197           {
8198             report_bad_range (ip, 3, pos, 0, 63, FALSE);
8199             pos = 1;
8200           }
8201         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8202           {
8203             report_bad_field (pos, size);
8204             size = 1;
8205           }
8206
8207         if (size <= 32 && pos < 32)
8208           {
8209             s = "dext";
8210             fmt = "t,r,+A,+C";
8211           }
8212         else if (size <= 32)
8213           {
8214             s = "dextu";
8215             fmt = "t,r,+E,+H";
8216           }
8217         else
8218           {
8219             s = "dextm";
8220             fmt = "t,r,+A,+G";
8221           }
8222         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
8223                      (int) (size - 1));
8224       }
8225       break;
8226
8227     case M_DINS:
8228       {
8229         /* Use unsigned arithmetic.  */
8230         addressT pos;
8231         addressT size;
8232
8233         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8234           {
8235             as_bad (_("Unsupported large constant"));
8236             pos = size = 1;
8237           }
8238         else
8239           {
8240             pos = imm_expr.X_add_number;
8241             size = imm2_expr.X_add_number;
8242           }
8243
8244         if (pos > 63)
8245           {
8246             report_bad_range (ip, 3, pos, 0, 63, FALSE);
8247             pos = 1;
8248           }
8249         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8250           {
8251             report_bad_field (pos, size);
8252             size = 1;
8253           }
8254
8255         if (pos < 32 && (pos + size - 1) < 32)
8256           {
8257             s = "dins";
8258             fmt = "t,r,+A,+B";
8259           }
8260         else if (pos >= 32)
8261           {
8262             s = "dinsu";
8263             fmt = "t,r,+E,+F";
8264           }
8265         else
8266           {
8267             s = "dinsm";
8268             fmt = "t,r,+A,+F";
8269           }
8270         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
8271                      (int) (pos + size - 1));
8272       }
8273       break;
8274
8275     case M_DDIV_3:
8276       dbl = 1;
8277     case M_DIV_3:
8278       s = "mflo";
8279       goto do_div3;
8280     case M_DREM_3:
8281       dbl = 1;
8282     case M_REM_3:
8283       s = "mfhi";
8284     do_div3:
8285       if (treg == 0)
8286         {
8287           as_warn (_("Divide by zero."));
8288           if (mips_trap)
8289             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8290           else
8291             macro_build (NULL, "break", BRK_FMT, 7);
8292           break;
8293         }
8294
8295       start_noreorder ();
8296       if (mips_trap)
8297         {
8298           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
8299           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
8300         }
8301       else
8302         {
8303           if (mips_opts.micromips)
8304             micromips_label_expr (&label_expr);
8305           else
8306             label_expr.X_add_number = 8;
8307           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
8308           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
8309           macro_build (NULL, "break", BRK_FMT, 7);
8310           if (mips_opts.micromips)
8311             micromips_add_label ();
8312         }
8313       expr1.X_add_number = -1;
8314       used_at = 1;
8315       load_register (AT, &expr1, dbl);
8316       if (mips_opts.micromips)
8317         micromips_label_expr (&label_expr);
8318       else
8319         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
8320       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
8321       if (dbl)
8322         {
8323           expr1.X_add_number = 1;
8324           load_register (AT, &expr1, dbl);
8325           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
8326         }
8327       else
8328         {
8329           expr1.X_add_number = 0x80000000;
8330           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
8331         }
8332       if (mips_trap)
8333         {
8334           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
8335           /* We want to close the noreorder block as soon as possible, so
8336              that later insns are available for delay slot filling.  */
8337           end_noreorder ();
8338         }
8339       else
8340         {
8341           if (mips_opts.micromips)
8342             micromips_label_expr (&label_expr);
8343           else
8344             label_expr.X_add_number = 8;
8345           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
8346           macro_build (NULL, "nop", "");
8347
8348           /* We want to close the noreorder block as soon as possible, so
8349              that later insns are available for delay slot filling.  */
8350           end_noreorder ();
8351
8352           macro_build (NULL, "break", BRK_FMT, 6);
8353         }
8354       if (mips_opts.micromips)
8355         micromips_add_label ();
8356       macro_build (NULL, s, MFHL_FMT, dreg);
8357       break;
8358
8359     case M_DIV_3I:
8360       s = "div";
8361       s2 = "mflo";
8362       goto do_divi;
8363     case M_DIVU_3I:
8364       s = "divu";
8365       s2 = "mflo";
8366       goto do_divi;
8367     case M_REM_3I:
8368       s = "div";
8369       s2 = "mfhi";
8370       goto do_divi;
8371     case M_REMU_3I:
8372       s = "divu";
8373       s2 = "mfhi";
8374       goto do_divi;
8375     case M_DDIV_3I:
8376       dbl = 1;
8377       s = "ddiv";
8378       s2 = "mflo";
8379       goto do_divi;
8380     case M_DDIVU_3I:
8381       dbl = 1;
8382       s = "ddivu";
8383       s2 = "mflo";
8384       goto do_divi;
8385     case M_DREM_3I:
8386       dbl = 1;
8387       s = "ddiv";
8388       s2 = "mfhi";
8389       goto do_divi;
8390     case M_DREMU_3I:
8391       dbl = 1;
8392       s = "ddivu";
8393       s2 = "mfhi";
8394     do_divi:
8395       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8396         {
8397           as_warn (_("Divide by zero."));
8398           if (mips_trap)
8399             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8400           else
8401             macro_build (NULL, "break", BRK_FMT, 7);
8402           break;
8403         }
8404       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8405         {
8406           if (strcmp (s2, "mflo") == 0)
8407             move_register (dreg, sreg);
8408           else
8409             move_register (dreg, ZERO);
8410           break;
8411         }
8412       if (imm_expr.X_op == O_constant
8413           && imm_expr.X_add_number == -1
8414           && s[strlen (s) - 1] != 'u')
8415         {
8416           if (strcmp (s2, "mflo") == 0)
8417             {
8418               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
8419             }
8420           else
8421             move_register (dreg, ZERO);
8422           break;
8423         }
8424
8425       used_at = 1;
8426       load_register (AT, &imm_expr, dbl);
8427       macro_build (NULL, s, "z,s,t", sreg, AT);
8428       macro_build (NULL, s2, MFHL_FMT, dreg);
8429       break;
8430
8431     case M_DIVU_3:
8432       s = "divu";
8433       s2 = "mflo";
8434       goto do_divu3;
8435     case M_REMU_3:
8436       s = "divu";
8437       s2 = "mfhi";
8438       goto do_divu3;
8439     case M_DDIVU_3:
8440       s = "ddivu";
8441       s2 = "mflo";
8442       goto do_divu3;
8443     case M_DREMU_3:
8444       s = "ddivu";
8445       s2 = "mfhi";
8446     do_divu3:
8447       start_noreorder ();
8448       if (mips_trap)
8449         {
8450           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
8451           macro_build (NULL, s, "z,s,t", sreg, treg);
8452           /* We want to close the noreorder block as soon as possible, so
8453              that later insns are available for delay slot filling.  */
8454           end_noreorder ();
8455         }
8456       else
8457         {
8458           if (mips_opts.micromips)
8459             micromips_label_expr (&label_expr);
8460           else
8461             label_expr.X_add_number = 8;
8462           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
8463           macro_build (NULL, s, "z,s,t", sreg, treg);
8464
8465           /* We want to close the noreorder block as soon as possible, so
8466              that later insns are available for delay slot filling.  */
8467           end_noreorder ();
8468           macro_build (NULL, "break", BRK_FMT, 7);
8469           if (mips_opts.micromips)
8470             micromips_add_label ();
8471         }
8472       macro_build (NULL, s2, MFHL_FMT, dreg);
8473       break;
8474
8475     case M_DLCA_AB:
8476       dbl = 1;
8477     case M_LCA_AB:
8478       call = 1;
8479       goto do_la;
8480     case M_DLA_AB:
8481       dbl = 1;
8482     case M_LA_AB:
8483     do_la:
8484       /* Load the address of a symbol into a register.  If breg is not
8485          zero, we then add a base register to it.  */
8486
8487       if (dbl && HAVE_32BIT_GPRS)
8488         as_warn (_("dla used to load 32-bit register"));
8489
8490       if (!dbl && HAVE_64BIT_OBJECTS)
8491         as_warn (_("la used to load 64-bit address"));
8492
8493       if (small_offset_p (0, align, 16))
8494         {
8495           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", treg, breg,
8496                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
8497           break;
8498         }
8499
8500       if (mips_opts.at && (treg == breg))
8501         {
8502           tempreg = AT;
8503           used_at = 1;
8504         }
8505       else
8506         {
8507           tempreg = treg;
8508         }
8509
8510       if (offset_expr.X_op != O_symbol
8511           && offset_expr.X_op != O_constant)
8512         {
8513           as_bad (_("Expression too complex"));
8514           offset_expr.X_op = O_constant;
8515         }
8516
8517       if (offset_expr.X_op == O_constant)
8518         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
8519       else if (mips_pic == NO_PIC)
8520         {
8521           /* If this is a reference to a GP relative symbol, we want
8522                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
8523              Otherwise we want
8524                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8525                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8526              If we have a constant, we need two instructions anyhow,
8527              so we may as well always use the latter form.
8528
8529              With 64bit address space and a usable $at we want
8530                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8531                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8532                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8533                daddiu   $at,<sym>               (BFD_RELOC_LO16)
8534                dsll32   $tempreg,0
8535                daddu    $tempreg,$tempreg,$at
8536
8537              If $at is already in use, we use a path which is suboptimal
8538              on superscalar processors.
8539                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8540                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8541                dsll     $tempreg,16
8542                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8543                dsll     $tempreg,16
8544                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
8545
8546              For GP relative symbols in 64bit address space we can use
8547              the same sequence as in 32bit address space.  */
8548           if (HAVE_64BIT_SYMBOLS)
8549             {
8550               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8551                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8552                 {
8553                   relax_start (offset_expr.X_add_symbol);
8554                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8555                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
8556                   relax_switch ();
8557                 }
8558
8559               if (used_at == 0 && mips_opts.at)
8560                 {
8561                   macro_build (&offset_expr, "lui", LUI_FMT,
8562                                tempreg, BFD_RELOC_MIPS_HIGHEST);
8563                   macro_build (&offset_expr, "lui", LUI_FMT,
8564                                AT, BFD_RELOC_HI16_S);
8565                   macro_build (&offset_expr, "daddiu", "t,r,j",
8566                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
8567                   macro_build (&offset_expr, "daddiu", "t,r,j",
8568                                AT, AT, BFD_RELOC_LO16);
8569                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
8570                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
8571                   used_at = 1;
8572                 }
8573               else
8574                 {
8575                   macro_build (&offset_expr, "lui", LUI_FMT,
8576                                tempreg, BFD_RELOC_MIPS_HIGHEST);
8577                   macro_build (&offset_expr, "daddiu", "t,r,j",
8578                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
8579                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8580                   macro_build (&offset_expr, "daddiu", "t,r,j",
8581                                tempreg, tempreg, BFD_RELOC_HI16_S);
8582                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8583                   macro_build (&offset_expr, "daddiu", "t,r,j",
8584                                tempreg, tempreg, BFD_RELOC_LO16);
8585                 }
8586
8587               if (mips_relax.sequence)
8588                 relax_end ();
8589             }
8590           else
8591             {
8592               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8593                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8594                 {
8595                   relax_start (offset_expr.X_add_symbol);
8596                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8597                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
8598                   relax_switch ();
8599                 }
8600               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8601                 as_bad (_("Offset too large"));
8602               macro_build_lui (&offset_expr, tempreg);
8603               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8604                            tempreg, tempreg, BFD_RELOC_LO16);
8605               if (mips_relax.sequence)
8606                 relax_end ();
8607             }
8608         }
8609       else if (!mips_big_got && !HAVE_NEWABI)
8610         {
8611           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8612
8613           /* If this is a reference to an external symbol, and there
8614              is no constant, we want
8615                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8616              or for lca or if tempreg is PIC_CALL_REG
8617                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
8618              For a local symbol, we want
8619                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8620                nop
8621                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8622
8623              If we have a small constant, and this is a reference to
8624              an external symbol, we want
8625                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8626                nop
8627                addiu    $tempreg,$tempreg,<constant>
8628              For a local symbol, we want the same instruction
8629              sequence, but we output a BFD_RELOC_LO16 reloc on the
8630              addiu instruction.
8631
8632              If we have a large constant, and this is a reference to
8633              an external symbol, we want
8634                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8635                lui      $at,<hiconstant>
8636                addiu    $at,$at,<loconstant>
8637                addu     $tempreg,$tempreg,$at
8638              For a local symbol, we want the same instruction
8639              sequence, but we output a BFD_RELOC_LO16 reloc on the
8640              addiu instruction.
8641            */
8642
8643           if (offset_expr.X_add_number == 0)
8644             {
8645               if (mips_pic == SVR4_PIC
8646                   && breg == 0
8647                   && (call || tempreg == PIC_CALL_REG))
8648                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
8649
8650               relax_start (offset_expr.X_add_symbol);
8651               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8652                            lw_reloc_type, mips_gp_register);
8653               if (breg != 0)
8654                 {
8655                   /* We're going to put in an addu instruction using
8656                      tempreg, so we may as well insert the nop right
8657                      now.  */
8658                   load_delay_nop ();
8659                 }
8660               relax_switch ();
8661               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8662                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
8663               load_delay_nop ();
8664               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8665                            tempreg, tempreg, BFD_RELOC_LO16);
8666               relax_end ();
8667               /* FIXME: If breg == 0, and the next instruction uses
8668                  $tempreg, then if this variant case is used an extra
8669                  nop will be generated.  */
8670             }
8671           else if (offset_expr.X_add_number >= -0x8000
8672                    && offset_expr.X_add_number < 0x8000)
8673             {
8674               load_got_offset (tempreg, &offset_expr);
8675               load_delay_nop ();
8676               add_got_offset (tempreg, &offset_expr);
8677             }
8678           else
8679             {
8680               expr1.X_add_number = offset_expr.X_add_number;
8681               offset_expr.X_add_number =
8682                 SEXT_16BIT (offset_expr.X_add_number);
8683               load_got_offset (tempreg, &offset_expr);
8684               offset_expr.X_add_number = expr1.X_add_number;
8685               /* If we are going to add in a base register, and the
8686                  target register and the base register are the same,
8687                  then we are using AT as a temporary register.  Since
8688                  we want to load the constant into AT, we add our
8689                  current AT (from the global offset table) and the
8690                  register into the register now, and pretend we were
8691                  not using a base register.  */
8692               if (breg == treg)
8693                 {
8694                   load_delay_nop ();
8695                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8696                                treg, AT, breg);
8697                   breg = 0;
8698                   tempreg = treg;
8699                 }
8700               add_got_offset_hilo (tempreg, &offset_expr, AT);
8701               used_at = 1;
8702             }
8703         }
8704       else if (!mips_big_got && HAVE_NEWABI)
8705         {
8706           int add_breg_early = 0;
8707
8708           /* If this is a reference to an external, and there is no
8709              constant, or local symbol (*), with or without a
8710              constant, we want
8711                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8712              or for lca or if tempreg is PIC_CALL_REG
8713                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
8714
8715              If we have a small constant, and this is a reference to
8716              an external symbol, we want
8717                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8718                addiu    $tempreg,$tempreg,<constant>
8719
8720              If we have a large constant, and this is a reference to
8721              an external symbol, we want
8722                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8723                lui      $at,<hiconstant>
8724                addiu    $at,$at,<loconstant>
8725                addu     $tempreg,$tempreg,$at
8726
8727              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
8728              local symbols, even though it introduces an additional
8729              instruction.  */
8730
8731           if (offset_expr.X_add_number)
8732             {
8733               expr1.X_add_number = offset_expr.X_add_number;
8734               offset_expr.X_add_number = 0;
8735
8736               relax_start (offset_expr.X_add_symbol);
8737               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8738                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8739
8740               if (expr1.X_add_number >= -0x8000
8741                   && expr1.X_add_number < 0x8000)
8742                 {
8743                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8744                                tempreg, tempreg, BFD_RELOC_LO16);
8745                 }
8746               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8747                 {
8748                   /* If we are going to add in a base register, and the
8749                      target register and the base register are the same,
8750                      then we are using AT as a temporary register.  Since
8751                      we want to load the constant into AT, we add our
8752                      current AT (from the global offset table) and the
8753                      register into the register now, and pretend we were
8754                      not using a base register.  */
8755                   if (breg != treg)
8756                     dreg = tempreg;
8757                   else
8758                     {
8759                       gas_assert (tempreg == AT);
8760                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8761                                    treg, AT, breg);
8762                       dreg = treg;
8763                       add_breg_early = 1;
8764                     }
8765
8766                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8767                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8768                                dreg, dreg, AT);
8769
8770                   used_at = 1;
8771                 }
8772               else
8773                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
8774
8775               relax_switch ();
8776               offset_expr.X_add_number = expr1.X_add_number;
8777
8778               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8779                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8780               if (add_breg_early)
8781                 {
8782                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8783                                treg, tempreg, breg);
8784                   breg = 0;
8785                   tempreg = treg;
8786                 }
8787               relax_end ();
8788             }
8789           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
8790             {
8791               relax_start (offset_expr.X_add_symbol);
8792               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8793                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
8794               relax_switch ();
8795               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8796                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8797               relax_end ();
8798             }
8799           else
8800             {
8801               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8802                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8803             }
8804         }
8805       else if (mips_big_got && !HAVE_NEWABI)
8806         {
8807           int gpdelay;
8808           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8809           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8810           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8811
8812           /* This is the large GOT case.  If this is a reference to an
8813              external symbol, and there is no constant, we want
8814                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8815                addu     $tempreg,$tempreg,$gp
8816                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8817              or for lca or if tempreg is PIC_CALL_REG
8818                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8819                addu     $tempreg,$tempreg,$gp
8820                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8821              For a local symbol, we want
8822                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8823                nop
8824                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8825
8826              If we have a small constant, and this is a reference to
8827              an external symbol, we want
8828                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8829                addu     $tempreg,$tempreg,$gp
8830                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8831                nop
8832                addiu    $tempreg,$tempreg,<constant>
8833              For a local symbol, we want
8834                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8835                nop
8836                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
8837
8838              If we have a large constant, and this is a reference to
8839              an external symbol, we want
8840                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8841                addu     $tempreg,$tempreg,$gp
8842                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8843                lui      $at,<hiconstant>
8844                addiu    $at,$at,<loconstant>
8845                addu     $tempreg,$tempreg,$at
8846              For a local symbol, we want
8847                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8848                lui      $at,<hiconstant>
8849                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
8850                addu     $tempreg,$tempreg,$at
8851           */
8852
8853           expr1.X_add_number = offset_expr.X_add_number;
8854           offset_expr.X_add_number = 0;
8855           relax_start (offset_expr.X_add_symbol);
8856           gpdelay = reg_needs_delay (mips_gp_register);
8857           if (expr1.X_add_number == 0 && breg == 0
8858               && (call || tempreg == PIC_CALL_REG))
8859             {
8860               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8861               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8862             }
8863           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8864           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8865                        tempreg, tempreg, mips_gp_register);
8866           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8867                        tempreg, lw_reloc_type, tempreg);
8868           if (expr1.X_add_number == 0)
8869             {
8870               if (breg != 0)
8871                 {
8872                   /* We're going to put in an addu instruction using
8873                      tempreg, so we may as well insert the nop right
8874                      now.  */
8875                   load_delay_nop ();
8876                 }
8877             }
8878           else if (expr1.X_add_number >= -0x8000
8879                    && expr1.X_add_number < 0x8000)
8880             {
8881               load_delay_nop ();
8882               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8883                            tempreg, tempreg, BFD_RELOC_LO16);
8884             }
8885           else
8886             {
8887               /* If we are going to add in a base register, and the
8888                  target register and the base register are the same,
8889                  then we are using AT as a temporary register.  Since
8890                  we want to load the constant into AT, we add our
8891                  current AT (from the global offset table) and the
8892                  register into the register now, and pretend we were
8893                  not using a base register.  */
8894               if (breg != treg)
8895                 dreg = tempreg;
8896               else
8897                 {
8898                   gas_assert (tempreg == AT);
8899                   load_delay_nop ();
8900                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8901                                treg, AT, breg);
8902                   dreg = treg;
8903                 }
8904
8905               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8906               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
8907
8908               used_at = 1;
8909             }
8910           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
8911           relax_switch ();
8912
8913           if (gpdelay)
8914             {
8915               /* This is needed because this instruction uses $gp, but
8916                  the first instruction on the main stream does not.  */
8917               macro_build (NULL, "nop", "");
8918             }
8919
8920           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8921                        local_reloc_type, mips_gp_register);
8922           if (expr1.X_add_number >= -0x8000
8923               && expr1.X_add_number < 0x8000)
8924             {
8925               load_delay_nop ();
8926               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8927                            tempreg, tempreg, BFD_RELOC_LO16);
8928               /* FIXME: If add_number is 0, and there was no base
8929                  register, the external symbol case ended with a load,
8930                  so if the symbol turns out to not be external, and
8931                  the next instruction uses tempreg, an unnecessary nop
8932                  will be inserted.  */
8933             }
8934           else
8935             {
8936               if (breg == treg)
8937                 {
8938                   /* We must add in the base register now, as in the
8939                      external symbol case.  */
8940                   gas_assert (tempreg == AT);
8941                   load_delay_nop ();
8942                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8943                                treg, AT, breg);
8944                   tempreg = treg;
8945                   /* We set breg to 0 because we have arranged to add
8946                      it in in both cases.  */
8947                   breg = 0;
8948                 }
8949
8950               macro_build_lui (&expr1, AT);
8951               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8952                            AT, AT, BFD_RELOC_LO16);
8953               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8954                            tempreg, tempreg, AT);
8955               used_at = 1;
8956             }
8957           relax_end ();
8958         }
8959       else if (mips_big_got && HAVE_NEWABI)
8960         {
8961           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8962           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8963           int add_breg_early = 0;
8964
8965           /* This is the large GOT case.  If this is a reference to an
8966              external symbol, and there is no constant, we want
8967                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8968                add      $tempreg,$tempreg,$gp
8969                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8970              or for lca or if tempreg is PIC_CALL_REG
8971                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8972                add      $tempreg,$tempreg,$gp
8973                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8974
8975              If we have a small constant, and this is a reference to
8976              an external symbol, we want
8977                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8978                add      $tempreg,$tempreg,$gp
8979                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8980                addi     $tempreg,$tempreg,<constant>
8981
8982              If we have a large constant, and this is a reference to
8983              an external symbol, we want
8984                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8985                addu     $tempreg,$tempreg,$gp
8986                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8987                lui      $at,<hiconstant>
8988                addi     $at,$at,<loconstant>
8989                add      $tempreg,$tempreg,$at
8990
8991              If we have NewABI, and we know it's a local symbol, we want
8992                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8993                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8994              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
8995
8996           relax_start (offset_expr.X_add_symbol);
8997
8998           expr1.X_add_number = offset_expr.X_add_number;
8999           offset_expr.X_add_number = 0;
9000
9001           if (expr1.X_add_number == 0 && breg == 0
9002               && (call || tempreg == PIC_CALL_REG))
9003             {
9004               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
9005               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
9006             }
9007           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
9008           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9009                        tempreg, tempreg, mips_gp_register);
9010           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9011                        tempreg, lw_reloc_type, tempreg);
9012
9013           if (expr1.X_add_number == 0)
9014             ;
9015           else if (expr1.X_add_number >= -0x8000
9016                    && expr1.X_add_number < 0x8000)
9017             {
9018               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9019                            tempreg, tempreg, BFD_RELOC_LO16);
9020             }
9021           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
9022             {
9023               /* If we are going to add in a base register, and the
9024                  target register and the base register are the same,
9025                  then we are using AT as a temporary register.  Since
9026                  we want to load the constant into AT, we add our
9027                  current AT (from the global offset table) and the
9028                  register into the register now, and pretend we were
9029                  not using a base register.  */
9030               if (breg != treg)
9031                 dreg = tempreg;
9032               else
9033                 {
9034                   gas_assert (tempreg == AT);
9035                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9036                                treg, AT, breg);
9037                   dreg = treg;
9038                   add_breg_early = 1;
9039                 }
9040
9041               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9042               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
9043
9044               used_at = 1;
9045             }
9046           else
9047             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
9048
9049           relax_switch ();
9050           offset_expr.X_add_number = expr1.X_add_number;
9051           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9052                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9053           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9054                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
9055           if (add_breg_early)
9056             {
9057               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9058                            treg, tempreg, breg);
9059               breg = 0;
9060               tempreg = treg;
9061             }
9062           relax_end ();
9063         }
9064       else
9065         abort ();
9066
9067       if (breg != 0)
9068         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
9069       break;
9070
9071     case M_MSGSND:
9072       gas_assert (!mips_opts.micromips);
9073       macro_build (NULL, "c2", "C", (treg << 16) | 0x01);
9074       break;
9075
9076     case M_MSGLD:
9077       gas_assert (!mips_opts.micromips);
9078       macro_build (NULL, "c2", "C", 0x02);
9079       break;
9080
9081     case M_MSGLD_T:
9082       gas_assert (!mips_opts.micromips);
9083       macro_build (NULL, "c2", "C", (treg << 16) | 0x02);
9084       break;
9085
9086     case M_MSGWAIT:
9087       gas_assert (!mips_opts.micromips);
9088       macro_build (NULL, "c2", "C", 3);
9089       break;
9090
9091     case M_MSGWAIT_T:
9092       gas_assert (!mips_opts.micromips);
9093       macro_build (NULL, "c2", "C", (treg << 16) | 0x03);
9094       break;
9095
9096     case M_J_A:
9097       /* The j instruction may not be used in PIC code, since it
9098          requires an absolute address.  We convert it to a b
9099          instruction.  */
9100       if (mips_pic == NO_PIC)
9101         macro_build (&offset_expr, "j", "a");
9102       else
9103         macro_build (&offset_expr, "b", "p");
9104       break;
9105
9106       /* The jal instructions must be handled as macros because when
9107          generating PIC code they expand to multi-instruction
9108          sequences.  Normally they are simple instructions.  */
9109     case M_JALS_1:
9110       dreg = RA;
9111       /* Fall through.  */
9112     case M_JALS_2:
9113       gas_assert (mips_opts.micromips);
9114       if (mips_opts.insn32)
9115         {
9116           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9117           break;
9118         }
9119       jals = 1;
9120       goto jal;
9121     case M_JAL_1:
9122       dreg = RA;
9123       /* Fall through.  */
9124     case M_JAL_2:
9125     jal:
9126       if (mips_pic == NO_PIC)
9127         {
9128           s = jals ? "jalrs" : "jalr";
9129           if (mips_opts.micromips
9130               && !mips_opts.insn32
9131               && dreg == RA
9132               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9133             macro_build (NULL, s, "mj", sreg);
9134           else
9135             macro_build (NULL, s, JALR_FMT, dreg, sreg);
9136         }
9137       else
9138         {
9139           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
9140                            && mips_cprestore_offset >= 0);
9141
9142           if (sreg != PIC_CALL_REG)
9143             as_warn (_("MIPS PIC call to register other than $25"));
9144
9145           s = ((mips_opts.micromips
9146                 && !mips_opts.insn32
9147                 && (!mips_opts.noreorder || cprestore))
9148                ? "jalrs" : "jalr");
9149           if (mips_opts.micromips
9150               && !mips_opts.insn32
9151               && dreg == RA
9152               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9153             macro_build (NULL, s, "mj", sreg);
9154           else
9155             macro_build (NULL, s, JALR_FMT, dreg, sreg);
9156           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
9157             {
9158               if (mips_cprestore_offset < 0)
9159                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9160               else
9161                 {
9162                   if (!mips_frame_reg_valid)
9163                     {
9164                       as_warn (_("No .frame pseudo-op used in PIC code"));
9165                       /* Quiet this warning.  */
9166                       mips_frame_reg_valid = 1;
9167                     }
9168                   if (!mips_cprestore_valid)
9169                     {
9170                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9171                       /* Quiet this warning.  */
9172                       mips_cprestore_valid = 1;
9173                     }
9174                   if (mips_opts.noreorder)
9175                     macro_build (NULL, "nop", "");
9176                   expr1.X_add_number = mips_cprestore_offset;
9177                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9178                                                 mips_gp_register,
9179                                                 mips_frame_reg,
9180                                                 HAVE_64BIT_ADDRESSES);
9181                 }
9182             }
9183         }
9184
9185       break;
9186
9187     case M_JALS_A:
9188       gas_assert (mips_opts.micromips);
9189       if (mips_opts.insn32)
9190         {
9191           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9192           break;
9193         }
9194       jals = 1;
9195       /* Fall through.  */
9196     case M_JAL_A:
9197       if (mips_pic == NO_PIC)
9198         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
9199       else if (mips_pic == SVR4_PIC)
9200         {
9201           /* If this is a reference to an external symbol, and we are
9202              using a small GOT, we want
9203                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
9204                nop
9205                jalr     $ra,$25
9206                nop
9207                lw       $gp,cprestore($sp)
9208              The cprestore value is set using the .cprestore
9209              pseudo-op.  If we are using a big GOT, we want
9210                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
9211                addu     $25,$25,$gp
9212                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
9213                nop
9214                jalr     $ra,$25
9215                nop
9216                lw       $gp,cprestore($sp)
9217              If the symbol is not external, we want
9218                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9219                nop
9220                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
9221                jalr     $ra,$25
9222                nop
9223                lw $gp,cprestore($sp)
9224
9225              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
9226              sequences above, minus nops, unless the symbol is local,
9227              which enables us to use GOT_PAGE/GOT_OFST (big got) or
9228              GOT_DISP.  */
9229           if (HAVE_NEWABI)
9230             {
9231               if (!mips_big_got)
9232                 {
9233                   relax_start (offset_expr.X_add_symbol);
9234                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9235                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9236                                mips_gp_register);
9237                   relax_switch ();
9238                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9239                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
9240                                mips_gp_register);
9241                   relax_end ();
9242                 }
9243               else
9244                 {
9245                   relax_start (offset_expr.X_add_symbol);
9246                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9247                                BFD_RELOC_MIPS_CALL_HI16);
9248                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9249                                PIC_CALL_REG, mips_gp_register);
9250                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9251                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9252                                PIC_CALL_REG);
9253                   relax_switch ();
9254                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9255                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
9256                                mips_gp_register);
9257                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9258                                PIC_CALL_REG, PIC_CALL_REG,
9259                                BFD_RELOC_MIPS_GOT_OFST);
9260                   relax_end ();
9261                 }
9262
9263               macro_build_jalr (&offset_expr, 0);
9264             }
9265           else
9266             {
9267               relax_start (offset_expr.X_add_symbol);
9268               if (!mips_big_got)
9269                 {
9270                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9271                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9272                                mips_gp_register);
9273                   load_delay_nop ();
9274                   relax_switch ();
9275                 }
9276               else
9277                 {
9278                   int gpdelay;
9279
9280                   gpdelay = reg_needs_delay (mips_gp_register);
9281                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9282                                BFD_RELOC_MIPS_CALL_HI16);
9283                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9284                                PIC_CALL_REG, mips_gp_register);
9285                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9286                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9287                                PIC_CALL_REG);
9288                   load_delay_nop ();
9289                   relax_switch ();
9290                   if (gpdelay)
9291                     macro_build (NULL, "nop", "");
9292                 }
9293               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9294                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
9295                            mips_gp_register);
9296               load_delay_nop ();
9297               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9298                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
9299               relax_end ();
9300               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
9301
9302               if (mips_cprestore_offset < 0)
9303                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9304               else
9305                 {
9306                   if (!mips_frame_reg_valid)
9307                     {
9308                       as_warn (_("No .frame pseudo-op used in PIC code"));
9309                       /* Quiet this warning.  */
9310                       mips_frame_reg_valid = 1;
9311                     }
9312                   if (!mips_cprestore_valid)
9313                     {
9314                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9315                       /* Quiet this warning.  */
9316                       mips_cprestore_valid = 1;
9317                     }
9318                   if (mips_opts.noreorder)
9319                     macro_build (NULL, "nop", "");
9320                   expr1.X_add_number = mips_cprestore_offset;
9321                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9322                                                 mips_gp_register,
9323                                                 mips_frame_reg,
9324                                                 HAVE_64BIT_ADDRESSES);
9325                 }
9326             }
9327         }
9328       else if (mips_pic == VXWORKS_PIC)
9329         as_bad (_("Non-PIC jump used in PIC library"));
9330       else
9331         abort ();
9332
9333       break;
9334
9335     case M_LBUE_AB:
9336       s = "lbue";
9337       fmt = "t,+j(b)";
9338       offbits = 9;
9339       goto ld_st;
9340     case M_LHUE_AB:
9341       s = "lhue";
9342       fmt = "t,+j(b)";
9343       offbits = 9;
9344       goto ld_st;
9345     case M_LBE_AB:
9346       s = "lbe";
9347       fmt = "t,+j(b)";
9348       offbits = 9;
9349       goto ld_st;
9350     case M_LHE_AB:
9351       s = "lhe";
9352       fmt = "t,+j(b)";
9353       offbits = 9;
9354       goto ld_st;
9355     case M_LLE_AB:
9356       s = "lle";
9357       fmt = "t,+j(b)";
9358       offbits = 9;
9359       goto ld_st;
9360     case M_LWE_AB:
9361       s = "lwe";
9362       fmt = "t,+j(b)";
9363       offbits = 9;
9364       goto ld_st;
9365     case M_LWLE_AB:
9366       s = "lwle";
9367       fmt = "t,+j(b)";
9368       offbits = 9;
9369       goto ld_st;
9370     case M_LWRE_AB:
9371       s = "lwre";
9372       fmt = "t,+j(b)";
9373       offbits = 9;
9374       goto ld_st;
9375     case M_SBE_AB:
9376       s = "sbe";
9377       fmt = "t,+j(b)";
9378       offbits = 9;
9379       goto ld_st;
9380     case M_SCE_AB:
9381       s = "sce";
9382       fmt = "t,+j(b)";
9383       offbits = 9;
9384       goto ld_st;
9385     case M_SHE_AB:
9386       s = "she";
9387       fmt = "t,+j(b)";
9388       offbits = 9;
9389       goto ld_st;
9390     case M_SWE_AB:
9391       s = "swe";
9392       fmt = "t,+j(b)";
9393       offbits = 9;
9394       goto ld_st;
9395     case M_SWLE_AB:
9396       s = "swle";
9397       fmt = "t,+j(b)";
9398       offbits = 9;
9399       goto ld_st;
9400     case M_SWRE_AB:
9401       s = "swre";
9402       fmt = "t,+j(b)";
9403       offbits = 9;
9404       goto ld_st;
9405     case M_ACLR_AB:
9406       s = "aclr";
9407       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
9408       fmt = "\\,~(b)";
9409       offbits = 12;
9410       goto ld_st;
9411     case M_ASET_AB:
9412       s = "aset";
9413       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
9414       fmt = "\\,~(b)";
9415       offbits = 12;
9416       goto ld_st;
9417     case M_LB_AB:
9418       s = "lb";
9419       fmt = "t,o(b)";
9420       goto ld;
9421     case M_LBU_AB:
9422       s = "lbu";
9423       fmt = "t,o(b)";
9424       goto ld;
9425     case M_LH_AB:
9426       s = "lh";
9427       fmt = "t,o(b)";
9428       goto ld;
9429     case M_LHU_AB:
9430       s = "lhu";
9431       fmt = "t,o(b)";
9432       goto ld;
9433     case M_LW_AB:
9434       s = "lw";
9435       fmt = "t,o(b)";
9436       goto ld;
9437     case M_LWC0_AB:
9438       gas_assert (!mips_opts.micromips);
9439       s = "lwc0";
9440       fmt = "E,o(b)";
9441       /* Itbl support may require additional care here.  */
9442       coproc = 1;
9443       goto ld_st;
9444     case M_LWC1_AB:
9445       s = "lwc1";
9446       fmt = "T,o(b)";
9447       /* Itbl support may require additional care here.  */
9448       coproc = 1;
9449       goto ld_st;
9450     case M_LWC2_AB:
9451       s = "lwc2";
9452       fmt = COP12_FMT;
9453       offbits = (mips_opts.micromips ? 12 : 16);
9454       /* Itbl support may require additional care here.  */
9455       coproc = 1;
9456       goto ld_st;
9457     case M_LWC3_AB:
9458       gas_assert (!mips_opts.micromips);
9459       s = "lwc3";
9460       fmt = "E,o(b)";
9461       /* Itbl support may require additional care here.  */
9462       coproc = 1;
9463       goto ld_st;
9464     case M_LWL_AB:
9465       s = "lwl";
9466       fmt = MEM12_FMT;
9467       offbits = (mips_opts.micromips ? 12 : 16);
9468       goto ld_st;
9469     case M_LWR_AB:
9470       s = "lwr";
9471       fmt = MEM12_FMT;
9472       offbits = (mips_opts.micromips ? 12 : 16);
9473       goto ld_st;
9474     case M_LDC1_AB:
9475       s = "ldc1";
9476       fmt = "T,o(b)";
9477       /* Itbl support may require additional care here.  */
9478       coproc = 1;
9479       goto ld_st;
9480     case M_LDC2_AB:
9481       s = "ldc2";
9482       fmt = COP12_FMT;
9483       offbits = (mips_opts.micromips ? 12 : 16);
9484       /* Itbl support may require additional care here.  */
9485       coproc = 1;
9486       goto ld_st;
9487     case M_LQC2_AB:
9488       s = "lqc2";
9489       fmt = "E,o(b)";
9490       /* Itbl support may require additional care here.  */
9491       coproc = 1;
9492       goto ld_st;
9493     case M_LDC3_AB:
9494       s = "ldc3";
9495       fmt = "E,o(b)";
9496       /* Itbl support may require additional care here.  */
9497       coproc = 1;
9498       goto ld_st;
9499     case M_LDL_AB:
9500       s = "ldl";
9501       fmt = MEM12_FMT;
9502       offbits = (mips_opts.micromips ? 12 : 16);
9503       goto ld_st;
9504     case M_LDR_AB:
9505       s = "ldr";
9506       fmt = MEM12_FMT;
9507       offbits = (mips_opts.micromips ? 12 : 16);
9508       goto ld_st;
9509     case M_LL_AB:
9510       s = "ll";
9511       fmt = MEM12_FMT;
9512       offbits = (mips_opts.micromips ? 12 : 16);
9513       goto ld;
9514     case M_LLD_AB:
9515       s = "lld";
9516       fmt = MEM12_FMT;
9517       offbits = (mips_opts.micromips ? 12 : 16);
9518       goto ld;
9519     case M_LWU_AB:
9520       s = "lwu";
9521       fmt = MEM12_FMT;
9522       offbits = (mips_opts.micromips ? 12 : 16);
9523       goto ld;
9524     case M_LWP_AB:
9525       gas_assert (mips_opts.micromips);
9526       s = "lwp";
9527       fmt = "t,~(b)";
9528       offbits = 12;
9529       lp = 1;
9530       goto ld;
9531     case M_LDP_AB:
9532       gas_assert (mips_opts.micromips);
9533       s = "ldp";
9534       fmt = "t,~(b)";
9535       offbits = 12;
9536       lp = 1;
9537       goto ld;
9538     case M_LWM_AB:
9539       gas_assert (mips_opts.micromips);
9540       s = "lwm";
9541       fmt = "n,~(b)";
9542       offbits = 12;
9543       goto ld_st;
9544     case M_LDM_AB:
9545       gas_assert (mips_opts.micromips);
9546       s = "ldm";
9547       fmt = "n,~(b)";
9548       offbits = 12;
9549       goto ld_st;
9550
9551     ld:
9552       /* We don't want to use $0 as tempreg.  */
9553       if (breg == treg + lp || treg + lp == ZERO)
9554         goto ld_st;
9555       else
9556         tempreg = treg + lp;
9557       goto ld_noat;
9558
9559     case M_SB_AB:
9560       s = "sb";
9561       fmt = "t,o(b)";
9562       goto ld_st;
9563     case M_SH_AB:
9564       s = "sh";
9565       fmt = "t,o(b)";
9566       goto ld_st;
9567     case M_SW_AB:
9568       s = "sw";
9569       fmt = "t,o(b)";
9570       goto ld_st;
9571     case M_SWC0_AB:
9572       gas_assert (!mips_opts.micromips);
9573       s = "swc0";
9574       fmt = "E,o(b)";
9575       /* Itbl support may require additional care here.  */
9576       coproc = 1;
9577       goto ld_st;
9578     case M_SWC1_AB:
9579       s = "swc1";
9580       fmt = "T,o(b)";
9581       /* Itbl support may require additional care here.  */
9582       coproc = 1;
9583       goto ld_st;
9584     case M_SWC2_AB:
9585       s = "swc2";
9586       fmt = COP12_FMT;
9587       offbits = (mips_opts.micromips ? 12 : 16);
9588       /* Itbl support may require additional care here.  */
9589       coproc = 1;
9590       goto ld_st;
9591     case M_SWC3_AB:
9592       gas_assert (!mips_opts.micromips);
9593       s = "swc3";
9594       fmt = "E,o(b)";
9595       /* Itbl support may require additional care here.  */
9596       coproc = 1;
9597       goto ld_st;
9598     case M_SWL_AB:
9599       s = "swl";
9600       fmt = MEM12_FMT;
9601       offbits = (mips_opts.micromips ? 12 : 16);
9602       goto ld_st;
9603     case M_SWR_AB:
9604       s = "swr";
9605       fmt = MEM12_FMT;
9606       offbits = (mips_opts.micromips ? 12 : 16);
9607       goto ld_st;
9608     case M_SC_AB:
9609       s = "sc";
9610       fmt = MEM12_FMT;
9611       offbits = (mips_opts.micromips ? 12 : 16);
9612       goto ld_st;
9613     case M_SCD_AB:
9614       s = "scd";
9615       fmt = MEM12_FMT;
9616       offbits = (mips_opts.micromips ? 12 : 16);
9617       goto ld_st;
9618     case M_CACHE_AB:
9619       s = "cache";
9620       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
9621       offbits = (mips_opts.micromips ? 12 : 16);
9622       goto ld_st;
9623     case M_CACHEE_AB:
9624       s = "cachee";
9625       fmt = "k,+j(b)";
9626       offbits = 9;
9627       goto ld_st;
9628     case M_PREF_AB:
9629       s = "pref";
9630       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
9631       offbits = (mips_opts.micromips ? 12 : 16);
9632       goto ld_st;
9633     case M_PREFE_AB:
9634       s = "prefe";
9635       fmt = "k,+j(b)";
9636       offbits = 9;
9637       goto ld_st;
9638     case M_SDC1_AB:
9639       s = "sdc1";
9640       fmt = "T,o(b)";
9641       coproc = 1;
9642       /* Itbl support may require additional care here.  */
9643       goto ld_st;
9644     case M_SDC2_AB:
9645       s = "sdc2";
9646       fmt = COP12_FMT;
9647       offbits = (mips_opts.micromips ? 12 : 16);
9648       /* Itbl support may require additional care here.  */
9649       coproc = 1;
9650       goto ld_st;
9651     case M_SQC2_AB:
9652       s = "sqc2";
9653       fmt = "E,o(b)";
9654       /* Itbl support may require additional care here.  */
9655       coproc = 1;
9656       goto ld_st;
9657     case M_SDC3_AB:
9658       gas_assert (!mips_opts.micromips);
9659       s = "sdc3";
9660       fmt = "E,o(b)";
9661       /* Itbl support may require additional care here.  */
9662       coproc = 1;
9663       goto ld_st;
9664     case M_SDL_AB:
9665       s = "sdl";
9666       fmt = MEM12_FMT;
9667       offbits = (mips_opts.micromips ? 12 : 16);
9668       goto ld_st;
9669     case M_SDR_AB:
9670       s = "sdr";
9671       fmt = MEM12_FMT;
9672       offbits = (mips_opts.micromips ? 12 : 16);
9673       goto ld_st;
9674     case M_SWP_AB:
9675       gas_assert (mips_opts.micromips);
9676       s = "swp";
9677       fmt = "t,~(b)";
9678       offbits = 12;
9679       goto ld_st;
9680     case M_SDP_AB:
9681       gas_assert (mips_opts.micromips);
9682       s = "sdp";
9683       fmt = "t,~(b)";
9684       offbits = 12;
9685       goto ld_st;
9686     case M_SWM_AB:
9687       gas_assert (mips_opts.micromips);
9688       s = "swm";
9689       fmt = "n,~(b)";
9690       offbits = 12;
9691       goto ld_st;
9692     case M_SDM_AB:
9693       gas_assert (mips_opts.micromips);
9694       s = "sdm";
9695       fmt = "n,~(b)";
9696       offbits = 12;
9697
9698     ld_st:
9699       tempreg = AT;
9700     ld_noat:
9701       if (small_offset_p (0, align, 16))
9702         {
9703           /* The first case exists for M_LD_AB and M_SD_AB, which are
9704              macros for o32 but which should act like normal instructions
9705              otherwise.  */
9706           if (offbits == 16)
9707             macro_build (&offset_expr, s, fmt, treg, -1, offset_reloc[0],
9708                          offset_reloc[1], offset_reloc[2], breg);
9709           else if (small_offset_p (0, align, offbits))
9710             {
9711               if (offbits == 0)
9712                 macro_build (NULL, s, fmt, treg, breg);
9713               else
9714                 macro_build (NULL, s, fmt, treg,
9715                              (int) offset_expr.X_add_number, breg);
9716             }
9717           else
9718             {
9719               if (tempreg == AT)
9720                 used_at = 1;
9721               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9722                            tempreg, breg, -1, offset_reloc[0],
9723                            offset_reloc[1], offset_reloc[2]);
9724               if (offbits == 0)
9725                 macro_build (NULL, s, fmt, treg, tempreg);
9726               else
9727                 macro_build (NULL, s, fmt, treg, 0, tempreg);
9728             }
9729           break;
9730         }
9731
9732       if (tempreg == AT)
9733         used_at = 1;
9734
9735       if (offset_expr.X_op != O_constant
9736           && offset_expr.X_op != O_symbol)
9737         {
9738           as_bad (_("Expression too complex"));
9739           offset_expr.X_op = O_constant;
9740         }
9741
9742       if (HAVE_32BIT_ADDRESSES
9743           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9744         {
9745           char value [32];
9746
9747           sprintf_vma (value, offset_expr.X_add_number);
9748           as_bad (_("Number (0x%s) larger than 32 bits"), value);
9749         }
9750
9751       /* A constant expression in PIC code can be handled just as it
9752          is in non PIC code.  */
9753       if (offset_expr.X_op == O_constant)
9754         {
9755           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
9756                                                  offbits == 0 ? 16 : offbits);
9757           offset_expr.X_add_number -= expr1.X_add_number;
9758
9759           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
9760           if (breg != 0)
9761             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9762                          tempreg, tempreg, breg);
9763           if (offbits == 0)
9764             {
9765               if (offset_expr.X_add_number != 0)
9766                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
9767                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
9768               macro_build (NULL, s, fmt, treg, tempreg);
9769             }
9770           else if (offbits == 16)
9771             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9772           else
9773             macro_build (NULL, s, fmt, treg,
9774                          (int) offset_expr.X_add_number, tempreg);
9775         }
9776       else if (offbits != 16)
9777         {
9778           /* The offset field is too narrow to be used for a low-part
9779              relocation, so load the whole address into the auxillary
9780              register.  */
9781           load_address (tempreg, &offset_expr, &used_at);
9782           if (breg != 0)
9783             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9784                          tempreg, tempreg, breg);
9785           if (offbits == 0)
9786             macro_build (NULL, s, fmt, treg, tempreg);
9787           else
9788             macro_build (NULL, s, fmt, treg, 0, tempreg);
9789         }
9790       else if (mips_pic == NO_PIC)
9791         {
9792           /* If this is a reference to a GP relative symbol, and there
9793              is no base register, we want
9794                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
9795              Otherwise, if there is no base register, we want
9796                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9797                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9798              If we have a constant, we need two instructions anyhow,
9799              so we always use the latter form.
9800
9801              If we have a base register, and this is a reference to a
9802              GP relative symbol, we want
9803                addu     $tempreg,$breg,$gp
9804                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
9805              Otherwise we want
9806                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9807                addu     $tempreg,$tempreg,$breg
9808                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9809              With a constant we always use the latter case.
9810
9811              With 64bit address space and no base register and $at usable,
9812              we want
9813                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9814                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9815                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9816                dsll32   $tempreg,0
9817                daddu    $tempreg,$at
9818                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9819              If we have a base register, we want
9820                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9821                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9822                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9823                daddu    $at,$breg
9824                dsll32   $tempreg,0
9825                daddu    $tempreg,$at
9826                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9827
9828              Without $at we can't generate the optimal path for superscalar
9829              processors here since this would require two temporary registers.
9830                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9831                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9832                dsll     $tempreg,16
9833                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9834                dsll     $tempreg,16
9835                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9836              If we have a base register, we want
9837                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9838                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9839                dsll     $tempreg,16
9840                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9841                dsll     $tempreg,16
9842                daddu    $tempreg,$tempreg,$breg
9843                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9844
9845              For GP relative symbols in 64bit address space we can use
9846              the same sequence as in 32bit address space.  */
9847           if (HAVE_64BIT_SYMBOLS)
9848             {
9849               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9850                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9851                 {
9852                   relax_start (offset_expr.X_add_symbol);
9853                   if (breg == 0)
9854                     {
9855                       macro_build (&offset_expr, s, fmt, treg,
9856                                    BFD_RELOC_GPREL16, mips_gp_register);
9857                     }
9858                   else
9859                     {
9860                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9861                                    tempreg, breg, mips_gp_register);
9862                       macro_build (&offset_expr, s, fmt, treg,
9863                                    BFD_RELOC_GPREL16, tempreg);
9864                     }
9865                   relax_switch ();
9866                 }
9867
9868               if (used_at == 0 && mips_opts.at)
9869                 {
9870                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9871                                BFD_RELOC_MIPS_HIGHEST);
9872                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
9873                                BFD_RELOC_HI16_S);
9874                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9875                                tempreg, BFD_RELOC_MIPS_HIGHER);
9876                   if (breg != 0)
9877                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
9878                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9879                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9880                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
9881                                tempreg);
9882                   used_at = 1;
9883                 }
9884               else
9885                 {
9886                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9887                                BFD_RELOC_MIPS_HIGHEST);
9888                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9889                                tempreg, BFD_RELOC_MIPS_HIGHER);
9890                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9891                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9892                                tempreg, BFD_RELOC_HI16_S);
9893                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9894                   if (breg != 0)
9895                     macro_build (NULL, "daddu", "d,v,t",
9896                                  tempreg, tempreg, breg);
9897                   macro_build (&offset_expr, s, fmt, treg,
9898                                BFD_RELOC_LO16, tempreg);
9899                 }
9900
9901               if (mips_relax.sequence)
9902                 relax_end ();
9903               break;
9904             }
9905
9906           if (breg == 0)
9907             {
9908               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9909                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9910                 {
9911                   relax_start (offset_expr.X_add_symbol);
9912                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
9913                                mips_gp_register);
9914                   relax_switch ();
9915                 }
9916               macro_build_lui (&offset_expr, tempreg);
9917               macro_build (&offset_expr, s, fmt, treg,
9918                            BFD_RELOC_LO16, tempreg);
9919               if (mips_relax.sequence)
9920                 relax_end ();
9921             }
9922           else
9923             {
9924               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9925                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9926                 {
9927                   relax_start (offset_expr.X_add_symbol);
9928                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9929                                tempreg, breg, mips_gp_register);
9930                   macro_build (&offset_expr, s, fmt, treg,
9931                                BFD_RELOC_GPREL16, tempreg);
9932                   relax_switch ();
9933                 }
9934               macro_build_lui (&offset_expr, tempreg);
9935               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9936                            tempreg, tempreg, breg);
9937               macro_build (&offset_expr, s, fmt, treg,
9938                            BFD_RELOC_LO16, tempreg);
9939               if (mips_relax.sequence)
9940                 relax_end ();
9941             }
9942         }
9943       else if (!mips_big_got)
9944         {
9945           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9946
9947           /* If this is a reference to an external symbol, we want
9948                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9949                nop
9950                <op>     $treg,0($tempreg)
9951              Otherwise we want
9952                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9953                nop
9954                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9955                <op>     $treg,0($tempreg)
9956
9957              For NewABI, we want
9958                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9959                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
9960
9961              If there is a base register, we add it to $tempreg before
9962              the <op>.  If there is a constant, we stick it in the
9963              <op> instruction.  We don't handle constants larger than
9964              16 bits, because we have no way to load the upper 16 bits
9965              (actually, we could handle them for the subset of cases
9966              in which we are not using $at).  */
9967           gas_assert (offset_expr.X_op == O_symbol);
9968           if (HAVE_NEWABI)
9969             {
9970               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9971                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9972               if (breg != 0)
9973                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9974                              tempreg, tempreg, breg);
9975               macro_build (&offset_expr, s, fmt, treg,
9976                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
9977               break;
9978             }
9979           expr1.X_add_number = offset_expr.X_add_number;
9980           offset_expr.X_add_number = 0;
9981           if (expr1.X_add_number < -0x8000
9982               || expr1.X_add_number >= 0x8000)
9983             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9984           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9985                        lw_reloc_type, mips_gp_register);
9986           load_delay_nop ();
9987           relax_start (offset_expr.X_add_symbol);
9988           relax_switch ();
9989           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9990                        tempreg, BFD_RELOC_LO16);
9991           relax_end ();
9992           if (breg != 0)
9993             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9994                          tempreg, tempreg, breg);
9995           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9996         }
9997       else if (mips_big_got && !HAVE_NEWABI)
9998         {
9999           int gpdelay;
10000
10001           /* If this is a reference to an external symbol, we want
10002                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10003                addu     $tempreg,$tempreg,$gp
10004                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10005                <op>     $treg,0($tempreg)
10006              Otherwise we want
10007                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10008                nop
10009                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10010                <op>     $treg,0($tempreg)
10011              If there is a base register, we add it to $tempreg before
10012              the <op>.  If there is a constant, we stick it in the
10013              <op> instruction.  We don't handle constants larger than
10014              16 bits, because we have no way to load the upper 16 bits
10015              (actually, we could handle them for the subset of cases
10016              in which we are not using $at).  */
10017           gas_assert (offset_expr.X_op == O_symbol);
10018           expr1.X_add_number = offset_expr.X_add_number;
10019           offset_expr.X_add_number = 0;
10020           if (expr1.X_add_number < -0x8000
10021               || expr1.X_add_number >= 0x8000)
10022             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10023           gpdelay = reg_needs_delay (mips_gp_register);
10024           relax_start (offset_expr.X_add_symbol);
10025           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10026                        BFD_RELOC_MIPS_GOT_HI16);
10027           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
10028                        mips_gp_register);
10029           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10030                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
10031           relax_switch ();
10032           if (gpdelay)
10033             macro_build (NULL, "nop", "");
10034           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10035                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10036           load_delay_nop ();
10037           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10038                        tempreg, BFD_RELOC_LO16);
10039           relax_end ();
10040
10041           if (breg != 0)
10042             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10043                          tempreg, tempreg, breg);
10044           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
10045         }
10046       else if (mips_big_got && HAVE_NEWABI)
10047         {
10048           /* If this is a reference to an external symbol, we want
10049                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10050                add      $tempreg,$tempreg,$gp
10051                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10052                <op>     $treg,<ofst>($tempreg)
10053              Otherwise, for local symbols, we want:
10054                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
10055                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
10056           gas_assert (offset_expr.X_op == O_symbol);
10057           expr1.X_add_number = offset_expr.X_add_number;
10058           offset_expr.X_add_number = 0;
10059           if (expr1.X_add_number < -0x8000
10060               || expr1.X_add_number >= 0x8000)
10061             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10062           relax_start (offset_expr.X_add_symbol);
10063           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10064                        BFD_RELOC_MIPS_GOT_HI16);
10065           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
10066                        mips_gp_register);
10067           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10068                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
10069           if (breg != 0)
10070             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10071                          tempreg, tempreg, breg);
10072           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
10073
10074           relax_switch ();
10075           offset_expr.X_add_number = expr1.X_add_number;
10076           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10077                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10078           if (breg != 0)
10079             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10080                          tempreg, tempreg, breg);
10081           macro_build (&offset_expr, s, fmt, treg,
10082                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
10083           relax_end ();
10084         }
10085       else
10086         abort ();
10087
10088       break;
10089
10090     case M_JRADDIUSP:
10091       gas_assert (mips_opts.micromips);
10092       gas_assert (mips_opts.insn32);
10093       start_noreorder ();
10094       macro_build (NULL, "jr", "s", RA);
10095       expr1.X_add_number = EXTRACT_OPERAND (1, IMMP, *ip) << 2;
10096       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
10097       end_noreorder ();
10098       break;
10099
10100     case M_JRC:
10101       gas_assert (mips_opts.micromips);
10102       gas_assert (mips_opts.insn32);
10103       macro_build (NULL, "jr", "s", sreg);
10104       if (mips_opts.noreorder)
10105         macro_build (NULL, "nop", "");
10106       break;
10107
10108     case M_LI:
10109     case M_LI_S:
10110       load_register (treg, &imm_expr, 0);
10111       break;
10112
10113     case M_DLI:
10114       load_register (treg, &imm_expr, 1);
10115       break;
10116
10117     case M_LI_SS:
10118       if (imm_expr.X_op == O_constant)
10119         {
10120           used_at = 1;
10121           load_register (AT, &imm_expr, 0);
10122           macro_build (NULL, "mtc1", "t,G", AT, treg);
10123           break;
10124         }
10125       else
10126         {
10127           gas_assert (offset_expr.X_op == O_symbol
10128                       && strcmp (segment_name (S_GET_SEGMENT
10129                                                (offset_expr.X_add_symbol)),
10130                                  ".lit4") == 0
10131                       && offset_expr.X_add_number == 0);
10132           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
10133                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
10134           break;
10135         }
10136
10137     case M_LI_D:
10138       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
10139          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
10140          order 32 bits of the value and the low order 32 bits are either
10141          zero or in OFFSET_EXPR.  */
10142       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10143         {
10144           if (HAVE_64BIT_GPRS)
10145             load_register (treg, &imm_expr, 1);
10146           else
10147             {
10148               int hreg, lreg;
10149
10150               if (target_big_endian)
10151                 {
10152                   hreg = treg;
10153                   lreg = treg + 1;
10154                 }
10155               else
10156                 {
10157                   hreg = treg + 1;
10158                   lreg = treg;
10159                 }
10160
10161               if (hreg <= 31)
10162                 load_register (hreg, &imm_expr, 0);
10163               if (lreg <= 31)
10164                 {
10165                   if (offset_expr.X_op == O_absent)
10166                     move_register (lreg, 0);
10167                   else
10168                     {
10169                       gas_assert (offset_expr.X_op == O_constant);
10170                       load_register (lreg, &offset_expr, 0);
10171                     }
10172                 }
10173             }
10174           break;
10175         }
10176
10177       /* We know that sym is in the .rdata section.  First we get the
10178          upper 16 bits of the address.  */
10179       if (mips_pic == NO_PIC)
10180         {
10181           macro_build_lui (&offset_expr, AT);
10182           used_at = 1;
10183         }
10184       else
10185         {
10186           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10187                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10188           used_at = 1;
10189         }
10190
10191       /* Now we load the register(s).  */
10192       if (HAVE_64BIT_GPRS)
10193         {
10194           used_at = 1;
10195           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
10196         }
10197       else
10198         {
10199           used_at = 1;
10200           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
10201           if (treg != RA)
10202             {
10203               /* FIXME: How in the world do we deal with the possible
10204                  overflow here?  */
10205               offset_expr.X_add_number += 4;
10206               macro_build (&offset_expr, "lw", "t,o(b)",
10207                            treg + 1, BFD_RELOC_LO16, AT);
10208             }
10209         }
10210       break;
10211
10212     case M_LI_DD:
10213       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
10214          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
10215          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
10216          the value and the low order 32 bits are either zero or in
10217          OFFSET_EXPR.  */
10218       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10219         {
10220           used_at = 1;
10221           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
10222           if (HAVE_64BIT_FPRS)
10223             {
10224               gas_assert (HAVE_64BIT_GPRS);
10225               macro_build (NULL, "dmtc1", "t,S", AT, treg);
10226             }
10227           else
10228             {
10229               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
10230               if (offset_expr.X_op == O_absent)
10231                 macro_build (NULL, "mtc1", "t,G", 0, treg);
10232               else
10233                 {
10234                   gas_assert (offset_expr.X_op == O_constant);
10235                   load_register (AT, &offset_expr, 0);
10236                   macro_build (NULL, "mtc1", "t,G", AT, treg);
10237                 }
10238             }
10239           break;
10240         }
10241
10242       gas_assert (offset_expr.X_op == O_symbol
10243                   && offset_expr.X_add_number == 0);
10244       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
10245       if (strcmp (s, ".lit8") == 0)
10246         {
10247           breg = mips_gp_register;
10248           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
10249           offset_reloc[1] = BFD_RELOC_UNUSED;
10250           offset_reloc[2] = BFD_RELOC_UNUSED;
10251         }
10252       else
10253         {
10254           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
10255           used_at = 1;
10256           if (mips_pic != NO_PIC)
10257             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10258                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
10259           else
10260             {
10261               /* FIXME: This won't work for a 64 bit address.  */
10262               macro_build_lui (&offset_expr, AT);
10263             }
10264
10265           breg = AT;
10266           offset_reloc[0] = BFD_RELOC_LO16;
10267           offset_reloc[1] = BFD_RELOC_UNUSED;
10268           offset_reloc[2] = BFD_RELOC_UNUSED;
10269         }
10270       align = 8;
10271       /* Fall through */
10272
10273     case M_L_DAB:
10274       /*
10275        * The MIPS assembler seems to check for X_add_number not
10276        * being double aligned and generating:
10277        *        lui     at,%hi(foo+1)
10278        *        addu    at,at,v1
10279        *        addiu   at,at,%lo(foo+1)
10280        *        lwc1    f2,0(at)
10281        *        lwc1    f3,4(at)
10282        * But, the resulting address is the same after relocation so why
10283        * generate the extra instruction?
10284        */
10285       /* Itbl support may require additional care here.  */
10286       coproc = 1;
10287       fmt = "T,o(b)";
10288       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10289         {
10290           s = "ldc1";
10291           goto ld_st;
10292         }
10293       s = "lwc1";
10294       goto ldd_std;
10295
10296     case M_S_DAB:
10297       gas_assert (!mips_opts.micromips);
10298       /* Itbl support may require additional care here.  */
10299       coproc = 1;
10300       fmt = "T,o(b)";
10301       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10302         {
10303           s = "sdc1";
10304           goto ld_st;
10305         }
10306       s = "swc1";
10307       goto ldd_std;
10308
10309     case M_LQ_AB:
10310       fmt = "t,o(b)";
10311       s = "lq";
10312       goto ld;
10313
10314     case M_SQ_AB:
10315       fmt = "t,o(b)";
10316       s = "sq";
10317       goto ld_st;
10318
10319     case M_LD_AB:
10320       fmt = "t,o(b)";
10321       if (HAVE_64BIT_GPRS)
10322         {
10323           s = "ld";
10324           goto ld;
10325         }
10326       s = "lw";
10327       goto ldd_std;
10328
10329     case M_SD_AB:
10330       fmt = "t,o(b)";
10331       if (HAVE_64BIT_GPRS)
10332         {
10333           s = "sd";
10334           goto ld_st;
10335         }
10336       s = "sw";
10337
10338     ldd_std:
10339       /* Even on a big endian machine $fn comes before $fn+1.  We have
10340          to adjust when loading from memory.  We set coproc if we must
10341          load $fn+1 first.  */
10342       /* Itbl support may require additional care here.  */
10343       if (!target_big_endian)
10344         coproc = 0;
10345
10346       if (small_offset_p (0, align, 16))
10347         {
10348           ep = &offset_expr;
10349           if (!small_offset_p (4, align, 16))
10350             {
10351               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
10352                            -1, offset_reloc[0], offset_reloc[1],
10353                            offset_reloc[2]);
10354               expr1.X_add_number = 0;
10355               ep = &expr1;
10356               breg = AT;
10357               used_at = 1;
10358               offset_reloc[0] = BFD_RELOC_LO16;
10359               offset_reloc[1] = BFD_RELOC_UNUSED;
10360               offset_reloc[2] = BFD_RELOC_UNUSED;
10361             }
10362           if (strcmp (s, "lw") == 0 && treg == breg)
10363             {
10364               ep->X_add_number += 4;
10365               macro_build (ep, s, fmt, treg + 1, -1, offset_reloc[0],
10366                            offset_reloc[1], offset_reloc[2], breg);
10367               ep->X_add_number -= 4;
10368               macro_build (ep, s, fmt, treg, -1, offset_reloc[0],
10369                            offset_reloc[1], offset_reloc[2], breg);
10370             }
10371           else
10372             {
10373               macro_build (ep, s, fmt, coproc ? treg + 1 : treg, -1,
10374                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
10375                            breg);
10376               ep->X_add_number += 4;
10377               macro_build (ep, s, fmt, coproc ? treg : treg + 1, -1,
10378                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
10379                            breg);
10380             }
10381           break;
10382         }
10383
10384       if (offset_expr.X_op != O_symbol
10385           && offset_expr.X_op != O_constant)
10386         {
10387           as_bad (_("Expression too complex"));
10388           offset_expr.X_op = O_constant;
10389         }
10390
10391       if (HAVE_32BIT_ADDRESSES
10392           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10393         {
10394           char value [32];
10395
10396           sprintf_vma (value, offset_expr.X_add_number);
10397           as_bad (_("Number (0x%s) larger than 32 bits"), value);
10398         }
10399
10400       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
10401         {
10402           /* If this is a reference to a GP relative symbol, we want
10403                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
10404                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
10405              If we have a base register, we use this
10406                addu     $at,$breg,$gp
10407                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
10408                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
10409              If this is not a GP relative symbol, we want
10410                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10411                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10412                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10413              If there is a base register, we add it to $at after the
10414              lui instruction.  If there is a constant, we always use
10415              the last case.  */
10416           if (offset_expr.X_op == O_symbol
10417               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10418               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10419             {
10420               relax_start (offset_expr.X_add_symbol);
10421               if (breg == 0)
10422                 {
10423                   tempreg = mips_gp_register;
10424                 }
10425               else
10426                 {
10427                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10428                                AT, breg, mips_gp_register);
10429                   tempreg = AT;
10430                   used_at = 1;
10431                 }
10432
10433               /* Itbl support may require additional care here.  */
10434               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10435                            BFD_RELOC_GPREL16, tempreg);
10436               offset_expr.X_add_number += 4;
10437
10438               /* Set mips_optimize to 2 to avoid inserting an
10439                  undesired nop.  */
10440               hold_mips_optimize = mips_optimize;
10441               mips_optimize = 2;
10442               /* Itbl support may require additional care here.  */
10443               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10444                            BFD_RELOC_GPREL16, tempreg);
10445               mips_optimize = hold_mips_optimize;
10446
10447               relax_switch ();
10448
10449               offset_expr.X_add_number -= 4;
10450             }
10451           used_at = 1;
10452           if (offset_high_part (offset_expr.X_add_number, 16)
10453               != offset_high_part (offset_expr.X_add_number + 4, 16))
10454             {
10455               load_address (AT, &offset_expr, &used_at);
10456               offset_expr.X_op = O_constant;
10457               offset_expr.X_add_number = 0;
10458             }
10459           else
10460             macro_build_lui (&offset_expr, AT);
10461           if (breg != 0)
10462             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10463           /* Itbl support may require additional care here.  */
10464           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10465                        BFD_RELOC_LO16, AT);
10466           /* FIXME: How do we handle overflow here?  */
10467           offset_expr.X_add_number += 4;
10468           /* Itbl support may require additional care here.  */
10469           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10470                        BFD_RELOC_LO16, AT);
10471           if (mips_relax.sequence)
10472             relax_end ();
10473         }
10474       else if (!mips_big_got)
10475         {
10476           /* If this is a reference to an external symbol, we want
10477                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10478                nop
10479                <op>     $treg,0($at)
10480                <op>     $treg+1,4($at)
10481              Otherwise we want
10482                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10483                nop
10484                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10485                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10486              If there is a base register we add it to $at before the
10487              lwc1 instructions.  If there is a constant we include it
10488              in the lwc1 instructions.  */
10489           used_at = 1;
10490           expr1.X_add_number = offset_expr.X_add_number;
10491           if (expr1.X_add_number < -0x8000
10492               || expr1.X_add_number >= 0x8000 - 4)
10493             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10494           load_got_offset (AT, &offset_expr);
10495           load_delay_nop ();
10496           if (breg != 0)
10497             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10498
10499           /* Set mips_optimize to 2 to avoid inserting an undesired
10500              nop.  */
10501           hold_mips_optimize = mips_optimize;
10502           mips_optimize = 2;
10503
10504           /* Itbl support may require additional care here.  */
10505           relax_start (offset_expr.X_add_symbol);
10506           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
10507                        BFD_RELOC_LO16, AT);
10508           expr1.X_add_number += 4;
10509           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
10510                        BFD_RELOC_LO16, AT);
10511           relax_switch ();
10512           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10513                        BFD_RELOC_LO16, AT);
10514           offset_expr.X_add_number += 4;
10515           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10516                        BFD_RELOC_LO16, AT);
10517           relax_end ();
10518
10519           mips_optimize = hold_mips_optimize;
10520         }
10521       else if (mips_big_got)
10522         {
10523           int gpdelay;
10524
10525           /* If this is a reference to an external symbol, we want
10526                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
10527                addu     $at,$at,$gp
10528                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
10529                nop
10530                <op>     $treg,0($at)
10531                <op>     $treg+1,4($at)
10532              Otherwise we want
10533                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10534                nop
10535                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10536                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10537              If there is a base register we add it to $at before the
10538              lwc1 instructions.  If there is a constant we include it
10539              in the lwc1 instructions.  */
10540           used_at = 1;
10541           expr1.X_add_number = offset_expr.X_add_number;
10542           offset_expr.X_add_number = 0;
10543           if (expr1.X_add_number < -0x8000
10544               || expr1.X_add_number >= 0x8000 - 4)
10545             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10546           gpdelay = reg_needs_delay (mips_gp_register);
10547           relax_start (offset_expr.X_add_symbol);
10548           macro_build (&offset_expr, "lui", LUI_FMT,
10549                        AT, BFD_RELOC_MIPS_GOT_HI16);
10550           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10551                        AT, AT, mips_gp_register);
10552           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10553                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
10554           load_delay_nop ();
10555           if (breg != 0)
10556             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10557           /* Itbl support may require additional care here.  */
10558           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
10559                        BFD_RELOC_LO16, AT);
10560           expr1.X_add_number += 4;
10561
10562           /* Set mips_optimize to 2 to avoid inserting an undesired
10563              nop.  */
10564           hold_mips_optimize = mips_optimize;
10565           mips_optimize = 2;
10566           /* Itbl support may require additional care here.  */
10567           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
10568                        BFD_RELOC_LO16, AT);
10569           mips_optimize = hold_mips_optimize;
10570           expr1.X_add_number -= 4;
10571
10572           relax_switch ();
10573           offset_expr.X_add_number = expr1.X_add_number;
10574           if (gpdelay)
10575             macro_build (NULL, "nop", "");
10576           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10577                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10578           load_delay_nop ();
10579           if (breg != 0)
10580             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10581           /* Itbl support may require additional care here.  */
10582           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10583                        BFD_RELOC_LO16, AT);
10584           offset_expr.X_add_number += 4;
10585
10586           /* Set mips_optimize to 2 to avoid inserting an undesired
10587              nop.  */
10588           hold_mips_optimize = mips_optimize;
10589           mips_optimize = 2;
10590           /* Itbl support may require additional care here.  */
10591           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10592                        BFD_RELOC_LO16, AT);
10593           mips_optimize = hold_mips_optimize;
10594           relax_end ();
10595         }
10596       else
10597         abort ();
10598
10599       break;
10600         
10601     case M_SAA_AB:
10602       s = "saa";
10603       offbits = 0;
10604       fmt = "t,(b)";
10605       goto ld_st;
10606     case M_SAAD_AB:
10607       s = "saad";
10608       offbits = 0;
10609       fmt = "t,(b)";
10610       goto ld_st;
10611
10612    /* New code added to support COPZ instructions.
10613       This code builds table entries out of the macros in mip_opcodes.
10614       R4000 uses interlocks to handle coproc delays.
10615       Other chips (like the R3000) require nops to be inserted for delays.
10616
10617       FIXME: Currently, we require that the user handle delays.
10618       In order to fill delay slots for non-interlocked chips,
10619       we must have a way to specify delays based on the coprocessor.
10620       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
10621       What are the side-effects of the cop instruction?
10622       What cache support might we have and what are its effects?
10623       Both coprocessor & memory require delays. how long???
10624       What registers are read/set/modified?
10625
10626       If an itbl is provided to interpret cop instructions,
10627       this knowledge can be encoded in the itbl spec.  */
10628
10629     case M_COP0:
10630       s = "c0";
10631       goto copz;
10632     case M_COP1:
10633       s = "c1";
10634       goto copz;
10635     case M_COP2:
10636       s = "c2";
10637       goto copz;
10638     case M_COP3:
10639       s = "c3";
10640     copz:
10641       gas_assert (!mips_opts.micromips);
10642       /* For now we just do C (same as Cz).  The parameter will be
10643          stored in insn_opcode by mips_ip.  */
10644       macro_build (NULL, s, "C", (int) ip->insn_opcode);
10645       break;
10646
10647     case M_MOVE:
10648       move_register (dreg, sreg);
10649       break;
10650
10651     case M_MOVEP:
10652       gas_assert (mips_opts.micromips);
10653       gas_assert (mips_opts.insn32);
10654       dreg = micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
10655       breg = micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
10656       sreg = micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
10657       treg = micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
10658       move_register (dreg, sreg);
10659       move_register (breg, treg);
10660       break;
10661
10662     case M_DMUL:
10663       dbl = 1;
10664     case M_MUL:
10665       if (mips_opts.arch == CPU_R5900)
10666         {
10667           macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", dreg, sreg, treg);
10668         }
10669       else
10670         {
10671       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
10672       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10673         }
10674       break;
10675
10676     case M_DMUL_I:
10677       dbl = 1;
10678     case M_MUL_I:
10679       /* The MIPS assembler some times generates shifts and adds.  I'm
10680          not trying to be that fancy. GCC should do this for us
10681          anyway.  */
10682       used_at = 1;
10683       load_register (AT, &imm_expr, dbl);
10684       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
10685       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10686       break;
10687
10688     case M_DMULO_I:
10689       dbl = 1;
10690     case M_MULO_I:
10691       imm = 1;
10692       goto do_mulo;
10693
10694     case M_DMULO:
10695       dbl = 1;
10696     case M_MULO:
10697     do_mulo:
10698       start_noreorder ();
10699       used_at = 1;
10700       if (imm)
10701         load_register (AT, &imm_expr, dbl);
10702       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
10703       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10704       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
10705       macro_build (NULL, "mfhi", MFHL_FMT, AT);
10706       if (mips_trap)
10707         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
10708       else
10709         {
10710           if (mips_opts.micromips)
10711             micromips_label_expr (&label_expr);
10712           else
10713             label_expr.X_add_number = 8;
10714           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
10715           macro_build (NULL, "nop", "");
10716           macro_build (NULL, "break", BRK_FMT, 6);
10717           if (mips_opts.micromips)
10718             micromips_add_label ();
10719         }
10720       end_noreorder ();
10721       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10722       break;
10723
10724     case M_DMULOU_I:
10725       dbl = 1;
10726     case M_MULOU_I:
10727       imm = 1;
10728       goto do_mulou;
10729
10730     case M_DMULOU:
10731       dbl = 1;
10732     case M_MULOU:
10733     do_mulou:
10734       start_noreorder ();
10735       used_at = 1;
10736       if (imm)
10737         load_register (AT, &imm_expr, dbl);
10738       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
10739                    sreg, imm ? AT : treg);
10740       macro_build (NULL, "mfhi", MFHL_FMT, AT);
10741       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10742       if (mips_trap)
10743         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
10744       else
10745         {
10746           if (mips_opts.micromips)
10747             micromips_label_expr (&label_expr);
10748           else
10749             label_expr.X_add_number = 8;
10750           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
10751           macro_build (NULL, "nop", "");
10752           macro_build (NULL, "break", BRK_FMT, 6);
10753           if (mips_opts.micromips)
10754             micromips_add_label ();
10755         }
10756       end_noreorder ();
10757       break;
10758
10759     case M_DROL:
10760       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10761         {
10762           if (dreg == sreg)
10763             {
10764               tempreg = AT;
10765               used_at = 1;
10766             }
10767           else
10768             {
10769               tempreg = dreg;
10770             }
10771           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
10772           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
10773           break;
10774         }
10775       used_at = 1;
10776       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10777       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
10778       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
10779       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10780       break;
10781
10782     case M_ROL:
10783       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10784         {
10785           if (dreg == sreg)
10786             {
10787               tempreg = AT;
10788               used_at = 1;
10789             }
10790           else
10791             {
10792               tempreg = dreg;
10793             }
10794           macro_build (NULL, "negu", "d,w", tempreg, treg);
10795           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
10796           break;
10797         }
10798       used_at = 1;
10799       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10800       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
10801       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
10802       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10803       break;
10804
10805     case M_DROL_I:
10806       {
10807         unsigned int rot;
10808         char *l;
10809         char *rr;
10810
10811         if (imm_expr.X_op != O_constant)
10812           as_bad (_("Improper rotate count"));
10813         rot = imm_expr.X_add_number & 0x3f;
10814         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10815           {
10816             rot = (64 - rot) & 0x3f;
10817             if (rot >= 32)
10818               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10819             else
10820               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10821             break;
10822           }
10823         if (rot == 0)
10824           {
10825             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10826             break;
10827           }
10828         l = (rot < 0x20) ? "dsll" : "dsll32";
10829         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
10830         rot &= 0x1f;
10831         used_at = 1;
10832         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
10833         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10834         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10835       }
10836       break;
10837
10838     case M_ROL_I:
10839       {
10840         unsigned int rot;
10841
10842         if (imm_expr.X_op != O_constant)
10843           as_bad (_("Improper rotate count"));
10844         rot = imm_expr.X_add_number & 0x1f;
10845         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10846           {
10847             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
10848             break;
10849           }
10850         if (rot == 0)
10851           {
10852             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10853             break;
10854           }
10855         used_at = 1;
10856         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
10857         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10858         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10859       }
10860       break;
10861
10862     case M_DROR:
10863       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10864         {
10865           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
10866           break;
10867         }
10868       used_at = 1;
10869       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10870       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
10871       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
10872       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10873       break;
10874
10875     case M_ROR:
10876       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10877         {
10878           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
10879           break;
10880         }
10881       used_at = 1;
10882       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10883       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
10884       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
10885       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10886       break;
10887
10888     case M_DROR_I:
10889       {
10890         unsigned int rot;
10891         char *l;
10892         char *rr;
10893
10894         if (imm_expr.X_op != O_constant)
10895           as_bad (_("Improper rotate count"));
10896         rot = imm_expr.X_add_number & 0x3f;
10897         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10898           {
10899             if (rot >= 32)
10900               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10901             else
10902               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10903             break;
10904           }
10905         if (rot == 0)
10906           {
10907             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10908             break;
10909           }
10910         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
10911         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
10912         rot &= 0x1f;
10913         used_at = 1;
10914         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
10915         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10916         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10917       }
10918       break;
10919
10920     case M_ROR_I:
10921       {
10922         unsigned int rot;
10923
10924         if (imm_expr.X_op != O_constant)
10925           as_bad (_("Improper rotate count"));
10926         rot = imm_expr.X_add_number & 0x1f;
10927         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10928           {
10929             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
10930             break;
10931           }
10932         if (rot == 0)
10933           {
10934             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10935             break;
10936           }
10937         used_at = 1;
10938         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
10939         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10940         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10941       }
10942       break;
10943
10944     case M_SEQ:
10945       if (sreg == 0)
10946         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
10947       else if (treg == 0)
10948         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10949       else
10950         {
10951           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10952           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10953         }
10954       break;
10955
10956     case M_SEQ_I:
10957       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10958         {
10959           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10960           break;
10961         }
10962       if (sreg == 0)
10963         {
10964           as_warn (_("Instruction %s: result is always false"),
10965                    ip->insn_mo->name);
10966           move_register (dreg, 0);
10967           break;
10968         }
10969       if (CPU_HAS_SEQ (mips_opts.arch)
10970           && -512 <= imm_expr.X_add_number
10971           && imm_expr.X_add_number < 512)
10972         {
10973           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
10974                        (int) imm_expr.X_add_number);
10975           break;
10976         }
10977       if (imm_expr.X_op == O_constant
10978           && imm_expr.X_add_number >= 0
10979           && imm_expr.X_add_number < 0x10000)
10980         {
10981           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10982         }
10983       else if (imm_expr.X_op == O_constant
10984                && imm_expr.X_add_number > -0x8000
10985                && imm_expr.X_add_number < 0)
10986         {
10987           imm_expr.X_add_number = -imm_expr.X_add_number;
10988           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10989                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10990         }
10991       else if (CPU_HAS_SEQ (mips_opts.arch))
10992         {
10993           used_at = 1;
10994           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10995           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
10996           break;
10997         }
10998       else
10999         {
11000           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11001           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
11002           used_at = 1;
11003         }
11004       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
11005       break;
11006
11007     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
11008       s = "slt";
11009       goto sge;
11010     case M_SGEU:
11011       s = "sltu";
11012     sge:
11013       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
11014       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11015       break;
11016
11017     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
11018     case M_SGEU_I:
11019       if (imm_expr.X_op == O_constant
11020           && imm_expr.X_add_number >= -0x8000
11021           && imm_expr.X_add_number < 0x8000)
11022         {
11023           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
11024                        dreg, sreg, BFD_RELOC_LO16);
11025         }
11026       else
11027         {
11028           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11029           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
11030                        dreg, sreg, AT);
11031           used_at = 1;
11032         }
11033       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11034       break;
11035
11036     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
11037       s = "slt";
11038       goto sgt;
11039     case M_SGTU:
11040       s = "sltu";
11041     sgt:
11042       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
11043       break;
11044
11045     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
11046       s = "slt";
11047       goto sgti;
11048     case M_SGTU_I:
11049       s = "sltu";
11050     sgti:
11051       used_at = 1;
11052       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11053       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
11054       break;
11055
11056     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
11057       s = "slt";
11058       goto sle;
11059     case M_SLEU:
11060       s = "sltu";
11061     sle:
11062       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
11063       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11064       break;
11065
11066     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
11067       s = "slt";
11068       goto slei;
11069     case M_SLEU_I:
11070       s = "sltu";
11071     slei:
11072       used_at = 1;
11073       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11074       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
11075       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11076       break;
11077
11078     case M_SLT_I:
11079       if (imm_expr.X_op == O_constant
11080           && imm_expr.X_add_number >= -0x8000
11081           && imm_expr.X_add_number < 0x8000)
11082         {
11083           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11084           break;
11085         }
11086       used_at = 1;
11087       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11088       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
11089       break;
11090
11091     case M_SLTU_I:
11092       if (imm_expr.X_op == O_constant
11093           && imm_expr.X_add_number >= -0x8000
11094           && imm_expr.X_add_number < 0x8000)
11095         {
11096           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
11097                        BFD_RELOC_LO16);
11098           break;
11099         }
11100       used_at = 1;
11101       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11102       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
11103       break;
11104
11105     case M_SNE:
11106       if (sreg == 0)
11107         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
11108       else if (treg == 0)
11109         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
11110       else
11111         {
11112           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
11113           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
11114         }
11115       break;
11116
11117     case M_SNE_I:
11118       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
11119         {
11120           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
11121           break;
11122         }
11123       if (sreg == 0)
11124         {
11125           as_warn (_("Instruction %s: result is always true"),
11126                    ip->insn_mo->name);
11127           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
11128                        dreg, 0, BFD_RELOC_LO16);
11129           break;
11130         }
11131       if (CPU_HAS_SEQ (mips_opts.arch)
11132           && -512 <= imm_expr.X_add_number
11133           && imm_expr.X_add_number < 512)
11134         {
11135           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
11136                        (int) imm_expr.X_add_number);
11137           break;
11138         }
11139       if (imm_expr.X_op == O_constant
11140           && imm_expr.X_add_number >= 0
11141           && imm_expr.X_add_number < 0x10000)
11142         {
11143           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
11144         }
11145       else if (imm_expr.X_op == O_constant
11146                && imm_expr.X_add_number > -0x8000
11147                && imm_expr.X_add_number < 0)
11148         {
11149           imm_expr.X_add_number = -imm_expr.X_add_number;
11150           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
11151                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11152         }
11153       else if (CPU_HAS_SEQ (mips_opts.arch))
11154         {
11155           used_at = 1;
11156           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11157           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
11158           break;
11159         }
11160       else
11161         {
11162           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11163           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
11164           used_at = 1;
11165         }
11166       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
11167       break;
11168
11169     case M_SUB_I:
11170       s = "addi";
11171       s2 = "sub";
11172       goto do_subi;
11173     case M_SUBU_I:
11174       s = "addiu";
11175       s2 = "subu";
11176       goto do_subi;
11177     case M_DSUB_I:
11178       dbl = 1;
11179       s = "daddi";
11180       s2 = "dsub";
11181       if (!mips_opts.micromips)
11182         goto do_subi;
11183       if (imm_expr.X_op == O_constant
11184           && imm_expr.X_add_number > -0x200
11185           && imm_expr.X_add_number <= 0x200)
11186         {
11187           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
11188           break;
11189         }
11190       goto do_subi_i;
11191     case M_DSUBU_I:
11192       dbl = 1;
11193       s = "daddiu";
11194       s2 = "dsubu";
11195     do_subi:
11196       if (imm_expr.X_op == O_constant
11197           && imm_expr.X_add_number > -0x8000
11198           && imm_expr.X_add_number <= 0x8000)
11199         {
11200           imm_expr.X_add_number = -imm_expr.X_add_number;
11201           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11202           break;
11203         }
11204     do_subi_i:
11205       used_at = 1;
11206       load_register (AT, &imm_expr, dbl);
11207       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
11208       break;
11209
11210     case M_TEQ_I:
11211       s = "teq";
11212       goto trap;
11213     case M_TGE_I:
11214       s = "tge";
11215       goto trap;
11216     case M_TGEU_I:
11217       s = "tgeu";
11218       goto trap;
11219     case M_TLT_I:
11220       s = "tlt";
11221       goto trap;
11222     case M_TLTU_I:
11223       s = "tltu";
11224       goto trap;
11225     case M_TNE_I:
11226       s = "tne";
11227     trap:
11228       used_at = 1;
11229       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11230       macro_build (NULL, s, "s,t", sreg, AT);
11231       break;
11232
11233     case M_TRUNCWS:
11234     case M_TRUNCWD:
11235       gas_assert (!mips_opts.micromips);
11236       gas_assert (mips_opts.isa == ISA_MIPS1);
11237       used_at = 1;
11238       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
11239       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
11240
11241       /*
11242        * Is the double cfc1 instruction a bug in the mips assembler;
11243        * or is there a reason for it?
11244        */
11245       start_noreorder ();
11246       macro_build (NULL, "cfc1", "t,G", treg, RA);
11247       macro_build (NULL, "cfc1", "t,G", treg, RA);
11248       macro_build (NULL, "nop", "");
11249       expr1.X_add_number = 3;
11250       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
11251       expr1.X_add_number = 2;
11252       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
11253       macro_build (NULL, "ctc1", "t,G", AT, RA);
11254       macro_build (NULL, "nop", "");
11255       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
11256                    dreg, sreg);
11257       macro_build (NULL, "ctc1", "t,G", treg, RA);
11258       macro_build (NULL, "nop", "");
11259       end_noreorder ();
11260       break;
11261
11262     case M_ULH_AB:
11263       s = "lb";
11264       s2 = "lbu";
11265       off = 1;
11266       goto uld_st;
11267     case M_ULHU_AB:
11268       s = "lbu";
11269       s2 = "lbu";
11270       off = 1;
11271       goto uld_st;
11272     case M_ULW_AB:
11273       s = "lwl";
11274       s2 = "lwr";
11275       offbits = (mips_opts.micromips ? 12 : 16);
11276       off = 3;
11277       goto uld_st;
11278     case M_ULD_AB:
11279       s = "ldl";
11280       s2 = "ldr";
11281       offbits = (mips_opts.micromips ? 12 : 16);
11282       off = 7;
11283       goto uld_st;
11284     case M_USH_AB:
11285       s = "sb";
11286       s2 = "sb";
11287       off = 1;
11288       ust = 1;
11289       goto uld_st;
11290     case M_USW_AB:
11291       s = "swl";
11292       s2 = "swr";
11293       offbits = (mips_opts.micromips ? 12 : 16);
11294       off = 3;
11295       ust = 1;
11296       goto uld_st;
11297     case M_USD_AB:
11298       s = "sdl";
11299       s2 = "sdr";
11300       offbits = (mips_opts.micromips ? 12 : 16);
11301       off = 7;
11302       ust = 1;
11303
11304     uld_st:
11305       large_offset = !small_offset_p (off, align, offbits);
11306       ep = &offset_expr;
11307       expr1.X_add_number = 0;
11308       if (large_offset)
11309         {
11310           used_at = 1;
11311           tempreg = AT;
11312           if (small_offset_p (0, align, 16))
11313             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
11314                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
11315           else
11316             {
11317               load_address (tempreg, ep, &used_at);
11318               if (breg != 0)
11319                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11320                              tempreg, tempreg, breg);
11321             }
11322           offset_reloc[0] = BFD_RELOC_LO16;
11323           offset_reloc[1] = BFD_RELOC_UNUSED;
11324           offset_reloc[2] = BFD_RELOC_UNUSED;
11325           breg = tempreg;
11326           tempreg = treg;
11327           ep = &expr1;
11328         }
11329       else if (!ust && treg == breg)
11330         {
11331           used_at = 1;
11332           tempreg = AT;
11333         }
11334       else
11335         tempreg = treg;
11336
11337       if (off == 1)
11338         goto ulh_sh;
11339
11340       if (!target_big_endian)
11341         ep->X_add_number += off;
11342       if (offbits == 12)
11343         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
11344       else
11345         macro_build (ep, s, "t,o(b)", tempreg, -1,
11346                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11347
11348       if (!target_big_endian)
11349         ep->X_add_number -= off;
11350       else
11351         ep->X_add_number += off;
11352       if (offbits == 12)
11353         macro_build (NULL, s2, "t,~(b)",
11354                      tempreg, (int) ep->X_add_number, breg);
11355       else
11356         macro_build (ep, s2, "t,o(b)", tempreg, -1,
11357                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11358
11359       /* If necessary, move the result in tempreg to the final destination.  */
11360       if (!ust && treg != tempreg)
11361         {
11362           /* Protect second load's delay slot.  */
11363           load_delay_nop ();
11364           move_register (treg, tempreg);
11365         }
11366       break;
11367
11368     ulh_sh:
11369       used_at = 1;
11370       if (target_big_endian == ust)
11371         ep->X_add_number += off;
11372       tempreg = ust || large_offset ? treg : AT;
11373       macro_build (ep, s, "t,o(b)", tempreg, -1,
11374                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11375
11376       /* For halfword transfers we need a temporary register to shuffle
11377          bytes.  Unfortunately for M_USH_A we have none available before
11378          the next store as AT holds the base address.  We deal with this
11379          case by clobbering TREG and then restoring it as with ULH.  */
11380       tempreg = ust == large_offset ? treg : AT;
11381       if (ust)
11382         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
11383
11384       if (target_big_endian == ust)
11385         ep->X_add_number -= off;
11386       else
11387         ep->X_add_number += off;
11388       macro_build (ep, s2, "t,o(b)", tempreg, -1,
11389                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11390
11391       /* For M_USH_A re-retrieve the LSB.  */
11392       if (ust && large_offset)
11393         {
11394           if (target_big_endian)
11395             ep->X_add_number += off;
11396           else
11397             ep->X_add_number -= off;
11398           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
11399                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
11400         }
11401       /* For ULH and M_USH_A OR the LSB in.  */
11402       if (!ust || large_offset)
11403         {
11404           tempreg = !large_offset ? AT : treg;
11405           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
11406           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
11407         }
11408       break;
11409
11410     default:
11411       /* FIXME: Check if this is one of the itbl macros, since they
11412          are added dynamically.  */
11413       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
11414       break;
11415     }
11416   if (!mips_opts.at && used_at)
11417     as_bad (_("Macro used $at after \".set noat\""));
11418 }
11419
11420 /* Implement macros in mips16 mode.  */
11421
11422 static void
11423 mips16_macro (struct mips_cl_insn *ip)
11424 {
11425   int mask;
11426   int xreg, yreg, zreg, tmp;
11427   expressionS expr1;
11428   int dbl;
11429   const char *s, *s2, *s3;
11430
11431   mask = ip->insn_mo->mask;
11432
11433   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
11434   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
11435   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
11436
11437   expr1.X_op = O_constant;
11438   expr1.X_op_symbol = NULL;
11439   expr1.X_add_symbol = NULL;
11440   expr1.X_add_number = 1;
11441
11442   dbl = 0;
11443
11444   switch (mask)
11445     {
11446     default:
11447       abort ();
11448
11449     case M_DDIV_3:
11450       dbl = 1;
11451     case M_DIV_3:
11452       s = "mflo";
11453       goto do_div3;
11454     case M_DREM_3:
11455       dbl = 1;
11456     case M_REM_3:
11457       s = "mfhi";
11458     do_div3:
11459       start_noreorder ();
11460       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
11461       expr1.X_add_number = 2;
11462       macro_build (&expr1, "bnez", "x,p", yreg);
11463       macro_build (NULL, "break", "6", 7);
11464
11465       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
11466          since that causes an overflow.  We should do that as well,
11467          but I don't see how to do the comparisons without a temporary
11468          register.  */
11469       end_noreorder ();
11470       macro_build (NULL, s, "x", zreg);
11471       break;
11472
11473     case M_DIVU_3:
11474       s = "divu";
11475       s2 = "mflo";
11476       goto do_divu3;
11477     case M_REMU_3:
11478       s = "divu";
11479       s2 = "mfhi";
11480       goto do_divu3;
11481     case M_DDIVU_3:
11482       s = "ddivu";
11483       s2 = "mflo";
11484       goto do_divu3;
11485     case M_DREMU_3:
11486       s = "ddivu";
11487       s2 = "mfhi";
11488     do_divu3:
11489       start_noreorder ();
11490       macro_build (NULL, s, "0,x,y", xreg, yreg);
11491       expr1.X_add_number = 2;
11492       macro_build (&expr1, "bnez", "x,p", yreg);
11493       macro_build (NULL, "break", "6", 7);
11494       end_noreorder ();
11495       macro_build (NULL, s2, "x", zreg);
11496       break;
11497
11498     case M_DMUL:
11499       dbl = 1;
11500     case M_MUL:
11501       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
11502       macro_build (NULL, "mflo", "x", zreg);
11503       break;
11504
11505     case M_DSUBU_I:
11506       dbl = 1;
11507       goto do_subu;
11508     case M_SUBU_I:
11509     do_subu:
11510       if (imm_expr.X_op != O_constant)
11511         as_bad (_("Unsupported large constant"));
11512       imm_expr.X_add_number = -imm_expr.X_add_number;
11513       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
11514       break;
11515
11516     case M_SUBU_I_2:
11517       if (imm_expr.X_op != O_constant)
11518         as_bad (_("Unsupported large constant"));
11519       imm_expr.X_add_number = -imm_expr.X_add_number;
11520       macro_build (&imm_expr, "addiu", "x,k", xreg);
11521       break;
11522
11523     case M_DSUBU_I_2:
11524       if (imm_expr.X_op != O_constant)
11525         as_bad (_("Unsupported large constant"));
11526       imm_expr.X_add_number = -imm_expr.X_add_number;
11527       macro_build (&imm_expr, "daddiu", "y,j", yreg);
11528       break;
11529
11530     case M_BEQ:
11531       s = "cmp";
11532       s2 = "bteqz";
11533       goto do_branch;
11534     case M_BNE:
11535       s = "cmp";
11536       s2 = "btnez";
11537       goto do_branch;
11538     case M_BLT:
11539       s = "slt";
11540       s2 = "btnez";
11541       goto do_branch;
11542     case M_BLTU:
11543       s = "sltu";
11544       s2 = "btnez";
11545       goto do_branch;
11546     case M_BLE:
11547       s = "slt";
11548       s2 = "bteqz";
11549       goto do_reverse_branch;
11550     case M_BLEU:
11551       s = "sltu";
11552       s2 = "bteqz";
11553       goto do_reverse_branch;
11554     case M_BGE:
11555       s = "slt";
11556       s2 = "bteqz";
11557       goto do_branch;
11558     case M_BGEU:
11559       s = "sltu";
11560       s2 = "bteqz";
11561       goto do_branch;
11562     case M_BGT:
11563       s = "slt";
11564       s2 = "btnez";
11565       goto do_reverse_branch;
11566     case M_BGTU:
11567       s = "sltu";
11568       s2 = "btnez";
11569
11570     do_reverse_branch:
11571       tmp = xreg;
11572       xreg = yreg;
11573       yreg = tmp;
11574
11575     do_branch:
11576       macro_build (NULL, s, "x,y", xreg, yreg);
11577       macro_build (&offset_expr, s2, "p");
11578       break;
11579
11580     case M_BEQ_I:
11581       s = "cmpi";
11582       s2 = "bteqz";
11583       s3 = "x,U";
11584       goto do_branch_i;
11585     case M_BNE_I:
11586       s = "cmpi";
11587       s2 = "btnez";
11588       s3 = "x,U";
11589       goto do_branch_i;
11590     case M_BLT_I:
11591       s = "slti";
11592       s2 = "btnez";
11593       s3 = "x,8";
11594       goto do_branch_i;
11595     case M_BLTU_I:
11596       s = "sltiu";
11597       s2 = "btnez";
11598       s3 = "x,8";
11599       goto do_branch_i;
11600     case M_BLE_I:
11601       s = "slti";
11602       s2 = "btnez";
11603       s3 = "x,8";
11604       goto do_addone_branch_i;
11605     case M_BLEU_I:
11606       s = "sltiu";
11607       s2 = "btnez";
11608       s3 = "x,8";
11609       goto do_addone_branch_i;
11610     case M_BGE_I:
11611       s = "slti";
11612       s2 = "bteqz";
11613       s3 = "x,8";
11614       goto do_branch_i;
11615     case M_BGEU_I:
11616       s = "sltiu";
11617       s2 = "bteqz";
11618       s3 = "x,8";
11619       goto do_branch_i;
11620     case M_BGT_I:
11621       s = "slti";
11622       s2 = "bteqz";
11623       s3 = "x,8";
11624       goto do_addone_branch_i;
11625     case M_BGTU_I:
11626       s = "sltiu";
11627       s2 = "bteqz";
11628       s3 = "x,8";
11629
11630     do_addone_branch_i:
11631       if (imm_expr.X_op != O_constant)
11632         as_bad (_("Unsupported large constant"));
11633       ++imm_expr.X_add_number;
11634
11635     do_branch_i:
11636       macro_build (&imm_expr, s, s3, xreg);
11637       macro_build (&offset_expr, s2, "p");
11638       break;
11639
11640     case M_ABS:
11641       expr1.X_add_number = 0;
11642       macro_build (&expr1, "slti", "x,8", yreg);
11643       if (xreg != yreg)
11644         move_register (xreg, yreg);
11645       expr1.X_add_number = 2;
11646       macro_build (&expr1, "bteqz", "p");
11647       macro_build (NULL, "neg", "x,w", xreg, xreg);
11648     }
11649 }
11650
11651 /* Assemble an instruction into its binary format.  If the instruction
11652    is a macro, set imm_expr, imm2_expr and offset_expr to the values
11653    associated with "I", "+I" and "A" operands respectively.  Otherwise
11654    store the value of the relocatable field (if any) in offset_expr.
11655    In both cases set offset_reloc to the relocation operators applied
11656    to offset_expr.  */
11657
11658 static void
11659 mips_ip (char *str, struct mips_cl_insn *ip)
11660 {
11661   bfd_boolean wrong_delay_slot_insns = FALSE;
11662   bfd_boolean need_delay_slot_ok = TRUE;
11663   struct mips_opcode *firstinsn = NULL;
11664   const struct mips_opcode *past;
11665   struct hash_control *hash;
11666   char *s;
11667   const char *args;
11668   char c = 0;
11669   struct mips_opcode *insn;
11670   char *argsStart;
11671   long opend;
11672   char *name;
11673   char *dot;
11674   long end;
11675   const struct mips_operand *operand;
11676   struct mips_arg_info arg;
11677
11678   insn_error = NULL;
11679
11680   if (mips_opts.micromips)
11681     {
11682       hash = micromips_op_hash;
11683       past = &micromips_opcodes[bfd_micromips_num_opcodes];
11684     }
11685   else
11686     {
11687       hash = op_hash;
11688       past = &mips_opcodes[NUMOPCODES];
11689     }
11690   forced_insn_length = 0;
11691   insn = NULL;
11692
11693   /* We first try to match an instruction up to a space or to the end.  */
11694   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
11695     continue;
11696
11697   /* Make a copy of the instruction so that we can fiddle with it.  */
11698   name = alloca (end + 1);
11699   memcpy (name, str, end);
11700   name[end] = '\0';
11701
11702   for (;;)
11703     {
11704       insn = (struct mips_opcode *) hash_find (hash, name);
11705
11706       if (insn != NULL || !mips_opts.micromips)
11707         break;
11708       if (forced_insn_length)
11709         break;
11710
11711       /* See if there's an instruction size override suffix,
11712          either `16' or `32', at the end of the mnemonic proper,
11713          that defines the operation, i.e. before the first `.'
11714          character if any.  Strip it and retry.  */
11715       dot = strchr (name, '.');
11716       opend = dot != NULL ? dot - name : end;
11717       if (opend < 3)
11718         break;
11719       if (name[opend - 2] == '1' && name[opend - 1] == '6')
11720         forced_insn_length = 2;
11721       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
11722         forced_insn_length = 4;
11723       else
11724         break;
11725       memcpy (name + opend - 2, name + opend, end - opend + 1);
11726     }
11727   if (insn == NULL)
11728     {
11729       insn_error = _("Unrecognized opcode");
11730       return;
11731     }
11732
11733   /* For microMIPS instructions placed in a fixed-length branch delay slot
11734      we make up to two passes over the relevant fragment of the opcode
11735      table.  First we try instructions that meet the delay slot's length
11736      requirement.  If none matched, then we retry with the remaining ones
11737      and if one matches, then we use it and then issue an appropriate
11738      warning later on.  */
11739   argsStart = s = str + end;
11740   for (;;)
11741     {
11742       bfd_boolean delay_slot_ok;
11743       bfd_boolean size_ok;
11744       bfd_boolean ok;
11745       bfd_boolean more_alts;
11746
11747       gas_assert (strcmp (insn->name, name) == 0);
11748
11749       ok = is_opcode_valid (insn);
11750       size_ok = is_size_valid (insn);
11751       delay_slot_ok = is_delay_slot_valid (insn);
11752       if (!delay_slot_ok && !wrong_delay_slot_insns)
11753         {
11754           firstinsn = insn;
11755           wrong_delay_slot_insns = TRUE;
11756         }
11757       more_alts = (insn + 1 < past
11758                    && strcmp (insn[0].name, insn[1].name) == 0);
11759       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
11760         {
11761           static char buf[256];
11762
11763           if (more_alts)
11764             {
11765               ++insn;
11766               continue;
11767             }
11768           if (wrong_delay_slot_insns && need_delay_slot_ok)
11769             {
11770               gas_assert (firstinsn);
11771               need_delay_slot_ok = FALSE;
11772               past = insn + 1;
11773               insn = firstinsn;
11774               continue;
11775             }
11776
11777           if (insn_error)
11778             return;
11779
11780           if (!ok)
11781             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
11782                      mips_cpu_info_from_arch (mips_opts.arch)->name,
11783                      mips_cpu_info_from_isa (mips_opts.isa)->name);
11784           else if (mips_opts.insn32)
11785             sprintf (buf, _("Opcode not supported in the `insn32' mode"));
11786           else
11787             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
11788                      8 * forced_insn_length);
11789           insn_error = buf;
11790
11791           return;
11792         }
11793
11794       imm_expr.X_op = O_absent;
11795       imm2_expr.X_op = O_absent;
11796       offset_expr.X_op = O_absent;
11797       offset_reloc[0] = BFD_RELOC_UNUSED;
11798       offset_reloc[1] = BFD_RELOC_UNUSED;
11799       offset_reloc[2] = BFD_RELOC_UNUSED;
11800
11801       create_insn (ip, insn);
11802       insn_error = NULL;
11803       memset (&arg, 0, sizeof (arg));
11804       arg.insn = ip;
11805       arg.argnum = 1;
11806       arg.last_regno = ILLEGAL_REG;
11807       arg.dest_regno = ILLEGAL_REG;
11808       arg.soft_match = (more_alts
11809                         || (wrong_delay_slot_insns && need_delay_slot_ok));
11810       for (args = insn->args;; ++args)
11811         {
11812           SKIP_SPACE_TABS (s);
11813           if (*s == 0)
11814             {
11815               /* Handle unary instructions in which only one operand is given.
11816                  The source is then the same as the destination.  */
11817               if (arg.opnum == 1 && *args == ',')
11818                 switch (args[1])
11819                   {
11820                   case 'r':
11821                   case 'v':
11822                   case 'w':
11823                   case 'W':
11824                   case 'V':
11825                     arg.argnum = 1;
11826                     s = argsStart;
11827                     continue;
11828                   }
11829
11830               /* Treat elided base registers as $0.  */
11831               if (strcmp (args, "(b)") == 0)
11832                 args += 3;
11833
11834               /* Fail the match if there were too few operands.  */
11835               if (*args)
11836                 break;
11837
11838               /* Successful match.  */
11839               if (arg.dest_regno == arg.last_regno
11840                   && strncmp (ip->insn_mo->name, "jalr", 4) == 0)
11841                 {
11842                   if (arg.opnum == 2)
11843                     as_bad (_("Source and destination must be different"));
11844                   else if (arg.last_regno == 31)
11845                     as_bad (_("A destination register must be supplied"));
11846                 }
11847               check_completed_insn (&arg);
11848               return;
11849             }
11850
11851           /* Fail the match if the line has too many operands.   */
11852           if (*args == 0)
11853             break;
11854
11855           /* Handle characters that need to match exactly.  */
11856           if (*args == '(' || *args == ')' || *args == ',')
11857             {
11858               if (*s != *args)
11859                 break;
11860               if (*s == ',')
11861                 arg.argnum += 1;
11862               ++s;
11863               continue;
11864             }
11865
11866           /* Handle special macro operands.  Work out the properties of
11867              other operands.  */
11868           arg.opnum += 1;
11869           arg.optional_reg = FALSE;
11870           arg.lax_max = FALSE;
11871           switch (*args)
11872             {
11873             case '+':
11874               switch (args[1])
11875                 {
11876                 case '1':
11877                 case '2':
11878                 case '3':
11879                 case '4':
11880                 case 'B':
11881                 case 'C':
11882                 case 'F':
11883                 case 'G':
11884                 case 'H':
11885                 case 'J':
11886                 case 'Q':
11887                 case 'S':
11888                 case 's':
11889                   /* If these integer forms come last, there is no other
11890                      form of the instruction that could match.  Prefer to
11891                      give detailed error messages where possible.  */
11892                   if (args[2] == 0)
11893                     arg.soft_match = FALSE;
11894                   break;
11895
11896                 case 'I':
11897                   /* "+I" is like "I", except that imm2_expr is used.  */
11898                   my_getExpression (&imm2_expr, s);
11899                   if (imm2_expr.X_op != O_big
11900                       && imm2_expr.X_op != O_constant)
11901                   insn_error = _("absolute expression required");
11902                   if (HAVE_32BIT_GPRS)
11903                     normalize_constant_expr (&imm2_expr);
11904                   s = expr_end;
11905                   ++args;
11906                   continue;
11907
11908                 case 'i':
11909                   *offset_reloc = BFD_RELOC_MIPS_JMP;
11910                   break;
11911                 }
11912               break;
11913
11914             case '\'':
11915             case ':':
11916             case '@':
11917             case '^':
11918             case '$':
11919             case '\\':
11920             case '%':
11921             case '|':
11922             case '0':
11923             case '1':
11924             case '2':
11925             case '3':
11926             case '4':
11927             case '5':
11928             case '6':
11929             case '8':
11930             case 'B':
11931             case 'C':
11932             case 'J':
11933             case 'O':
11934             case 'P':
11935             case 'Q':
11936             case 'c':
11937             case 'h':
11938             case 'q':
11939               /* If these integer forms come last, there is no other
11940                  form of the instruction that could match.  Prefer to
11941                  give detailed error messages where possible.  */
11942               if (args[1] == 0)
11943                 arg.soft_match = FALSE;
11944               break;
11945
11946             case 'r':
11947             case 'v':
11948             case 'w':
11949             case 'W':
11950             case 'V':
11951               /* We have already matched a comma by this point, so the register
11952                  is only optional if there is another operand to come.  */
11953               gas_assert (arg.opnum == 2);
11954               arg.optional_reg = (args[1] == ',');
11955               break;
11956
11957             case 'I':
11958               my_getExpression (&imm_expr, s);
11959               if (imm_expr.X_op != O_big
11960                   && imm_expr.X_op != O_constant)
11961                 insn_error = _("absolute expression required");
11962               if (HAVE_32BIT_GPRS)
11963                 normalize_constant_expr (&imm_expr);
11964               s = expr_end;
11965               continue;
11966
11967             case 'A':
11968               my_getSmallExpression (&offset_expr, offset_reloc, s);
11969               if (offset_expr.X_op == O_register)
11970                 {
11971                   /* Assume that the offset has been elided and that what
11972                      we saw was a base register.  The match will fail later
11973                      if that assumption turns out to be wrong.  */
11974                   offset_expr.X_op = O_constant;
11975                   offset_expr.X_add_number = 0;
11976                 }
11977               else
11978                 {
11979                   normalize_address_expr (&offset_expr);
11980                   s = expr_end;
11981                 }
11982               continue;
11983
11984             case 'F':
11985             case 'L':
11986             case 'f':
11987             case 'l':
11988               {
11989                 int f64;
11990                 int using_gprs;
11991                 char *save_in;
11992                 char *err;
11993                 unsigned char temp[8];
11994                 int len;
11995                 unsigned int length;
11996                 segT seg;
11997                 subsegT subseg;
11998                 char *p;
11999
12000                 /* These only appear as the last operand in an
12001                    instruction, and every instruction that accepts
12002                    them in any variant accepts them in all variants.
12003                    This means we don't have to worry about backing out
12004                    any changes if the instruction does not match.
12005
12006                    The difference between them is the size of the
12007                    floating point constant and where it goes.  For 'F'
12008                    and 'L' the constant is 64 bits; for 'f' and 'l' it
12009                    is 32 bits.  Where the constant is placed is based
12010                    on how the MIPS assembler does things:
12011                     F -- .rdata
12012                     L -- .lit8
12013                     f -- immediate value
12014                     l -- .lit4
12015
12016                     The .lit4 and .lit8 sections are only used if
12017                     permitted by the -G argument.
12018
12019                     The code below needs to know whether the target register
12020                     is 32 or 64 bits wide.  It relies on the fact 'f' and
12021                     'F' are used with GPR-based instructions and 'l' and
12022                     'L' are used with FPR-based instructions.  */
12023
12024                 f64 = *args == 'F' || *args == 'L';
12025                 using_gprs = *args == 'F' || *args == 'f';
12026
12027                 save_in = input_line_pointer;
12028                 input_line_pointer = s;
12029                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
12030                 length = len;
12031                 s = input_line_pointer;
12032                 input_line_pointer = save_in;
12033                 if (err != NULL && *err != '\0')
12034                   {
12035                     as_bad (_("Bad floating point constant: %s"), err);
12036                     memset (temp, '\0', sizeof temp);
12037                     length = f64 ? 8 : 4;
12038                   }
12039
12040                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
12041
12042                 if (*args == 'f'
12043                     || (*args == 'l'
12044                         && (g_switch_value < 4
12045                             || (temp[0] == 0 && temp[1] == 0)
12046                             || (temp[2] == 0 && temp[3] == 0))))
12047                   {
12048                     imm_expr.X_op = O_constant;
12049                     if (!target_big_endian)
12050                       imm_expr.X_add_number = bfd_getl32 (temp);
12051                     else
12052                       imm_expr.X_add_number = bfd_getb32 (temp);
12053                   }
12054                 else if (length > 4
12055                          && !mips_disable_float_construction
12056                          /* Constants can only be constructed in GPRs and
12057                             copied to FPRs if the GPRs are at least as wide
12058                             as the FPRs.  Force the constant into memory if
12059                             we are using 64-bit FPRs but the GPRs are only
12060                             32 bits wide.  */
12061                          && (using_gprs
12062                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
12063                          && ((temp[0] == 0 && temp[1] == 0)
12064                              || (temp[2] == 0 && temp[3] == 0))
12065                          && ((temp[4] == 0 && temp[5] == 0)
12066                              || (temp[6] == 0 && temp[7] == 0)))
12067                   {
12068                     /* The value is simple enough to load with a couple of
12069                        instructions.  If using 32-bit registers, set
12070                        imm_expr to the high order 32 bits and offset_expr to
12071                        the low order 32 bits.  Otherwise, set imm_expr to
12072                        the entire 64 bit constant.  */
12073                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
12074                       {
12075                         imm_expr.X_op = O_constant;
12076                         offset_expr.X_op = O_constant;
12077                         if (!target_big_endian)
12078                           {
12079                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
12080                             offset_expr.X_add_number = bfd_getl32 (temp);
12081                           }
12082                         else
12083                           {
12084                             imm_expr.X_add_number = bfd_getb32 (temp);
12085                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
12086                           }
12087                         if (offset_expr.X_add_number == 0)
12088                           offset_expr.X_op = O_absent;
12089                       }
12090                     else
12091                       {
12092                         imm_expr.X_op = O_constant;
12093                         if (!target_big_endian)
12094                           imm_expr.X_add_number = bfd_getl64 (temp);
12095                         else
12096                           imm_expr.X_add_number = bfd_getb64 (temp);
12097                       }
12098                   }
12099                 else
12100                   {
12101                     const char *newname;
12102                     segT new_seg;
12103
12104                     /* Switch to the right section.  */
12105                     seg = now_seg;
12106                     subseg = now_subseg;
12107                     switch (*args)
12108                       {
12109                       default: /* unused default case avoids warnings.  */
12110                       case 'L':
12111                         newname = RDATA_SECTION_NAME;
12112                         if (g_switch_value >= 8)
12113                           newname = ".lit8";
12114                         break;
12115                       case 'F':
12116                         newname = RDATA_SECTION_NAME;
12117                         break;
12118                       case 'l':
12119                         gas_assert (g_switch_value >= 4);
12120                         newname = ".lit4";
12121                         break;
12122                       }
12123                     new_seg = subseg_new (newname, (subsegT) 0);
12124                     bfd_set_section_flags (stdoutput, new_seg,
12125                                            (SEC_ALLOC
12126                                             | SEC_LOAD
12127                                             | SEC_READONLY
12128                                             | SEC_DATA));
12129                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
12130                     if (strncmp (TARGET_OS, "elf", 3) != 0)
12131                       record_alignment (new_seg, 4);
12132                     else
12133                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
12134                     if (seg == now_seg)
12135                       as_bad (_("Can't use floating point insn in this section"));
12136
12137                     /* Set the argument to the current address in the
12138                        section.  */
12139                     offset_expr.X_op = O_symbol;
12140                     offset_expr.X_add_symbol = symbol_temp_new_now ();
12141                     offset_expr.X_add_number = 0;
12142
12143                     /* Put the floating point number into the section.  */
12144                     p = frag_more ((int) length);
12145                     memcpy (p, temp, length);
12146
12147                     /* Switch back to the original section.  */
12148                     subseg_set (seg, subseg);
12149                   }
12150               }
12151               continue;
12152
12153               /* ??? This is the traditional behavior, but is flaky if
12154                  there are alternative versions of the same instruction
12155                  for different subarchitectures.  The next alternative
12156                  might not be suitable.  */
12157             case 'j':
12158               /* For compatibility with older assemblers, we accept
12159                  0x8000-0xffff as signed 16-bit numbers when only
12160                  signed numbers are allowed.  */
12161               arg.lax_max = !more_alts;
12162             case 'i':
12163               /* Only accept non-constant operands if this is the
12164                  final alternative.  Later alternatives might include
12165                  a macro implementation.  */
12166               arg.allow_nonconst = !more_alts;
12167               break;
12168
12169             case 'u':
12170               /* There are no macro implementations for out-of-range values.  */
12171               arg.allow_nonconst = TRUE;
12172               break;
12173
12174             case 'o':
12175               /* There should always be a macro implementation.  */
12176               arg.allow_nonconst = FALSE;
12177               break;
12178
12179             case 'p':
12180               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12181               break;
12182
12183             case 'a':
12184               *offset_reloc = BFD_RELOC_MIPS_JMP;
12185               break;
12186
12187             case 'm':
12188               gas_assert (mips_opts.micromips);
12189               c = args[1];
12190               switch (c)
12191                 {
12192                 case 't':
12193                 case 'c':
12194                 case 'e':
12195                   /* We have already matched a comma by this point,
12196                      so the register is only optional if there is another
12197                      operand to come.  */
12198                   gas_assert (arg.opnum == 2);
12199                   arg.optional_reg = (args[2] == ',');
12200                   break;
12201
12202                 case 'D':
12203                 case 'E':
12204                   if (!forced_insn_length)
12205                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
12206                   else if (c == 'D')
12207                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
12208                   else
12209                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
12210                   break;
12211                 }
12212               break;
12213             }
12214
12215           operand = (mips_opts.micromips
12216                      ? decode_micromips_operand (args)
12217                      : decode_mips_operand (args));
12218           if (!operand)
12219             abort ();
12220
12221           s = match_operand (&arg, operand, s);
12222           if (!s && arg.optional_reg)
12223             {
12224               /* Assume that the register has been elided and is the
12225                  same as the first operand.  */
12226               arg.optional_reg = FALSE;
12227               arg.argnum = 1;
12228               s = argsStart;
12229               SKIP_SPACE_TABS (s);
12230               s = match_operand (&arg, operand, s);
12231             }
12232           if (!s)
12233             break;
12234
12235           /* Skip prefixes.  */
12236           if (*args == '+' || *args == 'm')
12237             args++;
12238
12239           continue;
12240         }
12241       /* Args don't match.  */
12242       s = argsStart;
12243       insn_error = _("Illegal operands");
12244       if (more_alts)
12245         {
12246           ++insn;
12247           continue;
12248         }
12249       if (wrong_delay_slot_insns && need_delay_slot_ok)
12250         {
12251           gas_assert (firstinsn);
12252           need_delay_slot_ok = FALSE;
12253           past = insn + 1;
12254           insn = firstinsn;
12255           continue;
12256         }
12257       return;
12258     }
12259 }
12260
12261 /* As for mips_ip, but used when assembling MIPS16 code.
12262    Also set forced_insn_length to the resulting instruction size in
12263    bytes if the user explicitly requested a small or extended instruction.  */
12264
12265 static void
12266 mips16_ip (char *str, struct mips_cl_insn *ip)
12267 {
12268   char *s;
12269   const char *args;
12270   struct mips_opcode *insn;
12271   char *argsstart;
12272   size_t i;
12273   const struct mips_operand *operand;
12274   const struct mips_operand *ext_operand;
12275   struct mips_arg_info arg;
12276
12277   insn_error = NULL;
12278
12279   forced_insn_length = 0;
12280
12281   for (s = str; ISLOWER (*s); ++s)
12282     ;
12283   switch (*s)
12284     {
12285     case '\0':
12286       break;
12287
12288     case ' ':
12289       *s++ = '\0';
12290       break;
12291
12292     case '.':
12293       if (s[1] == 't' && s[2] == ' ')
12294         {
12295           *s = '\0';
12296           forced_insn_length = 2;
12297           s += 3;
12298           break;
12299         }
12300       else if (s[1] == 'e' && s[2] == ' ')
12301         {
12302           *s = '\0';
12303           forced_insn_length = 4;
12304           s += 3;
12305           break;
12306         }
12307       /* Fall through.  */
12308     default:
12309       insn_error = _("unknown opcode");
12310       return;
12311     }
12312
12313   if (mips_opts.noautoextend && !forced_insn_length)
12314     forced_insn_length = 2;
12315
12316   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
12317     {
12318       insn_error = _("unrecognized opcode");
12319       return;
12320     }
12321
12322   argsstart = s;
12323   for (;;)
12324     {
12325       bfd_boolean ok;
12326       bfd_boolean more_alts;
12327       char relax_char;
12328
12329       gas_assert (strcmp (insn->name, str) == 0);
12330
12331       ok = is_opcode_valid_16 (insn);
12332       more_alts = (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
12333                    && strcmp (insn[0].name, insn[1].name) == 0);
12334       if (! ok)
12335         {
12336           if (more_alts)
12337             {
12338               ++insn;
12339               continue;
12340             }
12341           else
12342             {
12343               if (!insn_error)
12344                 {
12345                   static char buf[100];
12346                   sprintf (buf,
12347                            _("Opcode not supported on this processor: %s (%s)"),
12348                            mips_cpu_info_from_arch (mips_opts.arch)->name,
12349                            mips_cpu_info_from_isa (mips_opts.isa)->name);
12350                   insn_error = buf;
12351                 }
12352               return;
12353             }
12354         }
12355
12356       create_insn (ip, insn);
12357       imm_expr.X_op = O_absent;
12358       imm2_expr.X_op = O_absent;
12359       offset_expr.X_op = O_absent;
12360       offset_reloc[0] = BFD_RELOC_UNUSED;
12361       offset_reloc[1] = BFD_RELOC_UNUSED;
12362       offset_reloc[2] = BFD_RELOC_UNUSED;
12363       relax_char = 0;
12364
12365       memset (&arg, 0, sizeof (arg));
12366       arg.insn = ip;
12367       arg.argnum = 1;
12368       arg.last_regno = ILLEGAL_REG;
12369       arg.dest_regno = ILLEGAL_REG;
12370       arg.soft_match = more_alts;
12371       relax_char = 0;
12372       for (args = insn->args; 1; ++args)
12373         {
12374           int c;
12375
12376           SKIP_SPACE_TABS (s);
12377           if (*s == 0)
12378             {
12379               offsetT value;
12380
12381               /* Handle unary instructions in which only one operand is given.
12382                  The source is then the same as the destination.  */
12383               if (arg.opnum == 1 && *args == ',')
12384                 switch (args[1])
12385                   {
12386                   case 'v':
12387                   case 'w':
12388                     arg.argnum = 1;
12389                     s = argsstart;
12390                     continue;
12391                   }
12392
12393               /* Fail the match if there were too few operands.  */
12394               if (*args)
12395                 break;
12396
12397               /* Successful match.  Stuff the immediate value in now, if
12398                  we can.  */
12399               if (insn->pinfo == INSN_MACRO)
12400                 {
12401                   gas_assert (relax_char == 0);
12402                   gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
12403                 }
12404               else if (relax_char
12405                        && offset_expr.X_op == O_constant
12406                        && calculate_reloc (*offset_reloc,
12407                                            offset_expr.X_add_number,
12408                                            &value))
12409                 {
12410                   mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
12411                                 forced_insn_length, &ip->insn_opcode);
12412                   offset_expr.X_op = O_absent;
12413                   *offset_reloc = BFD_RELOC_UNUSED;
12414                 }
12415               else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
12416                 {
12417                   if (forced_insn_length == 2)
12418                     as_bad (_("invalid unextended operand value"));
12419                   forced_insn_length = 4;
12420                   ip->insn_opcode |= MIPS16_EXTEND;
12421                 }
12422               else if (relax_char)
12423                 *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
12424
12425               check_completed_insn (&arg);
12426               return;
12427             }
12428
12429           /* Fail the match if the line has too many operands.   */
12430           if (*args == 0)
12431             break;
12432
12433           /* Handle characters that need to match exactly.  */
12434           if (*args == '(' || *args == ')' || *args == ',')
12435             {
12436               if (*s != *args)
12437                 break;
12438               if (*s == ',')
12439                 arg.argnum += 1;
12440               ++s;
12441               continue;
12442             }
12443
12444           arg.opnum += 1;
12445           arg.optional_reg = FALSE;
12446           c = *args;
12447           switch (c)
12448             {
12449             case 'v':
12450             case 'w':
12451               arg.optional_reg = (args[1] == ',');
12452               break;
12453
12454             case 'p':
12455             case 'q':
12456             case 'A':
12457             case 'B':
12458             case 'E':
12459               relax_char = c;
12460               break;
12461
12462             case 'I':
12463               my_getExpression (&imm_expr, s);
12464               if (imm_expr.X_op != O_big
12465                   && imm_expr.X_op != O_constant)
12466                 insn_error = _("absolute expression required");
12467               if (HAVE_32BIT_GPRS)
12468                 normalize_constant_expr (&imm_expr);
12469               s = expr_end;
12470               continue;
12471
12472             case 'a':
12473             case 'i':
12474               *offset_reloc = BFD_RELOC_MIPS16_JMP;
12475               ip->insn_opcode <<= 16;
12476               break;
12477             }
12478
12479           operand = decode_mips16_operand (c, FALSE);
12480           if (!operand)
12481             abort ();
12482
12483           /* '6' is a special case.  It is used for BREAK and SDBBP,
12484              whose operands are only meaningful to the software that decodes
12485              them.  This means that there is no architectural reason why
12486              they cannot be prefixed by EXTEND, but in practice,
12487              exception handlers will only look at the instruction
12488              itself.  We therefore allow '6' to be extended when
12489              disassembling but not when assembling.  */
12490           if (operand->type != OP_PCREL && c != '6')
12491             {
12492               ext_operand = decode_mips16_operand (c, TRUE);
12493               if (operand != ext_operand)
12494                 {
12495                   /* Parse the expression, allowing relocation operators.  */
12496                   i = my_getSmallExpression (&offset_expr, offset_reloc, s);
12497                   s = expr_end;
12498
12499                   if (offset_expr.X_op == O_register)
12500                     {
12501                       /* Handle elided offsets, which are equivalent to 0.  */
12502                       if (*s == '(')
12503                         {
12504                           offset_expr.X_op = O_constant;
12505                           offset_expr.X_add_number = 0;
12506                           relax_char = c;
12507                           continue;
12508                         }
12509                       /* Fail the match.  */
12510                       break;
12511                     }
12512                   /* '8' is used for SLTI(U) and has traditionally not
12513                      been allowed to take relocation operators.  */
12514                   if (i > 0 && (ext_operand->size != 16 || c == '8'))
12515                     break;
12516                   relax_char = c;
12517                   continue;
12518                 }
12519             }
12520
12521           s = match_operand (&arg, operand, s);
12522           if (!s && arg.optional_reg)
12523             {
12524               /* Assume that the register has been elided and is the
12525                  same as the first operand.  */
12526               arg.optional_reg = FALSE;
12527               arg.argnum = 1;
12528               s = argsstart;
12529               SKIP_SPACE_TABS (s);
12530               s = match_operand (&arg, operand, s);
12531             }
12532           if (!s)
12533             break;
12534           continue;
12535         }
12536
12537       /* Args don't match.  */
12538       if (more_alts)
12539         {
12540           ++insn;
12541           s = argsstart;
12542           continue;
12543         }
12544
12545       insn_error = _("illegal operands");
12546
12547       return;
12548     }
12549 }
12550
12551 /* This structure holds information we know about a mips16 immediate
12552    argument type.  */
12553
12554 struct mips16_immed_operand
12555 {
12556   /* The type code used in the argument string in the opcode table.  */
12557   int type;
12558   /* The number of bits in the short form of the opcode.  */
12559   int nbits;
12560   /* The number of bits in the extended form of the opcode.  */
12561   int extbits;
12562   /* The amount by which the short form is shifted when it is used;
12563      for example, the sw instruction has a shift count of 2.  */
12564   int shift;
12565   /* The amount by which the short form is shifted when it is stored
12566      into the instruction code.  */
12567   int op_shift;
12568   /* Non-zero if the short form is unsigned.  */
12569   int unsp;
12570   /* Non-zero if the extended form is unsigned.  */
12571   int extu;
12572   /* Non-zero if the value is PC relative.  */
12573   int pcrel;
12574 };
12575
12576 /* The mips16 immediate operand types.  */
12577
12578 static const struct mips16_immed_operand mips16_immed_operands[] =
12579 {
12580   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
12581   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
12582   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
12583   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
12584   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
12585   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
12586   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
12587   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
12588   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
12589   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
12590   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
12591   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
12592   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
12593   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
12594   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
12595   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
12596   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
12597   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
12598   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
12599   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
12600   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
12601 };
12602
12603 #define MIPS16_NUM_IMMED \
12604   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
12605
12606 /* Marshal immediate value VAL for an extended MIPS16 instruction.
12607    NBITS is the number of significant bits in VAL.  */
12608
12609 static unsigned long
12610 mips16_immed_extend (offsetT val, unsigned int nbits)
12611 {
12612   int extval;
12613   if (nbits == 16)
12614     {
12615       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
12616       val &= 0x1f;
12617     }
12618   else if (nbits == 15)
12619     {
12620       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
12621       val &= 0xf;
12622     }
12623   else
12624     {
12625       extval = ((val & 0x1f) << 6) | (val & 0x20);
12626       val = 0;
12627     }
12628   return (extval << 16) | val;
12629 }
12630
12631 /* Install immediate value VAL into MIPS16 instruction *INSN,
12632    extending it if necessary.  The instruction in *INSN may
12633    already be extended.
12634
12635    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
12636    if none.  In the former case, VAL is a 16-bit number with no
12637    defined signedness.
12638
12639    TYPE is the type of the immediate field.  USER_INSN_LENGTH
12640    is the length that the user requested, or 0 if none.  */
12641
12642 static void
12643 mips16_immed (char *file, unsigned int line, int type,
12644               bfd_reloc_code_real_type reloc, offsetT val,
12645               unsigned int user_insn_length, unsigned long *insn)
12646 {
12647   const struct mips16_immed_operand *op;
12648   int mintiny, maxtiny;
12649
12650   op = mips16_immed_operands;
12651   while (op->type != type)
12652     {
12653       ++op;
12654       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
12655     }
12656
12657   if (op->unsp)
12658     {
12659       if (type == '<' || type == '>' || type == '[' || type == ']')
12660         {
12661           mintiny = 1;
12662           maxtiny = 1 << op->nbits;
12663         }
12664       else
12665         {
12666           mintiny = 0;
12667           maxtiny = (1 << op->nbits) - 1;
12668         }
12669       if (reloc != BFD_RELOC_UNUSED)
12670         val &= 0xffff;
12671     }
12672   else
12673     {
12674       mintiny = - (1 << (op->nbits - 1));
12675       maxtiny = (1 << (op->nbits - 1)) - 1;
12676       if (reloc != BFD_RELOC_UNUSED)
12677         val = SEXT_16BIT (val);
12678     }
12679
12680   /* Branch offsets have an implicit 0 in the lowest bit.  */
12681   if (type == 'p' || type == 'q')
12682     val /= 2;
12683
12684   if ((val & ((1 << op->shift) - 1)) != 0
12685       || val < (mintiny << op->shift)
12686       || val > (maxtiny << op->shift))
12687     {
12688       /* We need an extended instruction.  */
12689       if (user_insn_length == 2)
12690         as_bad_where (file, line, _("invalid unextended operand value"));
12691       else
12692         *insn |= MIPS16_EXTEND;
12693     }
12694   else if (user_insn_length == 4)
12695     {
12696       /* The operand doesn't force an unextended instruction to be extended.
12697          Warn if the user wanted an extended instruction anyway.  */
12698       *insn |= MIPS16_EXTEND;
12699       as_warn_where (file, line,
12700                      _("extended operand requested but not required"));
12701     }
12702
12703   if (mips16_opcode_length (*insn) == 2)
12704     {
12705       int insnval;
12706
12707       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
12708       insnval <<= op->op_shift;
12709       *insn |= insnval;
12710     }
12711   else
12712     {
12713       long minext, maxext;
12714
12715       if (reloc == BFD_RELOC_UNUSED)
12716         {
12717           if (op->extu)
12718             {
12719               minext = 0;
12720               maxext = (1 << op->extbits) - 1;
12721             }
12722           else
12723             {
12724               minext = - (1 << (op->extbits - 1));
12725               maxext = (1 << (op->extbits - 1)) - 1;
12726             }
12727           if (val < minext || val > maxext)
12728             as_bad_where (file, line,
12729                           _("operand value out of range for instruction"));
12730         }
12731
12732       *insn |= mips16_immed_extend (val, op->extbits);
12733     }
12734 }
12735 \f
12736 struct percent_op_match
12737 {
12738   const char *str;
12739   bfd_reloc_code_real_type reloc;
12740 };
12741
12742 static const struct percent_op_match mips_percent_op[] =
12743 {
12744   {"%lo", BFD_RELOC_LO16},
12745   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
12746   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
12747   {"%call16", BFD_RELOC_MIPS_CALL16},
12748   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
12749   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
12750   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
12751   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
12752   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
12753   {"%got", BFD_RELOC_MIPS_GOT16},
12754   {"%gp_rel", BFD_RELOC_GPREL16},
12755   {"%half", BFD_RELOC_16},
12756   {"%highest", BFD_RELOC_MIPS_HIGHEST},
12757   {"%higher", BFD_RELOC_MIPS_HIGHER},
12758   {"%neg", BFD_RELOC_MIPS_SUB},
12759   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
12760   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
12761   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
12762   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
12763   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
12764   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
12765   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
12766   {"%hi", BFD_RELOC_HI16_S}
12767 };
12768
12769 static const struct percent_op_match mips16_percent_op[] =
12770 {
12771   {"%lo", BFD_RELOC_MIPS16_LO16},
12772   {"%gprel", BFD_RELOC_MIPS16_GPREL},
12773   {"%got", BFD_RELOC_MIPS16_GOT16},
12774   {"%call16", BFD_RELOC_MIPS16_CALL16},
12775   {"%hi", BFD_RELOC_MIPS16_HI16_S},
12776   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
12777   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
12778   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
12779   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
12780   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
12781   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
12782   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
12783 };
12784
12785
12786 /* Return true if *STR points to a relocation operator.  When returning true,
12787    move *STR over the operator and store its relocation code in *RELOC.
12788    Leave both *STR and *RELOC alone when returning false.  */
12789
12790 static bfd_boolean
12791 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
12792 {
12793   const struct percent_op_match *percent_op;
12794   size_t limit, i;
12795
12796   if (mips_opts.mips16)
12797     {
12798       percent_op = mips16_percent_op;
12799       limit = ARRAY_SIZE (mips16_percent_op);
12800     }
12801   else
12802     {
12803       percent_op = mips_percent_op;
12804       limit = ARRAY_SIZE (mips_percent_op);
12805     }
12806
12807   for (i = 0; i < limit; i++)
12808     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
12809       {
12810         int len = strlen (percent_op[i].str);
12811
12812         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
12813           continue;
12814
12815         *str += strlen (percent_op[i].str);
12816         *reloc = percent_op[i].reloc;
12817
12818         /* Check whether the output BFD supports this relocation.
12819            If not, issue an error and fall back on something safe.  */
12820         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
12821           {
12822             as_bad (_("relocation %s isn't supported by the current ABI"),
12823                     percent_op[i].str);
12824             *reloc = BFD_RELOC_UNUSED;
12825           }
12826         return TRUE;
12827       }
12828   return FALSE;
12829 }
12830
12831
12832 /* Parse string STR as a 16-bit relocatable operand.  Store the
12833    expression in *EP and the relocations in the array starting
12834    at RELOC.  Return the number of relocation operators used.
12835
12836    On exit, EXPR_END points to the first character after the expression.  */
12837
12838 static size_t
12839 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
12840                        char *str)
12841 {
12842   bfd_reloc_code_real_type reversed_reloc[3];
12843   size_t reloc_index, i;
12844   int crux_depth, str_depth;
12845   char *crux;
12846
12847   /* Search for the start of the main expression, recoding relocations
12848      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
12849      of the main expression and with CRUX_DEPTH containing the number
12850      of open brackets at that point.  */
12851   reloc_index = -1;
12852   str_depth = 0;
12853   do
12854     {
12855       reloc_index++;
12856       crux = str;
12857       crux_depth = str_depth;
12858
12859       /* Skip over whitespace and brackets, keeping count of the number
12860          of brackets.  */
12861       while (*str == ' ' || *str == '\t' || *str == '(')
12862         if (*str++ == '(')
12863           str_depth++;
12864     }
12865   while (*str == '%'
12866          && reloc_index < (HAVE_NEWABI ? 3 : 1)
12867          && parse_relocation (&str, &reversed_reloc[reloc_index]));
12868
12869   my_getExpression (ep, crux);
12870   str = expr_end;
12871
12872   /* Match every open bracket.  */
12873   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
12874     if (*str++ == ')')
12875       crux_depth--;
12876
12877   if (crux_depth > 0)
12878     as_bad (_("unclosed '('"));
12879
12880   expr_end = str;
12881
12882   if (reloc_index != 0)
12883     {
12884       prev_reloc_op_frag = frag_now;
12885       for (i = 0; i < reloc_index; i++)
12886         reloc[i] = reversed_reloc[reloc_index - 1 - i];
12887     }
12888
12889   return reloc_index;
12890 }
12891
12892 static void
12893 my_getExpression (expressionS *ep, char *str)
12894 {
12895   char *save_in;
12896
12897   save_in = input_line_pointer;
12898   input_line_pointer = str;
12899   expression (ep);
12900   expr_end = input_line_pointer;
12901   input_line_pointer = save_in;
12902 }
12903
12904 char *
12905 md_atof (int type, char *litP, int *sizeP)
12906 {
12907   return ieee_md_atof (type, litP, sizeP, target_big_endian);
12908 }
12909
12910 void
12911 md_number_to_chars (char *buf, valueT val, int n)
12912 {
12913   if (target_big_endian)
12914     number_to_chars_bigendian (buf, val, n);
12915   else
12916     number_to_chars_littleendian (buf, val, n);
12917 }
12918 \f
12919 static int support_64bit_objects(void)
12920 {
12921   const char **list, **l;
12922   int yes;
12923
12924   list = bfd_target_list ();
12925   for (l = list; *l != NULL; l++)
12926     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
12927         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
12928       break;
12929   yes = (*l != NULL);
12930   free (list);
12931   return yes;
12932 }
12933
12934 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
12935    NEW_VALUE.  Warn if another value was already specified.  Note:
12936    we have to defer parsing the -march and -mtune arguments in order
12937    to handle 'from-abi' correctly, since the ABI might be specified
12938    in a later argument.  */
12939
12940 static void
12941 mips_set_option_string (const char **string_ptr, const char *new_value)
12942 {
12943   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
12944     as_warn (_("A different %s was already specified, is now %s"),
12945              string_ptr == &mips_arch_string ? "-march" : "-mtune",
12946              new_value);
12947
12948   *string_ptr = new_value;
12949 }
12950
12951 int
12952 md_parse_option (int c, char *arg)
12953 {
12954   unsigned int i;
12955
12956   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
12957     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
12958       {
12959         file_ase_explicit |= mips_set_ase (&mips_ases[i],
12960                                            c == mips_ases[i].option_on);
12961         return 1;
12962       }
12963
12964   switch (c)
12965     {
12966     case OPTION_CONSTRUCT_FLOATS:
12967       mips_disable_float_construction = 0;
12968       break;
12969
12970     case OPTION_NO_CONSTRUCT_FLOATS:
12971       mips_disable_float_construction = 1;
12972       break;
12973
12974     case OPTION_TRAP:
12975       mips_trap = 1;
12976       break;
12977
12978     case OPTION_BREAK:
12979       mips_trap = 0;
12980       break;
12981
12982     case OPTION_EB:
12983       target_big_endian = 1;
12984       break;
12985
12986     case OPTION_EL:
12987       target_big_endian = 0;
12988       break;
12989
12990     case 'O':
12991       if (arg == NULL)
12992         mips_optimize = 1;
12993       else if (arg[0] == '0')
12994         mips_optimize = 0;
12995       else if (arg[0] == '1')
12996         mips_optimize = 1;
12997       else
12998         mips_optimize = 2;
12999       break;
13000
13001     case 'g':
13002       if (arg == NULL)
13003         mips_debug = 2;
13004       else
13005         mips_debug = atoi (arg);
13006       break;
13007
13008     case OPTION_MIPS1:
13009       file_mips_isa = ISA_MIPS1;
13010       break;
13011
13012     case OPTION_MIPS2:
13013       file_mips_isa = ISA_MIPS2;
13014       break;
13015
13016     case OPTION_MIPS3:
13017       file_mips_isa = ISA_MIPS3;
13018       break;
13019
13020     case OPTION_MIPS4:
13021       file_mips_isa = ISA_MIPS4;
13022       break;
13023
13024     case OPTION_MIPS5:
13025       file_mips_isa = ISA_MIPS5;
13026       break;
13027
13028     case OPTION_MIPS32:
13029       file_mips_isa = ISA_MIPS32;
13030       break;
13031
13032     case OPTION_MIPS32R2:
13033       file_mips_isa = ISA_MIPS32R2;
13034       break;
13035
13036     case OPTION_MIPS64R2:
13037       file_mips_isa = ISA_MIPS64R2;
13038       break;
13039
13040     case OPTION_MIPS64:
13041       file_mips_isa = ISA_MIPS64;
13042       break;
13043
13044     case OPTION_MTUNE:
13045       mips_set_option_string (&mips_tune_string, arg);
13046       break;
13047
13048     case OPTION_MARCH:
13049       mips_set_option_string (&mips_arch_string, arg);
13050       break;
13051
13052     case OPTION_M4650:
13053       mips_set_option_string (&mips_arch_string, "4650");
13054       mips_set_option_string (&mips_tune_string, "4650");
13055       break;
13056
13057     case OPTION_NO_M4650:
13058       break;
13059
13060     case OPTION_M4010:
13061       mips_set_option_string (&mips_arch_string, "4010");
13062       mips_set_option_string (&mips_tune_string, "4010");
13063       break;
13064
13065     case OPTION_NO_M4010:
13066       break;
13067
13068     case OPTION_M4100:
13069       mips_set_option_string (&mips_arch_string, "4100");
13070       mips_set_option_string (&mips_tune_string, "4100");
13071       break;
13072
13073     case OPTION_NO_M4100:
13074       break;
13075
13076     case OPTION_M3900:
13077       mips_set_option_string (&mips_arch_string, "3900");
13078       mips_set_option_string (&mips_tune_string, "3900");
13079       break;
13080
13081     case OPTION_NO_M3900:
13082       break;
13083
13084     case OPTION_MICROMIPS:
13085       if (mips_opts.mips16 == 1)
13086         {
13087           as_bad (_("-mmicromips cannot be used with -mips16"));
13088           return 0;
13089         }
13090       mips_opts.micromips = 1;
13091       mips_no_prev_insn ();
13092       break;
13093
13094     case OPTION_NO_MICROMIPS:
13095       mips_opts.micromips = 0;
13096       mips_no_prev_insn ();
13097       break;
13098
13099     case OPTION_MIPS16:
13100       if (mips_opts.micromips == 1)
13101         {
13102           as_bad (_("-mips16 cannot be used with -micromips"));
13103           return 0;
13104         }
13105       mips_opts.mips16 = 1;
13106       mips_no_prev_insn ();
13107       break;
13108
13109     case OPTION_NO_MIPS16:
13110       mips_opts.mips16 = 0;
13111       mips_no_prev_insn ();
13112       break;
13113
13114     case OPTION_FIX_24K:
13115       mips_fix_24k = 1;
13116       break;
13117
13118     case OPTION_NO_FIX_24K:
13119       mips_fix_24k = 0;
13120       break;
13121
13122     case OPTION_FIX_LOONGSON2F_JUMP:
13123       mips_fix_loongson2f_jump = TRUE;
13124       break;
13125
13126     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13127       mips_fix_loongson2f_jump = FALSE;
13128       break;
13129
13130     case OPTION_FIX_LOONGSON2F_NOP:
13131       mips_fix_loongson2f_nop = TRUE;
13132       break;
13133
13134     case OPTION_NO_FIX_LOONGSON2F_NOP:
13135       mips_fix_loongson2f_nop = FALSE;
13136       break;
13137
13138     case OPTION_FIX_VR4120:
13139       mips_fix_vr4120 = 1;
13140       break;
13141
13142     case OPTION_NO_FIX_VR4120:
13143       mips_fix_vr4120 = 0;
13144       break;
13145
13146     case OPTION_FIX_VR4130:
13147       mips_fix_vr4130 = 1;
13148       break;
13149
13150     case OPTION_NO_FIX_VR4130:
13151       mips_fix_vr4130 = 0;
13152       break;
13153
13154     case OPTION_FIX_CN63XXP1:
13155       mips_fix_cn63xxp1 = TRUE;
13156       break;
13157
13158     case OPTION_NO_FIX_CN63XXP1:
13159       mips_fix_cn63xxp1 = FALSE;
13160       break;
13161
13162     case OPTION_RELAX_BRANCH:
13163       mips_relax_branch = 1;
13164       break;
13165
13166     case OPTION_NO_RELAX_BRANCH:
13167       mips_relax_branch = 0;
13168       break;
13169
13170     case OPTION_INSN32:
13171       mips_opts.insn32 = TRUE;
13172       break;
13173
13174     case OPTION_NO_INSN32:
13175       mips_opts.insn32 = FALSE;
13176       break;
13177
13178     case OPTION_MSHARED:
13179       mips_in_shared = TRUE;
13180       break;
13181
13182     case OPTION_MNO_SHARED:
13183       mips_in_shared = FALSE;
13184       break;
13185
13186     case OPTION_MSYM32:
13187       mips_opts.sym32 = TRUE;
13188       break;
13189
13190     case OPTION_MNO_SYM32:
13191       mips_opts.sym32 = FALSE;
13192       break;
13193
13194       /* When generating ELF code, we permit -KPIC and -call_shared to
13195          select SVR4_PIC, and -non_shared to select no PIC.  This is
13196          intended to be compatible with Irix 5.  */
13197     case OPTION_CALL_SHARED:
13198       mips_pic = SVR4_PIC;
13199       mips_abicalls = TRUE;
13200       break;
13201
13202     case OPTION_CALL_NONPIC:
13203       mips_pic = NO_PIC;
13204       mips_abicalls = TRUE;
13205       break;
13206
13207     case OPTION_NON_SHARED:
13208       mips_pic = NO_PIC;
13209       mips_abicalls = FALSE;
13210       break;
13211
13212       /* The -xgot option tells the assembler to use 32 bit offsets
13213          when accessing the got in SVR4_PIC mode.  It is for Irix
13214          compatibility.  */
13215     case OPTION_XGOT:
13216       mips_big_got = 1;
13217       break;
13218
13219     case 'G':
13220       g_switch_value = atoi (arg);
13221       g_switch_seen = 1;
13222       break;
13223
13224       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13225          and -mabi=64.  */
13226     case OPTION_32:
13227       mips_abi = O32_ABI;
13228       break;
13229
13230     case OPTION_N32:
13231       mips_abi = N32_ABI;
13232       break;
13233
13234     case OPTION_64:
13235       mips_abi = N64_ABI;
13236       if (!support_64bit_objects())
13237         as_fatal (_("No compiled in support for 64 bit object file format"));
13238       break;
13239
13240     case OPTION_GP32:
13241       file_mips_gp32 = 1;
13242       break;
13243
13244     case OPTION_GP64:
13245       file_mips_gp32 = 0;
13246       break;
13247
13248     case OPTION_FP32:
13249       file_mips_fp32 = 1;
13250       break;
13251
13252     case OPTION_FP64:
13253       file_mips_fp32 = 0;
13254       break;
13255
13256     case OPTION_SINGLE_FLOAT:
13257       file_mips_single_float = 1;
13258       break;
13259
13260     case OPTION_DOUBLE_FLOAT:
13261       file_mips_single_float = 0;
13262       break;
13263
13264     case OPTION_SOFT_FLOAT:
13265       file_mips_soft_float = 1;
13266       break;
13267
13268     case OPTION_HARD_FLOAT:
13269       file_mips_soft_float = 0;
13270       break;
13271
13272     case OPTION_MABI:
13273       if (strcmp (arg, "32") == 0)
13274         mips_abi = O32_ABI;
13275       else if (strcmp (arg, "o64") == 0)
13276         mips_abi = O64_ABI;
13277       else if (strcmp (arg, "n32") == 0)
13278         mips_abi = N32_ABI;
13279       else if (strcmp (arg, "64") == 0)
13280         {
13281           mips_abi = N64_ABI;
13282           if (! support_64bit_objects())
13283             as_fatal (_("No compiled in support for 64 bit object file "
13284                         "format"));
13285         }
13286       else if (strcmp (arg, "eabi") == 0)
13287         mips_abi = EABI_ABI;
13288       else
13289         {
13290           as_fatal (_("invalid abi -mabi=%s"), arg);
13291           return 0;
13292         }
13293       break;
13294
13295     case OPTION_M7000_HILO_FIX:
13296       mips_7000_hilo_fix = TRUE;
13297       break;
13298
13299     case OPTION_MNO_7000_HILO_FIX:
13300       mips_7000_hilo_fix = FALSE;
13301       break;
13302
13303     case OPTION_MDEBUG:
13304       mips_flag_mdebug = TRUE;
13305       break;
13306
13307     case OPTION_NO_MDEBUG:
13308       mips_flag_mdebug = FALSE;
13309       break;
13310
13311     case OPTION_PDR:
13312       mips_flag_pdr = TRUE;
13313       break;
13314
13315     case OPTION_NO_PDR:
13316       mips_flag_pdr = FALSE;
13317       break;
13318
13319     case OPTION_MVXWORKS_PIC:
13320       mips_pic = VXWORKS_PIC;
13321       break;
13322
13323     case OPTION_NAN:
13324       if (strcmp (arg, "2008") == 0)
13325         mips_flag_nan2008 = TRUE;
13326       else if (strcmp (arg, "legacy") == 0)
13327         mips_flag_nan2008 = FALSE;
13328       else
13329         {
13330           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
13331           return 0;
13332         }
13333       break;
13334
13335     default:
13336       return 0;
13337     }
13338
13339     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13340
13341   return 1;
13342 }
13343 \f
13344 /* Set up globals to generate code for the ISA or processor
13345    described by INFO.  */
13346
13347 static void
13348 mips_set_architecture (const struct mips_cpu_info *info)
13349 {
13350   if (info != 0)
13351     {
13352       file_mips_arch = info->cpu;
13353       mips_opts.arch = info->cpu;
13354       mips_opts.isa = info->isa;
13355     }
13356 }
13357
13358
13359 /* Likewise for tuning.  */
13360
13361 static void
13362 mips_set_tune (const struct mips_cpu_info *info)
13363 {
13364   if (info != 0)
13365     mips_tune = info->cpu;
13366 }
13367
13368
13369 void
13370 mips_after_parse_args (void)
13371 {
13372   const struct mips_cpu_info *arch_info = 0;
13373   const struct mips_cpu_info *tune_info = 0;
13374
13375   /* GP relative stuff not working for PE */
13376   if (strncmp (TARGET_OS, "pe", 2) == 0)
13377     {
13378       if (g_switch_seen && g_switch_value != 0)
13379         as_bad (_("-G not supported in this configuration."));
13380       g_switch_value = 0;
13381     }
13382
13383   if (mips_abi == NO_ABI)
13384     mips_abi = MIPS_DEFAULT_ABI;
13385
13386   /* The following code determines the architecture and register size.
13387      Similar code was added to GCC 3.3 (see override_options() in
13388      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13389      as much as possible.  */
13390
13391   if (mips_arch_string != 0)
13392     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13393
13394   if (file_mips_isa != ISA_UNKNOWN)
13395     {
13396       /* Handle -mipsN.  At this point, file_mips_isa contains the
13397          ISA level specified by -mipsN, while arch_info->isa contains
13398          the -march selection (if any).  */
13399       if (arch_info != 0)
13400         {
13401           /* -march takes precedence over -mipsN, since it is more descriptive.
13402              There's no harm in specifying both as long as the ISA levels
13403              are the same.  */
13404           if (file_mips_isa != arch_info->isa)
13405             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
13406                     mips_cpu_info_from_isa (file_mips_isa)->name,
13407                     mips_cpu_info_from_isa (arch_info->isa)->name);
13408         }
13409       else
13410         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13411     }
13412
13413   if (arch_info == 0)
13414     {
13415       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13416       gas_assert (arch_info);
13417     }
13418
13419   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13420     as_bad (_("-march=%s is not compatible with the selected ABI"),
13421             arch_info->name);
13422
13423   mips_set_architecture (arch_info);
13424
13425   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13426   if (mips_tune_string != 0)
13427     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13428
13429   if (tune_info == 0)
13430     mips_set_tune (arch_info);
13431   else
13432     mips_set_tune (tune_info);
13433
13434   if (file_mips_gp32 >= 0)
13435     {
13436       /* The user specified the size of the integer registers.  Make sure
13437          it agrees with the ABI and ISA.  */
13438       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13439         as_bad (_("-mgp64 used with a 32-bit processor"));
13440       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13441         as_bad (_("-mgp32 used with a 64-bit ABI"));
13442       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13443         as_bad (_("-mgp64 used with a 32-bit ABI"));
13444     }
13445   else
13446     {
13447       /* Infer the integer register size from the ABI and processor.
13448          Restrict ourselves to 32-bit registers if that's all the
13449          processor has, or if the ABI cannot handle 64-bit registers.  */
13450       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13451                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13452     }
13453
13454   switch (file_mips_fp32)
13455     {
13456     default:
13457     case -1:
13458       /* No user specified float register size.
13459          ??? GAS treats single-float processors as though they had 64-bit
13460          float registers (although it complains when double-precision
13461          instructions are used).  As things stand, saying they have 32-bit
13462          registers would lead to spurious "register must be even" messages.
13463          So here we assume float registers are never smaller than the
13464          integer ones.  */
13465       if (file_mips_gp32 == 0)
13466         /* 64-bit integer registers implies 64-bit float registers.  */
13467         file_mips_fp32 = 0;
13468       else if ((mips_opts.ase & FP64_ASES)
13469                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13470         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13471         file_mips_fp32 = 0;
13472       else
13473         /* 32-bit float registers.  */
13474         file_mips_fp32 = 1;
13475       break;
13476
13477     /* The user specified the size of the float registers.  Check if it
13478        agrees with the ABI and ISA.  */
13479     case 0:
13480       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13481         as_bad (_("-mfp64 used with a 32-bit fpu"));
13482       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13483                && !ISA_HAS_MXHC1 (mips_opts.isa))
13484         as_warn (_("-mfp64 used with a 32-bit ABI"));
13485       break;
13486     case 1:
13487       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13488         as_warn (_("-mfp32 used with a 64-bit ABI"));
13489       break;
13490     }
13491
13492   /* End of GCC-shared inference code.  */
13493
13494   /* This flag is set when we have a 64-bit capable CPU but use only
13495      32-bit wide registers.  Note that EABI does not use it.  */
13496   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
13497       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
13498           || mips_abi == O32_ABI))
13499     mips_32bitmode = 1;
13500
13501   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
13502     as_bad (_("trap exception not supported at ISA 1"));
13503
13504   /* If the selected architecture includes support for ASEs, enable
13505      generation of code for them.  */
13506   if (mips_opts.mips16 == -1)
13507     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
13508   if (mips_opts.micromips == -1)
13509     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
13510
13511   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
13512      ASEs from being selected implicitly.  */
13513   if (file_mips_fp32 == 1)
13514     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
13515
13516   /* If the user didn't explicitly select or deselect a particular ASE,
13517      use the default setting for the CPU.  */
13518   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
13519
13520   file_mips_isa = mips_opts.isa;
13521   file_ase = mips_opts.ase;
13522   mips_opts.gp32 = file_mips_gp32;
13523   mips_opts.fp32 = file_mips_fp32;
13524   mips_opts.soft_float = file_mips_soft_float;
13525   mips_opts.single_float = file_mips_single_float;
13526
13527   mips_check_isa_supports_ases ();
13528
13529   if (mips_flag_mdebug < 0)
13530     mips_flag_mdebug = 0;
13531 }
13532 \f
13533 void
13534 mips_init_after_args (void)
13535 {
13536   /* initialize opcodes */
13537   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
13538   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
13539 }
13540
13541 long
13542 md_pcrel_from (fixS *fixP)
13543 {
13544   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
13545   switch (fixP->fx_r_type)
13546     {
13547     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
13548     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
13549       /* Return the address of the delay slot.  */
13550       return addr + 2;
13551
13552     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
13553     case BFD_RELOC_MICROMIPS_JMP:
13554     case BFD_RELOC_16_PCREL_S2:
13555     case BFD_RELOC_MIPS_JMP:
13556       /* Return the address of the delay slot.  */
13557       return addr + 4;
13558
13559     case BFD_RELOC_32_PCREL:
13560       return addr;
13561
13562     default:
13563       /* We have no relocation type for PC relative MIPS16 instructions.  */
13564       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
13565         as_bad_where (fixP->fx_file, fixP->fx_line,
13566                       _("PC relative MIPS16 instruction references a different section"));
13567       return addr;
13568     }
13569 }
13570
13571 /* This is called before the symbol table is processed.  In order to
13572    work with gcc when using mips-tfile, we must keep all local labels.
13573    However, in other cases, we want to discard them.  If we were
13574    called with -g, but we didn't see any debugging information, it may
13575    mean that gcc is smuggling debugging information through to
13576    mips-tfile, in which case we must generate all local labels.  */
13577
13578 void
13579 mips_frob_file_before_adjust (void)
13580 {
13581 #ifndef NO_ECOFF_DEBUGGING
13582   if (ECOFF_DEBUGGING
13583       && mips_debug != 0
13584       && ! ecoff_debugging_seen)
13585     flag_keep_locals = 1;
13586 #endif
13587 }
13588
13589 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
13590    the corresponding LO16 reloc.  This is called before md_apply_fix and
13591    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
13592    relocation operators.
13593
13594    For our purposes, a %lo() expression matches a %got() or %hi()
13595    expression if:
13596
13597       (a) it refers to the same symbol; and
13598       (b) the offset applied in the %lo() expression is no lower than
13599           the offset applied in the %got() or %hi().
13600
13601    (b) allows us to cope with code like:
13602
13603         lui     $4,%hi(foo)
13604         lh      $4,%lo(foo+2)($4)
13605
13606    ...which is legal on RELA targets, and has a well-defined behaviour
13607    if the user knows that adding 2 to "foo" will not induce a carry to
13608    the high 16 bits.
13609
13610    When several %lo()s match a particular %got() or %hi(), we use the
13611    following rules to distinguish them:
13612
13613      (1) %lo()s with smaller offsets are a better match than %lo()s with
13614          higher offsets.
13615
13616      (2) %lo()s with no matching %got() or %hi() are better than those
13617          that already have a matching %got() or %hi().
13618
13619      (3) later %lo()s are better than earlier %lo()s.
13620
13621    These rules are applied in order.
13622
13623    (1) means, among other things, that %lo()s with identical offsets are
13624    chosen if they exist.
13625
13626    (2) means that we won't associate several high-part relocations with
13627    the same low-part relocation unless there's no alternative.  Having
13628    several high parts for the same low part is a GNU extension; this rule
13629    allows careful users to avoid it.
13630
13631    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
13632    with the last high-part relocation being at the front of the list.
13633    It therefore makes sense to choose the last matching low-part
13634    relocation, all other things being equal.  It's also easier
13635    to code that way.  */
13636
13637 void
13638 mips_frob_file (void)
13639 {
13640   struct mips_hi_fixup *l;
13641   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
13642
13643   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
13644     {
13645       segment_info_type *seginfo;
13646       bfd_boolean matched_lo_p;
13647       fixS **hi_pos, **lo_pos, **pos;
13648
13649       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
13650
13651       /* If a GOT16 relocation turns out to be against a global symbol,
13652          there isn't supposed to be a matching LO.  Ignore %gots against
13653          constants; we'll report an error for those later.  */
13654       if (got16_reloc_p (l->fixp->fx_r_type)
13655           && !(l->fixp->fx_addsy
13656                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
13657         continue;
13658
13659       /* Check quickly whether the next fixup happens to be a matching %lo.  */
13660       if (fixup_has_matching_lo_p (l->fixp))
13661         continue;
13662
13663       seginfo = seg_info (l->seg);
13664
13665       /* Set HI_POS to the position of this relocation in the chain.
13666          Set LO_POS to the position of the chosen low-part relocation.
13667          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
13668          relocation that matches an immediately-preceding high-part
13669          relocation.  */
13670       hi_pos = NULL;
13671       lo_pos = NULL;
13672       matched_lo_p = FALSE;
13673       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
13674
13675       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
13676         {
13677           if (*pos == l->fixp)
13678             hi_pos = pos;
13679
13680           if ((*pos)->fx_r_type == looking_for_rtype
13681               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
13682               && (*pos)->fx_offset >= l->fixp->fx_offset
13683               && (lo_pos == NULL
13684                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
13685                   || (!matched_lo_p
13686                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
13687             lo_pos = pos;
13688
13689           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
13690                           && fixup_has_matching_lo_p (*pos));
13691         }
13692
13693       /* If we found a match, remove the high-part relocation from its
13694          current position and insert it before the low-part relocation.
13695          Make the offsets match so that fixup_has_matching_lo_p()
13696          will return true.
13697
13698          We don't warn about unmatched high-part relocations since some
13699          versions of gcc have been known to emit dead "lui ...%hi(...)"
13700          instructions.  */
13701       if (lo_pos != NULL)
13702         {
13703           l->fixp->fx_offset = (*lo_pos)->fx_offset;
13704           if (l->fixp->fx_next != *lo_pos)
13705             {
13706               *hi_pos = l->fixp->fx_next;
13707               l->fixp->fx_next = *lo_pos;
13708               *lo_pos = l->fixp;
13709             }
13710         }
13711     }
13712 }
13713
13714 int
13715 mips_force_relocation (fixS *fixp)
13716 {
13717   if (generic_force_reloc (fixp))
13718     return 1;
13719
13720   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
13721      so that the linker relaxation can update targets.  */
13722   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
13723       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
13724       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
13725     return 1;
13726
13727   return 0;
13728 }
13729
13730 /* Read the instruction associated with RELOC from BUF.  */
13731
13732 static unsigned int
13733 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
13734 {
13735   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
13736     return read_compressed_insn (buf, 4);
13737   else
13738     return read_insn (buf);
13739 }
13740
13741 /* Write instruction INSN to BUF, given that it has been relocated
13742    by RELOC.  */
13743
13744 static void
13745 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
13746                   unsigned long insn)
13747 {
13748   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
13749     write_compressed_insn (buf, insn, 4);
13750   else
13751     write_insn (buf, insn);
13752 }
13753
13754 /* Apply a fixup to the object file.  */
13755
13756 void
13757 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
13758 {
13759   char *buf;
13760   unsigned long insn;
13761   reloc_howto_type *howto;
13762
13763   /* We ignore generic BFD relocations we don't know about.  */
13764   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
13765   if (! howto)
13766     return;
13767
13768   gas_assert (fixP->fx_size == 2
13769               || fixP->fx_size == 4
13770               || fixP->fx_r_type == BFD_RELOC_16
13771               || fixP->fx_r_type == BFD_RELOC_64
13772               || fixP->fx_r_type == BFD_RELOC_CTOR
13773               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
13774               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
13775               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
13776               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
13777               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
13778
13779   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
13780
13781   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
13782               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
13783               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
13784               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
13785               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
13786
13787   /* Don't treat parts of a composite relocation as done.  There are two
13788      reasons for this:
13789
13790      (1) The second and third parts will be against 0 (RSS_UNDEF) but
13791          should nevertheless be emitted if the first part is.
13792
13793      (2) In normal usage, composite relocations are never assembly-time
13794          constants.  The easiest way of dealing with the pathological
13795          exceptions is to generate a relocation against STN_UNDEF and
13796          leave everything up to the linker.  */
13797   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
13798     fixP->fx_done = 1;
13799
13800   switch (fixP->fx_r_type)
13801     {
13802     case BFD_RELOC_MIPS_TLS_GD:
13803     case BFD_RELOC_MIPS_TLS_LDM:
13804     case BFD_RELOC_MIPS_TLS_DTPREL32:
13805     case BFD_RELOC_MIPS_TLS_DTPREL64:
13806     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
13807     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
13808     case BFD_RELOC_MIPS_TLS_GOTTPREL:
13809     case BFD_RELOC_MIPS_TLS_TPREL32:
13810     case BFD_RELOC_MIPS_TLS_TPREL64:
13811     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
13812     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
13813     case BFD_RELOC_MICROMIPS_TLS_GD:
13814     case BFD_RELOC_MICROMIPS_TLS_LDM:
13815     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
13816     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
13817     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
13818     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
13819     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
13820     case BFD_RELOC_MIPS16_TLS_GD:
13821     case BFD_RELOC_MIPS16_TLS_LDM:
13822     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
13823     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
13824     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
13825     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
13826     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
13827       if (!fixP->fx_addsy)
13828         {
13829           as_bad_where (fixP->fx_file, fixP->fx_line,
13830                         _("TLS relocation against a constant"));
13831           break;
13832         }
13833       S_SET_THREAD_LOCAL (fixP->fx_addsy);
13834       /* fall through */
13835
13836     case BFD_RELOC_MIPS_JMP:
13837     case BFD_RELOC_MIPS_SHIFT5:
13838     case BFD_RELOC_MIPS_SHIFT6:
13839     case BFD_RELOC_MIPS_GOT_DISP:
13840     case BFD_RELOC_MIPS_GOT_PAGE:
13841     case BFD_RELOC_MIPS_GOT_OFST:
13842     case BFD_RELOC_MIPS_SUB:
13843     case BFD_RELOC_MIPS_INSERT_A:
13844     case BFD_RELOC_MIPS_INSERT_B:
13845     case BFD_RELOC_MIPS_DELETE:
13846     case BFD_RELOC_MIPS_HIGHEST:
13847     case BFD_RELOC_MIPS_HIGHER:
13848     case BFD_RELOC_MIPS_SCN_DISP:
13849     case BFD_RELOC_MIPS_REL16:
13850     case BFD_RELOC_MIPS_RELGOT:
13851     case BFD_RELOC_MIPS_JALR:
13852     case BFD_RELOC_HI16:
13853     case BFD_RELOC_HI16_S:
13854     case BFD_RELOC_LO16:
13855     case BFD_RELOC_GPREL16:
13856     case BFD_RELOC_MIPS_LITERAL:
13857     case BFD_RELOC_MIPS_CALL16:
13858     case BFD_RELOC_MIPS_GOT16:
13859     case BFD_RELOC_GPREL32:
13860     case BFD_RELOC_MIPS_GOT_HI16:
13861     case BFD_RELOC_MIPS_GOT_LO16:
13862     case BFD_RELOC_MIPS_CALL_HI16:
13863     case BFD_RELOC_MIPS_CALL_LO16:
13864     case BFD_RELOC_MIPS16_GPREL:
13865     case BFD_RELOC_MIPS16_GOT16:
13866     case BFD_RELOC_MIPS16_CALL16:
13867     case BFD_RELOC_MIPS16_HI16:
13868     case BFD_RELOC_MIPS16_HI16_S:
13869     case BFD_RELOC_MIPS16_LO16:
13870     case BFD_RELOC_MIPS16_JMP:
13871     case BFD_RELOC_MICROMIPS_JMP:
13872     case BFD_RELOC_MICROMIPS_GOT_DISP:
13873     case BFD_RELOC_MICROMIPS_GOT_PAGE:
13874     case BFD_RELOC_MICROMIPS_GOT_OFST:
13875     case BFD_RELOC_MICROMIPS_SUB:
13876     case BFD_RELOC_MICROMIPS_HIGHEST:
13877     case BFD_RELOC_MICROMIPS_HIGHER:
13878     case BFD_RELOC_MICROMIPS_SCN_DISP:
13879     case BFD_RELOC_MICROMIPS_JALR:
13880     case BFD_RELOC_MICROMIPS_HI16:
13881     case BFD_RELOC_MICROMIPS_HI16_S:
13882     case BFD_RELOC_MICROMIPS_LO16:
13883     case BFD_RELOC_MICROMIPS_GPREL16:
13884     case BFD_RELOC_MICROMIPS_LITERAL:
13885     case BFD_RELOC_MICROMIPS_CALL16:
13886     case BFD_RELOC_MICROMIPS_GOT16:
13887     case BFD_RELOC_MICROMIPS_GOT_HI16:
13888     case BFD_RELOC_MICROMIPS_GOT_LO16:
13889     case BFD_RELOC_MICROMIPS_CALL_HI16:
13890     case BFD_RELOC_MICROMIPS_CALL_LO16:
13891     case BFD_RELOC_MIPS_EH:
13892       if (fixP->fx_done)
13893         {
13894           offsetT value;
13895
13896           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
13897             {
13898               insn = read_reloc_insn (buf, fixP->fx_r_type);
13899               if (mips16_reloc_p (fixP->fx_r_type))
13900                 insn |= mips16_immed_extend (value, 16);
13901               else
13902                 insn |= (value & 0xffff);
13903               write_reloc_insn (buf, fixP->fx_r_type, insn);
13904             }
13905           else
13906             as_bad_where (fixP->fx_file, fixP->fx_line,
13907                           _("Unsupported constant in relocation"));
13908         }
13909       break;
13910
13911     case BFD_RELOC_64:
13912       /* This is handled like BFD_RELOC_32, but we output a sign
13913          extended value if we are only 32 bits.  */
13914       if (fixP->fx_done)
13915         {
13916           if (8 <= sizeof (valueT))
13917             md_number_to_chars (buf, *valP, 8);
13918           else
13919             {
13920               valueT hiv;
13921
13922               if ((*valP & 0x80000000) != 0)
13923                 hiv = 0xffffffff;
13924               else
13925                 hiv = 0;
13926               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
13927               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
13928             }
13929         }
13930       break;
13931
13932     case BFD_RELOC_RVA:
13933     case BFD_RELOC_32:
13934     case BFD_RELOC_32_PCREL:
13935     case BFD_RELOC_16:
13936       /* If we are deleting this reloc entry, we must fill in the
13937          value now.  This can happen if we have a .word which is not
13938          resolved when it appears but is later defined.  */
13939       if (fixP->fx_done)
13940         md_number_to_chars (buf, *valP, fixP->fx_size);
13941       break;
13942
13943     case BFD_RELOC_16_PCREL_S2:
13944       if ((*valP & 0x3) != 0)
13945         as_bad_where (fixP->fx_file, fixP->fx_line,
13946                       _("Branch to misaligned address (%lx)"), (long) *valP);
13947
13948       /* We need to save the bits in the instruction since fixup_segment()
13949          might be deleting the relocation entry (i.e., a branch within
13950          the current segment).  */
13951       if (! fixP->fx_done)
13952         break;
13953
13954       /* Update old instruction data.  */
13955       insn = read_insn (buf);
13956
13957       if (*valP + 0x20000 <= 0x3ffff)
13958         {
13959           insn |= (*valP >> 2) & 0xffff;
13960           write_insn (buf, insn);
13961         }
13962       else if (mips_pic == NO_PIC
13963                && fixP->fx_done
13964                && fixP->fx_frag->fr_address >= text_section->vma
13965                && (fixP->fx_frag->fr_address
13966                    < text_section->vma + bfd_get_section_size (text_section))
13967                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
13968                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
13969                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
13970         {
13971           /* The branch offset is too large.  If this is an
13972              unconditional branch, and we are not generating PIC code,
13973              we can convert it to an absolute jump instruction.  */
13974           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
13975             insn = 0x0c000000;  /* jal */
13976           else
13977             insn = 0x08000000;  /* j */
13978           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
13979           fixP->fx_done = 0;
13980           fixP->fx_addsy = section_symbol (text_section);
13981           *valP += md_pcrel_from (fixP);
13982           write_insn (buf, insn);
13983         }
13984       else
13985         {
13986           /* If we got here, we have branch-relaxation disabled,
13987              and there's nothing we can do to fix this instruction
13988              without turning it into a longer sequence.  */
13989           as_bad_where (fixP->fx_file, fixP->fx_line,
13990                         _("Branch out of range"));
13991         }
13992       break;
13993
13994     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
13995     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
13996     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
13997       /* We adjust the offset back to even.  */
13998       if ((*valP & 0x1) != 0)
13999         --(*valP);
14000
14001       if (! fixP->fx_done)
14002         break;
14003
14004       /* Should never visit here, because we keep the relocation.  */
14005       abort ();
14006       break;
14007
14008     case BFD_RELOC_VTABLE_INHERIT:
14009       fixP->fx_done = 0;
14010       if (fixP->fx_addsy
14011           && !S_IS_DEFINED (fixP->fx_addsy)
14012           && !S_IS_WEAK (fixP->fx_addsy))
14013         S_SET_WEAK (fixP->fx_addsy);
14014       break;
14015
14016     case BFD_RELOC_VTABLE_ENTRY:
14017       fixP->fx_done = 0;
14018       break;
14019
14020     default:
14021       abort ();
14022     }
14023
14024   /* Remember value for tc_gen_reloc.  */
14025   fixP->fx_addnumber = *valP;
14026 }
14027
14028 static symbolS *
14029 get_symbol (void)
14030 {
14031   int c;
14032   char *name;
14033   symbolS *p;
14034
14035   name = input_line_pointer;
14036   c = get_symbol_end ();
14037   p = (symbolS *) symbol_find_or_make (name);
14038   *input_line_pointer = c;
14039   return p;
14040 }
14041
14042 /* Align the current frag to a given power of two.  If a particular
14043    fill byte should be used, FILL points to an integer that contains
14044    that byte, otherwise FILL is null.
14045
14046    This function used to have the comment:
14047
14048       The MIPS assembler also automatically adjusts any preceding label.
14049
14050    The implementation therefore applied the adjustment to a maximum of
14051    one label.  However, other label adjustments are applied to batches
14052    of labels, and adjusting just one caused problems when new labels
14053    were added for the sake of debugging or unwind information.
14054    We therefore adjust all preceding labels (given as LABELS) instead.  */
14055
14056 static void
14057 mips_align (int to, int *fill, struct insn_label_list *labels)
14058 {
14059   mips_emit_delays ();
14060   mips_record_compressed_mode ();
14061   if (fill == NULL && subseg_text_p (now_seg))
14062     frag_align_code (to, 0);
14063   else
14064     frag_align (to, fill ? *fill : 0, 0);
14065   record_alignment (now_seg, to);
14066   mips_move_labels (labels, FALSE);
14067 }
14068
14069 /* Align to a given power of two.  .align 0 turns off the automatic
14070    alignment used by the data creating pseudo-ops.  */
14071
14072 static void
14073 s_align (int x ATTRIBUTE_UNUSED)
14074 {
14075   int temp, fill_value, *fill_ptr;
14076   long max_alignment = 28;
14077
14078   /* o Note that the assembler pulls down any immediately preceding label
14079        to the aligned address.
14080      o It's not documented but auto alignment is reinstated by
14081        a .align pseudo instruction.
14082      o Note also that after auto alignment is turned off the mips assembler
14083        issues an error on attempt to assemble an improperly aligned data item.
14084        We don't.  */
14085
14086   temp = get_absolute_expression ();
14087   if (temp > max_alignment)
14088     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
14089   else if (temp < 0)
14090     {
14091       as_warn (_("Alignment negative: 0 assumed."));
14092       temp = 0;
14093     }
14094   if (*input_line_pointer == ',')
14095     {
14096       ++input_line_pointer;
14097       fill_value = get_absolute_expression ();
14098       fill_ptr = &fill_value;
14099     }
14100   else
14101     fill_ptr = 0;
14102   if (temp)
14103     {
14104       segment_info_type *si = seg_info (now_seg);
14105       struct insn_label_list *l = si->label_list;
14106       /* Auto alignment should be switched on by next section change.  */
14107       auto_align = 1;
14108       mips_align (temp, fill_ptr, l);
14109     }
14110   else
14111     {
14112       auto_align = 0;
14113     }
14114
14115   demand_empty_rest_of_line ();
14116 }
14117
14118 static void
14119 s_change_sec (int sec)
14120 {
14121   segT seg;
14122
14123   /* The ELF backend needs to know that we are changing sections, so
14124      that .previous works correctly.  We could do something like check
14125      for an obj_section_change_hook macro, but that might be confusing
14126      as it would not be appropriate to use it in the section changing
14127      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14128      This should be cleaner, somehow.  */
14129   obj_elf_section_change_hook ();
14130
14131   mips_emit_delays ();
14132
14133   switch (sec)
14134     {
14135     case 't':
14136       s_text (0);
14137       break;
14138     case 'd':
14139       s_data (0);
14140       break;
14141     case 'b':
14142       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14143       demand_empty_rest_of_line ();
14144       break;
14145
14146     case 'r':
14147       seg = subseg_new (RDATA_SECTION_NAME,
14148                         (subsegT) get_absolute_expression ());
14149       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14150                                               | SEC_READONLY | SEC_RELOC
14151                                               | SEC_DATA));
14152       if (strncmp (TARGET_OS, "elf", 3) != 0)
14153         record_alignment (seg, 4);
14154       demand_empty_rest_of_line ();
14155       break;
14156
14157     case 's':
14158       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14159       bfd_set_section_flags (stdoutput, seg,
14160                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14161       if (strncmp (TARGET_OS, "elf", 3) != 0)
14162         record_alignment (seg, 4);
14163       demand_empty_rest_of_line ();
14164       break;
14165
14166     case 'B':
14167       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14168       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14169       if (strncmp (TARGET_OS, "elf", 3) != 0)
14170         record_alignment (seg, 4);
14171       demand_empty_rest_of_line ();
14172       break;
14173     }
14174
14175   auto_align = 1;
14176 }
14177
14178 void
14179 s_change_section (int ignore ATTRIBUTE_UNUSED)
14180 {
14181   char *section_name;
14182   char c;
14183   char next_c = 0;
14184   int section_type;
14185   int section_flag;
14186   int section_entry_size;
14187   int section_alignment;
14188
14189   section_name = input_line_pointer;
14190   c = get_symbol_end ();
14191   if (c)
14192     next_c = *(input_line_pointer + 1);
14193
14194   /* Do we have .section Name<,"flags">?  */
14195   if (c != ',' || (c == ',' && next_c == '"'))
14196     {
14197       /* just after name is now '\0'.  */
14198       *input_line_pointer = c;
14199       input_line_pointer = section_name;
14200       obj_elf_section (ignore);
14201       return;
14202     }
14203   input_line_pointer++;
14204
14205   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14206   if (c == ',')
14207     section_type = get_absolute_expression ();
14208   else
14209     section_type = 0;
14210   if (*input_line_pointer++ == ',')
14211     section_flag = get_absolute_expression ();
14212   else
14213     section_flag = 0;
14214   if (*input_line_pointer++ == ',')
14215     section_entry_size = get_absolute_expression ();
14216   else
14217     section_entry_size = 0;
14218   if (*input_line_pointer++ == ',')
14219     section_alignment = get_absolute_expression ();
14220   else
14221     section_alignment = 0;
14222   /* FIXME: really ignore?  */
14223   (void) section_alignment;
14224
14225   section_name = xstrdup (section_name);
14226
14227   /* When using the generic form of .section (as implemented by obj-elf.c),
14228      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14229      traditionally had to fall back on the more common @progbits instead.
14230
14231      There's nothing really harmful in this, since bfd will correct
14232      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14233      means that, for backwards compatibility, the special_section entries
14234      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14235
14236      Even so, we shouldn't force users of the MIPS .section syntax to
14237      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14238      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14239      generic type-checking code.  */
14240   if (section_type == SHT_MIPS_DWARF)
14241     section_type = SHT_PROGBITS;
14242
14243   obj_elf_change_section (section_name, section_type, section_flag,
14244                           section_entry_size, 0, 0, 0);
14245
14246   if (now_seg->name != section_name)
14247     free (section_name);
14248 }
14249
14250 void
14251 mips_enable_auto_align (void)
14252 {
14253   auto_align = 1;
14254 }
14255
14256 static void
14257 s_cons (int log_size)
14258 {
14259   segment_info_type *si = seg_info (now_seg);
14260   struct insn_label_list *l = si->label_list;
14261
14262   mips_emit_delays ();
14263   if (log_size > 0 && auto_align)
14264     mips_align (log_size, 0, l);
14265   cons (1 << log_size);
14266   mips_clear_insn_labels ();
14267 }
14268
14269 static void
14270 s_float_cons (int type)
14271 {
14272   segment_info_type *si = seg_info (now_seg);
14273   struct insn_label_list *l = si->label_list;
14274
14275   mips_emit_delays ();
14276
14277   if (auto_align)
14278     {
14279       if (type == 'd')
14280         mips_align (3, 0, l);
14281       else
14282         mips_align (2, 0, l);
14283     }
14284
14285   float_cons (type);
14286   mips_clear_insn_labels ();
14287 }
14288
14289 /* Handle .globl.  We need to override it because on Irix 5 you are
14290    permitted to say
14291        .globl foo .text
14292    where foo is an undefined symbol, to mean that foo should be
14293    considered to be the address of a function.  */
14294
14295 static void
14296 s_mips_globl (int x ATTRIBUTE_UNUSED)
14297 {
14298   char *name;
14299   int c;
14300   symbolS *symbolP;
14301   flagword flag;
14302
14303   do
14304     {
14305       name = input_line_pointer;
14306       c = get_symbol_end ();
14307       symbolP = symbol_find_or_make (name);
14308       S_SET_EXTERNAL (symbolP);
14309
14310       *input_line_pointer = c;
14311       SKIP_WHITESPACE ();
14312
14313       /* On Irix 5, every global symbol that is not explicitly labelled as
14314          being a function is apparently labelled as being an object.  */
14315       flag = BSF_OBJECT;
14316
14317       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14318           && (*input_line_pointer != ','))
14319         {
14320           char *secname;
14321           asection *sec;
14322
14323           secname = input_line_pointer;
14324           c = get_symbol_end ();
14325           sec = bfd_get_section_by_name (stdoutput, secname);
14326           if (sec == NULL)
14327             as_bad (_("%s: no such section"), secname);
14328           *input_line_pointer = c;
14329
14330           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14331             flag = BSF_FUNCTION;
14332         }
14333
14334       symbol_get_bfdsym (symbolP)->flags |= flag;
14335
14336       c = *input_line_pointer;
14337       if (c == ',')
14338         {
14339           input_line_pointer++;
14340           SKIP_WHITESPACE ();
14341           if (is_end_of_line[(unsigned char) *input_line_pointer])
14342             c = '\n';
14343         }
14344     }
14345   while (c == ',');
14346
14347   demand_empty_rest_of_line ();
14348 }
14349
14350 static void
14351 s_option (int x ATTRIBUTE_UNUSED)
14352 {
14353   char *opt;
14354   char c;
14355
14356   opt = input_line_pointer;
14357   c = get_symbol_end ();
14358
14359   if (*opt == 'O')
14360     {
14361       /* FIXME: What does this mean?  */
14362     }
14363   else if (strncmp (opt, "pic", 3) == 0)
14364     {
14365       int i;
14366
14367       i = atoi (opt + 3);
14368       if (i == 0)
14369         mips_pic = NO_PIC;
14370       else if (i == 2)
14371         {
14372           mips_pic = SVR4_PIC;
14373           mips_abicalls = TRUE;
14374         }
14375       else
14376         as_bad (_(".option pic%d not supported"), i);
14377
14378       if (mips_pic == SVR4_PIC)
14379         {
14380           if (g_switch_seen && g_switch_value != 0)
14381             as_warn (_("-G may not be used with SVR4 PIC code"));
14382           g_switch_value = 0;
14383           bfd_set_gp_size (stdoutput, 0);
14384         }
14385     }
14386   else
14387     as_warn (_("Unrecognized option \"%s\""), opt);
14388
14389   *input_line_pointer = c;
14390   demand_empty_rest_of_line ();
14391 }
14392
14393 /* This structure is used to hold a stack of .set values.  */
14394
14395 struct mips_option_stack
14396 {
14397   struct mips_option_stack *next;
14398   struct mips_set_options options;
14399 };
14400
14401 static struct mips_option_stack *mips_opts_stack;
14402
14403 /* Handle the .set pseudo-op.  */
14404
14405 static void
14406 s_mipsset (int x ATTRIBUTE_UNUSED)
14407 {
14408   char *name = input_line_pointer, ch;
14409   const struct mips_ase *ase;
14410
14411   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14412     ++input_line_pointer;
14413   ch = *input_line_pointer;
14414   *input_line_pointer = '\0';
14415
14416   if (strcmp (name, "reorder") == 0)
14417     {
14418       if (mips_opts.noreorder)
14419         end_noreorder ();
14420     }
14421   else if (strcmp (name, "noreorder") == 0)
14422     {
14423       if (!mips_opts.noreorder)
14424         start_noreorder ();
14425     }
14426   else if (strncmp (name, "at=", 3) == 0)
14427     {
14428       char *s = name + 3;
14429
14430       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14431         as_bad (_("Unrecognized register name `%s'"), s);
14432     }
14433   else if (strcmp (name, "at") == 0)
14434     {
14435       mips_opts.at = ATREG;
14436     }
14437   else if (strcmp (name, "noat") == 0)
14438     {
14439       mips_opts.at = ZERO;
14440     }
14441   else if (strcmp (name, "macro") == 0)
14442     {
14443       mips_opts.warn_about_macros = 0;
14444     }
14445   else if (strcmp (name, "nomacro") == 0)
14446     {
14447       if (mips_opts.noreorder == 0)
14448         as_bad (_("`noreorder' must be set before `nomacro'"));
14449       mips_opts.warn_about_macros = 1;
14450     }
14451   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14452     {
14453       mips_opts.nomove = 0;
14454     }
14455   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14456     {
14457       mips_opts.nomove = 1;
14458     }
14459   else if (strcmp (name, "bopt") == 0)
14460     {
14461       mips_opts.nobopt = 0;
14462     }
14463   else if (strcmp (name, "nobopt") == 0)
14464     {
14465       mips_opts.nobopt = 1;
14466     }
14467   else if (strcmp (name, "gp=default") == 0)
14468     mips_opts.gp32 = file_mips_gp32;
14469   else if (strcmp (name, "gp=32") == 0)
14470     mips_opts.gp32 = 1;
14471   else if (strcmp (name, "gp=64") == 0)
14472     {
14473       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14474         as_warn (_("%s isa does not support 64-bit registers"),
14475                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14476       mips_opts.gp32 = 0;
14477     }
14478   else if (strcmp (name, "fp=default") == 0)
14479     mips_opts.fp32 = file_mips_fp32;
14480   else if (strcmp (name, "fp=32") == 0)
14481     mips_opts.fp32 = 1;
14482   else if (strcmp (name, "fp=64") == 0)
14483     {
14484       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14485         as_warn (_("%s isa does not support 64-bit floating point registers"),
14486                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14487       mips_opts.fp32 = 0;
14488     }
14489   else if (strcmp (name, "softfloat") == 0)
14490     mips_opts.soft_float = 1;
14491   else if (strcmp (name, "hardfloat") == 0)
14492     mips_opts.soft_float = 0;
14493   else if (strcmp (name, "singlefloat") == 0)
14494     mips_opts.single_float = 1;
14495   else if (strcmp (name, "doublefloat") == 0)
14496     mips_opts.single_float = 0;
14497   else if (strcmp (name, "mips16") == 0
14498            || strcmp (name, "MIPS-16") == 0)
14499     {
14500       if (mips_opts.micromips == 1)
14501         as_fatal (_("`mips16' cannot be used with `micromips'"));
14502       mips_opts.mips16 = 1;
14503     }
14504   else if (strcmp (name, "nomips16") == 0
14505            || strcmp (name, "noMIPS-16") == 0)
14506     mips_opts.mips16 = 0;
14507   else if (strcmp (name, "micromips") == 0)
14508     {
14509       if (mips_opts.mips16 == 1)
14510         as_fatal (_("`micromips' cannot be used with `mips16'"));
14511       mips_opts.micromips = 1;
14512     }
14513   else if (strcmp (name, "nomicromips") == 0)
14514     mips_opts.micromips = 0;
14515   else if (name[0] == 'n'
14516            && name[1] == 'o'
14517            && (ase = mips_lookup_ase (name + 2)))
14518     mips_set_ase (ase, FALSE);
14519   else if ((ase = mips_lookup_ase (name)))
14520     mips_set_ase (ase, TRUE);
14521   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
14522     {
14523       int reset = 0;
14524
14525       /* Permit the user to change the ISA and architecture on the fly.
14526          Needless to say, misuse can cause serious problems.  */
14527       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
14528         {
14529           reset = 1;
14530           mips_opts.isa = file_mips_isa;
14531           mips_opts.arch = file_mips_arch;
14532         }
14533       else if (strncmp (name, "arch=", 5) == 0)
14534         {
14535           const struct mips_cpu_info *p;
14536
14537           p = mips_parse_cpu("internal use", name + 5);
14538           if (!p)
14539             as_bad (_("unknown architecture %s"), name + 5);
14540           else
14541             {
14542               mips_opts.arch = p->cpu;
14543               mips_opts.isa = p->isa;
14544             }
14545         }
14546       else if (strncmp (name, "mips", 4) == 0)
14547         {
14548           const struct mips_cpu_info *p;
14549
14550           p = mips_parse_cpu("internal use", name);
14551           if (!p)
14552             as_bad (_("unknown ISA level %s"), name + 4);
14553           else
14554             {
14555               mips_opts.arch = p->cpu;
14556               mips_opts.isa = p->isa;
14557             }
14558         }
14559       else
14560         as_bad (_("unknown ISA or architecture %s"), name);
14561
14562       switch (mips_opts.isa)
14563         {
14564         case  0:
14565           break;
14566         case ISA_MIPS1:
14567         case ISA_MIPS2:
14568         case ISA_MIPS32:
14569         case ISA_MIPS32R2:
14570           mips_opts.gp32 = 1;
14571           mips_opts.fp32 = 1;
14572           break;
14573         case ISA_MIPS3:
14574         case ISA_MIPS4:
14575         case ISA_MIPS5:
14576         case ISA_MIPS64:
14577         case ISA_MIPS64R2:
14578           mips_opts.gp32 = 0;
14579           if (mips_opts.arch == CPU_R5900)
14580             {
14581                 mips_opts.fp32 = 1;
14582             }
14583           else
14584             {
14585           mips_opts.fp32 = 0;
14586             }
14587           break;
14588         default:
14589           as_bad (_("unknown ISA level %s"), name + 4);
14590           break;
14591         }
14592       if (reset)
14593         {
14594           mips_opts.gp32 = file_mips_gp32;
14595           mips_opts.fp32 = file_mips_fp32;
14596         }
14597     }
14598   else if (strcmp (name, "autoextend") == 0)
14599     mips_opts.noautoextend = 0;
14600   else if (strcmp (name, "noautoextend") == 0)
14601     mips_opts.noautoextend = 1;
14602   else if (strcmp (name, "insn32") == 0)
14603     mips_opts.insn32 = TRUE;
14604   else if (strcmp (name, "noinsn32") == 0)
14605     mips_opts.insn32 = FALSE;
14606   else if (strcmp (name, "push") == 0)
14607     {
14608       struct mips_option_stack *s;
14609
14610       s = (struct mips_option_stack *) xmalloc (sizeof *s);
14611       s->next = mips_opts_stack;
14612       s->options = mips_opts;
14613       mips_opts_stack = s;
14614     }
14615   else if (strcmp (name, "pop") == 0)
14616     {
14617       struct mips_option_stack *s;
14618
14619       s = mips_opts_stack;
14620       if (s == NULL)
14621         as_bad (_(".set pop with no .set push"));
14622       else
14623         {
14624           /* If we're changing the reorder mode we need to handle
14625              delay slots correctly.  */
14626           if (s->options.noreorder && ! mips_opts.noreorder)
14627             start_noreorder ();
14628           else if (! s->options.noreorder && mips_opts.noreorder)
14629             end_noreorder ();
14630
14631           mips_opts = s->options;
14632           mips_opts_stack = s->next;
14633           free (s);
14634         }
14635     }
14636   else if (strcmp (name, "sym32") == 0)
14637     mips_opts.sym32 = TRUE;
14638   else if (strcmp (name, "nosym32") == 0)
14639     mips_opts.sym32 = FALSE;
14640   else if (strchr (name, ','))
14641     {
14642       /* Generic ".set" directive; use the generic handler.  */
14643       *input_line_pointer = ch;
14644       input_line_pointer = name;
14645       s_set (0);
14646       return;
14647     }
14648   else
14649     {
14650       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
14651     }
14652   mips_check_isa_supports_ases ();
14653   *input_line_pointer = ch;
14654   demand_empty_rest_of_line ();
14655 }
14656
14657 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
14658    .option pic2.  It means to generate SVR4 PIC calls.  */
14659
14660 static void
14661 s_abicalls (int ignore ATTRIBUTE_UNUSED)
14662 {
14663   mips_pic = SVR4_PIC;
14664   mips_abicalls = TRUE;
14665
14666   if (g_switch_seen && g_switch_value != 0)
14667     as_warn (_("-G may not be used with SVR4 PIC code"));
14668   g_switch_value = 0;
14669
14670   bfd_set_gp_size (stdoutput, 0);
14671   demand_empty_rest_of_line ();
14672 }
14673
14674 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
14675    PIC code.  It sets the $gp register for the function based on the
14676    function address, which is in the register named in the argument.
14677    This uses a relocation against _gp_disp, which is handled specially
14678    by the linker.  The result is:
14679         lui     $gp,%hi(_gp_disp)
14680         addiu   $gp,$gp,%lo(_gp_disp)
14681         addu    $gp,$gp,.cpload argument
14682    The .cpload argument is normally $25 == $t9.
14683
14684    The -mno-shared option changes this to:
14685         lui     $gp,%hi(__gnu_local_gp)
14686         addiu   $gp,$gp,%lo(__gnu_local_gp)
14687    and the argument is ignored.  This saves an instruction, but the
14688    resulting code is not position independent; it uses an absolute
14689    address for __gnu_local_gp.  Thus code assembled with -mno-shared
14690    can go into an ordinary executable, but not into a shared library.  */
14691
14692 static void
14693 s_cpload (int ignore ATTRIBUTE_UNUSED)
14694 {
14695   expressionS ex;
14696   int reg;
14697   int in_shared;
14698
14699   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
14700      .cpload is ignored.  */
14701   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
14702     {
14703       s_ignore (0);
14704       return;
14705     }
14706
14707   if (mips_opts.mips16)
14708     {
14709       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
14710       ignore_rest_of_line ();
14711       return;
14712     }
14713
14714   /* .cpload should be in a .set noreorder section.  */
14715   if (mips_opts.noreorder == 0)
14716     as_warn (_(".cpload not in noreorder section"));
14717
14718   reg = tc_get_register (0);
14719
14720   /* If we need to produce a 64-bit address, we are better off using
14721      the default instruction sequence.  */
14722   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
14723
14724   ex.X_op = O_symbol;
14725   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
14726                                          "__gnu_local_gp");
14727   ex.X_op_symbol = NULL;
14728   ex.X_add_number = 0;
14729
14730   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
14731   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
14732
14733   mips_mark_labels ();
14734   mips_assembling_insn = TRUE;
14735
14736   macro_start ();
14737   macro_build_lui (&ex, mips_gp_register);
14738   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
14739                mips_gp_register, BFD_RELOC_LO16);
14740   if (in_shared)
14741     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
14742                  mips_gp_register, reg);
14743   macro_end ();
14744
14745   mips_assembling_insn = FALSE;
14746   demand_empty_rest_of_line ();
14747 }
14748
14749 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
14750      .cpsetup $reg1, offset|$reg2, label
14751
14752    If offset is given, this results in:
14753      sd         $gp, offset($sp)
14754      lui        $gp, %hi(%neg(%gp_rel(label)))
14755      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
14756      daddu      $gp, $gp, $reg1
14757
14758    If $reg2 is given, this results in:
14759      daddu      $reg2, $gp, $0
14760      lui        $gp, %hi(%neg(%gp_rel(label)))
14761      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
14762      daddu      $gp, $gp, $reg1
14763    $reg1 is normally $25 == $t9.
14764
14765    The -mno-shared option replaces the last three instructions with
14766         lui     $gp,%hi(_gp)
14767         addiu   $gp,$gp,%lo(_gp)  */
14768
14769 static void
14770 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
14771 {
14772   expressionS ex_off;
14773   expressionS ex_sym;
14774   int reg1;
14775
14776   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
14777      We also need NewABI support.  */
14778   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14779     {
14780       s_ignore (0);
14781       return;
14782     }
14783
14784   if (mips_opts.mips16)
14785     {
14786       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
14787       ignore_rest_of_line ();
14788       return;
14789     }
14790
14791   reg1 = tc_get_register (0);
14792   SKIP_WHITESPACE ();
14793   if (*input_line_pointer != ',')
14794     {
14795       as_bad (_("missing argument separator ',' for .cpsetup"));
14796       return;
14797     }
14798   else
14799     ++input_line_pointer;
14800   SKIP_WHITESPACE ();
14801   if (*input_line_pointer == '$')
14802     {
14803       mips_cpreturn_register = tc_get_register (0);
14804       mips_cpreturn_offset = -1;
14805     }
14806   else
14807     {
14808       mips_cpreturn_offset = get_absolute_expression ();
14809       mips_cpreturn_register = -1;
14810     }
14811   SKIP_WHITESPACE ();
14812   if (*input_line_pointer != ',')
14813     {
14814       as_bad (_("missing argument separator ',' for .cpsetup"));
14815       return;
14816     }
14817   else
14818     ++input_line_pointer;
14819   SKIP_WHITESPACE ();
14820   expression (&ex_sym);
14821
14822   mips_mark_labels ();
14823   mips_assembling_insn = TRUE;
14824
14825   macro_start ();
14826   if (mips_cpreturn_register == -1)
14827     {
14828       ex_off.X_op = O_constant;
14829       ex_off.X_add_symbol = NULL;
14830       ex_off.X_op_symbol = NULL;
14831       ex_off.X_add_number = mips_cpreturn_offset;
14832
14833       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
14834                    BFD_RELOC_LO16, SP);
14835     }
14836   else
14837     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
14838                  mips_gp_register, 0);
14839
14840   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
14841     {
14842       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
14843                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
14844                    BFD_RELOC_HI16_S);
14845
14846       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
14847                    mips_gp_register, -1, BFD_RELOC_GPREL16,
14848                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
14849
14850       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
14851                    mips_gp_register, reg1);
14852     }
14853   else
14854     {
14855       expressionS ex;
14856
14857       ex.X_op = O_symbol;
14858       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
14859       ex.X_op_symbol = NULL;
14860       ex.X_add_number = 0;
14861
14862       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
14863       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
14864
14865       macro_build_lui (&ex, mips_gp_register);
14866       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
14867                    mips_gp_register, BFD_RELOC_LO16);
14868     }
14869
14870   macro_end ();
14871
14872   mips_assembling_insn = FALSE;
14873   demand_empty_rest_of_line ();
14874 }
14875
14876 static void
14877 s_cplocal (int ignore ATTRIBUTE_UNUSED)
14878 {
14879   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
14880      .cplocal is ignored.  */
14881   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14882     {
14883       s_ignore (0);
14884       return;
14885     }
14886
14887   if (mips_opts.mips16)
14888     {
14889       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
14890       ignore_rest_of_line ();
14891       return;
14892     }
14893
14894   mips_gp_register = tc_get_register (0);
14895   demand_empty_rest_of_line ();
14896 }
14897
14898 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
14899    offset from $sp.  The offset is remembered, and after making a PIC
14900    call $gp is restored from that location.  */
14901
14902 static void
14903 s_cprestore (int ignore ATTRIBUTE_UNUSED)
14904 {
14905   expressionS ex;
14906
14907   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
14908      .cprestore is ignored.  */
14909   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
14910     {
14911       s_ignore (0);
14912       return;
14913     }
14914
14915   if (mips_opts.mips16)
14916     {
14917       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
14918       ignore_rest_of_line ();
14919       return;
14920     }
14921
14922   mips_cprestore_offset = get_absolute_expression ();
14923   mips_cprestore_valid = 1;
14924
14925   ex.X_op = O_constant;
14926   ex.X_add_symbol = NULL;
14927   ex.X_op_symbol = NULL;
14928   ex.X_add_number = mips_cprestore_offset;
14929
14930   mips_mark_labels ();
14931   mips_assembling_insn = TRUE;
14932
14933   macro_start ();
14934   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
14935                                 SP, HAVE_64BIT_ADDRESSES);
14936   macro_end ();
14937
14938   mips_assembling_insn = FALSE;
14939   demand_empty_rest_of_line ();
14940 }
14941
14942 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
14943    was given in the preceding .cpsetup, it results in:
14944      ld         $gp, offset($sp)
14945
14946    If a register $reg2 was given there, it results in:
14947      daddu      $gp, $reg2, $0  */
14948
14949 static void
14950 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
14951 {
14952   expressionS ex;
14953
14954   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
14955      We also need NewABI support.  */
14956   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14957     {
14958       s_ignore (0);
14959       return;
14960     }
14961
14962   if (mips_opts.mips16)
14963     {
14964       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
14965       ignore_rest_of_line ();
14966       return;
14967     }
14968
14969   mips_mark_labels ();
14970   mips_assembling_insn = TRUE;
14971
14972   macro_start ();
14973   if (mips_cpreturn_register == -1)
14974     {
14975       ex.X_op = O_constant;
14976       ex.X_add_symbol = NULL;
14977       ex.X_op_symbol = NULL;
14978       ex.X_add_number = mips_cpreturn_offset;
14979
14980       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
14981     }
14982   else
14983     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
14984                  mips_cpreturn_register, 0);
14985   macro_end ();
14986
14987   mips_assembling_insn = FALSE;
14988   demand_empty_rest_of_line ();
14989 }
14990
14991 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
14992    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
14993    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
14994    debug information or MIPS16 TLS.  */
14995
14996 static void
14997 s_tls_rel_directive (const size_t bytes, const char *dirstr,
14998                      bfd_reloc_code_real_type rtype)
14999 {
15000   expressionS ex;
15001   char *p;
15002
15003   expression (&ex);
15004
15005   if (ex.X_op != O_symbol)
15006     {
15007       as_bad (_("Unsupported use of %s"), dirstr);
15008       ignore_rest_of_line ();
15009     }
15010
15011   p = frag_more (bytes);
15012   md_number_to_chars (p, 0, bytes);
15013   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15014   demand_empty_rest_of_line ();
15015   mips_clear_insn_labels ();
15016 }
15017
15018 /* Handle .dtprelword.  */
15019
15020 static void
15021 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15022 {
15023   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15024 }
15025
15026 /* Handle .dtpreldword.  */
15027
15028 static void
15029 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15030 {
15031   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15032 }
15033
15034 /* Handle .tprelword.  */
15035
15036 static void
15037 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15038 {
15039   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15040 }
15041
15042 /* Handle .tpreldword.  */
15043
15044 static void
15045 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15046 {
15047   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15048 }
15049
15050 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15051    code.  It sets the offset to use in gp_rel relocations.  */
15052
15053 static void
15054 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15055 {
15056   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15057      We also need NewABI support.  */
15058   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15059     {
15060       s_ignore (0);
15061       return;
15062     }
15063
15064   mips_gprel_offset = get_absolute_expression ();
15065
15066   demand_empty_rest_of_line ();
15067 }
15068
15069 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15070    code.  It generates a 32 bit GP relative reloc.  */
15071
15072 static void
15073 s_gpword (int ignore ATTRIBUTE_UNUSED)
15074 {
15075   segment_info_type *si;
15076   struct insn_label_list *l;
15077   expressionS ex;
15078   char *p;
15079
15080   /* When not generating PIC code, this is treated as .word.  */
15081   if (mips_pic != SVR4_PIC)
15082     {
15083       s_cons (2);
15084       return;
15085     }
15086
15087   si = seg_info (now_seg);
15088   l = si->label_list;
15089   mips_emit_delays ();
15090   if (auto_align)
15091     mips_align (2, 0, l);
15092
15093   expression (&ex);
15094   mips_clear_insn_labels ();
15095
15096   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15097     {
15098       as_bad (_("Unsupported use of .gpword"));
15099       ignore_rest_of_line ();
15100     }
15101
15102   p = frag_more (4);
15103   md_number_to_chars (p, 0, 4);
15104   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15105                BFD_RELOC_GPREL32);
15106
15107   demand_empty_rest_of_line ();
15108 }
15109
15110 static void
15111 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15112 {
15113   segment_info_type *si;
15114   struct insn_label_list *l;
15115   expressionS ex;
15116   char *p;
15117
15118   /* When not generating PIC code, this is treated as .dword.  */
15119   if (mips_pic != SVR4_PIC)
15120     {
15121       s_cons (3);
15122       return;
15123     }
15124
15125   si = seg_info (now_seg);
15126   l = si->label_list;
15127   mips_emit_delays ();
15128   if (auto_align)
15129     mips_align (3, 0, l);
15130
15131   expression (&ex);
15132   mips_clear_insn_labels ();
15133
15134   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15135     {
15136       as_bad (_("Unsupported use of .gpdword"));
15137       ignore_rest_of_line ();
15138     }
15139
15140   p = frag_more (8);
15141   md_number_to_chars (p, 0, 8);
15142   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15143                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15144
15145   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15146   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15147            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15148
15149   demand_empty_rest_of_line ();
15150 }
15151
15152 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15153    tables.  It generates a R_MIPS_EH reloc.  */
15154
15155 static void
15156 s_ehword (int ignore ATTRIBUTE_UNUSED)
15157 {
15158   expressionS ex;
15159   char *p;
15160
15161   mips_emit_delays ();
15162
15163   expression (&ex);
15164   mips_clear_insn_labels ();
15165
15166   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15167     {
15168       as_bad (_("Unsupported use of .ehword"));
15169       ignore_rest_of_line ();
15170     }
15171
15172   p = frag_more (4);
15173   md_number_to_chars (p, 0, 4);
15174   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15175                BFD_RELOC_MIPS_EH);
15176
15177   demand_empty_rest_of_line ();
15178 }
15179
15180 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15181    tables in SVR4 PIC code.  */
15182
15183 static void
15184 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15185 {
15186   int reg;
15187
15188   /* This is ignored when not generating SVR4 PIC code.  */
15189   if (mips_pic != SVR4_PIC)
15190     {
15191       s_ignore (0);
15192       return;
15193     }
15194
15195   mips_mark_labels ();
15196   mips_assembling_insn = TRUE;
15197
15198   /* Add $gp to the register named as an argument.  */
15199   macro_start ();
15200   reg = tc_get_register (0);
15201   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15202   macro_end ();
15203
15204   mips_assembling_insn = FALSE;
15205   demand_empty_rest_of_line ();
15206 }
15207
15208 /* Handle the .insn pseudo-op.  This marks instruction labels in
15209    mips16/micromips mode.  This permits the linker to handle them specially,
15210    such as generating jalx instructions when needed.  We also make
15211    them odd for the duration of the assembly, in order to generate the
15212    right sort of code.  We will make them even in the adjust_symtab
15213    routine, while leaving them marked.  This is convenient for the
15214    debugger and the disassembler.  The linker knows to make them odd
15215    again.  */
15216
15217 static void
15218 s_insn (int ignore ATTRIBUTE_UNUSED)
15219 {
15220   mips_mark_labels ();
15221
15222   demand_empty_rest_of_line ();
15223 }
15224
15225 /* Handle the .nan pseudo-op.  */
15226
15227 static void
15228 s_nan (int ignore ATTRIBUTE_UNUSED)
15229 {
15230   static const char str_legacy[] = "legacy";
15231   static const char str_2008[] = "2008";
15232   size_t i;
15233
15234   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15235
15236   if (i == sizeof (str_2008) - 1
15237       && memcmp (input_line_pointer, str_2008, i) == 0)
15238     mips_flag_nan2008 = TRUE;
15239   else if (i == sizeof (str_legacy) - 1
15240            && memcmp (input_line_pointer, str_legacy, i) == 0)
15241     mips_flag_nan2008 = FALSE;
15242   else
15243     as_bad (_("Bad .nan directive"));
15244
15245   input_line_pointer += i;
15246   demand_empty_rest_of_line ();
15247 }
15248
15249 /* Handle a .stab[snd] directive.  Ideally these directives would be
15250    implemented in a transparent way, so that removing them would not
15251    have any effect on the generated instructions.  However, s_stab
15252    internally changes the section, so in practice we need to decide
15253    now whether the preceding label marks compressed code.  We do not
15254    support changing the compression mode of a label after a .stab*
15255    directive, such as in:
15256
15257    foo:
15258         .stabs ...
15259         .set mips16
15260
15261    so the current mode wins.  */
15262
15263 static void
15264 s_mips_stab (int type)
15265 {
15266   mips_mark_labels ();
15267   s_stab (type);
15268 }
15269
15270 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15271
15272 static void
15273 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15274 {
15275   char *name;
15276   int c;
15277   symbolS *symbolP;
15278   expressionS exp;
15279
15280   name = input_line_pointer;
15281   c = get_symbol_end ();
15282   symbolP = symbol_find_or_make (name);
15283   S_SET_WEAK (symbolP);
15284   *input_line_pointer = c;
15285
15286   SKIP_WHITESPACE ();
15287
15288   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15289     {
15290       if (S_IS_DEFINED (symbolP))
15291         {
15292           as_bad (_("ignoring attempt to redefine symbol %s"),
15293                   S_GET_NAME (symbolP));
15294           ignore_rest_of_line ();
15295           return;
15296         }
15297
15298       if (*input_line_pointer == ',')
15299         {
15300           ++input_line_pointer;
15301           SKIP_WHITESPACE ();
15302         }
15303
15304       expression (&exp);
15305       if (exp.X_op != O_symbol)
15306         {
15307           as_bad (_("bad .weakext directive"));
15308           ignore_rest_of_line ();
15309           return;
15310         }
15311       symbol_set_value_expression (symbolP, &exp);
15312     }
15313
15314   demand_empty_rest_of_line ();
15315 }
15316
15317 /* Parse a register string into a number.  Called from the ECOFF code
15318    to parse .frame.  The argument is non-zero if this is the frame
15319    register, so that we can record it in mips_frame_reg.  */
15320
15321 int
15322 tc_get_register (int frame)
15323 {
15324   unsigned int reg;
15325
15326   SKIP_WHITESPACE ();
15327   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15328     reg = 0;
15329   if (frame)
15330     {
15331       mips_frame_reg = reg != 0 ? reg : SP;
15332       mips_frame_reg_valid = 1;
15333       mips_cprestore_valid = 0;
15334     }
15335   return reg;
15336 }
15337
15338 valueT
15339 md_section_align (asection *seg, valueT addr)
15340 {
15341   int align = bfd_get_section_alignment (stdoutput, seg);
15342
15343   /* We don't need to align ELF sections to the full alignment.
15344      However, Irix 5 may prefer that we align them at least to a 16
15345      byte boundary.  We don't bother to align the sections if we
15346      are targeted for an embedded system.  */
15347   if (strncmp (TARGET_OS, "elf", 3) == 0)
15348     return addr;
15349   if (align > 4)
15350     align = 4;
15351
15352   return ((addr + (1 << align) - 1) & (-1 << align));
15353 }
15354
15355 /* Utility routine, called from above as well.  If called while the
15356    input file is still being read, it's only an approximation.  (For
15357    example, a symbol may later become defined which appeared to be
15358    undefined earlier.)  */
15359
15360 static int
15361 nopic_need_relax (symbolS *sym, int before_relaxing)
15362 {
15363   if (sym == 0)
15364     return 0;
15365
15366   if (g_switch_value > 0)
15367     {
15368       const char *symname;
15369       int change;
15370
15371       /* Find out whether this symbol can be referenced off the $gp
15372          register.  It can be if it is smaller than the -G size or if
15373          it is in the .sdata or .sbss section.  Certain symbols can
15374          not be referenced off the $gp, although it appears as though
15375          they can.  */
15376       symname = S_GET_NAME (sym);
15377       if (symname != (const char *) NULL
15378           && (strcmp (symname, "eprol") == 0
15379               || strcmp (symname, "etext") == 0
15380               || strcmp (symname, "_gp") == 0
15381               || strcmp (symname, "edata") == 0
15382               || strcmp (symname, "_fbss") == 0
15383               || strcmp (symname, "_fdata") == 0
15384               || strcmp (symname, "_ftext") == 0
15385               || strcmp (symname, "end") == 0
15386               || strcmp (symname, "_gp_disp") == 0))
15387         change = 1;
15388       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15389                && (0
15390 #ifndef NO_ECOFF_DEBUGGING
15391                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15392                        && (symbol_get_obj (sym)->ecoff_extern_size
15393                            <= g_switch_value))
15394 #endif
15395                    /* We must defer this decision until after the whole
15396                       file has been read, since there might be a .extern
15397                       after the first use of this symbol.  */
15398                    || (before_relaxing
15399 #ifndef NO_ECOFF_DEBUGGING
15400                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15401 #endif
15402                        && S_GET_VALUE (sym) == 0)
15403                    || (S_GET_VALUE (sym) != 0
15404                        && S_GET_VALUE (sym) <= g_switch_value)))
15405         change = 0;
15406       else
15407         {
15408           const char *segname;
15409
15410           segname = segment_name (S_GET_SEGMENT (sym));
15411           gas_assert (strcmp (segname, ".lit8") != 0
15412                   && strcmp (segname, ".lit4") != 0);
15413           change = (strcmp (segname, ".sdata") != 0
15414                     && strcmp (segname, ".sbss") != 0
15415                     && strncmp (segname, ".sdata.", 7) != 0
15416                     && strncmp (segname, ".sbss.", 6) != 0
15417                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15418                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15419         }
15420       return change;
15421     }
15422   else
15423     /* We are not optimizing for the $gp register.  */
15424     return 1;
15425 }
15426
15427
15428 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15429
15430 static bfd_boolean
15431 pic_need_relax (symbolS *sym, asection *segtype)
15432 {
15433   asection *symsec;
15434
15435   /* Handle the case of a symbol equated to another symbol.  */
15436   while (symbol_equated_reloc_p (sym))
15437     {
15438       symbolS *n;
15439
15440       /* It's possible to get a loop here in a badly written program.  */
15441       n = symbol_get_value_expression (sym)->X_add_symbol;
15442       if (n == sym)
15443         break;
15444       sym = n;
15445     }
15446
15447   if (symbol_section_p (sym))
15448     return TRUE;
15449
15450   symsec = S_GET_SEGMENT (sym);
15451
15452   /* This must duplicate the test in adjust_reloc_syms.  */
15453   return (!bfd_is_und_section (symsec)
15454           && !bfd_is_abs_section (symsec)
15455           && !bfd_is_com_section (symsec)
15456           && !s_is_linkonce (sym, segtype)
15457           /* A global or weak symbol is treated as external.  */
15458           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15459 }
15460
15461
15462 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15463    extended opcode.  SEC is the section the frag is in.  */
15464
15465 static int
15466 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15467 {
15468   int type;
15469   const struct mips16_immed_operand *op;
15470   offsetT val;
15471   int mintiny, maxtiny;
15472   segT symsec;
15473   fragS *sym_frag;
15474
15475   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15476     return 0;
15477   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15478     return 1;
15479
15480   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
15481   op = mips16_immed_operands;
15482   while (op->type != type)
15483     {
15484       ++op;
15485       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
15486     }
15487
15488   if (op->unsp)
15489     {
15490       if (type == '<' || type == '>' || type == '[' || type == ']')
15491         {
15492           mintiny = 1;
15493           maxtiny = 1 << op->nbits;
15494         }
15495       else
15496         {
15497           mintiny = 0;
15498           maxtiny = (1 << op->nbits) - 1;
15499         }
15500     }
15501   else
15502     {
15503       mintiny = - (1 << (op->nbits - 1));
15504       maxtiny = (1 << (op->nbits - 1)) - 1;
15505     }
15506
15507   sym_frag = symbol_get_frag (fragp->fr_symbol);
15508   val = S_GET_VALUE (fragp->fr_symbol);
15509   symsec = S_GET_SEGMENT (fragp->fr_symbol);
15510
15511   if (op->pcrel)
15512     {
15513       addressT addr;
15514
15515       /* We won't have the section when we are called from
15516          mips_relax_frag.  However, we will always have been called
15517          from md_estimate_size_before_relax first.  If this is a
15518          branch to a different section, we mark it as such.  If SEC is
15519          NULL, and the frag is not marked, then it must be a branch to
15520          the same section.  */
15521       if (sec == NULL)
15522         {
15523           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
15524             return 1;
15525         }
15526       else
15527         {
15528           /* Must have been called from md_estimate_size_before_relax.  */
15529           if (symsec != sec)
15530             {
15531               fragp->fr_subtype =
15532                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15533
15534               /* FIXME: We should support this, and let the linker
15535                  catch branches and loads that are out of range.  */
15536               as_bad_where (fragp->fr_file, fragp->fr_line,
15537                             _("unsupported PC relative reference to different section"));
15538
15539               return 1;
15540             }
15541           if (fragp != sym_frag && sym_frag->fr_address == 0)
15542             /* Assume non-extended on the first relaxation pass.
15543                The address we have calculated will be bogus if this is
15544                a forward branch to another frag, as the forward frag
15545                will have fr_address == 0.  */
15546             return 0;
15547         }
15548
15549       /* In this case, we know for sure that the symbol fragment is in
15550          the same section.  If the relax_marker of the symbol fragment
15551          differs from the relax_marker of this fragment, we have not
15552          yet adjusted the symbol fragment fr_address.  We want to add
15553          in STRETCH in order to get a better estimate of the address.
15554          This particularly matters because of the shift bits.  */
15555       if (stretch != 0
15556           && sym_frag->relax_marker != fragp->relax_marker)
15557         {
15558           fragS *f;
15559
15560           /* Adjust stretch for any alignment frag.  Note that if have
15561              been expanding the earlier code, the symbol may be
15562              defined in what appears to be an earlier frag.  FIXME:
15563              This doesn't handle the fr_subtype field, which specifies
15564              a maximum number of bytes to skip when doing an
15565              alignment.  */
15566           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
15567             {
15568               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
15569                 {
15570                   if (stretch < 0)
15571                     stretch = - ((- stretch)
15572                                  & ~ ((1 << (int) f->fr_offset) - 1));
15573                   else
15574                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
15575                   if (stretch == 0)
15576                     break;
15577                 }
15578             }
15579           if (f != NULL)
15580             val += stretch;
15581         }
15582
15583       addr = fragp->fr_address + fragp->fr_fix;
15584
15585       /* The base address rules are complicated.  The base address of
15586          a branch is the following instruction.  The base address of a
15587          PC relative load or add is the instruction itself, but if it
15588          is in a delay slot (in which case it can not be extended) use
15589          the address of the instruction whose delay slot it is in.  */
15590       if (type == 'p' || type == 'q')
15591         {
15592           addr += 2;
15593
15594           /* If we are currently assuming that this frag should be
15595              extended, then, the current address is two bytes
15596              higher.  */
15597           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
15598             addr += 2;
15599
15600           /* Ignore the low bit in the target, since it will be set
15601              for a text label.  */
15602           if ((val & 1) != 0)
15603             --val;
15604         }
15605       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
15606         addr -= 4;
15607       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
15608         addr -= 2;
15609
15610       val -= addr & ~ ((1 << op->shift) - 1);
15611
15612       /* Branch offsets have an implicit 0 in the lowest bit.  */
15613       if (type == 'p' || type == 'q')
15614         val /= 2;
15615
15616       /* If any of the shifted bits are set, we must use an extended
15617          opcode.  If the address depends on the size of this
15618          instruction, this can lead to a loop, so we arrange to always
15619          use an extended opcode.  We only check this when we are in
15620          the main relaxation loop, when SEC is NULL.  */
15621       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
15622         {
15623           fragp->fr_subtype =
15624             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15625           return 1;
15626         }
15627
15628       /* If we are about to mark a frag as extended because the value
15629          is precisely maxtiny + 1, then there is a chance of an
15630          infinite loop as in the following code:
15631              la $4,foo
15632              .skip      1020
15633              .align     2
15634            foo:
15635          In this case when the la is extended, foo is 0x3fc bytes
15636          away, so the la can be shrunk, but then foo is 0x400 away, so
15637          the la must be extended.  To avoid this loop, we mark the
15638          frag as extended if it was small, and is about to become
15639          extended with a value of maxtiny + 1.  */
15640       if (val == ((maxtiny + 1) << op->shift)
15641           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
15642           && sec == NULL)
15643         {
15644           fragp->fr_subtype =
15645             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15646           return 1;
15647         }
15648     }
15649   else if (symsec != absolute_section && sec != NULL)
15650     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
15651
15652   if ((val & ((1 << op->shift) - 1)) != 0
15653       || val < (mintiny << op->shift)
15654       || val > (maxtiny << op->shift))
15655     return 1;
15656   else
15657     return 0;
15658 }
15659
15660 /* Compute the length of a branch sequence, and adjust the
15661    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
15662    worst-case length is computed, with UPDATE being used to indicate
15663    whether an unconditional (-1), branch-likely (+1) or regular (0)
15664    branch is to be computed.  */
15665 static int
15666 relaxed_branch_length (fragS *fragp, asection *sec, int update)
15667 {
15668   bfd_boolean toofar;
15669   int length;
15670
15671   if (fragp
15672       && S_IS_DEFINED (fragp->fr_symbol)
15673       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15674     {
15675       addressT addr;
15676       offsetT val;
15677
15678       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15679
15680       addr = fragp->fr_address + fragp->fr_fix + 4;
15681
15682       val -= addr;
15683
15684       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
15685     }
15686   else if (fragp)
15687     /* If the symbol is not defined or it's in a different segment,
15688        assume the user knows what's going on and emit a short
15689        branch.  */
15690     toofar = FALSE;
15691   else
15692     toofar = TRUE;
15693
15694   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
15695     fragp->fr_subtype
15696       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
15697                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
15698                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
15699                              RELAX_BRANCH_LINK (fragp->fr_subtype),
15700                              toofar);
15701
15702   length = 4;
15703   if (toofar)
15704     {
15705       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
15706         length += 8;
15707
15708       if (mips_pic != NO_PIC)
15709         {
15710           /* Additional space for PIC loading of target address.  */
15711           length += 8;
15712           if (mips_opts.isa == ISA_MIPS1)
15713             /* Additional space for $at-stabilizing nop.  */
15714             length += 4;
15715         }
15716
15717       /* If branch is conditional.  */
15718       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
15719         length += 8;
15720     }
15721
15722   return length;
15723 }
15724
15725 /* Compute the length of a branch sequence, and adjust the
15726    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
15727    worst-case length is computed, with UPDATE being used to indicate
15728    whether an unconditional (-1), or regular (0) branch is to be
15729    computed.  */
15730
15731 static int
15732 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
15733 {
15734   bfd_boolean toofar;
15735   int length;
15736
15737   if (fragp
15738       && S_IS_DEFINED (fragp->fr_symbol)
15739       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15740     {
15741       addressT addr;
15742       offsetT val;
15743
15744       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15745       /* Ignore the low bit in the target, since it will be set
15746          for a text label.  */
15747       if ((val & 1) != 0)
15748         --val;
15749
15750       addr = fragp->fr_address + fragp->fr_fix + 4;
15751
15752       val -= addr;
15753
15754       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
15755     }
15756   else if (fragp)
15757     /* If the symbol is not defined or it's in a different segment,
15758        assume the user knows what's going on and emit a short
15759        branch.  */
15760     toofar = FALSE;
15761   else
15762     toofar = TRUE;
15763
15764   if (fragp && update
15765       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
15766     fragp->fr_subtype = (toofar
15767                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
15768                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
15769
15770   length = 4;
15771   if (toofar)
15772     {
15773       bfd_boolean compact_known = fragp != NULL;
15774       bfd_boolean compact = FALSE;
15775       bfd_boolean uncond;
15776
15777       if (compact_known)
15778         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
15779       if (fragp)
15780         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
15781       else
15782         uncond = update < 0;
15783
15784       /* If label is out of range, we turn branch <br>:
15785
15786                 <br>    label                   # 4 bytes
15787             0:
15788
15789          into:
15790
15791                 j       label                   # 4 bytes
15792                 nop                             # 2 bytes if compact && !PIC
15793             0:
15794        */
15795       if (mips_pic == NO_PIC && (!compact_known || compact))
15796         length += 2;
15797
15798       /* If assembling PIC code, we further turn:
15799
15800                         j       label                   # 4 bytes
15801
15802          into:
15803
15804                         lw/ld   at, %got(label)(gp)     # 4 bytes
15805                         d/addiu at, %lo(label)          # 4 bytes
15806                         jr/c    at                      # 2 bytes
15807        */
15808       if (mips_pic != NO_PIC)
15809         length += 6;
15810
15811       /* If branch <br> is conditional, we prepend negated branch <brneg>:
15812
15813                         <brneg> 0f                      # 4 bytes
15814                         nop                             # 2 bytes if !compact
15815        */
15816       if (!uncond)
15817         length += (compact_known && compact) ? 4 : 6;
15818     }
15819
15820   return length;
15821 }
15822
15823 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
15824    bit accordingly.  */
15825
15826 static int
15827 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
15828 {
15829   bfd_boolean toofar;
15830
15831   if (fragp
15832       && S_IS_DEFINED (fragp->fr_symbol)
15833       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15834     {
15835       addressT addr;
15836       offsetT val;
15837       int type;
15838
15839       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15840       /* Ignore the low bit in the target, since it will be set
15841          for a text label.  */
15842       if ((val & 1) != 0)
15843         --val;
15844
15845       /* Assume this is a 2-byte branch.  */
15846       addr = fragp->fr_address + fragp->fr_fix + 2;
15847
15848       /* We try to avoid the infinite loop by not adding 2 more bytes for
15849          long branches.  */
15850
15851       val -= addr;
15852
15853       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
15854       if (type == 'D')
15855         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
15856       else if (type == 'E')
15857         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
15858       else
15859         abort ();
15860     }
15861   else
15862     /* If the symbol is not defined or it's in a different segment,
15863        we emit a normal 32-bit branch.  */
15864     toofar = TRUE;
15865
15866   if (fragp && update
15867       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
15868     fragp->fr_subtype
15869       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
15870                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
15871
15872   if (toofar)
15873     return 4;
15874
15875   return 2;
15876 }
15877
15878 /* Estimate the size of a frag before relaxing.  Unless this is the
15879    mips16, we are not really relaxing here, and the final size is
15880    encoded in the subtype information.  For the mips16, we have to
15881    decide whether we are using an extended opcode or not.  */
15882
15883 int
15884 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
15885 {
15886   int change;
15887
15888   if (RELAX_BRANCH_P (fragp->fr_subtype))
15889     {
15890
15891       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
15892
15893       return fragp->fr_var;
15894     }
15895
15896   if (RELAX_MIPS16_P (fragp->fr_subtype))
15897     /* We don't want to modify the EXTENDED bit here; it might get us
15898        into infinite loops.  We change it only in mips_relax_frag().  */
15899     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
15900
15901   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
15902     {
15903       int length = 4;
15904
15905       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
15906         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
15907       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
15908         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
15909       fragp->fr_var = length;
15910
15911       return length;
15912     }
15913
15914   if (mips_pic == NO_PIC)
15915     change = nopic_need_relax (fragp->fr_symbol, 0);
15916   else if (mips_pic == SVR4_PIC)
15917     change = pic_need_relax (fragp->fr_symbol, segtype);
15918   else if (mips_pic == VXWORKS_PIC)
15919     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
15920     change = 0;
15921   else
15922     abort ();
15923
15924   if (change)
15925     {
15926       fragp->fr_subtype |= RELAX_USE_SECOND;
15927       return -RELAX_FIRST (fragp->fr_subtype);
15928     }
15929   else
15930     return -RELAX_SECOND (fragp->fr_subtype);
15931 }
15932
15933 /* This is called to see whether a reloc against a defined symbol
15934    should be converted into a reloc against a section.  */
15935
15936 int
15937 mips_fix_adjustable (fixS *fixp)
15938 {
15939   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15940       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
15941     return 0;
15942
15943   if (fixp->fx_addsy == NULL)
15944     return 1;
15945
15946   /* If symbol SYM is in a mergeable section, relocations of the form
15947      SYM + 0 can usually be made section-relative.  The mergeable data
15948      is then identified by the section offset rather than by the symbol.
15949
15950      However, if we're generating REL LO16 relocations, the offset is split
15951      between the LO16 and parterning high part relocation.  The linker will
15952      need to recalculate the complete offset in order to correctly identify
15953      the merge data.
15954
15955      The linker has traditionally not looked for the parterning high part
15956      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
15957      placed anywhere.  Rather than break backwards compatibility by changing
15958      this, it seems better not to force the issue, and instead keep the
15959      original symbol.  This will work with either linker behavior.  */
15960   if ((lo16_reloc_p (fixp->fx_r_type)
15961        || reloc_needs_lo_p (fixp->fx_r_type))
15962       && HAVE_IN_PLACE_ADDENDS
15963       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
15964     return 0;
15965
15966   /* There is no place to store an in-place offset for JALR relocations.
15967      Likewise an in-range offset of limited PC-relative relocations may
15968      overflow the in-place relocatable field if recalculated against the
15969      start address of the symbol's containing section.  */
15970   if (HAVE_IN_PLACE_ADDENDS
15971       && (limited_pcrel_reloc_p (fixp->fx_r_type)
15972           || jalr_reloc_p (fixp->fx_r_type)))
15973     return 0;
15974
15975   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
15976      to a floating-point stub.  The same is true for non-R_MIPS16_26
15977      relocations against MIPS16 functions; in this case, the stub becomes
15978      the function's canonical address.
15979
15980      Floating-point stubs are stored in unique .mips16.call.* or
15981      .mips16.fn.* sections.  If a stub T for function F is in section S,
15982      the first relocation in section S must be against F; this is how the
15983      linker determines the target function.  All relocations that might
15984      resolve to T must also be against F.  We therefore have the following
15985      restrictions, which are given in an intentionally-redundant way:
15986
15987        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
15988           symbols.
15989
15990        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
15991           if that stub might be used.
15992
15993        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
15994           symbols.
15995
15996        4. We cannot reduce a stub's relocations against MIPS16 symbols if
15997           that stub might be used.
15998
15999      There is a further restriction:
16000
16001        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16002           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16003           targets with in-place addends; the relocation field cannot
16004           encode the low bit.
16005
16006      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16007      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16008      such relocations on REL targets.
16009
16010      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16011      relocation against some symbol R, no relocation against R may be
16012      reduced.  (Note that this deals with (2) as well as (1) because
16013      relocations against global symbols will never be reduced on ELF
16014      targets.)  This approach is a little simpler than trying to detect
16015      stub sections, and gives the "all or nothing" per-symbol consistency
16016      that we have for MIPS16 symbols.  */
16017   if (fixp->fx_subsy == NULL
16018       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16019           || *symbol_get_tc (fixp->fx_addsy)
16020           || (HAVE_IN_PLACE_ADDENDS
16021               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16022               && jmp_reloc_p (fixp->fx_r_type))))
16023     return 0;
16024
16025   return 1;
16026 }
16027
16028 /* Translate internal representation of relocation info to BFD target
16029    format.  */
16030
16031 arelent **
16032 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16033 {
16034   static arelent *retval[4];
16035   arelent *reloc;
16036   bfd_reloc_code_real_type code;
16037
16038   memset (retval, 0, sizeof(retval));
16039   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16040   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16041   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16042   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16043
16044   if (fixp->fx_pcrel)
16045     {
16046       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16047                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16048                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16049                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16050                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16051
16052       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16053          Relocations want only the symbol offset.  */
16054       reloc->addend = fixp->fx_addnumber + reloc->address;
16055     }
16056   else
16057     reloc->addend = fixp->fx_addnumber;
16058
16059   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16060      entry to be used in the relocation's section offset.  */
16061   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16062     {
16063       reloc->address = reloc->addend;
16064       reloc->addend = 0;
16065     }
16066
16067   code = fixp->fx_r_type;
16068
16069   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16070   if (reloc->howto == NULL)
16071     {
16072       as_bad_where (fixp->fx_file, fixp->fx_line,
16073                     _("Can not represent %s relocation in this object file format"),
16074                     bfd_get_reloc_code_name (code));
16075       retval[0] = NULL;
16076     }
16077
16078   return retval;
16079 }
16080
16081 /* Relax a machine dependent frag.  This returns the amount by which
16082    the current size of the frag should change.  */
16083
16084 int
16085 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16086 {
16087   if (RELAX_BRANCH_P (fragp->fr_subtype))
16088     {
16089       offsetT old_var = fragp->fr_var;
16090
16091       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16092
16093       return fragp->fr_var - old_var;
16094     }
16095
16096   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16097     {
16098       offsetT old_var = fragp->fr_var;
16099       offsetT new_var = 4;
16100
16101       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16102         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16103       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16104         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16105       fragp->fr_var = new_var;
16106
16107       return new_var - old_var;
16108     }
16109
16110   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16111     return 0;
16112
16113   if (mips16_extended_frag (fragp, NULL, stretch))
16114     {
16115       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16116         return 0;
16117       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16118       return 2;
16119     }
16120   else
16121     {
16122       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16123         return 0;
16124       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16125       return -2;
16126     }
16127
16128   return 0;
16129 }
16130
16131 /* Convert a machine dependent frag.  */
16132
16133 void
16134 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16135 {
16136   if (RELAX_BRANCH_P (fragp->fr_subtype))
16137     {
16138       char *buf;
16139       unsigned long insn;
16140       expressionS exp;
16141       fixS *fixp;
16142
16143       buf = fragp->fr_literal + fragp->fr_fix;
16144       insn = read_insn (buf);
16145
16146       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16147         {
16148           /* We generate a fixup instead of applying it right now
16149              because, if there are linker relaxations, we're going to
16150              need the relocations.  */
16151           exp.X_op = O_symbol;
16152           exp.X_add_symbol = fragp->fr_symbol;
16153           exp.X_add_number = fragp->fr_offset;
16154
16155           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16156                               BFD_RELOC_16_PCREL_S2);
16157           fixp->fx_file = fragp->fr_file;
16158           fixp->fx_line = fragp->fr_line;
16159
16160           buf = write_insn (buf, insn);
16161         }
16162       else
16163         {
16164           int i;
16165
16166           as_warn_where (fragp->fr_file, fragp->fr_line,
16167                          _("Relaxed out-of-range branch into a jump"));
16168
16169           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16170             goto uncond;
16171
16172           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16173             {
16174               /* Reverse the branch.  */
16175               switch ((insn >> 28) & 0xf)
16176                 {
16177                 case 4:
16178                   /* bc[0-3][tf]l? instructions can have the condition
16179                      reversed by tweaking a single TF bit, and their
16180                      opcodes all have 0x4???????.  */
16181                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
16182                   insn ^= 0x00010000;
16183                   break;
16184
16185                 case 0:
16186                   /* bltz       0x04000000      bgez    0x04010000
16187                      bltzal     0x04100000      bgezal  0x04110000  */
16188                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16189                   insn ^= 0x00010000;
16190                   break;
16191
16192                 case 1:
16193                   /* beq        0x10000000      bne     0x14000000
16194                      blez       0x18000000      bgtz    0x1c000000  */
16195                   insn ^= 0x04000000;
16196                   break;
16197
16198                 default:
16199                   abort ();
16200                 }
16201             }
16202
16203           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16204             {
16205               /* Clear the and-link bit.  */
16206               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16207
16208               /* bltzal         0x04100000      bgezal  0x04110000
16209                  bltzall        0x04120000      bgezall 0x04130000  */
16210               insn &= ~0x00100000;
16211             }
16212
16213           /* Branch over the branch (if the branch was likely) or the
16214              full jump (not likely case).  Compute the offset from the
16215              current instruction to branch to.  */
16216           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16217             i = 16;
16218           else
16219             {
16220               /* How many bytes in instructions we've already emitted?  */
16221               i = buf - fragp->fr_literal - fragp->fr_fix;
16222               /* How many bytes in instructions from here to the end?  */
16223               i = fragp->fr_var - i;
16224             }
16225           /* Convert to instruction count.  */
16226           i >>= 2;
16227           /* Branch counts from the next instruction.  */
16228           i--;
16229           insn |= i;
16230           /* Branch over the jump.  */
16231           buf = write_insn (buf, insn);
16232
16233           /* nop */
16234           buf = write_insn (buf, 0);
16235
16236           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16237             {
16238               /* beql $0, $0, 2f */
16239               insn = 0x50000000;
16240               /* Compute the PC offset from the current instruction to
16241                  the end of the variable frag.  */
16242               /* How many bytes in instructions we've already emitted?  */
16243               i = buf - fragp->fr_literal - fragp->fr_fix;
16244               /* How many bytes in instructions from here to the end?  */
16245               i = fragp->fr_var - i;
16246               /* Convert to instruction count.  */
16247               i >>= 2;
16248               /* Don't decrement i, because we want to branch over the
16249                  delay slot.  */
16250               insn |= i;
16251
16252               buf = write_insn (buf, insn);
16253               buf = write_insn (buf, 0);
16254             }
16255
16256         uncond:
16257           if (mips_pic == NO_PIC)
16258             {
16259               /* j or jal.  */
16260               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16261                       ? 0x0c000000 : 0x08000000);
16262               exp.X_op = O_symbol;
16263               exp.X_add_symbol = fragp->fr_symbol;
16264               exp.X_add_number = fragp->fr_offset;
16265
16266               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16267                                   FALSE, BFD_RELOC_MIPS_JMP);
16268               fixp->fx_file = fragp->fr_file;
16269               fixp->fx_line = fragp->fr_line;
16270
16271               buf = write_insn (buf, insn);
16272             }
16273           else
16274             {
16275               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16276
16277               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16278               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16279               insn |= at << OP_SH_RT;
16280               exp.X_op = O_symbol;
16281               exp.X_add_symbol = fragp->fr_symbol;
16282               exp.X_add_number = fragp->fr_offset;
16283
16284               if (fragp->fr_offset)
16285                 {
16286                   exp.X_add_symbol = make_expr_symbol (&exp);
16287                   exp.X_add_number = 0;
16288                 }
16289
16290               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16291                                   FALSE, BFD_RELOC_MIPS_GOT16);
16292               fixp->fx_file = fragp->fr_file;
16293               fixp->fx_line = fragp->fr_line;
16294
16295               buf = write_insn (buf, insn);
16296
16297               if (mips_opts.isa == ISA_MIPS1)
16298                 /* nop */
16299                 buf = write_insn (buf, 0);
16300
16301               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16302               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16303               insn |= at << OP_SH_RS | at << OP_SH_RT;
16304
16305               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16306                                   FALSE, BFD_RELOC_LO16);
16307               fixp->fx_file = fragp->fr_file;
16308               fixp->fx_line = fragp->fr_line;
16309
16310               buf = write_insn (buf, insn);
16311
16312               /* j(al)r $at.  */
16313               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16314                 insn = 0x0000f809;
16315               else
16316                 insn = 0x00000008;
16317               insn |= at << OP_SH_RS;
16318
16319               buf = write_insn (buf, insn);
16320             }
16321         }
16322
16323       fragp->fr_fix += fragp->fr_var;
16324       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16325       return;
16326     }
16327
16328   /* Relax microMIPS branches.  */
16329   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16330     {
16331       char *buf = fragp->fr_literal + fragp->fr_fix;
16332       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16333       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16334       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16335       bfd_boolean short_ds;
16336       unsigned long insn;
16337       expressionS exp;
16338       fixS *fixp;
16339
16340       exp.X_op = O_symbol;
16341       exp.X_add_symbol = fragp->fr_symbol;
16342       exp.X_add_number = fragp->fr_offset;
16343
16344       fragp->fr_fix += fragp->fr_var;
16345
16346       /* Handle 16-bit branches that fit or are forced to fit.  */
16347       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16348         {
16349           /* We generate a fixup instead of applying it right now,
16350              because if there is linker relaxation, we're going to
16351              need the relocations.  */
16352           if (type == 'D')
16353             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16354                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16355           else if (type == 'E')
16356             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16357                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16358           else
16359             abort ();
16360
16361           fixp->fx_file = fragp->fr_file;
16362           fixp->fx_line = fragp->fr_line;
16363
16364           /* These relocations can have an addend that won't fit in
16365              2 octets.  */
16366           fixp->fx_no_overflow = 1;
16367
16368           return;
16369         }
16370
16371       /* Handle 32-bit branches that fit or are forced to fit.  */
16372       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16373           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16374         {
16375           /* We generate a fixup instead of applying it right now,
16376              because if there is linker relaxation, we're going to
16377              need the relocations.  */
16378           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16379                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16380           fixp->fx_file = fragp->fr_file;
16381           fixp->fx_line = fragp->fr_line;
16382
16383           if (type == 0)
16384             return;
16385         }
16386
16387       /* Relax 16-bit branches to 32-bit branches.  */
16388       if (type != 0)
16389         {
16390           insn = read_compressed_insn (buf, 2);
16391
16392           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16393             insn = 0x94000000;                          /* beq  */
16394           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16395             {
16396               unsigned long regno;
16397
16398               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16399               regno = micromips_to_32_reg_d_map [regno];
16400               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16401               insn |= regno << MICROMIPSOP_SH_RS;
16402             }
16403           else
16404             abort ();
16405
16406           /* Nothing else to do, just write it out.  */
16407           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16408               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16409             {
16410               buf = write_compressed_insn (buf, insn, 4);
16411               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16412               return;
16413             }
16414         }
16415       else
16416         insn = read_compressed_insn (buf, 4);
16417
16418       /* Relax 32-bit branches to a sequence of instructions.  */
16419       as_warn_where (fragp->fr_file, fragp->fr_line,
16420                      _("Relaxed out-of-range branch into a jump"));
16421
16422       /* Set the short-delay-slot bit.  */
16423       short_ds = al && (insn & 0x02000000) != 0;
16424
16425       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16426         {
16427           symbolS *l;
16428
16429           /* Reverse the branch.  */
16430           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16431               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16432             insn ^= 0x20000000;
16433           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16434                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16435                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16436                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16437                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16438                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16439                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16440                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16441                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16442                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16443             insn ^= 0x00400000;
16444           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16445                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16446                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16447                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16448             insn ^= 0x00200000;
16449           else
16450             abort ();
16451
16452           if (al)
16453             {
16454               /* Clear the and-link and short-delay-slot bits.  */
16455               gas_assert ((insn & 0xfda00000) == 0x40200000);
16456
16457               /* bltzal  0x40200000     bgezal  0x40600000  */
16458               /* bltzals 0x42200000     bgezals 0x42600000  */
16459               insn &= ~0x02200000;
16460             }
16461
16462           /* Make a label at the end for use with the branch.  */
16463           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16464           micromips_label_inc ();
16465           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16466
16467           /* Refer to it.  */
16468           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16469                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16470           fixp->fx_file = fragp->fr_file;
16471           fixp->fx_line = fragp->fr_line;
16472
16473           /* Branch over the jump.  */
16474           buf = write_compressed_insn (buf, insn, 4);
16475           if (!compact)
16476             /* nop */
16477             buf = write_compressed_insn (buf, 0x0c00, 2);
16478         }
16479
16480       if (mips_pic == NO_PIC)
16481         {
16482           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16483
16484           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16485           insn = al ? jal : 0xd4000000;
16486
16487           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16488                               BFD_RELOC_MICROMIPS_JMP);
16489           fixp->fx_file = fragp->fr_file;
16490           fixp->fx_line = fragp->fr_line;
16491
16492           buf = write_compressed_insn (buf, insn, 4);
16493           if (compact)
16494             /* nop */
16495             buf = write_compressed_insn (buf, 0x0c00, 2);
16496         }
16497       else
16498         {
16499           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
16500           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
16501           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
16502
16503           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
16504           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
16505           insn |= at << MICROMIPSOP_SH_RT;
16506
16507           if (exp.X_add_number)
16508             {
16509               exp.X_add_symbol = make_expr_symbol (&exp);
16510               exp.X_add_number = 0;
16511             }
16512
16513           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16514                               BFD_RELOC_MICROMIPS_GOT16);
16515           fixp->fx_file = fragp->fr_file;
16516           fixp->fx_line = fragp->fr_line;
16517
16518           buf = write_compressed_insn (buf, insn, 4);
16519
16520           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
16521           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
16522           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
16523
16524           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16525                               BFD_RELOC_MICROMIPS_LO16);
16526           fixp->fx_file = fragp->fr_file;
16527           fixp->fx_line = fragp->fr_line;
16528
16529           buf = write_compressed_insn (buf, insn, 4);
16530
16531           /* jr/jrc/jalr/jalrs $at  */
16532           insn = al ? jalr : jr;
16533           insn |= at << MICROMIPSOP_SH_MJ;
16534
16535           buf = write_compressed_insn (buf, insn, 2);
16536         }
16537
16538       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16539       return;
16540     }
16541
16542   if (RELAX_MIPS16_P (fragp->fr_subtype))
16543     {
16544       int type;
16545       const struct mips16_immed_operand *op;
16546       offsetT val;
16547       char *buf;
16548       unsigned int user_length, length;
16549       unsigned long insn;
16550       bfd_boolean ext;
16551
16552       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16553       op = mips16_immed_operands;
16554       while (op->type != type)
16555         ++op;
16556
16557       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
16558       val = resolve_symbol_value (fragp->fr_symbol);
16559       if (op->pcrel)
16560         {
16561           addressT addr;
16562
16563           addr = fragp->fr_address + fragp->fr_fix;
16564
16565           /* The rules for the base address of a PC relative reloc are
16566              complicated; see mips16_extended_frag.  */
16567           if (type == 'p' || type == 'q')
16568             {
16569               addr += 2;
16570               if (ext)
16571                 addr += 2;
16572               /* Ignore the low bit in the target, since it will be
16573                  set for a text label.  */
16574               if ((val & 1) != 0)
16575                 --val;
16576             }
16577           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16578             addr -= 4;
16579           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16580             addr -= 2;
16581
16582           addr &= ~ (addressT) ((1 << op->shift) - 1);
16583           val -= addr;
16584
16585           /* Make sure the section winds up with the alignment we have
16586              assumed.  */
16587           if (op->shift > 0)
16588             record_alignment (asec, op->shift);
16589         }
16590
16591       if (ext
16592           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
16593               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
16594         as_warn_where (fragp->fr_file, fragp->fr_line,
16595                        _("extended instruction in delay slot"));
16596
16597       buf = fragp->fr_literal + fragp->fr_fix;
16598
16599       insn = read_compressed_insn (buf, 2);
16600       if (ext)
16601         insn |= MIPS16_EXTEND;
16602
16603       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16604         user_length = 4;
16605       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16606         user_length = 2;
16607       else
16608         user_length = 0;
16609
16610       mips16_immed (fragp->fr_file, fragp->fr_line, type,
16611                     BFD_RELOC_UNUSED, val, user_length, &insn);
16612
16613       length = (ext ? 4 : 2);
16614       gas_assert (mips16_opcode_length (insn) == length);
16615       write_compressed_insn (buf, insn, length);
16616       fragp->fr_fix += length;
16617     }
16618   else
16619     {
16620       relax_substateT subtype = fragp->fr_subtype;
16621       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
16622       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
16623       int first, second;
16624       fixS *fixp;
16625
16626       first = RELAX_FIRST (subtype);
16627       second = RELAX_SECOND (subtype);
16628       fixp = (fixS *) fragp->fr_opcode;
16629
16630       /* If the delay slot chosen does not match the size of the instruction,
16631          then emit a warning.  */
16632       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
16633            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
16634         {
16635           relax_substateT s;
16636           const char *msg;
16637
16638           s = subtype & (RELAX_DELAY_SLOT_16BIT
16639                          | RELAX_DELAY_SLOT_SIZE_FIRST
16640                          | RELAX_DELAY_SLOT_SIZE_SECOND);
16641           msg = macro_warning (s);
16642           if (msg != NULL)
16643             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
16644           subtype &= ~s;
16645         }
16646
16647       /* Possibly emit a warning if we've chosen the longer option.  */
16648       if (use_second == second_longer)
16649         {
16650           relax_substateT s;
16651           const char *msg;
16652
16653           s = (subtype
16654                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
16655           msg = macro_warning (s);
16656           if (msg != NULL)
16657             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
16658           subtype &= ~s;
16659         }
16660
16661       /* Go through all the fixups for the first sequence.  Disable them
16662          (by marking them as done) if we're going to use the second
16663          sequence instead.  */
16664       while (fixp
16665              && fixp->fx_frag == fragp
16666              && fixp->fx_where < fragp->fr_fix - second)
16667         {
16668           if (subtype & RELAX_USE_SECOND)
16669             fixp->fx_done = 1;
16670           fixp = fixp->fx_next;
16671         }
16672
16673       /* Go through the fixups for the second sequence.  Disable them if
16674          we're going to use the first sequence, otherwise adjust their
16675          addresses to account for the relaxation.  */
16676       while (fixp && fixp->fx_frag == fragp)
16677         {
16678           if (subtype & RELAX_USE_SECOND)
16679             fixp->fx_where -= first;
16680           else
16681             fixp->fx_done = 1;
16682           fixp = fixp->fx_next;
16683         }
16684
16685       /* Now modify the frag contents.  */
16686       if (subtype & RELAX_USE_SECOND)
16687         {
16688           char *start;
16689
16690           start = fragp->fr_literal + fragp->fr_fix - first - second;
16691           memmove (start, start + first, second);
16692           fragp->fr_fix -= first;
16693         }
16694       else
16695         fragp->fr_fix -= second;
16696     }
16697 }
16698
16699 /* This function is called after the relocs have been generated.
16700    We've been storing mips16 text labels as odd.  Here we convert them
16701    back to even for the convenience of the debugger.  */
16702
16703 void
16704 mips_frob_file_after_relocs (void)
16705 {
16706   asymbol **syms;
16707   unsigned int count, i;
16708
16709   syms = bfd_get_outsymbols (stdoutput);
16710   count = bfd_get_symcount (stdoutput);
16711   for (i = 0; i < count; i++, syms++)
16712     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
16713         && ((*syms)->value & 1) != 0)
16714       {
16715         (*syms)->value &= ~1;
16716         /* If the symbol has an odd size, it was probably computed
16717            incorrectly, so adjust that as well.  */
16718         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
16719           ++elf_symbol (*syms)->internal_elf_sym.st_size;
16720       }
16721 }
16722
16723 /* This function is called whenever a label is defined, including fake
16724    labels instantiated off the dot special symbol.  It is used when
16725    handling branch delays; if a branch has a label, we assume we cannot
16726    move it.  This also bumps the value of the symbol by 1 in compressed
16727    code.  */
16728
16729 static void
16730 mips_record_label (symbolS *sym)
16731 {
16732   segment_info_type *si = seg_info (now_seg);
16733   struct insn_label_list *l;
16734
16735   if (free_insn_labels == NULL)
16736     l = (struct insn_label_list *) xmalloc (sizeof *l);
16737   else
16738     {
16739       l = free_insn_labels;
16740       free_insn_labels = l->next;
16741     }
16742
16743   l->label = sym;
16744   l->next = si->label_list;
16745   si->label_list = l;
16746 }
16747
16748 /* This function is called as tc_frob_label() whenever a label is defined
16749    and adds a DWARF-2 record we only want for true labels.  */
16750
16751 void
16752 mips_define_label (symbolS *sym)
16753 {
16754   mips_record_label (sym);
16755   dwarf2_emit_label (sym);
16756 }
16757
16758 /* This function is called by tc_new_dot_label whenever a new dot symbol
16759    is defined.  */
16760
16761 void
16762 mips_add_dot_label (symbolS *sym)
16763 {
16764   mips_record_label (sym);
16765   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
16766     mips_compressed_mark_label (sym);
16767 }
16768 \f
16769 /* Some special processing for a MIPS ELF file.  */
16770
16771 void
16772 mips_elf_final_processing (void)
16773 {
16774   /* Write out the register information.  */
16775   if (mips_abi != N64_ABI)
16776     {
16777       Elf32_RegInfo s;
16778
16779       s.ri_gprmask = mips_gprmask;
16780       s.ri_cprmask[0] = mips_cprmask[0];
16781       s.ri_cprmask[1] = mips_cprmask[1];
16782       s.ri_cprmask[2] = mips_cprmask[2];
16783       s.ri_cprmask[3] = mips_cprmask[3];
16784       /* The gp_value field is set by the MIPS ELF backend.  */
16785
16786       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
16787                                        ((Elf32_External_RegInfo *)
16788                                         mips_regmask_frag));
16789     }
16790   else
16791     {
16792       Elf64_Internal_RegInfo s;
16793
16794       s.ri_gprmask = mips_gprmask;
16795       s.ri_pad = 0;
16796       s.ri_cprmask[0] = mips_cprmask[0];
16797       s.ri_cprmask[1] = mips_cprmask[1];
16798       s.ri_cprmask[2] = mips_cprmask[2];
16799       s.ri_cprmask[3] = mips_cprmask[3];
16800       /* The gp_value field is set by the MIPS ELF backend.  */
16801
16802       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
16803                                        ((Elf64_External_RegInfo *)
16804                                         mips_regmask_frag));
16805     }
16806
16807   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
16808      sort of BFD interface for this.  */
16809   if (mips_any_noreorder)
16810     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
16811   if (mips_pic != NO_PIC)
16812     {
16813       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
16814       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
16815     }
16816   if (mips_abicalls)
16817     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
16818
16819   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
16820      defined at present; this might need to change in future.  */
16821   if (file_ase_mips16)
16822     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
16823   if (file_ase_micromips)
16824     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
16825   if (file_ase & ASE_MDMX)
16826     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
16827
16828   /* Set the MIPS ELF ABI flags.  */
16829   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
16830     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
16831   else if (mips_abi == O64_ABI)
16832     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
16833   else if (mips_abi == EABI_ABI)
16834     {
16835       if (!file_mips_gp32)
16836         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
16837       else
16838         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
16839     }
16840   else if (mips_abi == N32_ABI)
16841     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
16842
16843   /* Nothing to do for N64_ABI.  */
16844
16845   if (mips_32bitmode)
16846     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
16847
16848   if (mips_flag_nan2008)
16849     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
16850
16851 #if 0 /* XXX FIXME */
16852   /* 32 bit code with 64 bit FP registers.  */
16853   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
16854     elf_elfheader (stdoutput)->e_flags |= ???;
16855 #endif
16856 }
16857 \f
16858 typedef struct proc {
16859   symbolS *func_sym;
16860   symbolS *func_end_sym;
16861   unsigned long reg_mask;
16862   unsigned long reg_offset;
16863   unsigned long fpreg_mask;
16864   unsigned long fpreg_offset;
16865   unsigned long frame_offset;
16866   unsigned long frame_reg;
16867   unsigned long pc_reg;
16868 } procS;
16869
16870 static procS cur_proc;
16871 static procS *cur_proc_ptr;
16872 static int numprocs;
16873
16874 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
16875    as "2", and a normal nop as "0".  */
16876
16877 #define NOP_OPCODE_MIPS         0
16878 #define NOP_OPCODE_MIPS16       1
16879 #define NOP_OPCODE_MICROMIPS    2
16880
16881 char
16882 mips_nop_opcode (void)
16883 {
16884   if (seg_info (now_seg)->tc_segment_info_data.micromips)
16885     return NOP_OPCODE_MICROMIPS;
16886   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
16887     return NOP_OPCODE_MIPS16;
16888   else
16889     return NOP_OPCODE_MIPS;
16890 }
16891
16892 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
16893    32-bit microMIPS NOPs here (if applicable).  */
16894
16895 void
16896 mips_handle_align (fragS *fragp)
16897 {
16898   char nop_opcode;
16899   char *p;
16900   int bytes, size, excess;
16901   valueT opcode;
16902
16903   if (fragp->fr_type != rs_align_code)
16904     return;
16905
16906   p = fragp->fr_literal + fragp->fr_fix;
16907   nop_opcode = *p;
16908   switch (nop_opcode)
16909     {
16910     case NOP_OPCODE_MICROMIPS:
16911       opcode = micromips_nop32_insn.insn_opcode;
16912       size = 4;
16913       break;
16914     case NOP_OPCODE_MIPS16:
16915       opcode = mips16_nop_insn.insn_opcode;
16916       size = 2;
16917       break;
16918     case NOP_OPCODE_MIPS:
16919     default:
16920       opcode = nop_insn.insn_opcode;
16921       size = 4;
16922       break;
16923     }
16924
16925   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
16926   excess = bytes % size;
16927
16928   /* Handle the leading part if we're not inserting a whole number of
16929      instructions, and make it the end of the fixed part of the frag.
16930      Try to fit in a short microMIPS NOP if applicable and possible,
16931      and use zeroes otherwise.  */
16932   gas_assert (excess < 4);
16933   fragp->fr_fix += excess;
16934   switch (excess)
16935     {
16936     case 3:
16937       *p++ = '\0';
16938       /* Fall through.  */
16939     case 2:
16940       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
16941         {
16942           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
16943           break;
16944         }
16945       *p++ = '\0';
16946       /* Fall through.  */
16947     case 1:
16948       *p++ = '\0';
16949       /* Fall through.  */
16950     case 0:
16951       break;
16952     }
16953
16954   md_number_to_chars (p, opcode, size);
16955   fragp->fr_var = size;
16956 }
16957
16958 static void
16959 md_obj_begin (void)
16960 {
16961 }
16962
16963 static void
16964 md_obj_end (void)
16965 {
16966   /* Check for premature end, nesting errors, etc.  */
16967   if (cur_proc_ptr)
16968     as_warn (_("missing .end at end of assembly"));
16969 }
16970
16971 static long
16972 get_number (void)
16973 {
16974   int negative = 0;
16975   long val = 0;
16976
16977   if (*input_line_pointer == '-')
16978     {
16979       ++input_line_pointer;
16980       negative = 1;
16981     }
16982   if (!ISDIGIT (*input_line_pointer))
16983     as_bad (_("expected simple number"));
16984   if (input_line_pointer[0] == '0')
16985     {
16986       if (input_line_pointer[1] == 'x')
16987         {
16988           input_line_pointer += 2;
16989           while (ISXDIGIT (*input_line_pointer))
16990             {
16991               val <<= 4;
16992               val |= hex_value (*input_line_pointer++);
16993             }
16994           return negative ? -val : val;
16995         }
16996       else
16997         {
16998           ++input_line_pointer;
16999           while (ISDIGIT (*input_line_pointer))
17000             {
17001               val <<= 3;
17002               val |= *input_line_pointer++ - '0';
17003             }
17004           return negative ? -val : val;
17005         }
17006     }
17007   if (!ISDIGIT (*input_line_pointer))
17008     {
17009       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17010               *input_line_pointer, *input_line_pointer);
17011       as_warn (_("invalid number"));
17012       return -1;
17013     }
17014   while (ISDIGIT (*input_line_pointer))
17015     {
17016       val *= 10;
17017       val += *input_line_pointer++ - '0';
17018     }
17019   return negative ? -val : val;
17020 }
17021
17022 /* The .file directive; just like the usual .file directive, but there
17023    is an initial number which is the ECOFF file index.  In the non-ECOFF
17024    case .file implies DWARF-2.  */
17025
17026 static void
17027 s_mips_file (int x ATTRIBUTE_UNUSED)
17028 {
17029   static int first_file_directive = 0;
17030
17031   if (ECOFF_DEBUGGING)
17032     {
17033       get_number ();
17034       s_app_file (0);
17035     }
17036   else
17037     {
17038       char *filename;
17039
17040       filename = dwarf2_directive_file (0);
17041
17042       /* Versions of GCC up to 3.1 start files with a ".file"
17043          directive even for stabs output.  Make sure that this
17044          ".file" is handled.  Note that you need a version of GCC
17045          after 3.1 in order to support DWARF-2 on MIPS.  */
17046       if (filename != NULL && ! first_file_directive)
17047         {
17048           (void) new_logical_line (filename, -1);
17049           s_app_file_string (filename, 0);
17050         }
17051       first_file_directive = 1;
17052     }
17053 }
17054
17055 /* The .loc directive, implying DWARF-2.  */
17056
17057 static void
17058 s_mips_loc (int x ATTRIBUTE_UNUSED)
17059 {
17060   if (!ECOFF_DEBUGGING)
17061     dwarf2_directive_loc (0);
17062 }
17063
17064 /* The .end directive.  */
17065
17066 static void
17067 s_mips_end (int x ATTRIBUTE_UNUSED)
17068 {
17069   symbolS *p;
17070
17071   /* Following functions need their own .frame and .cprestore directives.  */
17072   mips_frame_reg_valid = 0;
17073   mips_cprestore_valid = 0;
17074
17075   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17076     {
17077       p = get_symbol ();
17078       demand_empty_rest_of_line ();
17079     }
17080   else
17081     p = NULL;
17082
17083   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17084     as_warn (_(".end not in text section"));
17085
17086   if (!cur_proc_ptr)
17087     {
17088       as_warn (_(".end directive without a preceding .ent directive."));
17089       demand_empty_rest_of_line ();
17090       return;
17091     }
17092
17093   if (p != NULL)
17094     {
17095       gas_assert (S_GET_NAME (p));
17096       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17097         as_warn (_(".end symbol does not match .ent symbol."));
17098
17099       if (debug_type == DEBUG_STABS)
17100         stabs_generate_asm_endfunc (S_GET_NAME (p),
17101                                     S_GET_NAME (p));
17102     }
17103   else
17104     as_warn (_(".end directive missing or unknown symbol"));
17105
17106   /* Create an expression to calculate the size of the function.  */
17107   if (p && cur_proc_ptr)
17108     {
17109       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17110       expressionS *exp = xmalloc (sizeof (expressionS));
17111
17112       obj->size = exp;
17113       exp->X_op = O_subtract;
17114       exp->X_add_symbol = symbol_temp_new_now ();
17115       exp->X_op_symbol = p;
17116       exp->X_add_number = 0;
17117
17118       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17119     }
17120
17121   /* Generate a .pdr section.  */
17122   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17123     {
17124       segT saved_seg = now_seg;
17125       subsegT saved_subseg = now_subseg;
17126       expressionS exp;
17127       char *fragp;
17128
17129 #ifdef md_flush_pending_output
17130       md_flush_pending_output ();
17131 #endif
17132
17133       gas_assert (pdr_seg);
17134       subseg_set (pdr_seg, 0);
17135
17136       /* Write the symbol.  */
17137       exp.X_op = O_symbol;
17138       exp.X_add_symbol = p;
17139       exp.X_add_number = 0;
17140       emit_expr (&exp, 4);
17141
17142       fragp = frag_more (7 * 4);
17143
17144       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17145       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17146       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17147       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17148       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17149       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17150       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17151
17152       subseg_set (saved_seg, saved_subseg);
17153     }
17154
17155   cur_proc_ptr = NULL;
17156 }
17157
17158 /* The .aent and .ent directives.  */
17159
17160 static void
17161 s_mips_ent (int aent)
17162 {
17163   symbolS *symbolP;
17164
17165   symbolP = get_symbol ();
17166   if (*input_line_pointer == ',')
17167     ++input_line_pointer;
17168   SKIP_WHITESPACE ();
17169   if (ISDIGIT (*input_line_pointer)
17170       || *input_line_pointer == '-')
17171     get_number ();
17172
17173   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17174     as_warn (_(".ent or .aent not in text section."));
17175
17176   if (!aent && cur_proc_ptr)
17177     as_warn (_("missing .end"));
17178
17179   if (!aent)
17180     {
17181       /* This function needs its own .frame and .cprestore directives.  */
17182       mips_frame_reg_valid = 0;
17183       mips_cprestore_valid = 0;
17184
17185       cur_proc_ptr = &cur_proc;
17186       memset (cur_proc_ptr, '\0', sizeof (procS));
17187
17188       cur_proc_ptr->func_sym = symbolP;
17189
17190       ++numprocs;
17191
17192       if (debug_type == DEBUG_STABS)
17193         stabs_generate_asm_func (S_GET_NAME (symbolP),
17194                                  S_GET_NAME (symbolP));
17195     }
17196
17197   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17198
17199   demand_empty_rest_of_line ();
17200 }
17201
17202 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17203    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17204    s_mips_frame is used so that we can set the PDR information correctly.
17205    We can't use the ecoff routines because they make reference to the ecoff
17206    symbol table (in the mdebug section).  */
17207
17208 static void
17209 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17210 {
17211   if (ECOFF_DEBUGGING)
17212     s_ignore (ignore);
17213   else
17214     {
17215       long val;
17216
17217       if (cur_proc_ptr == (procS *) NULL)
17218         {
17219           as_warn (_(".frame outside of .ent"));
17220           demand_empty_rest_of_line ();
17221           return;
17222         }
17223
17224       cur_proc_ptr->frame_reg = tc_get_register (1);
17225
17226       SKIP_WHITESPACE ();
17227       if (*input_line_pointer++ != ','
17228           || get_absolute_expression_and_terminator (&val) != ',')
17229         {
17230           as_warn (_("Bad .frame directive"));
17231           --input_line_pointer;
17232           demand_empty_rest_of_line ();
17233           return;
17234         }
17235
17236       cur_proc_ptr->frame_offset = val;
17237       cur_proc_ptr->pc_reg = tc_get_register (0);
17238
17239       demand_empty_rest_of_line ();
17240     }
17241 }
17242
17243 /* The .fmask and .mask directives. If the mdebug section is present
17244    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17245    embedded targets, s_mips_mask is used so that we can set the PDR
17246    information correctly. We can't use the ecoff routines because they
17247    make reference to the ecoff symbol table (in the mdebug section).  */
17248
17249 static void
17250 s_mips_mask (int reg_type)
17251 {
17252   if (ECOFF_DEBUGGING)
17253     s_ignore (reg_type);
17254   else
17255     {
17256       long mask, off;
17257
17258       if (cur_proc_ptr == (procS *) NULL)
17259         {
17260           as_warn (_(".mask/.fmask outside of .ent"));
17261           demand_empty_rest_of_line ();
17262           return;
17263         }
17264
17265       if (get_absolute_expression_and_terminator (&mask) != ',')
17266         {
17267           as_warn (_("Bad .mask/.fmask directive"));
17268           --input_line_pointer;
17269           demand_empty_rest_of_line ();
17270           return;
17271         }
17272
17273       off = get_absolute_expression ();
17274
17275       if (reg_type == 'F')
17276         {
17277           cur_proc_ptr->fpreg_mask = mask;
17278           cur_proc_ptr->fpreg_offset = off;
17279         }
17280       else
17281         {
17282           cur_proc_ptr->reg_mask = mask;
17283           cur_proc_ptr->reg_offset = off;
17284         }
17285
17286       demand_empty_rest_of_line ();
17287     }
17288 }
17289
17290 /* A table describing all the processors gas knows about.  Names are
17291    matched in the order listed.
17292
17293    To ease comparison, please keep this table in the same order as
17294    gcc's mips_cpu_info_table[].  */
17295 static const struct mips_cpu_info mips_cpu_info_table[] =
17296 {
17297   /* Entries for generic ISAs */
17298   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17299   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17300   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17301   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17302   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17303   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17304   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17305   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17306   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17307
17308   /* MIPS I */
17309   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17310   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17311   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17312
17313   /* MIPS II */
17314   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17315
17316   /* MIPS III */
17317   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17318   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17319   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17320   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17321   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17322   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17323   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17324   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17325   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17326   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17327   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17328   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17329   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17330   /* ST Microelectronics Loongson 2E and 2F cores */
17331   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17332   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17333
17334   /* MIPS IV */
17335   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17336   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17337   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17338   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17339   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17340   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17341   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17342   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17343   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17344   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17345   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17346   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17347   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17348   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17349   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17350
17351   /* MIPS 32 */
17352   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17353   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17354   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17355   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17356
17357   /* MIPS 32 Release 2 */
17358   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17359   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17360   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17361   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17362   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17363   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17364   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17365   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17366   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17367                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17368   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17369                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17370   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17371   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17372   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17373   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17374   /* Deprecated forms of the above.  */
17375   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17376   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17377   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17378   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17379   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17380   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17381   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17382   /* Deprecated forms of the above.  */
17383   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17384   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17385   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17386   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17387   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17388   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17389   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17390   /* Deprecated forms of the above.  */
17391   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17392   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17393   /* 34Kn is a 34kc without DSP.  */
17394   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17395   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17396   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17397   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17398   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17399   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17400   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17401   /* Deprecated forms of the above.  */
17402   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17403   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17404   /* 1004K cores are multiprocessor versions of the 34K.  */
17405   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17406   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17407   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17408   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17409
17410   /* MIPS 64 */
17411   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17412   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17413   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17414   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17415
17416   /* Broadcom SB-1 CPU core */
17417   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17418   /* Broadcom SB-1A CPU core */
17419   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17420   
17421   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
17422
17423   /* MIPS 64 Release 2 */
17424
17425   /* Cavium Networks Octeon CPU core */
17426   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17427   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17428   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17429
17430   /* RMI Xlr */
17431   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17432
17433   /* Broadcom XLP.
17434      XLP is mostly like XLR, with the prominent exception that it is
17435      MIPS64R2 rather than MIPS64.  */
17436   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17437
17438   /* End marker */
17439   { NULL, 0, 0, 0, 0 }
17440 };
17441
17442
17443 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17444    with a final "000" replaced by "k".  Ignore case.
17445
17446    Note: this function is shared between GCC and GAS.  */
17447
17448 static bfd_boolean
17449 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17450 {
17451   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17452     given++, canonical++;
17453
17454   return ((*given == 0 && *canonical == 0)
17455           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17456 }
17457
17458
17459 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17460    CPU name.  We've traditionally allowed a lot of variation here.
17461
17462    Note: this function is shared between GCC and GAS.  */
17463
17464 static bfd_boolean
17465 mips_matching_cpu_name_p (const char *canonical, const char *given)
17466 {
17467   /* First see if the name matches exactly, or with a final "000"
17468      turned into "k".  */
17469   if (mips_strict_matching_cpu_name_p (canonical, given))
17470     return TRUE;
17471
17472   /* If not, try comparing based on numerical designation alone.
17473      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17474   if (TOLOWER (*given) == 'r')
17475     given++;
17476   if (!ISDIGIT (*given))
17477     return FALSE;
17478
17479   /* Skip over some well-known prefixes in the canonical name,
17480      hoping to find a number there too.  */
17481   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17482     canonical += 2;
17483   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17484     canonical += 2;
17485   else if (TOLOWER (canonical[0]) == 'r')
17486     canonical += 1;
17487
17488   return mips_strict_matching_cpu_name_p (canonical, given);
17489 }
17490
17491
17492 /* Parse an option that takes the name of a processor as its argument.
17493    OPTION is the name of the option and CPU_STRING is the argument.
17494    Return the corresponding processor enumeration if the CPU_STRING is
17495    recognized, otherwise report an error and return null.
17496
17497    A similar function exists in GCC.  */
17498
17499 static const struct mips_cpu_info *
17500 mips_parse_cpu (const char *option, const char *cpu_string)
17501 {
17502   const struct mips_cpu_info *p;
17503
17504   /* 'from-abi' selects the most compatible architecture for the given
17505      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
17506      EABIs, we have to decide whether we're using the 32-bit or 64-bit
17507      version.  Look first at the -mgp options, if given, otherwise base
17508      the choice on MIPS_DEFAULT_64BIT.
17509
17510      Treat NO_ABI like the EABIs.  One reason to do this is that the
17511      plain 'mips' and 'mips64' configs have 'from-abi' as their default
17512      architecture.  This code picks MIPS I for 'mips' and MIPS III for
17513      'mips64', just as we did in the days before 'from-abi'.  */
17514   if (strcasecmp (cpu_string, "from-abi") == 0)
17515     {
17516       if (ABI_NEEDS_32BIT_REGS (mips_abi))
17517         return mips_cpu_info_from_isa (ISA_MIPS1);
17518
17519       if (ABI_NEEDS_64BIT_REGS (mips_abi))
17520         return mips_cpu_info_from_isa (ISA_MIPS3);
17521
17522       if (file_mips_gp32 >= 0)
17523         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
17524
17525       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
17526                                      ? ISA_MIPS3
17527                                      : ISA_MIPS1);
17528     }
17529
17530   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
17531   if (strcasecmp (cpu_string, "default") == 0)
17532     return 0;
17533
17534   for (p = mips_cpu_info_table; p->name != 0; p++)
17535     if (mips_matching_cpu_name_p (p->name, cpu_string))
17536       return p;
17537
17538   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
17539   return 0;
17540 }
17541
17542 /* Return the canonical processor information for ISA (a member of the
17543    ISA_MIPS* enumeration).  */
17544
17545 static const struct mips_cpu_info *
17546 mips_cpu_info_from_isa (int isa)
17547 {
17548   int i;
17549
17550   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17551     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
17552         && isa == mips_cpu_info_table[i].isa)
17553       return (&mips_cpu_info_table[i]);
17554
17555   return NULL;
17556 }
17557
17558 static const struct mips_cpu_info *
17559 mips_cpu_info_from_arch (int arch)
17560 {
17561   int i;
17562
17563   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17564     if (arch == mips_cpu_info_table[i].cpu)
17565       return (&mips_cpu_info_table[i]);
17566
17567   return NULL;
17568 }
17569 \f
17570 static void
17571 show (FILE *stream, const char *string, int *col_p, int *first_p)
17572 {
17573   if (*first_p)
17574     {
17575       fprintf (stream, "%24s", "");
17576       *col_p = 24;
17577     }
17578   else
17579     {
17580       fprintf (stream, ", ");
17581       *col_p += 2;
17582     }
17583
17584   if (*col_p + strlen (string) > 72)
17585     {
17586       fprintf (stream, "\n%24s", "");
17587       *col_p = 24;
17588     }
17589
17590   fprintf (stream, "%s", string);
17591   *col_p += strlen (string);
17592
17593   *first_p = 0;
17594 }
17595
17596 void
17597 md_show_usage (FILE *stream)
17598 {
17599   int column, first;
17600   size_t i;
17601
17602   fprintf (stream, _("\
17603 MIPS options:\n\
17604 -EB                     generate big endian output\n\
17605 -EL                     generate little endian output\n\
17606 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
17607 -G NUM                  allow referencing objects up to NUM bytes\n\
17608                         implicitly with the gp register [default 8]\n"));
17609   fprintf (stream, _("\
17610 -mips1                  generate MIPS ISA I instructions\n\
17611 -mips2                  generate MIPS ISA II instructions\n\
17612 -mips3                  generate MIPS ISA III instructions\n\
17613 -mips4                  generate MIPS ISA IV instructions\n\
17614 -mips5                  generate MIPS ISA V instructions\n\
17615 -mips32                 generate MIPS32 ISA instructions\n\
17616 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
17617 -mips64                 generate MIPS64 ISA instructions\n\
17618 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
17619 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
17620
17621   first = 1;
17622
17623   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17624     show (stream, mips_cpu_info_table[i].name, &column, &first);
17625   show (stream, "from-abi", &column, &first);
17626   fputc ('\n', stream);
17627
17628   fprintf (stream, _("\
17629 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
17630 -no-mCPU                don't generate code specific to CPU.\n\
17631                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
17632
17633   first = 1;
17634
17635   show (stream, "3900", &column, &first);
17636   show (stream, "4010", &column, &first);
17637   show (stream, "4100", &column, &first);
17638   show (stream, "4650", &column, &first);
17639   fputc ('\n', stream);
17640
17641   fprintf (stream, _("\
17642 -mips16                 generate mips16 instructions\n\
17643 -no-mips16              do not generate mips16 instructions\n"));
17644   fprintf (stream, _("\
17645 -mmicromips             generate microMIPS instructions\n\
17646 -mno-micromips          do not generate microMIPS instructions\n"));
17647   fprintf (stream, _("\
17648 -msmartmips             generate smartmips instructions\n\
17649 -mno-smartmips          do not generate smartmips instructions\n"));  
17650   fprintf (stream, _("\
17651 -mdsp                   generate DSP instructions\n\
17652 -mno-dsp                do not generate DSP instructions\n"));
17653   fprintf (stream, _("\
17654 -mdspr2                 generate DSP R2 instructions\n\
17655 -mno-dspr2              do not generate DSP R2 instructions\n"));
17656   fprintf (stream, _("\
17657 -mmt                    generate MT instructions\n\
17658 -mno-mt                 do not generate MT instructions\n"));
17659   fprintf (stream, _("\
17660 -mmcu                   generate MCU instructions\n\
17661 -mno-mcu                do not generate MCU instructions\n"));
17662   fprintf (stream, _("\
17663 -mvirt                  generate Virtualization instructions\n\
17664 -mno-virt               do not generate Virtualization instructions\n"));
17665   fprintf (stream, _("\
17666 -minsn32                only generate 32-bit microMIPS instructions\n\
17667 -mno-insn32             generate all microMIPS instructions\n"));
17668   fprintf (stream, _("\
17669 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
17670 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
17671 -mfix-vr4120            work around certain VR4120 errata\n\
17672 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
17673 -mfix-24k               insert a nop after ERET and DERET instructions\n\
17674 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
17675 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
17676 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
17677 -msym32                 assume all symbols have 32-bit values\n\
17678 -O0                     remove unneeded NOPs, do not swap branches\n\
17679 -O                      remove unneeded NOPs and swap branches\n\
17680 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
17681 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
17682   fprintf (stream, _("\
17683 -mhard-float            allow floating-point instructions\n\
17684 -msoft-float            do not allow floating-point instructions\n\
17685 -msingle-float          only allow 32-bit floating-point operations\n\
17686 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
17687 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
17688 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
17689 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
17690
17691   first = 1;
17692
17693   show (stream, "legacy", &column, &first);
17694   show (stream, "2008", &column, &first);
17695
17696   fputc ('\n', stream);
17697
17698   fprintf (stream, _("\
17699 -KPIC, -call_shared     generate SVR4 position independent code\n\
17700 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
17701 -mvxworks-pic           generate VxWorks position independent code\n\
17702 -non_shared             do not generate code that can operate with DSOs\n\
17703 -xgot                   assume a 32 bit GOT\n\
17704 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
17705 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
17706                         position dependent (non shared) code\n\
17707 -mabi=ABI               create ABI conformant object file for:\n"));
17708
17709   first = 1;
17710
17711   show (stream, "32", &column, &first);
17712   show (stream, "o64", &column, &first);
17713   show (stream, "n32", &column, &first);
17714   show (stream, "64", &column, &first);
17715   show (stream, "eabi", &column, &first);
17716
17717   fputc ('\n', stream);
17718
17719   fprintf (stream, _("\
17720 -32                     create o32 ABI object file (default)\n\
17721 -n32                    create n32 ABI object file\n\
17722 -64                     create 64 ABI object file\n"));
17723 }
17724
17725 #ifdef TE_IRIX
17726 enum dwarf2_format
17727 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
17728 {
17729   if (HAVE_64BIT_SYMBOLS)
17730     return dwarf2_format_64bit_irix;
17731   else
17732     return dwarf2_format_32bit;
17733 }
17734 #endif
17735
17736 int
17737 mips_dwarf2_addr_size (void)
17738 {
17739   if (HAVE_64BIT_OBJECTS)
17740     return 8;
17741   else
17742     return 4;
17743 }
17744
17745 /* Standard calling conventions leave the CFA at SP on entry.  */
17746 void
17747 mips_cfi_frame_initial_instructions (void)
17748 {
17749   cfi_add_CFA_def_cfa_register (SP);
17750 }
17751
17752 int
17753 tc_mips_regname_to_dw2regnum (char *regname)
17754 {
17755   unsigned int regnum = -1;
17756   unsigned int reg;
17757
17758   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
17759     regnum = reg;
17760
17761   return regnum;
17762 }