gas/
[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 /* Types of printf format used for instruction-related error messages.
634    "I" means int ("%d") and "S" means string ("%s"). */
635 enum mips_insn_error_format {
636   ERR_FMT_PLAIN,
637   ERR_FMT_I,
638   ERR_FMT_SS,
639 };
640
641 /* Information about an error that was found while assembling the current
642    instruction.  */
643 struct mips_insn_error {
644   /* We sometimes need to match an instruction against more than one
645      opcode table entry.  Errors found during this matching are reported
646      against a particular syntactic argument rather than against the
647      instruction as a whole.  We grade these messages so that errors
648      against argument N have a greater priority than an error against
649      any argument < N, since the former implies that arguments up to N
650      were acceptable and that the opcode entry was therefore a closer match.
651      If several matches report an error against the same argument,
652      we only use that error if it is the same in all cases.
653
654      min_argnum is the minimum argument number for which an error message
655      should be accepted.  It is 0 if MSG is against the instruction as
656      a whole.  */
657   int min_argnum;
658
659   /* The printf()-style message, including its format and arguments.  */
660   enum mips_insn_error_format format;
661   const char *msg;
662   union {
663     int i;
664     const char *ss[2];
665   } u;
666 };
667
668 /* The error that should be reported for the current instruction.  */
669 static struct mips_insn_error insn_error;
670
671 static int auto_align = 1;
672
673 /* When outputting SVR4 PIC code, the assembler needs to know the
674    offset in the stack frame from which to restore the $gp register.
675    This is set by the .cprestore pseudo-op, and saved in this
676    variable.  */
677 static offsetT mips_cprestore_offset = -1;
678
679 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
680    more optimizations, it can use a register value instead of a memory-saved
681    offset and even an other register than $gp as global pointer.  */
682 static offsetT mips_cpreturn_offset = -1;
683 static int mips_cpreturn_register = -1;
684 static int mips_gp_register = GP;
685 static int mips_gprel_offset = 0;
686
687 /* Whether mips_cprestore_offset has been set in the current function
688    (or whether it has already been warned about, if not).  */
689 static int mips_cprestore_valid = 0;
690
691 /* This is the register which holds the stack frame, as set by the
692    .frame pseudo-op.  This is needed to implement .cprestore.  */
693 static int mips_frame_reg = SP;
694
695 /* Whether mips_frame_reg has been set in the current function
696    (or whether it has already been warned about, if not).  */
697 static int mips_frame_reg_valid = 0;
698
699 /* To output NOP instructions correctly, we need to keep information
700    about the previous two instructions.  */
701
702 /* Whether we are optimizing.  The default value of 2 means to remove
703    unneeded NOPs and swap branch instructions when possible.  A value
704    of 1 means to not swap branches.  A value of 0 means to always
705    insert NOPs.  */
706 static int mips_optimize = 2;
707
708 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
709    equivalent to seeing no -g option at all.  */
710 static int mips_debug = 0;
711
712 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
713 #define MAX_VR4130_NOPS 4
714
715 /* The maximum number of NOPs needed to fill delay slots.  */
716 #define MAX_DELAY_NOPS 2
717
718 /* The maximum number of NOPs needed for any purpose.  */
719 #define MAX_NOPS 4
720
721 /* A list of previous instructions, with index 0 being the most recent.
722    We need to look back MAX_NOPS instructions when filling delay slots
723    or working around processor errata.  We need to look back one
724    instruction further if we're thinking about using history[0] to
725    fill a branch delay slot.  */
726 static struct mips_cl_insn history[1 + MAX_NOPS];
727
728 /* Arrays of operands for each instruction.  */
729 #define MAX_OPERANDS 6
730 struct mips_operand_array {
731   const struct mips_operand *operand[MAX_OPERANDS];
732 };
733 static struct mips_operand_array *mips_operands;
734 static struct mips_operand_array *mips16_operands;
735 static struct mips_operand_array *micromips_operands;
736
737 /* Nop instructions used by emit_nop.  */
738 static struct mips_cl_insn nop_insn;
739 static struct mips_cl_insn mips16_nop_insn;
740 static struct mips_cl_insn micromips_nop16_insn;
741 static struct mips_cl_insn micromips_nop32_insn;
742
743 /* The appropriate nop for the current mode.  */
744 #define NOP_INSN (mips_opts.mips16                                      \
745                   ? &mips16_nop_insn                                    \
746                   : (mips_opts.micromips                                \
747                      ? (mips_opts.insn32                                \
748                         ? &micromips_nop32_insn                         \
749                         : &micromips_nop16_insn)                        \
750                      : &nop_insn))
751
752 /* The size of NOP_INSN in bytes.  */
753 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
754                         || (mips_opts.micromips && !mips_opts.insn32))  \
755                        ? 2 : 4)
756
757 /* If this is set, it points to a frag holding nop instructions which
758    were inserted before the start of a noreorder section.  If those
759    nops turn out to be unnecessary, the size of the frag can be
760    decreased.  */
761 static fragS *prev_nop_frag;
762
763 /* The number of nop instructions we created in prev_nop_frag.  */
764 static int prev_nop_frag_holds;
765
766 /* The number of nop instructions that we know we need in
767    prev_nop_frag.  */
768 static int prev_nop_frag_required;
769
770 /* The number of instructions we've seen since prev_nop_frag.  */
771 static int prev_nop_frag_since;
772
773 /* Relocations against symbols are sometimes done in two parts, with a HI
774    relocation and a LO relocation.  Each relocation has only 16 bits of
775    space to store an addend.  This means that in order for the linker to
776    handle carries correctly, it must be able to locate both the HI and
777    the LO relocation.  This means that the relocations must appear in
778    order in the relocation table.
779
780    In order to implement this, we keep track of each unmatched HI
781    relocation.  We then sort them so that they immediately precede the
782    corresponding LO relocation.  */
783
784 struct mips_hi_fixup
785 {
786   /* Next HI fixup.  */
787   struct mips_hi_fixup *next;
788   /* This fixup.  */
789   fixS *fixp;
790   /* The section this fixup is in.  */
791   segT seg;
792 };
793
794 /* The list of unmatched HI relocs.  */
795
796 static struct mips_hi_fixup *mips_hi_fixup_list;
797
798 /* The frag containing the last explicit relocation operator.
799    Null if explicit relocations have not been used.  */
800
801 static fragS *prev_reloc_op_frag;
802
803 /* Map mips16 register numbers to normal MIPS register numbers.  */
804
805 static const unsigned int mips16_to_32_reg_map[] =
806 {
807   16, 17, 2, 3, 4, 5, 6, 7
808 };
809
810 /* Map microMIPS register numbers to normal MIPS register numbers.  */
811
812 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
813
814 /* The microMIPS registers with type h.  */
815 static const unsigned int micromips_to_32_reg_h_map1[] =
816 {
817   5, 5, 6, 4, 4, 4, 4, 4
818 };
819 static const unsigned int micromips_to_32_reg_h_map2[] =
820 {
821   6, 7, 7, 21, 22, 5, 6, 7
822 };
823
824 /* The microMIPS registers with type m.  */
825 static const unsigned int micromips_to_32_reg_m_map[] =
826 {
827   0, 17, 2, 3, 16, 18, 19, 20
828 };
829
830 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
831
832 /* Classifies the kind of instructions we're interested in when
833    implementing -mfix-vr4120.  */
834 enum fix_vr4120_class
835 {
836   FIX_VR4120_MACC,
837   FIX_VR4120_DMACC,
838   FIX_VR4120_MULT,
839   FIX_VR4120_DMULT,
840   FIX_VR4120_DIV,
841   FIX_VR4120_MTHILO,
842   NUM_FIX_VR4120_CLASSES
843 };
844
845 /* ...likewise -mfix-loongson2f-jump.  */
846 static bfd_boolean mips_fix_loongson2f_jump;
847
848 /* ...likewise -mfix-loongson2f-nop.  */
849 static bfd_boolean mips_fix_loongson2f_nop;
850
851 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
852 static bfd_boolean mips_fix_loongson2f;
853
854 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
855    there must be at least one other instruction between an instruction
856    of type X and an instruction of type Y.  */
857 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
858
859 /* True if -mfix-vr4120 is in force.  */
860 static int mips_fix_vr4120;
861
862 /* ...likewise -mfix-vr4130.  */
863 static int mips_fix_vr4130;
864
865 /* ...likewise -mfix-24k.  */
866 static int mips_fix_24k;
867
868 /* ...likewise -mfix-cn63xxp1 */
869 static bfd_boolean mips_fix_cn63xxp1;
870
871 /* We don't relax branches by default, since this causes us to expand
872    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
873    fail to compute the offset before expanding the macro to the most
874    efficient expansion.  */
875
876 static int mips_relax_branch;
877 \f
878 /* The expansion of many macros depends on the type of symbol that
879    they refer to.  For example, when generating position-dependent code,
880    a macro that refers to a symbol may have two different expansions,
881    one which uses GP-relative addresses and one which uses absolute
882    addresses.  When generating SVR4-style PIC, a macro may have
883    different expansions for local and global symbols.
884
885    We handle these situations by generating both sequences and putting
886    them in variant frags.  In position-dependent code, the first sequence
887    will be the GP-relative one and the second sequence will be the
888    absolute one.  In SVR4 PIC, the first sequence will be for global
889    symbols and the second will be for local symbols.
890
891    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
892    SECOND are the lengths of the two sequences in bytes.  These fields
893    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
894    the subtype has the following flags:
895
896    RELAX_USE_SECOND
897         Set if it has been decided that we should use the second
898         sequence instead of the first.
899
900    RELAX_SECOND_LONGER
901         Set in the first variant frag if the macro's second implementation
902         is longer than its first.  This refers to the macro as a whole,
903         not an individual relaxation.
904
905    RELAX_NOMACRO
906         Set in the first variant frag if the macro appeared in a .set nomacro
907         block and if one alternative requires a warning but the other does not.
908
909    RELAX_DELAY_SLOT
910         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
911         delay slot.
912
913    RELAX_DELAY_SLOT_16BIT
914         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
915         16-bit instruction.
916
917    RELAX_DELAY_SLOT_SIZE_FIRST
918         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
919         the macro is of the wrong size for the branch delay slot.
920
921    RELAX_DELAY_SLOT_SIZE_SECOND
922         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
923         the macro is of the wrong size for the branch delay slot.
924
925    The frag's "opcode" points to the first fixup for relaxable code.
926
927    Relaxable macros are generated using a sequence such as:
928
929       relax_start (SYMBOL);
930       ... generate first expansion ...
931       relax_switch ();
932       ... generate second expansion ...
933       relax_end ();
934
935    The code and fixups for the unwanted alternative are discarded
936    by md_convert_frag.  */
937 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
938
939 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
940 #define RELAX_SECOND(X) ((X) & 0xff)
941 #define RELAX_USE_SECOND 0x10000
942 #define RELAX_SECOND_LONGER 0x20000
943 #define RELAX_NOMACRO 0x40000
944 #define RELAX_DELAY_SLOT 0x80000
945 #define RELAX_DELAY_SLOT_16BIT 0x100000
946 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
947 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
948
949 /* Branch without likely bit.  If label is out of range, we turn:
950
951         beq reg1, reg2, label
952         delay slot
953
954    into
955
956         bne reg1, reg2, 0f
957         nop
958         j label
959      0: delay slot
960
961    with the following opcode replacements:
962
963         beq <-> bne
964         blez <-> bgtz
965         bltz <-> bgez
966         bc1f <-> bc1t
967
968         bltzal <-> bgezal  (with jal label instead of j label)
969
970    Even though keeping the delay slot instruction in the delay slot of
971    the branch would be more efficient, it would be very tricky to do
972    correctly, because we'd have to introduce a variable frag *after*
973    the delay slot instruction, and expand that instead.  Let's do it
974    the easy way for now, even if the branch-not-taken case now costs
975    one additional instruction.  Out-of-range branches are not supposed
976    to be common, anyway.
977
978    Branch likely.  If label is out of range, we turn:
979
980         beql reg1, reg2, label
981         delay slot (annulled if branch not taken)
982
983    into
984
985         beql reg1, reg2, 1f
986         nop
987         beql $0, $0, 2f
988         nop
989      1: j[al] label
990         delay slot (executed only if branch taken)
991      2:
992
993    It would be possible to generate a shorter sequence by losing the
994    likely bit, generating something like:
995
996         bne reg1, reg2, 0f
997         nop
998         j[al] label
999         delay slot (executed only if branch taken)
1000      0:
1001
1002         beql -> bne
1003         bnel -> beq
1004         blezl -> bgtz
1005         bgtzl -> blez
1006         bltzl -> bgez
1007         bgezl -> bltz
1008         bc1fl -> bc1t
1009         bc1tl -> bc1f
1010
1011         bltzall -> bgezal  (with jal label instead of j label)
1012         bgezall -> bltzal  (ditto)
1013
1014
1015    but it's not clear that it would actually improve performance.  */
1016 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1017   ((relax_substateT)                                            \
1018    (0xc0000000                                                  \
1019     | ((at) & 0x1f)                                             \
1020     | ((toofar) ? 0x20 : 0)                                     \
1021     | ((link) ? 0x40 : 0)                                       \
1022     | ((likely) ? 0x80 : 0)                                     \
1023     | ((uncond) ? 0x100 : 0)))
1024 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1025 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1026 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1027 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1028 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1029 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1030
1031 /* For mips16 code, we use an entirely different form of relaxation.
1032    mips16 supports two versions of most instructions which take
1033    immediate values: a small one which takes some small value, and a
1034    larger one which takes a 16 bit value.  Since branches also follow
1035    this pattern, relaxing these values is required.
1036
1037    We can assemble both mips16 and normal MIPS code in a single
1038    object.  Therefore, we need to support this type of relaxation at
1039    the same time that we support the relaxation described above.  We
1040    use the high bit of the subtype field to distinguish these cases.
1041
1042    The information we store for this type of relaxation is the
1043    argument code found in the opcode file for this relocation, whether
1044    the user explicitly requested a small or extended form, and whether
1045    the relocation is in a jump or jal delay slot.  That tells us the
1046    size of the value, and how it should be stored.  We also store
1047    whether the fragment is considered to be extended or not.  We also
1048    store whether this is known to be a branch to a different section,
1049    whether we have tried to relax this frag yet, and whether we have
1050    ever extended a PC relative fragment because of a shift count.  */
1051 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1052   (0x80000000                                                   \
1053    | ((type) & 0xff)                                            \
1054    | ((small) ? 0x100 : 0)                                      \
1055    | ((ext) ? 0x200 : 0)                                        \
1056    | ((dslot) ? 0x400 : 0)                                      \
1057    | ((jal_dslot) ? 0x800 : 0))
1058 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1059 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1060 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1061 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1062 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1063 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1064 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1065 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1066 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1067 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1068 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1069 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1070
1071 /* For microMIPS code, we use relaxation similar to one we use for
1072    MIPS16 code.  Some instructions that take immediate values support
1073    two encodings: a small one which takes some small value, and a
1074    larger one which takes a 16 bit value.  As some branches also follow
1075    this pattern, relaxing these values is required.
1076
1077    We can assemble both microMIPS and normal MIPS code in a single
1078    object.  Therefore, we need to support this type of relaxation at
1079    the same time that we support the relaxation described above.  We
1080    use one of the high bits of the subtype field to distinguish these
1081    cases.
1082
1083    The information we store for this type of relaxation is the argument
1084    code found in the opcode file for this relocation, the register
1085    selected as the assembler temporary, whether the branch is
1086    unconditional, whether it is compact, whether it stores the link
1087    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1088    branches to a sequence of instructions is enabled, and whether the
1089    displacement of a branch is too large to fit as an immediate argument
1090    of a 16-bit and a 32-bit branch, respectively.  */
1091 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1092                                relax32, toofar16, toofar32)     \
1093   (0x40000000                                                   \
1094    | ((type) & 0xff)                                            \
1095    | (((at) & 0x1f) << 8)                                       \
1096    | ((uncond) ? 0x2000 : 0)                                    \
1097    | ((compact) ? 0x4000 : 0)                                   \
1098    | ((link) ? 0x8000 : 0)                                      \
1099    | ((relax32) ? 0x10000 : 0)                                  \
1100    | ((toofar16) ? 0x20000 : 0)                                 \
1101    | ((toofar32) ? 0x40000 : 0))
1102 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1103 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1104 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1105 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1106 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1107 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1108 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1109
1110 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1111 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1112 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1113 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1114 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1115 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1116
1117 /* Sign-extend 16-bit value X.  */
1118 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1119
1120 /* Is the given value a sign-extended 32-bit value?  */
1121 #define IS_SEXT_32BIT_NUM(x)                                            \
1122   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1123    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1124
1125 /* Is the given value a sign-extended 16-bit value?  */
1126 #define IS_SEXT_16BIT_NUM(x)                                            \
1127   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1128    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1129
1130 /* Is the given value a sign-extended 12-bit value?  */
1131 #define IS_SEXT_12BIT_NUM(x)                                            \
1132   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1133
1134 /* Is the given value a sign-extended 9-bit value?  */
1135 #define IS_SEXT_9BIT_NUM(x)                                             \
1136   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1137
1138 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1139 #define IS_ZEXT_32BIT_NUM(x)                                            \
1140   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1141    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1142
1143 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1144    SHIFT places.  */
1145 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1146   (((STRUCT) >> (SHIFT)) & (MASK))
1147
1148 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1149 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1150   (!(MICROMIPS) \
1151    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1152    : EXTRACT_BITS ((INSN).insn_opcode, \
1153                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1154 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1155   EXTRACT_BITS ((INSN).insn_opcode, \
1156                 MIPS16OP_MASK_##FIELD, \
1157                 MIPS16OP_SH_##FIELD)
1158
1159 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1160 #define MIPS16_EXTEND (0xf000U << 16)
1161 \f
1162 /* Whether or not we are emitting a branch-likely macro.  */
1163 static bfd_boolean emit_branch_likely_macro = FALSE;
1164
1165 /* Global variables used when generating relaxable macros.  See the
1166    comment above RELAX_ENCODE for more details about how relaxation
1167    is used.  */
1168 static struct {
1169   /* 0 if we're not emitting a relaxable macro.
1170      1 if we're emitting the first of the two relaxation alternatives.
1171      2 if we're emitting the second alternative.  */
1172   int sequence;
1173
1174   /* The first relaxable fixup in the current frag.  (In other words,
1175      the first fixup that refers to relaxable code.)  */
1176   fixS *first_fixup;
1177
1178   /* sizes[0] says how many bytes of the first alternative are stored in
1179      the current frag.  Likewise sizes[1] for the second alternative.  */
1180   unsigned int sizes[2];
1181
1182   /* The symbol on which the choice of sequence depends.  */
1183   symbolS *symbol;
1184 } mips_relax;
1185 \f
1186 /* Global variables used to decide whether a macro needs a warning.  */
1187 static struct {
1188   /* True if the macro is in a branch delay slot.  */
1189   bfd_boolean delay_slot_p;
1190
1191   /* Set to the length in bytes required if the macro is in a delay slot
1192      that requires a specific length of instruction, otherwise zero.  */
1193   unsigned int delay_slot_length;
1194
1195   /* For relaxable macros, sizes[0] is the length of the first alternative
1196      in bytes and sizes[1] is the length of the second alternative.
1197      For non-relaxable macros, both elements give the length of the
1198      macro in bytes.  */
1199   unsigned int sizes[2];
1200
1201   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1202      instruction of the first alternative in bytes and first_insn_sizes[1]
1203      is the length of the first instruction of the second alternative.
1204      For non-relaxable macros, both elements give the length of the first
1205      instruction in bytes.
1206
1207      Set to zero if we haven't yet seen the first instruction.  */
1208   unsigned int first_insn_sizes[2];
1209
1210   /* For relaxable macros, insns[0] is the number of instructions for the
1211      first alternative and insns[1] is the number of instructions for the
1212      second alternative.
1213
1214      For non-relaxable macros, both elements give the number of
1215      instructions for the macro.  */
1216   unsigned int insns[2];
1217
1218   /* The first variant frag for this macro.  */
1219   fragS *first_frag;
1220 } mips_macro_warning;
1221 \f
1222 /* Prototypes for static functions.  */
1223
1224 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1225
1226 static void append_insn
1227   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1228    bfd_boolean expansionp);
1229 static void mips_no_prev_insn (void);
1230 static void macro_build (expressionS *, const char *, const char *, ...);
1231 static void mips16_macro_build
1232   (expressionS *, const char *, const char *, va_list *);
1233 static void load_register (int, expressionS *, int);
1234 static void macro_start (void);
1235 static void macro_end (void);
1236 static void macro (struct mips_cl_insn *ip, char *str);
1237 static void mips16_macro (struct mips_cl_insn * ip);
1238 static void mips_ip (char *str, struct mips_cl_insn * ip);
1239 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1240 static void mips16_immed
1241   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1242    unsigned int, unsigned long *);
1243 static size_t my_getSmallExpression
1244   (expressionS *, bfd_reloc_code_real_type *, char *);
1245 static void my_getExpression (expressionS *, char *);
1246 static void s_align (int);
1247 static void s_change_sec (int);
1248 static void s_change_section (int);
1249 static void s_cons (int);
1250 static void s_float_cons (int);
1251 static void s_mips_globl (int);
1252 static void s_option (int);
1253 static void s_mipsset (int);
1254 static void s_abicalls (int);
1255 static void s_cpload (int);
1256 static void s_cpsetup (int);
1257 static void s_cplocal (int);
1258 static void s_cprestore (int);
1259 static void s_cpreturn (int);
1260 static void s_dtprelword (int);
1261 static void s_dtpreldword (int);
1262 static void s_tprelword (int);
1263 static void s_tpreldword (int);
1264 static void s_gpvalue (int);
1265 static void s_gpword (int);
1266 static void s_gpdword (int);
1267 static void s_ehword (int);
1268 static void s_cpadd (int);
1269 static void s_insn (int);
1270 static void s_nan (int);
1271 static void md_obj_begin (void);
1272 static void md_obj_end (void);
1273 static void s_mips_ent (int);
1274 static void s_mips_end (int);
1275 static void s_mips_frame (int);
1276 static void s_mips_mask (int reg_type);
1277 static void s_mips_stab (int);
1278 static void s_mips_weakext (int);
1279 static void s_mips_file (int);
1280 static void s_mips_loc (int);
1281 static bfd_boolean pic_need_relax (symbolS *, asection *);
1282 static int relaxed_branch_length (fragS *, asection *, int);
1283 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1284 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1285
1286 /* Table and functions used to map between CPU/ISA names, and
1287    ISA levels, and CPU numbers.  */
1288
1289 struct mips_cpu_info
1290 {
1291   const char *name;           /* CPU or ISA name.  */
1292   int flags;                  /* MIPS_CPU_* flags.  */
1293   int ase;                    /* Set of ASEs implemented by the CPU.  */
1294   int isa;                    /* ISA level.  */
1295   int cpu;                    /* CPU number (default CPU if ISA).  */
1296 };
1297
1298 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1299
1300 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1301 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1302 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1303 \f
1304 /* Command-line options.  */
1305 const char *md_shortopts = "O::g::G:";
1306
1307 enum options
1308   {
1309     OPTION_MARCH = OPTION_MD_BASE,
1310     OPTION_MTUNE,
1311     OPTION_MIPS1,
1312     OPTION_MIPS2,
1313     OPTION_MIPS3,
1314     OPTION_MIPS4,
1315     OPTION_MIPS5,
1316     OPTION_MIPS32,
1317     OPTION_MIPS64,
1318     OPTION_MIPS32R2,
1319     OPTION_MIPS64R2,
1320     OPTION_MIPS16,
1321     OPTION_NO_MIPS16,
1322     OPTION_MIPS3D,
1323     OPTION_NO_MIPS3D,
1324     OPTION_MDMX,
1325     OPTION_NO_MDMX,
1326     OPTION_DSP,
1327     OPTION_NO_DSP,
1328     OPTION_MT,
1329     OPTION_NO_MT,
1330     OPTION_VIRT,
1331     OPTION_NO_VIRT,
1332     OPTION_SMARTMIPS,
1333     OPTION_NO_SMARTMIPS,
1334     OPTION_DSPR2,
1335     OPTION_NO_DSPR2,
1336     OPTION_EVA,
1337     OPTION_NO_EVA,
1338     OPTION_MICROMIPS,
1339     OPTION_NO_MICROMIPS,
1340     OPTION_MCU,
1341     OPTION_NO_MCU,
1342     OPTION_COMPAT_ARCH_BASE,
1343     OPTION_M4650,
1344     OPTION_NO_M4650,
1345     OPTION_M4010,
1346     OPTION_NO_M4010,
1347     OPTION_M4100,
1348     OPTION_NO_M4100,
1349     OPTION_M3900,
1350     OPTION_NO_M3900,
1351     OPTION_M7000_HILO_FIX,
1352     OPTION_MNO_7000_HILO_FIX,
1353     OPTION_FIX_24K,
1354     OPTION_NO_FIX_24K,
1355     OPTION_FIX_LOONGSON2F_JUMP,
1356     OPTION_NO_FIX_LOONGSON2F_JUMP,
1357     OPTION_FIX_LOONGSON2F_NOP,
1358     OPTION_NO_FIX_LOONGSON2F_NOP,
1359     OPTION_FIX_VR4120,
1360     OPTION_NO_FIX_VR4120,
1361     OPTION_FIX_VR4130,
1362     OPTION_NO_FIX_VR4130,
1363     OPTION_FIX_CN63XXP1,
1364     OPTION_NO_FIX_CN63XXP1,
1365     OPTION_TRAP,
1366     OPTION_BREAK,
1367     OPTION_EB,
1368     OPTION_EL,
1369     OPTION_FP32,
1370     OPTION_GP32,
1371     OPTION_CONSTRUCT_FLOATS,
1372     OPTION_NO_CONSTRUCT_FLOATS,
1373     OPTION_FP64,
1374     OPTION_GP64,
1375     OPTION_RELAX_BRANCH,
1376     OPTION_NO_RELAX_BRANCH,
1377     OPTION_INSN32,
1378     OPTION_NO_INSN32,
1379     OPTION_MSHARED,
1380     OPTION_MNO_SHARED,
1381     OPTION_MSYM32,
1382     OPTION_MNO_SYM32,
1383     OPTION_SOFT_FLOAT,
1384     OPTION_HARD_FLOAT,
1385     OPTION_SINGLE_FLOAT,
1386     OPTION_DOUBLE_FLOAT,
1387     OPTION_32,
1388     OPTION_CALL_SHARED,
1389     OPTION_CALL_NONPIC,
1390     OPTION_NON_SHARED,
1391     OPTION_XGOT,
1392     OPTION_MABI,
1393     OPTION_N32,
1394     OPTION_64,
1395     OPTION_MDEBUG,
1396     OPTION_NO_MDEBUG,
1397     OPTION_PDR,
1398     OPTION_NO_PDR,
1399     OPTION_MVXWORKS_PIC,
1400     OPTION_NAN,
1401     OPTION_END_OF_ENUM
1402   };
1403
1404 struct option md_longopts[] =
1405 {
1406   /* Options which specify architecture.  */
1407   {"march", required_argument, NULL, OPTION_MARCH},
1408   {"mtune", required_argument, NULL, OPTION_MTUNE},
1409   {"mips0", no_argument, NULL, OPTION_MIPS1},
1410   {"mips1", no_argument, NULL, OPTION_MIPS1},
1411   {"mips2", no_argument, NULL, OPTION_MIPS2},
1412   {"mips3", no_argument, NULL, OPTION_MIPS3},
1413   {"mips4", no_argument, NULL, OPTION_MIPS4},
1414   {"mips5", no_argument, NULL, OPTION_MIPS5},
1415   {"mips32", no_argument, NULL, OPTION_MIPS32},
1416   {"mips64", no_argument, NULL, OPTION_MIPS64},
1417   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1418   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1419
1420   /* Options which specify Application Specific Extensions (ASEs).  */
1421   {"mips16", no_argument, NULL, OPTION_MIPS16},
1422   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1423   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1424   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1425   {"mdmx", no_argument, NULL, OPTION_MDMX},
1426   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1427   {"mdsp", no_argument, NULL, OPTION_DSP},
1428   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1429   {"mmt", no_argument, NULL, OPTION_MT},
1430   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1431   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1432   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1433   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1434   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1435   {"meva", no_argument, NULL, OPTION_EVA},
1436   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1437   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1438   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1439   {"mmcu", no_argument, NULL, OPTION_MCU},
1440   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1441   {"mvirt", no_argument, NULL, OPTION_VIRT},
1442   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1443
1444   /* Old-style architecture options.  Don't add more of these.  */
1445   {"m4650", no_argument, NULL, OPTION_M4650},
1446   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1447   {"m4010", no_argument, NULL, OPTION_M4010},
1448   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1449   {"m4100", no_argument, NULL, OPTION_M4100},
1450   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1451   {"m3900", no_argument, NULL, OPTION_M3900},
1452   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1453
1454   /* Options which enable bug fixes.  */
1455   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1456   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1457   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1458   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1459   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1460   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1461   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1462   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1463   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1464   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1465   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1466   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1467   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1468   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1469   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1470
1471   /* Miscellaneous options.  */
1472   {"trap", no_argument, NULL, OPTION_TRAP},
1473   {"no-break", no_argument, NULL, OPTION_TRAP},
1474   {"break", no_argument, NULL, OPTION_BREAK},
1475   {"no-trap", no_argument, NULL, OPTION_BREAK},
1476   {"EB", no_argument, NULL, OPTION_EB},
1477   {"EL", no_argument, NULL, OPTION_EL},
1478   {"mfp32", no_argument, NULL, OPTION_FP32},
1479   {"mgp32", no_argument, NULL, OPTION_GP32},
1480   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1481   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1482   {"mfp64", no_argument, NULL, OPTION_FP64},
1483   {"mgp64", no_argument, NULL, OPTION_GP64},
1484   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1485   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1486   {"minsn32", no_argument, NULL, OPTION_INSN32},
1487   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1488   {"mshared", no_argument, NULL, OPTION_MSHARED},
1489   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1490   {"msym32", no_argument, NULL, OPTION_MSYM32},
1491   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1492   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1493   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1494   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1495   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1496
1497   /* Strictly speaking this next option is ELF specific,
1498      but we allow it for other ports as well in order to
1499      make testing easier.  */
1500   {"32", no_argument, NULL, OPTION_32},
1501
1502   /* ELF-specific options.  */
1503   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1504   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1505   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1506   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1507   {"xgot", no_argument, NULL, OPTION_XGOT},
1508   {"mabi", required_argument, NULL, OPTION_MABI},
1509   {"n32", no_argument, NULL, OPTION_N32},
1510   {"64", no_argument, NULL, OPTION_64},
1511   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1512   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1513   {"mpdr", no_argument, NULL, OPTION_PDR},
1514   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1515   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1516   {"mnan", required_argument, NULL, OPTION_NAN},
1517
1518   {NULL, no_argument, NULL, 0}
1519 };
1520 size_t md_longopts_size = sizeof (md_longopts);
1521 \f
1522 /* Information about either an Application Specific Extension or an
1523    optional architecture feature that, for simplicity, we treat in the
1524    same way as an ASE.  */
1525 struct mips_ase
1526 {
1527   /* The name of the ASE, used in both the command-line and .set options.  */
1528   const char *name;
1529
1530   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1531      and 64-bit architectures, the flags here refer to the subset that
1532      is available on both.  */
1533   unsigned int flags;
1534
1535   /* The ASE_* flag used for instructions that are available on 64-bit
1536      architectures but that are not included in FLAGS.  */
1537   unsigned int flags64;
1538
1539   /* The command-line options that turn the ASE on and off.  */
1540   int option_on;
1541   int option_off;
1542
1543   /* The minimum required architecture revisions for MIPS32, MIPS64,
1544      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1545   int mips32_rev;
1546   int mips64_rev;
1547   int micromips32_rev;
1548   int micromips64_rev;
1549 };
1550
1551 /* A table of all supported ASEs.  */
1552 static const struct mips_ase mips_ases[] = {
1553   { "dsp", ASE_DSP, ASE_DSP64,
1554     OPTION_DSP, OPTION_NO_DSP,
1555     2, 2, 2, 2 },
1556
1557   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1558     OPTION_DSPR2, OPTION_NO_DSPR2,
1559     2, 2, 2, 2 },
1560
1561   { "eva", ASE_EVA, 0,
1562     OPTION_EVA, OPTION_NO_EVA,
1563     2, 2, 2, 2 },
1564
1565   { "mcu", ASE_MCU, 0,
1566     OPTION_MCU, OPTION_NO_MCU,
1567     2, 2, 2, 2 },
1568
1569   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1570   { "mdmx", ASE_MDMX, 0,
1571     OPTION_MDMX, OPTION_NO_MDMX,
1572     -1, 1, -1, -1 },
1573
1574   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1575   { "mips3d", ASE_MIPS3D, 0,
1576     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1577     2, 1, -1, -1 },
1578
1579   { "mt", ASE_MT, 0,
1580     OPTION_MT, OPTION_NO_MT,
1581     2, 2, -1, -1 },
1582
1583   { "smartmips", ASE_SMARTMIPS, 0,
1584     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1585     1, -1, -1, -1 },
1586
1587   { "virt", ASE_VIRT, ASE_VIRT64,
1588     OPTION_VIRT, OPTION_NO_VIRT,
1589     2, 2, 2, 2 }
1590 };
1591
1592 /* The set of ASEs that require -mfp64.  */
1593 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1594
1595 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1596 static const unsigned int mips_ase_groups[] = {
1597   ASE_DSP | ASE_DSPR2
1598 };
1599 \f
1600 /* Pseudo-op table.
1601
1602    The following pseudo-ops from the Kane and Heinrich MIPS book
1603    should be defined here, but are currently unsupported: .alias,
1604    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1605
1606    The following pseudo-ops from the Kane and Heinrich MIPS book are
1607    specific to the type of debugging information being generated, and
1608    should be defined by the object format: .aent, .begin, .bend,
1609    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1610    .vreg.
1611
1612    The following pseudo-ops from the Kane and Heinrich MIPS book are
1613    not MIPS CPU specific, but are also not specific to the object file
1614    format.  This file is probably the best place to define them, but
1615    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1616
1617 static const pseudo_typeS mips_pseudo_table[] =
1618 {
1619   /* MIPS specific pseudo-ops.  */
1620   {"option", s_option, 0},
1621   {"set", s_mipsset, 0},
1622   {"rdata", s_change_sec, 'r'},
1623   {"sdata", s_change_sec, 's'},
1624   {"livereg", s_ignore, 0},
1625   {"abicalls", s_abicalls, 0},
1626   {"cpload", s_cpload, 0},
1627   {"cpsetup", s_cpsetup, 0},
1628   {"cplocal", s_cplocal, 0},
1629   {"cprestore", s_cprestore, 0},
1630   {"cpreturn", s_cpreturn, 0},
1631   {"dtprelword", s_dtprelword, 0},
1632   {"dtpreldword", s_dtpreldword, 0},
1633   {"tprelword", s_tprelword, 0},
1634   {"tpreldword", s_tpreldword, 0},
1635   {"gpvalue", s_gpvalue, 0},
1636   {"gpword", s_gpword, 0},
1637   {"gpdword", s_gpdword, 0},
1638   {"ehword", s_ehword, 0},
1639   {"cpadd", s_cpadd, 0},
1640   {"insn", s_insn, 0},
1641   {"nan", s_nan, 0},
1642
1643   /* Relatively generic pseudo-ops that happen to be used on MIPS
1644      chips.  */
1645   {"asciiz", stringer, 8 + 1},
1646   {"bss", s_change_sec, 'b'},
1647   {"err", s_err, 0},
1648   {"half", s_cons, 1},
1649   {"dword", s_cons, 3},
1650   {"weakext", s_mips_weakext, 0},
1651   {"origin", s_org, 0},
1652   {"repeat", s_rept, 0},
1653
1654   /* For MIPS this is non-standard, but we define it for consistency.  */
1655   {"sbss", s_change_sec, 'B'},
1656
1657   /* These pseudo-ops are defined in read.c, but must be overridden
1658      here for one reason or another.  */
1659   {"align", s_align, 0},
1660   {"byte", s_cons, 0},
1661   {"data", s_change_sec, 'd'},
1662   {"double", s_float_cons, 'd'},
1663   {"float", s_float_cons, 'f'},
1664   {"globl", s_mips_globl, 0},
1665   {"global", s_mips_globl, 0},
1666   {"hword", s_cons, 1},
1667   {"int", s_cons, 2},
1668   {"long", s_cons, 2},
1669   {"octa", s_cons, 4},
1670   {"quad", s_cons, 3},
1671   {"section", s_change_section, 0},
1672   {"short", s_cons, 1},
1673   {"single", s_float_cons, 'f'},
1674   {"stabd", s_mips_stab, 'd'},
1675   {"stabn", s_mips_stab, 'n'},
1676   {"stabs", s_mips_stab, 's'},
1677   {"text", s_change_sec, 't'},
1678   {"word", s_cons, 2},
1679
1680   { "extern", ecoff_directive_extern, 0},
1681
1682   { NULL, NULL, 0 },
1683 };
1684
1685 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1686 {
1687   /* These pseudo-ops should be defined by the object file format.
1688      However, a.out doesn't support them, so we have versions here.  */
1689   {"aent", s_mips_ent, 1},
1690   {"bgnb", s_ignore, 0},
1691   {"end", s_mips_end, 0},
1692   {"endb", s_ignore, 0},
1693   {"ent", s_mips_ent, 0},
1694   {"file", s_mips_file, 0},
1695   {"fmask", s_mips_mask, 'F'},
1696   {"frame", s_mips_frame, 0},
1697   {"loc", s_mips_loc, 0},
1698   {"mask", s_mips_mask, 'R'},
1699   {"verstamp", s_ignore, 0},
1700   { NULL, NULL, 0 },
1701 };
1702
1703 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1704    purpose of the `.dc.a' internal pseudo-op.  */
1705
1706 int
1707 mips_address_bytes (void)
1708 {
1709   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1710 }
1711
1712 extern void pop_insert (const pseudo_typeS *);
1713
1714 void
1715 mips_pop_insert (void)
1716 {
1717   pop_insert (mips_pseudo_table);
1718   if (! ECOFF_DEBUGGING)
1719     pop_insert (mips_nonecoff_pseudo_table);
1720 }
1721 \f
1722 /* Symbols labelling the current insn.  */
1723
1724 struct insn_label_list
1725 {
1726   struct insn_label_list *next;
1727   symbolS *label;
1728 };
1729
1730 static struct insn_label_list *free_insn_labels;
1731 #define label_list tc_segment_info_data.labels
1732
1733 static void mips_clear_insn_labels (void);
1734 static void mips_mark_labels (void);
1735 static void mips_compressed_mark_labels (void);
1736
1737 static inline void
1738 mips_clear_insn_labels (void)
1739 {
1740   register struct insn_label_list **pl;
1741   segment_info_type *si;
1742
1743   if (now_seg)
1744     {
1745       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1746         ;
1747       
1748       si = seg_info (now_seg);
1749       *pl = si->label_list;
1750       si->label_list = NULL;
1751     }
1752 }
1753
1754 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1755
1756 static inline void
1757 mips_mark_labels (void)
1758 {
1759   if (HAVE_CODE_COMPRESSION)
1760     mips_compressed_mark_labels ();
1761 }
1762 \f
1763 static char *expr_end;
1764
1765 /* Expressions which appear in macro instructions.  These are set by
1766    mips_ip and read by macro.  */
1767
1768 static expressionS imm_expr;
1769 static expressionS imm2_expr;
1770
1771 /* The relocatable field in an instruction and the relocs associated
1772    with it.  These variables are used for instructions like LUI and
1773    JAL as well as true offsets.  They are also used for address
1774    operands in macros.  */
1775
1776 static expressionS offset_expr;
1777 static bfd_reloc_code_real_type offset_reloc[3]
1778   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1779
1780 /* This is set to the resulting size of the instruction to be produced
1781    by mips16_ip if an explicit extension is used or by mips_ip if an
1782    explicit size is supplied.  */
1783
1784 static unsigned int forced_insn_length;
1785
1786 /* True if we are assembling an instruction.  All dot symbols defined during
1787    this time should be treated as code labels.  */
1788
1789 static bfd_boolean mips_assembling_insn;
1790
1791 /* The pdr segment for per procedure frame/regmask info.  Not used for
1792    ECOFF debugging.  */
1793
1794 static segT pdr_seg;
1795
1796 /* The default target format to use.  */
1797
1798 #if defined (TE_FreeBSD)
1799 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1800 #elif defined (TE_TMIPS)
1801 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1802 #else
1803 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1804 #endif
1805
1806 const char *
1807 mips_target_format (void)
1808 {
1809   switch (OUTPUT_FLAVOR)
1810     {
1811     case bfd_target_elf_flavour:
1812 #ifdef TE_VXWORKS
1813       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1814         return (target_big_endian
1815                 ? "elf32-bigmips-vxworks"
1816                 : "elf32-littlemips-vxworks");
1817 #endif
1818       return (target_big_endian
1819               ? (HAVE_64BIT_OBJECTS
1820                  ? ELF_TARGET ("elf64-", "big")
1821                  : (HAVE_NEWABI
1822                     ? ELF_TARGET ("elf32-n", "big")
1823                     : ELF_TARGET ("elf32-", "big")))
1824               : (HAVE_64BIT_OBJECTS
1825                  ? ELF_TARGET ("elf64-", "little")
1826                  : (HAVE_NEWABI
1827                     ? ELF_TARGET ("elf32-n", "little")
1828                     : ELF_TARGET ("elf32-", "little"))));
1829     default:
1830       abort ();
1831       return NULL;
1832     }
1833 }
1834
1835 /* Return the ISA revision that is currently in use, or 0 if we are
1836    generating code for MIPS V or below.  */
1837
1838 static int
1839 mips_isa_rev (void)
1840 {
1841   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1842     return 2;
1843
1844   /* microMIPS implies revision 2 or above.  */
1845   if (mips_opts.micromips)
1846     return 2;
1847
1848   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1849     return 1;
1850
1851   return 0;
1852 }
1853
1854 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1855
1856 static unsigned int
1857 mips_ase_mask (unsigned int flags)
1858 {
1859   unsigned int i;
1860
1861   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1862     if (flags & mips_ase_groups[i])
1863       flags |= mips_ase_groups[i];
1864   return flags;
1865 }
1866
1867 /* Check whether the current ISA supports ASE.  Issue a warning if
1868    appropriate.  */
1869
1870 static void
1871 mips_check_isa_supports_ase (const struct mips_ase *ase)
1872 {
1873   const char *base;
1874   int min_rev, size;
1875   static unsigned int warned_isa;
1876   static unsigned int warned_fp32;
1877
1878   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1879     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1880   else
1881     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1882   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1883       && (warned_isa & ase->flags) != ase->flags)
1884     {
1885       warned_isa |= ase->flags;
1886       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1887       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1888       if (min_rev < 0)
1889         as_warn (_("The %d-bit %s architecture does not support the"
1890                    " `%s' extension"), size, base, ase->name);
1891       else
1892         as_warn (_("The `%s' extension requires %s%d revision %d or greater"),
1893                  ase->name, base, size, min_rev);
1894     }
1895   if ((ase->flags & FP64_ASES)
1896       && mips_opts.fp32
1897       && (warned_fp32 & ase->flags) != ase->flags)
1898     {
1899       warned_fp32 |= ase->flags;
1900       as_warn (_("The `%s' extension requires 64-bit FPRs"), ase->name);
1901     }
1902 }
1903
1904 /* Check all enabled ASEs to see whether they are supported by the
1905    chosen architecture.  */
1906
1907 static void
1908 mips_check_isa_supports_ases (void)
1909 {
1910   unsigned int i, mask;
1911
1912   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1913     {
1914       mask = mips_ase_mask (mips_ases[i].flags);
1915       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1916         mips_check_isa_supports_ase (&mips_ases[i]);
1917     }
1918 }
1919
1920 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1921    that were affected.  */
1922
1923 static unsigned int
1924 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1925 {
1926   unsigned int mask;
1927
1928   mask = mips_ase_mask (ase->flags);
1929   mips_opts.ase &= ~mask;
1930   if (enabled_p)
1931     mips_opts.ase |= ase->flags;
1932   return mask;
1933 }
1934
1935 /* Return the ASE called NAME, or null if none.  */
1936
1937 static const struct mips_ase *
1938 mips_lookup_ase (const char *name)
1939 {
1940   unsigned int i;
1941
1942   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1943     if (strcmp (name, mips_ases[i].name) == 0)
1944       return &mips_ases[i];
1945   return NULL;
1946 }
1947
1948 /* Return the length of a microMIPS instruction in bytes.  If bits of
1949    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1950    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1951    major opcode) will require further modifications to the opcode
1952    table.  */
1953
1954 static inline unsigned int
1955 micromips_insn_length (const struct mips_opcode *mo)
1956 {
1957   return (mo->mask >> 16) == 0 ? 2 : 4;
1958 }
1959
1960 /* Return the length of MIPS16 instruction OPCODE.  */
1961
1962 static inline unsigned int
1963 mips16_opcode_length (unsigned long opcode)
1964 {
1965   return (opcode >> 16) == 0 ? 2 : 4;
1966 }
1967
1968 /* Return the length of instruction INSN.  */
1969
1970 static inline unsigned int
1971 insn_length (const struct mips_cl_insn *insn)
1972 {
1973   if (mips_opts.micromips)
1974     return micromips_insn_length (insn->insn_mo);
1975   else if (mips_opts.mips16)
1976     return mips16_opcode_length (insn->insn_opcode);
1977   else
1978     return 4;
1979 }
1980
1981 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1982
1983 static void
1984 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1985 {
1986   size_t i;
1987
1988   insn->insn_mo = mo;
1989   insn->insn_opcode = mo->match;
1990   insn->frag = NULL;
1991   insn->where = 0;
1992   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1993     insn->fixp[i] = NULL;
1994   insn->fixed_p = (mips_opts.noreorder > 0);
1995   insn->noreorder_p = (mips_opts.noreorder > 0);
1996   insn->mips16_absolute_jump_p = 0;
1997   insn->complete_p = 0;
1998   insn->cleared_p = 0;
1999 }
2000
2001 /* Get a list of all the operands in INSN.  */
2002
2003 static const struct mips_operand_array *
2004 insn_operands (const struct mips_cl_insn *insn)
2005 {
2006   if (insn->insn_mo >= &mips_opcodes[0]
2007       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2008     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2009
2010   if (insn->insn_mo >= &mips16_opcodes[0]
2011       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2012     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2013
2014   if (insn->insn_mo >= &micromips_opcodes[0]
2015       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2016     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2017
2018   abort ();
2019 }
2020
2021 /* Get a description of operand OPNO of INSN.  */
2022
2023 static const struct mips_operand *
2024 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2025 {
2026   const struct mips_operand_array *operands;
2027
2028   operands = insn_operands (insn);
2029   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2030     abort ();
2031   return operands->operand[opno];
2032 }
2033
2034 /* Install UVAL as the value of OPERAND in INSN.  */
2035
2036 static inline void
2037 insn_insert_operand (struct mips_cl_insn *insn,
2038                      const struct mips_operand *operand, unsigned int uval)
2039 {
2040   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2041 }
2042
2043 /* Extract the value of OPERAND from INSN.  */
2044
2045 static inline unsigned
2046 insn_extract_operand (const struct mips_cl_insn *insn,
2047                       const struct mips_operand *operand)
2048 {
2049   return mips_extract_operand (operand, insn->insn_opcode);
2050 }
2051
2052 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2053
2054 static void
2055 mips_record_compressed_mode (void)
2056 {
2057   segment_info_type *si;
2058
2059   si = seg_info (now_seg);
2060   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2061     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2062   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2063     si->tc_segment_info_data.micromips = mips_opts.micromips;
2064 }
2065
2066 /* Read a standard MIPS instruction from BUF.  */
2067
2068 static unsigned long
2069 read_insn (char *buf)
2070 {
2071   if (target_big_endian)
2072     return bfd_getb32 ((bfd_byte *) buf);
2073   else
2074     return bfd_getl32 ((bfd_byte *) buf);
2075 }
2076
2077 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2078    the next byte.  */
2079
2080 static char *
2081 write_insn (char *buf, unsigned int insn)
2082 {
2083   md_number_to_chars (buf, insn, 4);
2084   return buf + 4;
2085 }
2086
2087 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2088    has length LENGTH.  */
2089
2090 static unsigned long
2091 read_compressed_insn (char *buf, unsigned int length)
2092 {
2093   unsigned long insn;
2094   unsigned int i;
2095
2096   insn = 0;
2097   for (i = 0; i < length; i += 2)
2098     {
2099       insn <<= 16;
2100       if (target_big_endian)
2101         insn |= bfd_getb16 ((char *) buf);
2102       else
2103         insn |= bfd_getl16 ((char *) buf);
2104       buf += 2;
2105     }
2106   return insn;
2107 }
2108
2109 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2110    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2111
2112 static char *
2113 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2114 {
2115   unsigned int i;
2116
2117   for (i = 0; i < length; i += 2)
2118     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2119   return buf + length;
2120 }
2121
2122 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2123
2124 static void
2125 install_insn (const struct mips_cl_insn *insn)
2126 {
2127   char *f = insn->frag->fr_literal + insn->where;
2128   if (HAVE_CODE_COMPRESSION)
2129     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2130   else
2131     write_insn (f, insn->insn_opcode);
2132   mips_record_compressed_mode ();
2133 }
2134
2135 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2136    and install the opcode in the new location.  */
2137
2138 static void
2139 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2140 {
2141   size_t i;
2142
2143   insn->frag = frag;
2144   insn->where = where;
2145   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2146     if (insn->fixp[i] != NULL)
2147       {
2148         insn->fixp[i]->fx_frag = frag;
2149         insn->fixp[i]->fx_where = where;
2150       }
2151   install_insn (insn);
2152 }
2153
2154 /* Add INSN to the end of the output.  */
2155
2156 static void
2157 add_fixed_insn (struct mips_cl_insn *insn)
2158 {
2159   char *f = frag_more (insn_length (insn));
2160   move_insn (insn, frag_now, f - frag_now->fr_literal);
2161 }
2162
2163 /* Start a variant frag and move INSN to the start of the variant part,
2164    marking it as fixed.  The other arguments are as for frag_var.  */
2165
2166 static void
2167 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2168                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2169 {
2170   frag_grow (max_chars);
2171   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2172   insn->fixed_p = 1;
2173   frag_var (rs_machine_dependent, max_chars, var,
2174             subtype, symbol, offset, NULL);
2175 }
2176
2177 /* Insert N copies of INSN into the history buffer, starting at
2178    position FIRST.  Neither FIRST nor N need to be clipped.  */
2179
2180 static void
2181 insert_into_history (unsigned int first, unsigned int n,
2182                      const struct mips_cl_insn *insn)
2183 {
2184   if (mips_relax.sequence != 2)
2185     {
2186       unsigned int i;
2187
2188       for (i = ARRAY_SIZE (history); i-- > first;)
2189         if (i >= first + n)
2190           history[i] = history[i - n];
2191         else
2192           history[i] = *insn;
2193     }
2194 }
2195
2196 /* Clear the error in insn_error.  */
2197
2198 static void
2199 clear_insn_error (void)
2200 {
2201   memset (&insn_error, 0, sizeof (insn_error));
2202 }
2203
2204 /* Possibly record error message MSG for the current instruction.
2205    If the error is about a particular argument, ARGNUM is the 1-based
2206    number of that argument, otherwise it is 0.  FORMAT is the format
2207    of MSG.  Return true if MSG was used, false if the current message
2208    was kept.  */
2209
2210 static bfd_boolean
2211 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2212                        const char *msg)
2213 {
2214   if (argnum == 0)
2215     {
2216       /* Give priority to errors against specific arguments, and to
2217          the first whole-instruction message.  */
2218       if (insn_error.msg)
2219         return FALSE;
2220     }
2221   else
2222     {
2223       /* Keep insn_error if it is against a later argument.  */
2224       if (argnum < insn_error.min_argnum)
2225         return FALSE;
2226
2227       /* If both errors are against the same argument but are different,
2228          give up on reporting a specific error for this argument.
2229          See the comment about mips_insn_error for details.  */
2230       if (argnum == insn_error.min_argnum
2231           && insn_error.msg
2232           && strcmp (insn_error.msg, msg) != 0)
2233         {
2234           insn_error.msg = 0;
2235           insn_error.min_argnum += 1;
2236           return FALSE;
2237         }
2238     }
2239   insn_error.min_argnum = argnum;
2240   insn_error.format = format;
2241   insn_error.msg = msg;
2242   return TRUE;
2243 }
2244
2245 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2246    as for set_insn_error_format.  */
2247
2248 static void
2249 set_insn_error (int argnum, const char *msg)
2250 {
2251   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2252 }
2253
2254 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2255    as for set_insn_error_format.  */
2256
2257 static void
2258 set_insn_error_i (int argnum, const char *msg, int i)
2259 {
2260   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2261     insn_error.u.i = i;
2262 }
2263
2264 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2265    are as for set_insn_error_format.  */
2266
2267 static void
2268 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2269 {
2270   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2271     {
2272       insn_error.u.ss[0] = s1;
2273       insn_error.u.ss[1] = s2;
2274     }
2275 }
2276
2277 /* Report the error in insn_error, which is against assembly code STR.  */
2278
2279 static void
2280 report_insn_error (const char *str)
2281 {
2282   const char *msg;
2283
2284   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2285   switch (insn_error.format)
2286     {
2287     case ERR_FMT_PLAIN:
2288       as_bad (msg, str);
2289       break;
2290
2291     case ERR_FMT_I:
2292       as_bad (msg, insn_error.u.i, str);
2293       break;
2294
2295     case ERR_FMT_SS:
2296       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2297       break;
2298     }
2299 }
2300
2301 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2302    the idea is to make it obvious at a glance that each errata is
2303    included.  */
2304
2305 static void
2306 init_vr4120_conflicts (void)
2307 {
2308 #define CONFLICT(FIRST, SECOND) \
2309     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2310
2311   /* Errata 21 - [D]DIV[U] after [D]MACC */
2312   CONFLICT (MACC, DIV);
2313   CONFLICT (DMACC, DIV);
2314
2315   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2316   CONFLICT (DMULT, DMULT);
2317   CONFLICT (DMULT, DMACC);
2318   CONFLICT (DMACC, DMULT);
2319   CONFLICT (DMACC, DMACC);
2320
2321   /* Errata 24 - MT{LO,HI} after [D]MACC */
2322   CONFLICT (MACC, MTHILO);
2323   CONFLICT (DMACC, MTHILO);
2324
2325   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2326      instruction is executed immediately after a MACC or DMACC
2327      instruction, the result of [either instruction] is incorrect."  */
2328   CONFLICT (MACC, MULT);
2329   CONFLICT (MACC, DMULT);
2330   CONFLICT (DMACC, MULT);
2331   CONFLICT (DMACC, DMULT);
2332
2333   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2334      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2335      DDIV or DDIVU instruction, the result of the MACC or
2336      DMACC instruction is incorrect.".  */
2337   CONFLICT (DMULT, MACC);
2338   CONFLICT (DMULT, DMACC);
2339   CONFLICT (DIV, MACC);
2340   CONFLICT (DIV, DMACC);
2341
2342 #undef CONFLICT
2343 }
2344
2345 struct regname {
2346   const char *name;
2347   unsigned int num;
2348 };
2349
2350 #define RNUM_MASK       0x00000ff
2351 #define RTYPE_MASK      0x0efff00
2352 #define RTYPE_NUM       0x0000100
2353 #define RTYPE_FPU       0x0000200
2354 #define RTYPE_FCC       0x0000400
2355 #define RTYPE_VEC       0x0000800
2356 #define RTYPE_GP        0x0001000
2357 #define RTYPE_CP0       0x0002000
2358 #define RTYPE_PC        0x0004000
2359 #define RTYPE_ACC       0x0008000
2360 #define RTYPE_CCC       0x0010000
2361 #define RTYPE_VI        0x0020000
2362 #define RTYPE_VF        0x0040000
2363 #define RTYPE_R5900_I   0x0080000
2364 #define RTYPE_R5900_Q   0x0100000
2365 #define RTYPE_R5900_R   0x0200000
2366 #define RTYPE_R5900_ACC 0x0400000
2367 #define RWARN           0x8000000
2368
2369 #define GENERIC_REGISTER_NUMBERS \
2370     {"$0",      RTYPE_NUM | 0},  \
2371     {"$1",      RTYPE_NUM | 1},  \
2372     {"$2",      RTYPE_NUM | 2},  \
2373     {"$3",      RTYPE_NUM | 3},  \
2374     {"$4",      RTYPE_NUM | 4},  \
2375     {"$5",      RTYPE_NUM | 5},  \
2376     {"$6",      RTYPE_NUM | 6},  \
2377     {"$7",      RTYPE_NUM | 7},  \
2378     {"$8",      RTYPE_NUM | 8},  \
2379     {"$9",      RTYPE_NUM | 9},  \
2380     {"$10",     RTYPE_NUM | 10}, \
2381     {"$11",     RTYPE_NUM | 11}, \
2382     {"$12",     RTYPE_NUM | 12}, \
2383     {"$13",     RTYPE_NUM | 13}, \
2384     {"$14",     RTYPE_NUM | 14}, \
2385     {"$15",     RTYPE_NUM | 15}, \
2386     {"$16",     RTYPE_NUM | 16}, \
2387     {"$17",     RTYPE_NUM | 17}, \
2388     {"$18",     RTYPE_NUM | 18}, \
2389     {"$19",     RTYPE_NUM | 19}, \
2390     {"$20",     RTYPE_NUM | 20}, \
2391     {"$21",     RTYPE_NUM | 21}, \
2392     {"$22",     RTYPE_NUM | 22}, \
2393     {"$23",     RTYPE_NUM | 23}, \
2394     {"$24",     RTYPE_NUM | 24}, \
2395     {"$25",     RTYPE_NUM | 25}, \
2396     {"$26",     RTYPE_NUM | 26}, \
2397     {"$27",     RTYPE_NUM | 27}, \
2398     {"$28",     RTYPE_NUM | 28}, \
2399     {"$29",     RTYPE_NUM | 29}, \
2400     {"$30",     RTYPE_NUM | 30}, \
2401     {"$31",     RTYPE_NUM | 31} 
2402
2403 #define FPU_REGISTER_NAMES       \
2404     {"$f0",     RTYPE_FPU | 0},  \
2405     {"$f1",     RTYPE_FPU | 1},  \
2406     {"$f2",     RTYPE_FPU | 2},  \
2407     {"$f3",     RTYPE_FPU | 3},  \
2408     {"$f4",     RTYPE_FPU | 4},  \
2409     {"$f5",     RTYPE_FPU | 5},  \
2410     {"$f6",     RTYPE_FPU | 6},  \
2411     {"$f7",     RTYPE_FPU | 7},  \
2412     {"$f8",     RTYPE_FPU | 8},  \
2413     {"$f9",     RTYPE_FPU | 9},  \
2414     {"$f10",    RTYPE_FPU | 10}, \
2415     {"$f11",    RTYPE_FPU | 11}, \
2416     {"$f12",    RTYPE_FPU | 12}, \
2417     {"$f13",    RTYPE_FPU | 13}, \
2418     {"$f14",    RTYPE_FPU | 14}, \
2419     {"$f15",    RTYPE_FPU | 15}, \
2420     {"$f16",    RTYPE_FPU | 16}, \
2421     {"$f17",    RTYPE_FPU | 17}, \
2422     {"$f18",    RTYPE_FPU | 18}, \
2423     {"$f19",    RTYPE_FPU | 19}, \
2424     {"$f20",    RTYPE_FPU | 20}, \
2425     {"$f21",    RTYPE_FPU | 21}, \
2426     {"$f22",    RTYPE_FPU | 22}, \
2427     {"$f23",    RTYPE_FPU | 23}, \
2428     {"$f24",    RTYPE_FPU | 24}, \
2429     {"$f25",    RTYPE_FPU | 25}, \
2430     {"$f26",    RTYPE_FPU | 26}, \
2431     {"$f27",    RTYPE_FPU | 27}, \
2432     {"$f28",    RTYPE_FPU | 28}, \
2433     {"$f29",    RTYPE_FPU | 29}, \
2434     {"$f30",    RTYPE_FPU | 30}, \
2435     {"$f31",    RTYPE_FPU | 31}
2436
2437 #define FPU_CONDITION_CODE_NAMES \
2438     {"$fcc0",   RTYPE_FCC | 0},  \
2439     {"$fcc1",   RTYPE_FCC | 1},  \
2440     {"$fcc2",   RTYPE_FCC | 2},  \
2441     {"$fcc3",   RTYPE_FCC | 3},  \
2442     {"$fcc4",   RTYPE_FCC | 4},  \
2443     {"$fcc5",   RTYPE_FCC | 5},  \
2444     {"$fcc6",   RTYPE_FCC | 6},  \
2445     {"$fcc7",   RTYPE_FCC | 7}
2446
2447 #define COPROC_CONDITION_CODE_NAMES         \
2448     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2449     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2450     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2451     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2452     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2453     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2454     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2455     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2456
2457 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2458     {"$a4",     RTYPE_GP | 8},  \
2459     {"$a5",     RTYPE_GP | 9},  \
2460     {"$a6",     RTYPE_GP | 10}, \
2461     {"$a7",     RTYPE_GP | 11}, \
2462     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2463     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2464     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2465     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2466     {"$t0",     RTYPE_GP | 12}, \
2467     {"$t1",     RTYPE_GP | 13}, \
2468     {"$t2",     RTYPE_GP | 14}, \
2469     {"$t3",     RTYPE_GP | 15}
2470
2471 #define O32_SYMBOLIC_REGISTER_NAMES \
2472     {"$t0",     RTYPE_GP | 8},  \
2473     {"$t1",     RTYPE_GP | 9},  \
2474     {"$t2",     RTYPE_GP | 10}, \
2475     {"$t3",     RTYPE_GP | 11}, \
2476     {"$t4",     RTYPE_GP | 12}, \
2477     {"$t5",     RTYPE_GP | 13}, \
2478     {"$t6",     RTYPE_GP | 14}, \
2479     {"$t7",     RTYPE_GP | 15}, \
2480     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2481     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2482     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2483     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2484
2485 /* Remaining symbolic register names */
2486 #define SYMBOLIC_REGISTER_NAMES \
2487     {"$zero",   RTYPE_GP | 0},  \
2488     {"$at",     RTYPE_GP | 1},  \
2489     {"$AT",     RTYPE_GP | 1},  \
2490     {"$v0",     RTYPE_GP | 2},  \
2491     {"$v1",     RTYPE_GP | 3},  \
2492     {"$a0",     RTYPE_GP | 4},  \
2493     {"$a1",     RTYPE_GP | 5},  \
2494     {"$a2",     RTYPE_GP | 6},  \
2495     {"$a3",     RTYPE_GP | 7},  \
2496     {"$s0",     RTYPE_GP | 16}, \
2497     {"$s1",     RTYPE_GP | 17}, \
2498     {"$s2",     RTYPE_GP | 18}, \
2499     {"$s3",     RTYPE_GP | 19}, \
2500     {"$s4",     RTYPE_GP | 20}, \
2501     {"$s5",     RTYPE_GP | 21}, \
2502     {"$s6",     RTYPE_GP | 22}, \
2503     {"$s7",     RTYPE_GP | 23}, \
2504     {"$t8",     RTYPE_GP | 24}, \
2505     {"$t9",     RTYPE_GP | 25}, \
2506     {"$k0",     RTYPE_GP | 26}, \
2507     {"$kt0",    RTYPE_GP | 26}, \
2508     {"$k1",     RTYPE_GP | 27}, \
2509     {"$kt1",    RTYPE_GP | 27}, \
2510     {"$gp",     RTYPE_GP | 28}, \
2511     {"$sp",     RTYPE_GP | 29}, \
2512     {"$s8",     RTYPE_GP | 30}, \
2513     {"$fp",     RTYPE_GP | 30}, \
2514     {"$ra",     RTYPE_GP | 31}
2515
2516 #define MIPS16_SPECIAL_REGISTER_NAMES \
2517     {"$pc",     RTYPE_PC | 0}
2518
2519 #define MDMX_VECTOR_REGISTER_NAMES \
2520     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2521     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2522     {"$v2",     RTYPE_VEC | 2},  \
2523     {"$v3",     RTYPE_VEC | 3},  \
2524     {"$v4",     RTYPE_VEC | 4},  \
2525     {"$v5",     RTYPE_VEC | 5},  \
2526     {"$v6",     RTYPE_VEC | 6},  \
2527     {"$v7",     RTYPE_VEC | 7},  \
2528     {"$v8",     RTYPE_VEC | 8},  \
2529     {"$v9",     RTYPE_VEC | 9},  \
2530     {"$v10",    RTYPE_VEC | 10}, \
2531     {"$v11",    RTYPE_VEC | 11}, \
2532     {"$v12",    RTYPE_VEC | 12}, \
2533     {"$v13",    RTYPE_VEC | 13}, \
2534     {"$v14",    RTYPE_VEC | 14}, \
2535     {"$v15",    RTYPE_VEC | 15}, \
2536     {"$v16",    RTYPE_VEC | 16}, \
2537     {"$v17",    RTYPE_VEC | 17}, \
2538     {"$v18",    RTYPE_VEC | 18}, \
2539     {"$v19",    RTYPE_VEC | 19}, \
2540     {"$v20",    RTYPE_VEC | 20}, \
2541     {"$v21",    RTYPE_VEC | 21}, \
2542     {"$v22",    RTYPE_VEC | 22}, \
2543     {"$v23",    RTYPE_VEC | 23}, \
2544     {"$v24",    RTYPE_VEC | 24}, \
2545     {"$v25",    RTYPE_VEC | 25}, \
2546     {"$v26",    RTYPE_VEC | 26}, \
2547     {"$v27",    RTYPE_VEC | 27}, \
2548     {"$v28",    RTYPE_VEC | 28}, \
2549     {"$v29",    RTYPE_VEC | 29}, \
2550     {"$v30",    RTYPE_VEC | 30}, \
2551     {"$v31",    RTYPE_VEC | 31}
2552
2553 #define R5900_I_NAMES \
2554     {"$I",      RTYPE_R5900_I | 0}
2555
2556 #define R5900_Q_NAMES \
2557     {"$Q",      RTYPE_R5900_Q | 0}
2558
2559 #define R5900_R_NAMES \
2560     {"$R",      RTYPE_R5900_R | 0}
2561
2562 #define R5900_ACC_NAMES \
2563     {"$ACC",    RTYPE_R5900_ACC | 0 }
2564
2565 #define MIPS_DSP_ACCUMULATOR_NAMES \
2566     {"$ac0",    RTYPE_ACC | 0}, \
2567     {"$ac1",    RTYPE_ACC | 1}, \
2568     {"$ac2",    RTYPE_ACC | 2}, \
2569     {"$ac3",    RTYPE_ACC | 3}
2570
2571 static const struct regname reg_names[] = {
2572   GENERIC_REGISTER_NUMBERS,
2573   FPU_REGISTER_NAMES,
2574   FPU_CONDITION_CODE_NAMES,
2575   COPROC_CONDITION_CODE_NAMES,
2576
2577   /* The $txx registers depends on the abi,
2578      these will be added later into the symbol table from
2579      one of the tables below once mips_abi is set after 
2580      parsing of arguments from the command line. */
2581   SYMBOLIC_REGISTER_NAMES,
2582
2583   MIPS16_SPECIAL_REGISTER_NAMES,
2584   MDMX_VECTOR_REGISTER_NAMES,
2585   R5900_I_NAMES,
2586   R5900_Q_NAMES,
2587   R5900_R_NAMES,
2588   R5900_ACC_NAMES,
2589   MIPS_DSP_ACCUMULATOR_NAMES,
2590   {0, 0}
2591 };
2592
2593 static const struct regname reg_names_o32[] = {
2594   O32_SYMBOLIC_REGISTER_NAMES,
2595   {0, 0}
2596 };
2597
2598 static const struct regname reg_names_n32n64[] = {
2599   N32N64_SYMBOLIC_REGISTER_NAMES,
2600   {0, 0}
2601 };
2602
2603 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2604    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2605    of these register symbols, return the associated vector register,
2606    otherwise return SYMVAL itself.  */
2607
2608 static unsigned int
2609 mips_prefer_vec_regno (unsigned int symval)
2610 {
2611   if ((symval & -2) == (RTYPE_GP | 2))
2612     return RTYPE_VEC | (symval & 1);
2613   return symval;
2614 }
2615
2616 /* Return true if string [S, E) is a valid register name, storing its
2617    symbol value in *SYMVAL_PTR if so.  */
2618
2619 static bfd_boolean
2620 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2621 {
2622   char save_c;
2623   symbolS *symbol;
2624
2625   /* Terminate name.  */
2626   save_c = *e;
2627   *e = '\0';
2628
2629   /* Look up the name.  */
2630   symbol = symbol_find (s);
2631   *e = save_c;
2632
2633   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2634     return FALSE;
2635
2636   *symval_ptr = S_GET_VALUE (symbol);
2637   return TRUE;
2638 }
2639
2640 /* Return true if the string at *SPTR is a valid register name.  Allow it
2641    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2642    is nonnull.
2643
2644    When returning true, move *SPTR past the register, store the
2645    register's symbol value in *SYMVAL_PTR and the channel mask in
2646    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2647    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2648    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2649
2650 static bfd_boolean
2651 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2652                      unsigned int *channels_ptr)
2653 {
2654   char *s, *e, *m;
2655   const char *q;
2656   unsigned int channels, symval, bit;
2657
2658   /* Find end of name.  */
2659   s = e = *sptr;
2660   if (is_name_beginner (*e))
2661     ++e;
2662   while (is_part_of_name (*e))
2663     ++e;
2664
2665   channels = 0;
2666   if (!mips_parse_register_1 (s, e, &symval))
2667     {
2668       if (!channels_ptr)
2669         return FALSE;
2670
2671       /* Eat characters from the end of the string that are valid
2672          channel suffixes.  The preceding register must be $ACC or
2673          end with a digit, so there is no ambiguity.  */
2674       bit = 1;
2675       m = e;
2676       for (q = "wzyx"; *q; q++, bit <<= 1)
2677         if (m > s && m[-1] == *q)
2678           {
2679             --m;
2680             channels |= bit;
2681           }
2682
2683       if (channels == 0
2684           || !mips_parse_register_1 (s, m, &symval)
2685           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2686         return FALSE;
2687     }
2688
2689   *sptr = e;
2690   *symval_ptr = symval;
2691   if (channels_ptr)
2692     *channels_ptr = channels;
2693   return TRUE;
2694 }
2695
2696 /* Check if SPTR points at a valid register specifier according to TYPES.
2697    If so, then return 1, advance S to consume the specifier and store
2698    the register's number in REGNOP, otherwise return 0.  */
2699
2700 static int
2701 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2702 {
2703   unsigned int regno;
2704
2705   if (mips_parse_register (s, &regno, NULL))
2706     {
2707       if (types & RTYPE_VEC)
2708         regno = mips_prefer_vec_regno (regno);
2709       if (regno & types)
2710         regno &= RNUM_MASK;
2711       else
2712         regno = ~0;
2713     }
2714   else
2715     {
2716       if (types & RWARN)
2717         as_warn (_("Unrecognized register name `%s'"), *s);
2718       regno = ~0;
2719     }
2720   if (regnop)
2721     *regnop = regno;
2722   return regno <= RNUM_MASK;
2723 }
2724
2725 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2726    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2727
2728 static char *
2729 mips_parse_vu0_channels (char *s, unsigned int *channels)
2730 {
2731   unsigned int i;
2732
2733   *channels = 0;
2734   for (i = 0; i < 4; i++)
2735     if (*s == "xyzw"[i])
2736       {
2737         *channels |= 1 << (3 - i);
2738         ++s;
2739       }
2740   return s;
2741 }
2742
2743 /* Token types for parsed operand lists.  */
2744 enum mips_operand_token_type {
2745   /* A plain register, e.g. $f2.  */
2746   OT_REG,
2747
2748   /* A 4-bit XYZW channel mask.  */
2749   OT_CHANNELS,
2750
2751   /* An element of a vector, e.g. $v0[1].  */
2752   OT_REG_ELEMENT,
2753
2754   /* A continuous range of registers, e.g. $s0-$s4.  */
2755   OT_REG_RANGE,
2756
2757   /* A (possibly relocated) expression.  */
2758   OT_INTEGER,
2759
2760   /* A floating-point value.  */
2761   OT_FLOAT,
2762
2763   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2764      before OT_REGs.  */
2765   OT_CHAR,
2766
2767   /* A doubled character, either "--" or "++".  */
2768   OT_DOUBLE_CHAR,
2769
2770   /* The end of the operand list.  */
2771   OT_END
2772 };
2773
2774 /* A parsed operand token.  */
2775 struct mips_operand_token
2776 {
2777   /* The type of token.  */
2778   enum mips_operand_token_type type;
2779   union
2780   {
2781     /* The register symbol value for an OT_REG.  */
2782     unsigned int regno;
2783
2784     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2785     unsigned int channels;
2786
2787     /* The register symbol value and index for an OT_REG_ELEMENT.  */
2788     struct {
2789       unsigned int regno;
2790       addressT index;
2791     } reg_element;
2792
2793     /* The two register symbol values involved in an OT_REG_RANGE.  */
2794     struct {
2795       unsigned int regno1;
2796       unsigned int regno2;
2797     } reg_range;
2798
2799     /* The value of an OT_INTEGER.  The value is represented as an
2800        expression and the relocation operators that were applied to
2801        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2802        relocation operators were used.  */
2803     struct {
2804       expressionS value;
2805       bfd_reloc_code_real_type relocs[3];
2806     } integer;
2807
2808     /* The binary data for an OT_FLOAT constant, and the number of bytes
2809        in the constant.  */
2810     struct {
2811       unsigned char data[8];
2812       int length;
2813     } flt;
2814
2815     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2816     char ch;
2817   } u;
2818 };
2819
2820 /* An obstack used to construct lists of mips_operand_tokens.  */
2821 static struct obstack mips_operand_tokens;
2822
2823 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2824
2825 static void
2826 mips_add_token (struct mips_operand_token *token,
2827                 enum mips_operand_token_type type)
2828 {
2829   token->type = type;
2830   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2831 }
2832
2833 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2834    and OT_REG tokens for them if so, and return a pointer to the first
2835    unconsumed character.  Return null otherwise.  */
2836
2837 static char *
2838 mips_parse_base_start (char *s)
2839 {
2840   struct mips_operand_token token;
2841   unsigned int regno, channels;
2842   bfd_boolean decrement_p;
2843
2844   if (*s != '(')
2845     return 0;
2846
2847   ++s;
2848   SKIP_SPACE_TABS (s);
2849
2850   /* Only match "--" as part of a base expression.  In other contexts "--X"
2851      is a double negative.  */
2852   decrement_p = (s[0] == '-' && s[1] == '-');
2853   if (decrement_p)
2854     {
2855       s += 2;
2856       SKIP_SPACE_TABS (s);
2857     }
2858
2859   /* Allow a channel specifier because that leads to better error messages
2860      than treating something like "$vf0x++" as an expression.  */
2861   if (!mips_parse_register (&s, &regno, &channels))
2862     return 0;
2863
2864   token.u.ch = '(';
2865   mips_add_token (&token, OT_CHAR);
2866
2867   if (decrement_p)
2868     {
2869       token.u.ch = '-';
2870       mips_add_token (&token, OT_DOUBLE_CHAR);
2871     }
2872
2873   token.u.regno = regno;
2874   mips_add_token (&token, OT_REG);
2875
2876   if (channels)
2877     {
2878       token.u.channels = channels;
2879       mips_add_token (&token, OT_CHANNELS);
2880     }
2881
2882   /* For consistency, only match "++" as part of base expressions too.  */
2883   SKIP_SPACE_TABS (s);
2884   if (s[0] == '+' && s[1] == '+')
2885     {
2886       s += 2;
2887       token.u.ch = '+';
2888       mips_add_token (&token, OT_DOUBLE_CHAR);
2889     }
2890
2891   return s;
2892 }
2893
2894 /* Parse one or more tokens from S.  Return a pointer to the first
2895    unconsumed character on success.  Return null if an error was found
2896    and store the error text in insn_error.  FLOAT_FORMAT is as for
2897    mips_parse_arguments.  */
2898
2899 static char *
2900 mips_parse_argument_token (char *s, char float_format)
2901 {
2902   char *end, *save_in, *err;
2903   unsigned int regno1, regno2, channels;
2904   struct mips_operand_token token;
2905
2906   /* First look for "($reg", since we want to treat that as an
2907      OT_CHAR and OT_REG rather than an expression.  */
2908   end = mips_parse_base_start (s);
2909   if (end)
2910     return end;
2911
2912   /* Handle other characters that end up as OT_CHARs.  */
2913   if (*s == ')' || *s == ',')
2914     {
2915       token.u.ch = *s;
2916       mips_add_token (&token, OT_CHAR);
2917       ++s;
2918       return s;
2919     }
2920
2921   /* Handle tokens that start with a register.  */
2922   if (mips_parse_register (&s, &regno1, &channels))
2923     {
2924       if (channels)
2925         {
2926           /* A register and a VU0 channel suffix.  */
2927           token.u.regno = regno1;
2928           mips_add_token (&token, OT_REG);
2929
2930           token.u.channels = channels;
2931           mips_add_token (&token, OT_CHANNELS);
2932           return s;
2933         }
2934
2935       SKIP_SPACE_TABS (s);
2936       if (*s == '-')
2937         {
2938           /* A register range.  */
2939           ++s;
2940           SKIP_SPACE_TABS (s);
2941           if (!mips_parse_register (&s, &regno2, NULL))
2942             {
2943               set_insn_error (0, _("Invalid register range"));
2944               return 0;
2945             }
2946
2947           token.u.reg_range.regno1 = regno1;
2948           token.u.reg_range.regno2 = regno2;
2949           mips_add_token (&token, OT_REG_RANGE);
2950           return s;
2951         }
2952       else if (*s == '[')
2953         {
2954           /* A vector element.  */
2955           expressionS element;
2956
2957           ++s;
2958           SKIP_SPACE_TABS (s);
2959           my_getExpression (&element, s);
2960           if (element.X_op != O_constant)
2961             {
2962               set_insn_error (0, _("Vector element must be constant"));
2963               return 0;
2964             }
2965           s = expr_end;
2966           SKIP_SPACE_TABS (s);
2967           if (*s != ']')
2968             {
2969               set_insn_error (0, _("Missing `]'"));
2970               return 0;
2971             }
2972           ++s;
2973
2974           token.u.reg_element.regno = regno1;
2975           token.u.reg_element.index = element.X_add_number;
2976           mips_add_token (&token, OT_REG_ELEMENT);
2977           return s;
2978         }
2979
2980       /* Looks like just a plain register.  */
2981       token.u.regno = regno1;
2982       mips_add_token (&token, OT_REG);
2983       return s;
2984     }
2985
2986   if (float_format)
2987     {
2988       /* First try to treat expressions as floats.  */
2989       save_in = input_line_pointer;
2990       input_line_pointer = s;
2991       err = md_atof (float_format, (char *) token.u.flt.data,
2992                      &token.u.flt.length);
2993       end = input_line_pointer;
2994       input_line_pointer = save_in;
2995       if (err && *err)
2996         {
2997           set_insn_error (0, err);
2998           return 0;
2999         }
3000       if (s != end)
3001         {
3002           mips_add_token (&token, OT_FLOAT);
3003           return end;
3004         }
3005     }
3006
3007   /* Treat everything else as an integer expression.  */
3008   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3009   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3010   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3011   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3012   s = expr_end;
3013   mips_add_token (&token, OT_INTEGER);
3014   return s;
3015 }
3016
3017 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3018    if expressions should be treated as 32-bit floating-point constants,
3019    'd' if they should be treated as 64-bit floating-point constants,
3020    or 0 if they should be treated as integer expressions (the usual case).
3021
3022    Return a list of tokens on success, otherwise return 0.  The caller
3023    must obstack_free the list after use.  */
3024
3025 static struct mips_operand_token *
3026 mips_parse_arguments (char *s, char float_format)
3027 {
3028   struct mips_operand_token token;
3029
3030   SKIP_SPACE_TABS (s);
3031   while (*s)
3032     {
3033       s = mips_parse_argument_token (s, float_format);
3034       if (!s)
3035         {
3036           obstack_free (&mips_operand_tokens,
3037                         obstack_finish (&mips_operand_tokens));
3038           return 0;
3039         }
3040       SKIP_SPACE_TABS (s);
3041     }
3042   mips_add_token (&token, OT_END);
3043   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3044 }
3045
3046 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3047    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3048
3049 static bfd_boolean
3050 is_opcode_valid (const struct mips_opcode *mo)
3051 {
3052   int isa = mips_opts.isa;
3053   int ase = mips_opts.ase;
3054   int fp_s, fp_d;
3055   unsigned int i;
3056
3057   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3058     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3059       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3060         ase |= mips_ases[i].flags64;
3061
3062   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3063     return FALSE;
3064
3065   /* Check whether the instruction or macro requires single-precision or
3066      double-precision floating-point support.  Note that this information is
3067      stored differently in the opcode table for insns and macros.  */
3068   if (mo->pinfo == INSN_MACRO)
3069     {
3070       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3071       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3072     }
3073   else
3074     {
3075       fp_s = mo->pinfo & FP_S;
3076       fp_d = mo->pinfo & FP_D;
3077     }
3078
3079   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3080     return FALSE;
3081
3082   if (fp_s && mips_opts.soft_float)
3083     return FALSE;
3084
3085   return TRUE;
3086 }
3087
3088 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3089    selected ISA and architecture.  */
3090
3091 static bfd_boolean
3092 is_opcode_valid_16 (const struct mips_opcode *mo)
3093 {
3094   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3095 }
3096
3097 /* Return TRUE if the size of the microMIPS opcode MO matches one
3098    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3099
3100 static bfd_boolean
3101 is_size_valid (const struct mips_opcode *mo)
3102 {
3103   if (!mips_opts.micromips)
3104     return TRUE;
3105
3106   if (mips_opts.insn32)
3107     {
3108       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3109         return FALSE;
3110       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3111         return FALSE;
3112     }
3113   if (!forced_insn_length)
3114     return TRUE;
3115   if (mo->pinfo == INSN_MACRO)
3116     return FALSE;
3117   return forced_insn_length == micromips_insn_length (mo);
3118 }
3119
3120 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3121    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3122
3123    We don't accept macros in 16-bit delay slots to avoid a case where
3124    a macro expansion fails because it relies on a preceding 32-bit real
3125    instruction to have matched and does not handle the operands correctly.
3126    The only macros that may expand to 16-bit instructions are JAL that
3127    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3128    and BGT (that likewise cannot be placed in a delay slot) that decay to
3129    a NOP.  In all these cases the macros precede any corresponding real
3130    instruction definitions in the opcode table, so they will match in the
3131    second pass where the size of the delay slot is ignored and therefore
3132    produce correct code.  */
3133
3134 static bfd_boolean
3135 is_delay_slot_valid (const struct mips_opcode *mo)
3136 {
3137   if (!mips_opts.micromips)
3138     return TRUE;
3139
3140   if (mo->pinfo == INSN_MACRO)
3141     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3142   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3143       && micromips_insn_length (mo) != 4)
3144     return FALSE;
3145   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3146       && micromips_insn_length (mo) != 2)
3147     return FALSE;
3148
3149   return TRUE;
3150 }
3151
3152 /* For consistency checking, verify that all bits of OPCODE are specified
3153    either by the match/mask part of the instruction definition, or by the
3154    operand list.  Also build up a list of operands in OPERANDS.
3155
3156    INSN_BITS says which bits of the instruction are significant.
3157    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3158    provides the mips_operand description of each operand.  DECODE_OPERAND
3159    is null for MIPS16 instructions.  */
3160
3161 static int
3162 validate_mips_insn (const struct mips_opcode *opcode,
3163                     unsigned long insn_bits,
3164                     const struct mips_operand *(*decode_operand) (const char *),
3165                     struct mips_operand_array *operands)
3166 {
3167   const char *s;
3168   unsigned long used_bits, doubled, undefined, opno, mask;
3169   const struct mips_operand *operand;
3170
3171   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3172   if ((mask & opcode->match) != opcode->match)
3173     {
3174       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3175               opcode->name, opcode->args);
3176       return 0;
3177     }
3178   used_bits = 0;
3179   opno = 0;
3180   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3181     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3182   for (s = opcode->args; *s; ++s)
3183     switch (*s)
3184       {
3185       case ',':
3186       case '(':
3187       case ')':
3188         break;
3189
3190       case '#':
3191         s++;
3192         break;
3193
3194       default:
3195         if (!decode_operand)
3196           operand = decode_mips16_operand (*s, FALSE);
3197         else
3198           operand = decode_operand (s);
3199         if (!operand && opcode->pinfo != INSN_MACRO)
3200           {
3201             as_bad (_("internal: unknown operand type: %s %s"),
3202                     opcode->name, opcode->args);
3203             return 0;
3204           }
3205         gas_assert (opno < MAX_OPERANDS);
3206         operands->operand[opno] = operand;
3207         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3208           {
3209             used_bits = mips_insert_operand (operand, used_bits, -1);
3210             if (operand->type == OP_MDMX_IMM_REG)
3211               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3212                  has separate entries for each format.  */
3213               used_bits &= ~(1 << (operand->lsb + 5));
3214             if (operand->type == OP_ENTRY_EXIT_LIST)
3215               used_bits &= ~(mask & 0x700);
3216           }
3217         /* Skip prefix characters.  */
3218         if (decode_operand && (*s == '+' || *s == 'm'))
3219           ++s;
3220         opno += 1;
3221         break;
3222       }
3223   doubled = used_bits & mask & insn_bits;
3224   if (doubled)
3225     {
3226       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3227                 " %s %s"), doubled, opcode->name, opcode->args);
3228       return 0;
3229     }
3230   used_bits |= mask;
3231   undefined = ~used_bits & insn_bits;
3232   if (opcode->pinfo != INSN_MACRO && undefined)
3233     {
3234       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3235               undefined, opcode->name, opcode->args);
3236       return 0;
3237     }
3238   used_bits &= ~insn_bits;
3239   if (used_bits)
3240     {
3241       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3242               used_bits, opcode->name, opcode->args);
3243       return 0;
3244     }
3245   return 1;
3246 }
3247
3248 /* The MIPS16 version of validate_mips_insn.  */
3249
3250 static int
3251 validate_mips16_insn (const struct mips_opcode *opcode,
3252                       struct mips_operand_array *operands)
3253 {
3254   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3255     {
3256       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3257          instruction.  Use TMP to describe the full instruction.  */
3258       struct mips_opcode tmp;
3259
3260       tmp = *opcode;
3261       tmp.match <<= 16;
3262       tmp.mask <<= 16;
3263       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3264     }
3265   return validate_mips_insn (opcode, 0xffff, 0, operands);
3266 }
3267
3268 /* The microMIPS version of validate_mips_insn.  */
3269
3270 static int
3271 validate_micromips_insn (const struct mips_opcode *opc,
3272                          struct mips_operand_array *operands)
3273 {
3274   unsigned long insn_bits;
3275   unsigned long major;
3276   unsigned int length;
3277
3278   if (opc->pinfo == INSN_MACRO)
3279     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3280                                operands);
3281
3282   length = micromips_insn_length (opc);
3283   if (length != 2 && length != 4)
3284     {
3285       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
3286                 "%s %s"), length, opc->name, opc->args);
3287       return 0;
3288     }
3289   major = opc->match >> (10 + 8 * (length - 2));
3290   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3291       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3292     {
3293       as_bad (_("Internal error: bad microMIPS opcode "
3294                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3295       return 0;
3296     }
3297
3298   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3299   insn_bits = 1 << 4 * length;
3300   insn_bits <<= 4 * length;
3301   insn_bits -= 1;
3302   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3303                              operands);
3304 }
3305
3306 /* This function is called once, at assembler startup time.  It should set up
3307    all the tables, etc. that the MD part of the assembler will need.  */
3308
3309 void
3310 md_begin (void)
3311 {
3312   const char *retval = NULL;
3313   int i = 0;
3314   int broken = 0;
3315
3316   if (mips_pic != NO_PIC)
3317     {
3318       if (g_switch_seen && g_switch_value != 0)
3319         as_bad (_("-G may not be used in position-independent code"));
3320       g_switch_value = 0;
3321     }
3322
3323   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
3324     as_warn (_("Could not set architecture and machine"));
3325
3326   op_hash = hash_new ();
3327
3328   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3329   for (i = 0; i < NUMOPCODES;)
3330     {
3331       const char *name = mips_opcodes[i].name;
3332
3333       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3334       if (retval != NULL)
3335         {
3336           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3337                    mips_opcodes[i].name, retval);
3338           /* Probably a memory allocation problem?  Give up now.  */
3339           as_fatal (_("Broken assembler.  No assembly attempted."));
3340         }
3341       do
3342         {
3343           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3344                                    decode_mips_operand, &mips_operands[i]))
3345             broken = 1;
3346           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3347             {
3348               create_insn (&nop_insn, mips_opcodes + i);
3349               if (mips_fix_loongson2f_nop)
3350                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3351               nop_insn.fixed_p = 1;
3352             }
3353           ++i;
3354         }
3355       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3356     }
3357
3358   mips16_op_hash = hash_new ();
3359   mips16_operands = XCNEWVEC (struct mips_operand_array,
3360                               bfd_mips16_num_opcodes);
3361
3362   i = 0;
3363   while (i < bfd_mips16_num_opcodes)
3364     {
3365       const char *name = mips16_opcodes[i].name;
3366
3367       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3368       if (retval != NULL)
3369         as_fatal (_("internal: can't hash `%s': %s"),
3370                   mips16_opcodes[i].name, retval);
3371       do
3372         {
3373           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3374             broken = 1;
3375           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3376             {
3377               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3378               mips16_nop_insn.fixed_p = 1;
3379             }
3380           ++i;
3381         }
3382       while (i < bfd_mips16_num_opcodes
3383              && strcmp (mips16_opcodes[i].name, name) == 0);
3384     }
3385
3386   micromips_op_hash = hash_new ();
3387   micromips_operands = XCNEWVEC (struct mips_operand_array,
3388                                  bfd_micromips_num_opcodes);
3389
3390   i = 0;
3391   while (i < bfd_micromips_num_opcodes)
3392     {
3393       const char *name = micromips_opcodes[i].name;
3394
3395       retval = hash_insert (micromips_op_hash, name,
3396                             (void *) &micromips_opcodes[i]);
3397       if (retval != NULL)
3398         as_fatal (_("internal: can't hash `%s': %s"),
3399                   micromips_opcodes[i].name, retval);
3400       do
3401         {
3402           struct mips_cl_insn *micromips_nop_insn;
3403
3404           if (!validate_micromips_insn (&micromips_opcodes[i],
3405                                         &micromips_operands[i]))
3406             broken = 1;
3407
3408           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3409             {
3410               if (micromips_insn_length (micromips_opcodes + i) == 2)
3411                 micromips_nop_insn = &micromips_nop16_insn;
3412               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3413                 micromips_nop_insn = &micromips_nop32_insn;
3414               else
3415                 continue;
3416
3417               if (micromips_nop_insn->insn_mo == NULL
3418                   && strcmp (name, "nop") == 0)
3419                 {
3420                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3421                   micromips_nop_insn->fixed_p = 1;
3422                 }
3423             }
3424         }
3425       while (++i < bfd_micromips_num_opcodes
3426              && strcmp (micromips_opcodes[i].name, name) == 0);
3427     }
3428
3429   if (broken)
3430     as_fatal (_("Broken assembler.  No assembly attempted."));
3431
3432   /* We add all the general register names to the symbol table.  This
3433      helps us detect invalid uses of them.  */
3434   for (i = 0; reg_names[i].name; i++) 
3435     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3436                                      reg_names[i].num, /* & RNUM_MASK, */
3437                                      &zero_address_frag));
3438   if (HAVE_NEWABI)
3439     for (i = 0; reg_names_n32n64[i].name; i++) 
3440       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3441                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3442                                        &zero_address_frag));
3443   else
3444     for (i = 0; reg_names_o32[i].name; i++) 
3445       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3446                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3447                                        &zero_address_frag));
3448
3449   for (i = 0; i < 32; i++)
3450     {
3451       char regname[7];
3452
3453       /* R5900 VU0 floating-point register.  */
3454       regname[sizeof (rename) - 1] = 0;
3455       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3456       symbol_table_insert (symbol_new (regname, reg_section,
3457                                        RTYPE_VF | i, &zero_address_frag));
3458
3459       /* R5900 VU0 integer register.  */
3460       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3461       symbol_table_insert (symbol_new (regname, reg_section,
3462                                        RTYPE_VI | i, &zero_address_frag));
3463
3464     }
3465
3466   obstack_init (&mips_operand_tokens);
3467
3468   mips_no_prev_insn ();
3469
3470   mips_gprmask = 0;
3471   mips_cprmask[0] = 0;
3472   mips_cprmask[1] = 0;
3473   mips_cprmask[2] = 0;
3474   mips_cprmask[3] = 0;
3475
3476   /* set the default alignment for the text section (2**2) */
3477   record_alignment (text_section, 2);
3478
3479   bfd_set_gp_size (stdoutput, g_switch_value);
3480
3481   /* On a native system other than VxWorks, sections must be aligned
3482      to 16 byte boundaries.  When configured for an embedded ELF
3483      target, we don't bother.  */
3484   if (strncmp (TARGET_OS, "elf", 3) != 0
3485       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3486     {
3487       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3488       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3489       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3490     }
3491
3492   /* Create a .reginfo section for register masks and a .mdebug
3493      section for debugging information.  */
3494   {
3495     segT seg;
3496     subsegT subseg;
3497     flagword flags;
3498     segT sec;
3499
3500     seg = now_seg;
3501     subseg = now_subseg;
3502
3503     /* The ABI says this section should be loaded so that the
3504        running program can access it.  However, we don't load it
3505        if we are configured for an embedded target */
3506     flags = SEC_READONLY | SEC_DATA;
3507     if (strncmp (TARGET_OS, "elf", 3) != 0)
3508       flags |= SEC_ALLOC | SEC_LOAD;
3509
3510     if (mips_abi != N64_ABI)
3511       {
3512         sec = subseg_new (".reginfo", (subsegT) 0);
3513
3514         bfd_set_section_flags (stdoutput, sec, flags);
3515         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3516
3517         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3518       }
3519     else
3520       {
3521         /* The 64-bit ABI uses a .MIPS.options section rather than
3522            .reginfo section.  */
3523         sec = subseg_new (".MIPS.options", (subsegT) 0);
3524         bfd_set_section_flags (stdoutput, sec, flags);
3525         bfd_set_section_alignment (stdoutput, sec, 3);
3526
3527         /* Set up the option header.  */
3528         {
3529           Elf_Internal_Options opthdr;
3530           char *f;
3531
3532           opthdr.kind = ODK_REGINFO;
3533           opthdr.size = (sizeof (Elf_External_Options)
3534                          + sizeof (Elf64_External_RegInfo));
3535           opthdr.section = 0;
3536           opthdr.info = 0;
3537           f = frag_more (sizeof (Elf_External_Options));
3538           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3539                                          (Elf_External_Options *) f);
3540
3541           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3542         }
3543       }
3544
3545     if (ECOFF_DEBUGGING)
3546       {
3547         sec = subseg_new (".mdebug", (subsegT) 0);
3548         (void) bfd_set_section_flags (stdoutput, sec,
3549                                       SEC_HAS_CONTENTS | SEC_READONLY);
3550         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3551       }
3552     else if (mips_flag_pdr)
3553       {
3554         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3555         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3556                                       SEC_READONLY | SEC_RELOC
3557                                       | SEC_DEBUGGING);
3558         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3559       }
3560
3561     subseg_set (seg, subseg);
3562   }
3563
3564   if (! ECOFF_DEBUGGING)
3565     md_obj_begin ();
3566
3567   if (mips_fix_vr4120)
3568     init_vr4120_conflicts ();
3569 }
3570
3571 void
3572 md_mips_end (void)
3573 {
3574   mips_emit_delays ();
3575   if (! ECOFF_DEBUGGING)
3576     md_obj_end ();
3577 }
3578
3579 void
3580 md_assemble (char *str)
3581 {
3582   struct mips_cl_insn insn;
3583   bfd_reloc_code_real_type unused_reloc[3]
3584     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3585
3586   imm_expr.X_op = O_absent;
3587   imm2_expr.X_op = O_absent;
3588   offset_expr.X_op = O_absent;
3589   offset_reloc[0] = BFD_RELOC_UNUSED;
3590   offset_reloc[1] = BFD_RELOC_UNUSED;
3591   offset_reloc[2] = BFD_RELOC_UNUSED;
3592
3593   mips_mark_labels ();
3594   mips_assembling_insn = TRUE;
3595   clear_insn_error ();
3596
3597   if (mips_opts.mips16)
3598     mips16_ip (str, &insn);
3599   else
3600     {
3601       mips_ip (str, &insn);
3602       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3603             str, insn.insn_opcode));
3604     }
3605
3606   if (insn_error.msg)
3607     report_insn_error (str);
3608   else if (insn.insn_mo->pinfo == INSN_MACRO)
3609     {
3610       macro_start ();
3611       if (mips_opts.mips16)
3612         mips16_macro (&insn);
3613       else
3614         macro (&insn, str);
3615       macro_end ();
3616     }
3617   else
3618     {
3619       if (offset_expr.X_op != O_absent)
3620         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3621       else
3622         append_insn (&insn, NULL, unused_reloc, FALSE);
3623     }
3624
3625   mips_assembling_insn = FALSE;
3626 }
3627
3628 /* Convenience functions for abstracting away the differences between
3629    MIPS16 and non-MIPS16 relocations.  */
3630
3631 static inline bfd_boolean
3632 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3633 {
3634   switch (reloc)
3635     {
3636     case BFD_RELOC_MIPS16_JMP:
3637     case BFD_RELOC_MIPS16_GPREL:
3638     case BFD_RELOC_MIPS16_GOT16:
3639     case BFD_RELOC_MIPS16_CALL16:
3640     case BFD_RELOC_MIPS16_HI16_S:
3641     case BFD_RELOC_MIPS16_HI16:
3642     case BFD_RELOC_MIPS16_LO16:
3643       return TRUE;
3644
3645     default:
3646       return FALSE;
3647     }
3648 }
3649
3650 static inline bfd_boolean
3651 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3652 {
3653   switch (reloc)
3654     {
3655     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3656     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3657     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3658     case BFD_RELOC_MICROMIPS_GPREL16:
3659     case BFD_RELOC_MICROMIPS_JMP:
3660     case BFD_RELOC_MICROMIPS_HI16:
3661     case BFD_RELOC_MICROMIPS_HI16_S:
3662     case BFD_RELOC_MICROMIPS_LO16:
3663     case BFD_RELOC_MICROMIPS_LITERAL:
3664     case BFD_RELOC_MICROMIPS_GOT16:
3665     case BFD_RELOC_MICROMIPS_CALL16:
3666     case BFD_RELOC_MICROMIPS_GOT_HI16:
3667     case BFD_RELOC_MICROMIPS_GOT_LO16:
3668     case BFD_RELOC_MICROMIPS_CALL_HI16:
3669     case BFD_RELOC_MICROMIPS_CALL_LO16:
3670     case BFD_RELOC_MICROMIPS_SUB:
3671     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3672     case BFD_RELOC_MICROMIPS_GOT_OFST:
3673     case BFD_RELOC_MICROMIPS_GOT_DISP:
3674     case BFD_RELOC_MICROMIPS_HIGHEST:
3675     case BFD_RELOC_MICROMIPS_HIGHER:
3676     case BFD_RELOC_MICROMIPS_SCN_DISP:
3677     case BFD_RELOC_MICROMIPS_JALR:
3678       return TRUE;
3679
3680     default:
3681       return FALSE;
3682     }
3683 }
3684
3685 static inline bfd_boolean
3686 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3687 {
3688   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3689 }
3690
3691 static inline bfd_boolean
3692 got16_reloc_p (bfd_reloc_code_real_type reloc)
3693 {
3694   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3695           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3696 }
3697
3698 static inline bfd_boolean
3699 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3700 {
3701   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3702           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3703 }
3704
3705 static inline bfd_boolean
3706 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3707 {
3708   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3709           || reloc == BFD_RELOC_MICROMIPS_LO16);
3710 }
3711
3712 static inline bfd_boolean
3713 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3714 {
3715   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3716 }
3717
3718 static inline bfd_boolean
3719 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3720 {
3721   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3722           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3723 }
3724
3725 /* Return true if RELOC is a PC-relative relocation that does not have
3726    full address range.  */
3727
3728 static inline bfd_boolean
3729 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3730 {
3731   switch (reloc)
3732     {
3733     case BFD_RELOC_16_PCREL_S2:
3734     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3735     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3736     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3737       return TRUE;
3738
3739     case BFD_RELOC_32_PCREL:
3740       return HAVE_64BIT_ADDRESSES;
3741
3742     default:
3743       return FALSE;
3744     }
3745 }
3746
3747 /* Return true if the given relocation might need a matching %lo().
3748    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3749    need a matching %lo() when applied to local symbols.  */
3750
3751 static inline bfd_boolean
3752 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3753 {
3754   return (HAVE_IN_PLACE_ADDENDS
3755           && (hi16_reloc_p (reloc)
3756               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3757                  all GOT16 relocations evaluate to "G".  */
3758               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3759 }
3760
3761 /* Return the type of %lo() reloc needed by RELOC, given that
3762    reloc_needs_lo_p.  */
3763
3764 static inline bfd_reloc_code_real_type
3765 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3766 {
3767   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3768           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3769              : BFD_RELOC_LO16));
3770 }
3771
3772 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3773    relocation.  */
3774
3775 static inline bfd_boolean
3776 fixup_has_matching_lo_p (fixS *fixp)
3777 {
3778   return (fixp->fx_next != NULL
3779           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3780           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3781           && fixp->fx_offset == fixp->fx_next->fx_offset);
3782 }
3783
3784 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3785    says whether the labels refer to text or data.  */
3786
3787 static void
3788 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3789 {
3790   struct insn_label_list *l;
3791   valueT val;
3792
3793   for (l = labels; l != NULL; l = l->next)
3794     {
3795       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3796       symbol_set_frag (l->label, frag_now);
3797       val = (valueT) frag_now_fix ();
3798       /* MIPS16/microMIPS text labels are stored as odd.  */
3799       if (text_p && HAVE_CODE_COMPRESSION)
3800         ++val;
3801       S_SET_VALUE (l->label, val);
3802     }
3803 }
3804
3805 /* Move all labels in insn_labels to the current insertion point
3806    and treat them as text labels.  */
3807
3808 static void
3809 mips_move_text_labels (void)
3810 {
3811   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3812 }
3813
3814 static bfd_boolean
3815 s_is_linkonce (symbolS *sym, segT from_seg)
3816 {
3817   bfd_boolean linkonce = FALSE;
3818   segT symseg = S_GET_SEGMENT (sym);
3819
3820   if (symseg != from_seg && !S_IS_LOCAL (sym))
3821     {
3822       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3823         linkonce = TRUE;
3824       /* The GNU toolchain uses an extension for ELF: a section
3825          beginning with the magic string .gnu.linkonce is a
3826          linkonce section.  */
3827       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3828                    sizeof ".gnu.linkonce" - 1) == 0)
3829         linkonce = TRUE;
3830     }
3831   return linkonce;
3832 }
3833
3834 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3835    linker to handle them specially, such as generating jalx instructions
3836    when needed.  We also make them odd for the duration of the assembly,
3837    in order to generate the right sort of code.  We will make them even
3838    in the adjust_symtab routine, while leaving them marked.  This is
3839    convenient for the debugger and the disassembler.  The linker knows
3840    to make them odd again.  */
3841
3842 static void
3843 mips_compressed_mark_label (symbolS *label)
3844 {
3845   gas_assert (HAVE_CODE_COMPRESSION);
3846
3847   if (mips_opts.mips16)
3848     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3849   else
3850     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3851   if ((S_GET_VALUE (label) & 1) == 0
3852       /* Don't adjust the address if the label is global or weak, or
3853          in a link-once section, since we'll be emitting symbol reloc
3854          references to it which will be patched up by the linker, and
3855          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3856       && !S_IS_WEAK (label)
3857       && !S_IS_EXTERNAL (label)
3858       && !s_is_linkonce (label, now_seg))
3859     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3860 }
3861
3862 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3863
3864 static void
3865 mips_compressed_mark_labels (void)
3866 {
3867   struct insn_label_list *l;
3868
3869   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3870     mips_compressed_mark_label (l->label);
3871 }
3872
3873 /* End the current frag.  Make it a variant frag and record the
3874    relaxation info.  */
3875
3876 static void
3877 relax_close_frag (void)
3878 {
3879   mips_macro_warning.first_frag = frag_now;
3880   frag_var (rs_machine_dependent, 0, 0,
3881             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3882             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3883
3884   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3885   mips_relax.first_fixup = 0;
3886 }
3887
3888 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3889    See the comment above RELAX_ENCODE for more details.  */
3890
3891 static void
3892 relax_start (symbolS *symbol)
3893 {
3894   gas_assert (mips_relax.sequence == 0);
3895   mips_relax.sequence = 1;
3896   mips_relax.symbol = symbol;
3897 }
3898
3899 /* Start generating the second version of a relaxable sequence.
3900    See the comment above RELAX_ENCODE for more details.  */
3901
3902 static void
3903 relax_switch (void)
3904 {
3905   gas_assert (mips_relax.sequence == 1);
3906   mips_relax.sequence = 2;
3907 }
3908
3909 /* End the current relaxable sequence.  */
3910
3911 static void
3912 relax_end (void)
3913 {
3914   gas_assert (mips_relax.sequence == 2);
3915   relax_close_frag ();
3916   mips_relax.sequence = 0;
3917 }
3918
3919 /* Return true if IP is a delayed branch or jump.  */
3920
3921 static inline bfd_boolean
3922 delayed_branch_p (const struct mips_cl_insn *ip)
3923 {
3924   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3925                                 | INSN_COND_BRANCH_DELAY
3926                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3927 }
3928
3929 /* Return true if IP is a compact branch or jump.  */
3930
3931 static inline bfd_boolean
3932 compact_branch_p (const struct mips_cl_insn *ip)
3933 {
3934   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3935                                  | INSN2_COND_BRANCH)) != 0;
3936 }
3937
3938 /* Return true if IP is an unconditional branch or jump.  */
3939
3940 static inline bfd_boolean
3941 uncond_branch_p (const struct mips_cl_insn *ip)
3942 {
3943   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3944           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
3945 }
3946
3947 /* Return true if IP is a branch-likely instruction.  */
3948
3949 static inline bfd_boolean
3950 branch_likely_p (const struct mips_cl_insn *ip)
3951 {
3952   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3953 }
3954
3955 /* Return the type of nop that should be used to fill the delay slot
3956    of delayed branch IP.  */
3957
3958 static struct mips_cl_insn *
3959 get_delay_slot_nop (const struct mips_cl_insn *ip)
3960 {
3961   if (mips_opts.micromips
3962       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3963     return &micromips_nop32_insn;
3964   return NOP_INSN;
3965 }
3966
3967 /* Return a mask that has bit N set if OPCODE reads the register(s)
3968    in operand N.  */
3969
3970 static unsigned int
3971 insn_read_mask (const struct mips_opcode *opcode)
3972 {
3973   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
3974 }
3975
3976 /* Return a mask that has bit N set if OPCODE writes to the register(s)
3977    in operand N.  */
3978
3979 static unsigned int
3980 insn_write_mask (const struct mips_opcode *opcode)
3981 {
3982   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
3983 }
3984
3985 /* Return a mask of the registers specified by operand OPERAND of INSN.
3986    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
3987    is set.  */
3988
3989 static unsigned int
3990 operand_reg_mask (const struct mips_cl_insn *insn,
3991                   const struct mips_operand *operand,
3992                   unsigned int type_mask)
3993 {
3994   unsigned int uval, vsel;
3995
3996   switch (operand->type)
3997     {
3998     case OP_INT:
3999     case OP_MAPPED_INT:
4000     case OP_MSB:
4001     case OP_PCREL:
4002     case OP_PERF_REG:
4003     case OP_ADDIUSP_INT:
4004     case OP_ENTRY_EXIT_LIST:
4005     case OP_REPEAT_DEST_REG:
4006     case OP_REPEAT_PREV_REG:
4007     case OP_PC:
4008     case OP_VU0_SUFFIX:
4009     case OP_VU0_MATCH_SUFFIX:
4010       abort ();
4011
4012     case OP_REG:
4013     case OP_OPTIONAL_REG:
4014       {
4015         const struct mips_reg_operand *reg_op;
4016
4017         reg_op = (const struct mips_reg_operand *) operand;
4018         if (!(type_mask & (1 << reg_op->reg_type)))
4019           return 0;
4020         uval = insn_extract_operand (insn, operand);
4021         return 1 << mips_decode_reg_operand (reg_op, uval);
4022       }
4023
4024     case OP_REG_PAIR:
4025       {
4026         const struct mips_reg_pair_operand *pair_op;
4027
4028         pair_op = (const struct mips_reg_pair_operand *) operand;
4029         if (!(type_mask & (1 << pair_op->reg_type)))
4030           return 0;
4031         uval = insn_extract_operand (insn, operand);
4032         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4033       }
4034
4035     case OP_CLO_CLZ_DEST:
4036       if (!(type_mask & (1 << OP_REG_GP)))
4037         return 0;
4038       uval = insn_extract_operand (insn, operand);
4039       return (1 << (uval & 31)) | (1 << (uval >> 5));
4040
4041     case OP_LWM_SWM_LIST:
4042       abort ();
4043
4044     case OP_SAVE_RESTORE_LIST:
4045       abort ();
4046
4047     case OP_MDMX_IMM_REG:
4048       if (!(type_mask & (1 << OP_REG_VEC)))
4049         return 0;
4050       uval = insn_extract_operand (insn, operand);
4051       vsel = uval >> 5;
4052       if ((vsel & 0x18) == 0x18)
4053         return 0;
4054       return 1 << (uval & 31);
4055     }
4056   abort ();
4057 }
4058
4059 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4060    where bit N of OPNO_MASK is set if operand N should be included.
4061    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4062    is set.  */
4063
4064 static unsigned int
4065 insn_reg_mask (const struct mips_cl_insn *insn,
4066                unsigned int type_mask, unsigned int opno_mask)
4067 {
4068   unsigned int opno, reg_mask;
4069
4070   opno = 0;
4071   reg_mask = 0;
4072   while (opno_mask != 0)
4073     {
4074       if (opno_mask & 1)
4075         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4076       opno_mask >>= 1;
4077       opno += 1;
4078     }
4079   return reg_mask;
4080 }
4081
4082 /* Return the mask of core registers that IP reads.  */
4083
4084 static unsigned int
4085 gpr_read_mask (const struct mips_cl_insn *ip)
4086 {
4087   unsigned long pinfo, pinfo2;
4088   unsigned int mask;
4089
4090   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4091   pinfo = ip->insn_mo->pinfo;
4092   pinfo2 = ip->insn_mo->pinfo2;
4093   if (pinfo & INSN_UDI)
4094     {
4095       /* UDI instructions have traditionally been assumed to read RS
4096          and RT.  */
4097       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4098       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4099     }
4100   if (pinfo & INSN_READ_GPR_24)
4101     mask |= 1 << 24;
4102   if (pinfo2 & INSN2_READ_GPR_16)
4103     mask |= 1 << 16;
4104   if (pinfo2 & INSN2_READ_SP)
4105     mask |= 1 << SP;
4106   if (pinfo2 & INSN2_READ_GPR_31)
4107     mask |= 1 << 31;
4108   /* Don't include register 0.  */
4109   return mask & ~1;
4110 }
4111
4112 /* Return the mask of core registers that IP writes.  */
4113
4114 static unsigned int
4115 gpr_write_mask (const struct mips_cl_insn *ip)
4116 {
4117   unsigned long pinfo, pinfo2;
4118   unsigned int mask;
4119
4120   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4121   pinfo = ip->insn_mo->pinfo;
4122   pinfo2 = ip->insn_mo->pinfo2;
4123   if (pinfo & INSN_WRITE_GPR_24)
4124     mask |= 1 << 24;
4125   if (pinfo & INSN_WRITE_GPR_31)
4126     mask |= 1 << 31;
4127   if (pinfo & INSN_UDI)
4128     /* UDI instructions have traditionally been assumed to write to RD.  */
4129     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4130   if (pinfo2 & INSN2_WRITE_SP)
4131     mask |= 1 << SP;
4132   /* Don't include register 0.  */
4133   return mask & ~1;
4134 }
4135
4136 /* Return the mask of floating-point registers that IP reads.  */
4137
4138 static unsigned int
4139 fpr_read_mask (const struct mips_cl_insn *ip)
4140 {
4141   unsigned long pinfo;
4142   unsigned int mask;
4143
4144   mask = insn_reg_mask (ip, (1 << OP_REG_FP) | (1 << OP_REG_VEC),
4145                         insn_read_mask (ip->insn_mo));
4146   pinfo = ip->insn_mo->pinfo;
4147   /* Conservatively treat all operands to an FP_D instruction are doubles.
4148      (This is overly pessimistic for things like cvt.d.s.)  */
4149   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4150     mask |= mask << 1;
4151   return mask;
4152 }
4153
4154 /* Return the mask of floating-point registers that IP writes.  */
4155
4156 static unsigned int
4157 fpr_write_mask (const struct mips_cl_insn *ip)
4158 {
4159   unsigned long pinfo;
4160   unsigned int mask;
4161
4162   mask = insn_reg_mask (ip, (1 << OP_REG_FP) | (1 << OP_REG_VEC),
4163                         insn_write_mask (ip->insn_mo));
4164   pinfo = ip->insn_mo->pinfo;
4165   /* Conservatively treat all operands to an FP_D instruction are doubles.
4166      (This is overly pessimistic for things like cvt.s.d.)  */
4167   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4168     mask |= mask << 1;
4169   return mask;
4170 }
4171
4172 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4173    Check whether that is allowed.  */
4174
4175 static bfd_boolean
4176 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4177 {
4178   const char *s = insn->name;
4179
4180   if (insn->pinfo == INSN_MACRO)
4181     /* Let a macro pass, we'll catch it later when it is expanded.  */
4182     return TRUE;
4183
4184   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4185     {
4186       /* Allow odd registers for single-precision ops.  */
4187       switch (insn->pinfo & (FP_S | FP_D))
4188         {
4189         case FP_S:
4190         case 0:
4191           return TRUE;
4192         case FP_D:
4193           return FALSE;
4194         default:
4195           break;
4196         }
4197
4198       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4199       s = strchr (insn->name, '.');
4200       if (s != NULL && opnum == 2)
4201         s = strchr (s + 1, '.');
4202       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4203     }
4204
4205   /* Single-precision coprocessor loads and moves are OK too.  */
4206   if ((insn->pinfo & FP_S)
4207       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4208                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4209     return TRUE;
4210
4211   return FALSE;
4212 }
4213
4214 /* Report that user-supplied argument ARGNUM for INSN was VAL, but should
4215    have been in the range [MIN_VAL, MAX_VAL].  PRINT_HEX says whether
4216    this operand is normally printed in hex or decimal.  */
4217
4218 static void
4219 report_bad_range (struct mips_cl_insn *insn, int argnum,
4220                   offsetT val, int min_val, int max_val,
4221                   bfd_boolean print_hex)
4222 {
4223   if (print_hex && val >= 0)
4224     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
4225               " was 0x%lx."),
4226             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
4227   else if (print_hex)
4228     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
4229               " was %ld."),
4230             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
4231   else
4232     as_bad (_("Operand %d of `%s' must be in the range [%d, %d],"
4233               " was %ld."),
4234             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
4235 }
4236
4237 /* Report an invalid combination of position and size operands for a bitfield
4238    operation.  POS and SIZE are the values that were given.  */
4239
4240 static void
4241 report_bad_field (offsetT pos, offsetT size)
4242 {
4243   as_bad (_("Invalid field specification (position %ld, size %ld)"),
4244           (unsigned long) pos, (unsigned long) size);
4245 }
4246
4247 /* Information about an instruction argument that we're trying to match.  */
4248 struct mips_arg_info
4249 {
4250   /* The instruction so far.  */
4251   struct mips_cl_insn *insn;
4252
4253   /* The first unconsumed operand token.  */
4254   struct mips_operand_token *token;
4255
4256   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4257   int opnum;
4258
4259   /* The 1-based argument number, for error reporting.  This does not
4260      count elided optional registers, etc..  */
4261   int argnum;
4262
4263   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4264   unsigned int last_regno;
4265
4266   /* If the first operand was an OP_REG, this is the register that it
4267      specified, otherwise it is ILLEGAL_REG.  */
4268   unsigned int dest_regno;
4269
4270   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4271      where it gives the lsb position.  */
4272   unsigned int last_op_int;
4273
4274   /* If true, the OP_INT match routine should treat plain symbolic operands
4275      as if a relocation operator like %lo(...) had been used.  This is only
4276      ever true if the operand can be relocated.  */
4277   bfd_boolean allow_nonconst;
4278
4279   /* When true, the OP_INT match routine should allow unsigned N-bit
4280      arguments to be used where a signed N-bit operand is expected.  */
4281   bfd_boolean lax_max;
4282
4283   /* True if a reference to the current AT register was seen.  */
4284   bfd_boolean seen_at;
4285 };
4286
4287 /* Record that the argument is out of range.  */
4288
4289 static void
4290 match_out_of_range (struct mips_arg_info *arg)
4291 {
4292   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4293 }
4294
4295 /* Record that the argument isn't constant but needs to be.  */
4296
4297 static void
4298 match_not_constant (struct mips_arg_info *arg)
4299 {
4300   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4301                     arg->argnum);
4302 }
4303
4304 /* Try to match an OT_CHAR token for character CH.  Consume the token
4305    and return true on success, otherwise return false.  */
4306
4307 static bfd_boolean
4308 match_char (struct mips_arg_info *arg, char ch)
4309 {
4310   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4311     {
4312       ++arg->token;
4313       if (ch == ',')
4314         arg->argnum += 1;
4315       return TRUE;
4316     }
4317   return FALSE;
4318 }
4319
4320 /* Try to get an expression from the next tokens in ARG.  Consume the
4321    tokens and return true on success, storing the expression value in
4322    VALUE and relocation types in R.  */
4323
4324 static bfd_boolean
4325 match_expression (struct mips_arg_info *arg, expressionS *value,
4326                   bfd_reloc_code_real_type *r)
4327 {
4328   /* If the next token is a '(' that was parsed as being part of a base
4329      expression, assume we have an elided offset.  The later match will fail
4330      if this turns out to be wrong.  */
4331   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4332     {
4333       value->X_op = O_constant;
4334       value->X_add_number = 0;
4335       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4336       return TRUE;
4337     }
4338
4339   /* Reject register-based expressions such as "0+$2" and "(($2))".
4340      For plain registers the default error seems more appropriate.  */
4341   if (arg->token->type == OT_INTEGER
4342       && arg->token->u.integer.value.X_op == O_register)
4343     {
4344       set_insn_error (arg->argnum, _("register value used as expression"));
4345       return FALSE;
4346     }
4347
4348   if (arg->token->type == OT_INTEGER)
4349     {
4350       *value = arg->token->u.integer.value;
4351       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4352       ++arg->token;
4353       return TRUE;
4354     }
4355
4356   set_insn_error_i
4357     (arg->argnum, _("operand %d must be an immediate expression"),
4358      arg->argnum);
4359   return FALSE;
4360 }
4361
4362 /* Try to get a constant expression from the next tokens in ARG.  Consume
4363    the tokens and return return true on success, storing the constant value
4364    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4365    error.  */
4366
4367 static bfd_boolean
4368 match_const_int (struct mips_arg_info *arg, offsetT *value)
4369 {
4370   expressionS ex;
4371   bfd_reloc_code_real_type r[3];
4372
4373   if (!match_expression (arg, &ex, r))
4374     return FALSE;
4375
4376   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4377     *value = ex.X_add_number;
4378   else
4379     {
4380       match_not_constant (arg);
4381       return FALSE;
4382     }
4383   return TRUE;
4384 }
4385
4386 /* Return the RTYPE_* flags for a register operand of type TYPE that
4387    appears in instruction OPCODE.  */
4388
4389 static unsigned int
4390 convert_reg_type (const struct mips_opcode *opcode,
4391                   enum mips_reg_operand_type type)
4392 {
4393   switch (type)
4394     {
4395     case OP_REG_GP:
4396       return RTYPE_NUM | RTYPE_GP;
4397
4398     case OP_REG_FP:
4399       /* Allow vector register names for MDMX if the instruction is a 64-bit
4400          FPR load, store or move (including moves to and from GPRs).  */
4401       if ((mips_opts.ase & ASE_MDMX)
4402           && (opcode->pinfo & FP_D)
4403           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4404                                | INSN_COPROC_MEMORY_DELAY
4405                                | INSN_LOAD_COPROC_DELAY
4406                                | INSN_LOAD_MEMORY_DELAY
4407                                | INSN_STORE_MEMORY)))
4408         return RTYPE_FPU | RTYPE_VEC;
4409       return RTYPE_FPU;
4410
4411     case OP_REG_CCC:
4412       if (opcode->pinfo & (FP_D | FP_S))
4413         return RTYPE_CCC | RTYPE_FCC;
4414       return RTYPE_CCC;
4415
4416     case OP_REG_VEC:
4417       if (opcode->membership & INSN_5400)
4418         return RTYPE_FPU;
4419       return RTYPE_FPU | RTYPE_VEC;
4420
4421     case OP_REG_ACC:
4422       return RTYPE_ACC;
4423
4424     case OP_REG_COPRO:
4425       if (opcode->name[strlen (opcode->name) - 1] == '0')
4426         return RTYPE_NUM | RTYPE_CP0;
4427       return RTYPE_NUM;
4428
4429     case OP_REG_HW:
4430       return RTYPE_NUM;
4431
4432     case OP_REG_VI:
4433       return RTYPE_NUM | RTYPE_VI;
4434
4435     case OP_REG_VF:
4436       return RTYPE_NUM | RTYPE_VF;
4437
4438     case OP_REG_R5900_I:
4439       return RTYPE_R5900_I;
4440
4441     case OP_REG_R5900_Q:
4442       return RTYPE_R5900_Q;
4443
4444     case OP_REG_R5900_R:
4445       return RTYPE_R5900_R;
4446
4447     case OP_REG_R5900_ACC:
4448       return RTYPE_R5900_ACC;
4449     }
4450   abort ();
4451 }
4452
4453 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4454
4455 static void
4456 check_regno (struct mips_arg_info *arg,
4457              enum mips_reg_operand_type type, unsigned int regno)
4458 {
4459   if (AT && type == OP_REG_GP && regno == AT)
4460     arg->seen_at = TRUE;
4461
4462   if (type == OP_REG_FP
4463       && (regno & 1) != 0
4464       && HAVE_32BIT_FPRS
4465       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4466     as_warn (_("Float register should be even, was %d"), regno);
4467
4468   if (type == OP_REG_CCC)
4469     {
4470       const char *name;
4471       size_t length;
4472
4473       name = arg->insn->insn_mo->name;
4474       length = strlen (name);
4475       if ((regno & 1) != 0
4476           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4477               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4478         as_warn (_("Condition code register should be even for %s, was %d"),
4479                  name, regno);
4480
4481       if ((regno & 3) != 0
4482           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4483         as_warn (_("Condition code register should be 0 or 4 for %s, was %d"),
4484                  name, regno);
4485     }
4486 }
4487
4488 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4489    a register of type TYPE.  Return true on success, storing the register
4490    number in *REGNO and warning about any dubious uses.  */
4491
4492 static bfd_boolean
4493 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4494              unsigned int symval, unsigned int *regno)
4495 {
4496   if (type == OP_REG_VEC)
4497     symval = mips_prefer_vec_regno (symval);
4498   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4499     return FALSE;
4500
4501   *regno = symval & RNUM_MASK;
4502   check_regno (arg, type, *regno);
4503   return TRUE;
4504 }
4505
4506 /* Try to interpret the next token in ARG as a register of type TYPE.
4507    Consume the token and return true on success, storing the register
4508    number in *REGNO.  Return false on failure.  */
4509
4510 static bfd_boolean
4511 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4512            unsigned int *regno)
4513 {
4514   if (arg->token->type == OT_REG
4515       && match_regno (arg, type, arg->token->u.regno, regno))
4516     {
4517       ++arg->token;
4518       return TRUE;
4519     }
4520   return FALSE;
4521 }
4522
4523 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4524    Consume the token and return true on success, storing the register numbers
4525    in *REGNO1 and *REGNO2.  Return false on failure.  */
4526
4527 static bfd_boolean
4528 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4529                  unsigned int *regno1, unsigned int *regno2)
4530 {
4531   if (match_reg (arg, type, regno1))
4532     {
4533       *regno2 = *regno1;
4534       return TRUE;
4535     }
4536   if (arg->token->type == OT_REG_RANGE
4537       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4538       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4539       && *regno1 <= *regno2)
4540     {
4541       ++arg->token;
4542       return TRUE;
4543     }
4544   return FALSE;
4545 }
4546
4547 /* OP_INT matcher.  */
4548
4549 static bfd_boolean
4550 match_int_operand (struct mips_arg_info *arg,
4551                    const struct mips_operand *operand_base)
4552 {
4553   const struct mips_int_operand *operand;
4554   unsigned int uval;
4555   int min_val, max_val, factor;
4556   offsetT sval;
4557
4558   operand = (const struct mips_int_operand *) operand_base;
4559   factor = 1 << operand->shift;
4560   min_val = mips_int_operand_min (operand);
4561   max_val = mips_int_operand_max (operand);
4562   if (arg->lax_max)
4563     max_val = ((1 << operand_base->size) - 1) << operand->shift;
4564
4565   if (operand_base->lsb == 0
4566       && operand_base->size == 16
4567       && operand->shift == 0
4568       && operand->bias == 0
4569       && (operand->max_val == 32767 || operand->max_val == 65535))
4570     {
4571       /* The operand can be relocated.  */
4572       if (!match_expression (arg, &offset_expr, offset_reloc))
4573         return FALSE;
4574
4575       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4576         /* Relocation operators were used.  Accept the arguent and
4577            leave the relocation value in offset_expr and offset_relocs
4578            for the caller to process.  */
4579         return TRUE;
4580
4581       if (offset_expr.X_op != O_constant)
4582         {
4583           /* If non-constant operands are allowed then leave them for
4584              the caller to process, otherwise fail the match.  */
4585           if (!arg->allow_nonconst)
4586             {
4587               match_not_constant (arg);
4588               return FALSE;
4589             }
4590           offset_reloc[0] = BFD_RELOC_LO16;
4591           return TRUE;
4592         }
4593
4594       /* Clear the global state; we're going to install the operand
4595          ourselves.  */
4596       sval = offset_expr.X_add_number;
4597       offset_expr.X_op = O_absent;
4598     }
4599   else
4600     {
4601       if (!match_const_int (arg, &sval))
4602         return FALSE;
4603     }
4604
4605   arg->last_op_int = sval;
4606
4607   if (sval < min_val || sval > max_val || sval % factor)
4608     {
4609       match_out_of_range (arg);
4610       return FALSE;
4611     }
4612
4613   uval = (unsigned int) sval >> operand->shift;
4614   uval -= operand->bias;
4615
4616   /* Handle -mfix-cn63xxp1.  */
4617   if (arg->opnum == 1
4618       && mips_fix_cn63xxp1
4619       && !mips_opts.micromips
4620       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4621     switch (uval)
4622       {
4623       case 5:
4624       case 25:
4625       case 26:
4626       case 27:
4627       case 28:
4628       case 29:
4629       case 30:
4630       case 31:
4631         /* These are ok.  */
4632         break;
4633
4634       default:
4635         /* The rest must be changed to 28.  */
4636         uval = 28;
4637         break;
4638       }
4639
4640   insn_insert_operand (arg->insn, operand_base, uval);
4641   return TRUE;
4642 }
4643
4644 /* OP_MAPPED_INT matcher.  */
4645
4646 static bfd_boolean
4647 match_mapped_int_operand (struct mips_arg_info *arg,
4648                           const struct mips_operand *operand_base)
4649 {
4650   const struct mips_mapped_int_operand *operand;
4651   unsigned int uval, num_vals;
4652   offsetT sval;
4653
4654   operand = (const struct mips_mapped_int_operand *) operand_base;
4655   if (!match_const_int (arg, &sval))
4656     return FALSE;
4657
4658   num_vals = 1 << operand_base->size;
4659   for (uval = 0; uval < num_vals; uval++)
4660     if (operand->int_map[uval] == sval)
4661       break;
4662   if (uval == num_vals)
4663     {
4664       match_out_of_range (arg);
4665       return FALSE;
4666     }
4667
4668   insn_insert_operand (arg->insn, operand_base, uval);
4669   return TRUE;
4670 }
4671
4672 /* OP_MSB matcher.  */
4673
4674 static bfd_boolean
4675 match_msb_operand (struct mips_arg_info *arg,
4676                    const struct mips_operand *operand_base)
4677 {
4678   const struct mips_msb_operand *operand;
4679   int min_val, max_val, max_high;
4680   offsetT size, sval, high;
4681
4682   operand = (const struct mips_msb_operand *) operand_base;
4683   min_val = operand->bias;
4684   max_val = min_val + (1 << operand_base->size) - 1;
4685   max_high = operand->opsize;
4686
4687   if (!match_const_int (arg, &size))
4688     return FALSE;
4689
4690   high = size + arg->last_op_int;
4691   sval = operand->add_lsb ? high : size;
4692
4693   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4694     {
4695       match_out_of_range (arg);
4696       return FALSE;
4697     }
4698   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4699   return TRUE;
4700 }
4701
4702 /* OP_REG matcher.  */
4703
4704 static bfd_boolean
4705 match_reg_operand (struct mips_arg_info *arg,
4706                    const struct mips_operand *operand_base)
4707 {
4708   const struct mips_reg_operand *operand;
4709   unsigned int regno, uval, num_vals;
4710
4711   operand = (const struct mips_reg_operand *) operand_base;
4712   if (!match_reg (arg, operand->reg_type, &regno))
4713     return FALSE;
4714
4715   if (operand->reg_map)
4716     {
4717       num_vals = 1 << operand->root.size;
4718       for (uval = 0; uval < num_vals; uval++)
4719         if (operand->reg_map[uval] == regno)
4720           break;
4721       if (num_vals == uval)
4722         return FALSE;
4723     }
4724   else
4725     uval = regno;
4726
4727   arg->last_regno = regno;
4728   if (arg->opnum == 1)
4729     arg->dest_regno = regno;
4730   insn_insert_operand (arg->insn, operand_base, uval);
4731   return TRUE;
4732 }
4733
4734 /* OP_REG_PAIR matcher.  */
4735
4736 static bfd_boolean
4737 match_reg_pair_operand (struct mips_arg_info *arg,
4738                         const struct mips_operand *operand_base)
4739 {
4740   const struct mips_reg_pair_operand *operand;
4741   unsigned int regno1, regno2, uval, num_vals;
4742
4743   operand = (const struct mips_reg_pair_operand *) operand_base;
4744   if (!match_reg (arg, operand->reg_type, &regno1)
4745       || !match_char (arg, ',')
4746       || !match_reg (arg, operand->reg_type, &regno2))
4747     return FALSE;
4748
4749   num_vals = 1 << operand_base->size;
4750   for (uval = 0; uval < num_vals; uval++)
4751     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4752       break;
4753   if (uval == num_vals)
4754     return FALSE;
4755
4756   insn_insert_operand (arg->insn, operand_base, uval);
4757   return TRUE;
4758 }
4759
4760 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4761
4762 static bfd_boolean
4763 match_pcrel_operand (struct mips_arg_info *arg)
4764 {
4765   bfd_reloc_code_real_type r[3];
4766
4767   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4768 }
4769
4770 /* OP_PERF_REG matcher.  */
4771
4772 static bfd_boolean
4773 match_perf_reg_operand (struct mips_arg_info *arg,
4774                         const struct mips_operand *operand)
4775 {
4776   offsetT sval;
4777
4778   if (!match_const_int (arg, &sval))
4779     return FALSE;
4780
4781   if (sval != 0
4782       && (sval != 1
4783           || (mips_opts.arch == CPU_R5900
4784               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4785                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4786     {
4787       set_insn_error (arg->argnum, _("invalid performance register"));
4788       return FALSE;
4789     }
4790
4791   insn_insert_operand (arg->insn, operand, sval);
4792   return TRUE;
4793 }
4794
4795 /* OP_ADDIUSP matcher.  */
4796
4797 static bfd_boolean
4798 match_addiusp_operand (struct mips_arg_info *arg,
4799                        const struct mips_operand *operand)
4800 {
4801   offsetT sval;
4802   unsigned int uval;
4803
4804   if (!match_const_int (arg, &sval))
4805     return FALSE;
4806
4807   if (sval % 4)
4808     {
4809       match_out_of_range (arg);
4810       return FALSE;
4811     }
4812
4813   sval /= 4;
4814   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4815     {
4816       match_out_of_range (arg);
4817       return FALSE;
4818     }
4819
4820   uval = (unsigned int) sval;
4821   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4822   insn_insert_operand (arg->insn, operand, uval);
4823   return TRUE;
4824 }
4825
4826 /* OP_CLO_CLZ_DEST matcher.  */
4827
4828 static bfd_boolean
4829 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4830                             const struct mips_operand *operand)
4831 {
4832   unsigned int regno;
4833
4834   if (!match_reg (arg, OP_REG_GP, &regno))
4835     return FALSE;
4836
4837   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4838   return TRUE;
4839 }
4840
4841 /* OP_LWM_SWM_LIST matcher.  */
4842
4843 static bfd_boolean
4844 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4845                             const struct mips_operand *operand)
4846 {
4847   unsigned int reglist, sregs, ra, regno1, regno2;
4848   struct mips_arg_info reset;
4849
4850   reglist = 0;
4851   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4852     return FALSE;
4853   do
4854     {
4855       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
4856         {
4857           reglist |= 1 << FP;
4858           regno2 = S7;
4859         }
4860       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
4861       reset = *arg;
4862     }
4863   while (match_char (arg, ',')
4864          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
4865   *arg = reset;
4866
4867   if (operand->size == 2)
4868     {
4869       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4870
4871          s0, ra
4872          s0, s1, ra, s2, s3
4873          s0-s2, ra
4874
4875          and any permutations of these.  */
4876       if ((reglist & 0xfff1ffff) != 0x80010000)
4877         return FALSE;
4878
4879       sregs = (reglist >> 17) & 7;
4880       ra = 0;
4881     }
4882   else
4883     {
4884       /* The list must include at least one of ra and s0-sN,
4885          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4886          which are $23 and $30 respectively.)  E.g.:
4887
4888          ra
4889          s0
4890          ra, s0, s1, s2
4891          s0-s8
4892          s0-s5, ra
4893
4894          and any permutations of these.  */
4895       if ((reglist & 0x3f00ffff) != 0)
4896         return FALSE;
4897
4898       ra = (reglist >> 27) & 0x10;
4899       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4900     }
4901   sregs += 1;
4902   if ((sregs & -sregs) != sregs)
4903     return FALSE;
4904
4905   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4906   return TRUE;
4907 }
4908
4909 /* OP_ENTRY_EXIT_LIST matcher.  */
4910
4911 static unsigned int
4912 match_entry_exit_operand (struct mips_arg_info *arg,
4913                           const struct mips_operand *operand)
4914 {
4915   unsigned int mask;
4916   bfd_boolean is_exit;
4917
4918   /* The format is the same for both ENTRY and EXIT, but the constraints
4919      are different.  */
4920   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4921   mask = (is_exit ? 7 << 3 : 0);
4922   do
4923     {
4924       unsigned int regno1, regno2;
4925       bfd_boolean is_freg;
4926
4927       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4928         is_freg = FALSE;
4929       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
4930         is_freg = TRUE;
4931       else
4932         return FALSE;
4933
4934       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4935         {
4936           mask &= ~(7 << 3);
4937           mask |= (5 + regno2) << 3;
4938         }
4939       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4940         mask |= (regno2 - 3) << 3;
4941       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4942         mask |= (regno2 - 15) << 1;
4943       else if (regno1 == RA && regno2 == RA)
4944         mask |= 1;
4945       else
4946         return FALSE;
4947     }
4948   while (match_char (arg, ','));
4949
4950   insn_insert_operand (arg->insn, operand, mask);
4951   return TRUE;
4952 }
4953
4954 /* OP_SAVE_RESTORE_LIST matcher.  */
4955
4956 static bfd_boolean
4957 match_save_restore_list_operand (struct mips_arg_info *arg)
4958 {
4959   unsigned int opcode, args, statics, sregs;
4960   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4961   offsetT frame_size;
4962
4963   opcode = arg->insn->insn_opcode;
4964   frame_size = 0;
4965   num_frame_sizes = 0;
4966   args = 0;
4967   statics = 0;
4968   sregs = 0;
4969   do
4970     {
4971       unsigned int regno1, regno2;
4972
4973       if (arg->token->type == OT_INTEGER)
4974         {
4975           /* Handle the frame size.  */
4976           if (!match_const_int (arg, &frame_size))
4977             return FALSE;
4978           num_frame_sizes += 1;
4979         }
4980       else
4981         {
4982           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4983             return FALSE;
4984
4985           while (regno1 <= regno2)
4986             {
4987               if (regno1 >= 4 && regno1 <= 7)
4988                 {
4989                   if (num_frame_sizes == 0)
4990                     /* args $a0-$a3 */
4991                     args |= 1 << (regno1 - 4);
4992                   else
4993                     /* statics $a0-$a3 */
4994                     statics |= 1 << (regno1 - 4);
4995                 }
4996               else if (regno1 >= 16 && regno1 <= 23)
4997                 /* $s0-$s7 */
4998                 sregs |= 1 << (regno1 - 16);
4999               else if (regno1 == 30)
5000                 /* $s8 */
5001                 sregs |= 1 << 8;
5002               else if (regno1 == 31)
5003                 /* Add $ra to insn.  */
5004                 opcode |= 0x40;
5005               else
5006                 return FALSE;
5007               regno1 += 1;
5008               if (regno1 == 24)
5009                 regno1 = 30;
5010             }
5011         }
5012     }
5013   while (match_char (arg, ','));
5014
5015   /* Encode args/statics combination.  */
5016   if (args & statics)
5017     return FALSE;
5018   else if (args == 0xf)
5019     /* All $a0-$a3 are args.  */
5020     opcode |= MIPS16_ALL_ARGS << 16;
5021   else if (statics == 0xf)
5022     /* All $a0-$a3 are statics.  */
5023     opcode |= MIPS16_ALL_STATICS << 16;
5024   else
5025     {
5026       /* Count arg registers.  */
5027       num_args = 0;
5028       while (args & 0x1)
5029         {
5030           args >>= 1;
5031           num_args += 1;
5032         }
5033       if (args != 0)
5034         return FALSE;
5035
5036       /* Count static registers.  */
5037       num_statics = 0;
5038       while (statics & 0x8)
5039         {
5040           statics = (statics << 1) & 0xf;
5041           num_statics += 1;
5042         }
5043       if (statics != 0)
5044         return FALSE;
5045
5046       /* Encode args/statics.  */
5047       opcode |= ((num_args << 2) | num_statics) << 16;
5048     }
5049
5050   /* Encode $s0/$s1.  */
5051   if (sregs & (1 << 0))         /* $s0 */
5052     opcode |= 0x20;
5053   if (sregs & (1 << 1))         /* $s1 */
5054     opcode |= 0x10;
5055   sregs >>= 2;
5056
5057   /* Encode $s2-$s8. */
5058   num_sregs = 0;
5059   while (sregs & 1)
5060     {
5061       sregs >>= 1;
5062       num_sregs += 1;
5063     }
5064   if (sregs != 0)
5065     return FALSE;
5066   opcode |= num_sregs << 24;
5067
5068   /* Encode frame size.  */
5069   if (num_frame_sizes == 0)
5070     {
5071       set_insn_error (arg->argnum, _("missing frame size"));
5072       return FALSE;
5073     }
5074   if (num_frame_sizes > 1)
5075     {
5076       set_insn_error (arg->argnum, _("frame size specified twice"));
5077       return FALSE;
5078     }
5079   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5080     {
5081       set_insn_error (arg->argnum, _("invalid frame size"));
5082       return FALSE;
5083     }
5084   if (frame_size != 128 || (opcode >> 16) != 0)
5085     {
5086       frame_size /= 8;
5087       opcode |= (((frame_size & 0xf0) << 16)
5088                  | (frame_size & 0x0f));
5089     }
5090
5091   /* Finally build the instruction.  */
5092   if ((opcode >> 16) != 0 || frame_size == 0)
5093     opcode |= MIPS16_EXTEND;
5094   arg->insn->insn_opcode = opcode;
5095   return TRUE;
5096 }
5097
5098 /* OP_MDMX_IMM_REG matcher.  */
5099
5100 static bfd_boolean
5101 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5102                             const struct mips_operand *operand)
5103 {
5104   unsigned int regno, uval;
5105   bfd_boolean is_qh;
5106   const struct mips_opcode *opcode;
5107
5108   /* The mips_opcode records whether this is an octobyte or quadhalf
5109      instruction.  Start out with that bit in place.  */
5110   opcode = arg->insn->insn_mo;
5111   uval = mips_extract_operand (operand, opcode->match);
5112   is_qh = (uval != 0);
5113
5114   if (arg->token->type == OT_REG || arg->token->type == OT_REG_ELEMENT)
5115     {
5116       if ((opcode->membership & INSN_5400)
5117           && strcmp (opcode->name, "rzu.ob") == 0)
5118         {
5119           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5120                             arg->argnum);
5121           return FALSE;
5122         }
5123
5124       /* Check whether this is a vector register or a broadcast of
5125          a single element.  */
5126       if (arg->token->type == OT_REG_ELEMENT)
5127         {
5128           if (!match_regno (arg, OP_REG_VEC, arg->token->u.reg_element.regno,
5129                             &regno))
5130             return FALSE;
5131           if (arg->token->u.reg_element.index > (is_qh ? 3 : 7))
5132             {
5133               set_insn_error (arg->argnum, _("invalid element selector"));
5134               return FALSE;
5135             }
5136           else
5137             uval |= arg->token->u.reg_element.index << (is_qh ? 2 : 1) << 5;
5138         }
5139       else
5140         {
5141           /* A full vector.  */
5142           if ((opcode->membership & INSN_5400)
5143               && (strcmp (opcode->name, "sll.ob") == 0
5144                   || strcmp (opcode->name, "srl.ob") == 0))
5145             {
5146               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5147                                 arg->argnum);
5148               return FALSE;
5149             }
5150
5151           if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5152             return FALSE;
5153           if (is_qh)
5154             uval |= MDMX_FMTSEL_VEC_QH << 5;
5155           else
5156             uval |= MDMX_FMTSEL_VEC_OB << 5;
5157         }
5158       uval |= regno;
5159       ++arg->token;
5160     }
5161   else
5162     {
5163       offsetT sval;
5164
5165       if (!match_const_int (arg, &sval))
5166         return FALSE;
5167       if (sval < 0 || sval > 31)
5168         {
5169           match_out_of_range (arg);
5170           return FALSE;
5171         }
5172       uval |= (sval & 31);
5173       if (is_qh)
5174         uval |= MDMX_FMTSEL_IMM_QH << 5;
5175       else
5176         uval |= MDMX_FMTSEL_IMM_OB << 5;
5177     }
5178   insn_insert_operand (arg->insn, operand, uval);
5179   return TRUE;
5180 }
5181
5182 /* OP_PC matcher.  */
5183
5184 static bfd_boolean
5185 match_pc_operand (struct mips_arg_info *arg)
5186 {
5187   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5188     {
5189       ++arg->token;
5190       return TRUE;
5191     }
5192   return FALSE;
5193 }
5194
5195 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5196    register that we need to match.  */
5197
5198 static bfd_boolean
5199 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5200 {
5201   unsigned int regno;
5202
5203   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5204 }
5205
5206 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5207    the length of the value in bytes (4 for float, 8 for double) and
5208    USING_GPRS says whether the destination is a GPR rather than an FPR.
5209
5210    Return the constant in IMM and OFFSET as follows:
5211
5212    - If the constant should be loaded via memory, set IMM to O_absent and
5213      OFFSET to the memory address.
5214
5215    - Otherwise, if the constant should be loaded into two 32-bit registers,
5216      set IMM to the O_constant to load into the high register and OFFSET
5217      to the corresponding value for the low register.
5218
5219    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5220
5221    These constants only appear as the last operand in an instruction,
5222    and every instruction that accepts them in any variant accepts them
5223    in all variants.  This means we don't have to worry about backing out
5224    any changes if the instruction does not match.  We just match
5225    unconditionally and report an error if the constant is invalid.  */
5226
5227 static bfd_boolean
5228 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5229                       expressionS *offset, int length, bfd_boolean using_gprs)
5230 {
5231   char *p;
5232   segT seg, new_seg;
5233   subsegT subseg;
5234   const char *newname;
5235   unsigned char *data;
5236
5237   /* Where the constant is placed is based on how the MIPS assembler
5238      does things:
5239
5240      length == 4 && using_gprs  -- immediate value only
5241      length == 8 && using_gprs  -- .rdata or immediate value
5242      length == 4 && !using_gprs -- .lit4 or immediate value
5243      length == 8 && !using_gprs -- .lit8 or immediate value
5244
5245      The .lit4 and .lit8 sections are only used if permitted by the
5246      -G argument.  */
5247   if (arg->token->type != OT_FLOAT)
5248     {
5249       set_insn_error (arg->argnum, _("floating-point expression required"));
5250       return FALSE;
5251     }
5252
5253   gas_assert (arg->token->u.flt.length == length);
5254   data = arg->token->u.flt.data;
5255   ++arg->token;
5256
5257   /* Handle 32-bit constants for which an immediate value is best.  */
5258   if (length == 4
5259       && (using_gprs
5260           || g_switch_value < 4
5261           || (data[0] == 0 && data[1] == 0)
5262           || (data[2] == 0 && data[3] == 0)))
5263     {
5264       imm->X_op = O_constant;
5265       if (!target_big_endian)
5266         imm->X_add_number = bfd_getl32 (data);
5267       else
5268         imm->X_add_number = bfd_getb32 (data);
5269       offset->X_op = O_absent;
5270       return TRUE;
5271     }
5272
5273   /* Handle 64-bit constants for which an immediate value is best.  */
5274   if (length == 8
5275       && !mips_disable_float_construction
5276       /* Constants can only be constructed in GPRs and copied
5277          to FPRs if the GPRs are at least as wide as the FPRs.
5278          Force the constant into memory if we are using 64-bit FPRs
5279          but the GPRs are only 32 bits wide.  */
5280       /* ??? No longer true with the addition of MTHC1, but this
5281          is legacy code...  */
5282       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
5283       && ((data[0] == 0 && data[1] == 0)
5284           || (data[2] == 0 && data[3] == 0))
5285       && ((data[4] == 0 && data[5] == 0)
5286           || (data[6] == 0 && data[7] == 0)))
5287     {
5288       /* The value is simple enough to load with a couple of instructions.
5289          If using 32-bit registers, set IMM to the high order 32 bits and
5290          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5291          64 bit constant.  */
5292       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
5293         {
5294           imm->X_op = O_constant;
5295           offset->X_op = O_constant;
5296           if (!target_big_endian)
5297             {
5298               imm->X_add_number = bfd_getl32 (data + 4);
5299               offset->X_add_number = bfd_getl32 (data);
5300             }
5301           else
5302             {
5303               imm->X_add_number = bfd_getb32 (data);
5304               offset->X_add_number = bfd_getb32 (data + 4);
5305             }
5306           if (offset->X_add_number == 0)
5307             offset->X_op = O_absent;
5308         }
5309       else
5310         {
5311           imm->X_op = O_constant;
5312           if (!target_big_endian)
5313             imm->X_add_number = bfd_getl64 (data);
5314           else
5315             imm->X_add_number = bfd_getb64 (data);
5316           offset->X_op = O_absent;
5317         }
5318       return TRUE;
5319     }
5320
5321   /* Switch to the right section.  */
5322   seg = now_seg;
5323   subseg = now_subseg;
5324   if (length == 4)
5325     {
5326       gas_assert (!using_gprs && g_switch_value >= 4);
5327       newname = ".lit4";
5328     }
5329   else
5330     {
5331       if (using_gprs || g_switch_value < 8)
5332         newname = RDATA_SECTION_NAME;
5333       else
5334         newname = ".lit8";
5335     }
5336
5337   new_seg = subseg_new (newname, (subsegT) 0);
5338   bfd_set_section_flags (stdoutput, new_seg,
5339                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5340   frag_align (length == 4 ? 2 : 3, 0, 0);
5341   if (strncmp (TARGET_OS, "elf", 3) != 0)
5342     record_alignment (new_seg, 4);
5343   else
5344     record_alignment (new_seg, length == 4 ? 2 : 3);
5345   if (seg == now_seg)
5346     as_bad (_("Can't use floating point insn in this section"));
5347
5348   /* Set the argument to the current address in the section.  */
5349   imm->X_op = O_absent;
5350   offset->X_op = O_symbol;
5351   offset->X_add_symbol = symbol_temp_new_now ();
5352   offset->X_add_number = 0;
5353
5354   /* Put the floating point number into the section.  */
5355   p = frag_more (length);
5356   memcpy (p, data, length);
5357
5358   /* Switch back to the original section.  */
5359   subseg_set (seg, subseg);
5360   return TRUE;
5361 }
5362
5363 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5364    them.  */
5365
5366 static bfd_boolean
5367 match_vu0_suffix_operand (struct mips_arg_info *arg,
5368                           const struct mips_operand *operand,
5369                           bfd_boolean match_p)
5370 {
5371   unsigned int uval;
5372
5373   /* The operand can be an XYZW mask or a single 2-bit channel index
5374      (with X being 0).  */
5375   gas_assert (operand->size == 2 || operand->size == 4);
5376
5377   /* The suffix can be omitted when it is already part of the opcode.  */
5378   if (arg->token->type != OT_CHANNELS)
5379     return match_p;
5380
5381   uval = arg->token->u.channels;
5382   if (operand->size == 2)
5383     {
5384       /* Check that a single bit is set and convert it into a 2-bit index.  */
5385       if ((uval & -uval) != uval)
5386         return FALSE;
5387       uval = 4 - ffs (uval);
5388     }
5389
5390   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5391     return FALSE;
5392
5393   ++arg->token;
5394   if (!match_p)
5395     insn_insert_operand (arg->insn, operand, uval);
5396   return TRUE;
5397 }
5398
5399 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5400    of the argument text if the match is successful, otherwise return null.  */
5401
5402 static bfd_boolean
5403 match_operand (struct mips_arg_info *arg,
5404                const struct mips_operand *operand)
5405 {
5406   switch (operand->type)
5407     {
5408     case OP_INT:
5409       return match_int_operand (arg, operand);
5410
5411     case OP_MAPPED_INT:
5412       return match_mapped_int_operand (arg, operand);
5413
5414     case OP_MSB:
5415       return match_msb_operand (arg, operand);
5416
5417     case OP_REG:
5418     case OP_OPTIONAL_REG:
5419       return match_reg_operand (arg, operand);
5420
5421     case OP_REG_PAIR:
5422       return match_reg_pair_operand (arg, operand);
5423
5424     case OP_PCREL:
5425       return match_pcrel_operand (arg);
5426
5427     case OP_PERF_REG:
5428       return match_perf_reg_operand (arg, operand);
5429
5430     case OP_ADDIUSP_INT:
5431       return match_addiusp_operand (arg, operand);
5432
5433     case OP_CLO_CLZ_DEST:
5434       return match_clo_clz_dest_operand (arg, operand);
5435
5436     case OP_LWM_SWM_LIST:
5437       return match_lwm_swm_list_operand (arg, operand);
5438
5439     case OP_ENTRY_EXIT_LIST:
5440       return match_entry_exit_operand (arg, operand);
5441
5442     case OP_SAVE_RESTORE_LIST:
5443       return match_save_restore_list_operand (arg);
5444
5445     case OP_MDMX_IMM_REG:
5446       return match_mdmx_imm_reg_operand (arg, operand);
5447
5448     case OP_REPEAT_DEST_REG:
5449       return match_tied_reg_operand (arg, arg->dest_regno);
5450
5451     case OP_REPEAT_PREV_REG:
5452       return match_tied_reg_operand (arg, arg->last_regno);
5453
5454     case OP_PC:
5455       return match_pc_operand (arg);
5456
5457     case OP_VU0_SUFFIX:
5458       return match_vu0_suffix_operand (arg, operand, FALSE);
5459
5460     case OP_VU0_MATCH_SUFFIX:
5461       return match_vu0_suffix_operand (arg, operand, TRUE);
5462     }
5463   abort ();
5464 }
5465
5466 /* ARG is the state after successfully matching an instruction.
5467    Issue any queued-up warnings.  */
5468
5469 static void
5470 check_completed_insn (struct mips_arg_info *arg)
5471 {
5472   if (arg->seen_at)
5473     {
5474       if (AT == ATREG)
5475         as_warn (_("Used $at without \".set noat\""));
5476       else
5477         as_warn (_("Used $%u with \".set at=$%u\""), AT, AT);
5478     }
5479 }
5480
5481 /* Return true if modifying general-purpose register REG needs a delay.  */
5482
5483 static bfd_boolean
5484 reg_needs_delay (unsigned int reg)
5485 {
5486   unsigned long prev_pinfo;
5487
5488   prev_pinfo = history[0].insn_mo->pinfo;
5489   if (!mips_opts.noreorder
5490       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY) && !gpr_interlocks)
5491           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5492       && (gpr_write_mask (&history[0]) & (1 << reg)))
5493     return TRUE;
5494
5495   return FALSE;
5496 }
5497
5498 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5499    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5500    by VR4120 errata.  */
5501
5502 static unsigned int
5503 classify_vr4120_insn (const char *name)
5504 {
5505   if (strncmp (name, "macc", 4) == 0)
5506     return FIX_VR4120_MACC;
5507   if (strncmp (name, "dmacc", 5) == 0)
5508     return FIX_VR4120_DMACC;
5509   if (strncmp (name, "mult", 4) == 0)
5510     return FIX_VR4120_MULT;
5511   if (strncmp (name, "dmult", 5) == 0)
5512     return FIX_VR4120_DMULT;
5513   if (strstr (name, "div"))
5514     return FIX_VR4120_DIV;
5515   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5516     return FIX_VR4120_MTHILO;
5517   return NUM_FIX_VR4120_CLASSES;
5518 }
5519
5520 #define INSN_ERET  0x42000018
5521 #define INSN_DERET 0x4200001f
5522
5523 /* Return the number of instructions that must separate INSN1 and INSN2,
5524    where INSN1 is the earlier instruction.  Return the worst-case value
5525    for any INSN2 if INSN2 is null.  */
5526
5527 static unsigned int
5528 insns_between (const struct mips_cl_insn *insn1,
5529                const struct mips_cl_insn *insn2)
5530 {
5531   unsigned long pinfo1, pinfo2;
5532   unsigned int mask;
5533
5534   /* If INFO2 is null, pessimistically assume that all flags are set for
5535      the second instruction.  */
5536   pinfo1 = insn1->insn_mo->pinfo;
5537   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5538
5539   /* For most targets, write-after-read dependencies on the HI and LO
5540      registers must be separated by at least two instructions.  */
5541   if (!hilo_interlocks)
5542     {
5543       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5544         return 2;
5545       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5546         return 2;
5547     }
5548
5549   /* If we're working around r7000 errata, there must be two instructions
5550      between an mfhi or mflo and any instruction that uses the result.  */
5551   if (mips_7000_hilo_fix
5552       && !mips_opts.micromips
5553       && MF_HILO_INSN (pinfo1)
5554       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5555     return 2;
5556
5557   /* If we're working around 24K errata, one instruction is required
5558      if an ERET or DERET is followed by a branch instruction.  */
5559   if (mips_fix_24k && !mips_opts.micromips)
5560     {
5561       if (insn1->insn_opcode == INSN_ERET
5562           || insn1->insn_opcode == INSN_DERET)
5563         {
5564           if (insn2 == NULL
5565               || insn2->insn_opcode == INSN_ERET
5566               || insn2->insn_opcode == INSN_DERET
5567               || delayed_branch_p (insn2))
5568             return 1;
5569         }
5570     }
5571
5572   /* If working around VR4120 errata, check for combinations that need
5573      a single intervening instruction.  */
5574   if (mips_fix_vr4120 && !mips_opts.micromips)
5575     {
5576       unsigned int class1, class2;
5577
5578       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5579       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5580         {
5581           if (insn2 == NULL)
5582             return 1;
5583           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5584           if (vr4120_conflicts[class1] & (1 << class2))
5585             return 1;
5586         }
5587     }
5588
5589   if (!HAVE_CODE_COMPRESSION)
5590     {
5591       /* Check for GPR or coprocessor load delays.  All such delays
5592          are on the RT register.  */
5593       /* Itbl support may require additional care here.  */
5594       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
5595           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5596         {
5597           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5598             return 1;
5599         }
5600
5601       /* Check for generic coprocessor hazards.
5602
5603          This case is not handled very well.  There is no special
5604          knowledge of CP0 handling, and the coprocessors other than
5605          the floating point unit are not distinguished at all.  */
5606       /* Itbl support may require additional care here. FIXME!
5607          Need to modify this to include knowledge about
5608          user specified delays!  */
5609       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5610                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5611         {
5612           /* Handle cases where INSN1 writes to a known general coprocessor
5613              register.  There must be a one instruction delay before INSN2
5614              if INSN2 reads that register, otherwise no delay is needed.  */
5615           mask = fpr_write_mask (insn1);
5616           if (mask != 0)
5617             {
5618               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5619                 return 1;
5620             }
5621           else
5622             {
5623               /* Read-after-write dependencies on the control registers
5624                  require a two-instruction gap.  */
5625               if ((pinfo1 & INSN_WRITE_COND_CODE)
5626                   && (pinfo2 & INSN_READ_COND_CODE))
5627                 return 2;
5628
5629               /* We don't know exactly what INSN1 does.  If INSN2 is
5630                  also a coprocessor instruction, assume there must be
5631                  a one instruction gap.  */
5632               if (pinfo2 & INSN_COP)
5633                 return 1;
5634             }
5635         }
5636
5637       /* Check for read-after-write dependencies on the coprocessor
5638          control registers in cases where INSN1 does not need a general
5639          coprocessor delay.  This means that INSN1 is a floating point
5640          comparison instruction.  */
5641       /* Itbl support may require additional care here.  */
5642       else if (!cop_interlocks
5643                && (pinfo1 & INSN_WRITE_COND_CODE)
5644                && (pinfo2 & INSN_READ_COND_CODE))
5645         return 1;
5646     }
5647
5648   return 0;
5649 }
5650
5651 /* Return the number of nops that would be needed to work around the
5652    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5653    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5654    that are contained within the first IGNORE instructions of HIST.  */
5655
5656 static int
5657 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5658                  const struct mips_cl_insn *insn)
5659 {
5660   int i, j;
5661   unsigned int mask;
5662
5663   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5664      are not affected by the errata.  */
5665   if (insn != 0
5666       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5667           || strcmp (insn->insn_mo->name, "mtlo") == 0
5668           || strcmp (insn->insn_mo->name, "mthi") == 0))
5669     return 0;
5670
5671   /* Search for the first MFLO or MFHI.  */
5672   for (i = 0; i < MAX_VR4130_NOPS; i++)
5673     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5674       {
5675         /* Extract the destination register.  */
5676         mask = gpr_write_mask (&hist[i]);
5677
5678         /* No nops are needed if INSN reads that register.  */
5679         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5680           return 0;
5681
5682         /* ...or if any of the intervening instructions do.  */
5683         for (j = 0; j < i; j++)
5684           if (gpr_read_mask (&hist[j]) & mask)
5685             return 0;
5686
5687         if (i >= ignore)
5688           return MAX_VR4130_NOPS - i;
5689       }
5690   return 0;
5691 }
5692
5693 #define BASE_REG_EQ(INSN1, INSN2)       \
5694   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5695       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5696
5697 /* Return the minimum alignment for this store instruction.  */
5698
5699 static int
5700 fix_24k_align_to (const struct mips_opcode *mo)
5701 {
5702   if (strcmp (mo->name, "sh") == 0)
5703     return 2;
5704
5705   if (strcmp (mo->name, "swc1") == 0
5706       || strcmp (mo->name, "swc2") == 0
5707       || strcmp (mo->name, "sw") == 0
5708       || strcmp (mo->name, "sc") == 0
5709       || strcmp (mo->name, "s.s") == 0)
5710     return 4;
5711
5712   if (strcmp (mo->name, "sdc1") == 0
5713       || strcmp (mo->name, "sdc2") == 0
5714       || strcmp (mo->name, "s.d") == 0)
5715     return 8;
5716
5717   /* sb, swl, swr */
5718   return 1;
5719 }
5720
5721 struct fix_24k_store_info
5722   {
5723     /* Immediate offset, if any, for this store instruction.  */
5724     short off;
5725     /* Alignment required by this store instruction.  */
5726     int align_to;
5727     /* True for register offsets.  */
5728     int register_offset;
5729   };
5730
5731 /* Comparison function used by qsort.  */
5732
5733 static int
5734 fix_24k_sort (const void *a, const void *b)
5735 {
5736   const struct fix_24k_store_info *pos1 = a;
5737   const struct fix_24k_store_info *pos2 = b;
5738
5739   return (pos1->off - pos2->off);
5740 }
5741
5742 /* INSN is a store instruction.  Try to record the store information
5743    in STINFO.  Return false if the information isn't known.  */
5744
5745 static bfd_boolean
5746 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5747                            const struct mips_cl_insn *insn)
5748 {
5749   /* The instruction must have a known offset.  */
5750   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5751     return FALSE;
5752
5753   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5754   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5755   return TRUE;
5756 }
5757
5758 /* Return the number of nops that would be needed to work around the 24k
5759    "lost data on stores during refill" errata if instruction INSN
5760    immediately followed the 2 instructions described by HIST.
5761    Ignore hazards that are contained within the first IGNORE
5762    instructions of HIST.
5763
5764    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5765    for the data cache refills and store data. The following describes
5766    the scenario where the store data could be lost.
5767
5768    * A data cache miss, due to either a load or a store, causing fill
5769      data to be supplied by the memory subsystem
5770    * The first three doublewords of fill data are returned and written
5771      into the cache
5772    * A sequence of four stores occurs in consecutive cycles around the
5773      final doubleword of the fill:
5774    * Store A
5775    * Store B
5776    * Store C
5777    * Zero, One or more instructions
5778    * Store D
5779
5780    The four stores A-D must be to different doublewords of the line that
5781    is being filled. The fourth instruction in the sequence above permits
5782    the fill of the final doubleword to be transferred from the FSB into
5783    the cache. In the sequence above, the stores may be either integer
5784    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5785    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5786    different doublewords on the line. If the floating point unit is
5787    running in 1:2 mode, it is not possible to create the sequence above
5788    using only floating point store instructions.
5789
5790    In this case, the cache line being filled is incorrectly marked
5791    invalid, thereby losing the data from any store to the line that
5792    occurs between the original miss and the completion of the five
5793    cycle sequence shown above.
5794
5795    The workarounds are:
5796
5797    * Run the data cache in write-through mode.
5798    * Insert a non-store instruction between
5799      Store A and Store B or Store B and Store C.  */
5800   
5801 static int
5802 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5803               const struct mips_cl_insn *insn)
5804 {
5805   struct fix_24k_store_info pos[3];
5806   int align, i, base_offset;
5807
5808   if (ignore >= 2)
5809     return 0;
5810
5811   /* If the previous instruction wasn't a store, there's nothing to
5812      worry about.  */
5813   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5814     return 0;
5815
5816   /* If the instructions after the previous one are unknown, we have
5817      to assume the worst.  */
5818   if (!insn)
5819     return 1;
5820
5821   /* Check whether we are dealing with three consecutive stores.  */
5822   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5823       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5824     return 0;
5825
5826   /* If we don't know the relationship between the store addresses,
5827      assume the worst.  */
5828   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5829       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5830     return 1;
5831
5832   if (!fix_24k_record_store_info (&pos[0], insn)
5833       || !fix_24k_record_store_info (&pos[1], &hist[0])
5834       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5835     return 1;
5836
5837   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5838
5839   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5840      X bytes and such that the base register + X is known to be aligned
5841      to align bytes.  */
5842
5843   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5844     align = 8;
5845   else
5846     {
5847       align = pos[0].align_to;
5848       base_offset = pos[0].off;
5849       for (i = 1; i < 3; i++)
5850         if (align < pos[i].align_to)
5851           {
5852             align = pos[i].align_to;
5853             base_offset = pos[i].off;
5854           }
5855       for (i = 0; i < 3; i++)
5856         pos[i].off -= base_offset;
5857     }
5858
5859   pos[0].off &= ~align + 1;
5860   pos[1].off &= ~align + 1;
5861   pos[2].off &= ~align + 1;
5862
5863   /* If any two stores write to the same chunk, they also write to the
5864      same doubleword.  The offsets are still sorted at this point.  */
5865   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5866     return 0;
5867
5868   /* A range of at least 9 bytes is needed for the stores to be in
5869      non-overlapping doublewords.  */
5870   if (pos[2].off - pos[0].off <= 8)
5871     return 0;
5872
5873   if (pos[2].off - pos[1].off >= 24
5874       || pos[1].off - pos[0].off >= 24
5875       || pos[2].off - pos[0].off >= 32)
5876     return 0;
5877
5878   return 1;
5879 }
5880
5881 /* Return the number of nops that would be needed if instruction INSN
5882    immediately followed the MAX_NOPS instructions given by HIST,
5883    where HIST[0] is the most recent instruction.  Ignore hazards
5884    between INSN and the first IGNORE instructions in HIST.
5885
5886    If INSN is null, return the worse-case number of nops for any
5887    instruction.  */
5888
5889 static int
5890 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5891                const struct mips_cl_insn *insn)
5892 {
5893   int i, nops, tmp_nops;
5894
5895   nops = 0;
5896   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5897     {
5898       tmp_nops = insns_between (hist + i, insn) - i;
5899       if (tmp_nops > nops)
5900         nops = tmp_nops;
5901     }
5902
5903   if (mips_fix_vr4130 && !mips_opts.micromips)
5904     {
5905       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5906       if (tmp_nops > nops)
5907         nops = tmp_nops;
5908     }
5909
5910   if (mips_fix_24k && !mips_opts.micromips)
5911     {
5912       tmp_nops = nops_for_24k (ignore, hist, insn);
5913       if (tmp_nops > nops)
5914         nops = tmp_nops;
5915     }
5916
5917   return nops;
5918 }
5919
5920 /* The variable arguments provide NUM_INSNS extra instructions that
5921    might be added to HIST.  Return the largest number of nops that
5922    would be needed after the extended sequence, ignoring hazards
5923    in the first IGNORE instructions.  */
5924
5925 static int
5926 nops_for_sequence (int num_insns, int ignore,
5927                    const struct mips_cl_insn *hist, ...)
5928 {
5929   va_list args;
5930   struct mips_cl_insn buffer[MAX_NOPS];
5931   struct mips_cl_insn *cursor;
5932   int nops;
5933
5934   va_start (args, hist);
5935   cursor = buffer + num_insns;
5936   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
5937   while (cursor > buffer)
5938     *--cursor = *va_arg (args, const struct mips_cl_insn *);
5939
5940   nops = nops_for_insn (ignore, buffer, NULL);
5941   va_end (args);
5942   return nops;
5943 }
5944
5945 /* Like nops_for_insn, but if INSN is a branch, take into account the
5946    worst-case delay for the branch target.  */
5947
5948 static int
5949 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
5950                          const struct mips_cl_insn *insn)
5951 {
5952   int nops, tmp_nops;
5953
5954   nops = nops_for_insn (ignore, hist, insn);
5955   if (delayed_branch_p (insn))
5956     {
5957       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
5958                                     hist, insn, get_delay_slot_nop (insn));
5959       if (tmp_nops > nops)
5960         nops = tmp_nops;
5961     }
5962   else if (compact_branch_p (insn))
5963     {
5964       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
5965       if (tmp_nops > nops)
5966         nops = tmp_nops;
5967     }
5968   return nops;
5969 }
5970
5971 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
5972
5973 static void
5974 fix_loongson2f_nop (struct mips_cl_insn * ip)
5975 {
5976   gas_assert (!HAVE_CODE_COMPRESSION);
5977   if (strcmp (ip->insn_mo->name, "nop") == 0)
5978     ip->insn_opcode = LOONGSON2F_NOP_INSN;
5979 }
5980
5981 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
5982                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
5983
5984 static void
5985 fix_loongson2f_jump (struct mips_cl_insn * ip)
5986 {
5987   gas_assert (!HAVE_CODE_COMPRESSION);
5988   if (strcmp (ip->insn_mo->name, "j") == 0
5989       || strcmp (ip->insn_mo->name, "jr") == 0
5990       || strcmp (ip->insn_mo->name, "jalr") == 0)
5991     {
5992       int sreg;
5993       expressionS ep;
5994
5995       if (! mips_opts.at)
5996         return;
5997
5998       sreg = EXTRACT_OPERAND (0, RS, *ip);
5999       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6000         return;
6001
6002       ep.X_op = O_constant;
6003       ep.X_add_number = 0xcfff0000;
6004       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6005       ep.X_add_number = 0xffff;
6006       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6007       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6008     }
6009 }
6010
6011 static void
6012 fix_loongson2f (struct mips_cl_insn * ip)
6013 {
6014   if (mips_fix_loongson2f_nop)
6015     fix_loongson2f_nop (ip);
6016
6017   if (mips_fix_loongson2f_jump)
6018     fix_loongson2f_jump (ip);
6019 }
6020
6021 /* IP is a branch that has a delay slot, and we need to fill it
6022    automatically.   Return true if we can do that by swapping IP
6023    with the previous instruction.
6024    ADDRESS_EXPR is an operand of the instruction to be used with
6025    RELOC_TYPE.  */
6026
6027 static bfd_boolean
6028 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6029                    bfd_reloc_code_real_type *reloc_type)
6030 {
6031   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6032   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6033
6034   /* -O2 and above is required for this optimization.  */
6035   if (mips_optimize < 2)
6036     return FALSE;
6037
6038   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6039   if (mips_opts.nomove)
6040     return FALSE;
6041
6042   /* We can't swap if the previous instruction's position is fixed.  */
6043   if (history[0].fixed_p)
6044     return FALSE;
6045
6046   /* If the previous previous insn was in a .set noreorder, we can't
6047      swap.  Actually, the MIPS assembler will swap in this situation.
6048      However, gcc configured -with-gnu-as will generate code like
6049
6050         .set    noreorder
6051         lw      $4,XXX
6052         .set    reorder
6053         INSN
6054         bne     $4,$0,foo
6055
6056      in which we can not swap the bne and INSN.  If gcc is not configured
6057      -with-gnu-as, it does not output the .set pseudo-ops.  */
6058   if (history[1].noreorder_p)
6059     return FALSE;
6060
6061   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6062      This means that the previous instruction was a 4-byte one anyhow.  */
6063   if (mips_opts.mips16 && history[0].fixp[0])
6064     return FALSE;
6065
6066   /* If the branch is itself the target of a branch, we can not swap.
6067      We cheat on this; all we check for is whether there is a label on
6068      this instruction.  If there are any branches to anything other than
6069      a label, users must use .set noreorder.  */
6070   if (seg_info (now_seg)->label_list)
6071     return FALSE;
6072
6073   /* If the previous instruction is in a variant frag other than this
6074      branch's one, we cannot do the swap.  This does not apply to
6075      MIPS16 code, which uses variant frags for different purposes.  */
6076   if (!mips_opts.mips16
6077       && history[0].frag
6078       && history[0].frag->fr_type == rs_machine_dependent)
6079     return FALSE;
6080
6081   /* We do not swap with instructions that cannot architecturally
6082      be placed in a branch delay slot, such as SYNC or ERET.  We
6083      also refrain from swapping with a trap instruction, since it
6084      complicates trap handlers to have the trap instruction be in
6085      a delay slot.  */
6086   prev_pinfo = history[0].insn_mo->pinfo;
6087   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6088     return FALSE;
6089
6090   /* Check for conflicts between the branch and the instructions
6091      before the candidate delay slot.  */
6092   if (nops_for_insn (0, history + 1, ip) > 0)
6093     return FALSE;
6094
6095   /* Check for conflicts between the swapped sequence and the
6096      target of the branch.  */
6097   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6098     return FALSE;
6099
6100   /* If the branch reads a register that the previous
6101      instruction sets, we can not swap.  */
6102   gpr_read = gpr_read_mask (ip);
6103   prev_gpr_write = gpr_write_mask (&history[0]);
6104   if (gpr_read & prev_gpr_write)
6105     return FALSE;
6106
6107   /* If the branch writes a register that the previous
6108      instruction sets, we can not swap.  */
6109   gpr_write = gpr_write_mask (ip);
6110   if (gpr_write & prev_gpr_write)
6111     return FALSE;
6112
6113   /* If the branch writes a register that the previous
6114      instruction reads, we can not swap.  */
6115   prev_gpr_read = gpr_read_mask (&history[0]);
6116   if (gpr_write & prev_gpr_read)
6117     return FALSE;
6118
6119   /* If one instruction sets a condition code and the
6120      other one uses a condition code, we can not swap.  */
6121   pinfo = ip->insn_mo->pinfo;
6122   if ((pinfo & INSN_READ_COND_CODE)
6123       && (prev_pinfo & INSN_WRITE_COND_CODE))
6124     return FALSE;
6125   if ((pinfo & INSN_WRITE_COND_CODE)
6126       && (prev_pinfo & INSN_READ_COND_CODE))
6127     return FALSE;
6128
6129   /* If the previous instruction uses the PC, we can not swap.  */
6130   prev_pinfo2 = history[0].insn_mo->pinfo2;
6131   if (prev_pinfo2 & INSN2_READ_PC)
6132     return FALSE;
6133
6134   /* If the previous instruction has an incorrect size for a fixed
6135      branch delay slot in microMIPS mode, we cannot swap.  */
6136   pinfo2 = ip->insn_mo->pinfo2;
6137   if (mips_opts.micromips
6138       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6139       && insn_length (history) != 2)
6140     return FALSE;
6141   if (mips_opts.micromips
6142       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6143       && insn_length (history) != 4)
6144     return FALSE;
6145
6146   /* On R5900 short loops need to be fixed by inserting a nop in
6147      the branch delay slots.
6148      A short loop can be terminated too early.  */
6149   if (mips_opts.arch == CPU_R5900
6150       /* Check if instruction has a parameter, ignore "j $31". */
6151       && (address_expr != NULL)
6152       /* Parameter must be 16 bit. */
6153       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6154       /* Branch to same segment. */
6155       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6156       /* Branch to same code fragment. */
6157       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6158       /* Can only calculate branch offset if value is known. */
6159       && symbol_constant_p(address_expr->X_add_symbol)
6160       /* Check if branch is really conditional. */
6161       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6162         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6163         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6164     {
6165       int distance;
6166       /* Check if loop is shorter than 6 instructions including
6167          branch and delay slot.  */
6168       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6169       if (distance <= 20)
6170         {
6171           int i;
6172           int rv;
6173
6174           rv = FALSE;
6175           /* When the loop includes branches or jumps,
6176              it is not a short loop. */
6177           for (i = 0; i < (distance / 4); i++)
6178             {
6179               if ((history[i].cleared_p)
6180                   || delayed_branch_p(&history[i]))
6181                 {
6182                   rv = TRUE;
6183                   break;
6184                 }
6185             }
6186           if (rv == FALSE)
6187             {
6188               /* Insert nop after branch to fix short loop. */
6189               return FALSE;
6190             }
6191         }
6192     }
6193
6194   return TRUE;
6195 }
6196
6197 /* Decide how we should add IP to the instruction stream.
6198    ADDRESS_EXPR is an operand of the instruction to be used with
6199    RELOC_TYPE.  */
6200
6201 static enum append_method
6202 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6203                    bfd_reloc_code_real_type *reloc_type)
6204 {
6205   /* The relaxed version of a macro sequence must be inherently
6206      hazard-free.  */
6207   if (mips_relax.sequence == 2)
6208     return APPEND_ADD;
6209
6210   /* We must not dabble with instructions in a ".set norerorder" block.  */
6211   if (mips_opts.noreorder)
6212     return APPEND_ADD;
6213
6214   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6215   if (delayed_branch_p (ip))
6216     {
6217       if (!branch_likely_p (ip)
6218           && can_swap_branch_p (ip, address_expr, reloc_type))
6219         return APPEND_SWAP;
6220
6221       if (mips_opts.mips16
6222           && ISA_SUPPORTS_MIPS16E
6223           && gpr_read_mask (ip) != 0)
6224         return APPEND_ADD_COMPACT;
6225
6226       return APPEND_ADD_WITH_NOP;
6227     }
6228
6229   return APPEND_ADD;
6230 }
6231
6232 /* IP is a MIPS16 instruction whose opcode we have just changed.
6233    Point IP->insn_mo to the new opcode's definition.  */
6234
6235 static void
6236 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6237 {
6238   const struct mips_opcode *mo, *end;
6239
6240   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6241   for (mo = ip->insn_mo; mo < end; mo++)
6242     if ((ip->insn_opcode & mo->mask) == mo->match)
6243       {
6244         ip->insn_mo = mo;
6245         return;
6246       }
6247   abort ();
6248 }
6249
6250 /* For microMIPS macros, we need to generate a local number label
6251    as the target of branches.  */
6252 #define MICROMIPS_LABEL_CHAR            '\037'
6253 static unsigned long micromips_target_label;
6254 static char micromips_target_name[32];
6255
6256 static char *
6257 micromips_label_name (void)
6258 {
6259   char *p = micromips_target_name;
6260   char symbol_name_temporary[24];
6261   unsigned long l;
6262   int i;
6263
6264   if (*p)
6265     return p;
6266
6267   i = 0;
6268   l = micromips_target_label;
6269 #ifdef LOCAL_LABEL_PREFIX
6270   *p++ = LOCAL_LABEL_PREFIX;
6271 #endif
6272   *p++ = 'L';
6273   *p++ = MICROMIPS_LABEL_CHAR;
6274   do
6275     {
6276       symbol_name_temporary[i++] = l % 10 + '0';
6277       l /= 10;
6278     }
6279   while (l != 0);
6280   while (i > 0)
6281     *p++ = symbol_name_temporary[--i];
6282   *p = '\0';
6283
6284   return micromips_target_name;
6285 }
6286
6287 static void
6288 micromips_label_expr (expressionS *label_expr)
6289 {
6290   label_expr->X_op = O_symbol;
6291   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6292   label_expr->X_add_number = 0;
6293 }
6294
6295 static void
6296 micromips_label_inc (void)
6297 {
6298   micromips_target_label++;
6299   *micromips_target_name = '\0';
6300 }
6301
6302 static void
6303 micromips_add_label (void)
6304 {
6305   symbolS *s;
6306
6307   s = colon (micromips_label_name ());
6308   micromips_label_inc ();
6309   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6310 }
6311
6312 /* If assembling microMIPS code, then return the microMIPS reloc
6313    corresponding to the requested one if any.  Otherwise return
6314    the reloc unchanged.  */
6315
6316 static bfd_reloc_code_real_type
6317 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6318 {
6319   static const bfd_reloc_code_real_type relocs[][2] =
6320     {
6321       /* Keep sorted incrementally by the left-hand key.  */
6322       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6323       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6324       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6325       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6326       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6327       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6328       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6329       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6330       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6331       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6332       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6333       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6334       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6335       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6336       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6337       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6338       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6339       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6340       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6341       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6342       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6343       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6344       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6345       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6346       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6347       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6348       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6349     };
6350   bfd_reloc_code_real_type r;
6351   size_t i;
6352
6353   if (!mips_opts.micromips)
6354     return reloc;
6355   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6356     {
6357       r = relocs[i][0];
6358       if (r > reloc)
6359         return reloc;
6360       if (r == reloc)
6361         return relocs[i][1];
6362     }
6363   return reloc;
6364 }
6365
6366 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6367    Return true on success, storing the resolved value in RESULT.  */
6368
6369 static bfd_boolean
6370 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6371                  offsetT *result)
6372 {
6373   switch (reloc)
6374     {
6375     case BFD_RELOC_MIPS_HIGHEST:
6376     case BFD_RELOC_MICROMIPS_HIGHEST:
6377       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6378       return TRUE;
6379
6380     case BFD_RELOC_MIPS_HIGHER:
6381     case BFD_RELOC_MICROMIPS_HIGHER:
6382       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6383       return TRUE;
6384
6385     case BFD_RELOC_HI16_S:
6386     case BFD_RELOC_MICROMIPS_HI16_S:
6387     case BFD_RELOC_MIPS16_HI16_S:
6388       *result = ((operand + 0x8000) >> 16) & 0xffff;
6389       return TRUE;
6390
6391     case BFD_RELOC_HI16:
6392     case BFD_RELOC_MICROMIPS_HI16:
6393     case BFD_RELOC_MIPS16_HI16:
6394       *result = (operand >> 16) & 0xffff;
6395       return TRUE;
6396
6397     case BFD_RELOC_LO16:
6398     case BFD_RELOC_MICROMIPS_LO16:
6399     case BFD_RELOC_MIPS16_LO16:
6400       *result = operand & 0xffff;
6401       return TRUE;
6402
6403     case BFD_RELOC_UNUSED:
6404       *result = operand;
6405       return TRUE;
6406
6407     default:
6408       return FALSE;
6409     }
6410 }
6411
6412 /* Output an instruction.  IP is the instruction information.
6413    ADDRESS_EXPR is an operand of the instruction to be used with
6414    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6415    a macro expansion.  */
6416
6417 static void
6418 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6419              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6420 {
6421   unsigned long prev_pinfo2, pinfo;
6422   bfd_boolean relaxed_branch = FALSE;
6423   enum append_method method;
6424   bfd_boolean relax32;
6425   int branch_disp;
6426
6427   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6428     fix_loongson2f (ip);
6429
6430   file_ase_mips16 |= mips_opts.mips16;
6431   file_ase_micromips |= mips_opts.micromips;
6432
6433   prev_pinfo2 = history[0].insn_mo->pinfo2;
6434   pinfo = ip->insn_mo->pinfo;
6435
6436   if (mips_opts.micromips
6437       && !expansionp
6438       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6439            && micromips_insn_length (ip->insn_mo) != 2)
6440           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6441               && micromips_insn_length (ip->insn_mo) != 4)))
6442     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
6443              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6444
6445   if (address_expr == NULL)
6446     ip->complete_p = 1;
6447   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6448            && reloc_type[1] == BFD_RELOC_UNUSED
6449            && reloc_type[2] == BFD_RELOC_UNUSED
6450            && address_expr->X_op == O_constant)
6451     {
6452       switch (*reloc_type)
6453         {
6454         case BFD_RELOC_MIPS_JMP:
6455           {
6456             int shift;
6457
6458             shift = mips_opts.micromips ? 1 : 2;
6459             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6460               as_bad (_("jump to misaligned address (0x%lx)"),
6461                       (unsigned long) address_expr->X_add_number);
6462             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6463                                 & 0x3ffffff);
6464             ip->complete_p = 1;
6465           }
6466           break;
6467
6468         case BFD_RELOC_MIPS16_JMP:
6469           if ((address_expr->X_add_number & 3) != 0)
6470             as_bad (_("jump to misaligned address (0x%lx)"),
6471                     (unsigned long) address_expr->X_add_number);
6472           ip->insn_opcode |=
6473             (((address_expr->X_add_number & 0x7c0000) << 3)
6474                | ((address_expr->X_add_number & 0xf800000) >> 7)
6475                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6476           ip->complete_p = 1;
6477           break;
6478
6479         case BFD_RELOC_16_PCREL_S2:
6480           {
6481             int shift;
6482
6483             shift = mips_opts.micromips ? 1 : 2;
6484             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6485               as_bad (_("branch to misaligned address (0x%lx)"),
6486                       (unsigned long) address_expr->X_add_number);
6487             if (!mips_relax_branch)
6488               {
6489                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6490                     & ~((1 << (shift + 16)) - 1))
6491                   as_bad (_("branch address range overflow (0x%lx)"),
6492                           (unsigned long) address_expr->X_add_number);
6493                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6494                                     & 0xffff);
6495               }
6496           }
6497           break;
6498
6499         default:
6500           {
6501             offsetT value;
6502
6503             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6504                                  &value))
6505               {
6506                 ip->insn_opcode |= value & 0xffff;
6507                 ip->complete_p = 1;
6508               }
6509           }
6510           break;
6511         }
6512     }
6513
6514   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6515     {
6516       /* There are a lot of optimizations we could do that we don't.
6517          In particular, we do not, in general, reorder instructions.
6518          If you use gcc with optimization, it will reorder
6519          instructions and generally do much more optimization then we
6520          do here; repeating all that work in the assembler would only
6521          benefit hand written assembly code, and does not seem worth
6522          it.  */
6523       int nops = (mips_optimize == 0
6524                   ? nops_for_insn (0, history, NULL)
6525                   : nops_for_insn_or_target (0, history, ip));
6526       if (nops > 0)
6527         {
6528           fragS *old_frag;
6529           unsigned long old_frag_offset;
6530           int i;
6531
6532           old_frag = frag_now;
6533           old_frag_offset = frag_now_fix ();
6534
6535           for (i = 0; i < nops; i++)
6536             add_fixed_insn (NOP_INSN);
6537           insert_into_history (0, nops, NOP_INSN);
6538
6539           if (listing)
6540             {
6541               listing_prev_line ();
6542               /* We may be at the start of a variant frag.  In case we
6543                  are, make sure there is enough space for the frag
6544                  after the frags created by listing_prev_line.  The
6545                  argument to frag_grow here must be at least as large
6546                  as the argument to all other calls to frag_grow in
6547                  this file.  We don't have to worry about being in the
6548                  middle of a variant frag, because the variants insert
6549                  all needed nop instructions themselves.  */
6550               frag_grow (40);
6551             }
6552
6553           mips_move_text_labels ();
6554
6555 #ifndef NO_ECOFF_DEBUGGING
6556           if (ECOFF_DEBUGGING)
6557             ecoff_fix_loc (old_frag, old_frag_offset);
6558 #endif
6559         }
6560     }
6561   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6562     {
6563       int nops;
6564
6565       /* Work out how many nops in prev_nop_frag are needed by IP,
6566          ignoring hazards generated by the first prev_nop_frag_since
6567          instructions.  */
6568       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6569       gas_assert (nops <= prev_nop_frag_holds);
6570
6571       /* Enforce NOPS as a minimum.  */
6572       if (nops > prev_nop_frag_required)
6573         prev_nop_frag_required = nops;
6574
6575       if (prev_nop_frag_holds == prev_nop_frag_required)
6576         {
6577           /* Settle for the current number of nops.  Update the history
6578              accordingly (for the benefit of any future .set reorder code).  */
6579           prev_nop_frag = NULL;
6580           insert_into_history (prev_nop_frag_since,
6581                                prev_nop_frag_holds, NOP_INSN);
6582         }
6583       else
6584         {
6585           /* Allow this instruction to replace one of the nops that was
6586              tentatively added to prev_nop_frag.  */
6587           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6588           prev_nop_frag_holds--;
6589           prev_nop_frag_since++;
6590         }
6591     }
6592
6593   method = get_append_method (ip, address_expr, reloc_type);
6594   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6595
6596   dwarf2_emit_insn (0);
6597   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6598      so "move" the instruction address accordingly.
6599
6600      Also, it doesn't seem appropriate for the assembler to reorder .loc
6601      entries.  If this instruction is a branch that we are going to swap
6602      with the previous instruction, the two instructions should be
6603      treated as a unit, and the debug information for both instructions
6604      should refer to the start of the branch sequence.  Using the
6605      current position is certainly wrong when swapping a 32-bit branch
6606      and a 16-bit delay slot, since the current position would then be
6607      in the middle of a branch.  */
6608   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6609
6610   relax32 = (mips_relax_branch
6611              /* Don't try branch relaxation within .set nomacro, or within
6612                 .set noat if we use $at for PIC computations.  If it turns
6613                 out that the branch was out-of-range, we'll get an error.  */
6614              && !mips_opts.warn_about_macros
6615              && (mips_opts.at || mips_pic == NO_PIC)
6616              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6617                 as they have no complementing branches.  */
6618              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6619
6620   if (!HAVE_CODE_COMPRESSION
6621       && address_expr
6622       && relax32
6623       && *reloc_type == BFD_RELOC_16_PCREL_S2
6624       && delayed_branch_p (ip))
6625     {
6626       relaxed_branch = TRUE;
6627       add_relaxed_insn (ip, (relaxed_branch_length
6628                              (NULL, NULL,
6629                               uncond_branch_p (ip) ? -1
6630                               : branch_likely_p (ip) ? 1
6631                               : 0)), 4,
6632                         RELAX_BRANCH_ENCODE
6633                         (AT,
6634                          uncond_branch_p (ip),
6635                          branch_likely_p (ip),
6636                          pinfo & INSN_WRITE_GPR_31,
6637                          0),
6638                         address_expr->X_add_symbol,
6639                         address_expr->X_add_number);
6640       *reloc_type = BFD_RELOC_UNUSED;
6641     }
6642   else if (mips_opts.micromips
6643            && address_expr
6644            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6645                || *reloc_type > BFD_RELOC_UNUSED)
6646            && (delayed_branch_p (ip) || compact_branch_p (ip))
6647            /* Don't try branch relaxation when users specify
6648               16-bit/32-bit instructions.  */
6649            && !forced_insn_length)
6650     {
6651       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6652       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6653       int uncond = uncond_branch_p (ip) ? -1 : 0;
6654       int compact = compact_branch_p (ip);
6655       int al = pinfo & INSN_WRITE_GPR_31;
6656       int length32;
6657
6658       gas_assert (address_expr != NULL);
6659       gas_assert (!mips_relax.sequence);
6660
6661       relaxed_branch = TRUE;
6662       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6663       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6664                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6665                                                 relax32, 0, 0),
6666                         address_expr->X_add_symbol,
6667                         address_expr->X_add_number);
6668       *reloc_type = BFD_RELOC_UNUSED;
6669     }
6670   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6671     {
6672       /* We need to set up a variant frag.  */
6673       gas_assert (address_expr != NULL);
6674       add_relaxed_insn (ip, 4, 0,
6675                         RELAX_MIPS16_ENCODE
6676                         (*reloc_type - BFD_RELOC_UNUSED,
6677                          forced_insn_length == 2, forced_insn_length == 4,
6678                          delayed_branch_p (&history[0]),
6679                          history[0].mips16_absolute_jump_p),
6680                         make_expr_symbol (address_expr), 0);
6681     }
6682   else if (mips_opts.mips16 && insn_length (ip) == 2)
6683     {
6684       if (!delayed_branch_p (ip))
6685         /* Make sure there is enough room to swap this instruction with
6686            a following jump instruction.  */
6687         frag_grow (6);
6688       add_fixed_insn (ip);
6689     }
6690   else
6691     {
6692       if (mips_opts.mips16
6693           && mips_opts.noreorder
6694           && delayed_branch_p (&history[0]))
6695         as_warn (_("extended instruction in delay slot"));
6696
6697       if (mips_relax.sequence)
6698         {
6699           /* If we've reached the end of this frag, turn it into a variant
6700              frag and record the information for the instructions we've
6701              written so far.  */
6702           if (frag_room () < 4)
6703             relax_close_frag ();
6704           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6705         }
6706
6707       if (mips_relax.sequence != 2)
6708         {
6709           if (mips_macro_warning.first_insn_sizes[0] == 0)
6710             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6711           mips_macro_warning.sizes[0] += insn_length (ip);
6712           mips_macro_warning.insns[0]++;
6713         }
6714       if (mips_relax.sequence != 1)
6715         {
6716           if (mips_macro_warning.first_insn_sizes[1] == 0)
6717             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6718           mips_macro_warning.sizes[1] += insn_length (ip);
6719           mips_macro_warning.insns[1]++;
6720         }
6721
6722       if (mips_opts.mips16)
6723         {
6724           ip->fixed_p = 1;
6725           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6726         }
6727       add_fixed_insn (ip);
6728     }
6729
6730   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6731     {
6732       bfd_reloc_code_real_type final_type[3];
6733       reloc_howto_type *howto0;
6734       reloc_howto_type *howto;
6735       int i;
6736
6737       /* Perform any necessary conversion to microMIPS relocations
6738          and find out how many relocations there actually are.  */
6739       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6740         final_type[i] = micromips_map_reloc (reloc_type[i]);
6741
6742       /* In a compound relocation, it is the final (outermost)
6743          operator that determines the relocated field.  */
6744       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6745       if (!howto)
6746         abort ();
6747
6748       if (i > 1)
6749         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6750       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6751                                  bfd_get_reloc_size (howto),
6752                                  address_expr,
6753                                  howto0 && howto0->pc_relative,
6754                                  final_type[0]);
6755
6756       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6757       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6758         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6759
6760       /* These relocations can have an addend that won't fit in
6761          4 octets for 64bit assembly.  */
6762       if (HAVE_64BIT_GPRS
6763           && ! howto->partial_inplace
6764           && (reloc_type[0] == BFD_RELOC_16
6765               || reloc_type[0] == BFD_RELOC_32
6766               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6767               || reloc_type[0] == BFD_RELOC_GPREL16
6768               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6769               || reloc_type[0] == BFD_RELOC_GPREL32
6770               || reloc_type[0] == BFD_RELOC_64
6771               || reloc_type[0] == BFD_RELOC_CTOR
6772               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6773               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6774               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6775               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6776               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6777               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6778               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6779               || hi16_reloc_p (reloc_type[0])
6780               || lo16_reloc_p (reloc_type[0])))
6781         ip->fixp[0]->fx_no_overflow = 1;
6782
6783       /* These relocations can have an addend that won't fit in 2 octets.  */
6784       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6785           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6786         ip->fixp[0]->fx_no_overflow = 1;
6787
6788       if (mips_relax.sequence)
6789         {
6790           if (mips_relax.first_fixup == 0)
6791             mips_relax.first_fixup = ip->fixp[0];
6792         }
6793       else if (reloc_needs_lo_p (*reloc_type))
6794         {
6795           struct mips_hi_fixup *hi_fixup;
6796
6797           /* Reuse the last entry if it already has a matching %lo.  */
6798           hi_fixup = mips_hi_fixup_list;
6799           if (hi_fixup == 0
6800               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6801             {
6802               hi_fixup = ((struct mips_hi_fixup *)
6803                           xmalloc (sizeof (struct mips_hi_fixup)));
6804               hi_fixup->next = mips_hi_fixup_list;
6805               mips_hi_fixup_list = hi_fixup;
6806             }
6807           hi_fixup->fixp = ip->fixp[0];
6808           hi_fixup->seg = now_seg;
6809         }
6810
6811       /* Add fixups for the second and third relocations, if given.
6812          Note that the ABI allows the second relocation to be
6813          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6814          moment we only use RSS_UNDEF, but we could add support
6815          for the others if it ever becomes necessary.  */
6816       for (i = 1; i < 3; i++)
6817         if (reloc_type[i] != BFD_RELOC_UNUSED)
6818           {
6819             ip->fixp[i] = fix_new (ip->frag, ip->where,
6820                                    ip->fixp[0]->fx_size, NULL, 0,
6821                                    FALSE, final_type[i]);
6822
6823             /* Use fx_tcbit to mark compound relocs.  */
6824             ip->fixp[0]->fx_tcbit = 1;
6825             ip->fixp[i]->fx_tcbit = 1;
6826           }
6827     }
6828   install_insn (ip);
6829
6830   /* Update the register mask information.  */
6831   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6832   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6833
6834   switch (method)
6835     {
6836     case APPEND_ADD:
6837       insert_into_history (0, 1, ip);
6838       break;
6839
6840     case APPEND_ADD_WITH_NOP:
6841       {
6842         struct mips_cl_insn *nop;
6843
6844         insert_into_history (0, 1, ip);
6845         nop = get_delay_slot_nop (ip);
6846         add_fixed_insn (nop);
6847         insert_into_history (0, 1, nop);
6848         if (mips_relax.sequence)
6849           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6850       }
6851       break;
6852
6853     case APPEND_ADD_COMPACT:
6854       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6855       gas_assert (mips_opts.mips16);
6856       ip->insn_opcode |= 0x0080;
6857       find_altered_mips16_opcode (ip);
6858       install_insn (ip);
6859       insert_into_history (0, 1, ip);
6860       break;
6861
6862     case APPEND_SWAP:
6863       {
6864         struct mips_cl_insn delay = history[0];
6865         if (mips_opts.mips16)
6866           {
6867             know (delay.frag == ip->frag);
6868             move_insn (ip, delay.frag, delay.where);
6869             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6870           }
6871         else if (relaxed_branch || delay.frag != ip->frag)
6872           {
6873             /* Add the delay slot instruction to the end of the
6874                current frag and shrink the fixed part of the
6875                original frag.  If the branch occupies the tail of
6876                the latter, move it backwards to cover the gap.  */
6877             delay.frag->fr_fix -= branch_disp;
6878             if (delay.frag == ip->frag)
6879               move_insn (ip, ip->frag, ip->where - branch_disp);
6880             add_fixed_insn (&delay);
6881           }
6882         else
6883           {
6884             move_insn (&delay, ip->frag,
6885                        ip->where - branch_disp + insn_length (ip));
6886             move_insn (ip, history[0].frag, history[0].where);
6887           }
6888         history[0] = *ip;
6889         delay.fixed_p = 1;
6890         insert_into_history (0, 1, &delay);
6891       }
6892       break;
6893     }
6894
6895   /* If we have just completed an unconditional branch, clear the history.  */
6896   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6897       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6898     {
6899       unsigned int i;
6900
6901       mips_no_prev_insn ();
6902
6903       for (i = 0; i < ARRAY_SIZE (history); i++)
6904         history[i].cleared_p = 1;
6905     }
6906
6907   /* We need to emit a label at the end of branch-likely macros.  */
6908   if (emit_branch_likely_macro)
6909     {
6910       emit_branch_likely_macro = FALSE;
6911       micromips_add_label ();
6912     }
6913
6914   /* We just output an insn, so the next one doesn't have a label.  */
6915   mips_clear_insn_labels ();
6916 }
6917
6918 /* Forget that there was any previous instruction or label.
6919    When BRANCH is true, the branch history is also flushed.  */
6920
6921 static void
6922 mips_no_prev_insn (void)
6923 {
6924   prev_nop_frag = NULL;
6925   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6926   mips_clear_insn_labels ();
6927 }
6928
6929 /* This function must be called before we emit something other than
6930    instructions.  It is like mips_no_prev_insn except that it inserts
6931    any NOPS that might be needed by previous instructions.  */
6932
6933 void
6934 mips_emit_delays (void)
6935 {
6936   if (! mips_opts.noreorder)
6937     {
6938       int nops = nops_for_insn (0, history, NULL);
6939       if (nops > 0)
6940         {
6941           while (nops-- > 0)
6942             add_fixed_insn (NOP_INSN);
6943           mips_move_text_labels ();
6944         }
6945     }
6946   mips_no_prev_insn ();
6947 }
6948
6949 /* Start a (possibly nested) noreorder block.  */
6950
6951 static void
6952 start_noreorder (void)
6953 {
6954   if (mips_opts.noreorder == 0)
6955     {
6956       unsigned int i;
6957       int nops;
6958
6959       /* None of the instructions before the .set noreorder can be moved.  */
6960       for (i = 0; i < ARRAY_SIZE (history); i++)
6961         history[i].fixed_p = 1;
6962
6963       /* Insert any nops that might be needed between the .set noreorder
6964          block and the previous instructions.  We will later remove any
6965          nops that turn out not to be needed.  */
6966       nops = nops_for_insn (0, history, NULL);
6967       if (nops > 0)
6968         {
6969           if (mips_optimize != 0)
6970             {
6971               /* Record the frag which holds the nop instructions, so
6972                  that we can remove them if we don't need them.  */
6973               frag_grow (nops * NOP_INSN_SIZE);
6974               prev_nop_frag = frag_now;
6975               prev_nop_frag_holds = nops;
6976               prev_nop_frag_required = 0;
6977               prev_nop_frag_since = 0;
6978             }
6979
6980           for (; nops > 0; --nops)
6981             add_fixed_insn (NOP_INSN);
6982
6983           /* Move on to a new frag, so that it is safe to simply
6984              decrease the size of prev_nop_frag.  */
6985           frag_wane (frag_now);
6986           frag_new (0);
6987           mips_move_text_labels ();
6988         }
6989       mips_mark_labels ();
6990       mips_clear_insn_labels ();
6991     }
6992   mips_opts.noreorder++;
6993   mips_any_noreorder = 1;
6994 }
6995
6996 /* End a nested noreorder block.  */
6997
6998 static void
6999 end_noreorder (void)
7000 {
7001   mips_opts.noreorder--;
7002   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7003     {
7004       /* Commit to inserting prev_nop_frag_required nops and go back to
7005          handling nop insertion the .set reorder way.  */
7006       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7007                                 * NOP_INSN_SIZE);
7008       insert_into_history (prev_nop_frag_since,
7009                            prev_nop_frag_required, NOP_INSN);
7010       prev_nop_frag = NULL;
7011     }
7012 }
7013
7014 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7015    higher bits unset.  */
7016
7017 static void
7018 normalize_constant_expr (expressionS *ex)
7019 {
7020   if (ex->X_op == O_constant
7021       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7022     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7023                         - 0x80000000);
7024 }
7025
7026 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7027    all higher bits unset.  */
7028
7029 static void
7030 normalize_address_expr (expressionS *ex)
7031 {
7032   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7033         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7034       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7035     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7036                         - 0x80000000);
7037 }
7038
7039 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7040    Return true if the match was successful.
7041
7042    OPCODE_EXTRA is a value that should be ORed into the opcode
7043    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7044    there are more alternatives after OPCODE and SOFT_MATCH is
7045    as for mips_arg_info.  */
7046
7047 static bfd_boolean
7048 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7049             struct mips_operand_token *tokens, unsigned int opcode_extra,
7050             bfd_boolean more_alts)
7051 {
7052   const char *args;
7053   struct mips_arg_info arg;
7054   const struct mips_operand *operand;
7055   char c;
7056
7057   imm_expr.X_op = O_absent;
7058   imm2_expr.X_op = O_absent;
7059   offset_expr.X_op = O_absent;
7060   offset_reloc[0] = BFD_RELOC_UNUSED;
7061   offset_reloc[1] = BFD_RELOC_UNUSED;
7062   offset_reloc[2] = BFD_RELOC_UNUSED;
7063
7064   create_insn (insn, opcode);
7065   insn->insn_opcode |= opcode_extra;
7066   memset (&arg, 0, sizeof (arg));
7067   arg.insn = insn;
7068   arg.token = tokens;
7069   arg.argnum = 1;
7070   arg.last_regno = ILLEGAL_REG;
7071   arg.dest_regno = ILLEGAL_REG;
7072   for (args = opcode->args;; ++args)
7073     {
7074       if (arg.token->type == OT_END)
7075         {
7076           /* Handle unary instructions in which only one operand is given.
7077              The source is then the same as the destination.  */
7078           if (arg.opnum == 1 && *args == ',')
7079             {
7080               operand = (mips_opts.micromips
7081                          ? decode_micromips_operand (args + 1)
7082                          : decode_mips_operand (args + 1));
7083               if (operand && mips_optional_operand_p (operand))
7084                 {
7085                   arg.token = tokens;
7086                   arg.argnum = 1;
7087                   continue;
7088                 }
7089             }
7090
7091           /* Treat elided base registers as $0.  */
7092           if (strcmp (args, "(b)") == 0)
7093             args += 3;
7094
7095           if (args[0] == '+')
7096             switch (args[1])
7097               {
7098               case 'K':
7099               case 'N':
7100                 /* The register suffix is optional. */
7101                 args += 2;
7102                 break;
7103               }
7104
7105           /* Fail the match if there were too few operands.  */
7106           if (*args)
7107             return FALSE;
7108
7109           /* Successful match.  */
7110           clear_insn_error ();
7111           if (arg.dest_regno == arg.last_regno
7112               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7113             {
7114               if (arg.opnum == 2)
7115                 set_insn_error
7116                   (0, _("Source and destination must be different"));
7117               else if (arg.last_regno == 31)
7118                 set_insn_error
7119                   (0, _("A destination register must be supplied"));
7120             }
7121           check_completed_insn (&arg);
7122           return TRUE;
7123         }
7124
7125       /* Fail the match if the line has too many operands.   */
7126       if (*args == 0)
7127         return FALSE;
7128
7129       /* Handle characters that need to match exactly.  */
7130       if (*args == '(' || *args == ')' || *args == ',')
7131         {
7132           if (match_char (&arg, *args))
7133             continue;
7134           return FALSE;
7135         }
7136       if (*args == '#')
7137         {
7138           ++args;
7139           if (arg.token->type == OT_DOUBLE_CHAR
7140               && arg.token->u.ch == *args)
7141             {
7142               ++arg.token;
7143               continue;
7144             }
7145           return FALSE;
7146         }
7147
7148       /* Handle special macro operands.  Work out the properties of
7149          other operands.  */
7150       arg.opnum += 1;
7151       arg.lax_max = FALSE;
7152       switch (*args)
7153         {
7154         case '+':
7155           switch (args[1])
7156             {
7157             case 'I':
7158               /* "+I" is like "I", except that imm2_expr is used.  */
7159               if (!match_const_int (&arg, &imm2_expr.X_add_number))
7160                 return FALSE;
7161               imm2_expr.X_op = O_constant;
7162               if (HAVE_32BIT_GPRS)
7163                 normalize_constant_expr (&imm2_expr);
7164               ++args;
7165               continue;
7166
7167             case 'i':
7168               *offset_reloc = BFD_RELOC_MIPS_JMP;
7169               break;
7170             }
7171           break;
7172
7173         case 'I':
7174           if (!match_const_int (&arg, &imm_expr.X_add_number))
7175             return FALSE;
7176           imm_expr.X_op = O_constant;
7177           if (HAVE_32BIT_GPRS)
7178             normalize_constant_expr (&imm_expr);
7179           continue;
7180
7181         case 'A':
7182           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7183             {
7184               /* Assume that the offset has been elided and that what
7185                  we saw was a base register.  The match will fail later
7186                  if that assumption turns out to be wrong.  */
7187               offset_expr.X_op = O_constant;
7188               offset_expr.X_add_number = 0;
7189             }
7190           else
7191             {
7192               if (!match_expression (&arg, &offset_expr, offset_reloc))
7193                 return FALSE;
7194               normalize_address_expr (&offset_expr);
7195             }
7196           continue;
7197
7198         case 'F':
7199           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7200                                      8, TRUE))
7201             return FALSE;
7202           continue;
7203
7204         case 'L':
7205           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7206                                      8, FALSE))
7207             return FALSE;
7208           continue;
7209
7210         case 'f':
7211           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7212                                      4, TRUE))
7213             return FALSE;
7214           continue;
7215
7216         case 'l':
7217           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7218                                      4, FALSE))
7219             return FALSE;
7220           continue;
7221
7222           /* ??? This is the traditional behavior, but is flaky if
7223              there are alternative versions of the same instruction
7224              for different subarchitectures.  The next alternative
7225              might not be suitable.  */
7226         case 'j':
7227           /* For compatibility with older assemblers, we accept
7228              0x8000-0xffff as signed 16-bit numbers when only
7229              signed numbers are allowed.  */
7230           arg.lax_max = !more_alts;
7231         case 'i':
7232           /* Only accept non-constant operands if this is the
7233              final alternative.  Later alternatives might include
7234              a macro implementation.  */
7235           arg.allow_nonconst = !more_alts;
7236           break;
7237
7238         case 'u':
7239           /* There are no macro implementations for out-of-range values.  */
7240           arg.allow_nonconst = TRUE;
7241           break;
7242
7243         case 'o':
7244           /* There should always be a macro implementation.  */
7245           arg.allow_nonconst = FALSE;
7246           break;
7247
7248         case 'p':
7249           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7250           break;
7251
7252         case 'a':
7253           *offset_reloc = BFD_RELOC_MIPS_JMP;
7254           break;
7255
7256         case 'm':
7257           gas_assert (mips_opts.micromips);
7258           c = args[1];
7259           switch (c)
7260             {
7261             case 'D':
7262             case 'E':
7263               if (!forced_insn_length)
7264                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7265               else if (c == 'D')
7266                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7267               else
7268                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7269               break;
7270             }
7271           break;
7272         }
7273
7274       operand = (mips_opts.micromips
7275                  ? decode_micromips_operand (args)
7276                  : decode_mips_operand (args));
7277       if (!operand)
7278         abort ();
7279
7280       /* Skip prefixes.  */
7281       if (*args == '+' || *args == 'm')
7282         args++;
7283
7284       if (mips_optional_operand_p (operand)
7285           && args[1] == ','
7286           && (arg.token[0].type != OT_REG
7287               || arg.token[1].type == OT_END))
7288         {
7289           /* Assume that the register has been elided and is the
7290              same as the first operand.  */
7291           arg.token = tokens;
7292           arg.argnum = 1;
7293         }
7294
7295       if (!match_operand (&arg, operand))
7296         return FALSE;
7297     }
7298 }
7299
7300 /* Like match_insn, but for MIPS16.  */
7301
7302 static bfd_boolean
7303 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7304                    struct mips_operand_token *tokens)
7305 {
7306   const char *args;
7307   const struct mips_operand *operand;
7308   const struct mips_operand *ext_operand;
7309   struct mips_arg_info arg;
7310   int relax_char;
7311
7312   create_insn (insn, opcode);
7313   imm_expr.X_op = O_absent;
7314   imm2_expr.X_op = O_absent;
7315   offset_expr.X_op = O_absent;
7316   offset_reloc[0] = BFD_RELOC_UNUSED;
7317   offset_reloc[1] = BFD_RELOC_UNUSED;
7318   offset_reloc[2] = BFD_RELOC_UNUSED;
7319   relax_char = 0;
7320
7321   memset (&arg, 0, sizeof (arg));
7322   arg.insn = insn;
7323   arg.token = tokens;
7324   arg.argnum = 1;
7325   arg.last_regno = ILLEGAL_REG;
7326   arg.dest_regno = ILLEGAL_REG;
7327   relax_char = 0;
7328   for (args = opcode->args;; ++args)
7329     {
7330       int c;
7331
7332       if (arg.token->type == OT_END)
7333         {
7334           offsetT value;
7335
7336           /* Handle unary instructions in which only one operand is given.
7337              The source is then the same as the destination.  */
7338           if (arg.opnum == 1 && *args == ',')
7339             {
7340               operand = decode_mips16_operand (args[1], FALSE);
7341               if (operand && mips_optional_operand_p (operand))
7342                 {
7343                   arg.token = tokens;
7344                   arg.argnum = 1;
7345                   continue;
7346                 }
7347             }
7348
7349           /* Fail the match if there were too few operands.  */
7350           if (*args)
7351             return FALSE;
7352
7353           /* Successful match.  Stuff the immediate value in now, if
7354              we can.  */
7355           clear_insn_error ();
7356           if (opcode->pinfo == INSN_MACRO)
7357             {
7358               gas_assert (relax_char == 0 || relax_char == 'p');
7359               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7360             }
7361           else if (relax_char
7362                    && offset_expr.X_op == O_constant
7363                    && calculate_reloc (*offset_reloc,
7364                                        offset_expr.X_add_number,
7365                                        &value))
7366             {
7367               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7368                             forced_insn_length, &insn->insn_opcode);
7369               offset_expr.X_op = O_absent;
7370               *offset_reloc = BFD_RELOC_UNUSED;
7371             }
7372           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7373             {
7374               if (forced_insn_length == 2)
7375                 set_insn_error (0, _("invalid unextended operand value"));
7376               forced_insn_length = 4;
7377               insn->insn_opcode |= MIPS16_EXTEND;
7378             }
7379           else if (relax_char)
7380             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7381
7382           check_completed_insn (&arg);
7383           return TRUE;
7384         }
7385
7386       /* Fail the match if the line has too many operands.   */
7387       if (*args == 0)
7388         return FALSE;
7389
7390       /* Handle characters that need to match exactly.  */
7391       if (*args == '(' || *args == ')' || *args == ',')
7392         {
7393           if (match_char (&arg, *args))
7394             continue;
7395           return FALSE;
7396         }
7397
7398       arg.opnum += 1;
7399       c = *args;
7400       switch (c)
7401         {
7402         case 'p':
7403         case 'q':
7404         case 'A':
7405         case 'B':
7406         case 'E':
7407           relax_char = c;
7408           break;
7409
7410         case 'I':
7411           if (!match_const_int (&arg, &imm_expr.X_add_number))
7412             return FALSE;
7413           imm_expr.X_op = O_constant;
7414           if (HAVE_32BIT_GPRS)
7415             normalize_constant_expr (&imm_expr);
7416           continue;
7417
7418         case 'a':
7419         case 'i':
7420           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7421           insn->insn_opcode <<= 16;
7422           break;
7423         }
7424
7425       operand = decode_mips16_operand (c, FALSE);
7426       if (!operand)
7427         abort ();
7428
7429       /* '6' is a special case.  It is used for BREAK and SDBBP,
7430          whose operands are only meaningful to the software that decodes
7431          them.  This means that there is no architectural reason why
7432          they cannot be prefixed by EXTEND, but in practice,
7433          exception handlers will only look at the instruction
7434          itself.  We therefore allow '6' to be extended when
7435          disassembling but not when assembling.  */
7436       if (operand->type != OP_PCREL && c != '6')
7437         {
7438           ext_operand = decode_mips16_operand (c, TRUE);
7439           if (operand != ext_operand)
7440             {
7441               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7442                 {
7443                   offset_expr.X_op = O_constant;
7444                   offset_expr.X_add_number = 0;
7445                   relax_char = c;
7446                   continue;
7447                 }
7448
7449               /* We need the OT_INTEGER check because some MIPS16
7450                  immediate variants are listed before the register ones.  */
7451               if (arg.token->type != OT_INTEGER
7452                   || !match_expression (&arg, &offset_expr, offset_reloc))
7453                 return FALSE;
7454
7455               /* '8' is used for SLTI(U) and has traditionally not
7456                  been allowed to take relocation operators.  */
7457               if (offset_reloc[0] != BFD_RELOC_UNUSED
7458                   && (ext_operand->size != 16 || c == '8'))
7459                 return FALSE;
7460
7461               relax_char = c;
7462               continue;
7463             }
7464         }
7465
7466       if (mips_optional_operand_p (operand)
7467           && args[1] == ','
7468           && (arg.token[0].type != OT_REG
7469               || arg.token[1].type == OT_END))
7470         {
7471           /* Assume that the register has been elided and is the
7472              same as the first operand.  */
7473           arg.token = tokens;
7474           arg.argnum = 1;
7475         }
7476
7477       if (!match_operand (&arg, operand))
7478         return FALSE;
7479     }
7480 }
7481
7482 /* Set up global variables for the start of a new macro.  */
7483
7484 static void
7485 macro_start (void)
7486 {
7487   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7488   memset (&mips_macro_warning.first_insn_sizes, 0,
7489           sizeof (mips_macro_warning.first_insn_sizes));
7490   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7491   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7492                                      && delayed_branch_p (&history[0]));
7493   switch (history[0].insn_mo->pinfo2
7494           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7495     {
7496     case INSN2_BRANCH_DELAY_32BIT:
7497       mips_macro_warning.delay_slot_length = 4;
7498       break;
7499     case INSN2_BRANCH_DELAY_16BIT:
7500       mips_macro_warning.delay_slot_length = 2;
7501       break;
7502     default:
7503       mips_macro_warning.delay_slot_length = 0;
7504       break;
7505     }
7506   mips_macro_warning.first_frag = NULL;
7507 }
7508
7509 /* Given that a macro is longer than one instruction or of the wrong size,
7510    return the appropriate warning for it.  Return null if no warning is
7511    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7512    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7513    and RELAX_NOMACRO.  */
7514
7515 static const char *
7516 macro_warning (relax_substateT subtype)
7517 {
7518   if (subtype & RELAX_DELAY_SLOT)
7519     return _("Macro instruction expanded into multiple instructions"
7520              " in a branch delay slot");
7521   else if (subtype & RELAX_NOMACRO)
7522     return _("Macro instruction expanded into multiple instructions");
7523   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
7524                       | RELAX_DELAY_SLOT_SIZE_SECOND))
7525     return ((subtype & RELAX_DELAY_SLOT_16BIT)
7526             ? _("Macro instruction expanded into a wrong size instruction"
7527                 " in a 16-bit branch delay slot")
7528             : _("Macro instruction expanded into a wrong size instruction"
7529                 " in a 32-bit branch delay slot"));
7530   else
7531     return 0;
7532 }
7533
7534 /* Finish up a macro.  Emit warnings as appropriate.  */
7535
7536 static void
7537 macro_end (void)
7538 {
7539   /* Relaxation warning flags.  */
7540   relax_substateT subtype = 0;
7541
7542   /* Check delay slot size requirements.  */
7543   if (mips_macro_warning.delay_slot_length == 2)
7544     subtype |= RELAX_DELAY_SLOT_16BIT;
7545   if (mips_macro_warning.delay_slot_length != 0)
7546     {
7547       if (mips_macro_warning.delay_slot_length
7548           != mips_macro_warning.first_insn_sizes[0])
7549         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
7550       if (mips_macro_warning.delay_slot_length
7551           != mips_macro_warning.first_insn_sizes[1])
7552         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
7553     }
7554
7555   /* Check instruction count requirements.  */
7556   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
7557     {
7558       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
7559         subtype |= RELAX_SECOND_LONGER;
7560       if (mips_opts.warn_about_macros)
7561         subtype |= RELAX_NOMACRO;
7562       if (mips_macro_warning.delay_slot_p)
7563         subtype |= RELAX_DELAY_SLOT;
7564     }
7565
7566   /* If both alternatives fail to fill a delay slot correctly,
7567      emit the warning now.  */
7568   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
7569       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
7570     {
7571       relax_substateT s;
7572       const char *msg;
7573
7574       s = subtype & (RELAX_DELAY_SLOT_16BIT
7575                      | RELAX_DELAY_SLOT_SIZE_FIRST
7576                      | RELAX_DELAY_SLOT_SIZE_SECOND);
7577       msg = macro_warning (s);
7578       if (msg != NULL)
7579         as_warn ("%s", msg);
7580       subtype &= ~s;
7581     }
7582
7583   /* If both implementations are longer than 1 instruction, then emit the
7584      warning now.  */
7585   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
7586     {
7587       relax_substateT s;
7588       const char *msg;
7589
7590       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
7591       msg = macro_warning (s);
7592       if (msg != NULL)
7593         as_warn ("%s", msg);
7594       subtype &= ~s;
7595     }
7596
7597   /* If any flags still set, then one implementation might need a warning
7598      and the other either will need one of a different kind or none at all.
7599      Pass any remaining flags over to relaxation.  */
7600   if (mips_macro_warning.first_frag != NULL)
7601     mips_macro_warning.first_frag->fr_subtype |= subtype;
7602 }
7603
7604 /* Instruction operand formats used in macros that vary between
7605    standard MIPS and microMIPS code.  */
7606
7607 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7608 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7609 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7610 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7611 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7612 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7613 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7614 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7615
7616 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7617 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7618 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7619 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7620 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7621 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7622 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7623 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7624
7625 /* Read a macro's relocation codes from *ARGS and store them in *R.
7626    The first argument in *ARGS will be either the code for a single
7627    relocation or -1 followed by the three codes that make up a
7628    composite relocation.  */
7629
7630 static void
7631 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7632 {
7633   int i, next;
7634
7635   next = va_arg (*args, int);
7636   if (next >= 0)
7637     r[0] = (bfd_reloc_code_real_type) next;
7638   else
7639     {
7640       for (i = 0; i < 3; i++)
7641         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7642       /* This function is only used for 16-bit relocation fields.
7643          To make the macro code simpler, treat an unrelocated value
7644          in the same way as BFD_RELOC_LO16.  */
7645       if (r[0] == BFD_RELOC_UNUSED)
7646         r[0] = BFD_RELOC_LO16;
7647     }
7648 }
7649
7650 /* Build an instruction created by a macro expansion.  This is passed
7651    a pointer to the count of instructions created so far, an
7652    expression, the name of the instruction to build, an operand format
7653    string, and corresponding arguments.  */
7654
7655 static void
7656 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
7657 {
7658   const struct mips_opcode *mo = NULL;
7659   bfd_reloc_code_real_type r[3];
7660   const struct mips_opcode *amo;
7661   const struct mips_operand *operand;
7662   struct hash_control *hash;
7663   struct mips_cl_insn insn;
7664   va_list args;
7665   unsigned int uval;
7666
7667   va_start (args, fmt);
7668
7669   if (mips_opts.mips16)
7670     {
7671       mips16_macro_build (ep, name, fmt, &args);
7672       va_end (args);
7673       return;
7674     }
7675
7676   r[0] = BFD_RELOC_UNUSED;
7677   r[1] = BFD_RELOC_UNUSED;
7678   r[2] = BFD_RELOC_UNUSED;
7679   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
7680   amo = (struct mips_opcode *) hash_find (hash, name);
7681   gas_assert (amo);
7682   gas_assert (strcmp (name, amo->name) == 0);
7683
7684   do
7685     {
7686       /* Search until we get a match for NAME.  It is assumed here that
7687          macros will never generate MDMX, MIPS-3D, or MT instructions.
7688          We try to match an instruction that fulfils the branch delay
7689          slot instruction length requirement (if any) of the previous
7690          instruction.  While doing this we record the first instruction
7691          seen that matches all the other conditions and use it anyway
7692          if the requirement cannot be met; we will issue an appropriate
7693          warning later on.  */
7694       if (strcmp (fmt, amo->args) == 0
7695           && amo->pinfo != INSN_MACRO
7696           && is_opcode_valid (amo)
7697           && is_size_valid (amo))
7698         {
7699           if (is_delay_slot_valid (amo))
7700             {
7701               mo = amo;
7702               break;
7703             }
7704           else if (!mo)
7705             mo = amo;
7706         }
7707
7708       ++amo;
7709       gas_assert (amo->name);
7710     }
7711   while (strcmp (name, amo->name) == 0);
7712
7713   gas_assert (mo);
7714   create_insn (&insn, mo);
7715   for (; *fmt; ++fmt)
7716     {
7717       switch (*fmt)
7718         {
7719         case ',':
7720         case '(':
7721         case ')':
7722         case 'z':
7723           break;
7724
7725         case 'i':
7726         case 'j':
7727           macro_read_relocs (&args, r);
7728           gas_assert (*r == BFD_RELOC_GPREL16
7729                       || *r == BFD_RELOC_MIPS_HIGHER
7730                       || *r == BFD_RELOC_HI16_S
7731                       || *r == BFD_RELOC_LO16
7732                       || *r == BFD_RELOC_MIPS_GOT_OFST);
7733           break;
7734
7735         case 'o':
7736           macro_read_relocs (&args, r);
7737           break;
7738
7739         case 'u':
7740           macro_read_relocs (&args, r);
7741           gas_assert (ep != NULL
7742                       && (ep->X_op == O_constant
7743                           || (ep->X_op == O_symbol
7744                               && (*r == BFD_RELOC_MIPS_HIGHEST
7745                                   || *r == BFD_RELOC_HI16_S
7746                                   || *r == BFD_RELOC_HI16
7747                                   || *r == BFD_RELOC_GPREL16
7748                                   || *r == BFD_RELOC_MIPS_GOT_HI16
7749                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
7750           break;
7751
7752         case 'p':
7753           gas_assert (ep != NULL);
7754
7755           /*
7756            * This allows macro() to pass an immediate expression for
7757            * creating short branches without creating a symbol.
7758            *
7759            * We don't allow branch relaxation for these branches, as
7760            * they should only appear in ".set nomacro" anyway.
7761            */
7762           if (ep->X_op == O_constant)
7763             {
7764               /* For microMIPS we always use relocations for branches.
7765                  So we should not resolve immediate values.  */
7766               gas_assert (!mips_opts.micromips);
7767
7768               if ((ep->X_add_number & 3) != 0)
7769                 as_bad (_("branch to misaligned address (0x%lx)"),
7770                         (unsigned long) ep->X_add_number);
7771               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
7772                 as_bad (_("branch address range overflow (0x%lx)"),
7773                         (unsigned long) ep->X_add_number);
7774               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
7775               ep = NULL;
7776             }
7777           else
7778             *r = BFD_RELOC_16_PCREL_S2;
7779           break;
7780
7781         case 'a':
7782           gas_assert (ep != NULL);
7783           *r = BFD_RELOC_MIPS_JMP;
7784           break;
7785
7786         default:
7787           operand = (mips_opts.micromips
7788                      ? decode_micromips_operand (fmt)
7789                      : decode_mips_operand (fmt));
7790           if (!operand)
7791             abort ();
7792
7793           uval = va_arg (args, int);
7794           if (operand->type == OP_CLO_CLZ_DEST)
7795             uval |= (uval << 5);
7796           insn_insert_operand (&insn, operand, uval);
7797
7798           if (*fmt == '+' || *fmt == 'm')
7799             ++fmt;
7800           break;
7801         }
7802     }
7803   va_end (args);
7804   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7805
7806   append_insn (&insn, ep, r, TRUE);
7807 }
7808
7809 static void
7810 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
7811                     va_list *args)
7812 {
7813   struct mips_opcode *mo;
7814   struct mips_cl_insn insn;
7815   const struct mips_operand *operand;
7816   bfd_reloc_code_real_type r[3]
7817     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
7818
7819   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
7820   gas_assert (mo);
7821   gas_assert (strcmp (name, mo->name) == 0);
7822
7823   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
7824     {
7825       ++mo;
7826       gas_assert (mo->name);
7827       gas_assert (strcmp (name, mo->name) == 0);
7828     }
7829
7830   create_insn (&insn, mo);
7831   for (; *fmt; ++fmt)
7832     {
7833       int c;
7834
7835       c = *fmt;
7836       switch (c)
7837         {
7838         case ',':
7839         case '(':
7840         case ')':
7841           break;
7842
7843         case '0':
7844         case 'S':
7845         case 'P':
7846         case 'R':
7847           break;
7848
7849         case '<':
7850         case '>':
7851         case '4':
7852         case '5':
7853         case 'H':
7854         case 'W':
7855         case 'D':
7856         case 'j':
7857         case '8':
7858         case 'V':
7859         case 'C':
7860         case 'U':
7861         case 'k':
7862         case 'K':
7863         case 'p':
7864         case 'q':
7865           {
7866             offsetT value;
7867
7868             gas_assert (ep != NULL);
7869
7870             if (ep->X_op != O_constant)
7871               *r = (int) BFD_RELOC_UNUSED + c;
7872             else if (calculate_reloc (*r, ep->X_add_number, &value))
7873               {
7874                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
7875                 ep = NULL;
7876                 *r = BFD_RELOC_UNUSED;
7877               }
7878           }
7879           break;
7880
7881         default:
7882           operand = decode_mips16_operand (c, FALSE);
7883           if (!operand)
7884             abort ();
7885
7886           insn_insert_operand (&insn, operand, va_arg (*args, int));
7887           break;
7888         }
7889     }
7890
7891   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7892
7893   append_insn (&insn, ep, r, TRUE);
7894 }
7895
7896 /*
7897  * Generate a "jalr" instruction with a relocation hint to the called
7898  * function.  This occurs in NewABI PIC code.
7899  */
7900 static void
7901 macro_build_jalr (expressionS *ep, int cprestore)
7902 {
7903   static const bfd_reloc_code_real_type jalr_relocs[2]
7904     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
7905   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
7906   const char *jalr;
7907   char *f = NULL;
7908
7909   if (MIPS_JALR_HINT_P (ep))
7910     {
7911       frag_grow (8);
7912       f = frag_more (0);
7913     }
7914   if (mips_opts.micromips)
7915     {
7916       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
7917               ? "jalr" : "jalrs");
7918       if (MIPS_JALR_HINT_P (ep)
7919           || mips_opts.insn32
7920           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
7921         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
7922       else
7923         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
7924     }
7925   else
7926     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
7927   if (MIPS_JALR_HINT_P (ep))
7928     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
7929 }
7930
7931 /*
7932  * Generate a "lui" instruction.
7933  */
7934 static void
7935 macro_build_lui (expressionS *ep, int regnum)
7936 {
7937   gas_assert (! mips_opts.mips16);
7938
7939   if (ep->X_op != O_constant)
7940     {
7941       gas_assert (ep->X_op == O_symbol);
7942       /* _gp_disp is a special case, used from s_cpload.
7943          __gnu_local_gp is used if mips_no_shared.  */
7944       gas_assert (mips_pic == NO_PIC
7945               || (! HAVE_NEWABI
7946                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
7947               || (! mips_in_shared
7948                   && strcmp (S_GET_NAME (ep->X_add_symbol),
7949                              "__gnu_local_gp") == 0));
7950     }
7951
7952   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
7953 }
7954
7955 /* Generate a sequence of instructions to do a load or store from a constant
7956    offset off of a base register (breg) into/from a target register (treg),
7957    using AT if necessary.  */
7958 static void
7959 macro_build_ldst_constoffset (expressionS *ep, const char *op,
7960                               int treg, int breg, int dbl)
7961 {
7962   gas_assert (ep->X_op == O_constant);
7963
7964   /* Sign-extending 32-bit constants makes their handling easier.  */
7965   if (!dbl)
7966     normalize_constant_expr (ep);
7967
7968   /* Right now, this routine can only handle signed 32-bit constants.  */
7969   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
7970     as_warn (_("operand overflow"));
7971
7972   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
7973     {
7974       /* Signed 16-bit offset will fit in the op.  Easy!  */
7975       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
7976     }
7977   else
7978     {
7979       /* 32-bit offset, need multiple instructions and AT, like:
7980            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
7981            addu     $tempreg,$tempreg,$breg
7982            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
7983          to handle the complete offset.  */
7984       macro_build_lui (ep, AT);
7985       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7986       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7987
7988       if (!mips_opts.at)
7989         as_bad (_("Macro used $at after \".set noat\""));
7990     }
7991 }
7992
7993 /*                      set_at()
7994  * Generates code to set the $at register to true (one)
7995  * if reg is less than the immediate expression.
7996  */
7997 static void
7998 set_at (int reg, int unsignedp)
7999 {
8000   if (imm_expr.X_op == O_constant
8001       && imm_expr.X_add_number >= -0x8000
8002       && imm_expr.X_add_number < 0x8000)
8003     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8004                  AT, reg, BFD_RELOC_LO16);
8005   else
8006     {
8007       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
8008       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8009     }
8010 }
8011
8012 /* Count the leading zeroes by performing a binary chop. This is a
8013    bulky bit of source, but performance is a LOT better for the
8014    majority of values than a simple loop to count the bits:
8015        for (lcnt = 0; (lcnt < 32); lcnt++)
8016          if ((v) & (1 << (31 - lcnt)))
8017            break;
8018   However it is not code size friendly, and the gain will drop a bit
8019   on certain cached systems.
8020 */
8021 #define COUNT_TOP_ZEROES(v)             \
8022   (((v) & ~0xffff) == 0                 \
8023    ? ((v) & ~0xff) == 0                 \
8024      ? ((v) & ~0xf) == 0                \
8025        ? ((v) & ~0x3) == 0              \
8026          ? ((v) & ~0x1) == 0            \
8027            ? !(v)                       \
8028              ? 32                       \
8029              : 31                       \
8030            : 30                         \
8031          : ((v) & ~0x7) == 0            \
8032            ? 29                         \
8033            : 28                         \
8034        : ((v) & ~0x3f) == 0             \
8035          ? ((v) & ~0x1f) == 0           \
8036            ? 27                         \
8037            : 26                         \
8038          : ((v) & ~0x7f) == 0           \
8039            ? 25                         \
8040            : 24                         \
8041      : ((v) & ~0xfff) == 0              \
8042        ? ((v) & ~0x3ff) == 0            \
8043          ? ((v) & ~0x1ff) == 0          \
8044            ? 23                         \
8045            : 22                         \
8046          : ((v) & ~0x7ff) == 0          \
8047            ? 21                         \
8048            : 20                         \
8049        : ((v) & ~0x3fff) == 0           \
8050          ? ((v) & ~0x1fff) == 0         \
8051            ? 19                         \
8052            : 18                         \
8053          : ((v) & ~0x7fff) == 0         \
8054            ? 17                         \
8055            : 16                         \
8056    : ((v) & ~0xffffff) == 0             \
8057      ? ((v) & ~0xfffff) == 0            \
8058        ? ((v) & ~0x3ffff) == 0          \
8059          ? ((v) & ~0x1ffff) == 0        \
8060            ? 15                         \
8061            : 14                         \
8062          : ((v) & ~0x7ffff) == 0        \
8063            ? 13                         \
8064            : 12                         \
8065        : ((v) & ~0x3fffff) == 0         \
8066          ? ((v) & ~0x1fffff) == 0       \
8067            ? 11                         \
8068            : 10                         \
8069          : ((v) & ~0x7fffff) == 0       \
8070            ? 9                          \
8071            : 8                          \
8072      : ((v) & ~0xfffffff) == 0          \
8073        ? ((v) & ~0x3ffffff) == 0        \
8074          ? ((v) & ~0x1ffffff) == 0      \
8075            ? 7                          \
8076            : 6                          \
8077          : ((v) & ~0x7ffffff) == 0      \
8078            ? 5                          \
8079            : 4                          \
8080        : ((v) & ~0x3fffffff) == 0       \
8081          ? ((v) & ~0x1fffffff) == 0     \
8082            ? 3                          \
8083            : 2                          \
8084          : ((v) & ~0x7fffffff) == 0     \
8085            ? 1                          \
8086            : 0)
8087
8088 /*                      load_register()
8089  *  This routine generates the least number of instructions necessary to load
8090  *  an absolute expression value into a register.
8091  */
8092 static void
8093 load_register (int reg, expressionS *ep, int dbl)
8094 {
8095   int freg;
8096   expressionS hi32, lo32;
8097
8098   if (ep->X_op != O_big)
8099     {
8100       gas_assert (ep->X_op == O_constant);
8101
8102       /* Sign-extending 32-bit constants makes their handling easier.  */
8103       if (!dbl)
8104         normalize_constant_expr (ep);
8105
8106       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8107         {
8108           /* We can handle 16 bit signed values with an addiu to
8109              $zero.  No need to ever use daddiu here, since $zero and
8110              the result are always correct in 32 bit mode.  */
8111           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8112           return;
8113         }
8114       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8115         {
8116           /* We can handle 16 bit unsigned values with an ori to
8117              $zero.  */
8118           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8119           return;
8120         }
8121       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8122         {
8123           /* 32 bit values require an lui.  */
8124           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8125           if ((ep->X_add_number & 0xffff) != 0)
8126             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8127           return;
8128         }
8129     }
8130
8131   /* The value is larger than 32 bits.  */
8132
8133   if (!dbl || HAVE_32BIT_GPRS)
8134     {
8135       char value[32];
8136
8137       sprintf_vma (value, ep->X_add_number);
8138       as_bad (_("Number (0x%s) larger than 32 bits"), value);
8139       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8140       return;
8141     }
8142
8143   if (ep->X_op != O_big)
8144     {
8145       hi32 = *ep;
8146       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8147       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8148       hi32.X_add_number &= 0xffffffff;
8149       lo32 = *ep;
8150       lo32.X_add_number &= 0xffffffff;
8151     }
8152   else
8153     {
8154       gas_assert (ep->X_add_number > 2);
8155       if (ep->X_add_number == 3)
8156         generic_bignum[3] = 0;
8157       else if (ep->X_add_number > 4)
8158         as_bad (_("Number larger than 64 bits"));
8159       lo32.X_op = O_constant;
8160       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8161       hi32.X_op = O_constant;
8162       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8163     }
8164
8165   if (hi32.X_add_number == 0)
8166     freg = 0;
8167   else
8168     {
8169       int shift, bit;
8170       unsigned long hi, lo;
8171
8172       if (hi32.X_add_number == (offsetT) 0xffffffff)
8173         {
8174           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8175             {
8176               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8177               return;
8178             }
8179           if (lo32.X_add_number & 0x80000000)
8180             {
8181               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8182               if (lo32.X_add_number & 0xffff)
8183                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8184               return;
8185             }
8186         }
8187
8188       /* Check for 16bit shifted constant.  We know that hi32 is
8189          non-zero, so start the mask on the first bit of the hi32
8190          value.  */
8191       shift = 17;
8192       do
8193         {
8194           unsigned long himask, lomask;
8195
8196           if (shift < 32)
8197             {
8198               himask = 0xffff >> (32 - shift);
8199               lomask = (0xffff << shift) & 0xffffffff;
8200             }
8201           else
8202             {
8203               himask = 0xffff << (shift - 32);
8204               lomask = 0;
8205             }
8206           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8207               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8208             {
8209               expressionS tmp;
8210
8211               tmp.X_op = O_constant;
8212               if (shift < 32)
8213                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8214                                     | (lo32.X_add_number >> shift));
8215               else
8216                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8217               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8218               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8219                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8220               return;
8221             }
8222           ++shift;
8223         }
8224       while (shift <= (64 - 16));
8225
8226       /* Find the bit number of the lowest one bit, and store the
8227          shifted value in hi/lo.  */
8228       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8229       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8230       if (lo != 0)
8231         {
8232           bit = 0;
8233           while ((lo & 1) == 0)
8234             {
8235               lo >>= 1;
8236               ++bit;
8237             }
8238           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8239           hi >>= bit;
8240         }
8241       else
8242         {
8243           bit = 32;
8244           while ((hi & 1) == 0)
8245             {
8246               hi >>= 1;
8247               ++bit;
8248             }
8249           lo = hi;
8250           hi = 0;
8251         }
8252
8253       /* Optimize if the shifted value is a (power of 2) - 1.  */
8254       if ((hi == 0 && ((lo + 1) & lo) == 0)
8255           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8256         {
8257           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8258           if (shift != 0)
8259             {
8260               expressionS tmp;
8261
8262               /* This instruction will set the register to be all
8263                  ones.  */
8264               tmp.X_op = O_constant;
8265               tmp.X_add_number = (offsetT) -1;
8266               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8267               if (bit != 0)
8268                 {
8269                   bit += shift;
8270                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8271                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8272                 }
8273               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8274                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8275               return;
8276             }
8277         }
8278
8279       /* Sign extend hi32 before calling load_register, because we can
8280          generally get better code when we load a sign extended value.  */
8281       if ((hi32.X_add_number & 0x80000000) != 0)
8282         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8283       load_register (reg, &hi32, 0);
8284       freg = reg;
8285     }
8286   if ((lo32.X_add_number & 0xffff0000) == 0)
8287     {
8288       if (freg != 0)
8289         {
8290           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8291           freg = reg;
8292         }
8293     }
8294   else
8295     {
8296       expressionS mid16;
8297
8298       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8299         {
8300           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8301           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8302           return;
8303         }
8304
8305       if (freg != 0)
8306         {
8307           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8308           freg = reg;
8309         }
8310       mid16 = lo32;
8311       mid16.X_add_number >>= 16;
8312       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8313       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8314       freg = reg;
8315     }
8316   if ((lo32.X_add_number & 0xffff) != 0)
8317     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8318 }
8319
8320 static inline void
8321 load_delay_nop (void)
8322 {
8323   if (!gpr_interlocks)
8324     macro_build (NULL, "nop", "");
8325 }
8326
8327 /* Load an address into a register.  */
8328
8329 static void
8330 load_address (int reg, expressionS *ep, int *used_at)
8331 {
8332   if (ep->X_op != O_constant
8333       && ep->X_op != O_symbol)
8334     {
8335       as_bad (_("expression too complex"));
8336       ep->X_op = O_constant;
8337     }
8338
8339   if (ep->X_op == O_constant)
8340     {
8341       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8342       return;
8343     }
8344
8345   if (mips_pic == NO_PIC)
8346     {
8347       /* If this is a reference to a GP relative symbol, we want
8348            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8349          Otherwise we want
8350            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8351            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8352          If we have an addend, we always use the latter form.
8353
8354          With 64bit address space and a usable $at we want
8355            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8356            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8357            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8358            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8359            dsll32       $reg,0
8360            daddu        $reg,$reg,$at
8361
8362          If $at is already in use, we use a path which is suboptimal
8363          on superscalar processors.
8364            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8365            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8366            dsll         $reg,16
8367            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8368            dsll         $reg,16
8369            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8370
8371          For GP relative symbols in 64bit address space we can use
8372          the same sequence as in 32bit address space.  */
8373       if (HAVE_64BIT_SYMBOLS)
8374         {
8375           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8376               && !nopic_need_relax (ep->X_add_symbol, 1))
8377             {
8378               relax_start (ep->X_add_symbol);
8379               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8380                            mips_gp_register, BFD_RELOC_GPREL16);
8381               relax_switch ();
8382             }
8383
8384           if (*used_at == 0 && mips_opts.at)
8385             {
8386               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8387               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8388               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8389                            BFD_RELOC_MIPS_HIGHER);
8390               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8391               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8392               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8393               *used_at = 1;
8394             }
8395           else
8396             {
8397               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8398               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8399                            BFD_RELOC_MIPS_HIGHER);
8400               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8401               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8402               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8403               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8404             }
8405
8406           if (mips_relax.sequence)
8407             relax_end ();
8408         }
8409       else
8410         {
8411           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8412               && !nopic_need_relax (ep->X_add_symbol, 1))
8413             {
8414               relax_start (ep->X_add_symbol);
8415               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8416                            mips_gp_register, BFD_RELOC_GPREL16);
8417               relax_switch ();
8418             }
8419           macro_build_lui (ep, reg);
8420           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8421                        reg, reg, BFD_RELOC_LO16);
8422           if (mips_relax.sequence)
8423             relax_end ();
8424         }
8425     }
8426   else if (!mips_big_got)
8427     {
8428       expressionS ex;
8429
8430       /* If this is a reference to an external symbol, we want
8431            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8432          Otherwise we want
8433            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8434            nop
8435            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8436          If there is a constant, it must be added in after.
8437
8438          If we have NewABI, we want
8439            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8440          unless we're referencing a global symbol with a non-zero
8441          offset, in which case cst must be added separately.  */
8442       if (HAVE_NEWABI)
8443         {
8444           if (ep->X_add_number)
8445             {
8446               ex.X_add_number = ep->X_add_number;
8447               ep->X_add_number = 0;
8448               relax_start (ep->X_add_symbol);
8449               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8450                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8451               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8452                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8453               ex.X_op = O_constant;
8454               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8455                            reg, reg, BFD_RELOC_LO16);
8456               ep->X_add_number = ex.X_add_number;
8457               relax_switch ();
8458             }
8459           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8460                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8461           if (mips_relax.sequence)
8462             relax_end ();
8463         }
8464       else
8465         {
8466           ex.X_add_number = ep->X_add_number;
8467           ep->X_add_number = 0;
8468           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8469                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8470           load_delay_nop ();
8471           relax_start (ep->X_add_symbol);
8472           relax_switch ();
8473           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8474                        BFD_RELOC_LO16);
8475           relax_end ();
8476
8477           if (ex.X_add_number != 0)
8478             {
8479               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8480                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8481               ex.X_op = O_constant;
8482               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8483                            reg, reg, BFD_RELOC_LO16);
8484             }
8485         }
8486     }
8487   else if (mips_big_got)
8488     {
8489       expressionS ex;
8490
8491       /* This is the large GOT case.  If this is a reference to an
8492          external symbol, we want
8493            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8494            addu         $reg,$reg,$gp
8495            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8496
8497          Otherwise, for a reference to a local symbol in old ABI, we want
8498            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8499            nop
8500            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8501          If there is a constant, it must be added in after.
8502
8503          In the NewABI, for local symbols, with or without offsets, we want:
8504            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8505            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8506       */
8507       if (HAVE_NEWABI)
8508         {
8509           ex.X_add_number = ep->X_add_number;
8510           ep->X_add_number = 0;
8511           relax_start (ep->X_add_symbol);
8512           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8513           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8514                        reg, reg, mips_gp_register);
8515           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8516                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8517           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8518             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8519           else if (ex.X_add_number)
8520             {
8521               ex.X_op = O_constant;
8522               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8523                            BFD_RELOC_LO16);
8524             }
8525
8526           ep->X_add_number = ex.X_add_number;
8527           relax_switch ();
8528           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8529                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8530           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8531                        BFD_RELOC_MIPS_GOT_OFST);
8532           relax_end ();
8533         }
8534       else
8535         {
8536           ex.X_add_number = ep->X_add_number;
8537           ep->X_add_number = 0;
8538           relax_start (ep->X_add_symbol);
8539           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8540           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8541                        reg, reg, mips_gp_register);
8542           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8543                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8544           relax_switch ();
8545           if (reg_needs_delay (mips_gp_register))
8546             {
8547               /* We need a nop before loading from $gp.  This special
8548                  check is required because the lui which starts the main
8549                  instruction stream does not refer to $gp, and so will not
8550                  insert the nop which may be required.  */
8551               macro_build (NULL, "nop", "");
8552             }
8553           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8554                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8555           load_delay_nop ();
8556           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8557                        BFD_RELOC_LO16);
8558           relax_end ();
8559
8560           if (ex.X_add_number != 0)
8561             {
8562               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8563                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8564               ex.X_op = O_constant;
8565               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8566                            BFD_RELOC_LO16);
8567             }
8568         }
8569     }
8570   else
8571     abort ();
8572
8573   if (!mips_opts.at && *used_at == 1)
8574     as_bad (_("Macro used $at after \".set noat\""));
8575 }
8576
8577 /* Move the contents of register SOURCE into register DEST.  */
8578
8579 static void
8580 move_register (int dest, int source)
8581 {
8582   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8583      instruction specifically requires a 32-bit one.  */
8584   if (mips_opts.micromips
8585       && !mips_opts.insn32
8586       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8587     macro_build (NULL, "move", "mp,mj", dest, source);
8588   else
8589     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
8590                  dest, source, 0);
8591 }
8592
8593 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8594    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8595    The two alternatives are:
8596
8597    Global symbol                Local sybmol
8598    -------------                ------------
8599    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8600    ...                          ...
8601    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8602
8603    load_got_offset emits the first instruction and add_got_offset
8604    emits the second for a 16-bit offset or add_got_offset_hilo emits
8605    a sequence to add a 32-bit offset using a scratch register.  */
8606
8607 static void
8608 load_got_offset (int dest, expressionS *local)
8609 {
8610   expressionS global;
8611
8612   global = *local;
8613   global.X_add_number = 0;
8614
8615   relax_start (local->X_add_symbol);
8616   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8617                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8618   relax_switch ();
8619   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8620                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8621   relax_end ();
8622 }
8623
8624 static void
8625 add_got_offset (int dest, expressionS *local)
8626 {
8627   expressionS global;
8628
8629   global.X_op = O_constant;
8630   global.X_op_symbol = NULL;
8631   global.X_add_symbol = NULL;
8632   global.X_add_number = local->X_add_number;
8633
8634   relax_start (local->X_add_symbol);
8635   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8636                dest, dest, BFD_RELOC_LO16);
8637   relax_switch ();
8638   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8639   relax_end ();
8640 }
8641
8642 static void
8643 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8644 {
8645   expressionS global;
8646   int hold_mips_optimize;
8647
8648   global.X_op = O_constant;
8649   global.X_op_symbol = NULL;
8650   global.X_add_symbol = NULL;
8651   global.X_add_number = local->X_add_number;
8652
8653   relax_start (local->X_add_symbol);
8654   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
8655   relax_switch ();
8656   /* Set mips_optimize around the lui instruction to avoid
8657      inserting an unnecessary nop after the lw.  */
8658   hold_mips_optimize = mips_optimize;
8659   mips_optimize = 2;
8660   macro_build_lui (&global, tmp);
8661   mips_optimize = hold_mips_optimize;
8662   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
8663   relax_end ();
8664
8665   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
8666 }
8667
8668 /* Emit a sequence of instructions to emulate a branch likely operation.
8669    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
8670    is its complementing branch with the original condition negated.
8671    CALL is set if the original branch specified the link operation.
8672    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
8673
8674    Code like this is produced in the noreorder mode:
8675
8676         BRNEG   <args>, 1f
8677          nop
8678         b       <sym>
8679          delay slot (executed only if branch taken)
8680     1:
8681
8682    or, if CALL is set:
8683
8684         BRNEG   <args>, 1f
8685          nop
8686         bal     <sym>
8687          delay slot (executed only if branch taken)
8688     1:
8689
8690    In the reorder mode the delay slot would be filled with a nop anyway,
8691    so code produced is simply:
8692
8693         BR      <args>, <sym>
8694          nop
8695
8696    This function is used when producing code for the microMIPS ASE that
8697    does not implement branch likely instructions in hardware.  */
8698
8699 static void
8700 macro_build_branch_likely (const char *br, const char *brneg,
8701                            int call, expressionS *ep, const char *fmt,
8702                            unsigned int sreg, unsigned int treg)
8703 {
8704   int noreorder = mips_opts.noreorder;
8705   expressionS expr1;
8706
8707   gas_assert (mips_opts.micromips);
8708   start_noreorder ();
8709   if (noreorder)
8710     {
8711       micromips_label_expr (&expr1);
8712       macro_build (&expr1, brneg, fmt, sreg, treg);
8713       macro_build (NULL, "nop", "");
8714       macro_build (ep, call ? "bal" : "b", "p");
8715
8716       /* Set to true so that append_insn adds a label.  */
8717       emit_branch_likely_macro = TRUE;
8718     }
8719   else
8720     {
8721       macro_build (ep, br, fmt, sreg, treg);
8722       macro_build (NULL, "nop", "");
8723     }
8724   end_noreorder ();
8725 }
8726
8727 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
8728    the condition code tested.  EP specifies the branch target.  */
8729
8730 static void
8731 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
8732 {
8733   const int call = 0;
8734   const char *brneg;
8735   const char *br;
8736
8737   switch (type)
8738     {
8739     case M_BC1FL:
8740       br = "bc1f";
8741       brneg = "bc1t";
8742       break;
8743     case M_BC1TL:
8744       br = "bc1t";
8745       brneg = "bc1f";
8746       break;
8747     case M_BC2FL:
8748       br = "bc2f";
8749       brneg = "bc2t";
8750       break;
8751     case M_BC2TL:
8752       br = "bc2t";
8753       brneg = "bc2f";
8754       break;
8755     default:
8756       abort ();
8757     }
8758   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
8759 }
8760
8761 /* Emit a two-argument branch macro specified by TYPE, using SREG as
8762    the register tested.  EP specifies the branch target.  */
8763
8764 static void
8765 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
8766 {
8767   const char *brneg = NULL;
8768   const char *br;
8769   int call = 0;
8770
8771   switch (type)
8772     {
8773     case M_BGEZ:
8774       br = "bgez";
8775       break;
8776     case M_BGEZL:
8777       br = mips_opts.micromips ? "bgez" : "bgezl";
8778       brneg = "bltz";
8779       break;
8780     case M_BGEZALL:
8781       gas_assert (mips_opts.micromips);
8782       br = mips_opts.insn32 ? "bgezal" : "bgezals";
8783       brneg = "bltz";
8784       call = 1;
8785       break;
8786     case M_BGTZ:
8787       br = "bgtz";
8788       break;
8789     case M_BGTZL:
8790       br = mips_opts.micromips ? "bgtz" : "bgtzl";
8791       brneg = "blez";
8792       break;
8793     case M_BLEZ:
8794       br = "blez";
8795       break;
8796     case M_BLEZL:
8797       br = mips_opts.micromips ? "blez" : "blezl";
8798       brneg = "bgtz";
8799       break;
8800     case M_BLTZ:
8801       br = "bltz";
8802       break;
8803     case M_BLTZL:
8804       br = mips_opts.micromips ? "bltz" : "bltzl";
8805       brneg = "bgez";
8806       break;
8807     case M_BLTZALL:
8808       gas_assert (mips_opts.micromips);
8809       br = mips_opts.insn32 ? "bltzal" : "bltzals";
8810       brneg = "bgez";
8811       call = 1;
8812       break;
8813     default:
8814       abort ();
8815     }
8816   if (mips_opts.micromips && brneg)
8817     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
8818   else
8819     macro_build (ep, br, "s,p", sreg);
8820 }
8821
8822 /* Emit a three-argument branch macro specified by TYPE, using SREG and
8823    TREG as the registers tested.  EP specifies the branch target.  */
8824
8825 static void
8826 macro_build_branch_rsrt (int type, expressionS *ep,
8827                          unsigned int sreg, unsigned int treg)
8828 {
8829   const char *brneg = NULL;
8830   const int call = 0;
8831   const char *br;
8832
8833   switch (type)
8834     {
8835     case M_BEQ:
8836     case M_BEQ_I:
8837       br = "beq";
8838       break;
8839     case M_BEQL:
8840     case M_BEQL_I:
8841       br = mips_opts.micromips ? "beq" : "beql";
8842       brneg = "bne";
8843       break;
8844     case M_BNE:
8845     case M_BNE_I:
8846       br = "bne";
8847       break;
8848     case M_BNEL:
8849     case M_BNEL_I:
8850       br = mips_opts.micromips ? "bne" : "bnel";
8851       brneg = "beq";
8852       break;
8853     default:
8854       abort ();
8855     }
8856   if (mips_opts.micromips && brneg)
8857     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
8858   else
8859     macro_build (ep, br, "s,t,p", sreg, treg);
8860 }
8861
8862 /* Return the high part that should be loaded in order to make the low
8863    part of VALUE accessible using an offset of OFFBITS bits.  */
8864
8865 static offsetT
8866 offset_high_part (offsetT value, unsigned int offbits)
8867 {
8868   offsetT bias;
8869   addressT low_mask;
8870
8871   if (offbits == 0)
8872     return value;
8873   bias = 1 << (offbits - 1);
8874   low_mask = bias * 2 - 1;
8875   return (value + bias) & ~low_mask;
8876 }
8877
8878 /* Return true if the value stored in offset_expr and offset_reloc
8879    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
8880    amount that the caller wants to add without inducing overflow
8881    and ALIGN is the known alignment of the value in bytes.  */
8882
8883 static bfd_boolean
8884 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
8885 {
8886   if (offbits == 16)
8887     {
8888       /* Accept any relocation operator if overflow isn't a concern.  */
8889       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
8890         return TRUE;
8891
8892       /* These relocations are guaranteed not to overflow in correct links.  */
8893       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
8894           || gprel16_reloc_p (*offset_reloc))
8895         return TRUE;
8896     }
8897   if (offset_expr.X_op == O_constant
8898       && offset_high_part (offset_expr.X_add_number, offbits) == 0
8899       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
8900     return TRUE;
8901   return FALSE;
8902 }
8903
8904 /*
8905  *                      Build macros
8906  *   This routine implements the seemingly endless macro or synthesized
8907  * instructions and addressing modes in the mips assembly language. Many
8908  * of these macros are simple and are similar to each other. These could
8909  * probably be handled by some kind of table or grammar approach instead of
8910  * this verbose method. Others are not simple macros but are more like
8911  * optimizing code generation.
8912  *   One interesting optimization is when several store macros appear
8913  * consecutively that would load AT with the upper half of the same address.
8914  * The ensuing load upper instructions are ommited. This implies some kind
8915  * of global optimization. We currently only optimize within a single macro.
8916  *   For many of the load and store macros if the address is specified as a
8917  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
8918  * first load register 'at' with zero and use it as the base register. The
8919  * mips assembler simply uses register $zero. Just one tiny optimization
8920  * we're missing.
8921  */
8922 static void
8923 macro (struct mips_cl_insn *ip, char *str)
8924 {
8925   const struct mips_operand_array *operands;
8926   unsigned int breg, i;
8927   unsigned int tempreg;
8928   int mask;
8929   int used_at = 0;
8930   expressionS label_expr;
8931   expressionS expr1;
8932   expressionS *ep;
8933   const char *s;
8934   const char *s2;
8935   const char *fmt;
8936   int likely = 0;
8937   int coproc = 0;
8938   int offbits = 16;
8939   int call = 0;
8940   int jals = 0;
8941   int dbl = 0;
8942   int imm = 0;
8943   int ust = 0;
8944   int lp = 0;
8945   bfd_boolean large_offset;
8946   int off;
8947   int hold_mips_optimize;
8948   unsigned int align;
8949   unsigned int op[MAX_OPERANDS];
8950
8951   gas_assert (! mips_opts.mips16);
8952
8953   operands = insn_operands (ip);
8954   for (i = 0; i < MAX_OPERANDS; i++)
8955     if (operands->operand[i])
8956       op[i] = insn_extract_operand (ip, operands->operand[i]);
8957     else
8958       op[i] = -1;
8959
8960   mask = ip->insn_mo->mask;
8961
8962   label_expr.X_op = O_constant;
8963   label_expr.X_op_symbol = NULL;
8964   label_expr.X_add_symbol = NULL;
8965   label_expr.X_add_number = 0;
8966
8967   expr1.X_op = O_constant;
8968   expr1.X_op_symbol = NULL;
8969   expr1.X_add_symbol = NULL;
8970   expr1.X_add_number = 1;
8971   align = 1;
8972
8973   switch (mask)
8974     {
8975     case M_DABS:
8976       dbl = 1;
8977     case M_ABS:
8978       /*    bgez    $a0,1f
8979             move    v0,$a0
8980             sub     v0,$zero,$a0
8981          1:
8982        */
8983
8984       start_noreorder ();
8985
8986       if (mips_opts.micromips)
8987         micromips_label_expr (&label_expr);
8988       else
8989         label_expr.X_add_number = 8;
8990       macro_build (&label_expr, "bgez", "s,p", op[1]);
8991       if (op[0] == op[1])
8992         macro_build (NULL, "nop", "");
8993       else
8994         move_register (op[0], op[1]);
8995       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
8996       if (mips_opts.micromips)
8997         micromips_add_label ();
8998
8999       end_noreorder ();
9000       break;
9001
9002     case M_ADD_I:
9003       s = "addi";
9004       s2 = "add";
9005       goto do_addi;
9006     case M_ADDU_I:
9007       s = "addiu";
9008       s2 = "addu";
9009       goto do_addi;
9010     case M_DADD_I:
9011       dbl = 1;
9012       s = "daddi";
9013       s2 = "dadd";
9014       if (!mips_opts.micromips)
9015         goto do_addi;
9016       if (imm_expr.X_op == O_constant
9017           && imm_expr.X_add_number >= -0x200
9018           && imm_expr.X_add_number < 0x200)
9019         {
9020           macro_build (NULL, s, "t,r,.", op[0], op[1], imm_expr.X_add_number);
9021           break;
9022         }
9023       goto do_addi_i;
9024     case M_DADDU_I:
9025       dbl = 1;
9026       s = "daddiu";
9027       s2 = "daddu";
9028     do_addi:
9029       if (imm_expr.X_op == O_constant
9030           && imm_expr.X_add_number >= -0x8000
9031           && imm_expr.X_add_number < 0x8000)
9032         {
9033           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9034           break;
9035         }
9036     do_addi_i:
9037       used_at = 1;
9038       load_register (AT, &imm_expr, dbl);
9039       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9040       break;
9041
9042     case M_AND_I:
9043       s = "andi";
9044       s2 = "and";
9045       goto do_bit;
9046     case M_OR_I:
9047       s = "ori";
9048       s2 = "or";
9049       goto do_bit;
9050     case M_NOR_I:
9051       s = "";
9052       s2 = "nor";
9053       goto do_bit;
9054     case M_XOR_I:
9055       s = "xori";
9056       s2 = "xor";
9057     do_bit:
9058       if (imm_expr.X_op == O_constant
9059           && imm_expr.X_add_number >= 0
9060           && imm_expr.X_add_number < 0x10000)
9061         {
9062           if (mask != M_NOR_I)
9063             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9064           else
9065             {
9066               macro_build (&imm_expr, "ori", "t,r,i",
9067                            op[0], op[1], BFD_RELOC_LO16);
9068               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9069             }
9070           break;
9071         }
9072
9073       used_at = 1;
9074       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9075       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9076       break;
9077
9078     case M_BALIGN:
9079       switch (imm_expr.X_add_number)
9080         {
9081         case 0:
9082           macro_build (NULL, "nop", "");
9083           break;
9084         case 2:
9085           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9086           break;
9087         case 1:
9088         case 3:
9089           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9090                        (int) imm_expr.X_add_number);
9091           break;
9092         default:
9093           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9094                   (unsigned long) imm_expr.X_add_number);
9095           break;
9096         }
9097       break;
9098
9099     case M_BC1FL:
9100     case M_BC1TL:
9101     case M_BC2FL:
9102     case M_BC2TL:
9103       gas_assert (mips_opts.micromips);
9104       macro_build_branch_ccl (mask, &offset_expr,
9105                               EXTRACT_OPERAND (1, BCC, *ip));
9106       break;
9107
9108     case M_BEQ_I:
9109     case M_BEQL_I:
9110     case M_BNE_I:
9111     case M_BNEL_I:
9112       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9113         op[1] = 0;
9114       else
9115         {
9116           op[1] = AT;
9117           used_at = 1;
9118           load_register (op[1], &imm_expr, HAVE_64BIT_GPRS);
9119         }
9120       /* Fall through.  */
9121     case M_BEQL:
9122     case M_BNEL:
9123       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9124       break;
9125
9126     case M_BGEL:
9127       likely = 1;
9128     case M_BGE:
9129       if (op[1] == 0)
9130         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9131       else if (op[0] == 0)
9132         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9133       else
9134         {
9135           used_at = 1;
9136           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9137           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9138                                    &offset_expr, AT, ZERO);
9139         }
9140       break;
9141
9142     case M_BGEZL:
9143     case M_BGEZALL:
9144     case M_BGTZL:
9145     case M_BLEZL:
9146     case M_BLTZL:
9147     case M_BLTZALL:
9148       macro_build_branch_rs (mask, &offset_expr, op[0]);
9149       break;
9150
9151     case M_BGTL_I:
9152       likely = 1;
9153     case M_BGT_I:
9154       /* Check for > max integer.  */
9155       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
9156         {
9157         do_false:
9158           /* Result is always false.  */
9159           if (! likely)
9160             macro_build (NULL, "nop", "");
9161           else
9162             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9163           break;
9164         }
9165       if (imm_expr.X_op != O_constant)
9166         as_bad (_("Unsupported large constant"));
9167       ++imm_expr.X_add_number;
9168       /* FALLTHROUGH */
9169     case M_BGE_I:
9170     case M_BGEL_I:
9171       if (mask == M_BGEL_I)
9172         likely = 1;
9173       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9174         {
9175           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9176                                  &offset_expr, op[0]);
9177           break;
9178         }
9179       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9180         {
9181           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9182                                  &offset_expr, op[0]);
9183           break;
9184         }
9185       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
9186         {
9187         do_true:
9188           /* result is always true */
9189           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
9190           macro_build (&offset_expr, "b", "p");
9191           break;
9192         }
9193       used_at = 1;
9194       set_at (op[0], 0);
9195       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9196                                &offset_expr, AT, ZERO);
9197       break;
9198
9199     case M_BGEUL:
9200       likely = 1;
9201     case M_BGEU:
9202       if (op[1] == 0)
9203         goto do_true;
9204       else if (op[0] == 0)
9205         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9206                                  &offset_expr, ZERO, op[1]);
9207       else
9208         {
9209           used_at = 1;
9210           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9211           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9212                                    &offset_expr, AT, ZERO);
9213         }
9214       break;
9215
9216     case M_BGTUL_I:
9217       likely = 1;
9218     case M_BGTU_I:
9219       if (op[0] == 0
9220           || (HAVE_32BIT_GPRS
9221               && imm_expr.X_op == O_constant
9222               && imm_expr.X_add_number == -1))
9223         goto do_false;
9224       if (imm_expr.X_op != O_constant)
9225         as_bad (_("Unsupported large constant"));
9226       ++imm_expr.X_add_number;
9227       /* FALLTHROUGH */
9228     case M_BGEU_I:
9229     case M_BGEUL_I:
9230       if (mask == M_BGEUL_I)
9231         likely = 1;
9232       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9233         goto do_true;
9234       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9235         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9236                                  &offset_expr, op[0], ZERO);
9237       else
9238         {
9239           used_at = 1;
9240           set_at (op[0], 1);
9241           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9242                                    &offset_expr, AT, ZERO);
9243         }
9244       break;
9245
9246     case M_BGTL:
9247       likely = 1;
9248     case M_BGT:
9249       if (op[1] == 0)
9250         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9251       else if (op[0] == 0)
9252         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9253       else
9254         {
9255           used_at = 1;
9256           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9257           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9258                                    &offset_expr, AT, ZERO);
9259         }
9260       break;
9261
9262     case M_BGTUL:
9263       likely = 1;
9264     case M_BGTU:
9265       if (op[1] == 0)
9266         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9267                                  &offset_expr, op[0], ZERO);
9268       else if (op[0] == 0)
9269         goto do_false;
9270       else
9271         {
9272           used_at = 1;
9273           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9274           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9275                                    &offset_expr, AT, ZERO);
9276         }
9277       break;
9278
9279     case M_BLEL:
9280       likely = 1;
9281     case M_BLE:
9282       if (op[1] == 0)
9283         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9284       else if (op[0] == 0)
9285         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9286       else
9287         {
9288           used_at = 1;
9289           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9290           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9291                                    &offset_expr, AT, ZERO);
9292         }
9293       break;
9294
9295     case M_BLEL_I:
9296       likely = 1;
9297     case M_BLE_I:
9298       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
9299         goto do_true;
9300       if (imm_expr.X_op != O_constant)
9301         as_bad (_("Unsupported large constant"));
9302       ++imm_expr.X_add_number;
9303       /* FALLTHROUGH */
9304     case M_BLT_I:
9305     case M_BLTL_I:
9306       if (mask == M_BLTL_I)
9307         likely = 1;
9308       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9309         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9310       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9311         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9312       else
9313         {
9314           used_at = 1;
9315           set_at (op[0], 0);
9316           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9317                                    &offset_expr, AT, ZERO);
9318         }
9319       break;
9320
9321     case M_BLEUL:
9322       likely = 1;
9323     case M_BLEU:
9324       if (op[1] == 0)
9325         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9326                                  &offset_expr, op[0], ZERO);
9327       else if (op[0] == 0)
9328         goto do_true;
9329       else
9330         {
9331           used_at = 1;
9332           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9333           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9334                                    &offset_expr, AT, ZERO);
9335         }
9336       break;
9337
9338     case M_BLEUL_I:
9339       likely = 1;
9340     case M_BLEU_I:
9341       if (op[0] == 0
9342           || (HAVE_32BIT_GPRS
9343               && imm_expr.X_op == O_constant
9344               && imm_expr.X_add_number == -1))
9345         goto do_true;
9346       if (imm_expr.X_op != O_constant)
9347         as_bad (_("Unsupported large constant"));
9348       ++imm_expr.X_add_number;
9349       /* FALLTHROUGH */
9350     case M_BLTU_I:
9351     case M_BLTUL_I:
9352       if (mask == M_BLTUL_I)
9353         likely = 1;
9354       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9355         goto do_false;
9356       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9357         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9358                                  &offset_expr, op[0], ZERO);
9359       else
9360         {
9361           used_at = 1;
9362           set_at (op[0], 1);
9363           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9364                                    &offset_expr, AT, ZERO);
9365         }
9366       break;
9367
9368     case M_BLTL:
9369       likely = 1;
9370     case M_BLT:
9371       if (op[1] == 0)
9372         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9373       else if (op[0] == 0)
9374         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9375       else
9376         {
9377           used_at = 1;
9378           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9379           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9380                                    &offset_expr, AT, ZERO);
9381         }
9382       break;
9383
9384     case M_BLTUL:
9385       likely = 1;
9386     case M_BLTU:
9387       if (op[1] == 0)
9388         goto do_false;
9389       else if (op[0] == 0)
9390         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9391                                  &offset_expr, ZERO, op[1]);
9392       else
9393         {
9394           used_at = 1;
9395           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9396           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9397                                    &offset_expr, AT, ZERO);
9398         }
9399       break;
9400
9401     case M_DEXT:
9402       {
9403         /* Use unsigned arithmetic.  */
9404         addressT pos;
9405         addressT size;
9406
9407         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
9408           {
9409             as_bad (_("Unsupported large constant"));
9410             pos = size = 1;
9411           }
9412         else
9413           {
9414             pos = imm_expr.X_add_number;
9415             size = imm2_expr.X_add_number;
9416           }
9417
9418         if (pos > 63)
9419           {
9420             report_bad_range (ip, 3, pos, 0, 63, FALSE);
9421             pos = 1;
9422           }
9423         if (size == 0 || size > 64 || (pos + size - 1) > 63)
9424           {
9425             report_bad_field (pos, size);
9426             size = 1;
9427           }
9428
9429         if (size <= 32 && pos < 32)
9430           {
9431             s = "dext";
9432             fmt = "t,r,+A,+C";
9433           }
9434         else if (size <= 32)
9435           {
9436             s = "dextu";
9437             fmt = "t,r,+E,+H";
9438           }
9439         else
9440           {
9441             s = "dextm";
9442             fmt = "t,r,+A,+G";
9443           }
9444         macro_build ((expressionS *) NULL, s, fmt, op[0], op[1], (int) pos,
9445                      (int) (size - 1));
9446       }
9447       break;
9448
9449     case M_DINS:
9450       {
9451         /* Use unsigned arithmetic.  */
9452         addressT pos;
9453         addressT size;
9454
9455         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
9456           {
9457             as_bad (_("Unsupported large constant"));
9458             pos = size = 1;
9459           }
9460         else
9461           {
9462             pos = imm_expr.X_add_number;
9463             size = imm2_expr.X_add_number;
9464           }
9465
9466         if (pos > 63)
9467           {
9468             report_bad_range (ip, 3, pos, 0, 63, FALSE);
9469             pos = 1;
9470           }
9471         if (size == 0 || size > 64 || (pos + size - 1) > 63)
9472           {
9473             report_bad_field (pos, size);
9474             size = 1;
9475           }
9476
9477         if (pos < 32 && (pos + size - 1) < 32)
9478           {
9479             s = "dins";
9480             fmt = "t,r,+A,+B";
9481           }
9482         else if (pos >= 32)
9483           {
9484             s = "dinsu";
9485             fmt = "t,r,+E,+F";
9486           }
9487         else
9488           {
9489             s = "dinsm";
9490             fmt = "t,r,+A,+F";
9491           }
9492         macro_build ((expressionS *) NULL, s, fmt, op[0], op[1], (int) pos,
9493                      (int) (pos + size - 1));
9494       }
9495       break;
9496
9497     case M_DDIV_3:
9498       dbl = 1;
9499     case M_DIV_3:
9500       s = "mflo";
9501       goto do_div3;
9502     case M_DREM_3:
9503       dbl = 1;
9504     case M_REM_3:
9505       s = "mfhi";
9506     do_div3:
9507       if (op[2] == 0)
9508         {
9509           as_warn (_("Divide by zero."));
9510           if (mips_trap)
9511             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9512           else
9513             macro_build (NULL, "break", BRK_FMT, 7);
9514           break;
9515         }
9516
9517       start_noreorder ();
9518       if (mips_trap)
9519         {
9520           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9521           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9522         }
9523       else
9524         {
9525           if (mips_opts.micromips)
9526             micromips_label_expr (&label_expr);
9527           else
9528             label_expr.X_add_number = 8;
9529           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9530           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9531           macro_build (NULL, "break", BRK_FMT, 7);
9532           if (mips_opts.micromips)
9533             micromips_add_label ();
9534         }
9535       expr1.X_add_number = -1;
9536       used_at = 1;
9537       load_register (AT, &expr1, dbl);
9538       if (mips_opts.micromips)
9539         micromips_label_expr (&label_expr);
9540       else
9541         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9542       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9543       if (dbl)
9544         {
9545           expr1.X_add_number = 1;
9546           load_register (AT, &expr1, dbl);
9547           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9548         }
9549       else
9550         {
9551           expr1.X_add_number = 0x80000000;
9552           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9553         }
9554       if (mips_trap)
9555         {
9556           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9557           /* We want to close the noreorder block as soon as possible, so
9558              that later insns are available for delay slot filling.  */
9559           end_noreorder ();
9560         }
9561       else
9562         {
9563           if (mips_opts.micromips)
9564             micromips_label_expr (&label_expr);
9565           else
9566             label_expr.X_add_number = 8;
9567           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9568           macro_build (NULL, "nop", "");
9569
9570           /* We want to close the noreorder block as soon as possible, so
9571              that later insns are available for delay slot filling.  */
9572           end_noreorder ();
9573
9574           macro_build (NULL, "break", BRK_FMT, 6);
9575         }
9576       if (mips_opts.micromips)
9577         micromips_add_label ();
9578       macro_build (NULL, s, MFHL_FMT, op[0]);
9579       break;
9580
9581     case M_DIV_3I:
9582       s = "div";
9583       s2 = "mflo";
9584       goto do_divi;
9585     case M_DIVU_3I:
9586       s = "divu";
9587       s2 = "mflo";
9588       goto do_divi;
9589     case M_REM_3I:
9590       s = "div";
9591       s2 = "mfhi";
9592       goto do_divi;
9593     case M_REMU_3I:
9594       s = "divu";
9595       s2 = "mfhi";
9596       goto do_divi;
9597     case M_DDIV_3I:
9598       dbl = 1;
9599       s = "ddiv";
9600       s2 = "mflo";
9601       goto do_divi;
9602     case M_DDIVU_3I:
9603       dbl = 1;
9604       s = "ddivu";
9605       s2 = "mflo";
9606       goto do_divi;
9607     case M_DREM_3I:
9608       dbl = 1;
9609       s = "ddiv";
9610       s2 = "mfhi";
9611       goto do_divi;
9612     case M_DREMU_3I:
9613       dbl = 1;
9614       s = "ddivu";
9615       s2 = "mfhi";
9616     do_divi:
9617       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9618         {
9619           as_warn (_("Divide by zero."));
9620           if (mips_trap)
9621             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9622           else
9623             macro_build (NULL, "break", BRK_FMT, 7);
9624           break;
9625         }
9626       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9627         {
9628           if (strcmp (s2, "mflo") == 0)
9629             move_register (op[0], op[1]);
9630           else
9631             move_register (op[0], ZERO);
9632           break;
9633         }
9634       if (imm_expr.X_op == O_constant
9635           && imm_expr.X_add_number == -1
9636           && s[strlen (s) - 1] != 'u')
9637         {
9638           if (strcmp (s2, "mflo") == 0)
9639             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9640           else
9641             move_register (op[0], ZERO);
9642           break;
9643         }
9644
9645       used_at = 1;
9646       load_register (AT, &imm_expr, dbl);
9647       macro_build (NULL, s, "z,s,t", op[1], AT);
9648       macro_build (NULL, s2, MFHL_FMT, op[0]);
9649       break;
9650
9651     case M_DIVU_3:
9652       s = "divu";
9653       s2 = "mflo";
9654       goto do_divu3;
9655     case M_REMU_3:
9656       s = "divu";
9657       s2 = "mfhi";
9658       goto do_divu3;
9659     case M_DDIVU_3:
9660       s = "ddivu";
9661       s2 = "mflo";
9662       goto do_divu3;
9663     case M_DREMU_3:
9664       s = "ddivu";
9665       s2 = "mfhi";
9666     do_divu3:
9667       start_noreorder ();
9668       if (mips_trap)
9669         {
9670           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9671           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9672           /* We want to close the noreorder block as soon as possible, so
9673              that later insns are available for delay slot filling.  */
9674           end_noreorder ();
9675         }
9676       else
9677         {
9678           if (mips_opts.micromips)
9679             micromips_label_expr (&label_expr);
9680           else
9681             label_expr.X_add_number = 8;
9682           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9683           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9684
9685           /* We want to close the noreorder block as soon as possible, so
9686              that later insns are available for delay slot filling.  */
9687           end_noreorder ();
9688           macro_build (NULL, "break", BRK_FMT, 7);
9689           if (mips_opts.micromips)
9690             micromips_add_label ();
9691         }
9692       macro_build (NULL, s2, MFHL_FMT, op[0]);
9693       break;
9694
9695     case M_DLCA_AB:
9696       dbl = 1;
9697     case M_LCA_AB:
9698       call = 1;
9699       goto do_la;
9700     case M_DLA_AB:
9701       dbl = 1;
9702     case M_LA_AB:
9703     do_la:
9704       /* Load the address of a symbol into a register.  If breg is not
9705          zero, we then add a base register to it.  */
9706
9707       breg = op[2];
9708       if (dbl && HAVE_32BIT_GPRS)
9709         as_warn (_("dla used to load 32-bit register"));
9710
9711       if (!dbl && HAVE_64BIT_OBJECTS)
9712         as_warn (_("la used to load 64-bit address"));
9713
9714       if (small_offset_p (0, align, 16))
9715         {
9716           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9717                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9718           break;
9719         }
9720
9721       if (mips_opts.at && (op[0] == breg))
9722         {
9723           tempreg = AT;
9724           used_at = 1;
9725         }
9726       else
9727         tempreg = op[0];
9728
9729       if (offset_expr.X_op != O_symbol
9730           && offset_expr.X_op != O_constant)
9731         {
9732           as_bad (_("Expression too complex"));
9733           offset_expr.X_op = O_constant;
9734         }
9735
9736       if (offset_expr.X_op == O_constant)
9737         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9738       else if (mips_pic == NO_PIC)
9739         {
9740           /* If this is a reference to a GP relative symbol, we want
9741                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9742              Otherwise we want
9743                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9744                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9745              If we have a constant, we need two instructions anyhow,
9746              so we may as well always use the latter form.
9747
9748              With 64bit address space and a usable $at we want
9749                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9750                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9751                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9752                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9753                dsll32   $tempreg,0
9754                daddu    $tempreg,$tempreg,$at
9755
9756              If $at is already in use, we use a path which is suboptimal
9757              on superscalar processors.
9758                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9759                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9760                dsll     $tempreg,16
9761                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9762                dsll     $tempreg,16
9763                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
9764
9765              For GP relative symbols in 64bit address space we can use
9766              the same sequence as in 32bit address space.  */
9767           if (HAVE_64BIT_SYMBOLS)
9768             {
9769               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9770                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9771                 {
9772                   relax_start (offset_expr.X_add_symbol);
9773                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9774                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9775                   relax_switch ();
9776                 }
9777
9778               if (used_at == 0 && mips_opts.at)
9779                 {
9780                   macro_build (&offset_expr, "lui", LUI_FMT,
9781                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9782                   macro_build (&offset_expr, "lui", LUI_FMT,
9783                                AT, BFD_RELOC_HI16_S);
9784                   macro_build (&offset_expr, "daddiu", "t,r,j",
9785                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9786                   macro_build (&offset_expr, "daddiu", "t,r,j",
9787                                AT, AT, BFD_RELOC_LO16);
9788                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9789                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9790                   used_at = 1;
9791                 }
9792               else
9793                 {
9794                   macro_build (&offset_expr, "lui", LUI_FMT,
9795                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9796                   macro_build (&offset_expr, "daddiu", "t,r,j",
9797                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9798                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9799                   macro_build (&offset_expr, "daddiu", "t,r,j",
9800                                tempreg, tempreg, BFD_RELOC_HI16_S);
9801                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9802                   macro_build (&offset_expr, "daddiu", "t,r,j",
9803                                tempreg, tempreg, BFD_RELOC_LO16);
9804                 }
9805
9806               if (mips_relax.sequence)
9807                 relax_end ();
9808             }
9809           else
9810             {
9811               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9812                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9813                 {
9814                   relax_start (offset_expr.X_add_symbol);
9815                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9816                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9817                   relax_switch ();
9818                 }
9819               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9820                 as_bad (_("Offset too large"));
9821               macro_build_lui (&offset_expr, tempreg);
9822               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9823                            tempreg, tempreg, BFD_RELOC_LO16);
9824               if (mips_relax.sequence)
9825                 relax_end ();
9826             }
9827         }
9828       else if (!mips_big_got && !HAVE_NEWABI)
9829         {
9830           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9831
9832           /* If this is a reference to an external symbol, and there
9833              is no constant, we want
9834                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9835              or for lca or if tempreg is PIC_CALL_REG
9836                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9837              For a local symbol, we want
9838                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9839                nop
9840                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9841
9842              If we have a small constant, and this is a reference to
9843              an external symbol, we want
9844                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9845                nop
9846                addiu    $tempreg,$tempreg,<constant>
9847              For a local symbol, we want the same instruction
9848              sequence, but we output a BFD_RELOC_LO16 reloc on the
9849              addiu instruction.
9850
9851              If we have a large constant, and this is a reference to
9852              an external symbol, we want
9853                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9854                lui      $at,<hiconstant>
9855                addiu    $at,$at,<loconstant>
9856                addu     $tempreg,$tempreg,$at
9857              For a local symbol, we want the same instruction
9858              sequence, but we output a BFD_RELOC_LO16 reloc on the
9859              addiu instruction.
9860            */
9861
9862           if (offset_expr.X_add_number == 0)
9863             {
9864               if (mips_pic == SVR4_PIC
9865                   && breg == 0
9866                   && (call || tempreg == PIC_CALL_REG))
9867                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
9868
9869               relax_start (offset_expr.X_add_symbol);
9870               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9871                            lw_reloc_type, mips_gp_register);
9872               if (breg != 0)
9873                 {
9874                   /* We're going to put in an addu instruction using
9875                      tempreg, so we may as well insert the nop right
9876                      now.  */
9877                   load_delay_nop ();
9878                 }
9879               relax_switch ();
9880               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9881                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
9882               load_delay_nop ();
9883               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9884                            tempreg, tempreg, BFD_RELOC_LO16);
9885               relax_end ();
9886               /* FIXME: If breg == 0, and the next instruction uses
9887                  $tempreg, then if this variant case is used an extra
9888                  nop will be generated.  */
9889             }
9890           else if (offset_expr.X_add_number >= -0x8000
9891                    && offset_expr.X_add_number < 0x8000)
9892             {
9893               load_got_offset (tempreg, &offset_expr);
9894               load_delay_nop ();
9895               add_got_offset (tempreg, &offset_expr);
9896             }
9897           else
9898             {
9899               expr1.X_add_number = offset_expr.X_add_number;
9900               offset_expr.X_add_number =
9901                 SEXT_16BIT (offset_expr.X_add_number);
9902               load_got_offset (tempreg, &offset_expr);
9903               offset_expr.X_add_number = expr1.X_add_number;
9904               /* If we are going to add in a base register, and the
9905                  target register and the base register are the same,
9906                  then we are using AT as a temporary register.  Since
9907                  we want to load the constant into AT, we add our
9908                  current AT (from the global offset table) and the
9909                  register into the register now, and pretend we were
9910                  not using a base register.  */
9911               if (breg == op[0])
9912                 {
9913                   load_delay_nop ();
9914                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9915                                op[0], AT, breg);
9916                   breg = 0;
9917                   tempreg = op[0];
9918                 }
9919               add_got_offset_hilo (tempreg, &offset_expr, AT);
9920               used_at = 1;
9921             }
9922         }
9923       else if (!mips_big_got && HAVE_NEWABI)
9924         {
9925           int add_breg_early = 0;
9926
9927           /* If this is a reference to an external, and there is no
9928              constant, or local symbol (*), with or without a
9929              constant, we want
9930                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9931              or for lca or if tempreg is PIC_CALL_REG
9932                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9933
9934              If we have a small constant, and this is a reference to
9935              an external symbol, we want
9936                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9937                addiu    $tempreg,$tempreg,<constant>
9938
9939              If we have a large constant, and this is a reference to
9940              an external symbol, we want
9941                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9942                lui      $at,<hiconstant>
9943                addiu    $at,$at,<loconstant>
9944                addu     $tempreg,$tempreg,$at
9945
9946              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
9947              local symbols, even though it introduces an additional
9948              instruction.  */
9949
9950           if (offset_expr.X_add_number)
9951             {
9952               expr1.X_add_number = offset_expr.X_add_number;
9953               offset_expr.X_add_number = 0;
9954
9955               relax_start (offset_expr.X_add_symbol);
9956               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9957                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9958
9959               if (expr1.X_add_number >= -0x8000
9960                   && expr1.X_add_number < 0x8000)
9961                 {
9962                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9963                                tempreg, tempreg, BFD_RELOC_LO16);
9964                 }
9965               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
9966                 {
9967                   unsigned int dreg;
9968
9969                   /* If we are going to add in a base register, and the
9970                      target register and the base register are the same,
9971                      then we are using AT as a temporary register.  Since
9972                      we want to load the constant into AT, we add our
9973                      current AT (from the global offset table) and the
9974                      register into the register now, and pretend we were
9975                      not using a base register.  */
9976                   if (breg != op[0])
9977                     dreg = tempreg;
9978                   else
9979                     {
9980                       gas_assert (tempreg == AT);
9981                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9982                                    op[0], AT, breg);
9983                       dreg = op[0];
9984                       add_breg_early = 1;
9985                     }
9986
9987                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9988                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9989                                dreg, dreg, AT);
9990
9991                   used_at = 1;
9992                 }
9993               else
9994                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
9995
9996               relax_switch ();
9997               offset_expr.X_add_number = expr1.X_add_number;
9998
9999               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10000                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10001               if (add_breg_early)
10002                 {
10003                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10004                                op[0], tempreg, breg);
10005                   breg = 0;
10006                   tempreg = op[0];
10007                 }
10008               relax_end ();
10009             }
10010           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10011             {
10012               relax_start (offset_expr.X_add_symbol);
10013               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10014                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10015               relax_switch ();
10016               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10017                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10018               relax_end ();
10019             }
10020           else
10021             {
10022               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10023                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10024             }
10025         }
10026       else if (mips_big_got && !HAVE_NEWABI)
10027         {
10028           int gpdelay;
10029           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10030           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10031           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10032
10033           /* This is the large GOT case.  If this is a reference to an
10034              external symbol, and there is no constant, we want
10035                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10036                addu     $tempreg,$tempreg,$gp
10037                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10038              or for lca or if tempreg is PIC_CALL_REG
10039                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10040                addu     $tempreg,$tempreg,$gp
10041                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10042              For a local symbol, we want
10043                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10044                nop
10045                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10046
10047              If we have a small constant, and this is a reference to
10048              an external symbol, we want
10049                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10050                addu     $tempreg,$tempreg,$gp
10051                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10052                nop
10053                addiu    $tempreg,$tempreg,<constant>
10054              For a local symbol, we want
10055                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10056                nop
10057                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10058
10059              If we have a large constant, and this is a reference to
10060              an external symbol, we want
10061                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10062                addu     $tempreg,$tempreg,$gp
10063                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10064                lui      $at,<hiconstant>
10065                addiu    $at,$at,<loconstant>
10066                addu     $tempreg,$tempreg,$at
10067              For a local symbol, we want
10068                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10069                lui      $at,<hiconstant>
10070                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10071                addu     $tempreg,$tempreg,$at
10072           */
10073
10074           expr1.X_add_number = offset_expr.X_add_number;
10075           offset_expr.X_add_number = 0;
10076           relax_start (offset_expr.X_add_symbol);
10077           gpdelay = reg_needs_delay (mips_gp_register);
10078           if (expr1.X_add_number == 0 && breg == 0
10079               && (call || tempreg == PIC_CALL_REG))
10080             {
10081               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10082               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10083             }
10084           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10085           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10086                        tempreg, tempreg, mips_gp_register);
10087           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10088                        tempreg, lw_reloc_type, tempreg);
10089           if (expr1.X_add_number == 0)
10090             {
10091               if (breg != 0)
10092                 {
10093                   /* We're going to put in an addu instruction using
10094                      tempreg, so we may as well insert the nop right
10095                      now.  */
10096                   load_delay_nop ();
10097                 }
10098             }
10099           else if (expr1.X_add_number >= -0x8000
10100                    && expr1.X_add_number < 0x8000)
10101             {
10102               load_delay_nop ();
10103               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10104                            tempreg, tempreg, BFD_RELOC_LO16);
10105             }
10106           else
10107             {
10108               unsigned int dreg;
10109
10110               /* If we are going to add in a base register, and the
10111                  target register and the base register are the same,
10112                  then we are using AT as a temporary register.  Since
10113                  we want to load the constant into AT, we add our
10114                  current AT (from the global offset table) and the
10115                  register into the register now, and pretend we were
10116                  not using a base register.  */
10117               if (breg != op[0])
10118                 dreg = tempreg;
10119               else
10120                 {
10121                   gas_assert (tempreg == AT);
10122                   load_delay_nop ();
10123                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10124                                op[0], AT, breg);
10125                   dreg = op[0];
10126                 }
10127
10128               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10129               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10130
10131               used_at = 1;
10132             }
10133           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10134           relax_switch ();
10135
10136           if (gpdelay)
10137             {
10138               /* This is needed because this instruction uses $gp, but
10139                  the first instruction on the main stream does not.  */
10140               macro_build (NULL, "nop", "");
10141             }
10142
10143           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10144                        local_reloc_type, mips_gp_register);
10145           if (expr1.X_add_number >= -0x8000
10146               && expr1.X_add_number < 0x8000)
10147             {
10148               load_delay_nop ();
10149               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10150                            tempreg, tempreg, BFD_RELOC_LO16);
10151               /* FIXME: If add_number is 0, and there was no base
10152                  register, the external symbol case ended with a load,
10153                  so if the symbol turns out to not be external, and
10154                  the next instruction uses tempreg, an unnecessary nop
10155                  will be inserted.  */
10156             }
10157           else
10158             {
10159               if (breg == op[0])
10160                 {
10161                   /* We must add in the base register now, as in the
10162                      external symbol case.  */
10163                   gas_assert (tempreg == AT);
10164                   load_delay_nop ();
10165                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10166                                op[0], AT, breg);
10167                   tempreg = op[0];
10168                   /* We set breg to 0 because we have arranged to add
10169                      it in in both cases.  */
10170                   breg = 0;
10171                 }
10172
10173               macro_build_lui (&expr1, AT);
10174               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10175                            AT, AT, BFD_RELOC_LO16);
10176               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10177                            tempreg, tempreg, AT);
10178               used_at = 1;
10179             }
10180           relax_end ();
10181         }
10182       else if (mips_big_got && HAVE_NEWABI)
10183         {
10184           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10185           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10186           int add_breg_early = 0;
10187
10188           /* This is the large GOT case.  If this is a reference to an
10189              external symbol, and there is no constant, we want
10190                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10191                add      $tempreg,$tempreg,$gp
10192                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10193              or for lca or if tempreg is PIC_CALL_REG
10194                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10195                add      $tempreg,$tempreg,$gp
10196                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10197
10198              If we have a small constant, and this is a reference to
10199              an external symbol, we want
10200                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10201                add      $tempreg,$tempreg,$gp
10202                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10203                addi     $tempreg,$tempreg,<constant>
10204
10205              If we have a large constant, and this is a reference to
10206              an external symbol, we want
10207                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10208                addu     $tempreg,$tempreg,$gp
10209                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10210                lui      $at,<hiconstant>
10211                addi     $at,$at,<loconstant>
10212                add      $tempreg,$tempreg,$at
10213
10214              If we have NewABI, and we know it's a local symbol, we want
10215                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10216                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10217              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10218
10219           relax_start (offset_expr.X_add_symbol);
10220
10221           expr1.X_add_number = offset_expr.X_add_number;
10222           offset_expr.X_add_number = 0;
10223
10224           if (expr1.X_add_number == 0 && breg == 0
10225               && (call || tempreg == PIC_CALL_REG))
10226             {
10227               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10228               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10229             }
10230           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10231           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10232                        tempreg, tempreg, mips_gp_register);
10233           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10234                        tempreg, lw_reloc_type, tempreg);
10235
10236           if (expr1.X_add_number == 0)
10237             ;
10238           else if (expr1.X_add_number >= -0x8000
10239                    && expr1.X_add_number < 0x8000)
10240             {
10241               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10242                            tempreg, tempreg, BFD_RELOC_LO16);
10243             }
10244           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10245             {
10246               unsigned int dreg;
10247
10248               /* If we are going to add in a base register, and the
10249                  target register and the base register are the same,
10250                  then we are using AT as a temporary register.  Since
10251                  we want to load the constant into AT, we add our
10252                  current AT (from the global offset table) and the
10253                  register into the register now, and pretend we were
10254                  not using a base register.  */
10255               if (breg != op[0])
10256                 dreg = tempreg;
10257               else
10258                 {
10259                   gas_assert (tempreg == AT);
10260                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10261                                op[0], AT, breg);
10262                   dreg = op[0];
10263                   add_breg_early = 1;
10264                 }
10265
10266               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10267               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10268
10269               used_at = 1;
10270             }
10271           else
10272             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10273
10274           relax_switch ();
10275           offset_expr.X_add_number = expr1.X_add_number;
10276           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10277                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10278           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10279                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10280           if (add_breg_early)
10281             {
10282               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10283                            op[0], tempreg, breg);
10284               breg = 0;
10285               tempreg = op[0];
10286             }
10287           relax_end ();
10288         }
10289       else
10290         abort ();
10291
10292       if (breg != 0)
10293         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10294       break;
10295
10296     case M_MSGSND:
10297       gas_assert (!mips_opts.micromips);
10298       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10299       break;
10300
10301     case M_MSGLD:
10302       gas_assert (!mips_opts.micromips);
10303       macro_build (NULL, "c2", "C", 0x02);
10304       break;
10305
10306     case M_MSGLD_T:
10307       gas_assert (!mips_opts.micromips);
10308       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10309       break;
10310
10311     case M_MSGWAIT:
10312       gas_assert (!mips_opts.micromips);
10313       macro_build (NULL, "c2", "C", 3);
10314       break;
10315
10316     case M_MSGWAIT_T:
10317       gas_assert (!mips_opts.micromips);
10318       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10319       break;
10320
10321     case M_J_A:
10322       /* The j instruction may not be used in PIC code, since it
10323          requires an absolute address.  We convert it to a b
10324          instruction.  */
10325       if (mips_pic == NO_PIC)
10326         macro_build (&offset_expr, "j", "a");
10327       else
10328         macro_build (&offset_expr, "b", "p");
10329       break;
10330
10331       /* The jal instructions must be handled as macros because when
10332          generating PIC code they expand to multi-instruction
10333          sequences.  Normally they are simple instructions.  */
10334     case M_JALS_1:
10335       op[1] = op[0];
10336       op[0] = RA;
10337       /* Fall through.  */
10338     case M_JALS_2:
10339       gas_assert (mips_opts.micromips);
10340       if (mips_opts.insn32)
10341         {
10342           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
10343           break;
10344         }
10345       jals = 1;
10346       goto jal;
10347     case M_JAL_1:
10348       op[1] = op[0];
10349       op[0] = RA;
10350       /* Fall through.  */
10351     case M_JAL_2:
10352     jal:
10353       if (mips_pic == NO_PIC)
10354         {
10355           s = jals ? "jalrs" : "jalr";
10356           if (mips_opts.micromips
10357               && !mips_opts.insn32
10358               && op[0] == RA
10359               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10360             macro_build (NULL, s, "mj", op[1]);
10361           else
10362             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10363         }
10364       else
10365         {
10366           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10367                            && mips_cprestore_offset >= 0);
10368
10369           if (op[1] != PIC_CALL_REG)
10370             as_warn (_("MIPS PIC call to register other than $25"));
10371
10372           s = ((mips_opts.micromips
10373                 && !mips_opts.insn32
10374                 && (!mips_opts.noreorder || cprestore))
10375                ? "jalrs" : "jalr");
10376           if (mips_opts.micromips
10377               && !mips_opts.insn32
10378               && op[0] == RA
10379               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10380             macro_build (NULL, s, "mj", op[1]);
10381           else
10382             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10383           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10384             {
10385               if (mips_cprestore_offset < 0)
10386                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
10387               else
10388                 {
10389                   if (!mips_frame_reg_valid)
10390                     {
10391                       as_warn (_("No .frame pseudo-op used in PIC code"));
10392                       /* Quiet this warning.  */
10393                       mips_frame_reg_valid = 1;
10394                     }
10395                   if (!mips_cprestore_valid)
10396                     {
10397                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
10398                       /* Quiet this warning.  */
10399                       mips_cprestore_valid = 1;
10400                     }
10401                   if (mips_opts.noreorder)
10402                     macro_build (NULL, "nop", "");
10403                   expr1.X_add_number = mips_cprestore_offset;
10404                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10405                                                 mips_gp_register,
10406                                                 mips_frame_reg,
10407                                                 HAVE_64BIT_ADDRESSES);
10408                 }
10409             }
10410         }
10411
10412       break;
10413
10414     case M_JALS_A:
10415       gas_assert (mips_opts.micromips);
10416       if (mips_opts.insn32)
10417         {
10418           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
10419           break;
10420         }
10421       jals = 1;
10422       /* Fall through.  */
10423     case M_JAL_A:
10424       if (mips_pic == NO_PIC)
10425         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10426       else if (mips_pic == SVR4_PIC)
10427         {
10428           /* If this is a reference to an external symbol, and we are
10429              using a small GOT, we want
10430                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10431                nop
10432                jalr     $ra,$25
10433                nop
10434                lw       $gp,cprestore($sp)
10435              The cprestore value is set using the .cprestore
10436              pseudo-op.  If we are using a big GOT, we want
10437                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10438                addu     $25,$25,$gp
10439                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10440                nop
10441                jalr     $ra,$25
10442                nop
10443                lw       $gp,cprestore($sp)
10444              If the symbol is not external, we want
10445                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10446                nop
10447                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10448                jalr     $ra,$25
10449                nop
10450                lw $gp,cprestore($sp)
10451
10452              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10453              sequences above, minus nops, unless the symbol is local,
10454              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10455              GOT_DISP.  */
10456           if (HAVE_NEWABI)
10457             {
10458               if (!mips_big_got)
10459                 {
10460                   relax_start (offset_expr.X_add_symbol);
10461                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10462                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10463                                mips_gp_register);
10464                   relax_switch ();
10465                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10466                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10467                                mips_gp_register);
10468                   relax_end ();
10469                 }
10470               else
10471                 {
10472                   relax_start (offset_expr.X_add_symbol);
10473                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10474                                BFD_RELOC_MIPS_CALL_HI16);
10475                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10476                                PIC_CALL_REG, mips_gp_register);
10477                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10478                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10479                                PIC_CALL_REG);
10480                   relax_switch ();
10481                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10482                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10483                                mips_gp_register);
10484                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10485                                PIC_CALL_REG, PIC_CALL_REG,
10486                                BFD_RELOC_MIPS_GOT_OFST);
10487                   relax_end ();
10488                 }
10489
10490               macro_build_jalr (&offset_expr, 0);
10491             }
10492           else
10493             {
10494               relax_start (offset_expr.X_add_symbol);
10495               if (!mips_big_got)
10496                 {
10497                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10498                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10499                                mips_gp_register);
10500                   load_delay_nop ();
10501                   relax_switch ();
10502                 }
10503               else
10504                 {
10505                   int gpdelay;
10506
10507                   gpdelay = reg_needs_delay (mips_gp_register);
10508                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10509                                BFD_RELOC_MIPS_CALL_HI16);
10510                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10511                                PIC_CALL_REG, mips_gp_register);
10512                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10513                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10514                                PIC_CALL_REG);
10515                   load_delay_nop ();
10516                   relax_switch ();
10517                   if (gpdelay)
10518                     macro_build (NULL, "nop", "");
10519                 }
10520               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10521                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10522                            mips_gp_register);
10523               load_delay_nop ();
10524               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10525                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10526               relax_end ();
10527               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10528
10529               if (mips_cprestore_offset < 0)
10530                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
10531               else
10532                 {
10533                   if (!mips_frame_reg_valid)
10534                     {
10535                       as_warn (_("No .frame pseudo-op used in PIC code"));
10536                       /* Quiet this warning.  */
10537                       mips_frame_reg_valid = 1;
10538                     }
10539                   if (!mips_cprestore_valid)
10540                     {
10541                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
10542                       /* Quiet this warning.  */
10543                       mips_cprestore_valid = 1;
10544                     }
10545                   if (mips_opts.noreorder)
10546                     macro_build (NULL, "nop", "");
10547                   expr1.X_add_number = mips_cprestore_offset;
10548                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10549                                                 mips_gp_register,
10550                                                 mips_frame_reg,
10551                                                 HAVE_64BIT_ADDRESSES);
10552                 }
10553             }
10554         }
10555       else if (mips_pic == VXWORKS_PIC)
10556         as_bad (_("Non-PIC jump used in PIC library"));
10557       else
10558         abort ();
10559
10560       break;
10561
10562     case M_LBUE_AB:
10563       s = "lbue";
10564       fmt = "t,+j(b)";
10565       offbits = 9;
10566       goto ld_st;
10567     case M_LHUE_AB:
10568       s = "lhue";
10569       fmt = "t,+j(b)";
10570       offbits = 9;
10571       goto ld_st;
10572     case M_LBE_AB:
10573       s = "lbe";
10574       fmt = "t,+j(b)";
10575       offbits = 9;
10576       goto ld_st;
10577     case M_LHE_AB:
10578       s = "lhe";
10579       fmt = "t,+j(b)";
10580       offbits = 9;
10581       goto ld_st;
10582     case M_LLE_AB:
10583       s = "lle";
10584       fmt = "t,+j(b)";
10585       offbits = 9;
10586       goto ld_st;
10587     case M_LWE_AB:
10588       s = "lwe";
10589       fmt = "t,+j(b)";
10590       offbits = 9;
10591       goto ld_st;
10592     case M_LWLE_AB:
10593       s = "lwle";
10594       fmt = "t,+j(b)";
10595       offbits = 9;
10596       goto ld_st;
10597     case M_LWRE_AB:
10598       s = "lwre";
10599       fmt = "t,+j(b)";
10600       offbits = 9;
10601       goto ld_st;
10602     case M_SBE_AB:
10603       s = "sbe";
10604       fmt = "t,+j(b)";
10605       offbits = 9;
10606       goto ld_st;
10607     case M_SCE_AB:
10608       s = "sce";
10609       fmt = "t,+j(b)";
10610       offbits = 9;
10611       goto ld_st;
10612     case M_SHE_AB:
10613       s = "she";
10614       fmt = "t,+j(b)";
10615       offbits = 9;
10616       goto ld_st;
10617     case M_SWE_AB:
10618       s = "swe";
10619       fmt = "t,+j(b)";
10620       offbits = 9;
10621       goto ld_st;
10622     case M_SWLE_AB:
10623       s = "swle";
10624       fmt = "t,+j(b)";
10625       offbits = 9;
10626       goto ld_st;
10627     case M_SWRE_AB:
10628       s = "swre";
10629       fmt = "t,+j(b)";
10630       offbits = 9;
10631       goto ld_st;
10632     case M_ACLR_AB:
10633       s = "aclr";
10634       fmt = "\\,~(b)";
10635       offbits = 12;
10636       goto ld_st;
10637     case M_ASET_AB:
10638       s = "aset";
10639       fmt = "\\,~(b)";
10640       offbits = 12;
10641       goto ld_st;
10642     case M_LB_AB:
10643       s = "lb";
10644       fmt = "t,o(b)";
10645       goto ld;
10646     case M_LBU_AB:
10647       s = "lbu";
10648       fmt = "t,o(b)";
10649       goto ld;
10650     case M_LH_AB:
10651       s = "lh";
10652       fmt = "t,o(b)";
10653       goto ld;
10654     case M_LHU_AB:
10655       s = "lhu";
10656       fmt = "t,o(b)";
10657       goto ld;
10658     case M_LW_AB:
10659       s = "lw";
10660       fmt = "t,o(b)";
10661       goto ld;
10662     case M_LWC0_AB:
10663       gas_assert (!mips_opts.micromips);
10664       s = "lwc0";
10665       fmt = "E,o(b)";
10666       /* Itbl support may require additional care here.  */
10667       coproc = 1;
10668       goto ld_st;
10669     case M_LWC1_AB:
10670       s = "lwc1";
10671       fmt = "T,o(b)";
10672       /* Itbl support may require additional care here.  */
10673       coproc = 1;
10674       goto ld_st;
10675     case M_LWC2_AB:
10676       s = "lwc2";
10677       fmt = COP12_FMT;
10678       offbits = (mips_opts.micromips ? 12 : 16);
10679       /* Itbl support may require additional care here.  */
10680       coproc = 1;
10681       goto ld_st;
10682     case M_LWC3_AB:
10683       gas_assert (!mips_opts.micromips);
10684       s = "lwc3";
10685       fmt = "E,o(b)";
10686       /* Itbl support may require additional care here.  */
10687       coproc = 1;
10688       goto ld_st;
10689     case M_LWL_AB:
10690       s = "lwl";
10691       fmt = MEM12_FMT;
10692       offbits = (mips_opts.micromips ? 12 : 16);
10693       goto ld_st;
10694     case M_LWR_AB:
10695       s = "lwr";
10696       fmt = MEM12_FMT;
10697       offbits = (mips_opts.micromips ? 12 : 16);
10698       goto ld_st;
10699     case M_LDC1_AB:
10700       s = "ldc1";
10701       fmt = "T,o(b)";
10702       /* Itbl support may require additional care here.  */
10703       coproc = 1;
10704       goto ld_st;
10705     case M_LDC2_AB:
10706       s = "ldc2";
10707       fmt = COP12_FMT;
10708       offbits = (mips_opts.micromips ? 12 : 16);
10709       /* Itbl support may require additional care here.  */
10710       coproc = 1;
10711       goto ld_st;
10712     case M_LQC2_AB:
10713       s = "lqc2";
10714       fmt = "+7,o(b)";
10715       /* Itbl support may require additional care here.  */
10716       coproc = 1;
10717       goto ld_st;
10718     case M_LDC3_AB:
10719       s = "ldc3";
10720       fmt = "E,o(b)";
10721       /* Itbl support may require additional care here.  */
10722       coproc = 1;
10723       goto ld_st;
10724     case M_LDL_AB:
10725       s = "ldl";
10726       fmt = MEM12_FMT;
10727       offbits = (mips_opts.micromips ? 12 : 16);
10728       goto ld_st;
10729     case M_LDR_AB:
10730       s = "ldr";
10731       fmt = MEM12_FMT;
10732       offbits = (mips_opts.micromips ? 12 : 16);
10733       goto ld_st;
10734     case M_LL_AB:
10735       s = "ll";
10736       fmt = MEM12_FMT;
10737       offbits = (mips_opts.micromips ? 12 : 16);
10738       goto ld;
10739     case M_LLD_AB:
10740       s = "lld";
10741       fmt = MEM12_FMT;
10742       offbits = (mips_opts.micromips ? 12 : 16);
10743       goto ld;
10744     case M_LWU_AB:
10745       s = "lwu";
10746       fmt = MEM12_FMT;
10747       offbits = (mips_opts.micromips ? 12 : 16);
10748       goto ld;
10749     case M_LWP_AB:
10750       gas_assert (mips_opts.micromips);
10751       s = "lwp";
10752       fmt = "t,~(b)";
10753       offbits = 12;
10754       lp = 1;
10755       goto ld;
10756     case M_LDP_AB:
10757       gas_assert (mips_opts.micromips);
10758       s = "ldp";
10759       fmt = "t,~(b)";
10760       offbits = 12;
10761       lp = 1;
10762       goto ld;
10763     case M_LWM_AB:
10764       gas_assert (mips_opts.micromips);
10765       s = "lwm";
10766       fmt = "n,~(b)";
10767       offbits = 12;
10768       goto ld_st;
10769     case M_LDM_AB:
10770       gas_assert (mips_opts.micromips);
10771       s = "ldm";
10772       fmt = "n,~(b)";
10773       offbits = 12;
10774       goto ld_st;
10775
10776     ld:
10777       /* We don't want to use $0 as tempreg.  */
10778       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
10779         goto ld_st;
10780       else
10781         tempreg = op[0] + lp;
10782       goto ld_noat;
10783
10784     case M_SB_AB:
10785       s = "sb";
10786       fmt = "t,o(b)";
10787       goto ld_st;
10788     case M_SH_AB:
10789       s = "sh";
10790       fmt = "t,o(b)";
10791       goto ld_st;
10792     case M_SW_AB:
10793       s = "sw";
10794       fmt = "t,o(b)";
10795       goto ld_st;
10796     case M_SWC0_AB:
10797       gas_assert (!mips_opts.micromips);
10798       s = "swc0";
10799       fmt = "E,o(b)";
10800       /* Itbl support may require additional care here.  */
10801       coproc = 1;
10802       goto ld_st;
10803     case M_SWC1_AB:
10804       s = "swc1";
10805       fmt = "T,o(b)";
10806       /* Itbl support may require additional care here.  */
10807       coproc = 1;
10808       goto ld_st;
10809     case M_SWC2_AB:
10810       s = "swc2";
10811       fmt = COP12_FMT;
10812       offbits = (mips_opts.micromips ? 12 : 16);
10813       /* Itbl support may require additional care here.  */
10814       coproc = 1;
10815       goto ld_st;
10816     case M_SWC3_AB:
10817       gas_assert (!mips_opts.micromips);
10818       s = "swc3";
10819       fmt = "E,o(b)";
10820       /* Itbl support may require additional care here.  */
10821       coproc = 1;
10822       goto ld_st;
10823     case M_SWL_AB:
10824       s = "swl";
10825       fmt = MEM12_FMT;
10826       offbits = (mips_opts.micromips ? 12 : 16);
10827       goto ld_st;
10828     case M_SWR_AB:
10829       s = "swr";
10830       fmt = MEM12_FMT;
10831       offbits = (mips_opts.micromips ? 12 : 16);
10832       goto ld_st;
10833     case M_SC_AB:
10834       s = "sc";
10835       fmt = MEM12_FMT;
10836       offbits = (mips_opts.micromips ? 12 : 16);
10837       goto ld_st;
10838     case M_SCD_AB:
10839       s = "scd";
10840       fmt = MEM12_FMT;
10841       offbits = (mips_opts.micromips ? 12 : 16);
10842       goto ld_st;
10843     case M_CACHE_AB:
10844       s = "cache";
10845       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
10846       offbits = (mips_opts.micromips ? 12 : 16);
10847       goto ld_st;
10848     case M_CACHEE_AB:
10849       s = "cachee";
10850       fmt = "k,+j(b)";
10851       offbits = 9;
10852       goto ld_st;
10853     case M_PREF_AB:
10854       s = "pref";
10855       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
10856       offbits = (mips_opts.micromips ? 12 : 16);
10857       goto ld_st;
10858     case M_PREFE_AB:
10859       s = "prefe";
10860       fmt = "k,+j(b)";
10861       offbits = 9;
10862       goto ld_st;
10863     case M_SDC1_AB:
10864       s = "sdc1";
10865       fmt = "T,o(b)";
10866       coproc = 1;
10867       /* Itbl support may require additional care here.  */
10868       goto ld_st;
10869     case M_SDC2_AB:
10870       s = "sdc2";
10871       fmt = COP12_FMT;
10872       offbits = (mips_opts.micromips ? 12 : 16);
10873       /* Itbl support may require additional care here.  */
10874       coproc = 1;
10875       goto ld_st;
10876     case M_SQC2_AB:
10877       s = "sqc2";
10878       fmt = "+7,o(b)";
10879       /* Itbl support may require additional care here.  */
10880       coproc = 1;
10881       goto ld_st;
10882     case M_SDC3_AB:
10883       gas_assert (!mips_opts.micromips);
10884       s = "sdc3";
10885       fmt = "E,o(b)";
10886       /* Itbl support may require additional care here.  */
10887       coproc = 1;
10888       goto ld_st;
10889     case M_SDL_AB:
10890       s = "sdl";
10891       fmt = MEM12_FMT;
10892       offbits = (mips_opts.micromips ? 12 : 16);
10893       goto ld_st;
10894     case M_SDR_AB:
10895       s = "sdr";
10896       fmt = MEM12_FMT;
10897       offbits = (mips_opts.micromips ? 12 : 16);
10898       goto ld_st;
10899     case M_SWP_AB:
10900       gas_assert (mips_opts.micromips);
10901       s = "swp";
10902       fmt = "t,~(b)";
10903       offbits = 12;
10904       goto ld_st;
10905     case M_SDP_AB:
10906       gas_assert (mips_opts.micromips);
10907       s = "sdp";
10908       fmt = "t,~(b)";
10909       offbits = 12;
10910       goto ld_st;
10911     case M_SWM_AB:
10912       gas_assert (mips_opts.micromips);
10913       s = "swm";
10914       fmt = "n,~(b)";
10915       offbits = 12;
10916       goto ld_st;
10917     case M_SDM_AB:
10918       gas_assert (mips_opts.micromips);
10919       s = "sdm";
10920       fmt = "n,~(b)";
10921       offbits = 12;
10922
10923     ld_st:
10924       tempreg = AT;
10925     ld_noat:
10926       breg = op[2];
10927       if (small_offset_p (0, align, 16))
10928         {
10929           /* The first case exists for M_LD_AB and M_SD_AB, which are
10930              macros for o32 but which should act like normal instructions
10931              otherwise.  */
10932           if (offbits == 16)
10933             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
10934                          offset_reloc[1], offset_reloc[2], breg);
10935           else if (small_offset_p (0, align, offbits))
10936             {
10937               if (offbits == 0)
10938                 macro_build (NULL, s, fmt, op[0], breg);
10939               else
10940                 macro_build (NULL, s, fmt, op[0],
10941                              (int) offset_expr.X_add_number, breg);
10942             }
10943           else
10944             {
10945               if (tempreg == AT)
10946                 used_at = 1;
10947               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10948                            tempreg, breg, -1, offset_reloc[0],
10949                            offset_reloc[1], offset_reloc[2]);
10950               if (offbits == 0)
10951                 macro_build (NULL, s, fmt, op[0], tempreg);
10952               else
10953                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
10954             }
10955           break;
10956         }
10957
10958       if (tempreg == AT)
10959         used_at = 1;
10960
10961       if (offset_expr.X_op != O_constant
10962           && offset_expr.X_op != O_symbol)
10963         {
10964           as_bad (_("Expression too complex"));
10965           offset_expr.X_op = O_constant;
10966         }
10967
10968       if (HAVE_32BIT_ADDRESSES
10969           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10970         {
10971           char value [32];
10972
10973           sprintf_vma (value, offset_expr.X_add_number);
10974           as_bad (_("Number (0x%s) larger than 32 bits"), value);
10975         }
10976
10977       /* A constant expression in PIC code can be handled just as it
10978          is in non PIC code.  */
10979       if (offset_expr.X_op == O_constant)
10980         {
10981           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
10982                                                  offbits == 0 ? 16 : offbits);
10983           offset_expr.X_add_number -= expr1.X_add_number;
10984
10985           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
10986           if (breg != 0)
10987             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10988                          tempreg, tempreg, breg);
10989           if (offbits == 0)
10990             {
10991               if (offset_expr.X_add_number != 0)
10992                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
10993                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
10994               macro_build (NULL, s, fmt, op[0], tempreg);
10995             }
10996           else if (offbits == 16)
10997             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
10998           else
10999             macro_build (NULL, s, fmt, op[0],
11000                          (int) offset_expr.X_add_number, tempreg);
11001         }
11002       else if (offbits != 16)
11003         {
11004           /* The offset field is too narrow to be used for a low-part
11005              relocation, so load the whole address into the auxillary
11006              register.  */
11007           load_address (tempreg, &offset_expr, &used_at);
11008           if (breg != 0)
11009             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11010                          tempreg, tempreg, breg);
11011           if (offbits == 0)
11012             macro_build (NULL, s, fmt, op[0], tempreg);
11013           else
11014             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11015         }
11016       else if (mips_pic == NO_PIC)
11017         {
11018           /* If this is a reference to a GP relative symbol, and there
11019              is no base register, we want
11020                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11021              Otherwise, if there is no base register, we want
11022                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11023                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11024              If we have a constant, we need two instructions anyhow,
11025              so we always use the latter form.
11026
11027              If we have a base register, and this is a reference to a
11028              GP relative symbol, we want
11029                addu     $tempreg,$breg,$gp
11030                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11031              Otherwise we want
11032                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11033                addu     $tempreg,$tempreg,$breg
11034                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11035              With a constant we always use the latter case.
11036
11037              With 64bit address space and no base register and $at usable,
11038              we want
11039                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11040                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11041                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11042                dsll32   $tempreg,0
11043                daddu    $tempreg,$at
11044                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11045              If we have a base register, we want
11046                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11047                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11048                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11049                daddu    $at,$breg
11050                dsll32   $tempreg,0
11051                daddu    $tempreg,$at
11052                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11053
11054              Without $at we can't generate the optimal path for superscalar
11055              processors here since this would require two temporary registers.
11056                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11057                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11058                dsll     $tempreg,16
11059                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11060                dsll     $tempreg,16
11061                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11062              If we have a base register, we want
11063                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11064                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11065                dsll     $tempreg,16
11066                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11067                dsll     $tempreg,16
11068                daddu    $tempreg,$tempreg,$breg
11069                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11070
11071              For GP relative symbols in 64bit address space we can use
11072              the same sequence as in 32bit address space.  */
11073           if (HAVE_64BIT_SYMBOLS)
11074             {
11075               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11076                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11077                 {
11078                   relax_start (offset_expr.X_add_symbol);
11079                   if (breg == 0)
11080                     {
11081                       macro_build (&offset_expr, s, fmt, op[0],
11082                                    BFD_RELOC_GPREL16, mips_gp_register);
11083                     }
11084                   else
11085                     {
11086                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11087                                    tempreg, breg, mips_gp_register);
11088                       macro_build (&offset_expr, s, fmt, op[0],
11089                                    BFD_RELOC_GPREL16, tempreg);
11090                     }
11091                   relax_switch ();
11092                 }
11093
11094               if (used_at == 0 && mips_opts.at)
11095                 {
11096                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11097                                BFD_RELOC_MIPS_HIGHEST);
11098                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11099                                BFD_RELOC_HI16_S);
11100                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11101                                tempreg, BFD_RELOC_MIPS_HIGHER);
11102                   if (breg != 0)
11103                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11104                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11105                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11106                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11107                                tempreg);
11108                   used_at = 1;
11109                 }
11110               else
11111                 {
11112                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11113                                BFD_RELOC_MIPS_HIGHEST);
11114                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11115                                tempreg, BFD_RELOC_MIPS_HIGHER);
11116                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11117                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11118                                tempreg, BFD_RELOC_HI16_S);
11119                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11120                   if (breg != 0)
11121                     macro_build (NULL, "daddu", "d,v,t",
11122                                  tempreg, tempreg, breg);
11123                   macro_build (&offset_expr, s, fmt, op[0],
11124                                BFD_RELOC_LO16, tempreg);
11125                 }
11126
11127               if (mips_relax.sequence)
11128                 relax_end ();
11129               break;
11130             }
11131
11132           if (breg == 0)
11133             {
11134               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11135                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11136                 {
11137                   relax_start (offset_expr.X_add_symbol);
11138                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11139                                mips_gp_register);
11140                   relax_switch ();
11141                 }
11142               macro_build_lui (&offset_expr, tempreg);
11143               macro_build (&offset_expr, s, fmt, op[0],
11144                            BFD_RELOC_LO16, tempreg);
11145               if (mips_relax.sequence)
11146                 relax_end ();
11147             }
11148           else
11149             {
11150               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11151                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11152                 {
11153                   relax_start (offset_expr.X_add_symbol);
11154                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11155                                tempreg, breg, mips_gp_register);
11156                   macro_build (&offset_expr, s, fmt, op[0],
11157                                BFD_RELOC_GPREL16, tempreg);
11158                   relax_switch ();
11159                 }
11160               macro_build_lui (&offset_expr, tempreg);
11161               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11162                            tempreg, tempreg, breg);
11163               macro_build (&offset_expr, s, fmt, op[0],
11164                            BFD_RELOC_LO16, tempreg);
11165               if (mips_relax.sequence)
11166                 relax_end ();
11167             }
11168         }
11169       else if (!mips_big_got)
11170         {
11171           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11172
11173           /* If this is a reference to an external symbol, we want
11174                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11175                nop
11176                <op>     op[0],0($tempreg)
11177              Otherwise we want
11178                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11179                nop
11180                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11181                <op>     op[0],0($tempreg)
11182
11183              For NewABI, we want
11184                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11185                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11186
11187              If there is a base register, we add it to $tempreg before
11188              the <op>.  If there is a constant, we stick it in the
11189              <op> instruction.  We don't handle constants larger than
11190              16 bits, because we have no way to load the upper 16 bits
11191              (actually, we could handle them for the subset of cases
11192              in which we are not using $at).  */
11193           gas_assert (offset_expr.X_op == O_symbol);
11194           if (HAVE_NEWABI)
11195             {
11196               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11197                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11198               if (breg != 0)
11199                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11200                              tempreg, tempreg, breg);
11201               macro_build (&offset_expr, s, fmt, op[0],
11202                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11203               break;
11204             }
11205           expr1.X_add_number = offset_expr.X_add_number;
11206           offset_expr.X_add_number = 0;
11207           if (expr1.X_add_number < -0x8000
11208               || expr1.X_add_number >= 0x8000)
11209             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11210           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11211                        lw_reloc_type, mips_gp_register);
11212           load_delay_nop ();
11213           relax_start (offset_expr.X_add_symbol);
11214           relax_switch ();
11215           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11216                        tempreg, BFD_RELOC_LO16);
11217           relax_end ();
11218           if (breg != 0)
11219             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11220                          tempreg, tempreg, breg);
11221           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11222         }
11223       else if (mips_big_got && !HAVE_NEWABI)
11224         {
11225           int gpdelay;
11226
11227           /* If this is a reference to an external symbol, we want
11228                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11229                addu     $tempreg,$tempreg,$gp
11230                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11231                <op>     op[0],0($tempreg)
11232              Otherwise we want
11233                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11234                nop
11235                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11236                <op>     op[0],0($tempreg)
11237              If there is a base register, we add it to $tempreg before
11238              the <op>.  If there is a constant, we stick it in the
11239              <op> instruction.  We don't handle constants larger than
11240              16 bits, because we have no way to load the upper 16 bits
11241              (actually, we could handle them for the subset of cases
11242              in which we are not using $at).  */
11243           gas_assert (offset_expr.X_op == O_symbol);
11244           expr1.X_add_number = offset_expr.X_add_number;
11245           offset_expr.X_add_number = 0;
11246           if (expr1.X_add_number < -0x8000
11247               || expr1.X_add_number >= 0x8000)
11248             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11249           gpdelay = reg_needs_delay (mips_gp_register);
11250           relax_start (offset_expr.X_add_symbol);
11251           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11252                        BFD_RELOC_MIPS_GOT_HI16);
11253           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11254                        mips_gp_register);
11255           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11256                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11257           relax_switch ();
11258           if (gpdelay)
11259             macro_build (NULL, "nop", "");
11260           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11261                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11262           load_delay_nop ();
11263           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11264                        tempreg, BFD_RELOC_LO16);
11265           relax_end ();
11266
11267           if (breg != 0)
11268             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11269                          tempreg, tempreg, breg);
11270           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11271         }
11272       else if (mips_big_got && HAVE_NEWABI)
11273         {
11274           /* If this is a reference to an external symbol, we want
11275                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11276                add      $tempreg,$tempreg,$gp
11277                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11278                <op>     op[0],<ofst>($tempreg)
11279              Otherwise, for local symbols, we want:
11280                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11281                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11282           gas_assert (offset_expr.X_op == O_symbol);
11283           expr1.X_add_number = offset_expr.X_add_number;
11284           offset_expr.X_add_number = 0;
11285           if (expr1.X_add_number < -0x8000
11286               || expr1.X_add_number >= 0x8000)
11287             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11288           relax_start (offset_expr.X_add_symbol);
11289           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11290                        BFD_RELOC_MIPS_GOT_HI16);
11291           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11292                        mips_gp_register);
11293           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11294                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11295           if (breg != 0)
11296             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11297                          tempreg, tempreg, breg);
11298           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11299
11300           relax_switch ();
11301           offset_expr.X_add_number = expr1.X_add_number;
11302           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11303                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11304           if (breg != 0)
11305             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11306                          tempreg, tempreg, breg);
11307           macro_build (&offset_expr, s, fmt, op[0],
11308                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11309           relax_end ();
11310         }
11311       else
11312         abort ();
11313
11314       break;
11315
11316     case M_JRADDIUSP:
11317       gas_assert (mips_opts.micromips);
11318       gas_assert (mips_opts.insn32);
11319       start_noreorder ();
11320       macro_build (NULL, "jr", "s", RA);
11321       expr1.X_add_number = op[0] << 2;
11322       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11323       end_noreorder ();
11324       break;
11325
11326     case M_JRC:
11327       gas_assert (mips_opts.micromips);
11328       gas_assert (mips_opts.insn32);
11329       macro_build (NULL, "jr", "s", op[0]);
11330       if (mips_opts.noreorder)
11331         macro_build (NULL, "nop", "");
11332       break;
11333
11334     case M_LI:
11335     case M_LI_S:
11336       load_register (op[0], &imm_expr, 0);
11337       break;
11338
11339     case M_DLI:
11340       load_register (op[0], &imm_expr, 1);
11341       break;
11342
11343     case M_LI_SS:
11344       if (imm_expr.X_op == O_constant)
11345         {
11346           used_at = 1;
11347           load_register (AT, &imm_expr, 0);
11348           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11349           break;
11350         }
11351       else
11352         {
11353           gas_assert (offset_expr.X_op == O_symbol
11354                       && strcmp (segment_name (S_GET_SEGMENT
11355                                                (offset_expr.X_add_symbol)),
11356                                  ".lit4") == 0
11357                       && offset_expr.X_add_number == 0);
11358           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11359                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11360           break;
11361         }
11362
11363     case M_LI_D:
11364       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11365          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11366          order 32 bits of the value and the low order 32 bits are either
11367          zero or in OFFSET_EXPR.  */
11368       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
11369         {
11370           if (HAVE_64BIT_GPRS)
11371             load_register (op[0], &imm_expr, 1);
11372           else
11373             {
11374               int hreg, lreg;
11375
11376               if (target_big_endian)
11377                 {
11378                   hreg = op[0];
11379                   lreg = op[0] + 1;
11380                 }
11381               else
11382                 {
11383                   hreg = op[0] + 1;
11384                   lreg = op[0];
11385                 }
11386
11387               if (hreg <= 31)
11388                 load_register (hreg, &imm_expr, 0);
11389               if (lreg <= 31)
11390                 {
11391                   if (offset_expr.X_op == O_absent)
11392                     move_register (lreg, 0);
11393                   else
11394                     {
11395                       gas_assert (offset_expr.X_op == O_constant);
11396                       load_register (lreg, &offset_expr, 0);
11397                     }
11398                 }
11399             }
11400           break;
11401         }
11402
11403       /* We know that sym is in the .rdata section.  First we get the
11404          upper 16 bits of the address.  */
11405       if (mips_pic == NO_PIC)
11406         {
11407           macro_build_lui (&offset_expr, AT);
11408           used_at = 1;
11409         }
11410       else
11411         {
11412           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11413                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11414           used_at = 1;
11415         }
11416
11417       /* Now we load the register(s).  */
11418       if (HAVE_64BIT_GPRS)
11419         {
11420           used_at = 1;
11421           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11422                        BFD_RELOC_LO16, AT);
11423         }
11424       else
11425         {
11426           used_at = 1;
11427           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11428                        BFD_RELOC_LO16, AT);
11429           if (op[0] != RA)
11430             {
11431               /* FIXME: How in the world do we deal with the possible
11432                  overflow here?  */
11433               offset_expr.X_add_number += 4;
11434               macro_build (&offset_expr, "lw", "t,o(b)",
11435                            op[0] + 1, BFD_RELOC_LO16, AT);
11436             }
11437         }
11438       break;
11439
11440     case M_LI_DD:
11441       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11442          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11443          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11444          the value and the low order 32 bits are either zero or in
11445          OFFSET_EXPR.  */
11446       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
11447         {
11448           used_at = 1;
11449           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
11450           if (HAVE_64BIT_FPRS)
11451             {
11452               gas_assert (HAVE_64BIT_GPRS);
11453               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11454             }
11455           else
11456             {
11457               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11458               if (offset_expr.X_op == O_absent)
11459                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11460               else
11461                 {
11462                   gas_assert (offset_expr.X_op == O_constant);
11463                   load_register (AT, &offset_expr, 0);
11464                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11465                 }
11466             }
11467           break;
11468         }
11469
11470       gas_assert (offset_expr.X_op == O_symbol
11471                   && offset_expr.X_add_number == 0);
11472       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11473       if (strcmp (s, ".lit8") == 0)
11474         {
11475           op[2] = mips_gp_register;
11476           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11477           offset_reloc[1] = BFD_RELOC_UNUSED;
11478           offset_reloc[2] = BFD_RELOC_UNUSED;
11479         }
11480       else
11481         {
11482           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11483           used_at = 1;
11484           if (mips_pic != NO_PIC)
11485             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11486                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11487           else
11488             {
11489               /* FIXME: This won't work for a 64 bit address.  */
11490               macro_build_lui (&offset_expr, AT);
11491             }
11492
11493           op[2] = AT;
11494           offset_reloc[0] = BFD_RELOC_LO16;
11495           offset_reloc[1] = BFD_RELOC_UNUSED;
11496           offset_reloc[2] = BFD_RELOC_UNUSED;
11497         }
11498       align = 8;
11499       /* Fall through */
11500
11501     case M_L_DAB:
11502       /*
11503        * The MIPS assembler seems to check for X_add_number not
11504        * being double aligned and generating:
11505        *        lui     at,%hi(foo+1)
11506        *        addu    at,at,v1
11507        *        addiu   at,at,%lo(foo+1)
11508        *        lwc1    f2,0(at)
11509        *        lwc1    f3,4(at)
11510        * But, the resulting address is the same after relocation so why
11511        * generate the extra instruction?
11512        */
11513       /* Itbl support may require additional care here.  */
11514       coproc = 1;
11515       fmt = "T,o(b)";
11516       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11517         {
11518           s = "ldc1";
11519           goto ld_st;
11520         }
11521       s = "lwc1";
11522       goto ldd_std;
11523
11524     case M_S_DAB:
11525       gas_assert (!mips_opts.micromips);
11526       /* Itbl support may require additional care here.  */
11527       coproc = 1;
11528       fmt = "T,o(b)";
11529       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11530         {
11531           s = "sdc1";
11532           goto ld_st;
11533         }
11534       s = "swc1";
11535       goto ldd_std;
11536
11537     case M_LQ_AB:
11538       fmt = "t,o(b)";
11539       s = "lq";
11540       goto ld;
11541
11542     case M_SQ_AB:
11543       fmt = "t,o(b)";
11544       s = "sq";
11545       goto ld_st;
11546
11547     case M_LD_AB:
11548       fmt = "t,o(b)";
11549       if (HAVE_64BIT_GPRS)
11550         {
11551           s = "ld";
11552           goto ld;
11553         }
11554       s = "lw";
11555       goto ldd_std;
11556
11557     case M_SD_AB:
11558       fmt = "t,o(b)";
11559       if (HAVE_64BIT_GPRS)
11560         {
11561           s = "sd";
11562           goto ld_st;
11563         }
11564       s = "sw";
11565
11566     ldd_std:
11567       /* Even on a big endian machine $fn comes before $fn+1.  We have
11568          to adjust when loading from memory.  We set coproc if we must
11569          load $fn+1 first.  */
11570       /* Itbl support may require additional care here.  */
11571       if (!target_big_endian)
11572         coproc = 0;
11573
11574       breg = op[2];
11575       if (small_offset_p (0, align, 16))
11576         {
11577           ep = &offset_expr;
11578           if (!small_offset_p (4, align, 16))
11579             {
11580               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11581                            -1, offset_reloc[0], offset_reloc[1],
11582                            offset_reloc[2]);
11583               expr1.X_add_number = 0;
11584               ep = &expr1;
11585               breg = AT;
11586               used_at = 1;
11587               offset_reloc[0] = BFD_RELOC_LO16;
11588               offset_reloc[1] = BFD_RELOC_UNUSED;
11589               offset_reloc[2] = BFD_RELOC_UNUSED;
11590             }
11591           if (strcmp (s, "lw") == 0 && op[0] == breg)
11592             {
11593               ep->X_add_number += 4;
11594               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11595                            offset_reloc[1], offset_reloc[2], breg);
11596               ep->X_add_number -= 4;
11597               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11598                            offset_reloc[1], offset_reloc[2], breg);
11599             }
11600           else
11601             {
11602               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11603                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11604                            breg);
11605               ep->X_add_number += 4;
11606               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11607                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11608                            breg);
11609             }
11610           break;
11611         }
11612
11613       if (offset_expr.X_op != O_symbol
11614           && offset_expr.X_op != O_constant)
11615         {
11616           as_bad (_("Expression too complex"));
11617           offset_expr.X_op = O_constant;
11618         }
11619
11620       if (HAVE_32BIT_ADDRESSES
11621           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11622         {
11623           char value [32];
11624
11625           sprintf_vma (value, offset_expr.X_add_number);
11626           as_bad (_("Number (0x%s) larger than 32 bits"), value);
11627         }
11628
11629       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11630         {
11631           /* If this is a reference to a GP relative symbol, we want
11632                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11633                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11634              If we have a base register, we use this
11635                addu     $at,$breg,$gp
11636                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11637                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11638              If this is not a GP relative symbol, we want
11639                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11640                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11641                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11642              If there is a base register, we add it to $at after the
11643              lui instruction.  If there is a constant, we always use
11644              the last case.  */
11645           if (offset_expr.X_op == O_symbol
11646               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11647               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11648             {
11649               relax_start (offset_expr.X_add_symbol);
11650               if (breg == 0)
11651                 {
11652                   tempreg = mips_gp_register;
11653                 }
11654               else
11655                 {
11656                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11657                                AT, breg, mips_gp_register);
11658                   tempreg = AT;
11659                   used_at = 1;
11660                 }
11661
11662               /* Itbl support may require additional care here.  */
11663               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11664                            BFD_RELOC_GPREL16, tempreg);
11665               offset_expr.X_add_number += 4;
11666
11667               /* Set mips_optimize to 2 to avoid inserting an
11668                  undesired nop.  */
11669               hold_mips_optimize = mips_optimize;
11670               mips_optimize = 2;
11671               /* Itbl support may require additional care here.  */
11672               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11673                            BFD_RELOC_GPREL16, tempreg);
11674               mips_optimize = hold_mips_optimize;
11675
11676               relax_switch ();
11677
11678               offset_expr.X_add_number -= 4;
11679             }
11680           used_at = 1;
11681           if (offset_high_part (offset_expr.X_add_number, 16)
11682               != offset_high_part (offset_expr.X_add_number + 4, 16))
11683             {
11684               load_address (AT, &offset_expr, &used_at);
11685               offset_expr.X_op = O_constant;
11686               offset_expr.X_add_number = 0;
11687             }
11688           else
11689             macro_build_lui (&offset_expr, AT);
11690           if (breg != 0)
11691             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11692           /* Itbl support may require additional care here.  */
11693           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11694                        BFD_RELOC_LO16, AT);
11695           /* FIXME: How do we handle overflow here?  */
11696           offset_expr.X_add_number += 4;
11697           /* Itbl support may require additional care here.  */
11698           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11699                        BFD_RELOC_LO16, AT);
11700           if (mips_relax.sequence)
11701             relax_end ();
11702         }
11703       else if (!mips_big_got)
11704         {
11705           /* If this is a reference to an external symbol, we want
11706                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11707                nop
11708                <op>     op[0],0($at)
11709                <op>     op[0]+1,4($at)
11710              Otherwise we want
11711                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11712                nop
11713                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11714                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11715              If there is a base register we add it to $at before the
11716              lwc1 instructions.  If there is a constant we include it
11717              in the lwc1 instructions.  */
11718           used_at = 1;
11719           expr1.X_add_number = offset_expr.X_add_number;
11720           if (expr1.X_add_number < -0x8000
11721               || expr1.X_add_number >= 0x8000 - 4)
11722             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11723           load_got_offset (AT, &offset_expr);
11724           load_delay_nop ();
11725           if (breg != 0)
11726             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11727
11728           /* Set mips_optimize to 2 to avoid inserting an undesired
11729              nop.  */
11730           hold_mips_optimize = mips_optimize;
11731           mips_optimize = 2;
11732
11733           /* Itbl support may require additional care here.  */
11734           relax_start (offset_expr.X_add_symbol);
11735           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11736                        BFD_RELOC_LO16, AT);
11737           expr1.X_add_number += 4;
11738           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11739                        BFD_RELOC_LO16, AT);
11740           relax_switch ();
11741           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11742                        BFD_RELOC_LO16, AT);
11743           offset_expr.X_add_number += 4;
11744           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11745                        BFD_RELOC_LO16, AT);
11746           relax_end ();
11747
11748           mips_optimize = hold_mips_optimize;
11749         }
11750       else if (mips_big_got)
11751         {
11752           int gpdelay;
11753
11754           /* If this is a reference to an external symbol, we want
11755                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11756                addu     $at,$at,$gp
11757                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11758                nop
11759                <op>     op[0],0($at)
11760                <op>     op[0]+1,4($at)
11761              Otherwise we want
11762                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11763                nop
11764                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11765                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11766              If there is a base register we add it to $at before the
11767              lwc1 instructions.  If there is a constant we include it
11768              in the lwc1 instructions.  */
11769           used_at = 1;
11770           expr1.X_add_number = offset_expr.X_add_number;
11771           offset_expr.X_add_number = 0;
11772           if (expr1.X_add_number < -0x8000
11773               || expr1.X_add_number >= 0x8000 - 4)
11774             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11775           gpdelay = reg_needs_delay (mips_gp_register);
11776           relax_start (offset_expr.X_add_symbol);
11777           macro_build (&offset_expr, "lui", LUI_FMT,
11778                        AT, BFD_RELOC_MIPS_GOT_HI16);
11779           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11780                        AT, AT, mips_gp_register);
11781           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11782                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
11783           load_delay_nop ();
11784           if (breg != 0)
11785             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11786           /* Itbl support may require additional care here.  */
11787           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11788                        BFD_RELOC_LO16, AT);
11789           expr1.X_add_number += 4;
11790
11791           /* Set mips_optimize to 2 to avoid inserting an undesired
11792              nop.  */
11793           hold_mips_optimize = mips_optimize;
11794           mips_optimize = 2;
11795           /* Itbl support may require additional care here.  */
11796           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11797                        BFD_RELOC_LO16, AT);
11798           mips_optimize = hold_mips_optimize;
11799           expr1.X_add_number -= 4;
11800
11801           relax_switch ();
11802           offset_expr.X_add_number = expr1.X_add_number;
11803           if (gpdelay)
11804             macro_build (NULL, "nop", "");
11805           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11806                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11807           load_delay_nop ();
11808           if (breg != 0)
11809             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11810           /* Itbl support may require additional care here.  */
11811           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11812                        BFD_RELOC_LO16, AT);
11813           offset_expr.X_add_number += 4;
11814
11815           /* Set mips_optimize to 2 to avoid inserting an undesired
11816              nop.  */
11817           hold_mips_optimize = mips_optimize;
11818           mips_optimize = 2;
11819           /* Itbl support may require additional care here.  */
11820           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11821                        BFD_RELOC_LO16, AT);
11822           mips_optimize = hold_mips_optimize;
11823           relax_end ();
11824         }
11825       else
11826         abort ();
11827
11828       break;
11829         
11830     case M_SAA_AB:
11831       s = "saa";
11832       offbits = 0;
11833       fmt = "t,(b)";
11834       goto ld_st;
11835     case M_SAAD_AB:
11836       s = "saad";
11837       offbits = 0;
11838       fmt = "t,(b)";
11839       goto ld_st;
11840
11841    /* New code added to support COPZ instructions.
11842       This code builds table entries out of the macros in mip_opcodes.
11843       R4000 uses interlocks to handle coproc delays.
11844       Other chips (like the R3000) require nops to be inserted for delays.
11845
11846       FIXME: Currently, we require that the user handle delays.
11847       In order to fill delay slots for non-interlocked chips,
11848       we must have a way to specify delays based on the coprocessor.
11849       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
11850       What are the side-effects of the cop instruction?
11851       What cache support might we have and what are its effects?
11852       Both coprocessor & memory require delays. how long???
11853       What registers are read/set/modified?
11854
11855       If an itbl is provided to interpret cop instructions,
11856       this knowledge can be encoded in the itbl spec.  */
11857
11858     case M_COP0:
11859       s = "c0";
11860       goto copz;
11861     case M_COP1:
11862       s = "c1";
11863       goto copz;
11864     case M_COP2:
11865       s = "c2";
11866       goto copz;
11867     case M_COP3:
11868       s = "c3";
11869     copz:
11870       gas_assert (!mips_opts.micromips);
11871       /* For now we just do C (same as Cz).  The parameter will be
11872          stored in insn_opcode by mips_ip.  */
11873       macro_build (NULL, s, "C", (int) ip->insn_opcode);
11874       break;
11875
11876     case M_MOVE:
11877       move_register (op[0], op[1]);
11878       break;
11879
11880     case M_MOVEP:
11881       gas_assert (mips_opts.micromips);
11882       gas_assert (mips_opts.insn32);
11883       move_register (micromips_to_32_reg_h_map1[op[0]],
11884                      micromips_to_32_reg_m_map[op[1]]);
11885       move_register (micromips_to_32_reg_h_map2[op[0]],
11886                      micromips_to_32_reg_n_map[op[2]]);
11887       break;
11888
11889     case M_DMUL:
11890       dbl = 1;
11891     case M_MUL:
11892       if (mips_opts.arch == CPU_R5900)
11893         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
11894                      op[2]);
11895       else
11896         {
11897           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
11898           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11899         }
11900       break;
11901
11902     case M_DMUL_I:
11903       dbl = 1;
11904     case M_MUL_I:
11905       /* The MIPS assembler some times generates shifts and adds.  I'm
11906          not trying to be that fancy. GCC should do this for us
11907          anyway.  */
11908       used_at = 1;
11909       load_register (AT, &imm_expr, dbl);
11910       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
11911       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11912       break;
11913
11914     case M_DMULO_I:
11915       dbl = 1;
11916     case M_MULO_I:
11917       imm = 1;
11918       goto do_mulo;
11919
11920     case M_DMULO:
11921       dbl = 1;
11922     case M_MULO:
11923     do_mulo:
11924       start_noreorder ();
11925       used_at = 1;
11926       if (imm)
11927         load_register (AT, &imm_expr, dbl);
11928       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
11929                    op[1], imm ? AT : op[2]);
11930       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11931       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
11932       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11933       if (mips_trap)
11934         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
11935       else
11936         {
11937           if (mips_opts.micromips)
11938             micromips_label_expr (&label_expr);
11939           else
11940             label_expr.X_add_number = 8;
11941           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
11942           macro_build (NULL, "nop", "");
11943           macro_build (NULL, "break", BRK_FMT, 6);
11944           if (mips_opts.micromips)
11945             micromips_add_label ();
11946         }
11947       end_noreorder ();
11948       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11949       break;
11950
11951     case M_DMULOU_I:
11952       dbl = 1;
11953     case M_MULOU_I:
11954       imm = 1;
11955       goto do_mulou;
11956
11957     case M_DMULOU:
11958       dbl = 1;
11959     case M_MULOU:
11960     do_mulou:
11961       start_noreorder ();
11962       used_at = 1;
11963       if (imm)
11964         load_register (AT, &imm_expr, dbl);
11965       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
11966                    op[1], imm ? AT : op[2]);
11967       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11968       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11969       if (mips_trap)
11970         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
11971       else
11972         {
11973           if (mips_opts.micromips)
11974             micromips_label_expr (&label_expr);
11975           else
11976             label_expr.X_add_number = 8;
11977           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
11978           macro_build (NULL, "nop", "");
11979           macro_build (NULL, "break", BRK_FMT, 6);
11980           if (mips_opts.micromips)
11981             micromips_add_label ();
11982         }
11983       end_noreorder ();
11984       break;
11985
11986     case M_DROL:
11987       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11988         {
11989           if (op[0] == op[1])
11990             {
11991               tempreg = AT;
11992               used_at = 1;
11993             }
11994           else
11995             tempreg = op[0];
11996           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
11997           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
11998           break;
11999         }
12000       used_at = 1;
12001       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12002       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12003       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12004       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12005       break;
12006
12007     case M_ROL:
12008       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12009         {
12010           if (op[0] == op[1])
12011             {
12012               tempreg = AT;
12013               used_at = 1;
12014             }
12015           else
12016             tempreg = op[0];
12017           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12018           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12019           break;
12020         }
12021       used_at = 1;
12022       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12023       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12024       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12025       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12026       break;
12027
12028     case M_DROL_I:
12029       {
12030         unsigned int rot;
12031         char *l;
12032         char *rr;
12033
12034         if (imm_expr.X_op != O_constant)
12035           as_bad (_("Improper rotate count"));
12036         rot = imm_expr.X_add_number & 0x3f;
12037         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12038           {
12039             rot = (64 - rot) & 0x3f;
12040             if (rot >= 32)
12041               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12042             else
12043               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12044             break;
12045           }
12046         if (rot == 0)
12047           {
12048             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12049             break;
12050           }
12051         l = (rot < 0x20) ? "dsll" : "dsll32";
12052         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12053         rot &= 0x1f;
12054         used_at = 1;
12055         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12056         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12057         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12058       }
12059       break;
12060
12061     case M_ROL_I:
12062       {
12063         unsigned int rot;
12064
12065         if (imm_expr.X_op != O_constant)
12066           as_bad (_("Improper rotate count"));
12067         rot = imm_expr.X_add_number & 0x1f;
12068         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12069           {
12070             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12071                          (32 - rot) & 0x1f);
12072             break;
12073           }
12074         if (rot == 0)
12075           {
12076             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12077             break;
12078           }
12079         used_at = 1;
12080         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12081         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12082         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12083       }
12084       break;
12085
12086     case M_DROR:
12087       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12088         {
12089           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12090           break;
12091         }
12092       used_at = 1;
12093       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12094       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12095       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12096       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12097       break;
12098
12099     case M_ROR:
12100       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12101         {
12102           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12103           break;
12104         }
12105       used_at = 1;
12106       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12107       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12108       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12109       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12110       break;
12111
12112     case M_DROR_I:
12113       {
12114         unsigned int rot;
12115         char *l;
12116         char *rr;
12117
12118         if (imm_expr.X_op != O_constant)
12119           as_bad (_("Improper rotate count"));
12120         rot = imm_expr.X_add_number & 0x3f;
12121         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12122           {
12123             if (rot >= 32)
12124               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12125             else
12126               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12127             break;
12128           }
12129         if (rot == 0)
12130           {
12131             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12132             break;
12133           }
12134         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12135         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12136         rot &= 0x1f;
12137         used_at = 1;
12138         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12139         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12140         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12141       }
12142       break;
12143
12144     case M_ROR_I:
12145       {
12146         unsigned int rot;
12147
12148         if (imm_expr.X_op != O_constant)
12149           as_bad (_("Improper rotate count"));
12150         rot = imm_expr.X_add_number & 0x1f;
12151         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12152           {
12153             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12154             break;
12155           }
12156         if (rot == 0)
12157           {
12158             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12159             break;
12160           }
12161         used_at = 1;
12162         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12163         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12164         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12165       }
12166       break;
12167
12168     case M_SEQ:
12169       if (op[1] == 0)
12170         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12171       else if (op[2] == 0)
12172         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12173       else
12174         {
12175           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12176           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12177         }
12178       break;
12179
12180     case M_SEQ_I:
12181       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
12182         {
12183           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12184           break;
12185         }
12186       if (op[1] == 0)
12187         {
12188           as_warn (_("Instruction %s: result is always false"),
12189                    ip->insn_mo->name);
12190           move_register (op[0], 0);
12191           break;
12192         }
12193       if (CPU_HAS_SEQ (mips_opts.arch)
12194           && -512 <= imm_expr.X_add_number
12195           && imm_expr.X_add_number < 512)
12196         {
12197           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12198                        (int) imm_expr.X_add_number);
12199           break;
12200         }
12201       if (imm_expr.X_op == O_constant
12202           && imm_expr.X_add_number >= 0
12203           && imm_expr.X_add_number < 0x10000)
12204         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12205       else if (imm_expr.X_op == O_constant
12206                && imm_expr.X_add_number > -0x8000
12207                && imm_expr.X_add_number < 0)
12208         {
12209           imm_expr.X_add_number = -imm_expr.X_add_number;
12210           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12211                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12212         }
12213       else if (CPU_HAS_SEQ (mips_opts.arch))
12214         {
12215           used_at = 1;
12216           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12217           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12218           break;
12219         }
12220       else
12221         {
12222           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12223           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12224           used_at = 1;
12225         }
12226       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12227       break;
12228
12229     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12230       s = "slt";
12231       goto sge;
12232     case M_SGEU:
12233       s = "sltu";
12234     sge:
12235       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12236       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12237       break;
12238
12239     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12240     case M_SGEU_I:
12241       if (imm_expr.X_op == O_constant
12242           && imm_expr.X_add_number >= -0x8000
12243           && imm_expr.X_add_number < 0x8000)
12244         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12245                      op[0], op[1], BFD_RELOC_LO16);
12246       else
12247         {
12248           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12249           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12250                        op[0], op[1], AT);
12251           used_at = 1;
12252         }
12253       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12254       break;
12255
12256     case M_SGT:         /* X > Y  <==>  Y < X */
12257       s = "slt";
12258       goto sgt;
12259     case M_SGTU:
12260       s = "sltu";
12261     sgt:
12262       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12263       break;
12264
12265     case M_SGT_I:       /* X > I  <==>  I < X */
12266       s = "slt";
12267       goto sgti;
12268     case M_SGTU_I:
12269       s = "sltu";
12270     sgti:
12271       used_at = 1;
12272       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12273       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12274       break;
12275
12276     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12277       s = "slt";
12278       goto sle;
12279     case M_SLEU:
12280       s = "sltu";
12281     sle:
12282       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12283       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12284       break;
12285
12286     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12287       s = "slt";
12288       goto slei;
12289     case M_SLEU_I:
12290       s = "sltu";
12291     slei:
12292       used_at = 1;
12293       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12294       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12295       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12296       break;
12297
12298     case M_SLT_I:
12299       if (imm_expr.X_op == O_constant
12300           && imm_expr.X_add_number >= -0x8000
12301           && imm_expr.X_add_number < 0x8000)
12302         {
12303           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12304                        BFD_RELOC_LO16);
12305           break;
12306         }
12307       used_at = 1;
12308       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12309       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12310       break;
12311
12312     case M_SLTU_I:
12313       if (imm_expr.X_op == O_constant
12314           && imm_expr.X_add_number >= -0x8000
12315           && imm_expr.X_add_number < 0x8000)
12316         {
12317           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12318                        BFD_RELOC_LO16);
12319           break;
12320         }
12321       used_at = 1;
12322       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12323       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12324       break;
12325
12326     case M_SNE:
12327       if (op[1] == 0)
12328         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12329       else if (op[2] == 0)
12330         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12331       else
12332         {
12333           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12334           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12335         }
12336       break;
12337
12338     case M_SNE_I:
12339       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
12340         {
12341           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12342           break;
12343         }
12344       if (op[1] == 0)
12345         {
12346           as_warn (_("Instruction %s: result is always true"),
12347                    ip->insn_mo->name);
12348           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
12349                        op[0], 0, BFD_RELOC_LO16);
12350           break;
12351         }
12352       if (CPU_HAS_SEQ (mips_opts.arch)
12353           && -512 <= imm_expr.X_add_number
12354           && imm_expr.X_add_number < 512)
12355         {
12356           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12357                        (int) imm_expr.X_add_number);
12358           break;
12359         }
12360       if (imm_expr.X_op == O_constant
12361           && imm_expr.X_add_number >= 0
12362           && imm_expr.X_add_number < 0x10000)
12363         {
12364           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12365                        BFD_RELOC_LO16);
12366         }
12367       else if (imm_expr.X_op == O_constant
12368                && imm_expr.X_add_number > -0x8000
12369                && imm_expr.X_add_number < 0)
12370         {
12371           imm_expr.X_add_number = -imm_expr.X_add_number;
12372           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12373                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12374         }
12375       else if (CPU_HAS_SEQ (mips_opts.arch))
12376         {
12377           used_at = 1;
12378           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12379           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12380           break;
12381         }
12382       else
12383         {
12384           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12385           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12386           used_at = 1;
12387         }
12388       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12389       break;
12390
12391     case M_SUB_I:
12392       s = "addi";
12393       s2 = "sub";
12394       goto do_subi;
12395     case M_SUBU_I:
12396       s = "addiu";
12397       s2 = "subu";
12398       goto do_subi;
12399     case M_DSUB_I:
12400       dbl = 1;
12401       s = "daddi";
12402       s2 = "dsub";
12403       if (!mips_opts.micromips)
12404         goto do_subi;
12405       if (imm_expr.X_op == O_constant
12406           && imm_expr.X_add_number > -0x200
12407           && imm_expr.X_add_number <= 0x200)
12408         {
12409           macro_build (NULL, s, "t,r,.", op[0], op[1], -imm_expr.X_add_number);
12410           break;
12411         }
12412       goto do_subi_i;
12413     case M_DSUBU_I:
12414       dbl = 1;
12415       s = "daddiu";
12416       s2 = "dsubu";
12417     do_subi:
12418       if (imm_expr.X_op == O_constant
12419           && imm_expr.X_add_number > -0x8000
12420           && imm_expr.X_add_number <= 0x8000)
12421         {
12422           imm_expr.X_add_number = -imm_expr.X_add_number;
12423           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12424           break;
12425         }
12426     do_subi_i:
12427       used_at = 1;
12428       load_register (AT, &imm_expr, dbl);
12429       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12430       break;
12431
12432     case M_TEQ_I:
12433       s = "teq";
12434       goto trap;
12435     case M_TGE_I:
12436       s = "tge";
12437       goto trap;
12438     case M_TGEU_I:
12439       s = "tgeu";
12440       goto trap;
12441     case M_TLT_I:
12442       s = "tlt";
12443       goto trap;
12444     case M_TLTU_I:
12445       s = "tltu";
12446       goto trap;
12447     case M_TNE_I:
12448       s = "tne";
12449     trap:
12450       used_at = 1;
12451       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12452       macro_build (NULL, s, "s,t", op[0], AT);
12453       break;
12454
12455     case M_TRUNCWS:
12456     case M_TRUNCWD:
12457       gas_assert (!mips_opts.micromips);
12458       gas_assert (mips_opts.isa == ISA_MIPS1);
12459       used_at = 1;
12460
12461       /*
12462        * Is the double cfc1 instruction a bug in the mips assembler;
12463        * or is there a reason for it?
12464        */
12465       start_noreorder ();
12466       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12467       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12468       macro_build (NULL, "nop", "");
12469       expr1.X_add_number = 3;
12470       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12471       expr1.X_add_number = 2;
12472       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12473       macro_build (NULL, "ctc1", "t,G", AT, RA);
12474       macro_build (NULL, "nop", "");
12475       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12476                    op[0], op[1]);
12477       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12478       macro_build (NULL, "nop", "");
12479       end_noreorder ();
12480       break;
12481
12482     case M_ULH_AB:
12483       s = "lb";
12484       s2 = "lbu";
12485       off = 1;
12486       goto uld_st;
12487     case M_ULHU_AB:
12488       s = "lbu";
12489       s2 = "lbu";
12490       off = 1;
12491       goto uld_st;
12492     case M_ULW_AB:
12493       s = "lwl";
12494       s2 = "lwr";
12495       offbits = (mips_opts.micromips ? 12 : 16);
12496       off = 3;
12497       goto uld_st;
12498     case M_ULD_AB:
12499       s = "ldl";
12500       s2 = "ldr";
12501       offbits = (mips_opts.micromips ? 12 : 16);
12502       off = 7;
12503       goto uld_st;
12504     case M_USH_AB:
12505       s = "sb";
12506       s2 = "sb";
12507       off = 1;
12508       ust = 1;
12509       goto uld_st;
12510     case M_USW_AB:
12511       s = "swl";
12512       s2 = "swr";
12513       offbits = (mips_opts.micromips ? 12 : 16);
12514       off = 3;
12515       ust = 1;
12516       goto uld_st;
12517     case M_USD_AB:
12518       s = "sdl";
12519       s2 = "sdr";
12520       offbits = (mips_opts.micromips ? 12 : 16);
12521       off = 7;
12522       ust = 1;
12523
12524     uld_st:
12525       breg = op[2];
12526       large_offset = !small_offset_p (off, align, offbits);
12527       ep = &offset_expr;
12528       expr1.X_add_number = 0;
12529       if (large_offset)
12530         {
12531           used_at = 1;
12532           tempreg = AT;
12533           if (small_offset_p (0, align, 16))
12534             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12535                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12536           else
12537             {
12538               load_address (tempreg, ep, &used_at);
12539               if (breg != 0)
12540                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12541                              tempreg, tempreg, breg);
12542             }
12543           offset_reloc[0] = BFD_RELOC_LO16;
12544           offset_reloc[1] = BFD_RELOC_UNUSED;
12545           offset_reloc[2] = BFD_RELOC_UNUSED;
12546           breg = tempreg;
12547           tempreg = op[0];
12548           ep = &expr1;
12549         }
12550       else if (!ust && op[0] == breg)
12551         {
12552           used_at = 1;
12553           tempreg = AT;
12554         }
12555       else
12556         tempreg = op[0];
12557
12558       if (off == 1)
12559         goto ulh_sh;
12560
12561       if (!target_big_endian)
12562         ep->X_add_number += off;
12563       if (offbits == 12)
12564         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12565       else
12566         macro_build (ep, s, "t,o(b)", tempreg, -1,
12567                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12568
12569       if (!target_big_endian)
12570         ep->X_add_number -= off;
12571       else
12572         ep->X_add_number += off;
12573       if (offbits == 12)
12574         macro_build (NULL, s2, "t,~(b)",
12575                      tempreg, (int) ep->X_add_number, breg);
12576       else
12577         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12578                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12579
12580       /* If necessary, move the result in tempreg to the final destination.  */
12581       if (!ust && op[0] != tempreg)
12582         {
12583           /* Protect second load's delay slot.  */
12584           load_delay_nop ();
12585           move_register (op[0], tempreg);
12586         }
12587       break;
12588
12589     ulh_sh:
12590       used_at = 1;
12591       if (target_big_endian == ust)
12592         ep->X_add_number += off;
12593       tempreg = ust || large_offset ? op[0] : AT;
12594       macro_build (ep, s, "t,o(b)", tempreg, -1,
12595                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12596
12597       /* For halfword transfers we need a temporary register to shuffle
12598          bytes.  Unfortunately for M_USH_A we have none available before
12599          the next store as AT holds the base address.  We deal with this
12600          case by clobbering TREG and then restoring it as with ULH.  */
12601       tempreg = ust == large_offset ? op[0] : AT;
12602       if (ust)
12603         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12604
12605       if (target_big_endian == ust)
12606         ep->X_add_number -= off;
12607       else
12608         ep->X_add_number += off;
12609       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12610                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12611
12612       /* For M_USH_A re-retrieve the LSB.  */
12613       if (ust && large_offset)
12614         {
12615           if (target_big_endian)
12616             ep->X_add_number += off;
12617           else
12618             ep->X_add_number -= off;
12619           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12620                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12621         }
12622       /* For ULH and M_USH_A OR the LSB in.  */
12623       if (!ust || large_offset)
12624         {
12625           tempreg = !large_offset ? AT : op[0];
12626           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12627           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12628         }
12629       break;
12630
12631     default:
12632       /* FIXME: Check if this is one of the itbl macros, since they
12633          are added dynamically.  */
12634       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
12635       break;
12636     }
12637   if (!mips_opts.at && used_at)
12638     as_bad (_("Macro used $at after \".set noat\""));
12639 }
12640
12641 /* Implement macros in mips16 mode.  */
12642
12643 static void
12644 mips16_macro (struct mips_cl_insn *ip)
12645 {
12646   const struct mips_operand_array *operands;
12647   int mask;
12648   int tmp;
12649   expressionS expr1;
12650   int dbl;
12651   const char *s, *s2, *s3;
12652   unsigned int op[MAX_OPERANDS];
12653   unsigned int i;
12654
12655   mask = ip->insn_mo->mask;
12656
12657   operands = insn_operands (ip);
12658   for (i = 0; i < MAX_OPERANDS; i++)
12659     if (operands->operand[i])
12660       op[i] = insn_extract_operand (ip, operands->operand[i]);
12661     else
12662       op[i] = -1;
12663
12664   expr1.X_op = O_constant;
12665   expr1.X_op_symbol = NULL;
12666   expr1.X_add_symbol = NULL;
12667   expr1.X_add_number = 1;
12668
12669   dbl = 0;
12670
12671   switch (mask)
12672     {
12673     default:
12674       abort ();
12675
12676     case M_DDIV_3:
12677       dbl = 1;
12678     case M_DIV_3:
12679       s = "mflo";
12680       goto do_div3;
12681     case M_DREM_3:
12682       dbl = 1;
12683     case M_REM_3:
12684       s = "mfhi";
12685     do_div3:
12686       start_noreorder ();
12687       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12688       expr1.X_add_number = 2;
12689       macro_build (&expr1, "bnez", "x,p", op[2]);
12690       macro_build (NULL, "break", "6", 7);
12691
12692       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12693          since that causes an overflow.  We should do that as well,
12694          but I don't see how to do the comparisons without a temporary
12695          register.  */
12696       end_noreorder ();
12697       macro_build (NULL, s, "x", op[0]);
12698       break;
12699
12700     case M_DIVU_3:
12701       s = "divu";
12702       s2 = "mflo";
12703       goto do_divu3;
12704     case M_REMU_3:
12705       s = "divu";
12706       s2 = "mfhi";
12707       goto do_divu3;
12708     case M_DDIVU_3:
12709       s = "ddivu";
12710       s2 = "mflo";
12711       goto do_divu3;
12712     case M_DREMU_3:
12713       s = "ddivu";
12714       s2 = "mfhi";
12715     do_divu3:
12716       start_noreorder ();
12717       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12718       expr1.X_add_number = 2;
12719       macro_build (&expr1, "bnez", "x,p", op[2]);
12720       macro_build (NULL, "break", "6", 7);
12721       end_noreorder ();
12722       macro_build (NULL, s2, "x", op[0]);
12723       break;
12724
12725     case M_DMUL:
12726       dbl = 1;
12727     case M_MUL:
12728       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12729       macro_build (NULL, "mflo", "x", op[0]);
12730       break;
12731
12732     case M_DSUBU_I:
12733       dbl = 1;
12734       goto do_subu;
12735     case M_SUBU_I:
12736     do_subu:
12737       if (imm_expr.X_op != O_constant)
12738         as_bad (_("Unsupported large constant"));
12739       imm_expr.X_add_number = -imm_expr.X_add_number;
12740       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12741       break;
12742
12743     case M_SUBU_I_2:
12744       if (imm_expr.X_op != O_constant)
12745         as_bad (_("Unsupported large constant"));
12746       imm_expr.X_add_number = -imm_expr.X_add_number;
12747       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12748       break;
12749
12750     case M_DSUBU_I_2:
12751       if (imm_expr.X_op != O_constant)
12752         as_bad (_("Unsupported large constant"));
12753       imm_expr.X_add_number = -imm_expr.X_add_number;
12754       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12755       break;
12756
12757     case M_BEQ:
12758       s = "cmp";
12759       s2 = "bteqz";
12760       goto do_branch;
12761     case M_BNE:
12762       s = "cmp";
12763       s2 = "btnez";
12764       goto do_branch;
12765     case M_BLT:
12766       s = "slt";
12767       s2 = "btnez";
12768       goto do_branch;
12769     case M_BLTU:
12770       s = "sltu";
12771       s2 = "btnez";
12772       goto do_branch;
12773     case M_BLE:
12774       s = "slt";
12775       s2 = "bteqz";
12776       goto do_reverse_branch;
12777     case M_BLEU:
12778       s = "sltu";
12779       s2 = "bteqz";
12780       goto do_reverse_branch;
12781     case M_BGE:
12782       s = "slt";
12783       s2 = "bteqz";
12784       goto do_branch;
12785     case M_BGEU:
12786       s = "sltu";
12787       s2 = "bteqz";
12788       goto do_branch;
12789     case M_BGT:
12790       s = "slt";
12791       s2 = "btnez";
12792       goto do_reverse_branch;
12793     case M_BGTU:
12794       s = "sltu";
12795       s2 = "btnez";
12796
12797     do_reverse_branch:
12798       tmp = op[1];
12799       op[1] = op[0];
12800       op[0] = tmp;
12801
12802     do_branch:
12803       macro_build (NULL, s, "x,y", op[0], op[1]);
12804       macro_build (&offset_expr, s2, "p");
12805       break;
12806
12807     case M_BEQ_I:
12808       s = "cmpi";
12809       s2 = "bteqz";
12810       s3 = "x,U";
12811       goto do_branch_i;
12812     case M_BNE_I:
12813       s = "cmpi";
12814       s2 = "btnez";
12815       s3 = "x,U";
12816       goto do_branch_i;
12817     case M_BLT_I:
12818       s = "slti";
12819       s2 = "btnez";
12820       s3 = "x,8";
12821       goto do_branch_i;
12822     case M_BLTU_I:
12823       s = "sltiu";
12824       s2 = "btnez";
12825       s3 = "x,8";
12826       goto do_branch_i;
12827     case M_BLE_I:
12828       s = "slti";
12829       s2 = "btnez";
12830       s3 = "x,8";
12831       goto do_addone_branch_i;
12832     case M_BLEU_I:
12833       s = "sltiu";
12834       s2 = "btnez";
12835       s3 = "x,8";
12836       goto do_addone_branch_i;
12837     case M_BGE_I:
12838       s = "slti";
12839       s2 = "bteqz";
12840       s3 = "x,8";
12841       goto do_branch_i;
12842     case M_BGEU_I:
12843       s = "sltiu";
12844       s2 = "bteqz";
12845       s3 = "x,8";
12846       goto do_branch_i;
12847     case M_BGT_I:
12848       s = "slti";
12849       s2 = "bteqz";
12850       s3 = "x,8";
12851       goto do_addone_branch_i;
12852     case M_BGTU_I:
12853       s = "sltiu";
12854       s2 = "bteqz";
12855       s3 = "x,8";
12856
12857     do_addone_branch_i:
12858       if (imm_expr.X_op != O_constant)
12859         as_bad (_("Unsupported large constant"));
12860       ++imm_expr.X_add_number;
12861
12862     do_branch_i:
12863       macro_build (&imm_expr, s, s3, op[0]);
12864       macro_build (&offset_expr, s2, "p");
12865       break;
12866
12867     case M_ABS:
12868       expr1.X_add_number = 0;
12869       macro_build (&expr1, "slti", "x,8", op[1]);
12870       if (op[0] != op[1])
12871         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
12872       expr1.X_add_number = 2;
12873       macro_build (&expr1, "bteqz", "p");
12874       macro_build (NULL, "neg", "x,w", op[0], op[0]);
12875       break;
12876     }
12877 }
12878
12879 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
12880    opcode bits in *OPCODE_EXTRA.  */
12881
12882 static struct mips_opcode *
12883 mips_lookup_insn (struct hash_control *hash, const char *start,
12884                   ssize_t length, unsigned int *opcode_extra)
12885 {
12886   char *name, *dot, *p;
12887   unsigned int mask, suffix;
12888   ssize_t opend;
12889   struct mips_opcode *insn;
12890
12891   /* Make a copy of the instruction so that we can fiddle with it.  */
12892   name = alloca (length + 1);
12893   memcpy (name, start, length);
12894   name[length] = '\0';
12895
12896   /* Look up the instruction as-is.  */
12897   insn = (struct mips_opcode *) hash_find (hash, name);
12898   if (insn)
12899     return insn;
12900
12901   dot = strchr (name, '.');
12902   if (dot && dot[1])
12903     {
12904       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
12905       p = mips_parse_vu0_channels (dot + 1, &mask);
12906       if (*p == 0 && mask != 0)
12907         {
12908           *dot = 0;
12909           insn = (struct mips_opcode *) hash_find (hash, name);
12910           *dot = '.';
12911           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
12912             {
12913               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
12914               return insn;
12915             }
12916         }
12917     }
12918
12919   if (mips_opts.micromips)
12920     {
12921       /* See if there's an instruction size override suffix,
12922          either `16' or `32', at the end of the mnemonic proper,
12923          that defines the operation, i.e. before the first `.'
12924          character if any.  Strip it and retry.  */
12925       opend = dot != NULL ? dot - name : length;
12926       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
12927         suffix = 2;
12928       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
12929         suffix = 4;
12930       else
12931         suffix = 0;
12932       if (suffix)
12933         {
12934           memcpy (name + opend - 2, name + opend, length - opend + 1);
12935           insn = (struct mips_opcode *) hash_find (hash, name);
12936           if (insn)
12937             {
12938               forced_insn_length = suffix;
12939               return insn;
12940             }
12941         }
12942     }
12943
12944   return NULL;
12945 }
12946
12947 /* Assemble an instruction into its binary format.  If the instruction
12948    is a macro, set imm_expr, imm2_expr and offset_expr to the values
12949    associated with "I", "+I" and "A" operands respectively.  Otherwise
12950    store the value of the relocatable field (if any) in offset_expr.
12951    In both cases set offset_reloc to the relocation operators applied
12952    to offset_expr.  */
12953
12954 static void
12955 mips_ip (char *str, struct mips_cl_insn *ip)
12956 {
12957   bfd_boolean wrong_delay_slot_insns = FALSE;
12958   bfd_boolean need_delay_slot_ok = TRUE;
12959   struct mips_opcode *firstinsn = NULL;
12960   const struct mips_opcode *past;
12961   struct hash_control *hash;
12962   struct mips_opcode *first, *insn;
12963   char format;
12964   size_t end;
12965   struct mips_operand_token *tokens;
12966   unsigned int opcode_extra;
12967
12968   if (mips_opts.micromips)
12969     {
12970       hash = micromips_op_hash;
12971       past = &micromips_opcodes[bfd_micromips_num_opcodes];
12972     }
12973   else
12974     {
12975       hash = op_hash;
12976       past = &mips_opcodes[NUMOPCODES];
12977     }
12978   forced_insn_length = 0;
12979   insn = NULL;
12980   opcode_extra = 0;
12981
12982   /* We first try to match an instruction up to a space or to the end.  */
12983   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
12984     continue;
12985
12986   first = insn = mips_lookup_insn (hash, str, end, &opcode_extra);
12987   if (insn == NULL)
12988     {
12989       set_insn_error (0, _("Unrecognized opcode"));
12990       return;
12991     }
12992   /* When no opcode suffix is specified, assume ".xyzw". */
12993   if ((insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
12994     opcode_extra = 0xf << mips_vu0_channel_mask.lsb;
12995
12996   if (strcmp (insn->name, "li.s") == 0)
12997     format = 'f';
12998   else if (strcmp (insn->name, "li.d") == 0)
12999     format = 'd';
13000   else
13001     format = 0;
13002   tokens = mips_parse_arguments (str + end, format);
13003   if (!tokens)
13004     return;
13005
13006   /* For microMIPS instructions placed in a fixed-length branch delay slot
13007      we make up to two passes over the relevant fragment of the opcode
13008      table.  First we try instructions that meet the delay slot's length
13009      requirement.  If none matched, then we retry with the remaining ones
13010      and if one matches, then we use it and then issue an appropriate
13011      warning later on.  */
13012   for (;;)
13013     {
13014       bfd_boolean delay_slot_ok;
13015       bfd_boolean size_ok;
13016       bfd_boolean ok;
13017       bfd_boolean more_alts;
13018
13019       gas_assert (strcmp (insn->name, first->name) == 0);
13020
13021       ok = is_opcode_valid (insn);
13022       size_ok = is_size_valid (insn);
13023       delay_slot_ok = is_delay_slot_valid (insn);
13024       if (!delay_slot_ok && !wrong_delay_slot_insns)
13025         {
13026           firstinsn = insn;
13027           wrong_delay_slot_insns = TRUE;
13028         }
13029       more_alts = (insn + 1 < past
13030                    && strcmp (insn[0].name, insn[1].name) == 0);
13031       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
13032         {
13033           if (more_alts)
13034             {
13035               ++insn;
13036               continue;
13037             }
13038           if (wrong_delay_slot_insns && need_delay_slot_ok)
13039             {
13040               gas_assert (firstinsn);
13041               need_delay_slot_ok = FALSE;
13042               past = insn + 1;
13043               insn = firstinsn;
13044               continue;
13045             }
13046
13047           if (!ok)
13048             set_insn_error_ss
13049               (0, _("Opcode not supported on this processor: %s (%s)"),
13050                mips_cpu_info_from_arch (mips_opts.arch)->name,
13051                mips_cpu_info_from_isa (mips_opts.isa)->name);
13052           else if (mips_opts.insn32)
13053             set_insn_error
13054               (0, _("Opcode not supported in the `insn32' mode"));
13055           else
13056             set_insn_error_i
13057               (0, _("Unrecognized %d-bit version of microMIPS opcode"),
13058                8 * forced_insn_length);
13059           break;
13060         }
13061
13062       if (match_insn (ip, insn, tokens, opcode_extra,
13063                       more_alts || (wrong_delay_slot_insns
13064                                     && need_delay_slot_ok)))
13065         break;
13066
13067       /* Args don't match.  */
13068       set_insn_error (0, _("Illegal operands"));
13069       if (more_alts)
13070         {
13071           ++insn;
13072           continue;
13073         }
13074       if (wrong_delay_slot_insns && need_delay_slot_ok)
13075         {
13076           gas_assert (firstinsn);
13077           need_delay_slot_ok = FALSE;
13078           past = insn + 1;
13079           insn = firstinsn;
13080           continue;
13081         }
13082       break;
13083     }
13084   obstack_free (&mips_operand_tokens, tokens);
13085 }
13086
13087 /* As for mips_ip, but used when assembling MIPS16 code.
13088    Also set forced_insn_length to the resulting instruction size in
13089    bytes if the user explicitly requested a small or extended instruction.  */
13090
13091 static void
13092 mips16_ip (char *str, struct mips_cl_insn *ip)
13093 {
13094   char *end, *s, c;
13095   struct mips_opcode *insn, *first;
13096   struct mips_operand_token *tokens;
13097
13098   forced_insn_length = 0;
13099
13100   for (s = str; ISLOWER (*s); ++s)
13101     ;
13102   end = s;
13103   c = *end;
13104   switch (c)
13105     {
13106     case '\0':
13107       break;
13108
13109     case ' ':
13110       s++;
13111       break;
13112
13113     case '.':
13114       if (s[1] == 't' && s[2] == ' ')
13115         {
13116           forced_insn_length = 2;
13117           s += 3;
13118           break;
13119         }
13120       else if (s[1] == 'e' && s[2] == ' ')
13121         {
13122           forced_insn_length = 4;
13123           s += 3;
13124           break;
13125         }
13126       /* Fall through.  */
13127     default:
13128       set_insn_error (0, _("Unrecognized opcode"));
13129       return;
13130     }
13131
13132   if (mips_opts.noautoextend && !forced_insn_length)
13133     forced_insn_length = 2;
13134
13135   *end = 0;
13136   first = insn = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13137   *end = c;
13138
13139   if (!insn)
13140     {
13141       set_insn_error (0, _("Unrecognized opcode"));
13142       return;
13143     }
13144
13145   tokens = mips_parse_arguments (s, 0);
13146   if (!tokens)
13147     return;
13148
13149   for (;;)
13150     {
13151       bfd_boolean ok;
13152       bfd_boolean more_alts;
13153
13154       gas_assert (strcmp (insn->name, first->name) == 0);
13155
13156       ok = is_opcode_valid_16 (insn);
13157       more_alts = (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
13158                    && strcmp (insn[0].name, insn[1].name) == 0);
13159       if (! ok)
13160         {
13161           if (more_alts)
13162             {
13163               ++insn;
13164               continue;
13165             }
13166           else
13167             {
13168               set_insn_error_ss
13169                 (0, _("Opcode not supported on this processor: %s (%s)"),
13170                  mips_cpu_info_from_arch (mips_opts.arch)->name,
13171                  mips_cpu_info_from_isa (mips_opts.isa)->name);
13172               break;
13173             }
13174         }
13175
13176       if (match_mips16_insn (ip, insn, tokens))
13177         break;
13178
13179       /* Args don't match.  */
13180       set_insn_error (0, _("Illegal operands"));
13181       if (more_alts)
13182         {
13183           ++insn;
13184           continue;
13185         }
13186       break;
13187     }
13188   obstack_free (&mips_operand_tokens, tokens);
13189 }
13190
13191 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13192    NBITS is the number of significant bits in VAL.  */
13193
13194 static unsigned long
13195 mips16_immed_extend (offsetT val, unsigned int nbits)
13196 {
13197   int extval;
13198   if (nbits == 16)
13199     {
13200       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13201       val &= 0x1f;
13202     }
13203   else if (nbits == 15)
13204     {
13205       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13206       val &= 0xf;
13207     }
13208   else
13209     {
13210       extval = ((val & 0x1f) << 6) | (val & 0x20);
13211       val = 0;
13212     }
13213   return (extval << 16) | val;
13214 }
13215
13216 /* Like decode_mips16_operand, but require the operand to be defined and
13217    require it to be an integer.  */
13218
13219 static const struct mips_int_operand *
13220 mips16_immed_operand (int type, bfd_boolean extended_p)
13221 {
13222   const struct mips_operand *operand;
13223
13224   operand = decode_mips16_operand (type, extended_p);
13225   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13226     abort ();
13227   return (const struct mips_int_operand *) operand;
13228 }
13229
13230 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13231
13232 static bfd_boolean
13233 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13234                          bfd_reloc_code_real_type reloc, offsetT sval)
13235 {
13236   int min_val, max_val;
13237
13238   min_val = mips_int_operand_min (operand);
13239   max_val = mips_int_operand_max (operand);
13240   if (reloc != BFD_RELOC_UNUSED)
13241     {
13242       if (min_val < 0)
13243         sval = SEXT_16BIT (sval);
13244       else
13245         sval &= 0xffff;
13246     }
13247
13248   return (sval >= min_val
13249           && sval <= max_val
13250           && (sval & ((1 << operand->shift) - 1)) == 0);
13251 }
13252
13253 /* Install immediate value VAL into MIPS16 instruction *INSN,
13254    extending it if necessary.  The instruction in *INSN may
13255    already be extended.
13256
13257    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13258    if none.  In the former case, VAL is a 16-bit number with no
13259    defined signedness.
13260
13261    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13262    is the length that the user requested, or 0 if none.  */
13263
13264 static void
13265 mips16_immed (char *file, unsigned int line, int type,
13266               bfd_reloc_code_real_type reloc, offsetT val,
13267               unsigned int user_insn_length, unsigned long *insn)
13268 {
13269   const struct mips_int_operand *operand;
13270   unsigned int uval, length;
13271
13272   operand = mips16_immed_operand (type, FALSE);
13273   if (!mips16_immed_in_range_p (operand, reloc, val))
13274     {
13275       /* We need an extended instruction.  */
13276       if (user_insn_length == 2)
13277         as_bad_where (file, line, _("invalid unextended operand value"));
13278       else
13279         *insn |= MIPS16_EXTEND;
13280     }
13281   else if (user_insn_length == 4)
13282     {
13283       /* The operand doesn't force an unextended instruction to be extended.
13284          Warn if the user wanted an extended instruction anyway.  */
13285       *insn |= MIPS16_EXTEND;
13286       as_warn_where (file, line,
13287                      _("extended operand requested but not required"));
13288     }
13289
13290   length = mips16_opcode_length (*insn);
13291   if (length == 4)
13292     {
13293       operand = mips16_immed_operand (type, TRUE);
13294       if (!mips16_immed_in_range_p (operand, reloc, val))
13295         as_bad_where (file, line,
13296                       _("operand value out of range for instruction"));
13297     }
13298   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13299   if (length == 2)
13300     *insn = mips_insert_operand (&operand->root, *insn, uval);
13301   else
13302     *insn |= mips16_immed_extend (uval, operand->root.size);
13303 }
13304 \f
13305 struct percent_op_match
13306 {
13307   const char *str;
13308   bfd_reloc_code_real_type reloc;
13309 };
13310
13311 static const struct percent_op_match mips_percent_op[] =
13312 {
13313   {"%lo", BFD_RELOC_LO16},
13314   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13315   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13316   {"%call16", BFD_RELOC_MIPS_CALL16},
13317   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13318   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13319   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13320   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13321   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13322   {"%got", BFD_RELOC_MIPS_GOT16},
13323   {"%gp_rel", BFD_RELOC_GPREL16},
13324   {"%half", BFD_RELOC_16},
13325   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13326   {"%higher", BFD_RELOC_MIPS_HIGHER},
13327   {"%neg", BFD_RELOC_MIPS_SUB},
13328   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13329   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13330   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13331   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13332   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13333   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13334   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13335   {"%hi", BFD_RELOC_HI16_S}
13336 };
13337
13338 static const struct percent_op_match mips16_percent_op[] =
13339 {
13340   {"%lo", BFD_RELOC_MIPS16_LO16},
13341   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13342   {"%got", BFD_RELOC_MIPS16_GOT16},
13343   {"%call16", BFD_RELOC_MIPS16_CALL16},
13344   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13345   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13346   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13347   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13348   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13349   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13350   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13351   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13352 };
13353
13354
13355 /* Return true if *STR points to a relocation operator.  When returning true,
13356    move *STR over the operator and store its relocation code in *RELOC.
13357    Leave both *STR and *RELOC alone when returning false.  */
13358
13359 static bfd_boolean
13360 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13361 {
13362   const struct percent_op_match *percent_op;
13363   size_t limit, i;
13364
13365   if (mips_opts.mips16)
13366     {
13367       percent_op = mips16_percent_op;
13368       limit = ARRAY_SIZE (mips16_percent_op);
13369     }
13370   else
13371     {
13372       percent_op = mips_percent_op;
13373       limit = ARRAY_SIZE (mips_percent_op);
13374     }
13375
13376   for (i = 0; i < limit; i++)
13377     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13378       {
13379         int len = strlen (percent_op[i].str);
13380
13381         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13382           continue;
13383
13384         *str += strlen (percent_op[i].str);
13385         *reloc = percent_op[i].reloc;
13386
13387         /* Check whether the output BFD supports this relocation.
13388            If not, issue an error and fall back on something safe.  */
13389         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13390           {
13391             as_bad (_("relocation %s isn't supported by the current ABI"),
13392                     percent_op[i].str);
13393             *reloc = BFD_RELOC_UNUSED;
13394           }
13395         return TRUE;
13396       }
13397   return FALSE;
13398 }
13399
13400
13401 /* Parse string STR as a 16-bit relocatable operand.  Store the
13402    expression in *EP and the relocations in the array starting
13403    at RELOC.  Return the number of relocation operators used.
13404
13405    On exit, EXPR_END points to the first character after the expression.  */
13406
13407 static size_t
13408 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13409                        char *str)
13410 {
13411   bfd_reloc_code_real_type reversed_reloc[3];
13412   size_t reloc_index, i;
13413   int crux_depth, str_depth;
13414   char *crux;
13415
13416   /* Search for the start of the main expression, recoding relocations
13417      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13418      of the main expression and with CRUX_DEPTH containing the number
13419      of open brackets at that point.  */
13420   reloc_index = -1;
13421   str_depth = 0;
13422   do
13423     {
13424       reloc_index++;
13425       crux = str;
13426       crux_depth = str_depth;
13427
13428       /* Skip over whitespace and brackets, keeping count of the number
13429          of brackets.  */
13430       while (*str == ' ' || *str == '\t' || *str == '(')
13431         if (*str++ == '(')
13432           str_depth++;
13433     }
13434   while (*str == '%'
13435          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13436          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13437
13438   my_getExpression (ep, crux);
13439   str = expr_end;
13440
13441   /* Match every open bracket.  */
13442   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13443     if (*str++ == ')')
13444       crux_depth--;
13445
13446   if (crux_depth > 0)
13447     as_bad (_("unclosed '('"));
13448
13449   expr_end = str;
13450
13451   if (reloc_index != 0)
13452     {
13453       prev_reloc_op_frag = frag_now;
13454       for (i = 0; i < reloc_index; i++)
13455         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13456     }
13457
13458   return reloc_index;
13459 }
13460
13461 static void
13462 my_getExpression (expressionS *ep, char *str)
13463 {
13464   char *save_in;
13465
13466   save_in = input_line_pointer;
13467   input_line_pointer = str;
13468   expression (ep);
13469   expr_end = input_line_pointer;
13470   input_line_pointer = save_in;
13471 }
13472
13473 char *
13474 md_atof (int type, char *litP, int *sizeP)
13475 {
13476   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13477 }
13478
13479 void
13480 md_number_to_chars (char *buf, valueT val, int n)
13481 {
13482   if (target_big_endian)
13483     number_to_chars_bigendian (buf, val, n);
13484   else
13485     number_to_chars_littleendian (buf, val, n);
13486 }
13487 \f
13488 static int support_64bit_objects(void)
13489 {
13490   const char **list, **l;
13491   int yes;
13492
13493   list = bfd_target_list ();
13494   for (l = list; *l != NULL; l++)
13495     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13496         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13497       break;
13498   yes = (*l != NULL);
13499   free (list);
13500   return yes;
13501 }
13502
13503 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13504    NEW_VALUE.  Warn if another value was already specified.  Note:
13505    we have to defer parsing the -march and -mtune arguments in order
13506    to handle 'from-abi' correctly, since the ABI might be specified
13507    in a later argument.  */
13508
13509 static void
13510 mips_set_option_string (const char **string_ptr, const char *new_value)
13511 {
13512   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13513     as_warn (_("A different %s was already specified, is now %s"),
13514              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13515              new_value);
13516
13517   *string_ptr = new_value;
13518 }
13519
13520 int
13521 md_parse_option (int c, char *arg)
13522 {
13523   unsigned int i;
13524
13525   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13526     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13527       {
13528         file_ase_explicit |= mips_set_ase (&mips_ases[i],
13529                                            c == mips_ases[i].option_on);
13530         return 1;
13531       }
13532
13533   switch (c)
13534     {
13535     case OPTION_CONSTRUCT_FLOATS:
13536       mips_disable_float_construction = 0;
13537       break;
13538
13539     case OPTION_NO_CONSTRUCT_FLOATS:
13540       mips_disable_float_construction = 1;
13541       break;
13542
13543     case OPTION_TRAP:
13544       mips_trap = 1;
13545       break;
13546
13547     case OPTION_BREAK:
13548       mips_trap = 0;
13549       break;
13550
13551     case OPTION_EB:
13552       target_big_endian = 1;
13553       break;
13554
13555     case OPTION_EL:
13556       target_big_endian = 0;
13557       break;
13558
13559     case 'O':
13560       if (arg == NULL)
13561         mips_optimize = 1;
13562       else if (arg[0] == '0')
13563         mips_optimize = 0;
13564       else if (arg[0] == '1')
13565         mips_optimize = 1;
13566       else
13567         mips_optimize = 2;
13568       break;
13569
13570     case 'g':
13571       if (arg == NULL)
13572         mips_debug = 2;
13573       else
13574         mips_debug = atoi (arg);
13575       break;
13576
13577     case OPTION_MIPS1:
13578       file_mips_isa = ISA_MIPS1;
13579       break;
13580
13581     case OPTION_MIPS2:
13582       file_mips_isa = ISA_MIPS2;
13583       break;
13584
13585     case OPTION_MIPS3:
13586       file_mips_isa = ISA_MIPS3;
13587       break;
13588
13589     case OPTION_MIPS4:
13590       file_mips_isa = ISA_MIPS4;
13591       break;
13592
13593     case OPTION_MIPS5:
13594       file_mips_isa = ISA_MIPS5;
13595       break;
13596
13597     case OPTION_MIPS32:
13598       file_mips_isa = ISA_MIPS32;
13599       break;
13600
13601     case OPTION_MIPS32R2:
13602       file_mips_isa = ISA_MIPS32R2;
13603       break;
13604
13605     case OPTION_MIPS64R2:
13606       file_mips_isa = ISA_MIPS64R2;
13607       break;
13608
13609     case OPTION_MIPS64:
13610       file_mips_isa = ISA_MIPS64;
13611       break;
13612
13613     case OPTION_MTUNE:
13614       mips_set_option_string (&mips_tune_string, arg);
13615       break;
13616
13617     case OPTION_MARCH:
13618       mips_set_option_string (&mips_arch_string, arg);
13619       break;
13620
13621     case OPTION_M4650:
13622       mips_set_option_string (&mips_arch_string, "4650");
13623       mips_set_option_string (&mips_tune_string, "4650");
13624       break;
13625
13626     case OPTION_NO_M4650:
13627       break;
13628
13629     case OPTION_M4010:
13630       mips_set_option_string (&mips_arch_string, "4010");
13631       mips_set_option_string (&mips_tune_string, "4010");
13632       break;
13633
13634     case OPTION_NO_M4010:
13635       break;
13636
13637     case OPTION_M4100:
13638       mips_set_option_string (&mips_arch_string, "4100");
13639       mips_set_option_string (&mips_tune_string, "4100");
13640       break;
13641
13642     case OPTION_NO_M4100:
13643       break;
13644
13645     case OPTION_M3900:
13646       mips_set_option_string (&mips_arch_string, "3900");
13647       mips_set_option_string (&mips_tune_string, "3900");
13648       break;
13649
13650     case OPTION_NO_M3900:
13651       break;
13652
13653     case OPTION_MICROMIPS:
13654       if (mips_opts.mips16 == 1)
13655         {
13656           as_bad (_("-mmicromips cannot be used with -mips16"));
13657           return 0;
13658         }
13659       mips_opts.micromips = 1;
13660       mips_no_prev_insn ();
13661       break;
13662
13663     case OPTION_NO_MICROMIPS:
13664       mips_opts.micromips = 0;
13665       mips_no_prev_insn ();
13666       break;
13667
13668     case OPTION_MIPS16:
13669       if (mips_opts.micromips == 1)
13670         {
13671           as_bad (_("-mips16 cannot be used with -micromips"));
13672           return 0;
13673         }
13674       mips_opts.mips16 = 1;
13675       mips_no_prev_insn ();
13676       break;
13677
13678     case OPTION_NO_MIPS16:
13679       mips_opts.mips16 = 0;
13680       mips_no_prev_insn ();
13681       break;
13682
13683     case OPTION_FIX_24K:
13684       mips_fix_24k = 1;
13685       break;
13686
13687     case OPTION_NO_FIX_24K:
13688       mips_fix_24k = 0;
13689       break;
13690
13691     case OPTION_FIX_LOONGSON2F_JUMP:
13692       mips_fix_loongson2f_jump = TRUE;
13693       break;
13694
13695     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13696       mips_fix_loongson2f_jump = FALSE;
13697       break;
13698
13699     case OPTION_FIX_LOONGSON2F_NOP:
13700       mips_fix_loongson2f_nop = TRUE;
13701       break;
13702
13703     case OPTION_NO_FIX_LOONGSON2F_NOP:
13704       mips_fix_loongson2f_nop = FALSE;
13705       break;
13706
13707     case OPTION_FIX_VR4120:
13708       mips_fix_vr4120 = 1;
13709       break;
13710
13711     case OPTION_NO_FIX_VR4120:
13712       mips_fix_vr4120 = 0;
13713       break;
13714
13715     case OPTION_FIX_VR4130:
13716       mips_fix_vr4130 = 1;
13717       break;
13718
13719     case OPTION_NO_FIX_VR4130:
13720       mips_fix_vr4130 = 0;
13721       break;
13722
13723     case OPTION_FIX_CN63XXP1:
13724       mips_fix_cn63xxp1 = TRUE;
13725       break;
13726
13727     case OPTION_NO_FIX_CN63XXP1:
13728       mips_fix_cn63xxp1 = FALSE;
13729       break;
13730
13731     case OPTION_RELAX_BRANCH:
13732       mips_relax_branch = 1;
13733       break;
13734
13735     case OPTION_NO_RELAX_BRANCH:
13736       mips_relax_branch = 0;
13737       break;
13738
13739     case OPTION_INSN32:
13740       mips_opts.insn32 = TRUE;
13741       break;
13742
13743     case OPTION_NO_INSN32:
13744       mips_opts.insn32 = FALSE;
13745       break;
13746
13747     case OPTION_MSHARED:
13748       mips_in_shared = TRUE;
13749       break;
13750
13751     case OPTION_MNO_SHARED:
13752       mips_in_shared = FALSE;
13753       break;
13754
13755     case OPTION_MSYM32:
13756       mips_opts.sym32 = TRUE;
13757       break;
13758
13759     case OPTION_MNO_SYM32:
13760       mips_opts.sym32 = FALSE;
13761       break;
13762
13763       /* When generating ELF code, we permit -KPIC and -call_shared to
13764          select SVR4_PIC, and -non_shared to select no PIC.  This is
13765          intended to be compatible with Irix 5.  */
13766     case OPTION_CALL_SHARED:
13767       mips_pic = SVR4_PIC;
13768       mips_abicalls = TRUE;
13769       break;
13770
13771     case OPTION_CALL_NONPIC:
13772       mips_pic = NO_PIC;
13773       mips_abicalls = TRUE;
13774       break;
13775
13776     case OPTION_NON_SHARED:
13777       mips_pic = NO_PIC;
13778       mips_abicalls = FALSE;
13779       break;
13780
13781       /* The -xgot option tells the assembler to use 32 bit offsets
13782          when accessing the got in SVR4_PIC mode.  It is for Irix
13783          compatibility.  */
13784     case OPTION_XGOT:
13785       mips_big_got = 1;
13786       break;
13787
13788     case 'G':
13789       g_switch_value = atoi (arg);
13790       g_switch_seen = 1;
13791       break;
13792
13793       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13794          and -mabi=64.  */
13795     case OPTION_32:
13796       mips_abi = O32_ABI;
13797       break;
13798
13799     case OPTION_N32:
13800       mips_abi = N32_ABI;
13801       break;
13802
13803     case OPTION_64:
13804       mips_abi = N64_ABI;
13805       if (!support_64bit_objects())
13806         as_fatal (_("No compiled in support for 64 bit object file format"));
13807       break;
13808
13809     case OPTION_GP32:
13810       file_mips_gp32 = 1;
13811       break;
13812
13813     case OPTION_GP64:
13814       file_mips_gp32 = 0;
13815       break;
13816
13817     case OPTION_FP32:
13818       file_mips_fp32 = 1;
13819       break;
13820
13821     case OPTION_FP64:
13822       file_mips_fp32 = 0;
13823       break;
13824
13825     case OPTION_SINGLE_FLOAT:
13826       file_mips_single_float = 1;
13827       break;
13828
13829     case OPTION_DOUBLE_FLOAT:
13830       file_mips_single_float = 0;
13831       break;
13832
13833     case OPTION_SOFT_FLOAT:
13834       file_mips_soft_float = 1;
13835       break;
13836
13837     case OPTION_HARD_FLOAT:
13838       file_mips_soft_float = 0;
13839       break;
13840
13841     case OPTION_MABI:
13842       if (strcmp (arg, "32") == 0)
13843         mips_abi = O32_ABI;
13844       else if (strcmp (arg, "o64") == 0)
13845         mips_abi = O64_ABI;
13846       else if (strcmp (arg, "n32") == 0)
13847         mips_abi = N32_ABI;
13848       else if (strcmp (arg, "64") == 0)
13849         {
13850           mips_abi = N64_ABI;
13851           if (! support_64bit_objects())
13852             as_fatal (_("No compiled in support for 64 bit object file "
13853                         "format"));
13854         }
13855       else if (strcmp (arg, "eabi") == 0)
13856         mips_abi = EABI_ABI;
13857       else
13858         {
13859           as_fatal (_("invalid abi -mabi=%s"), arg);
13860           return 0;
13861         }
13862       break;
13863
13864     case OPTION_M7000_HILO_FIX:
13865       mips_7000_hilo_fix = TRUE;
13866       break;
13867
13868     case OPTION_MNO_7000_HILO_FIX:
13869       mips_7000_hilo_fix = FALSE;
13870       break;
13871
13872     case OPTION_MDEBUG:
13873       mips_flag_mdebug = TRUE;
13874       break;
13875
13876     case OPTION_NO_MDEBUG:
13877       mips_flag_mdebug = FALSE;
13878       break;
13879
13880     case OPTION_PDR:
13881       mips_flag_pdr = TRUE;
13882       break;
13883
13884     case OPTION_NO_PDR:
13885       mips_flag_pdr = FALSE;
13886       break;
13887
13888     case OPTION_MVXWORKS_PIC:
13889       mips_pic = VXWORKS_PIC;
13890       break;
13891
13892     case OPTION_NAN:
13893       if (strcmp (arg, "2008") == 0)
13894         mips_flag_nan2008 = TRUE;
13895       else if (strcmp (arg, "legacy") == 0)
13896         mips_flag_nan2008 = FALSE;
13897       else
13898         {
13899           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
13900           return 0;
13901         }
13902       break;
13903
13904     default:
13905       return 0;
13906     }
13907
13908     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13909
13910   return 1;
13911 }
13912 \f
13913 /* Set up globals to generate code for the ISA or processor
13914    described by INFO.  */
13915
13916 static void
13917 mips_set_architecture (const struct mips_cpu_info *info)
13918 {
13919   if (info != 0)
13920     {
13921       file_mips_arch = info->cpu;
13922       mips_opts.arch = info->cpu;
13923       mips_opts.isa = info->isa;
13924     }
13925 }
13926
13927
13928 /* Likewise for tuning.  */
13929
13930 static void
13931 mips_set_tune (const struct mips_cpu_info *info)
13932 {
13933   if (info != 0)
13934     mips_tune = info->cpu;
13935 }
13936
13937
13938 void
13939 mips_after_parse_args (void)
13940 {
13941   const struct mips_cpu_info *arch_info = 0;
13942   const struct mips_cpu_info *tune_info = 0;
13943
13944   /* GP relative stuff not working for PE */
13945   if (strncmp (TARGET_OS, "pe", 2) == 0)
13946     {
13947       if (g_switch_seen && g_switch_value != 0)
13948         as_bad (_("-G not supported in this configuration."));
13949       g_switch_value = 0;
13950     }
13951
13952   if (mips_abi == NO_ABI)
13953     mips_abi = MIPS_DEFAULT_ABI;
13954
13955   /* The following code determines the architecture and register size.
13956      Similar code was added to GCC 3.3 (see override_options() in
13957      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13958      as much as possible.  */
13959
13960   if (mips_arch_string != 0)
13961     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13962
13963   if (file_mips_isa != ISA_UNKNOWN)
13964     {
13965       /* Handle -mipsN.  At this point, file_mips_isa contains the
13966          ISA level specified by -mipsN, while arch_info->isa contains
13967          the -march selection (if any).  */
13968       if (arch_info != 0)
13969         {
13970           /* -march takes precedence over -mipsN, since it is more descriptive.
13971              There's no harm in specifying both as long as the ISA levels
13972              are the same.  */
13973           if (file_mips_isa != arch_info->isa)
13974             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
13975                     mips_cpu_info_from_isa (file_mips_isa)->name,
13976                     mips_cpu_info_from_isa (arch_info->isa)->name);
13977         }
13978       else
13979         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13980     }
13981
13982   if (arch_info == 0)
13983     {
13984       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13985       gas_assert (arch_info);
13986     }
13987
13988   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13989     as_bad (_("-march=%s is not compatible with the selected ABI"),
13990             arch_info->name);
13991
13992   mips_set_architecture (arch_info);
13993
13994   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13995   if (mips_tune_string != 0)
13996     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13997
13998   if (tune_info == 0)
13999     mips_set_tune (arch_info);
14000   else
14001     mips_set_tune (tune_info);
14002
14003   if (file_mips_gp32 >= 0)
14004     {
14005       /* The user specified the size of the integer registers.  Make sure
14006          it agrees with the ABI and ISA.  */
14007       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
14008         as_bad (_("-mgp64 used with a 32-bit processor"));
14009       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
14010         as_bad (_("-mgp32 used with a 64-bit ABI"));
14011       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
14012         as_bad (_("-mgp64 used with a 32-bit ABI"));
14013     }
14014   else
14015     {
14016       /* Infer the integer register size from the ABI and processor.
14017          Restrict ourselves to 32-bit registers if that's all the
14018          processor has, or if the ABI cannot handle 64-bit registers.  */
14019       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
14020                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
14021     }
14022
14023   switch (file_mips_fp32)
14024     {
14025     default:
14026     case -1:
14027       /* No user specified float register size.
14028          ??? GAS treats single-float processors as though they had 64-bit
14029          float registers (although it complains when double-precision
14030          instructions are used).  As things stand, saying they have 32-bit
14031          registers would lead to spurious "register must be even" messages.
14032          So here we assume float registers are never smaller than the
14033          integer ones.  */
14034       if (file_mips_gp32 == 0)
14035         /* 64-bit integer registers implies 64-bit float registers.  */
14036         file_mips_fp32 = 0;
14037       else if ((mips_opts.ase & FP64_ASES)
14038                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
14039         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
14040         file_mips_fp32 = 0;
14041       else
14042         /* 32-bit float registers.  */
14043         file_mips_fp32 = 1;
14044       break;
14045
14046     /* The user specified the size of the float registers.  Check if it
14047        agrees with the ABI and ISA.  */
14048     case 0:
14049       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14050         as_bad (_("-mfp64 used with a 32-bit fpu"));
14051       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
14052                && !ISA_HAS_MXHC1 (mips_opts.isa))
14053         as_warn (_("-mfp64 used with a 32-bit ABI"));
14054       break;
14055     case 1:
14056       if (ABI_NEEDS_64BIT_REGS (mips_abi))
14057         as_warn (_("-mfp32 used with a 64-bit ABI"));
14058       break;
14059     }
14060
14061   /* End of GCC-shared inference code.  */
14062
14063   /* This flag is set when we have a 64-bit capable CPU but use only
14064      32-bit wide registers.  Note that EABI does not use it.  */
14065   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
14066       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
14067           || mips_abi == O32_ABI))
14068     mips_32bitmode = 1;
14069
14070   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
14071     as_bad (_("trap exception not supported at ISA 1"));
14072
14073   /* If the selected architecture includes support for ASEs, enable
14074      generation of code for them.  */
14075   if (mips_opts.mips16 == -1)
14076     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
14077   if (mips_opts.micromips == -1)
14078     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
14079
14080   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
14081      ASEs from being selected implicitly.  */
14082   if (file_mips_fp32 == 1)
14083     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
14084
14085   /* If the user didn't explicitly select or deselect a particular ASE,
14086      use the default setting for the CPU.  */
14087   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
14088
14089   file_mips_isa = mips_opts.isa;
14090   file_ase = mips_opts.ase;
14091   mips_opts.gp32 = file_mips_gp32;
14092   mips_opts.fp32 = file_mips_fp32;
14093   mips_opts.soft_float = file_mips_soft_float;
14094   mips_opts.single_float = file_mips_single_float;
14095
14096   mips_check_isa_supports_ases ();
14097
14098   if (mips_flag_mdebug < 0)
14099     mips_flag_mdebug = 0;
14100 }
14101 \f
14102 void
14103 mips_init_after_args (void)
14104 {
14105   /* initialize opcodes */
14106   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14107   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14108 }
14109
14110 long
14111 md_pcrel_from (fixS *fixP)
14112 {
14113   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14114   switch (fixP->fx_r_type)
14115     {
14116     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14117     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14118       /* Return the address of the delay slot.  */
14119       return addr + 2;
14120
14121     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14122     case BFD_RELOC_MICROMIPS_JMP:
14123     case BFD_RELOC_16_PCREL_S2:
14124     case BFD_RELOC_MIPS_JMP:
14125       /* Return the address of the delay slot.  */
14126       return addr + 4;
14127
14128     case BFD_RELOC_32_PCREL:
14129       return addr;
14130
14131     default:
14132       /* We have no relocation type for PC relative MIPS16 instructions.  */
14133       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
14134         as_bad_where (fixP->fx_file, fixP->fx_line,
14135                       _("PC relative MIPS16 instruction references a different section"));
14136       return addr;
14137     }
14138 }
14139
14140 /* This is called before the symbol table is processed.  In order to
14141    work with gcc when using mips-tfile, we must keep all local labels.
14142    However, in other cases, we want to discard them.  If we were
14143    called with -g, but we didn't see any debugging information, it may
14144    mean that gcc is smuggling debugging information through to
14145    mips-tfile, in which case we must generate all local labels.  */
14146
14147 void
14148 mips_frob_file_before_adjust (void)
14149 {
14150 #ifndef NO_ECOFF_DEBUGGING
14151   if (ECOFF_DEBUGGING
14152       && mips_debug != 0
14153       && ! ecoff_debugging_seen)
14154     flag_keep_locals = 1;
14155 #endif
14156 }
14157
14158 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14159    the corresponding LO16 reloc.  This is called before md_apply_fix and
14160    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14161    relocation operators.
14162
14163    For our purposes, a %lo() expression matches a %got() or %hi()
14164    expression if:
14165
14166       (a) it refers to the same symbol; and
14167       (b) the offset applied in the %lo() expression is no lower than
14168           the offset applied in the %got() or %hi().
14169
14170    (b) allows us to cope with code like:
14171
14172         lui     $4,%hi(foo)
14173         lh      $4,%lo(foo+2)($4)
14174
14175    ...which is legal on RELA targets, and has a well-defined behaviour
14176    if the user knows that adding 2 to "foo" will not induce a carry to
14177    the high 16 bits.
14178
14179    When several %lo()s match a particular %got() or %hi(), we use the
14180    following rules to distinguish them:
14181
14182      (1) %lo()s with smaller offsets are a better match than %lo()s with
14183          higher offsets.
14184
14185      (2) %lo()s with no matching %got() or %hi() are better than those
14186          that already have a matching %got() or %hi().
14187
14188      (3) later %lo()s are better than earlier %lo()s.
14189
14190    These rules are applied in order.
14191
14192    (1) means, among other things, that %lo()s with identical offsets are
14193    chosen if they exist.
14194
14195    (2) means that we won't associate several high-part relocations with
14196    the same low-part relocation unless there's no alternative.  Having
14197    several high parts for the same low part is a GNU extension; this rule
14198    allows careful users to avoid it.
14199
14200    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14201    with the last high-part relocation being at the front of the list.
14202    It therefore makes sense to choose the last matching low-part
14203    relocation, all other things being equal.  It's also easier
14204    to code that way.  */
14205
14206 void
14207 mips_frob_file (void)
14208 {
14209   struct mips_hi_fixup *l;
14210   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14211
14212   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14213     {
14214       segment_info_type *seginfo;
14215       bfd_boolean matched_lo_p;
14216       fixS **hi_pos, **lo_pos, **pos;
14217
14218       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14219
14220       /* If a GOT16 relocation turns out to be against a global symbol,
14221          there isn't supposed to be a matching LO.  Ignore %gots against
14222          constants; we'll report an error for those later.  */
14223       if (got16_reloc_p (l->fixp->fx_r_type)
14224           && !(l->fixp->fx_addsy
14225                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14226         continue;
14227
14228       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14229       if (fixup_has_matching_lo_p (l->fixp))
14230         continue;
14231
14232       seginfo = seg_info (l->seg);
14233
14234       /* Set HI_POS to the position of this relocation in the chain.
14235          Set LO_POS to the position of the chosen low-part relocation.
14236          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14237          relocation that matches an immediately-preceding high-part
14238          relocation.  */
14239       hi_pos = NULL;
14240       lo_pos = NULL;
14241       matched_lo_p = FALSE;
14242       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14243
14244       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14245         {
14246           if (*pos == l->fixp)
14247             hi_pos = pos;
14248
14249           if ((*pos)->fx_r_type == looking_for_rtype
14250               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14251               && (*pos)->fx_offset >= l->fixp->fx_offset
14252               && (lo_pos == NULL
14253                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14254                   || (!matched_lo_p
14255                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14256             lo_pos = pos;
14257
14258           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14259                           && fixup_has_matching_lo_p (*pos));
14260         }
14261
14262       /* If we found a match, remove the high-part relocation from its
14263          current position and insert it before the low-part relocation.
14264          Make the offsets match so that fixup_has_matching_lo_p()
14265          will return true.
14266
14267          We don't warn about unmatched high-part relocations since some
14268          versions of gcc have been known to emit dead "lui ...%hi(...)"
14269          instructions.  */
14270       if (lo_pos != NULL)
14271         {
14272           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14273           if (l->fixp->fx_next != *lo_pos)
14274             {
14275               *hi_pos = l->fixp->fx_next;
14276               l->fixp->fx_next = *lo_pos;
14277               *lo_pos = l->fixp;
14278             }
14279         }
14280     }
14281 }
14282
14283 int
14284 mips_force_relocation (fixS *fixp)
14285 {
14286   if (generic_force_reloc (fixp))
14287     return 1;
14288
14289   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14290      so that the linker relaxation can update targets.  */
14291   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14292       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14293       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14294     return 1;
14295
14296   return 0;
14297 }
14298
14299 /* Read the instruction associated with RELOC from BUF.  */
14300
14301 static unsigned int
14302 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14303 {
14304   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14305     return read_compressed_insn (buf, 4);
14306   else
14307     return read_insn (buf);
14308 }
14309
14310 /* Write instruction INSN to BUF, given that it has been relocated
14311    by RELOC.  */
14312
14313 static void
14314 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14315                   unsigned long insn)
14316 {
14317   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14318     write_compressed_insn (buf, insn, 4);
14319   else
14320     write_insn (buf, insn);
14321 }
14322
14323 /* Apply a fixup to the object file.  */
14324
14325 void
14326 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14327 {
14328   char *buf;
14329   unsigned long insn;
14330   reloc_howto_type *howto;
14331
14332   /* We ignore generic BFD relocations we don't know about.  */
14333   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14334   if (! howto)
14335     return;
14336
14337   gas_assert (fixP->fx_size == 2
14338               || fixP->fx_size == 4
14339               || fixP->fx_r_type == BFD_RELOC_16
14340               || fixP->fx_r_type == BFD_RELOC_64
14341               || fixP->fx_r_type == BFD_RELOC_CTOR
14342               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14343               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14344               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14345               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14346               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14347
14348   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14349
14350   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
14351               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14352               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14353               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
14354               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
14355
14356   /* Don't treat parts of a composite relocation as done.  There are two
14357      reasons for this:
14358
14359      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14360          should nevertheless be emitted if the first part is.
14361
14362      (2) In normal usage, composite relocations are never assembly-time
14363          constants.  The easiest way of dealing with the pathological
14364          exceptions is to generate a relocation against STN_UNDEF and
14365          leave everything up to the linker.  */
14366   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14367     fixP->fx_done = 1;
14368
14369   switch (fixP->fx_r_type)
14370     {
14371     case BFD_RELOC_MIPS_TLS_GD:
14372     case BFD_RELOC_MIPS_TLS_LDM:
14373     case BFD_RELOC_MIPS_TLS_DTPREL32:
14374     case BFD_RELOC_MIPS_TLS_DTPREL64:
14375     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14376     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14377     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14378     case BFD_RELOC_MIPS_TLS_TPREL32:
14379     case BFD_RELOC_MIPS_TLS_TPREL64:
14380     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14381     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14382     case BFD_RELOC_MICROMIPS_TLS_GD:
14383     case BFD_RELOC_MICROMIPS_TLS_LDM:
14384     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14385     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14386     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14387     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14388     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14389     case BFD_RELOC_MIPS16_TLS_GD:
14390     case BFD_RELOC_MIPS16_TLS_LDM:
14391     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14392     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14393     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14394     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14395     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14396       if (!fixP->fx_addsy)
14397         {
14398           as_bad_where (fixP->fx_file, fixP->fx_line,
14399                         _("TLS relocation against a constant"));
14400           break;
14401         }
14402       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14403       /* fall through */
14404
14405     case BFD_RELOC_MIPS_JMP:
14406     case BFD_RELOC_MIPS_SHIFT5:
14407     case BFD_RELOC_MIPS_SHIFT6:
14408     case BFD_RELOC_MIPS_GOT_DISP:
14409     case BFD_RELOC_MIPS_GOT_PAGE:
14410     case BFD_RELOC_MIPS_GOT_OFST:
14411     case BFD_RELOC_MIPS_SUB:
14412     case BFD_RELOC_MIPS_INSERT_A:
14413     case BFD_RELOC_MIPS_INSERT_B:
14414     case BFD_RELOC_MIPS_DELETE:
14415     case BFD_RELOC_MIPS_HIGHEST:
14416     case BFD_RELOC_MIPS_HIGHER:
14417     case BFD_RELOC_MIPS_SCN_DISP:
14418     case BFD_RELOC_MIPS_REL16:
14419     case BFD_RELOC_MIPS_RELGOT:
14420     case BFD_RELOC_MIPS_JALR:
14421     case BFD_RELOC_HI16:
14422     case BFD_RELOC_HI16_S:
14423     case BFD_RELOC_LO16:
14424     case BFD_RELOC_GPREL16:
14425     case BFD_RELOC_MIPS_LITERAL:
14426     case BFD_RELOC_MIPS_CALL16:
14427     case BFD_RELOC_MIPS_GOT16:
14428     case BFD_RELOC_GPREL32:
14429     case BFD_RELOC_MIPS_GOT_HI16:
14430     case BFD_RELOC_MIPS_GOT_LO16:
14431     case BFD_RELOC_MIPS_CALL_HI16:
14432     case BFD_RELOC_MIPS_CALL_LO16:
14433     case BFD_RELOC_MIPS16_GPREL:
14434     case BFD_RELOC_MIPS16_GOT16:
14435     case BFD_RELOC_MIPS16_CALL16:
14436     case BFD_RELOC_MIPS16_HI16:
14437     case BFD_RELOC_MIPS16_HI16_S:
14438     case BFD_RELOC_MIPS16_LO16:
14439     case BFD_RELOC_MIPS16_JMP:
14440     case BFD_RELOC_MICROMIPS_JMP:
14441     case BFD_RELOC_MICROMIPS_GOT_DISP:
14442     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14443     case BFD_RELOC_MICROMIPS_GOT_OFST:
14444     case BFD_RELOC_MICROMIPS_SUB:
14445     case BFD_RELOC_MICROMIPS_HIGHEST:
14446     case BFD_RELOC_MICROMIPS_HIGHER:
14447     case BFD_RELOC_MICROMIPS_SCN_DISP:
14448     case BFD_RELOC_MICROMIPS_JALR:
14449     case BFD_RELOC_MICROMIPS_HI16:
14450     case BFD_RELOC_MICROMIPS_HI16_S:
14451     case BFD_RELOC_MICROMIPS_LO16:
14452     case BFD_RELOC_MICROMIPS_GPREL16:
14453     case BFD_RELOC_MICROMIPS_LITERAL:
14454     case BFD_RELOC_MICROMIPS_CALL16:
14455     case BFD_RELOC_MICROMIPS_GOT16:
14456     case BFD_RELOC_MICROMIPS_GOT_HI16:
14457     case BFD_RELOC_MICROMIPS_GOT_LO16:
14458     case BFD_RELOC_MICROMIPS_CALL_HI16:
14459     case BFD_RELOC_MICROMIPS_CALL_LO16:
14460     case BFD_RELOC_MIPS_EH:
14461       if (fixP->fx_done)
14462         {
14463           offsetT value;
14464
14465           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14466             {
14467               insn = read_reloc_insn (buf, fixP->fx_r_type);
14468               if (mips16_reloc_p (fixP->fx_r_type))
14469                 insn |= mips16_immed_extend (value, 16);
14470               else
14471                 insn |= (value & 0xffff);
14472               write_reloc_insn (buf, fixP->fx_r_type, insn);
14473             }
14474           else
14475             as_bad_where (fixP->fx_file, fixP->fx_line,
14476                           _("Unsupported constant in relocation"));
14477         }
14478       break;
14479
14480     case BFD_RELOC_64:
14481       /* This is handled like BFD_RELOC_32, but we output a sign
14482          extended value if we are only 32 bits.  */
14483       if (fixP->fx_done)
14484         {
14485           if (8 <= sizeof (valueT))
14486             md_number_to_chars (buf, *valP, 8);
14487           else
14488             {
14489               valueT hiv;
14490
14491               if ((*valP & 0x80000000) != 0)
14492                 hiv = 0xffffffff;
14493               else
14494                 hiv = 0;
14495               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14496               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14497             }
14498         }
14499       break;
14500
14501     case BFD_RELOC_RVA:
14502     case BFD_RELOC_32:
14503     case BFD_RELOC_32_PCREL:
14504     case BFD_RELOC_16:
14505       /* If we are deleting this reloc entry, we must fill in the
14506          value now.  This can happen if we have a .word which is not
14507          resolved when it appears but is later defined.  */
14508       if (fixP->fx_done)
14509         md_number_to_chars (buf, *valP, fixP->fx_size);
14510       break;
14511
14512     case BFD_RELOC_16_PCREL_S2:
14513       if ((*valP & 0x3) != 0)
14514         as_bad_where (fixP->fx_file, fixP->fx_line,
14515                       _("Branch to misaligned address (%lx)"), (long) *valP);
14516
14517       /* We need to save the bits in the instruction since fixup_segment()
14518          might be deleting the relocation entry (i.e., a branch within
14519          the current segment).  */
14520       if (! fixP->fx_done)
14521         break;
14522
14523       /* Update old instruction data.  */
14524       insn = read_insn (buf);
14525
14526       if (*valP + 0x20000 <= 0x3ffff)
14527         {
14528           insn |= (*valP >> 2) & 0xffff;
14529           write_insn (buf, insn);
14530         }
14531       else if (mips_pic == NO_PIC
14532                && fixP->fx_done
14533                && fixP->fx_frag->fr_address >= text_section->vma
14534                && (fixP->fx_frag->fr_address
14535                    < text_section->vma + bfd_get_section_size (text_section))
14536                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14537                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14538                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14539         {
14540           /* The branch offset is too large.  If this is an
14541              unconditional branch, and we are not generating PIC code,
14542              we can convert it to an absolute jump instruction.  */
14543           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14544             insn = 0x0c000000;  /* jal */
14545           else
14546             insn = 0x08000000;  /* j */
14547           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14548           fixP->fx_done = 0;
14549           fixP->fx_addsy = section_symbol (text_section);
14550           *valP += md_pcrel_from (fixP);
14551           write_insn (buf, insn);
14552         }
14553       else
14554         {
14555           /* If we got here, we have branch-relaxation disabled,
14556              and there's nothing we can do to fix this instruction
14557              without turning it into a longer sequence.  */
14558           as_bad_where (fixP->fx_file, fixP->fx_line,
14559                         _("Branch out of range"));
14560         }
14561       break;
14562
14563     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14564     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14565     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14566       /* We adjust the offset back to even.  */
14567       if ((*valP & 0x1) != 0)
14568         --(*valP);
14569
14570       if (! fixP->fx_done)
14571         break;
14572
14573       /* Should never visit here, because we keep the relocation.  */
14574       abort ();
14575       break;
14576
14577     case BFD_RELOC_VTABLE_INHERIT:
14578       fixP->fx_done = 0;
14579       if (fixP->fx_addsy
14580           && !S_IS_DEFINED (fixP->fx_addsy)
14581           && !S_IS_WEAK (fixP->fx_addsy))
14582         S_SET_WEAK (fixP->fx_addsy);
14583       break;
14584
14585     case BFD_RELOC_VTABLE_ENTRY:
14586       fixP->fx_done = 0;
14587       break;
14588
14589     default:
14590       abort ();
14591     }
14592
14593   /* Remember value for tc_gen_reloc.  */
14594   fixP->fx_addnumber = *valP;
14595 }
14596
14597 static symbolS *
14598 get_symbol (void)
14599 {
14600   int c;
14601   char *name;
14602   symbolS *p;
14603
14604   name = input_line_pointer;
14605   c = get_symbol_end ();
14606   p = (symbolS *) symbol_find_or_make (name);
14607   *input_line_pointer = c;
14608   return p;
14609 }
14610
14611 /* Align the current frag to a given power of two.  If a particular
14612    fill byte should be used, FILL points to an integer that contains
14613    that byte, otherwise FILL is null.
14614
14615    This function used to have the comment:
14616
14617       The MIPS assembler also automatically adjusts any preceding label.
14618
14619    The implementation therefore applied the adjustment to a maximum of
14620    one label.  However, other label adjustments are applied to batches
14621    of labels, and adjusting just one caused problems when new labels
14622    were added for the sake of debugging or unwind information.
14623    We therefore adjust all preceding labels (given as LABELS) instead.  */
14624
14625 static void
14626 mips_align (int to, int *fill, struct insn_label_list *labels)
14627 {
14628   mips_emit_delays ();
14629   mips_record_compressed_mode ();
14630   if (fill == NULL && subseg_text_p (now_seg))
14631     frag_align_code (to, 0);
14632   else
14633     frag_align (to, fill ? *fill : 0, 0);
14634   record_alignment (now_seg, to);
14635   mips_move_labels (labels, FALSE);
14636 }
14637
14638 /* Align to a given power of two.  .align 0 turns off the automatic
14639    alignment used by the data creating pseudo-ops.  */
14640
14641 static void
14642 s_align (int x ATTRIBUTE_UNUSED)
14643 {
14644   int temp, fill_value, *fill_ptr;
14645   long max_alignment = 28;
14646
14647   /* o Note that the assembler pulls down any immediately preceding label
14648        to the aligned address.
14649      o It's not documented but auto alignment is reinstated by
14650        a .align pseudo instruction.
14651      o Note also that after auto alignment is turned off the mips assembler
14652        issues an error on attempt to assemble an improperly aligned data item.
14653        We don't.  */
14654
14655   temp = get_absolute_expression ();
14656   if (temp > max_alignment)
14657     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
14658   else if (temp < 0)
14659     {
14660       as_warn (_("Alignment negative: 0 assumed."));
14661       temp = 0;
14662     }
14663   if (*input_line_pointer == ',')
14664     {
14665       ++input_line_pointer;
14666       fill_value = get_absolute_expression ();
14667       fill_ptr = &fill_value;
14668     }
14669   else
14670     fill_ptr = 0;
14671   if (temp)
14672     {
14673       segment_info_type *si = seg_info (now_seg);
14674       struct insn_label_list *l = si->label_list;
14675       /* Auto alignment should be switched on by next section change.  */
14676       auto_align = 1;
14677       mips_align (temp, fill_ptr, l);
14678     }
14679   else
14680     {
14681       auto_align = 0;
14682     }
14683
14684   demand_empty_rest_of_line ();
14685 }
14686
14687 static void
14688 s_change_sec (int sec)
14689 {
14690   segT seg;
14691
14692   /* The ELF backend needs to know that we are changing sections, so
14693      that .previous works correctly.  We could do something like check
14694      for an obj_section_change_hook macro, but that might be confusing
14695      as it would not be appropriate to use it in the section changing
14696      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14697      This should be cleaner, somehow.  */
14698   obj_elf_section_change_hook ();
14699
14700   mips_emit_delays ();
14701
14702   switch (sec)
14703     {
14704     case 't':
14705       s_text (0);
14706       break;
14707     case 'd':
14708       s_data (0);
14709       break;
14710     case 'b':
14711       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14712       demand_empty_rest_of_line ();
14713       break;
14714
14715     case 'r':
14716       seg = subseg_new (RDATA_SECTION_NAME,
14717                         (subsegT) get_absolute_expression ());
14718       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14719                                               | SEC_READONLY | SEC_RELOC
14720                                               | SEC_DATA));
14721       if (strncmp (TARGET_OS, "elf", 3) != 0)
14722         record_alignment (seg, 4);
14723       demand_empty_rest_of_line ();
14724       break;
14725
14726     case 's':
14727       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14728       bfd_set_section_flags (stdoutput, seg,
14729                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14730       if (strncmp (TARGET_OS, "elf", 3) != 0)
14731         record_alignment (seg, 4);
14732       demand_empty_rest_of_line ();
14733       break;
14734
14735     case 'B':
14736       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14737       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14738       if (strncmp (TARGET_OS, "elf", 3) != 0)
14739         record_alignment (seg, 4);
14740       demand_empty_rest_of_line ();
14741       break;
14742     }
14743
14744   auto_align = 1;
14745 }
14746
14747 void
14748 s_change_section (int ignore ATTRIBUTE_UNUSED)
14749 {
14750   char *section_name;
14751   char c;
14752   char next_c = 0;
14753   int section_type;
14754   int section_flag;
14755   int section_entry_size;
14756   int section_alignment;
14757
14758   section_name = input_line_pointer;
14759   c = get_symbol_end ();
14760   if (c)
14761     next_c = *(input_line_pointer + 1);
14762
14763   /* Do we have .section Name<,"flags">?  */
14764   if (c != ',' || (c == ',' && next_c == '"'))
14765     {
14766       /* just after name is now '\0'.  */
14767       *input_line_pointer = c;
14768       input_line_pointer = section_name;
14769       obj_elf_section (ignore);
14770       return;
14771     }
14772   input_line_pointer++;
14773
14774   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14775   if (c == ',')
14776     section_type = get_absolute_expression ();
14777   else
14778     section_type = 0;
14779   if (*input_line_pointer++ == ',')
14780     section_flag = get_absolute_expression ();
14781   else
14782     section_flag = 0;
14783   if (*input_line_pointer++ == ',')
14784     section_entry_size = get_absolute_expression ();
14785   else
14786     section_entry_size = 0;
14787   if (*input_line_pointer++ == ',')
14788     section_alignment = get_absolute_expression ();
14789   else
14790     section_alignment = 0;
14791   /* FIXME: really ignore?  */
14792   (void) section_alignment;
14793
14794   section_name = xstrdup (section_name);
14795
14796   /* When using the generic form of .section (as implemented by obj-elf.c),
14797      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14798      traditionally had to fall back on the more common @progbits instead.
14799
14800      There's nothing really harmful in this, since bfd will correct
14801      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14802      means that, for backwards compatibility, the special_section entries
14803      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14804
14805      Even so, we shouldn't force users of the MIPS .section syntax to
14806      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14807      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14808      generic type-checking code.  */
14809   if (section_type == SHT_MIPS_DWARF)
14810     section_type = SHT_PROGBITS;
14811
14812   obj_elf_change_section (section_name, section_type, section_flag,
14813                           section_entry_size, 0, 0, 0);
14814
14815   if (now_seg->name != section_name)
14816     free (section_name);
14817 }
14818
14819 void
14820 mips_enable_auto_align (void)
14821 {
14822   auto_align = 1;
14823 }
14824
14825 static void
14826 s_cons (int log_size)
14827 {
14828   segment_info_type *si = seg_info (now_seg);
14829   struct insn_label_list *l = si->label_list;
14830
14831   mips_emit_delays ();
14832   if (log_size > 0 && auto_align)
14833     mips_align (log_size, 0, l);
14834   cons (1 << log_size);
14835   mips_clear_insn_labels ();
14836 }
14837
14838 static void
14839 s_float_cons (int type)
14840 {
14841   segment_info_type *si = seg_info (now_seg);
14842   struct insn_label_list *l = si->label_list;
14843
14844   mips_emit_delays ();
14845
14846   if (auto_align)
14847     {
14848       if (type == 'd')
14849         mips_align (3, 0, l);
14850       else
14851         mips_align (2, 0, l);
14852     }
14853
14854   float_cons (type);
14855   mips_clear_insn_labels ();
14856 }
14857
14858 /* Handle .globl.  We need to override it because on Irix 5 you are
14859    permitted to say
14860        .globl foo .text
14861    where foo is an undefined symbol, to mean that foo should be
14862    considered to be the address of a function.  */
14863
14864 static void
14865 s_mips_globl (int x ATTRIBUTE_UNUSED)
14866 {
14867   char *name;
14868   int c;
14869   symbolS *symbolP;
14870   flagword flag;
14871
14872   do
14873     {
14874       name = input_line_pointer;
14875       c = get_symbol_end ();
14876       symbolP = symbol_find_or_make (name);
14877       S_SET_EXTERNAL (symbolP);
14878
14879       *input_line_pointer = c;
14880       SKIP_WHITESPACE ();
14881
14882       /* On Irix 5, every global symbol that is not explicitly labelled as
14883          being a function is apparently labelled as being an object.  */
14884       flag = BSF_OBJECT;
14885
14886       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14887           && (*input_line_pointer != ','))
14888         {
14889           char *secname;
14890           asection *sec;
14891
14892           secname = input_line_pointer;
14893           c = get_symbol_end ();
14894           sec = bfd_get_section_by_name (stdoutput, secname);
14895           if (sec == NULL)
14896             as_bad (_("%s: no such section"), secname);
14897           *input_line_pointer = c;
14898
14899           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14900             flag = BSF_FUNCTION;
14901         }
14902
14903       symbol_get_bfdsym (symbolP)->flags |= flag;
14904
14905       c = *input_line_pointer;
14906       if (c == ',')
14907         {
14908           input_line_pointer++;
14909           SKIP_WHITESPACE ();
14910           if (is_end_of_line[(unsigned char) *input_line_pointer])
14911             c = '\n';
14912         }
14913     }
14914   while (c == ',');
14915
14916   demand_empty_rest_of_line ();
14917 }
14918
14919 static void
14920 s_option (int x ATTRIBUTE_UNUSED)
14921 {
14922   char *opt;
14923   char c;
14924
14925   opt = input_line_pointer;
14926   c = get_symbol_end ();
14927
14928   if (*opt == 'O')
14929     {
14930       /* FIXME: What does this mean?  */
14931     }
14932   else if (strncmp (opt, "pic", 3) == 0)
14933     {
14934       int i;
14935
14936       i = atoi (opt + 3);
14937       if (i == 0)
14938         mips_pic = NO_PIC;
14939       else if (i == 2)
14940         {
14941           mips_pic = SVR4_PIC;
14942           mips_abicalls = TRUE;
14943         }
14944       else
14945         as_bad (_(".option pic%d not supported"), i);
14946
14947       if (mips_pic == SVR4_PIC)
14948         {
14949           if (g_switch_seen && g_switch_value != 0)
14950             as_warn (_("-G may not be used with SVR4 PIC code"));
14951           g_switch_value = 0;
14952           bfd_set_gp_size (stdoutput, 0);
14953         }
14954     }
14955   else
14956     as_warn (_("Unrecognized option \"%s\""), opt);
14957
14958   *input_line_pointer = c;
14959   demand_empty_rest_of_line ();
14960 }
14961
14962 /* This structure is used to hold a stack of .set values.  */
14963
14964 struct mips_option_stack
14965 {
14966   struct mips_option_stack *next;
14967   struct mips_set_options options;
14968 };
14969
14970 static struct mips_option_stack *mips_opts_stack;
14971
14972 /* Handle the .set pseudo-op.  */
14973
14974 static void
14975 s_mipsset (int x ATTRIBUTE_UNUSED)
14976 {
14977   char *name = input_line_pointer, ch;
14978   const struct mips_ase *ase;
14979
14980   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14981     ++input_line_pointer;
14982   ch = *input_line_pointer;
14983   *input_line_pointer = '\0';
14984
14985   if (strcmp (name, "reorder") == 0)
14986     {
14987       if (mips_opts.noreorder)
14988         end_noreorder ();
14989     }
14990   else if (strcmp (name, "noreorder") == 0)
14991     {
14992       if (!mips_opts.noreorder)
14993         start_noreorder ();
14994     }
14995   else if (strncmp (name, "at=", 3) == 0)
14996     {
14997       char *s = name + 3;
14998
14999       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
15000         as_bad (_("Unrecognized register name `%s'"), s);
15001     }
15002   else if (strcmp (name, "at") == 0)
15003     {
15004       mips_opts.at = ATREG;
15005     }
15006   else if (strcmp (name, "noat") == 0)
15007     {
15008       mips_opts.at = ZERO;
15009     }
15010   else if (strcmp (name, "macro") == 0)
15011     {
15012       mips_opts.warn_about_macros = 0;
15013     }
15014   else if (strcmp (name, "nomacro") == 0)
15015     {
15016       if (mips_opts.noreorder == 0)
15017         as_bad (_("`noreorder' must be set before `nomacro'"));
15018       mips_opts.warn_about_macros = 1;
15019     }
15020   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
15021     {
15022       mips_opts.nomove = 0;
15023     }
15024   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
15025     {
15026       mips_opts.nomove = 1;
15027     }
15028   else if (strcmp (name, "bopt") == 0)
15029     {
15030       mips_opts.nobopt = 0;
15031     }
15032   else if (strcmp (name, "nobopt") == 0)
15033     {
15034       mips_opts.nobopt = 1;
15035     }
15036   else if (strcmp (name, "gp=default") == 0)
15037     mips_opts.gp32 = file_mips_gp32;
15038   else if (strcmp (name, "gp=32") == 0)
15039     mips_opts.gp32 = 1;
15040   else if (strcmp (name, "gp=64") == 0)
15041     {
15042       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
15043         as_warn (_("%s isa does not support 64-bit registers"),
15044                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15045       mips_opts.gp32 = 0;
15046     }
15047   else if (strcmp (name, "fp=default") == 0)
15048     mips_opts.fp32 = file_mips_fp32;
15049   else if (strcmp (name, "fp=32") == 0)
15050     mips_opts.fp32 = 1;
15051   else if (strcmp (name, "fp=64") == 0)
15052     {
15053       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15054         as_warn (_("%s isa does not support 64-bit floating point registers"),
15055                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15056       mips_opts.fp32 = 0;
15057     }
15058   else if (strcmp (name, "softfloat") == 0)
15059     mips_opts.soft_float = 1;
15060   else if (strcmp (name, "hardfloat") == 0)
15061     mips_opts.soft_float = 0;
15062   else if (strcmp (name, "singlefloat") == 0)
15063     mips_opts.single_float = 1;
15064   else if (strcmp (name, "doublefloat") == 0)
15065     mips_opts.single_float = 0;
15066   else if (strcmp (name, "mips16") == 0
15067            || strcmp (name, "MIPS-16") == 0)
15068     {
15069       if (mips_opts.micromips == 1)
15070         as_fatal (_("`mips16' cannot be used with `micromips'"));
15071       mips_opts.mips16 = 1;
15072     }
15073   else if (strcmp (name, "nomips16") == 0
15074            || strcmp (name, "noMIPS-16") == 0)
15075     mips_opts.mips16 = 0;
15076   else if (strcmp (name, "micromips") == 0)
15077     {
15078       if (mips_opts.mips16 == 1)
15079         as_fatal (_("`micromips' cannot be used with `mips16'"));
15080       mips_opts.micromips = 1;
15081     }
15082   else if (strcmp (name, "nomicromips") == 0)
15083     mips_opts.micromips = 0;
15084   else if (name[0] == 'n'
15085            && name[1] == 'o'
15086            && (ase = mips_lookup_ase (name + 2)))
15087     mips_set_ase (ase, FALSE);
15088   else if ((ase = mips_lookup_ase (name)))
15089     mips_set_ase (ase, TRUE);
15090   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15091     {
15092       int reset = 0;
15093
15094       /* Permit the user to change the ISA and architecture on the fly.
15095          Needless to say, misuse can cause serious problems.  */
15096       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
15097         {
15098           reset = 1;
15099           mips_opts.isa = file_mips_isa;
15100           mips_opts.arch = file_mips_arch;
15101         }
15102       else if (strncmp (name, "arch=", 5) == 0)
15103         {
15104           const struct mips_cpu_info *p;
15105
15106           p = mips_parse_cpu("internal use", name + 5);
15107           if (!p)
15108             as_bad (_("unknown architecture %s"), name + 5);
15109           else
15110             {
15111               mips_opts.arch = p->cpu;
15112               mips_opts.isa = p->isa;
15113             }
15114         }
15115       else if (strncmp (name, "mips", 4) == 0)
15116         {
15117           const struct mips_cpu_info *p;
15118
15119           p = mips_parse_cpu("internal use", name);
15120           if (!p)
15121             as_bad (_("unknown ISA level %s"), name + 4);
15122           else
15123             {
15124               mips_opts.arch = p->cpu;
15125               mips_opts.isa = p->isa;
15126             }
15127         }
15128       else
15129         as_bad (_("unknown ISA or architecture %s"), name);
15130
15131       switch (mips_opts.isa)
15132         {
15133         case  0:
15134           break;
15135         case ISA_MIPS1:
15136         case ISA_MIPS2:
15137         case ISA_MIPS32:
15138         case ISA_MIPS32R2:
15139           mips_opts.gp32 = 1;
15140           mips_opts.fp32 = 1;
15141           break;
15142         case ISA_MIPS3:
15143         case ISA_MIPS4:
15144         case ISA_MIPS5:
15145         case ISA_MIPS64:
15146         case ISA_MIPS64R2:
15147           mips_opts.gp32 = 0;
15148           if (mips_opts.arch == CPU_R5900)
15149             {
15150                 mips_opts.fp32 = 1;
15151             }
15152           else
15153             {
15154           mips_opts.fp32 = 0;
15155             }
15156           break;
15157         default:
15158           as_bad (_("unknown ISA level %s"), name + 4);
15159           break;
15160         }
15161       if (reset)
15162         {
15163           mips_opts.gp32 = file_mips_gp32;
15164           mips_opts.fp32 = file_mips_fp32;
15165         }
15166     }
15167   else if (strcmp (name, "autoextend") == 0)
15168     mips_opts.noautoextend = 0;
15169   else if (strcmp (name, "noautoextend") == 0)
15170     mips_opts.noautoextend = 1;
15171   else if (strcmp (name, "insn32") == 0)
15172     mips_opts.insn32 = TRUE;
15173   else if (strcmp (name, "noinsn32") == 0)
15174     mips_opts.insn32 = FALSE;
15175   else if (strcmp (name, "push") == 0)
15176     {
15177       struct mips_option_stack *s;
15178
15179       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15180       s->next = mips_opts_stack;
15181       s->options = mips_opts;
15182       mips_opts_stack = s;
15183     }
15184   else if (strcmp (name, "pop") == 0)
15185     {
15186       struct mips_option_stack *s;
15187
15188       s = mips_opts_stack;
15189       if (s == NULL)
15190         as_bad (_(".set pop with no .set push"));
15191       else
15192         {
15193           /* If we're changing the reorder mode we need to handle
15194              delay slots correctly.  */
15195           if (s->options.noreorder && ! mips_opts.noreorder)
15196             start_noreorder ();
15197           else if (! s->options.noreorder && mips_opts.noreorder)
15198             end_noreorder ();
15199
15200           mips_opts = s->options;
15201           mips_opts_stack = s->next;
15202           free (s);
15203         }
15204     }
15205   else if (strcmp (name, "sym32") == 0)
15206     mips_opts.sym32 = TRUE;
15207   else if (strcmp (name, "nosym32") == 0)
15208     mips_opts.sym32 = FALSE;
15209   else if (strchr (name, ','))
15210     {
15211       /* Generic ".set" directive; use the generic handler.  */
15212       *input_line_pointer = ch;
15213       input_line_pointer = name;
15214       s_set (0);
15215       return;
15216     }
15217   else
15218     {
15219       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
15220     }
15221   mips_check_isa_supports_ases ();
15222   *input_line_pointer = ch;
15223   demand_empty_rest_of_line ();
15224 }
15225
15226 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15227    .option pic2.  It means to generate SVR4 PIC calls.  */
15228
15229 static void
15230 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15231 {
15232   mips_pic = SVR4_PIC;
15233   mips_abicalls = TRUE;
15234
15235   if (g_switch_seen && g_switch_value != 0)
15236     as_warn (_("-G may not be used with SVR4 PIC code"));
15237   g_switch_value = 0;
15238
15239   bfd_set_gp_size (stdoutput, 0);
15240   demand_empty_rest_of_line ();
15241 }
15242
15243 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15244    PIC code.  It sets the $gp register for the function based on the
15245    function address, which is in the register named in the argument.
15246    This uses a relocation against _gp_disp, which is handled specially
15247    by the linker.  The result is:
15248         lui     $gp,%hi(_gp_disp)
15249         addiu   $gp,$gp,%lo(_gp_disp)
15250         addu    $gp,$gp,.cpload argument
15251    The .cpload argument is normally $25 == $t9.
15252
15253    The -mno-shared option changes this to:
15254         lui     $gp,%hi(__gnu_local_gp)
15255         addiu   $gp,$gp,%lo(__gnu_local_gp)
15256    and the argument is ignored.  This saves an instruction, but the
15257    resulting code is not position independent; it uses an absolute
15258    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15259    can go into an ordinary executable, but not into a shared library.  */
15260
15261 static void
15262 s_cpload (int ignore ATTRIBUTE_UNUSED)
15263 {
15264   expressionS ex;
15265   int reg;
15266   int in_shared;
15267
15268   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15269      .cpload is ignored.  */
15270   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15271     {
15272       s_ignore (0);
15273       return;
15274     }
15275
15276   if (mips_opts.mips16)
15277     {
15278       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15279       ignore_rest_of_line ();
15280       return;
15281     }
15282
15283   /* .cpload should be in a .set noreorder section.  */
15284   if (mips_opts.noreorder == 0)
15285     as_warn (_(".cpload not in noreorder section"));
15286
15287   reg = tc_get_register (0);
15288
15289   /* If we need to produce a 64-bit address, we are better off using
15290      the default instruction sequence.  */
15291   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15292
15293   ex.X_op = O_symbol;
15294   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15295                                          "__gnu_local_gp");
15296   ex.X_op_symbol = NULL;
15297   ex.X_add_number = 0;
15298
15299   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15300   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15301
15302   mips_mark_labels ();
15303   mips_assembling_insn = TRUE;
15304
15305   macro_start ();
15306   macro_build_lui (&ex, mips_gp_register);
15307   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15308                mips_gp_register, BFD_RELOC_LO16);
15309   if (in_shared)
15310     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15311                  mips_gp_register, reg);
15312   macro_end ();
15313
15314   mips_assembling_insn = FALSE;
15315   demand_empty_rest_of_line ();
15316 }
15317
15318 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15319      .cpsetup $reg1, offset|$reg2, label
15320
15321    If offset is given, this results in:
15322      sd         $gp, offset($sp)
15323      lui        $gp, %hi(%neg(%gp_rel(label)))
15324      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15325      daddu      $gp, $gp, $reg1
15326
15327    If $reg2 is given, this results in:
15328      daddu      $reg2, $gp, $0
15329      lui        $gp, %hi(%neg(%gp_rel(label)))
15330      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15331      daddu      $gp, $gp, $reg1
15332    $reg1 is normally $25 == $t9.
15333
15334    The -mno-shared option replaces the last three instructions with
15335         lui     $gp,%hi(_gp)
15336         addiu   $gp,$gp,%lo(_gp)  */
15337
15338 static void
15339 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15340 {
15341   expressionS ex_off;
15342   expressionS ex_sym;
15343   int reg1;
15344
15345   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15346      We also need NewABI support.  */
15347   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15348     {
15349       s_ignore (0);
15350       return;
15351     }
15352
15353   if (mips_opts.mips16)
15354     {
15355       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15356       ignore_rest_of_line ();
15357       return;
15358     }
15359
15360   reg1 = tc_get_register (0);
15361   SKIP_WHITESPACE ();
15362   if (*input_line_pointer != ',')
15363     {
15364       as_bad (_("missing argument separator ',' for .cpsetup"));
15365       return;
15366     }
15367   else
15368     ++input_line_pointer;
15369   SKIP_WHITESPACE ();
15370   if (*input_line_pointer == '$')
15371     {
15372       mips_cpreturn_register = tc_get_register (0);
15373       mips_cpreturn_offset = -1;
15374     }
15375   else
15376     {
15377       mips_cpreturn_offset = get_absolute_expression ();
15378       mips_cpreturn_register = -1;
15379     }
15380   SKIP_WHITESPACE ();
15381   if (*input_line_pointer != ',')
15382     {
15383       as_bad (_("missing argument separator ',' for .cpsetup"));
15384       return;
15385     }
15386   else
15387     ++input_line_pointer;
15388   SKIP_WHITESPACE ();
15389   expression (&ex_sym);
15390
15391   mips_mark_labels ();
15392   mips_assembling_insn = TRUE;
15393
15394   macro_start ();
15395   if (mips_cpreturn_register == -1)
15396     {
15397       ex_off.X_op = O_constant;
15398       ex_off.X_add_symbol = NULL;
15399       ex_off.X_op_symbol = NULL;
15400       ex_off.X_add_number = mips_cpreturn_offset;
15401
15402       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15403                    BFD_RELOC_LO16, SP);
15404     }
15405   else
15406     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15407                  mips_gp_register, 0);
15408
15409   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15410     {
15411       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15412                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15413                    BFD_RELOC_HI16_S);
15414
15415       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15416                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15417                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15418
15419       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15420                    mips_gp_register, reg1);
15421     }
15422   else
15423     {
15424       expressionS ex;
15425
15426       ex.X_op = O_symbol;
15427       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15428       ex.X_op_symbol = NULL;
15429       ex.X_add_number = 0;
15430
15431       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15432       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15433
15434       macro_build_lui (&ex, mips_gp_register);
15435       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15436                    mips_gp_register, BFD_RELOC_LO16);
15437     }
15438
15439   macro_end ();
15440
15441   mips_assembling_insn = FALSE;
15442   demand_empty_rest_of_line ();
15443 }
15444
15445 static void
15446 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15447 {
15448   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15449      .cplocal is ignored.  */
15450   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15451     {
15452       s_ignore (0);
15453       return;
15454     }
15455
15456   if (mips_opts.mips16)
15457     {
15458       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15459       ignore_rest_of_line ();
15460       return;
15461     }
15462
15463   mips_gp_register = tc_get_register (0);
15464   demand_empty_rest_of_line ();
15465 }
15466
15467 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15468    offset from $sp.  The offset is remembered, and after making a PIC
15469    call $gp is restored from that location.  */
15470
15471 static void
15472 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15473 {
15474   expressionS ex;
15475
15476   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15477      .cprestore is ignored.  */
15478   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15479     {
15480       s_ignore (0);
15481       return;
15482     }
15483
15484   if (mips_opts.mips16)
15485     {
15486       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15487       ignore_rest_of_line ();
15488       return;
15489     }
15490
15491   mips_cprestore_offset = get_absolute_expression ();
15492   mips_cprestore_valid = 1;
15493
15494   ex.X_op = O_constant;
15495   ex.X_add_symbol = NULL;
15496   ex.X_op_symbol = NULL;
15497   ex.X_add_number = mips_cprestore_offset;
15498
15499   mips_mark_labels ();
15500   mips_assembling_insn = TRUE;
15501
15502   macro_start ();
15503   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15504                                 SP, HAVE_64BIT_ADDRESSES);
15505   macro_end ();
15506
15507   mips_assembling_insn = FALSE;
15508   demand_empty_rest_of_line ();
15509 }
15510
15511 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15512    was given in the preceding .cpsetup, it results in:
15513      ld         $gp, offset($sp)
15514
15515    If a register $reg2 was given there, it results in:
15516      daddu      $gp, $reg2, $0  */
15517
15518 static void
15519 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15520 {
15521   expressionS ex;
15522
15523   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15524      We also need NewABI support.  */
15525   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15526     {
15527       s_ignore (0);
15528       return;
15529     }
15530
15531   if (mips_opts.mips16)
15532     {
15533       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15534       ignore_rest_of_line ();
15535       return;
15536     }
15537
15538   mips_mark_labels ();
15539   mips_assembling_insn = TRUE;
15540
15541   macro_start ();
15542   if (mips_cpreturn_register == -1)
15543     {
15544       ex.X_op = O_constant;
15545       ex.X_add_symbol = NULL;
15546       ex.X_op_symbol = NULL;
15547       ex.X_add_number = mips_cpreturn_offset;
15548
15549       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15550     }
15551   else
15552     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15553                  mips_cpreturn_register, 0);
15554   macro_end ();
15555
15556   mips_assembling_insn = FALSE;
15557   demand_empty_rest_of_line ();
15558 }
15559
15560 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15561    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15562    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15563    debug information or MIPS16 TLS.  */
15564
15565 static void
15566 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15567                      bfd_reloc_code_real_type rtype)
15568 {
15569   expressionS ex;
15570   char *p;
15571
15572   expression (&ex);
15573
15574   if (ex.X_op != O_symbol)
15575     {
15576       as_bad (_("Unsupported use of %s"), dirstr);
15577       ignore_rest_of_line ();
15578     }
15579
15580   p = frag_more (bytes);
15581   md_number_to_chars (p, 0, bytes);
15582   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15583   demand_empty_rest_of_line ();
15584   mips_clear_insn_labels ();
15585 }
15586
15587 /* Handle .dtprelword.  */
15588
15589 static void
15590 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15591 {
15592   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15593 }
15594
15595 /* Handle .dtpreldword.  */
15596
15597 static void
15598 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15599 {
15600   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15601 }
15602
15603 /* Handle .tprelword.  */
15604
15605 static void
15606 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15607 {
15608   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15609 }
15610
15611 /* Handle .tpreldword.  */
15612
15613 static void
15614 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15615 {
15616   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15617 }
15618
15619 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15620    code.  It sets the offset to use in gp_rel relocations.  */
15621
15622 static void
15623 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15624 {
15625   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15626      We also need NewABI support.  */
15627   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15628     {
15629       s_ignore (0);
15630       return;
15631     }
15632
15633   mips_gprel_offset = get_absolute_expression ();
15634
15635   demand_empty_rest_of_line ();
15636 }
15637
15638 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15639    code.  It generates a 32 bit GP relative reloc.  */
15640
15641 static void
15642 s_gpword (int ignore ATTRIBUTE_UNUSED)
15643 {
15644   segment_info_type *si;
15645   struct insn_label_list *l;
15646   expressionS ex;
15647   char *p;
15648
15649   /* When not generating PIC code, this is treated as .word.  */
15650   if (mips_pic != SVR4_PIC)
15651     {
15652       s_cons (2);
15653       return;
15654     }
15655
15656   si = seg_info (now_seg);
15657   l = si->label_list;
15658   mips_emit_delays ();
15659   if (auto_align)
15660     mips_align (2, 0, l);
15661
15662   expression (&ex);
15663   mips_clear_insn_labels ();
15664
15665   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15666     {
15667       as_bad (_("Unsupported use of .gpword"));
15668       ignore_rest_of_line ();
15669     }
15670
15671   p = frag_more (4);
15672   md_number_to_chars (p, 0, 4);
15673   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15674                BFD_RELOC_GPREL32);
15675
15676   demand_empty_rest_of_line ();
15677 }
15678
15679 static void
15680 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15681 {
15682   segment_info_type *si;
15683   struct insn_label_list *l;
15684   expressionS ex;
15685   char *p;
15686
15687   /* When not generating PIC code, this is treated as .dword.  */
15688   if (mips_pic != SVR4_PIC)
15689     {
15690       s_cons (3);
15691       return;
15692     }
15693
15694   si = seg_info (now_seg);
15695   l = si->label_list;
15696   mips_emit_delays ();
15697   if (auto_align)
15698     mips_align (3, 0, l);
15699
15700   expression (&ex);
15701   mips_clear_insn_labels ();
15702
15703   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15704     {
15705       as_bad (_("Unsupported use of .gpdword"));
15706       ignore_rest_of_line ();
15707     }
15708
15709   p = frag_more (8);
15710   md_number_to_chars (p, 0, 8);
15711   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15712                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15713
15714   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15715   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15716            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15717
15718   demand_empty_rest_of_line ();
15719 }
15720
15721 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15722    tables.  It generates a R_MIPS_EH reloc.  */
15723
15724 static void
15725 s_ehword (int ignore ATTRIBUTE_UNUSED)
15726 {
15727   expressionS ex;
15728   char *p;
15729
15730   mips_emit_delays ();
15731
15732   expression (&ex);
15733   mips_clear_insn_labels ();
15734
15735   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15736     {
15737       as_bad (_("Unsupported use of .ehword"));
15738       ignore_rest_of_line ();
15739     }
15740
15741   p = frag_more (4);
15742   md_number_to_chars (p, 0, 4);
15743   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15744                BFD_RELOC_MIPS_EH);
15745
15746   demand_empty_rest_of_line ();
15747 }
15748
15749 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15750    tables in SVR4 PIC code.  */
15751
15752 static void
15753 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15754 {
15755   int reg;
15756
15757   /* This is ignored when not generating SVR4 PIC code.  */
15758   if (mips_pic != SVR4_PIC)
15759     {
15760       s_ignore (0);
15761       return;
15762     }
15763
15764   mips_mark_labels ();
15765   mips_assembling_insn = TRUE;
15766
15767   /* Add $gp to the register named as an argument.  */
15768   macro_start ();
15769   reg = tc_get_register (0);
15770   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15771   macro_end ();
15772
15773   mips_assembling_insn = FALSE;
15774   demand_empty_rest_of_line ();
15775 }
15776
15777 /* Handle the .insn pseudo-op.  This marks instruction labels in
15778    mips16/micromips mode.  This permits the linker to handle them specially,
15779    such as generating jalx instructions when needed.  We also make
15780    them odd for the duration of the assembly, in order to generate the
15781    right sort of code.  We will make them even in the adjust_symtab
15782    routine, while leaving them marked.  This is convenient for the
15783    debugger and the disassembler.  The linker knows to make them odd
15784    again.  */
15785
15786 static void
15787 s_insn (int ignore ATTRIBUTE_UNUSED)
15788 {
15789   mips_mark_labels ();
15790
15791   demand_empty_rest_of_line ();
15792 }
15793
15794 /* Handle the .nan pseudo-op.  */
15795
15796 static void
15797 s_nan (int ignore ATTRIBUTE_UNUSED)
15798 {
15799   static const char str_legacy[] = "legacy";
15800   static const char str_2008[] = "2008";
15801   size_t i;
15802
15803   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15804
15805   if (i == sizeof (str_2008) - 1
15806       && memcmp (input_line_pointer, str_2008, i) == 0)
15807     mips_flag_nan2008 = TRUE;
15808   else if (i == sizeof (str_legacy) - 1
15809            && memcmp (input_line_pointer, str_legacy, i) == 0)
15810     mips_flag_nan2008 = FALSE;
15811   else
15812     as_bad (_("Bad .nan directive"));
15813
15814   input_line_pointer += i;
15815   demand_empty_rest_of_line ();
15816 }
15817
15818 /* Handle a .stab[snd] directive.  Ideally these directives would be
15819    implemented in a transparent way, so that removing them would not
15820    have any effect on the generated instructions.  However, s_stab
15821    internally changes the section, so in practice we need to decide
15822    now whether the preceding label marks compressed code.  We do not
15823    support changing the compression mode of a label after a .stab*
15824    directive, such as in:
15825
15826    foo:
15827         .stabs ...
15828         .set mips16
15829
15830    so the current mode wins.  */
15831
15832 static void
15833 s_mips_stab (int type)
15834 {
15835   mips_mark_labels ();
15836   s_stab (type);
15837 }
15838
15839 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15840
15841 static void
15842 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15843 {
15844   char *name;
15845   int c;
15846   symbolS *symbolP;
15847   expressionS exp;
15848
15849   name = input_line_pointer;
15850   c = get_symbol_end ();
15851   symbolP = symbol_find_or_make (name);
15852   S_SET_WEAK (symbolP);
15853   *input_line_pointer = c;
15854
15855   SKIP_WHITESPACE ();
15856
15857   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15858     {
15859       if (S_IS_DEFINED (symbolP))
15860         {
15861           as_bad (_("ignoring attempt to redefine symbol %s"),
15862                   S_GET_NAME (symbolP));
15863           ignore_rest_of_line ();
15864           return;
15865         }
15866
15867       if (*input_line_pointer == ',')
15868         {
15869           ++input_line_pointer;
15870           SKIP_WHITESPACE ();
15871         }
15872
15873       expression (&exp);
15874       if (exp.X_op != O_symbol)
15875         {
15876           as_bad (_("bad .weakext directive"));
15877           ignore_rest_of_line ();
15878           return;
15879         }
15880       symbol_set_value_expression (symbolP, &exp);
15881     }
15882
15883   demand_empty_rest_of_line ();
15884 }
15885
15886 /* Parse a register string into a number.  Called from the ECOFF code
15887    to parse .frame.  The argument is non-zero if this is the frame
15888    register, so that we can record it in mips_frame_reg.  */
15889
15890 int
15891 tc_get_register (int frame)
15892 {
15893   unsigned int reg;
15894
15895   SKIP_WHITESPACE ();
15896   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15897     reg = 0;
15898   if (frame)
15899     {
15900       mips_frame_reg = reg != 0 ? reg : SP;
15901       mips_frame_reg_valid = 1;
15902       mips_cprestore_valid = 0;
15903     }
15904   return reg;
15905 }
15906
15907 valueT
15908 md_section_align (asection *seg, valueT addr)
15909 {
15910   int align = bfd_get_section_alignment (stdoutput, seg);
15911
15912   /* We don't need to align ELF sections to the full alignment.
15913      However, Irix 5 may prefer that we align them at least to a 16
15914      byte boundary.  We don't bother to align the sections if we
15915      are targeted for an embedded system.  */
15916   if (strncmp (TARGET_OS, "elf", 3) == 0)
15917     return addr;
15918   if (align > 4)
15919     align = 4;
15920
15921   return ((addr + (1 << align) - 1) & (-1 << align));
15922 }
15923
15924 /* Utility routine, called from above as well.  If called while the
15925    input file is still being read, it's only an approximation.  (For
15926    example, a symbol may later become defined which appeared to be
15927    undefined earlier.)  */
15928
15929 static int
15930 nopic_need_relax (symbolS *sym, int before_relaxing)
15931 {
15932   if (sym == 0)
15933     return 0;
15934
15935   if (g_switch_value > 0)
15936     {
15937       const char *symname;
15938       int change;
15939
15940       /* Find out whether this symbol can be referenced off the $gp
15941          register.  It can be if it is smaller than the -G size or if
15942          it is in the .sdata or .sbss section.  Certain symbols can
15943          not be referenced off the $gp, although it appears as though
15944          they can.  */
15945       symname = S_GET_NAME (sym);
15946       if (symname != (const char *) NULL
15947           && (strcmp (symname, "eprol") == 0
15948               || strcmp (symname, "etext") == 0
15949               || strcmp (symname, "_gp") == 0
15950               || strcmp (symname, "edata") == 0
15951               || strcmp (symname, "_fbss") == 0
15952               || strcmp (symname, "_fdata") == 0
15953               || strcmp (symname, "_ftext") == 0
15954               || strcmp (symname, "end") == 0
15955               || strcmp (symname, "_gp_disp") == 0))
15956         change = 1;
15957       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15958                && (0
15959 #ifndef NO_ECOFF_DEBUGGING
15960                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15961                        && (symbol_get_obj (sym)->ecoff_extern_size
15962                            <= g_switch_value))
15963 #endif
15964                    /* We must defer this decision until after the whole
15965                       file has been read, since there might be a .extern
15966                       after the first use of this symbol.  */
15967                    || (before_relaxing
15968 #ifndef NO_ECOFF_DEBUGGING
15969                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15970 #endif
15971                        && S_GET_VALUE (sym) == 0)
15972                    || (S_GET_VALUE (sym) != 0
15973                        && S_GET_VALUE (sym) <= g_switch_value)))
15974         change = 0;
15975       else
15976         {
15977           const char *segname;
15978
15979           segname = segment_name (S_GET_SEGMENT (sym));
15980           gas_assert (strcmp (segname, ".lit8") != 0
15981                   && strcmp (segname, ".lit4") != 0);
15982           change = (strcmp (segname, ".sdata") != 0
15983                     && strcmp (segname, ".sbss") != 0
15984                     && strncmp (segname, ".sdata.", 7) != 0
15985                     && strncmp (segname, ".sbss.", 6) != 0
15986                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15987                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15988         }
15989       return change;
15990     }
15991   else
15992     /* We are not optimizing for the $gp register.  */
15993     return 1;
15994 }
15995
15996
15997 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15998
15999 static bfd_boolean
16000 pic_need_relax (symbolS *sym, asection *segtype)
16001 {
16002   asection *symsec;
16003
16004   /* Handle the case of a symbol equated to another symbol.  */
16005   while (symbol_equated_reloc_p (sym))
16006     {
16007       symbolS *n;
16008
16009       /* It's possible to get a loop here in a badly written program.  */
16010       n = symbol_get_value_expression (sym)->X_add_symbol;
16011       if (n == sym)
16012         break;
16013       sym = n;
16014     }
16015
16016   if (symbol_section_p (sym))
16017     return TRUE;
16018
16019   symsec = S_GET_SEGMENT (sym);
16020
16021   /* This must duplicate the test in adjust_reloc_syms.  */
16022   return (!bfd_is_und_section (symsec)
16023           && !bfd_is_abs_section (symsec)
16024           && !bfd_is_com_section (symsec)
16025           && !s_is_linkonce (sym, segtype)
16026           /* A global or weak symbol is treated as external.  */
16027           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
16028 }
16029
16030
16031 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
16032    extended opcode.  SEC is the section the frag is in.  */
16033
16034 static int
16035 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
16036 {
16037   int type;
16038   const struct mips_int_operand *operand;
16039   offsetT val;
16040   segT symsec;
16041   fragS *sym_frag;
16042
16043   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16044     return 0;
16045   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16046     return 1;
16047
16048   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16049   operand = mips16_immed_operand (type, FALSE);
16050
16051   sym_frag = symbol_get_frag (fragp->fr_symbol);
16052   val = S_GET_VALUE (fragp->fr_symbol);
16053   symsec = S_GET_SEGMENT (fragp->fr_symbol);
16054
16055   if (operand->root.type == OP_PCREL)
16056     {
16057       const struct mips_pcrel_operand *pcrel_op;
16058       addressT addr;
16059       offsetT maxtiny;
16060
16061       /* We won't have the section when we are called from
16062          mips_relax_frag.  However, we will always have been called
16063          from md_estimate_size_before_relax first.  If this is a
16064          branch to a different section, we mark it as such.  If SEC is
16065          NULL, and the frag is not marked, then it must be a branch to
16066          the same section.  */
16067       pcrel_op = (const struct mips_pcrel_operand *) operand;
16068       if (sec == NULL)
16069         {
16070           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16071             return 1;
16072         }
16073       else
16074         {
16075           /* Must have been called from md_estimate_size_before_relax.  */
16076           if (symsec != sec)
16077             {
16078               fragp->fr_subtype =
16079                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16080
16081               /* FIXME: We should support this, and let the linker
16082                  catch branches and loads that are out of range.  */
16083               as_bad_where (fragp->fr_file, fragp->fr_line,
16084                             _("unsupported PC relative reference to different section"));
16085
16086               return 1;
16087             }
16088           if (fragp != sym_frag && sym_frag->fr_address == 0)
16089             /* Assume non-extended on the first relaxation pass.
16090                The address we have calculated will be bogus if this is
16091                a forward branch to another frag, as the forward frag
16092                will have fr_address == 0.  */
16093             return 0;
16094         }
16095
16096       /* In this case, we know for sure that the symbol fragment is in
16097          the same section.  If the relax_marker of the symbol fragment
16098          differs from the relax_marker of this fragment, we have not
16099          yet adjusted the symbol fragment fr_address.  We want to add
16100          in STRETCH in order to get a better estimate of the address.
16101          This particularly matters because of the shift bits.  */
16102       if (stretch != 0
16103           && sym_frag->relax_marker != fragp->relax_marker)
16104         {
16105           fragS *f;
16106
16107           /* Adjust stretch for any alignment frag.  Note that if have
16108              been expanding the earlier code, the symbol may be
16109              defined in what appears to be an earlier frag.  FIXME:
16110              This doesn't handle the fr_subtype field, which specifies
16111              a maximum number of bytes to skip when doing an
16112              alignment.  */
16113           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16114             {
16115               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16116                 {
16117                   if (stretch < 0)
16118                     stretch = - ((- stretch)
16119                                  & ~ ((1 << (int) f->fr_offset) - 1));
16120                   else
16121                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16122                   if (stretch == 0)
16123                     break;
16124                 }
16125             }
16126           if (f != NULL)
16127             val += stretch;
16128         }
16129
16130       addr = fragp->fr_address + fragp->fr_fix;
16131
16132       /* The base address rules are complicated.  The base address of
16133          a branch is the following instruction.  The base address of a
16134          PC relative load or add is the instruction itself, but if it
16135          is in a delay slot (in which case it can not be extended) use
16136          the address of the instruction whose delay slot it is in.  */
16137       if (pcrel_op->include_isa_bit)
16138         {
16139           addr += 2;
16140
16141           /* If we are currently assuming that this frag should be
16142              extended, then, the current address is two bytes
16143              higher.  */
16144           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16145             addr += 2;
16146
16147           /* Ignore the low bit in the target, since it will be set
16148              for a text label.  */
16149           val &= -2;
16150         }
16151       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16152         addr -= 4;
16153       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16154         addr -= 2;
16155
16156       val -= addr & -(1 << pcrel_op->align_log2);
16157
16158       /* If any of the shifted bits are set, we must use an extended
16159          opcode.  If the address depends on the size of this
16160          instruction, this can lead to a loop, so we arrange to always
16161          use an extended opcode.  We only check this when we are in
16162          the main relaxation loop, when SEC is NULL.  */
16163       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16164         {
16165           fragp->fr_subtype =
16166             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16167           return 1;
16168         }
16169
16170       /* If we are about to mark a frag as extended because the value
16171          is precisely the next value above maxtiny, then there is a
16172          chance of an infinite loop as in the following code:
16173              la $4,foo
16174              .skip      1020
16175              .align     2
16176            foo:
16177          In this case when the la is extended, foo is 0x3fc bytes
16178          away, so the la can be shrunk, but then foo is 0x400 away, so
16179          the la must be extended.  To avoid this loop, we mark the
16180          frag as extended if it was small, and is about to become
16181          extended with the next value above maxtiny.  */
16182       maxtiny = mips_int_operand_max (operand);
16183       if (val == maxtiny + (1 << operand->shift)
16184           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16185           && sec == NULL)
16186         {
16187           fragp->fr_subtype =
16188             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16189           return 1;
16190         }
16191     }
16192   else if (symsec != absolute_section && sec != NULL)
16193     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16194
16195   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16196 }
16197
16198 /* Compute the length of a branch sequence, and adjust the
16199    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16200    worst-case length is computed, with UPDATE being used to indicate
16201    whether an unconditional (-1), branch-likely (+1) or regular (0)
16202    branch is to be computed.  */
16203 static int
16204 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16205 {
16206   bfd_boolean toofar;
16207   int length;
16208
16209   if (fragp
16210       && S_IS_DEFINED (fragp->fr_symbol)
16211       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16212     {
16213       addressT addr;
16214       offsetT val;
16215
16216       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16217
16218       addr = fragp->fr_address + fragp->fr_fix + 4;
16219
16220       val -= addr;
16221
16222       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16223     }
16224   else if (fragp)
16225     /* If the symbol is not defined or it's in a different segment,
16226        assume the user knows what's going on and emit a short
16227        branch.  */
16228     toofar = FALSE;
16229   else
16230     toofar = TRUE;
16231
16232   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16233     fragp->fr_subtype
16234       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16235                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16236                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16237                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16238                              toofar);
16239
16240   length = 4;
16241   if (toofar)
16242     {
16243       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16244         length += 8;
16245
16246       if (mips_pic != NO_PIC)
16247         {
16248           /* Additional space for PIC loading of target address.  */
16249           length += 8;
16250           if (mips_opts.isa == ISA_MIPS1)
16251             /* Additional space for $at-stabilizing nop.  */
16252             length += 4;
16253         }
16254
16255       /* If branch is conditional.  */
16256       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16257         length += 8;
16258     }
16259
16260   return length;
16261 }
16262
16263 /* Compute the length of a branch sequence, and adjust the
16264    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16265    worst-case length is computed, with UPDATE being used to indicate
16266    whether an unconditional (-1), or regular (0) branch is to be
16267    computed.  */
16268
16269 static int
16270 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16271 {
16272   bfd_boolean toofar;
16273   int length;
16274
16275   if (fragp
16276       && S_IS_DEFINED (fragp->fr_symbol)
16277       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16278     {
16279       addressT addr;
16280       offsetT val;
16281
16282       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16283       /* Ignore the low bit in the target, since it will be set
16284          for a text label.  */
16285       if ((val & 1) != 0)
16286         --val;
16287
16288       addr = fragp->fr_address + fragp->fr_fix + 4;
16289
16290       val -= addr;
16291
16292       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16293     }
16294   else if (fragp)
16295     /* If the symbol is not defined or it's in a different segment,
16296        assume the user knows what's going on and emit a short
16297        branch.  */
16298     toofar = FALSE;
16299   else
16300     toofar = TRUE;
16301
16302   if (fragp && update
16303       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16304     fragp->fr_subtype = (toofar
16305                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16306                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16307
16308   length = 4;
16309   if (toofar)
16310     {
16311       bfd_boolean compact_known = fragp != NULL;
16312       bfd_boolean compact = FALSE;
16313       bfd_boolean uncond;
16314
16315       if (compact_known)
16316         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16317       if (fragp)
16318         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16319       else
16320         uncond = update < 0;
16321
16322       /* If label is out of range, we turn branch <br>:
16323
16324                 <br>    label                   # 4 bytes
16325             0:
16326
16327          into:
16328
16329                 j       label                   # 4 bytes
16330                 nop                             # 2 bytes if compact && !PIC
16331             0:
16332        */
16333       if (mips_pic == NO_PIC && (!compact_known || compact))
16334         length += 2;
16335
16336       /* If assembling PIC code, we further turn:
16337
16338                         j       label                   # 4 bytes
16339
16340          into:
16341
16342                         lw/ld   at, %got(label)(gp)     # 4 bytes
16343                         d/addiu at, %lo(label)          # 4 bytes
16344                         jr/c    at                      # 2 bytes
16345        */
16346       if (mips_pic != NO_PIC)
16347         length += 6;
16348
16349       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16350
16351                         <brneg> 0f                      # 4 bytes
16352                         nop                             # 2 bytes if !compact
16353        */
16354       if (!uncond)
16355         length += (compact_known && compact) ? 4 : 6;
16356     }
16357
16358   return length;
16359 }
16360
16361 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16362    bit accordingly.  */
16363
16364 static int
16365 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16366 {
16367   bfd_boolean toofar;
16368
16369   if (fragp
16370       && S_IS_DEFINED (fragp->fr_symbol)
16371       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16372     {
16373       addressT addr;
16374       offsetT val;
16375       int type;
16376
16377       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16378       /* Ignore the low bit in the target, since it will be set
16379          for a text label.  */
16380       if ((val & 1) != 0)
16381         --val;
16382
16383       /* Assume this is a 2-byte branch.  */
16384       addr = fragp->fr_address + fragp->fr_fix + 2;
16385
16386       /* We try to avoid the infinite loop by not adding 2 more bytes for
16387          long branches.  */
16388
16389       val -= addr;
16390
16391       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16392       if (type == 'D')
16393         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16394       else if (type == 'E')
16395         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16396       else
16397         abort ();
16398     }
16399   else
16400     /* If the symbol is not defined or it's in a different segment,
16401        we emit a normal 32-bit branch.  */
16402     toofar = TRUE;
16403
16404   if (fragp && update
16405       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16406     fragp->fr_subtype
16407       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16408                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16409
16410   if (toofar)
16411     return 4;
16412
16413   return 2;
16414 }
16415
16416 /* Estimate the size of a frag before relaxing.  Unless this is the
16417    mips16, we are not really relaxing here, and the final size is
16418    encoded in the subtype information.  For the mips16, we have to
16419    decide whether we are using an extended opcode or not.  */
16420
16421 int
16422 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16423 {
16424   int change;
16425
16426   if (RELAX_BRANCH_P (fragp->fr_subtype))
16427     {
16428
16429       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16430
16431       return fragp->fr_var;
16432     }
16433
16434   if (RELAX_MIPS16_P (fragp->fr_subtype))
16435     /* We don't want to modify the EXTENDED bit here; it might get us
16436        into infinite loops.  We change it only in mips_relax_frag().  */
16437     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16438
16439   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16440     {
16441       int length = 4;
16442
16443       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16444         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16445       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16446         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16447       fragp->fr_var = length;
16448
16449       return length;
16450     }
16451
16452   if (mips_pic == NO_PIC)
16453     change = nopic_need_relax (fragp->fr_symbol, 0);
16454   else if (mips_pic == SVR4_PIC)
16455     change = pic_need_relax (fragp->fr_symbol, segtype);
16456   else if (mips_pic == VXWORKS_PIC)
16457     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16458     change = 0;
16459   else
16460     abort ();
16461
16462   if (change)
16463     {
16464       fragp->fr_subtype |= RELAX_USE_SECOND;
16465       return -RELAX_FIRST (fragp->fr_subtype);
16466     }
16467   else
16468     return -RELAX_SECOND (fragp->fr_subtype);
16469 }
16470
16471 /* This is called to see whether a reloc against a defined symbol
16472    should be converted into a reloc against a section.  */
16473
16474 int
16475 mips_fix_adjustable (fixS *fixp)
16476 {
16477   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16478       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16479     return 0;
16480
16481   if (fixp->fx_addsy == NULL)
16482     return 1;
16483
16484   /* If symbol SYM is in a mergeable section, relocations of the form
16485      SYM + 0 can usually be made section-relative.  The mergeable data
16486      is then identified by the section offset rather than by the symbol.
16487
16488      However, if we're generating REL LO16 relocations, the offset is split
16489      between the LO16 and parterning high part relocation.  The linker will
16490      need to recalculate the complete offset in order to correctly identify
16491      the merge data.
16492
16493      The linker has traditionally not looked for the parterning high part
16494      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16495      placed anywhere.  Rather than break backwards compatibility by changing
16496      this, it seems better not to force the issue, and instead keep the
16497      original symbol.  This will work with either linker behavior.  */
16498   if ((lo16_reloc_p (fixp->fx_r_type)
16499        || reloc_needs_lo_p (fixp->fx_r_type))
16500       && HAVE_IN_PLACE_ADDENDS
16501       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16502     return 0;
16503
16504   /* There is no place to store an in-place offset for JALR relocations.
16505      Likewise an in-range offset of limited PC-relative relocations may
16506      overflow the in-place relocatable field if recalculated against the
16507      start address of the symbol's containing section.  */
16508   if (HAVE_IN_PLACE_ADDENDS
16509       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16510           || jalr_reloc_p (fixp->fx_r_type)))
16511     return 0;
16512
16513   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16514      to a floating-point stub.  The same is true for non-R_MIPS16_26
16515      relocations against MIPS16 functions; in this case, the stub becomes
16516      the function's canonical address.
16517
16518      Floating-point stubs are stored in unique .mips16.call.* or
16519      .mips16.fn.* sections.  If a stub T for function F is in section S,
16520      the first relocation in section S must be against F; this is how the
16521      linker determines the target function.  All relocations that might
16522      resolve to T must also be against F.  We therefore have the following
16523      restrictions, which are given in an intentionally-redundant way:
16524
16525        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16526           symbols.
16527
16528        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16529           if that stub might be used.
16530
16531        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16532           symbols.
16533
16534        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16535           that stub might be used.
16536
16537      There is a further restriction:
16538
16539        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16540           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16541           targets with in-place addends; the relocation field cannot
16542           encode the low bit.
16543
16544      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16545      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16546      such relocations on REL targets.
16547
16548      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16549      relocation against some symbol R, no relocation against R may be
16550      reduced.  (Note that this deals with (2) as well as (1) because
16551      relocations against global symbols will never be reduced on ELF
16552      targets.)  This approach is a little simpler than trying to detect
16553      stub sections, and gives the "all or nothing" per-symbol consistency
16554      that we have for MIPS16 symbols.  */
16555   if (fixp->fx_subsy == NULL
16556       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16557           || *symbol_get_tc (fixp->fx_addsy)
16558           || (HAVE_IN_PLACE_ADDENDS
16559               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16560               && jmp_reloc_p (fixp->fx_r_type))))
16561     return 0;
16562
16563   return 1;
16564 }
16565
16566 /* Translate internal representation of relocation info to BFD target
16567    format.  */
16568
16569 arelent **
16570 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16571 {
16572   static arelent *retval[4];
16573   arelent *reloc;
16574   bfd_reloc_code_real_type code;
16575
16576   memset (retval, 0, sizeof(retval));
16577   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16578   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16579   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16580   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16581
16582   if (fixp->fx_pcrel)
16583     {
16584       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16585                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16586                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16587                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16588                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16589
16590       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16591          Relocations want only the symbol offset.  */
16592       reloc->addend = fixp->fx_addnumber + reloc->address;
16593     }
16594   else
16595     reloc->addend = fixp->fx_addnumber;
16596
16597   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16598      entry to be used in the relocation's section offset.  */
16599   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16600     {
16601       reloc->address = reloc->addend;
16602       reloc->addend = 0;
16603     }
16604
16605   code = fixp->fx_r_type;
16606
16607   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16608   if (reloc->howto == NULL)
16609     {
16610       as_bad_where (fixp->fx_file, fixp->fx_line,
16611                     _("Can not represent %s relocation in this object file format"),
16612                     bfd_get_reloc_code_name (code));
16613       retval[0] = NULL;
16614     }
16615
16616   return retval;
16617 }
16618
16619 /* Relax a machine dependent frag.  This returns the amount by which
16620    the current size of the frag should change.  */
16621
16622 int
16623 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16624 {
16625   if (RELAX_BRANCH_P (fragp->fr_subtype))
16626     {
16627       offsetT old_var = fragp->fr_var;
16628
16629       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16630
16631       return fragp->fr_var - old_var;
16632     }
16633
16634   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16635     {
16636       offsetT old_var = fragp->fr_var;
16637       offsetT new_var = 4;
16638
16639       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16640         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16641       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16642         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16643       fragp->fr_var = new_var;
16644
16645       return new_var - old_var;
16646     }
16647
16648   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16649     return 0;
16650
16651   if (mips16_extended_frag (fragp, NULL, stretch))
16652     {
16653       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16654         return 0;
16655       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16656       return 2;
16657     }
16658   else
16659     {
16660       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16661         return 0;
16662       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16663       return -2;
16664     }
16665
16666   return 0;
16667 }
16668
16669 /* Convert a machine dependent frag.  */
16670
16671 void
16672 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16673 {
16674   if (RELAX_BRANCH_P (fragp->fr_subtype))
16675     {
16676       char *buf;
16677       unsigned long insn;
16678       expressionS exp;
16679       fixS *fixp;
16680
16681       buf = fragp->fr_literal + fragp->fr_fix;
16682       insn = read_insn (buf);
16683
16684       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16685         {
16686           /* We generate a fixup instead of applying it right now
16687              because, if there are linker relaxations, we're going to
16688              need the relocations.  */
16689           exp.X_op = O_symbol;
16690           exp.X_add_symbol = fragp->fr_symbol;
16691           exp.X_add_number = fragp->fr_offset;
16692
16693           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16694                               BFD_RELOC_16_PCREL_S2);
16695           fixp->fx_file = fragp->fr_file;
16696           fixp->fx_line = fragp->fr_line;
16697
16698           buf = write_insn (buf, insn);
16699         }
16700       else
16701         {
16702           int i;
16703
16704           as_warn_where (fragp->fr_file, fragp->fr_line,
16705                          _("Relaxed out-of-range branch into a jump"));
16706
16707           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16708             goto uncond;
16709
16710           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16711             {
16712               /* Reverse the branch.  */
16713               switch ((insn >> 28) & 0xf)
16714                 {
16715                 case 4:
16716                   /* bc[0-3][tf]l? instructions can have the condition
16717                      reversed by tweaking a single TF bit, and their
16718                      opcodes all have 0x4???????.  */
16719                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
16720                   insn ^= 0x00010000;
16721                   break;
16722
16723                 case 0:
16724                   /* bltz       0x04000000      bgez    0x04010000
16725                      bltzal     0x04100000      bgezal  0x04110000  */
16726                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16727                   insn ^= 0x00010000;
16728                   break;
16729
16730                 case 1:
16731                   /* beq        0x10000000      bne     0x14000000
16732                      blez       0x18000000      bgtz    0x1c000000  */
16733                   insn ^= 0x04000000;
16734                   break;
16735
16736                 default:
16737                   abort ();
16738                 }
16739             }
16740
16741           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16742             {
16743               /* Clear the and-link bit.  */
16744               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16745
16746               /* bltzal         0x04100000      bgezal  0x04110000
16747                  bltzall        0x04120000      bgezall 0x04130000  */
16748               insn &= ~0x00100000;
16749             }
16750
16751           /* Branch over the branch (if the branch was likely) or the
16752              full jump (not likely case).  Compute the offset from the
16753              current instruction to branch to.  */
16754           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16755             i = 16;
16756           else
16757             {
16758               /* How many bytes in instructions we've already emitted?  */
16759               i = buf - fragp->fr_literal - fragp->fr_fix;
16760               /* How many bytes in instructions from here to the end?  */
16761               i = fragp->fr_var - i;
16762             }
16763           /* Convert to instruction count.  */
16764           i >>= 2;
16765           /* Branch counts from the next instruction.  */
16766           i--;
16767           insn |= i;
16768           /* Branch over the jump.  */
16769           buf = write_insn (buf, insn);
16770
16771           /* nop */
16772           buf = write_insn (buf, 0);
16773
16774           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16775             {
16776               /* beql $0, $0, 2f */
16777               insn = 0x50000000;
16778               /* Compute the PC offset from the current instruction to
16779                  the end of the variable frag.  */
16780               /* How many bytes in instructions we've already emitted?  */
16781               i = buf - fragp->fr_literal - fragp->fr_fix;
16782               /* How many bytes in instructions from here to the end?  */
16783               i = fragp->fr_var - i;
16784               /* Convert to instruction count.  */
16785               i >>= 2;
16786               /* Don't decrement i, because we want to branch over the
16787                  delay slot.  */
16788               insn |= i;
16789
16790               buf = write_insn (buf, insn);
16791               buf = write_insn (buf, 0);
16792             }
16793
16794         uncond:
16795           if (mips_pic == NO_PIC)
16796             {
16797               /* j or jal.  */
16798               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16799                       ? 0x0c000000 : 0x08000000);
16800               exp.X_op = O_symbol;
16801               exp.X_add_symbol = fragp->fr_symbol;
16802               exp.X_add_number = fragp->fr_offset;
16803
16804               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16805                                   FALSE, BFD_RELOC_MIPS_JMP);
16806               fixp->fx_file = fragp->fr_file;
16807               fixp->fx_line = fragp->fr_line;
16808
16809               buf = write_insn (buf, insn);
16810             }
16811           else
16812             {
16813               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16814
16815               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16816               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16817               insn |= at << OP_SH_RT;
16818               exp.X_op = O_symbol;
16819               exp.X_add_symbol = fragp->fr_symbol;
16820               exp.X_add_number = fragp->fr_offset;
16821
16822               if (fragp->fr_offset)
16823                 {
16824                   exp.X_add_symbol = make_expr_symbol (&exp);
16825                   exp.X_add_number = 0;
16826                 }
16827
16828               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16829                                   FALSE, BFD_RELOC_MIPS_GOT16);
16830               fixp->fx_file = fragp->fr_file;
16831               fixp->fx_line = fragp->fr_line;
16832
16833               buf = write_insn (buf, insn);
16834
16835               if (mips_opts.isa == ISA_MIPS1)
16836                 /* nop */
16837                 buf = write_insn (buf, 0);
16838
16839               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16840               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16841               insn |= at << OP_SH_RS | at << OP_SH_RT;
16842
16843               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16844                                   FALSE, BFD_RELOC_LO16);
16845               fixp->fx_file = fragp->fr_file;
16846               fixp->fx_line = fragp->fr_line;
16847
16848               buf = write_insn (buf, insn);
16849
16850               /* j(al)r $at.  */
16851               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16852                 insn = 0x0000f809;
16853               else
16854                 insn = 0x00000008;
16855               insn |= at << OP_SH_RS;
16856
16857               buf = write_insn (buf, insn);
16858             }
16859         }
16860
16861       fragp->fr_fix += fragp->fr_var;
16862       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16863       return;
16864     }
16865
16866   /* Relax microMIPS branches.  */
16867   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16868     {
16869       char *buf = fragp->fr_literal + fragp->fr_fix;
16870       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16871       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16872       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16873       bfd_boolean short_ds;
16874       unsigned long insn;
16875       expressionS exp;
16876       fixS *fixp;
16877
16878       exp.X_op = O_symbol;
16879       exp.X_add_symbol = fragp->fr_symbol;
16880       exp.X_add_number = fragp->fr_offset;
16881
16882       fragp->fr_fix += fragp->fr_var;
16883
16884       /* Handle 16-bit branches that fit or are forced to fit.  */
16885       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16886         {
16887           /* We generate a fixup instead of applying it right now,
16888              because if there is linker relaxation, we're going to
16889              need the relocations.  */
16890           if (type == 'D')
16891             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16892                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16893           else if (type == 'E')
16894             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16895                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16896           else
16897             abort ();
16898
16899           fixp->fx_file = fragp->fr_file;
16900           fixp->fx_line = fragp->fr_line;
16901
16902           /* These relocations can have an addend that won't fit in
16903              2 octets.  */
16904           fixp->fx_no_overflow = 1;
16905
16906           return;
16907         }
16908
16909       /* Handle 32-bit branches that fit or are forced to fit.  */
16910       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16911           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16912         {
16913           /* We generate a fixup instead of applying it right now,
16914              because if there is linker relaxation, we're going to
16915              need the relocations.  */
16916           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16917                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16918           fixp->fx_file = fragp->fr_file;
16919           fixp->fx_line = fragp->fr_line;
16920
16921           if (type == 0)
16922             return;
16923         }
16924
16925       /* Relax 16-bit branches to 32-bit branches.  */
16926       if (type != 0)
16927         {
16928           insn = read_compressed_insn (buf, 2);
16929
16930           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16931             insn = 0x94000000;                          /* beq  */
16932           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16933             {
16934               unsigned long regno;
16935
16936               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16937               regno = micromips_to_32_reg_d_map [regno];
16938               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16939               insn |= regno << MICROMIPSOP_SH_RS;
16940             }
16941           else
16942             abort ();
16943
16944           /* Nothing else to do, just write it out.  */
16945           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16946               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16947             {
16948               buf = write_compressed_insn (buf, insn, 4);
16949               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16950               return;
16951             }
16952         }
16953       else
16954         insn = read_compressed_insn (buf, 4);
16955
16956       /* Relax 32-bit branches to a sequence of instructions.  */
16957       as_warn_where (fragp->fr_file, fragp->fr_line,
16958                      _("Relaxed out-of-range branch into a jump"));
16959
16960       /* Set the short-delay-slot bit.  */
16961       short_ds = al && (insn & 0x02000000) != 0;
16962
16963       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16964         {
16965           symbolS *l;
16966
16967           /* Reverse the branch.  */
16968           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16969               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16970             insn ^= 0x20000000;
16971           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16972                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16973                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16974                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16975                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16976                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16977                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16978                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16979                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16980                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16981             insn ^= 0x00400000;
16982           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16983                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16984                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16985                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16986             insn ^= 0x00200000;
16987           else
16988             abort ();
16989
16990           if (al)
16991             {
16992               /* Clear the and-link and short-delay-slot bits.  */
16993               gas_assert ((insn & 0xfda00000) == 0x40200000);
16994
16995               /* bltzal  0x40200000     bgezal  0x40600000  */
16996               /* bltzals 0x42200000     bgezals 0x42600000  */
16997               insn &= ~0x02200000;
16998             }
16999
17000           /* Make a label at the end for use with the branch.  */
17001           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
17002           micromips_label_inc ();
17003           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
17004
17005           /* Refer to it.  */
17006           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
17007                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
17008           fixp->fx_file = fragp->fr_file;
17009           fixp->fx_line = fragp->fr_line;
17010
17011           /* Branch over the jump.  */
17012           buf = write_compressed_insn (buf, insn, 4);
17013           if (!compact)
17014             /* nop */
17015             buf = write_compressed_insn (buf, 0x0c00, 2);
17016         }
17017
17018       if (mips_pic == NO_PIC)
17019         {
17020           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
17021
17022           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
17023           insn = al ? jal : 0xd4000000;
17024
17025           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17026                               BFD_RELOC_MICROMIPS_JMP);
17027           fixp->fx_file = fragp->fr_file;
17028           fixp->fx_line = fragp->fr_line;
17029
17030           buf = write_compressed_insn (buf, insn, 4);
17031           if (compact)
17032             /* nop */
17033             buf = write_compressed_insn (buf, 0x0c00, 2);
17034         }
17035       else
17036         {
17037           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
17038           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
17039           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
17040
17041           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
17042           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
17043           insn |= at << MICROMIPSOP_SH_RT;
17044
17045           if (exp.X_add_number)
17046             {
17047               exp.X_add_symbol = make_expr_symbol (&exp);
17048               exp.X_add_number = 0;
17049             }
17050
17051           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17052                               BFD_RELOC_MICROMIPS_GOT16);
17053           fixp->fx_file = fragp->fr_file;
17054           fixp->fx_line = fragp->fr_line;
17055
17056           buf = write_compressed_insn (buf, insn, 4);
17057
17058           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
17059           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
17060           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
17061
17062           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17063                               BFD_RELOC_MICROMIPS_LO16);
17064           fixp->fx_file = fragp->fr_file;
17065           fixp->fx_line = fragp->fr_line;
17066
17067           buf = write_compressed_insn (buf, insn, 4);
17068
17069           /* jr/jrc/jalr/jalrs $at  */
17070           insn = al ? jalr : jr;
17071           insn |= at << MICROMIPSOP_SH_MJ;
17072
17073           buf = write_compressed_insn (buf, insn, 2);
17074         }
17075
17076       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17077       return;
17078     }
17079
17080   if (RELAX_MIPS16_P (fragp->fr_subtype))
17081     {
17082       int type;
17083       const struct mips_int_operand *operand;
17084       offsetT val;
17085       char *buf;
17086       unsigned int user_length, length;
17087       unsigned long insn;
17088       bfd_boolean ext;
17089
17090       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17091       operand = mips16_immed_operand (type, FALSE);
17092
17093       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
17094       val = resolve_symbol_value (fragp->fr_symbol);
17095       if (operand->root.type == OP_PCREL)
17096         {
17097           const struct mips_pcrel_operand *pcrel_op;
17098           addressT addr;
17099
17100           pcrel_op = (const struct mips_pcrel_operand *) operand;
17101           addr = fragp->fr_address + fragp->fr_fix;
17102
17103           /* The rules for the base address of a PC relative reloc are
17104              complicated; see mips16_extended_frag.  */
17105           if (pcrel_op->include_isa_bit)
17106             {
17107               addr += 2;
17108               if (ext)
17109                 addr += 2;
17110               /* Ignore the low bit in the target, since it will be
17111                  set for a text label.  */
17112               val &= -2;
17113             }
17114           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17115             addr -= 4;
17116           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17117             addr -= 2;
17118
17119           addr &= -(1 << pcrel_op->align_log2);
17120           val -= addr;
17121
17122           /* Make sure the section winds up with the alignment we have
17123              assumed.  */
17124           if (operand->shift > 0)
17125             record_alignment (asec, operand->shift);
17126         }
17127
17128       if (ext
17129           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17130               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17131         as_warn_where (fragp->fr_file, fragp->fr_line,
17132                        _("extended instruction in delay slot"));
17133
17134       buf = fragp->fr_literal + fragp->fr_fix;
17135
17136       insn = read_compressed_insn (buf, 2);
17137       if (ext)
17138         insn |= MIPS16_EXTEND;
17139
17140       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17141         user_length = 4;
17142       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17143         user_length = 2;
17144       else
17145         user_length = 0;
17146
17147       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17148                     BFD_RELOC_UNUSED, val, user_length, &insn);
17149
17150       length = (ext ? 4 : 2);
17151       gas_assert (mips16_opcode_length (insn) == length);
17152       write_compressed_insn (buf, insn, length);
17153       fragp->fr_fix += length;
17154     }
17155   else
17156     {
17157       relax_substateT subtype = fragp->fr_subtype;
17158       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17159       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17160       int first, second;
17161       fixS *fixp;
17162
17163       first = RELAX_FIRST (subtype);
17164       second = RELAX_SECOND (subtype);
17165       fixp = (fixS *) fragp->fr_opcode;
17166
17167       /* If the delay slot chosen does not match the size of the instruction,
17168          then emit a warning.  */
17169       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17170            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17171         {
17172           relax_substateT s;
17173           const char *msg;
17174
17175           s = subtype & (RELAX_DELAY_SLOT_16BIT
17176                          | RELAX_DELAY_SLOT_SIZE_FIRST
17177                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17178           msg = macro_warning (s);
17179           if (msg != NULL)
17180             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17181           subtype &= ~s;
17182         }
17183
17184       /* Possibly emit a warning if we've chosen the longer option.  */
17185       if (use_second == second_longer)
17186         {
17187           relax_substateT s;
17188           const char *msg;
17189
17190           s = (subtype
17191                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17192           msg = macro_warning (s);
17193           if (msg != NULL)
17194             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17195           subtype &= ~s;
17196         }
17197
17198       /* Go through all the fixups for the first sequence.  Disable them
17199          (by marking them as done) if we're going to use the second
17200          sequence instead.  */
17201       while (fixp
17202              && fixp->fx_frag == fragp
17203              && fixp->fx_where < fragp->fr_fix - second)
17204         {
17205           if (subtype & RELAX_USE_SECOND)
17206             fixp->fx_done = 1;
17207           fixp = fixp->fx_next;
17208         }
17209
17210       /* Go through the fixups for the second sequence.  Disable them if
17211          we're going to use the first sequence, otherwise adjust their
17212          addresses to account for the relaxation.  */
17213       while (fixp && fixp->fx_frag == fragp)
17214         {
17215           if (subtype & RELAX_USE_SECOND)
17216             fixp->fx_where -= first;
17217           else
17218             fixp->fx_done = 1;
17219           fixp = fixp->fx_next;
17220         }
17221
17222       /* Now modify the frag contents.  */
17223       if (subtype & RELAX_USE_SECOND)
17224         {
17225           char *start;
17226
17227           start = fragp->fr_literal + fragp->fr_fix - first - second;
17228           memmove (start, start + first, second);
17229           fragp->fr_fix -= first;
17230         }
17231       else
17232         fragp->fr_fix -= second;
17233     }
17234 }
17235
17236 /* This function is called after the relocs have been generated.
17237    We've been storing mips16 text labels as odd.  Here we convert them
17238    back to even for the convenience of the debugger.  */
17239
17240 void
17241 mips_frob_file_after_relocs (void)
17242 {
17243   asymbol **syms;
17244   unsigned int count, i;
17245
17246   syms = bfd_get_outsymbols (stdoutput);
17247   count = bfd_get_symcount (stdoutput);
17248   for (i = 0; i < count; i++, syms++)
17249     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17250         && ((*syms)->value & 1) != 0)
17251       {
17252         (*syms)->value &= ~1;
17253         /* If the symbol has an odd size, it was probably computed
17254            incorrectly, so adjust that as well.  */
17255         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17256           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17257       }
17258 }
17259
17260 /* This function is called whenever a label is defined, including fake
17261    labels instantiated off the dot special symbol.  It is used when
17262    handling branch delays; if a branch has a label, we assume we cannot
17263    move it.  This also bumps the value of the symbol by 1 in compressed
17264    code.  */
17265
17266 static void
17267 mips_record_label (symbolS *sym)
17268 {
17269   segment_info_type *si = seg_info (now_seg);
17270   struct insn_label_list *l;
17271
17272   if (free_insn_labels == NULL)
17273     l = (struct insn_label_list *) xmalloc (sizeof *l);
17274   else
17275     {
17276       l = free_insn_labels;
17277       free_insn_labels = l->next;
17278     }
17279
17280   l->label = sym;
17281   l->next = si->label_list;
17282   si->label_list = l;
17283 }
17284
17285 /* This function is called as tc_frob_label() whenever a label is defined
17286    and adds a DWARF-2 record we only want for true labels.  */
17287
17288 void
17289 mips_define_label (symbolS *sym)
17290 {
17291   mips_record_label (sym);
17292   dwarf2_emit_label (sym);
17293 }
17294
17295 /* This function is called by tc_new_dot_label whenever a new dot symbol
17296    is defined.  */
17297
17298 void
17299 mips_add_dot_label (symbolS *sym)
17300 {
17301   mips_record_label (sym);
17302   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17303     mips_compressed_mark_label (sym);
17304 }
17305 \f
17306 /* Some special processing for a MIPS ELF file.  */
17307
17308 void
17309 mips_elf_final_processing (void)
17310 {
17311   /* Write out the register information.  */
17312   if (mips_abi != N64_ABI)
17313     {
17314       Elf32_RegInfo s;
17315
17316       s.ri_gprmask = mips_gprmask;
17317       s.ri_cprmask[0] = mips_cprmask[0];
17318       s.ri_cprmask[1] = mips_cprmask[1];
17319       s.ri_cprmask[2] = mips_cprmask[2];
17320       s.ri_cprmask[3] = mips_cprmask[3];
17321       /* The gp_value field is set by the MIPS ELF backend.  */
17322
17323       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17324                                        ((Elf32_External_RegInfo *)
17325                                         mips_regmask_frag));
17326     }
17327   else
17328     {
17329       Elf64_Internal_RegInfo s;
17330
17331       s.ri_gprmask = mips_gprmask;
17332       s.ri_pad = 0;
17333       s.ri_cprmask[0] = mips_cprmask[0];
17334       s.ri_cprmask[1] = mips_cprmask[1];
17335       s.ri_cprmask[2] = mips_cprmask[2];
17336       s.ri_cprmask[3] = mips_cprmask[3];
17337       /* The gp_value field is set by the MIPS ELF backend.  */
17338
17339       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17340                                        ((Elf64_External_RegInfo *)
17341                                         mips_regmask_frag));
17342     }
17343
17344   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17345      sort of BFD interface for this.  */
17346   if (mips_any_noreorder)
17347     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17348   if (mips_pic != NO_PIC)
17349     {
17350       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17351       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17352     }
17353   if (mips_abicalls)
17354     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17355
17356   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17357      defined at present; this might need to change in future.  */
17358   if (file_ase_mips16)
17359     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17360   if (file_ase_micromips)
17361     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17362   if (file_ase & ASE_MDMX)
17363     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17364
17365   /* Set the MIPS ELF ABI flags.  */
17366   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17367     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17368   else if (mips_abi == O64_ABI)
17369     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17370   else if (mips_abi == EABI_ABI)
17371     {
17372       if (!file_mips_gp32)
17373         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17374       else
17375         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17376     }
17377   else if (mips_abi == N32_ABI)
17378     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17379
17380   /* Nothing to do for N64_ABI.  */
17381
17382   if (mips_32bitmode)
17383     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17384
17385   if (mips_flag_nan2008)
17386     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17387
17388 #if 0 /* XXX FIXME */
17389   /* 32 bit code with 64 bit FP registers.  */
17390   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
17391     elf_elfheader (stdoutput)->e_flags |= ???;
17392 #endif
17393 }
17394 \f
17395 typedef struct proc {
17396   symbolS *func_sym;
17397   symbolS *func_end_sym;
17398   unsigned long reg_mask;
17399   unsigned long reg_offset;
17400   unsigned long fpreg_mask;
17401   unsigned long fpreg_offset;
17402   unsigned long frame_offset;
17403   unsigned long frame_reg;
17404   unsigned long pc_reg;
17405 } procS;
17406
17407 static procS cur_proc;
17408 static procS *cur_proc_ptr;
17409 static int numprocs;
17410
17411 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17412    as "2", and a normal nop as "0".  */
17413
17414 #define NOP_OPCODE_MIPS         0
17415 #define NOP_OPCODE_MIPS16       1
17416 #define NOP_OPCODE_MICROMIPS    2
17417
17418 char
17419 mips_nop_opcode (void)
17420 {
17421   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17422     return NOP_OPCODE_MICROMIPS;
17423   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17424     return NOP_OPCODE_MIPS16;
17425   else
17426     return NOP_OPCODE_MIPS;
17427 }
17428
17429 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17430    32-bit microMIPS NOPs here (if applicable).  */
17431
17432 void
17433 mips_handle_align (fragS *fragp)
17434 {
17435   char nop_opcode;
17436   char *p;
17437   int bytes, size, excess;
17438   valueT opcode;
17439
17440   if (fragp->fr_type != rs_align_code)
17441     return;
17442
17443   p = fragp->fr_literal + fragp->fr_fix;
17444   nop_opcode = *p;
17445   switch (nop_opcode)
17446     {
17447     case NOP_OPCODE_MICROMIPS:
17448       opcode = micromips_nop32_insn.insn_opcode;
17449       size = 4;
17450       break;
17451     case NOP_OPCODE_MIPS16:
17452       opcode = mips16_nop_insn.insn_opcode;
17453       size = 2;
17454       break;
17455     case NOP_OPCODE_MIPS:
17456     default:
17457       opcode = nop_insn.insn_opcode;
17458       size = 4;
17459       break;
17460     }
17461
17462   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17463   excess = bytes % size;
17464
17465   /* Handle the leading part if we're not inserting a whole number of
17466      instructions, and make it the end of the fixed part of the frag.
17467      Try to fit in a short microMIPS NOP if applicable and possible,
17468      and use zeroes otherwise.  */
17469   gas_assert (excess < 4);
17470   fragp->fr_fix += excess;
17471   switch (excess)
17472     {
17473     case 3:
17474       *p++ = '\0';
17475       /* Fall through.  */
17476     case 2:
17477       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17478         {
17479           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17480           break;
17481         }
17482       *p++ = '\0';
17483       /* Fall through.  */
17484     case 1:
17485       *p++ = '\0';
17486       /* Fall through.  */
17487     case 0:
17488       break;
17489     }
17490
17491   md_number_to_chars (p, opcode, size);
17492   fragp->fr_var = size;
17493 }
17494
17495 static void
17496 md_obj_begin (void)
17497 {
17498 }
17499
17500 static void
17501 md_obj_end (void)
17502 {
17503   /* Check for premature end, nesting errors, etc.  */
17504   if (cur_proc_ptr)
17505     as_warn (_("missing .end at end of assembly"));
17506 }
17507
17508 static long
17509 get_number (void)
17510 {
17511   int negative = 0;
17512   long val = 0;
17513
17514   if (*input_line_pointer == '-')
17515     {
17516       ++input_line_pointer;
17517       negative = 1;
17518     }
17519   if (!ISDIGIT (*input_line_pointer))
17520     as_bad (_("expected simple number"));
17521   if (input_line_pointer[0] == '0')
17522     {
17523       if (input_line_pointer[1] == 'x')
17524         {
17525           input_line_pointer += 2;
17526           while (ISXDIGIT (*input_line_pointer))
17527             {
17528               val <<= 4;
17529               val |= hex_value (*input_line_pointer++);
17530             }
17531           return negative ? -val : val;
17532         }
17533       else
17534         {
17535           ++input_line_pointer;
17536           while (ISDIGIT (*input_line_pointer))
17537             {
17538               val <<= 3;
17539               val |= *input_line_pointer++ - '0';
17540             }
17541           return negative ? -val : val;
17542         }
17543     }
17544   if (!ISDIGIT (*input_line_pointer))
17545     {
17546       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17547               *input_line_pointer, *input_line_pointer);
17548       as_warn (_("invalid number"));
17549       return -1;
17550     }
17551   while (ISDIGIT (*input_line_pointer))
17552     {
17553       val *= 10;
17554       val += *input_line_pointer++ - '0';
17555     }
17556   return negative ? -val : val;
17557 }
17558
17559 /* The .file directive; just like the usual .file directive, but there
17560    is an initial number which is the ECOFF file index.  In the non-ECOFF
17561    case .file implies DWARF-2.  */
17562
17563 static void
17564 s_mips_file (int x ATTRIBUTE_UNUSED)
17565 {
17566   static int first_file_directive = 0;
17567
17568   if (ECOFF_DEBUGGING)
17569     {
17570       get_number ();
17571       s_app_file (0);
17572     }
17573   else
17574     {
17575       char *filename;
17576
17577       filename = dwarf2_directive_file (0);
17578
17579       /* Versions of GCC up to 3.1 start files with a ".file"
17580          directive even for stabs output.  Make sure that this
17581          ".file" is handled.  Note that you need a version of GCC
17582          after 3.1 in order to support DWARF-2 on MIPS.  */
17583       if (filename != NULL && ! first_file_directive)
17584         {
17585           (void) new_logical_line (filename, -1);
17586           s_app_file_string (filename, 0);
17587         }
17588       first_file_directive = 1;
17589     }
17590 }
17591
17592 /* The .loc directive, implying DWARF-2.  */
17593
17594 static void
17595 s_mips_loc (int x ATTRIBUTE_UNUSED)
17596 {
17597   if (!ECOFF_DEBUGGING)
17598     dwarf2_directive_loc (0);
17599 }
17600
17601 /* The .end directive.  */
17602
17603 static void
17604 s_mips_end (int x ATTRIBUTE_UNUSED)
17605 {
17606   symbolS *p;
17607
17608   /* Following functions need their own .frame and .cprestore directives.  */
17609   mips_frame_reg_valid = 0;
17610   mips_cprestore_valid = 0;
17611
17612   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17613     {
17614       p = get_symbol ();
17615       demand_empty_rest_of_line ();
17616     }
17617   else
17618     p = NULL;
17619
17620   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17621     as_warn (_(".end not in text section"));
17622
17623   if (!cur_proc_ptr)
17624     {
17625       as_warn (_(".end directive without a preceding .ent directive."));
17626       demand_empty_rest_of_line ();
17627       return;
17628     }
17629
17630   if (p != NULL)
17631     {
17632       gas_assert (S_GET_NAME (p));
17633       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17634         as_warn (_(".end symbol does not match .ent symbol."));
17635
17636       if (debug_type == DEBUG_STABS)
17637         stabs_generate_asm_endfunc (S_GET_NAME (p),
17638                                     S_GET_NAME (p));
17639     }
17640   else
17641     as_warn (_(".end directive missing or unknown symbol"));
17642
17643   /* Create an expression to calculate the size of the function.  */
17644   if (p && cur_proc_ptr)
17645     {
17646       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17647       expressionS *exp = xmalloc (sizeof (expressionS));
17648
17649       obj->size = exp;
17650       exp->X_op = O_subtract;
17651       exp->X_add_symbol = symbol_temp_new_now ();
17652       exp->X_op_symbol = p;
17653       exp->X_add_number = 0;
17654
17655       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17656     }
17657
17658   /* Generate a .pdr section.  */
17659   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17660     {
17661       segT saved_seg = now_seg;
17662       subsegT saved_subseg = now_subseg;
17663       expressionS exp;
17664       char *fragp;
17665
17666 #ifdef md_flush_pending_output
17667       md_flush_pending_output ();
17668 #endif
17669
17670       gas_assert (pdr_seg);
17671       subseg_set (pdr_seg, 0);
17672
17673       /* Write the symbol.  */
17674       exp.X_op = O_symbol;
17675       exp.X_add_symbol = p;
17676       exp.X_add_number = 0;
17677       emit_expr (&exp, 4);
17678
17679       fragp = frag_more (7 * 4);
17680
17681       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17682       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17683       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17684       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17685       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17686       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17687       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17688
17689       subseg_set (saved_seg, saved_subseg);
17690     }
17691
17692   cur_proc_ptr = NULL;
17693 }
17694
17695 /* The .aent and .ent directives.  */
17696
17697 static void
17698 s_mips_ent (int aent)
17699 {
17700   symbolS *symbolP;
17701
17702   symbolP = get_symbol ();
17703   if (*input_line_pointer == ',')
17704     ++input_line_pointer;
17705   SKIP_WHITESPACE ();
17706   if (ISDIGIT (*input_line_pointer)
17707       || *input_line_pointer == '-')
17708     get_number ();
17709
17710   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17711     as_warn (_(".ent or .aent not in text section."));
17712
17713   if (!aent && cur_proc_ptr)
17714     as_warn (_("missing .end"));
17715
17716   if (!aent)
17717     {
17718       /* This function needs its own .frame and .cprestore directives.  */
17719       mips_frame_reg_valid = 0;
17720       mips_cprestore_valid = 0;
17721
17722       cur_proc_ptr = &cur_proc;
17723       memset (cur_proc_ptr, '\0', sizeof (procS));
17724
17725       cur_proc_ptr->func_sym = symbolP;
17726
17727       ++numprocs;
17728
17729       if (debug_type == DEBUG_STABS)
17730         stabs_generate_asm_func (S_GET_NAME (symbolP),
17731                                  S_GET_NAME (symbolP));
17732     }
17733
17734   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17735
17736   demand_empty_rest_of_line ();
17737 }
17738
17739 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17740    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17741    s_mips_frame is used so that we can set the PDR information correctly.
17742    We can't use the ecoff routines because they make reference to the ecoff
17743    symbol table (in the mdebug section).  */
17744
17745 static void
17746 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17747 {
17748   if (ECOFF_DEBUGGING)
17749     s_ignore (ignore);
17750   else
17751     {
17752       long val;
17753
17754       if (cur_proc_ptr == (procS *) NULL)
17755         {
17756           as_warn (_(".frame outside of .ent"));
17757           demand_empty_rest_of_line ();
17758           return;
17759         }
17760
17761       cur_proc_ptr->frame_reg = tc_get_register (1);
17762
17763       SKIP_WHITESPACE ();
17764       if (*input_line_pointer++ != ','
17765           || get_absolute_expression_and_terminator (&val) != ',')
17766         {
17767           as_warn (_("Bad .frame directive"));
17768           --input_line_pointer;
17769           demand_empty_rest_of_line ();
17770           return;
17771         }
17772
17773       cur_proc_ptr->frame_offset = val;
17774       cur_proc_ptr->pc_reg = tc_get_register (0);
17775
17776       demand_empty_rest_of_line ();
17777     }
17778 }
17779
17780 /* The .fmask and .mask directives. If the mdebug section is present
17781    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17782    embedded targets, s_mips_mask is used so that we can set the PDR
17783    information correctly. We can't use the ecoff routines because they
17784    make reference to the ecoff symbol table (in the mdebug section).  */
17785
17786 static void
17787 s_mips_mask (int reg_type)
17788 {
17789   if (ECOFF_DEBUGGING)
17790     s_ignore (reg_type);
17791   else
17792     {
17793       long mask, off;
17794
17795       if (cur_proc_ptr == (procS *) NULL)
17796         {
17797           as_warn (_(".mask/.fmask outside of .ent"));
17798           demand_empty_rest_of_line ();
17799           return;
17800         }
17801
17802       if (get_absolute_expression_and_terminator (&mask) != ',')
17803         {
17804           as_warn (_("Bad .mask/.fmask directive"));
17805           --input_line_pointer;
17806           demand_empty_rest_of_line ();
17807           return;
17808         }
17809
17810       off = get_absolute_expression ();
17811
17812       if (reg_type == 'F')
17813         {
17814           cur_proc_ptr->fpreg_mask = mask;
17815           cur_proc_ptr->fpreg_offset = off;
17816         }
17817       else
17818         {
17819           cur_proc_ptr->reg_mask = mask;
17820           cur_proc_ptr->reg_offset = off;
17821         }
17822
17823       demand_empty_rest_of_line ();
17824     }
17825 }
17826
17827 /* A table describing all the processors gas knows about.  Names are
17828    matched in the order listed.
17829
17830    To ease comparison, please keep this table in the same order as
17831    gcc's mips_cpu_info_table[].  */
17832 static const struct mips_cpu_info mips_cpu_info_table[] =
17833 {
17834   /* Entries for generic ISAs */
17835   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17836   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17837   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17838   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17839   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17840   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17841   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17842   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17843   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17844
17845   /* MIPS I */
17846   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17847   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17848   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17849
17850   /* MIPS II */
17851   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17852
17853   /* MIPS III */
17854   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17855   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17856   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17857   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17858   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17859   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17860   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17861   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17862   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17863   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17864   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17865   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17866   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17867   /* ST Microelectronics Loongson 2E and 2F cores */
17868   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17869   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17870
17871   /* MIPS IV */
17872   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17873   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17874   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17875   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17876   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17877   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17878   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17879   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17880   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17881   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17882   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17883   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17884   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17885   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17886   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17887
17888   /* MIPS 32 */
17889   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17890   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17891   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17892   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17893
17894   /* MIPS 32 Release 2 */
17895   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17896   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17897   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17898   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17899   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17900   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17901   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17902   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17903   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17904                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17905   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17906                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17907   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17908   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17909   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17910   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17911   /* Deprecated forms of the above.  */
17912   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17913   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17914   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17915   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17916   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17917   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17918   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17919   /* Deprecated forms of the above.  */
17920   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17921   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17922   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17923   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17924   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17925   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17926   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17927   /* Deprecated forms of the above.  */
17928   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17929   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17930   /* 34Kn is a 34kc without DSP.  */
17931   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17932   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17933   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17934   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17935   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17936   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17937   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17938   /* Deprecated forms of the above.  */
17939   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17940   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17941   /* 1004K cores are multiprocessor versions of the 34K.  */
17942   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17943   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17944   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17945   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17946
17947   /* MIPS 64 */
17948   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17949   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17950   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17951   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17952
17953   /* Broadcom SB-1 CPU core */
17954   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17955   /* Broadcom SB-1A CPU core */
17956   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17957   
17958   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
17959
17960   /* MIPS 64 Release 2 */
17961
17962   /* Cavium Networks Octeon CPU core */
17963   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17964   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17965   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17966
17967   /* RMI Xlr */
17968   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17969
17970   /* Broadcom XLP.
17971      XLP is mostly like XLR, with the prominent exception that it is
17972      MIPS64R2 rather than MIPS64.  */
17973   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17974
17975   /* End marker */
17976   { NULL, 0, 0, 0, 0 }
17977 };
17978
17979
17980 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17981    with a final "000" replaced by "k".  Ignore case.
17982
17983    Note: this function is shared between GCC and GAS.  */
17984
17985 static bfd_boolean
17986 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17987 {
17988   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17989     given++, canonical++;
17990
17991   return ((*given == 0 && *canonical == 0)
17992           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17993 }
17994
17995
17996 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17997    CPU name.  We've traditionally allowed a lot of variation here.
17998
17999    Note: this function is shared between GCC and GAS.  */
18000
18001 static bfd_boolean
18002 mips_matching_cpu_name_p (const char *canonical, const char *given)
18003 {
18004   /* First see if the name matches exactly, or with a final "000"
18005      turned into "k".  */
18006   if (mips_strict_matching_cpu_name_p (canonical, given))
18007     return TRUE;
18008
18009   /* If not, try comparing based on numerical designation alone.
18010      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
18011   if (TOLOWER (*given) == 'r')
18012     given++;
18013   if (!ISDIGIT (*given))
18014     return FALSE;
18015
18016   /* Skip over some well-known prefixes in the canonical name,
18017      hoping to find a number there too.  */
18018   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
18019     canonical += 2;
18020   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
18021     canonical += 2;
18022   else if (TOLOWER (canonical[0]) == 'r')
18023     canonical += 1;
18024
18025   return mips_strict_matching_cpu_name_p (canonical, given);
18026 }
18027
18028
18029 /* Parse an option that takes the name of a processor as its argument.
18030    OPTION is the name of the option and CPU_STRING is the argument.
18031    Return the corresponding processor enumeration if the CPU_STRING is
18032    recognized, otherwise report an error and return null.
18033
18034    A similar function exists in GCC.  */
18035
18036 static const struct mips_cpu_info *
18037 mips_parse_cpu (const char *option, const char *cpu_string)
18038 {
18039   const struct mips_cpu_info *p;
18040
18041   /* 'from-abi' selects the most compatible architecture for the given
18042      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
18043      EABIs, we have to decide whether we're using the 32-bit or 64-bit
18044      version.  Look first at the -mgp options, if given, otherwise base
18045      the choice on MIPS_DEFAULT_64BIT.
18046
18047      Treat NO_ABI like the EABIs.  One reason to do this is that the
18048      plain 'mips' and 'mips64' configs have 'from-abi' as their default
18049      architecture.  This code picks MIPS I for 'mips' and MIPS III for
18050      'mips64', just as we did in the days before 'from-abi'.  */
18051   if (strcasecmp (cpu_string, "from-abi") == 0)
18052     {
18053       if (ABI_NEEDS_32BIT_REGS (mips_abi))
18054         return mips_cpu_info_from_isa (ISA_MIPS1);
18055
18056       if (ABI_NEEDS_64BIT_REGS (mips_abi))
18057         return mips_cpu_info_from_isa (ISA_MIPS3);
18058
18059       if (file_mips_gp32 >= 0)
18060         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
18061
18062       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
18063                                      ? ISA_MIPS3
18064                                      : ISA_MIPS1);
18065     }
18066
18067   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
18068   if (strcasecmp (cpu_string, "default") == 0)
18069     return 0;
18070
18071   for (p = mips_cpu_info_table; p->name != 0; p++)
18072     if (mips_matching_cpu_name_p (p->name, cpu_string))
18073       return p;
18074
18075   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
18076   return 0;
18077 }
18078
18079 /* Return the canonical processor information for ISA (a member of the
18080    ISA_MIPS* enumeration).  */
18081
18082 static const struct mips_cpu_info *
18083 mips_cpu_info_from_isa (int isa)
18084 {
18085   int i;
18086
18087   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18088     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
18089         && isa == mips_cpu_info_table[i].isa)
18090       return (&mips_cpu_info_table[i]);
18091
18092   return NULL;
18093 }
18094
18095 static const struct mips_cpu_info *
18096 mips_cpu_info_from_arch (int arch)
18097 {
18098   int i;
18099
18100   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18101     if (arch == mips_cpu_info_table[i].cpu)
18102       return (&mips_cpu_info_table[i]);
18103
18104   return NULL;
18105 }
18106 \f
18107 static void
18108 show (FILE *stream, const char *string, int *col_p, int *first_p)
18109 {
18110   if (*first_p)
18111     {
18112       fprintf (stream, "%24s", "");
18113       *col_p = 24;
18114     }
18115   else
18116     {
18117       fprintf (stream, ", ");
18118       *col_p += 2;
18119     }
18120
18121   if (*col_p + strlen (string) > 72)
18122     {
18123       fprintf (stream, "\n%24s", "");
18124       *col_p = 24;
18125     }
18126
18127   fprintf (stream, "%s", string);
18128   *col_p += strlen (string);
18129
18130   *first_p = 0;
18131 }
18132
18133 void
18134 md_show_usage (FILE *stream)
18135 {
18136   int column, first;
18137   size_t i;
18138
18139   fprintf (stream, _("\
18140 MIPS options:\n\
18141 -EB                     generate big endian output\n\
18142 -EL                     generate little endian output\n\
18143 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18144 -G NUM                  allow referencing objects up to NUM bytes\n\
18145                         implicitly with the gp register [default 8]\n"));
18146   fprintf (stream, _("\
18147 -mips1                  generate MIPS ISA I instructions\n\
18148 -mips2                  generate MIPS ISA II instructions\n\
18149 -mips3                  generate MIPS ISA III instructions\n\
18150 -mips4                  generate MIPS ISA IV instructions\n\
18151 -mips5                  generate MIPS ISA V instructions\n\
18152 -mips32                 generate MIPS32 ISA instructions\n\
18153 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18154 -mips64                 generate MIPS64 ISA instructions\n\
18155 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18156 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18157
18158   first = 1;
18159
18160   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18161     show (stream, mips_cpu_info_table[i].name, &column, &first);
18162   show (stream, "from-abi", &column, &first);
18163   fputc ('\n', stream);
18164
18165   fprintf (stream, _("\
18166 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18167 -no-mCPU                don't generate code specific to CPU.\n\
18168                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18169
18170   first = 1;
18171
18172   show (stream, "3900", &column, &first);
18173   show (stream, "4010", &column, &first);
18174   show (stream, "4100", &column, &first);
18175   show (stream, "4650", &column, &first);
18176   fputc ('\n', stream);
18177
18178   fprintf (stream, _("\
18179 -mips16                 generate mips16 instructions\n\
18180 -no-mips16              do not generate mips16 instructions\n"));
18181   fprintf (stream, _("\
18182 -mmicromips             generate microMIPS instructions\n\
18183 -mno-micromips          do not generate microMIPS instructions\n"));
18184   fprintf (stream, _("\
18185 -msmartmips             generate smartmips instructions\n\
18186 -mno-smartmips          do not generate smartmips instructions\n"));  
18187   fprintf (stream, _("\
18188 -mdsp                   generate DSP instructions\n\
18189 -mno-dsp                do not generate DSP instructions\n"));
18190   fprintf (stream, _("\
18191 -mdspr2                 generate DSP R2 instructions\n\
18192 -mno-dspr2              do not generate DSP R2 instructions\n"));
18193   fprintf (stream, _("\
18194 -mmt                    generate MT instructions\n\
18195 -mno-mt                 do not generate MT instructions\n"));
18196   fprintf (stream, _("\
18197 -mmcu                   generate MCU instructions\n\
18198 -mno-mcu                do not generate MCU instructions\n"));
18199   fprintf (stream, _("\
18200 -mvirt                  generate Virtualization instructions\n\
18201 -mno-virt               do not generate Virtualization instructions\n"));
18202   fprintf (stream, _("\
18203 -minsn32                only generate 32-bit microMIPS instructions\n\
18204 -mno-insn32             generate all microMIPS instructions\n"));
18205   fprintf (stream, _("\
18206 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18207 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18208 -mfix-vr4120            work around certain VR4120 errata\n\
18209 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18210 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18211 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18212 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18213 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18214 -msym32                 assume all symbols have 32-bit values\n\
18215 -O0                     remove unneeded NOPs, do not swap branches\n\
18216 -O                      remove unneeded NOPs and swap branches\n\
18217 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18218 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18219   fprintf (stream, _("\
18220 -mhard-float            allow floating-point instructions\n\
18221 -msoft-float            do not allow floating-point instructions\n\
18222 -msingle-float          only allow 32-bit floating-point operations\n\
18223 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18224 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18225 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18226 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18227
18228   first = 1;
18229
18230   show (stream, "legacy", &column, &first);
18231   show (stream, "2008", &column, &first);
18232
18233   fputc ('\n', stream);
18234
18235   fprintf (stream, _("\
18236 -KPIC, -call_shared     generate SVR4 position independent code\n\
18237 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18238 -mvxworks-pic           generate VxWorks position independent code\n\
18239 -non_shared             do not generate code that can operate with DSOs\n\
18240 -xgot                   assume a 32 bit GOT\n\
18241 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18242 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18243                         position dependent (non shared) code\n\
18244 -mabi=ABI               create ABI conformant object file for:\n"));
18245
18246   first = 1;
18247
18248   show (stream, "32", &column, &first);
18249   show (stream, "o64", &column, &first);
18250   show (stream, "n32", &column, &first);
18251   show (stream, "64", &column, &first);
18252   show (stream, "eabi", &column, &first);
18253
18254   fputc ('\n', stream);
18255
18256   fprintf (stream, _("\
18257 -32                     create o32 ABI object file (default)\n\
18258 -n32                    create n32 ABI object file\n\
18259 -64                     create 64 ABI object file\n"));
18260 }
18261
18262 #ifdef TE_IRIX
18263 enum dwarf2_format
18264 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18265 {
18266   if (HAVE_64BIT_SYMBOLS)
18267     return dwarf2_format_64bit_irix;
18268   else
18269     return dwarf2_format_32bit;
18270 }
18271 #endif
18272
18273 int
18274 mips_dwarf2_addr_size (void)
18275 {
18276   if (HAVE_64BIT_OBJECTS)
18277     return 8;
18278   else
18279     return 4;
18280 }
18281
18282 /* Standard calling conventions leave the CFA at SP on entry.  */
18283 void
18284 mips_cfi_frame_initial_instructions (void)
18285 {
18286   cfi_add_CFA_def_cfa_register (SP);
18287 }
18288
18289 int
18290 tc_mips_regname_to_dw2regnum (char *regname)
18291 {
18292   unsigned int regnum = -1;
18293   unsigned int reg;
18294
18295   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18296     regnum = reg;
18297
18298   return regnum;
18299 }