Home | History | Annotate | Download | only in config
      1 /* tc-xtensa.c -- Assemble Xtensa instructions.
      2    Copyright (C) 2003-2014 Free Software Foundation, Inc.
      3 
      4    This file is part of GAS, the GNU Assembler.
      5 
      6    GAS is free software; you can redistribute it and/or modify
      7    it under the terms of the GNU General Public License as published by
      8    the Free Software Foundation; either version 3, or (at your option)
      9    any later version.
     10 
     11    GAS is distributed in the hope that it will be useful,
     12    but WITHOUT ANY WARRANTY; without even the implied warranty of
     13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     14    GNU General Public License for more details.
     15 
     16    You should have received a copy of the GNU General Public License
     17    along with GAS; see the file COPYING.  If not, write to
     18    the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston,
     19    MA 02110-1301, USA.  */
     20 
     21 #include "as.h"
     22 #include <limits.h>
     23 #include "sb.h"
     24 #include "safe-ctype.h"
     25 #include "tc-xtensa.h"
     26 #include "subsegs.h"
     27 #include "xtensa-relax.h"
     28 #include "dwarf2dbg.h"
     29 #include "xtensa-istack.h"
     30 #include "struc-symbol.h"
     31 #include "xtensa-config.h"
     32 
     33 /* Provide default values for new configuration settings.  */
     34 #ifndef XSHAL_ABI
     35 #define XSHAL_ABI 0
     36 #endif
     37 
     38 #ifndef uint32
     39 #define uint32 unsigned int
     40 #endif
     41 #ifndef int32
     42 #define int32 signed int
     43 #endif
     44 
     45 /* Notes:
     46 
     47    Naming conventions (used somewhat inconsistently):
     48       The xtensa_ functions are exported
     49       The xg_ functions are internal
     50 
     51    We also have a couple of different extensibility mechanisms.
     52    1) The idiom replacement:
     53       This is used when a line is first parsed to
     54       replace an instruction pattern with another instruction
     55       It is currently limited to replacements of instructions
     56       with constant operands.
     57    2) The xtensa-relax.c mechanism that has stronger instruction
     58       replacement patterns.  When an instruction's immediate field
     59       does not fit the next instruction sequence is attempted.
     60       In addition, "narrow" opcodes are supported this way.  */
     61 
     62 
     63 /* Define characters with special meanings to GAS.  */
     64 const char comment_chars[] = "#";
     65 const char line_comment_chars[] = "#";
     66 const char line_separator_chars[] = ";";
     67 const char EXP_CHARS[] = "eE";
     68 const char FLT_CHARS[] = "rRsSfFdDxXpP";
     69 
     70 
     71 /* Flags to indicate whether the hardware supports the density and
     72    absolute literals options.  */
     73 
     74 bfd_boolean density_supported = XCHAL_HAVE_DENSITY;
     75 bfd_boolean absolute_literals_supported = XSHAL_USE_ABSOLUTE_LITERALS;
     76 
     77 static vliw_insn cur_vinsn;
     78 
     79 unsigned xtensa_num_pipe_stages;
     80 unsigned xtensa_fetch_width = XCHAL_INST_FETCH_WIDTH;
     81 
     82 static enum debug_info_type xt_saved_debug_type = DEBUG_NONE;
     83 
     84 /* Some functions are only valid in the front end.  This variable
     85    allows us to assert that we haven't crossed over into the
     86    back end.  */
     87 static bfd_boolean past_xtensa_end = FALSE;
     88 
     89 /* Flags for properties of the last instruction in a segment.  */
     90 #define FLAG_IS_A0_WRITER	0x1
     91 #define FLAG_IS_BAD_LOOPEND	0x2
     92 
     93 
     94 /* We define a special segment names ".literal" to place literals
     95    into.  The .fini and .init sections are special because they
     96    contain code that is moved together by the linker.  We give them
     97    their own special .fini.literal and .init.literal sections.  */
     98 
     99 #define LITERAL_SECTION_NAME		xtensa_section_rename (".literal")
    100 #define LIT4_SECTION_NAME		xtensa_section_rename (".lit4")
    101 #define INIT_SECTION_NAME		xtensa_section_rename (".init")
    102 #define FINI_SECTION_NAME		xtensa_section_rename (".fini")
    103 
    104 
    105 /* This type is used for the directive_stack to keep track of the
    106    state of the literal collection pools.  If lit_prefix is set, it is
    107    used to determine the literal section names; otherwise, the literal
    108    sections are determined based on the current text section.  The
    109    lit_seg and lit4_seg fields cache these literal sections, with the
    110    current_text_seg field used a tag to indicate whether the cached
    111    values are valid.  */
    112 
    113 typedef struct lit_state_struct
    114 {
    115   char *lit_prefix;
    116   segT current_text_seg;
    117   segT lit_seg;
    118   segT lit4_seg;
    119 } lit_state;
    120 
    121 static lit_state default_lit_sections;
    122 
    123 
    124 /* We keep a list of literal segments.  The seg_list type is the node
    125    for this list.  The literal_head pointer is the head of the list,
    126    with the literal_head_h dummy node at the start.  */
    127 
    128 typedef struct seg_list_struct
    129 {
    130   struct seg_list_struct *next;
    131   segT seg;
    132 } seg_list;
    133 
    134 static seg_list literal_head_h;
    135 static seg_list *literal_head = &literal_head_h;
    136 
    137 
    138 /* Lists of symbols.  We keep a list of symbols that label the current
    139    instruction, so that we can adjust the symbols when inserting alignment
    140    for various instructions.  We also keep a list of all the symbols on
    141    literals, so that we can fix up those symbols when the literals are
    142    later moved into the text sections.  */
    143 
    144 typedef struct sym_list_struct
    145 {
    146   struct sym_list_struct *next;
    147   symbolS *sym;
    148 } sym_list;
    149 
    150 static sym_list *insn_labels = NULL;
    151 static sym_list *free_insn_labels = NULL;
    152 static sym_list *saved_insn_labels = NULL;
    153 
    154 static sym_list *literal_syms;
    155 
    156 
    157 /* Flags to determine whether to prefer const16 or l32r
    158    if both options are available.  */
    159 int prefer_const16 = 0;
    160 int prefer_l32r = 0;
    161 
    162 /* Global flag to indicate when we are emitting literals.  */
    163 int generating_literals = 0;
    164 
    165 /* The following PROPERTY table definitions are copied from
    166    <elf/xtensa.h> and must be kept in sync with the code there.  */
    167 
    168 /* Flags in the property tables to specify whether blocks of memory
    169    are literals, instructions, data, or unreachable.  For
    170    instructions, blocks that begin loop targets and branch targets are
    171    designated.  Blocks that do not allow density, instruction
    172    reordering or transformation are also specified.  Finally, for
    173    branch targets, branch target alignment priority is included.
    174    Alignment of the next block is specified in the current block
    175    and the size of the current block does not include any fill required
    176    to align to the next block.  */
    177 
    178 #define XTENSA_PROP_LITERAL		0x00000001
    179 #define XTENSA_PROP_INSN		0x00000002
    180 #define XTENSA_PROP_DATA		0x00000004
    181 #define XTENSA_PROP_UNREACHABLE		0x00000008
    182 /* Instruction only properties at beginning of code.  */
    183 #define XTENSA_PROP_INSN_LOOP_TARGET	0x00000010
    184 #define XTENSA_PROP_INSN_BRANCH_TARGET	0x00000020
    185 /* Instruction only properties about code.  */
    186 #define XTENSA_PROP_INSN_NO_DENSITY	0x00000040
    187 #define XTENSA_PROP_INSN_NO_REORDER	0x00000080
    188 /* Historically, NO_TRANSFORM was a property of instructions,
    189    but it should apply to literals under certain circumstances.  */
    190 #define XTENSA_PROP_NO_TRANSFORM	0x00000100
    191 
    192 /*  Branch target alignment information.  This transmits information
    193     to the linker optimization about the priority of aligning a
    194     particular block for branch target alignment: None, low priority,
    195     high priority, or required.  These only need to be checked in
    196     instruction blocks marked as XTENSA_PROP_INSN_BRANCH_TARGET.
    197     Common usage is
    198 
    199     switch (GET_XTENSA_PROP_BT_ALIGN (flags))
    200     case XTENSA_PROP_BT_ALIGN_NONE:
    201     case XTENSA_PROP_BT_ALIGN_LOW:
    202     case XTENSA_PROP_BT_ALIGN_HIGH:
    203     case XTENSA_PROP_BT_ALIGN_REQUIRE:
    204 */
    205 #define XTENSA_PROP_BT_ALIGN_MASK       0x00000600
    206 
    207 /* No branch target alignment.  */
    208 #define XTENSA_PROP_BT_ALIGN_NONE       0x0
    209 /* Low priority branch target alignment.  */
    210 #define XTENSA_PROP_BT_ALIGN_LOW        0x1
    211 /* High priority branch target alignment.  */
    212 #define XTENSA_PROP_BT_ALIGN_HIGH       0x2
    213 /* Required branch target alignment.  */
    214 #define XTENSA_PROP_BT_ALIGN_REQUIRE    0x3
    215 
    216 #define GET_XTENSA_PROP_BT_ALIGN(flag) \
    217   (((unsigned) ((flag) & (XTENSA_PROP_BT_ALIGN_MASK))) >> 9)
    218 #define SET_XTENSA_PROP_BT_ALIGN(flag, align) \
    219   (((flag) & (~XTENSA_PROP_BT_ALIGN_MASK)) | \
    220     (((align) << 9) & XTENSA_PROP_BT_ALIGN_MASK))
    221 
    222 
    223 /* Alignment is specified in the block BEFORE the one that needs
    224    alignment.  Up to 5 bits.  Use GET_XTENSA_PROP_ALIGNMENT(flags) to
    225    get the required alignment specified as a power of 2.  Use
    226    SET_XTENSA_PROP_ALIGNMENT(flags, pow2) to set the required
    227    alignment.  Be careful of side effects since the SET will evaluate
    228    flags twice.  Also, note that the SIZE of a block in the property
    229    table does not include the alignment size, so the alignment fill
    230    must be calculated to determine if two blocks are contiguous.
    231    TEXT_ALIGN is not currently implemented but is a placeholder for a
    232    possible future implementation.  */
    233 
    234 #define XTENSA_PROP_ALIGN		0x00000800
    235 
    236 #define XTENSA_PROP_ALIGNMENT_MASK      0x0001f000
    237 
    238 #define GET_XTENSA_PROP_ALIGNMENT(flag) \
    239   (((unsigned) ((flag) & (XTENSA_PROP_ALIGNMENT_MASK))) >> 12)
    240 #define SET_XTENSA_PROP_ALIGNMENT(flag, align) \
    241   (((flag) & (~XTENSA_PROP_ALIGNMENT_MASK)) | \
    242     (((align) << 12) & XTENSA_PROP_ALIGNMENT_MASK))
    243 
    244 #define XTENSA_PROP_INSN_ABSLIT 0x00020000
    245 
    246 
    247 /* Structure for saving instruction and alignment per-fragment data
    248    that will be written to the object file.  This structure is
    249    equivalent to the actual data that will be written out to the file
    250    but is easier to use.   We provide a conversion to file flags
    251    in frag_flags_to_number.  */
    252 
    253 typedef struct frag_flags_struct frag_flags;
    254 
    255 struct frag_flags_struct
    256 {
    257   /* is_literal should only be used after xtensa_move_literals.
    258      If you need to check if you are generating a literal fragment,
    259      then use the generating_literals global.  */
    260 
    261   unsigned is_literal : 1;
    262   unsigned is_insn : 1;
    263   unsigned is_data : 1;
    264   unsigned is_unreachable : 1;
    265 
    266   /* is_specific_opcode implies no_transform.  */
    267   unsigned is_no_transform : 1;
    268 
    269   struct
    270   {
    271     unsigned is_loop_target : 1;
    272     unsigned is_branch_target : 1; /* Branch targets have a priority.  */
    273     unsigned bt_align_priority : 2;
    274 
    275     unsigned is_no_density : 1;
    276     /* no_longcalls flag does not need to be placed in the object file.  */
    277 
    278     unsigned is_no_reorder : 1;
    279 
    280     /* Uses absolute literal addressing for l32r.  */
    281     unsigned is_abslit : 1;
    282   } insn;
    283   unsigned is_align : 1;
    284   unsigned alignment : 5;
    285 };
    286 
    287 
    288 /* Structure for saving information about a block of property data
    289    for frags that have the same flags.  */
    290 struct xtensa_block_info_struct
    291 {
    292   segT sec;
    293   bfd_vma offset;
    294   size_t size;
    295   frag_flags flags;
    296   struct xtensa_block_info_struct *next;
    297 };
    298 
    299 
    300 /* Structure for saving the current state before emitting literals.  */
    301 typedef struct emit_state_struct
    302 {
    303   const char *name;
    304   segT now_seg;
    305   subsegT now_subseg;
    306   int generating_literals;
    307 } emit_state;
    308 
    309 
    310 /* Opcode placement information */
    311 
    312 typedef unsigned long long bitfield;
    313 #define bit_is_set(bit, bf)	((bf) & (0x01ll << (bit)))
    314 #define set_bit(bit, bf)	((bf) |= (0x01ll << (bit)))
    315 #define clear_bit(bit, bf)	((bf) &= ~(0x01ll << (bit)))
    316 
    317 #define MAX_FORMATS 32
    318 
    319 typedef struct op_placement_info_struct
    320 {
    321   int num_formats;
    322   /* A number describing how restrictive the issue is for this
    323      opcode.  For example, an opcode that fits lots of different
    324      formats has a high freedom, as does an opcode that fits
    325      only one format but many slots in that format.  The most
    326      restrictive is the opcode that fits only one slot in one
    327      format.  */
    328   int issuef;
    329   xtensa_format narrowest;
    330   char narrowest_size;
    331   char narrowest_slot;
    332 
    333   /* formats is a bitfield with the Nth bit set
    334      if the opcode fits in the Nth xtensa_format.  */
    335   bitfield formats;
    336 
    337   /* slots[N]'s Mth bit is set if the op fits in the
    338      Mth slot of the Nth xtensa_format.  */
    339   bitfield slots[MAX_FORMATS];
    340 
    341   /* A count of the number of slots in a given format
    342      an op can fit (i.e., the bitcount of the slot field above).  */
    343   char slots_in_format[MAX_FORMATS];
    344 
    345 } op_placement_info, *op_placement_info_table;
    346 
    347 op_placement_info_table op_placement_table;
    348 
    349 
    350 /* Extra expression types.  */
    351 
    352 #define O_pltrel	O_md1	/* like O_symbol but use a PLT reloc */
    353 #define O_hi16		O_md2	/* use high 16 bits of symbolic value */
    354 #define O_lo16		O_md3	/* use low 16 bits of symbolic value */
    355 #define O_pcrel		O_md4	/* value is a PC-relative offset */
    356 #define O_tlsfunc	O_md5	/* TLS_FUNC/TLSDESC_FN relocation */
    357 #define O_tlsarg	O_md6	/* TLS_ARG/TLSDESC_ARG relocation */
    358 #define O_tlscall	O_md7	/* TLS_CALL relocation */
    359 #define O_tpoff		O_md8	/* TPOFF relocation */
    360 #define O_dtpoff	O_md9	/* DTPOFF relocation */
    361 
    362 struct suffix_reloc_map
    363 {
    364   char *suffix;
    365   int length;
    366   bfd_reloc_code_real_type reloc;
    367   unsigned char operator;
    368 };
    369 
    370 #define SUFFIX_MAP(str, reloc, op) { str, sizeof (str) - 1, reloc, op }
    371 
    372 static struct suffix_reloc_map suffix_relocs[] =
    373 {
    374   SUFFIX_MAP ("l",	BFD_RELOC_LO16,			O_lo16),
    375   SUFFIX_MAP ("h",	BFD_RELOC_HI16,			O_hi16),
    376   SUFFIX_MAP ("plt",	BFD_RELOC_XTENSA_PLT,		O_pltrel),
    377   SUFFIX_MAP ("pcrel",	BFD_RELOC_32_PCREL,		O_pcrel),
    378   SUFFIX_MAP ("tlsfunc", BFD_RELOC_XTENSA_TLS_FUNC,	O_tlsfunc),
    379   SUFFIX_MAP ("tlsarg",	BFD_RELOC_XTENSA_TLS_ARG,	O_tlsarg),
    380   SUFFIX_MAP ("tlscall", BFD_RELOC_XTENSA_TLS_CALL,	O_tlscall),
    381   SUFFIX_MAP ("tpoff",	BFD_RELOC_XTENSA_TLS_TPOFF,	O_tpoff),
    382   SUFFIX_MAP ("dtpoff",	BFD_RELOC_XTENSA_TLS_DTPOFF,	O_dtpoff),
    383   { (char *) 0, 0,	BFD_RELOC_UNUSED,		0 }
    384 };
    385 
    386 
    387 /* Directives.  */
    388 
    389 typedef enum
    390 {
    391   directive_none = 0,
    392   directive_literal,
    393   directive_density,
    394   directive_transform,
    395   directive_freeregs,
    396   directive_longcalls,
    397   directive_literal_prefix,
    398   directive_schedule,
    399   directive_absolute_literals,
    400   directive_last_directive
    401 } directiveE;
    402 
    403 typedef struct
    404 {
    405   const char *name;
    406   bfd_boolean can_be_negated;
    407 } directive_infoS;
    408 
    409 const directive_infoS directive_info[] =
    410 {
    411   { "none",		FALSE },
    412   { "literal",		FALSE },
    413   { "density",		TRUE },
    414   { "transform",	TRUE },
    415   { "freeregs",		FALSE },
    416   { "longcalls",	TRUE },
    417   { "literal_prefix",	FALSE },
    418   { "schedule",		TRUE },
    419   { "absolute-literals", TRUE }
    420 };
    421 
    422 bfd_boolean directive_state[] =
    423 {
    424   FALSE,			/* none */
    425   FALSE,			/* literal */
    426 #if !XCHAL_HAVE_DENSITY
    427   FALSE,			/* density */
    428 #else
    429   TRUE,				/* density */
    430 #endif
    431   TRUE,				/* transform */
    432   FALSE,			/* freeregs */
    433   FALSE,			/* longcalls */
    434   FALSE,			/* literal_prefix */
    435   FALSE,			/* schedule */
    436 #if XSHAL_USE_ABSOLUTE_LITERALS
    437   TRUE				/* absolute_literals */
    438 #else
    439   FALSE				/* absolute_literals */
    440 #endif
    441 };
    442 
    443 
    444 /* Directive functions.  */
    445 
    446 static void xtensa_begin_directive (int);
    447 static void xtensa_end_directive (int);
    448 static void xtensa_literal_prefix (void);
    449 static void xtensa_literal_position (int);
    450 static void xtensa_literal_pseudo (int);
    451 static void xtensa_frequency_pseudo (int);
    452 static void xtensa_elf_cons (int);
    453 static void xtensa_leb128 (int);
    454 
    455 /* Parsing and Idiom Translation.  */
    456 
    457 static bfd_reloc_code_real_type xtensa_elf_suffix (char **, expressionS *);
    458 
    459 /* Various Other Internal Functions.  */
    460 
    461 extern bfd_boolean xg_is_single_relaxable_insn (TInsn *, TInsn *, bfd_boolean);
    462 static bfd_boolean xg_build_to_insn (TInsn *, TInsn *, BuildInstr *);
    463 static void xtensa_mark_literal_pool_location (void);
    464 static addressT get_expanded_loop_offset (xtensa_opcode);
    465 static fragS *get_literal_pool_location (segT);
    466 static void set_literal_pool_location (segT, fragS *);
    467 static void xtensa_set_frag_assembly_state (fragS *);
    468 static void finish_vinsn (vliw_insn *);
    469 static bfd_boolean emit_single_op (TInsn *);
    470 static int total_frag_text_expansion (fragS *);
    471 static bfd_boolean use_trampolines = TRUE;
    472 static void xtensa_check_frag_count (void);
    473 static void xtensa_create_trampoline_frag (bfd_boolean);
    474 static void xtensa_maybe_create_trampoline_frag (void);
    475 struct trampoline_frag;
    476 static int init_trampoline_frag (struct trampoline_frag *);
    477 
    478 /* Alignment Functions.  */
    479 
    480 static int get_text_align_power (unsigned);
    481 static int get_text_align_max_fill_size (int, bfd_boolean, bfd_boolean);
    482 static int branch_align_power (segT);
    483 
    484 /* Helpers for xtensa_relax_frag().  */
    485 
    486 static long relax_frag_add_nop (fragS *);
    487 
    488 /* Accessors for additional per-subsegment information.  */
    489 
    490 static unsigned get_last_insn_flags (segT, subsegT);
    491 static void set_last_insn_flags (segT, subsegT, unsigned, bfd_boolean);
    492 static float get_subseg_total_freq (segT, subsegT);
    493 static float get_subseg_target_freq (segT, subsegT);
    494 static void set_subseg_freq (segT, subsegT, float, float);
    495 
    496 /* Segment list functions.  */
    497 
    498 static void xtensa_move_literals (void);
    499 static void xtensa_reorder_segments (void);
    500 static void xtensa_switch_to_literal_fragment (emit_state *);
    501 static void xtensa_switch_to_non_abs_literal_fragment (emit_state *);
    502 static void xtensa_switch_section_emit_state (emit_state *, segT, subsegT);
    503 static void xtensa_restore_emit_state (emit_state *);
    504 static segT cache_literal_section (bfd_boolean);
    505 
    506 /* Import from elf32-xtensa.c in BFD library.  */
    507 
    508 extern asection *xtensa_make_property_section (asection *, const char *);
    509 
    510 /* op_placement_info functions.  */
    511 
    512 static void init_op_placement_info_table (void);
    513 extern bfd_boolean opcode_fits_format_slot (xtensa_opcode, xtensa_format, int);
    514 static int xg_get_single_size (xtensa_opcode);
    515 static xtensa_format xg_get_single_format (xtensa_opcode);
    516 static int xg_get_single_slot (xtensa_opcode);
    517 
    518 /* TInsn and IStack functions.  */
    519 
    520 static bfd_boolean tinsn_has_symbolic_operands (const TInsn *);
    521 static bfd_boolean tinsn_has_invalid_symbolic_operands (const TInsn *);
    522 static bfd_boolean tinsn_has_complex_operands (const TInsn *);
    523 static bfd_boolean tinsn_to_insnbuf (TInsn *, xtensa_insnbuf);
    524 static bfd_boolean tinsn_check_arguments (const TInsn *);
    525 static void tinsn_from_chars (TInsn *, char *, int);
    526 static void tinsn_immed_from_frag (TInsn *, fragS *, int);
    527 static int get_num_stack_text_bytes (IStack *);
    528 static int get_num_stack_literal_bytes (IStack *);
    529 static bfd_boolean tinsn_to_slotbuf (xtensa_format, int, TInsn *, xtensa_insnbuf);
    530 
    531 /* vliw_insn functions.  */
    532 
    533 static void xg_init_vinsn (vliw_insn *);
    534 static void xg_copy_vinsn (vliw_insn *, vliw_insn *);
    535 static void xg_clear_vinsn (vliw_insn *);
    536 static bfd_boolean vinsn_has_specific_opcodes (vliw_insn *);
    537 static void xg_free_vinsn (vliw_insn *);
    538 static bfd_boolean vinsn_to_insnbuf
    539   (vliw_insn *, char *, fragS *, bfd_boolean);
    540 static void vinsn_from_chars (vliw_insn *, char *);
    541 
    542 /* Expression Utilities.  */
    543 
    544 bfd_boolean expr_is_const (const expressionS *);
    545 offsetT get_expr_const (const expressionS *);
    546 void set_expr_const (expressionS *, offsetT);
    547 bfd_boolean expr_is_register (const expressionS *);
    548 offsetT get_expr_register (const expressionS *);
    549 void set_expr_symbol_offset (expressionS *, symbolS *, offsetT);
    550 bfd_boolean expr_is_equal (expressionS *, expressionS *);
    551 static void copy_expr (expressionS *, const expressionS *);
    552 
    553 /* Section renaming.  */
    554 
    555 static void build_section_rename (const char *);
    556 
    557 
    558 /* ISA imported from bfd.  */
    559 extern xtensa_isa xtensa_default_isa;
    560 
    561 extern int target_big_endian;
    562 
    563 static xtensa_opcode xtensa_addi_opcode;
    564 static xtensa_opcode xtensa_addmi_opcode;
    565 static xtensa_opcode xtensa_call0_opcode;
    566 static xtensa_opcode xtensa_call4_opcode;
    567 static xtensa_opcode xtensa_call8_opcode;
    568 static xtensa_opcode xtensa_call12_opcode;
    569 static xtensa_opcode xtensa_callx0_opcode;
    570 static xtensa_opcode xtensa_callx4_opcode;
    571 static xtensa_opcode xtensa_callx8_opcode;
    572 static xtensa_opcode xtensa_callx12_opcode;
    573 static xtensa_opcode xtensa_const16_opcode;
    574 static xtensa_opcode xtensa_entry_opcode;
    575 static xtensa_opcode xtensa_extui_opcode;
    576 static xtensa_opcode xtensa_movi_opcode;
    577 static xtensa_opcode xtensa_movi_n_opcode;
    578 static xtensa_opcode xtensa_isync_opcode;
    579 static xtensa_opcode xtensa_j_opcode;
    580 static xtensa_opcode xtensa_jx_opcode;
    581 static xtensa_opcode xtensa_l32r_opcode;
    582 static xtensa_opcode xtensa_loop_opcode;
    583 static xtensa_opcode xtensa_loopnez_opcode;
    584 static xtensa_opcode xtensa_loopgtz_opcode;
    585 static xtensa_opcode xtensa_nop_opcode;
    586 static xtensa_opcode xtensa_nop_n_opcode;
    587 static xtensa_opcode xtensa_or_opcode;
    588 static xtensa_opcode xtensa_ret_opcode;
    589 static xtensa_opcode xtensa_ret_n_opcode;
    590 static xtensa_opcode xtensa_retw_opcode;
    591 static xtensa_opcode xtensa_retw_n_opcode;
    592 static xtensa_opcode xtensa_rsr_lcount_opcode;
    593 static xtensa_opcode xtensa_waiti_opcode;
    594 static int config_max_slots = 0;
    595 
    596 
    597 /* Command-line Options.  */
    599 
    600 bfd_boolean use_literal_section = TRUE;
    601 enum flix_level produce_flix = FLIX_ALL;
    602 static bfd_boolean align_targets = TRUE;
    603 static bfd_boolean warn_unaligned_branch_targets = FALSE;
    604 static bfd_boolean has_a0_b_retw = FALSE;
    605 static bfd_boolean workaround_a0_b_retw = FALSE;
    606 static bfd_boolean workaround_b_j_loop_end = FALSE;
    607 static bfd_boolean workaround_short_loop = FALSE;
    608 static bfd_boolean maybe_has_short_loop = FALSE;
    609 static bfd_boolean workaround_close_loop_end = FALSE;
    610 static bfd_boolean maybe_has_close_loop_end = FALSE;
    611 static bfd_boolean enforce_three_byte_loop_align = FALSE;
    612 
    613 /* When workaround_short_loops is TRUE, all loops with early exits must
    614    have at least 3 instructions.  workaround_all_short_loops is a modifier
    615    to the workaround_short_loop flag.  In addition to the
    616    workaround_short_loop actions, all straightline loopgtz and loopnez
    617    must have at least 3 instructions.  */
    618 
    619 static bfd_boolean workaround_all_short_loops = FALSE;
    620 
    621 
    622 static void
    623 xtensa_setup_hw_workarounds (int earliest, int latest)
    624 {
    625   if (earliest > latest)
    626     as_fatal (_("illegal range of target hardware versions"));
    627 
    628   /* Enable all workarounds for pre-T1050.0 hardware.  */
    629   if (earliest < 105000 || latest < 105000)
    630     {
    631       workaround_a0_b_retw |= TRUE;
    632       workaround_b_j_loop_end |= TRUE;
    633       workaround_short_loop |= TRUE;
    634       workaround_close_loop_end |= TRUE;
    635       workaround_all_short_loops |= TRUE;
    636       enforce_three_byte_loop_align = TRUE;
    637     }
    638 }
    639 
    640 
    641 enum
    642 {
    643   option_density = OPTION_MD_BASE,
    644   option_no_density,
    645 
    646   option_flix,
    647   option_no_generate_flix,
    648   option_no_flix,
    649 
    650   option_relax,
    651   option_no_relax,
    652 
    653   option_link_relax,
    654   option_no_link_relax,
    655 
    656   option_generics,
    657   option_no_generics,
    658 
    659   option_transform,
    660   option_no_transform,
    661 
    662   option_text_section_literals,
    663   option_no_text_section_literals,
    664 
    665   option_absolute_literals,
    666   option_no_absolute_literals,
    667 
    668   option_align_targets,
    669   option_no_align_targets,
    670 
    671   option_warn_unaligned_targets,
    672 
    673   option_longcalls,
    674   option_no_longcalls,
    675 
    676   option_workaround_a0_b_retw,
    677   option_no_workaround_a0_b_retw,
    678 
    679   option_workaround_b_j_loop_end,
    680   option_no_workaround_b_j_loop_end,
    681 
    682   option_workaround_short_loop,
    683   option_no_workaround_short_loop,
    684 
    685   option_workaround_all_short_loops,
    686   option_no_workaround_all_short_loops,
    687 
    688   option_workaround_close_loop_end,
    689   option_no_workaround_close_loop_end,
    690 
    691   option_no_workarounds,
    692 
    693   option_rename_section_name,
    694 
    695   option_prefer_l32r,
    696   option_prefer_const16,
    697 
    698   option_target_hardware,
    699 
    700   option_trampolines,
    701   option_no_trampolines,
    702 };
    703 
    704 const char *md_shortopts = "";
    705 
    706 struct option md_longopts[] =
    707 {
    708   { "density", no_argument, NULL, option_density },
    709   { "no-density", no_argument, NULL, option_no_density },
    710 
    711   { "flix", no_argument, NULL, option_flix },
    712   { "no-generate-flix", no_argument, NULL, option_no_generate_flix },
    713   { "no-allow-flix", no_argument, NULL, option_no_flix },
    714 
    715   /* Both "relax" and "generics" are deprecated and treated as equivalent
    716      to the "transform" option.  */
    717   { "relax", no_argument, NULL, option_relax },
    718   { "no-relax", no_argument, NULL, option_no_relax },
    719   { "generics", no_argument, NULL, option_generics },
    720   { "no-generics", no_argument, NULL, option_no_generics },
    721 
    722   { "transform", no_argument, NULL, option_transform },
    723   { "no-transform", no_argument, NULL, option_no_transform },
    724   { "text-section-literals", no_argument, NULL, option_text_section_literals },
    725   { "no-text-section-literals", no_argument, NULL,
    726     option_no_text_section_literals },
    727   { "absolute-literals", no_argument, NULL, option_absolute_literals },
    728   { "no-absolute-literals", no_argument, NULL, option_no_absolute_literals },
    729   /* This option was changed from -align-target to -target-align
    730      because it conflicted with the "-al" option.  */
    731   { "target-align", no_argument, NULL, option_align_targets },
    732   { "no-target-align", no_argument, NULL, option_no_align_targets },
    733   { "warn-unaligned-targets", no_argument, NULL,
    734     option_warn_unaligned_targets },
    735   { "longcalls", no_argument, NULL, option_longcalls },
    736   { "no-longcalls", no_argument, NULL, option_no_longcalls },
    737 
    738   { "no-workaround-a0-b-retw", no_argument, NULL,
    739     option_no_workaround_a0_b_retw },
    740   { "workaround-a0-b-retw", no_argument, NULL, option_workaround_a0_b_retw },
    741 
    742   { "no-workaround-b-j-loop-end", no_argument, NULL,
    743     option_no_workaround_b_j_loop_end },
    744   { "workaround-b-j-loop-end", no_argument, NULL,
    745     option_workaround_b_j_loop_end },
    746 
    747   { "no-workaround-short-loops", no_argument, NULL,
    748     option_no_workaround_short_loop },
    749   { "workaround-short-loops", no_argument, NULL,
    750     option_workaround_short_loop },
    751 
    752   { "no-workaround-all-short-loops", no_argument, NULL,
    753     option_no_workaround_all_short_loops },
    754   { "workaround-all-short-loop", no_argument, NULL,
    755     option_workaround_all_short_loops },
    756 
    757   { "prefer-l32r", no_argument, NULL, option_prefer_l32r },
    758   { "prefer-const16", no_argument, NULL, option_prefer_const16 },
    759 
    760   { "no-workarounds", no_argument, NULL, option_no_workarounds },
    761 
    762   { "no-workaround-close-loop-end", no_argument, NULL,
    763     option_no_workaround_close_loop_end },
    764   { "workaround-close-loop-end", no_argument, NULL,
    765     option_workaround_close_loop_end },
    766 
    767   { "rename-section", required_argument, NULL, option_rename_section_name },
    768 
    769   { "link-relax", no_argument, NULL, option_link_relax },
    770   { "no-link-relax", no_argument, NULL, option_no_link_relax },
    771 
    772   { "target-hardware", required_argument, NULL, option_target_hardware },
    773 
    774   { "trampolines", no_argument, NULL, option_trampolines },
    775   { "no-trampolines", no_argument, NULL, option_no_trampolines },
    776 
    777   { NULL, no_argument, NULL, 0 }
    778 };
    779 
    780 size_t md_longopts_size = sizeof md_longopts;
    781 
    782 
    783 int
    784 md_parse_option (int c, char *arg)
    785 {
    786   switch (c)
    787     {
    788     case option_density:
    789       as_warn (_("--density option is ignored"));
    790       return 1;
    791     case option_no_density:
    792       as_warn (_("--no-density option is ignored"));
    793       return 1;
    794     case option_link_relax:
    795       linkrelax = 1;
    796       return 1;
    797     case option_no_link_relax:
    798       linkrelax = 0;
    799       return 1;
    800     case option_flix:
    801       produce_flix = FLIX_ALL;
    802       return 1;
    803     case option_no_generate_flix:
    804       produce_flix = FLIX_NO_GENERATE;
    805       return 1;
    806     case option_no_flix:
    807       produce_flix = FLIX_NONE;
    808       return 1;
    809     case option_generics:
    810       as_warn (_("--generics is deprecated; use --transform instead"));
    811       return md_parse_option (option_transform, arg);
    812     case option_no_generics:
    813       as_warn (_("--no-generics is deprecated; use --no-transform instead"));
    814       return md_parse_option (option_no_transform, arg);
    815     case option_relax:
    816       as_warn (_("--relax is deprecated; use --transform instead"));
    817       return md_parse_option (option_transform, arg);
    818     case option_no_relax:
    819       as_warn (_("--no-relax is deprecated; use --no-transform instead"));
    820       return md_parse_option (option_no_transform, arg);
    821     case option_longcalls:
    822       directive_state[directive_longcalls] = TRUE;
    823       return 1;
    824     case option_no_longcalls:
    825       directive_state[directive_longcalls] = FALSE;
    826       return 1;
    827     case option_text_section_literals:
    828       use_literal_section = FALSE;
    829       return 1;
    830     case option_no_text_section_literals:
    831       use_literal_section = TRUE;
    832       return 1;
    833     case option_absolute_literals:
    834       if (!absolute_literals_supported)
    835 	{
    836 	  as_fatal (_("--absolute-literals option not supported in this Xtensa configuration"));
    837 	  return 0;
    838 	}
    839       directive_state[directive_absolute_literals] = TRUE;
    840       return 1;
    841     case option_no_absolute_literals:
    842       directive_state[directive_absolute_literals] = FALSE;
    843       return 1;
    844 
    845     case option_workaround_a0_b_retw:
    846       workaround_a0_b_retw = TRUE;
    847       return 1;
    848     case option_no_workaround_a0_b_retw:
    849       workaround_a0_b_retw = FALSE;
    850       return 1;
    851     case option_workaround_b_j_loop_end:
    852       workaround_b_j_loop_end = TRUE;
    853       return 1;
    854     case option_no_workaround_b_j_loop_end:
    855       workaround_b_j_loop_end = FALSE;
    856       return 1;
    857 
    858     case option_workaround_short_loop:
    859       workaround_short_loop = TRUE;
    860       return 1;
    861     case option_no_workaround_short_loop:
    862       workaround_short_loop = FALSE;
    863       return 1;
    864 
    865     case option_workaround_all_short_loops:
    866       workaround_all_short_loops = TRUE;
    867       return 1;
    868     case option_no_workaround_all_short_loops:
    869       workaround_all_short_loops = FALSE;
    870       return 1;
    871 
    872     case option_workaround_close_loop_end:
    873       workaround_close_loop_end = TRUE;
    874       return 1;
    875     case option_no_workaround_close_loop_end:
    876       workaround_close_loop_end = FALSE;
    877       return 1;
    878 
    879     case option_no_workarounds:
    880       workaround_a0_b_retw = FALSE;
    881       workaround_b_j_loop_end = FALSE;
    882       workaround_short_loop = FALSE;
    883       workaround_all_short_loops = FALSE;
    884       workaround_close_loop_end = FALSE;
    885       return 1;
    886 
    887     case option_align_targets:
    888       align_targets = TRUE;
    889       return 1;
    890     case option_no_align_targets:
    891       align_targets = FALSE;
    892       return 1;
    893 
    894     case option_warn_unaligned_targets:
    895       warn_unaligned_branch_targets = TRUE;
    896       return 1;
    897 
    898     case option_rename_section_name:
    899       build_section_rename (arg);
    900       return 1;
    901 
    902     case 'Q':
    903       /* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
    904          should be emitted or not.  FIXME: Not implemented.  */
    905       return 1;
    906 
    907     case option_prefer_l32r:
    908       if (prefer_const16)
    909 	as_fatal (_("prefer-l32r conflicts with prefer-const16"));
    910       prefer_l32r = 1;
    911       return 1;
    912 
    913     case option_prefer_const16:
    914       if (prefer_l32r)
    915 	as_fatal (_("prefer-const16 conflicts with prefer-l32r"));
    916       prefer_const16 = 1;
    917       return 1;
    918 
    919     case option_target_hardware:
    920       {
    921 	int earliest, latest = 0;
    922 	if (*arg == 0 || *arg == '-')
    923 	  as_fatal (_("invalid target hardware version"));
    924 
    925 	earliest = strtol (arg, &arg, 0);
    926 
    927 	if (*arg == 0)
    928 	  latest = earliest;
    929 	else if (*arg == '-')
    930 	  {
    931 	    if (*++arg == 0)
    932 	      as_fatal (_("invalid target hardware version"));
    933 	    latest = strtol (arg, &arg, 0);
    934 	  }
    935 	if (*arg != 0)
    936 	  as_fatal (_("invalid target hardware version"));
    937 
    938 	xtensa_setup_hw_workarounds (earliest, latest);
    939 	return 1;
    940       }
    941 
    942     case option_transform:
    943       /* This option has no affect other than to use the defaults,
    944 	 which are already set.  */
    945       return 1;
    946 
    947     case option_no_transform:
    948       /* This option turns off all transformations of any kind.
    949 	 However, because we want to preserve the state of other
    950 	 directives, we only change its own field.  Thus, before
    951 	 you perform any transformation, always check if transform
    952 	 is available.  If you use the functions we provide for this
    953 	 purpose, you will be ok.  */
    954       directive_state[directive_transform] = FALSE;
    955       return 1;
    956 
    957     case option_trampolines:
    958       use_trampolines = TRUE;
    959       return 1;
    960 
    961     case option_no_trampolines:
    962       use_trampolines = FALSE;
    963       return 1;
    964 
    965     default:
    966       return 0;
    967     }
    968 }
    969 
    970 
    971 void
    972 md_show_usage (FILE *stream)
    973 {
    974   fputs ("\n\
    975 Xtensa options:\n\
    976   --[no-]text-section-literals\n\
    977                           [Do not] put literals in the text section\n\
    978   --[no-]absolute-literals\n\
    979                           [Do not] default to use non-PC-relative literals\n\
    980   --[no-]target-align     [Do not] try to align branch targets\n\
    981   --[no-]longcalls        [Do not] emit 32-bit call sequences\n\
    982   --[no-]transform        [Do not] transform instructions\n\
    983   --flix                  both allow hand-written and generate flix bundles\n\
    984   --no-generate-flix      allow hand-written but do not generate\n\
    985                           flix bundles\n\
    986   --no-allow-flix         neither allow hand-written nor generate\n\
    987                           flix bundles\n\
    988   --rename-section old=new Rename section 'old' to 'new'\n\
    989   --[no-]trampolines      [Do not] generate trampolines (jumps to jumps)\n\
    990                           when jumps do not reach their targets\n", stream);
    991 }
    992 
    993 
    994 /* Functions related to the list of current label symbols.  */
    996 
    997 static void
    998 xtensa_add_insn_label (symbolS *sym)
    999 {
   1000   sym_list *l;
   1001 
   1002   if (!free_insn_labels)
   1003     l = (sym_list *) xmalloc (sizeof (sym_list));
   1004   else
   1005     {
   1006       l = free_insn_labels;
   1007       free_insn_labels = l->next;
   1008     }
   1009 
   1010   l->sym = sym;
   1011   l->next = insn_labels;
   1012   insn_labels = l;
   1013 }
   1014 
   1015 
   1016 static void
   1017 xtensa_clear_insn_labels (void)
   1018 {
   1019   sym_list **pl;
   1020 
   1021   for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
   1022     ;
   1023   *pl = insn_labels;
   1024   insn_labels = NULL;
   1025 }
   1026 
   1027 
   1028 static void
   1029 xtensa_move_labels (fragS *new_frag, valueT new_offset)
   1030 {
   1031   sym_list *lit;
   1032 
   1033   for (lit = insn_labels; lit; lit = lit->next)
   1034     {
   1035       symbolS *lit_sym = lit->sym;
   1036       S_SET_VALUE (lit_sym, new_offset);
   1037       symbol_set_frag (lit_sym, new_frag);
   1038     }
   1039 }
   1040 
   1041 
   1042 /* Directive data and functions.  */
   1044 
   1045 typedef struct state_stackS_struct
   1046 {
   1047   directiveE directive;
   1048   bfd_boolean negated;
   1049   bfd_boolean old_state;
   1050   const char *file;
   1051   unsigned int line;
   1052   const void *datum;
   1053   struct state_stackS_struct *prev;
   1054 } state_stackS;
   1055 
   1056 state_stackS *directive_state_stack;
   1057 
   1058 const pseudo_typeS md_pseudo_table[] =
   1059 {
   1060   { "align", s_align_bytes, 0 }, /* Defaulting is invalid (0).  */
   1061   { "literal_position", xtensa_literal_position, 0 },
   1062   { "frame", s_ignore, 0 },	/* Formerly used for STABS debugging.  */
   1063   { "long", xtensa_elf_cons, 4 },
   1064   { "word", xtensa_elf_cons, 4 },
   1065   { "4byte", xtensa_elf_cons, 4 },
   1066   { "short", xtensa_elf_cons, 2 },
   1067   { "2byte", xtensa_elf_cons, 2 },
   1068   { "sleb128", xtensa_leb128, 1},
   1069   { "uleb128", xtensa_leb128, 0},
   1070   { "begin", xtensa_begin_directive, 0 },
   1071   { "end", xtensa_end_directive, 0 },
   1072   { "literal", xtensa_literal_pseudo, 0 },
   1073   { "frequency", xtensa_frequency_pseudo, 0 },
   1074   { NULL, 0, 0 },
   1075 };
   1076 
   1077 
   1078 static bfd_boolean
   1079 use_transform (void)
   1080 {
   1081   /* After md_end, you should be checking frag by frag, rather
   1082      than state directives.  */
   1083   gas_assert (!past_xtensa_end);
   1084   return directive_state[directive_transform];
   1085 }
   1086 
   1087 
   1088 static bfd_boolean
   1089 do_align_targets (void)
   1090 {
   1091   /* Do not use this function after md_end; just look at align_targets
   1092      instead.  There is no target-align directive, so alignment is either
   1093      enabled for all frags or not done at all.  */
   1094   gas_assert (!past_xtensa_end);
   1095   return align_targets && use_transform ();
   1096 }
   1097 
   1098 
   1099 static void
   1100 directive_push (directiveE directive, bfd_boolean negated, const void *datum)
   1101 {
   1102   char *file;
   1103   unsigned int line;
   1104   state_stackS *stack = (state_stackS *) xmalloc (sizeof (state_stackS));
   1105 
   1106   as_where (&file, &line);
   1107 
   1108   stack->directive = directive;
   1109   stack->negated = negated;
   1110   stack->old_state = directive_state[directive];
   1111   stack->file = file;
   1112   stack->line = line;
   1113   stack->datum = datum;
   1114   stack->prev = directive_state_stack;
   1115   directive_state_stack = stack;
   1116 
   1117   directive_state[directive] = !negated;
   1118 }
   1119 
   1120 
   1121 static void
   1122 directive_pop (directiveE *directive,
   1123 	       bfd_boolean *negated,
   1124 	       const char **file,
   1125 	       unsigned int *line,
   1126 	       const void **datum)
   1127 {
   1128   state_stackS *top = directive_state_stack;
   1129 
   1130   if (!directive_state_stack)
   1131     {
   1132       as_bad (_("unmatched end directive"));
   1133       *directive = directive_none;
   1134       return;
   1135     }
   1136 
   1137   directive_state[directive_state_stack->directive] = top->old_state;
   1138   *directive = top->directive;
   1139   *negated = top->negated;
   1140   *file = top->file;
   1141   *line = top->line;
   1142   *datum = top->datum;
   1143   directive_state_stack = top->prev;
   1144   free (top);
   1145 }
   1146 
   1147 
   1148 static void
   1149 directive_balance (void)
   1150 {
   1151   while (directive_state_stack)
   1152     {
   1153       directiveE directive;
   1154       bfd_boolean negated;
   1155       const char *file;
   1156       unsigned int line;
   1157       const void *datum;
   1158 
   1159       directive_pop (&directive, &negated, &file, &line, &datum);
   1160       as_warn_where ((char *) file, line,
   1161 		     _(".begin directive with no matching .end directive"));
   1162     }
   1163 }
   1164 
   1165 
   1166 static bfd_boolean
   1167 inside_directive (directiveE dir)
   1168 {
   1169   state_stackS *top = directive_state_stack;
   1170 
   1171   while (top && top->directive != dir)
   1172     top = top->prev;
   1173 
   1174   return (top != NULL);
   1175 }
   1176 
   1177 
   1178 static void
   1179 get_directive (directiveE *directive, bfd_boolean *negated)
   1180 {
   1181   int len;
   1182   unsigned i;
   1183   char *directive_string;
   1184 
   1185   if (strncmp (input_line_pointer, "no-", 3) != 0)
   1186     *negated = FALSE;
   1187   else
   1188     {
   1189       *negated = TRUE;
   1190       input_line_pointer += 3;
   1191     }
   1192 
   1193   len = strspn (input_line_pointer,
   1194 		"abcdefghijklmnopqrstuvwxyz_-/0123456789.");
   1195 
   1196   /* This code is a hack to make .begin [no-][generics|relax] exactly
   1197      equivalent to .begin [no-]transform.  We should remove it when
   1198      we stop accepting those options.  */
   1199 
   1200   if (strncmp (input_line_pointer, "generics", strlen ("generics")) == 0)
   1201     {
   1202       as_warn (_("[no-]generics is deprecated; use [no-]transform instead"));
   1203       directive_string = "transform";
   1204     }
   1205   else if (strncmp (input_line_pointer, "relax", strlen ("relax")) == 0)
   1206     {
   1207       as_warn (_("[no-]relax is deprecated; use [no-]transform instead"));
   1208       directive_string = "transform";
   1209     }
   1210   else
   1211     directive_string = input_line_pointer;
   1212 
   1213   for (i = 0; i < sizeof (directive_info) / sizeof (*directive_info); ++i)
   1214     {
   1215       if (strncmp (directive_string, directive_info[i].name, len) == 0)
   1216 	{
   1217 	  input_line_pointer += len;
   1218 	  *directive = (directiveE) i;
   1219 	  if (*negated && !directive_info[i].can_be_negated)
   1220 	    as_bad (_("directive %s cannot be negated"),
   1221 		    directive_info[i].name);
   1222 	  return;
   1223 	}
   1224     }
   1225 
   1226   as_bad (_("unknown directive"));
   1227   *directive = (directiveE) XTENSA_UNDEFINED;
   1228 }
   1229 
   1230 
   1231 static void
   1232 xtensa_begin_directive (int ignore ATTRIBUTE_UNUSED)
   1233 {
   1234   directiveE directive;
   1235   bfd_boolean negated;
   1236   emit_state *state;
   1237   lit_state *ls;
   1238 
   1239   get_directive (&directive, &negated);
   1240   if (directive == (directiveE) XTENSA_UNDEFINED)
   1241     {
   1242       discard_rest_of_line ();
   1243       return;
   1244     }
   1245 
   1246   if (cur_vinsn.inside_bundle)
   1247     as_bad (_("directives are not valid inside bundles"));
   1248 
   1249   switch (directive)
   1250     {
   1251     case directive_literal:
   1252       if (!inside_directive (directive_literal))
   1253 	{
   1254 	  /* Previous labels go with whatever follows this directive, not with
   1255 	     the literal, so save them now.  */
   1256 	  saved_insn_labels = insn_labels;
   1257 	  insn_labels = NULL;
   1258 	}
   1259       as_warn (_(".begin literal is deprecated; use .literal instead"));
   1260       state = (emit_state *) xmalloc (sizeof (emit_state));
   1261       xtensa_switch_to_literal_fragment (state);
   1262       directive_push (directive_literal, negated, state);
   1263       break;
   1264 
   1265     case directive_literal_prefix:
   1266       /* Have to flush pending output because a movi relaxed to an l32r
   1267 	 might produce a literal.  */
   1268       md_flush_pending_output ();
   1269       /* Check to see if the current fragment is a literal
   1270 	 fragment.  If it is, then this operation is not allowed.  */
   1271       if (generating_literals)
   1272 	{
   1273 	  as_bad (_("cannot set literal_prefix inside literal fragment"));
   1274 	  return;
   1275 	}
   1276 
   1277       /* Allocate the literal state for this section and push
   1278 	 onto the directive stack.  */
   1279       ls = xmalloc (sizeof (lit_state));
   1280       gas_assert (ls);
   1281 
   1282       *ls = default_lit_sections;
   1283       directive_push (directive_literal_prefix, negated, ls);
   1284 
   1285       /* Process the new prefix.  */
   1286       xtensa_literal_prefix ();
   1287       break;
   1288 
   1289     case directive_freeregs:
   1290       /* This information is currently unused, but we'll accept the statement
   1291          and just discard the rest of the line.  This won't check the syntax,
   1292          but it will accept every correct freeregs directive.  */
   1293       input_line_pointer += strcspn (input_line_pointer, "\n");
   1294       directive_push (directive_freeregs, negated, 0);
   1295       break;
   1296 
   1297     case directive_schedule:
   1298       md_flush_pending_output ();
   1299       frag_var (rs_fill, 0, 0, frag_now->fr_subtype,
   1300 		frag_now->fr_symbol, frag_now->fr_offset, NULL);
   1301       directive_push (directive_schedule, negated, 0);
   1302       xtensa_set_frag_assembly_state (frag_now);
   1303       break;
   1304 
   1305     case directive_density:
   1306       as_warn (_(".begin [no-]density is ignored"));
   1307       break;
   1308 
   1309     case directive_absolute_literals:
   1310       md_flush_pending_output ();
   1311       if (!absolute_literals_supported && !negated)
   1312 	{
   1313 	  as_warn (_("Xtensa absolute literals option not supported; ignored"));
   1314 	  break;
   1315 	}
   1316       xtensa_set_frag_assembly_state (frag_now);
   1317       directive_push (directive, negated, 0);
   1318       break;
   1319 
   1320     default:
   1321       md_flush_pending_output ();
   1322       xtensa_set_frag_assembly_state (frag_now);
   1323       directive_push (directive, negated, 0);
   1324       break;
   1325     }
   1326 
   1327   demand_empty_rest_of_line ();
   1328 }
   1329 
   1330 
   1331 static void
   1332 xtensa_end_directive (int ignore ATTRIBUTE_UNUSED)
   1333 {
   1334   directiveE begin_directive, end_directive;
   1335   bfd_boolean begin_negated, end_negated;
   1336   const char *file;
   1337   unsigned int line;
   1338   emit_state *state;
   1339   emit_state **state_ptr;
   1340   lit_state *s;
   1341 
   1342   if (cur_vinsn.inside_bundle)
   1343     as_bad (_("directives are not valid inside bundles"));
   1344 
   1345   get_directive (&end_directive, &end_negated);
   1346 
   1347   md_flush_pending_output ();
   1348 
   1349   switch ((int) end_directive)
   1350     {
   1351     case XTENSA_UNDEFINED:
   1352       discard_rest_of_line ();
   1353       return;
   1354 
   1355     case (int) directive_density:
   1356       as_warn (_(".end [no-]density is ignored"));
   1357       demand_empty_rest_of_line ();
   1358       break;
   1359 
   1360     case (int) directive_absolute_literals:
   1361       if (!absolute_literals_supported && !end_negated)
   1362 	{
   1363 	  as_warn (_("Xtensa absolute literals option not supported; ignored"));
   1364 	  demand_empty_rest_of_line ();
   1365 	  return;
   1366 	}
   1367       break;
   1368 
   1369     default:
   1370       break;
   1371     }
   1372 
   1373   state_ptr = &state; /* use state_ptr to avoid type-punning warning */
   1374   directive_pop (&begin_directive, &begin_negated, &file, &line,
   1375 		 (const void **) state_ptr);
   1376 
   1377   if (begin_directive != directive_none)
   1378     {
   1379       if (begin_directive != end_directive || begin_negated != end_negated)
   1380 	{
   1381 	  as_bad (_("does not match begin %s%s at %s:%d"),
   1382 		  begin_negated ? "no-" : "",
   1383 		  directive_info[begin_directive].name, file, line);
   1384 	}
   1385       else
   1386 	{
   1387 	  switch (end_directive)
   1388 	    {
   1389 	    case directive_literal:
   1390 	      frag_var (rs_fill, 0, 0, 0, NULL, 0, NULL);
   1391 	      xtensa_restore_emit_state (state);
   1392 	      xtensa_set_frag_assembly_state (frag_now);
   1393 	      free (state);
   1394 	      if (!inside_directive (directive_literal))
   1395 		{
   1396 		  /* Restore the list of current labels.  */
   1397 		  xtensa_clear_insn_labels ();
   1398 		  insn_labels = saved_insn_labels;
   1399 		}
   1400 	      break;
   1401 
   1402 	    case directive_literal_prefix:
   1403 	      /* Restore the default collection sections from saved state.  */
   1404 	      s = (lit_state *) state;
   1405 	      gas_assert (s);
   1406 	      default_lit_sections = *s;
   1407 
   1408 	      /* Free the state storage.  */
   1409 	      free (s->lit_prefix);
   1410 	      free (s);
   1411 	      break;
   1412 
   1413 	    case directive_schedule:
   1414 	    case directive_freeregs:
   1415 	      break;
   1416 
   1417 	    default:
   1418 	      xtensa_set_frag_assembly_state (frag_now);
   1419 	      break;
   1420 	    }
   1421 	}
   1422     }
   1423 
   1424   demand_empty_rest_of_line ();
   1425 }
   1426 
   1427 
   1428 /* Place an aligned literal fragment at the current location.  */
   1429 
   1430 static void
   1431 xtensa_literal_position (int ignore ATTRIBUTE_UNUSED)
   1432 {
   1433   md_flush_pending_output ();
   1434 
   1435   if (inside_directive (directive_literal))
   1436     as_warn (_(".literal_position inside literal directive; ignoring"));
   1437   xtensa_mark_literal_pool_location ();
   1438 
   1439   demand_empty_rest_of_line ();
   1440   xtensa_clear_insn_labels ();
   1441 }
   1442 
   1443 
   1444 /* Support .literal label, expr, ...  */
   1445 
   1446 static void
   1447 xtensa_literal_pseudo (int ignored ATTRIBUTE_UNUSED)
   1448 {
   1449   emit_state state;
   1450   char *p, *base_name;
   1451   char c;
   1452   segT dest_seg;
   1453 
   1454   if (inside_directive (directive_literal))
   1455     {
   1456       as_bad (_(".literal not allowed inside .begin literal region"));
   1457       ignore_rest_of_line ();
   1458       return;
   1459     }
   1460 
   1461   md_flush_pending_output ();
   1462 
   1463   /* Previous labels go with whatever follows this directive, not with
   1464      the literal, so save them now.  */
   1465   saved_insn_labels = insn_labels;
   1466   insn_labels = NULL;
   1467 
   1468   /* If we are using text-section literals, then this is the right value... */
   1469   dest_seg = now_seg;
   1470 
   1471   base_name = input_line_pointer;
   1472 
   1473   xtensa_switch_to_literal_fragment (&state);
   1474 
   1475   /* ...but if we aren't using text-section-literals, then we
   1476      need to put them in the section we just switched to.  */
   1477   if (use_literal_section || directive_state[directive_absolute_literals])
   1478     dest_seg = now_seg;
   1479 
   1480   /* FIXME, despite the previous comments, dest_seg is unused...  */
   1481   (void) dest_seg;
   1482 
   1483   /* All literals are aligned to four-byte boundaries.  */
   1484   frag_align (2, 0, 0);
   1485   record_alignment (now_seg, 2);
   1486 
   1487   c = get_symbol_end ();
   1488   /* Just after name is now '\0'.  */
   1489   p = input_line_pointer;
   1490   *p = c;
   1491   SKIP_WHITESPACE ();
   1492 
   1493   if (*input_line_pointer != ',' && *input_line_pointer != ':')
   1494     {
   1495       as_bad (_("expected comma or colon after symbol name; "
   1496 		"rest of line ignored"));
   1497       ignore_rest_of_line ();
   1498       xtensa_restore_emit_state (&state);
   1499       return;
   1500     }
   1501   *p = 0;
   1502 
   1503   colon (base_name);
   1504 
   1505   *p = c;
   1506   input_line_pointer++;		/* skip ',' or ':' */
   1507 
   1508   xtensa_elf_cons (4);
   1509 
   1510   xtensa_restore_emit_state (&state);
   1511 
   1512   /* Restore the list of current labels.  */
   1513   xtensa_clear_insn_labels ();
   1514   insn_labels = saved_insn_labels;
   1515 }
   1516 
   1517 
   1518 static void
   1519 xtensa_literal_prefix (void)
   1520 {
   1521   char *name;
   1522   int len;
   1523 
   1524   /* Parse the new prefix from the input_line_pointer.  */
   1525   SKIP_WHITESPACE ();
   1526   len = strspn (input_line_pointer,
   1527 		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   1528 		"abcdefghijklmnopqrstuvwxyz_/0123456789.$");
   1529 
   1530   /* Get a null-terminated copy of the name.  */
   1531   name = xmalloc (len + 1);
   1532   gas_assert (name);
   1533   strncpy (name, input_line_pointer, len);
   1534   name[len] = 0;
   1535 
   1536   /* Skip the name in the input line.  */
   1537   input_line_pointer += len;
   1538 
   1539   default_lit_sections.lit_prefix = name;
   1540 
   1541   /* Clear cached literal sections, since the prefix has changed.  */
   1542   default_lit_sections.lit_seg = NULL;
   1543   default_lit_sections.lit4_seg = NULL;
   1544 }
   1545 
   1546 
   1547 /* Support ".frequency branch_target_frequency fall_through_frequency".  */
   1548 
   1549 static void
   1550 xtensa_frequency_pseudo (int ignored ATTRIBUTE_UNUSED)
   1551 {
   1552   float fall_through_f, target_f;
   1553 
   1554   fall_through_f = (float) strtod (input_line_pointer, &input_line_pointer);
   1555   if (fall_through_f < 0)
   1556     {
   1557       as_bad (_("fall through frequency must be greater than 0"));
   1558       ignore_rest_of_line ();
   1559       return;
   1560     }
   1561 
   1562   target_f = (float) strtod (input_line_pointer, &input_line_pointer);
   1563   if (target_f < 0)
   1564     {
   1565       as_bad (_("branch target frequency must be greater than 0"));
   1566       ignore_rest_of_line ();
   1567       return;
   1568     }
   1569 
   1570   set_subseg_freq (now_seg, now_subseg, target_f + fall_through_f, target_f);
   1571 
   1572   demand_empty_rest_of_line ();
   1573 }
   1574 
   1575 
   1576 /* Like normal .long/.short/.word, except support @plt, etc.
   1577    Clobbers input_line_pointer, checks end-of-line.  */
   1578 
   1579 static void
   1580 xtensa_elf_cons (int nbytes)
   1581 {
   1582   expressionS exp;
   1583   bfd_reloc_code_real_type reloc;
   1584 
   1585   md_flush_pending_output ();
   1586 
   1587   if (cur_vinsn.inside_bundle)
   1588     as_bad (_("directives are not valid inside bundles"));
   1589 
   1590   if (is_it_end_of_statement ())
   1591     {
   1592       demand_empty_rest_of_line ();
   1593       return;
   1594     }
   1595 
   1596   do
   1597     {
   1598       expression (&exp);
   1599       if (exp.X_op == O_symbol
   1600 	  && *input_line_pointer == '@'
   1601 	  && ((reloc = xtensa_elf_suffix (&input_line_pointer, &exp))
   1602 	      != BFD_RELOC_NONE))
   1603 	{
   1604 	  reloc_howto_type *reloc_howto =
   1605 	    bfd_reloc_type_lookup (stdoutput, reloc);
   1606 
   1607 	  if (reloc == BFD_RELOC_UNUSED || !reloc_howto)
   1608 	    as_bad (_("unsupported relocation"));
   1609 	  else if ((reloc >= BFD_RELOC_XTENSA_SLOT0_OP
   1610 		    && reloc <= BFD_RELOC_XTENSA_SLOT14_OP)
   1611 		   || (reloc >= BFD_RELOC_XTENSA_SLOT0_ALT
   1612 		       && reloc <= BFD_RELOC_XTENSA_SLOT14_ALT))
   1613 	    as_bad (_("opcode-specific %s relocation used outside "
   1614 		      "an instruction"), reloc_howto->name);
   1615 	  else if (nbytes != (int) bfd_get_reloc_size (reloc_howto))
   1616 	    as_bad (_("%s relocations do not fit in %d bytes"),
   1617 		    reloc_howto->name, nbytes);
   1618 	  else if (reloc == BFD_RELOC_XTENSA_TLS_FUNC
   1619 		   || reloc == BFD_RELOC_XTENSA_TLS_ARG
   1620 		   || reloc == BFD_RELOC_XTENSA_TLS_CALL)
   1621 	    as_bad (_("invalid use of %s relocation"), reloc_howto->name);
   1622 	  else
   1623 	    {
   1624 	      char *p = frag_more ((int) nbytes);
   1625 	      xtensa_set_frag_assembly_state (frag_now);
   1626 	      fix_new_exp (frag_now, p - frag_now->fr_literal,
   1627 			   nbytes, &exp, reloc_howto->pc_relative, reloc);
   1628 	    }
   1629 	}
   1630       else
   1631 	{
   1632 	  xtensa_set_frag_assembly_state (frag_now);
   1633 	  emit_expr (&exp, (unsigned int) nbytes);
   1634 	}
   1635     }
   1636   while (*input_line_pointer++ == ',');
   1637 
   1638   input_line_pointer--;		/* Put terminator back into stream.  */
   1639   demand_empty_rest_of_line ();
   1640 }
   1641 
   1642 static bfd_boolean is_leb128_expr;
   1643 
   1644 static void
   1645 xtensa_leb128 (int sign)
   1646 {
   1647   is_leb128_expr = TRUE;
   1648   s_leb128 (sign);
   1649   is_leb128_expr = FALSE;
   1650 }
   1651 
   1652 
   1653 /* Parsing and Idiom Translation.  */
   1655 
   1656 /* Parse @plt, etc. and return the desired relocation.  */
   1657 static bfd_reloc_code_real_type
   1658 xtensa_elf_suffix (char **str_p, expressionS *exp_p)
   1659 {
   1660   char ident[20];
   1661   char *str = *str_p;
   1662   char *str2;
   1663   int ch;
   1664   int len;
   1665   struct suffix_reloc_map *ptr;
   1666 
   1667   if (*str++ != '@')
   1668     return BFD_RELOC_NONE;
   1669 
   1670   for (ch = *str, str2 = ident;
   1671        (str2 < ident + sizeof (ident) - 1
   1672 	&& (ISALNUM (ch) || ch == '@'));
   1673        ch = *++str)
   1674     {
   1675       *str2++ = (ISLOWER (ch)) ? ch : TOLOWER (ch);
   1676     }
   1677 
   1678   *str2 = '\0';
   1679   len = str2 - ident;
   1680 
   1681   ch = ident[0];
   1682   for (ptr = &suffix_relocs[0]; ptr->length > 0; ptr++)
   1683     if (ch == ptr->suffix[0]
   1684 	&& len == ptr->length
   1685 	&& memcmp (ident, ptr->suffix, ptr->length) == 0)
   1686       {
   1687 	/* Now check for "identifier@suffix+constant".  */
   1688 	if (*str == '-' || *str == '+')
   1689 	  {
   1690 	    char *orig_line = input_line_pointer;
   1691 	    expressionS new_exp;
   1692 
   1693 	    input_line_pointer = str;
   1694 	    expression (&new_exp);
   1695 	    if (new_exp.X_op == O_constant)
   1696 	      {
   1697 		exp_p->X_add_number += new_exp.X_add_number;
   1698 		str = input_line_pointer;
   1699 	      }
   1700 
   1701 	    if (&input_line_pointer != str_p)
   1702 	      input_line_pointer = orig_line;
   1703 	  }
   1704 
   1705 	*str_p = str;
   1706 	return ptr->reloc;
   1707       }
   1708 
   1709   return BFD_RELOC_UNUSED;
   1710 }
   1711 
   1712 
   1713 /* Find the matching operator type.  */
   1714 static unsigned char
   1715 map_suffix_reloc_to_operator (bfd_reloc_code_real_type reloc)
   1716 {
   1717   struct suffix_reloc_map *sfx;
   1718   unsigned char operator = (unsigned char) -1;
   1719 
   1720   for (sfx = &suffix_relocs[0]; sfx->suffix; sfx++)
   1721     {
   1722       if (sfx->reloc == reloc)
   1723 	{
   1724 	  operator = sfx->operator;
   1725 	  break;
   1726 	}
   1727     }
   1728   gas_assert (operator != (unsigned char) -1);
   1729   return operator;
   1730 }
   1731 
   1732 
   1733 /* Find the matching reloc type.  */
   1734 static bfd_reloc_code_real_type
   1735 map_operator_to_reloc (unsigned char operator, bfd_boolean is_literal)
   1736 {
   1737   struct suffix_reloc_map *sfx;
   1738   bfd_reloc_code_real_type reloc = BFD_RELOC_UNUSED;
   1739 
   1740   for (sfx = &suffix_relocs[0]; sfx->suffix; sfx++)
   1741     {
   1742       if (sfx->operator == operator)
   1743 	{
   1744 	  reloc = sfx->reloc;
   1745 	  break;
   1746 	}
   1747     }
   1748 
   1749   if (is_literal)
   1750     {
   1751       if (reloc == BFD_RELOC_XTENSA_TLS_FUNC)
   1752 	return BFD_RELOC_XTENSA_TLSDESC_FN;
   1753       else if (reloc == BFD_RELOC_XTENSA_TLS_ARG)
   1754 	return BFD_RELOC_XTENSA_TLSDESC_ARG;
   1755     }
   1756 
   1757   if (reloc == BFD_RELOC_UNUSED)
   1758     return BFD_RELOC_32;
   1759 
   1760   return reloc;
   1761 }
   1762 
   1763 
   1764 static const char *
   1765 expression_end (const char *name)
   1766 {
   1767   while (1)
   1768     {
   1769       switch (*name)
   1770 	{
   1771 	case '}':
   1772 	case ';':
   1773 	case '\0':
   1774 	case ',':
   1775 	case ':':
   1776 	  return name;
   1777 	case ' ':
   1778 	case '\t':
   1779 	  ++name;
   1780 	  continue;
   1781 	default:
   1782 	  return 0;
   1783 	}
   1784     }
   1785 }
   1786 
   1787 
   1788 #define ERROR_REG_NUM ((unsigned) -1)
   1789 
   1790 static unsigned
   1791 tc_get_register (const char *prefix)
   1792 {
   1793   unsigned reg;
   1794   const char *next_expr;
   1795   const char *old_line_pointer;
   1796 
   1797   SKIP_WHITESPACE ();
   1798   old_line_pointer = input_line_pointer;
   1799 
   1800   if (*input_line_pointer == '$')
   1801     ++input_line_pointer;
   1802 
   1803   /* Accept "sp" as a synonym for "a1".  */
   1804   if (input_line_pointer[0] == 's' && input_line_pointer[1] == 'p'
   1805       && expression_end (input_line_pointer + 2))
   1806     {
   1807       input_line_pointer += 2;
   1808       return 1;  /* AR[1] */
   1809     }
   1810 
   1811   while (*input_line_pointer++ == *prefix++)
   1812     ;
   1813   --input_line_pointer;
   1814   --prefix;
   1815 
   1816   if (*prefix)
   1817     {
   1818       as_bad (_("bad register name: %s"), old_line_pointer);
   1819       return ERROR_REG_NUM;
   1820     }
   1821 
   1822   if (!ISDIGIT ((unsigned char) *input_line_pointer))
   1823     {
   1824       as_bad (_("bad register number: %s"), input_line_pointer);
   1825       return ERROR_REG_NUM;
   1826     }
   1827 
   1828   reg = 0;
   1829 
   1830   while (ISDIGIT ((int) *input_line_pointer))
   1831     reg = reg * 10 + *input_line_pointer++ - '0';
   1832 
   1833   if (!(next_expr = expression_end (input_line_pointer)))
   1834     {
   1835       as_bad (_("bad register name: %s"), old_line_pointer);
   1836       return ERROR_REG_NUM;
   1837     }
   1838 
   1839   input_line_pointer = (char *) next_expr;
   1840 
   1841   return reg;
   1842 }
   1843 
   1844 
   1845 static void
   1846 expression_maybe_register (xtensa_opcode opc, int opnd, expressionS *tok)
   1847 {
   1848   xtensa_isa isa = xtensa_default_isa;
   1849 
   1850   /* Check if this is an immediate operand.  */
   1851   if (xtensa_operand_is_register (isa, opc, opnd) == 0)
   1852     {
   1853       bfd_reloc_code_real_type reloc;
   1854       segT t = expression (tok);
   1855 
   1856       if (t == absolute_section
   1857 	  && xtensa_operand_is_PCrelative (isa, opc, opnd) == 1)
   1858 	{
   1859 	  gas_assert (tok->X_op == O_constant);
   1860 	  tok->X_op = O_symbol;
   1861 	  tok->X_add_symbol = &abs_symbol;
   1862 	}
   1863 
   1864       if ((tok->X_op == O_constant || tok->X_op == O_symbol)
   1865 	  && ((reloc = xtensa_elf_suffix (&input_line_pointer, tok))
   1866 	      != BFD_RELOC_NONE))
   1867 	{
   1868 	  switch (reloc)
   1869 	    {
   1870 	    case BFD_RELOC_LO16:
   1871 	      if (tok->X_op == O_constant)
   1872 		{
   1873 		  tok->X_add_number &= 0xffff;
   1874 		  return;
   1875 		}
   1876 	      break;
   1877 	    case BFD_RELOC_HI16:
   1878 	      if (tok->X_op == O_constant)
   1879 		{
   1880 		  tok->X_add_number = ((unsigned) tok->X_add_number) >> 16;
   1881 		  return;
   1882 		}
   1883 	      break;
   1884 	    case BFD_RELOC_UNUSED:
   1885 	      as_bad (_("unsupported relocation"));
   1886 	      return;
   1887 	    case BFD_RELOC_32_PCREL:
   1888 	      as_bad (_("pcrel relocation not allowed in an instruction"));
   1889 	      return;
   1890 	    default:
   1891 	      break;
   1892 	    }
   1893 	  tok->X_op = map_suffix_reloc_to_operator (reloc);
   1894 	}
   1895     }
   1896   else
   1897     {
   1898       xtensa_regfile opnd_rf = xtensa_operand_regfile (isa, opc, opnd);
   1899       unsigned reg = tc_get_register (xtensa_regfile_shortname (isa, opnd_rf));
   1900 
   1901       if (reg != ERROR_REG_NUM)	/* Already errored */
   1902 	{
   1903 	  uint32 buf = reg;
   1904 	  if (xtensa_operand_encode (isa, opc, opnd, &buf))
   1905 	    as_bad (_("register number out of range"));
   1906 	}
   1907 
   1908       tok->X_op = O_register;
   1909       tok->X_add_symbol = 0;
   1910       tok->X_add_number = reg;
   1911     }
   1912 }
   1913 
   1914 
   1915 /* Split up the arguments for an opcode or pseudo-op.  */
   1916 
   1917 static int
   1918 tokenize_arguments (char **args, char *str)
   1919 {
   1920   char *old_input_line_pointer;
   1921   bfd_boolean saw_comma = FALSE;
   1922   bfd_boolean saw_arg = FALSE;
   1923   bfd_boolean saw_colon = FALSE;
   1924   int num_args = 0;
   1925   char *arg_end, *arg;
   1926   int arg_len;
   1927 
   1928   /* Save and restore input_line_pointer around this function.  */
   1929   old_input_line_pointer = input_line_pointer;
   1930   input_line_pointer = str;
   1931 
   1932   while (*input_line_pointer)
   1933     {
   1934       SKIP_WHITESPACE ();
   1935       switch (*input_line_pointer)
   1936 	{
   1937 	case '\0':
   1938 	case '}':
   1939 	  goto fini;
   1940 
   1941 	case ':':
   1942 	  input_line_pointer++;
   1943 	  if (saw_comma || saw_colon || !saw_arg)
   1944 	    goto err;
   1945 	  saw_colon = TRUE;
   1946 	  break;
   1947 
   1948 	case ',':
   1949 	  input_line_pointer++;
   1950 	  if (saw_comma || saw_colon || !saw_arg)
   1951 	    goto err;
   1952 	  saw_comma = TRUE;
   1953 	  break;
   1954 
   1955 	default:
   1956 	  if (!saw_comma && !saw_colon && saw_arg)
   1957 	    goto err;
   1958 
   1959 	  arg_end = input_line_pointer + 1;
   1960 	  while (!expression_end (arg_end))
   1961 	    arg_end += 1;
   1962 
   1963 	  arg_len = arg_end - input_line_pointer;
   1964 	  arg = (char *) xmalloc ((saw_colon ? 1 : 0) + arg_len + 1);
   1965 	  args[num_args] = arg;
   1966 
   1967 	  if (saw_colon)
   1968 	    *arg++ = ':';
   1969 	  strncpy (arg, input_line_pointer, arg_len);
   1970 	  arg[arg_len] = '\0';
   1971 
   1972 	  input_line_pointer = arg_end;
   1973 	  num_args += 1;
   1974 	  saw_comma = FALSE;
   1975 	  saw_colon = FALSE;
   1976 	  saw_arg = TRUE;
   1977 	  break;
   1978 	}
   1979     }
   1980 
   1981 fini:
   1982   if (saw_comma || saw_colon)
   1983     goto err;
   1984   input_line_pointer = old_input_line_pointer;
   1985   return num_args;
   1986 
   1987 err:
   1988   if (saw_comma)
   1989     as_bad (_("extra comma"));
   1990   else if (saw_colon)
   1991     as_bad (_("extra colon"));
   1992   else if (!saw_arg)
   1993     as_bad (_("missing argument"));
   1994   else
   1995     as_bad (_("missing comma or colon"));
   1996   input_line_pointer = old_input_line_pointer;
   1997   return -1;
   1998 }
   1999 
   2000 
   2001 /* Parse the arguments to an opcode.  Return TRUE on error.  */
   2002 
   2003 static bfd_boolean
   2004 parse_arguments (TInsn *insn, int num_args, char **arg_strings)
   2005 {
   2006   expressionS *tok, *last_tok;
   2007   xtensa_opcode opcode = insn->opcode;
   2008   bfd_boolean had_error = TRUE;
   2009   xtensa_isa isa = xtensa_default_isa;
   2010   int n, num_regs = 0;
   2011   int opcode_operand_count;
   2012   int opnd_cnt, last_opnd_cnt;
   2013   unsigned int next_reg = 0;
   2014   char *old_input_line_pointer;
   2015 
   2016   if (insn->insn_type == ITYPE_LITERAL)
   2017     opcode_operand_count = 1;
   2018   else
   2019     opcode_operand_count = xtensa_opcode_num_operands (isa, opcode);
   2020 
   2021   tok = insn->tok;
   2022   memset (tok, 0, sizeof (*tok) * MAX_INSN_ARGS);
   2023 
   2024   /* Save and restore input_line_pointer around this function.  */
   2025   old_input_line_pointer = input_line_pointer;
   2026 
   2027   last_tok = 0;
   2028   last_opnd_cnt = -1;
   2029   opnd_cnt = 0;
   2030 
   2031   /* Skip invisible operands.  */
   2032   while (xtensa_operand_is_visible (isa, opcode, opnd_cnt) == 0)
   2033     {
   2034       opnd_cnt += 1;
   2035       tok++;
   2036     }
   2037 
   2038   for (n = 0; n < num_args; n++)
   2039     {
   2040       input_line_pointer = arg_strings[n];
   2041       if (*input_line_pointer == ':')
   2042 	{
   2043 	  xtensa_regfile opnd_rf;
   2044 	  input_line_pointer++;
   2045 	  if (num_regs == 0)
   2046 	    goto err;
   2047 	  gas_assert (opnd_cnt > 0);
   2048 	  num_regs--;
   2049 	  opnd_rf = xtensa_operand_regfile (isa, opcode, last_opnd_cnt);
   2050 	  if (next_reg
   2051 	      != tc_get_register (xtensa_regfile_shortname (isa, opnd_rf)))
   2052 	    as_warn (_("incorrect register number, ignoring"));
   2053 	  next_reg++;
   2054 	}
   2055       else
   2056 	{
   2057 	  if (opnd_cnt >= opcode_operand_count)
   2058 	    {
   2059 	      as_warn (_("too many arguments"));
   2060 	      goto err;
   2061 	    }
   2062 	  gas_assert (opnd_cnt < MAX_INSN_ARGS);
   2063 
   2064 	  expression_maybe_register (opcode, opnd_cnt, tok);
   2065 	  next_reg = tok->X_add_number + 1;
   2066 
   2067 	  if (tok->X_op == O_illegal || tok->X_op == O_absent)
   2068 	    goto err;
   2069 	  if (xtensa_operand_is_register (isa, opcode, opnd_cnt) == 1)
   2070 	    {
   2071 	      num_regs = xtensa_operand_num_regs (isa, opcode, opnd_cnt) - 1;
   2072 	      /* minus 1 because we are seeing one right now */
   2073 	    }
   2074 	  else
   2075 	    num_regs = 0;
   2076 
   2077 	  last_tok = tok;
   2078 	  last_opnd_cnt = opnd_cnt;
   2079 	  demand_empty_rest_of_line ();
   2080 
   2081 	  do
   2082 	    {
   2083 	      opnd_cnt += 1;
   2084 	      tok++;
   2085 	    }
   2086 	  while (xtensa_operand_is_visible (isa, opcode, opnd_cnt) == 0);
   2087 	}
   2088     }
   2089 
   2090   if (num_regs > 0 && ((int) next_reg != last_tok->X_add_number + 1))
   2091     goto err;
   2092 
   2093   insn->ntok = tok - insn->tok;
   2094   had_error = FALSE;
   2095 
   2096  err:
   2097   input_line_pointer = old_input_line_pointer;
   2098   return had_error;
   2099 }
   2100 
   2101 
   2102 static int
   2103 get_invisible_operands (TInsn *insn)
   2104 {
   2105   xtensa_isa isa = xtensa_default_isa;
   2106   static xtensa_insnbuf slotbuf = NULL;
   2107   xtensa_format fmt;
   2108   xtensa_opcode opc = insn->opcode;
   2109   int slot, opnd, fmt_found;
   2110   unsigned val;
   2111 
   2112   if (!slotbuf)
   2113     slotbuf = xtensa_insnbuf_alloc (isa);
   2114 
   2115   /* Find format/slot where this can be encoded.  */
   2116   fmt_found = 0;
   2117   slot = 0;
   2118   for (fmt = 0; fmt < xtensa_isa_num_formats (isa); fmt++)
   2119     {
   2120       for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
   2121 	{
   2122 	  if (xtensa_opcode_encode (isa, fmt, slot, slotbuf, opc) == 0)
   2123 	    {
   2124 	      fmt_found = 1;
   2125 	      break;
   2126 	    }
   2127 	}
   2128       if (fmt_found) break;
   2129     }
   2130 
   2131   if (!fmt_found)
   2132     {
   2133       as_bad (_("cannot encode opcode \"%s\""), xtensa_opcode_name (isa, opc));
   2134       return -1;
   2135     }
   2136 
   2137   /* First encode all the visible operands
   2138      (to deal with shared field operands).  */
   2139   for (opnd = 0; opnd < insn->ntok; opnd++)
   2140     {
   2141       if (xtensa_operand_is_visible (isa, opc, opnd) == 1
   2142 	  && (insn->tok[opnd].X_op == O_register
   2143 	      || insn->tok[opnd].X_op == O_constant))
   2144 	{
   2145 	  val = insn->tok[opnd].X_add_number;
   2146 	  xtensa_operand_encode (isa, opc, opnd, &val);
   2147 	  xtensa_operand_set_field (isa, opc, opnd, fmt, slot, slotbuf, val);
   2148 	}
   2149     }
   2150 
   2151   /* Then pull out the values for the invisible ones.  */
   2152   for (opnd = 0; opnd < insn->ntok; opnd++)
   2153     {
   2154       if (xtensa_operand_is_visible (isa, opc, opnd) == 0)
   2155 	{
   2156 	  xtensa_operand_get_field (isa, opc, opnd, fmt, slot, slotbuf, &val);
   2157 	  xtensa_operand_decode (isa, opc, opnd, &val);
   2158 	  insn->tok[opnd].X_add_number = val;
   2159 	  if (xtensa_operand_is_register (isa, opc, opnd) == 1)
   2160 	    insn->tok[opnd].X_op = O_register;
   2161 	  else
   2162 	    insn->tok[opnd].X_op = O_constant;
   2163 	}
   2164     }
   2165 
   2166   return 0;
   2167 }
   2168 
   2169 
   2170 static void
   2171 xg_reverse_shift_count (char **cnt_argp)
   2172 {
   2173   char *cnt_arg, *new_arg;
   2174   cnt_arg = *cnt_argp;
   2175 
   2176   /* replace the argument with "31-(argument)" */
   2177   new_arg = (char *) xmalloc (strlen (cnt_arg) + 6);
   2178   sprintf (new_arg, "31-(%s)", cnt_arg);
   2179 
   2180   free (cnt_arg);
   2181   *cnt_argp = new_arg;
   2182 }
   2183 
   2184 
   2185 /* If "arg" is a constant expression, return non-zero with the value
   2186    in *valp.  */
   2187 
   2188 static int
   2189 xg_arg_is_constant (char *arg, offsetT *valp)
   2190 {
   2191   expressionS exp;
   2192   char *save_ptr = input_line_pointer;
   2193 
   2194   input_line_pointer = arg;
   2195   expression (&exp);
   2196   input_line_pointer = save_ptr;
   2197 
   2198   if (exp.X_op == O_constant)
   2199     {
   2200       *valp = exp.X_add_number;
   2201       return 1;
   2202     }
   2203 
   2204   return 0;
   2205 }
   2206 
   2207 
   2208 static void
   2209 xg_replace_opname (char **popname, char *newop)
   2210 {
   2211   free (*popname);
   2212   *popname = (char *) xmalloc (strlen (newop) + 1);
   2213   strcpy (*popname, newop);
   2214 }
   2215 
   2216 
   2217 static int
   2218 xg_check_num_args (int *pnum_args,
   2219 		   int expected_num,
   2220 		   char *opname,
   2221 		   char **arg_strings)
   2222 {
   2223   int num_args = *pnum_args;
   2224 
   2225   if (num_args < expected_num)
   2226     {
   2227       as_bad (_("not enough operands (%d) for '%s'; expected %d"),
   2228 	      num_args, opname, expected_num);
   2229       return -1;
   2230     }
   2231 
   2232   if (num_args > expected_num)
   2233     {
   2234       as_warn (_("too many operands (%d) for '%s'; expected %d"),
   2235 	       num_args, opname, expected_num);
   2236       while (num_args-- > expected_num)
   2237 	{
   2238 	  free (arg_strings[num_args]);
   2239 	  arg_strings[num_args] = 0;
   2240 	}
   2241       *pnum_args = expected_num;
   2242       return -1;
   2243     }
   2244 
   2245   return 0;
   2246 }
   2247 
   2248 
   2249 /* If the register is not specified as part of the opcode,
   2250    then get it from the operand and move it to the opcode.  */
   2251 
   2252 static int
   2253 xg_translate_sysreg_op (char **popname, int *pnum_args, char **arg_strings)
   2254 {
   2255   xtensa_isa isa = xtensa_default_isa;
   2256   xtensa_sysreg sr;
   2257   char *opname, *new_opname;
   2258   const char *sr_name;
   2259   int is_user, is_write;
   2260 
   2261   opname = *popname;
   2262   if (*opname == '_')
   2263     opname += 1;
   2264   is_user = (opname[1] == 'u');
   2265   is_write = (opname[0] == 'w');
   2266 
   2267   /* Opname == [rw]ur or [rwx]sr... */
   2268 
   2269   if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
   2270     return -1;
   2271 
   2272   /* Check if the argument is a symbolic register name.  */
   2273   sr = xtensa_sysreg_lookup_name (isa, arg_strings[1]);
   2274   /* Handle WSR to "INTSET" as a special case.  */
   2275   if (sr == XTENSA_UNDEFINED && is_write && !is_user
   2276       && !strcasecmp (arg_strings[1], "intset"))
   2277     sr = xtensa_sysreg_lookup_name (isa, "interrupt");
   2278   if (sr == XTENSA_UNDEFINED
   2279       || (xtensa_sysreg_is_user (isa, sr) == 1) != is_user)
   2280     {
   2281       /* Maybe it's a register number.... */
   2282       offsetT val;
   2283       if (!xg_arg_is_constant (arg_strings[1], &val))
   2284 	{
   2285 	  as_bad (_("invalid register '%s' for '%s' instruction"),
   2286 		  arg_strings[1], opname);
   2287 	  return -1;
   2288 	}
   2289       sr = xtensa_sysreg_lookup (isa, val, is_user);
   2290       if (sr == XTENSA_UNDEFINED)
   2291 	{
   2292 	  as_bad (_("invalid register number (%ld) for '%s' instruction"),
   2293 		  (long) val, opname);
   2294 	  return -1;
   2295 	}
   2296     }
   2297 
   2298   /* Remove the last argument, which is now part of the opcode.  */
   2299   free (arg_strings[1]);
   2300   arg_strings[1] = 0;
   2301   *pnum_args = 1;
   2302 
   2303   /* Translate the opcode.  */
   2304   sr_name = xtensa_sysreg_name (isa, sr);
   2305   /* Another special case for "WSR.INTSET"....  */
   2306   if (is_write && !is_user && !strcasecmp ("interrupt", sr_name))
   2307     sr_name = "intset";
   2308   new_opname = (char *) xmalloc (strlen (sr_name) + 6);
   2309   sprintf (new_opname, "%s.%s", *popname, sr_name);
   2310   free (*popname);
   2311   *popname = new_opname;
   2312 
   2313   return 0;
   2314 }
   2315 
   2316 
   2317 static int
   2318 xtensa_translate_old_userreg_ops (char **popname)
   2319 {
   2320   xtensa_isa isa = xtensa_default_isa;
   2321   xtensa_sysreg sr;
   2322   char *opname, *new_opname;
   2323   const char *sr_name;
   2324   bfd_boolean has_underbar = FALSE;
   2325 
   2326   opname = *popname;
   2327   if (opname[0] == '_')
   2328     {
   2329       has_underbar = TRUE;
   2330       opname += 1;
   2331     }
   2332 
   2333   sr = xtensa_sysreg_lookup_name (isa, opname + 1);
   2334   if (sr != XTENSA_UNDEFINED)
   2335     {
   2336       /* The new default name ("nnn") is different from the old default
   2337 	 name ("URnnn").  The old default is handled below, and we don't
   2338 	 want to recognize [RW]nnn, so do nothing if the name is the (new)
   2339 	 default.  */
   2340       static char namebuf[10];
   2341       sprintf (namebuf, "%d", xtensa_sysreg_number (isa, sr));
   2342       if (strcmp (namebuf, opname + 1) == 0)
   2343 	return 0;
   2344     }
   2345   else
   2346     {
   2347       offsetT val;
   2348       char *end;
   2349 
   2350       /* Only continue if the reg name is "URnnn".  */
   2351       if (opname[1] != 'u' || opname[2] != 'r')
   2352 	return 0;
   2353       val = strtoul (opname + 3, &end, 10);
   2354       if (*end != '\0')
   2355 	return 0;
   2356 
   2357       sr = xtensa_sysreg_lookup (isa, val, 1);
   2358       if (sr == XTENSA_UNDEFINED)
   2359 	{
   2360 	  as_bad (_("invalid register number (%ld) for '%s'"),
   2361 		  (long) val, opname);
   2362 	  return -1;
   2363 	}
   2364     }
   2365 
   2366   /* Translate the opcode.  */
   2367   sr_name = xtensa_sysreg_name (isa, sr);
   2368   new_opname = (char *) xmalloc (strlen (sr_name) + 6);
   2369   sprintf (new_opname, "%s%cur.%s", (has_underbar ? "_" : ""),
   2370 	   opname[0], sr_name);
   2371   free (*popname);
   2372   *popname = new_opname;
   2373 
   2374   return 0;
   2375 }
   2376 
   2377 
   2378 static int
   2379 xtensa_translate_zero_immed (char *old_op,
   2380 			     char *new_op,
   2381 			     char **popname,
   2382 			     int *pnum_args,
   2383 			     char **arg_strings)
   2384 {
   2385   char *opname;
   2386   offsetT val;
   2387 
   2388   opname = *popname;
   2389   gas_assert (opname[0] != '_');
   2390 
   2391   if (strcmp (opname, old_op) != 0)
   2392     return 0;
   2393 
   2394   if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
   2395     return -1;
   2396   if (xg_arg_is_constant (arg_strings[1], &val) && val == 0)
   2397     {
   2398       xg_replace_opname (popname, new_op);
   2399       free (arg_strings[1]);
   2400       arg_strings[1] = arg_strings[2];
   2401       arg_strings[2] = 0;
   2402       *pnum_args = 2;
   2403     }
   2404 
   2405   return 0;
   2406 }
   2407 
   2408 
   2409 /* If the instruction is an idiom (i.e., a built-in macro), translate it.
   2410    Returns non-zero if an error was found.  */
   2411 
   2412 static int
   2413 xg_translate_idioms (char **popname, int *pnum_args, char **arg_strings)
   2414 {
   2415   char *opname = *popname;
   2416   bfd_boolean has_underbar = FALSE;
   2417 
   2418   if (*opname == '_')
   2419     {
   2420       has_underbar = TRUE;
   2421       opname += 1;
   2422     }
   2423 
   2424   if (strcmp (opname, "mov") == 0)
   2425     {
   2426       if (use_transform () && !has_underbar && density_supported)
   2427 	xg_replace_opname (popname, "mov.n");
   2428       else
   2429 	{
   2430 	  if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
   2431 	    return -1;
   2432 	  xg_replace_opname (popname, (has_underbar ? "_or" : "or"));
   2433 	  arg_strings[2] = (char *) xmalloc (strlen (arg_strings[1]) + 1);
   2434 	  strcpy (arg_strings[2], arg_strings[1]);
   2435 	  *pnum_args = 3;
   2436 	}
   2437       return 0;
   2438     }
   2439 
   2440   if (strcmp (opname, "bbsi.l") == 0)
   2441     {
   2442       if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
   2443 	return -1;
   2444       xg_replace_opname (popname, (has_underbar ? "_bbsi" : "bbsi"));
   2445       if (target_big_endian)
   2446 	xg_reverse_shift_count (&arg_strings[1]);
   2447       return 0;
   2448     }
   2449 
   2450   if (strcmp (opname, "bbci.l") == 0)
   2451     {
   2452       if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
   2453 	return -1;
   2454       xg_replace_opname (popname, (has_underbar ? "_bbci" : "bbci"));
   2455       if (target_big_endian)
   2456 	xg_reverse_shift_count (&arg_strings[1]);
   2457       return 0;
   2458     }
   2459 
   2460   /* Don't do anything special with NOPs inside FLIX instructions.  They
   2461      are handled elsewhere.  Real NOP instructions are always available
   2462      in configurations with FLIX, so this should never be an issue but
   2463      check for it anyway.  */
   2464   if (!cur_vinsn.inside_bundle && xtensa_nop_opcode == XTENSA_UNDEFINED
   2465       && strcmp (opname, "nop") == 0)
   2466     {
   2467       if (use_transform () && !has_underbar && density_supported)
   2468 	xg_replace_opname (popname, "nop.n");
   2469       else
   2470 	{
   2471 	  if (xg_check_num_args (pnum_args, 0, opname, arg_strings))
   2472 	    return -1;
   2473 	  xg_replace_opname (popname, (has_underbar ? "_or" : "or"));
   2474 	  arg_strings[0] = (char *) xmalloc (3);
   2475 	  arg_strings[1] = (char *) xmalloc (3);
   2476 	  arg_strings[2] = (char *) xmalloc (3);
   2477 	  strcpy (arg_strings[0], "a1");
   2478 	  strcpy (arg_strings[1], "a1");
   2479 	  strcpy (arg_strings[2], "a1");
   2480 	  *pnum_args = 3;
   2481 	}
   2482       return 0;
   2483     }
   2484 
   2485   /* Recognize [RW]UR and [RWX]SR.  */
   2486   if ((((opname[0] == 'r' || opname[0] == 'w')
   2487 	&& (opname[1] == 'u' || opname[1] == 's'))
   2488        || (opname[0] == 'x' && opname[1] == 's'))
   2489       && opname[2] == 'r'
   2490       && opname[3] == '\0')
   2491     return xg_translate_sysreg_op (popname, pnum_args, arg_strings);
   2492 
   2493   /* Backward compatibility for RUR and WUR: Recognize [RW]UR<nnn> and
   2494      [RW]<name> if <name> is the non-default name of a user register.  */
   2495   if ((opname[0] == 'r' || opname[0] == 'w')
   2496       && xtensa_opcode_lookup (xtensa_default_isa, opname) == XTENSA_UNDEFINED)
   2497     return xtensa_translate_old_userreg_ops (popname);
   2498 
   2499   /* Relax branches that don't allow comparisons against an immediate value
   2500      of zero to the corresponding branches with implicit zero immediates.  */
   2501   if (!has_underbar && use_transform ())
   2502     {
   2503       if (xtensa_translate_zero_immed ("bnei", "bnez", popname,
   2504 				       pnum_args, arg_strings))
   2505 	return -1;
   2506 
   2507       if (xtensa_translate_zero_immed ("beqi", "beqz", popname,
   2508 				       pnum_args, arg_strings))
   2509 	return -1;
   2510 
   2511       if (xtensa_translate_zero_immed ("bgei", "bgez", popname,
   2512 				       pnum_args, arg_strings))
   2513 	return -1;
   2514 
   2515       if (xtensa_translate_zero_immed ("blti", "bltz", popname,
   2516 				       pnum_args, arg_strings))
   2517 	return -1;
   2518     }
   2519 
   2520   return 0;
   2521 }
   2522 
   2523 
   2524 /* Functions for dealing with the Xtensa ISA.  */
   2526 
   2527 /* Currently the assembler only allows us to use a single target per
   2528    fragment.  Because of this, only one operand for a given
   2529    instruction may be symbolic.  If there is a PC-relative operand,
   2530    the last one is chosen.  Otherwise, the result is the number of the
   2531    last immediate operand, and if there are none of those, we fail and
   2532    return -1.  */
   2533 
   2534 static int
   2535 get_relaxable_immed (xtensa_opcode opcode)
   2536 {
   2537   int last_immed = -1;
   2538   int noperands, opi;
   2539 
   2540   if (opcode == XTENSA_UNDEFINED)
   2541     return -1;
   2542 
   2543   noperands = xtensa_opcode_num_operands (xtensa_default_isa, opcode);
   2544   for (opi = noperands - 1; opi >= 0; opi--)
   2545     {
   2546       if (xtensa_operand_is_visible (xtensa_default_isa, opcode, opi) == 0)
   2547 	continue;
   2548       if (xtensa_operand_is_PCrelative (xtensa_default_isa, opcode, opi) == 1)
   2549 	return opi;
   2550       if (last_immed == -1
   2551 	  && xtensa_operand_is_register (xtensa_default_isa, opcode, opi) == 0)
   2552 	last_immed = opi;
   2553     }
   2554   return last_immed;
   2555 }
   2556 
   2557 
   2558 static xtensa_opcode
   2559 get_opcode_from_buf (const char *buf, int slot)
   2560 {
   2561   static xtensa_insnbuf insnbuf = NULL;
   2562   static xtensa_insnbuf slotbuf = NULL;
   2563   xtensa_isa isa = xtensa_default_isa;
   2564   xtensa_format fmt;
   2565 
   2566   if (!insnbuf)
   2567     {
   2568       insnbuf = xtensa_insnbuf_alloc (isa);
   2569       slotbuf = xtensa_insnbuf_alloc (isa);
   2570     }
   2571 
   2572   xtensa_insnbuf_from_chars (isa, insnbuf, (const unsigned char *) buf, 0);
   2573   fmt = xtensa_format_decode (isa, insnbuf);
   2574   if (fmt == XTENSA_UNDEFINED)
   2575     return XTENSA_UNDEFINED;
   2576 
   2577   if (slot >= xtensa_format_num_slots (isa, fmt))
   2578     return XTENSA_UNDEFINED;
   2579 
   2580   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
   2581   return xtensa_opcode_decode (isa, fmt, slot, slotbuf);
   2582 }
   2583 
   2584 
   2585 #ifdef TENSILICA_DEBUG
   2586 
   2587 /* For debugging, print out the mapping of opcode numbers to opcodes.  */
   2588 
   2589 static void
   2590 xtensa_print_insn_table (void)
   2591 {
   2592   int num_opcodes, num_operands;
   2593   xtensa_opcode opcode;
   2594   xtensa_isa isa = xtensa_default_isa;
   2595 
   2596   num_opcodes = xtensa_isa_num_opcodes (xtensa_default_isa);
   2597   for (opcode = 0; opcode < num_opcodes; opcode++)
   2598     {
   2599       int opn;
   2600       fprintf (stderr, "%d: %s: ", opcode, xtensa_opcode_name (isa, opcode));
   2601       num_operands = xtensa_opcode_num_operands (isa, opcode);
   2602       for (opn = 0; opn < num_operands; opn++)
   2603 	{
   2604 	  if (xtensa_operand_is_visible (isa, opcode, opn) == 0)
   2605 	    continue;
   2606 	  if (xtensa_operand_is_register (isa, opcode, opn) == 1)
   2607 	    {
   2608 	      xtensa_regfile opnd_rf =
   2609 		xtensa_operand_regfile (isa, opcode, opn);
   2610 	      fprintf (stderr, "%s ", xtensa_regfile_shortname (isa, opnd_rf));
   2611 	    }
   2612 	  else if (xtensa_operand_is_PCrelative (isa, opcode, opn) == 1)
   2613 	    fputs ("[lLr] ", stderr);
   2614 	  else
   2615 	    fputs ("i ", stderr);
   2616 	}
   2617       fprintf (stderr, "\n");
   2618     }
   2619 }
   2620 
   2621 
   2622 static void
   2623 print_vliw_insn (xtensa_insnbuf vbuf)
   2624 {
   2625   xtensa_isa isa = xtensa_default_isa;
   2626   xtensa_format f = xtensa_format_decode (isa, vbuf);
   2627   xtensa_insnbuf sbuf = xtensa_insnbuf_alloc (isa);
   2628   int op;
   2629 
   2630   fprintf (stderr, "format = %d\n", f);
   2631 
   2632   for (op = 0; op < xtensa_format_num_slots (isa, f); op++)
   2633     {
   2634       xtensa_opcode opcode;
   2635       const char *opname;
   2636       int operands;
   2637 
   2638       xtensa_format_get_slot (isa, f, op, vbuf, sbuf);
   2639       opcode = xtensa_opcode_decode (isa, f, op, sbuf);
   2640       opname = xtensa_opcode_name (isa, opcode);
   2641 
   2642       fprintf (stderr, "op in slot %i is %s;\n", op, opname);
   2643       fprintf (stderr, "   operands = ");
   2644       for (operands = 0;
   2645 	   operands < xtensa_opcode_num_operands (isa, opcode);
   2646 	   operands++)
   2647 	{
   2648 	  unsigned int val;
   2649 	  if (xtensa_operand_is_visible (isa, opcode, operands) == 0)
   2650 	    continue;
   2651 	  xtensa_operand_get_field (isa, opcode, operands, f, op, sbuf, &val);
   2652 	  xtensa_operand_decode (isa, opcode, operands, &val);
   2653 	  fprintf (stderr, "%d ", val);
   2654 	}
   2655       fprintf (stderr, "\n");
   2656     }
   2657   xtensa_insnbuf_free (isa, sbuf);
   2658 }
   2659 
   2660 #endif /* TENSILICA_DEBUG */
   2661 
   2662 
   2663 static bfd_boolean
   2664 is_direct_call_opcode (xtensa_opcode opcode)
   2665 {
   2666   xtensa_isa isa = xtensa_default_isa;
   2667   int n, num_operands;
   2668 
   2669   if (xtensa_opcode_is_call (isa, opcode) != 1)
   2670     return FALSE;
   2671 
   2672   num_operands = xtensa_opcode_num_operands (isa, opcode);
   2673   for (n = 0; n < num_operands; n++)
   2674     {
   2675       if (xtensa_operand_is_register (isa, opcode, n) == 0
   2676 	  && xtensa_operand_is_PCrelative (isa, opcode, n) == 1)
   2677 	return TRUE;
   2678     }
   2679   return FALSE;
   2680 }
   2681 
   2682 
   2683 /* Convert from BFD relocation type code to slot and operand number.
   2684    Returns non-zero on failure.  */
   2685 
   2686 static int
   2687 decode_reloc (bfd_reloc_code_real_type reloc, int *slot, bfd_boolean *is_alt)
   2688 {
   2689   if (reloc >= BFD_RELOC_XTENSA_SLOT0_OP
   2690       && reloc <= BFD_RELOC_XTENSA_SLOT14_OP)
   2691     {
   2692       *slot = reloc - BFD_RELOC_XTENSA_SLOT0_OP;
   2693       *is_alt = FALSE;
   2694     }
   2695   else if (reloc >= BFD_RELOC_XTENSA_SLOT0_ALT
   2696       && reloc <= BFD_RELOC_XTENSA_SLOT14_ALT)
   2697     {
   2698       *slot = reloc - BFD_RELOC_XTENSA_SLOT0_ALT;
   2699       *is_alt = TRUE;
   2700     }
   2701   else
   2702     return -1;
   2703 
   2704   return 0;
   2705 }
   2706 
   2707 
   2708 /* Convert from slot number to BFD relocation type code for the
   2709    standard PC-relative relocations.  Return BFD_RELOC_NONE on
   2710    failure.  */
   2711 
   2712 static bfd_reloc_code_real_type
   2713 encode_reloc (int slot)
   2714 {
   2715   if (slot < 0 || slot > 14)
   2716     return BFD_RELOC_NONE;
   2717 
   2718   return BFD_RELOC_XTENSA_SLOT0_OP + slot;
   2719 }
   2720 
   2721 
   2722 /* Convert from slot numbers to BFD relocation type code for the
   2723    "alternate" relocations.  Return BFD_RELOC_NONE on failure.  */
   2724 
   2725 static bfd_reloc_code_real_type
   2726 encode_alt_reloc (int slot)
   2727 {
   2728   if (slot < 0 || slot > 14)
   2729     return BFD_RELOC_NONE;
   2730 
   2731   return BFD_RELOC_XTENSA_SLOT0_ALT + slot;
   2732 }
   2733 
   2734 
   2735 static void
   2736 xtensa_insnbuf_set_operand (xtensa_insnbuf slotbuf,
   2737 			    xtensa_format fmt,
   2738 			    int slot,
   2739 			    xtensa_opcode opcode,
   2740 			    int operand,
   2741 			    uint32 value,
   2742 			    const char *file,
   2743 			    unsigned int line)
   2744 {
   2745   uint32 valbuf = value;
   2746 
   2747   if (xtensa_operand_encode (xtensa_default_isa, opcode, operand, &valbuf))
   2748     {
   2749       if (xtensa_operand_is_PCrelative (xtensa_default_isa, opcode, operand)
   2750 	  == 1)
   2751 	as_bad_where ((char *) file, line,
   2752 		      _("operand %d of '%s' has out of range value '%u'"),
   2753 		      operand + 1,
   2754 		      xtensa_opcode_name (xtensa_default_isa, opcode),
   2755 		      value);
   2756       else
   2757 	as_bad_where ((char *) file, line,
   2758 		      _("operand %d of '%s' has invalid value '%u'"),
   2759 		      operand + 1,
   2760 		      xtensa_opcode_name (xtensa_default_isa, opcode),
   2761 		      value);
   2762       return;
   2763     }
   2764 
   2765   xtensa_operand_set_field (xtensa_default_isa, opcode, operand, fmt, slot,
   2766 			    slotbuf, valbuf);
   2767 }
   2768 
   2769 
   2770 static uint32
   2771 xtensa_insnbuf_get_operand (xtensa_insnbuf slotbuf,
   2772 			    xtensa_format fmt,
   2773 			    int slot,
   2774 			    xtensa_opcode opcode,
   2775 			    int opnum)
   2776 {
   2777   uint32 val = 0;
   2778   (void) xtensa_operand_get_field (xtensa_default_isa, opcode, opnum,
   2779 				   fmt, slot, slotbuf, &val);
   2780   (void) xtensa_operand_decode (xtensa_default_isa, opcode, opnum, &val);
   2781   return val;
   2782 }
   2783 
   2784 
   2785 /* Checks for rules from xtensa-relax tables.  */
   2787 
   2788 /* The routine xg_instruction_matches_option_term must return TRUE
   2789    when a given option term is true.  The meaning of all of the option
   2790    terms is given interpretation by this function.  */
   2791 
   2792 static bfd_boolean
   2793 xg_instruction_matches_option_term (TInsn *insn, const ReqOrOption *option)
   2794 {
   2795   if (strcmp (option->option_name, "realnop") == 0
   2796       || strncmp (option->option_name, "IsaUse", 6) == 0)
   2797     {
   2798       /* These conditions were evaluated statically when building the
   2799 	 relaxation table.  There's no need to reevaluate them now.  */
   2800       return TRUE;
   2801     }
   2802   else if (strcmp (option->option_name, "FREEREG") == 0)
   2803     return insn->extra_arg.X_op == O_register;
   2804   else
   2805     {
   2806       as_fatal (_("internal error: unknown option name '%s'"),
   2807 		option->option_name);
   2808     }
   2809 }
   2810 
   2811 
   2812 static bfd_boolean
   2813 xg_instruction_matches_or_options (TInsn *insn,
   2814 				   const ReqOrOptionList *or_option)
   2815 {
   2816   const ReqOrOption *option;
   2817   /* Must match each of the AND terms.  */
   2818   for (option = or_option; option != NULL; option = option->next)
   2819     {
   2820       if (xg_instruction_matches_option_term (insn, option))
   2821 	return TRUE;
   2822     }
   2823   return FALSE;
   2824 }
   2825 
   2826 
   2827 static bfd_boolean
   2828 xg_instruction_matches_options (TInsn *insn, const ReqOptionList *options)
   2829 {
   2830   const ReqOption *req_options;
   2831   /* Must match each of the AND terms.  */
   2832   for (req_options = options;
   2833        req_options != NULL;
   2834        req_options = req_options->next)
   2835     {
   2836       /* Must match one of the OR clauses.  */
   2837       if (!xg_instruction_matches_or_options (insn,
   2838 					      req_options->or_option_terms))
   2839 	return FALSE;
   2840     }
   2841   return TRUE;
   2842 }
   2843 
   2844 
   2845 /* Return the transition rule that matches or NULL if none matches.  */
   2846 
   2847 static bfd_boolean
   2848 xg_instruction_matches_rule (TInsn *insn, TransitionRule *rule)
   2849 {
   2850   PreconditionList *condition_l;
   2851 
   2852   if (rule->opcode != insn->opcode)
   2853     return FALSE;
   2854 
   2855   for (condition_l = rule->conditions;
   2856        condition_l != NULL;
   2857        condition_l = condition_l->next)
   2858     {
   2859       expressionS *exp1;
   2860       expressionS *exp2;
   2861       Precondition *cond = condition_l->precond;
   2862 
   2863       switch (cond->typ)
   2864 	{
   2865 	case OP_CONSTANT:
   2866 	  /* The expression must be the constant.  */
   2867 	  gas_assert (cond->op_num < insn->ntok);
   2868 	  exp1 = &insn->tok[cond->op_num];
   2869 	  if (expr_is_const (exp1))
   2870 	    {
   2871 	      switch (cond->cmp)
   2872 		{
   2873 		case OP_EQUAL:
   2874 		  if (get_expr_const (exp1) != cond->op_data)
   2875 		    return FALSE;
   2876 		  break;
   2877 		case OP_NOTEQUAL:
   2878 		  if (get_expr_const (exp1) == cond->op_data)
   2879 		    return FALSE;
   2880 		  break;
   2881 		default:
   2882 		  return FALSE;
   2883 		}
   2884 	    }
   2885 	  else if (expr_is_register (exp1))
   2886 	    {
   2887 	      switch (cond->cmp)
   2888 		{
   2889 		case OP_EQUAL:
   2890 		  if (get_expr_register (exp1) != cond->op_data)
   2891 		    return FALSE;
   2892 		  break;
   2893 		case OP_NOTEQUAL:
   2894 		  if (get_expr_register (exp1) == cond->op_data)
   2895 		    return FALSE;
   2896 		  break;
   2897 		default:
   2898 		  return FALSE;
   2899 		}
   2900 	    }
   2901 	  else
   2902 	    return FALSE;
   2903 	  break;
   2904 
   2905 	case OP_OPERAND:
   2906 	  gas_assert (cond->op_num < insn->ntok);
   2907 	  gas_assert (cond->op_data < insn->ntok);
   2908 	  exp1 = &insn->tok[cond->op_num];
   2909 	  exp2 = &insn->tok[cond->op_data];
   2910 
   2911 	  switch (cond->cmp)
   2912 	    {
   2913 	    case OP_EQUAL:
   2914 	      if (!expr_is_equal (exp1, exp2))
   2915 		return FALSE;
   2916 	      break;
   2917 	    case OP_NOTEQUAL:
   2918 	      if (expr_is_equal (exp1, exp2))
   2919 		return FALSE;
   2920 	      break;
   2921 	    }
   2922 	  break;
   2923 
   2924 	case OP_LITERAL:
   2925 	case OP_LABEL:
   2926 	default:
   2927 	  return FALSE;
   2928 	}
   2929     }
   2930   if (!xg_instruction_matches_options (insn, rule->options))
   2931     return FALSE;
   2932 
   2933   return TRUE;
   2934 }
   2935 
   2936 
   2937 static int
   2938 transition_rule_cmp (const TransitionRule *a, const TransitionRule *b)
   2939 {
   2940   bfd_boolean a_greater = FALSE;
   2941   bfd_boolean b_greater = FALSE;
   2942 
   2943   ReqOptionList *l_a = a->options;
   2944   ReqOptionList *l_b = b->options;
   2945 
   2946   /* We only care if they both are the same except for
   2947      a const16 vs. an l32r.  */
   2948 
   2949   while (l_a && l_b && ((l_a->next == NULL) == (l_b->next == NULL)))
   2950     {
   2951       ReqOrOptionList *l_or_a = l_a->or_option_terms;
   2952       ReqOrOptionList *l_or_b = l_b->or_option_terms;
   2953       while (l_or_a && l_or_b && ((l_a->next == NULL) == (l_b->next == NULL)))
   2954 	{
   2955 	  if (l_or_a->is_true != l_or_b->is_true)
   2956 	    return 0;
   2957 	  if (strcmp (l_or_a->option_name, l_or_b->option_name) != 0)
   2958 	    {
   2959 	      /* This is the case we care about.  */
   2960 	      if (strcmp (l_or_a->option_name, "IsaUseConst16") == 0
   2961 		  && strcmp (l_or_b->option_name, "IsaUseL32R") == 0)
   2962 		{
   2963 		  if (prefer_const16)
   2964 		    a_greater = TRUE;
   2965 		  else
   2966 		    b_greater = TRUE;
   2967 		}
   2968 	      else if (strcmp (l_or_a->option_name, "IsaUseL32R") == 0
   2969 		       && strcmp (l_or_b->option_name, "IsaUseConst16") == 0)
   2970 		{
   2971 		  if (prefer_const16)
   2972 		    b_greater = TRUE;
   2973 		  else
   2974 		    a_greater = TRUE;
   2975 		}
   2976 	      else
   2977 		return 0;
   2978 	    }
   2979 	  l_or_a = l_or_a->next;
   2980 	  l_or_b = l_or_b->next;
   2981 	}
   2982       if (l_or_a || l_or_b)
   2983 	return 0;
   2984 
   2985       l_a = l_a->next;
   2986       l_b = l_b->next;
   2987     }
   2988   if (l_a || l_b)
   2989     return 0;
   2990 
   2991   /* Incomparable if the substitution was used differently in two cases.  */
   2992   if (a_greater && b_greater)
   2993     return 0;
   2994 
   2995   if (b_greater)
   2996     return 1;
   2997   if (a_greater)
   2998     return -1;
   2999 
   3000   return 0;
   3001 }
   3002 
   3003 
   3004 static TransitionRule *
   3005 xg_instruction_match (TInsn *insn)
   3006 {
   3007   TransitionTable *table = xg_build_simplify_table (&transition_rule_cmp);
   3008   TransitionList *l;
   3009   gas_assert (insn->opcode < table->num_opcodes);
   3010 
   3011   /* Walk through all of the possible transitions.  */
   3012   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
   3013     {
   3014       TransitionRule *rule = l->rule;
   3015       if (xg_instruction_matches_rule (insn, rule))
   3016 	return rule;
   3017     }
   3018   return NULL;
   3019 }
   3020 
   3021 
   3022 /* Various Other Internal Functions.  */
   3024 
   3025 static bfd_boolean
   3026 is_unique_insn_expansion (TransitionRule *r)
   3027 {
   3028   if (!r->to_instr || r->to_instr->next != NULL)
   3029     return FALSE;
   3030   if (r->to_instr->typ != INSTR_INSTR)
   3031     return FALSE;
   3032   return TRUE;
   3033 }
   3034 
   3035 
   3036 /* Check if there is exactly one relaxation for INSN that converts it to
   3037    another instruction of equal or larger size.  If so, and if TARG is
   3038    non-null, go ahead and generate the relaxed instruction into TARG.  If
   3039    NARROW_ONLY is true, then only consider relaxations that widen a narrow
   3040    instruction, i.e., ignore relaxations that convert to an instruction of
   3041    equal size.  In some contexts where this function is used, only
   3042    a single widening is allowed and the NARROW_ONLY argument is used to
   3043    exclude cases like ADDI being "widened" to an ADDMI, which may
   3044    later be relaxed to an ADDMI/ADDI pair.  */
   3045 
   3046 bfd_boolean
   3047 xg_is_single_relaxable_insn (TInsn *insn, TInsn *targ, bfd_boolean narrow_only)
   3048 {
   3049   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
   3050   TransitionList *l;
   3051   TransitionRule *match = 0;
   3052 
   3053   gas_assert (insn->insn_type == ITYPE_INSN);
   3054   gas_assert (insn->opcode < table->num_opcodes);
   3055 
   3056   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
   3057     {
   3058       TransitionRule *rule = l->rule;
   3059 
   3060       if (xg_instruction_matches_rule (insn, rule)
   3061 	  && is_unique_insn_expansion (rule)
   3062 	  && (xg_get_single_size (insn->opcode) + (narrow_only ? 1 : 0)
   3063 	      <= xg_get_single_size (rule->to_instr->opcode)))
   3064 	{
   3065 	  if (match)
   3066 	    return FALSE;
   3067 	  match = rule;
   3068 	}
   3069     }
   3070   if (!match)
   3071     return FALSE;
   3072 
   3073   if (targ)
   3074     xg_build_to_insn (targ, insn, match->to_instr);
   3075   return TRUE;
   3076 }
   3077 
   3078 
   3079 /* Return the maximum number of bytes this opcode can expand to.  */
   3080 
   3081 static int
   3082 xg_get_max_insn_widen_size (xtensa_opcode opcode)
   3083 {
   3084   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
   3085   TransitionList *l;
   3086   int max_size = xg_get_single_size (opcode);
   3087 
   3088   gas_assert (opcode < table->num_opcodes);
   3089 
   3090   for (l = table->table[opcode]; l != NULL; l = l->next)
   3091     {
   3092       TransitionRule *rule = l->rule;
   3093       BuildInstr *build_list;
   3094       int this_size = 0;
   3095 
   3096       if (!rule)
   3097 	continue;
   3098       build_list = rule->to_instr;
   3099       if (is_unique_insn_expansion (rule))
   3100 	{
   3101 	  gas_assert (build_list->typ == INSTR_INSTR);
   3102 	  this_size = xg_get_max_insn_widen_size (build_list->opcode);
   3103 	}
   3104       else
   3105 	for (; build_list != NULL; build_list = build_list->next)
   3106 	  {
   3107 	    switch (build_list->typ)
   3108 	      {
   3109 	      case INSTR_INSTR:
   3110 		this_size += xg_get_single_size (build_list->opcode);
   3111 		break;
   3112 	      case INSTR_LITERAL_DEF:
   3113 	      case INSTR_LABEL_DEF:
   3114 	      default:
   3115 		break;
   3116 	      }
   3117 	  }
   3118       if (this_size > max_size)
   3119 	max_size = this_size;
   3120     }
   3121   return max_size;
   3122 }
   3123 
   3124 
   3125 /* Return the maximum number of literal bytes this opcode can generate.  */
   3126 
   3127 static int
   3128 xg_get_max_insn_widen_literal_size (xtensa_opcode opcode)
   3129 {
   3130   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
   3131   TransitionList *l;
   3132   int max_size = 0;
   3133 
   3134   gas_assert (opcode < table->num_opcodes);
   3135 
   3136   for (l = table->table[opcode]; l != NULL; l = l->next)
   3137     {
   3138       TransitionRule *rule = l->rule;
   3139       BuildInstr *build_list;
   3140       int this_size = 0;
   3141 
   3142       if (!rule)
   3143 	continue;
   3144       build_list = rule->to_instr;
   3145       if (is_unique_insn_expansion (rule))
   3146 	{
   3147 	  gas_assert (build_list->typ == INSTR_INSTR);
   3148 	  this_size = xg_get_max_insn_widen_literal_size (build_list->opcode);
   3149 	}
   3150       else
   3151 	for (; build_list != NULL; build_list = build_list->next)
   3152 	  {
   3153 	    switch (build_list->typ)
   3154 	      {
   3155 	      case INSTR_LITERAL_DEF:
   3156 		/* Hard-coded 4-byte literal.  */
   3157 		this_size += 4;
   3158 		break;
   3159 	      case INSTR_INSTR:
   3160 	      case INSTR_LABEL_DEF:
   3161 	      default:
   3162 		break;
   3163 	      }
   3164 	  }
   3165       if (this_size > max_size)
   3166 	max_size = this_size;
   3167     }
   3168   return max_size;
   3169 }
   3170 
   3171 
   3172 static bfd_boolean
   3173 xg_is_relaxable_insn (TInsn *insn, int lateral_steps)
   3174 {
   3175   int steps_taken = 0;
   3176   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
   3177   TransitionList *l;
   3178 
   3179   gas_assert (insn->insn_type == ITYPE_INSN);
   3180   gas_assert (insn->opcode < table->num_opcodes);
   3181 
   3182   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
   3183     {
   3184       TransitionRule *rule = l->rule;
   3185 
   3186       if (xg_instruction_matches_rule (insn, rule))
   3187 	{
   3188 	  if (steps_taken == lateral_steps)
   3189 	    return TRUE;
   3190 	  steps_taken++;
   3191 	}
   3192     }
   3193   return FALSE;
   3194 }
   3195 
   3196 
   3197 static symbolS *
   3198 get_special_literal_symbol (void)
   3199 {
   3200   static symbolS *sym = NULL;
   3201 
   3202   if (sym == NULL)
   3203     sym = symbol_find_or_make ("SPECIAL_LITERAL0\001");
   3204   return sym;
   3205 }
   3206 
   3207 
   3208 static symbolS *
   3209 get_special_label_symbol (void)
   3210 {
   3211   static symbolS *sym = NULL;
   3212 
   3213   if (sym == NULL)
   3214     sym = symbol_find_or_make ("SPECIAL_LABEL0\001");
   3215   return sym;
   3216 }
   3217 
   3218 
   3219 static bfd_boolean
   3220 xg_valid_literal_expression (const expressionS *exp)
   3221 {
   3222   switch (exp->X_op)
   3223     {
   3224     case O_constant:
   3225     case O_symbol:
   3226     case O_big:
   3227     case O_uminus:
   3228     case O_subtract:
   3229     case O_pltrel:
   3230     case O_pcrel:
   3231     case O_tlsfunc:
   3232     case O_tlsarg:
   3233     case O_tpoff:
   3234     case O_dtpoff:
   3235       return TRUE;
   3236     default:
   3237       return FALSE;
   3238     }
   3239 }
   3240 
   3241 
   3242 /* This will check to see if the value can be converted into the
   3243    operand type.  It will return TRUE if it does not fit.  */
   3244 
   3245 static bfd_boolean
   3246 xg_check_operand (int32 value, xtensa_opcode opcode, int operand)
   3247 {
   3248   uint32 valbuf = value;
   3249   if (xtensa_operand_encode (xtensa_default_isa, opcode, operand, &valbuf))
   3250     return TRUE;
   3251   return FALSE;
   3252 }
   3253 
   3254 
   3255 /* Assumes: All immeds are constants.  Check that all constants fit
   3256    into their immeds; return FALSE if not.  */
   3257 
   3258 static bfd_boolean
   3259 xg_immeds_fit (const TInsn *insn)
   3260 {
   3261   xtensa_isa isa = xtensa_default_isa;
   3262   int i;
   3263 
   3264   int n = insn->ntok;
   3265   gas_assert (insn->insn_type == ITYPE_INSN);
   3266   for (i = 0; i < n; ++i)
   3267     {
   3268       const expressionS *exp = &insn->tok[i];
   3269 
   3270       if (xtensa_operand_is_register (isa, insn->opcode, i) == 1)
   3271 	continue;
   3272 
   3273       switch (exp->X_op)
   3274 	{
   3275 	case O_register:
   3276 	case O_constant:
   3277 	  if (xg_check_operand (exp->X_add_number, insn->opcode, i))
   3278 	    return FALSE;
   3279 	  break;
   3280 
   3281 	default:
   3282 	  /* The symbol should have a fixup associated with it.  */
   3283 	  gas_assert (FALSE);
   3284 	  break;
   3285 	}
   3286     }
   3287   return TRUE;
   3288 }
   3289 
   3290 
   3291 /* This should only be called after we have an initial
   3292    estimate of the addresses.  */
   3293 
   3294 static bfd_boolean
   3295 xg_symbolic_immeds_fit (const TInsn *insn,
   3296 			segT pc_seg,
   3297 			fragS *pc_frag,
   3298 			offsetT pc_offset,
   3299 			long stretch)
   3300 {
   3301   xtensa_isa isa = xtensa_default_isa;
   3302   symbolS *symbolP;
   3303   fragS *sym_frag;
   3304   offsetT target, pc;
   3305   uint32 new_offset;
   3306   int i;
   3307   int n = insn->ntok;
   3308 
   3309   gas_assert (insn->insn_type == ITYPE_INSN);
   3310 
   3311   for (i = 0; i < n; ++i)
   3312     {
   3313       const expressionS *exp = &insn->tok[i];
   3314 
   3315       if (xtensa_operand_is_register (isa, insn->opcode, i) == 1)
   3316 	continue;
   3317 
   3318       switch (exp->X_op)
   3319 	{
   3320 	case O_register:
   3321 	case O_constant:
   3322 	  if (xg_check_operand (exp->X_add_number, insn->opcode, i))
   3323 	    return FALSE;
   3324 	  break;
   3325 
   3326 	case O_lo16:
   3327 	case O_hi16:
   3328 	  /* Check for the worst case.  */
   3329 	  if (xg_check_operand (0xffff, insn->opcode, i))
   3330 	    return FALSE;
   3331 	  break;
   3332 
   3333 	case O_symbol:
   3334 	  /* We only allow symbols for PC-relative references.
   3335 	     If pc_frag == 0, then we don't have frag locations yet.  */
   3336 	  if (pc_frag == 0
   3337 	      || xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 0)
   3338 	    return FALSE;
   3339 
   3340 	  /* If it is a weak symbol or a symbol in a different section,
   3341 	     it cannot be known to fit at assembly time.  */
   3342 	  if (S_IS_WEAK (exp->X_add_symbol)
   3343 	      || S_GET_SEGMENT (exp->X_add_symbol) != pc_seg)
   3344 	    {
   3345 	      /* For a direct call with --no-longcalls, be optimistic and
   3346 		 assume it will be in range.  If the symbol is weak and
   3347 		 undefined, it may remain undefined at link-time, in which
   3348 		 case it will have a zero value and almost certainly be out
   3349 		 of range for a direct call; thus, relax for undefined weak
   3350 		 symbols even if longcalls is not enabled.  */
   3351 	      if (is_direct_call_opcode (insn->opcode)
   3352 		  && ! pc_frag->tc_frag_data.use_longcalls
   3353 		  && (! S_IS_WEAK (exp->X_add_symbol)
   3354 		      || S_IS_DEFINED (exp->X_add_symbol)))
   3355 		return TRUE;
   3356 
   3357 	      return FALSE;
   3358 	    }
   3359 
   3360 	  symbolP = exp->X_add_symbol;
   3361 	  sym_frag = symbol_get_frag (symbolP);
   3362 	  target = S_GET_VALUE (symbolP) + exp->X_add_number;
   3363 	  pc = pc_frag->fr_address + pc_offset;
   3364 
   3365 	  /* If frag has yet to be reached on this pass, assume it
   3366 	     will move by STRETCH just as we did.  If this is not so,
   3367 	     it will be because some frag between grows, and that will
   3368 	     force another pass.  Beware zero-length frags.  There
   3369 	     should be a faster way to do this.  */
   3370 
   3371 	  if (stretch != 0
   3372 	      && sym_frag->relax_marker != pc_frag->relax_marker
   3373 	      && S_GET_SEGMENT (symbolP) == pc_seg)
   3374 	    {
   3375 	      target += stretch;
   3376 	    }
   3377 
   3378 	  new_offset = target;
   3379 	  xtensa_operand_do_reloc (isa, insn->opcode, i, &new_offset, pc);
   3380 	  if (xg_check_operand (new_offset, insn->opcode, i))
   3381 	    return FALSE;
   3382 	  break;
   3383 
   3384 	default:
   3385 	  /* The symbol should have a fixup associated with it.  */
   3386 	  return FALSE;
   3387 	}
   3388     }
   3389 
   3390   return TRUE;
   3391 }
   3392 
   3393 
   3394 /* Return TRUE on success.  */
   3395 
   3396 static bfd_boolean
   3397 xg_build_to_insn (TInsn *targ, TInsn *insn, BuildInstr *bi)
   3398 {
   3399   BuildOp *op;
   3400   symbolS *sym;
   3401 
   3402   tinsn_init (targ);
   3403   targ->debug_line = insn->debug_line;
   3404   targ->loc_directive_seen = insn->loc_directive_seen;
   3405   switch (bi->typ)
   3406     {
   3407     case INSTR_INSTR:
   3408       op = bi->ops;
   3409       targ->opcode = bi->opcode;
   3410       targ->insn_type = ITYPE_INSN;
   3411       targ->is_specific_opcode = FALSE;
   3412 
   3413       for (; op != NULL; op = op->next)
   3414 	{
   3415 	  int op_num = op->op_num;
   3416 	  int op_data = op->op_data;
   3417 
   3418 	  gas_assert (op->op_num < MAX_INSN_ARGS);
   3419 
   3420 	  if (targ->ntok <= op_num)
   3421 	    targ->ntok = op_num + 1;
   3422 
   3423 	  switch (op->typ)
   3424 	    {
   3425 	    case OP_CONSTANT:
   3426 	      set_expr_const (&targ->tok[op_num], op_data);
   3427 	      break;
   3428 	    case OP_OPERAND:
   3429 	      gas_assert (op_data < insn->ntok);
   3430 	      copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
   3431 	      break;
   3432 	    case OP_FREEREG:
   3433 	      if (insn->extra_arg.X_op != O_register)
   3434 		return FALSE;
   3435 	      copy_expr (&targ->tok[op_num], &insn->extra_arg);
   3436 	      break;
   3437 	    case OP_LITERAL:
   3438 	      sym = get_special_literal_symbol ();
   3439 	      set_expr_symbol_offset (&targ->tok[op_num], sym, 0);
   3440 	      if (insn->tok[op_data].X_op == O_tlsfunc
   3441 		  || insn->tok[op_data].X_op == O_tlsarg)
   3442 		copy_expr (&targ->extra_arg, &insn->tok[op_data]);
   3443 	      break;
   3444 	    case OP_LABEL:
   3445 	      sym = get_special_label_symbol ();
   3446 	      set_expr_symbol_offset (&targ->tok[op_num], sym, 0);
   3447 	      break;
   3448 	    case OP_OPERAND_HI16U:
   3449 	    case OP_OPERAND_LOW16U:
   3450 	      gas_assert (op_data < insn->ntok);
   3451 	      if (expr_is_const (&insn->tok[op_data]))
   3452 		{
   3453 		  long val;
   3454 		  copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
   3455 		  val = xg_apply_userdef_op_fn (op->typ,
   3456 						targ->tok[op_num].
   3457 						X_add_number);
   3458 		  targ->tok[op_num].X_add_number = val;
   3459 		}
   3460 	      else
   3461 		{
   3462 		  /* For const16 we can create relocations for these.  */
   3463 		  if (targ->opcode == XTENSA_UNDEFINED
   3464 		      || (targ->opcode != xtensa_const16_opcode))
   3465 		    return FALSE;
   3466 		  gas_assert (op_data < insn->ntok);
   3467 		  /* Need to build a O_lo16 or O_hi16.  */
   3468 		  copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
   3469 		  if (targ->tok[op_num].X_op == O_symbol)
   3470 		    {
   3471 		      if (op->typ == OP_OPERAND_HI16U)
   3472 			targ->tok[op_num].X_op = O_hi16;
   3473 		      else if (op->typ == OP_OPERAND_LOW16U)
   3474 			targ->tok[op_num].X_op = O_lo16;
   3475 		      else
   3476 			return FALSE;
   3477 		    }
   3478 		}
   3479 	      break;
   3480 	    default:
   3481 	      /* currently handles:
   3482 		 OP_OPERAND_LOW8
   3483 		 OP_OPERAND_HI24S
   3484 		 OP_OPERAND_F32MINUS */
   3485 	      if (xg_has_userdef_op_fn (op->typ))
   3486 		{
   3487 		  gas_assert (op_data < insn->ntok);
   3488 		  if (expr_is_const (&insn->tok[op_data]))
   3489 		    {
   3490 		      long val;
   3491 		      copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
   3492 		      val = xg_apply_userdef_op_fn (op->typ,
   3493 						    targ->tok[op_num].
   3494 						    X_add_number);
   3495 		      targ->tok[op_num].X_add_number = val;
   3496 		    }
   3497 		  else
   3498 		    return FALSE; /* We cannot use a relocation for this.  */
   3499 		  break;
   3500 		}
   3501 	      gas_assert (0);
   3502 	      break;
   3503 	    }
   3504 	}
   3505       break;
   3506 
   3507     case INSTR_LITERAL_DEF:
   3508       op = bi->ops;
   3509       targ->opcode = XTENSA_UNDEFINED;
   3510       targ->insn_type = ITYPE_LITERAL;
   3511       targ->is_specific_opcode = FALSE;
   3512       for (; op != NULL; op = op->next)
   3513 	{
   3514 	  int op_num = op->op_num;
   3515 	  int op_data = op->op_data;
   3516 	  gas_assert (op->op_num < MAX_INSN_ARGS);
   3517 
   3518 	  if (targ->ntok <= op_num)
   3519 	    targ->ntok = op_num + 1;
   3520 
   3521 	  switch (op->typ)
   3522 	    {
   3523 	    case OP_OPERAND:
   3524 	      gas_assert (op_data < insn->ntok);
   3525 	      /* We can only pass resolvable literals through.  */
   3526 	      if (!xg_valid_literal_expression (&insn->tok[op_data]))
   3527 		return FALSE;
   3528 	      copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
   3529 	      break;
   3530 	    case OP_LITERAL:
   3531 	    case OP_CONSTANT:
   3532 	    case OP_LABEL:
   3533 	    default:
   3534 	      gas_assert (0);
   3535 	      break;
   3536 	    }
   3537 	}
   3538       break;
   3539 
   3540     case INSTR_LABEL_DEF:
   3541       op = bi->ops;
   3542       targ->opcode = XTENSA_UNDEFINED;
   3543       targ->insn_type = ITYPE_LABEL;
   3544       targ->is_specific_opcode = FALSE;
   3545       /* Literal with no ops is a label?  */
   3546       gas_assert (op == NULL);
   3547       break;
   3548 
   3549     default:
   3550       gas_assert (0);
   3551     }
   3552 
   3553   return TRUE;
   3554 }
   3555 
   3556 
   3557 /* Return TRUE on success.  */
   3558 
   3559 static bfd_boolean
   3560 xg_build_to_stack (IStack *istack, TInsn *insn, BuildInstr *bi)
   3561 {
   3562   for (; bi != NULL; bi = bi->next)
   3563     {
   3564       TInsn *next_insn = istack_push_space (istack);
   3565 
   3566       if (!xg_build_to_insn (next_insn, insn, bi))
   3567 	return FALSE;
   3568     }
   3569   return TRUE;
   3570 }
   3571 
   3572 
   3573 /* Return TRUE on valid expansion.  */
   3574 
   3575 static bfd_boolean
   3576 xg_expand_to_stack (IStack *istack, TInsn *insn, int lateral_steps)
   3577 {
   3578   int stack_size = istack->ninsn;
   3579   int steps_taken = 0;
   3580   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
   3581   TransitionList *l;
   3582 
   3583   gas_assert (insn->insn_type == ITYPE_INSN);
   3584   gas_assert (insn->opcode < table->num_opcodes);
   3585 
   3586   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
   3587     {
   3588       TransitionRule *rule = l->rule;
   3589 
   3590       if (xg_instruction_matches_rule (insn, rule))
   3591 	{
   3592 	  if (lateral_steps == steps_taken)
   3593 	    {
   3594 	      int i;
   3595 
   3596 	      /* This is it.  Expand the rule to the stack.  */
   3597 	      if (!xg_build_to_stack (istack, insn, rule->to_instr))
   3598 		return FALSE;
   3599 
   3600 	      /* Check to see if it fits.  */
   3601 	      for (i = stack_size; i < istack->ninsn; i++)
   3602 		{
   3603 		  TInsn *tinsn = &istack->insn[i];
   3604 
   3605 		  if (tinsn->insn_type == ITYPE_INSN
   3606 		      && !tinsn_has_symbolic_operands (tinsn)
   3607 		      && !xg_immeds_fit (tinsn))
   3608 		    {
   3609 		      istack->ninsn = stack_size;
   3610 		      return FALSE;
   3611 		    }
   3612 		}
   3613 	      return TRUE;
   3614 	    }
   3615 	  steps_taken++;
   3616 	}
   3617     }
   3618   return FALSE;
   3619 }
   3620 
   3621 
   3622 /* Relax the assembly instruction at least "min_steps".
   3624    Return the number of steps taken.
   3625 
   3626    For relaxation to correctly terminate, every relaxation chain must
   3627    terminate in one of two ways:
   3628 
   3629    1.  If the chain from one instruction to the next consists entirely of
   3630        single instructions, then the chain *must* handle all possible
   3631        immediates without failing.  It must not ever fail because an
   3632        immediate is out of range.  The MOVI.N -> MOVI -> L32R relaxation
   3633        chain is one example.  L32R loads 32 bits, and there cannot be an
   3634        immediate larger than 32 bits, so it satisfies this condition.
   3635        Single instruction relaxation chains are as defined by
   3636        xg_is_single_relaxable_instruction.
   3637 
   3638    2.  Otherwise, the chain must end in a multi-instruction expansion: e.g.,
   3639        BNEZ.N -> BNEZ -> BNEZ.W15 -> BENZ.N/J
   3640 
   3641    Strictly speaking, in most cases you can violate condition 1 and be OK
   3642    -- in particular when the last two instructions have the same single
   3643    size.  But nevertheless, you should guarantee the above two conditions.
   3644 
   3645    We could fix this so that single-instruction expansions correctly
   3646    terminate when they can't handle the range, but the error messages are
   3647    worse, and it actually turns out that in every case but one (18-bit wide
   3648    branches), you need a multi-instruction expansion to get the full range
   3649    anyway.  And because 18-bit branches are handled identically to 15-bit
   3650    branches, there isn't any point in changing it.  */
   3651 
   3652 static int
   3653 xg_assembly_relax (IStack *istack,
   3654 		   TInsn *insn,
   3655 		   segT pc_seg,
   3656 		   fragS *pc_frag,	/* if pc_frag == 0, not pc-relative */
   3657 		   offsetT pc_offset,	/* offset in fragment */
   3658 		   int min_steps,	/* minimum conversion steps */
   3659 		   long stretch)	/* number of bytes stretched so far */
   3660 {
   3661   int steps_taken = 0;
   3662 
   3663   /* Some of its immeds don't fit.  Try to build a relaxed version.
   3664      This may go through a couple of stages of single instruction
   3665      transformations before we get there.  */
   3666 
   3667   TInsn single_target;
   3668   TInsn current_insn;
   3669   int lateral_steps = 0;
   3670   int istack_size = istack->ninsn;
   3671 
   3672   if (xg_symbolic_immeds_fit (insn, pc_seg, pc_frag, pc_offset, stretch)
   3673       && steps_taken >= min_steps)
   3674     {
   3675       istack_push (istack, insn);
   3676       return steps_taken;
   3677     }
   3678   current_insn = *insn;
   3679 
   3680   /* Walk through all of the single instruction expansions.  */
   3681   while (xg_is_single_relaxable_insn (&current_insn, &single_target, FALSE))
   3682     {
   3683       steps_taken++;
   3684       if (xg_symbolic_immeds_fit (&single_target, pc_seg, pc_frag, pc_offset,
   3685 				  stretch))
   3686 	{
   3687 	  if (steps_taken >= min_steps)
   3688 	    {
   3689 	      istack_push (istack, &single_target);
   3690 	      return steps_taken;
   3691 	    }
   3692 	}
   3693       current_insn = single_target;
   3694     }
   3695 
   3696   /* Now check for a multi-instruction expansion.  */
   3697   while (xg_is_relaxable_insn (&current_insn, lateral_steps))
   3698     {
   3699       if (xg_symbolic_immeds_fit (&current_insn, pc_seg, pc_frag, pc_offset,
   3700 				  stretch))
   3701 	{
   3702 	  if (steps_taken >= min_steps)
   3703 	    {
   3704 	      istack_push (istack, &current_insn);
   3705 	      return steps_taken;
   3706 	    }
   3707 	}
   3708       steps_taken++;
   3709       if (xg_expand_to_stack (istack, &current_insn, lateral_steps))
   3710 	{
   3711 	  if (steps_taken >= min_steps)
   3712 	    return steps_taken;
   3713 	}
   3714       lateral_steps++;
   3715       istack->ninsn = istack_size;
   3716     }
   3717 
   3718   /* It's not going to work -- use the original.  */
   3719   istack_push (istack, insn);
   3720   return steps_taken;
   3721 }
   3722 
   3723 
   3724 static void
   3725 xg_finish_frag (char *last_insn,
   3726 		enum xtensa_relax_statesE frag_state,
   3727 		enum xtensa_relax_statesE slot0_state,
   3728 		int max_growth,
   3729 		bfd_boolean is_insn)
   3730 {
   3731   /* Finish off this fragment so that it has at LEAST the desired
   3732      max_growth.  If it doesn't fit in this fragment, close this one
   3733      and start a new one.  In either case, return a pointer to the
   3734      beginning of the growth area.  */
   3735 
   3736   fragS *old_frag;
   3737 
   3738   frag_grow (max_growth);
   3739   old_frag = frag_now;
   3740 
   3741   frag_now->fr_opcode = last_insn;
   3742   if (is_insn)
   3743     frag_now->tc_frag_data.is_insn = TRUE;
   3744 
   3745   frag_var (rs_machine_dependent, max_growth, max_growth,
   3746 	    frag_state, frag_now->fr_symbol, frag_now->fr_offset, last_insn);
   3747 
   3748   old_frag->tc_frag_data.slot_subtypes[0] = slot0_state;
   3749   xtensa_set_frag_assembly_state (frag_now);
   3750 
   3751   /* Just to make sure that we did not split it up.  */
   3752   gas_assert (old_frag->fr_next == frag_now);
   3753 }
   3754 
   3755 
   3756 /* Return TRUE if the target frag is one of the next non-empty frags.  */
   3757 
   3758 static bfd_boolean
   3759 is_next_frag_target (const fragS *fragP, const fragS *target)
   3760 {
   3761   if (fragP == NULL)
   3762     return FALSE;
   3763 
   3764   for (; fragP; fragP = fragP->fr_next)
   3765     {
   3766       if (fragP == target)
   3767 	return TRUE;
   3768       if (fragP->fr_fix != 0)
   3769 	return FALSE;
   3770       if (fragP->fr_type == rs_fill && fragP->fr_offset != 0)
   3771 	return FALSE;
   3772       if ((fragP->fr_type == rs_align || fragP->fr_type == rs_align_code)
   3773 	  && ((fragP->fr_address % (1 << fragP->fr_offset)) != 0))
   3774 	return FALSE;
   3775       if (fragP->fr_type == rs_space)
   3776 	return FALSE;
   3777     }
   3778   return FALSE;
   3779 }
   3780 
   3781 
   3782 static bfd_boolean
   3783 is_branch_jmp_to_next (TInsn *insn, fragS *fragP)
   3784 {
   3785   xtensa_isa isa = xtensa_default_isa;
   3786   int i;
   3787   int num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
   3788   int target_op = -1;
   3789   symbolS *sym;
   3790   fragS *target_frag;
   3791 
   3792   if (xtensa_opcode_is_branch (isa, insn->opcode) != 1
   3793       && xtensa_opcode_is_jump (isa, insn->opcode) != 1)
   3794     return FALSE;
   3795 
   3796   for (i = 0; i < num_ops; i++)
   3797     {
   3798       if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1)
   3799 	{
   3800 	  target_op = i;
   3801 	  break;
   3802 	}
   3803     }
   3804   if (target_op == -1)
   3805     return FALSE;
   3806 
   3807   if (insn->ntok <= target_op)
   3808     return FALSE;
   3809 
   3810   if (insn->tok[target_op].X_op != O_symbol)
   3811     return FALSE;
   3812 
   3813   sym = insn->tok[target_op].X_add_symbol;
   3814   if (sym == NULL)
   3815     return FALSE;
   3816 
   3817   if (insn->tok[target_op].X_add_number != 0)
   3818     return FALSE;
   3819 
   3820   target_frag = symbol_get_frag (sym);
   3821   if (target_frag == NULL)
   3822     return FALSE;
   3823 
   3824   if (is_next_frag_target (fragP->fr_next, target_frag)
   3825       && S_GET_VALUE (sym) == target_frag->fr_address)
   3826     return TRUE;
   3827 
   3828   return FALSE;
   3829 }
   3830 
   3831 
   3832 static void
   3833 xg_add_branch_and_loop_targets (TInsn *insn)
   3834 {
   3835   xtensa_isa isa = xtensa_default_isa;
   3836   int num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
   3837 
   3838   if (xtensa_opcode_is_loop (isa, insn->opcode) == 1)
   3839     {
   3840       int i = 1;
   3841       if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1
   3842 	  && insn->tok[i].X_op == O_symbol)
   3843 	symbol_get_tc (insn->tok[i].X_add_symbol)->is_loop_target = TRUE;
   3844       return;
   3845     }
   3846 
   3847   if (xtensa_opcode_is_branch (isa, insn->opcode) == 1
   3848       || xtensa_opcode_is_loop (isa, insn->opcode) == 1)
   3849     {
   3850       int i;
   3851 
   3852       for (i = 0; i < insn->ntok && i < num_ops; i++)
   3853 	{
   3854 	  if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1
   3855 	      && insn->tok[i].X_op == O_symbol)
   3856 	    {
   3857 	      symbolS *sym = insn->tok[i].X_add_symbol;
   3858 	      symbol_get_tc (sym)->is_branch_target = TRUE;
   3859 	      if (S_IS_DEFINED (sym))
   3860 		symbol_get_frag (sym)->tc_frag_data.is_branch_target = TRUE;
   3861 	    }
   3862 	}
   3863     }
   3864 }
   3865 
   3866 
   3867 /* Return FALSE if no error.  */
   3868 
   3869 static bfd_boolean
   3870 xg_build_token_insn (BuildInstr *instr_spec, TInsn *old_insn, TInsn *new_insn)
   3871 {
   3872   int num_ops = 0;
   3873   BuildOp *b_op;
   3874 
   3875   switch (instr_spec->typ)
   3876     {
   3877     case INSTR_INSTR:
   3878       new_insn->insn_type = ITYPE_INSN;
   3879       new_insn->opcode = instr_spec->opcode;
   3880       break;
   3881     case INSTR_LITERAL_DEF:
   3882       new_insn->insn_type = ITYPE_LITERAL;
   3883       new_insn->opcode = XTENSA_UNDEFINED;
   3884       break;
   3885     case INSTR_LABEL_DEF:
   3886       abort ();
   3887     }
   3888   new_insn->is_specific_opcode = FALSE;
   3889   new_insn->debug_line = old_insn->debug_line;
   3890   new_insn->loc_directive_seen = old_insn->loc_directive_seen;
   3891 
   3892   for (b_op = instr_spec->ops; b_op != NULL; b_op = b_op->next)
   3893     {
   3894       expressionS *exp;
   3895       const expressionS *src_exp;
   3896 
   3897       num_ops++;
   3898       switch (b_op->typ)
   3899 	{
   3900 	case OP_CONSTANT:
   3901 	  /* The expression must be the constant.  */
   3902 	  gas_assert (b_op->op_num < MAX_INSN_ARGS);
   3903 	  exp = &new_insn->tok[b_op->op_num];
   3904 	  set_expr_const (exp, b_op->op_data);
   3905 	  break;
   3906 
   3907 	case OP_OPERAND:
   3908 	  gas_assert (b_op->op_num < MAX_INSN_ARGS);
   3909 	  gas_assert (b_op->op_data < (unsigned) old_insn->ntok);
   3910 	  src_exp = &old_insn->tok[b_op->op_data];
   3911 	  exp = &new_insn->tok[b_op->op_num];
   3912 	  copy_expr (exp, src_exp);
   3913 	  break;
   3914 
   3915 	case OP_LITERAL:
   3916 	case OP_LABEL:
   3917 	  as_bad (_("can't handle generation of literal/labels yet"));
   3918 	  gas_assert (0);
   3919 
   3920 	default:
   3921 	  as_bad (_("can't handle undefined OP TYPE"));
   3922 	  gas_assert (0);
   3923 	}
   3924     }
   3925 
   3926   new_insn->ntok = num_ops;
   3927   return FALSE;
   3928 }
   3929 
   3930 
   3931 /* Return TRUE if it was simplified.  */
   3932 
   3933 static bfd_boolean
   3934 xg_simplify_insn (TInsn *old_insn, TInsn *new_insn)
   3935 {
   3936   TransitionRule *rule;
   3937   BuildInstr *insn_spec;
   3938 
   3939   if (old_insn->is_specific_opcode || !density_supported)
   3940     return FALSE;
   3941 
   3942   rule = xg_instruction_match (old_insn);
   3943   if (rule == NULL)
   3944     return FALSE;
   3945 
   3946   insn_spec = rule->to_instr;
   3947   /* There should only be one.  */
   3948   gas_assert (insn_spec != NULL);
   3949   gas_assert (insn_spec->next == NULL);
   3950   if (insn_spec->next != NULL)
   3951     return FALSE;
   3952 
   3953   xg_build_token_insn (insn_spec, old_insn, new_insn);
   3954 
   3955   return TRUE;
   3956 }
   3957 
   3958 
   3959 /* xg_expand_assembly_insn: (1) Simplify the instruction, i.e., l32i ->
   3960    l32i.n. (2) Check the number of operands.  (3) Place the instruction
   3961    tokens into the stack or relax it and place multiple
   3962    instructions/literals onto the stack.  Return FALSE if no error.  */
   3963 
   3964 static bfd_boolean
   3965 xg_expand_assembly_insn (IStack *istack, TInsn *orig_insn)
   3966 {
   3967   int noperands;
   3968   TInsn new_insn;
   3969   bfd_boolean do_expand;
   3970 
   3971   tinsn_init (&new_insn);
   3972 
   3973   /* Narrow it if we can.  xg_simplify_insn now does all the
   3974      appropriate checking (e.g., for the density option).  */
   3975   if (xg_simplify_insn (orig_insn, &new_insn))
   3976     orig_insn = &new_insn;
   3977 
   3978   noperands = xtensa_opcode_num_operands (xtensa_default_isa,
   3979 					  orig_insn->opcode);
   3980   if (orig_insn->ntok < noperands)
   3981     {
   3982       as_bad (_("found %d operands for '%s':  Expected %d"),
   3983 	      orig_insn->ntok,
   3984 	      xtensa_opcode_name (xtensa_default_isa, orig_insn->opcode),
   3985 	      noperands);
   3986       return TRUE;
   3987     }
   3988   if (orig_insn->ntok > noperands)
   3989     as_warn (_("found too many (%d) operands for '%s':  Expected %d"),
   3990 	     orig_insn->ntok,
   3991 	     xtensa_opcode_name (xtensa_default_isa, orig_insn->opcode),
   3992 	     noperands);
   3993 
   3994   /* If there are not enough operands, we will assert above.  If there
   3995      are too many, just cut out the extras here.  */
   3996   orig_insn->ntok = noperands;
   3997 
   3998   if (tinsn_has_invalid_symbolic_operands (orig_insn))
   3999     return TRUE;
   4000 
   4001   /* Special case for extui opcode which has constraints not handled
   4002      by the ordinary operand encoding checks.  The number of operands
   4003      and related syntax issues have already been checked.  */
   4004   if (orig_insn->opcode == xtensa_extui_opcode)
   4005     {
   4006       int shiftimm = orig_insn->tok[2].X_add_number;
   4007       int maskimm = orig_insn->tok[3].X_add_number;
   4008       if (shiftimm + maskimm > 32)
   4009 	{
   4010 	  as_bad (_("immediate operands sum to greater than 32"));
   4011 	  return TRUE;
   4012 	}
   4013     }
   4014 
   4015   /* If the instruction will definitely need to be relaxed, it is better
   4016      to expand it now for better scheduling.  Decide whether to expand
   4017      now....  */
   4018   do_expand = (!orig_insn->is_specific_opcode && use_transform ());
   4019 
   4020   /* Calls should be expanded to longcalls only in the backend relaxation
   4021      so that the assembly scheduler will keep the L32R/CALLX instructions
   4022      adjacent.  */
   4023   if (is_direct_call_opcode (orig_insn->opcode))
   4024     do_expand = FALSE;
   4025 
   4026   if (tinsn_has_symbolic_operands (orig_insn))
   4027     {
   4028       /* The values of symbolic operands are not known yet, so only expand
   4029 	 now if an operand is "complex" (e.g., difference of symbols) and
   4030 	 will have to be stored as a literal regardless of the value.  */
   4031       if (!tinsn_has_complex_operands (orig_insn))
   4032 	do_expand = FALSE;
   4033     }
   4034   else if (xg_immeds_fit (orig_insn))
   4035     do_expand = FALSE;
   4036 
   4037   if (do_expand)
   4038     xg_assembly_relax (istack, orig_insn, 0, 0, 0, 0, 0);
   4039   else
   4040     istack_push (istack, orig_insn);
   4041 
   4042   return FALSE;
   4043 }
   4044 
   4045 
   4046 /* Return TRUE if the section flags are marked linkonce
   4047    or the name is .gnu.linkonce.*.  */
   4048 
   4049 static int linkonce_len = sizeof (".gnu.linkonce.") - 1;
   4050 
   4051 static bfd_boolean
   4052 get_is_linkonce_section (bfd *abfd ATTRIBUTE_UNUSED, segT sec)
   4053 {
   4054   flagword flags, link_once_flags;
   4055 
   4056   flags = bfd_get_section_flags (abfd, sec);
   4057   link_once_flags = (flags & SEC_LINK_ONCE);
   4058 
   4059   /* Flags might not be set yet.  */
   4060   if (!link_once_flags
   4061       && strncmp (segment_name (sec), ".gnu.linkonce.", linkonce_len) == 0)
   4062     link_once_flags = SEC_LINK_ONCE;
   4063 
   4064   return (link_once_flags != 0);
   4065 }
   4066 
   4067 
   4068 static void
   4069 xtensa_add_literal_sym (symbolS *sym)
   4070 {
   4071   sym_list *l;
   4072 
   4073   l = (sym_list *) xmalloc (sizeof (sym_list));
   4074   l->sym = sym;
   4075   l->next = literal_syms;
   4076   literal_syms = l;
   4077 }
   4078 
   4079 
   4080 static symbolS *
   4081 xtensa_create_literal_symbol (segT sec, fragS *frag)
   4082 {
   4083   static int lit_num = 0;
   4084   static char name[256];
   4085   symbolS *symbolP;
   4086 
   4087   sprintf (name, ".L_lit_sym%d", lit_num);
   4088 
   4089   /* Create a local symbol.  If it is in a linkonce section, we have to
   4090      be careful to make sure that if it is used in a relocation that the
   4091      symbol will be in the output file.  */
   4092   if (get_is_linkonce_section (stdoutput, sec))
   4093     {
   4094       symbolP = symbol_new (name, sec, 0, frag);
   4095       S_CLEAR_EXTERNAL (symbolP);
   4096       /* symbolP->local = 1; */
   4097     }
   4098   else
   4099     symbolP = symbol_new (name, sec, 0, frag);
   4100 
   4101   xtensa_add_literal_sym (symbolP);
   4102 
   4103   lit_num++;
   4104   return symbolP;
   4105 }
   4106 
   4107 
   4108 /* Currently all literals that are generated here are 32-bit L32R targets.  */
   4109 
   4110 static symbolS *
   4111 xg_assemble_literal (/* const */ TInsn *insn)
   4112 {
   4113   emit_state state;
   4114   symbolS *lit_sym = NULL;
   4115   bfd_reloc_code_real_type reloc;
   4116   bfd_boolean pcrel = FALSE;
   4117   char *p;
   4118 
   4119   /* size = 4 for L32R.  It could easily be larger when we move to
   4120      larger constants.  Add a parameter later.  */
   4121   offsetT litsize = 4;
   4122   offsetT litalign = 2;		/* 2^2 = 4 */
   4123   expressionS saved_loc;
   4124   expressionS * emit_val;
   4125 
   4126   set_expr_symbol_offset (&saved_loc, frag_now->fr_symbol, frag_now_fix ());
   4127 
   4128   gas_assert (insn->insn_type == ITYPE_LITERAL);
   4129   gas_assert (insn->ntok == 1);	/* must be only one token here */
   4130 
   4131   xtensa_switch_to_literal_fragment (&state);
   4132 
   4133   emit_val = &insn->tok[0];
   4134   if (emit_val->X_op == O_big)
   4135     {
   4136       int size = emit_val->X_add_number * CHARS_PER_LITTLENUM;
   4137       if (size > litsize)
   4138 	{
   4139 	  /* This happens when someone writes a "movi a2, big_number".  */
   4140 	  as_bad_where (frag_now->fr_file, frag_now->fr_line,
   4141 			_("invalid immediate"));
   4142 	  xtensa_restore_emit_state (&state);
   4143 	  return NULL;
   4144 	}
   4145     }
   4146 
   4147   /* Force a 4-byte align here.  Note that this opens a new frag, so all
   4148      literals done with this function have a frag to themselves.  That's
   4149      important for the way text section literals work.  */
   4150   frag_align (litalign, 0, 0);
   4151   record_alignment (now_seg, litalign);
   4152 
   4153   switch (emit_val->X_op)
   4154     {
   4155     case O_pcrel:
   4156       pcrel = TRUE;
   4157       /* fall through */
   4158     case O_pltrel:
   4159     case O_tlsfunc:
   4160     case O_tlsarg:
   4161     case O_tpoff:
   4162     case O_dtpoff:
   4163       p = frag_more (litsize);
   4164       xtensa_set_frag_assembly_state (frag_now);
   4165       reloc = map_operator_to_reloc (emit_val->X_op, TRUE);
   4166       if (emit_val->X_add_symbol)
   4167 	emit_val->X_op = O_symbol;
   4168       else
   4169 	emit_val->X_op = O_constant;
   4170       fix_new_exp (frag_now, p - frag_now->fr_literal,
   4171 		   litsize, emit_val, pcrel, reloc);
   4172       break;
   4173 
   4174     default:
   4175       emit_expr (emit_val, litsize);
   4176       break;
   4177     }
   4178 
   4179   gas_assert (frag_now->tc_frag_data.literal_frag == NULL);
   4180   frag_now->tc_frag_data.literal_frag = get_literal_pool_location (now_seg);
   4181   frag_now->fr_symbol = xtensa_create_literal_symbol (now_seg, frag_now);
   4182   lit_sym = frag_now->fr_symbol;
   4183 
   4184   /* Go back.  */
   4185   xtensa_restore_emit_state (&state);
   4186   return lit_sym;
   4187 }
   4188 
   4189 
   4190 static void
   4191 xg_assemble_literal_space (/* const */ int size, int slot)
   4192 {
   4193   emit_state state;
   4194   /* We might have to do something about this alignment.  It only
   4195      takes effect if something is placed here.  */
   4196   offsetT litalign = 2;		/* 2^2 = 4 */
   4197   fragS *lit_saved_frag;
   4198 
   4199   gas_assert (size % 4 == 0);
   4200 
   4201   xtensa_switch_to_literal_fragment (&state);
   4202 
   4203   /* Force a 4-byte align here.  */
   4204   frag_align (litalign, 0, 0);
   4205   record_alignment (now_seg, litalign);
   4206 
   4207   frag_grow (size);
   4208 
   4209   lit_saved_frag = frag_now;
   4210   frag_now->tc_frag_data.literal_frag = get_literal_pool_location (now_seg);
   4211   frag_now->fr_symbol = xtensa_create_literal_symbol (now_seg, frag_now);
   4212   xg_finish_frag (0, RELAX_LITERAL, 0, size, FALSE);
   4213 
   4214   /* Go back.  */
   4215   xtensa_restore_emit_state (&state);
   4216   frag_now->tc_frag_data.literal_frags[slot] = lit_saved_frag;
   4217 }
   4218 
   4219 
   4220 /* Put in a fixup record based on the opcode.
   4221    Return TRUE on success.  */
   4222 
   4223 static bfd_boolean
   4224 xg_add_opcode_fix (TInsn *tinsn,
   4225 		   int opnum,
   4226 		   xtensa_format fmt,
   4227 		   int slot,
   4228 		   expressionS *exp,
   4229 		   fragS *fragP,
   4230 		   offsetT offset)
   4231 {
   4232   xtensa_opcode opcode = tinsn->opcode;
   4233   bfd_reloc_code_real_type reloc;
   4234   reloc_howto_type *howto;
   4235   int fmt_length;
   4236   fixS *the_fix;
   4237 
   4238   reloc = BFD_RELOC_NONE;
   4239 
   4240   /* First try the special cases for "alternate" relocs.  */
   4241   if (opcode == xtensa_l32r_opcode)
   4242     {
   4243       if (fragP->tc_frag_data.use_absolute_literals)
   4244 	reloc = encode_alt_reloc (slot);
   4245     }
   4246   else if (opcode == xtensa_const16_opcode)
   4247     {
   4248       if (exp->X_op == O_lo16)
   4249 	{
   4250 	  reloc = encode_reloc (slot);
   4251 	  exp->X_op = O_symbol;
   4252 	}
   4253       else if (exp->X_op == O_hi16)
   4254 	{
   4255 	  reloc = encode_alt_reloc (slot);
   4256 	  exp->X_op = O_symbol;
   4257 	}
   4258     }
   4259 
   4260   if (opnum != get_relaxable_immed (opcode))
   4261     {
   4262       as_bad (_("invalid relocation for operand %i of '%s'"),
   4263 	      opnum + 1, xtensa_opcode_name (xtensa_default_isa, opcode));
   4264       return FALSE;
   4265     }
   4266 
   4267   /* Handle erroneous "@h" and "@l" expressions here before they propagate
   4268      into the symbol table where the generic portions of the assembler
   4269      won't know what to do with them.  */
   4270   if (exp->X_op == O_lo16 || exp->X_op == O_hi16)
   4271     {
   4272       as_bad (_("invalid expression for operand %i of '%s'"),
   4273 	      opnum + 1, xtensa_opcode_name (xtensa_default_isa, opcode));
   4274       return FALSE;
   4275     }
   4276 
   4277   /* Next try the generic relocs.  */
   4278   if (reloc == BFD_RELOC_NONE)
   4279     reloc = encode_reloc (slot);
   4280   if (reloc == BFD_RELOC_NONE)
   4281     {
   4282       as_bad (_("invalid relocation in instruction slot %i"), slot);
   4283       return FALSE;
   4284     }
   4285 
   4286   howto = bfd_reloc_type_lookup (stdoutput, reloc);
   4287   if (!howto)
   4288     {
   4289       as_bad (_("undefined symbol for opcode \"%s\""),
   4290 	      xtensa_opcode_name (xtensa_default_isa, opcode));
   4291       return FALSE;
   4292     }
   4293 
   4294   fmt_length = xtensa_format_length (xtensa_default_isa, fmt);
   4295   the_fix = fix_new_exp (fragP, offset, fmt_length, exp,
   4296 			 howto->pc_relative, reloc);
   4297   the_fix->fx_no_overflow = 1;
   4298   the_fix->tc_fix_data.X_add_symbol = exp->X_add_symbol;
   4299   the_fix->tc_fix_data.X_add_number = exp->X_add_number;
   4300   the_fix->tc_fix_data.slot = slot;
   4301 
   4302   return TRUE;
   4303 }
   4304 
   4305 
   4306 static bfd_boolean
   4307 xg_emit_insn_to_buf (TInsn *tinsn,
   4308 		     char *buf,
   4309 		     fragS *fragP,
   4310 		     offsetT offset,
   4311 		     bfd_boolean build_fix)
   4312 {
   4313   static xtensa_insnbuf insnbuf = NULL;
   4314   bfd_boolean has_symbolic_immed = FALSE;
   4315   bfd_boolean ok = TRUE;
   4316 
   4317   if (!insnbuf)
   4318     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
   4319 
   4320   has_symbolic_immed = tinsn_to_insnbuf (tinsn, insnbuf);
   4321   if (has_symbolic_immed && build_fix)
   4322     {
   4323       /* Add a fixup.  */
   4324       xtensa_format fmt = xg_get_single_format (tinsn->opcode);
   4325       int slot = xg_get_single_slot (tinsn->opcode);
   4326       int opnum = get_relaxable_immed (tinsn->opcode);
   4327       expressionS *exp = &tinsn->tok[opnum];
   4328 
   4329       if (!xg_add_opcode_fix (tinsn, opnum, fmt, slot, exp, fragP, offset))
   4330 	ok = FALSE;
   4331     }
   4332   fragP->tc_frag_data.is_insn = TRUE;
   4333   xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf,
   4334 			   (unsigned char *) buf, 0);
   4335   return ok;
   4336 }
   4337 
   4338 
   4339 static void
   4340 xg_resolve_literals (TInsn *insn, symbolS *lit_sym)
   4341 {
   4342   symbolS *sym = get_special_literal_symbol ();
   4343   int i;
   4344   if (lit_sym == 0)
   4345     return;
   4346   gas_assert (insn->insn_type == ITYPE_INSN);
   4347   for (i = 0; i < insn->ntok; i++)
   4348     if (insn->tok[i].X_add_symbol == sym)
   4349       insn->tok[i].X_add_symbol = lit_sym;
   4350 
   4351 }
   4352 
   4353 
   4354 static void
   4355 xg_resolve_labels (TInsn *insn, symbolS *label_sym)
   4356 {
   4357   symbolS *sym = get_special_label_symbol ();
   4358   int i;
   4359   for (i = 0; i < insn->ntok; i++)
   4360     if (insn->tok[i].X_add_symbol == sym)
   4361       insn->tok[i].X_add_symbol = label_sym;
   4362 
   4363 }
   4364 
   4365 
   4366 /* Return TRUE if the instruction can write to the specified
   4367    integer register.  */
   4368 
   4369 static bfd_boolean
   4370 is_register_writer (const TInsn *insn, const char *regset, int regnum)
   4371 {
   4372   int i;
   4373   int num_ops;
   4374   xtensa_isa isa = xtensa_default_isa;
   4375 
   4376   num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
   4377 
   4378   for (i = 0; i < num_ops; i++)
   4379     {
   4380       char inout;
   4381       inout = xtensa_operand_inout (isa, insn->opcode, i);
   4382       if ((inout == 'o' || inout == 'm')
   4383 	  && xtensa_operand_is_register (isa, insn->opcode, i) == 1)
   4384 	{
   4385 	  xtensa_regfile opnd_rf =
   4386 	    xtensa_operand_regfile (isa, insn->opcode, i);
   4387 	  if (!strcmp (xtensa_regfile_shortname (isa, opnd_rf), regset))
   4388 	    {
   4389 	      if ((insn->tok[i].X_op == O_register)
   4390 		  && (insn->tok[i].X_add_number == regnum))
   4391 		return TRUE;
   4392 	    }
   4393 	}
   4394     }
   4395   return FALSE;
   4396 }
   4397 
   4398 
   4399 static bfd_boolean
   4400 is_bad_loopend_opcode (const TInsn *tinsn)
   4401 {
   4402   xtensa_opcode opcode = tinsn->opcode;
   4403 
   4404   if (opcode == XTENSA_UNDEFINED)
   4405     return FALSE;
   4406 
   4407   if (opcode == xtensa_call0_opcode
   4408       || opcode == xtensa_callx0_opcode
   4409       || opcode == xtensa_call4_opcode
   4410       || opcode == xtensa_callx4_opcode
   4411       || opcode == xtensa_call8_opcode
   4412       || opcode == xtensa_callx8_opcode
   4413       || opcode == xtensa_call12_opcode
   4414       || opcode == xtensa_callx12_opcode
   4415       || opcode == xtensa_isync_opcode
   4416       || opcode == xtensa_ret_opcode
   4417       || opcode == xtensa_ret_n_opcode
   4418       || opcode == xtensa_retw_opcode
   4419       || opcode == xtensa_retw_n_opcode
   4420       || opcode == xtensa_waiti_opcode
   4421       || opcode == xtensa_rsr_lcount_opcode)
   4422     return TRUE;
   4423 
   4424   return FALSE;
   4425 }
   4426 
   4427 
   4428 /* Labels that begin with ".Ln" or ".LM"  are unaligned.
   4429    This allows the debugger to add unaligned labels.
   4430    Also, the assembler generates stabs labels that need
   4431    not be aligned:  FAKE_LABEL_NAME . {"F", "L", "endfunc"}.  */
   4432 
   4433 static bfd_boolean
   4434 is_unaligned_label (symbolS *sym)
   4435 {
   4436   const char *name = S_GET_NAME (sym);
   4437   static size_t fake_size = 0;
   4438 
   4439   if (name
   4440       && name[0] == '.'
   4441       && name[1] == 'L' && (name[2] == 'n' || name[2] == 'M'))
   4442     return TRUE;
   4443 
   4444   /* FAKE_LABEL_NAME followed by "F", "L" or "endfunc" */
   4445   if (fake_size == 0)
   4446     fake_size = strlen (FAKE_LABEL_NAME);
   4447 
   4448   if (name
   4449       && strncmp (FAKE_LABEL_NAME, name, fake_size) == 0
   4450       && (name[fake_size] == 'F'
   4451 	  || name[fake_size] == 'L'
   4452 	  || (name[fake_size] == 'e'
   4453 	      && strncmp ("endfunc", name+fake_size, 7) == 0)))
   4454     return TRUE;
   4455 
   4456   return FALSE;
   4457 }
   4458 
   4459 
   4460 static fragS *
   4461 next_non_empty_frag (const fragS *fragP)
   4462 {
   4463   fragS *next_fragP = fragP->fr_next;
   4464 
   4465   /* Sometimes an empty will end up here due storage allocation issues.
   4466      So we have to skip until we find something legit.  */
   4467   while (next_fragP && next_fragP->fr_fix == 0)
   4468     next_fragP = next_fragP->fr_next;
   4469 
   4470   if (next_fragP == NULL || next_fragP->fr_fix == 0)
   4471     return NULL;
   4472 
   4473   return next_fragP;
   4474 }
   4475 
   4476 
   4477 static bfd_boolean
   4478 next_frag_opcode_is_loop (const fragS *fragP, xtensa_opcode *opcode)
   4479 {
   4480   xtensa_opcode out_opcode;
   4481   const fragS *next_fragP = next_non_empty_frag (fragP);
   4482 
   4483   if (next_fragP == NULL)
   4484     return FALSE;
   4485 
   4486   out_opcode = get_opcode_from_buf (next_fragP->fr_literal, 0);
   4487   if (xtensa_opcode_is_loop (xtensa_default_isa, out_opcode) == 1)
   4488     {
   4489       *opcode = out_opcode;
   4490       return TRUE;
   4491     }
   4492   return FALSE;
   4493 }
   4494 
   4495 
   4496 static int
   4497 frag_format_size (const fragS *fragP)
   4498 {
   4499   static xtensa_insnbuf insnbuf = NULL;
   4500   xtensa_isa isa = xtensa_default_isa;
   4501   xtensa_format fmt;
   4502   int fmt_size;
   4503 
   4504   if (!insnbuf)
   4505     insnbuf = xtensa_insnbuf_alloc (isa);
   4506 
   4507   if (fragP == NULL)
   4508     return XTENSA_UNDEFINED;
   4509 
   4510   xtensa_insnbuf_from_chars (isa, insnbuf,
   4511 			     (unsigned char *) fragP->fr_literal, 0);
   4512 
   4513   fmt = xtensa_format_decode (isa, insnbuf);
   4514   if (fmt == XTENSA_UNDEFINED)
   4515     return XTENSA_UNDEFINED;
   4516   fmt_size = xtensa_format_length (isa, fmt);
   4517 
   4518   /* If the next format won't be changing due to relaxation, just
   4519      return the length of the first format.  */
   4520   if (fragP->fr_opcode != fragP->fr_literal)
   4521     return fmt_size;
   4522 
   4523   /* If during relaxation we have to pull an instruction out of a
   4524      multi-slot instruction, we will return the more conservative
   4525      number.  This works because alignment on bigger instructions
   4526      is more restrictive than alignment on smaller instructions.
   4527      This is more conservative than we would like, but it happens
   4528      infrequently.  */
   4529 
   4530   if (xtensa_format_num_slots (xtensa_default_isa, fmt) > 1)
   4531     return fmt_size;
   4532 
   4533   /* If we aren't doing one of our own relaxations or it isn't
   4534      slot-based, then the insn size won't change.  */
   4535   if (fragP->fr_type != rs_machine_dependent)
   4536     return fmt_size;
   4537   if (fragP->fr_subtype != RELAX_SLOTS)
   4538     return fmt_size;
   4539 
   4540   /* If an instruction is about to grow, return the longer size.  */
   4541   if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED_STEP1
   4542       || fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED_STEP2
   4543       || fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED_STEP3)
   4544     {
   4545       /* For most frags at RELAX_IMMED_STEPX, with X > 0, the first
   4546 	 instruction in the relaxed version is of length 3.  (The case
   4547 	 where we have to pull the instruction out of a FLIX bundle
   4548 	 is handled conservatively above.)  However, frags with opcodes
   4549 	 that are expanding to wide branches end up having formats that
   4550 	 are not determinable by the RELAX_IMMED_STEPX enumeration, and
   4551 	 we can't tell directly what format the relaxer picked.  This
   4552 	 is a wart in the design of the relaxer that should someday be
   4553 	 fixed, but would require major changes, or at least should
   4554 	 be accompanied by major changes to make use of that data.
   4555 
   4556 	 In any event, we can tell that we are expanding from a single-slot
   4557 	 format to a wider one with the logic below.  */
   4558 
   4559       int i;
   4560       int relaxed_size = fmt_size + fragP->tc_frag_data.text_expansion[0];
   4561 
   4562       for (i = 0; i < xtensa_isa_num_formats (isa); i++)
   4563 	{
   4564 	  if (relaxed_size == xtensa_format_length (isa, i))
   4565 	    return relaxed_size;
   4566 	}
   4567 
   4568       return 3;
   4569     }
   4570 
   4571   if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
   4572     return 2 + fragP->tc_frag_data.text_expansion[0];
   4573 
   4574   return fmt_size;
   4575 }
   4576 
   4577 
   4578 static int
   4579 next_frag_format_size (const fragS *fragP)
   4580 {
   4581   const fragS *next_fragP = next_non_empty_frag (fragP);
   4582   return frag_format_size (next_fragP);
   4583 }
   4584 
   4585 
   4586 /* In early Xtensa Processors, for reasons that are unclear, the ISA
   4587    required two-byte instructions to be treated as three-byte instructions
   4588    for loop instruction alignment.  This restriction was removed beginning
   4589    with Xtensa LX.  Now the only requirement on loop instruction alignment
   4590    is that the first instruction of the loop must appear at an address that
   4591    does not cross a fetch boundary.  */
   4592 
   4593 static int
   4594 get_loop_align_size (int insn_size)
   4595 {
   4596   if (insn_size == XTENSA_UNDEFINED)
   4597     return xtensa_fetch_width;
   4598 
   4599   if (enforce_three_byte_loop_align && insn_size == 2)
   4600     return 3;
   4601 
   4602   return insn_size;
   4603 }
   4604 
   4605 
   4606 /* If the next legit fragment is an end-of-loop marker,
   4607    switch its state so it will instantiate a NOP.  */
   4608 
   4609 static void
   4610 update_next_frag_state (fragS *fragP)
   4611 {
   4612   fragS *next_fragP = fragP->fr_next;
   4613   fragS *new_target = NULL;
   4614 
   4615   if (align_targets)
   4616     {
   4617       /* We are guaranteed there will be one of these...   */
   4618       while (!(next_fragP->fr_type == rs_machine_dependent
   4619 	       && (next_fragP->fr_subtype == RELAX_MAYBE_UNREACHABLE
   4620 		   || next_fragP->fr_subtype == RELAX_UNREACHABLE)))
   4621 	next_fragP = next_fragP->fr_next;
   4622 
   4623       gas_assert (next_fragP->fr_type == rs_machine_dependent
   4624 	      && (next_fragP->fr_subtype == RELAX_MAYBE_UNREACHABLE
   4625 		  || next_fragP->fr_subtype == RELAX_UNREACHABLE));
   4626 
   4627       /* ...and one of these.  */
   4628       new_target = next_fragP->fr_next;
   4629       while (!(new_target->fr_type == rs_machine_dependent
   4630 	       && (new_target->fr_subtype == RELAX_MAYBE_DESIRE_ALIGN
   4631 		   || new_target->fr_subtype == RELAX_DESIRE_ALIGN)))
   4632 	new_target = new_target->fr_next;
   4633 
   4634       gas_assert (new_target->fr_type == rs_machine_dependent
   4635 	      && (new_target->fr_subtype == RELAX_MAYBE_DESIRE_ALIGN
   4636 		  || new_target->fr_subtype == RELAX_DESIRE_ALIGN));
   4637     }
   4638 
   4639   while (next_fragP && next_fragP->fr_fix == 0)
   4640     {
   4641       if (next_fragP->fr_type == rs_machine_dependent
   4642 	  && next_fragP->fr_subtype == RELAX_LOOP_END)
   4643 	{
   4644 	  next_fragP->fr_subtype = RELAX_LOOP_END_ADD_NOP;
   4645 	  return;
   4646 	}
   4647 
   4648       next_fragP = next_fragP->fr_next;
   4649     }
   4650 }
   4651 
   4652 
   4653 static bfd_boolean
   4654 next_frag_is_branch_target (const fragS *fragP)
   4655 {
   4656   /* Sometimes an empty will end up here due to storage allocation issues,
   4657      so we have to skip until we find something legit.  */
   4658   for (fragP = fragP->fr_next; fragP; fragP = fragP->fr_next)
   4659     {
   4660       if (fragP->tc_frag_data.is_branch_target)
   4661 	return TRUE;
   4662       if (fragP->fr_fix != 0)
   4663 	break;
   4664     }
   4665   return FALSE;
   4666 }
   4667 
   4668 
   4669 static bfd_boolean
   4670 next_frag_is_loop_target (const fragS *fragP)
   4671 {
   4672   /* Sometimes an empty will end up here due storage allocation issues.
   4673      So we have to skip until we find something legit. */
   4674   for (fragP = fragP->fr_next; fragP; fragP = fragP->fr_next)
   4675     {
   4676       if (fragP->tc_frag_data.is_loop_target)
   4677 	return TRUE;
   4678       if (fragP->fr_fix != 0)
   4679 	break;
   4680     }
   4681   return FALSE;
   4682 }
   4683 
   4684 
   4685 /* As specified in the relaxation table, when a loop instruction is
   4686    relaxed, there are 24 bytes between the loop instruction itself and
   4687    the first instruction in the loop.  */
   4688 
   4689 #define RELAXED_LOOP_INSN_BYTES 24
   4690 
   4691 static addressT
   4692 next_frag_pre_opcode_bytes (const fragS *fragp)
   4693 {
   4694   const fragS *next_fragp = fragp->fr_next;
   4695   xtensa_opcode next_opcode;
   4696 
   4697   if (!next_frag_opcode_is_loop (fragp, &next_opcode))
   4698     return 0;
   4699 
   4700   /* Sometimes an empty will end up here due to storage allocation issues,
   4701      so we have to skip until we find something legit.  */
   4702   while (next_fragp->fr_fix == 0)
   4703     next_fragp = next_fragp->fr_next;
   4704 
   4705   if (next_fragp->fr_type != rs_machine_dependent)
   4706     return 0;
   4707 
   4708   /* There is some implicit knowledge encoded in here.
   4709      The LOOP instructions that are NOT RELAX_IMMED have
   4710      been relaxed.  Note that we can assume that the LOOP
   4711      instruction is in slot 0 because loops aren't bundleable.  */
   4712   if (next_fragp->tc_frag_data.slot_subtypes[0] > RELAX_IMMED)
   4713       return get_expanded_loop_offset (next_opcode) + RELAXED_LOOP_INSN_BYTES;
   4714 
   4715   return 0;
   4716 }
   4717 
   4718 
   4719 /* Mark a location where we can later insert literal frags.  Update
   4720    the section's literal_pool_loc, so subsequent literals can be
   4721    placed nearest to their use.  */
   4722 
   4723 static void
   4724 xtensa_mark_literal_pool_location (void)
   4725 {
   4726   /* Any labels pointing to the current location need
   4727      to be adjusted to after the literal pool.  */
   4728   emit_state s;
   4729   fragS *pool_location;
   4730 
   4731   if (use_literal_section)
   4732     return;
   4733 
   4734   /* We stash info in these frags so we can later move the literal's
   4735      fixes into this frchain's fix list.  */
   4736   pool_location = frag_now;
   4737   frag_now->tc_frag_data.lit_frchain = frchain_now;
   4738   frag_now->tc_frag_data.literal_frag = frag_now;
   4739   frag_variant (rs_machine_dependent, 0, 0,
   4740 		RELAX_LITERAL_POOL_BEGIN, NULL, 0, NULL);
   4741   xtensa_set_frag_assembly_state (frag_now);
   4742   frag_now->tc_frag_data.lit_seg = now_seg;
   4743   frag_variant (rs_machine_dependent, 0, 0,
   4744 		RELAX_LITERAL_POOL_END, NULL, 0, NULL);
   4745   xtensa_set_frag_assembly_state (frag_now);
   4746 
   4747   /* Now put a frag into the literal pool that points to this location.  */
   4748   set_literal_pool_location (now_seg, pool_location);
   4749   xtensa_switch_to_non_abs_literal_fragment (&s);
   4750   frag_align (2, 0, 0);
   4751   record_alignment (now_seg, 2);
   4752 
   4753   /* Close whatever frag is there.  */
   4754   frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
   4755   xtensa_set_frag_assembly_state (frag_now);
   4756   frag_now->tc_frag_data.literal_frag = pool_location;
   4757   frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
   4758   xtensa_restore_emit_state (&s);
   4759   xtensa_set_frag_assembly_state (frag_now);
   4760 }
   4761 
   4762 
   4763 /* Build a nop of the correct size into tinsn.  */
   4764 
   4765 static void
   4766 build_nop (TInsn *tinsn, int size)
   4767 {
   4768   tinsn_init (tinsn);
   4769   switch (size)
   4770     {
   4771     case 2:
   4772       tinsn->opcode = xtensa_nop_n_opcode;
   4773       tinsn->ntok = 0;
   4774       if (tinsn->opcode == XTENSA_UNDEFINED)
   4775 	as_fatal (_("opcode 'NOP.N' unavailable in this configuration"));
   4776       break;
   4777 
   4778     case 3:
   4779       if (xtensa_nop_opcode == XTENSA_UNDEFINED)
   4780 	{
   4781 	  tinsn->opcode = xtensa_or_opcode;
   4782 	  set_expr_const (&tinsn->tok[0], 1);
   4783 	  set_expr_const (&tinsn->tok[1], 1);
   4784 	  set_expr_const (&tinsn->tok[2], 1);
   4785 	  tinsn->ntok = 3;
   4786 	}
   4787       else
   4788 	tinsn->opcode = xtensa_nop_opcode;
   4789 
   4790       gas_assert (tinsn->opcode != XTENSA_UNDEFINED);
   4791     }
   4792 }
   4793 
   4794 
   4795 /* Assemble a NOP of the requested size in the buffer.  User must have
   4796    allocated "buf" with at least "size" bytes.  */
   4797 
   4798 static void
   4799 assemble_nop (int size, char *buf)
   4800 {
   4801   static xtensa_insnbuf insnbuf = NULL;
   4802   TInsn tinsn;
   4803 
   4804   build_nop (&tinsn, size);
   4805 
   4806   if (!insnbuf)
   4807     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
   4808 
   4809   tinsn_to_insnbuf (&tinsn, insnbuf);
   4810   xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf,
   4811 			   (unsigned char *) buf, 0);
   4812 }
   4813 
   4814 
   4815 /* Return the number of bytes for the offset of the expanded loop
   4816    instruction.  This should be incorporated into the relaxation
   4817    specification but is hard-coded here.  This is used to auto-align
   4818    the loop instruction.  It is invalid to call this function if the
   4819    configuration does not have loops or if the opcode is not a loop
   4820    opcode.  */
   4821 
   4822 static addressT
   4823 get_expanded_loop_offset (xtensa_opcode opcode)
   4824 {
   4825   /* This is the OFFSET of the loop instruction in the expanded loop.
   4826      This MUST correspond directly to the specification of the loop
   4827      expansion.  It will be validated on fragment conversion.  */
   4828   gas_assert (opcode != XTENSA_UNDEFINED);
   4829   if (opcode == xtensa_loop_opcode)
   4830     return 0;
   4831   if (opcode == xtensa_loopnez_opcode)
   4832     return 3;
   4833   if (opcode == xtensa_loopgtz_opcode)
   4834     return 6;
   4835   as_fatal (_("get_expanded_loop_offset: invalid opcode"));
   4836   return 0;
   4837 }
   4838 
   4839 
   4840 static fragS *
   4841 get_literal_pool_location (segT seg)
   4842 {
   4843   return seg_info (seg)->tc_segment_info_data.literal_pool_loc;
   4844 }
   4845 
   4846 
   4847 static void
   4848 set_literal_pool_location (segT seg, fragS *literal_pool_loc)
   4849 {
   4850   seg_info (seg)->tc_segment_info_data.literal_pool_loc = literal_pool_loc;
   4851 }
   4852 
   4853 
   4854 /* Set frag assembly state should be called when a new frag is
   4855    opened and after a frag has been closed.  */
   4856 
   4857 static void
   4858 xtensa_set_frag_assembly_state (fragS *fragP)
   4859 {
   4860   if (!density_supported)
   4861     fragP->tc_frag_data.is_no_density = TRUE;
   4862 
   4863   /* This function is called from subsegs_finish, which is called
   4864      after xtensa_end, so we can't use "use_transform" or
   4865      "use_schedule" here.  */
   4866   if (!directive_state[directive_transform])
   4867     fragP->tc_frag_data.is_no_transform = TRUE;
   4868   if (directive_state[directive_longcalls])
   4869     fragP->tc_frag_data.use_longcalls = TRUE;
   4870   fragP->tc_frag_data.use_absolute_literals =
   4871     directive_state[directive_absolute_literals];
   4872   fragP->tc_frag_data.is_assembly_state_set = TRUE;
   4873 }
   4874 
   4875 
   4876 static bfd_boolean
   4877 relaxable_section (asection *sec)
   4878 {
   4879   return ((sec->flags & SEC_DEBUGGING) == 0
   4880 	  && strcmp (sec->name, ".eh_frame") != 0);
   4881 }
   4882 
   4883 
   4884 static void
   4885 xtensa_mark_frags_for_org (void)
   4886 {
   4887   segT *seclist;
   4888 
   4889   /* Walk over each fragment of all of the current segments.  If we find
   4890      a .org frag in any of the segments, mark all frags prior to it as
   4891      "no transform", which will prevent linker optimizations from messing
   4892      up the .org distance.  This should be done after
   4893      xtensa_find_unmarked_state_frags, because we don't want to worry here
   4894      about that function trashing the data we save here.  */
   4895 
   4896   for (seclist = &stdoutput->sections;
   4897        seclist && *seclist;
   4898        seclist = &(*seclist)->next)
   4899     {
   4900       segT sec = *seclist;
   4901       segment_info_type *seginfo;
   4902       fragS *fragP;
   4903       flagword flags;
   4904       flags = bfd_get_section_flags (stdoutput, sec);
   4905       if (flags & SEC_DEBUGGING)
   4906 	continue;
   4907       if (!(flags & SEC_ALLOC))
   4908 	continue;
   4909 
   4910       seginfo = seg_info (sec);
   4911       if (seginfo && seginfo->frchainP)
   4912 	{
   4913 	  fragS *last_fragP = seginfo->frchainP->frch_root;
   4914 	  for (fragP = seginfo->frchainP->frch_root; fragP;
   4915 	       fragP = fragP->fr_next)
   4916 	    {
   4917 	      /* cvt_frag_to_fill has changed the fr_type of org frags to
   4918 		 rs_fill, so use the value as cached in rs_subtype here.  */
   4919 	      if (fragP->fr_subtype == RELAX_ORG)
   4920 		{
   4921 		  while (last_fragP != fragP->fr_next)
   4922 		    {
   4923 		      last_fragP->tc_frag_data.is_no_transform = TRUE;
   4924 		      last_fragP = last_fragP->fr_next;
   4925 		    }
   4926 		}
   4927 	    }
   4928 	}
   4929     }
   4930 }
   4931 
   4932 
   4933 static void
   4934 xtensa_find_unmarked_state_frags (void)
   4935 {
   4936   segT *seclist;
   4937 
   4938   /* Walk over each fragment of all of the current segments.  For each
   4939      unmarked fragment, mark it with the same info as the previous
   4940      fragment.  */
   4941   for (seclist = &stdoutput->sections;
   4942        seclist && *seclist;
   4943        seclist = &(*seclist)->next)
   4944     {
   4945       segT sec = *seclist;
   4946       segment_info_type *seginfo;
   4947       fragS *fragP;
   4948       flagword flags;
   4949       flags = bfd_get_section_flags (stdoutput, sec);
   4950       if (flags & SEC_DEBUGGING)
   4951 	continue;
   4952       if (!(flags & SEC_ALLOC))
   4953 	continue;
   4954 
   4955       seginfo = seg_info (sec);
   4956       if (seginfo && seginfo->frchainP)
   4957 	{
   4958 	  fragS *last_fragP = 0;
   4959 	  for (fragP = seginfo->frchainP->frch_root; fragP;
   4960 	       fragP = fragP->fr_next)
   4961 	    {
   4962 	      if (fragP->fr_fix != 0
   4963 		  && !fragP->tc_frag_data.is_assembly_state_set)
   4964 		{
   4965 		  if (last_fragP == 0)
   4966 		    {
   4967 		      as_warn_where (fragP->fr_file, fragP->fr_line,
   4968 				     _("assembly state not set for first frag in section %s"),
   4969 				     sec->name);
   4970 		    }
   4971 		  else
   4972 		    {
   4973 		      fragP->tc_frag_data.is_assembly_state_set = TRUE;
   4974 		      fragP->tc_frag_data.is_no_density =
   4975 			last_fragP->tc_frag_data.is_no_density;
   4976 		      fragP->tc_frag_data.is_no_transform =
   4977 			last_fragP->tc_frag_data.is_no_transform;
   4978 		      fragP->tc_frag_data.use_longcalls =
   4979 			last_fragP->tc_frag_data.use_longcalls;
   4980 		      fragP->tc_frag_data.use_absolute_literals =
   4981 			last_fragP->tc_frag_data.use_absolute_literals;
   4982 		    }
   4983 		}
   4984 	      if (fragP->tc_frag_data.is_assembly_state_set)
   4985 		last_fragP = fragP;
   4986 	    }
   4987 	}
   4988     }
   4989 }
   4990 
   4991 
   4992 static void
   4993 xtensa_find_unaligned_branch_targets (bfd *abfd ATTRIBUTE_UNUSED,
   4994 				      asection *sec,
   4995 				      void *unused ATTRIBUTE_UNUSED)
   4996 {
   4997   flagword flags = bfd_get_section_flags (abfd, sec);
   4998   segment_info_type *seginfo = seg_info (sec);
   4999   fragS *frag = seginfo->frchainP->frch_root;
   5000 
   5001   if (flags & SEC_CODE)
   5002     {
   5003       xtensa_isa isa = xtensa_default_isa;
   5004       xtensa_insnbuf insnbuf = xtensa_insnbuf_alloc (isa);
   5005       while (frag != NULL)
   5006 	{
   5007 	  if (frag->tc_frag_data.is_branch_target)
   5008 	    {
   5009 	      int op_size;
   5010 	      addressT branch_align, frag_addr;
   5011 	      xtensa_format fmt;
   5012 
   5013 	      xtensa_insnbuf_from_chars
   5014 		(isa, insnbuf, (unsigned char *) frag->fr_literal, 0);
   5015 	      fmt = xtensa_format_decode (isa, insnbuf);
   5016 	      op_size = xtensa_format_length (isa, fmt);
   5017 	      branch_align = 1 << branch_align_power (sec);
   5018 	      frag_addr = frag->fr_address % branch_align;
   5019 	      if (frag_addr + op_size > branch_align)
   5020 		as_warn_where (frag->fr_file, frag->fr_line,
   5021 			       _("unaligned branch target: %d bytes at 0x%lx"),
   5022 			       op_size, (long) frag->fr_address);
   5023 	    }
   5024 	  frag = frag->fr_next;
   5025 	}
   5026       xtensa_insnbuf_free (isa, insnbuf);
   5027     }
   5028 }
   5029 
   5030 
   5031 static void
   5032 xtensa_find_unaligned_loops (bfd *abfd ATTRIBUTE_UNUSED,
   5033 			     asection *sec,
   5034 			     void *unused ATTRIBUTE_UNUSED)
   5035 {
   5036   flagword flags = bfd_get_section_flags (abfd, sec);
   5037   segment_info_type *seginfo = seg_info (sec);
   5038   fragS *frag = seginfo->frchainP->frch_root;
   5039   xtensa_isa isa = xtensa_default_isa;
   5040 
   5041   if (flags & SEC_CODE)
   5042     {
   5043       xtensa_insnbuf insnbuf = xtensa_insnbuf_alloc (isa);
   5044       while (frag != NULL)
   5045 	{
   5046 	  if (frag->tc_frag_data.is_first_loop_insn)
   5047 	    {
   5048 	      int op_size;
   5049 	      addressT frag_addr;
   5050 	      xtensa_format fmt;
   5051 
   5052 	      if (frag->fr_fix == 0)
   5053 		frag = next_non_empty_frag (frag);
   5054 
   5055 	      if (frag)
   5056 		{
   5057 		  xtensa_insnbuf_from_chars
   5058 		    (isa, insnbuf, (unsigned char *) frag->fr_literal, 0);
   5059 		  fmt = xtensa_format_decode (isa, insnbuf);
   5060 		  op_size = xtensa_format_length (isa, fmt);
   5061 		  frag_addr = frag->fr_address % xtensa_fetch_width;
   5062 
   5063 		  if (frag_addr + op_size > xtensa_fetch_width)
   5064 		    as_warn_where (frag->fr_file, frag->fr_line,
   5065 				   _("unaligned loop: %d bytes at 0x%lx"),
   5066 				   op_size, (long) frag->fr_address);
   5067 		}
   5068 	    }
   5069 	  frag = frag->fr_next;
   5070 	}
   5071       xtensa_insnbuf_free (isa, insnbuf);
   5072     }
   5073 }
   5074 
   5075 
   5076 static int
   5077 xg_apply_fix_value (fixS *fixP, valueT val)
   5078 {
   5079   xtensa_isa isa = xtensa_default_isa;
   5080   static xtensa_insnbuf insnbuf = NULL;
   5081   static xtensa_insnbuf slotbuf = NULL;
   5082   xtensa_format fmt;
   5083   int slot;
   5084   bfd_boolean alt_reloc;
   5085   xtensa_opcode opcode;
   5086   char *const fixpos = fixP->fx_frag->fr_literal + fixP->fx_where;
   5087 
   5088   if (decode_reloc (fixP->fx_r_type, &slot, &alt_reloc)
   5089       || alt_reloc)
   5090     as_fatal (_("unexpected fix"));
   5091 
   5092   if (!insnbuf)
   5093     {
   5094       insnbuf = xtensa_insnbuf_alloc (isa);
   5095       slotbuf = xtensa_insnbuf_alloc (isa);
   5096     }
   5097 
   5098   xtensa_insnbuf_from_chars (isa, insnbuf, (unsigned char *) fixpos, 0);
   5099   fmt = xtensa_format_decode (isa, insnbuf);
   5100   if (fmt == XTENSA_UNDEFINED)
   5101     as_fatal (_("undecodable fix"));
   5102   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
   5103   opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
   5104   if (opcode == XTENSA_UNDEFINED)
   5105     as_fatal (_("undecodable fix"));
   5106 
   5107   /* CONST16 immediates are not PC-relative, despite the fact that we
   5108      reuse the normal PC-relative operand relocations for the low part
   5109      of a CONST16 operand.  */
   5110   if (opcode == xtensa_const16_opcode)
   5111     return 0;
   5112 
   5113   xtensa_insnbuf_set_operand (slotbuf, fmt, slot, opcode,
   5114 			      get_relaxable_immed (opcode), val,
   5115 			      fixP->fx_file, fixP->fx_line);
   5116 
   5117   xtensa_format_set_slot (isa, fmt, slot, insnbuf, slotbuf);
   5118   xtensa_insnbuf_to_chars (isa, insnbuf, (unsigned char *) fixpos, 0);
   5119 
   5120   return 1;
   5121 }
   5122 
   5123 
   5124 /* External Functions and Other GAS Hooks.  */
   5126 
   5127 const char *
   5128 xtensa_target_format (void)
   5129 {
   5130   return (target_big_endian ? "elf32-xtensa-be" : "elf32-xtensa-le");
   5131 }
   5132 
   5133 
   5134 void
   5135 xtensa_file_arch_init (bfd *abfd)
   5136 {
   5137   bfd_set_private_flags (abfd, 0x100 | 0x200);
   5138 }
   5139 
   5140 
   5141 void
   5142 md_number_to_chars (char *buf, valueT val, int n)
   5143 {
   5144   if (target_big_endian)
   5145     number_to_chars_bigendian (buf, val, n);
   5146   else
   5147     number_to_chars_littleendian (buf, val, n);
   5148 }
   5149 
   5150 
   5151 /* This function is called once, at assembler startup time.  It should
   5152    set up all the tables, etc. that the MD part of the assembler will
   5153    need.  */
   5154 
   5155 void
   5156 md_begin (void)
   5157 {
   5158   segT current_section = now_seg;
   5159   int current_subsec = now_subseg;
   5160   xtensa_isa isa;
   5161   int i;
   5162 
   5163   xtensa_default_isa = xtensa_isa_init (0, 0);
   5164   isa = xtensa_default_isa;
   5165 
   5166   linkrelax = 1;
   5167 
   5168   /* Set up the literal sections.  */
   5169   memset (&default_lit_sections, 0, sizeof (default_lit_sections));
   5170 
   5171   subseg_set (current_section, current_subsec);
   5172 
   5173   xtensa_addi_opcode = xtensa_opcode_lookup (isa, "addi");
   5174   xtensa_addmi_opcode = xtensa_opcode_lookup (isa, "addmi");
   5175   xtensa_call0_opcode = xtensa_opcode_lookup (isa, "call0");
   5176   xtensa_call4_opcode = xtensa_opcode_lookup (isa, "call4");
   5177   xtensa_call8_opcode = xtensa_opcode_lookup (isa, "call8");
   5178   xtensa_call12_opcode = xtensa_opcode_lookup (isa, "call12");
   5179   xtensa_callx0_opcode = xtensa_opcode_lookup (isa, "callx0");
   5180   xtensa_callx4_opcode = xtensa_opcode_lookup (isa, "callx4");
   5181   xtensa_callx8_opcode = xtensa_opcode_lookup (isa, "callx8");
   5182   xtensa_callx12_opcode = xtensa_opcode_lookup (isa, "callx12");
   5183   xtensa_const16_opcode = xtensa_opcode_lookup (isa, "const16");
   5184   xtensa_entry_opcode = xtensa_opcode_lookup (isa, "entry");
   5185   xtensa_extui_opcode = xtensa_opcode_lookup (isa, "extui");
   5186   xtensa_movi_opcode = xtensa_opcode_lookup (isa, "movi");
   5187   xtensa_movi_n_opcode = xtensa_opcode_lookup (isa, "movi.n");
   5188   xtensa_isync_opcode = xtensa_opcode_lookup (isa, "isync");
   5189   xtensa_j_opcode = xtensa_opcode_lookup (isa, "j");
   5190   xtensa_jx_opcode = xtensa_opcode_lookup (isa, "jx");
   5191   xtensa_l32r_opcode = xtensa_opcode_lookup (isa, "l32r");
   5192   xtensa_loop_opcode = xtensa_opcode_lookup (isa, "loop");
   5193   xtensa_loopnez_opcode = xtensa_opcode_lookup (isa, "loopnez");
   5194   xtensa_loopgtz_opcode = xtensa_opcode_lookup (isa, "loopgtz");
   5195   xtensa_nop_opcode = xtensa_opcode_lookup (isa, "nop");
   5196   xtensa_nop_n_opcode = xtensa_opcode_lookup (isa, "nop.n");
   5197   xtensa_or_opcode = xtensa_opcode_lookup (isa, "or");
   5198   xtensa_ret_opcode = xtensa_opcode_lookup (isa, "ret");
   5199   xtensa_ret_n_opcode = xtensa_opcode_lookup (isa, "ret.n");
   5200   xtensa_retw_opcode = xtensa_opcode_lookup (isa, "retw");
   5201   xtensa_retw_n_opcode = xtensa_opcode_lookup (isa, "retw.n");
   5202   xtensa_rsr_lcount_opcode = xtensa_opcode_lookup (isa, "rsr.lcount");
   5203   xtensa_waiti_opcode = xtensa_opcode_lookup (isa, "waiti");
   5204 
   5205   for (i = 0; i < xtensa_isa_num_formats (isa); i++)
   5206     {
   5207       int format_slots = xtensa_format_num_slots (isa, i);
   5208       if (format_slots > config_max_slots)
   5209 	config_max_slots = format_slots;
   5210     }
   5211 
   5212   xg_init_vinsn (&cur_vinsn);
   5213 
   5214   xtensa_num_pipe_stages = xtensa_isa_num_pipe_stages (isa);
   5215 
   5216   init_op_placement_info_table ();
   5217 
   5218   /* Set up the assembly state.  */
   5219   if (!frag_now->tc_frag_data.is_assembly_state_set)
   5220     xtensa_set_frag_assembly_state (frag_now);
   5221 }
   5222 
   5223 
   5224 /* TC_INIT_FIX_DATA hook */
   5225 
   5226 void
   5227 xtensa_init_fix_data (fixS *x)
   5228 {
   5229   x->tc_fix_data.slot = 0;
   5230   x->tc_fix_data.X_add_symbol = NULL;
   5231   x->tc_fix_data.X_add_number = 0;
   5232 }
   5233 
   5234 
   5235 /* tc_frob_label hook */
   5236 
   5237 void
   5238 xtensa_frob_label (symbolS *sym)
   5239 {
   5240   float freq;
   5241 
   5242   if (cur_vinsn.inside_bundle)
   5243     {
   5244       as_bad (_("labels are not valid inside bundles"));
   5245       return;
   5246     }
   5247 
   5248   freq = get_subseg_target_freq (now_seg, now_subseg);
   5249 
   5250   /* Since the label was already attached to a frag associated with the
   5251      previous basic block, it now needs to be reset to the current frag.  */
   5252   symbol_set_frag (sym, frag_now);
   5253   S_SET_VALUE (sym, (valueT) frag_now_fix ());
   5254 
   5255   if (generating_literals)
   5256     xtensa_add_literal_sym (sym);
   5257   else
   5258     xtensa_add_insn_label (sym);
   5259 
   5260   if (symbol_get_tc (sym)->is_loop_target)
   5261     {
   5262       if ((get_last_insn_flags (now_seg, now_subseg)
   5263 	  & FLAG_IS_BAD_LOOPEND) != 0)
   5264 	as_bad (_("invalid last instruction for a zero-overhead loop"));
   5265 
   5266       xtensa_set_frag_assembly_state (frag_now);
   5267       frag_var (rs_machine_dependent, 4, 4, RELAX_LOOP_END,
   5268 		frag_now->fr_symbol, frag_now->fr_offset, NULL);
   5269 
   5270       xtensa_set_frag_assembly_state (frag_now);
   5271       xtensa_move_labels (frag_now, 0);
   5272     }
   5273 
   5274   /* No target aligning in the absolute section.  */
   5275   if (now_seg != absolute_section
   5276       && !is_unaligned_label (sym)
   5277       && !generating_literals)
   5278     {
   5279       xtensa_set_frag_assembly_state (frag_now);
   5280 
   5281       if (do_align_targets ())
   5282 	frag_var (rs_machine_dependent, 0, (int) freq,
   5283 		  RELAX_DESIRE_ALIGN_IF_TARGET, frag_now->fr_symbol,
   5284 		  frag_now->fr_offset, NULL);
   5285       else
   5286 	frag_var (rs_fill, 0, 0, frag_now->fr_subtype,
   5287 		  frag_now->fr_symbol, frag_now->fr_offset, NULL);
   5288       xtensa_set_frag_assembly_state (frag_now);
   5289       xtensa_move_labels (frag_now, 0);
   5290     }
   5291 
   5292   /* We need to mark the following properties even if we aren't aligning.  */
   5293 
   5294   /* If the label is already known to be a branch target, i.e., a
   5295      forward branch, mark the frag accordingly.  Backward branches
   5296      are handled by xg_add_branch_and_loop_targets.  */
   5297   if (symbol_get_tc (sym)->is_branch_target)
   5298     symbol_get_frag (sym)->tc_frag_data.is_branch_target = TRUE;
   5299 
   5300   /* Loops only go forward, so they can be identified here.  */
   5301   if (symbol_get_tc (sym)->is_loop_target)
   5302     symbol_get_frag (sym)->tc_frag_data.is_loop_target = TRUE;
   5303 
   5304   dwarf2_emit_label (sym);
   5305 }
   5306 
   5307 
   5308 /* tc_unrecognized_line hook */
   5309 
   5310 int
   5311 xtensa_unrecognized_line (int ch)
   5312 {
   5313   switch (ch)
   5314     {
   5315     case '{' :
   5316       if (cur_vinsn.inside_bundle == 0)
   5317 	{
   5318 	  /* PR8110: Cannot emit line number info inside a FLIX bundle
   5319 	     when using --gstabs.  Temporarily disable debug info.  */
   5320 	  generate_lineno_debug ();
   5321 	  if (debug_type == DEBUG_STABS)
   5322 	    {
   5323 	      xt_saved_debug_type = debug_type;
   5324 	      debug_type = DEBUG_NONE;
   5325 	    }
   5326 
   5327 	  cur_vinsn.inside_bundle = 1;
   5328 	}
   5329       else
   5330 	{
   5331 	  as_bad (_("extra opening brace"));
   5332 	  return 0;
   5333 	}
   5334       break;
   5335 
   5336     case '}' :
   5337       if (cur_vinsn.inside_bundle)
   5338 	finish_vinsn (&cur_vinsn);
   5339       else
   5340 	{
   5341 	  as_bad (_("extra closing brace"));
   5342 	  return 0;
   5343 	}
   5344       break;
   5345     default:
   5346       as_bad (_("syntax error"));
   5347       return 0;
   5348     }
   5349   return 1;
   5350 }
   5351 
   5352 
   5353 /* md_flush_pending_output hook */
   5354 
   5355 void
   5356 xtensa_flush_pending_output (void)
   5357 {
   5358   /* This line fixes a bug where automatically generated gstabs info
   5359      separates a function label from its entry instruction, ending up
   5360      with the literal position between the function label and the entry
   5361      instruction and crashing code.  It only happens with --gstabs and
   5362      --text-section-literals, and when several other obscure relaxation
   5363      conditions are met.  */
   5364   if (outputting_stabs_line_debug)
   5365     return;
   5366 
   5367   if (cur_vinsn.inside_bundle)
   5368     as_bad (_("missing closing brace"));
   5369 
   5370   /* If there is a non-zero instruction fragment, close it.  */
   5371   if (frag_now_fix () != 0 && frag_now->tc_frag_data.is_insn)
   5372     {
   5373       frag_wane (frag_now);
   5374       frag_new (0);
   5375       xtensa_set_frag_assembly_state (frag_now);
   5376     }
   5377   frag_now->tc_frag_data.is_insn = FALSE;
   5378 
   5379   xtensa_clear_insn_labels ();
   5380 }
   5381 
   5382 
   5383 /* We had an error while parsing an instruction.  The string might look
   5384    like this: "insn arg1, arg2 }".  If so, we need to see the closing
   5385    brace and reset some fields.  Otherwise, the vinsn never gets closed
   5386    and the num_slots field will grow past the end of the array of slots,
   5387    and bad things happen.  */
   5388 
   5389 static void
   5390 error_reset_cur_vinsn (void)
   5391 {
   5392   if (cur_vinsn.inside_bundle)
   5393     {
   5394       if (*input_line_pointer == '}'
   5395 	  || *(input_line_pointer - 1) == '}'
   5396 	  || *(input_line_pointer - 2) == '}')
   5397 	xg_clear_vinsn (&cur_vinsn);
   5398     }
   5399 }
   5400 
   5401 
   5402 void
   5403 md_assemble (char *str)
   5404 {
   5405   xtensa_isa isa = xtensa_default_isa;
   5406   char *opname;
   5407   unsigned opnamelen;
   5408   bfd_boolean has_underbar = FALSE;
   5409   char *arg_strings[MAX_INSN_ARGS];
   5410   int num_args;
   5411   TInsn orig_insn;		/* Original instruction from the input.  */
   5412 
   5413   tinsn_init (&orig_insn);
   5414 
   5415   /* Split off the opcode.  */
   5416   opnamelen = strspn (str, "abcdefghijklmnopqrstuvwxyz_/0123456789.");
   5417   opname = xmalloc (opnamelen + 1);
   5418   memcpy (opname, str, opnamelen);
   5419   opname[opnamelen] = '\0';
   5420 
   5421   num_args = tokenize_arguments (arg_strings, str + opnamelen);
   5422   if (num_args == -1)
   5423     {
   5424       as_bad (_("syntax error"));
   5425       return;
   5426     }
   5427 
   5428   if (xg_translate_idioms (&opname, &num_args, arg_strings))
   5429     return;
   5430 
   5431   /* Check for an underbar prefix.  */
   5432   if (*opname == '_')
   5433     {
   5434       has_underbar = TRUE;
   5435       opname += 1;
   5436     }
   5437 
   5438   orig_insn.insn_type = ITYPE_INSN;
   5439   orig_insn.ntok = 0;
   5440   orig_insn.is_specific_opcode = (has_underbar || !use_transform ());
   5441   orig_insn.opcode = xtensa_opcode_lookup (isa, opname);
   5442 
   5443   /* Special case: Check for "CALLXn.TLS" psuedo op.  If found, grab its
   5444      extra argument and set the opcode to "CALLXn".  */
   5445   if (orig_insn.opcode == XTENSA_UNDEFINED
   5446       && strncasecmp (opname, "callx", 5) == 0)
   5447     {
   5448       unsigned long window_size;
   5449       char *suffix;
   5450 
   5451       window_size = strtoul (opname + 5, &suffix, 10);
   5452       if (suffix != opname + 5
   5453 	  && (window_size == 0
   5454 	      || window_size == 4
   5455 	      || window_size == 8
   5456 	      || window_size == 12)
   5457 	  && strcasecmp (suffix, ".tls") == 0)
   5458 	{
   5459 	  switch (window_size)
   5460 	    {
   5461 	    case 0: orig_insn.opcode = xtensa_callx0_opcode; break;
   5462 	    case 4: orig_insn.opcode = xtensa_callx4_opcode; break;
   5463 	    case 8: orig_insn.opcode = xtensa_callx8_opcode; break;
   5464 	    case 12: orig_insn.opcode = xtensa_callx12_opcode; break;
   5465 	    }
   5466 
   5467 	  if (num_args != 2)
   5468 	    as_bad (_("wrong number of operands for '%s'"), opname);
   5469 	  else
   5470 	    {
   5471 	      bfd_reloc_code_real_type reloc;
   5472 	      char *old_input_line_pointer;
   5473 	      expressionS *tok = &orig_insn.extra_arg;
   5474 
   5475 	      old_input_line_pointer = input_line_pointer;
   5476 	      input_line_pointer = arg_strings[num_args - 1];
   5477 
   5478 	      expression (tok);
   5479 	      if (tok->X_op == O_symbol
   5480 		  && ((reloc = xtensa_elf_suffix (&input_line_pointer, tok))
   5481 		      == BFD_RELOC_XTENSA_TLS_CALL))
   5482 		tok->X_op = map_suffix_reloc_to_operator (reloc);
   5483 	      else
   5484 		as_bad (_("bad relocation expression for '%s'"), opname);
   5485 
   5486 	      input_line_pointer = old_input_line_pointer;
   5487 	      num_args -= 1;
   5488 	    }
   5489 	}
   5490     }
   5491 
   5492   /* Special case: Check for "j.l" psuedo op.  */
   5493   if (orig_insn.opcode == XTENSA_UNDEFINED
   5494       && strncasecmp (opname, "j.l", 3) == 0)
   5495     {
   5496       if (num_args != 2)
   5497 	as_bad (_("wrong number of operands for '%s'"), opname);
   5498       else
   5499 	{
   5500 	  char *old_input_line_pointer;
   5501 	  expressionS *tok = &orig_insn.extra_arg;
   5502 
   5503 	  old_input_line_pointer = input_line_pointer;
   5504 	  input_line_pointer = arg_strings[num_args - 1];
   5505 
   5506 	  expression_maybe_register (xtensa_jx_opcode, 0, tok);
   5507 	  input_line_pointer = old_input_line_pointer;
   5508 
   5509 	  num_args -= 1;
   5510 	  orig_insn.opcode = xtensa_j_opcode;
   5511 	}
   5512     }
   5513 
   5514   if (orig_insn.opcode == XTENSA_UNDEFINED)
   5515     {
   5516       xtensa_format fmt = xtensa_format_lookup (isa, opname);
   5517       if (fmt == XTENSA_UNDEFINED)
   5518 	{
   5519 	  as_bad (_("unknown opcode or format name '%s'"), opname);
   5520 	  error_reset_cur_vinsn ();
   5521 	  return;
   5522 	}
   5523       if (!cur_vinsn.inside_bundle)
   5524 	{
   5525 	  as_bad (_("format names only valid inside bundles"));
   5526 	  error_reset_cur_vinsn ();
   5527 	  return;
   5528 	}
   5529       if (cur_vinsn.format != XTENSA_UNDEFINED)
   5530 	as_warn (_("multiple formats specified for one bundle; using '%s'"),
   5531 		 opname);
   5532       cur_vinsn.format = fmt;
   5533       free (has_underbar ? opname - 1 : opname);
   5534       error_reset_cur_vinsn ();
   5535       return;
   5536     }
   5537 
   5538   /* Parse the arguments.  */
   5539   if (parse_arguments (&orig_insn, num_args, arg_strings))
   5540     {
   5541       as_bad (_("syntax error"));
   5542       error_reset_cur_vinsn ();
   5543       return;
   5544     }
   5545 
   5546   /* Free the opcode and argument strings, now that they've been parsed.  */
   5547   free (has_underbar ? opname - 1 : opname);
   5548   opname = 0;
   5549   while (num_args-- > 0)
   5550     free (arg_strings[num_args]);
   5551 
   5552   /* Get expressions for invisible operands.  */
   5553   if (get_invisible_operands (&orig_insn))
   5554     {
   5555       error_reset_cur_vinsn ();
   5556       return;
   5557     }
   5558 
   5559   /* Check for the right number and type of arguments.  */
   5560   if (tinsn_check_arguments (&orig_insn))
   5561     {
   5562       error_reset_cur_vinsn ();
   5563       return;
   5564     }
   5565 
   5566   /* Record the line number for each TInsn, because a FLIX bundle may be
   5567      spread across multiple input lines and individual instructions may be
   5568      moved around in some cases.  */
   5569   orig_insn.loc_directive_seen = dwarf2_loc_directive_seen;
   5570   dwarf2_where (&orig_insn.debug_line);
   5571   dwarf2_consume_line_info ();
   5572 
   5573   xg_add_branch_and_loop_targets (&orig_insn);
   5574 
   5575   /* Check that immediate value for ENTRY is >= 16.  */
   5576   if (orig_insn.opcode == xtensa_entry_opcode && orig_insn.ntok >= 3)
   5577     {
   5578       expressionS *exp = &orig_insn.tok[2];
   5579       if (exp->X_op == O_constant && exp->X_add_number < 16)
   5580 	as_warn (_("entry instruction with stack decrement < 16"));
   5581     }
   5582 
   5583   /* Finish it off:
   5584      assemble_tokens (opcode, tok, ntok);
   5585      expand the tokens from the orig_insn into the
   5586      stack of instructions that will not expand
   5587      unless required at relaxation time.  */
   5588 
   5589   if (!cur_vinsn.inside_bundle)
   5590     emit_single_op (&orig_insn);
   5591   else /* We are inside a bundle.  */
   5592     {
   5593       cur_vinsn.slots[cur_vinsn.num_slots] = orig_insn;
   5594       cur_vinsn.num_slots++;
   5595       if (*input_line_pointer == '}'
   5596 	  || *(input_line_pointer - 1) == '}'
   5597 	  || *(input_line_pointer - 2) == '}')
   5598 	finish_vinsn (&cur_vinsn);
   5599     }
   5600 
   5601   /* We've just emitted a new instruction so clear the list of labels.  */
   5602   xtensa_clear_insn_labels ();
   5603 
   5604   xtensa_check_frag_count ();
   5605 }
   5606 
   5607 
   5608 /* HANDLE_ALIGN hook */
   5609 
   5610 /* For a .align directive, we mark the previous block with the alignment
   5611    information.  This will be placed in the object file in the
   5612    property section corresponding to this section.  */
   5613 
   5614 void
   5615 xtensa_handle_align (fragS *fragP)
   5616 {
   5617   if (linkrelax
   5618       && ! fragP->tc_frag_data.is_literal
   5619       && (fragP->fr_type == rs_align
   5620 	  || fragP->fr_type == rs_align_code)
   5621       && fragP->fr_offset > 0
   5622       && now_seg != bss_section)
   5623     {
   5624       fragP->tc_frag_data.is_align = TRUE;
   5625       fragP->tc_frag_data.alignment = fragP->fr_offset;
   5626     }
   5627 
   5628   if (fragP->fr_type == rs_align_test)
   5629     {
   5630       int count;
   5631       count = fragP->fr_next->fr_address - fragP->fr_address - fragP->fr_fix;
   5632       if (count != 0)
   5633 	as_bad_where (fragP->fr_file, fragP->fr_line,
   5634 		      _("unaligned entry instruction"));
   5635     }
   5636 
   5637   if (linkrelax && fragP->fr_type == rs_org)
   5638     fragP->fr_subtype = RELAX_ORG;
   5639 }
   5640 
   5641 
   5642 /* TC_FRAG_INIT hook */
   5643 
   5644 void
   5645 xtensa_frag_init (fragS *frag)
   5646 {
   5647   xtensa_set_frag_assembly_state (frag);
   5648 }
   5649 
   5650 
   5651 symbolS *
   5652 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
   5653 {
   5654   return NULL;
   5655 }
   5656 
   5657 
   5658 /* Round up a section size to the appropriate boundary.  */
   5659 
   5660 valueT
   5661 md_section_align (segT segment ATTRIBUTE_UNUSED, valueT size)
   5662 {
   5663   return size;			/* Byte alignment is fine.  */
   5664 }
   5665 
   5666 
   5667 long
   5668 md_pcrel_from (fixS *fixP)
   5669 {
   5670   char *insn_p;
   5671   static xtensa_insnbuf insnbuf = NULL;
   5672   static xtensa_insnbuf slotbuf = NULL;
   5673   int opnum;
   5674   uint32 opnd_value;
   5675   xtensa_opcode opcode;
   5676   xtensa_format fmt;
   5677   int slot;
   5678   xtensa_isa isa = xtensa_default_isa;
   5679   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
   5680   bfd_boolean alt_reloc;
   5681 
   5682   if (fixP->fx_r_type == BFD_RELOC_XTENSA_ASM_EXPAND)
   5683     return 0;
   5684 
   5685   if (fixP->fx_r_type == BFD_RELOC_32_PCREL)
   5686     return addr;
   5687 
   5688   if (!insnbuf)
   5689     {
   5690       insnbuf = xtensa_insnbuf_alloc (isa);
   5691       slotbuf = xtensa_insnbuf_alloc (isa);
   5692     }
   5693 
   5694   insn_p = &fixP->fx_frag->fr_literal[fixP->fx_where];
   5695   xtensa_insnbuf_from_chars (isa, insnbuf, (unsigned char *) insn_p, 0);
   5696   fmt = xtensa_format_decode (isa, insnbuf);
   5697 
   5698   if (fmt == XTENSA_UNDEFINED)
   5699     as_fatal (_("bad instruction format"));
   5700 
   5701   if (decode_reloc (fixP->fx_r_type, &slot, &alt_reloc) != 0)
   5702     as_fatal (_("invalid relocation"));
   5703 
   5704   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
   5705   opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
   5706 
   5707   /* Check for "alternate" relocations (operand not specified).  None
   5708      of the current uses for these are really PC-relative.  */
   5709   if (alt_reloc || opcode == xtensa_const16_opcode)
   5710     {
   5711       if (opcode != xtensa_l32r_opcode
   5712 	  && opcode != xtensa_const16_opcode)
   5713 	as_fatal (_("invalid relocation for '%s' instruction"),
   5714 		  xtensa_opcode_name (isa, opcode));
   5715       return 0;
   5716     }
   5717 
   5718   opnum = get_relaxable_immed (opcode);
   5719   opnd_value = 0;
   5720   if (xtensa_operand_is_PCrelative (isa, opcode, opnum) != 1
   5721       || xtensa_operand_do_reloc (isa, opcode, opnum, &opnd_value, addr))
   5722     {
   5723       as_bad_where (fixP->fx_file,
   5724 		    fixP->fx_line,
   5725 		    _("invalid relocation for operand %d of '%s'"),
   5726 		    opnum, xtensa_opcode_name (isa, opcode));
   5727       return 0;
   5728     }
   5729   return 0 - opnd_value;
   5730 }
   5731 
   5732 
   5733 /* TC_FORCE_RELOCATION hook */
   5734 
   5735 int
   5736 xtensa_force_relocation (fixS *fix)
   5737 {
   5738   switch (fix->fx_r_type)
   5739     {
   5740     case BFD_RELOC_XTENSA_ASM_EXPAND:
   5741     case BFD_RELOC_XTENSA_SLOT0_ALT:
   5742     case BFD_RELOC_XTENSA_SLOT1_ALT:
   5743     case BFD_RELOC_XTENSA_SLOT2_ALT:
   5744     case BFD_RELOC_XTENSA_SLOT3_ALT:
   5745     case BFD_RELOC_XTENSA_SLOT4_ALT:
   5746     case BFD_RELOC_XTENSA_SLOT5_ALT:
   5747     case BFD_RELOC_XTENSA_SLOT6_ALT:
   5748     case BFD_RELOC_XTENSA_SLOT7_ALT:
   5749     case BFD_RELOC_XTENSA_SLOT8_ALT:
   5750     case BFD_RELOC_XTENSA_SLOT9_ALT:
   5751     case BFD_RELOC_XTENSA_SLOT10_ALT:
   5752     case BFD_RELOC_XTENSA_SLOT11_ALT:
   5753     case BFD_RELOC_XTENSA_SLOT12_ALT:
   5754     case BFD_RELOC_XTENSA_SLOT13_ALT:
   5755     case BFD_RELOC_XTENSA_SLOT14_ALT:
   5756       return 1;
   5757     default:
   5758       break;
   5759     }
   5760 
   5761   if (linkrelax && fix->fx_addsy
   5762       && relaxable_section (S_GET_SEGMENT (fix->fx_addsy)))
   5763     return 1;
   5764 
   5765   return generic_force_reloc (fix);
   5766 }
   5767 
   5768 
   5769 /* TC_VALIDATE_FIX_SUB hook */
   5770 
   5771 int
   5772 xtensa_validate_fix_sub (fixS *fix)
   5773 {
   5774   segT add_symbol_segment, sub_symbol_segment;
   5775 
   5776   /* The difference of two symbols should be resolved by the assembler when
   5777      linkrelax is not set.  If the linker may relax the section containing
   5778      the symbols, then an Xtensa DIFF relocation must be generated so that
   5779      the linker knows to adjust the difference value.  */
   5780   if (!linkrelax || fix->fx_addsy == NULL)
   5781     return 0;
   5782 
   5783   /* Make sure both symbols are in the same segment, and that segment is
   5784      "normal" and relaxable.  If the segment is not "normal", then the
   5785      fix is not valid.  If the segment is not "relaxable", then the fix
   5786      should have been handled earlier.  */
   5787   add_symbol_segment = S_GET_SEGMENT (fix->fx_addsy);
   5788   if (! SEG_NORMAL (add_symbol_segment) ||
   5789       ! relaxable_section (add_symbol_segment))
   5790     return 0;
   5791   sub_symbol_segment = S_GET_SEGMENT (fix->fx_subsy);
   5792   return (sub_symbol_segment == add_symbol_segment);
   5793 }
   5794 
   5795 
   5796 /* NO_PSEUDO_DOT hook */
   5797 
   5798 /* This function has nothing to do with pseudo dots, but this is the
   5799    nearest macro to where the check needs to take place.  FIXME: This
   5800    seems wrong.  */
   5801 
   5802 bfd_boolean
   5803 xtensa_check_inside_bundle (void)
   5804 {
   5805   if (cur_vinsn.inside_bundle && input_line_pointer[-1] == '.')
   5806     as_bad (_("directives are not valid inside bundles"));
   5807 
   5808   /* This function must always return FALSE because it is called via a
   5809      macro that has nothing to do with bundling.  */
   5810   return FALSE;
   5811 }
   5812 
   5813 
   5814 /* md_elf_section_change_hook */
   5815 
   5816 void
   5817 xtensa_elf_section_change_hook (void)
   5818 {
   5819   /* Set up the assembly state.  */
   5820   if (!frag_now->tc_frag_data.is_assembly_state_set)
   5821     xtensa_set_frag_assembly_state (frag_now);
   5822 }
   5823 
   5824 
   5825 /* tc_fix_adjustable hook */
   5826 
   5827 bfd_boolean
   5828 xtensa_fix_adjustable (fixS *fixP)
   5829 {
   5830   /* We need the symbol name for the VTABLE entries.  */
   5831   if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
   5832       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
   5833     return 0;
   5834 
   5835   return 1;
   5836 }
   5837 
   5838 
   5839 /* tc_symbol_new_hook */
   5840 
   5841 symbolS *expr_symbols = NULL;
   5842 
   5843 void
   5844 xtensa_symbol_new_hook (symbolS *sym)
   5845 {
   5846   if (is_leb128_expr && S_GET_SEGMENT (sym) == expr_section)
   5847     {
   5848       symbol_get_tc (sym)->next_expr_symbol = expr_symbols;
   5849       expr_symbols = sym;
   5850     }
   5851 }
   5852 
   5853 
   5854 void
   5855 md_apply_fix (fixS *fixP, valueT *valP, segT seg)
   5856 {
   5857   char *const fixpos = fixP->fx_frag->fr_literal + fixP->fx_where;
   5858   valueT val = 0;
   5859 
   5860   /* Subtracted symbols are only allowed for a few relocation types, and
   5861      unless linkrelax is enabled, they should not make it to this point.  */
   5862   if (fixP->fx_subsy && !(linkrelax && (fixP->fx_r_type == BFD_RELOC_32
   5863 					|| fixP->fx_r_type == BFD_RELOC_16
   5864 					|| fixP->fx_r_type == BFD_RELOC_8)))
   5865     as_bad_where (fixP->fx_file, fixP->fx_line, _("expression too complex"));
   5866 
   5867   switch (fixP->fx_r_type)
   5868     {
   5869     case BFD_RELOC_32_PCREL:
   5870     case BFD_RELOC_32:
   5871     case BFD_RELOC_16:
   5872     case BFD_RELOC_8:
   5873       if (fixP->fx_subsy)
   5874 	{
   5875 	  switch (fixP->fx_r_type)
   5876 	    {
   5877 	    case BFD_RELOC_8:
   5878 	      fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF8;
   5879 	      fixP->fx_signed = 1;
   5880 	      break;
   5881 	    case BFD_RELOC_16:
   5882 	      fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF16;
   5883 	      fixP->fx_signed = 1;
   5884 	      break;
   5885 	    case BFD_RELOC_32:
   5886 	      fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF32;
   5887 	      fixP->fx_signed = 1;
   5888 	      break;
   5889 	    default:
   5890 	      break;
   5891 	    }
   5892 
   5893 	  val = (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset
   5894 		 - S_GET_VALUE (fixP->fx_subsy));
   5895 
   5896 	  /* The difference value gets written out, and the DIFF reloc
   5897 	     identifies the address of the subtracted symbol (i.e., the one
   5898 	     with the lowest address).  */
   5899 	  *valP = val;
   5900 	  fixP->fx_offset -= val;
   5901 	  fixP->fx_subsy = NULL;
   5902 	}
   5903       else if (! fixP->fx_addsy)
   5904 	{
   5905 	  val = *valP;
   5906 	  fixP->fx_done = 1;
   5907 	}
   5908       /* fall through */
   5909 
   5910     case BFD_RELOC_XTENSA_PLT:
   5911       md_number_to_chars (fixpos, val, fixP->fx_size);
   5912       fixP->fx_no_overflow = 0; /* Use the standard overflow check.  */
   5913       break;
   5914 
   5915     case BFD_RELOC_XTENSA_TLSDESC_FN:
   5916     case BFD_RELOC_XTENSA_TLSDESC_ARG:
   5917     case BFD_RELOC_XTENSA_TLS_TPOFF:
   5918     case BFD_RELOC_XTENSA_TLS_DTPOFF:
   5919       S_SET_THREAD_LOCAL (fixP->fx_addsy);
   5920       md_number_to_chars (fixpos, 0, fixP->fx_size);
   5921       fixP->fx_no_overflow = 0; /* Use the standard overflow check.  */
   5922       break;
   5923 
   5924     case BFD_RELOC_XTENSA_SLOT0_OP:
   5925     case BFD_RELOC_XTENSA_SLOT1_OP:
   5926     case BFD_RELOC_XTENSA_SLOT2_OP:
   5927     case BFD_RELOC_XTENSA_SLOT3_OP:
   5928     case BFD_RELOC_XTENSA_SLOT4_OP:
   5929     case BFD_RELOC_XTENSA_SLOT5_OP:
   5930     case BFD_RELOC_XTENSA_SLOT6_OP:
   5931     case BFD_RELOC_XTENSA_SLOT7_OP:
   5932     case BFD_RELOC_XTENSA_SLOT8_OP:
   5933     case BFD_RELOC_XTENSA_SLOT9_OP:
   5934     case BFD_RELOC_XTENSA_SLOT10_OP:
   5935     case BFD_RELOC_XTENSA_SLOT11_OP:
   5936     case BFD_RELOC_XTENSA_SLOT12_OP:
   5937     case BFD_RELOC_XTENSA_SLOT13_OP:
   5938     case BFD_RELOC_XTENSA_SLOT14_OP:
   5939       if (linkrelax)
   5940 	{
   5941 	  /* Write the tentative value of a PC-relative relocation to a
   5942 	     local symbol into the instruction.  The value will be ignored
   5943 	     by the linker, and it makes the object file disassembly
   5944 	     readable when all branch targets are encoded in relocations.  */
   5945 
   5946 	  gas_assert (fixP->fx_addsy);
   5947 	  if (S_GET_SEGMENT (fixP->fx_addsy) == seg
   5948 	      && !S_FORCE_RELOC (fixP->fx_addsy, 1))
   5949 	    {
   5950 	      val = (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset
   5951 		     - md_pcrel_from (fixP));
   5952 	      (void) xg_apply_fix_value (fixP, val);
   5953 	    }
   5954 	}
   5955       else if (! fixP->fx_addsy)
   5956 	{
   5957 	  val = *valP;
   5958 	  if (xg_apply_fix_value (fixP, val))
   5959 	    fixP->fx_done = 1;
   5960 	}
   5961       break;
   5962 
   5963     case BFD_RELOC_XTENSA_ASM_EXPAND:
   5964     case BFD_RELOC_XTENSA_TLS_FUNC:
   5965     case BFD_RELOC_XTENSA_TLS_ARG:
   5966     case BFD_RELOC_XTENSA_TLS_CALL:
   5967     case BFD_RELOC_XTENSA_SLOT0_ALT:
   5968     case BFD_RELOC_XTENSA_SLOT1_ALT:
   5969     case BFD_RELOC_XTENSA_SLOT2_ALT:
   5970     case BFD_RELOC_XTENSA_SLOT3_ALT:
   5971     case BFD_RELOC_XTENSA_SLOT4_ALT:
   5972     case BFD_RELOC_XTENSA_SLOT5_ALT:
   5973     case BFD_RELOC_XTENSA_SLOT6_ALT:
   5974     case BFD_RELOC_XTENSA_SLOT7_ALT:
   5975     case BFD_RELOC_XTENSA_SLOT8_ALT:
   5976     case BFD_RELOC_XTENSA_SLOT9_ALT:
   5977     case BFD_RELOC_XTENSA_SLOT10_ALT:
   5978     case BFD_RELOC_XTENSA_SLOT11_ALT:
   5979     case BFD_RELOC_XTENSA_SLOT12_ALT:
   5980     case BFD_RELOC_XTENSA_SLOT13_ALT:
   5981     case BFD_RELOC_XTENSA_SLOT14_ALT:
   5982       /* These all need to be resolved at link-time.  Do nothing now.  */
   5983       break;
   5984 
   5985     case BFD_RELOC_VTABLE_INHERIT:
   5986     case BFD_RELOC_VTABLE_ENTRY:
   5987       fixP->fx_done = 0;
   5988       break;
   5989 
   5990     default:
   5991       as_bad (_("unhandled local relocation fix %s"),
   5992 	      bfd_get_reloc_code_name (fixP->fx_r_type));
   5993     }
   5994 }
   5995 
   5996 
   5997 char *
   5998 md_atof (int type, char *litP, int *sizeP)
   5999 {
   6000   return ieee_md_atof (type, litP, sizeP, target_big_endian);
   6001 }
   6002 
   6003 
   6004 int
   6005 md_estimate_size_before_relax (fragS *fragP, segT seg ATTRIBUTE_UNUSED)
   6006 {
   6007   return total_frag_text_expansion (fragP);
   6008 }
   6009 
   6010 
   6011 /* Translate internal representation of relocation info to BFD target
   6012    format.  */
   6013 
   6014 arelent *
   6015 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
   6016 {
   6017   arelent *reloc;
   6018 
   6019   reloc = (arelent *) xmalloc (sizeof (arelent));
   6020   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
   6021   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
   6022   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
   6023 
   6024   /* Make sure none of our internal relocations make it this far.
   6025      They'd better have been fully resolved by this point.  */
   6026   gas_assert ((int) fixp->fx_r_type > 0);
   6027 
   6028   reloc->addend = fixp->fx_offset;
   6029 
   6030   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
   6031   if (reloc->howto == NULL)
   6032     {
   6033       as_bad_where (fixp->fx_file, fixp->fx_line,
   6034 		    _("cannot represent `%s' relocation in object file"),
   6035 		    bfd_get_reloc_code_name (fixp->fx_r_type));
   6036       free (reloc->sym_ptr_ptr);
   6037       free (reloc);
   6038       return NULL;
   6039     }
   6040 
   6041   if (!fixp->fx_pcrel != !reloc->howto->pc_relative)
   6042     as_fatal (_("internal error; cannot generate `%s' relocation"),
   6043 	      bfd_get_reloc_code_name (fixp->fx_r_type));
   6044 
   6045   return reloc;
   6046 }
   6047 
   6048 
   6049 /* Checks for resource conflicts between instructions.  */
   6051 
   6052 /* The func unit stuff could be implemented as bit-vectors rather
   6053    than the iterative approach here.  If it ends up being too
   6054    slow, we will switch it.  */
   6055 
   6056 resource_table *
   6057 new_resource_table (void *data,
   6058 		    int cycles,
   6059 		    int nu,
   6060 		    unit_num_copies_func uncf,
   6061 		    opcode_num_units_func onuf,
   6062 		    opcode_funcUnit_use_unit_func ouuf,
   6063 		    opcode_funcUnit_use_stage_func ousf)
   6064 {
   6065   int i;
   6066   resource_table *rt = (resource_table *) xmalloc (sizeof (resource_table));
   6067   rt->data = data;
   6068   rt->cycles = cycles;
   6069   rt->allocated_cycles = cycles;
   6070   rt->num_units = nu;
   6071   rt->unit_num_copies = uncf;
   6072   rt->opcode_num_units = onuf;
   6073   rt->opcode_unit_use = ouuf;
   6074   rt->opcode_unit_stage = ousf;
   6075 
   6076   rt->units = (unsigned char **) xcalloc (cycles, sizeof (unsigned char *));
   6077   for (i = 0; i < cycles; i++)
   6078     rt->units[i] = (unsigned char *) xcalloc (nu, sizeof (unsigned char));
   6079 
   6080   return rt;
   6081 }
   6082 
   6083 
   6084 void
   6085 clear_resource_table (resource_table *rt)
   6086 {
   6087   int i, j;
   6088   for (i = 0; i < rt->allocated_cycles; i++)
   6089     for (j = 0; j < rt->num_units; j++)
   6090       rt->units[i][j] = 0;
   6091 }
   6092 
   6093 
   6094 /* We never shrink it, just fake it into thinking so.  */
   6095 
   6096 void
   6097 resize_resource_table (resource_table *rt, int cycles)
   6098 {
   6099   int i, old_cycles;
   6100 
   6101   rt->cycles = cycles;
   6102   if (cycles <= rt->allocated_cycles)
   6103     return;
   6104 
   6105   old_cycles = rt->allocated_cycles;
   6106   rt->allocated_cycles = cycles;
   6107 
   6108   rt->units = xrealloc (rt->units,
   6109 			rt->allocated_cycles * sizeof (unsigned char *));
   6110   for (i = 0; i < old_cycles; i++)
   6111     rt->units[i] = xrealloc (rt->units[i],
   6112 			     rt->num_units * sizeof (unsigned char));
   6113   for (i = old_cycles; i < cycles; i++)
   6114     rt->units[i] = xcalloc (rt->num_units, sizeof (unsigned char));
   6115 }
   6116 
   6117 
   6118 bfd_boolean
   6119 resources_available (resource_table *rt, xtensa_opcode opcode, int cycle)
   6120 {
   6121   int i;
   6122   int uses = (rt->opcode_num_units) (rt->data, opcode);
   6123 
   6124   for (i = 0; i < uses; i++)
   6125     {
   6126       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
   6127       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
   6128       int copies_in_use = rt->units[stage + cycle][unit];
   6129       int copies = (rt->unit_num_copies) (rt->data, unit);
   6130       if (copies_in_use >= copies)
   6131 	return FALSE;
   6132     }
   6133   return TRUE;
   6134 }
   6135 
   6136 
   6137 void
   6138 reserve_resources (resource_table *rt, xtensa_opcode opcode, int cycle)
   6139 {
   6140   int i;
   6141   int uses = (rt->opcode_num_units) (rt->data, opcode);
   6142 
   6143   for (i = 0; i < uses; i++)
   6144     {
   6145       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
   6146       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
   6147       /* Note that this allows resources to be oversubscribed.  That's
   6148 	 essential to the way the optional scheduler works.
   6149 	 resources_available reports when a resource is over-subscribed,
   6150 	 so it's easy to tell.  */
   6151       rt->units[stage + cycle][unit]++;
   6152     }
   6153 }
   6154 
   6155 
   6156 void
   6157 release_resources (resource_table *rt, xtensa_opcode opcode, int cycle)
   6158 {
   6159   int i;
   6160   int uses = (rt->opcode_num_units) (rt->data, opcode);
   6161 
   6162   for (i = 0; i < uses; i++)
   6163     {
   6164       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
   6165       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
   6166       gas_assert (rt->units[stage + cycle][unit] > 0);
   6167       rt->units[stage + cycle][unit]--;
   6168     }
   6169 }
   6170 
   6171 
   6172 /* Wrapper functions make parameterized resource reservation
   6173    more convenient.  */
   6174 
   6175 int
   6176 opcode_funcUnit_use_unit (void *data, xtensa_opcode opcode, int idx)
   6177 {
   6178   xtensa_funcUnit_use *use = xtensa_opcode_funcUnit_use (data, opcode, idx);
   6179   return use->unit;
   6180 }
   6181 
   6182 
   6183 int
   6184 opcode_funcUnit_use_stage (void *data, xtensa_opcode opcode, int idx)
   6185 {
   6186   xtensa_funcUnit_use *use = xtensa_opcode_funcUnit_use (data, opcode, idx);
   6187   return use->stage;
   6188 }
   6189 
   6190 
   6191 /* Note that this function does not check issue constraints, but
   6192    solely whether the hardware is available to execute the given
   6193    instructions together.  It also doesn't check if the tinsns
   6194    write the same state, or access the same tieports.  That is
   6195    checked by check_t1_t2_reads_and_writes.  */
   6196 
   6197 static bfd_boolean
   6198 resources_conflict (vliw_insn *vinsn)
   6199 {
   6200   int i;
   6201   static resource_table *rt = NULL;
   6202 
   6203   /* This is the most common case by far.  Optimize it.  */
   6204   if (vinsn->num_slots == 1)
   6205     return FALSE;
   6206 
   6207   if (rt == NULL)
   6208     {
   6209       xtensa_isa isa = xtensa_default_isa;
   6210       rt = new_resource_table
   6211 	(isa, xtensa_num_pipe_stages,
   6212 	 xtensa_isa_num_funcUnits (isa),
   6213 	 (unit_num_copies_func) xtensa_funcUnit_num_copies,
   6214 	 (opcode_num_units_func) xtensa_opcode_num_funcUnit_uses,
   6215 	 opcode_funcUnit_use_unit,
   6216 	 opcode_funcUnit_use_stage);
   6217     }
   6218 
   6219   clear_resource_table (rt);
   6220 
   6221   for (i = 0; i < vinsn->num_slots; i++)
   6222     {
   6223       if (!resources_available (rt, vinsn->slots[i].opcode, 0))
   6224 	return TRUE;
   6225       reserve_resources (rt, vinsn->slots[i].opcode, 0);
   6226     }
   6227 
   6228   return FALSE;
   6229 }
   6230 
   6231 
   6232 /* finish_vinsn, emit_single_op and helper functions.  */
   6234 
   6235 static bfd_boolean find_vinsn_conflicts (vliw_insn *);
   6236 static xtensa_format xg_find_narrowest_format (vliw_insn *);
   6237 static void xg_assemble_vliw_tokens (vliw_insn *);
   6238 
   6239 
   6240 /* We have reached the end of a bundle; emit into the frag.  */
   6241 
   6242 static void
   6243 finish_vinsn (vliw_insn *vinsn)
   6244 {
   6245   IStack slotstack;
   6246   int i;
   6247   char *file_name;
   6248   unsigned line;
   6249 
   6250   if (find_vinsn_conflicts (vinsn))
   6251     {
   6252       xg_clear_vinsn (vinsn);
   6253       return;
   6254     }
   6255 
   6256   /* First, find a format that works.  */
   6257   if (vinsn->format == XTENSA_UNDEFINED)
   6258     vinsn->format = xg_find_narrowest_format (vinsn);
   6259 
   6260   if (xtensa_format_num_slots (xtensa_default_isa, vinsn->format) > 1
   6261       && produce_flix == FLIX_NONE)
   6262     {
   6263       as_bad (_("The option \"--no-allow-flix\" prohibits multi-slot flix."));
   6264       xg_clear_vinsn (vinsn);
   6265       return;
   6266     }
   6267 
   6268   if (vinsn->format == XTENSA_UNDEFINED)
   6269     {
   6270       as_where (&file_name, &line);
   6271       as_bad_where (file_name, line,
   6272 		    _("couldn't find a valid instruction format"));
   6273       fprintf (stderr, _("    ops were: "));
   6274       for (i = 0; i < vinsn->num_slots; i++)
   6275 	fprintf (stderr, _(" %s;"),
   6276 		 xtensa_opcode_name (xtensa_default_isa,
   6277 				     vinsn->slots[i].opcode));
   6278       fprintf (stderr, _("\n"));
   6279       xg_clear_vinsn (vinsn);
   6280       return;
   6281     }
   6282 
   6283   if (vinsn->num_slots
   6284       != xtensa_format_num_slots (xtensa_default_isa, vinsn->format))
   6285     {
   6286       as_bad (_("format '%s' allows %d slots, but there are %d opcodes"),
   6287 	      xtensa_format_name (xtensa_default_isa, vinsn->format),
   6288 	      xtensa_format_num_slots (xtensa_default_isa, vinsn->format),
   6289 	      vinsn->num_slots);
   6290       xg_clear_vinsn (vinsn);
   6291       return;
   6292     }
   6293 
   6294   if (resources_conflict (vinsn))
   6295     {
   6296       as_where (&file_name, &line);
   6297       as_bad_where (file_name, line, _("illegal resource usage in bundle"));
   6298       fprintf (stderr, "    ops were: ");
   6299       for (i = 0; i < vinsn->num_slots; i++)
   6300 	fprintf (stderr, " %s;",
   6301 		 xtensa_opcode_name (xtensa_default_isa,
   6302 				     vinsn->slots[i].opcode));
   6303       fprintf (stderr, "\n");
   6304       xg_clear_vinsn (vinsn);
   6305       return;
   6306     }
   6307 
   6308   for (i = 0; i < vinsn->num_slots; i++)
   6309     {
   6310       if (vinsn->slots[i].opcode != XTENSA_UNDEFINED)
   6311 	{
   6312 	  symbolS *lit_sym = NULL;
   6313 	  int j;
   6314 	  bfd_boolean e = FALSE;
   6315 	  bfd_boolean saved_density = density_supported;
   6316 
   6317 	  /* We don't want to narrow ops inside multi-slot bundles.  */
   6318 	  if (vinsn->num_slots > 1)
   6319 	    density_supported = FALSE;
   6320 
   6321 	  istack_init (&slotstack);
   6322 	  if (vinsn->slots[i].opcode == xtensa_nop_opcode)
   6323 	    {
   6324 	      vinsn->slots[i].opcode =
   6325 		xtensa_format_slot_nop_opcode (xtensa_default_isa,
   6326 					       vinsn->format, i);
   6327 	      vinsn->slots[i].ntok = 0;
   6328 	    }
   6329 
   6330 	  if (xg_expand_assembly_insn (&slotstack, &vinsn->slots[i]))
   6331 	    {
   6332 	      e = TRUE;
   6333 	      continue;
   6334 	    }
   6335 
   6336 	  density_supported = saved_density;
   6337 
   6338 	  if (e)
   6339 	    {
   6340 	      xg_clear_vinsn (vinsn);
   6341 	      return;
   6342 	    }
   6343 
   6344 	  for (j = 0; j < slotstack.ninsn; j++)
   6345 	    {
   6346 	      TInsn *insn = &slotstack.insn[j];
   6347 	      if (insn->insn_type == ITYPE_LITERAL)
   6348 		{
   6349 		  gas_assert (lit_sym == NULL);
   6350 		  lit_sym = xg_assemble_literal (insn);
   6351 		}
   6352 	      else
   6353 		{
   6354 		  gas_assert (insn->insn_type == ITYPE_INSN);
   6355 		  if (lit_sym)
   6356 		    xg_resolve_literals (insn, lit_sym);
   6357 		  if (j != slotstack.ninsn - 1)
   6358 		    emit_single_op (insn);
   6359 		}
   6360 	    }
   6361 
   6362 	  if (vinsn->num_slots > 1)
   6363 	    {
   6364 	      if (opcode_fits_format_slot
   6365 		  (slotstack.insn[slotstack.ninsn - 1].opcode,
   6366 		   vinsn->format, i))
   6367 		{
   6368 		  vinsn->slots[i] = slotstack.insn[slotstack.ninsn - 1];
   6369 		}
   6370 	      else
   6371 		{
   6372 		  emit_single_op (&slotstack.insn[slotstack.ninsn - 1]);
   6373 		  if (vinsn->format == XTENSA_UNDEFINED)
   6374 		    vinsn->slots[i].opcode = xtensa_nop_opcode;
   6375 		  else
   6376 		    vinsn->slots[i].opcode
   6377 		      = xtensa_format_slot_nop_opcode (xtensa_default_isa,
   6378 						       vinsn->format, i);
   6379 
   6380 		  vinsn->slots[i].ntok = 0;
   6381 		}
   6382 	    }
   6383 	  else
   6384 	    {
   6385 	      vinsn->slots[0] = slotstack.insn[slotstack.ninsn - 1];
   6386 	      vinsn->format = XTENSA_UNDEFINED;
   6387 	    }
   6388 	}
   6389     }
   6390 
   6391   /* Now check resource conflicts on the modified bundle.  */
   6392   if (resources_conflict (vinsn))
   6393     {
   6394       as_where (&file_name, &line);
   6395       as_bad_where (file_name, line, _("illegal resource usage in bundle"));
   6396       fprintf (stderr, "    ops were: ");
   6397       for (i = 0; i < vinsn->num_slots; i++)
   6398 	fprintf (stderr, " %s;",
   6399 		 xtensa_opcode_name (xtensa_default_isa,
   6400 				     vinsn->slots[i].opcode));
   6401       fprintf (stderr, "\n");
   6402       xg_clear_vinsn (vinsn);
   6403       return;
   6404     }
   6405 
   6406   /* First, find a format that works.  */
   6407   if (vinsn->format == XTENSA_UNDEFINED)
   6408       vinsn->format = xg_find_narrowest_format (vinsn);
   6409 
   6410   xg_assemble_vliw_tokens (vinsn);
   6411 
   6412   xg_clear_vinsn (vinsn);
   6413 
   6414   xtensa_check_frag_count ();
   6415 }
   6416 
   6417 
   6418 /* Given an vliw instruction, what conflicts are there in register
   6419    usage and in writes to states and queues?
   6420 
   6421    This function does two things:
   6422    1. Reports an error when a vinsn contains illegal combinations
   6423       of writes to registers states or queues.
   6424    2. Marks individual tinsns as not relaxable if the combination
   6425       contains antidependencies.
   6426 
   6427    Job 2 handles things like swap semantics in instructions that need
   6428    to be relaxed.  For example,
   6429 
   6430 	addi a0, a1, 100000
   6431 
   6432    normally would be relaxed to
   6433 
   6434 	l32r a0, some_label
   6435 	add a0, a1, a0
   6436 
   6437    _but_, if the above instruction is bundled with an a0 reader, e.g.,
   6438 
   6439 	{ addi a0, a1, 10000 ; add a2, a0, a4 ; }
   6440 
   6441    then we can't relax it into
   6442 
   6443 	l32r a0, some_label
   6444 	{ add a0, a1, a0 ; add a2, a0, a4 ; }
   6445 
   6446    because the value of a0 is trashed before the second add can read it.  */
   6447 
   6448 static char check_t1_t2_reads_and_writes (TInsn *, TInsn *);
   6449 
   6450 static bfd_boolean
   6451 find_vinsn_conflicts (vliw_insn *vinsn)
   6452 {
   6453   int i, j;
   6454   int branches = 0;
   6455   xtensa_isa isa = xtensa_default_isa;
   6456 
   6457   gas_assert (!past_xtensa_end);
   6458 
   6459   for (i = 0 ; i < vinsn->num_slots; i++)
   6460     {
   6461       TInsn *op1 = &vinsn->slots[i];
   6462       if (op1->is_specific_opcode)
   6463 	op1->keep_wide = TRUE;
   6464       else
   6465 	op1->keep_wide = FALSE;
   6466     }
   6467 
   6468   for (i = 0 ; i < vinsn->num_slots; i++)
   6469     {
   6470       TInsn *op1 = &vinsn->slots[i];
   6471 
   6472       if (xtensa_opcode_is_branch (isa, op1->opcode) == 1)
   6473 	branches++;
   6474 
   6475       for (j = 0; j < vinsn->num_slots; j++)
   6476 	{
   6477 	  if (i != j)
   6478 	    {
   6479 	      TInsn *op2 = &vinsn->slots[j];
   6480 	      char conflict_type = check_t1_t2_reads_and_writes (op1, op2);
   6481 	      switch (conflict_type)
   6482 		{
   6483 		case 'c':
   6484 		  as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same register"),
   6485 			  xtensa_opcode_name (isa, op1->opcode), i,
   6486 			  xtensa_opcode_name (isa, op2->opcode), j);
   6487 		  return TRUE;
   6488 		case 'd':
   6489 		  as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same state"),
   6490 			  xtensa_opcode_name (isa, op1->opcode), i,
   6491 			  xtensa_opcode_name (isa, op2->opcode), j);
   6492 		  return TRUE;
   6493 		case 'e':
   6494 		  as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same port"),
   6495 			  xtensa_opcode_name (isa, op1->opcode), i,
   6496 			  xtensa_opcode_name (isa, op2->opcode), j);
   6497 		  return TRUE;
   6498 		case 'f':
   6499 		  as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) both have volatile port accesses"),
   6500 			  xtensa_opcode_name (isa, op1->opcode), i,
   6501 			  xtensa_opcode_name (isa, op2->opcode), j);
   6502 		  return TRUE;
   6503 		default:
   6504 		  /* Everything is OK.  */
   6505 		  break;
   6506 		}
   6507 	      op2->is_specific_opcode = (op2->is_specific_opcode
   6508 					 || conflict_type == 'a');
   6509 	    }
   6510 	}
   6511     }
   6512 
   6513   if (branches > 1)
   6514     {
   6515       as_bad (_("multiple branches or jumps in the same bundle"));
   6516       return TRUE;
   6517     }
   6518 
   6519   return FALSE;
   6520 }
   6521 
   6522 
   6523 /* Check how the state used by t1 and t2 relate.
   6524    Cases found are:
   6525 
   6526    case A: t1 reads a register t2 writes (an antidependency within a bundle)
   6527    case B: no relationship between what is read and written (both could
   6528            read the same reg though)
   6529    case C: t1 writes a register t2 writes (a register conflict within a
   6530            bundle)
   6531    case D: t1 writes a state that t2 also writes
   6532    case E: t1 writes a tie queue that t2 also writes
   6533    case F: two volatile queue accesses
   6534 */
   6535 
   6536 static char
   6537 check_t1_t2_reads_and_writes (TInsn *t1, TInsn *t2)
   6538 {
   6539   xtensa_isa isa = xtensa_default_isa;
   6540   xtensa_regfile t1_regfile, t2_regfile;
   6541   int t1_reg, t2_reg;
   6542   int t1_base_reg, t1_last_reg;
   6543   int t2_base_reg, t2_last_reg;
   6544   char t1_inout, t2_inout;
   6545   int i, j;
   6546   char conflict = 'b';
   6547   int t1_states;
   6548   int t2_states;
   6549   int t1_interfaces;
   6550   int t2_interfaces;
   6551   bfd_boolean t1_volatile = FALSE;
   6552   bfd_boolean t2_volatile = FALSE;
   6553 
   6554   /* Check registers.  */
   6555   for (j = 0; j < t2->ntok; j++)
   6556     {
   6557       if (xtensa_operand_is_register (isa, t2->opcode, j) != 1)
   6558 	continue;
   6559 
   6560       t2_regfile = xtensa_operand_regfile (isa, t2->opcode, j);
   6561       t2_base_reg = t2->tok[j].X_add_number;
   6562       t2_last_reg = t2_base_reg + xtensa_operand_num_regs (isa, t2->opcode, j);
   6563 
   6564       for (i = 0; i < t1->ntok; i++)
   6565 	{
   6566 	  if (xtensa_operand_is_register (isa, t1->opcode, i) != 1)
   6567 	    continue;
   6568 
   6569 	  t1_regfile = xtensa_operand_regfile (isa, t1->opcode, i);
   6570 
   6571 	  if (t1_regfile != t2_regfile)
   6572 	    continue;
   6573 
   6574 	  t1_inout = xtensa_operand_inout (isa, t1->opcode, i);
   6575 	  t2_inout = xtensa_operand_inout (isa, t2->opcode, j);
   6576 
   6577 	  if (xtensa_operand_is_known_reg (isa, t1->opcode, i) == 0
   6578 	      || xtensa_operand_is_known_reg (isa, t2->opcode, j) == 0)
   6579 	    {
   6580 	      if (t1_inout == 'm' || t1_inout == 'o'
   6581 		  || t2_inout == 'm' || t2_inout == 'o')
   6582 		{
   6583 		  conflict = 'a';
   6584 		  continue;
   6585 		}
   6586 	    }
   6587 
   6588 	  t1_base_reg = t1->tok[i].X_add_number;
   6589 	  t1_last_reg = (t1_base_reg
   6590 			 + xtensa_operand_num_regs (isa, t1->opcode, i));
   6591 
   6592 	  for (t1_reg = t1_base_reg; t1_reg < t1_last_reg; t1_reg++)
   6593 	    {
   6594 	      for (t2_reg = t2_base_reg; t2_reg < t2_last_reg; t2_reg++)
   6595 		{
   6596 		  if (t1_reg != t2_reg)
   6597 		    continue;
   6598 
   6599 		  if (t2_inout == 'i' && (t1_inout == 'm' || t1_inout == 'o'))
   6600 		    {
   6601 		      conflict = 'a';
   6602 		      continue;
   6603 		    }
   6604 
   6605 		  if (t1_inout == 'i' && (t2_inout == 'm' || t2_inout == 'o'))
   6606 		    {
   6607 		      conflict = 'a';
   6608 		      continue;
   6609 		    }
   6610 
   6611 		  if (t1_inout != 'i' && t2_inout != 'i')
   6612 		    return 'c';
   6613 		}
   6614 	    }
   6615 	}
   6616     }
   6617 
   6618   /* Check states.  */
   6619   t1_states = xtensa_opcode_num_stateOperands (isa, t1->opcode);
   6620   t2_states = xtensa_opcode_num_stateOperands (isa, t2->opcode);
   6621   for (j = 0; j < t2_states; j++)
   6622     {
   6623       xtensa_state t2_so = xtensa_stateOperand_state (isa, t2->opcode, j);
   6624       t2_inout = xtensa_stateOperand_inout (isa, t2->opcode, j);
   6625       for (i = 0; i < t1_states; i++)
   6626 	{
   6627 	  xtensa_state t1_so = xtensa_stateOperand_state (isa, t1->opcode, i);
   6628 	  t1_inout = xtensa_stateOperand_inout (isa, t1->opcode, i);
   6629 	  if (t1_so != t2_so || xtensa_state_is_shared_or (isa, t1_so) == 1)
   6630 	    continue;
   6631 
   6632 	  if (t2_inout == 'i' && (t1_inout == 'm' || t1_inout == 'o'))
   6633 	    {
   6634 	      conflict = 'a';
   6635 	      continue;
   6636 	    }
   6637 
   6638 	  if (t1_inout == 'i' && (t2_inout == 'm' || t2_inout == 'o'))
   6639 	    {
   6640 	      conflict = 'a';
   6641 	      continue;
   6642 	    }
   6643 
   6644 	  if (t1_inout != 'i' && t2_inout != 'i')
   6645 	    return 'd';
   6646 	}
   6647     }
   6648 
   6649   /* Check tieports.  */
   6650   t1_interfaces = xtensa_opcode_num_interfaceOperands (isa, t1->opcode);
   6651   t2_interfaces = xtensa_opcode_num_interfaceOperands (isa, t2->opcode);
   6652   for (j = 0; j < t2_interfaces; j++)
   6653     {
   6654       xtensa_interface t2_int
   6655 	= xtensa_interfaceOperand_interface (isa, t2->opcode, j);
   6656       int t2_class = xtensa_interface_class_id (isa, t2_int);
   6657 
   6658       t2_inout = xtensa_interface_inout (isa, t2_int);
   6659       if (xtensa_interface_has_side_effect (isa, t2_int) == 1)
   6660 	t2_volatile = TRUE;
   6661 
   6662       for (i = 0; i < t1_interfaces; i++)
   6663 	{
   6664 	  xtensa_interface t1_int
   6665 	    = xtensa_interfaceOperand_interface (isa, t1->opcode, j);
   6666 	  int t1_class = xtensa_interface_class_id (isa, t1_int);
   6667 
   6668 	  t1_inout = xtensa_interface_inout (isa, t1_int);
   6669 	  if (xtensa_interface_has_side_effect (isa, t1_int) == 1)
   6670 	    t1_volatile = TRUE;
   6671 
   6672 	  if (t1_volatile && t2_volatile && (t1_class == t2_class))
   6673 	    return 'f';
   6674 
   6675 	  if (t1_int != t2_int)
   6676 	    continue;
   6677 
   6678 	  if (t2_inout == 'i' && t1_inout == 'o')
   6679 	    {
   6680 	      conflict = 'a';
   6681 	      continue;
   6682 	    }
   6683 
   6684 	  if (t1_inout == 'i' && t2_inout == 'o')
   6685 	    {
   6686 	      conflict = 'a';
   6687 	      continue;
   6688 	    }
   6689 
   6690 	  if (t1_inout != 'i' && t2_inout != 'i')
   6691 	    return 'e';
   6692 	}
   6693     }
   6694 
   6695   return conflict;
   6696 }
   6697 
   6698 
   6699 static xtensa_format
   6700 xg_find_narrowest_format (vliw_insn *vinsn)
   6701 {
   6702   /* Right now we assume that the ops within the vinsn are properly
   6703      ordered for the slots that the programmer wanted them in.  In
   6704      other words, we don't rearrange the ops in hopes of finding a
   6705      better format.  The scheduler handles that.  */
   6706 
   6707   xtensa_isa isa = xtensa_default_isa;
   6708   xtensa_format format;
   6709   xtensa_opcode nop_opcode = xtensa_nop_opcode;
   6710 
   6711   if (vinsn->num_slots == 1)
   6712     return xg_get_single_format (vinsn->slots[0].opcode);
   6713 
   6714   for (format = 0; format < xtensa_isa_num_formats (isa); format++)
   6715     {
   6716       vliw_insn v_copy;
   6717       xg_copy_vinsn (&v_copy, vinsn);
   6718       if (xtensa_format_num_slots (isa, format) == v_copy.num_slots)
   6719 	{
   6720 	  int slot;
   6721 	  int fit = 0;
   6722 	  for (slot = 0; slot < v_copy.num_slots; slot++)
   6723 	    {
   6724 	      if (v_copy.slots[slot].opcode == nop_opcode)
   6725 		{
   6726 		  v_copy.slots[slot].opcode =
   6727 		    xtensa_format_slot_nop_opcode (isa, format, slot);
   6728 		  v_copy.slots[slot].ntok = 0;
   6729 		}
   6730 
   6731 	      if (opcode_fits_format_slot (v_copy.slots[slot].opcode,
   6732 					   format, slot))
   6733 		fit++;
   6734 	      else if (v_copy.num_slots > 1)
   6735 		{
   6736 		  TInsn widened;
   6737 		  /* Try the widened version.  */
   6738 		  if (!v_copy.slots[slot].keep_wide
   6739 		      && !v_copy.slots[slot].is_specific_opcode
   6740 		      && xg_is_single_relaxable_insn (&v_copy.slots[slot],
   6741 						      &widened, TRUE)
   6742 		      && opcode_fits_format_slot (widened.opcode,
   6743 						  format, slot))
   6744 		    {
   6745 		      v_copy.slots[slot] = widened;
   6746 		      fit++;
   6747 		    }
   6748 		}
   6749 	    }
   6750 	  if (fit == v_copy.num_slots)
   6751 	    {
   6752 	      xg_copy_vinsn (vinsn, &v_copy);
   6753 	      xtensa_format_encode (isa, format, vinsn->insnbuf);
   6754 	      vinsn->format = format;
   6755 	      break;
   6756 	    }
   6757 	}
   6758     }
   6759 
   6760   if (format == xtensa_isa_num_formats (isa))
   6761     return XTENSA_UNDEFINED;
   6762 
   6763   return format;
   6764 }
   6765 
   6766 
   6767 /* Return the additional space needed in a frag
   6768    for possible relaxations of any ops in a VLIW insn.
   6769    Also fill out the relaxations that might be required of
   6770    each tinsn in the vinsn.  */
   6771 
   6772 static int
   6773 relaxation_requirements (vliw_insn *vinsn, bfd_boolean *pfinish_frag)
   6774 {
   6775   bfd_boolean finish_frag = FALSE;
   6776   int extra_space = 0;
   6777   int slot;
   6778 
   6779   for (slot = 0; slot < vinsn->num_slots; slot++)
   6780     {
   6781       TInsn *tinsn = &vinsn->slots[slot];
   6782       if (!tinsn_has_symbolic_operands (tinsn))
   6783 	{
   6784 	  /* A narrow instruction could be widened later to help
   6785 	     alignment issues.  */
   6786 	  if (xg_is_single_relaxable_insn (tinsn, 0, TRUE)
   6787 	      && !tinsn->is_specific_opcode
   6788 	      && vinsn->num_slots == 1)
   6789 	    {
   6790 	      /* Difference in bytes between narrow and wide insns...  */
   6791 	      extra_space += 1;
   6792 	      tinsn->subtype = RELAX_NARROW;
   6793 	    }
   6794 	}
   6795       else
   6796 	{
   6797 	  if (workaround_b_j_loop_end
   6798 	      && tinsn->opcode == xtensa_jx_opcode
   6799 	      && use_transform ())
   6800 	    {
   6801 	      /* Add 2 of these.  */
   6802 	      extra_space += 3; /* for the nop size */
   6803 	      tinsn->subtype = RELAX_ADD_NOP_IF_PRE_LOOP_END;
   6804 	    }
   6805 
   6806 	  /* Need to assemble it with space for the relocation.  */
   6807 	  if (xg_is_relaxable_insn (tinsn, 0)
   6808 	      && !tinsn->is_specific_opcode)
   6809 	    {
   6810 	      int max_size = xg_get_max_insn_widen_size (tinsn->opcode);
   6811 	      int max_literal_size =
   6812 		xg_get_max_insn_widen_literal_size (tinsn->opcode);
   6813 
   6814 	      tinsn->literal_space = max_literal_size;
   6815 
   6816 	      tinsn->subtype = RELAX_IMMED;
   6817 	      extra_space += max_size;
   6818 	    }
   6819 	  else
   6820 	    {
   6821 	      /* A fix record will be added for this instruction prior
   6822 		 to relaxation, so make it end the frag.  */
   6823 	      finish_frag = TRUE;
   6824 	    }
   6825 	}
   6826     }
   6827   *pfinish_frag = finish_frag;
   6828   return extra_space;
   6829 }
   6830 
   6831 
   6832 static void
   6833 bundle_tinsn (TInsn *tinsn, vliw_insn *vinsn)
   6834 {
   6835   xtensa_isa isa = xtensa_default_isa;
   6836   int slot, chosen_slot;
   6837 
   6838   vinsn->format = xg_get_single_format (tinsn->opcode);
   6839   gas_assert (vinsn->format != XTENSA_UNDEFINED);
   6840   vinsn->num_slots = xtensa_format_num_slots (isa, vinsn->format);
   6841 
   6842   chosen_slot = xg_get_single_slot (tinsn->opcode);
   6843   for (slot = 0; slot < vinsn->num_slots; slot++)
   6844     {
   6845       if (slot == chosen_slot)
   6846 	vinsn->slots[slot] = *tinsn;
   6847       else
   6848 	{
   6849 	  vinsn->slots[slot].opcode =
   6850 	    xtensa_format_slot_nop_opcode (isa, vinsn->format, slot);
   6851 	  vinsn->slots[slot].ntok = 0;
   6852 	  vinsn->slots[slot].insn_type = ITYPE_INSN;
   6853 	}
   6854     }
   6855 }
   6856 
   6857 
   6858 static bfd_boolean
   6859 emit_single_op (TInsn *orig_insn)
   6860 {
   6861   int i;
   6862   IStack istack;		/* put instructions into here */
   6863   symbolS *lit_sym = NULL;
   6864   symbolS *label_sym = NULL;
   6865 
   6866   istack_init (&istack);
   6867 
   6868   /* Special-case for "movi aX, foo" which is guaranteed to need relaxing.
   6869      Because the scheduling and bundling characteristics of movi and
   6870      l32r or const16 are so different, we can do much better if we relax
   6871      it prior to scheduling and bundling, rather than after.  */
   6872   if ((orig_insn->opcode == xtensa_movi_opcode
   6873        || orig_insn->opcode == xtensa_movi_n_opcode)
   6874       && !cur_vinsn.inside_bundle
   6875       && (orig_insn->tok[1].X_op == O_symbol
   6876 	  || orig_insn->tok[1].X_op == O_pltrel
   6877 	  || orig_insn->tok[1].X_op == O_tlsfunc
   6878 	  || orig_insn->tok[1].X_op == O_tlsarg
   6879 	  || orig_insn->tok[1].X_op == O_tpoff
   6880 	  || orig_insn->tok[1].X_op == O_dtpoff)
   6881       && !orig_insn->is_specific_opcode && use_transform ())
   6882     xg_assembly_relax (&istack, orig_insn, now_seg, frag_now, 0, 1, 0);
   6883   else
   6884     if (xg_expand_assembly_insn (&istack, orig_insn))
   6885       return TRUE;
   6886 
   6887   for (i = 0; i < istack.ninsn; i++)
   6888     {
   6889       TInsn *insn = &istack.insn[i];
   6890       switch (insn->insn_type)
   6891 	{
   6892 	case ITYPE_LITERAL:
   6893 	  gas_assert (lit_sym == NULL);
   6894 	  lit_sym = xg_assemble_literal (insn);
   6895 	  break;
   6896 	case ITYPE_LABEL:
   6897 	  {
   6898 	    static int relaxed_sym_idx = 0;
   6899 	    char *label = xmalloc (strlen (FAKE_LABEL_NAME) + 12);
   6900 	    sprintf (label, "%s_rl_%x", FAKE_LABEL_NAME, relaxed_sym_idx++);
   6901 	    colon (label);
   6902 	    gas_assert (label_sym == NULL);
   6903 	    label_sym = symbol_find_or_make (label);
   6904 	    gas_assert (label_sym);
   6905 	    free (label);
   6906 	  }
   6907 	  break;
   6908 	case ITYPE_INSN:
   6909 	  {
   6910 	    vliw_insn v;
   6911 	    if (lit_sym)
   6912 	      xg_resolve_literals (insn, lit_sym);
   6913 	    if (label_sym)
   6914 	      xg_resolve_labels (insn, label_sym);
   6915 	    xg_init_vinsn (&v);
   6916 	    bundle_tinsn (insn, &v);
   6917 	    finish_vinsn (&v);
   6918 	    xg_free_vinsn (&v);
   6919 	  }
   6920 	  break;
   6921 	default:
   6922 	  gas_assert (0);
   6923 	  break;
   6924 	}
   6925     }
   6926   return FALSE;
   6927 }
   6928 
   6929 
   6930 static int
   6931 total_frag_text_expansion (fragS *fragP)
   6932 {
   6933   int slot;
   6934   int total_expansion = 0;
   6935 
   6936   for (slot = 0; slot < config_max_slots; slot++)
   6937     total_expansion += fragP->tc_frag_data.text_expansion[slot];
   6938 
   6939   return total_expansion;
   6940 }
   6941 
   6942 
   6943 /* Emit a vliw instruction to the current fragment.  */
   6944 
   6945 static void
   6946 xg_assemble_vliw_tokens (vliw_insn *vinsn)
   6947 {
   6948   bfd_boolean finish_frag;
   6949   bfd_boolean is_jump = FALSE;
   6950   bfd_boolean is_branch = FALSE;
   6951   xtensa_isa isa = xtensa_default_isa;
   6952   int insn_size;
   6953   int extra_space;
   6954   char *f = NULL;
   6955   int slot;
   6956   struct dwarf2_line_info debug_line;
   6957   bfd_boolean loc_directive_seen = FALSE;
   6958   TInsn *tinsn;
   6959 
   6960   memset (&debug_line, 0, sizeof (struct dwarf2_line_info));
   6961 
   6962   if (generating_literals)
   6963     {
   6964       static int reported = 0;
   6965       if (reported < 4)
   6966 	as_bad_where (frag_now->fr_file, frag_now->fr_line,
   6967 		      _("cannot assemble into a literal fragment"));
   6968       if (reported == 3)
   6969 	as_bad (_("..."));
   6970       reported++;
   6971       return;
   6972     }
   6973 
   6974   if (frag_now_fix () != 0
   6975       && (! frag_now->tc_frag_data.is_insn
   6976  	  || (vinsn_has_specific_opcodes (vinsn) && use_transform ())
   6977  	  || (!use_transform ()) != frag_now->tc_frag_data.is_no_transform
   6978  	  || (directive_state[directive_longcalls]
   6979 	      != frag_now->tc_frag_data.use_longcalls)
   6980  	  || (directive_state[directive_absolute_literals]
   6981 	      != frag_now->tc_frag_data.use_absolute_literals)))
   6982     {
   6983       frag_wane (frag_now);
   6984       frag_new (0);
   6985       xtensa_set_frag_assembly_state (frag_now);
   6986     }
   6987 
   6988   if (workaround_a0_b_retw
   6989       && vinsn->num_slots == 1
   6990       && (get_last_insn_flags (now_seg, now_subseg) & FLAG_IS_A0_WRITER) != 0
   6991       && xtensa_opcode_is_branch (isa, vinsn->slots[0].opcode) == 1
   6992       && use_transform ())
   6993     {
   6994       has_a0_b_retw = TRUE;
   6995 
   6996       /* Mark this fragment with the special RELAX_ADD_NOP_IF_A0_B_RETW.
   6997 	 After the first assembly pass we will check all of them and
   6998 	 add a nop if needed.  */
   6999       frag_now->tc_frag_data.is_insn = TRUE;
   7000       frag_var (rs_machine_dependent, 4, 4,
   7001 		RELAX_ADD_NOP_IF_A0_B_RETW,
   7002 		frag_now->fr_symbol,
   7003 		frag_now->fr_offset,
   7004 		NULL);
   7005       xtensa_set_frag_assembly_state (frag_now);
   7006       frag_now->tc_frag_data.is_insn = TRUE;
   7007       frag_var (rs_machine_dependent, 4, 4,
   7008 		RELAX_ADD_NOP_IF_A0_B_RETW,
   7009 		frag_now->fr_symbol,
   7010 		frag_now->fr_offset,
   7011 		NULL);
   7012       xtensa_set_frag_assembly_state (frag_now);
   7013     }
   7014 
   7015   for (slot = 0; slot < vinsn->num_slots; slot++)
   7016     {
   7017       tinsn = &vinsn->slots[slot];
   7018 
   7019       /* See if the instruction implies an aligned section.  */
   7020       if (xtensa_opcode_is_loop (isa, tinsn->opcode) == 1)
   7021 	record_alignment (now_seg, 2);
   7022 
   7023       /* Determine the best line number for debug info.  */
   7024       if ((tinsn->loc_directive_seen || !loc_directive_seen)
   7025 	  && (tinsn->debug_line.filenum != debug_line.filenum
   7026 	      || tinsn->debug_line.line < debug_line.line
   7027 	      || tinsn->debug_line.column < debug_line.column))
   7028 	debug_line = tinsn->debug_line;
   7029       if (tinsn->loc_directive_seen)
   7030 	loc_directive_seen = TRUE;
   7031     }
   7032 
   7033   /* Special cases for instructions that force an alignment... */
   7034   /* None of these opcodes are bundle-able.  */
   7035   if (xtensa_opcode_is_loop (isa, vinsn->slots[0].opcode) == 1)
   7036     {
   7037       int max_fill;
   7038 
   7039       /* Remember the symbol that marks the end of the loop in the frag
   7040 	 that marks the start of the loop.  This way we can easily find
   7041 	 the end of the loop at the beginning, without adding special code
   7042 	 to mark the loop instructions themselves.  */
   7043       symbolS *target_sym = NULL;
   7044       if (vinsn->slots[0].tok[1].X_op == O_symbol)
   7045 	target_sym = vinsn->slots[0].tok[1].X_add_symbol;
   7046 
   7047       xtensa_set_frag_assembly_state (frag_now);
   7048       frag_now->tc_frag_data.is_insn = TRUE;
   7049 
   7050       max_fill = get_text_align_max_fill_size
   7051 	(get_text_align_power (xtensa_fetch_width),
   7052 	 TRUE, frag_now->tc_frag_data.is_no_density);
   7053 
   7054       if (use_transform ())
   7055 	frag_var (rs_machine_dependent, max_fill, max_fill,
   7056 		  RELAX_ALIGN_NEXT_OPCODE, target_sym, 0, NULL);
   7057       else
   7058 	frag_var (rs_machine_dependent, 0, 0,
   7059 		  RELAX_CHECK_ALIGN_NEXT_OPCODE, target_sym, 0, NULL);
   7060       xtensa_set_frag_assembly_state (frag_now);
   7061     }
   7062 
   7063   if (vinsn->slots[0].opcode == xtensa_entry_opcode
   7064       && !vinsn->slots[0].is_specific_opcode)
   7065     {
   7066       xtensa_mark_literal_pool_location ();
   7067       xtensa_move_labels (frag_now, 0);
   7068       frag_var (rs_align_test, 1, 1, 0, NULL, 2, NULL);
   7069     }
   7070 
   7071   if (vinsn->num_slots == 1)
   7072     {
   7073       if (workaround_a0_b_retw && use_transform ())
   7074 	set_last_insn_flags (now_seg, now_subseg, FLAG_IS_A0_WRITER,
   7075 			     is_register_writer (&vinsn->slots[0], "a", 0));
   7076 
   7077       set_last_insn_flags (now_seg, now_subseg, FLAG_IS_BAD_LOOPEND,
   7078 			   is_bad_loopend_opcode (&vinsn->slots[0]));
   7079     }
   7080   else
   7081     set_last_insn_flags (now_seg, now_subseg, FLAG_IS_BAD_LOOPEND, FALSE);
   7082 
   7083   insn_size = xtensa_format_length (isa, vinsn->format);
   7084 
   7085   extra_space = relaxation_requirements (vinsn, &finish_frag);
   7086 
   7087   /* vinsn_to_insnbuf will produce the error.  */
   7088   if (vinsn->format != XTENSA_UNDEFINED)
   7089     {
   7090       f = frag_more (insn_size + extra_space);
   7091       xtensa_set_frag_assembly_state (frag_now);
   7092       frag_now->tc_frag_data.is_insn = TRUE;
   7093     }
   7094 
   7095   vinsn_to_insnbuf (vinsn, f, frag_now, FALSE);
   7096   if (vinsn->format == XTENSA_UNDEFINED)
   7097     return;
   7098 
   7099   xtensa_insnbuf_to_chars (isa, vinsn->insnbuf, (unsigned char *) f, 0);
   7100 
   7101   if (debug_type == DEBUG_DWARF2 || loc_directive_seen)
   7102     dwarf2_gen_line_info (frag_now_fix () - (insn_size + extra_space),
   7103 			  &debug_line);
   7104 
   7105   for (slot = 0; slot < vinsn->num_slots; slot++)
   7106     {
   7107       tinsn = &vinsn->slots[slot];
   7108       frag_now->tc_frag_data.slot_subtypes[slot] = tinsn->subtype;
   7109       frag_now->tc_frag_data.slot_symbols[slot] = tinsn->symbol;
   7110       frag_now->tc_frag_data.slot_offsets[slot] = tinsn->offset;
   7111       frag_now->tc_frag_data.literal_frags[slot] = tinsn->literal_frag;
   7112       if (tinsn->literal_space != 0)
   7113 	xg_assemble_literal_space (tinsn->literal_space, slot);
   7114       frag_now->tc_frag_data.free_reg[slot] = tinsn->extra_arg;
   7115 
   7116       if (tinsn->subtype == RELAX_NARROW)
   7117 	gas_assert (vinsn->num_slots == 1);
   7118       if (xtensa_opcode_is_jump (isa, tinsn->opcode) == 1)
   7119 	is_jump = TRUE;
   7120       if (xtensa_opcode_is_branch (isa, tinsn->opcode) == 1)
   7121 	is_branch = TRUE;
   7122 
   7123       if (tinsn->subtype || tinsn->symbol || tinsn->offset
   7124 	  || tinsn->literal_frag || is_jump || is_branch)
   7125 	finish_frag = TRUE;
   7126     }
   7127 
   7128   if (vinsn_has_specific_opcodes (vinsn) && use_transform ())
   7129     frag_now->tc_frag_data.is_specific_opcode = TRUE;
   7130 
   7131   if (finish_frag)
   7132     {
   7133       frag_variant (rs_machine_dependent,
   7134 		    extra_space, extra_space, RELAX_SLOTS,
   7135 		    frag_now->fr_symbol, frag_now->fr_offset, f);
   7136       xtensa_set_frag_assembly_state (frag_now);
   7137     }
   7138 
   7139   /* Special cases for loops:
   7140      close_loop_end should be inserted AFTER short_loop.
   7141      Make sure that CLOSE loops are processed BEFORE short_loops
   7142      when converting them.  */
   7143 
   7144   /* "short_loop": Add a NOP if the loop is < 4 bytes.  */
   7145   if (xtensa_opcode_is_loop (isa, vinsn->slots[0].opcode) == 1
   7146       && !vinsn->slots[0].is_specific_opcode)
   7147     {
   7148       if (workaround_short_loop && use_transform ())
   7149 	{
   7150 	  maybe_has_short_loop = TRUE;
   7151 	  frag_now->tc_frag_data.is_insn = TRUE;
   7152 	  frag_var (rs_machine_dependent, 4, 4,
   7153 		    RELAX_ADD_NOP_IF_SHORT_LOOP,
   7154 		    frag_now->fr_symbol, frag_now->fr_offset, NULL);
   7155 	  frag_now->tc_frag_data.is_insn = TRUE;
   7156 	  frag_var (rs_machine_dependent, 4, 4,
   7157 		    RELAX_ADD_NOP_IF_SHORT_LOOP,
   7158 		    frag_now->fr_symbol, frag_now->fr_offset, NULL);
   7159 	}
   7160 
   7161       /* "close_loop_end": Add up to 12 bytes of NOPs to keep a
   7162 	 loop at least 12 bytes away from another loop's end.  */
   7163       if (workaround_close_loop_end && use_transform ())
   7164 	{
   7165 	  maybe_has_close_loop_end = TRUE;
   7166 	  frag_now->tc_frag_data.is_insn = TRUE;
   7167 	  frag_var (rs_machine_dependent, 12, 12,
   7168 		    RELAX_ADD_NOP_IF_CLOSE_LOOP_END,
   7169 		    frag_now->fr_symbol, frag_now->fr_offset, NULL);
   7170 	}
   7171     }
   7172 
   7173   if (use_transform ())
   7174     {
   7175       if (is_jump)
   7176 	{
   7177 	  gas_assert (finish_frag);
   7178 	  frag_var (rs_machine_dependent,
   7179 		    xtensa_fetch_width, xtensa_fetch_width,
   7180 		    RELAX_UNREACHABLE,
   7181 		    frag_now->fr_symbol, frag_now->fr_offset, NULL);
   7182 	  xtensa_set_frag_assembly_state (frag_now);
   7183 	  xtensa_maybe_create_trampoline_frag ();
   7184 	}
   7185       else if (is_branch && do_align_targets ())
   7186 	{
   7187 	  gas_assert (finish_frag);
   7188 	  frag_var (rs_machine_dependent,
   7189 		    xtensa_fetch_width, xtensa_fetch_width,
   7190 		    RELAX_MAYBE_UNREACHABLE,
   7191 		    frag_now->fr_symbol, frag_now->fr_offset, NULL);
   7192 	  xtensa_set_frag_assembly_state (frag_now);
   7193 	  frag_var (rs_machine_dependent,
   7194 		    0, 0,
   7195 		    RELAX_MAYBE_DESIRE_ALIGN,
   7196 		    frag_now->fr_symbol, frag_now->fr_offset, NULL);
   7197 	  xtensa_set_frag_assembly_state (frag_now);
   7198 	}
   7199     }
   7200 
   7201   /* Now, if the original opcode was a call...  */
   7202   if (do_align_targets ()
   7203       && xtensa_opcode_is_call (isa, vinsn->slots[0].opcode) == 1)
   7204     {
   7205       float freq = get_subseg_total_freq (now_seg, now_subseg);
   7206       frag_now->tc_frag_data.is_insn = TRUE;
   7207       frag_var (rs_machine_dependent, 4, (int) freq, RELAX_DESIRE_ALIGN,
   7208 		frag_now->fr_symbol, frag_now->fr_offset, NULL);
   7209       xtensa_set_frag_assembly_state (frag_now);
   7210     }
   7211 
   7212   if (vinsn_has_specific_opcodes (vinsn) && use_transform ())
   7213     {
   7214       frag_wane (frag_now);
   7215       frag_new (0);
   7216       xtensa_set_frag_assembly_state (frag_now);
   7217     }
   7218 }
   7219 
   7220 
   7221 /* xtensa_end and helper functions.  */
   7223 
   7224 static void xtensa_cleanup_align_frags (void);
   7225 static void xtensa_fix_target_frags (void);
   7226 static void xtensa_mark_narrow_branches (void);
   7227 static void xtensa_mark_zcl_first_insns (void);
   7228 static void xtensa_mark_difference_of_two_symbols (void);
   7229 static void xtensa_fix_a0_b_retw_frags (void);
   7230 static void xtensa_fix_b_j_loop_end_frags (void);
   7231 static void xtensa_fix_close_loop_end_frags (void);
   7232 static void xtensa_fix_short_loop_frags (void);
   7233 static void xtensa_sanity_check (void);
   7234 static void xtensa_add_config_info (void);
   7235 
   7236 void
   7237 xtensa_end (void)
   7238 {
   7239   directive_balance ();
   7240   xtensa_flush_pending_output ();
   7241 
   7242   past_xtensa_end = TRUE;
   7243 
   7244   xtensa_move_literals ();
   7245 
   7246   xtensa_reorder_segments ();
   7247   xtensa_cleanup_align_frags ();
   7248   xtensa_fix_target_frags ();
   7249   if (workaround_a0_b_retw && has_a0_b_retw)
   7250     xtensa_fix_a0_b_retw_frags ();
   7251   if (workaround_b_j_loop_end)
   7252     xtensa_fix_b_j_loop_end_frags ();
   7253 
   7254   /* "close_loop_end" should be processed BEFORE "short_loop".  */
   7255   if (workaround_close_loop_end && maybe_has_close_loop_end)
   7256     xtensa_fix_close_loop_end_frags ();
   7257 
   7258   if (workaround_short_loop && maybe_has_short_loop)
   7259     xtensa_fix_short_loop_frags ();
   7260   if (align_targets)
   7261     xtensa_mark_narrow_branches ();
   7262   xtensa_mark_zcl_first_insns ();
   7263 
   7264   xtensa_sanity_check ();
   7265 
   7266   xtensa_add_config_info ();
   7267 
   7268   xtensa_check_frag_count ();
   7269 }
   7270 
   7271 
   7272 struct trampoline_frag
   7273 {
   7274   struct trampoline_frag *next;
   7275   bfd_boolean needs_jump_around;
   7276   fragS *fragP;
   7277   fixS *fixP;
   7278 };
   7279 
   7280 struct trampoline_seg
   7281 {
   7282   struct trampoline_seg *next;
   7283   asection *seg;
   7284   struct trampoline_frag trampoline_list;
   7285 };
   7286 
   7287 static struct trampoline_seg trampoline_seg_list;
   7288 #define J_RANGE (128 * 1024)
   7289 
   7290 static int unreachable_count = 0;
   7291 
   7292 
   7293 static void
   7294 xtensa_maybe_create_trampoline_frag (void)
   7295 {
   7296   if (!use_trampolines)
   7297     return;
   7298 
   7299   /* We create an area for possible trampolines every 10 unreachable frags.
   7300      These are preferred over the ones not preceded by an unreachable frag,
   7301      because we don't have to jump around them. This function is called after
   7302      each RELAX_UNREACHABLE frag is created.  */
   7303 
   7304   if (++unreachable_count > 10)
   7305     {
   7306       xtensa_create_trampoline_frag (FALSE);
   7307       clear_frag_count ();
   7308       unreachable_count = 0;
   7309     }
   7310 }
   7311 
   7312 static void
   7313 xtensa_check_frag_count (void)
   7314 {
   7315   if (!use_trampolines || frag_now->tc_frag_data.is_no_transform)
   7316     return;
   7317 
   7318   /* We create an area for possible trampolines every 8000 frags or so. This
   7319      is an estimate based on the max range of a "j" insn (+/-128K) divided
   7320      by a typical frag byte count (16), minus a few for safety. This function
   7321      is called after each source line is processed.  */
   7322 
   7323   if (get_frag_count () > 8000)
   7324     {
   7325       xtensa_create_trampoline_frag (TRUE);
   7326       clear_frag_count ();
   7327       unreachable_count = 0;
   7328     }
   7329 }
   7330 
   7331 static xtensa_insnbuf trampoline_buf = NULL;
   7332 static xtensa_insnbuf trampoline_slotbuf = NULL;
   7333 
   7334 #define TRAMPOLINE_FRAG_SIZE 3000
   7335 
   7336 static void
   7337 xtensa_create_trampoline_frag (bfd_boolean needs_jump_around)
   7338 {
   7339   /* Emit a frag where we can place intermediate jump instructions,
   7340      in case we need to jump farther than 128K bytes.
   7341      Each jump instruction takes three bytes.
   7342      We allocate enough for 1000 trampolines in each frag.
   7343      If that's not enough, oh well.  */
   7344 
   7345   struct trampoline_seg *ts = trampoline_seg_list.next;
   7346   struct trampoline_frag *tf;
   7347   char *varP;
   7348   fragS *fragP;
   7349   int size = TRAMPOLINE_FRAG_SIZE;
   7350 
   7351   for ( ; ts; ts = ts->next)
   7352     {
   7353       if (ts->seg == now_seg)
   7354 	break;
   7355     }
   7356 
   7357   if (ts == NULL)
   7358     {
   7359       ts = (struct trampoline_seg *)xcalloc(sizeof (struct trampoline_seg), 1);
   7360       ts->next = trampoline_seg_list.next;
   7361       trampoline_seg_list.next = ts;
   7362       ts->seg = now_seg;
   7363     }
   7364 
   7365   frag_wane (frag_now);
   7366   frag_new (0);
   7367   xtensa_set_frag_assembly_state (frag_now);
   7368   varP = frag_var (rs_machine_dependent, size, size, RELAX_TRAMPOLINE, NULL, 0, NULL);
   7369   fragP = (fragS *)(varP - SIZEOF_STRUCT_FRAG);
   7370   if (trampoline_buf == NULL)
   7371     {
   7372       trampoline_buf = xtensa_insnbuf_alloc (xtensa_default_isa);
   7373       trampoline_slotbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
   7374     }
   7375   tf = (struct trampoline_frag *)xmalloc(sizeof (struct trampoline_frag));
   7376   tf->next = ts->trampoline_list.next;
   7377   ts->trampoline_list.next = tf;
   7378   tf->needs_jump_around = needs_jump_around;
   7379   tf->fragP = fragP;
   7380   tf->fixP = NULL;
   7381 }
   7382 
   7383 
   7384 static struct trampoline_seg *
   7385 find_trampoline_seg (asection *seg)
   7386 {
   7387   struct trampoline_seg *ts = trampoline_seg_list.next;
   7388 
   7389   for ( ; ts; ts = ts->next)
   7390     {
   7391       if (ts->seg == seg)
   7392 	return ts;
   7393     }
   7394 
   7395   return NULL;
   7396 }
   7397 
   7398 
   7399 void dump_trampolines (void);
   7400 
   7401 void
   7402 dump_trampolines (void)
   7403 {
   7404   struct trampoline_seg *ts = trampoline_seg_list.next;
   7405 
   7406   for ( ; ts; ts = ts->next)
   7407     {
   7408       asection *seg = ts->seg;
   7409 
   7410       if (seg == NULL)
   7411 	continue;
   7412       fprintf(stderr, "SECTION %s\n", seg->name);
   7413       struct trampoline_frag *tf = ts->trampoline_list.next;
   7414       for ( ; tf; tf = tf->next)
   7415 	{
   7416 	  if (tf->fragP == NULL)
   7417 	    continue;
   7418 	  fprintf(stderr, "   0x%08x: fix=%d, jump_around=%s\n",
   7419 		  (int)tf->fragP->fr_address, (int)tf->fragP->fr_fix,
   7420 		  tf->needs_jump_around ? "T" : "F");
   7421 	}
   7422     }
   7423 }
   7424 
   7425 static void
   7426 xtensa_cleanup_align_frags (void)
   7427 {
   7428   frchainS *frchP;
   7429   asection *s;
   7430 
   7431   for (s = stdoutput->sections; s; s = s->next)
   7432     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   7433       {
   7434 	fragS *fragP;
   7435 	/* Walk over all of the fragments in a subsection.  */
   7436 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   7437 	  {
   7438 	    if ((fragP->fr_type == rs_align
   7439 		 || fragP->fr_type == rs_align_code
   7440 		 || (fragP->fr_type == rs_machine_dependent
   7441 		     && (fragP->fr_subtype == RELAX_DESIRE_ALIGN
   7442 			 || fragP->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)))
   7443 		&& fragP->fr_fix == 0)
   7444 	      {
   7445 		fragS *next = fragP->fr_next;
   7446 
   7447 		while (next
   7448 		       && next->fr_fix == 0
   7449 		       && next->fr_type == rs_machine_dependent
   7450 		       && next->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)
   7451 		  {
   7452 		    frag_wane (next);
   7453 		    next = next->fr_next;
   7454 		  }
   7455 	      }
   7456 	    /* If we don't widen branch targets, then they
   7457 	       will be easier to align.  */
   7458 	    if (fragP->tc_frag_data.is_branch_target
   7459 		&& fragP->fr_opcode == fragP->fr_literal
   7460 		&& fragP->fr_type == rs_machine_dependent
   7461 		&& fragP->fr_subtype == RELAX_SLOTS
   7462 		&& fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
   7463 	      frag_wane (fragP);
   7464 	    if (fragP->fr_type == rs_machine_dependent
   7465 		&& fragP->fr_subtype == RELAX_UNREACHABLE)
   7466 	      fragP->tc_frag_data.is_unreachable = TRUE;
   7467 	  }
   7468       }
   7469 }
   7470 
   7471 
   7472 /* Re-process all of the fragments looking to convert all of the
   7473    RELAX_DESIRE_ALIGN_IF_TARGET fragments.  If there is a branch
   7474    target in the next fragment, convert this to RELAX_DESIRE_ALIGN.
   7475    Otherwise, convert to a .fill 0.  */
   7476 
   7477 static void
   7478 xtensa_fix_target_frags (void)
   7479 {
   7480   frchainS *frchP;
   7481   asection *s;
   7482 
   7483   /* When this routine is called, all of the subsections are still intact
   7484      so we walk over subsections instead of sections.  */
   7485   for (s = stdoutput->sections; s; s = s->next)
   7486     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   7487       {
   7488 	fragS *fragP;
   7489 
   7490 	/* Walk over all of the fragments in a subsection.  */
   7491 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   7492 	  {
   7493 	    if (fragP->fr_type == rs_machine_dependent
   7494 		&& fragP->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)
   7495 	      {
   7496 		if (next_frag_is_branch_target (fragP))
   7497 		  fragP->fr_subtype = RELAX_DESIRE_ALIGN;
   7498 		else
   7499 		  frag_wane (fragP);
   7500 	      }
   7501 	  }
   7502       }
   7503 }
   7504 
   7505 
   7506 static bfd_boolean is_narrow_branch_guaranteed_in_range (fragS *, TInsn *);
   7507 
   7508 static void
   7509 xtensa_mark_narrow_branches (void)
   7510 {
   7511   frchainS *frchP;
   7512   asection *s;
   7513 
   7514   for (s = stdoutput->sections; s; s = s->next)
   7515     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   7516       {
   7517 	fragS *fragP;
   7518 	/* Walk over all of the fragments in a subsection.  */
   7519 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   7520 	  {
   7521 	    if (fragP->fr_type == rs_machine_dependent
   7522 		&& fragP->fr_subtype == RELAX_SLOTS
   7523 		&& fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED)
   7524 	      {
   7525 		vliw_insn vinsn;
   7526 
   7527 		vinsn_from_chars (&vinsn, fragP->fr_opcode);
   7528 		tinsn_immed_from_frag (&vinsn.slots[0], fragP, 0);
   7529 
   7530 		if (vinsn.num_slots == 1
   7531 		    && xtensa_opcode_is_branch (xtensa_default_isa,
   7532 						vinsn.slots[0].opcode) == 1
   7533 		    && xg_get_single_size (vinsn.slots[0].opcode) == 2
   7534 		    && is_narrow_branch_guaranteed_in_range (fragP,
   7535 							     &vinsn.slots[0]))
   7536 		  {
   7537 		    fragP->fr_subtype = RELAX_SLOTS;
   7538 		    fragP->tc_frag_data.slot_subtypes[0] = RELAX_NARROW;
   7539 		    fragP->tc_frag_data.is_aligning_branch = 1;
   7540 		  }
   7541 	      }
   7542 	  }
   7543       }
   7544 }
   7545 
   7546 
   7547 /* A branch is typically widened only when its target is out of
   7548    range.  However, we would like to widen them to align a subsequent
   7549    branch target when possible.
   7550 
   7551    Because the branch relaxation code is so convoluted, the optimal solution
   7552    (combining the two cases) is difficult to get right in all circumstances.
   7553    We therefore go with an "almost as good" solution, where we only
   7554    use for alignment narrow branches that definitely will not expand to a
   7555    jump and a branch.  These functions find and mark these cases.  */
   7556 
   7557 /* The range in bytes of BNEZ.N and BEQZ.N.  The target operand is encoded
   7558    as PC + 4 + imm6, where imm6 is a 6-bit immediate ranging from 0 to 63.
   7559    We start counting beginning with the frag after the 2-byte branch, so the
   7560    maximum offset is (4 - 2) + 63 = 65.  */
   7561 #define MAX_IMMED6 65
   7562 
   7563 static offsetT unrelaxed_frag_max_size (fragS *);
   7564 
   7565 static bfd_boolean
   7566 is_narrow_branch_guaranteed_in_range (fragS *fragP, TInsn *tinsn)
   7567 {
   7568   const expressionS *exp = &tinsn->tok[1];
   7569   symbolS *symbolP = exp->X_add_symbol;
   7570   offsetT max_distance = exp->X_add_number;
   7571   fragS *target_frag;
   7572 
   7573   if (exp->X_op != O_symbol)
   7574     return FALSE;
   7575 
   7576   target_frag = symbol_get_frag (symbolP);
   7577 
   7578   max_distance += (S_GET_VALUE (symbolP) - target_frag->fr_address);
   7579   if (is_branch_jmp_to_next (tinsn, fragP))
   7580     return FALSE;
   7581 
   7582   /* The branch doesn't branch over it's own frag,
   7583      but over the subsequent ones.  */
   7584   fragP = fragP->fr_next;
   7585   while (fragP != NULL && fragP != target_frag && max_distance <= MAX_IMMED6)
   7586     {
   7587       max_distance += unrelaxed_frag_max_size (fragP);
   7588       fragP = fragP->fr_next;
   7589     }
   7590   if (max_distance <= MAX_IMMED6 && fragP == target_frag)
   7591     return TRUE;
   7592   return FALSE;
   7593 }
   7594 
   7595 
   7596 static void
   7597 xtensa_mark_zcl_first_insns (void)
   7598 {
   7599   frchainS *frchP;
   7600   asection *s;
   7601 
   7602   for (s = stdoutput->sections; s; s = s->next)
   7603     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   7604       {
   7605 	fragS *fragP;
   7606 	/* Walk over all of the fragments in a subsection.  */
   7607 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   7608 	  {
   7609 	    if (fragP->fr_type == rs_machine_dependent
   7610 		&& (fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE
   7611 		    || fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE))
   7612 	      {
   7613 		/* Find the loop frag.  */
   7614 		fragS *loop_frag = next_non_empty_frag (fragP);
   7615 		/* Find the first insn frag.  */
   7616 		fragS *targ_frag = next_non_empty_frag (loop_frag);
   7617 
   7618 	      /* Handle a corner case that comes up in hardware
   7619 		 diagnostics.  The original assembly looks like this:
   7620 
   7621 		 loop aX, LabelA
   7622 		 <empty_frag>--not found by next_non_empty_frag
   7623 		 loop aY, LabelB
   7624 
   7625 		 Depending on the start address, the assembler may or
   7626 		 may not change it to look something like this:
   7627 
   7628 		 loop aX, LabelA
   7629 		 nop--frag isn't empty anymore
   7630 		 loop aY, LabelB
   7631 
   7632 		 So set up to check the alignment of the nop if it
   7633 		 exists  */
   7634 		while (loop_frag != targ_frag)
   7635 		  {
   7636 		    if (loop_frag->fr_type == rs_machine_dependent
   7637 			&& (loop_frag->fr_subtype == RELAX_ALIGN_NEXT_OPCODE
   7638 			    || loop_frag->fr_subtype
   7639 			    == RELAX_CHECK_ALIGN_NEXT_OPCODE))
   7640 		      targ_frag = loop_frag;
   7641 		    else
   7642 		      loop_frag = loop_frag->fr_next;
   7643 		  }
   7644 
   7645 		/* Of course, sometimes (mostly for toy test cases) a
   7646 		   zero-cost loop instruction is the last in a section.  */
   7647 		if (targ_frag)
   7648 		  {
   7649 		    targ_frag->tc_frag_data.is_first_loop_insn = TRUE;
   7650 		    /* Do not widen a frag that is the first instruction of a
   7651 		       zero-cost loop.  It makes that loop harder to align.  */
   7652 		    if (targ_frag->fr_type == rs_machine_dependent
   7653 			&& targ_frag->fr_subtype == RELAX_SLOTS
   7654 			&& (targ_frag->tc_frag_data.slot_subtypes[0]
   7655 			    == RELAX_NARROW))
   7656 		      {
   7657 			if (targ_frag->tc_frag_data.is_aligning_branch)
   7658 			  targ_frag->tc_frag_data.slot_subtypes[0] = RELAX_IMMED;
   7659 			else
   7660 			  {
   7661 			    frag_wane (targ_frag);
   7662 			    targ_frag->tc_frag_data.slot_subtypes[0] = 0;
   7663 			  }
   7664 		      }
   7665 		  }
   7666 		if (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)
   7667 		  frag_wane (fragP);
   7668 	      }
   7669 	  }
   7670       }
   7671 }
   7672 
   7673 
   7674 /* When a difference-of-symbols expression is encoded as a uleb128 or
   7675    sleb128 value, the linker is unable to adjust that value to account for
   7676    link-time relaxation.  Mark all the code between such symbols so that
   7677    its size cannot be changed by linker relaxation.  */
   7678 
   7679 static void
   7680 xtensa_mark_difference_of_two_symbols (void)
   7681 {
   7682   symbolS *expr_sym;
   7683 
   7684   for (expr_sym = expr_symbols; expr_sym;
   7685        expr_sym = symbol_get_tc (expr_sym)->next_expr_symbol)
   7686     {
   7687       expressionS *exp = symbol_get_value_expression (expr_sym);
   7688 
   7689       if (exp->X_op == O_subtract)
   7690 	{
   7691 	  symbolS *left = exp->X_add_symbol;
   7692 	  symbolS *right = exp->X_op_symbol;
   7693 
   7694 	  /* Difference of two symbols not in the same section
   7695 	     are handled with relocations in the linker.  */
   7696 	  if (S_GET_SEGMENT (left) == S_GET_SEGMENT (right))
   7697 	    {
   7698 	      fragS *start;
   7699 	      fragS *end;
   7700 	      fragS *walk;
   7701 
   7702 	      if (symbol_get_frag (left)->fr_address
   7703 		  <= symbol_get_frag (right)->fr_address)
   7704 		{
   7705 		  start = symbol_get_frag (left);
   7706 		  end = symbol_get_frag (right);
   7707 		}
   7708 	      else
   7709 		{
   7710 		  start = symbol_get_frag (right);
   7711 		  end = symbol_get_frag (left);
   7712 		}
   7713 
   7714 	      if (start->tc_frag_data.no_transform_end != NULL)
   7715 		walk = start->tc_frag_data.no_transform_end;
   7716 	      else
   7717 		walk = start;
   7718 	      do
   7719 		{
   7720 		  walk->tc_frag_data.is_no_transform = 1;
   7721 		  walk = walk->fr_next;
   7722 		}
   7723 	      while (walk && walk->fr_address < end->fr_address);
   7724 
   7725 	      start->tc_frag_data.no_transform_end = walk;
   7726 	    }
   7727 	}
   7728     }
   7729 }
   7730 
   7731 
   7732 /* Re-process all of the fragments looking to convert all of the
   7733    RELAX_ADD_NOP_IF_A0_B_RETW.  If the next instruction is a
   7734    conditional branch or a retw/retw.n, convert this frag to one that
   7735    will generate a NOP.  In any case close it off with a .fill 0.  */
   7736 
   7737 static bfd_boolean next_instrs_are_b_retw (fragS *);
   7738 
   7739 static void
   7740 xtensa_fix_a0_b_retw_frags (void)
   7741 {
   7742   frchainS *frchP;
   7743   asection *s;
   7744 
   7745   /* When this routine is called, all of the subsections are still intact
   7746      so we walk over subsections instead of sections.  */
   7747   for (s = stdoutput->sections; s; s = s->next)
   7748     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   7749       {
   7750 	fragS *fragP;
   7751 
   7752 	/* Walk over all of the fragments in a subsection.  */
   7753 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   7754 	  {
   7755 	    if (fragP->fr_type == rs_machine_dependent
   7756 		&& fragP->fr_subtype == RELAX_ADD_NOP_IF_A0_B_RETW)
   7757 	      {
   7758 		if (next_instrs_are_b_retw (fragP))
   7759 		  {
   7760 		    if (fragP->tc_frag_data.is_no_transform)
   7761 		      as_bad (_("instruction sequence (write a0, branch, retw) may trigger hardware errata"));
   7762 		    else
   7763 		      relax_frag_add_nop (fragP);
   7764 		  }
   7765 		frag_wane (fragP);
   7766 	      }
   7767 	  }
   7768       }
   7769 }
   7770 
   7771 
   7772 static bfd_boolean
   7773 next_instrs_are_b_retw (fragS *fragP)
   7774 {
   7775   xtensa_opcode opcode;
   7776   xtensa_format fmt;
   7777   const fragS *next_fragP = next_non_empty_frag (fragP);
   7778   static xtensa_insnbuf insnbuf = NULL;
   7779   static xtensa_insnbuf slotbuf = NULL;
   7780   xtensa_isa isa = xtensa_default_isa;
   7781   int offset = 0;
   7782   int slot;
   7783   bfd_boolean branch_seen = FALSE;
   7784 
   7785   if (!insnbuf)
   7786     {
   7787       insnbuf = xtensa_insnbuf_alloc (isa);
   7788       slotbuf = xtensa_insnbuf_alloc (isa);
   7789     }
   7790 
   7791   if (next_fragP == NULL)
   7792     return FALSE;
   7793 
   7794   /* Check for the conditional branch.  */
   7795   xtensa_insnbuf_from_chars
   7796     (isa, insnbuf, (unsigned char *) &next_fragP->fr_literal[offset], 0);
   7797   fmt = xtensa_format_decode (isa, insnbuf);
   7798   if (fmt == XTENSA_UNDEFINED)
   7799     return FALSE;
   7800 
   7801   for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
   7802     {
   7803       xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
   7804       opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
   7805 
   7806       branch_seen = (branch_seen
   7807 		     || xtensa_opcode_is_branch (isa, opcode) == 1);
   7808     }
   7809 
   7810   if (!branch_seen)
   7811     return FALSE;
   7812 
   7813   offset += xtensa_format_length (isa, fmt);
   7814   if (offset == next_fragP->fr_fix)
   7815     {
   7816       next_fragP = next_non_empty_frag (next_fragP);
   7817       offset = 0;
   7818     }
   7819 
   7820   if (next_fragP == NULL)
   7821     return FALSE;
   7822 
   7823   /* Check for the retw/retw.n.  */
   7824   xtensa_insnbuf_from_chars
   7825     (isa, insnbuf, (unsigned char *) &next_fragP->fr_literal[offset], 0);
   7826   fmt = xtensa_format_decode (isa, insnbuf);
   7827 
   7828   /* Because RETW[.N] is not bundleable, a VLIW bundle here means that we
   7829      have no problems.  */
   7830   if (fmt == XTENSA_UNDEFINED
   7831       || xtensa_format_num_slots (isa, fmt) != 1)
   7832     return FALSE;
   7833 
   7834   xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf);
   7835   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
   7836 
   7837   if (opcode == xtensa_retw_opcode || opcode == xtensa_retw_n_opcode)
   7838     return TRUE;
   7839 
   7840   return FALSE;
   7841 }
   7842 
   7843 
   7844 /* Re-process all of the fragments looking to convert all of the
   7845    RELAX_ADD_NOP_IF_PRE_LOOP_END.  If there is one instruction and a
   7846    loop end label, convert this frag to one that will generate a NOP.
   7847    In any case close it off with a .fill 0.  */
   7848 
   7849 static bfd_boolean next_instr_is_loop_end (fragS *);
   7850 
   7851 static void
   7852 xtensa_fix_b_j_loop_end_frags (void)
   7853 {
   7854   frchainS *frchP;
   7855   asection *s;
   7856 
   7857   /* When this routine is called, all of the subsections are still intact
   7858      so we walk over subsections instead of sections.  */
   7859   for (s = stdoutput->sections; s; s = s->next)
   7860     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   7861       {
   7862 	fragS *fragP;
   7863 
   7864 	/* Walk over all of the fragments in a subsection.  */
   7865 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   7866 	  {
   7867 	    if (fragP->fr_type == rs_machine_dependent
   7868 		&& fragP->fr_subtype == RELAX_ADD_NOP_IF_PRE_LOOP_END)
   7869 	      {
   7870 		if (next_instr_is_loop_end (fragP))
   7871 		  {
   7872 		    if (fragP->tc_frag_data.is_no_transform)
   7873 		      as_bad (_("branching or jumping to a loop end may trigger hardware errata"));
   7874 		    else
   7875 		      relax_frag_add_nop (fragP);
   7876 		  }
   7877 		frag_wane (fragP);
   7878 	      }
   7879 	  }
   7880       }
   7881 }
   7882 
   7883 
   7884 static bfd_boolean
   7885 next_instr_is_loop_end (fragS *fragP)
   7886 {
   7887   const fragS *next_fragP;
   7888 
   7889   if (next_frag_is_loop_target (fragP))
   7890     return FALSE;
   7891 
   7892   next_fragP = next_non_empty_frag (fragP);
   7893   if (next_fragP == NULL)
   7894     return FALSE;
   7895 
   7896   if (!next_frag_is_loop_target (next_fragP))
   7897     return FALSE;
   7898 
   7899   /* If the size is >= 3 then there is more than one instruction here.
   7900      The hardware bug will not fire.  */
   7901   if (next_fragP->fr_fix > 3)
   7902     return FALSE;
   7903 
   7904   return TRUE;
   7905 }
   7906 
   7907 
   7908 /* Re-process all of the fragments looking to convert all of the
   7909    RELAX_ADD_NOP_IF_CLOSE_LOOP_END.  If there is an loop end that is
   7910    not MY loop's loop end within 12 bytes, add enough nops here to
   7911    make it at least 12 bytes away.  In any case close it off with a
   7912    .fill 0.  */
   7913 
   7914 static offsetT min_bytes_to_other_loop_end
   7915   (fragS *, fragS *, offsetT);
   7916 
   7917 static void
   7918 xtensa_fix_close_loop_end_frags (void)
   7919 {
   7920   frchainS *frchP;
   7921   asection *s;
   7922 
   7923   /* When this routine is called, all of the subsections are still intact
   7924      so we walk over subsections instead of sections.  */
   7925   for (s = stdoutput->sections; s; s = s->next)
   7926     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   7927       {
   7928 	fragS *fragP;
   7929 
   7930 	fragS *current_target = NULL;
   7931 
   7932 	/* Walk over all of the fragments in a subsection.  */
   7933 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   7934 	  {
   7935 	    if (fragP->fr_type == rs_machine_dependent
   7936 		&& ((fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE)
   7937 		    || (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)))
   7938 	      current_target = symbol_get_frag (fragP->fr_symbol);
   7939 
   7940 	    if (current_target
   7941 		&& fragP->fr_type == rs_machine_dependent
   7942 		&& fragP->fr_subtype == RELAX_ADD_NOP_IF_CLOSE_LOOP_END)
   7943 	      {
   7944 		offsetT min_bytes;
   7945 		int bytes_added = 0;
   7946 
   7947 #define REQUIRED_LOOP_DIVIDING_BYTES 12
   7948 		/* Max out at 12.  */
   7949 		min_bytes = min_bytes_to_other_loop_end
   7950 		  (fragP->fr_next, current_target, REQUIRED_LOOP_DIVIDING_BYTES);
   7951 
   7952 		if (min_bytes < REQUIRED_LOOP_DIVIDING_BYTES)
   7953 		  {
   7954 		    if (fragP->tc_frag_data.is_no_transform)
   7955 		      as_bad (_("loop end too close to another loop end may trigger hardware errata"));
   7956 		    else
   7957 		      {
   7958 			while (min_bytes + bytes_added
   7959 			       < REQUIRED_LOOP_DIVIDING_BYTES)
   7960 			  {
   7961 			    int length = 3;
   7962 
   7963 			    if (fragP->fr_var < length)
   7964 			      as_fatal (_("fr_var %lu < length %d"),
   7965 					(long) fragP->fr_var, length);
   7966 			    else
   7967 			      {
   7968 				assemble_nop (length,
   7969 					      fragP->fr_literal + fragP->fr_fix);
   7970 				fragP->fr_fix += length;
   7971 				fragP->fr_var -= length;
   7972 			      }
   7973 			    bytes_added += length;
   7974 			  }
   7975 		      }
   7976 		  }
   7977 		frag_wane (fragP);
   7978 	      }
   7979 	    gas_assert (fragP->fr_type != rs_machine_dependent
   7980 		    || fragP->fr_subtype != RELAX_ADD_NOP_IF_CLOSE_LOOP_END);
   7981 	  }
   7982       }
   7983 }
   7984 
   7985 
   7986 static offsetT unrelaxed_frag_min_size (fragS *);
   7987 
   7988 static offsetT
   7989 min_bytes_to_other_loop_end (fragS *fragP,
   7990 			     fragS *current_target,
   7991 			     offsetT max_size)
   7992 {
   7993   offsetT offset = 0;
   7994   fragS *current_fragP;
   7995 
   7996   for (current_fragP = fragP;
   7997        current_fragP;
   7998        current_fragP = current_fragP->fr_next)
   7999     {
   8000       if (current_fragP->tc_frag_data.is_loop_target
   8001 	  && current_fragP != current_target)
   8002 	return offset;
   8003 
   8004       offset += unrelaxed_frag_min_size (current_fragP);
   8005 
   8006       if (offset >= max_size)
   8007 	return max_size;
   8008     }
   8009   return max_size;
   8010 }
   8011 
   8012 
   8013 static offsetT
   8014 unrelaxed_frag_min_size (fragS *fragP)
   8015 {
   8016   offsetT size = fragP->fr_fix;
   8017 
   8018   /* Add fill size.  */
   8019   if (fragP->fr_type == rs_fill)
   8020     size += fragP->fr_offset;
   8021 
   8022   return size;
   8023 }
   8024 
   8025 
   8026 static offsetT
   8027 unrelaxed_frag_max_size (fragS *fragP)
   8028 {
   8029   offsetT size = fragP->fr_fix;
   8030   switch (fragP->fr_type)
   8031     {
   8032     case 0:
   8033       /* Empty frags created by the obstack allocation scheme
   8034 	 end up with type 0.  */
   8035       break;
   8036     case rs_fill:
   8037     case rs_org:
   8038     case rs_space:
   8039       size += fragP->fr_offset;
   8040       break;
   8041     case rs_align:
   8042     case rs_align_code:
   8043     case rs_align_test:
   8044     case rs_leb128:
   8045     case rs_cfa:
   8046     case rs_dwarf2dbg:
   8047       /* No further adjustments needed.  */
   8048       break;
   8049     case rs_machine_dependent:
   8050       if (fragP->fr_subtype != RELAX_DESIRE_ALIGN)
   8051 	size += fragP->fr_var;
   8052       break;
   8053     default:
   8054       /* We had darn well better know how big it is.  */
   8055       gas_assert (0);
   8056       break;
   8057     }
   8058 
   8059   return size;
   8060 }
   8061 
   8062 
   8063 /* Re-process all of the fragments looking to convert all
   8064    of the RELAX_ADD_NOP_IF_SHORT_LOOP.  If:
   8065 
   8066    A)
   8067      1) the instruction size count to the loop end label
   8068         is too short (<= 2 instructions),
   8069      2) loop has a jump or branch in it
   8070 
   8071    or B)
   8072      1) workaround_all_short_loops is TRUE
   8073      2) The generating loop was a  'loopgtz' or 'loopnez'
   8074      3) the instruction size count to the loop end label is too short
   8075         (<= 2 instructions)
   8076    then convert this frag (and maybe the next one) to generate a NOP.
   8077    In any case close it off with a .fill 0.  */
   8078 
   8079 static int count_insns_to_loop_end (fragS *, bfd_boolean, int);
   8080 static bfd_boolean branch_before_loop_end (fragS *);
   8081 
   8082 static void
   8083 xtensa_fix_short_loop_frags (void)
   8084 {
   8085   frchainS *frchP;
   8086   asection *s;
   8087 
   8088   /* When this routine is called, all of the subsections are still intact
   8089      so we walk over subsections instead of sections.  */
   8090   for (s = stdoutput->sections; s; s = s->next)
   8091     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   8092       {
   8093 	fragS *fragP;
   8094 	xtensa_opcode current_opcode = XTENSA_UNDEFINED;
   8095 
   8096 	/* Walk over all of the fragments in a subsection.  */
   8097 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   8098 	  {
   8099 	    if (fragP->fr_type == rs_machine_dependent
   8100 		&& ((fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE)
   8101 		    || (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)))
   8102 	      {
   8103 		TInsn t_insn;
   8104 		fragS *loop_frag = next_non_empty_frag (fragP);
   8105 		tinsn_from_chars (&t_insn, loop_frag->fr_opcode, 0);
   8106 		current_opcode = t_insn.opcode;
   8107 		gas_assert (xtensa_opcode_is_loop (xtensa_default_isa,
   8108 					       current_opcode) == 1);
   8109 	      }
   8110 
   8111 	    if (fragP->fr_type == rs_machine_dependent
   8112 		&& fragP->fr_subtype == RELAX_ADD_NOP_IF_SHORT_LOOP)
   8113 	      {
   8114 		if (count_insns_to_loop_end (fragP->fr_next, TRUE, 3) < 3
   8115 		    && (branch_before_loop_end (fragP->fr_next)
   8116 			|| (workaround_all_short_loops
   8117 			    && current_opcode != XTENSA_UNDEFINED
   8118 			    && current_opcode != xtensa_loop_opcode)))
   8119 		  {
   8120 		    if (fragP->tc_frag_data.is_no_transform)
   8121 		      as_bad (_("loop containing less than three instructions may trigger hardware errata"));
   8122 		    else
   8123 		      relax_frag_add_nop (fragP);
   8124 		  }
   8125 		frag_wane (fragP);
   8126 	      }
   8127 	  }
   8128       }
   8129 }
   8130 
   8131 
   8132 static int unrelaxed_frag_min_insn_count (fragS *);
   8133 
   8134 static int
   8135 count_insns_to_loop_end (fragS *base_fragP,
   8136 			 bfd_boolean count_relax_add,
   8137 			 int max_count)
   8138 {
   8139   fragS *fragP = NULL;
   8140   int insn_count = 0;
   8141 
   8142   fragP = base_fragP;
   8143 
   8144   for (; fragP && !fragP->tc_frag_data.is_loop_target; fragP = fragP->fr_next)
   8145     {
   8146       insn_count += unrelaxed_frag_min_insn_count (fragP);
   8147       if (insn_count >= max_count)
   8148 	return max_count;
   8149 
   8150       if (count_relax_add)
   8151 	{
   8152 	  if (fragP->fr_type == rs_machine_dependent
   8153 	      && fragP->fr_subtype == RELAX_ADD_NOP_IF_SHORT_LOOP)
   8154 	    {
   8155 	      /* In order to add the appropriate number of
   8156 	         NOPs, we count an instruction for downstream
   8157 	         occurrences.  */
   8158 	      insn_count++;
   8159 	      if (insn_count >= max_count)
   8160 		return max_count;
   8161 	    }
   8162 	}
   8163     }
   8164   return insn_count;
   8165 }
   8166 
   8167 
   8168 static int
   8169 unrelaxed_frag_min_insn_count (fragS *fragP)
   8170 {
   8171   xtensa_isa isa = xtensa_default_isa;
   8172   static xtensa_insnbuf insnbuf = NULL;
   8173   int insn_count = 0;
   8174   int offset = 0;
   8175 
   8176   if (!fragP->tc_frag_data.is_insn)
   8177     return insn_count;
   8178 
   8179   if (!insnbuf)
   8180     insnbuf = xtensa_insnbuf_alloc (isa);
   8181 
   8182   /* Decode the fixed instructions.  */
   8183   while (offset < fragP->fr_fix)
   8184     {
   8185       xtensa_format fmt;
   8186 
   8187       xtensa_insnbuf_from_chars
   8188 	(isa, insnbuf, (unsigned char *) fragP->fr_literal + offset, 0);
   8189       fmt = xtensa_format_decode (isa, insnbuf);
   8190 
   8191       if (fmt == XTENSA_UNDEFINED)
   8192 	{
   8193 	  as_fatal (_("undecodable instruction in instruction frag"));
   8194 	  return insn_count;
   8195 	}
   8196       offset += xtensa_format_length (isa, fmt);
   8197       insn_count++;
   8198     }
   8199 
   8200   return insn_count;
   8201 }
   8202 
   8203 
   8204 static bfd_boolean unrelaxed_frag_has_b_j (fragS *);
   8205 
   8206 static bfd_boolean
   8207 branch_before_loop_end (fragS *base_fragP)
   8208 {
   8209   fragS *fragP;
   8210 
   8211   for (fragP = base_fragP;
   8212        fragP && !fragP->tc_frag_data.is_loop_target;
   8213        fragP = fragP->fr_next)
   8214     {
   8215       if (unrelaxed_frag_has_b_j (fragP))
   8216 	return TRUE;
   8217     }
   8218   return FALSE;
   8219 }
   8220 
   8221 
   8222 static bfd_boolean
   8223 unrelaxed_frag_has_b_j (fragS *fragP)
   8224 {
   8225   static xtensa_insnbuf insnbuf = NULL;
   8226   xtensa_isa isa = xtensa_default_isa;
   8227   int offset = 0;
   8228 
   8229   if (!fragP->tc_frag_data.is_insn)
   8230     return FALSE;
   8231 
   8232   if (!insnbuf)
   8233     insnbuf = xtensa_insnbuf_alloc (isa);
   8234 
   8235   /* Decode the fixed instructions.  */
   8236   while (offset < fragP->fr_fix)
   8237     {
   8238       xtensa_format fmt;
   8239       int slot;
   8240 
   8241       xtensa_insnbuf_from_chars
   8242 	(isa, insnbuf, (unsigned char *) fragP->fr_literal + offset, 0);
   8243       fmt = xtensa_format_decode (isa, insnbuf);
   8244       if (fmt == XTENSA_UNDEFINED)
   8245 	return FALSE;
   8246 
   8247       for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
   8248 	{
   8249 	  xtensa_opcode opcode =
   8250 	    get_opcode_from_buf (fragP->fr_literal + offset, slot);
   8251 	  if (xtensa_opcode_is_branch (isa, opcode) == 1
   8252 	      || xtensa_opcode_is_jump (isa, opcode) == 1)
   8253 	    return TRUE;
   8254 	}
   8255       offset += xtensa_format_length (isa, fmt);
   8256     }
   8257   return FALSE;
   8258 }
   8259 
   8260 
   8261 /* Checks to be made after initial assembly but before relaxation.  */
   8262 
   8263 static bfd_boolean is_empty_loop (const TInsn *, fragS *);
   8264 static bfd_boolean is_local_forward_loop (const TInsn *, fragS *);
   8265 
   8266 static void
   8267 xtensa_sanity_check (void)
   8268 {
   8269   char *file_name;
   8270   unsigned line;
   8271   frchainS *frchP;
   8272   asection *s;
   8273 
   8274   as_where (&file_name, &line);
   8275   for (s = stdoutput->sections; s; s = s->next)
   8276     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
   8277       {
   8278 	fragS *fragP;
   8279 
   8280 	/* Walk over all of the fragments in a subsection.  */
   8281 	for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
   8282 	  {
   8283 	    if (fragP->fr_type == rs_machine_dependent
   8284 		&& fragP->fr_subtype == RELAX_SLOTS
   8285 		&& fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED)
   8286 	      {
   8287 		static xtensa_insnbuf insnbuf = NULL;
   8288 		TInsn t_insn;
   8289 
   8290 		if (fragP->fr_opcode != NULL)
   8291 		  {
   8292 		    if (!insnbuf)
   8293 		      insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
   8294 		    tinsn_from_chars (&t_insn, fragP->fr_opcode, 0);
   8295 		    tinsn_immed_from_frag (&t_insn, fragP, 0);
   8296 
   8297 		    if (xtensa_opcode_is_loop (xtensa_default_isa,
   8298 					       t_insn.opcode) == 1)
   8299 		      {
   8300 			if (is_empty_loop (&t_insn, fragP))
   8301 			  {
   8302 			    new_logical_line (fragP->fr_file, fragP->fr_line);
   8303 			    as_bad (_("invalid empty loop"));
   8304 			  }
   8305 			if (!is_local_forward_loop (&t_insn, fragP))
   8306 			  {
   8307 			    new_logical_line (fragP->fr_file, fragP->fr_line);
   8308 			    as_bad (_("loop target does not follow "
   8309 				      "loop instruction in section"));
   8310 			  }
   8311 		      }
   8312 		  }
   8313 	      }
   8314 	  }
   8315       }
   8316   new_logical_line (file_name, line);
   8317 }
   8318 
   8319 
   8320 #define LOOP_IMMED_OPN 1
   8321 
   8322 /* Return TRUE if the loop target is the next non-zero fragment.  */
   8323 
   8324 static bfd_boolean
   8325 is_empty_loop (const TInsn *insn, fragS *fragP)
   8326 {
   8327   const expressionS *exp;
   8328   symbolS *symbolP;
   8329   fragS *next_fragP;
   8330 
   8331   if (insn->insn_type != ITYPE_INSN)
   8332     return FALSE;
   8333 
   8334   if (xtensa_opcode_is_loop (xtensa_default_isa, insn->opcode) != 1)
   8335     return FALSE;
   8336 
   8337   if (insn->ntok <= LOOP_IMMED_OPN)
   8338     return FALSE;
   8339 
   8340   exp = &insn->tok[LOOP_IMMED_OPN];
   8341 
   8342   if (exp->X_op != O_symbol)
   8343     return FALSE;
   8344 
   8345   symbolP = exp->X_add_symbol;
   8346   if (!symbolP)
   8347     return FALSE;
   8348 
   8349   if (symbol_get_frag (symbolP) == NULL)
   8350     return FALSE;
   8351 
   8352   if (S_GET_VALUE (symbolP) != 0)
   8353     return FALSE;
   8354 
   8355   /* Walk through the zero-size fragments from this one.  If we find
   8356      the target fragment, then this is a zero-size loop.  */
   8357 
   8358   for (next_fragP = fragP->fr_next;
   8359        next_fragP != NULL;
   8360        next_fragP = next_fragP->fr_next)
   8361     {
   8362       if (next_fragP == symbol_get_frag (symbolP))
   8363 	return TRUE;
   8364       if (next_fragP->fr_fix != 0)
   8365 	return FALSE;
   8366     }
   8367   return FALSE;
   8368 }
   8369 
   8370 
   8371 static bfd_boolean
   8372 is_local_forward_loop (const TInsn *insn, fragS *fragP)
   8373 {
   8374   const expressionS *exp;
   8375   symbolS *symbolP;
   8376   fragS *next_fragP;
   8377 
   8378   if (insn->insn_type != ITYPE_INSN)
   8379     return FALSE;
   8380 
   8381   if (xtensa_opcode_is_loop (xtensa_default_isa, insn->opcode) != 1)
   8382     return FALSE;
   8383 
   8384   if (insn->ntok <= LOOP_IMMED_OPN)
   8385     return FALSE;
   8386 
   8387   exp = &insn->tok[LOOP_IMMED_OPN];
   8388 
   8389   if (exp->X_op != O_symbol)
   8390     return FALSE;
   8391 
   8392   symbolP = exp->X_add_symbol;
   8393   if (!symbolP)
   8394     return FALSE;
   8395 
   8396   if (symbol_get_frag (symbolP) == NULL)
   8397     return FALSE;
   8398 
   8399   /* Walk through fragments until we find the target.
   8400      If we do not find the target, then this is an invalid loop.  */
   8401 
   8402   for (next_fragP = fragP->fr_next;
   8403        next_fragP != NULL;
   8404        next_fragP = next_fragP->fr_next)
   8405     {
   8406       if (next_fragP == symbol_get_frag (symbolP))
   8407 	return TRUE;
   8408     }
   8409 
   8410   return FALSE;
   8411 }
   8412 
   8413 
   8414 #define XTINFO_NAME "Xtensa_Info"
   8415 #define XTINFO_NAMESZ 12
   8416 #define XTINFO_TYPE 1
   8417 
   8418 static void
   8419 xtensa_add_config_info (void)
   8420 {
   8421   asection *info_sec;
   8422   char *data, *p;
   8423   int sz;
   8424 
   8425   info_sec = subseg_new (".xtensa.info", 0);
   8426   bfd_set_section_flags (stdoutput, info_sec, SEC_HAS_CONTENTS | SEC_READONLY);
   8427 
   8428   data = xmalloc (100);
   8429   sprintf (data, "USE_ABSOLUTE_LITERALS=%d\nABI=%d\n",
   8430 	   XSHAL_USE_ABSOLUTE_LITERALS, XSHAL_ABI);
   8431   sz = strlen (data) + 1;
   8432 
   8433   /* Add enough null terminators to pad to a word boundary.  */
   8434   do
   8435     data[sz++] = 0;
   8436   while ((sz & 3) != 0);
   8437 
   8438   /* Follow the standard note section layout:
   8439      First write the length of the name string.  */
   8440   p = frag_more (4);
   8441   md_number_to_chars (p, (valueT) XTINFO_NAMESZ, 4);
   8442 
   8443   /* Next comes the length of the "descriptor", i.e., the actual data.  */
   8444   p = frag_more (4);
   8445   md_number_to_chars (p, (valueT) sz, 4);
   8446 
   8447   /* Write the note type.  */
   8448   p = frag_more (4);
   8449   md_number_to_chars (p, (valueT) XTINFO_TYPE, 4);
   8450 
   8451   /* Write the name field.  */
   8452   p = frag_more (XTINFO_NAMESZ);
   8453   memcpy (p, XTINFO_NAME, XTINFO_NAMESZ);
   8454 
   8455   /* Finally, write the descriptor.  */
   8456   p = frag_more (sz);
   8457   memcpy (p, data, sz);
   8458 
   8459   free (data);
   8460 }
   8461 
   8462 
   8463 /* Alignment Functions.  */
   8465 
   8466 static int
   8467 get_text_align_power (unsigned target_size)
   8468 {
   8469   if (target_size <= 4)
   8470     return 2;
   8471 
   8472   if (target_size <= 8)
   8473     return 3;
   8474 
   8475   if (target_size <= 16)
   8476     return 4;
   8477 
   8478   if (target_size <= 32)
   8479     return 5;
   8480 
   8481   if (target_size <= 64)
   8482     return 6;
   8483 
   8484   if (target_size <= 128)
   8485     return 7;
   8486 
   8487   if (target_size <= 256)
   8488     return 8;
   8489 
   8490   if (target_size <= 512)
   8491     return 9;
   8492 
   8493   if (target_size <= 1024)
   8494     return 10;
   8495 
   8496   gas_assert (0);
   8497   return 0;
   8498 }
   8499 
   8500 
   8501 static int
   8502 get_text_align_max_fill_size (int align_pow,
   8503 			      bfd_boolean use_nops,
   8504 			      bfd_boolean use_no_density)
   8505 {
   8506   if (!use_nops)
   8507     return (1 << align_pow);
   8508   if (use_no_density)
   8509     return 3 * (1 << align_pow);
   8510 
   8511   return 1 + (1 << align_pow);
   8512 }
   8513 
   8514 
   8515 /* Calculate the minimum bytes of fill needed at "address" to align a
   8516    target instruction of size "target_size" so that it does not cross a
   8517    power-of-two boundary specified by "align_pow".  If "use_nops" is FALSE,
   8518    the fill can be an arbitrary number of bytes.  Otherwise, the space must
   8519    be filled by NOP instructions.  */
   8520 
   8521 static int
   8522 get_text_align_fill_size (addressT address,
   8523 			  int align_pow,
   8524 			  int target_size,
   8525 			  bfd_boolean use_nops,
   8526 			  bfd_boolean use_no_density)
   8527 {
   8528   addressT alignment, fill, fill_limit, fill_step;
   8529   bfd_boolean skip_one = FALSE;
   8530 
   8531   alignment = (1 << align_pow);
   8532   gas_assert (target_size > 0 && alignment >= (addressT) target_size);
   8533 
   8534   if (!use_nops)
   8535     {
   8536       fill_limit = alignment;
   8537       fill_step = 1;
   8538     }
   8539   else if (!use_no_density)
   8540     {
   8541       /* Combine 2- and 3-byte NOPs to fill anything larger than one.  */
   8542       fill_limit = alignment * 2;
   8543       fill_step = 1;
   8544       skip_one = TRUE;
   8545     }
   8546   else
   8547     {
   8548       /* Fill with 3-byte NOPs -- can only fill multiples of 3.  */
   8549       fill_limit = alignment * 3;
   8550       fill_step = 3;
   8551     }
   8552 
   8553   /* Try all fill sizes until finding one that works.  */
   8554   for (fill = 0; fill < fill_limit; fill += fill_step)
   8555     {
   8556       if (skip_one && fill == 1)
   8557 	continue;
   8558       if ((address + fill) >> align_pow
   8559 	  == (address + fill + target_size - 1) >> align_pow)
   8560 	return fill;
   8561     }
   8562   gas_assert (0);
   8563   return 0;
   8564 }
   8565 
   8566 
   8567 static int
   8568 branch_align_power (segT sec)
   8569 {
   8570   /* If the Xtensa processor has a fetch width of X, and
   8571      the section is aligned to at least that boundary, then a branch
   8572      target need only fit within that aligned block of memory to avoid
   8573      a stall.  Otherwise, try to fit branch targets within 4-byte
   8574      aligned blocks (which may be insufficient, e.g., if the section
   8575      has no alignment, but it's good enough).  */
   8576   int fetch_align = get_text_align_power(xtensa_fetch_width);
   8577   int sec_align = get_recorded_alignment (sec);
   8578 
   8579   if (sec_align >= fetch_align)
   8580     return fetch_align;
   8581 
   8582   return 2;
   8583 }
   8584 
   8585 
   8586 /* This will assert if it is not possible.  */
   8587 
   8588 static int
   8589 get_text_align_nop_count (offsetT fill_size, bfd_boolean use_no_density)
   8590 {
   8591   int count = 0;
   8592 
   8593   if (use_no_density)
   8594     {
   8595       gas_assert (fill_size % 3 == 0);
   8596       return (fill_size / 3);
   8597     }
   8598 
   8599   gas_assert (fill_size != 1);	/* Bad argument.  */
   8600 
   8601   while (fill_size > 1)
   8602     {
   8603       int insn_size = 3;
   8604       if (fill_size == 2 || fill_size == 4)
   8605 	insn_size = 2;
   8606       fill_size -= insn_size;
   8607       count++;
   8608     }
   8609   gas_assert (fill_size != 1);	/* Bad algorithm.  */
   8610   return count;
   8611 }
   8612 
   8613 
   8614 static int
   8615 get_text_align_nth_nop_size (offsetT fill_size,
   8616 			     int n,
   8617 			     bfd_boolean use_no_density)
   8618 {
   8619   int count = 0;
   8620 
   8621   if (use_no_density)
   8622     return 3;
   8623 
   8624   gas_assert (fill_size != 1);	/* Bad argument.  */
   8625 
   8626   while (fill_size > 1)
   8627     {
   8628       int insn_size = 3;
   8629       if (fill_size == 2 || fill_size == 4)
   8630 	insn_size = 2;
   8631       fill_size -= insn_size;
   8632       count++;
   8633       if (n + 1 == count)
   8634 	return insn_size;
   8635     }
   8636   gas_assert (0);
   8637   return 0;
   8638 }
   8639 
   8640 
   8641 /* For the given fragment, find the appropriate address
   8642    for it to begin at if we are using NOPs to align it.  */
   8643 
   8644 static addressT
   8645 get_noop_aligned_address (fragS *fragP, addressT address)
   8646 {
   8647   /* The rule is: get next fragment's FIRST instruction.  Find
   8648      the smallest number of bytes that need to be added to
   8649      ensure that the next fragment's FIRST instruction will fit
   8650      in a single word.
   8651 
   8652      E.G.,   2 bytes : 0, 1, 2 mod 4
   8653 	     3 bytes: 0, 1 mod 4
   8654 
   8655      If the FIRST instruction MIGHT be relaxed,
   8656      assume that it will become a 3-byte instruction.
   8657 
   8658      Note again here that LOOP instructions are not bundleable,
   8659      and this relaxation only applies to LOOP opcodes.  */
   8660 
   8661   int fill_size = 0;
   8662   int first_insn_size;
   8663   int loop_insn_size;
   8664   addressT pre_opcode_bytes;
   8665   int align_power;
   8666   fragS *first_insn;
   8667   xtensa_opcode opcode;
   8668   bfd_boolean is_loop;
   8669 
   8670   gas_assert (fragP->fr_type == rs_machine_dependent);
   8671   gas_assert (fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE);
   8672 
   8673   /* Find the loop frag.  */
   8674   first_insn = next_non_empty_frag (fragP);
   8675   /* Now find the first insn frag.  */
   8676   first_insn = next_non_empty_frag (first_insn);
   8677 
   8678   is_loop = next_frag_opcode_is_loop (fragP, &opcode);
   8679   gas_assert (is_loop);
   8680   loop_insn_size = xg_get_single_size (opcode);
   8681 
   8682   pre_opcode_bytes = next_frag_pre_opcode_bytes (fragP);
   8683   pre_opcode_bytes += loop_insn_size;
   8684 
   8685   /* For loops, the alignment depends on the size of the
   8686      instruction following the loop, not the LOOP instruction.  */
   8687 
   8688   if (first_insn == NULL)
   8689     first_insn_size = xtensa_fetch_width;
   8690   else
   8691     first_insn_size = get_loop_align_size (frag_format_size (first_insn));
   8692 
   8693   /* If it was 8, then we'll need a larger alignment for the section.  */
   8694   align_power = get_text_align_power (first_insn_size);
   8695   record_alignment (now_seg, align_power);
   8696 
   8697   fill_size = get_text_align_fill_size
   8698     (address + pre_opcode_bytes, align_power, first_insn_size, TRUE,
   8699      fragP->tc_frag_data.is_no_density);
   8700 
   8701   return address + fill_size;
   8702 }
   8703 
   8704 
   8705 /* 3 mechanisms for relaxing an alignment:
   8706 
   8707    Align to a power of 2.
   8708    Align so the next fragment's instruction does not cross a word boundary.
   8709    Align the current instruction so that if the next instruction
   8710        were 3 bytes, it would not cross a word boundary.
   8711 
   8712    We can align with:
   8713 
   8714    zeros    - This is easy; always insert zeros.
   8715    nops     - 3-byte and 2-byte instructions
   8716               2 - 2-byte nop
   8717               3 - 3-byte nop
   8718               4 - 2 2-byte nops
   8719               >=5 : 3-byte instruction + fn (n-3)
   8720    widening - widen previous instructions.  */
   8721 
   8722 static offsetT
   8723 get_aligned_diff (fragS *fragP, addressT address, offsetT *max_diff)
   8724 {
   8725   addressT target_address, loop_insn_offset;
   8726   int target_size;
   8727   xtensa_opcode loop_opcode;
   8728   bfd_boolean is_loop;
   8729   int align_power;
   8730   offsetT opt_diff;
   8731   offsetT branch_align;
   8732   fragS *loop_frag;
   8733 
   8734   gas_assert (fragP->fr_type == rs_machine_dependent);
   8735   switch (fragP->fr_subtype)
   8736     {
   8737     case RELAX_DESIRE_ALIGN:
   8738       target_size = next_frag_format_size (fragP);
   8739       if (target_size == XTENSA_UNDEFINED)
   8740 	target_size = 3;
   8741       align_power = branch_align_power (now_seg);
   8742       branch_align = 1 << align_power;
   8743       /* Don't count on the section alignment being as large as the target.  */
   8744       if (target_size > branch_align)
   8745 	target_size = branch_align;
   8746       opt_diff = get_text_align_fill_size (address, align_power,
   8747 					   target_size, FALSE, FALSE);
   8748 
   8749       *max_diff = (opt_diff + branch_align
   8750 		   - (target_size + ((address + opt_diff) % branch_align)));
   8751       gas_assert (*max_diff >= opt_diff);
   8752       return opt_diff;
   8753 
   8754     case RELAX_ALIGN_NEXT_OPCODE:
   8755       /* The next non-empty frag after this one holds the LOOP instruction
   8756 	 that needs to be aligned.  The required alignment depends on the
   8757 	 size of the next non-empty frag after the loop frag, i.e., the
   8758 	 first instruction in the loop.  */
   8759       loop_frag = next_non_empty_frag (fragP);
   8760       target_size = get_loop_align_size (next_frag_format_size (loop_frag));
   8761       loop_insn_offset = 0;
   8762       is_loop = next_frag_opcode_is_loop (fragP, &loop_opcode);
   8763       gas_assert (is_loop);
   8764 
   8765       /* If the loop has been expanded then the LOOP instruction
   8766 	 could be at an offset from this fragment.  */
   8767       if (loop_frag->tc_frag_data.slot_subtypes[0] != RELAX_IMMED)
   8768 	loop_insn_offset = get_expanded_loop_offset (loop_opcode);
   8769 
   8770       /* In an ideal world, which is what we are shooting for here,
   8771 	 we wouldn't need to use any NOPs immediately prior to the
   8772 	 LOOP instruction.  If this approach fails, relax_frag_loop_align
   8773 	 will call get_noop_aligned_address.  */
   8774       target_address =
   8775 	address + loop_insn_offset + xg_get_single_size (loop_opcode);
   8776       align_power = get_text_align_power (target_size);
   8777       opt_diff = get_text_align_fill_size (target_address, align_power,
   8778 					   target_size, FALSE, FALSE);
   8779 
   8780       *max_diff = xtensa_fetch_width
   8781 	- ((target_address + opt_diff) % xtensa_fetch_width)
   8782 	- target_size + opt_diff;
   8783       gas_assert (*max_diff >= opt_diff);
   8784       return opt_diff;
   8785 
   8786     default:
   8787       break;
   8788     }
   8789   gas_assert (0);
   8790   return 0;
   8791 }
   8792 
   8793 
   8794 /* md_relax_frag Hook and Helper Functions.  */
   8796 
   8797 static long relax_frag_loop_align (fragS *, long);
   8798 static long relax_frag_for_align (fragS *, long);
   8799 static long relax_frag_immed
   8800   (segT, fragS *, long, int, xtensa_format, int, int *, bfd_boolean);
   8801 
   8802 
   8803 /* Return the number of bytes added to this fragment, given that the
   8804    input has been stretched already by "stretch".  */
   8805 
   8806 long
   8807 xtensa_relax_frag (fragS *fragP, long stretch, int *stretched_p)
   8808 {
   8809   xtensa_isa isa = xtensa_default_isa;
   8810   int unreported = fragP->tc_frag_data.unreported_expansion;
   8811   long new_stretch = 0;
   8812   char *file_name;
   8813   unsigned line;
   8814   int lit_size;
   8815   static xtensa_insnbuf vbuf = NULL;
   8816   int slot, num_slots;
   8817   xtensa_format fmt;
   8818 
   8819   as_where (&file_name, &line);
   8820   new_logical_line (fragP->fr_file, fragP->fr_line);
   8821 
   8822   fragP->tc_frag_data.unreported_expansion = 0;
   8823 
   8824   switch (fragP->fr_subtype)
   8825     {
   8826     case RELAX_ALIGN_NEXT_OPCODE:
   8827       /* Always convert.  */
   8828       if (fragP->tc_frag_data.relax_seen)
   8829 	new_stretch = relax_frag_loop_align (fragP, stretch);
   8830       break;
   8831 
   8832     case RELAX_LOOP_END:
   8833       /* Do nothing.  */
   8834       break;
   8835 
   8836     case RELAX_LOOP_END_ADD_NOP:
   8837       /* Add a NOP and switch to .fill 0.  */
   8838       new_stretch = relax_frag_add_nop (fragP);
   8839       frag_wane (fragP);
   8840       break;
   8841 
   8842     case RELAX_DESIRE_ALIGN:
   8843       /* Do nothing. The narrowing before this frag will either align
   8844          it or not.  */
   8845       break;
   8846 
   8847     case RELAX_LITERAL:
   8848     case RELAX_LITERAL_FINAL:
   8849       return 0;
   8850 
   8851     case RELAX_LITERAL_NR:
   8852       lit_size = 4;
   8853       fragP->fr_subtype = RELAX_LITERAL_FINAL;
   8854       gas_assert (unreported == lit_size);
   8855       memset (&fragP->fr_literal[fragP->fr_fix], 0, 4);
   8856       fragP->fr_var -= lit_size;
   8857       fragP->fr_fix += lit_size;
   8858       new_stretch = 4;
   8859       break;
   8860 
   8861     case RELAX_SLOTS:
   8862       if (vbuf == NULL)
   8863 	vbuf = xtensa_insnbuf_alloc (isa);
   8864 
   8865       xtensa_insnbuf_from_chars
   8866 	(isa, vbuf, (unsigned char *) fragP->fr_opcode, 0);
   8867       fmt = xtensa_format_decode (isa, vbuf);
   8868       num_slots = xtensa_format_num_slots (isa, fmt);
   8869 
   8870       for (slot = 0; slot < num_slots; slot++)
   8871 	{
   8872 	  switch (fragP->tc_frag_data.slot_subtypes[slot])
   8873 	    {
   8874 	    case RELAX_NARROW:
   8875 	      if (fragP->tc_frag_data.relax_seen)
   8876 		new_stretch += relax_frag_for_align (fragP, stretch);
   8877 	      break;
   8878 
   8879 	    case RELAX_IMMED:
   8880 	    case RELAX_IMMED_STEP1:
   8881 	    case RELAX_IMMED_STEP2:
   8882 	    case RELAX_IMMED_STEP3:
   8883 	      /* Place the immediate.  */
   8884 	      new_stretch += relax_frag_immed
   8885 		(now_seg, fragP, stretch,
   8886 		 fragP->tc_frag_data.slot_subtypes[slot] - RELAX_IMMED,
   8887 		 fmt, slot, stretched_p, FALSE);
   8888 	      break;
   8889 
   8890 	    default:
   8891 	      /* This is OK; see the note in xg_assemble_vliw_tokens.  */
   8892 	      break;
   8893 	    }
   8894 	}
   8895       break;
   8896 
   8897     case RELAX_LITERAL_POOL_BEGIN:
   8898     case RELAX_LITERAL_POOL_END:
   8899     case RELAX_MAYBE_UNREACHABLE:
   8900     case RELAX_MAYBE_DESIRE_ALIGN:
   8901       /* No relaxation required.  */
   8902       break;
   8903 
   8904     case RELAX_FILL_NOP:
   8905     case RELAX_UNREACHABLE:
   8906       if (fragP->tc_frag_data.relax_seen)
   8907 	new_stretch += relax_frag_for_align (fragP, stretch);
   8908       break;
   8909 
   8910     case RELAX_TRAMPOLINE:
   8911       if (fragP->tc_frag_data.relax_seen)
   8912         {
   8913           segment_info_type *seginfo = seg_info (now_seg);
   8914           fragS *fP; /* The out-of-range jump.  */
   8915           fixS *fixP;
   8916 
   8917           /* Scan for jumps that will not reach.  */
   8918           for (fixP = seginfo->fix_root; fixP ; fixP = fixP->fx_next)
   8919             {
   8920               symbolS *s = fixP->fx_addsy;
   8921 	      xtensa_opcode opcode;
   8922               int target;
   8923               int addr;
   8924               int delta;
   8925 
   8926               if (fixP->fx_r_type < BFD_RELOC_XTENSA_SLOT0_OP ||
   8927                   fixP->fx_r_type > BFD_RELOC_XTENSA_SLOT14_OP)
   8928                 continue;
   8929 	      xtensa_insnbuf_from_chars (isa, trampoline_buf,
   8930 					 (unsigned char *) fixP->fx_frag->fr_literal + fixP->fx_where,
   8931 					 0);
   8932 	      fmt = xtensa_format_decode (isa, trampoline_buf);
   8933 	      gas_assert (fmt != XTENSA_UNDEFINED);
   8934 	      slot = fixP->tc_fix_data.slot;
   8935 	      xtensa_format_get_slot (isa, fmt, slot, trampoline_buf, trampoline_slotbuf);
   8936 	      opcode = xtensa_opcode_decode (isa, fmt, slot, trampoline_slotbuf);
   8937 	      if (opcode != xtensa_j_opcode)
   8938 		continue;
   8939               target = S_GET_VALUE (s);
   8940               addr = fixP->fx_frag->fr_address;
   8941               delta = target - addr + stretch;
   8942               if (delta > J_RANGE  || delta < -1 * J_RANGE)
   8943                 { /* Found an out-of-range jump; scan the list of trampolines for the best match.  */
   8944 		  struct trampoline_seg *ts = find_trampoline_seg (now_seg);
   8945 		  struct trampoline_frag *tf = ts->trampoline_list.next;
   8946 		  struct trampoline_frag *prev = &ts->trampoline_list;
   8947 		  int lower = (target < addr) ? target : addr;
   8948 		  int upper = (target > addr) ? target : addr;
   8949 		  int midpoint = lower + (upper - lower) / 2;
   8950 
   8951 		  if ((upper - lower) > 2 * J_RANGE)
   8952 		    {
   8953 		      /* One trampoline won't suffice; we need multiple jumps.
   8954 			 Jump to the trampoline that's farthest, but still in
   8955 			 range relative to the original "j" instruction.  */
   8956 		      for ( ; tf; prev = tf, tf = tf->next )
   8957 			{
   8958 			  int this_addr = tf->fragP->fr_address + tf->fragP->fr_fix;
   8959 			  int next_addr = (tf->next) ? tf->next->fragP->fr_address + tf->next->fragP->fr_fix : 0 ;
   8960 
   8961 			  if (addr == lower)
   8962 			    {
   8963 			      /* Forward jump.  */
   8964 			      if (this_addr - addr < J_RANGE)
   8965 				break;
   8966 			    }
   8967 			  else
   8968 			    {
   8969 			      /* Backward jump.  */
   8970 			      if (next_addr == 0 || addr - next_addr > J_RANGE)
   8971 				break;
   8972 			    }
   8973 			}
   8974 		    }
   8975 		  else
   8976 		    {
   8977 		      struct trampoline_frag *best_tf = NULL;
   8978 		      int best_delta = 0;
   8979 
   8980 		      for ( ; tf; prev = tf, tf = tf->next )
   8981 			{
   8982 			  int this_addr = tf->fragP->fr_address + tf->fragP->fr_fix;
   8983 			  int this_delta = abs (this_addr - midpoint);
   8984 
   8985 			  if (!best_tf || this_delta < best_delta)
   8986 			    {
   8987 			       best_tf = tf;
   8988 			       best_delta = this_delta;
   8989 			    }
   8990 			}
   8991 		      tf = best_tf;
   8992 		    }
   8993 		  if (tf->fragP == fragP)
   8994 		    {
   8995 		      int trampaddr = fragP->fr_address + fragP->fr_fix;
   8996 
   8997 		      if (abs (addr - trampaddr) < J_RANGE)
   8998 			{ /* The trampoline is in range of original; fix it!  */
   8999 			  fixS *newfixP;
   9000 			  int offset;
   9001 			  TInsn insn;
   9002 			  symbolS *lsym;
   9003 
   9004 			  new_stretch += init_trampoline_frag (tf);
   9005 			  offset = fragP->fr_fix; /* Where to assemble the j insn.  */
   9006 			  lsym = fragP->fr_symbol;
   9007 			  fP = fixP->fx_frag;
   9008 			  /* Assemble a jump to the target label here.  */
   9009 			  tinsn_init (&insn);
   9010 			  insn.insn_type = ITYPE_INSN;
   9011 			  insn.opcode = xtensa_j_opcode;
   9012 			  insn.ntok = 1;
   9013 			  set_expr_symbol_offset (&insn.tok[0], lsym, offset);
   9014 			  fmt = xg_get_single_format (xtensa_j_opcode);
   9015 			  tinsn_to_slotbuf (fmt, 0, &insn, trampoline_slotbuf);
   9016 			  xtensa_format_set_slot (isa, fmt, 0, trampoline_buf, trampoline_slotbuf);
   9017 			  xtensa_insnbuf_to_chars (isa, trampoline_buf, (unsigned char *)fragP->fr_literal + offset, 3);
   9018 			  fragP->fr_fix += 3;
   9019 			  fragP->fr_var -= 3;
   9020 			  /* Add a fix-up for the original j insn.  */
   9021 			  newfixP = fix_new (fP, fixP->fx_where, fixP->fx_size, lsym, fragP->fr_fix - 3, TRUE, fixP->fx_r_type);
   9022 			  newfixP->fx_no_overflow = 1;
   9023 			  newfixP->tc_fix_data.X_add_symbol = lsym;
   9024 			  newfixP->tc_fix_data.X_add_number = offset;
   9025 			  newfixP->tc_fix_data.slot = slot;
   9026 			  /* Move the fix-up from the original j insn to this one.  */
   9027 			  fixP->fx_frag = fragP;
   9028 			  fixP->fx_where = fragP->fr_fix - 3;
   9029 			  fixP->tc_fix_data.slot = 0;
   9030 			  /* Adjust the jump around this trampoline (if present).  */
   9031 			  if (tf->fixP != NULL)
   9032 			    {
   9033 			      tf->fixP->fx_offset += 3;
   9034 			    }
   9035 			  new_stretch += 3;
   9036 			  fragP->tc_frag_data.relax_seen = FALSE; /* Need another pass.  */
   9037 			  /* Do we have room for more?  */
   9038 			  if (fragP->fr_var < 3)
   9039 			    { /* No, convert to fill.  */
   9040 			      frag_wane (fragP);
   9041 			      fragP->fr_subtype = 0;
   9042 			      /* Remove from the trampoline_list.  */
   9043 			      prev->next = tf->next;
   9044 			      break;
   9045 			    }
   9046 			}
   9047 		    }
   9048                 }
   9049             }
   9050         }
   9051       break;
   9052 
   9053     default:
   9054       as_bad (_("bad relaxation state"));
   9055     }
   9056 
   9057   /* Tell gas we need another relaxation pass.  */
   9058   if (! fragP->tc_frag_data.relax_seen)
   9059     {
   9060       fragP->tc_frag_data.relax_seen = TRUE;
   9061       *stretched_p = 1;
   9062     }
   9063 
   9064   new_logical_line (file_name, line);
   9065   return new_stretch;
   9066 }
   9067 
   9068 
   9069 static long
   9070 relax_frag_loop_align (fragS *fragP, long stretch)
   9071 {
   9072   addressT old_address, old_next_address, old_size;
   9073   addressT new_address, new_next_address, new_size;
   9074   addressT growth;
   9075 
   9076   /* All the frags with relax_frag_for_alignment prior to this one in the
   9077      section have been done, hopefully eliminating the need for a NOP here.
   9078      But, this will put it in if necessary.  */
   9079 
   9080   /* Calculate the old address of this fragment and the next fragment.  */
   9081   old_address = fragP->fr_address - stretch;
   9082   old_next_address = (fragP->fr_address - stretch + fragP->fr_fix +
   9083 		      fragP->tc_frag_data.text_expansion[0]);
   9084   old_size = old_next_address - old_address;
   9085 
   9086   /* Calculate the new address of this fragment and the next fragment.  */
   9087   new_address = fragP->fr_address;
   9088   new_next_address =
   9089     get_noop_aligned_address (fragP, fragP->fr_address + fragP->fr_fix);
   9090   new_size = new_next_address - new_address;
   9091 
   9092   growth = new_size - old_size;
   9093 
   9094   /* Fix up the text_expansion field and return the new growth.  */
   9095   fragP->tc_frag_data.text_expansion[0] += growth;
   9096   return growth;
   9097 }
   9098 
   9099 
   9100 /* Add a NOP instruction.  */
   9101 
   9102 static long
   9103 relax_frag_add_nop (fragS *fragP)
   9104 {
   9105   char *nop_buf = fragP->fr_literal + fragP->fr_fix;
   9106   int length = fragP->tc_frag_data.is_no_density ? 3 : 2;
   9107   assemble_nop (length, nop_buf);
   9108   fragP->tc_frag_data.is_insn = TRUE;
   9109 
   9110   if (fragP->fr_var < length)
   9111     {
   9112       as_fatal (_("fr_var (%ld) < length (%d)"), (long) fragP->fr_var, length);
   9113       return 0;
   9114     }
   9115 
   9116   fragP->fr_fix += length;
   9117   fragP->fr_var -= length;
   9118   return length;
   9119 }
   9120 
   9121 
   9122 static long future_alignment_required (fragS *, long);
   9123 
   9124 static long
   9125 relax_frag_for_align (fragS *fragP, long stretch)
   9126 {
   9127   /* Overview of the relaxation procedure for alignment:
   9128      We can widen with NOPs or by widening instructions or by filling
   9129      bytes after jump instructions.  Find the opportune places and widen
   9130      them if necessary.  */
   9131 
   9132   long stretch_me;
   9133   long diff;
   9134 
   9135   gas_assert (fragP->fr_subtype == RELAX_FILL_NOP
   9136 	  || fragP->fr_subtype == RELAX_UNREACHABLE
   9137 	  || (fragP->fr_subtype == RELAX_SLOTS
   9138 	      && fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW));
   9139 
   9140   stretch_me = future_alignment_required (fragP, stretch);
   9141   diff = stretch_me - fragP->tc_frag_data.text_expansion[0];
   9142   if (diff == 0)
   9143     return 0;
   9144 
   9145   if (diff < 0)
   9146     {
   9147       /* We expanded on a previous pass.  Can we shrink now?  */
   9148       long shrink = fragP->tc_frag_data.text_expansion[0] - stretch_me;
   9149       if (shrink <= stretch && stretch > 0)
   9150 	{
   9151 	  fragP->tc_frag_data.text_expansion[0] = stretch_me;
   9152 	  return -shrink;
   9153 	}
   9154       return 0;
   9155     }
   9156 
   9157   /* Below here, diff > 0.  */
   9158   fragP->tc_frag_data.text_expansion[0] = stretch_me;
   9159 
   9160   return diff;
   9161 }
   9162 
   9163 
   9164 /* Return the address of the next frag that should be aligned.
   9165 
   9166    By "address" we mean the address it _would_ be at if there
   9167    is no action taken to align it between here and the target frag.
   9168    In other words, if no narrows and no fill nops are used between
   9169    here and the frag to align, _even_if_ some of the frags we use
   9170    to align targets have already expanded on a previous relaxation
   9171    pass.
   9172 
   9173    Also, count each frag that may be used to help align the target.
   9174 
   9175    Return 0 if there are no frags left in the chain that need to be
   9176    aligned.  */
   9177 
   9178 static addressT
   9179 find_address_of_next_align_frag (fragS **fragPP,
   9180 				 int *wide_nops,
   9181 				 int *narrow_nops,
   9182 				 int *widens,
   9183 				 bfd_boolean *paddable)
   9184 {
   9185   fragS *fragP = *fragPP;
   9186   addressT address = fragP->fr_address;
   9187 
   9188   /* Do not reset the counts to 0.  */
   9189 
   9190   while (fragP)
   9191     {
   9192       /* Limit this to a small search.  */
   9193       if (*widens >= (int) xtensa_fetch_width)
   9194 	{
   9195 	  *fragPP = fragP;
   9196 	  return 0;
   9197 	}
   9198       address += fragP->fr_fix;
   9199 
   9200       if (fragP->fr_type == rs_fill)
   9201 	address += fragP->fr_offset * fragP->fr_var;
   9202       else if (fragP->fr_type == rs_machine_dependent)
   9203 	{
   9204 	  switch (fragP->fr_subtype)
   9205 	    {
   9206 	    case RELAX_UNREACHABLE:
   9207 	      *paddable = TRUE;
   9208 	      break;
   9209 
   9210 	    case RELAX_FILL_NOP:
   9211 	      (*wide_nops)++;
   9212 	      if (!fragP->tc_frag_data.is_no_density)
   9213 		(*narrow_nops)++;
   9214 	      break;
   9215 
   9216 	    case RELAX_SLOTS:
   9217 	      if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
   9218 		{
   9219 		  (*widens)++;
   9220 		  break;
   9221 		}
   9222 	      address += total_frag_text_expansion (fragP);
   9223 	      break;
   9224 
   9225 	    case RELAX_IMMED:
   9226 	      address += fragP->tc_frag_data.text_expansion[0];
   9227 	      break;
   9228 
   9229 	    case RELAX_ALIGN_NEXT_OPCODE:
   9230 	    case RELAX_DESIRE_ALIGN:
   9231 	      *fragPP = fragP;
   9232 	      return address;
   9233 
   9234 	    case RELAX_MAYBE_UNREACHABLE:
   9235 	    case RELAX_MAYBE_DESIRE_ALIGN:
   9236 	      /* Do nothing.  */
   9237 	      break;
   9238 
   9239 	    default:
   9240 	      /* Just punt if we don't know the type.  */
   9241 	      *fragPP = fragP;
   9242 	      return 0;
   9243 	    }
   9244 	}
   9245       else
   9246 	{
   9247 	  /* Just punt if we don't know the type.  */
   9248 	  *fragPP = fragP;
   9249 	  return 0;
   9250 	}
   9251       fragP = fragP->fr_next;
   9252     }
   9253 
   9254   *fragPP = fragP;
   9255   return 0;
   9256 }
   9257 
   9258 
   9259 static long bytes_to_stretch (fragS *, int, int, int, int);
   9260 
   9261 static long
   9262 future_alignment_required (fragS *fragP, long stretch ATTRIBUTE_UNUSED)
   9263 {
   9264   fragS *this_frag = fragP;
   9265   long address;
   9266   int num_widens = 0;
   9267   int wide_nops = 0;
   9268   int narrow_nops = 0;
   9269   bfd_boolean paddable = FALSE;
   9270   offsetT local_opt_diff;
   9271   offsetT opt_diff;
   9272   offsetT max_diff;
   9273   int stretch_amount = 0;
   9274   int local_stretch_amount;
   9275   int global_stretch_amount;
   9276 
   9277   address = find_address_of_next_align_frag
   9278     (&fragP, &wide_nops, &narrow_nops, &num_widens, &paddable);
   9279 
   9280   if (!address)
   9281     {
   9282       if (this_frag->tc_frag_data.is_aligning_branch)
   9283 	this_frag->tc_frag_data.slot_subtypes[0] = RELAX_IMMED;
   9284       else
   9285 	frag_wane (this_frag);
   9286     }
   9287   else
   9288     {
   9289       local_opt_diff = get_aligned_diff (fragP, address, &max_diff);
   9290       opt_diff = local_opt_diff;
   9291       gas_assert (opt_diff >= 0);
   9292       gas_assert (max_diff >= opt_diff);
   9293       if (max_diff == 0)
   9294 	return 0;
   9295 
   9296       if (fragP)
   9297 	fragP = fragP->fr_next;
   9298 
   9299       while (fragP && opt_diff < max_diff && address)
   9300 	{
   9301 	  /* We only use these to determine if we can exit early
   9302 	     because there will be plenty of ways to align future
   9303 	     align frags.  */
   9304 	  int glob_widens = 0;
   9305 	  int dnn = 0;
   9306 	  int dw = 0;
   9307 	  bfd_boolean glob_pad = 0;
   9308 	  address = find_address_of_next_align_frag
   9309 	    (&fragP, &glob_widens, &dnn, &dw, &glob_pad);
   9310 	  /* If there is a padable portion, then skip.  */
   9311 	  if (glob_pad || glob_widens >= (1 << branch_align_power (now_seg)))
   9312 	    address = 0;
   9313 
   9314 	  if (address)
   9315 	    {
   9316 	      offsetT next_m_diff;
   9317 	      offsetT next_o_diff;
   9318 
   9319 	      /* Downrange frags haven't had stretch added to them yet.  */
   9320 	      address += stretch;
   9321 
   9322 	      /* The address also includes any text expansion from this
   9323 		 frag in a previous pass, but we don't want that.  */
   9324 	      address -= this_frag->tc_frag_data.text_expansion[0];
   9325 
   9326 	      /* Assume we are going to move at least opt_diff.  In
   9327 		 reality, we might not be able to, but assuming that
   9328 		 we will helps catch cases where moving opt_diff pushes
   9329 		 the next target from aligned to unaligned.  */
   9330 	      address += opt_diff;
   9331 
   9332 	      next_o_diff = get_aligned_diff (fragP, address, &next_m_diff);
   9333 
   9334 	      /* Now cleanup for the adjustments to address.  */
   9335 	      next_o_diff += opt_diff;
   9336 	      next_m_diff += opt_diff;
   9337 	      if (next_o_diff <= max_diff && next_o_diff > opt_diff)
   9338 		opt_diff = next_o_diff;
   9339 	      if (next_m_diff < max_diff)
   9340 		max_diff = next_m_diff;
   9341 	      fragP = fragP->fr_next;
   9342 	    }
   9343 	}
   9344 
   9345       /* If there are enough wideners in between, do it.  */
   9346       if (paddable)
   9347 	{
   9348 	  if (this_frag->fr_subtype == RELAX_UNREACHABLE)
   9349 	    {
   9350 	      gas_assert (opt_diff <= (signed) xtensa_fetch_width);
   9351 	      return opt_diff;
   9352 	    }
   9353 	  return 0;
   9354 	}
   9355       local_stretch_amount
   9356 	= bytes_to_stretch (this_frag, wide_nops, narrow_nops,
   9357 			    num_widens, local_opt_diff);
   9358       global_stretch_amount
   9359 	= bytes_to_stretch (this_frag, wide_nops, narrow_nops,
   9360 			    num_widens, opt_diff);
   9361       /* If the condition below is true, then the frag couldn't
   9362 	 stretch the correct amount for the global case, so we just
   9363 	 optimize locally.  We'll rely on the subsequent frags to get
   9364 	 the correct alignment in the global case.  */
   9365       if (global_stretch_amount < local_stretch_amount)
   9366 	stretch_amount = local_stretch_amount;
   9367       else
   9368 	stretch_amount = global_stretch_amount;
   9369 
   9370       if (this_frag->fr_subtype == RELAX_SLOTS
   9371 	  && this_frag->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
   9372 	gas_assert (stretch_amount <= 1);
   9373       else if (this_frag->fr_subtype == RELAX_FILL_NOP)
   9374 	{
   9375 	  if (this_frag->tc_frag_data.is_no_density)
   9376 	    gas_assert (stretch_amount == 3 || stretch_amount == 0);
   9377 	  else
   9378 	    gas_assert (stretch_amount <= 3);
   9379 	}
   9380     }
   9381   return stretch_amount;
   9382 }
   9383 
   9384 
   9385 /* The idea: widen everything you can to get a target or loop aligned,
   9386    then start using NOPs.
   9387 
   9388    wide_nops   = the number of wide NOPs available for aligning
   9389    narrow_nops = the number of narrow NOPs available for aligning
   9390 		 (a subset of wide_nops)
   9391    widens      = the number of narrow instructions that should be widened
   9392 
   9393 */
   9394 
   9395 static long
   9396 bytes_to_stretch (fragS *this_frag,
   9397 		  int wide_nops,
   9398 		  int narrow_nops,
   9399 		  int num_widens,
   9400 		  int desired_diff)
   9401 {
   9402   int nops_needed;
   9403   int nop_bytes;
   9404   int extra_bytes;
   9405   int bytes_short = desired_diff - num_widens;
   9406 
   9407   gas_assert (desired_diff >= 0
   9408 	      && desired_diff < (signed) xtensa_fetch_width);
   9409   if (desired_diff == 0)
   9410     return 0;
   9411 
   9412   gas_assert (wide_nops > 0 || num_widens > 0);
   9413 
   9414   /* Always prefer widening to NOP-filling.  */
   9415   if (bytes_short < 0)
   9416     {
   9417       /* There are enough RELAX_NARROW frags after this one
   9418 	 to align the target without widening this frag in any way.  */
   9419       return 0;
   9420     }
   9421 
   9422   if (bytes_short == 0)
   9423     {
   9424       /* Widen every narrow between here and the align target
   9425 	 and the align target will be properly aligned.  */
   9426       if (this_frag->fr_subtype == RELAX_FILL_NOP)
   9427 	return 0;
   9428       else
   9429 	return 1;
   9430     }
   9431 
   9432   /* From here we will need at least one NOP to get an alignment.
   9433      However, we may not be able to align at all, in which case,
   9434      don't widen.  */
   9435   nops_needed = desired_diff / 3;
   9436 
   9437   /* If there aren't enough nops, don't widen.  */
   9438   if (nops_needed > wide_nops)
   9439     return 0;
   9440 
   9441   /* First try it with all wide nops.  */
   9442   nop_bytes = nops_needed * 3;
   9443   extra_bytes = desired_diff - nop_bytes;
   9444 
   9445   if (nop_bytes + num_widens >= desired_diff)
   9446     {
   9447       if (this_frag->fr_subtype == RELAX_FILL_NOP)
   9448 	return 3;
   9449       else if (num_widens == extra_bytes)
   9450 	return 1;
   9451       return 0;
   9452     }
   9453 
   9454   /* Add a narrow nop.  */
   9455   nops_needed++;
   9456   nop_bytes += 2;
   9457   extra_bytes -= 2;
   9458   if (narrow_nops == 0 || nops_needed > wide_nops)
   9459     return 0;
   9460 
   9461   if (nop_bytes + num_widens >= desired_diff && extra_bytes >= 0)
   9462     {
   9463       if (this_frag->fr_subtype == RELAX_FILL_NOP)
   9464 	return !this_frag->tc_frag_data.is_no_density ? 2 : 3;
   9465       else if (num_widens == extra_bytes)
   9466 	return 1;
   9467       return 0;
   9468     }
   9469 
   9470   /* Replace a wide nop with a narrow nop--we can get here if
   9471      extra_bytes was negative in the previous conditional.  */
   9472   if (narrow_nops == 1)
   9473     return 0;
   9474   nop_bytes--;
   9475   extra_bytes++;
   9476   if (nop_bytes + num_widens >= desired_diff)
   9477     {
   9478       if (this_frag->fr_subtype == RELAX_FILL_NOP)
   9479 	return !this_frag->tc_frag_data.is_no_density ? 2 : 3;
   9480       else if (num_widens == extra_bytes)
   9481 	return 1;
   9482       return 0;
   9483     }
   9484 
   9485   /* If we can't satisfy any of the above cases, then we can't align
   9486      using padding or fill nops.  */
   9487   return 0;
   9488 }
   9489 
   9490 
   9491 static struct trampoline_frag *
   9492 search_trampolines (TInsn *tinsn, fragS *fragP, bfd_boolean unreachable_only)
   9493 {
   9494   struct trampoline_seg *ts = find_trampoline_seg (now_seg);
   9495   struct trampoline_frag *tf = (ts) ? ts->trampoline_list.next : NULL;
   9496   struct trampoline_frag *best_tf = NULL;
   9497   int best_delta = 0;
   9498   int best_addr = 0;
   9499   symbolS *sym = tinsn->tok[0].X_add_symbol;
   9500   offsetT target = S_GET_VALUE (sym) + tinsn->tok[0].X_add_number;
   9501   offsetT addr = fragP->fr_address;
   9502   offsetT lower = (addr < target) ? addr : target;
   9503   offsetT upper = (addr > target) ? addr : target;
   9504   int delta = upper - lower;
   9505   offsetT midpoint = lower + delta / 2;
   9506   int this_delta = -1;
   9507   int this_addr = -1;
   9508 
   9509   if (delta > 2 * J_RANGE)
   9510     {
   9511       /* One trampoline won't do; we need multiple.
   9512 	 Choose the farthest trampoline that's still in range of the original
   9513 	 and let a later pass finish the job.  */
   9514       for ( ; tf; tf = tf->next)
   9515 	{
   9516 	  int next_addr = (tf->next) ? tf->next->fragP->fr_address + tf->next->fragP->fr_fix : 0;
   9517 
   9518 	  this_addr = tf->fragP->fr_address + tf->fragP->fr_fix;
   9519 	  if (lower == addr)
   9520 	    {
   9521 	      /* Forward jump.  */
   9522 	      if (this_addr - addr < J_RANGE)
   9523 		break;
   9524 	    }
   9525 	  else
   9526 	    {
   9527 	      /* Backward jump.  */
   9528 	      if (next_addr == 0 || addr - next_addr > J_RANGE)
   9529 		break;
   9530 	    }
   9531 	  if (abs (addr - this_addr) < J_RANGE)
   9532 	    return tf;
   9533 
   9534 	  return NULL;
   9535 	}
   9536     }
   9537   for ( ; tf; tf = tf->next)
   9538     {
   9539       this_addr = tf->fragP->fr_address + tf->fragP->fr_fix;
   9540       this_delta = abs (this_addr - midpoint);
   9541       if (unreachable_only && tf->needs_jump_around)
   9542 	continue;
   9543       if (!best_tf || this_delta < best_delta)
   9544         {
   9545 	  best_tf = tf;
   9546 	  best_delta = this_delta;
   9547 	  best_addr = this_addr;
   9548         }
   9549     }
   9550 
   9551   if (best_tf &&
   9552       best_delta < J_RANGE &&
   9553       abs(best_addr - lower) < J_RANGE &&
   9554       abs(best_addr - upper) < J_RANGE)
   9555     return best_tf;
   9556 
   9557   return NULL; /* No suitable trampoline found.  */
   9558 }
   9559 
   9560 
   9561 static struct trampoline_frag *
   9562 get_best_trampoline (TInsn *tinsn, fragS *fragP)
   9563 {
   9564   struct trampoline_frag *tf = NULL;
   9565 
   9566   tf = search_trampolines (tinsn, fragP, TRUE); /* Try unreachable first.  */
   9567 
   9568   if (tf == NULL)
   9569     tf = search_trampolines (tinsn, fragP, FALSE); /* Try ones needing a jump-around, too.  */
   9570 
   9571   return tf;
   9572 }
   9573 
   9574 
   9575 static void
   9576 check_and_update_trampolines (void)
   9577 {
   9578   struct trampoline_seg *ts = find_trampoline_seg (now_seg);
   9579   struct trampoline_frag *tf = ts->trampoline_list.next;
   9580   struct trampoline_frag *prev = &ts->trampoline_list;
   9581 
   9582   for ( ; tf; prev = tf, tf = tf->next)
   9583     {
   9584       if (tf->fragP->fr_var < 3)
   9585 	{
   9586 	  frag_wane (tf->fragP);
   9587 	  prev->next = tf->next;
   9588 	  tf->fragP = NULL;
   9589 	}
   9590     }
   9591 }
   9592 
   9593 
   9594 static int
   9595 init_trampoline_frag (struct trampoline_frag *trampP)
   9596 {
   9597   fragS *fp = trampP->fragP;
   9598   int growth = 0;
   9599 
   9600   if (fp->fr_fix == 0)
   9601     {
   9602       symbolS *lsym;
   9603       char label[10 + 2 * sizeof(fp)];
   9604       sprintf (label, ".L0_TR_%p", fp);
   9605 
   9606       lsym = (symbolS *)local_symbol_make (label, now_seg, 0, fp);
   9607       fp->fr_symbol = lsym;
   9608       if (trampP->needs_jump_around)
   9609         {
   9610 	  /* Add a jump around this block of jumps, in case
   9611 	     control flows into this block.  */
   9612 	  fixS *fixP;
   9613 	  TInsn insn;
   9614 	  xtensa_format fmt;
   9615 	  xtensa_isa isa = xtensa_default_isa;
   9616 
   9617 	  fp->tc_frag_data.is_insn = 1;
   9618 	  /* Assemble a jump insn.  */
   9619 	  tinsn_init (&insn);
   9620 	  insn.insn_type = ITYPE_INSN;
   9621 	  insn.opcode = xtensa_j_opcode;
   9622 	  insn.ntok = 1;
   9623 	  set_expr_symbol_offset (&insn.tok[0], lsym, 3);
   9624 	  fmt = xg_get_single_format (xtensa_j_opcode);
   9625 	  tinsn_to_slotbuf (fmt, 0, &insn, trampoline_slotbuf);
   9626 	  xtensa_format_set_slot (isa, fmt, 0, trampoline_buf, trampoline_slotbuf);
   9627 	  xtensa_insnbuf_to_chars (isa, trampoline_buf, (unsigned char *)fp->fr_literal, 3);
   9628 	  fp->fr_fix += 3;
   9629 	  fp->fr_var -= 3;
   9630 	  growth = 3;
   9631 	  fixP = fix_new (fp, 0, 3, lsym, 3, TRUE, BFD_RELOC_XTENSA_SLOT0_OP);
   9632 	  trampP->fixP = fixP;
   9633         }
   9634     }
   9635   return growth;
   9636 }
   9637 
   9638 
   9639 static int
   9640 add_jump_to_trampoline (struct trampoline_frag *trampP, fragS *origfrag)
   9641 {
   9642   fragS *tramp = trampP->fragP;
   9643   fixS *fixP;
   9644   int offset = tramp->fr_fix; /* Where to assemble the j insn.  */
   9645   TInsn insn;
   9646   symbolS *lsym;
   9647   symbolS *tsym;
   9648   int toffset;
   9649   xtensa_format fmt;
   9650   xtensa_isa isa = xtensa_default_isa;
   9651   int growth = 0;
   9652 
   9653   lsym = tramp->fr_symbol;
   9654   /* Assemble a jump to the target label in the trampoline frag.  */
   9655   tsym = origfrag->tc_frag_data.slot_symbols[0];
   9656   toffset = origfrag-> tc_frag_data.slot_offsets[0];
   9657   tinsn_init (&insn);
   9658   insn.insn_type = ITYPE_INSN;
   9659   insn.opcode = xtensa_j_opcode;
   9660   insn.ntok = 1;
   9661   set_expr_symbol_offset (&insn.tok[0], tsym, toffset);
   9662   fmt = xg_get_single_format (xtensa_j_opcode);
   9663   tinsn_to_slotbuf (fmt, 0, &insn, trampoline_slotbuf);
   9664   xtensa_format_set_slot (isa, fmt, 0, trampoline_buf, trampoline_slotbuf);
   9665   xtensa_insnbuf_to_chars (isa, trampoline_buf, (unsigned char *)tramp->fr_literal + offset, 3);
   9666   tramp->fr_fix += 3;
   9667   tramp->fr_var -= 3;
   9668   growth = 3;
   9669   /* add a fix-up for the trampoline jump.  */
   9670   fixP = fix_new (tramp, tramp->fr_fix - 3, 3, tsym, toffset, TRUE, BFD_RELOC_XTENSA_SLOT0_OP);
   9671   /* Modify the jump at the start of this trampoline to point past the newly-added jump.  */
   9672   fixP = trampP->fixP;
   9673   if (fixP)
   9674     fixP->fx_offset += 3;
   9675   /* Modify the original j to point here.  */
   9676   origfrag->tc_frag_data.slot_symbols[0] = lsym;
   9677   origfrag->tc_frag_data.slot_offsets[0] = tramp->fr_fix - 3;
   9678   /* If trampoline is full, remove it from the list.  */
   9679   check_and_update_trampolines ();
   9680 
   9681   return growth;
   9682 }
   9683 
   9684 
   9685 static long
   9686 relax_frag_immed (segT segP,
   9687 		  fragS *fragP,
   9688 		  long stretch,
   9689 		  int min_steps,
   9690 		  xtensa_format fmt,
   9691 		  int slot,
   9692 		  int *stretched_p,
   9693 		  bfd_boolean estimate_only)
   9694 {
   9695   TInsn tinsn;
   9696   int old_size;
   9697   bfd_boolean negatable_branch = FALSE;
   9698   bfd_boolean branch_jmp_to_next = FALSE;
   9699   bfd_boolean from_wide_insn = FALSE;
   9700   xtensa_isa isa = xtensa_default_isa;
   9701   IStack istack;
   9702   offsetT frag_offset;
   9703   int num_steps;
   9704   int num_text_bytes, num_literal_bytes;
   9705   int literal_diff, total_text_diff, this_text_diff;
   9706 
   9707   gas_assert (fragP->fr_opcode != NULL);
   9708 
   9709   xg_clear_vinsn (&cur_vinsn);
   9710   vinsn_from_chars (&cur_vinsn, fragP->fr_opcode);
   9711   if (cur_vinsn.num_slots > 1)
   9712     from_wide_insn = TRUE;
   9713 
   9714   tinsn = cur_vinsn.slots[slot];
   9715   tinsn_immed_from_frag (&tinsn, fragP, slot);
   9716 
   9717   if (estimate_only && xtensa_opcode_is_loop (isa, tinsn.opcode) == 1)
   9718     return 0;
   9719 
   9720   if (workaround_b_j_loop_end && ! fragP->tc_frag_data.is_no_transform)
   9721     branch_jmp_to_next = is_branch_jmp_to_next (&tinsn, fragP);
   9722 
   9723   negatable_branch = (xtensa_opcode_is_branch (isa, tinsn.opcode) == 1);
   9724 
   9725   old_size = xtensa_format_length (isa, fmt);
   9726 
   9727   /* Special case: replace a branch to the next instruction with a NOP.
   9728      This is required to work around a hardware bug in T1040.0 and also
   9729      serves as an optimization.  */
   9730 
   9731   if (branch_jmp_to_next
   9732       && ((old_size == 2) || (old_size == 3))
   9733       && !next_frag_is_loop_target (fragP))
   9734     return 0;
   9735 
   9736   /* Here is the fun stuff: Get the immediate field from this
   9737      instruction.  If it fits, we are done.  If not, find the next
   9738      instruction sequence that fits.  */
   9739 
   9740   frag_offset = fragP->fr_opcode - fragP->fr_literal;
   9741   istack_init (&istack);
   9742   num_steps = xg_assembly_relax (&istack, &tinsn, segP, fragP, frag_offset,
   9743 				 min_steps, stretch);
   9744   gas_assert (num_steps >= min_steps && num_steps <= RELAX_IMMED_MAXSTEPS);
   9745 
   9746   fragP->tc_frag_data.slot_subtypes[slot] = (int) RELAX_IMMED + num_steps;
   9747 
   9748   /* Figure out the number of bytes needed.  */
   9749   num_literal_bytes = get_num_stack_literal_bytes (&istack);
   9750   literal_diff
   9751     = num_literal_bytes - fragP->tc_frag_data.literal_expansion[slot];
   9752   num_text_bytes = get_num_stack_text_bytes (&istack);
   9753 
   9754   if (from_wide_insn)
   9755     {
   9756       int first = 0;
   9757       while (istack.insn[first].opcode == XTENSA_UNDEFINED)
   9758 	first++;
   9759 
   9760       num_text_bytes += old_size;
   9761       if (opcode_fits_format_slot (istack.insn[first].opcode, fmt, slot))
   9762 	num_text_bytes -= xg_get_single_size (istack.insn[first].opcode);
   9763       else
   9764 	{
   9765 	  /* The first instruction in the relaxed sequence will go after
   9766 	     the current wide instruction, and thus its symbolic immediates
   9767 	     might not fit.  */
   9768 
   9769 	  istack_init (&istack);
   9770 	  num_steps = xg_assembly_relax (&istack, &tinsn, segP, fragP,
   9771 					 frag_offset + old_size,
   9772 					 min_steps, stretch + old_size);
   9773 	  gas_assert (num_steps >= min_steps && num_steps <= RELAX_IMMED_MAXSTEPS);
   9774 
   9775 	  fragP->tc_frag_data.slot_subtypes[slot]
   9776 	    = (int) RELAX_IMMED + num_steps;
   9777 
   9778 	  num_literal_bytes = get_num_stack_literal_bytes (&istack);
   9779 	  literal_diff
   9780 	    = num_literal_bytes - fragP->tc_frag_data.literal_expansion[slot];
   9781 
   9782 	  num_text_bytes = get_num_stack_text_bytes (&istack) + old_size;
   9783 	}
   9784     }
   9785 
   9786   total_text_diff = num_text_bytes - old_size;
   9787   this_text_diff = total_text_diff - fragP->tc_frag_data.text_expansion[slot];
   9788 
   9789   /* It MUST get larger.  If not, we could get an infinite loop.  */
   9790   gas_assert (num_text_bytes >= 0);
   9791   gas_assert (literal_diff >= 0);
   9792   gas_assert (total_text_diff >= 0);
   9793 
   9794   fragP->tc_frag_data.text_expansion[slot] = total_text_diff;
   9795   fragP->tc_frag_data.literal_expansion[slot] = num_literal_bytes;
   9796   gas_assert (fragP->tc_frag_data.text_expansion[slot] >= 0);
   9797   gas_assert (fragP->tc_frag_data.literal_expansion[slot] >= 0);
   9798 
   9799   /* Find the associated expandable literal for this.  */
   9800   if (literal_diff != 0)
   9801     {
   9802       fragS *lit_fragP = fragP->tc_frag_data.literal_frags[slot];
   9803       if (lit_fragP)
   9804 	{
   9805 	  gas_assert (literal_diff == 4);
   9806 	  lit_fragP->tc_frag_data.unreported_expansion += literal_diff;
   9807 
   9808 	  /* We expect that the literal section state has NOT been
   9809 	     modified yet.  */
   9810 	  gas_assert (lit_fragP->fr_type == rs_machine_dependent
   9811 		  && lit_fragP->fr_subtype == RELAX_LITERAL);
   9812 	  lit_fragP->fr_subtype = RELAX_LITERAL_NR;
   9813 
   9814 	  /* We need to mark this section for another iteration
   9815 	     of relaxation.  */
   9816 	  (*stretched_p)++;
   9817 	}
   9818     }
   9819 
   9820   if (negatable_branch && istack.ninsn > 1)
   9821     update_next_frag_state (fragP);
   9822 
   9823   /* If last insn is a jump, and it cannot reach its target, try to find a trampoline.  */
   9824   if (istack.ninsn > 2 &&
   9825       istack.insn[istack.ninsn - 1].insn_type == ITYPE_LABEL &&
   9826       istack.insn[istack.ninsn - 2].insn_type == ITYPE_INSN &&
   9827       istack.insn[istack.ninsn - 2].opcode == xtensa_j_opcode)
   9828     {
   9829       TInsn *jinsn = &istack.insn[istack.ninsn - 2];
   9830 
   9831       if (!xg_symbolic_immeds_fit (jinsn, segP, fragP, fragP->fr_offset, total_text_diff))
   9832 	{
   9833 	  struct trampoline_frag *tf = get_best_trampoline (jinsn, fragP);
   9834 
   9835 	  if (tf)
   9836 	    {
   9837 	      this_text_diff += init_trampoline_frag (tf);
   9838 	      this_text_diff += add_jump_to_trampoline (tf, fragP);
   9839 	    }
   9840 	  else
   9841 	    {
   9842 	      /* If target symbol is undefined, assume it will reach once linked.  */
   9843 	      expressionS *exp = &istack.insn[istack.ninsn - 2].tok[0];
   9844 
   9845 	      if (exp->X_op == O_symbol && S_IS_DEFINED (exp->X_add_symbol))
   9846 		{
   9847 		  as_bad_where (fragP->fr_file, fragP->fr_line,
   9848 		    _("jump target out of range; no usable trampoline found"));
   9849 		}
   9850 	    }
   9851 	}
   9852     }
   9853 
   9854   return this_text_diff;
   9855 }
   9856 
   9857 
   9858 /* md_convert_frag Hook and Helper Functions.  */
   9860 
   9861 static void convert_frag_align_next_opcode (fragS *);
   9862 static void convert_frag_narrow (segT, fragS *, xtensa_format, int);
   9863 static void convert_frag_fill_nop (fragS *);
   9864 static void convert_frag_immed (segT, fragS *, int, xtensa_format, int);
   9865 
   9866 void
   9867 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT sec, fragS *fragp)
   9868 {
   9869   static xtensa_insnbuf vbuf = NULL;
   9870   xtensa_isa isa = xtensa_default_isa;
   9871   int slot;
   9872   int num_slots;
   9873   xtensa_format fmt;
   9874   char *file_name;
   9875   unsigned line;
   9876 
   9877   as_where (&file_name, &line);
   9878   new_logical_line (fragp->fr_file, fragp->fr_line);
   9879 
   9880   switch (fragp->fr_subtype)
   9881     {
   9882     case RELAX_ALIGN_NEXT_OPCODE:
   9883       /* Always convert.  */
   9884       convert_frag_align_next_opcode (fragp);
   9885       break;
   9886 
   9887     case RELAX_DESIRE_ALIGN:
   9888       /* Do nothing.  If not aligned already, too bad.  */
   9889       break;
   9890 
   9891     case RELAX_LITERAL:
   9892     case RELAX_LITERAL_FINAL:
   9893       break;
   9894 
   9895     case RELAX_SLOTS:
   9896       if (vbuf == NULL)
   9897 	vbuf = xtensa_insnbuf_alloc (isa);
   9898 
   9899       xtensa_insnbuf_from_chars
   9900 	(isa, vbuf, (unsigned char *) fragp->fr_opcode, 0);
   9901       fmt = xtensa_format_decode (isa, vbuf);
   9902       num_slots = xtensa_format_num_slots (isa, fmt);
   9903 
   9904       for (slot = 0; slot < num_slots; slot++)
   9905 	{
   9906 	  switch (fragp->tc_frag_data.slot_subtypes[slot])
   9907 	    {
   9908 	    case RELAX_NARROW:
   9909 	      convert_frag_narrow (sec, fragp, fmt, slot);
   9910 	      break;
   9911 
   9912 	    case RELAX_IMMED:
   9913 	    case RELAX_IMMED_STEP1:
   9914 	    case RELAX_IMMED_STEP2:
   9915 	    case RELAX_IMMED_STEP3:
   9916 	      /* Place the immediate.  */
   9917 	      convert_frag_immed
   9918 		(sec, fragp,
   9919 		 fragp->tc_frag_data.slot_subtypes[slot] - RELAX_IMMED,
   9920 		 fmt, slot);
   9921 	      break;
   9922 
   9923 	    default:
   9924 	      /* This is OK because some slots could have
   9925 		 relaxations and others have none.  */
   9926 	      break;
   9927 	    }
   9928 	}
   9929       break;
   9930 
   9931     case RELAX_UNREACHABLE:
   9932       memset (&fragp->fr_literal[fragp->fr_fix], 0, fragp->fr_var);
   9933       fragp->fr_fix += fragp->tc_frag_data.text_expansion[0];
   9934       fragp->fr_var -= fragp->tc_frag_data.text_expansion[0];
   9935       frag_wane (fragp);
   9936       break;
   9937 
   9938     case RELAX_MAYBE_UNREACHABLE:
   9939     case RELAX_MAYBE_DESIRE_ALIGN:
   9940       frag_wane (fragp);
   9941       break;
   9942 
   9943     case RELAX_FILL_NOP:
   9944       convert_frag_fill_nop (fragp);
   9945       break;
   9946 
   9947     case RELAX_LITERAL_NR:
   9948       if (use_literal_section)
   9949 	{
   9950 	  /* This should have been handled during relaxation.  When
   9951 	     relaxing a code segment, literals sometimes need to be
   9952 	     added to the corresponding literal segment.  If that
   9953 	     literal segment has already been relaxed, then we end up
   9954 	     in this situation.  Marking the literal segments as data
   9955 	     would make this happen less often (since GAS always relaxes
   9956 	     code before data), but we could still get into trouble if
   9957 	     there are instructions in a segment that is not marked as
   9958 	     containing code.  Until we can implement a better solution,
   9959 	     cheat and adjust the addresses of all the following frags.
   9960 	     This could break subsequent alignments, but the linker's
   9961 	     literal coalescing will do that anyway.  */
   9962 
   9963 	  fragS *f;
   9964 	  fragp->fr_subtype = RELAX_LITERAL_FINAL;
   9965 	  gas_assert (fragp->tc_frag_data.unreported_expansion == 4);
   9966 	  memset (&fragp->fr_literal[fragp->fr_fix], 0, 4);
   9967 	  fragp->fr_var -= 4;
   9968 	  fragp->fr_fix += 4;
   9969 	  for (f = fragp->fr_next; f; f = f->fr_next)
   9970 	    f->fr_address += 4;
   9971 	}
   9972       else
   9973 	as_bad (_("invalid relaxation fragment result"));
   9974       break;
   9975 
   9976     case RELAX_TRAMPOLINE:
   9977       break;
   9978     }
   9979 
   9980   fragp->fr_var = 0;
   9981   new_logical_line (file_name, line);
   9982 }
   9983 
   9984 
   9985 static void
   9986 convert_frag_align_next_opcode (fragS *fragp)
   9987 {
   9988   char *nop_buf;		/* Location for Writing.  */
   9989   bfd_boolean use_no_density = fragp->tc_frag_data.is_no_density;
   9990   addressT aligned_address;
   9991   offsetT fill_size;
   9992   int nop, nop_count;
   9993 
   9994   aligned_address = get_noop_aligned_address (fragp, fragp->fr_address +
   9995 					      fragp->fr_fix);
   9996   fill_size = aligned_address - (fragp->fr_address + fragp->fr_fix);
   9997   nop_count = get_text_align_nop_count (fill_size, use_no_density);
   9998   nop_buf = fragp->fr_literal + fragp->fr_fix;
   9999 
   10000   for (nop = 0; nop < nop_count; nop++)
   10001     {
   10002       int nop_size;
   10003       nop_size = get_text_align_nth_nop_size (fill_size, nop, use_no_density);
   10004 
   10005       assemble_nop (nop_size, nop_buf);
   10006       nop_buf += nop_size;
   10007     }
   10008 
   10009   fragp->fr_fix += fill_size;
   10010   fragp->fr_var -= fill_size;
   10011 }
   10012 
   10013 
   10014 static void
   10015 convert_frag_narrow (segT segP, fragS *fragP, xtensa_format fmt, int slot)
   10016 {
   10017   TInsn tinsn, single_target;
   10018   int size, old_size, diff;
   10019   offsetT frag_offset;
   10020 
   10021   gas_assert (slot == 0);
   10022   tinsn_from_chars (&tinsn, fragP->fr_opcode, 0);
   10023 
   10024   if (fragP->tc_frag_data.is_aligning_branch == 1)
   10025     {
   10026       gas_assert (fragP->tc_frag_data.text_expansion[0] == 1
   10027 	      || fragP->tc_frag_data.text_expansion[0] == 0);
   10028       convert_frag_immed (segP, fragP, fragP->tc_frag_data.text_expansion[0],
   10029 			  fmt, slot);
   10030       return;
   10031     }
   10032 
   10033   if (fragP->tc_frag_data.text_expansion[0] == 0)
   10034     {
   10035       /* No conversion.  */
   10036       fragP->fr_var = 0;
   10037       return;
   10038     }
   10039 
   10040   gas_assert (fragP->fr_opcode != NULL);
   10041 
   10042   /* Frags in this relaxation state should only contain
   10043      single instruction bundles.  */
   10044   tinsn_immed_from_frag (&tinsn, fragP, 0);
   10045 
   10046   /* Just convert it to a wide form....  */
   10047   size = 0;
   10048   old_size = xg_get_single_size (tinsn.opcode);
   10049 
   10050   tinsn_init (&single_target);
   10051   frag_offset = fragP->fr_opcode - fragP->fr_literal;
   10052 
   10053   if (! xg_is_single_relaxable_insn (&tinsn, &single_target, FALSE))
   10054     {
   10055       as_bad (_("unable to widen instruction"));
   10056       return;
   10057     }
   10058 
   10059   size = xg_get_single_size (single_target.opcode);
   10060   xg_emit_insn_to_buf (&single_target, fragP->fr_opcode, fragP,
   10061 		       frag_offset, TRUE);
   10062 
   10063   diff = size - old_size;
   10064   gas_assert (diff >= 0);
   10065   gas_assert (diff <= fragP->fr_var);
   10066   fragP->fr_var -= diff;
   10067   fragP->fr_fix += diff;
   10068 
   10069   /* clean it up */
   10070   fragP->fr_var = 0;
   10071 }
   10072 
   10073 
   10074 static void
   10075 convert_frag_fill_nop (fragS *fragP)
   10076 {
   10077   char *loc = &fragP->fr_literal[fragP->fr_fix];
   10078   int size = fragP->tc_frag_data.text_expansion[0];
   10079   gas_assert ((unsigned) size == (fragP->fr_next->fr_address
   10080 			      - fragP->fr_address - fragP->fr_fix));
   10081   if (size == 0)
   10082     {
   10083       /* No conversion.  */
   10084       fragP->fr_var = 0;
   10085       return;
   10086     }
   10087   assemble_nop (size, loc);
   10088   fragP->tc_frag_data.is_insn = TRUE;
   10089   fragP->fr_var -= size;
   10090   fragP->fr_fix += size;
   10091   frag_wane (fragP);
   10092 }
   10093 
   10094 
   10095 static fixS *fix_new_exp_in_seg
   10096   (segT, subsegT, fragS *, int, int, expressionS *, int,
   10097    bfd_reloc_code_real_type);
   10098 static void convert_frag_immed_finish_loop (segT, fragS *, TInsn *);
   10099 
   10100 static void
   10101 convert_frag_immed (segT segP,
   10102 		    fragS *fragP,
   10103 		    int min_steps,
   10104 		    xtensa_format fmt,
   10105 		    int slot)
   10106 {
   10107   char *immed_instr = fragP->fr_opcode;
   10108   TInsn orig_tinsn;
   10109   bfd_boolean expanded = FALSE;
   10110   bfd_boolean branch_jmp_to_next = FALSE;
   10111   char *fr_opcode = fragP->fr_opcode;
   10112   xtensa_isa isa = xtensa_default_isa;
   10113   bfd_boolean from_wide_insn = FALSE;
   10114   int bytes;
   10115   bfd_boolean is_loop;
   10116 
   10117   gas_assert (fr_opcode != NULL);
   10118 
   10119   xg_clear_vinsn (&cur_vinsn);
   10120 
   10121   vinsn_from_chars (&cur_vinsn, fr_opcode);
   10122   if (cur_vinsn.num_slots > 1)
   10123     from_wide_insn = TRUE;
   10124 
   10125   orig_tinsn = cur_vinsn.slots[slot];
   10126   tinsn_immed_from_frag (&orig_tinsn, fragP, slot);
   10127 
   10128   is_loop = xtensa_opcode_is_loop (xtensa_default_isa, orig_tinsn.opcode) == 1;
   10129 
   10130   if (workaround_b_j_loop_end && ! fragP->tc_frag_data.is_no_transform)
   10131     branch_jmp_to_next = is_branch_jmp_to_next (&orig_tinsn, fragP);
   10132 
   10133   if (branch_jmp_to_next && !next_frag_is_loop_target (fragP))
   10134     {
   10135       /* Conversion just inserts a NOP and marks the fix as completed.  */
   10136       bytes = xtensa_format_length (isa, fmt);
   10137       if (bytes >= 4)
   10138 	{
   10139 	  cur_vinsn.slots[slot].opcode =
   10140 	    xtensa_format_slot_nop_opcode (isa, cur_vinsn.format, slot);
   10141 	  cur_vinsn.slots[slot].ntok = 0;
   10142 	}
   10143       else
   10144 	{
   10145 	  bytes += fragP->tc_frag_data.text_expansion[0];
   10146 	  gas_assert (bytes == 2 || bytes == 3);
   10147 	  build_nop (&cur_vinsn.slots[0], bytes);
   10148 	  fragP->fr_fix += fragP->tc_frag_data.text_expansion[0];
   10149 	}
   10150       vinsn_to_insnbuf (&cur_vinsn, fr_opcode, frag_now, TRUE);
   10151       xtensa_insnbuf_to_chars
   10152 	(isa, cur_vinsn.insnbuf, (unsigned char *) fr_opcode, 0);
   10153       fragP->fr_var = 0;
   10154     }
   10155   else
   10156     {
   10157       /* Here is the fun stuff:  Get the immediate field from this
   10158 	 instruction.  If it fits, we're done.  If not, find the next
   10159 	 instruction sequence that fits.  */
   10160 
   10161       IStack istack;
   10162       int i;
   10163       symbolS *lit_sym = NULL;
   10164       int total_size = 0;
   10165       int target_offset = 0;
   10166       int old_size;
   10167       int diff;
   10168       symbolS *gen_label = NULL;
   10169       offsetT frag_offset;
   10170       bfd_boolean first = TRUE;
   10171 
   10172       /* It does not fit.  Find something that does and
   10173          convert immediately.  */
   10174       frag_offset = fr_opcode - fragP->fr_literal;
   10175       istack_init (&istack);
   10176       xg_assembly_relax (&istack, &orig_tinsn,
   10177 			 segP, fragP, frag_offset, min_steps, 0);
   10178 
   10179       old_size = xtensa_format_length (isa, fmt);
   10180 
   10181       /* Assemble this right inline.  */
   10182 
   10183       /* First, create the mapping from a label name to the REAL label.  */
   10184       target_offset = 0;
   10185       for (i = 0; i < istack.ninsn; i++)
   10186 	{
   10187 	  TInsn *tinsn = &istack.insn[i];
   10188 	  fragS *lit_frag;
   10189 
   10190 	  switch (tinsn->insn_type)
   10191 	    {
   10192 	    case ITYPE_LITERAL:
   10193 	      if (lit_sym != NULL)
   10194 		as_bad (_("multiple literals in expansion"));
   10195 	      /* First find the appropriate space in the literal pool.  */
   10196 	      lit_frag = fragP->tc_frag_data.literal_frags[slot];
   10197 	      if (lit_frag == NULL)
   10198 		as_bad (_("no registered fragment for literal"));
   10199 	      if (tinsn->ntok != 1)
   10200 		as_bad (_("number of literal tokens != 1"));
   10201 
   10202 	      /* Set the literal symbol and add a fixup.  */
   10203 	      lit_sym = lit_frag->fr_symbol;
   10204 	      break;
   10205 
   10206 	    case ITYPE_LABEL:
   10207 	      if (align_targets && !is_loop)
   10208 		{
   10209 		  fragS *unreach = fragP->fr_next;
   10210 		  while (!(unreach->fr_type == rs_machine_dependent
   10211 			   && (unreach->fr_subtype == RELAX_MAYBE_UNREACHABLE
   10212 			       || unreach->fr_subtype == RELAX_UNREACHABLE)))
   10213 		    {
   10214 		      unreach = unreach->fr_next;
   10215 		    }
   10216 
   10217 		  gas_assert (unreach->fr_type == rs_machine_dependent
   10218 			  && (unreach->fr_subtype == RELAX_MAYBE_UNREACHABLE
   10219 			      || unreach->fr_subtype == RELAX_UNREACHABLE));
   10220 
   10221 		  target_offset += unreach->tc_frag_data.text_expansion[0];
   10222 		}
   10223 	      gas_assert (gen_label == NULL);
   10224 	      gen_label = symbol_new (FAKE_LABEL_NAME, now_seg,
   10225 				      fr_opcode - fragP->fr_literal
   10226 				      + target_offset, fragP);
   10227 	      break;
   10228 
   10229 	    case ITYPE_INSN:
   10230 	      if (first && from_wide_insn)
   10231 		{
   10232 		  target_offset += xtensa_format_length (isa, fmt);
   10233 		  first = FALSE;
   10234 		  if (!opcode_fits_format_slot (tinsn->opcode, fmt, slot))
   10235 		    target_offset += xg_get_single_size (tinsn->opcode);
   10236 		}
   10237 	      else
   10238 		target_offset += xg_get_single_size (tinsn->opcode);
   10239 	      break;
   10240 	    }
   10241 	}
   10242 
   10243       total_size = 0;
   10244       first = TRUE;
   10245       for (i = 0; i < istack.ninsn; i++)
   10246 	{
   10247 	  TInsn *tinsn = &istack.insn[i];
   10248 	  fragS *lit_frag;
   10249 	  int size;
   10250 	  segT target_seg;
   10251 	  bfd_reloc_code_real_type reloc_type;
   10252 
   10253 	  switch (tinsn->insn_type)
   10254 	    {
   10255 	    case ITYPE_LITERAL:
   10256 	      lit_frag = fragP->tc_frag_data.literal_frags[slot];
   10257 	      /* Already checked.  */
   10258 	      gas_assert (lit_frag != NULL);
   10259 	      gas_assert (lit_sym != NULL);
   10260 	      gas_assert (tinsn->ntok == 1);
   10261 	      /* Add a fixup.  */
   10262 	      target_seg = S_GET_SEGMENT (lit_sym);
   10263 	      gas_assert (target_seg);
   10264 	      reloc_type = map_operator_to_reloc (tinsn->tok[0].X_op, TRUE);
   10265 	      fix_new_exp_in_seg (target_seg, 0, lit_frag, 0, 4,
   10266 				  &tinsn->tok[0], FALSE, reloc_type);
   10267 	      break;
   10268 
   10269 	    case ITYPE_LABEL:
   10270 	      break;
   10271 
   10272 	    case ITYPE_INSN:
   10273 	      xg_resolve_labels (tinsn, gen_label);
   10274 	      xg_resolve_literals (tinsn, lit_sym);
   10275 	      if (from_wide_insn && first)
   10276 		{
   10277 		  first = FALSE;
   10278 		  if (opcode_fits_format_slot (tinsn->opcode, fmt, slot))
   10279 		    {
   10280 		      cur_vinsn.slots[slot] = *tinsn;
   10281 		    }
   10282 		  else
   10283 		    {
   10284 		      cur_vinsn.slots[slot].opcode =
   10285 			xtensa_format_slot_nop_opcode (isa, fmt, slot);
   10286 		      cur_vinsn.slots[slot].ntok = 0;
   10287 		    }
   10288 		  vinsn_to_insnbuf (&cur_vinsn, immed_instr, fragP, TRUE);
   10289 		  xtensa_insnbuf_to_chars (isa, cur_vinsn.insnbuf,
   10290 					   (unsigned char *) immed_instr, 0);
   10291 		  fragP->tc_frag_data.is_insn = TRUE;
   10292 		  size = xtensa_format_length (isa, fmt);
   10293 		  if (!opcode_fits_format_slot (tinsn->opcode, fmt, slot))
   10294 		    {
   10295 		      xg_emit_insn_to_buf
   10296 			(tinsn, immed_instr + size, fragP,
   10297 			 immed_instr - fragP->fr_literal + size, TRUE);
   10298 		      size += xg_get_single_size (tinsn->opcode);
   10299 		    }
   10300 		}
   10301 	      else
   10302 		{
   10303 		  size = xg_get_single_size (tinsn->opcode);
   10304 		  xg_emit_insn_to_buf (tinsn, immed_instr, fragP,
   10305 				       immed_instr - fragP->fr_literal, TRUE);
   10306 		}
   10307 	      immed_instr += size;
   10308 	      total_size += size;
   10309 	      break;
   10310 	    }
   10311 	}
   10312 
   10313       diff = total_size - old_size;
   10314       gas_assert (diff >= 0);
   10315       if (diff != 0)
   10316 	expanded = TRUE;
   10317       gas_assert (diff <= fragP->fr_var);
   10318       fragP->fr_var -= diff;
   10319       fragP->fr_fix += diff;
   10320     }
   10321 
   10322   /* Check for undefined immediates in LOOP instructions.  */
   10323   if (is_loop)
   10324     {
   10325       symbolS *sym;
   10326       sym = orig_tinsn.tok[1].X_add_symbol;
   10327       if (sym != NULL && !S_IS_DEFINED (sym))
   10328 	{
   10329 	  as_bad (_("unresolved loop target symbol: %s"), S_GET_NAME (sym));
   10330 	  return;
   10331 	}
   10332       sym = orig_tinsn.tok[1].X_op_symbol;
   10333       if (sym != NULL && !S_IS_DEFINED (sym))
   10334 	{
   10335 	  as_bad (_("unresolved loop target symbol: %s"), S_GET_NAME (sym));
   10336 	  return;
   10337 	}
   10338     }
   10339 
   10340   if (expanded && xtensa_opcode_is_loop (isa, orig_tinsn.opcode) == 1)
   10341     convert_frag_immed_finish_loop (segP, fragP, &orig_tinsn);
   10342 
   10343   if (expanded && is_direct_call_opcode (orig_tinsn.opcode))
   10344     {
   10345       /* Add an expansion note on the expanded instruction.  */
   10346       fix_new_exp_in_seg (now_seg, 0, fragP, fr_opcode - fragP->fr_literal, 4,
   10347 			  &orig_tinsn.tok[0], TRUE,
   10348 			  BFD_RELOC_XTENSA_ASM_EXPAND);
   10349     }
   10350 }
   10351 
   10352 
   10353 /* Add a new fix expression into the desired segment.  We have to
   10354    switch to that segment to do this.  */
   10355 
   10356 static fixS *
   10357 fix_new_exp_in_seg (segT new_seg,
   10358 		    subsegT new_subseg,
   10359 		    fragS *frag,
   10360 		    int where,
   10361 		    int size,
   10362 		    expressionS *exp,
   10363 		    int pcrel,
   10364 		    bfd_reloc_code_real_type r_type)
   10365 {
   10366   fixS *new_fix;
   10367   segT seg = now_seg;
   10368   subsegT subseg = now_subseg;
   10369 
   10370   gas_assert (new_seg != 0);
   10371   subseg_set (new_seg, new_subseg);
   10372 
   10373   new_fix = fix_new_exp (frag, where, size, exp, pcrel, r_type);
   10374   subseg_set (seg, subseg);
   10375   return new_fix;
   10376 }
   10377 
   10378 
   10379 /* Relax a loop instruction so that it can span loop >256 bytes.
   10380 
   10381                   loop    as, .L1
   10382           .L0:
   10383                   rsr     as, LEND
   10384                   wsr     as, LBEG
   10385                   addi    as, as, lo8 (label-.L1)
   10386                   addmi   as, as, mid8 (label-.L1)
   10387                   wsr     as, LEND
   10388                   isync
   10389                   rsr     as, LCOUNT
   10390                   addi    as, as, 1
   10391           .L1:
   10392                   <<body>>
   10393           label:
   10394 */
   10395 
   10396 static void
   10397 convert_frag_immed_finish_loop (segT segP, fragS *fragP, TInsn *tinsn)
   10398 {
   10399   TInsn loop_insn;
   10400   TInsn addi_insn;
   10401   TInsn addmi_insn;
   10402   unsigned long target;
   10403   static xtensa_insnbuf insnbuf = NULL;
   10404   unsigned int loop_length, loop_length_hi, loop_length_lo;
   10405   xtensa_isa isa = xtensa_default_isa;
   10406   addressT loop_offset;
   10407   addressT addi_offset = 9;
   10408   addressT addmi_offset = 12;
   10409   fragS *next_fragP;
   10410   int target_count;
   10411 
   10412   if (!insnbuf)
   10413     insnbuf = xtensa_insnbuf_alloc (isa);
   10414 
   10415   /* Get the loop offset.  */
   10416   loop_offset = get_expanded_loop_offset (tinsn->opcode);
   10417 
   10418   /* Validate that there really is a LOOP at the loop_offset.  Because
   10419      loops are not bundleable, we can assume that the instruction will be
   10420      in slot 0.  */
   10421   tinsn_from_chars (&loop_insn, fragP->fr_opcode + loop_offset, 0);
   10422   tinsn_immed_from_frag (&loop_insn, fragP, 0);
   10423 
   10424   gas_assert (xtensa_opcode_is_loop (isa, loop_insn.opcode) == 1);
   10425   addi_offset += loop_offset;
   10426   addmi_offset += loop_offset;
   10427 
   10428   gas_assert (tinsn->ntok == 2);
   10429   if (tinsn->tok[1].X_op == O_constant)
   10430     target = tinsn->tok[1].X_add_number;
   10431   else if (tinsn->tok[1].X_op == O_symbol)
   10432     {
   10433       /* Find the fragment.  */
   10434       symbolS *sym = tinsn->tok[1].X_add_symbol;
   10435       gas_assert (S_GET_SEGMENT (sym) == segP
   10436 	      || S_GET_SEGMENT (sym) == absolute_section);
   10437       target = (S_GET_VALUE (sym) + tinsn->tok[1].X_add_number);
   10438     }
   10439   else
   10440     {
   10441       as_bad (_("invalid expression evaluation type %d"), tinsn->tok[1].X_op);
   10442       target = 0;
   10443     }
   10444 
   10445   loop_length = target - (fragP->fr_address + fragP->fr_fix);
   10446   loop_length_hi = loop_length & ~0x0ff;
   10447   loop_length_lo = loop_length & 0x0ff;
   10448   if (loop_length_lo >= 128)
   10449     {
   10450       loop_length_lo -= 256;
   10451       loop_length_hi += 256;
   10452     }
   10453 
   10454   /* Because addmi sign-extends the immediate, 'loop_length_hi' can be at most
   10455      32512.  If the loop is larger than that, then we just fail.  */
   10456   if (loop_length_hi > 32512)
   10457     as_bad_where (fragP->fr_file, fragP->fr_line,
   10458 		  _("loop too long for LOOP instruction"));
   10459 
   10460   tinsn_from_chars (&addi_insn, fragP->fr_opcode + addi_offset, 0);
   10461   gas_assert (addi_insn.opcode == xtensa_addi_opcode);
   10462 
   10463   tinsn_from_chars (&addmi_insn, fragP->fr_opcode + addmi_offset, 0);
   10464   gas_assert (addmi_insn.opcode == xtensa_addmi_opcode);
   10465 
   10466   set_expr_const (&addi_insn.tok[2], loop_length_lo);
   10467   tinsn_to_insnbuf (&addi_insn, insnbuf);
   10468 
   10469   fragP->tc_frag_data.is_insn = TRUE;
   10470   xtensa_insnbuf_to_chars
   10471     (isa, insnbuf, (unsigned char *) fragP->fr_opcode + addi_offset, 0);
   10472 
   10473   set_expr_const (&addmi_insn.tok[2], loop_length_hi);
   10474   tinsn_to_insnbuf (&addmi_insn, insnbuf);
   10475   xtensa_insnbuf_to_chars
   10476     (isa, insnbuf, (unsigned char *) fragP->fr_opcode + addmi_offset, 0);
   10477 
   10478   /* Walk through all of the frags from here to the loop end
   10479      and mark them as no_transform to keep them from being modified
   10480      by the linker.  If we ever have a relocation for the
   10481      addi/addmi of the difference of two symbols we can remove this.  */
   10482 
   10483   target_count = 0;
   10484   for (next_fragP = fragP; next_fragP != NULL;
   10485        next_fragP = next_fragP->fr_next)
   10486     {
   10487       next_fragP->tc_frag_data.is_no_transform = TRUE;
   10488       if (next_fragP->tc_frag_data.is_loop_target)
   10489 	target_count++;
   10490       if (target_count == 2)
   10491 	break;
   10492     }
   10493 }
   10494 
   10495 
   10496 /* A map that keeps information on a per-subsegment basis.  This is
   10498    maintained during initial assembly, but is invalid once the
   10499    subsegments are smashed together.  I.E., it cannot be used during
   10500    the relaxation.  */
   10501 
   10502 typedef struct subseg_map_struct
   10503 {
   10504   /* the key */
   10505   segT seg;
   10506   subsegT subseg;
   10507 
   10508   /* the data */
   10509   unsigned flags;
   10510   float total_freq;	/* fall-through + branch target frequency */
   10511   float target_freq;	/* branch target frequency alone */
   10512 
   10513   struct subseg_map_struct *next;
   10514 } subseg_map;
   10515 
   10516 
   10517 static subseg_map *sseg_map = NULL;
   10518 
   10519 static subseg_map *
   10520 get_subseg_info (segT seg, subsegT subseg)
   10521 {
   10522   subseg_map *subseg_e;
   10523 
   10524   for (subseg_e = sseg_map; subseg_e; subseg_e = subseg_e->next)
   10525     {
   10526       if (seg == subseg_e->seg && subseg == subseg_e->subseg)
   10527 	break;
   10528     }
   10529   return subseg_e;
   10530 }
   10531 
   10532 
   10533 static subseg_map *
   10534 add_subseg_info (segT seg, subsegT subseg)
   10535 {
   10536   subseg_map *subseg_e = (subseg_map *) xmalloc (sizeof (subseg_map));
   10537   memset (subseg_e, 0, sizeof (subseg_map));
   10538   subseg_e->seg = seg;
   10539   subseg_e->subseg = subseg;
   10540   subseg_e->flags = 0;
   10541   /* Start off considering every branch target very important.  */
   10542   subseg_e->target_freq = 1.0;
   10543   subseg_e->total_freq = 1.0;
   10544   subseg_e->next = sseg_map;
   10545   sseg_map = subseg_e;
   10546   return subseg_e;
   10547 }
   10548 
   10549 
   10550 static unsigned
   10551 get_last_insn_flags (segT seg, subsegT subseg)
   10552 {
   10553   subseg_map *subseg_e = get_subseg_info (seg, subseg);
   10554   if (subseg_e)
   10555     return subseg_e->flags;
   10556   return 0;
   10557 }
   10558 
   10559 
   10560 static void
   10561 set_last_insn_flags (segT seg,
   10562 		     subsegT subseg,
   10563 		     unsigned fl,
   10564 		     bfd_boolean val)
   10565 {
   10566   subseg_map *subseg_e = get_subseg_info (seg, subseg);
   10567   if (! subseg_e)
   10568     subseg_e = add_subseg_info (seg, subseg);
   10569   if (val)
   10570     subseg_e->flags |= fl;
   10571   else
   10572     subseg_e->flags &= ~fl;
   10573 }
   10574 
   10575 
   10576 static float
   10577 get_subseg_total_freq (segT seg, subsegT subseg)
   10578 {
   10579   subseg_map *subseg_e = get_subseg_info (seg, subseg);
   10580   if (subseg_e)
   10581     return subseg_e->total_freq;
   10582   return 1.0;
   10583 }
   10584 
   10585 
   10586 static float
   10587 get_subseg_target_freq (segT seg, subsegT subseg)
   10588 {
   10589   subseg_map *subseg_e = get_subseg_info (seg, subseg);
   10590   if (subseg_e)
   10591     return subseg_e->target_freq;
   10592   return 1.0;
   10593 }
   10594 
   10595 
   10596 static void
   10597 set_subseg_freq (segT seg, subsegT subseg, float total_f, float target_f)
   10598 {
   10599   subseg_map *subseg_e = get_subseg_info (seg, subseg);
   10600   if (! subseg_e)
   10601     subseg_e = add_subseg_info (seg, subseg);
   10602   subseg_e->total_freq = total_f;
   10603   subseg_e->target_freq = target_f;
   10604 }
   10605 
   10606 
   10607 /* Segment Lists and emit_state Stuff.  */
   10609 
   10610 static void
   10611 xtensa_move_seg_list_to_beginning (seg_list *head)
   10612 {
   10613   head = head->next;
   10614   while (head)
   10615     {
   10616       segT literal_section = head->seg;
   10617 
   10618       /* Move the literal section to the front of the section list.  */
   10619       gas_assert (literal_section);
   10620       if (literal_section != stdoutput->sections)
   10621 	{
   10622 	  bfd_section_list_remove (stdoutput, literal_section);
   10623 	  bfd_section_list_prepend (stdoutput, literal_section);
   10624 	}
   10625       head = head->next;
   10626     }
   10627 }
   10628 
   10629 
   10630 static void mark_literal_frags (seg_list *);
   10631 
   10632 static void
   10633 xtensa_move_literals (void)
   10634 {
   10635   seg_list *segment;
   10636   frchainS *frchain_from, *frchain_to;
   10637   fragS *search_frag, *next_frag, *literal_pool, *insert_after;
   10638   fragS **frag_splice;
   10639   emit_state state;
   10640   segT dest_seg;
   10641   fixS *fix, *next_fix, **fix_splice;
   10642   sym_list *lit;
   10643 
   10644   mark_literal_frags (literal_head->next);
   10645 
   10646   if (use_literal_section)
   10647     return;
   10648 
   10649   for (segment = literal_head->next; segment; segment = segment->next)
   10650     {
   10651       /* Keep the literals for .init and .fini in separate sections.  */
   10652       if (!strcmp (segment_name (segment->seg), INIT_SECTION_NAME)
   10653 	  || !strcmp (segment_name (segment->seg), FINI_SECTION_NAME))
   10654 	continue;
   10655 
   10656       frchain_from = seg_info (segment->seg)->frchainP;
   10657       search_frag = frchain_from->frch_root;
   10658       literal_pool = NULL;
   10659       frchain_to = NULL;
   10660       frag_splice = &(frchain_from->frch_root);
   10661 
   10662       while (!search_frag->tc_frag_data.literal_frag)
   10663 	{
   10664 	  gas_assert (search_frag->fr_fix == 0
   10665 		  || search_frag->fr_type == rs_align);
   10666 	  search_frag = search_frag->fr_next;
   10667 	}
   10668 
   10669       gas_assert (search_frag->tc_frag_data.literal_frag->fr_subtype
   10670 	      == RELAX_LITERAL_POOL_BEGIN);
   10671       xtensa_switch_section_emit_state (&state, segment->seg, 0);
   10672 
   10673       /* Make sure that all the frags in this series are closed, and
   10674 	 that there is at least one left over of zero-size.  This
   10675 	 prevents us from making a segment with an frchain without any
   10676 	 frags in it.  */
   10677       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
   10678       xtensa_set_frag_assembly_state (frag_now);
   10679       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
   10680       xtensa_set_frag_assembly_state (frag_now);
   10681 
   10682       while (search_frag != frag_now)
   10683 	{
   10684 	  next_frag = search_frag->fr_next;
   10685 
   10686 	  /* First, move the frag out of the literal section and
   10687 	     to the appropriate place.  */
   10688 	  if (search_frag->tc_frag_data.literal_frag)
   10689 	    {
   10690 	      literal_pool = search_frag->tc_frag_data.literal_frag;
   10691 	      gas_assert (literal_pool->fr_subtype == RELAX_LITERAL_POOL_BEGIN);
   10692 	      frchain_to = literal_pool->tc_frag_data.lit_frchain;
   10693 	      gas_assert (frchain_to);
   10694 	    }
   10695 	  insert_after = literal_pool->tc_frag_data.literal_frag;
   10696 	  dest_seg = insert_after->fr_next->tc_frag_data.lit_seg;
   10697 
   10698 	  *frag_splice = next_frag;
   10699 	  search_frag->fr_next = insert_after->fr_next;
   10700 	  insert_after->fr_next = search_frag;
   10701 	  search_frag->tc_frag_data.lit_seg = dest_seg;
   10702 	  literal_pool->tc_frag_data.literal_frag = search_frag;
   10703 
   10704 	  /* Now move any fixups associated with this frag to the
   10705 	     right section.  */
   10706 	  fix = frchain_from->fix_root;
   10707 	  fix_splice = &(frchain_from->fix_root);
   10708 	  while (fix)
   10709 	    {
   10710 	      next_fix = fix->fx_next;
   10711 	      if (fix->fx_frag == search_frag)
   10712 		{
   10713 		  *fix_splice = next_fix;
   10714 		  fix->fx_next = frchain_to->fix_root;
   10715 		  frchain_to->fix_root = fix;
   10716 		  if (frchain_to->fix_tail == NULL)
   10717 		    frchain_to->fix_tail = fix;
   10718 		}
   10719 	      else
   10720 		fix_splice = &(fix->fx_next);
   10721 	      fix = next_fix;
   10722 	    }
   10723 	  search_frag = next_frag;
   10724 	}
   10725 
   10726       if (frchain_from->fix_root != NULL)
   10727 	{
   10728 	  frchain_from = seg_info (segment->seg)->frchainP;
   10729 	  as_warn (_("fixes not all moved from %s"), segment->seg->name);
   10730 
   10731 	  gas_assert (frchain_from->fix_root == NULL);
   10732 	}
   10733       frchain_from->fix_tail = NULL;
   10734       xtensa_restore_emit_state (&state);
   10735     }
   10736 
   10737   /* Now fix up the SEGMENT value for all the literal symbols.  */
   10738   for (lit = literal_syms; lit; lit = lit->next)
   10739     {
   10740       symbolS *lit_sym = lit->sym;
   10741       segT dseg = symbol_get_frag (lit_sym)->tc_frag_data.lit_seg;
   10742       if (dseg)
   10743 	S_SET_SEGMENT (lit_sym, dseg);
   10744     }
   10745 }
   10746 
   10747 
   10748 /* Walk over all the frags for segments in a list and mark them as
   10749    containing literals.  As clunky as this is, we can't rely on frag_var
   10750    and frag_variant to get called in all situations.  */
   10751 
   10752 static void
   10753 mark_literal_frags (seg_list *segment)
   10754 {
   10755   frchainS *frchain_from;
   10756   fragS *search_frag;
   10757 
   10758   while (segment)
   10759     {
   10760       frchain_from = seg_info (segment->seg)->frchainP;
   10761       search_frag = frchain_from->frch_root;
   10762       while (search_frag)
   10763 	{
   10764 	  search_frag->tc_frag_data.is_literal = TRUE;
   10765 	  search_frag = search_frag->fr_next;
   10766 	}
   10767       segment = segment->next;
   10768     }
   10769 }
   10770 
   10771 
   10772 static void
   10773 xtensa_reorder_seg_list (seg_list *head, segT after)
   10774 {
   10775   /* Move all of the sections in the section list to come
   10776      after "after" in the gnu segment list.  */
   10777 
   10778   head = head->next;
   10779   while (head)
   10780     {
   10781       segT literal_section = head->seg;
   10782 
   10783       /* Move the literal section after "after".  */
   10784       gas_assert (literal_section);
   10785       if (literal_section != after)
   10786 	{
   10787 	  bfd_section_list_remove (stdoutput, literal_section);
   10788 	  bfd_section_list_insert_after (stdoutput, after, literal_section);
   10789 	}
   10790 
   10791       head = head->next;
   10792     }
   10793 }
   10794 
   10795 
   10796 /* Push all the literal segments to the end of the gnu list.  */
   10797 
   10798 static void
   10799 xtensa_reorder_segments (void)
   10800 {
   10801   segT sec;
   10802   segT last_sec = 0;
   10803   int old_count = 0;
   10804   int new_count = 0;
   10805 
   10806   for (sec = stdoutput->sections; sec != NULL; sec = sec->next)
   10807     {
   10808       last_sec = sec;
   10809       old_count++;
   10810     }
   10811 
   10812   /* Now that we have the last section, push all the literal
   10813      sections to the end.  */
   10814   xtensa_reorder_seg_list (literal_head, last_sec);
   10815 
   10816   /* Now perform the final error check.  */
   10817   for (sec = stdoutput->sections; sec != NULL; sec = sec->next)
   10818     new_count++;
   10819   gas_assert (new_count == old_count);
   10820 }
   10821 
   10822 
   10823 /* Change the emit state (seg, subseg, and frag related stuff) to the
   10824    correct location.  Return a emit_state which can be passed to
   10825    xtensa_restore_emit_state to return to current fragment.  */
   10826 
   10827 static void
   10828 xtensa_switch_to_literal_fragment (emit_state *result)
   10829 {
   10830   if (directive_state[directive_absolute_literals])
   10831     {
   10832       segT lit4_seg = cache_literal_section (TRUE);
   10833       xtensa_switch_section_emit_state (result, lit4_seg, 0);
   10834     }
   10835   else
   10836     xtensa_switch_to_non_abs_literal_fragment (result);
   10837 
   10838   /* Do a 4-byte align here.  */
   10839   frag_align (2, 0, 0);
   10840   record_alignment (now_seg, 2);
   10841 }
   10842 
   10843 
   10844 static void
   10845 xtensa_switch_to_non_abs_literal_fragment (emit_state *result)
   10846 {
   10847   static bfd_boolean recursive = FALSE;
   10848   fragS *pool_location = get_literal_pool_location (now_seg);
   10849   segT lit_seg;
   10850   bfd_boolean is_init =
   10851     (now_seg && !strcmp (segment_name (now_seg), INIT_SECTION_NAME));
   10852   bfd_boolean is_fini =
   10853     (now_seg && !strcmp (segment_name (now_seg), FINI_SECTION_NAME));
   10854 
   10855   if (pool_location == NULL
   10856       && !use_literal_section
   10857       && !recursive
   10858       && !is_init && ! is_fini)
   10859     {
   10860       as_bad (_("literal pool location required for text-section-literals; specify with .literal_position"));
   10861 
   10862       /* When we mark a literal pool location, we want to put a frag in
   10863 	 the literal pool that points to it.  But to do that, we want to
   10864 	 switch_to_literal_fragment.  But literal sections don't have
   10865 	 literal pools, so their location is always null, so we would
   10866 	 recurse forever.  This is kind of hacky, but it works.  */
   10867 
   10868       recursive = TRUE;
   10869       xtensa_mark_literal_pool_location ();
   10870       recursive = FALSE;
   10871     }
   10872 
   10873   lit_seg = cache_literal_section (FALSE);
   10874   xtensa_switch_section_emit_state (result, lit_seg, 0);
   10875 
   10876   if (!use_literal_section
   10877       && !is_init && !is_fini
   10878       && get_literal_pool_location (now_seg) != pool_location)
   10879     {
   10880       /* Close whatever frag is there.  */
   10881       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
   10882       xtensa_set_frag_assembly_state (frag_now);
   10883       frag_now->tc_frag_data.literal_frag = pool_location;
   10884       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
   10885       xtensa_set_frag_assembly_state (frag_now);
   10886     }
   10887 }
   10888 
   10889 
   10890 /* Call this function before emitting data into the literal section.
   10891    This is a helper function for xtensa_switch_to_literal_fragment.
   10892    This is similar to a .section new_now_seg subseg. */
   10893 
   10894 static void
   10895 xtensa_switch_section_emit_state (emit_state *state,
   10896 				  segT new_now_seg,
   10897 				  subsegT new_now_subseg)
   10898 {
   10899   state->name = now_seg->name;
   10900   state->now_seg = now_seg;
   10901   state->now_subseg = now_subseg;
   10902   state->generating_literals = generating_literals;
   10903   generating_literals++;
   10904   subseg_set (new_now_seg, new_now_subseg);
   10905 }
   10906 
   10907 
   10908 /* Use to restore the emitting into the normal place.  */
   10909 
   10910 static void
   10911 xtensa_restore_emit_state (emit_state *state)
   10912 {
   10913   generating_literals = state->generating_literals;
   10914   subseg_set (state->now_seg, state->now_subseg);
   10915 }
   10916 
   10917 
   10918 /* Predicate function used to look up a section in a particular group.  */
   10919 
   10920 static bfd_boolean
   10921 match_section_group (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, void *inf)
   10922 {
   10923   const char *gname = inf;
   10924   const char *group_name = elf_group_name (sec);
   10925 
   10926   return (group_name == gname
   10927 	  || (group_name != NULL
   10928 	      && gname != NULL
   10929 	      && strcmp (group_name, gname) == 0));
   10930 }
   10931 
   10932 
   10933 /* Get the literal section to be used for the current text section.
   10934    The result may be cached in the default_lit_sections structure.  */
   10935 
   10936 static segT
   10937 cache_literal_section (bfd_boolean use_abs_literals)
   10938 {
   10939   const char *text_name, *group_name = 0;
   10940   char *base_name, *name, *suffix;
   10941   segT *pcached;
   10942   segT seg, current_section;
   10943   int current_subsec;
   10944   bfd_boolean linkonce = FALSE;
   10945 
   10946   /* Save the current section/subsection.  */
   10947   current_section = now_seg;
   10948   current_subsec = now_subseg;
   10949 
   10950   /* Clear the cached values if they are no longer valid.  */
   10951   if (now_seg != default_lit_sections.current_text_seg)
   10952     {
   10953       default_lit_sections.current_text_seg = now_seg;
   10954       default_lit_sections.lit_seg = NULL;
   10955       default_lit_sections.lit4_seg = NULL;
   10956     }
   10957 
   10958   /* Check if the literal section is already cached.  */
   10959   if (use_abs_literals)
   10960     pcached = &default_lit_sections.lit4_seg;
   10961   else
   10962     pcached = &default_lit_sections.lit_seg;
   10963 
   10964   if (*pcached)
   10965     return *pcached;
   10966 
   10967   text_name = default_lit_sections.lit_prefix;
   10968   if (! text_name || ! *text_name)
   10969     {
   10970       text_name = segment_name (current_section);
   10971       group_name = elf_group_name (current_section);
   10972       linkonce = (current_section->flags & SEC_LINK_ONCE) != 0;
   10973     }
   10974 
   10975   base_name = use_abs_literals ? ".lit4" : ".literal";
   10976   if (group_name)
   10977     {
   10978       name = xmalloc (strlen (base_name) + strlen (group_name) + 2);
   10979       sprintf (name, "%s.%s", base_name, group_name);
   10980     }
   10981   else if (strncmp (text_name, ".gnu.linkonce.", linkonce_len) == 0)
   10982     {
   10983       suffix = strchr (text_name + linkonce_len, '.');
   10984 
   10985       name = xmalloc (linkonce_len + strlen (base_name) + 1
   10986 		      + (suffix ? strlen (suffix) : 0));
   10987       strcpy (name, ".gnu.linkonce");
   10988       strcat (name, base_name);
   10989       if (suffix)
   10990 	strcat (name, suffix);
   10991       linkonce = TRUE;
   10992     }
   10993   else
   10994     {
   10995       /* If the section name begins or ends with ".text", then replace
   10996 	 that portion instead of appending an additional suffix.  */
   10997       size_t len = strlen (text_name);
   10998       if (len >= 5
   10999 	  && (strcmp (text_name + len - 5, ".text") == 0
   11000 	      || strncmp (text_name, ".text", 5) == 0))
   11001 	len -= 5;
   11002 
   11003       name = xmalloc (len + strlen (base_name) + 1);
   11004       if (strncmp (text_name, ".text", 5) == 0)
   11005 	{
   11006 	  strcpy (name, base_name);
   11007 	  strcat (name, text_name + 5);
   11008 	}
   11009       else
   11010 	{
   11011 	  strcpy (name, text_name);
   11012 	  strcpy (name + len, base_name);
   11013 	}
   11014     }
   11015 
   11016   /* Canonicalize section names to allow renaming literal sections.
   11017      The group name, if any, came from the current text section and
   11018      has already been canonicalized.  */
   11019   name = tc_canonicalize_symbol_name (name);
   11020 
   11021   seg = bfd_get_section_by_name_if (stdoutput, name, match_section_group,
   11022 				    (void *) group_name);
   11023   if (! seg)
   11024     {
   11025       flagword flags;
   11026 
   11027       seg = subseg_force_new (name, 0);
   11028 
   11029       if (! use_abs_literals)
   11030 	{
   11031 	  /* Add the newly created literal segment to the list.  */
   11032 	  seg_list *n = (seg_list *) xmalloc (sizeof (seg_list));
   11033 	  n->seg = seg;
   11034 	  n->next = literal_head->next;
   11035 	  literal_head->next = n;
   11036 	}
   11037 
   11038       flags = (SEC_HAS_CONTENTS | SEC_READONLY | SEC_ALLOC | SEC_LOAD
   11039 	       | (linkonce ? (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD) : 0)
   11040 	       | (use_abs_literals ? SEC_DATA : SEC_CODE));
   11041 
   11042       elf_group_name (seg) = group_name;
   11043 
   11044       bfd_set_section_flags (stdoutput, seg, flags);
   11045       bfd_set_section_alignment (stdoutput, seg, 2);
   11046     }
   11047 
   11048   *pcached = seg;
   11049   subseg_set (current_section, current_subsec);
   11050   return seg;
   11051 }
   11052 
   11053 
   11054 /* Property Tables Stuff.  */
   11056 
   11057 #define XTENSA_INSN_SEC_NAME ".xt.insn"
   11058 #define XTENSA_LIT_SEC_NAME ".xt.lit"
   11059 #define XTENSA_PROP_SEC_NAME ".xt.prop"
   11060 
   11061 typedef bfd_boolean (*frag_predicate) (const fragS *);
   11062 typedef void (*frag_flags_fn) (const fragS *, frag_flags *);
   11063 
   11064 static bfd_boolean get_frag_is_literal (const fragS *);
   11065 static void xtensa_create_property_segments
   11066   (frag_predicate, frag_predicate, const char *, xt_section_type);
   11067 static void xtensa_create_xproperty_segments
   11068   (frag_flags_fn, const char *, xt_section_type);
   11069 static bfd_boolean exclude_section_from_property_tables (segT);
   11070 static bfd_boolean section_has_property (segT, frag_predicate);
   11071 static bfd_boolean section_has_xproperty (segT, frag_flags_fn);
   11072 static void add_xt_block_frags
   11073   (segT, xtensa_block_info **, frag_predicate, frag_predicate);
   11074 static bfd_boolean xtensa_frag_flags_is_empty (const frag_flags *);
   11075 static void xtensa_frag_flags_init (frag_flags *);
   11076 static void get_frag_property_flags (const fragS *, frag_flags *);
   11077 static flagword frag_flags_to_number (const frag_flags *);
   11078 static void add_xt_prop_frags (segT, xtensa_block_info **, frag_flags_fn);
   11079 
   11080 /* Set up property tables after relaxation.  */
   11081 
   11082 void
   11083 xtensa_post_relax_hook (void)
   11084 {
   11085   xtensa_move_seg_list_to_beginning (literal_head);
   11086 
   11087   xtensa_find_unmarked_state_frags ();
   11088   xtensa_mark_frags_for_org ();
   11089   xtensa_mark_difference_of_two_symbols ();
   11090 
   11091   xtensa_create_property_segments (get_frag_is_literal,
   11092 				   NULL,
   11093 				   XTENSA_LIT_SEC_NAME,
   11094 				   xt_literal_sec);
   11095   xtensa_create_xproperty_segments (get_frag_property_flags,
   11096 				    XTENSA_PROP_SEC_NAME,
   11097 				    xt_prop_sec);
   11098 
   11099   if (warn_unaligned_branch_targets)
   11100     bfd_map_over_sections (stdoutput, xtensa_find_unaligned_branch_targets, 0);
   11101   bfd_map_over_sections (stdoutput, xtensa_find_unaligned_loops, 0);
   11102 }
   11103 
   11104 
   11105 /* This function is only meaningful after xtensa_move_literals.  */
   11106 
   11107 static bfd_boolean
   11108 get_frag_is_literal (const fragS *fragP)
   11109 {
   11110   gas_assert (fragP != NULL);
   11111   return fragP->tc_frag_data.is_literal;
   11112 }
   11113 
   11114 
   11115 static void
   11116 xtensa_create_property_segments (frag_predicate property_function,
   11117 				 frag_predicate end_property_function,
   11118 				 const char *section_name_base,
   11119 				 xt_section_type sec_type)
   11120 {
   11121   segT *seclist;
   11122 
   11123   /* Walk over all of the current segments.
   11124      Walk over each fragment
   11125      For each non-empty fragment,
   11126      Build a property record (append where possible).  */
   11127 
   11128   for (seclist = &stdoutput->sections;
   11129        seclist && *seclist;
   11130        seclist = &(*seclist)->next)
   11131     {
   11132       segT sec = *seclist;
   11133 
   11134       if (exclude_section_from_property_tables (sec))
   11135 	continue;
   11136 
   11137       if (section_has_property (sec, property_function))
   11138 	{
   11139 	  segment_info_type *xt_seg_info;
   11140 	  xtensa_block_info **xt_blocks;
   11141 	  segT prop_sec = xtensa_make_property_section (sec, section_name_base);
   11142 
   11143 	  prop_sec->output_section = prop_sec;
   11144 	  subseg_set (prop_sec, 0);
   11145 	  xt_seg_info = seg_info (prop_sec);
   11146 	  xt_blocks = &xt_seg_info->tc_segment_info_data.blocks[sec_type];
   11147 
   11148 	  /* Walk over all of the frchains here and add new sections.  */
   11149 	  add_xt_block_frags (sec, xt_blocks, property_function,
   11150 			      end_property_function);
   11151 	}
   11152     }
   11153 
   11154   /* Now we fill them out....  */
   11155 
   11156   for (seclist = &stdoutput->sections;
   11157        seclist && *seclist;
   11158        seclist = &(*seclist)->next)
   11159     {
   11160       segment_info_type *seginfo;
   11161       xtensa_block_info *block;
   11162       segT sec = *seclist;
   11163 
   11164       seginfo = seg_info (sec);
   11165       block = seginfo->tc_segment_info_data.blocks[sec_type];
   11166 
   11167       if (block)
   11168 	{
   11169 	  xtensa_block_info *cur_block;
   11170 	  int num_recs = 0;
   11171 	  bfd_size_type rec_size;
   11172 
   11173 	  for (cur_block = block; cur_block; cur_block = cur_block->next)
   11174 	    num_recs++;
   11175 
   11176 	  rec_size = num_recs * 8;
   11177 	  bfd_set_section_size (stdoutput, sec, rec_size);
   11178 
   11179 	  if (num_recs)
   11180 	    {
   11181 	      char *frag_data;
   11182 	      int i;
   11183 
   11184 	      subseg_set (sec, 0);
   11185 	      frag_data = frag_more (rec_size);
   11186 	      cur_block = block;
   11187 	      for (i = 0; i < num_recs; i++)
   11188 		{
   11189 		  fixS *fix;
   11190 
   11191 		  /* Write the fixup.  */
   11192 		  gas_assert (cur_block);
   11193 		  fix = fix_new (frag_now, i * 8, 4,
   11194 				 section_symbol (cur_block->sec),
   11195 				 cur_block->offset,
   11196 				 FALSE, BFD_RELOC_32);
   11197 		  fix->fx_file = "<internal>";
   11198 		  fix->fx_line = 0;
   11199 
   11200 		  /* Write the length.  */
   11201 		  md_number_to_chars (&frag_data[4 + i * 8],
   11202 				      cur_block->size, 4);
   11203 		  cur_block = cur_block->next;
   11204 		}
   11205 	      frag_wane (frag_now);
   11206 	      frag_new (0);
   11207 	      frag_wane (frag_now);
   11208 	    }
   11209 	}
   11210     }
   11211 }
   11212 
   11213 
   11214 static void
   11215 xtensa_create_xproperty_segments (frag_flags_fn flag_fn,
   11216 				  const char *section_name_base,
   11217 				  xt_section_type sec_type)
   11218 {
   11219   segT *seclist;
   11220 
   11221   /* Walk over all of the current segments.
   11222      Walk over each fragment.
   11223      For each fragment that has instructions,
   11224      build an instruction record (append where possible).  */
   11225 
   11226   for (seclist = &stdoutput->sections;
   11227        seclist && *seclist;
   11228        seclist = &(*seclist)->next)
   11229     {
   11230       segT sec = *seclist;
   11231 
   11232       if (exclude_section_from_property_tables (sec))
   11233 	continue;
   11234 
   11235       if (section_has_xproperty (sec, flag_fn))
   11236 	{
   11237 	  segment_info_type *xt_seg_info;
   11238 	  xtensa_block_info **xt_blocks;
   11239 	  segT prop_sec = xtensa_make_property_section (sec, section_name_base);
   11240 
   11241 	  prop_sec->output_section = prop_sec;
   11242 	  subseg_set (prop_sec, 0);
   11243 	  xt_seg_info = seg_info (prop_sec);
   11244 	  xt_blocks = &xt_seg_info->tc_segment_info_data.blocks[sec_type];
   11245 
   11246 	  /* Walk over all of the frchains here and add new sections.  */
   11247 	  add_xt_prop_frags (sec, xt_blocks, flag_fn);
   11248 	}
   11249     }
   11250 
   11251   /* Now we fill them out....  */
   11252 
   11253   for (seclist = &stdoutput->sections;
   11254        seclist && *seclist;
   11255        seclist = &(*seclist)->next)
   11256     {
   11257       segment_info_type *seginfo;
   11258       xtensa_block_info *block;
   11259       segT sec = *seclist;
   11260 
   11261       seginfo = seg_info (sec);
   11262       block = seginfo->tc_segment_info_data.blocks[sec_type];
   11263 
   11264       if (block)
   11265 	{
   11266 	  xtensa_block_info *cur_block;
   11267 	  int num_recs = 0;
   11268 	  bfd_size_type rec_size;
   11269 
   11270 	  for (cur_block = block; cur_block; cur_block = cur_block->next)
   11271 	    num_recs++;
   11272 
   11273 	  rec_size = num_recs * (8 + 4);
   11274 	  bfd_set_section_size (stdoutput, sec, rec_size);
   11275 	  /* elf_section_data (sec)->this_hdr.sh_entsize = 12; */
   11276 
   11277 	  if (num_recs)
   11278 	    {
   11279 	      char *frag_data;
   11280 	      int i;
   11281 
   11282 	      subseg_set (sec, 0);
   11283 	      frag_data = frag_more (rec_size);
   11284 	      cur_block = block;
   11285 	      for (i = 0; i < num_recs; i++)
   11286 		{
   11287 		  fixS *fix;
   11288 
   11289 		  /* Write the fixup.  */
   11290 		  gas_assert (cur_block);
   11291 		  fix = fix_new (frag_now, i * 12, 4,
   11292 				 section_symbol (cur_block->sec),
   11293 				 cur_block->offset,
   11294 				 FALSE, BFD_RELOC_32);
   11295 		  fix->fx_file = "<internal>";
   11296 		  fix->fx_line = 0;
   11297 
   11298 		  /* Write the length.  */
   11299 		  md_number_to_chars (&frag_data[4 + i * 12],
   11300 				      cur_block->size, 4);
   11301 		  md_number_to_chars (&frag_data[8 + i * 12],
   11302 				      frag_flags_to_number (&cur_block->flags),
   11303 				      sizeof (flagword));
   11304 		  cur_block = cur_block->next;
   11305 		}
   11306 	      frag_wane (frag_now);
   11307 	      frag_new (0);
   11308 	      frag_wane (frag_now);
   11309 	    }
   11310 	}
   11311     }
   11312 }
   11313 
   11314 
   11315 static bfd_boolean
   11316 exclude_section_from_property_tables (segT sec)
   11317 {
   11318   flagword flags = bfd_get_section_flags (stdoutput, sec);
   11319 
   11320   /* Sections that don't contribute to the memory footprint are excluded.  */
   11321   if ((flags & SEC_DEBUGGING)
   11322       || !(flags & SEC_ALLOC)
   11323       || (flags & SEC_MERGE))
   11324     return TRUE;
   11325 
   11326   /* Linker cie and fde optimizations mess up property entries for
   11327      eh_frame sections, but there is nothing inside them relevant to
   11328      property tables anyway.  */
   11329   if (strcmp (sec->name, ".eh_frame") == 0)
   11330     return TRUE;
   11331 
   11332   return FALSE;
   11333 }
   11334 
   11335 
   11336 static bfd_boolean
   11337 section_has_property (segT sec, frag_predicate property_function)
   11338 {
   11339   segment_info_type *seginfo = seg_info (sec);
   11340   fragS *fragP;
   11341 
   11342   if (seginfo && seginfo->frchainP)
   11343     {
   11344       for (fragP = seginfo->frchainP->frch_root; fragP; fragP = fragP->fr_next)
   11345 	{
   11346 	  if (property_function (fragP)
   11347 	      && (fragP->fr_type != rs_fill || fragP->fr_fix != 0))
   11348 	    return TRUE;
   11349 	}
   11350     }
   11351   return FALSE;
   11352 }
   11353 
   11354 
   11355 static bfd_boolean
   11356 section_has_xproperty (segT sec, frag_flags_fn property_function)
   11357 {
   11358   segment_info_type *seginfo = seg_info (sec);
   11359   fragS *fragP;
   11360 
   11361   if (seginfo && seginfo->frchainP)
   11362     {
   11363       for (fragP = seginfo->frchainP->frch_root; fragP; fragP = fragP->fr_next)
   11364 	{
   11365 	  frag_flags prop_flags;
   11366 	  property_function (fragP, &prop_flags);
   11367 	  if (!xtensa_frag_flags_is_empty (&prop_flags))
   11368 	    return TRUE;
   11369 	}
   11370     }
   11371   return FALSE;
   11372 }
   11373 
   11374 
   11375 /* Two types of block sections exist right now: literal and insns.  */
   11376 
   11377 static void
   11378 add_xt_block_frags (segT sec,
   11379 		    xtensa_block_info **xt_block,
   11380 		    frag_predicate property_function,
   11381 		    frag_predicate end_property_function)
   11382 {
   11383   fragS *fragP;
   11384 
   11385   /* Build it if needed.  */
   11386   while (*xt_block != NULL)
   11387     xt_block = &(*xt_block)->next;
   11388   /* We are either at NULL at the beginning or at the end.  */
   11389 
   11390   /* Walk through the frags.  */
   11391   if (seg_info (sec)->frchainP)
   11392     {
   11393       for (fragP = seg_info (sec)->frchainP->frch_root;
   11394 	   fragP;
   11395 	   fragP = fragP->fr_next)
   11396 	{
   11397 	  if (property_function (fragP)
   11398 	      && (fragP->fr_type != rs_fill || fragP->fr_fix != 0))
   11399 	    {
   11400 	      if (*xt_block != NULL)
   11401 		{
   11402 		  if ((*xt_block)->offset + (*xt_block)->size
   11403 		      == fragP->fr_address)
   11404 		    (*xt_block)->size += fragP->fr_fix;
   11405 		  else
   11406 		    xt_block = &((*xt_block)->next);
   11407 		}
   11408 	      if (*xt_block == NULL)
   11409 		{
   11410 		  xtensa_block_info *new_block = (xtensa_block_info *)
   11411 		    xmalloc (sizeof (xtensa_block_info));
   11412 		  new_block->sec = sec;
   11413 		  new_block->offset = fragP->fr_address;
   11414 		  new_block->size = fragP->fr_fix;
   11415 		  new_block->next = NULL;
   11416 		  xtensa_frag_flags_init (&new_block->flags);
   11417 		  *xt_block = new_block;
   11418 		}
   11419 	      if (end_property_function
   11420 		  && end_property_function (fragP))
   11421 		{
   11422 		  xt_block = &((*xt_block)->next);
   11423 		}
   11424 	    }
   11425 	}
   11426     }
   11427 }
   11428 
   11429 
   11430 /* Break the encapsulation of add_xt_prop_frags here.  */
   11431 
   11432 static bfd_boolean
   11433 xtensa_frag_flags_is_empty (const frag_flags *prop_flags)
   11434 {
   11435   if (prop_flags->is_literal
   11436       || prop_flags->is_insn
   11437       || prop_flags->is_data
   11438       || prop_flags->is_unreachable)
   11439     return FALSE;
   11440   return TRUE;
   11441 }
   11442 
   11443 
   11444 static void
   11445 xtensa_frag_flags_init (frag_flags *prop_flags)
   11446 {
   11447   memset (prop_flags, 0, sizeof (frag_flags));
   11448 }
   11449 
   11450 
   11451 static void
   11452 get_frag_property_flags (const fragS *fragP, frag_flags *prop_flags)
   11453 {
   11454   xtensa_frag_flags_init (prop_flags);
   11455   if (fragP->tc_frag_data.is_literal)
   11456     prop_flags->is_literal = TRUE;
   11457   if (fragP->tc_frag_data.is_specific_opcode
   11458       || fragP->tc_frag_data.is_no_transform)
   11459     {
   11460       prop_flags->is_no_transform = TRUE;
   11461       if (xtensa_frag_flags_is_empty (prop_flags))
   11462 	prop_flags->is_data = TRUE;
   11463     }
   11464   if (fragP->tc_frag_data.is_unreachable)
   11465     prop_flags->is_unreachable = TRUE;
   11466   else if (fragP->tc_frag_data.is_insn)
   11467     {
   11468       prop_flags->is_insn = TRUE;
   11469       if (fragP->tc_frag_data.is_loop_target)
   11470 	prop_flags->insn.is_loop_target = TRUE;
   11471       if (fragP->tc_frag_data.is_branch_target)
   11472 	prop_flags->insn.is_branch_target = TRUE;
   11473       if (fragP->tc_frag_data.is_no_density)
   11474 	prop_flags->insn.is_no_density = TRUE;
   11475       if (fragP->tc_frag_data.use_absolute_literals)
   11476 	prop_flags->insn.is_abslit = TRUE;
   11477     }
   11478   if (fragP->tc_frag_data.is_align)
   11479     {
   11480       prop_flags->is_align = TRUE;
   11481       prop_flags->alignment = fragP->tc_frag_data.alignment;
   11482       if (xtensa_frag_flags_is_empty (prop_flags))
   11483 	prop_flags->is_data = TRUE;
   11484     }
   11485 }
   11486 
   11487 
   11488 static flagword
   11489 frag_flags_to_number (const frag_flags *prop_flags)
   11490 {
   11491   flagword num = 0;
   11492   if (prop_flags->is_literal)
   11493     num |= XTENSA_PROP_LITERAL;
   11494   if (prop_flags->is_insn)
   11495     num |= XTENSA_PROP_INSN;
   11496   if (prop_flags->is_data)
   11497     num |= XTENSA_PROP_DATA;
   11498   if (prop_flags->is_unreachable)
   11499     num |= XTENSA_PROP_UNREACHABLE;
   11500   if (prop_flags->insn.is_loop_target)
   11501     num |= XTENSA_PROP_INSN_LOOP_TARGET;
   11502   if (prop_flags->insn.is_branch_target)
   11503     {
   11504       num |= XTENSA_PROP_INSN_BRANCH_TARGET;
   11505       num = SET_XTENSA_PROP_BT_ALIGN (num, prop_flags->insn.bt_align_priority);
   11506     }
   11507 
   11508   if (prop_flags->insn.is_no_density)
   11509     num |= XTENSA_PROP_INSN_NO_DENSITY;
   11510   if (prop_flags->is_no_transform)
   11511     num |= XTENSA_PROP_NO_TRANSFORM;
   11512   if (prop_flags->insn.is_no_reorder)
   11513     num |= XTENSA_PROP_INSN_NO_REORDER;
   11514   if (prop_flags->insn.is_abslit)
   11515     num |= XTENSA_PROP_INSN_ABSLIT;
   11516 
   11517   if (prop_flags->is_align)
   11518     {
   11519       num |= XTENSA_PROP_ALIGN;
   11520       num = SET_XTENSA_PROP_ALIGNMENT (num, prop_flags->alignment);
   11521     }
   11522 
   11523   return num;
   11524 }
   11525 
   11526 
   11527 static bfd_boolean
   11528 xtensa_frag_flags_combinable (const frag_flags *prop_flags_1,
   11529 			      const frag_flags *prop_flags_2)
   11530 {
   11531   /* Cannot combine with an end marker.  */
   11532 
   11533   if (prop_flags_1->is_literal != prop_flags_2->is_literal)
   11534     return FALSE;
   11535   if (prop_flags_1->is_insn != prop_flags_2->is_insn)
   11536     return FALSE;
   11537   if (prop_flags_1->is_data != prop_flags_2->is_data)
   11538     return FALSE;
   11539 
   11540   if (prop_flags_1->is_insn)
   11541     {
   11542       /* Properties of the beginning of the frag.  */
   11543       if (prop_flags_2->insn.is_loop_target)
   11544 	return FALSE;
   11545       if (prop_flags_2->insn.is_branch_target)
   11546 	return FALSE;
   11547       if (prop_flags_1->insn.is_no_density !=
   11548 	  prop_flags_2->insn.is_no_density)
   11549 	return FALSE;
   11550       if (prop_flags_1->is_no_transform !=
   11551 	  prop_flags_2->is_no_transform)
   11552 	return FALSE;
   11553       if (prop_flags_1->insn.is_no_reorder !=
   11554 	  prop_flags_2->insn.is_no_reorder)
   11555 	return FALSE;
   11556       if (prop_flags_1->insn.is_abslit !=
   11557 	  prop_flags_2->insn.is_abslit)
   11558 	return FALSE;
   11559     }
   11560 
   11561   if (prop_flags_1->is_align)
   11562     return FALSE;
   11563 
   11564   return TRUE;
   11565 }
   11566 
   11567 
   11568 static bfd_vma
   11569 xt_block_aligned_size (const xtensa_block_info *xt_block)
   11570 {
   11571   bfd_vma end_addr;
   11572   unsigned align_bits;
   11573 
   11574   if (!xt_block->flags.is_align)
   11575     return xt_block->size;
   11576 
   11577   end_addr = xt_block->offset + xt_block->size;
   11578   align_bits = xt_block->flags.alignment;
   11579   end_addr = ((end_addr + ((1 << align_bits) -1)) >> align_bits) << align_bits;
   11580   return end_addr - xt_block->offset;
   11581 }
   11582 
   11583 
   11584 static bfd_boolean
   11585 xtensa_xt_block_combine (xtensa_block_info *xt_block,
   11586 			 const xtensa_block_info *xt_block_2)
   11587 {
   11588   if (xt_block->sec != xt_block_2->sec)
   11589     return FALSE;
   11590   if (xt_block->offset + xt_block_aligned_size (xt_block)
   11591       != xt_block_2->offset)
   11592     return FALSE;
   11593 
   11594   if (xt_block_2->size == 0
   11595       && (!xt_block_2->flags.is_unreachable
   11596 	  || xt_block->flags.is_unreachable))
   11597     {
   11598       if (xt_block_2->flags.is_align
   11599 	  && xt_block->flags.is_align)
   11600 	{
   11601 	  /* Nothing needed.  */
   11602 	  if (xt_block->flags.alignment >= xt_block_2->flags.alignment)
   11603 	    return TRUE;
   11604 	}
   11605       else
   11606 	{
   11607 	  if (xt_block_2->flags.is_align)
   11608 	    {
   11609 	      /* Push alignment to previous entry.  */
   11610 	      xt_block->flags.is_align = xt_block_2->flags.is_align;
   11611 	      xt_block->flags.alignment = xt_block_2->flags.alignment;
   11612 	    }
   11613 	  return TRUE;
   11614 	}
   11615     }
   11616   if (!xtensa_frag_flags_combinable (&xt_block->flags,
   11617 				     &xt_block_2->flags))
   11618     return FALSE;
   11619 
   11620   xt_block->size += xt_block_2->size;
   11621 
   11622   if (xt_block_2->flags.is_align)
   11623     {
   11624       xt_block->flags.is_align = TRUE;
   11625       xt_block->flags.alignment = xt_block_2->flags.alignment;
   11626     }
   11627 
   11628   return TRUE;
   11629 }
   11630 
   11631 
   11632 static void
   11633 add_xt_prop_frags (segT sec,
   11634 		   xtensa_block_info **xt_block,
   11635 		   frag_flags_fn property_function)
   11636 {
   11637   fragS *fragP;
   11638 
   11639   /* Build it if needed.  */
   11640   while (*xt_block != NULL)
   11641     {
   11642       xt_block = &(*xt_block)->next;
   11643     }
   11644   /* We are either at NULL at the beginning or at the end.  */
   11645 
   11646   /* Walk through the frags.  */
   11647   if (seg_info (sec)->frchainP)
   11648     {
   11649       for (fragP = seg_info (sec)->frchainP->frch_root; fragP;
   11650 	   fragP = fragP->fr_next)
   11651 	{
   11652 	  xtensa_block_info tmp_block;
   11653 	  tmp_block.sec = sec;
   11654 	  tmp_block.offset = fragP->fr_address;
   11655 	  tmp_block.size = fragP->fr_fix;
   11656 	  tmp_block.next = NULL;
   11657 	  property_function (fragP, &tmp_block.flags);
   11658 
   11659 	  if (!xtensa_frag_flags_is_empty (&tmp_block.flags))
   11660 	    /* && fragP->fr_fix != 0) */
   11661 	    {
   11662 	      if ((*xt_block) == NULL
   11663 		  || !xtensa_xt_block_combine (*xt_block, &tmp_block))
   11664 		{
   11665 		  xtensa_block_info *new_block;
   11666 		  if ((*xt_block) != NULL)
   11667 		    xt_block = &(*xt_block)->next;
   11668 		  new_block = (xtensa_block_info *)
   11669 		    xmalloc (sizeof (xtensa_block_info));
   11670 		  *new_block = tmp_block;
   11671 		  *xt_block = new_block;
   11672 		}
   11673 	    }
   11674 	}
   11675     }
   11676 }
   11677 
   11678 
   11679 /* op_placement_info_table */
   11681 
   11682 /* op_placement_info makes it easier to determine which
   11683    ops can go in which slots.  */
   11684 
   11685 static void
   11686 init_op_placement_info_table (void)
   11687 {
   11688   xtensa_isa isa = xtensa_default_isa;
   11689   xtensa_insnbuf ibuf = xtensa_insnbuf_alloc (isa);
   11690   xtensa_opcode opcode;
   11691   xtensa_format fmt;
   11692   int slot;
   11693   int num_opcodes = xtensa_isa_num_opcodes (isa);
   11694 
   11695   op_placement_table = (op_placement_info_table)
   11696     xmalloc (sizeof (op_placement_info) * num_opcodes);
   11697   gas_assert (xtensa_isa_num_formats (isa) < MAX_FORMATS);
   11698 
   11699   for (opcode = 0; opcode < num_opcodes; opcode++)
   11700     {
   11701       op_placement_info *opi = &op_placement_table[opcode];
   11702       /* FIXME: Make tinsn allocation dynamic.  */
   11703       if (xtensa_opcode_num_operands (isa, opcode) > MAX_INSN_ARGS)
   11704 	as_fatal (_("too many operands in instruction"));
   11705       opi->narrowest = XTENSA_UNDEFINED;
   11706       opi->narrowest_size = 0x7F;
   11707       opi->narrowest_slot = 0;
   11708       opi->formats = 0;
   11709       opi->num_formats = 0;
   11710       opi->issuef = 0;
   11711       for (fmt = 0; fmt < xtensa_isa_num_formats (isa); fmt++)
   11712 	{
   11713 	  opi->slots[fmt] = 0;
   11714 	  for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
   11715 	    {
   11716 	      if (xtensa_opcode_encode (isa, fmt, slot, ibuf, opcode) == 0)
   11717 		{
   11718 		  int fmt_length = xtensa_format_length (isa, fmt);
   11719 		  opi->issuef++;
   11720 		  set_bit (fmt, opi->formats);
   11721 		  set_bit (slot, opi->slots[fmt]);
   11722 		  if (fmt_length < opi->narrowest_size
   11723 		      || (fmt_length == opi->narrowest_size
   11724 			  && (xtensa_format_num_slots (isa, fmt)
   11725 			      < xtensa_format_num_slots (isa,
   11726 							 opi->narrowest))))
   11727 		    {
   11728 		      opi->narrowest = fmt;
   11729 		      opi->narrowest_size = fmt_length;
   11730 		      opi->narrowest_slot = slot;
   11731 		    }
   11732 		}
   11733 	    }
   11734 	  if (opi->formats)
   11735 	    opi->num_formats++;
   11736 	}
   11737     }
   11738   xtensa_insnbuf_free (isa, ibuf);
   11739 }
   11740 
   11741 
   11742 bfd_boolean
   11743 opcode_fits_format_slot (xtensa_opcode opcode, xtensa_format fmt, int slot)
   11744 {
   11745   return bit_is_set (slot, op_placement_table[opcode].slots[fmt]);
   11746 }
   11747 
   11748 
   11749 /* If the opcode is available in a single slot format, return its size.  */
   11750 
   11751 static int
   11752 xg_get_single_size (xtensa_opcode opcode)
   11753 {
   11754   return op_placement_table[opcode].narrowest_size;
   11755 }
   11756 
   11757 
   11758 static xtensa_format
   11759 xg_get_single_format (xtensa_opcode opcode)
   11760 {
   11761   return op_placement_table[opcode].narrowest;
   11762 }
   11763 
   11764 
   11765 static int
   11766 xg_get_single_slot (xtensa_opcode opcode)
   11767 {
   11768   return op_placement_table[opcode].narrowest_slot;
   11769 }
   11770 
   11771 
   11772 /* Instruction Stack Functions (from "xtensa-istack.h").  */
   11774 
   11775 void
   11776 istack_init (IStack *stack)
   11777 {
   11778   stack->ninsn = 0;
   11779 }
   11780 
   11781 
   11782 bfd_boolean
   11783 istack_empty (IStack *stack)
   11784 {
   11785   return (stack->ninsn == 0);
   11786 }
   11787 
   11788 
   11789 bfd_boolean
   11790 istack_full (IStack *stack)
   11791 {
   11792   return (stack->ninsn == MAX_ISTACK);
   11793 }
   11794 
   11795 
   11796 /* Return a pointer to the top IStack entry.
   11797    It is an error to call this if istack_empty () is TRUE. */
   11798 
   11799 TInsn *
   11800 istack_top (IStack *stack)
   11801 {
   11802   int rec = stack->ninsn - 1;
   11803   gas_assert (!istack_empty (stack));
   11804   return &stack->insn[rec];
   11805 }
   11806 
   11807 
   11808 /* Add a new TInsn to an IStack.
   11809    It is an error to call this if istack_full () is TRUE.  */
   11810 
   11811 void
   11812 istack_push (IStack *stack, TInsn *insn)
   11813 {
   11814   int rec = stack->ninsn;
   11815   gas_assert (!istack_full (stack));
   11816   stack->insn[rec] = *insn;
   11817   stack->ninsn++;
   11818 }
   11819 
   11820 
   11821 /* Clear space for the next TInsn on the IStack and return a pointer
   11822    to it.  It is an error to call this if istack_full () is TRUE.  */
   11823 
   11824 TInsn *
   11825 istack_push_space (IStack *stack)
   11826 {
   11827   int rec = stack->ninsn;
   11828   TInsn *insn;
   11829   gas_assert (!istack_full (stack));
   11830   insn = &stack->insn[rec];
   11831   tinsn_init (insn);
   11832   stack->ninsn++;
   11833   return insn;
   11834 }
   11835 
   11836 
   11837 /* Remove the last pushed instruction.  It is an error to call this if
   11838    istack_empty () returns TRUE.  */
   11839 
   11840 void
   11841 istack_pop (IStack *stack)
   11842 {
   11843   int rec = stack->ninsn - 1;
   11844   gas_assert (!istack_empty (stack));
   11845   stack->ninsn--;
   11846   tinsn_init (&stack->insn[rec]);
   11847 }
   11848 
   11849 
   11850 /* TInsn functions.  */
   11852 
   11853 void
   11854 tinsn_init (TInsn *dst)
   11855 {
   11856   memset (dst, 0, sizeof (TInsn));
   11857 }
   11858 
   11859 
   11860 /* Return TRUE if ANY of the operands in the insn are symbolic.  */
   11861 
   11862 static bfd_boolean
   11863 tinsn_has_symbolic_operands (const TInsn *insn)
   11864 {
   11865   int i;
   11866   int n = insn->ntok;
   11867 
   11868   gas_assert (insn->insn_type == ITYPE_INSN);
   11869 
   11870   for (i = 0; i < n; ++i)
   11871     {
   11872       switch (insn->tok[i].X_op)
   11873 	{
   11874 	case O_register:
   11875 	case O_constant:
   11876 	  break;
   11877 	default:
   11878 	  return TRUE;
   11879 	}
   11880     }
   11881   return FALSE;
   11882 }
   11883 
   11884 
   11885 bfd_boolean
   11886 tinsn_has_invalid_symbolic_operands (const TInsn *insn)
   11887 {
   11888   xtensa_isa isa = xtensa_default_isa;
   11889   int i;
   11890   int n = insn->ntok;
   11891 
   11892   gas_assert (insn->insn_type == ITYPE_INSN);
   11893 
   11894   for (i = 0; i < n; ++i)
   11895     {
   11896       switch (insn->tok[i].X_op)
   11897 	{
   11898 	case O_register:
   11899 	case O_constant:
   11900 	  break;
   11901 	case O_big:
   11902 	case O_illegal:
   11903 	case O_absent:
   11904 	  /* Errors for these types are caught later.  */
   11905 	  break;
   11906 	case O_hi16:
   11907 	case O_lo16:
   11908 	default:
   11909 	  /* Symbolic immediates are only allowed on the last immediate
   11910 	     operand.  At this time, CONST16 is the only opcode where we
   11911 	     support non-PC-relative relocations.  */
   11912 	  if (i != get_relaxable_immed (insn->opcode)
   11913 	      || (xtensa_operand_is_PCrelative (isa, insn->opcode, i) != 1
   11914 		  && insn->opcode != xtensa_const16_opcode))
   11915 	    {
   11916 	      as_bad (_("invalid symbolic operand"));
   11917 	      return TRUE;
   11918 	    }
   11919 	}
   11920     }
   11921   return FALSE;
   11922 }
   11923 
   11924 
   11925 /* For assembly code with complex expressions (e.g. subtraction),
   11926    we have to build them in the literal pool so that
   11927    their results are calculated correctly after relaxation.
   11928    The relaxation only handles expressions that
   11929    boil down to SYMBOL + OFFSET.  */
   11930 
   11931 static bfd_boolean
   11932 tinsn_has_complex_operands (const TInsn *insn)
   11933 {
   11934   int i;
   11935   int n = insn->ntok;
   11936   gas_assert (insn->insn_type == ITYPE_INSN);
   11937   for (i = 0; i < n; ++i)
   11938     {
   11939       switch (insn->tok[i].X_op)
   11940 	{
   11941 	case O_register:
   11942 	case O_constant:
   11943 	case O_symbol:
   11944 	case O_lo16:
   11945 	case O_hi16:
   11946 	  break;
   11947 	default:
   11948 	  return TRUE;
   11949 	}
   11950     }
   11951   return FALSE;
   11952 }
   11953 
   11954 
   11955 /* Encode a TInsn opcode and its constant operands into slotbuf.
   11956    Return TRUE if there is a symbol in the immediate field.  This
   11957    function assumes that:
   11958    1) The number of operands are correct.
   11959    2) The insn_type is ITYPE_INSN.
   11960    3) The opcode can be encoded in the specified format and slot.
   11961    4) Operands are either O_constant or O_symbol, and all constants fit.  */
   11962 
   11963 static bfd_boolean
   11964 tinsn_to_slotbuf (xtensa_format fmt,
   11965 		  int slot,
   11966 		  TInsn *tinsn,
   11967 		  xtensa_insnbuf slotbuf)
   11968 {
   11969   xtensa_isa isa = xtensa_default_isa;
   11970   xtensa_opcode opcode = tinsn->opcode;
   11971   bfd_boolean has_fixup = FALSE;
   11972   int noperands = xtensa_opcode_num_operands (isa, opcode);
   11973   int i;
   11974 
   11975   gas_assert (tinsn->insn_type == ITYPE_INSN);
   11976   if (noperands != tinsn->ntok)
   11977     as_fatal (_("operand number mismatch"));
   11978 
   11979   if (xtensa_opcode_encode (isa, fmt, slot, slotbuf, opcode))
   11980     {
   11981       as_bad (_("cannot encode opcode \"%s\" in the given format \"%s\""),
   11982 	      xtensa_opcode_name (isa, opcode), xtensa_format_name (isa, fmt));
   11983       return FALSE;
   11984     }
   11985 
   11986   for (i = 0; i < noperands; i++)
   11987     {
   11988       expressionS *exp = &tinsn->tok[i];
   11989       int rc;
   11990       unsigned line;
   11991       char *file_name;
   11992       uint32 opnd_value;
   11993 
   11994       switch (exp->X_op)
   11995 	{
   11996 	case O_register:
   11997 	  if (xtensa_operand_is_visible (isa, opcode, i) == 0)
   11998 	    break;
   11999 	  /* The register number has already been checked in
   12000 	     expression_maybe_register, so we don't need to check here.  */
   12001 	  opnd_value = exp->X_add_number;
   12002 	  (void) xtensa_operand_encode (isa, opcode, i, &opnd_value);
   12003 	  rc = xtensa_operand_set_field (isa, opcode, i, fmt, slot, slotbuf,
   12004 					 opnd_value);
   12005 	  if (rc != 0)
   12006 	    as_warn (_("xtensa-isa failure: %s"), xtensa_isa_error_msg (isa));
   12007 	  break;
   12008 
   12009 	case O_constant:
   12010 	  if (xtensa_operand_is_visible (isa, opcode, i) == 0)
   12011 	    break;
   12012 	  as_where (&file_name, &line);
   12013 	  /* It is a constant and we called this function
   12014 	     then we have to try to fit it.  */
   12015 	  xtensa_insnbuf_set_operand (slotbuf, fmt, slot, opcode, i,
   12016 				      exp->X_add_number, file_name, line);
   12017 	  break;
   12018 
   12019 	default:
   12020 	  has_fixup = TRUE;
   12021 	  break;
   12022 	}
   12023     }
   12024 
   12025   return has_fixup;
   12026 }
   12027 
   12028 
   12029 /* Encode a single TInsn into an insnbuf.  If the opcode can only be encoded
   12030    into a multi-slot instruction, fill the other slots with NOPs.
   12031    Return TRUE if there is a symbol in the immediate field.  See also the
   12032    assumptions listed for tinsn_to_slotbuf.  */
   12033 
   12034 static bfd_boolean
   12035 tinsn_to_insnbuf (TInsn *tinsn, xtensa_insnbuf insnbuf)
   12036 {
   12037   static xtensa_insnbuf slotbuf = 0;
   12038   static vliw_insn vinsn;
   12039   xtensa_isa isa = xtensa_default_isa;
   12040   bfd_boolean has_fixup = FALSE;
   12041   int i;
   12042 
   12043   if (!slotbuf)
   12044     {
   12045       slotbuf = xtensa_insnbuf_alloc (isa);
   12046       xg_init_vinsn (&vinsn);
   12047     }
   12048 
   12049   xg_clear_vinsn (&vinsn);
   12050 
   12051   bundle_tinsn (tinsn, &vinsn);
   12052 
   12053   xtensa_format_encode (isa, vinsn.format, insnbuf);
   12054 
   12055   for (i = 0; i < vinsn.num_slots; i++)
   12056     {
   12057       /* Only one slot may have a fix-up because the rest contains NOPs.  */
   12058       has_fixup |=
   12059 	tinsn_to_slotbuf (vinsn.format, i, &vinsn.slots[i], vinsn.slotbuf[i]);
   12060       xtensa_format_set_slot (isa, vinsn.format, i, insnbuf, vinsn.slotbuf[i]);
   12061     }
   12062 
   12063   return has_fixup;
   12064 }
   12065 
   12066 
   12067 /* Check the instruction arguments.  Return TRUE on failure.  */
   12068 
   12069 static bfd_boolean
   12070 tinsn_check_arguments (const TInsn *insn)
   12071 {
   12072   xtensa_isa isa = xtensa_default_isa;
   12073   xtensa_opcode opcode = insn->opcode;
   12074   xtensa_regfile t1_regfile, t2_regfile;
   12075   int t1_reg, t2_reg;
   12076   int t1_base_reg, t1_last_reg;
   12077   int t2_base_reg, t2_last_reg;
   12078   char t1_inout, t2_inout;
   12079   int i, j;
   12080 
   12081   if (opcode == XTENSA_UNDEFINED)
   12082     {
   12083       as_bad (_("invalid opcode"));
   12084       return TRUE;
   12085     }
   12086 
   12087   if (xtensa_opcode_num_operands (isa, opcode) > insn->ntok)
   12088     {
   12089       as_bad (_("too few operands"));
   12090       return TRUE;
   12091     }
   12092 
   12093   if (xtensa_opcode_num_operands (isa, opcode) < insn->ntok)
   12094     {
   12095       as_bad (_("too many operands"));
   12096       return TRUE;
   12097     }
   12098 
   12099   /* Check registers.  */
   12100   for (j = 0; j < insn->ntok; j++)
   12101     {
   12102       if (xtensa_operand_is_register (isa, insn->opcode, j) != 1)
   12103 	continue;
   12104 
   12105       t2_regfile = xtensa_operand_regfile (isa, insn->opcode, j);
   12106       t2_base_reg = insn->tok[j].X_add_number;
   12107       t2_last_reg
   12108 	= t2_base_reg + xtensa_operand_num_regs (isa, insn->opcode, j);
   12109 
   12110       for (i = 0; i < insn->ntok; i++)
   12111 	{
   12112 	  if (i == j)
   12113 	    continue;
   12114 
   12115 	  if (xtensa_operand_is_register (isa, insn->opcode, i) != 1)
   12116 	    continue;
   12117 
   12118 	  t1_regfile = xtensa_operand_regfile (isa, insn->opcode, i);
   12119 
   12120 	  if (t1_regfile != t2_regfile)
   12121 	    continue;
   12122 
   12123 	  t1_inout = xtensa_operand_inout (isa, insn->opcode, i);
   12124 	  t2_inout = xtensa_operand_inout (isa, insn->opcode, j);
   12125 
   12126 	  t1_base_reg = insn->tok[i].X_add_number;
   12127 	  t1_last_reg = (t1_base_reg
   12128 			 + xtensa_operand_num_regs (isa, insn->opcode, i));
   12129 
   12130 	  for (t1_reg = t1_base_reg; t1_reg < t1_last_reg; t1_reg++)
   12131 	    {
   12132 	      for (t2_reg = t2_base_reg; t2_reg < t2_last_reg; t2_reg++)
   12133 		{
   12134 		  if (t1_reg != t2_reg)
   12135 		    continue;
   12136 
   12137 		  if (t1_inout != 'i' && t2_inout != 'i')
   12138 		    {
   12139 		      as_bad (_("multiple writes to the same register"));
   12140 		      return TRUE;
   12141 		    }
   12142 		}
   12143 	    }
   12144 	}
   12145     }
   12146   return FALSE;
   12147 }
   12148 
   12149 
   12150 /* Load an instruction from its encoded form.  */
   12151 
   12152 static void
   12153 tinsn_from_chars (TInsn *tinsn, char *f, int slot)
   12154 {
   12155   vliw_insn vinsn;
   12156 
   12157   xg_init_vinsn (&vinsn);
   12158   vinsn_from_chars (&vinsn, f);
   12159 
   12160   *tinsn = vinsn.slots[slot];
   12161   xg_free_vinsn (&vinsn);
   12162 }
   12163 
   12164 
   12165 static void
   12166 tinsn_from_insnbuf (TInsn *tinsn,
   12167 		    xtensa_insnbuf slotbuf,
   12168 		    xtensa_format fmt,
   12169 		    int slot)
   12170 {
   12171   int i;
   12172   xtensa_isa isa = xtensa_default_isa;
   12173 
   12174   /* Find the immed.  */
   12175   tinsn_init (tinsn);
   12176   tinsn->insn_type = ITYPE_INSN;
   12177   tinsn->is_specific_opcode = FALSE;	/* must not be specific */
   12178   tinsn->opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
   12179   tinsn->ntok = xtensa_opcode_num_operands (isa, tinsn->opcode);
   12180   for (i = 0; i < tinsn->ntok; i++)
   12181     {
   12182       set_expr_const (&tinsn->tok[i],
   12183 		      xtensa_insnbuf_get_operand (slotbuf, fmt, slot,
   12184 						  tinsn->opcode, i));
   12185     }
   12186 }
   12187 
   12188 
   12189 /* Read the value of the relaxable immed from the fr_symbol and fr_offset.  */
   12190 
   12191 static void
   12192 tinsn_immed_from_frag (TInsn *tinsn, fragS *fragP, int slot)
   12193 {
   12194   xtensa_opcode opcode = tinsn->opcode;
   12195   int opnum;
   12196 
   12197   if (fragP->tc_frag_data.slot_symbols[slot])
   12198     {
   12199       opnum = get_relaxable_immed (opcode);
   12200       gas_assert (opnum >= 0);
   12201       set_expr_symbol_offset (&tinsn->tok[opnum],
   12202 			      fragP->tc_frag_data.slot_symbols[slot],
   12203 			      fragP->tc_frag_data.slot_offsets[slot]);
   12204     }
   12205   tinsn->extra_arg = fragP->tc_frag_data.free_reg[slot];
   12206 }
   12207 
   12208 
   12209 static int
   12210 get_num_stack_text_bytes (IStack *istack)
   12211 {
   12212   int i;
   12213   int text_bytes = 0;
   12214 
   12215   for (i = 0; i < istack->ninsn; i++)
   12216     {
   12217       TInsn *tinsn = &istack->insn[i];
   12218       if (tinsn->insn_type == ITYPE_INSN)
   12219 	text_bytes += xg_get_single_size (tinsn->opcode);
   12220     }
   12221   return text_bytes;
   12222 }
   12223 
   12224 
   12225 static int
   12226 get_num_stack_literal_bytes (IStack *istack)
   12227 {
   12228   int i;
   12229   int lit_bytes = 0;
   12230 
   12231   for (i = 0; i < istack->ninsn; i++)
   12232     {
   12233       TInsn *tinsn = &istack->insn[i];
   12234       if (tinsn->insn_type == ITYPE_LITERAL && tinsn->ntok == 1)
   12235 	lit_bytes += 4;
   12236     }
   12237   return lit_bytes;
   12238 }
   12239 
   12240 
   12241 /* vliw_insn functions.  */
   12243 
   12244 static void
   12245 xg_init_vinsn (vliw_insn *v)
   12246 {
   12247   int i;
   12248   xtensa_isa isa = xtensa_default_isa;
   12249 
   12250   xg_clear_vinsn (v);
   12251 
   12252   v->insnbuf = xtensa_insnbuf_alloc (isa);
   12253   if (v->insnbuf == NULL)
   12254     as_fatal (_("out of memory"));
   12255 
   12256   for (i = 0; i < config_max_slots; i++)
   12257     {
   12258       v->slotbuf[i] = xtensa_insnbuf_alloc (isa);
   12259       if (v->slotbuf[i] == NULL)
   12260 	as_fatal (_("out of memory"));
   12261     }
   12262 }
   12263 
   12264 
   12265 static void
   12266 xg_clear_vinsn (vliw_insn *v)
   12267 {
   12268   int i;
   12269 
   12270   memset (v, 0, offsetof (vliw_insn, slots)
   12271                 + sizeof(TInsn) * config_max_slots);
   12272 
   12273   v->format = XTENSA_UNDEFINED;
   12274   v->num_slots = 0;
   12275   v->inside_bundle = FALSE;
   12276 
   12277   if (xt_saved_debug_type != DEBUG_NONE)
   12278     debug_type = xt_saved_debug_type;
   12279 
   12280   for (i = 0; i < config_max_slots; i++)
   12281     v->slots[i].opcode = XTENSA_UNDEFINED;
   12282 }
   12283 
   12284 
   12285 static void
   12286 xg_copy_vinsn (vliw_insn *dst, vliw_insn *src)
   12287 {
   12288   memcpy (dst, src,
   12289 	  offsetof(vliw_insn, slots) + src->num_slots * sizeof(TInsn));
   12290   dst->insnbuf = src->insnbuf;
   12291   memcpy (dst->slotbuf, src->slotbuf, src->num_slots * sizeof(xtensa_insnbuf));
   12292 }
   12293 
   12294 
   12295 static bfd_boolean
   12296 vinsn_has_specific_opcodes (vliw_insn *v)
   12297 {
   12298   int i;
   12299 
   12300   for (i = 0; i < v->num_slots; i++)
   12301     {
   12302       if (v->slots[i].is_specific_opcode)
   12303 	return TRUE;
   12304     }
   12305   return FALSE;
   12306 }
   12307 
   12308 
   12309 static void
   12310 xg_free_vinsn (vliw_insn *v)
   12311 {
   12312   int i;
   12313   xtensa_insnbuf_free (xtensa_default_isa, v->insnbuf);
   12314   for (i = 0; i < config_max_slots; i++)
   12315     xtensa_insnbuf_free (xtensa_default_isa, v->slotbuf[i]);
   12316 }
   12317 
   12318 
   12319 /* Encode a vliw_insn into an insnbuf.  Return TRUE if there are any symbolic
   12320    operands.  See also the assumptions listed for tinsn_to_slotbuf.  */
   12321 
   12322 static bfd_boolean
   12323 vinsn_to_insnbuf (vliw_insn *vinsn,
   12324 		  char *frag_offset,
   12325 		  fragS *fragP,
   12326 		  bfd_boolean record_fixup)
   12327 {
   12328   xtensa_isa isa = xtensa_default_isa;
   12329   xtensa_format fmt = vinsn->format;
   12330   xtensa_insnbuf insnbuf = vinsn->insnbuf;
   12331   int slot;
   12332   bfd_boolean has_fixup = FALSE;
   12333 
   12334   xtensa_format_encode (isa, fmt, insnbuf);
   12335 
   12336   for (slot = 0; slot < vinsn->num_slots; slot++)
   12337     {
   12338       TInsn *tinsn = &vinsn->slots[slot];
   12339       expressionS *extra_arg = &tinsn->extra_arg;
   12340       bfd_boolean tinsn_has_fixup =
   12341 	tinsn_to_slotbuf (vinsn->format, slot, tinsn,
   12342 			  vinsn->slotbuf[slot]);
   12343 
   12344       xtensa_format_set_slot (isa, fmt, slot,
   12345 			      insnbuf, vinsn->slotbuf[slot]);
   12346       if (extra_arg->X_op != O_illegal && extra_arg->X_op != O_register)
   12347 	{
   12348 	  if (vinsn->num_slots != 1)
   12349 	    as_bad (_("TLS relocation not allowed in FLIX bundle"));
   12350 	  else if (record_fixup)
   12351 	    /* Instructions that generate TLS relocations should always be
   12352 	       relaxed in the front-end.  If "record_fixup" is set, then this
   12353 	       function is being called during back-end relaxation, so flag
   12354 	       the unexpected behavior as an error.  */
   12355 	    as_bad (_("unexpected TLS relocation"));
   12356 	  else
   12357 	    fix_new (fragP, frag_offset - fragP->fr_literal,
   12358 		     xtensa_format_length (isa, fmt),
   12359 		     extra_arg->X_add_symbol, extra_arg->X_add_number,
   12360 		     FALSE, map_operator_to_reloc (extra_arg->X_op, FALSE));
   12361 	}
   12362       if (tinsn_has_fixup)
   12363 	{
   12364 	  int i;
   12365 	  xtensa_opcode opcode = tinsn->opcode;
   12366 	  int noperands = xtensa_opcode_num_operands (isa, opcode);
   12367 	  has_fixup = TRUE;
   12368 
   12369 	  for (i = 0; i < noperands; i++)
   12370 	    {
   12371 	      expressionS* exp = &tinsn->tok[i];
   12372 	      switch (exp->X_op)
   12373 		{
   12374 		case O_symbol:
   12375 		case O_lo16:
   12376 		case O_hi16:
   12377 		  if (get_relaxable_immed (opcode) == i)
   12378 		    {
   12379 		      /* Add a fix record for the instruction, except if this
   12380 			 function is being called prior to relaxation, i.e.,
   12381 			 if record_fixup is false, and the instruction might
   12382 			 be relaxed later.  */
   12383 		      if (record_fixup
   12384 			  || tinsn->is_specific_opcode
   12385 			  || !xg_is_relaxable_insn (tinsn, 0))
   12386 			{
   12387 			  xg_add_opcode_fix (tinsn, i, fmt, slot, exp, fragP,
   12388 					     frag_offset - fragP->fr_literal);
   12389 			}
   12390 		      else
   12391 			{
   12392 			  if (exp->X_op != O_symbol)
   12393 			    as_bad (_("invalid operand"));
   12394 			  tinsn->symbol = exp->X_add_symbol;
   12395 			  tinsn->offset = exp->X_add_number;
   12396 			}
   12397 		    }
   12398 		  else
   12399 		    as_bad (_("symbolic operand not allowed"));
   12400 		  break;
   12401 
   12402 		case O_constant:
   12403 		case O_register:
   12404 		  break;
   12405 
   12406 		default:
   12407 		  as_bad (_("expression too complex"));
   12408 		  break;
   12409 		}
   12410 	    }
   12411 	}
   12412     }
   12413 
   12414   return has_fixup;
   12415 }
   12416 
   12417 
   12418 static void
   12419 vinsn_from_chars (vliw_insn *vinsn, char *f)
   12420 {
   12421   static xtensa_insnbuf insnbuf = NULL;
   12422   static xtensa_insnbuf slotbuf = NULL;
   12423   int i;
   12424   xtensa_format fmt;
   12425   xtensa_isa isa = xtensa_default_isa;
   12426 
   12427   if (!insnbuf)
   12428     {
   12429       insnbuf = xtensa_insnbuf_alloc (isa);
   12430       slotbuf = xtensa_insnbuf_alloc (isa);
   12431     }
   12432 
   12433   xtensa_insnbuf_from_chars (isa, insnbuf, (unsigned char *) f, 0);
   12434   fmt = xtensa_format_decode (isa, insnbuf);
   12435   if (fmt == XTENSA_UNDEFINED)
   12436     as_fatal (_("cannot decode instruction format"));
   12437   vinsn->format = fmt;
   12438   vinsn->num_slots = xtensa_format_num_slots (isa, fmt);
   12439 
   12440   for (i = 0; i < vinsn->num_slots; i++)
   12441     {
   12442       TInsn *tinsn = &vinsn->slots[i];
   12443       xtensa_format_get_slot (isa, fmt, i, insnbuf, slotbuf);
   12444       tinsn_from_insnbuf (tinsn, slotbuf, fmt, i);
   12445     }
   12446 }
   12447 
   12448 
   12449 /* Expression utilities.  */
   12451 
   12452 /* Return TRUE if the expression is an integer constant.  */
   12453 
   12454 bfd_boolean
   12455 expr_is_const (const expressionS *s)
   12456 {
   12457   return (s->X_op == O_constant);
   12458 }
   12459 
   12460 
   12461 /* Get the expression constant.
   12462    Calling this is illegal if expr_is_const () returns TRUE.  */
   12463 
   12464 offsetT
   12465 get_expr_const (const expressionS *s)
   12466 {
   12467   gas_assert (expr_is_const (s));
   12468   return s->X_add_number;
   12469 }
   12470 
   12471 
   12472 /* Set the expression to a constant value.  */
   12473 
   12474 void
   12475 set_expr_const (expressionS *s, offsetT val)
   12476 {
   12477   s->X_op = O_constant;
   12478   s->X_add_number = val;
   12479   s->X_add_symbol = NULL;
   12480   s->X_op_symbol = NULL;
   12481 }
   12482 
   12483 
   12484 bfd_boolean
   12485 expr_is_register (const expressionS *s)
   12486 {
   12487   return (s->X_op == O_register);
   12488 }
   12489 
   12490 
   12491 /* Get the expression constant.
   12492    Calling this is illegal if expr_is_const () returns TRUE.  */
   12493 
   12494 offsetT
   12495 get_expr_register (const expressionS *s)
   12496 {
   12497   gas_assert (expr_is_register (s));
   12498   return s->X_add_number;
   12499 }
   12500 
   12501 
   12502 /* Set the expression to a symbol + constant offset.  */
   12503 
   12504 void
   12505 set_expr_symbol_offset (expressionS *s, symbolS *sym, offsetT offset)
   12506 {
   12507   s->X_op = O_symbol;
   12508   s->X_add_symbol = sym;
   12509   s->X_op_symbol = NULL;	/* unused */
   12510   s->X_add_number = offset;
   12511 }
   12512 
   12513 
   12514 /* Return TRUE if the two expressions are equal.  */
   12515 
   12516 bfd_boolean
   12517 expr_is_equal (expressionS *s1, expressionS *s2)
   12518 {
   12519   if (s1->X_op != s2->X_op)
   12520     return FALSE;
   12521   if (s1->X_add_symbol != s2->X_add_symbol)
   12522     return FALSE;
   12523   if (s1->X_op_symbol != s2->X_op_symbol)
   12524     return FALSE;
   12525   if (s1->X_add_number != s2->X_add_number)
   12526     return FALSE;
   12527   return TRUE;
   12528 }
   12529 
   12530 
   12531 static void
   12532 copy_expr (expressionS *dst, const expressionS *src)
   12533 {
   12534   memcpy (dst, src, sizeof (expressionS));
   12535 }
   12536 
   12537 
   12538 /* Support for the "--rename-section" option.  */
   12540 
   12541 struct rename_section_struct
   12542 {
   12543   char *old_name;
   12544   char *new_name;
   12545   struct rename_section_struct *next;
   12546 };
   12547 
   12548 static struct rename_section_struct *section_rename;
   12549 
   12550 
   12551 /* Parse the string "oldname=new_name(:oldname2=new_name2)*" and add
   12552    entries to the section_rename list.  Note: Specifying multiple
   12553    renamings separated by colons is not documented and is retained only
   12554    for backward compatibility.  */
   12555 
   12556 static void
   12557 build_section_rename (const char *arg)
   12558 {
   12559   struct rename_section_struct *r;
   12560   char *this_arg = NULL;
   12561   char *next_arg = NULL;
   12562 
   12563   for (this_arg = xstrdup (arg); this_arg != NULL; this_arg = next_arg)
   12564     {
   12565       char *old_name, *new_name;
   12566 
   12567       if (this_arg)
   12568 	{
   12569 	  next_arg = strchr (this_arg, ':');
   12570 	  if (next_arg)
   12571 	    {
   12572 	      *next_arg = '\0';
   12573 	      next_arg++;
   12574 	    }
   12575 	}
   12576 
   12577       old_name = this_arg;
   12578       new_name = strchr (this_arg, '=');
   12579 
   12580       if (*old_name == '\0')
   12581 	{
   12582 	  as_warn (_("ignoring extra '-rename-section' delimiter ':'"));
   12583 	  continue;
   12584 	}
   12585       if (!new_name || new_name[1] == '\0')
   12586 	{
   12587 	  as_warn (_("ignoring invalid '-rename-section' specification: '%s'"),
   12588 		   old_name);
   12589 	  continue;
   12590 	}
   12591       *new_name = '\0';
   12592       new_name++;
   12593 
   12594       /* Check for invalid section renaming.  */
   12595       for (r = section_rename; r != NULL; r = r->next)
   12596 	{
   12597 	  if (strcmp (r->old_name, old_name) == 0)
   12598 	    as_bad (_("section %s renamed multiple times"), old_name);
   12599 	  if (strcmp (r->new_name, new_name) == 0)
   12600 	    as_bad (_("multiple sections remapped to output section %s"),
   12601 		    new_name);
   12602 	}
   12603 
   12604       /* Now add it.  */
   12605       r = (struct rename_section_struct *)
   12606 	xmalloc (sizeof (struct rename_section_struct));
   12607       r->old_name = xstrdup (old_name);
   12608       r->new_name = xstrdup (new_name);
   12609       r->next = section_rename;
   12610       section_rename = r;
   12611     }
   12612 }
   12613 
   12614 
   12615 char *
   12616 xtensa_section_rename (char *name)
   12617 {
   12618   struct rename_section_struct *r = section_rename;
   12619 
   12620   for (r = section_rename; r != NULL; r = r->next)
   12621     {
   12622       if (strcmp (r->old_name, name) == 0)
   12623 	return r->new_name;
   12624     }
   12625 
   12626   return name;
   12627 }
   12628