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