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