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