packaging: Enable testing infrastructure
[external/binutils.git] / bfd / elf32-xtensa.c
1 /* Xtensa-specific support for 32-bit ELF.
2    Copyright (C) 2003-2019 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or
7    modify it under the terms of the GNU General Public License as
8    published by the Free Software Foundation; either version 3 of the
9    License, or (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful, but
12    WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
19    02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23
24 #include <stdarg.h>
25 #include <strings.h>
26
27 #include "bfdlink.h"
28 #include "libbfd.h"
29 #include "elf-bfd.h"
30 #include "elf/xtensa.h"
31 #include "splay-tree.h"
32 #include "xtensa-isa.h"
33 #include "xtensa-config.h"
34
35 #define XTENSA_NO_NOP_REMOVAL 0
36
37 /* Local helper functions.  */
38
39 static bfd_boolean add_extra_plt_sections (struct bfd_link_info *, int);
40 static char *vsprint_msg (const char *, const char *, int, ...) ATTRIBUTE_PRINTF(2,4);
41 static bfd_reloc_status_type bfd_elf_xtensa_reloc
42   (bfd *, arelent *, asymbol *, void *, asection *, bfd *, char **);
43 static bfd_boolean do_fix_for_relocatable_link
44   (Elf_Internal_Rela *, bfd *, asection *, bfd_byte *);
45 static void do_fix_for_final_link
46   (Elf_Internal_Rela *, bfd *, asection *, bfd_byte *, bfd_vma *);
47
48 /* Local functions to handle Xtensa configurability.  */
49
50 static bfd_boolean is_indirect_call_opcode (xtensa_opcode);
51 static bfd_boolean is_direct_call_opcode (xtensa_opcode);
52 static bfd_boolean is_windowed_call_opcode (xtensa_opcode);
53 static xtensa_opcode get_const16_opcode (void);
54 static xtensa_opcode get_l32r_opcode (void);
55 static bfd_vma l32r_offset (bfd_vma, bfd_vma);
56 static int get_relocation_opnd (xtensa_opcode, int);
57 static int get_relocation_slot (int);
58 static xtensa_opcode get_relocation_opcode
59   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *);
60 static bfd_boolean is_l32r_relocation
61   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *);
62 static bfd_boolean is_alt_relocation (int);
63 static bfd_boolean is_operand_relocation (int);
64 static bfd_size_type insn_decode_len
65   (bfd_byte *, bfd_size_type, bfd_size_type);
66 static int insn_num_slots
67   (bfd_byte *, bfd_size_type, bfd_size_type);
68 static xtensa_opcode insn_decode_opcode
69   (bfd_byte *, bfd_size_type, bfd_size_type, int);
70 static bfd_boolean check_branch_target_aligned
71   (bfd_byte *, bfd_size_type, bfd_vma, bfd_vma);
72 static bfd_boolean check_loop_aligned
73   (bfd_byte *, bfd_size_type, bfd_vma, bfd_vma);
74 static bfd_boolean check_branch_target_aligned_address (bfd_vma, int);
75 static bfd_size_type get_asm_simplify_size
76   (bfd_byte *, bfd_size_type, bfd_size_type);
77
78 /* Functions for link-time code simplifications.  */
79
80 static bfd_reloc_status_type elf_xtensa_do_asm_simplify
81   (bfd_byte *, bfd_vma, bfd_vma, char **);
82 static bfd_reloc_status_type contract_asm_expansion
83   (bfd_byte *, bfd_vma, Elf_Internal_Rela *, char **);
84 static xtensa_opcode swap_callx_for_call_opcode (xtensa_opcode);
85 static xtensa_opcode get_expanded_call_opcode (bfd_byte *, int, bfd_boolean *);
86
87 /* Access to internal relocations, section contents and symbols.  */
88
89 static Elf_Internal_Rela *retrieve_internal_relocs
90   (bfd *, asection *, bfd_boolean);
91 static void pin_internal_relocs (asection *, Elf_Internal_Rela *);
92 static void release_internal_relocs (asection *, Elf_Internal_Rela *);
93 static bfd_byte *retrieve_contents (bfd *, asection *, bfd_boolean);
94 static void pin_contents (asection *, bfd_byte *);
95 static void release_contents (asection *, bfd_byte *);
96 static Elf_Internal_Sym *retrieve_local_syms (bfd *);
97
98 /* Miscellaneous utility functions.  */
99
100 static asection *elf_xtensa_get_plt_section (struct bfd_link_info *, int);
101 static asection *elf_xtensa_get_gotplt_section (struct bfd_link_info *, int);
102 static asection *get_elf_r_symndx_section (bfd *, unsigned long);
103 static struct elf_link_hash_entry *get_elf_r_symndx_hash_entry
104   (bfd *, unsigned long);
105 static bfd_vma get_elf_r_symndx_offset (bfd *, unsigned long);
106 static bfd_boolean is_reloc_sym_weak (bfd *, Elf_Internal_Rela *);
107 static bfd_boolean pcrel_reloc_fits (xtensa_opcode, int, bfd_vma, bfd_vma);
108 static bfd_boolean xtensa_is_property_section (asection *);
109 static bfd_boolean xtensa_is_insntable_section (asection *);
110 static bfd_boolean xtensa_is_littable_section (asection *);
111 static bfd_boolean xtensa_is_proptable_section (asection *);
112 static int internal_reloc_compare (const void *, const void *);
113 static int internal_reloc_matches (const void *, const void *);
114 static asection *xtensa_get_property_section (asection *, const char *);
115 static flagword xtensa_get_property_predef_flags (asection *);
116
117 /* Other functions called directly by the linker.  */
118
119 typedef void (*deps_callback_t)
120   (asection *, bfd_vma, asection *, bfd_vma, void *);
121 extern bfd_boolean xtensa_callback_required_dependence
122   (bfd *, asection *, struct bfd_link_info *, deps_callback_t, void *);
123
124
125 /* Globally visible flag for choosing size optimization of NOP removal
126    instead of branch-target-aware minimization for NOP removal.
127    When nonzero, narrow all instructions and remove all NOPs possible
128    around longcall expansions.  */
129
130 int elf32xtensa_size_opt;
131
132
133 /* The "new_section_hook" is used to set up a per-section
134    "xtensa_relax_info" data structure with additional information used
135    during relaxation.  */
136
137 typedef struct xtensa_relax_info_struct xtensa_relax_info;
138
139
140 /* The GNU tools do not easily allow extending interfaces to pass around
141    the pointer to the Xtensa ISA information, so instead we add a global
142    variable here (in BFD) that can be used by any of the tools that need
143    this information. */
144
145 xtensa_isa xtensa_default_isa;
146
147
148 /* When this is true, relocations may have been modified to refer to
149    symbols from other input files.  The per-section list of "fix"
150    records needs to be checked when resolving relocations.  */
151
152 static bfd_boolean relaxing_section = FALSE;
153
154 /* When this is true, during final links, literals that cannot be
155    coalesced and their relocations may be moved to other sections.  */
156
157 int elf32xtensa_no_literal_movement = 1;
158
159 /* Place property records for a section into individual property section
160    with xt.prop. prefix.  */
161
162 bfd_boolean elf32xtensa_separate_props = FALSE;
163
164 /* Rename one of the generic section flags to better document how it
165    is used here.  */
166 /* Whether relocations have been processed.  */
167 #define reloc_done sec_flg0
168 \f
169 static reloc_howto_type elf_howto_table[] =
170 {
171   HOWTO (R_XTENSA_NONE, 0, 3, 0, FALSE, 0, complain_overflow_dont,
172          bfd_elf_xtensa_reloc, "R_XTENSA_NONE",
173          FALSE, 0, 0, FALSE),
174   HOWTO (R_XTENSA_32, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
175          bfd_elf_xtensa_reloc, "R_XTENSA_32",
176          TRUE, 0xffffffff, 0xffffffff, FALSE),
177
178   /* Replace a 32-bit value with a value from the runtime linker (only
179      used by linker-generated stub functions).  The r_addend value is
180      special: 1 means to substitute a pointer to the runtime linker's
181      dynamic resolver function; 2 means to substitute the link map for
182      the shared object.  */
183   HOWTO (R_XTENSA_RTLD, 0, 2, 32, FALSE, 0, complain_overflow_dont,
184          NULL, "R_XTENSA_RTLD", FALSE, 0, 0, FALSE),
185
186   HOWTO (R_XTENSA_GLOB_DAT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
187          bfd_elf_generic_reloc, "R_XTENSA_GLOB_DAT",
188          FALSE, 0, 0xffffffff, FALSE),
189   HOWTO (R_XTENSA_JMP_SLOT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
190          bfd_elf_generic_reloc, "R_XTENSA_JMP_SLOT",
191          FALSE, 0, 0xffffffff, FALSE),
192   HOWTO (R_XTENSA_RELATIVE, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
193          bfd_elf_generic_reloc, "R_XTENSA_RELATIVE",
194          FALSE, 0, 0xffffffff, FALSE),
195   HOWTO (R_XTENSA_PLT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
196          bfd_elf_xtensa_reloc, "R_XTENSA_PLT",
197          FALSE, 0, 0xffffffff, FALSE),
198
199   EMPTY_HOWTO (7),
200
201   /* Old relocations for backward compatibility.  */
202   HOWTO (R_XTENSA_OP0, 0, 0, 0, TRUE, 0, complain_overflow_dont,
203          bfd_elf_xtensa_reloc, "R_XTENSA_OP0", FALSE, 0, 0, TRUE),
204   HOWTO (R_XTENSA_OP1, 0, 0, 0, TRUE, 0, complain_overflow_dont,
205          bfd_elf_xtensa_reloc, "R_XTENSA_OP1", FALSE, 0, 0, TRUE),
206   HOWTO (R_XTENSA_OP2, 0, 0, 0, TRUE, 0, complain_overflow_dont,
207          bfd_elf_xtensa_reloc, "R_XTENSA_OP2", FALSE, 0, 0, TRUE),
208
209   /* Assembly auto-expansion.  */
210   HOWTO (R_XTENSA_ASM_EXPAND, 0, 0, 0, TRUE, 0, complain_overflow_dont,
211          bfd_elf_xtensa_reloc, "R_XTENSA_ASM_EXPAND", FALSE, 0, 0, TRUE),
212   /* Relax assembly auto-expansion.  */
213   HOWTO (R_XTENSA_ASM_SIMPLIFY, 0, 0, 0, TRUE, 0, complain_overflow_dont,
214          bfd_elf_xtensa_reloc, "R_XTENSA_ASM_SIMPLIFY", FALSE, 0, 0, TRUE),
215
216   EMPTY_HOWTO (13),
217
218   HOWTO (R_XTENSA_32_PCREL, 0, 2, 32, TRUE, 0, complain_overflow_bitfield,
219          bfd_elf_xtensa_reloc, "R_XTENSA_32_PCREL",
220          FALSE, 0, 0xffffffff, TRUE),
221
222   /* GNU extension to record C++ vtable hierarchy.  */
223   HOWTO (R_XTENSA_GNU_VTINHERIT, 0, 2, 0, FALSE, 0, complain_overflow_dont,
224          NULL, "R_XTENSA_GNU_VTINHERIT",
225          FALSE, 0, 0, FALSE),
226   /* GNU extension to record C++ vtable member usage.  */
227   HOWTO (R_XTENSA_GNU_VTENTRY, 0, 2, 0, FALSE, 0, complain_overflow_dont,
228          _bfd_elf_rel_vtable_reloc_fn, "R_XTENSA_GNU_VTENTRY",
229          FALSE, 0, 0, FALSE),
230
231   /* Relocations for supporting difference of symbols.  */
232   HOWTO (R_XTENSA_DIFF8, 0, 0, 8, FALSE, 0, complain_overflow_signed,
233          bfd_elf_xtensa_reloc, "R_XTENSA_DIFF8", FALSE, 0, 0xff, FALSE),
234   HOWTO (R_XTENSA_DIFF16, 0, 1, 16, FALSE, 0, complain_overflow_signed,
235          bfd_elf_xtensa_reloc, "R_XTENSA_DIFF16", FALSE, 0, 0xffff, FALSE),
236   HOWTO (R_XTENSA_DIFF32, 0, 2, 32, FALSE, 0, complain_overflow_signed,
237          bfd_elf_xtensa_reloc, "R_XTENSA_DIFF32", FALSE, 0, 0xffffffff, FALSE),
238
239   /* General immediate operand relocations.  */
240   HOWTO (R_XTENSA_SLOT0_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
241          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT0_OP", FALSE, 0, 0, TRUE),
242   HOWTO (R_XTENSA_SLOT1_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
243          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT1_OP", FALSE, 0, 0, TRUE),
244   HOWTO (R_XTENSA_SLOT2_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
245          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT2_OP", FALSE, 0, 0, TRUE),
246   HOWTO (R_XTENSA_SLOT3_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
247          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT3_OP", FALSE, 0, 0, TRUE),
248   HOWTO (R_XTENSA_SLOT4_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
249          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT4_OP", FALSE, 0, 0, TRUE),
250   HOWTO (R_XTENSA_SLOT5_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
251          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT5_OP", FALSE, 0, 0, TRUE),
252   HOWTO (R_XTENSA_SLOT6_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
253          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT6_OP", FALSE, 0, 0, TRUE),
254   HOWTO (R_XTENSA_SLOT7_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
255          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT7_OP", FALSE, 0, 0, TRUE),
256   HOWTO (R_XTENSA_SLOT8_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
257          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT8_OP", FALSE, 0, 0, TRUE),
258   HOWTO (R_XTENSA_SLOT9_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
259          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT9_OP", FALSE, 0, 0, TRUE),
260   HOWTO (R_XTENSA_SLOT10_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
261          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT10_OP", FALSE, 0, 0, TRUE),
262   HOWTO (R_XTENSA_SLOT11_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
263          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT11_OP", FALSE, 0, 0, TRUE),
264   HOWTO (R_XTENSA_SLOT12_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
265          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT12_OP", FALSE, 0, 0, TRUE),
266   HOWTO (R_XTENSA_SLOT13_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
267          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT13_OP", FALSE, 0, 0, TRUE),
268   HOWTO (R_XTENSA_SLOT14_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
269          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT14_OP", FALSE, 0, 0, TRUE),
270
271   /* "Alternate" relocations.  The meaning of these is opcode-specific.  */
272   HOWTO (R_XTENSA_SLOT0_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
273          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT0_ALT", FALSE, 0, 0, TRUE),
274   HOWTO (R_XTENSA_SLOT1_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
275          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT1_ALT", FALSE, 0, 0, TRUE),
276   HOWTO (R_XTENSA_SLOT2_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
277          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT2_ALT", FALSE, 0, 0, TRUE),
278   HOWTO (R_XTENSA_SLOT3_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
279          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT3_ALT", FALSE, 0, 0, TRUE),
280   HOWTO (R_XTENSA_SLOT4_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
281          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT4_ALT", FALSE, 0, 0, TRUE),
282   HOWTO (R_XTENSA_SLOT5_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
283          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT5_ALT", FALSE, 0, 0, TRUE),
284   HOWTO (R_XTENSA_SLOT6_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
285          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT6_ALT", FALSE, 0, 0, TRUE),
286   HOWTO (R_XTENSA_SLOT7_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
287          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT7_ALT", FALSE, 0, 0, TRUE),
288   HOWTO (R_XTENSA_SLOT8_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
289          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT8_ALT", FALSE, 0, 0, TRUE),
290   HOWTO (R_XTENSA_SLOT9_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
291          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT9_ALT", FALSE, 0, 0, TRUE),
292   HOWTO (R_XTENSA_SLOT10_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
293          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT10_ALT", FALSE, 0, 0, TRUE),
294   HOWTO (R_XTENSA_SLOT11_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
295          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT11_ALT", FALSE, 0, 0, TRUE),
296   HOWTO (R_XTENSA_SLOT12_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
297          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT12_ALT", FALSE, 0, 0, TRUE),
298   HOWTO (R_XTENSA_SLOT13_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
299          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT13_ALT", FALSE, 0, 0, TRUE),
300   HOWTO (R_XTENSA_SLOT14_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
301          bfd_elf_xtensa_reloc, "R_XTENSA_SLOT14_ALT", FALSE, 0, 0, TRUE),
302
303   /* TLS relocations.  */
304   HOWTO (R_XTENSA_TLSDESC_FN, 0, 2, 32, FALSE, 0, complain_overflow_dont,
305          bfd_elf_xtensa_reloc, "R_XTENSA_TLSDESC_FN",
306          FALSE, 0, 0xffffffff, FALSE),
307   HOWTO (R_XTENSA_TLSDESC_ARG, 0, 2, 32, FALSE, 0, complain_overflow_dont,
308          bfd_elf_xtensa_reloc, "R_XTENSA_TLSDESC_ARG",
309          FALSE, 0, 0xffffffff, FALSE),
310   HOWTO (R_XTENSA_TLS_DTPOFF, 0, 2, 32, FALSE, 0, complain_overflow_dont,
311          bfd_elf_xtensa_reloc, "R_XTENSA_TLS_DTPOFF",
312          FALSE, 0, 0xffffffff, FALSE),
313   HOWTO (R_XTENSA_TLS_TPOFF, 0, 2, 32, FALSE, 0, complain_overflow_dont,
314          bfd_elf_xtensa_reloc, "R_XTENSA_TLS_TPOFF",
315          FALSE, 0, 0xffffffff, FALSE),
316   HOWTO (R_XTENSA_TLS_FUNC, 0, 0, 0, FALSE, 0, complain_overflow_dont,
317          bfd_elf_xtensa_reloc, "R_XTENSA_TLS_FUNC",
318          FALSE, 0, 0, FALSE),
319   HOWTO (R_XTENSA_TLS_ARG, 0, 0, 0, FALSE, 0, complain_overflow_dont,
320          bfd_elf_xtensa_reloc, "R_XTENSA_TLS_ARG",
321          FALSE, 0, 0, FALSE),
322   HOWTO (R_XTENSA_TLS_CALL, 0, 0, 0, FALSE, 0, complain_overflow_dont,
323          bfd_elf_xtensa_reloc, "R_XTENSA_TLS_CALL",
324          FALSE, 0, 0, FALSE),
325 };
326
327 #if DEBUG_GEN_RELOC
328 #define TRACE(str) \
329   fprintf (stderr, "Xtensa bfd reloc lookup %d (%s)\n", code, str)
330 #else
331 #define TRACE(str)
332 #endif
333
334 static reloc_howto_type *
335 elf_xtensa_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED,
336                               bfd_reloc_code_real_type code)
337 {
338   switch (code)
339     {
340     case BFD_RELOC_NONE:
341       TRACE ("BFD_RELOC_NONE");
342       return &elf_howto_table[(unsigned) R_XTENSA_NONE ];
343
344     case BFD_RELOC_32:
345       TRACE ("BFD_RELOC_32");
346       return &elf_howto_table[(unsigned) R_XTENSA_32 ];
347
348     case BFD_RELOC_32_PCREL:
349       TRACE ("BFD_RELOC_32_PCREL");
350       return &elf_howto_table[(unsigned) R_XTENSA_32_PCREL ];
351
352     case BFD_RELOC_XTENSA_DIFF8:
353       TRACE ("BFD_RELOC_XTENSA_DIFF8");
354       return &elf_howto_table[(unsigned) R_XTENSA_DIFF8 ];
355
356     case BFD_RELOC_XTENSA_DIFF16:
357       TRACE ("BFD_RELOC_XTENSA_DIFF16");
358       return &elf_howto_table[(unsigned) R_XTENSA_DIFF16 ];
359
360     case BFD_RELOC_XTENSA_DIFF32:
361       TRACE ("BFD_RELOC_XTENSA_DIFF32");
362       return &elf_howto_table[(unsigned) R_XTENSA_DIFF32 ];
363
364     case BFD_RELOC_XTENSA_RTLD:
365       TRACE ("BFD_RELOC_XTENSA_RTLD");
366       return &elf_howto_table[(unsigned) R_XTENSA_RTLD ];
367
368     case BFD_RELOC_XTENSA_GLOB_DAT:
369       TRACE ("BFD_RELOC_XTENSA_GLOB_DAT");
370       return &elf_howto_table[(unsigned) R_XTENSA_GLOB_DAT ];
371
372     case BFD_RELOC_XTENSA_JMP_SLOT:
373       TRACE ("BFD_RELOC_XTENSA_JMP_SLOT");
374       return &elf_howto_table[(unsigned) R_XTENSA_JMP_SLOT ];
375
376     case BFD_RELOC_XTENSA_RELATIVE:
377       TRACE ("BFD_RELOC_XTENSA_RELATIVE");
378       return &elf_howto_table[(unsigned) R_XTENSA_RELATIVE ];
379
380     case BFD_RELOC_XTENSA_PLT:
381       TRACE ("BFD_RELOC_XTENSA_PLT");
382       return &elf_howto_table[(unsigned) R_XTENSA_PLT ];
383
384     case BFD_RELOC_XTENSA_OP0:
385       TRACE ("BFD_RELOC_XTENSA_OP0");
386       return &elf_howto_table[(unsigned) R_XTENSA_OP0 ];
387
388     case BFD_RELOC_XTENSA_OP1:
389       TRACE ("BFD_RELOC_XTENSA_OP1");
390       return &elf_howto_table[(unsigned) R_XTENSA_OP1 ];
391
392     case BFD_RELOC_XTENSA_OP2:
393       TRACE ("BFD_RELOC_XTENSA_OP2");
394       return &elf_howto_table[(unsigned) R_XTENSA_OP2 ];
395
396     case BFD_RELOC_XTENSA_ASM_EXPAND:
397       TRACE ("BFD_RELOC_XTENSA_ASM_EXPAND");
398       return &elf_howto_table[(unsigned) R_XTENSA_ASM_EXPAND ];
399
400     case BFD_RELOC_XTENSA_ASM_SIMPLIFY:
401       TRACE ("BFD_RELOC_XTENSA_ASM_SIMPLIFY");
402       return &elf_howto_table[(unsigned) R_XTENSA_ASM_SIMPLIFY ];
403
404     case BFD_RELOC_VTABLE_INHERIT:
405       TRACE ("BFD_RELOC_VTABLE_INHERIT");
406       return &elf_howto_table[(unsigned) R_XTENSA_GNU_VTINHERIT ];
407
408     case BFD_RELOC_VTABLE_ENTRY:
409       TRACE ("BFD_RELOC_VTABLE_ENTRY");
410       return &elf_howto_table[(unsigned) R_XTENSA_GNU_VTENTRY ];
411
412     case BFD_RELOC_XTENSA_TLSDESC_FN:
413       TRACE ("BFD_RELOC_XTENSA_TLSDESC_FN");
414       return &elf_howto_table[(unsigned) R_XTENSA_TLSDESC_FN ];
415
416     case BFD_RELOC_XTENSA_TLSDESC_ARG:
417       TRACE ("BFD_RELOC_XTENSA_TLSDESC_ARG");
418       return &elf_howto_table[(unsigned) R_XTENSA_TLSDESC_ARG ];
419
420     case BFD_RELOC_XTENSA_TLS_DTPOFF:
421       TRACE ("BFD_RELOC_XTENSA_TLS_DTPOFF");
422       return &elf_howto_table[(unsigned) R_XTENSA_TLS_DTPOFF ];
423
424     case BFD_RELOC_XTENSA_TLS_TPOFF:
425       TRACE ("BFD_RELOC_XTENSA_TLS_TPOFF");
426       return &elf_howto_table[(unsigned) R_XTENSA_TLS_TPOFF ];
427
428     case BFD_RELOC_XTENSA_TLS_FUNC:
429       TRACE ("BFD_RELOC_XTENSA_TLS_FUNC");
430       return &elf_howto_table[(unsigned) R_XTENSA_TLS_FUNC ];
431
432     case BFD_RELOC_XTENSA_TLS_ARG:
433       TRACE ("BFD_RELOC_XTENSA_TLS_ARG");
434       return &elf_howto_table[(unsigned) R_XTENSA_TLS_ARG ];
435
436     case BFD_RELOC_XTENSA_TLS_CALL:
437       TRACE ("BFD_RELOC_XTENSA_TLS_CALL");
438       return &elf_howto_table[(unsigned) R_XTENSA_TLS_CALL ];
439
440     default:
441       if (code >= BFD_RELOC_XTENSA_SLOT0_OP
442           && code <= BFD_RELOC_XTENSA_SLOT14_OP)
443         {
444           unsigned n = (R_XTENSA_SLOT0_OP +
445                         (code - BFD_RELOC_XTENSA_SLOT0_OP));
446           return &elf_howto_table[n];
447         }
448
449       if (code >= BFD_RELOC_XTENSA_SLOT0_ALT
450           && code <= BFD_RELOC_XTENSA_SLOT14_ALT)
451         {
452           unsigned n = (R_XTENSA_SLOT0_ALT +
453                         (code - BFD_RELOC_XTENSA_SLOT0_ALT));
454           return &elf_howto_table[n];
455         }
456
457       break;
458     }
459
460   /* xgettext:c-format */
461   _bfd_error_handler (_("%pB: unsupported relocation type %#x"), abfd, (int) code);
462   bfd_set_error (bfd_error_bad_value);
463   TRACE ("Unknown");
464   return NULL;
465 }
466
467 static reloc_howto_type *
468 elf_xtensa_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED,
469                               const char *r_name)
470 {
471   unsigned int i;
472
473   for (i = 0; i < sizeof (elf_howto_table) / sizeof (elf_howto_table[0]); i++)
474     if (elf_howto_table[i].name != NULL
475         && strcasecmp (elf_howto_table[i].name, r_name) == 0)
476       return &elf_howto_table[i];
477
478   return NULL;
479 }
480
481
482 /* Given an ELF "rela" relocation, find the corresponding howto and record
483    it in the BFD internal arelent representation of the relocation.  */
484
485 static bfd_boolean
486 elf_xtensa_info_to_howto_rela (bfd *abfd,
487                                arelent *cache_ptr,
488                                Elf_Internal_Rela *dst)
489 {
490   unsigned int r_type = ELF32_R_TYPE (dst->r_info);
491
492   if (r_type >= (unsigned int) R_XTENSA_max)
493     {
494       /* xgettext:c-format */
495       _bfd_error_handler (_("%pB: unsupported relocation type %#x"),
496                           abfd, r_type);
497       bfd_set_error (bfd_error_bad_value);
498       return FALSE;
499     }
500   cache_ptr->howto = &elf_howto_table[r_type];
501   return TRUE;
502 }
503
504 \f
505 /* Functions for the Xtensa ELF linker.  */
506
507 /* The name of the dynamic interpreter.  This is put in the .interp
508    section.  */
509
510 #define ELF_DYNAMIC_INTERPRETER "/lib/ld.so"
511
512 /* The size in bytes of an entry in the procedure linkage table.
513    (This does _not_ include the space for the literals associated with
514    the PLT entry.) */
515
516 #define PLT_ENTRY_SIZE 16
517
518 /* For _really_ large PLTs, we may need to alternate between literals
519    and code to keep the literals within the 256K range of the L32R
520    instructions in the code.  It's unlikely that anyone would ever need
521    such a big PLT, but an arbitrary limit on the PLT size would be bad.
522    Thus, we split the PLT into chunks.  Since there's very little
523    overhead (2 extra literals) for each chunk, the chunk size is kept
524    small so that the code for handling multiple chunks get used and
525    tested regularly.  With 254 entries, there are 1K of literals for
526    each chunk, and that seems like a nice round number.  */
527
528 #define PLT_ENTRIES_PER_CHUNK 254
529
530 /* PLT entries are actually used as stub functions for lazy symbol
531    resolution.  Once the symbol is resolved, the stub function is never
532    invoked.  Note: the 32-byte frame size used here cannot be changed
533    without a corresponding change in the runtime linker.  */
534
535 static const bfd_byte elf_xtensa_be_plt_entry[][PLT_ENTRY_SIZE] =
536 {
537     {
538       0x6c, 0x10, 0x04, /* entry sp, 32 */
539       0x18, 0x00, 0x00, /* l32r  a8, [got entry for rtld's resolver] */
540       0x1a, 0x00, 0x00, /* l32r  a10, [got entry for rtld's link map] */
541       0x1b, 0x00, 0x00, /* l32r  a11, [literal for reloc index] */
542       0x0a, 0x80, 0x00, /* jx    a8 */
543       0                 /* unused */
544     },
545     {
546       0x18, 0x00, 0x00, /* l32r  a8, [got entry for rtld's resolver] */
547       0x1a, 0x00, 0x00, /* l32r  a10, [got entry for rtld's link map] */
548       0x1b, 0x00, 0x00, /* l32r  a11, [literal for reloc index] */
549       0x0a, 0x80, 0x00, /* jx    a8 */
550       0                 /* unused */
551     }
552 };
553
554 static const bfd_byte elf_xtensa_le_plt_entry[][PLT_ENTRY_SIZE] =
555 {
556     {
557       0x36, 0x41, 0x00, /* entry sp, 32 */
558       0x81, 0x00, 0x00, /* l32r  a8, [got entry for rtld's resolver] */
559       0xa1, 0x00, 0x00, /* l32r  a10, [got entry for rtld's link map] */
560       0xb1, 0x00, 0x00, /* l32r  a11, [literal for reloc index] */
561       0xa0, 0x08, 0x00, /* jx    a8 */
562       0                 /* unused */
563     },
564     {
565       0x81, 0x00, 0x00, /* l32r  a8, [got entry for rtld's resolver] */
566       0xa1, 0x00, 0x00, /* l32r  a10, [got entry for rtld's link map] */
567       0xb1, 0x00, 0x00, /* l32r  a11, [literal for reloc index] */
568       0xa0, 0x08, 0x00, /* jx    a8 */
569       0                 /* unused */
570     }
571 };
572
573 /* The size of the thread control block.  */
574 #define TCB_SIZE        8
575
576 struct elf_xtensa_link_hash_entry
577 {
578   struct elf_link_hash_entry elf;
579
580   bfd_signed_vma tlsfunc_refcount;
581
582 #define GOT_UNKNOWN     0
583 #define GOT_NORMAL      1
584 #define GOT_TLS_GD      2       /* global or local dynamic */
585 #define GOT_TLS_IE      4       /* initial or local exec */
586 #define GOT_TLS_ANY     (GOT_TLS_GD | GOT_TLS_IE)
587   unsigned char tls_type;
588 };
589
590 #define elf_xtensa_hash_entry(ent) ((struct elf_xtensa_link_hash_entry *)(ent))
591
592 struct elf_xtensa_obj_tdata
593 {
594   struct elf_obj_tdata root;
595
596   /* tls_type for each local got entry.  */
597   char *local_got_tls_type;
598
599   bfd_signed_vma *local_tlsfunc_refcounts;
600 };
601
602 #define elf_xtensa_tdata(abfd) \
603   ((struct elf_xtensa_obj_tdata *) (abfd)->tdata.any)
604
605 #define elf_xtensa_local_got_tls_type(abfd) \
606   (elf_xtensa_tdata (abfd)->local_got_tls_type)
607
608 #define elf_xtensa_local_tlsfunc_refcounts(abfd) \
609   (elf_xtensa_tdata (abfd)->local_tlsfunc_refcounts)
610
611 #define is_xtensa_elf(bfd) \
612   (bfd_get_flavour (bfd) == bfd_target_elf_flavour \
613    && elf_tdata (bfd) != NULL \
614    && elf_object_id (bfd) == XTENSA_ELF_DATA)
615
616 static bfd_boolean
617 elf_xtensa_mkobject (bfd *abfd)
618 {
619   return bfd_elf_allocate_object (abfd, sizeof (struct elf_xtensa_obj_tdata),
620                                   XTENSA_ELF_DATA);
621 }
622
623 /* Xtensa ELF linker hash table.  */
624
625 struct elf_xtensa_link_hash_table
626 {
627   struct elf_link_hash_table elf;
628
629   /* Short-cuts to get to dynamic linker sections.  */
630   asection *sgotloc;
631   asection *spltlittbl;
632
633   /* Total count of PLT relocations seen during check_relocs.
634      The actual PLT code must be split into multiple sections and all
635      the sections have to be created before size_dynamic_sections,
636      where we figure out the exact number of PLT entries that will be
637      needed.  It is OK if this count is an overestimate, e.g., some
638      relocations may be removed by GC.  */
639   int plt_reloc_count;
640
641   struct elf_xtensa_link_hash_entry *tlsbase;
642 };
643
644 /* Get the Xtensa ELF linker hash table from a link_info structure.  */
645
646 #define elf_xtensa_hash_table(p) \
647   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
648   == XTENSA_ELF_DATA ? ((struct elf_xtensa_link_hash_table *) ((p)->hash)) : NULL)
649
650 /* Create an entry in an Xtensa ELF linker hash table.  */
651
652 static struct bfd_hash_entry *
653 elf_xtensa_link_hash_newfunc (struct bfd_hash_entry *entry,
654                               struct bfd_hash_table *table,
655                               const char *string)
656 {
657   /* Allocate the structure if it has not already been allocated by a
658      subclass.  */
659   if (entry == NULL)
660     {
661       entry = bfd_hash_allocate (table,
662                                  sizeof (struct elf_xtensa_link_hash_entry));
663       if (entry == NULL)
664         return entry;
665     }
666
667   /* Call the allocation method of the superclass.  */
668   entry = _bfd_elf_link_hash_newfunc (entry, table, string);
669   if (entry != NULL)
670     {
671       struct elf_xtensa_link_hash_entry *eh = elf_xtensa_hash_entry (entry);
672       eh->tlsfunc_refcount = 0;
673       eh->tls_type = GOT_UNKNOWN;
674     }
675
676   return entry;
677 }
678
679 /* Create an Xtensa ELF linker hash table.  */
680
681 static struct bfd_link_hash_table *
682 elf_xtensa_link_hash_table_create (bfd *abfd)
683 {
684   struct elf_link_hash_entry *tlsbase;
685   struct elf_xtensa_link_hash_table *ret;
686   bfd_size_type amt = sizeof (struct elf_xtensa_link_hash_table);
687
688   ret = bfd_zmalloc (amt);
689   if (ret == NULL)
690     return NULL;
691
692   if (!_bfd_elf_link_hash_table_init (&ret->elf, abfd,
693                                       elf_xtensa_link_hash_newfunc,
694                                       sizeof (struct elf_xtensa_link_hash_entry),
695                                       XTENSA_ELF_DATA))
696     {
697       free (ret);
698       return NULL;
699     }
700
701   /* Create a hash entry for "_TLS_MODULE_BASE_" to speed up checking
702      for it later.  */
703   tlsbase = elf_link_hash_lookup (&ret->elf, "_TLS_MODULE_BASE_",
704                                   TRUE, FALSE, FALSE);
705   tlsbase->root.type = bfd_link_hash_new;
706   tlsbase->root.u.undef.abfd = NULL;
707   tlsbase->non_elf = 0;
708   ret->tlsbase = elf_xtensa_hash_entry (tlsbase);
709   ret->tlsbase->tls_type = GOT_UNKNOWN;
710
711   return &ret->elf.root;
712 }
713
714 /* Copy the extra info we tack onto an elf_link_hash_entry.  */
715
716 static void
717 elf_xtensa_copy_indirect_symbol (struct bfd_link_info *info,
718                                  struct elf_link_hash_entry *dir,
719                                  struct elf_link_hash_entry *ind)
720 {
721   struct elf_xtensa_link_hash_entry *edir, *eind;
722
723   edir = elf_xtensa_hash_entry (dir);
724   eind = elf_xtensa_hash_entry (ind);
725
726   if (ind->root.type == bfd_link_hash_indirect)
727     {
728       edir->tlsfunc_refcount += eind->tlsfunc_refcount;
729       eind->tlsfunc_refcount = 0;
730
731       if (dir->got.refcount <= 0)
732         {
733           edir->tls_type = eind->tls_type;
734           eind->tls_type = GOT_UNKNOWN;
735         }
736     }
737
738   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
739 }
740
741 static inline bfd_boolean
742 elf_xtensa_dynamic_symbol_p (struct elf_link_hash_entry *h,
743                              struct bfd_link_info *info)
744 {
745   /* Check if we should do dynamic things to this symbol.  The
746      "ignore_protected" argument need not be set, because Xtensa code
747      does not require special handling of STV_PROTECTED to make function
748      pointer comparisons work properly.  The PLT addresses are never
749      used for function pointers.  */
750
751   return _bfd_elf_dynamic_symbol_p (h, info, 0);
752 }
753
754 \f
755 static int
756 property_table_compare (const void *ap, const void *bp)
757 {
758   const property_table_entry *a = (const property_table_entry *) ap;
759   const property_table_entry *b = (const property_table_entry *) bp;
760
761   if (a->address == b->address)
762     {
763       if (a->size != b->size)
764         return (a->size - b->size);
765
766       if ((a->flags & XTENSA_PROP_ALIGN) != (b->flags & XTENSA_PROP_ALIGN))
767         return ((b->flags & XTENSA_PROP_ALIGN)
768                 - (a->flags & XTENSA_PROP_ALIGN));
769
770       if ((a->flags & XTENSA_PROP_ALIGN)
771           && (GET_XTENSA_PROP_ALIGNMENT (a->flags)
772               != GET_XTENSA_PROP_ALIGNMENT (b->flags)))
773         return (GET_XTENSA_PROP_ALIGNMENT (a->flags)
774                 - GET_XTENSA_PROP_ALIGNMENT (b->flags));
775
776       if ((a->flags & XTENSA_PROP_UNREACHABLE)
777           != (b->flags & XTENSA_PROP_UNREACHABLE))
778         return ((b->flags & XTENSA_PROP_UNREACHABLE)
779                 - (a->flags & XTENSA_PROP_UNREACHABLE));
780
781       return (a->flags - b->flags);
782     }
783
784   return (a->address - b->address);
785 }
786
787
788 static int
789 property_table_matches (const void *ap, const void *bp)
790 {
791   const property_table_entry *a = (const property_table_entry *) ap;
792   const property_table_entry *b = (const property_table_entry *) bp;
793
794   /* Check if one entry overlaps with the other.  */
795   if ((b->address >= a->address && b->address < (a->address + a->size))
796       || (a->address >= b->address && a->address < (b->address + b->size)))
797     return 0;
798
799   return (a->address - b->address);
800 }
801
802
803 /* Get the literal table or property table entries for the given
804    section.  Sets TABLE_P and returns the number of entries.  On
805    error, returns a negative value.  */
806
807 int
808 xtensa_read_table_entries (bfd *abfd,
809                            asection *section,
810                            property_table_entry **table_p,
811                            const char *sec_name,
812                            bfd_boolean output_addr)
813 {
814   asection *table_section;
815   bfd_size_type table_size = 0;
816   bfd_byte *table_data;
817   property_table_entry *blocks;
818   int blk, block_count;
819   bfd_size_type num_records;
820   Elf_Internal_Rela *internal_relocs, *irel, *rel_end;
821   bfd_vma section_addr, off;
822   flagword predef_flags;
823   bfd_size_type table_entry_size, section_limit;
824
825   if (!section
826       || !(section->flags & SEC_ALLOC)
827       || (section->flags & SEC_DEBUGGING))
828     {
829       *table_p = NULL;
830       return 0;
831     }
832
833   table_section = xtensa_get_property_section (section, sec_name);
834   if (table_section)
835     table_size = table_section->size;
836
837   if (table_size == 0)
838     {
839       *table_p = NULL;
840       return 0;
841     }
842
843   predef_flags = xtensa_get_property_predef_flags (table_section);
844   table_entry_size = 12;
845   if (predef_flags)
846     table_entry_size -= 4;
847
848   num_records = table_size / table_entry_size;
849   table_data = retrieve_contents (abfd, table_section, TRUE);
850   blocks = (property_table_entry *)
851     bfd_malloc (num_records * sizeof (property_table_entry));
852   block_count = 0;
853
854   if (output_addr)
855     section_addr = section->output_section->vma + section->output_offset;
856   else
857     section_addr = section->vma;
858
859   internal_relocs = retrieve_internal_relocs (abfd, table_section, TRUE);
860   if (internal_relocs && !table_section->reloc_done)
861     {
862       qsort (internal_relocs, table_section->reloc_count,
863              sizeof (Elf_Internal_Rela), internal_reloc_compare);
864       irel = internal_relocs;
865     }
866   else
867     irel = NULL;
868
869   section_limit = bfd_get_section_limit (abfd, section);
870   rel_end = internal_relocs + table_section->reloc_count;
871
872   for (off = 0; off < table_size; off += table_entry_size)
873     {
874       bfd_vma address = bfd_get_32 (abfd, table_data + off);
875
876       /* Skip any relocations before the current offset.  This should help
877          avoid confusion caused by unexpected relocations for the preceding
878          table entry.  */
879       while (irel &&
880              (irel->r_offset < off
881               || (irel->r_offset == off
882                   && ELF32_R_TYPE (irel->r_info) == R_XTENSA_NONE)))
883         {
884           irel += 1;
885           if (irel >= rel_end)
886             irel = 0;
887         }
888
889       if (irel && irel->r_offset == off)
890         {
891           bfd_vma sym_off;
892           unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
893           BFD_ASSERT (ELF32_R_TYPE (irel->r_info) == R_XTENSA_32);
894
895           if (get_elf_r_symndx_section (abfd, r_symndx) != section)
896             continue;
897
898           sym_off = get_elf_r_symndx_offset (abfd, r_symndx);
899           BFD_ASSERT (sym_off == 0);
900           address += (section_addr + sym_off + irel->r_addend);
901         }
902       else
903         {
904           if (address < section_addr
905               || address >= section_addr + section_limit)
906             continue;
907         }
908
909       blocks[block_count].address = address;
910       blocks[block_count].size = bfd_get_32 (abfd, table_data + off + 4);
911       if (predef_flags)
912         blocks[block_count].flags = predef_flags;
913       else
914         blocks[block_count].flags = bfd_get_32 (abfd, table_data + off + 8);
915       block_count++;
916     }
917
918   release_contents (table_section, table_data);
919   release_internal_relocs (table_section, internal_relocs);
920
921   if (block_count > 0)
922     {
923       /* Now sort them into address order for easy reference.  */
924       qsort (blocks, block_count, sizeof (property_table_entry),
925              property_table_compare);
926
927       /* Check that the table contents are valid.  Problems may occur,
928          for example, if an unrelocated object file is stripped.  */
929       for (blk = 1; blk < block_count; blk++)
930         {
931           /* The only circumstance where two entries may legitimately
932              have the same address is when one of them is a zero-size
933              placeholder to mark a place where fill can be inserted.
934              The zero-size entry should come first.  */
935           if (blocks[blk - 1].address == blocks[blk].address &&
936               blocks[blk - 1].size != 0)
937             {
938               /* xgettext:c-format */
939               _bfd_error_handler (_("%pB(%pA): invalid property table"),
940                                   abfd, section);
941               bfd_set_error (bfd_error_bad_value);
942               free (blocks);
943               return -1;
944             }
945         }
946     }
947
948   *table_p = blocks;
949   return block_count;
950 }
951
952
953 static property_table_entry *
954 elf_xtensa_find_property_entry (property_table_entry *property_table,
955                                 int property_table_size,
956                                 bfd_vma addr)
957 {
958   property_table_entry entry;
959   property_table_entry *rv;
960
961   if (property_table_size == 0)
962     return NULL;
963
964   entry.address = addr;
965   entry.size = 1;
966   entry.flags = 0;
967
968   rv = bsearch (&entry, property_table, property_table_size,
969                 sizeof (property_table_entry), property_table_matches);
970   return rv;
971 }
972
973
974 static bfd_boolean
975 elf_xtensa_in_literal_pool (property_table_entry *lit_table,
976                             int lit_table_size,
977                             bfd_vma addr)
978 {
979   if (elf_xtensa_find_property_entry (lit_table, lit_table_size, addr))
980     return TRUE;
981
982   return FALSE;
983 }
984
985 \f
986 /* Look through the relocs for a section during the first phase, and
987    calculate needed space in the dynamic reloc sections.  */
988
989 static bfd_boolean
990 elf_xtensa_check_relocs (bfd *abfd,
991                          struct bfd_link_info *info,
992                          asection *sec,
993                          const Elf_Internal_Rela *relocs)
994 {
995   struct elf_xtensa_link_hash_table *htab;
996   Elf_Internal_Shdr *symtab_hdr;
997   struct elf_link_hash_entry **sym_hashes;
998   const Elf_Internal_Rela *rel;
999   const Elf_Internal_Rela *rel_end;
1000
1001   if (bfd_link_relocatable (info) || (sec->flags & SEC_ALLOC) == 0)
1002     return TRUE;
1003
1004   BFD_ASSERT (is_xtensa_elf (abfd));
1005
1006   htab = elf_xtensa_hash_table (info);
1007   if (htab == NULL)
1008     return FALSE;
1009
1010   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1011   sym_hashes = elf_sym_hashes (abfd);
1012
1013   rel_end = relocs + sec->reloc_count;
1014   for (rel = relocs; rel < rel_end; rel++)
1015     {
1016       unsigned int r_type;
1017       unsigned r_symndx;
1018       struct elf_link_hash_entry *h = NULL;
1019       struct elf_xtensa_link_hash_entry *eh;
1020       int tls_type, old_tls_type;
1021       bfd_boolean is_got = FALSE;
1022       bfd_boolean is_plt = FALSE;
1023       bfd_boolean is_tlsfunc = FALSE;
1024
1025       r_symndx = ELF32_R_SYM (rel->r_info);
1026       r_type = ELF32_R_TYPE (rel->r_info);
1027
1028       if (r_symndx >= NUM_SHDR_ENTRIES (symtab_hdr))
1029         {
1030           /* xgettext:c-format */
1031           _bfd_error_handler (_("%pB: bad symbol index: %d"),
1032                               abfd, r_symndx);
1033           return FALSE;
1034         }
1035
1036       if (r_symndx >= symtab_hdr->sh_info)
1037         {
1038           h = sym_hashes[r_symndx - symtab_hdr->sh_info];
1039           while (h->root.type == bfd_link_hash_indirect
1040                  || h->root.type == bfd_link_hash_warning)
1041             h = (struct elf_link_hash_entry *) h->root.u.i.link;
1042         }
1043       eh = elf_xtensa_hash_entry (h);
1044
1045       switch (r_type)
1046         {
1047         case R_XTENSA_TLSDESC_FN:
1048           if (bfd_link_pic (info))
1049             {
1050               tls_type = GOT_TLS_GD;
1051               is_got = TRUE;
1052               is_tlsfunc = TRUE;
1053             }
1054           else
1055             tls_type = GOT_TLS_IE;
1056           break;
1057
1058         case R_XTENSA_TLSDESC_ARG:
1059           if (bfd_link_pic (info))
1060             {
1061               tls_type = GOT_TLS_GD;
1062               is_got = TRUE;
1063             }
1064           else
1065             {
1066               tls_type = GOT_TLS_IE;
1067               if (h && elf_xtensa_hash_entry (h) != htab->tlsbase)
1068                 is_got = TRUE;
1069             }
1070           break;
1071
1072         case R_XTENSA_TLS_DTPOFF:
1073           if (bfd_link_pic (info))
1074             tls_type = GOT_TLS_GD;
1075           else
1076             tls_type = GOT_TLS_IE;
1077           break;
1078
1079         case R_XTENSA_TLS_TPOFF:
1080           tls_type = GOT_TLS_IE;
1081           if (bfd_link_pic (info))
1082             info->flags |= DF_STATIC_TLS;
1083           if (bfd_link_pic (info) || h)
1084             is_got = TRUE;
1085           break;
1086
1087         case R_XTENSA_32:
1088           tls_type = GOT_NORMAL;
1089           is_got = TRUE;
1090           break;
1091
1092         case R_XTENSA_PLT:
1093           tls_type = GOT_NORMAL;
1094           is_plt = TRUE;
1095           break;
1096
1097         case R_XTENSA_GNU_VTINHERIT:
1098           /* This relocation describes the C++ object vtable hierarchy.
1099              Reconstruct it for later use during GC.  */
1100           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
1101             return FALSE;
1102           continue;
1103
1104         case R_XTENSA_GNU_VTENTRY:
1105           /* This relocation describes which C++ vtable entries are actually
1106              used.  Record for later use during GC.  */
1107           if (!bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_addend))
1108             return FALSE;
1109           continue;
1110
1111         default:
1112           /* Nothing to do for any other relocations.  */
1113           continue;
1114         }
1115
1116       if (h)
1117         {
1118           if (is_plt)
1119             {
1120               if (h->plt.refcount <= 0)
1121                 {
1122                   h->needs_plt = 1;
1123                   h->plt.refcount = 1;
1124                 }
1125               else
1126                 h->plt.refcount += 1;
1127
1128               /* Keep track of the total PLT relocation count even if we
1129                  don't yet know whether the dynamic sections will be
1130                  created.  */
1131               htab->plt_reloc_count += 1;
1132
1133               if (elf_hash_table (info)->dynamic_sections_created)
1134                 {
1135                   if (! add_extra_plt_sections (info, htab->plt_reloc_count))
1136                     return FALSE;
1137                 }
1138             }
1139           else if (is_got)
1140             {
1141               if (h->got.refcount <= 0)
1142                 h->got.refcount = 1;
1143               else
1144                 h->got.refcount += 1;
1145             }
1146
1147           if (is_tlsfunc)
1148             eh->tlsfunc_refcount += 1;
1149
1150           old_tls_type = eh->tls_type;
1151         }
1152       else
1153         {
1154           /* Allocate storage the first time.  */
1155           if (elf_local_got_refcounts (abfd) == NULL)
1156             {
1157               bfd_size_type size = symtab_hdr->sh_info;
1158               void *mem;
1159
1160               mem = bfd_zalloc (abfd, size * sizeof (bfd_signed_vma));
1161               if (mem == NULL)
1162                 return FALSE;
1163               elf_local_got_refcounts (abfd) = (bfd_signed_vma *) mem;
1164
1165               mem = bfd_zalloc (abfd, size);
1166               if (mem == NULL)
1167                 return FALSE;
1168               elf_xtensa_local_got_tls_type (abfd) = (char *) mem;
1169
1170               mem = bfd_zalloc (abfd, size * sizeof (bfd_signed_vma));
1171               if (mem == NULL)
1172                 return FALSE;
1173               elf_xtensa_local_tlsfunc_refcounts (abfd)
1174                 = (bfd_signed_vma *) mem;
1175             }
1176
1177           /* This is a global offset table entry for a local symbol.  */
1178           if (is_got || is_plt)
1179             elf_local_got_refcounts (abfd) [r_symndx] += 1;
1180
1181           if (is_tlsfunc)
1182             elf_xtensa_local_tlsfunc_refcounts (abfd) [r_symndx] += 1;
1183
1184           old_tls_type = elf_xtensa_local_got_tls_type (abfd) [r_symndx];
1185         }
1186
1187       if ((old_tls_type & GOT_TLS_IE) && (tls_type & GOT_TLS_IE))
1188         tls_type |= old_tls_type;
1189       /* If a TLS symbol is accessed using IE at least once,
1190          there is no point to use a dynamic model for it.  */
1191       else if (old_tls_type != tls_type && old_tls_type != GOT_UNKNOWN
1192                && ((old_tls_type & GOT_TLS_GD) == 0
1193                    || (tls_type & GOT_TLS_IE) == 0))
1194         {
1195           if ((old_tls_type & GOT_TLS_IE) && (tls_type & GOT_TLS_GD))
1196             tls_type = old_tls_type;
1197           else if ((old_tls_type & GOT_TLS_GD) && (tls_type & GOT_TLS_GD))
1198             tls_type |= old_tls_type;
1199           else
1200             {
1201               _bfd_error_handler
1202                 /* xgettext:c-format */
1203                 (_("%pB: `%s' accessed both as normal and thread local symbol"),
1204                  abfd,
1205                  h ? h->root.root.string : "<local>");
1206               return FALSE;
1207             }
1208         }
1209
1210       if (old_tls_type != tls_type)
1211         {
1212           if (eh)
1213             eh->tls_type = tls_type;
1214           else
1215             elf_xtensa_local_got_tls_type (abfd) [r_symndx] = tls_type;
1216         }
1217     }
1218
1219   return TRUE;
1220 }
1221
1222
1223 static void
1224 elf_xtensa_make_sym_local (struct bfd_link_info *info,
1225                            struct elf_link_hash_entry *h)
1226 {
1227   if (bfd_link_pic (info))
1228     {
1229       if (h->plt.refcount > 0)
1230         {
1231           /* For shared objects, there's no need for PLT entries for local
1232              symbols (use RELATIVE relocs instead of JMP_SLOT relocs).  */
1233           if (h->got.refcount < 0)
1234             h->got.refcount = 0;
1235           h->got.refcount += h->plt.refcount;
1236           h->plt.refcount = 0;
1237         }
1238     }
1239   else
1240     {
1241       /* Don't need any dynamic relocations at all.  */
1242       h->plt.refcount = 0;
1243       h->got.refcount = 0;
1244     }
1245 }
1246
1247
1248 static void
1249 elf_xtensa_hide_symbol (struct bfd_link_info *info,
1250                         struct elf_link_hash_entry *h,
1251                         bfd_boolean force_local)
1252 {
1253   /* For a shared link, move the plt refcount to the got refcount to leave
1254      space for RELATIVE relocs.  */
1255   elf_xtensa_make_sym_local (info, h);
1256
1257   _bfd_elf_link_hash_hide_symbol (info, h, force_local);
1258 }
1259
1260
1261 /* Return the section that should be marked against GC for a given
1262    relocation.  */
1263
1264 static asection *
1265 elf_xtensa_gc_mark_hook (asection *sec,
1266                          struct bfd_link_info *info,
1267                          Elf_Internal_Rela *rel,
1268                          struct elf_link_hash_entry *h,
1269                          Elf_Internal_Sym *sym)
1270 {
1271   /* Property sections are marked "KEEP" in the linker scripts, but they
1272      should not cause other sections to be marked.  (This approach relies
1273      on elf_xtensa_discard_info to remove property table entries that
1274      describe discarded sections.  Alternatively, it might be more
1275      efficient to avoid using "KEEP" in the linker scripts and instead use
1276      the gc_mark_extra_sections hook to mark only the property sections
1277      that describe marked sections.  That alternative does not work well
1278      with the current property table sections, which do not correspond
1279      one-to-one with the sections they describe, but that should be fixed
1280      someday.) */
1281   if (xtensa_is_property_section (sec))
1282     return NULL;
1283
1284   if (h != NULL)
1285     switch (ELF32_R_TYPE (rel->r_info))
1286       {
1287       case R_XTENSA_GNU_VTINHERIT:
1288       case R_XTENSA_GNU_VTENTRY:
1289         return NULL;
1290       }
1291
1292   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
1293 }
1294
1295
1296 /* Create all the dynamic sections.  */
1297
1298 static bfd_boolean
1299 elf_xtensa_create_dynamic_sections (bfd *dynobj, struct bfd_link_info *info)
1300 {
1301   struct elf_xtensa_link_hash_table *htab;
1302   flagword flags, noalloc_flags;
1303
1304   htab = elf_xtensa_hash_table (info);
1305   if (htab == NULL)
1306     return FALSE;
1307
1308   /* First do all the standard stuff.  */
1309   if (! _bfd_elf_create_dynamic_sections (dynobj, info))
1310     return FALSE;
1311
1312   /* Create any extra PLT sections in case check_relocs has already
1313      been called on all the non-dynamic input files.  */
1314   if (! add_extra_plt_sections (info, htab->plt_reloc_count))
1315     return FALSE;
1316
1317   noalloc_flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
1318                    | SEC_LINKER_CREATED | SEC_READONLY);
1319   flags = noalloc_flags | SEC_ALLOC | SEC_LOAD;
1320
1321   /* Mark the ".got.plt" section READONLY.  */
1322   if (htab->elf.sgotplt == NULL
1323       || ! bfd_set_section_flags (dynobj, htab->elf.sgotplt, flags))
1324     return FALSE;
1325
1326   /* Create ".got.loc" (literal tables for use by dynamic linker).  */
1327   htab->sgotloc = bfd_make_section_anyway_with_flags (dynobj, ".got.loc",
1328                                                       flags);
1329   if (htab->sgotloc == NULL
1330       || ! bfd_set_section_alignment (dynobj, htab->sgotloc, 2))
1331     return FALSE;
1332
1333   /* Create ".xt.lit.plt" (literal table for ".got.plt*").  */
1334   htab->spltlittbl = bfd_make_section_anyway_with_flags (dynobj, ".xt.lit.plt",
1335                                                          noalloc_flags);
1336   if (htab->spltlittbl == NULL
1337       || ! bfd_set_section_alignment (dynobj, htab->spltlittbl, 2))
1338     return FALSE;
1339
1340   return TRUE;
1341 }
1342
1343
1344 static bfd_boolean
1345 add_extra_plt_sections (struct bfd_link_info *info, int count)
1346 {
1347   bfd *dynobj = elf_hash_table (info)->dynobj;
1348   int chunk;
1349
1350   /* Iterate over all chunks except 0 which uses the standard ".plt" and
1351      ".got.plt" sections.  */
1352   for (chunk = count / PLT_ENTRIES_PER_CHUNK; chunk > 0; chunk--)
1353     {
1354       char *sname;
1355       flagword flags;
1356       asection *s;
1357
1358       /* Stop when we find a section has already been created.  */
1359       if (elf_xtensa_get_plt_section (info, chunk))
1360         break;
1361
1362       flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
1363                | SEC_LINKER_CREATED | SEC_READONLY);
1364
1365       sname = (char *) bfd_malloc (10);
1366       sprintf (sname, ".plt.%u", chunk);
1367       s = bfd_make_section_anyway_with_flags (dynobj, sname, flags | SEC_CODE);
1368       if (s == NULL
1369           || ! bfd_set_section_alignment (dynobj, s, 2))
1370         return FALSE;
1371
1372       sname = (char *) bfd_malloc (14);
1373       sprintf (sname, ".got.plt.%u", chunk);
1374       s = bfd_make_section_anyway_with_flags (dynobj, sname, flags);
1375       if (s == NULL
1376           || ! bfd_set_section_alignment (dynobj, s, 2))
1377         return FALSE;
1378     }
1379
1380   return TRUE;
1381 }
1382
1383
1384 /* Adjust a symbol defined by a dynamic object and referenced by a
1385    regular object.  The current definition is in some section of the
1386    dynamic object, but we're not including those sections.  We have to
1387    change the definition to something the rest of the link can
1388    understand.  */
1389
1390 static bfd_boolean
1391 elf_xtensa_adjust_dynamic_symbol (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1392                                   struct elf_link_hash_entry *h)
1393 {
1394   /* If this is a weak symbol, and there is a real definition, the
1395      processor independent code will have arranged for us to see the
1396      real definition first, and we can just use the same value.  */
1397   if (h->is_weakalias)
1398     {
1399       struct elf_link_hash_entry *def = weakdef (h);
1400       BFD_ASSERT (def->root.type == bfd_link_hash_defined);
1401       h->root.u.def.section = def->root.u.def.section;
1402       h->root.u.def.value = def->root.u.def.value;
1403       return TRUE;
1404     }
1405
1406   /* This is a reference to a symbol defined by a dynamic object.  The
1407      reference must go through the GOT, so there's no need for COPY relocs,
1408      .dynbss, etc.  */
1409
1410   return TRUE;
1411 }
1412
1413
1414 static bfd_boolean
1415 elf_xtensa_allocate_dynrelocs (struct elf_link_hash_entry *h, void *arg)
1416 {
1417   struct bfd_link_info *info;
1418   struct elf_xtensa_link_hash_table *htab;
1419   struct elf_xtensa_link_hash_entry *eh = elf_xtensa_hash_entry (h);
1420
1421   if (h->root.type == bfd_link_hash_indirect)
1422     return TRUE;
1423
1424   info = (struct bfd_link_info *) arg;
1425   htab = elf_xtensa_hash_table (info);
1426   if (htab == NULL)
1427     return FALSE;
1428
1429   /* If we saw any use of an IE model for this symbol, we can then optimize
1430      away GOT entries for any TLSDESC_FN relocs.  */
1431   if ((eh->tls_type & GOT_TLS_IE) != 0)
1432     {
1433       BFD_ASSERT (h->got.refcount >= eh->tlsfunc_refcount);
1434       h->got.refcount -= eh->tlsfunc_refcount;
1435     }
1436
1437   if (! elf_xtensa_dynamic_symbol_p (h, info))
1438     elf_xtensa_make_sym_local (info, h);
1439
1440   if (! elf_xtensa_dynamic_symbol_p (h, info)
1441       && h->root.type == bfd_link_hash_undefweak)
1442     return TRUE;
1443
1444   if (h->plt.refcount > 0)
1445     htab->elf.srelplt->size += (h->plt.refcount * sizeof (Elf32_External_Rela));
1446
1447   if (h->got.refcount > 0)
1448     htab->elf.srelgot->size += (h->got.refcount * sizeof (Elf32_External_Rela));
1449
1450   return TRUE;
1451 }
1452
1453
1454 static void
1455 elf_xtensa_allocate_local_got_size (struct bfd_link_info *info)
1456 {
1457   struct elf_xtensa_link_hash_table *htab;
1458   bfd *i;
1459
1460   htab = elf_xtensa_hash_table (info);
1461   if (htab == NULL)
1462     return;
1463
1464   for (i = info->input_bfds; i; i = i->link.next)
1465     {
1466       bfd_signed_vma *local_got_refcounts;
1467       bfd_size_type j, cnt;
1468       Elf_Internal_Shdr *symtab_hdr;
1469
1470       local_got_refcounts = elf_local_got_refcounts (i);
1471       if (!local_got_refcounts)
1472         continue;
1473
1474       symtab_hdr = &elf_tdata (i)->symtab_hdr;
1475       cnt = symtab_hdr->sh_info;
1476
1477       for (j = 0; j < cnt; ++j)
1478         {
1479           /* If we saw any use of an IE model for this symbol, we can
1480              then optimize away GOT entries for any TLSDESC_FN relocs.  */
1481           if ((elf_xtensa_local_got_tls_type (i) [j] & GOT_TLS_IE) != 0)
1482             {
1483               bfd_signed_vma *tlsfunc_refcount
1484                 = &elf_xtensa_local_tlsfunc_refcounts (i) [j];
1485               BFD_ASSERT (local_got_refcounts[j] >= *tlsfunc_refcount);
1486               local_got_refcounts[j] -= *tlsfunc_refcount;
1487             }
1488
1489           if (local_got_refcounts[j] > 0)
1490             htab->elf.srelgot->size += (local_got_refcounts[j]
1491                                         * sizeof (Elf32_External_Rela));
1492         }
1493     }
1494 }
1495
1496
1497 /* Set the sizes of the dynamic sections.  */
1498
1499 static bfd_boolean
1500 elf_xtensa_size_dynamic_sections (bfd *output_bfd ATTRIBUTE_UNUSED,
1501                                   struct bfd_link_info *info)
1502 {
1503   struct elf_xtensa_link_hash_table *htab;
1504   bfd *dynobj, *abfd;
1505   asection *s, *srelplt, *splt, *sgotplt, *srelgot, *spltlittbl, *sgotloc;
1506   bfd_boolean relplt, relgot;
1507   int plt_entries, plt_chunks, chunk;
1508
1509   plt_entries = 0;
1510   plt_chunks = 0;
1511
1512   htab = elf_xtensa_hash_table (info);
1513   if (htab == NULL)
1514     return FALSE;
1515
1516   dynobj = elf_hash_table (info)->dynobj;
1517   if (dynobj == NULL)
1518     abort ();
1519   srelgot = htab->elf.srelgot;
1520   srelplt = htab->elf.srelplt;
1521
1522   if (elf_hash_table (info)->dynamic_sections_created)
1523     {
1524       BFD_ASSERT (htab->elf.srelgot != NULL
1525                   && htab->elf.srelplt != NULL
1526                   && htab->elf.sgot != NULL
1527                   && htab->spltlittbl != NULL
1528                   && htab->sgotloc != NULL);
1529
1530       /* Set the contents of the .interp section to the interpreter.  */
1531       if (bfd_link_executable (info) && !info->nointerp)
1532         {
1533           s = bfd_get_linker_section (dynobj, ".interp");
1534           if (s == NULL)
1535             abort ();
1536           s->size = sizeof ELF_DYNAMIC_INTERPRETER;
1537           s->contents = (unsigned char *) ELF_DYNAMIC_INTERPRETER;
1538         }
1539
1540       /* Allocate room for one word in ".got".  */
1541       htab->elf.sgot->size = 4;
1542
1543       /* Allocate space in ".rela.got" for literals that reference global
1544          symbols and space in ".rela.plt" for literals that have PLT
1545          entries.  */
1546       elf_link_hash_traverse (elf_hash_table (info),
1547                               elf_xtensa_allocate_dynrelocs,
1548                               (void *) info);
1549
1550       /* If we are generating a shared object, we also need space in
1551          ".rela.got" for R_XTENSA_RELATIVE relocs for literals that
1552          reference local symbols.  */
1553       if (bfd_link_pic (info))
1554         elf_xtensa_allocate_local_got_size (info);
1555
1556       /* Allocate space in ".plt" to match the size of ".rela.plt".  For
1557          each PLT entry, we need the PLT code plus a 4-byte literal.
1558          For each chunk of ".plt", we also need two more 4-byte
1559          literals, two corresponding entries in ".rela.got", and an
1560          8-byte entry in ".xt.lit.plt".  */
1561       spltlittbl = htab->spltlittbl;
1562       plt_entries = srelplt->size / sizeof (Elf32_External_Rela);
1563       plt_chunks =
1564         (plt_entries + PLT_ENTRIES_PER_CHUNK - 1) / PLT_ENTRIES_PER_CHUNK;
1565
1566       /* Iterate over all the PLT chunks, including any extra sections
1567          created earlier because the initial count of PLT relocations
1568          was an overestimate.  */
1569       for (chunk = 0;
1570            (splt = elf_xtensa_get_plt_section (info, chunk)) != NULL;
1571            chunk++)
1572         {
1573           int chunk_entries;
1574
1575           sgotplt = elf_xtensa_get_gotplt_section (info, chunk);
1576           BFD_ASSERT (sgotplt != NULL);
1577
1578           if (chunk < plt_chunks - 1)
1579             chunk_entries = PLT_ENTRIES_PER_CHUNK;
1580           else if (chunk == plt_chunks - 1)
1581             chunk_entries = plt_entries - (chunk * PLT_ENTRIES_PER_CHUNK);
1582           else
1583             chunk_entries = 0;
1584
1585           if (chunk_entries != 0)
1586             {
1587               sgotplt->size = 4 * (chunk_entries + 2);
1588               splt->size = PLT_ENTRY_SIZE * chunk_entries;
1589               srelgot->size += 2 * sizeof (Elf32_External_Rela);
1590               spltlittbl->size += 8;
1591             }
1592           else
1593             {
1594               sgotplt->size = 0;
1595               splt->size = 0;
1596             }
1597         }
1598
1599       /* Allocate space in ".got.loc" to match the total size of all the
1600          literal tables.  */
1601       sgotloc = htab->sgotloc;
1602       sgotloc->size = spltlittbl->size;
1603       for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
1604         {
1605           if (abfd->flags & DYNAMIC)
1606             continue;
1607           for (s = abfd->sections; s != NULL; s = s->next)
1608             {
1609               if (! discarded_section (s)
1610                   && xtensa_is_littable_section (s)
1611                   && s != spltlittbl)
1612                 sgotloc->size += s->size;
1613             }
1614         }
1615     }
1616
1617   /* Allocate memory for dynamic sections.  */
1618   relplt = FALSE;
1619   relgot = FALSE;
1620   for (s = dynobj->sections; s != NULL; s = s->next)
1621     {
1622       const char *name;
1623
1624       if ((s->flags & SEC_LINKER_CREATED) == 0)
1625         continue;
1626
1627       /* It's OK to base decisions on the section name, because none
1628          of the dynobj section names depend upon the input files.  */
1629       name = bfd_get_section_name (dynobj, s);
1630
1631       if (CONST_STRNEQ (name, ".rela"))
1632         {
1633           if (s->size != 0)
1634             {
1635               if (strcmp (name, ".rela.plt") == 0)
1636                 relplt = TRUE;
1637               else if (strcmp (name, ".rela.got") == 0)
1638                 relgot = TRUE;
1639
1640               /* We use the reloc_count field as a counter if we need
1641                  to copy relocs into the output file.  */
1642               s->reloc_count = 0;
1643             }
1644         }
1645       else if (! CONST_STRNEQ (name, ".plt.")
1646                && ! CONST_STRNEQ (name, ".got.plt.")
1647                && strcmp (name, ".got") != 0
1648                && strcmp (name, ".plt") != 0
1649                && strcmp (name, ".got.plt") != 0
1650                && strcmp (name, ".xt.lit.plt") != 0
1651                && strcmp (name, ".got.loc") != 0)
1652         {
1653           /* It's not one of our sections, so don't allocate space.  */
1654           continue;
1655         }
1656
1657       if (s->size == 0)
1658         {
1659           /* If we don't need this section, strip it from the output
1660              file.  We must create the ".plt*" and ".got.plt*"
1661              sections in create_dynamic_sections and/or check_relocs
1662              based on a conservative estimate of the PLT relocation
1663              count, because the sections must be created before the
1664              linker maps input sections to output sections.  The
1665              linker does that before size_dynamic_sections, where we
1666              compute the exact size of the PLT, so there may be more
1667              of these sections than are actually needed.  */
1668           s->flags |= SEC_EXCLUDE;
1669         }
1670       else if ((s->flags & SEC_HAS_CONTENTS) != 0)
1671         {
1672           /* Allocate memory for the section contents.  */
1673           s->contents = (bfd_byte *) bfd_zalloc (dynobj, s->size);
1674           if (s->contents == NULL)
1675             return FALSE;
1676         }
1677     }
1678
1679   if (elf_hash_table (info)->dynamic_sections_created)
1680     {
1681       /* Add the special XTENSA_RTLD relocations now.  The offsets won't be
1682          known until finish_dynamic_sections, but we need to get the relocs
1683          in place before they are sorted.  */
1684       for (chunk = 0; chunk < plt_chunks; chunk++)
1685         {
1686           Elf_Internal_Rela irela;
1687           bfd_byte *loc;
1688
1689           irela.r_offset = 0;
1690           irela.r_info = ELF32_R_INFO (0, R_XTENSA_RTLD);
1691           irela.r_addend = 0;
1692
1693           loc = (srelgot->contents
1694                  + srelgot->reloc_count * sizeof (Elf32_External_Rela));
1695           bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
1696           bfd_elf32_swap_reloca_out (output_bfd, &irela,
1697                                      loc + sizeof (Elf32_External_Rela));
1698           srelgot->reloc_count += 2;
1699         }
1700
1701       /* Add some entries to the .dynamic section.  We fill in the
1702          values later, in elf_xtensa_finish_dynamic_sections, but we
1703          must add the entries now so that we get the correct size for
1704          the .dynamic section.  The DT_DEBUG entry is filled in by the
1705          dynamic linker and used by the debugger.  */
1706 #define add_dynamic_entry(TAG, VAL) \
1707   _bfd_elf_add_dynamic_entry (info, TAG, VAL)
1708
1709       if (bfd_link_executable (info))
1710         {
1711           if (!add_dynamic_entry (DT_DEBUG, 0))
1712             return FALSE;
1713         }
1714
1715       if (relplt)
1716         {
1717           if (!add_dynamic_entry (DT_PLTRELSZ, 0)
1718               || !add_dynamic_entry (DT_PLTREL, DT_RELA)
1719               || !add_dynamic_entry (DT_JMPREL, 0))
1720             return FALSE;
1721         }
1722
1723       if (relgot)
1724         {
1725           if (!add_dynamic_entry (DT_RELA, 0)
1726               || !add_dynamic_entry (DT_RELASZ, 0)
1727               || !add_dynamic_entry (DT_RELAENT, sizeof (Elf32_External_Rela)))
1728             return FALSE;
1729         }
1730
1731       if (!add_dynamic_entry (DT_PLTGOT, 0)
1732           || !add_dynamic_entry (DT_XTENSA_GOT_LOC_OFF, 0)
1733           || !add_dynamic_entry (DT_XTENSA_GOT_LOC_SZ, 0))
1734         return FALSE;
1735     }
1736 #undef add_dynamic_entry
1737
1738   return TRUE;
1739 }
1740
1741 static bfd_boolean
1742 elf_xtensa_always_size_sections (bfd *output_bfd,
1743                                  struct bfd_link_info *info)
1744 {
1745   struct elf_xtensa_link_hash_table *htab;
1746   asection *tls_sec;
1747
1748   htab = elf_xtensa_hash_table (info);
1749   if (htab == NULL)
1750     return FALSE;
1751
1752   tls_sec = htab->elf.tls_sec;
1753
1754   if (tls_sec && (htab->tlsbase->tls_type & GOT_TLS_ANY) != 0)
1755     {
1756       struct elf_link_hash_entry *tlsbase = &htab->tlsbase->elf;
1757       struct bfd_link_hash_entry *bh = &tlsbase->root;
1758       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
1759
1760       tlsbase->type = STT_TLS;
1761       if (!(_bfd_generic_link_add_one_symbol
1762             (info, output_bfd, "_TLS_MODULE_BASE_", BSF_LOCAL,
1763              tls_sec, 0, NULL, FALSE,
1764              bed->collect, &bh)))
1765         return FALSE;
1766       tlsbase->def_regular = 1;
1767       tlsbase->other = STV_HIDDEN;
1768       (*bed->elf_backend_hide_symbol) (info, tlsbase, TRUE);
1769     }
1770
1771   return TRUE;
1772 }
1773
1774 \f
1775 /* Return the base VMA address which should be subtracted from real addresses
1776    when resolving @dtpoff relocation.
1777    This is PT_TLS segment p_vaddr.  */
1778
1779 static bfd_vma
1780 dtpoff_base (struct bfd_link_info *info)
1781 {
1782   /* If tls_sec is NULL, we should have signalled an error already.  */
1783   if (elf_hash_table (info)->tls_sec == NULL)
1784     return 0;
1785   return elf_hash_table (info)->tls_sec->vma;
1786 }
1787
1788 /* Return the relocation value for @tpoff relocation
1789    if STT_TLS virtual address is ADDRESS.  */
1790
1791 static bfd_vma
1792 tpoff (struct bfd_link_info *info, bfd_vma address)
1793 {
1794   struct elf_link_hash_table *htab = elf_hash_table (info);
1795   bfd_vma base;
1796
1797   /* If tls_sec is NULL, we should have signalled an error already.  */
1798   if (htab->tls_sec == NULL)
1799     return 0;
1800   base = align_power ((bfd_vma) TCB_SIZE, htab->tls_sec->alignment_power);
1801   return address - htab->tls_sec->vma + base;
1802 }
1803
1804 /* Perform the specified relocation.  The instruction at (contents + address)
1805    is modified to set one operand to represent the value in "relocation".  The
1806    operand position is determined by the relocation type recorded in the
1807    howto.  */
1808
1809 #define CALL_SEGMENT_BITS (30)
1810 #define CALL_SEGMENT_SIZE (1 << CALL_SEGMENT_BITS)
1811
1812 static bfd_reloc_status_type
1813 elf_xtensa_do_reloc (reloc_howto_type *howto,
1814                      bfd *abfd,
1815                      asection *input_section,
1816                      bfd_vma relocation,
1817                      bfd_byte *contents,
1818                      bfd_vma address,
1819                      bfd_boolean is_weak_undef,
1820                      char **error_message)
1821 {
1822   xtensa_format fmt;
1823   xtensa_opcode opcode;
1824   xtensa_isa isa = xtensa_default_isa;
1825   static xtensa_insnbuf ibuff = NULL;
1826   static xtensa_insnbuf sbuff = NULL;
1827   bfd_vma self_address;
1828   bfd_size_type input_size;
1829   int opnd, slot;
1830   uint32 newval;
1831
1832   if (!ibuff)
1833     {
1834       ibuff = xtensa_insnbuf_alloc (isa);
1835       sbuff = xtensa_insnbuf_alloc (isa);
1836     }
1837
1838   input_size = bfd_get_section_limit (abfd, input_section);
1839
1840   /* Calculate the PC address for this instruction.  */
1841   self_address = (input_section->output_section->vma
1842                   + input_section->output_offset
1843                   + address);
1844
1845   switch (howto->type)
1846     {
1847     case R_XTENSA_NONE:
1848     case R_XTENSA_DIFF8:
1849     case R_XTENSA_DIFF16:
1850     case R_XTENSA_DIFF32:
1851     case R_XTENSA_TLS_FUNC:
1852     case R_XTENSA_TLS_ARG:
1853     case R_XTENSA_TLS_CALL:
1854       return bfd_reloc_ok;
1855
1856     case R_XTENSA_ASM_EXPAND:
1857       if (!is_weak_undef)
1858         {
1859           /* Check for windowed CALL across a 1GB boundary.  */
1860           opcode = get_expanded_call_opcode (contents + address,
1861                                              input_size - address, 0);
1862           if (is_windowed_call_opcode (opcode))
1863             {
1864               if ((self_address >> CALL_SEGMENT_BITS)
1865                   != (relocation >> CALL_SEGMENT_BITS))
1866                 {
1867                   *error_message = "windowed longcall crosses 1GB boundary; "
1868                     "return may fail";
1869                   return bfd_reloc_dangerous;
1870                 }
1871             }
1872         }
1873       return bfd_reloc_ok;
1874
1875     case R_XTENSA_ASM_SIMPLIFY:
1876       {
1877         /* Convert the L32R/CALLX to CALL.  */
1878         bfd_reloc_status_type retval =
1879           elf_xtensa_do_asm_simplify (contents, address, input_size,
1880                                       error_message);
1881         if (retval != bfd_reloc_ok)
1882           return bfd_reloc_dangerous;
1883
1884         /* The CALL needs to be relocated.  Continue below for that part.  */
1885         address += 3;
1886         self_address += 3;
1887         howto = &elf_howto_table[(unsigned) R_XTENSA_SLOT0_OP ];
1888       }
1889       break;
1890
1891     case R_XTENSA_32:
1892       {
1893         bfd_vma x;
1894         x = bfd_get_32 (abfd, contents + address);
1895         x = x + relocation;
1896         bfd_put_32 (abfd, x, contents + address);
1897       }
1898       return bfd_reloc_ok;
1899
1900     case R_XTENSA_32_PCREL:
1901       bfd_put_32 (abfd, relocation - self_address, contents + address);
1902       return bfd_reloc_ok;
1903
1904     case R_XTENSA_PLT:
1905     case R_XTENSA_TLSDESC_FN:
1906     case R_XTENSA_TLSDESC_ARG:
1907     case R_XTENSA_TLS_DTPOFF:
1908     case R_XTENSA_TLS_TPOFF:
1909       bfd_put_32 (abfd, relocation, contents + address);
1910       return bfd_reloc_ok;
1911     }
1912
1913   /* Only instruction slot-specific relocations handled below.... */
1914   slot = get_relocation_slot (howto->type);
1915   if (slot == XTENSA_UNDEFINED)
1916     {
1917       *error_message = "unexpected relocation";
1918       return bfd_reloc_dangerous;
1919     }
1920
1921   /* Read the instruction into a buffer and decode the opcode.  */
1922   xtensa_insnbuf_from_chars (isa, ibuff, contents + address,
1923                              input_size - address);
1924   fmt = xtensa_format_decode (isa, ibuff);
1925   if (fmt == XTENSA_UNDEFINED)
1926     {
1927       *error_message = "cannot decode instruction format";
1928       return bfd_reloc_dangerous;
1929     }
1930
1931   xtensa_format_get_slot (isa, fmt, slot, ibuff, sbuff);
1932
1933   opcode = xtensa_opcode_decode (isa, fmt, slot, sbuff);
1934   if (opcode == XTENSA_UNDEFINED)
1935     {
1936       *error_message = "cannot decode instruction opcode";
1937       return bfd_reloc_dangerous;
1938     }
1939
1940   /* Check for opcode-specific "alternate" relocations.  */
1941   if (is_alt_relocation (howto->type))
1942     {
1943       if (opcode == get_l32r_opcode ())
1944         {
1945           /* Handle the special-case of non-PC-relative L32R instructions.  */
1946           bfd *output_bfd = input_section->output_section->owner;
1947           asection *lit4_sec = bfd_get_section_by_name (output_bfd, ".lit4");
1948           if (!lit4_sec)
1949             {
1950               *error_message = "relocation references missing .lit4 section";
1951               return bfd_reloc_dangerous;
1952             }
1953           self_address = ((lit4_sec->vma & ~0xfff)
1954                           + 0x40000 - 3); /* -3 to compensate for do_reloc */
1955           newval = relocation;
1956           opnd = 1;
1957         }
1958       else if (opcode == get_const16_opcode ())
1959         {
1960           /* ALT used for high 16 bits.
1961              Ignore 32-bit overflow.  */
1962           newval = (relocation >> 16) & 0xffff;
1963           opnd = 1;
1964         }
1965       else
1966         {
1967           /* No other "alternate" relocations currently defined.  */
1968           *error_message = "unexpected relocation";
1969           return bfd_reloc_dangerous;
1970         }
1971     }
1972   else /* Not an "alternate" relocation.... */
1973     {
1974       if (opcode == get_const16_opcode ())
1975         {
1976           newval = relocation & 0xffff;
1977           opnd = 1;
1978         }
1979       else
1980         {
1981           /* ...normal PC-relative relocation.... */
1982
1983           /* Determine which operand is being relocated.  */
1984           opnd = get_relocation_opnd (opcode, howto->type);
1985           if (opnd == XTENSA_UNDEFINED)
1986             {
1987               *error_message = "unexpected relocation";
1988               return bfd_reloc_dangerous;
1989             }
1990
1991           if (!howto->pc_relative)
1992             {
1993               *error_message = "expected PC-relative relocation";
1994               return bfd_reloc_dangerous;
1995             }
1996
1997           newval = relocation;
1998         }
1999     }
2000
2001   /* Apply the relocation.  */
2002   if (xtensa_operand_do_reloc (isa, opcode, opnd, &newval, self_address)
2003       || xtensa_operand_encode (isa, opcode, opnd, &newval)
2004       || xtensa_operand_set_field (isa, opcode, opnd, fmt, slot,
2005                                    sbuff, newval))
2006     {
2007       const char *opname = xtensa_opcode_name (isa, opcode);
2008       const char *msg;
2009
2010       msg = "cannot encode";
2011       if (is_direct_call_opcode (opcode))
2012         {
2013           if ((relocation & 0x3) != 0)
2014             msg = "misaligned call target";
2015           else
2016             msg = "call target out of range";
2017         }
2018       else if (opcode == get_l32r_opcode ())
2019         {
2020           if ((relocation & 0x3) != 0)
2021             msg = "misaligned literal target";
2022           else if (is_alt_relocation (howto->type))
2023             msg = "literal target out of range (too many literals)";
2024           else if (self_address > relocation)
2025             msg = "literal target out of range (try using text-section-literals)";
2026           else
2027             msg = "literal placed after use";
2028         }
2029
2030       *error_message = vsprint_msg (opname, ": %s", strlen (msg) + 2, msg);
2031       return bfd_reloc_dangerous;
2032     }
2033
2034   /* Check for calls across 1GB boundaries.  */
2035   if (is_direct_call_opcode (opcode)
2036       && is_windowed_call_opcode (opcode))
2037     {
2038       if ((self_address >> CALL_SEGMENT_BITS)
2039           != (relocation >> CALL_SEGMENT_BITS))
2040         {
2041           *error_message =
2042             "windowed call crosses 1GB boundary; return may fail";
2043           return bfd_reloc_dangerous;
2044         }
2045     }
2046
2047   /* Write the modified instruction back out of the buffer.  */
2048   xtensa_format_set_slot (isa, fmt, slot, ibuff, sbuff);
2049   xtensa_insnbuf_to_chars (isa, ibuff, contents + address,
2050                            input_size - address);
2051   return bfd_reloc_ok;
2052 }
2053
2054
2055 static char *
2056 vsprint_msg (const char *origmsg, const char *fmt, int arglen, ...)
2057 {
2058   /* To reduce the size of the memory leak,
2059      we only use a single message buffer.  */
2060   static bfd_size_type alloc_size = 0;
2061   static char *message = NULL;
2062   bfd_size_type orig_len, len = 0;
2063   bfd_boolean is_append;
2064   va_list ap;
2065
2066   va_start (ap, arglen);
2067
2068   is_append = (origmsg == message);
2069
2070   orig_len = strlen (origmsg);
2071   len = orig_len + strlen (fmt) + arglen + 20;
2072   if (len > alloc_size)
2073     {
2074       message = (char *) bfd_realloc_or_free (message, len);
2075       alloc_size = len;
2076     }
2077   if (message != NULL)
2078     {
2079       if (!is_append)
2080         memcpy (message, origmsg, orig_len);
2081       vsprintf (message + orig_len, fmt, ap);
2082     }
2083   va_end (ap);
2084   return message;
2085 }
2086
2087
2088 /* This function is registered as the "special_function" in the
2089    Xtensa howto for handling simplify operations.
2090    bfd_perform_relocation / bfd_install_relocation use it to
2091    perform (install) the specified relocation.  Since this replaces the code
2092    in bfd_perform_relocation, it is basically an Xtensa-specific,
2093    stripped-down version of bfd_perform_relocation.  */
2094
2095 static bfd_reloc_status_type
2096 bfd_elf_xtensa_reloc (bfd *abfd,
2097                       arelent *reloc_entry,
2098                       asymbol *symbol,
2099                       void *data,
2100                       asection *input_section,
2101                       bfd *output_bfd,
2102                       char **error_message)
2103 {
2104   bfd_vma relocation;
2105   bfd_reloc_status_type flag;
2106   bfd_size_type octets = reloc_entry->address * bfd_octets_per_byte (abfd);
2107   bfd_vma output_base = 0;
2108   reloc_howto_type *howto = reloc_entry->howto;
2109   asection *reloc_target_output_section;
2110   bfd_boolean is_weak_undef;
2111
2112   if (!xtensa_default_isa)
2113     xtensa_default_isa = xtensa_isa_init (0, 0);
2114
2115   /* ELF relocs are against symbols.  If we are producing relocatable
2116      output, and the reloc is against an external symbol, the resulting
2117      reloc will also be against the same symbol.  In such a case, we
2118      don't want to change anything about the way the reloc is handled,
2119      since it will all be done at final link time.  This test is similar
2120      to what bfd_elf_generic_reloc does except that it lets relocs with
2121      howto->partial_inplace go through even if the addend is non-zero.
2122      (The real problem is that partial_inplace is set for XTENSA_32
2123      relocs to begin with, but that's a long story and there's little we
2124      can do about it now....)  */
2125
2126   if (output_bfd && (symbol->flags & BSF_SECTION_SYM) == 0)
2127     {
2128       reloc_entry->address += input_section->output_offset;
2129       return bfd_reloc_ok;
2130     }
2131
2132   /* Is the address of the relocation really within the section?  */
2133   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2134     return bfd_reloc_outofrange;
2135
2136   /* Work out which section the relocation is targeted at and the
2137      initial relocation command value.  */
2138
2139   /* Get symbol value.  (Common symbols are special.)  */
2140   if (bfd_is_com_section (symbol->section))
2141     relocation = 0;
2142   else
2143     relocation = symbol->value;
2144
2145   reloc_target_output_section = symbol->section->output_section;
2146
2147   /* Convert input-section-relative symbol value to absolute.  */
2148   if ((output_bfd && !howto->partial_inplace)
2149       || reloc_target_output_section == NULL)
2150     output_base = 0;
2151   else
2152     output_base = reloc_target_output_section->vma;
2153
2154   relocation += output_base + symbol->section->output_offset;
2155
2156   /* Add in supplied addend.  */
2157   relocation += reloc_entry->addend;
2158
2159   /* Here the variable relocation holds the final address of the
2160      symbol we are relocating against, plus any addend.  */
2161   if (output_bfd)
2162     {
2163       if (!howto->partial_inplace)
2164         {
2165           /* This is a partial relocation, and we want to apply the relocation
2166              to the reloc entry rather than the raw data.  Everything except
2167              relocations against section symbols has already been handled
2168              above.  */
2169
2170           BFD_ASSERT (symbol->flags & BSF_SECTION_SYM);
2171           reloc_entry->addend = relocation;
2172           reloc_entry->address += input_section->output_offset;
2173           return bfd_reloc_ok;
2174         }
2175       else
2176         {
2177           reloc_entry->address += input_section->output_offset;
2178           reloc_entry->addend = 0;
2179         }
2180     }
2181
2182   is_weak_undef = (bfd_is_und_section (symbol->section)
2183                    && (symbol->flags & BSF_WEAK) != 0);
2184   flag = elf_xtensa_do_reloc (howto, abfd, input_section, relocation,
2185                               (bfd_byte *) data, (bfd_vma) octets,
2186                               is_weak_undef, error_message);
2187
2188   if (flag == bfd_reloc_dangerous)
2189     {
2190       /* Add the symbol name to the error message.  */
2191       if (! *error_message)
2192         *error_message = "";
2193       *error_message = vsprint_msg (*error_message, ": (%s + 0x%lx)",
2194                                     strlen (symbol->name) + 17,
2195                                     symbol->name,
2196                                     (unsigned long) reloc_entry->addend);
2197     }
2198
2199   return flag;
2200 }
2201
2202
2203 /* Set up an entry in the procedure linkage table.  */
2204
2205 static bfd_vma
2206 elf_xtensa_create_plt_entry (struct bfd_link_info *info,
2207                              bfd *output_bfd,
2208                              unsigned reloc_index)
2209 {
2210   asection *splt, *sgotplt;
2211   bfd_vma plt_base, got_base;
2212   bfd_vma code_offset, lit_offset, abi_offset;
2213   int chunk;
2214
2215   chunk = reloc_index / PLT_ENTRIES_PER_CHUNK;
2216   splt = elf_xtensa_get_plt_section (info, chunk);
2217   sgotplt = elf_xtensa_get_gotplt_section (info, chunk);
2218   BFD_ASSERT (splt != NULL && sgotplt != NULL);
2219
2220   plt_base = splt->output_section->vma + splt->output_offset;
2221   got_base = sgotplt->output_section->vma + sgotplt->output_offset;
2222
2223   lit_offset = 8 + (reloc_index % PLT_ENTRIES_PER_CHUNK) * 4;
2224   code_offset = (reloc_index % PLT_ENTRIES_PER_CHUNK) * PLT_ENTRY_SIZE;
2225
2226   /* Fill in the literal entry.  This is the offset of the dynamic
2227      relocation entry.  */
2228   bfd_put_32 (output_bfd, reloc_index * sizeof (Elf32_External_Rela),
2229               sgotplt->contents + lit_offset);
2230
2231   /* Fill in the entry in the procedure linkage table.  */
2232   memcpy (splt->contents + code_offset,
2233           (bfd_big_endian (output_bfd)
2234            ? elf_xtensa_be_plt_entry[XSHAL_ABI != XTHAL_ABI_WINDOWED]
2235            : elf_xtensa_le_plt_entry[XSHAL_ABI != XTHAL_ABI_WINDOWED]),
2236           PLT_ENTRY_SIZE);
2237   abi_offset = XSHAL_ABI == XTHAL_ABI_WINDOWED ? 3 : 0;
2238   bfd_put_16 (output_bfd, l32r_offset (got_base + 0,
2239                                        plt_base + code_offset + abi_offset),
2240               splt->contents + code_offset + abi_offset + 1);
2241   bfd_put_16 (output_bfd, l32r_offset (got_base + 4,
2242                                        plt_base + code_offset + abi_offset + 3),
2243               splt->contents + code_offset + abi_offset + 4);
2244   bfd_put_16 (output_bfd, l32r_offset (got_base + lit_offset,
2245                                        plt_base + code_offset + abi_offset + 6),
2246               splt->contents + code_offset + abi_offset + 7);
2247
2248   return plt_base + code_offset;
2249 }
2250
2251
2252 static bfd_boolean get_indirect_call_dest_reg (xtensa_opcode, unsigned *);
2253
2254 static bfd_boolean
2255 replace_tls_insn (Elf_Internal_Rela *rel,
2256                   bfd *abfd,
2257                   asection *input_section,
2258                   bfd_byte *contents,
2259                   bfd_boolean is_ld_model,
2260                   char **error_message)
2261 {
2262   static xtensa_insnbuf ibuff = NULL;
2263   static xtensa_insnbuf sbuff = NULL;
2264   xtensa_isa isa = xtensa_default_isa;
2265   xtensa_format fmt;
2266   xtensa_opcode old_op, new_op;
2267   bfd_size_type input_size;
2268   int r_type;
2269   unsigned dest_reg, src_reg;
2270
2271   if (ibuff == NULL)
2272     {
2273       ibuff = xtensa_insnbuf_alloc (isa);
2274       sbuff = xtensa_insnbuf_alloc (isa);
2275     }
2276
2277   input_size = bfd_get_section_limit (abfd, input_section);
2278
2279   /* Read the instruction into a buffer and decode the opcode.  */
2280   xtensa_insnbuf_from_chars (isa, ibuff, contents + rel->r_offset,
2281                              input_size - rel->r_offset);
2282   fmt = xtensa_format_decode (isa, ibuff);
2283   if (fmt == XTENSA_UNDEFINED)
2284     {
2285       *error_message = "cannot decode instruction format";
2286       return FALSE;
2287     }
2288
2289   BFD_ASSERT (xtensa_format_num_slots (isa, fmt) == 1);
2290   xtensa_format_get_slot (isa, fmt, 0, ibuff, sbuff);
2291
2292   old_op = xtensa_opcode_decode (isa, fmt, 0, sbuff);
2293   if (old_op == XTENSA_UNDEFINED)
2294     {
2295       *error_message = "cannot decode instruction opcode";
2296       return FALSE;
2297     }
2298
2299   r_type = ELF32_R_TYPE (rel->r_info);
2300   switch (r_type)
2301     {
2302     case R_XTENSA_TLS_FUNC:
2303     case R_XTENSA_TLS_ARG:
2304       if (old_op != get_l32r_opcode ()
2305           || xtensa_operand_get_field (isa, old_op, 0, fmt, 0,
2306                                        sbuff, &dest_reg) != 0)
2307         {
2308           *error_message = "cannot extract L32R destination for TLS access";
2309           return FALSE;
2310         }
2311       break;
2312
2313     case R_XTENSA_TLS_CALL:
2314       if (! get_indirect_call_dest_reg (old_op, &dest_reg)
2315           || xtensa_operand_get_field (isa, old_op, 0, fmt, 0,
2316                                        sbuff, &src_reg) != 0)
2317         {
2318           *error_message = "cannot extract CALLXn operands for TLS access";
2319           return FALSE;
2320         }
2321       break;
2322
2323     default:
2324       abort ();
2325     }
2326
2327   if (is_ld_model)
2328     {
2329       switch (r_type)
2330         {
2331         case R_XTENSA_TLS_FUNC:
2332         case R_XTENSA_TLS_ARG:
2333           /* Change the instruction to a NOP (or "OR a1, a1, a1" for older
2334              versions of Xtensa).  */
2335           new_op = xtensa_opcode_lookup (isa, "nop");
2336           if (new_op == XTENSA_UNDEFINED)
2337             {
2338               new_op = xtensa_opcode_lookup (isa, "or");
2339               if (new_op == XTENSA_UNDEFINED
2340                   || xtensa_opcode_encode (isa, fmt, 0, sbuff, new_op) != 0
2341                   || xtensa_operand_set_field (isa, new_op, 0, fmt, 0,
2342                                                sbuff, 1) != 0
2343                   || xtensa_operand_set_field (isa, new_op, 1, fmt, 0,
2344                                                sbuff, 1) != 0
2345                   || xtensa_operand_set_field (isa, new_op, 2, fmt, 0,
2346                                                sbuff, 1) != 0)
2347                 {
2348                   *error_message = "cannot encode OR for TLS access";
2349                   return FALSE;
2350                 }
2351             }
2352           else
2353             {
2354               if (xtensa_opcode_encode (isa, fmt, 0, sbuff, new_op) != 0)
2355                 {
2356                   *error_message = "cannot encode NOP for TLS access";
2357                   return FALSE;
2358                 }
2359             }
2360           break;
2361
2362         case R_XTENSA_TLS_CALL:
2363           /* Read THREADPTR into the CALLX's return value register.  */
2364           new_op = xtensa_opcode_lookup (isa, "rur.threadptr");
2365           if (new_op == XTENSA_UNDEFINED
2366               || xtensa_opcode_encode (isa, fmt, 0, sbuff, new_op) != 0
2367               || xtensa_operand_set_field (isa, new_op, 0, fmt, 0,
2368                                            sbuff, dest_reg + 2) != 0)
2369             {
2370               *error_message = "cannot encode RUR.THREADPTR for TLS access";
2371               return FALSE;
2372             }
2373           break;
2374         }
2375     }
2376   else
2377     {
2378       switch (r_type)
2379         {
2380         case R_XTENSA_TLS_FUNC:
2381           new_op = xtensa_opcode_lookup (isa, "rur.threadptr");
2382           if (new_op == XTENSA_UNDEFINED
2383               || xtensa_opcode_encode (isa, fmt, 0, sbuff, new_op) != 0
2384               || xtensa_operand_set_field (isa, new_op, 0, fmt, 0,
2385                                            sbuff, dest_reg) != 0)
2386             {
2387               *error_message = "cannot encode RUR.THREADPTR for TLS access";
2388               return FALSE;
2389             }
2390           break;
2391
2392         case R_XTENSA_TLS_ARG:
2393           /* Nothing to do.  Keep the original L32R instruction.  */
2394           return TRUE;
2395
2396         case R_XTENSA_TLS_CALL:
2397           /* Add the CALLX's src register (holding the THREADPTR value)
2398              to the first argument register (holding the offset) and put
2399              the result in the CALLX's return value register.  */
2400           new_op = xtensa_opcode_lookup (isa, "add");
2401           if (new_op == XTENSA_UNDEFINED
2402               || xtensa_opcode_encode (isa, fmt, 0, sbuff, new_op) != 0
2403               || xtensa_operand_set_field (isa, new_op, 0, fmt, 0,
2404                                            sbuff, dest_reg + 2) != 0
2405               || xtensa_operand_set_field (isa, new_op, 1, fmt, 0,
2406                                            sbuff, dest_reg + 2) != 0
2407               || xtensa_operand_set_field (isa, new_op, 2, fmt, 0,
2408                                            sbuff, src_reg) != 0)
2409             {
2410               *error_message = "cannot encode ADD for TLS access";
2411               return FALSE;
2412             }
2413           break;
2414         }
2415     }
2416
2417   xtensa_format_set_slot (isa, fmt, 0, ibuff, sbuff);
2418   xtensa_insnbuf_to_chars (isa, ibuff, contents + rel->r_offset,
2419                            input_size - rel->r_offset);
2420
2421   return TRUE;
2422 }
2423
2424
2425 #define IS_XTENSA_TLS_RELOC(R_TYPE) \
2426   ((R_TYPE) == R_XTENSA_TLSDESC_FN \
2427    || (R_TYPE) == R_XTENSA_TLSDESC_ARG \
2428    || (R_TYPE) == R_XTENSA_TLS_DTPOFF \
2429    || (R_TYPE) == R_XTENSA_TLS_TPOFF \
2430    || (R_TYPE) == R_XTENSA_TLS_FUNC \
2431    || (R_TYPE) == R_XTENSA_TLS_ARG \
2432    || (R_TYPE) == R_XTENSA_TLS_CALL)
2433
2434 /* Relocate an Xtensa ELF section.  This is invoked by the linker for
2435    both relocatable and final links.  */
2436
2437 static bfd_boolean
2438 elf_xtensa_relocate_section (bfd *output_bfd,
2439                              struct bfd_link_info *info,
2440                              bfd *input_bfd,
2441                              asection *input_section,
2442                              bfd_byte *contents,
2443                              Elf_Internal_Rela *relocs,
2444                              Elf_Internal_Sym *local_syms,
2445                              asection **local_sections)
2446 {
2447   struct elf_xtensa_link_hash_table *htab;
2448   Elf_Internal_Shdr *symtab_hdr;
2449   Elf_Internal_Rela *rel;
2450   Elf_Internal_Rela *relend;
2451   struct elf_link_hash_entry **sym_hashes;
2452   property_table_entry *lit_table = 0;
2453   int ltblsize = 0;
2454   char *local_got_tls_types;
2455   char *error_message = NULL;
2456   bfd_size_type input_size;
2457   int tls_type;
2458
2459   if (!xtensa_default_isa)
2460     xtensa_default_isa = xtensa_isa_init (0, 0);
2461
2462   if (!is_xtensa_elf (input_bfd))
2463     {
2464       bfd_set_error (bfd_error_wrong_format);
2465       return FALSE;
2466     }
2467
2468   htab = elf_xtensa_hash_table (info);
2469   if (htab == NULL)
2470     return FALSE;
2471
2472   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
2473   sym_hashes = elf_sym_hashes (input_bfd);
2474   local_got_tls_types = elf_xtensa_local_got_tls_type (input_bfd);
2475
2476   if (elf_hash_table (info)->dynamic_sections_created)
2477     {
2478       ltblsize = xtensa_read_table_entries (input_bfd, input_section,
2479                                             &lit_table, XTENSA_LIT_SEC_NAME,
2480                                             TRUE);
2481       if (ltblsize < 0)
2482         return FALSE;
2483     }
2484
2485   input_size = bfd_get_section_limit (input_bfd, input_section);
2486
2487   rel = relocs;
2488   relend = relocs + input_section->reloc_count;
2489   for (; rel < relend; rel++)
2490     {
2491       int r_type;
2492       reloc_howto_type *howto;
2493       unsigned long r_symndx;
2494       struct elf_link_hash_entry *h;
2495       Elf_Internal_Sym *sym;
2496       char sym_type;
2497       const char *name;
2498       asection *sec;
2499       bfd_vma relocation;
2500       bfd_reloc_status_type r;
2501       bfd_boolean is_weak_undef;
2502       bfd_boolean unresolved_reloc;
2503       bfd_boolean warned;
2504       bfd_boolean dynamic_symbol;
2505
2506       r_type = ELF32_R_TYPE (rel->r_info);
2507       if (r_type == (int) R_XTENSA_GNU_VTINHERIT
2508           || r_type == (int) R_XTENSA_GNU_VTENTRY)
2509         continue;
2510
2511       if (r_type < 0 || r_type >= (int) R_XTENSA_max)
2512         {
2513           bfd_set_error (bfd_error_bad_value);
2514           return FALSE;
2515         }
2516       howto = &elf_howto_table[r_type];
2517
2518       r_symndx = ELF32_R_SYM (rel->r_info);
2519
2520       h = NULL;
2521       sym = NULL;
2522       sec = NULL;
2523       is_weak_undef = FALSE;
2524       unresolved_reloc = FALSE;
2525       warned = FALSE;
2526
2527       if (howto->partial_inplace && !bfd_link_relocatable (info))
2528         {
2529           /* Because R_XTENSA_32 was made partial_inplace to fix some
2530              problems with DWARF info in partial links, there may be
2531              an addend stored in the contents.  Take it out of there
2532              and move it back into the addend field of the reloc.  */
2533           rel->r_addend += bfd_get_32 (input_bfd, contents + rel->r_offset);
2534           bfd_put_32 (input_bfd, 0, contents + rel->r_offset);
2535         }
2536
2537       if (r_symndx < symtab_hdr->sh_info)
2538         {
2539           sym = local_syms + r_symndx;
2540           sym_type = ELF32_ST_TYPE (sym->st_info);
2541           sec = local_sections[r_symndx];
2542           relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
2543         }
2544       else
2545         {
2546           bfd_boolean ignored;
2547
2548           RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
2549                                    r_symndx, symtab_hdr, sym_hashes,
2550                                    h, sec, relocation,
2551                                    unresolved_reloc, warned, ignored);
2552
2553           if (relocation == 0
2554               && !unresolved_reloc
2555               && h->root.type == bfd_link_hash_undefweak)
2556             is_weak_undef = TRUE;
2557
2558           sym_type = h->type;
2559         }
2560
2561       if (sec != NULL && discarded_section (sec))
2562         RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
2563                                          rel, 1, relend, howto, 0, contents);
2564
2565       if (bfd_link_relocatable (info))
2566         {
2567           bfd_vma dest_addr;
2568           asection * sym_sec = get_elf_r_symndx_section (input_bfd, r_symndx);
2569
2570           /* This is a relocatable link.
2571              1) If the reloc is against a section symbol, adjust
2572              according to the output section.
2573              2) If there is a new target for this relocation,
2574              the new target will be in the same output section.
2575              We adjust the relocation by the output section
2576              difference.  */
2577
2578           if (relaxing_section)
2579             {
2580               /* Check if this references a section in another input file.  */
2581               if (!do_fix_for_relocatable_link (rel, input_bfd, input_section,
2582                                                 contents))
2583                 return FALSE;
2584             }
2585
2586           dest_addr = sym_sec->output_section->vma + sym_sec->output_offset
2587             + get_elf_r_symndx_offset (input_bfd, r_symndx) + rel->r_addend;
2588
2589           if (r_type == R_XTENSA_ASM_SIMPLIFY)
2590             {
2591               error_message = NULL;
2592               /* Convert ASM_SIMPLIFY into the simpler relocation
2593                  so that they never escape a relaxing link.  */
2594               r = contract_asm_expansion (contents, input_size, rel,
2595                                           &error_message);
2596               if (r != bfd_reloc_ok)
2597                 (*info->callbacks->reloc_dangerous)
2598                   (info, error_message,
2599                    input_bfd, input_section, rel->r_offset);
2600
2601               r_type = ELF32_R_TYPE (rel->r_info);
2602             }
2603
2604           /* This is a relocatable link, so we don't have to change
2605              anything unless the reloc is against a section symbol,
2606              in which case we have to adjust according to where the
2607              section symbol winds up in the output section.  */
2608           if (r_symndx < symtab_hdr->sh_info)
2609             {
2610               sym = local_syms + r_symndx;
2611               if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
2612                 {
2613                   sec = local_sections[r_symndx];
2614                   rel->r_addend += sec->output_offset + sym->st_value;
2615                 }
2616             }
2617
2618           /* If there is an addend with a partial_inplace howto,
2619              then move the addend to the contents.  This is a hack
2620              to work around problems with DWARF in relocatable links
2621              with some previous version of BFD.  Now we can't easily get
2622              rid of the hack without breaking backward compatibility.... */
2623           r = bfd_reloc_ok;
2624           howto = &elf_howto_table[r_type];
2625           if (howto->partial_inplace && rel->r_addend)
2626             {
2627               r = elf_xtensa_do_reloc (howto, input_bfd, input_section,
2628                                        rel->r_addend, contents,
2629                                        rel->r_offset, FALSE,
2630                                        &error_message);
2631               rel->r_addend = 0;
2632             }
2633           else
2634             {
2635               /* Put the correct bits in the target instruction, even
2636                  though the relocation will still be present in the output
2637                  file.  This makes disassembly clearer, as well as
2638                  allowing loadable kernel modules to work without needing
2639                  relocations on anything other than calls and l32r's.  */
2640
2641               /* If it is not in the same section, there is nothing we can do.  */
2642               if (r_type >= R_XTENSA_SLOT0_OP && r_type <= R_XTENSA_SLOT14_OP &&
2643                   sym_sec->output_section == input_section->output_section)
2644                 {
2645                   r = elf_xtensa_do_reloc (howto, input_bfd, input_section,
2646                                            dest_addr, contents,
2647                                            rel->r_offset, FALSE,
2648                                            &error_message);
2649                 }
2650             }
2651           if (r != bfd_reloc_ok)
2652             (*info->callbacks->reloc_dangerous)
2653               (info, error_message,
2654                input_bfd, input_section, rel->r_offset);
2655
2656           /* Done with work for relocatable link; continue with next reloc.  */
2657           continue;
2658         }
2659
2660       /* This is a final link.  */
2661
2662       if (relaxing_section)
2663         {
2664           /* Check if this references a section in another input file.  */
2665           do_fix_for_final_link (rel, input_bfd, input_section, contents,
2666                                  &relocation);
2667         }
2668
2669       /* Sanity check the address.  */
2670       if (rel->r_offset >= input_size
2671           && ELF32_R_TYPE (rel->r_info) != R_XTENSA_NONE)
2672         {
2673           _bfd_error_handler
2674             /* xgettext:c-format */
2675             (_("%pB(%pA+%#" PRIx64 "): "
2676                "relocation offset out of range (size=%#" PRIx64 ")"),
2677              input_bfd, input_section, (uint64_t) rel->r_offset,
2678              (uint64_t) input_size);
2679           bfd_set_error (bfd_error_bad_value);
2680           return FALSE;
2681         }
2682
2683       if (h != NULL)
2684         name = h->root.root.string;
2685       else
2686         {
2687           name = (bfd_elf_string_from_elf_section
2688                   (input_bfd, symtab_hdr->sh_link, sym->st_name));
2689           if (name == NULL || *name == '\0')
2690             name = bfd_section_name (input_bfd, sec);
2691         }
2692
2693       if (r_symndx != STN_UNDEF
2694           && r_type != R_XTENSA_NONE
2695           && (h == NULL
2696               || h->root.type == bfd_link_hash_defined
2697               || h->root.type == bfd_link_hash_defweak)
2698           && IS_XTENSA_TLS_RELOC (r_type) != (sym_type == STT_TLS))
2699         {
2700           _bfd_error_handler
2701             ((sym_type == STT_TLS
2702               /* xgettext:c-format */
2703               ? _("%pB(%pA+%#" PRIx64 "): %s used with TLS symbol %s")
2704               /* xgettext:c-format */
2705               : _("%pB(%pA+%#" PRIx64 "): %s used with non-TLS symbol %s")),
2706              input_bfd,
2707              input_section,
2708              (uint64_t) rel->r_offset,
2709              howto->name,
2710              name);
2711         }
2712
2713       dynamic_symbol = elf_xtensa_dynamic_symbol_p (h, info);
2714
2715       tls_type = GOT_UNKNOWN;
2716       if (h)
2717         tls_type = elf_xtensa_hash_entry (h)->tls_type;
2718       else if (local_got_tls_types)
2719         tls_type = local_got_tls_types [r_symndx];
2720
2721       switch (r_type)
2722         {
2723         case R_XTENSA_32:
2724         case R_XTENSA_PLT:
2725           if (elf_hash_table (info)->dynamic_sections_created
2726               && (input_section->flags & SEC_ALLOC) != 0
2727               && (dynamic_symbol || bfd_link_pic (info)))
2728             {
2729               Elf_Internal_Rela outrel;
2730               bfd_byte *loc;
2731               asection *srel;
2732
2733               if (dynamic_symbol && r_type == R_XTENSA_PLT)
2734                 srel = htab->elf.srelplt;
2735               else
2736                 srel = htab->elf.srelgot;
2737
2738               BFD_ASSERT (srel != NULL);
2739
2740               outrel.r_offset =
2741                 _bfd_elf_section_offset (output_bfd, info,
2742                                          input_section, rel->r_offset);
2743
2744               if ((outrel.r_offset | 1) == (bfd_vma) -1)
2745                 memset (&outrel, 0, sizeof outrel);
2746               else
2747                 {
2748                   outrel.r_offset += (input_section->output_section->vma
2749                                       + input_section->output_offset);
2750
2751                   /* Complain if the relocation is in a read-only section
2752                      and not in a literal pool.  */
2753                   if ((input_section->flags & SEC_READONLY) != 0
2754                       && !elf_xtensa_in_literal_pool (lit_table, ltblsize,
2755                                                       outrel.r_offset))
2756                     {
2757                       error_message =
2758                         _("dynamic relocation in read-only section");
2759                       (*info->callbacks->reloc_dangerous)
2760                         (info, error_message,
2761                          input_bfd, input_section, rel->r_offset);
2762                     }
2763
2764                   if (dynamic_symbol)
2765                     {
2766                       outrel.r_addend = rel->r_addend;
2767                       rel->r_addend = 0;
2768
2769                       if (r_type == R_XTENSA_32)
2770                         {
2771                           outrel.r_info =
2772                             ELF32_R_INFO (h->dynindx, R_XTENSA_GLOB_DAT);
2773                           relocation = 0;
2774                         }
2775                       else /* r_type == R_XTENSA_PLT */
2776                         {
2777                           outrel.r_info =
2778                             ELF32_R_INFO (h->dynindx, R_XTENSA_JMP_SLOT);
2779
2780                           /* Create the PLT entry and set the initial
2781                              contents of the literal entry to the address of
2782                              the PLT entry.  */
2783                           relocation =
2784                             elf_xtensa_create_plt_entry (info, output_bfd,
2785                                                          srel->reloc_count);
2786                         }
2787                       unresolved_reloc = FALSE;
2788                     }
2789                   else if (!is_weak_undef)
2790                     {
2791                       /* Generate a RELATIVE relocation.  */
2792                       outrel.r_info = ELF32_R_INFO (0, R_XTENSA_RELATIVE);
2793                       outrel.r_addend = 0;
2794                     }
2795                   else
2796                     {
2797                       continue;
2798                     }
2799                 }
2800
2801               loc = (srel->contents
2802                      + srel->reloc_count++ * sizeof (Elf32_External_Rela));
2803               bfd_elf32_swap_reloca_out (output_bfd, &outrel, loc);
2804               BFD_ASSERT (sizeof (Elf32_External_Rela) * srel->reloc_count
2805                           <= srel->size);
2806             }
2807           else if (r_type == R_XTENSA_ASM_EXPAND && dynamic_symbol)
2808             {
2809               /* This should only happen for non-PIC code, which is not
2810                  supposed to be used on systems with dynamic linking.
2811                  Just ignore these relocations.  */
2812               continue;
2813             }
2814           break;
2815
2816         case R_XTENSA_TLS_TPOFF:
2817           /* Switch to LE model for local symbols in an executable.  */
2818           if (! bfd_link_pic (info) && ! dynamic_symbol)
2819             {
2820               relocation = tpoff (info, relocation);
2821               break;
2822             }
2823           /* fall through */
2824
2825         case R_XTENSA_TLSDESC_FN:
2826         case R_XTENSA_TLSDESC_ARG:
2827           {
2828             if (r_type == R_XTENSA_TLSDESC_FN)
2829               {
2830                 if (! bfd_link_pic (info) || (tls_type & GOT_TLS_IE) != 0)
2831                   r_type = R_XTENSA_NONE;
2832               }
2833             else if (r_type == R_XTENSA_TLSDESC_ARG)
2834               {
2835                 if (bfd_link_pic (info))
2836                   {
2837                     if ((tls_type & GOT_TLS_IE) != 0)
2838                       r_type = R_XTENSA_TLS_TPOFF;
2839                   }
2840                 else
2841                   {
2842                     r_type = R_XTENSA_TLS_TPOFF;
2843                     if (! dynamic_symbol)
2844                       {
2845                         relocation = tpoff (info, relocation);
2846                         break;
2847                       }
2848                   }
2849               }
2850
2851             if (r_type == R_XTENSA_NONE)
2852               /* Nothing to do here; skip to the next reloc.  */
2853               continue;
2854
2855             if (! elf_hash_table (info)->dynamic_sections_created)
2856               {
2857                 error_message =
2858                   _("TLS relocation invalid without dynamic sections");
2859                 (*info->callbacks->reloc_dangerous)
2860                   (info, error_message,
2861                    input_bfd, input_section, rel->r_offset);
2862               }
2863             else
2864               {
2865                 Elf_Internal_Rela outrel;
2866                 bfd_byte *loc;
2867                 asection *srel = htab->elf.srelgot;
2868                 int indx;
2869
2870                 outrel.r_offset = (input_section->output_section->vma
2871                                    + input_section->output_offset
2872                                    + rel->r_offset);
2873
2874                 /* Complain if the relocation is in a read-only section
2875                    and not in a literal pool.  */
2876                 if ((input_section->flags & SEC_READONLY) != 0
2877                     && ! elf_xtensa_in_literal_pool (lit_table, ltblsize,
2878                                                      outrel.r_offset))
2879                   {
2880                     error_message =
2881                       _("dynamic relocation in read-only section");
2882                     (*info->callbacks->reloc_dangerous)
2883                       (info, error_message,
2884                        input_bfd, input_section, rel->r_offset);
2885                   }
2886
2887                 indx = h && h->dynindx != -1 ? h->dynindx : 0;
2888                 if (indx == 0)
2889                   outrel.r_addend = relocation - dtpoff_base (info);
2890                 else
2891                   outrel.r_addend = 0;
2892                 rel->r_addend = 0;
2893
2894                 outrel.r_info = ELF32_R_INFO (indx, r_type);
2895                 relocation = 0;
2896                 unresolved_reloc = FALSE;
2897
2898                 BFD_ASSERT (srel);
2899                 loc = (srel->contents
2900                        + srel->reloc_count++ * sizeof (Elf32_External_Rela));
2901                 bfd_elf32_swap_reloca_out (output_bfd, &outrel, loc);
2902                 BFD_ASSERT (sizeof (Elf32_External_Rela) * srel->reloc_count
2903                             <= srel->size);
2904               }
2905           }
2906           break;
2907
2908         case R_XTENSA_TLS_DTPOFF:
2909           if (! bfd_link_pic (info))
2910             /* Switch from LD model to LE model.  */
2911             relocation = tpoff (info, relocation);
2912           else
2913             relocation -= dtpoff_base (info);
2914           break;
2915
2916         case R_XTENSA_TLS_FUNC:
2917         case R_XTENSA_TLS_ARG:
2918         case R_XTENSA_TLS_CALL:
2919           /* Check if optimizing to IE or LE model.  */
2920           if ((tls_type & GOT_TLS_IE) != 0)
2921             {
2922               bfd_boolean is_ld_model =
2923                 (h && elf_xtensa_hash_entry (h) == htab->tlsbase);
2924               if (! replace_tls_insn (rel, input_bfd, input_section, contents,
2925                                       is_ld_model, &error_message))
2926                 (*info->callbacks->reloc_dangerous)
2927                   (info, error_message,
2928                    input_bfd, input_section, rel->r_offset);
2929
2930               if (r_type != R_XTENSA_TLS_ARG || is_ld_model)
2931                 {
2932                   /* Skip subsequent relocations on the same instruction.  */
2933                   while (rel + 1 < relend && rel[1].r_offset == rel->r_offset)
2934                     rel++;
2935                 }
2936             }
2937           continue;
2938
2939         default:
2940           if (elf_hash_table (info)->dynamic_sections_created
2941               && dynamic_symbol && (is_operand_relocation (r_type)
2942                                     || r_type == R_XTENSA_32_PCREL))
2943             {
2944               error_message =
2945                 vsprint_msg ("invalid relocation for dynamic symbol", ": %s",
2946                              strlen (name) + 2, name);
2947               (*info->callbacks->reloc_dangerous)
2948                 (info, error_message, input_bfd, input_section, rel->r_offset);
2949               continue;
2950             }
2951           break;
2952         }
2953
2954       /* Dynamic relocs are not propagated for SEC_DEBUGGING sections
2955          because such sections are not SEC_ALLOC and thus ld.so will
2956          not process them.  */
2957       if (unresolved_reloc
2958           && !((input_section->flags & SEC_DEBUGGING) != 0
2959                && h->def_dynamic)
2960           && _bfd_elf_section_offset (output_bfd, info, input_section,
2961                                       rel->r_offset) != (bfd_vma) -1)
2962         {
2963           _bfd_error_handler
2964             /* xgettext:c-format */
2965             (_("%pB(%pA+%#" PRIx64 "): "
2966                "unresolvable %s relocation against symbol `%s'"),
2967              input_bfd,
2968              input_section,
2969              (uint64_t) rel->r_offset,
2970              howto->name,
2971              name);
2972           return FALSE;
2973         }
2974
2975       /* TLS optimizations may have changed r_type; update "howto".  */
2976       howto = &elf_howto_table[r_type];
2977
2978       /* There's no point in calling bfd_perform_relocation here.
2979          Just go directly to our "special function".  */
2980       r = elf_xtensa_do_reloc (howto, input_bfd, input_section,
2981                                relocation + rel->r_addend,
2982                                contents, rel->r_offset, is_weak_undef,
2983                                &error_message);
2984
2985       if (r != bfd_reloc_ok && !warned)
2986         {
2987           BFD_ASSERT (r == bfd_reloc_dangerous || r == bfd_reloc_other);
2988           BFD_ASSERT (error_message != NULL);
2989
2990           if (rel->r_addend == 0)
2991             error_message = vsprint_msg (error_message, ": %s",
2992                                          strlen (name) + 2, name);
2993           else
2994             error_message = vsprint_msg (error_message, ": (%s+0x%x)",
2995                                          strlen (name) + 22,
2996                                          name, (int) rel->r_addend);
2997
2998           (*info->callbacks->reloc_dangerous)
2999             (info, error_message, input_bfd, input_section, rel->r_offset);
3000         }
3001     }
3002
3003   if (lit_table)
3004     free (lit_table);
3005
3006   input_section->reloc_done = TRUE;
3007
3008   return TRUE;
3009 }
3010
3011
3012 /* Finish up dynamic symbol handling.  There's not much to do here since
3013    the PLT and GOT entries are all set up by relocate_section.  */
3014
3015 static bfd_boolean
3016 elf_xtensa_finish_dynamic_symbol (bfd *output_bfd ATTRIBUTE_UNUSED,
3017                                   struct bfd_link_info *info ATTRIBUTE_UNUSED,
3018                                   struct elf_link_hash_entry *h,
3019                                   Elf_Internal_Sym *sym)
3020 {
3021   if (h->needs_plt && !h->def_regular)
3022     {
3023       /* Mark the symbol as undefined, rather than as defined in
3024          the .plt section.  Leave the value alone.  */
3025       sym->st_shndx = SHN_UNDEF;
3026       /* If the symbol is weak, we do need to clear the value.
3027          Otherwise, the PLT entry would provide a definition for
3028          the symbol even if the symbol wasn't defined anywhere,
3029          and so the symbol would never be NULL.  */
3030       if (!h->ref_regular_nonweak)
3031         sym->st_value = 0;
3032     }
3033
3034   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
3035   if (h == elf_hash_table (info)->hdynamic
3036       || h == elf_hash_table (info)->hgot)
3037     sym->st_shndx = SHN_ABS;
3038
3039   return TRUE;
3040 }
3041
3042
3043 /* Combine adjacent literal table entries in the output.  Adjacent
3044    entries within each input section may have been removed during
3045    relaxation, but we repeat the process here, even though it's too late
3046    to shrink the output section, because it's important to minimize the
3047    number of literal table entries to reduce the start-up work for the
3048    runtime linker.  Returns the number of remaining table entries or -1
3049    on error.  */
3050
3051 static int
3052 elf_xtensa_combine_prop_entries (bfd *output_bfd,
3053                                  asection *sxtlit,
3054                                  asection *sgotloc)
3055 {
3056   bfd_byte *contents;
3057   property_table_entry *table;
3058   bfd_size_type section_size, sgotloc_size;
3059   bfd_vma offset;
3060   int n, m, num;
3061
3062   section_size = sxtlit->size;
3063   BFD_ASSERT (section_size % 8 == 0);
3064   num = section_size / 8;
3065
3066   sgotloc_size = sgotloc->size;
3067   if (sgotloc_size != section_size)
3068     {
3069       _bfd_error_handler
3070         (_("internal inconsistency in size of .got.loc section"));
3071       return -1;
3072     }
3073
3074   table = bfd_malloc (num * sizeof (property_table_entry));
3075   if (table == 0)
3076     return -1;
3077
3078   /* The ".xt.lit.plt" section has the SEC_IN_MEMORY flag set and this
3079      propagates to the output section, where it doesn't really apply and
3080      where it breaks the following call to bfd_malloc_and_get_section.  */
3081   sxtlit->flags &= ~SEC_IN_MEMORY;
3082
3083   if (!bfd_malloc_and_get_section (output_bfd, sxtlit, &contents))
3084     {
3085       if (contents != 0)
3086         free (contents);
3087       free (table);
3088       return -1;
3089     }
3090
3091   /* There should never be any relocations left at this point, so this
3092      is quite a bit easier than what is done during relaxation.  */
3093
3094   /* Copy the raw contents into a property table array and sort it.  */
3095   offset = 0;
3096   for (n = 0; n < num; n++)
3097     {
3098       table[n].address = bfd_get_32 (output_bfd, &contents[offset]);
3099       table[n].size = bfd_get_32 (output_bfd, &contents[offset + 4]);
3100       offset += 8;
3101     }
3102   qsort (table, num, sizeof (property_table_entry), property_table_compare);
3103
3104   for (n = 0; n < num; n++)
3105     {
3106       bfd_boolean remove_entry = FALSE;
3107
3108       if (table[n].size == 0)
3109         remove_entry = TRUE;
3110       else if (n > 0
3111                && (table[n-1].address + table[n-1].size == table[n].address))
3112         {
3113           table[n-1].size += table[n].size;
3114           remove_entry = TRUE;
3115         }
3116
3117       if (remove_entry)
3118         {
3119           for (m = n; m < num - 1; m++)
3120             {
3121               table[m].address = table[m+1].address;
3122               table[m].size = table[m+1].size;
3123             }
3124
3125           n--;
3126           num--;
3127         }
3128     }
3129
3130   /* Copy the data back to the raw contents.  */
3131   offset = 0;
3132   for (n = 0; n < num; n++)
3133     {
3134       bfd_put_32 (output_bfd, table[n].address, &contents[offset]);
3135       bfd_put_32 (output_bfd, table[n].size, &contents[offset + 4]);
3136       offset += 8;
3137     }
3138
3139   /* Clear the removed bytes.  */
3140   if ((bfd_size_type) (num * 8) < section_size)
3141     memset (&contents[num * 8], 0, section_size - num * 8);
3142
3143   if (! bfd_set_section_contents (output_bfd, sxtlit, contents, 0,
3144                                   section_size))
3145     return -1;
3146
3147   /* Copy the contents to ".got.loc".  */
3148   memcpy (sgotloc->contents, contents, section_size);
3149
3150   free (contents);
3151   free (table);
3152   return num;
3153 }
3154
3155
3156 /* Finish up the dynamic sections.  */
3157
3158 static bfd_boolean
3159 elf_xtensa_finish_dynamic_sections (bfd *output_bfd,
3160                                     struct bfd_link_info *info)
3161 {
3162   struct elf_xtensa_link_hash_table *htab;
3163   bfd *dynobj;
3164   asection *sdyn, *srelplt, *srelgot, *sgot, *sxtlit, *sgotloc;
3165   Elf32_External_Dyn *dyncon, *dynconend;
3166   int num_xtlit_entries = 0;
3167
3168   if (! elf_hash_table (info)->dynamic_sections_created)
3169     return TRUE;
3170
3171   htab = elf_xtensa_hash_table (info);
3172   if (htab == NULL)
3173     return FALSE;
3174
3175   dynobj = elf_hash_table (info)->dynobj;
3176   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3177   BFD_ASSERT (sdyn != NULL);
3178
3179   /* Set the first entry in the global offset table to the address of
3180      the dynamic section.  */
3181   sgot = htab->elf.sgot;
3182   if (sgot)
3183     {
3184       BFD_ASSERT (sgot->size == 4);
3185       if (sdyn == NULL)
3186         bfd_put_32 (output_bfd, 0, sgot->contents);
3187       else
3188         bfd_put_32 (output_bfd,
3189                     sdyn->output_section->vma + sdyn->output_offset,
3190                     sgot->contents);
3191     }
3192
3193   srelplt = htab->elf.srelplt;
3194   srelgot = htab->elf.srelgot;
3195   if (srelplt && srelplt->size != 0)
3196     {
3197       asection *sgotplt, *spltlittbl;
3198       int chunk, plt_chunks, plt_entries;
3199       Elf_Internal_Rela irela;
3200       bfd_byte *loc;
3201       unsigned rtld_reloc;
3202
3203       spltlittbl = htab->spltlittbl;
3204       BFD_ASSERT (srelgot != NULL && spltlittbl != NULL);
3205
3206       /* Find the first XTENSA_RTLD relocation.  Presumably the rest
3207          of them follow immediately after....  */
3208       for (rtld_reloc = 0; rtld_reloc < srelgot->reloc_count; rtld_reloc++)
3209         {
3210           loc = srelgot->contents + rtld_reloc * sizeof (Elf32_External_Rela);
3211           bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
3212           if (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD)
3213             break;
3214         }
3215       BFD_ASSERT (rtld_reloc < srelgot->reloc_count);
3216
3217       plt_entries = srelplt->size / sizeof (Elf32_External_Rela);
3218       plt_chunks =
3219         (plt_entries + PLT_ENTRIES_PER_CHUNK - 1) / PLT_ENTRIES_PER_CHUNK;
3220
3221       for (chunk = 0; chunk < plt_chunks; chunk++)
3222         {
3223           int chunk_entries = 0;
3224
3225           sgotplt = elf_xtensa_get_gotplt_section (info, chunk);
3226           BFD_ASSERT (sgotplt != NULL);
3227
3228           /* Emit special RTLD relocations for the first two entries in
3229              each chunk of the .got.plt section.  */
3230
3231           loc = srelgot->contents + rtld_reloc * sizeof (Elf32_External_Rela);
3232           bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
3233           BFD_ASSERT (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD);
3234           irela.r_offset = (sgotplt->output_section->vma
3235                             + sgotplt->output_offset);
3236           irela.r_addend = 1; /* tell rtld to set value to resolver function */
3237           bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
3238           rtld_reloc += 1;
3239           BFD_ASSERT (rtld_reloc <= srelgot->reloc_count);
3240
3241           /* Next literal immediately follows the first.  */
3242           loc += sizeof (Elf32_External_Rela);
3243           bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
3244           BFD_ASSERT (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD);
3245           irela.r_offset = (sgotplt->output_section->vma
3246                             + sgotplt->output_offset + 4);
3247           /* Tell rtld to set value to object's link map.  */
3248           irela.r_addend = 2;
3249           bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
3250           rtld_reloc += 1;
3251           BFD_ASSERT (rtld_reloc <= srelgot->reloc_count);
3252
3253           /* Fill in the literal table.  */
3254           if (chunk < plt_chunks - 1)
3255             chunk_entries = PLT_ENTRIES_PER_CHUNK;
3256           else
3257             chunk_entries = plt_entries - (chunk * PLT_ENTRIES_PER_CHUNK);
3258
3259           BFD_ASSERT ((unsigned) (chunk + 1) * 8 <= spltlittbl->size);
3260           bfd_put_32 (output_bfd,
3261                       sgotplt->output_section->vma + sgotplt->output_offset,
3262                       spltlittbl->contents + (chunk * 8) + 0);
3263           bfd_put_32 (output_bfd,
3264                       8 + (chunk_entries * 4),
3265                       spltlittbl->contents + (chunk * 8) + 4);
3266         }
3267
3268      /* The .xt.lit.plt section has just been modified.  This must
3269         happen before the code below which combines adjacent literal
3270         table entries, and the .xt.lit.plt contents have to be forced to
3271         the output here.  */
3272       if (! bfd_set_section_contents (output_bfd,
3273                                       spltlittbl->output_section,
3274                                       spltlittbl->contents,
3275                                       spltlittbl->output_offset,
3276                                       spltlittbl->size))
3277         return FALSE;
3278       /* Clear SEC_HAS_CONTENTS so the contents won't be output again.  */
3279       spltlittbl->flags &= ~SEC_HAS_CONTENTS;
3280     }
3281
3282   /* All the dynamic relocations have been emitted at this point.
3283      Make sure the relocation sections are the correct size.  */
3284   if ((srelgot && srelgot->size != (sizeof (Elf32_External_Rela)
3285                                     * srelgot->reloc_count))
3286       || (srelplt && srelplt->size != (sizeof (Elf32_External_Rela)
3287                                        * srelplt->reloc_count)))
3288     abort ();
3289
3290   /* Combine adjacent literal table entries.  */
3291   BFD_ASSERT (! bfd_link_relocatable (info));
3292   sxtlit = bfd_get_section_by_name (output_bfd, ".xt.lit");
3293   sgotloc = htab->sgotloc;
3294   BFD_ASSERT (sgotloc);
3295   if (sxtlit)
3296     {
3297       num_xtlit_entries =
3298         elf_xtensa_combine_prop_entries (output_bfd, sxtlit, sgotloc);
3299       if (num_xtlit_entries < 0)
3300         return FALSE;
3301     }
3302
3303   dyncon = (Elf32_External_Dyn *) sdyn->contents;
3304   dynconend = (Elf32_External_Dyn *) (sdyn->contents + sdyn->size);
3305   for (; dyncon < dynconend; dyncon++)
3306     {
3307       Elf_Internal_Dyn dyn;
3308
3309       bfd_elf32_swap_dyn_in (dynobj, dyncon, &dyn);
3310
3311       switch (dyn.d_tag)
3312         {
3313         default:
3314           break;
3315
3316         case DT_XTENSA_GOT_LOC_SZ:
3317           dyn.d_un.d_val = num_xtlit_entries;
3318           break;
3319
3320         case DT_XTENSA_GOT_LOC_OFF:
3321           dyn.d_un.d_ptr = (htab->sgotloc->output_section->vma
3322                             + htab->sgotloc->output_offset);
3323           break;
3324
3325         case DT_PLTGOT:
3326           dyn.d_un.d_ptr = (htab->elf.sgot->output_section->vma
3327                             + htab->elf.sgot->output_offset);
3328           break;
3329
3330         case DT_JMPREL:
3331           dyn.d_un.d_ptr = (htab->elf.srelplt->output_section->vma
3332                             + htab->elf.srelplt->output_offset);
3333           break;
3334
3335         case DT_PLTRELSZ:
3336           dyn.d_un.d_val = htab->elf.srelplt->size;
3337           break;
3338         }
3339
3340       bfd_elf32_swap_dyn_out (output_bfd, &dyn, dyncon);
3341     }
3342
3343   return TRUE;
3344 }
3345
3346 \f
3347 /* Functions for dealing with the e_flags field.  */
3348
3349 /* Merge backend specific data from an object file to the output
3350    object file when linking.  */
3351
3352 static bfd_boolean
3353 elf_xtensa_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info)
3354 {
3355   bfd *obfd = info->output_bfd;
3356   unsigned out_mach, in_mach;
3357   flagword out_flag, in_flag;
3358
3359   /* Check if we have the same endianness.  */
3360   if (!_bfd_generic_verify_endian_match (ibfd, info))
3361     return FALSE;
3362
3363   /* Don't even pretend to support mixed-format linking.  */
3364   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
3365       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
3366     return FALSE;
3367
3368   out_flag = elf_elfheader (obfd)->e_flags;
3369   in_flag = elf_elfheader (ibfd)->e_flags;
3370
3371   out_mach = out_flag & EF_XTENSA_MACH;
3372   in_mach = in_flag & EF_XTENSA_MACH;
3373   if (out_mach != in_mach)
3374     {
3375       _bfd_error_handler
3376         /* xgettext:c-format */
3377         (_("%pB: incompatible machine type; output is 0x%x; input is 0x%x"),
3378          ibfd, out_mach, in_mach);
3379       bfd_set_error (bfd_error_wrong_format);
3380       return FALSE;
3381     }
3382
3383   if (! elf_flags_init (obfd))
3384     {
3385       elf_flags_init (obfd) = TRUE;
3386       elf_elfheader (obfd)->e_flags = in_flag;
3387
3388       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
3389           && bfd_get_arch_info (obfd)->the_default)
3390         return bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
3391                                   bfd_get_mach (ibfd));
3392
3393       return TRUE;
3394     }
3395
3396   if ((out_flag & EF_XTENSA_XT_INSN) != (in_flag & EF_XTENSA_XT_INSN))
3397     elf_elfheader (obfd)->e_flags &= (~ EF_XTENSA_XT_INSN);
3398
3399   if ((out_flag & EF_XTENSA_XT_LIT) != (in_flag & EF_XTENSA_XT_LIT))
3400     elf_elfheader (obfd)->e_flags &= (~ EF_XTENSA_XT_LIT);
3401
3402   return TRUE;
3403 }
3404
3405
3406 static bfd_boolean
3407 elf_xtensa_set_private_flags (bfd *abfd, flagword flags)
3408 {
3409   BFD_ASSERT (!elf_flags_init (abfd)
3410               || elf_elfheader (abfd)->e_flags == flags);
3411
3412   elf_elfheader (abfd)->e_flags |= flags;
3413   elf_flags_init (abfd) = TRUE;
3414
3415   return TRUE;
3416 }
3417
3418
3419 static bfd_boolean
3420 elf_xtensa_print_private_bfd_data (bfd *abfd, void *farg)
3421 {
3422   FILE *f = (FILE *) farg;
3423   flagword e_flags = elf_elfheader (abfd)->e_flags;
3424
3425   fprintf (f, "\nXtensa header:\n");
3426   if ((e_flags & EF_XTENSA_MACH) == E_XTENSA_MACH)
3427     fprintf (f, "\nMachine     = Base\n");
3428   else
3429     fprintf (f, "\nMachine Id  = 0x%x\n", e_flags & EF_XTENSA_MACH);
3430
3431   fprintf (f, "Insn tables = %s\n",
3432            (e_flags & EF_XTENSA_XT_INSN) ? "true" : "false");
3433
3434   fprintf (f, "Literal tables = %s\n",
3435            (e_flags & EF_XTENSA_XT_LIT) ? "true" : "false");
3436
3437   return _bfd_elf_print_private_bfd_data (abfd, farg);
3438 }
3439
3440
3441 /* Set the right machine number for an Xtensa ELF file.  */
3442
3443 static bfd_boolean
3444 elf_xtensa_object_p (bfd *abfd)
3445 {
3446   int mach;
3447   unsigned long arch = elf_elfheader (abfd)->e_flags & EF_XTENSA_MACH;
3448
3449   switch (arch)
3450     {
3451     case E_XTENSA_MACH:
3452       mach = bfd_mach_xtensa;
3453       break;
3454     default:
3455       return FALSE;
3456     }
3457
3458   (void) bfd_default_set_arch_mach (abfd, bfd_arch_xtensa, mach);
3459   return TRUE;
3460 }
3461
3462
3463 /* The final processing done just before writing out an Xtensa ELF object
3464    file.  This gets the Xtensa architecture right based on the machine
3465    number.  */
3466
3467 static bfd_boolean
3468 elf_xtensa_final_write_processing (bfd *abfd)
3469 {
3470   int mach;
3471   unsigned long val = elf_elfheader (abfd)->e_flags & EF_XTENSA_MACH;
3472
3473   switch (mach = bfd_get_mach (abfd))
3474     {
3475     case bfd_mach_xtensa:
3476       val = E_XTENSA_MACH;
3477       break;
3478     default:
3479       break;
3480     }
3481
3482   elf_elfheader (abfd)->e_flags &= ~EF_XTENSA_MACH;
3483   elf_elfheader (abfd)->e_flags |= val;
3484   return _bfd_elf_final_write_processing (abfd);
3485 }
3486
3487
3488 static enum elf_reloc_type_class
3489 elf_xtensa_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
3490                              const asection *rel_sec ATTRIBUTE_UNUSED,
3491                              const Elf_Internal_Rela *rela)
3492 {
3493   switch ((int) ELF32_R_TYPE (rela->r_info))
3494     {
3495     case R_XTENSA_RELATIVE:
3496       return reloc_class_relative;
3497     case R_XTENSA_JMP_SLOT:
3498       return reloc_class_plt;
3499     default:
3500       return reloc_class_normal;
3501     }
3502 }
3503
3504 \f
3505 static bfd_boolean
3506 elf_xtensa_discard_info_for_section (bfd *abfd,
3507                                      struct elf_reloc_cookie *cookie,
3508                                      struct bfd_link_info *info,
3509                                      asection *sec)
3510 {
3511   bfd_byte *contents;
3512   bfd_vma offset, actual_offset;
3513   bfd_size_type removed_bytes = 0;
3514   bfd_size_type entry_size;
3515
3516   if (sec->output_section
3517       && bfd_is_abs_section (sec->output_section))
3518     return FALSE;
3519
3520   if (xtensa_is_proptable_section (sec))
3521     entry_size = 12;
3522   else
3523     entry_size = 8;
3524
3525   if (sec->size == 0 || sec->size % entry_size != 0)
3526     return FALSE;
3527
3528   contents = retrieve_contents (abfd, sec, info->keep_memory);
3529   if (!contents)
3530     return FALSE;
3531
3532   cookie->rels = retrieve_internal_relocs (abfd, sec, info->keep_memory);
3533   if (!cookie->rels)
3534     {
3535       release_contents (sec, contents);
3536       return FALSE;
3537     }
3538
3539   /* Sort the relocations.  They should already be in order when
3540      relaxation is enabled, but it might not be.  */
3541   qsort (cookie->rels, sec->reloc_count, sizeof (Elf_Internal_Rela),
3542          internal_reloc_compare);
3543
3544   cookie->rel = cookie->rels;
3545   cookie->relend = cookie->rels + sec->reloc_count;
3546
3547   for (offset = 0; offset < sec->size; offset += entry_size)
3548     {
3549       actual_offset = offset - removed_bytes;
3550
3551       /* The ...symbol_deleted_p function will skip over relocs but it
3552          won't adjust their offsets, so do that here.  */
3553       while (cookie->rel < cookie->relend
3554              && cookie->rel->r_offset < offset)
3555         {
3556           cookie->rel->r_offset -= removed_bytes;
3557           cookie->rel++;
3558         }
3559
3560       while (cookie->rel < cookie->relend
3561              && cookie->rel->r_offset == offset)
3562         {
3563           if (bfd_elf_reloc_symbol_deleted_p (offset, cookie))
3564             {
3565               /* Remove the table entry.  (If the reloc type is NONE, then
3566                  the entry has already been merged with another and deleted
3567                  during relaxation.)  */
3568               if (ELF32_R_TYPE (cookie->rel->r_info) != R_XTENSA_NONE)
3569                 {
3570                   /* Shift the contents up.  */
3571                   if (offset + entry_size < sec->size)
3572                     memmove (&contents[actual_offset],
3573                              &contents[actual_offset + entry_size],
3574                              sec->size - offset - entry_size);
3575                   removed_bytes += entry_size;
3576                 }
3577
3578               /* Remove this relocation.  */
3579               cookie->rel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
3580             }
3581
3582           /* Adjust the relocation offset for previous removals.  This
3583              should not be done before calling ...symbol_deleted_p
3584              because it might mess up the offset comparisons there.
3585              Make sure the offset doesn't underflow in the case where
3586              the first entry is removed.  */
3587           if (cookie->rel->r_offset >= removed_bytes)
3588             cookie->rel->r_offset -= removed_bytes;
3589           else
3590             cookie->rel->r_offset = 0;
3591
3592           cookie->rel++;
3593         }
3594     }
3595
3596   if (removed_bytes != 0)
3597     {
3598       /* Adjust any remaining relocs (shouldn't be any).  */
3599       for (; cookie->rel < cookie->relend; cookie->rel++)
3600         {
3601           if (cookie->rel->r_offset >= removed_bytes)
3602             cookie->rel->r_offset -= removed_bytes;
3603           else
3604             cookie->rel->r_offset = 0;
3605         }
3606
3607       /* Clear the removed bytes.  */
3608       memset (&contents[sec->size - removed_bytes], 0, removed_bytes);
3609
3610       pin_contents (sec, contents);
3611       pin_internal_relocs (sec, cookie->rels);
3612
3613       /* Shrink size.  */
3614       if (sec->rawsize == 0)
3615         sec->rawsize = sec->size;
3616       sec->size -= removed_bytes;
3617
3618       if (xtensa_is_littable_section (sec))
3619         {
3620           asection *sgotloc = elf_xtensa_hash_table (info)->sgotloc;
3621           if (sgotloc)
3622             sgotloc->size -= removed_bytes;
3623         }
3624     }
3625   else
3626     {
3627       release_contents (sec, contents);
3628       release_internal_relocs (sec, cookie->rels);
3629     }
3630
3631   return (removed_bytes != 0);
3632 }
3633
3634
3635 static bfd_boolean
3636 elf_xtensa_discard_info (bfd *abfd,
3637                          struct elf_reloc_cookie *cookie,
3638                          struct bfd_link_info *info)
3639 {
3640   asection *sec;
3641   bfd_boolean changed = FALSE;
3642
3643   for (sec = abfd->sections; sec != NULL; sec = sec->next)
3644     {
3645       if (xtensa_is_property_section (sec))
3646         {
3647           if (elf_xtensa_discard_info_for_section (abfd, cookie, info, sec))
3648             changed = TRUE;
3649         }
3650     }
3651
3652   return changed;
3653 }
3654
3655
3656 static bfd_boolean
3657 elf_xtensa_ignore_discarded_relocs (asection *sec)
3658 {
3659   return xtensa_is_property_section (sec);
3660 }
3661
3662
3663 static unsigned int
3664 elf_xtensa_action_discarded (asection *sec)
3665 {
3666   if (strcmp (".xt_except_table", sec->name) == 0)
3667     return 0;
3668
3669   if (strcmp (".xt_except_desc", sec->name) == 0)
3670     return 0;
3671
3672   return _bfd_elf_default_action_discarded (sec);
3673 }
3674
3675 \f
3676 /* Support for core dump NOTE sections.  */
3677
3678 static bfd_boolean
3679 elf_xtensa_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
3680 {
3681   int offset;
3682   unsigned int size;
3683
3684   /* The size for Xtensa is variable, so don't try to recognize the format
3685      based on the size.  Just assume this is GNU/Linux.  */
3686
3687   /* pr_cursig */
3688   elf_tdata (abfd)->core->signal = bfd_get_16 (abfd, note->descdata + 12);
3689
3690   /* pr_pid */
3691   elf_tdata (abfd)->core->lwpid = bfd_get_32 (abfd, note->descdata + 24);
3692
3693   /* pr_reg */
3694   offset = 72;
3695   size = note->descsz - offset - 4;
3696
3697   /* Make a ".reg/999" section.  */
3698   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
3699                                           size, note->descpos + offset);
3700 }
3701
3702
3703 static bfd_boolean
3704 elf_xtensa_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
3705 {
3706   switch (note->descsz)
3707     {
3708       default:
3709         return FALSE;
3710
3711       case 128:         /* GNU/Linux elf_prpsinfo */
3712         elf_tdata (abfd)->core->program
3713          = _bfd_elfcore_strndup (abfd, note->descdata + 32, 16);
3714         elf_tdata (abfd)->core->command
3715          = _bfd_elfcore_strndup (abfd, note->descdata + 48, 80);
3716     }
3717
3718   /* Note that for some reason, a spurious space is tacked
3719      onto the end of the args in some (at least one anyway)
3720      implementations, so strip it off if it exists.  */
3721
3722   {
3723     char *command = elf_tdata (abfd)->core->command;
3724     int n = strlen (command);
3725
3726     if (0 < n && command[n - 1] == ' ')
3727       command[n - 1] = '\0';
3728   }
3729
3730   return TRUE;
3731 }
3732
3733 \f
3734 /* Generic Xtensa configurability stuff.  */
3735
3736 static xtensa_opcode callx0_op = XTENSA_UNDEFINED;
3737 static xtensa_opcode callx4_op = XTENSA_UNDEFINED;
3738 static xtensa_opcode callx8_op = XTENSA_UNDEFINED;
3739 static xtensa_opcode callx12_op = XTENSA_UNDEFINED;
3740 static xtensa_opcode call0_op = XTENSA_UNDEFINED;
3741 static xtensa_opcode call4_op = XTENSA_UNDEFINED;
3742 static xtensa_opcode call8_op = XTENSA_UNDEFINED;
3743 static xtensa_opcode call12_op = XTENSA_UNDEFINED;
3744
3745 static void
3746 init_call_opcodes (void)
3747 {
3748   if (callx0_op == XTENSA_UNDEFINED)
3749     {
3750       callx0_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx0");
3751       callx4_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx4");
3752       callx8_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx8");
3753       callx12_op = xtensa_opcode_lookup (xtensa_default_isa, "callx12");
3754       call0_op   = xtensa_opcode_lookup (xtensa_default_isa, "call0");
3755       call4_op   = xtensa_opcode_lookup (xtensa_default_isa, "call4");
3756       call8_op   = xtensa_opcode_lookup (xtensa_default_isa, "call8");
3757       call12_op  = xtensa_opcode_lookup (xtensa_default_isa, "call12");
3758     }
3759 }
3760
3761
3762 static bfd_boolean
3763 is_indirect_call_opcode (xtensa_opcode opcode)
3764 {
3765   init_call_opcodes ();
3766   return (opcode == callx0_op
3767           || opcode == callx4_op
3768           || opcode == callx8_op
3769           || opcode == callx12_op);
3770 }
3771
3772
3773 static bfd_boolean
3774 is_direct_call_opcode (xtensa_opcode opcode)
3775 {
3776   init_call_opcodes ();
3777   return (opcode == call0_op
3778           || opcode == call4_op
3779           || opcode == call8_op
3780           || opcode == call12_op);
3781 }
3782
3783
3784 static bfd_boolean
3785 is_windowed_call_opcode (xtensa_opcode opcode)
3786 {
3787   init_call_opcodes ();
3788   return (opcode == call4_op
3789           || opcode == call8_op
3790           || opcode == call12_op
3791           || opcode == callx4_op
3792           || opcode == callx8_op
3793           || opcode == callx12_op);
3794 }
3795
3796
3797 static bfd_boolean
3798 get_indirect_call_dest_reg (xtensa_opcode opcode, unsigned *pdst)
3799 {
3800   unsigned dst = (unsigned) -1;
3801
3802   init_call_opcodes ();
3803   if (opcode == callx0_op)
3804     dst = 0;
3805   else if (opcode == callx4_op)
3806     dst = 4;
3807   else if (opcode == callx8_op)
3808     dst = 8;
3809   else if (opcode == callx12_op)
3810     dst = 12;
3811
3812   if (dst == (unsigned) -1)
3813     return FALSE;
3814
3815   *pdst = dst;
3816   return TRUE;
3817 }
3818
3819
3820 static xtensa_opcode
3821 get_const16_opcode (void)
3822 {
3823   static bfd_boolean done_lookup = FALSE;
3824   static xtensa_opcode const16_opcode = XTENSA_UNDEFINED;
3825   if (!done_lookup)
3826     {
3827       const16_opcode = xtensa_opcode_lookup (xtensa_default_isa, "const16");
3828       done_lookup = TRUE;
3829     }
3830   return const16_opcode;
3831 }
3832
3833
3834 static xtensa_opcode
3835 get_l32r_opcode (void)
3836 {
3837   static xtensa_opcode l32r_opcode = XTENSA_UNDEFINED;
3838   static bfd_boolean done_lookup = FALSE;
3839
3840   if (!done_lookup)
3841     {
3842       l32r_opcode = xtensa_opcode_lookup (xtensa_default_isa, "l32r");
3843       done_lookup = TRUE;
3844     }
3845   return l32r_opcode;
3846 }
3847
3848
3849 static bfd_vma
3850 l32r_offset (bfd_vma addr, bfd_vma pc)
3851 {
3852   bfd_vma offset;
3853
3854   offset = addr - ((pc+3) & -4);
3855   BFD_ASSERT ((offset & ((1 << 2) - 1)) == 0);
3856   offset = (signed int) offset >> 2;
3857   BFD_ASSERT ((signed int) offset >> 16 == -1);
3858   return offset;
3859 }
3860
3861
3862 static xtensa_opcode
3863 get_rsr_lend_opcode (void)
3864 {
3865   static xtensa_opcode rsr_lend_opcode = XTENSA_UNDEFINED;
3866   static bfd_boolean done_lookup = FALSE;
3867   if (!done_lookup)
3868     {
3869       rsr_lend_opcode = xtensa_opcode_lookup (xtensa_default_isa, "rsr.lend");
3870       done_lookup = TRUE;
3871     }
3872   return rsr_lend_opcode;
3873 }
3874
3875 static xtensa_opcode
3876 get_wsr_lbeg_opcode (void)
3877 {
3878   static xtensa_opcode wsr_lbeg_opcode = XTENSA_UNDEFINED;
3879   static bfd_boolean done_lookup = FALSE;
3880   if (!done_lookup)
3881     {
3882       wsr_lbeg_opcode = xtensa_opcode_lookup (xtensa_default_isa, "wsr.lbeg");
3883       done_lookup = TRUE;
3884     }
3885   return wsr_lbeg_opcode;
3886 }
3887
3888
3889 static int
3890 get_relocation_opnd (xtensa_opcode opcode, int r_type)
3891 {
3892   xtensa_isa isa = xtensa_default_isa;
3893   int last_immed, last_opnd, opi;
3894
3895   if (opcode == XTENSA_UNDEFINED)
3896     return XTENSA_UNDEFINED;
3897
3898   /* Find the last visible PC-relative immediate operand for the opcode.
3899      If there are no PC-relative immediates, then choose the last visible
3900      immediate; otherwise, fail and return XTENSA_UNDEFINED.  */
3901   last_immed = XTENSA_UNDEFINED;
3902   last_opnd = xtensa_opcode_num_operands (isa, opcode);
3903   for (opi = last_opnd - 1; opi >= 0; opi--)
3904     {
3905       if (xtensa_operand_is_visible (isa, opcode, opi) == 0)
3906         continue;
3907       if (xtensa_operand_is_PCrelative (isa, opcode, opi) == 1)
3908         {
3909           last_immed = opi;
3910           break;
3911         }
3912       if (last_immed == XTENSA_UNDEFINED
3913           && xtensa_operand_is_register (isa, opcode, opi) == 0)
3914         last_immed = opi;
3915     }
3916   if (last_immed < 0)
3917     return XTENSA_UNDEFINED;
3918
3919   /* If the operand number was specified in an old-style relocation,
3920      check for consistency with the operand computed above.  */
3921   if (r_type >= R_XTENSA_OP0 && r_type <= R_XTENSA_OP2)
3922     {
3923       int reloc_opnd = r_type - R_XTENSA_OP0;
3924       if (reloc_opnd != last_immed)
3925         return XTENSA_UNDEFINED;
3926     }
3927
3928   return last_immed;
3929 }
3930
3931
3932 int
3933 get_relocation_slot (int r_type)
3934 {
3935   switch (r_type)
3936     {
3937     case R_XTENSA_OP0:
3938     case R_XTENSA_OP1:
3939     case R_XTENSA_OP2:
3940       return 0;
3941
3942     default:
3943       if (r_type >= R_XTENSA_SLOT0_OP && r_type <= R_XTENSA_SLOT14_OP)
3944         return r_type - R_XTENSA_SLOT0_OP;
3945       if (r_type >= R_XTENSA_SLOT0_ALT && r_type <= R_XTENSA_SLOT14_ALT)
3946         return r_type - R_XTENSA_SLOT0_ALT;
3947       break;
3948     }
3949
3950   return XTENSA_UNDEFINED;
3951 }
3952
3953
3954 /* Get the opcode for a relocation.  */
3955
3956 static xtensa_opcode
3957 get_relocation_opcode (bfd *abfd,
3958                        asection *sec,
3959                        bfd_byte *contents,
3960                        Elf_Internal_Rela *irel)
3961 {
3962   static xtensa_insnbuf ibuff = NULL;
3963   static xtensa_insnbuf sbuff = NULL;
3964   xtensa_isa isa = xtensa_default_isa;
3965   xtensa_format fmt;
3966   int slot;
3967
3968   if (contents == NULL)
3969     return XTENSA_UNDEFINED;
3970
3971   if (bfd_get_section_limit (abfd, sec) <= irel->r_offset)
3972     return XTENSA_UNDEFINED;
3973
3974   if (ibuff == NULL)
3975     {
3976       ibuff = xtensa_insnbuf_alloc (isa);
3977       sbuff = xtensa_insnbuf_alloc (isa);
3978     }
3979
3980   /* Decode the instruction.  */
3981   xtensa_insnbuf_from_chars (isa, ibuff, &contents[irel->r_offset],
3982                              sec->size - irel->r_offset);
3983   fmt = xtensa_format_decode (isa, ibuff);
3984   slot = get_relocation_slot (ELF32_R_TYPE (irel->r_info));
3985   if (slot == XTENSA_UNDEFINED)
3986     return XTENSA_UNDEFINED;
3987   xtensa_format_get_slot (isa, fmt, slot, ibuff, sbuff);
3988   return xtensa_opcode_decode (isa, fmt, slot, sbuff);
3989 }
3990
3991
3992 bfd_boolean
3993 is_l32r_relocation (bfd *abfd,
3994                     asection *sec,
3995                     bfd_byte *contents,
3996                     Elf_Internal_Rela *irel)
3997 {
3998   xtensa_opcode opcode;
3999   if (!is_operand_relocation (ELF32_R_TYPE (irel->r_info)))
4000     return FALSE;
4001   opcode = get_relocation_opcode (abfd, sec, contents, irel);
4002   return (opcode == get_l32r_opcode ());
4003 }
4004
4005
4006 static bfd_size_type
4007 get_asm_simplify_size (bfd_byte *contents,
4008                        bfd_size_type content_len,
4009                        bfd_size_type offset)
4010 {
4011   bfd_size_type insnlen, size = 0;
4012
4013   /* Decode the size of the next two instructions.  */
4014   insnlen = insn_decode_len (contents, content_len, offset);
4015   if (insnlen == 0)
4016     return 0;
4017
4018   size += insnlen;
4019
4020   insnlen = insn_decode_len (contents, content_len, offset + size);
4021   if (insnlen == 0)
4022     return 0;
4023
4024   size += insnlen;
4025   return size;
4026 }
4027
4028
4029 bfd_boolean
4030 is_alt_relocation (int r_type)
4031 {
4032   return (r_type >= R_XTENSA_SLOT0_ALT
4033           && r_type <= R_XTENSA_SLOT14_ALT);
4034 }
4035
4036
4037 bfd_boolean
4038 is_operand_relocation (int r_type)
4039 {
4040   switch (r_type)
4041     {
4042     case R_XTENSA_OP0:
4043     case R_XTENSA_OP1:
4044     case R_XTENSA_OP2:
4045       return TRUE;
4046
4047     default:
4048       if (r_type >= R_XTENSA_SLOT0_OP && r_type <= R_XTENSA_SLOT14_OP)
4049         return TRUE;
4050       if (r_type >= R_XTENSA_SLOT0_ALT && r_type <= R_XTENSA_SLOT14_ALT)
4051         return TRUE;
4052       break;
4053     }
4054
4055   return FALSE;
4056 }
4057
4058
4059 #define MIN_INSN_LENGTH 2
4060
4061 /* Return 0 if it fails to decode.  */
4062
4063 bfd_size_type
4064 insn_decode_len (bfd_byte *contents,
4065                  bfd_size_type content_len,
4066                  bfd_size_type offset)
4067 {
4068   int insn_len;
4069   xtensa_isa isa = xtensa_default_isa;
4070   xtensa_format fmt;
4071   static xtensa_insnbuf ibuff = NULL;
4072
4073   if (offset + MIN_INSN_LENGTH > content_len)
4074     return 0;
4075
4076   if (ibuff == NULL)
4077     ibuff = xtensa_insnbuf_alloc (isa);
4078   xtensa_insnbuf_from_chars (isa, ibuff, &contents[offset],
4079                              content_len - offset);
4080   fmt = xtensa_format_decode (isa, ibuff);
4081   if (fmt == XTENSA_UNDEFINED)
4082     return 0;
4083   insn_len = xtensa_format_length (isa, fmt);
4084   if (insn_len ==  XTENSA_UNDEFINED)
4085     return 0;
4086   return insn_len;
4087 }
4088
4089 int
4090 insn_num_slots (bfd_byte *contents,
4091                 bfd_size_type content_len,
4092                 bfd_size_type offset)
4093 {
4094   xtensa_isa isa = xtensa_default_isa;
4095   xtensa_format fmt;
4096   static xtensa_insnbuf ibuff = NULL;
4097
4098   if (offset + MIN_INSN_LENGTH > content_len)
4099     return XTENSA_UNDEFINED;
4100
4101   if (ibuff == NULL)
4102     ibuff = xtensa_insnbuf_alloc (isa);
4103   xtensa_insnbuf_from_chars (isa, ibuff, &contents[offset],
4104                              content_len - offset);
4105   fmt = xtensa_format_decode (isa, ibuff);
4106   if (fmt == XTENSA_UNDEFINED)
4107     return XTENSA_UNDEFINED;
4108   return xtensa_format_num_slots (isa, fmt);
4109 }
4110
4111
4112 /* Decode the opcode for a single slot instruction.
4113    Return 0 if it fails to decode or the instruction is multi-slot.  */
4114
4115 xtensa_opcode
4116 insn_decode_opcode (bfd_byte *contents,
4117                     bfd_size_type content_len,
4118                     bfd_size_type offset,
4119                     int slot)
4120 {
4121   xtensa_isa isa = xtensa_default_isa;
4122   xtensa_format fmt;
4123   static xtensa_insnbuf insnbuf = NULL;
4124   static xtensa_insnbuf slotbuf = NULL;
4125
4126   if (offset + MIN_INSN_LENGTH > content_len)
4127     return XTENSA_UNDEFINED;
4128
4129   if (insnbuf == NULL)
4130     {
4131       insnbuf = xtensa_insnbuf_alloc (isa);
4132       slotbuf = xtensa_insnbuf_alloc (isa);
4133     }
4134
4135   xtensa_insnbuf_from_chars (isa, insnbuf, &contents[offset],
4136                              content_len - offset);
4137   fmt = xtensa_format_decode (isa, insnbuf);
4138   if (fmt == XTENSA_UNDEFINED)
4139     return XTENSA_UNDEFINED;
4140
4141   if (slot >= xtensa_format_num_slots (isa, fmt))
4142     return XTENSA_UNDEFINED;
4143
4144   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
4145   return xtensa_opcode_decode (isa, fmt, slot, slotbuf);
4146 }
4147
4148
4149 /* The offset is the offset in the contents.
4150    The address is the address of that offset.  */
4151
4152 static bfd_boolean
4153 check_branch_target_aligned (bfd_byte *contents,
4154                              bfd_size_type content_length,
4155                              bfd_vma offset,
4156                              bfd_vma address)
4157 {
4158   bfd_size_type insn_len = insn_decode_len (contents, content_length, offset);
4159   if (insn_len == 0)
4160     return FALSE;
4161   return check_branch_target_aligned_address (address, insn_len);
4162 }
4163
4164
4165 static bfd_boolean
4166 check_loop_aligned (bfd_byte *contents,
4167                     bfd_size_type content_length,
4168                     bfd_vma offset,
4169                     bfd_vma address)
4170 {
4171   bfd_size_type loop_len, insn_len;
4172   xtensa_opcode opcode;
4173
4174   opcode = insn_decode_opcode (contents, content_length, offset, 0);
4175   if (opcode == XTENSA_UNDEFINED
4176       || xtensa_opcode_is_loop (xtensa_default_isa, opcode) != 1)
4177     {
4178       BFD_ASSERT (FALSE);
4179       return FALSE;
4180     }
4181
4182   loop_len = insn_decode_len (contents, content_length, offset);
4183   insn_len = insn_decode_len (contents, content_length, offset + loop_len);
4184   if (loop_len == 0 || insn_len == 0)
4185     {
4186       BFD_ASSERT (FALSE);
4187       return FALSE;
4188     }
4189
4190   /* If this is relaxed loop, analyze first instruction of the actual loop
4191      body.  It must be at offset 27 from the loop instruction address.  */
4192   if (insn_len == 3
4193       && insn_num_slots (contents, content_length, offset + loop_len) == 1
4194       && insn_decode_opcode (contents, content_length,
4195                              offset + loop_len, 0) == get_rsr_lend_opcode()
4196       && insn_decode_len (contents, content_length, offset + loop_len + 3) == 3
4197       && insn_num_slots (contents, content_length, offset + loop_len + 3) == 1
4198       && insn_decode_opcode (contents, content_length,
4199                              offset + loop_len + 3, 0) == get_wsr_lbeg_opcode())
4200     {
4201       loop_len = 27;
4202       insn_len = insn_decode_len (contents, content_length, offset + loop_len);
4203     }
4204   return check_branch_target_aligned_address (address + loop_len, insn_len);
4205 }
4206
4207
4208 static bfd_boolean
4209 check_branch_target_aligned_address (bfd_vma addr, int len)
4210 {
4211   if (len == 8)
4212     return (addr % 8 == 0);
4213   return ((addr >> 2) == ((addr + len - 1) >> 2));
4214 }
4215
4216 \f
4217 /* Instruction widening and narrowing.  */
4218
4219 /* When FLIX is available we need to access certain instructions only
4220    when they are 16-bit or 24-bit instructions.  This table caches
4221    information about such instructions by walking through all the
4222    opcodes and finding the smallest single-slot format into which each
4223    can be encoded.  */
4224
4225 static xtensa_format *op_single_fmt_table = NULL;
4226
4227
4228 static void
4229 init_op_single_format_table (void)
4230 {
4231   xtensa_isa isa = xtensa_default_isa;
4232   xtensa_insnbuf ibuf;
4233   xtensa_opcode opcode;
4234   xtensa_format fmt;
4235   int num_opcodes;
4236
4237   if (op_single_fmt_table)
4238     return;
4239
4240   ibuf = xtensa_insnbuf_alloc (isa);
4241   num_opcodes = xtensa_isa_num_opcodes (isa);
4242
4243   op_single_fmt_table = (xtensa_format *)
4244     bfd_malloc (sizeof (xtensa_format) * num_opcodes);
4245   for (opcode = 0; opcode < num_opcodes; opcode++)
4246     {
4247       op_single_fmt_table[opcode] = XTENSA_UNDEFINED;
4248       for (fmt = 0; fmt < xtensa_isa_num_formats (isa); fmt++)
4249         {
4250           if (xtensa_format_num_slots (isa, fmt) == 1
4251               && xtensa_opcode_encode (isa, fmt, 0, ibuf, opcode) == 0)
4252             {
4253               xtensa_opcode old_fmt = op_single_fmt_table[opcode];
4254               int fmt_length = xtensa_format_length (isa, fmt);
4255               if (old_fmt == XTENSA_UNDEFINED
4256                   || fmt_length < xtensa_format_length (isa, old_fmt))
4257                 op_single_fmt_table[opcode] = fmt;
4258             }
4259         }
4260     }
4261   xtensa_insnbuf_free (isa, ibuf);
4262 }
4263
4264
4265 static xtensa_format
4266 get_single_format (xtensa_opcode opcode)
4267 {
4268   init_op_single_format_table ();
4269   return op_single_fmt_table[opcode];
4270 }
4271
4272
4273 /* For the set of narrowable instructions we do NOT include the
4274    narrowings beqz -> beqz.n or bnez -> bnez.n because of complexities
4275    involved during linker relaxation that may require these to
4276    re-expand in some conditions.  Also, the narrowing "or" -> mov.n
4277    requires special case code to ensure it only works when op1 == op2.  */
4278
4279 struct string_pair
4280 {
4281   const char *wide;
4282   const char *narrow;
4283 };
4284
4285 struct string_pair narrowable[] =
4286 {
4287   { "add", "add.n" },
4288   { "addi", "addi.n" },
4289   { "addmi", "addi.n" },
4290   { "l32i", "l32i.n" },
4291   { "movi", "movi.n" },
4292   { "ret", "ret.n" },
4293   { "retw", "retw.n" },
4294   { "s32i", "s32i.n" },
4295   { "or", "mov.n" } /* special case only when op1 == op2 */
4296 };
4297
4298 struct string_pair widenable[] =
4299 {
4300   { "add", "add.n" },
4301   { "addi", "addi.n" },
4302   { "addmi", "addi.n" },
4303   { "beqz", "beqz.n" },
4304   { "bnez", "bnez.n" },
4305   { "l32i", "l32i.n" },
4306   { "movi", "movi.n" },
4307   { "ret", "ret.n" },
4308   { "retw", "retw.n" },
4309   { "s32i", "s32i.n" },
4310   { "or", "mov.n" } /* special case only when op1 == op2 */
4311 };
4312
4313
4314 /* Check if an instruction can be "narrowed", i.e., changed from a standard
4315    3-byte instruction to a 2-byte "density" instruction.  If it is valid,
4316    return the instruction buffer holding the narrow instruction.  Otherwise,
4317    return 0.  The set of valid narrowing are specified by a string table
4318    but require some special case operand checks in some cases.  */
4319
4320 static xtensa_insnbuf
4321 can_narrow_instruction (xtensa_insnbuf slotbuf,
4322                         xtensa_format fmt,
4323                         xtensa_opcode opcode)
4324 {
4325   xtensa_isa isa = xtensa_default_isa;
4326   xtensa_format o_fmt;
4327   unsigned opi;
4328
4329   static xtensa_insnbuf o_insnbuf = NULL;
4330   static xtensa_insnbuf o_slotbuf = NULL;
4331
4332   if (o_insnbuf == NULL)
4333     {
4334       o_insnbuf = xtensa_insnbuf_alloc (isa);
4335       o_slotbuf = xtensa_insnbuf_alloc (isa);
4336     }
4337
4338   for (opi = 0; opi < (sizeof (narrowable)/sizeof (struct string_pair)); opi++)
4339     {
4340       bfd_boolean is_or = (strcmp ("or", narrowable[opi].wide) == 0);
4341
4342       if (opcode == xtensa_opcode_lookup (isa, narrowable[opi].wide))
4343         {
4344           uint32 value, newval;
4345           int i, operand_count, o_operand_count;
4346           xtensa_opcode o_opcode;
4347
4348           /* Address does not matter in this case.  We might need to
4349              fix it to handle branches/jumps.  */
4350           bfd_vma self_address = 0;
4351
4352           o_opcode = xtensa_opcode_lookup (isa, narrowable[opi].narrow);
4353           if (o_opcode == XTENSA_UNDEFINED)
4354             return 0;
4355           o_fmt = get_single_format (o_opcode);
4356           if (o_fmt == XTENSA_UNDEFINED)
4357             return 0;
4358
4359           if (xtensa_format_length (isa, fmt) != 3
4360               || xtensa_format_length (isa, o_fmt) != 2)
4361             return 0;
4362
4363           xtensa_format_encode (isa, o_fmt, o_insnbuf);
4364           operand_count = xtensa_opcode_num_operands (isa, opcode);
4365           o_operand_count = xtensa_opcode_num_operands (isa, o_opcode);
4366
4367           if (xtensa_opcode_encode (isa, o_fmt, 0, o_slotbuf, o_opcode) != 0)
4368             return 0;
4369
4370           if (!is_or)
4371             {
4372               if (xtensa_opcode_num_operands (isa, o_opcode) != operand_count)
4373                 return 0;
4374             }
4375           else
4376             {
4377               uint32 rawval0, rawval1, rawval2;
4378
4379               if (o_operand_count + 1 != operand_count
4380                   || xtensa_operand_get_field (isa, opcode, 0,
4381                                                fmt, 0, slotbuf, &rawval0) != 0
4382                   || xtensa_operand_get_field (isa, opcode, 1,
4383                                                fmt, 0, slotbuf, &rawval1) != 0
4384                   || xtensa_operand_get_field (isa, opcode, 2,
4385                                                fmt, 0, slotbuf, &rawval2) != 0
4386                   || rawval1 != rawval2
4387                   || rawval0 == rawval1 /* it is a nop */)
4388                 return 0;
4389             }
4390
4391           for (i = 0; i < o_operand_count; ++i)
4392             {
4393               if (xtensa_operand_get_field (isa, opcode, i, fmt, 0,
4394                                             slotbuf, &value)
4395                   || xtensa_operand_decode (isa, opcode, i, &value))
4396                 return 0;
4397
4398               /* PC-relative branches need adjustment, but
4399                  the PC-rel operand will always have a relocation.  */
4400               newval = value;
4401               if (xtensa_operand_do_reloc (isa, o_opcode, i, &newval,
4402                                            self_address)
4403                   || xtensa_operand_encode (isa, o_opcode, i, &newval)
4404                   || xtensa_operand_set_field (isa, o_opcode, i, o_fmt, 0,
4405                                                o_slotbuf, newval))
4406                 return 0;
4407             }
4408
4409           if (xtensa_format_set_slot (isa, o_fmt, 0, o_insnbuf, o_slotbuf))
4410             return 0;
4411
4412           return o_insnbuf;
4413         }
4414     }
4415   return 0;
4416 }
4417
4418
4419 /* Attempt to narrow an instruction.  If the narrowing is valid, perform
4420    the action in-place directly into the contents and return TRUE.  Otherwise,
4421    the return value is FALSE and the contents are not modified.  */
4422
4423 static bfd_boolean
4424 narrow_instruction (bfd_byte *contents,
4425                     bfd_size_type content_length,
4426                     bfd_size_type offset)
4427 {
4428   xtensa_opcode opcode;
4429   bfd_size_type insn_len;
4430   xtensa_isa isa = xtensa_default_isa;
4431   xtensa_format fmt;
4432   xtensa_insnbuf o_insnbuf;
4433
4434   static xtensa_insnbuf insnbuf = NULL;
4435   static xtensa_insnbuf slotbuf = NULL;
4436
4437   if (insnbuf == NULL)
4438     {
4439       insnbuf = xtensa_insnbuf_alloc (isa);
4440       slotbuf = xtensa_insnbuf_alloc (isa);
4441     }
4442
4443   BFD_ASSERT (offset < content_length);
4444
4445   if (content_length < 2)
4446     return FALSE;
4447
4448   /* We will hand-code a few of these for a little while.
4449      These have all been specified in the assembler aleady.  */
4450   xtensa_insnbuf_from_chars (isa, insnbuf, &contents[offset],
4451                              content_length - offset);
4452   fmt = xtensa_format_decode (isa, insnbuf);
4453   if (xtensa_format_num_slots (isa, fmt) != 1)
4454     return FALSE;
4455
4456   if (xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf) != 0)
4457     return FALSE;
4458
4459   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
4460   if (opcode == XTENSA_UNDEFINED)
4461     return FALSE;
4462   insn_len = xtensa_format_length (isa, fmt);
4463   if (insn_len > content_length)
4464     return FALSE;
4465
4466   o_insnbuf = can_narrow_instruction (slotbuf, fmt, opcode);
4467   if (o_insnbuf)
4468     {
4469       xtensa_insnbuf_to_chars (isa, o_insnbuf, contents + offset,
4470                                content_length - offset);
4471       return TRUE;
4472     }
4473
4474   return FALSE;
4475 }
4476
4477
4478 /* Check if an instruction can be "widened", i.e., changed from a 2-byte
4479    "density" instruction to a standard 3-byte instruction.  If it is valid,
4480    return the instruction buffer holding the wide instruction.  Otherwise,
4481    return 0.  The set of valid widenings are specified by a string table
4482    but require some special case operand checks in some cases.  */
4483
4484 static xtensa_insnbuf
4485 can_widen_instruction (xtensa_insnbuf slotbuf,
4486                        xtensa_format fmt,
4487                        xtensa_opcode opcode)
4488 {
4489   xtensa_isa isa = xtensa_default_isa;
4490   xtensa_format o_fmt;
4491   unsigned opi;
4492
4493   static xtensa_insnbuf o_insnbuf = NULL;
4494   static xtensa_insnbuf o_slotbuf = NULL;
4495
4496   if (o_insnbuf == NULL)
4497     {
4498       o_insnbuf = xtensa_insnbuf_alloc (isa);
4499       o_slotbuf = xtensa_insnbuf_alloc (isa);
4500     }
4501
4502   for (opi = 0; opi < (sizeof (widenable)/sizeof (struct string_pair)); opi++)
4503     {
4504       bfd_boolean is_or = (strcmp ("or", widenable[opi].wide) == 0);
4505       bfd_boolean is_branch = (strcmp ("beqz", widenable[opi].wide) == 0
4506                                || strcmp ("bnez", widenable[opi].wide) == 0);
4507
4508       if (opcode == xtensa_opcode_lookup (isa, widenable[opi].narrow))
4509         {
4510           uint32 value, newval;
4511           int i, operand_count, o_operand_count, check_operand_count;
4512           xtensa_opcode o_opcode;
4513
4514           /* Address does not matter in this case.  We might need to fix it
4515              to handle branches/jumps.  */
4516           bfd_vma self_address = 0;
4517
4518           o_opcode = xtensa_opcode_lookup (isa, widenable[opi].wide);
4519           if (o_opcode == XTENSA_UNDEFINED)
4520             return 0;
4521           o_fmt = get_single_format (o_opcode);
4522           if (o_fmt == XTENSA_UNDEFINED)
4523             return 0;
4524
4525           if (xtensa_format_length (isa, fmt) != 2
4526               || xtensa_format_length (isa, o_fmt) != 3)
4527             return 0;
4528
4529           xtensa_format_encode (isa, o_fmt, o_insnbuf);
4530           operand_count = xtensa_opcode_num_operands (isa, opcode);
4531           o_operand_count = xtensa_opcode_num_operands (isa, o_opcode);
4532           check_operand_count = o_operand_count;
4533
4534           if (xtensa_opcode_encode (isa, o_fmt, 0, o_slotbuf, o_opcode) != 0)
4535             return 0;
4536
4537           if (!is_or)
4538             {
4539               if (xtensa_opcode_num_operands (isa, o_opcode) != operand_count)
4540                 return 0;
4541             }
4542           else
4543             {
4544               uint32 rawval0, rawval1;
4545
4546               if (o_operand_count != operand_count + 1
4547                   || xtensa_operand_get_field (isa, opcode, 0,
4548                                                fmt, 0, slotbuf, &rawval0) != 0
4549                   || xtensa_operand_get_field (isa, opcode, 1,
4550                                                fmt, 0, slotbuf, &rawval1) != 0
4551                   || rawval0 == rawval1 /* it is a nop */)
4552                 return 0;
4553             }
4554           if (is_branch)
4555             check_operand_count--;
4556
4557           for (i = 0; i < check_operand_count; i++)
4558             {
4559               int new_i = i;
4560               if (is_or && i == o_operand_count - 1)
4561                 new_i = i - 1;
4562               if (xtensa_operand_get_field (isa, opcode, new_i, fmt, 0,
4563                                             slotbuf, &value)
4564                   || xtensa_operand_decode (isa, opcode, new_i, &value))
4565                 return 0;
4566
4567               /* PC-relative branches need adjustment, but
4568                  the PC-rel operand will always have a relocation.  */
4569               newval = value;
4570               if (xtensa_operand_do_reloc (isa, o_opcode, i, &newval,
4571                                            self_address)
4572                   || xtensa_operand_encode (isa, o_opcode, i, &newval)
4573                   || xtensa_operand_set_field (isa, o_opcode, i, o_fmt, 0,
4574                                                o_slotbuf, newval))
4575                 return 0;
4576             }
4577
4578           if (xtensa_format_set_slot (isa, o_fmt, 0, o_insnbuf, o_slotbuf))
4579             return 0;
4580
4581           return o_insnbuf;
4582         }
4583     }
4584   return 0;
4585 }
4586
4587
4588 /* Attempt to widen an instruction.  If the widening is valid, perform
4589    the action in-place directly into the contents and return TRUE.  Otherwise,
4590    the return value is FALSE and the contents are not modified.  */
4591
4592 static bfd_boolean
4593 widen_instruction (bfd_byte *contents,
4594                    bfd_size_type content_length,
4595                    bfd_size_type offset)
4596 {
4597   xtensa_opcode opcode;
4598   bfd_size_type insn_len;
4599   xtensa_isa isa = xtensa_default_isa;
4600   xtensa_format fmt;
4601   xtensa_insnbuf o_insnbuf;
4602
4603   static xtensa_insnbuf insnbuf = NULL;
4604   static xtensa_insnbuf slotbuf = NULL;
4605
4606   if (insnbuf == NULL)
4607     {
4608       insnbuf = xtensa_insnbuf_alloc (isa);
4609       slotbuf = xtensa_insnbuf_alloc (isa);
4610     }
4611
4612   BFD_ASSERT (offset < content_length);
4613
4614   if (content_length < 2)
4615     return FALSE;
4616
4617   /* We will hand-code a few of these for a little while.
4618      These have all been specified in the assembler aleady.  */
4619   xtensa_insnbuf_from_chars (isa, insnbuf, &contents[offset],
4620                              content_length - offset);
4621   fmt = xtensa_format_decode (isa, insnbuf);
4622   if (xtensa_format_num_slots (isa, fmt) != 1)
4623     return FALSE;
4624
4625   if (xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf) != 0)
4626     return FALSE;
4627
4628   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
4629   if (opcode == XTENSA_UNDEFINED)
4630     return FALSE;
4631   insn_len = xtensa_format_length (isa, fmt);
4632   if (insn_len > content_length)
4633     return FALSE;
4634
4635   o_insnbuf = can_widen_instruction (slotbuf, fmt, opcode);
4636   if (o_insnbuf)
4637     {
4638       xtensa_insnbuf_to_chars (isa, o_insnbuf, contents + offset,
4639                                content_length - offset);
4640       return TRUE;
4641     }
4642   return FALSE;
4643 }
4644
4645 \f
4646 /* Code for transforming CALLs at link-time.  */
4647
4648 static bfd_reloc_status_type
4649 elf_xtensa_do_asm_simplify (bfd_byte *contents,
4650                             bfd_vma address,
4651                             bfd_vma content_length,
4652                             char **error_message)
4653 {
4654   static xtensa_insnbuf insnbuf = NULL;
4655   static xtensa_insnbuf slotbuf = NULL;
4656   xtensa_format core_format = XTENSA_UNDEFINED;
4657   xtensa_opcode opcode;
4658   xtensa_opcode direct_call_opcode;
4659   xtensa_isa isa = xtensa_default_isa;
4660   bfd_byte *chbuf = contents + address;
4661   int opn;
4662
4663   if (insnbuf == NULL)
4664     {
4665       insnbuf = xtensa_insnbuf_alloc (isa);
4666       slotbuf = xtensa_insnbuf_alloc (isa);
4667     }
4668
4669   if (content_length < address)
4670     {
4671       *error_message = _("attempt to convert L32R/CALLX to CALL failed");
4672       return bfd_reloc_other;
4673     }
4674
4675   opcode = get_expanded_call_opcode (chbuf, content_length - address, 0);
4676   direct_call_opcode = swap_callx_for_call_opcode (opcode);
4677   if (direct_call_opcode == XTENSA_UNDEFINED)
4678     {
4679       *error_message = _("attempt to convert L32R/CALLX to CALL failed");
4680       return bfd_reloc_other;
4681     }
4682
4683   /* Assemble a NOP ("or a1, a1, a1") into the 0 byte offset.  */
4684   core_format = xtensa_format_lookup (isa, "x24");
4685   opcode = xtensa_opcode_lookup (isa, "or");
4686   xtensa_opcode_encode (isa, core_format, 0, slotbuf, opcode);
4687   for (opn = 0; opn < 3; opn++)
4688     {
4689       uint32 regno = 1;
4690       xtensa_operand_encode (isa, opcode, opn, &regno);
4691       xtensa_operand_set_field (isa, opcode, opn, core_format, 0,
4692                                 slotbuf, regno);
4693     }
4694   xtensa_format_encode (isa, core_format, insnbuf);
4695   xtensa_format_set_slot (isa, core_format, 0, insnbuf, slotbuf);
4696   xtensa_insnbuf_to_chars (isa, insnbuf, chbuf, content_length - address);
4697
4698   /* Assemble a CALL ("callN 0") into the 3 byte offset.  */
4699   xtensa_opcode_encode (isa, core_format, 0, slotbuf, direct_call_opcode);
4700   xtensa_operand_set_field (isa, opcode, 0, core_format, 0, slotbuf, 0);
4701
4702   xtensa_format_encode (isa, core_format, insnbuf);
4703   xtensa_format_set_slot (isa, core_format, 0, insnbuf, slotbuf);
4704   xtensa_insnbuf_to_chars (isa, insnbuf, chbuf + 3,
4705                            content_length - address - 3);
4706
4707   return bfd_reloc_ok;
4708 }
4709
4710
4711 static bfd_reloc_status_type
4712 contract_asm_expansion (bfd_byte *contents,
4713                         bfd_vma content_length,
4714                         Elf_Internal_Rela *irel,
4715                         char **error_message)
4716 {
4717   bfd_reloc_status_type retval =
4718     elf_xtensa_do_asm_simplify (contents, irel->r_offset, content_length,
4719                                 error_message);
4720
4721   if (retval != bfd_reloc_ok)
4722     return bfd_reloc_dangerous;
4723
4724   /* Update the irel->r_offset field so that the right immediate and
4725      the right instruction are modified during the relocation.  */
4726   irel->r_offset += 3;
4727   irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info), R_XTENSA_SLOT0_OP);
4728   return bfd_reloc_ok;
4729 }
4730
4731
4732 static xtensa_opcode
4733 swap_callx_for_call_opcode (xtensa_opcode opcode)
4734 {
4735   init_call_opcodes ();
4736
4737   if (opcode == callx0_op) return call0_op;
4738   if (opcode == callx4_op) return call4_op;
4739   if (opcode == callx8_op) return call8_op;
4740   if (opcode == callx12_op) return call12_op;
4741
4742   /* Return XTENSA_UNDEFINED if the opcode is not an indirect call.  */
4743   return XTENSA_UNDEFINED;
4744 }
4745
4746
4747 /* Check if "buf" is pointing to a "L32R aN; CALLX aN" or "CONST16 aN;
4748    CONST16 aN; CALLX aN" sequence, and if so, return the CALLX opcode.
4749    If not, return XTENSA_UNDEFINED.  */
4750
4751 #define L32R_TARGET_REG_OPERAND 0
4752 #define CONST16_TARGET_REG_OPERAND 0
4753 #define CALLN_SOURCE_OPERAND 0
4754
4755 static xtensa_opcode
4756 get_expanded_call_opcode (bfd_byte *buf, int bufsize, bfd_boolean *p_uses_l32r)
4757 {
4758   static xtensa_insnbuf insnbuf = NULL;
4759   static xtensa_insnbuf slotbuf = NULL;
4760   xtensa_format fmt;
4761   xtensa_opcode opcode;
4762   xtensa_isa isa = xtensa_default_isa;
4763   uint32 regno, const16_regno, call_regno;
4764   int offset = 0;
4765
4766   if (insnbuf == NULL)
4767     {
4768       insnbuf = xtensa_insnbuf_alloc (isa);
4769       slotbuf = xtensa_insnbuf_alloc (isa);
4770     }
4771
4772   xtensa_insnbuf_from_chars (isa, insnbuf, buf, bufsize);
4773   fmt = xtensa_format_decode (isa, insnbuf);
4774   if (fmt == XTENSA_UNDEFINED
4775       || xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf))
4776     return XTENSA_UNDEFINED;
4777
4778   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
4779   if (opcode == XTENSA_UNDEFINED)
4780     return XTENSA_UNDEFINED;
4781
4782   if (opcode == get_l32r_opcode ())
4783     {
4784       if (p_uses_l32r)
4785         *p_uses_l32r = TRUE;
4786       if (xtensa_operand_get_field (isa, opcode, L32R_TARGET_REG_OPERAND,
4787                                     fmt, 0, slotbuf, &regno)
4788           || xtensa_operand_decode (isa, opcode, L32R_TARGET_REG_OPERAND,
4789                                     &regno))
4790         return XTENSA_UNDEFINED;
4791     }
4792   else if (opcode == get_const16_opcode ())
4793     {
4794       if (p_uses_l32r)
4795         *p_uses_l32r = FALSE;
4796       if (xtensa_operand_get_field (isa, opcode, CONST16_TARGET_REG_OPERAND,
4797                                     fmt, 0, slotbuf, &regno)
4798           || xtensa_operand_decode (isa, opcode, CONST16_TARGET_REG_OPERAND,
4799                                     &regno))
4800         return XTENSA_UNDEFINED;
4801
4802       /* Check that the next instruction is also CONST16.  */
4803       offset += xtensa_format_length (isa, fmt);
4804       xtensa_insnbuf_from_chars (isa, insnbuf, buf + offset, bufsize - offset);
4805       fmt = xtensa_format_decode (isa, insnbuf);
4806       if (fmt == XTENSA_UNDEFINED
4807           || xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf))
4808         return XTENSA_UNDEFINED;
4809       opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
4810       if (opcode != get_const16_opcode ())
4811         return XTENSA_UNDEFINED;
4812
4813       if (xtensa_operand_get_field (isa, opcode, CONST16_TARGET_REG_OPERAND,
4814                                     fmt, 0, slotbuf, &const16_regno)
4815           || xtensa_operand_decode (isa, opcode, CONST16_TARGET_REG_OPERAND,
4816                                     &const16_regno)
4817           || const16_regno != regno)
4818         return XTENSA_UNDEFINED;
4819     }
4820   else
4821     return XTENSA_UNDEFINED;
4822
4823   /* Next instruction should be an CALLXn with operand 0 == regno.  */
4824   offset += xtensa_format_length (isa, fmt);
4825   xtensa_insnbuf_from_chars (isa, insnbuf, buf + offset, bufsize - offset);
4826   fmt = xtensa_format_decode (isa, insnbuf);
4827   if (fmt == XTENSA_UNDEFINED
4828       || xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf))
4829     return XTENSA_UNDEFINED;
4830   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
4831   if (opcode == XTENSA_UNDEFINED
4832       || !is_indirect_call_opcode (opcode))
4833     return XTENSA_UNDEFINED;
4834
4835   if (xtensa_operand_get_field (isa, opcode, CALLN_SOURCE_OPERAND,
4836                                 fmt, 0, slotbuf, &call_regno)
4837       || xtensa_operand_decode (isa, opcode, CALLN_SOURCE_OPERAND,
4838                                 &call_regno))
4839     return XTENSA_UNDEFINED;
4840
4841   if (call_regno != regno)
4842     return XTENSA_UNDEFINED;
4843
4844   return opcode;
4845 }
4846
4847 \f
4848 /* Data structures used during relaxation.  */
4849
4850 /* r_reloc: relocation values.  */
4851
4852 /* Through the relaxation process, we need to keep track of the values
4853    that will result from evaluating relocations.  The standard ELF
4854    relocation structure is not sufficient for this purpose because we're
4855    operating on multiple input files at once, so we need to know which
4856    input file a relocation refers to.  The r_reloc structure thus
4857    records both the input file (bfd) and ELF relocation.
4858
4859    For efficiency, an r_reloc also contains a "target_offset" field to
4860    cache the target-section-relative offset value that is represented by
4861    the relocation.
4862
4863    The r_reloc also contains a virtual offset that allows multiple
4864    inserted literals to be placed at the same "address" with
4865    different offsets.  */
4866
4867 typedef struct r_reloc_struct r_reloc;
4868
4869 struct r_reloc_struct
4870 {
4871   bfd *abfd;
4872   Elf_Internal_Rela rela;
4873   bfd_vma target_offset;
4874   bfd_vma virtual_offset;
4875 };
4876
4877
4878 /* The r_reloc structure is included by value in literal_value, but not
4879    every literal_value has an associated relocation -- some are simple
4880    constants.  In such cases, we set all the fields in the r_reloc
4881    struct to zero.  The r_reloc_is_const function should be used to
4882    detect this case.  */
4883
4884 static bfd_boolean
4885 r_reloc_is_const (const r_reloc *r_rel)
4886 {
4887   return (r_rel->abfd == NULL);
4888 }
4889
4890
4891 static bfd_vma
4892 r_reloc_get_target_offset (const r_reloc *r_rel)
4893 {
4894   bfd_vma target_offset;
4895   unsigned long r_symndx;
4896
4897   BFD_ASSERT (!r_reloc_is_const (r_rel));
4898   r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
4899   target_offset = get_elf_r_symndx_offset (r_rel->abfd, r_symndx);
4900   return (target_offset + r_rel->rela.r_addend);
4901 }
4902
4903
4904 static struct elf_link_hash_entry *
4905 r_reloc_get_hash_entry (const r_reloc *r_rel)
4906 {
4907   unsigned long r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
4908   return get_elf_r_symndx_hash_entry (r_rel->abfd, r_symndx);
4909 }
4910
4911
4912 static asection *
4913 r_reloc_get_section (const r_reloc *r_rel)
4914 {
4915   unsigned long r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
4916   return get_elf_r_symndx_section (r_rel->abfd, r_symndx);
4917 }
4918
4919
4920 static bfd_boolean
4921 r_reloc_is_defined (const r_reloc *r_rel)
4922 {
4923   asection *sec;
4924   if (r_rel == NULL)
4925     return FALSE;
4926
4927   sec = r_reloc_get_section (r_rel);
4928   if (sec == bfd_abs_section_ptr
4929       || sec == bfd_com_section_ptr
4930       || sec == bfd_und_section_ptr)
4931     return FALSE;
4932   return TRUE;
4933 }
4934
4935
4936 static void
4937 r_reloc_init (r_reloc *r_rel,
4938               bfd *abfd,
4939               Elf_Internal_Rela *irel,
4940               bfd_byte *contents,
4941               bfd_size_type content_length)
4942 {
4943   int r_type;
4944   reloc_howto_type *howto;
4945
4946   if (irel)
4947     {
4948       r_rel->rela = *irel;
4949       r_rel->abfd = abfd;
4950       r_rel->target_offset = r_reloc_get_target_offset (r_rel);
4951       r_rel->virtual_offset = 0;
4952       r_type = ELF32_R_TYPE (r_rel->rela.r_info);
4953       howto = &elf_howto_table[r_type];
4954       if (howto->partial_inplace)
4955         {
4956           bfd_vma inplace_val;
4957           BFD_ASSERT (r_rel->rela.r_offset < content_length);
4958
4959           inplace_val = bfd_get_32 (abfd, &contents[r_rel->rela.r_offset]);
4960           r_rel->target_offset += inplace_val;
4961         }
4962     }
4963   else
4964     memset (r_rel, 0, sizeof (r_reloc));
4965 }
4966
4967
4968 #if DEBUG
4969
4970 static void
4971 print_r_reloc (FILE *fp, const r_reloc *r_rel)
4972 {
4973   if (r_reloc_is_defined (r_rel))
4974     {
4975       asection *sec = r_reloc_get_section (r_rel);
4976       fprintf (fp, " %s(%s + ", sec->owner->filename, sec->name);
4977     }
4978   else if (r_reloc_get_hash_entry (r_rel))
4979     fprintf (fp, " %s + ", r_reloc_get_hash_entry (r_rel)->root.root.string);
4980   else
4981     fprintf (fp, " ?? + ");
4982
4983   fprintf_vma (fp, r_rel->target_offset);
4984   if (r_rel->virtual_offset)
4985     {
4986       fprintf (fp, " + ");
4987       fprintf_vma (fp, r_rel->virtual_offset);
4988     }
4989
4990   fprintf (fp, ")");
4991 }
4992
4993 #endif /* DEBUG */
4994
4995 \f
4996 /* source_reloc: relocations that reference literals.  */
4997
4998 /* To determine whether literals can be coalesced, we need to first
4999    record all the relocations that reference the literals.  The
5000    source_reloc structure below is used for this purpose.  The
5001    source_reloc entries are kept in a per-literal-section array, sorted
5002    by offset within the literal section (i.e., target offset).
5003
5004    The source_sec and r_rel.rela.r_offset fields identify the source of
5005    the relocation.  The r_rel field records the relocation value, i.e.,
5006    the offset of the literal being referenced.  The opnd field is needed
5007    to determine the range of the immediate field to which the relocation
5008    applies, so we can determine whether another literal with the same
5009    value is within range.  The is_null field is true when the relocation
5010    is being removed (e.g., when an L32R is being removed due to a CALLX
5011    that is converted to a direct CALL).  */
5012
5013 typedef struct source_reloc_struct source_reloc;
5014
5015 struct source_reloc_struct
5016 {
5017   asection *source_sec;
5018   r_reloc r_rel;
5019   xtensa_opcode opcode;
5020   int opnd;
5021   bfd_boolean is_null;
5022   bfd_boolean is_abs_literal;
5023 };
5024
5025
5026 static void
5027 init_source_reloc (source_reloc *reloc,
5028                    asection *source_sec,
5029                    const r_reloc *r_rel,
5030                    xtensa_opcode opcode,
5031                    int opnd,
5032                    bfd_boolean is_abs_literal)
5033 {
5034   reloc->source_sec = source_sec;
5035   reloc->r_rel = *r_rel;
5036   reloc->opcode = opcode;
5037   reloc->opnd = opnd;
5038   reloc->is_null = FALSE;
5039   reloc->is_abs_literal = is_abs_literal;
5040 }
5041
5042
5043 /* Find the source_reloc for a particular source offset and relocation
5044    type.  Note that the array is sorted by _target_ offset, so this is
5045    just a linear search.  */
5046
5047 static source_reloc *
5048 find_source_reloc (source_reloc *src_relocs,
5049                    int src_count,
5050                    asection *sec,
5051                    Elf_Internal_Rela *irel)
5052 {
5053   int i;
5054
5055   for (i = 0; i < src_count; i++)
5056     {
5057       if (src_relocs[i].source_sec == sec
5058           && src_relocs[i].r_rel.rela.r_offset == irel->r_offset
5059           && (ELF32_R_TYPE (src_relocs[i].r_rel.rela.r_info)
5060               == ELF32_R_TYPE (irel->r_info)))
5061         return &src_relocs[i];
5062     }
5063
5064   return NULL;
5065 }
5066
5067
5068 static int
5069 source_reloc_compare (const void *ap, const void *bp)
5070 {
5071   const source_reloc *a = (const source_reloc *) ap;
5072   const source_reloc *b = (const source_reloc *) bp;
5073
5074   if (a->r_rel.target_offset != b->r_rel.target_offset)
5075     return (a->r_rel.target_offset - b->r_rel.target_offset);
5076
5077   /* We don't need to sort on these criteria for correctness,
5078      but enforcing a more strict ordering prevents unstable qsort
5079      from behaving differently with different implementations.
5080      Without the code below we get correct but different results
5081      on Solaris 2.7 and 2.8.  We would like to always produce the
5082      same results no matter the host. */
5083
5084   if ((!a->is_null) - (!b->is_null))
5085     return ((!a->is_null) - (!b->is_null));
5086   return internal_reloc_compare (&a->r_rel.rela, &b->r_rel.rela);
5087 }
5088
5089 \f
5090 /* Literal values and value hash tables.  */
5091
5092 /* Literals with the same value can be coalesced.  The literal_value
5093    structure records the value of a literal: the "r_rel" field holds the
5094    information from the relocation on the literal (if there is one) and
5095    the "value" field holds the contents of the literal word itself.
5096
5097    The value_map structure records a literal value along with the
5098    location of a literal holding that value.  The value_map hash table
5099    is indexed by the literal value, so that we can quickly check if a
5100    particular literal value has been seen before and is thus a candidate
5101    for coalescing.  */
5102
5103 typedef struct literal_value_struct literal_value;
5104 typedef struct value_map_struct value_map;
5105 typedef struct value_map_hash_table_struct value_map_hash_table;
5106
5107 struct literal_value_struct
5108 {
5109   r_reloc r_rel;
5110   unsigned long value;
5111   bfd_boolean is_abs_literal;
5112 };
5113
5114 struct value_map_struct
5115 {
5116   literal_value val;                    /* The literal value.  */
5117   r_reloc loc;                          /* Location of the literal.  */
5118   value_map *next;
5119 };
5120
5121 struct value_map_hash_table_struct
5122 {
5123   unsigned bucket_count;
5124   value_map **buckets;
5125   unsigned count;
5126   bfd_boolean has_last_loc;
5127   r_reloc last_loc;
5128 };
5129
5130
5131 static void
5132 init_literal_value (literal_value *lit,
5133                     const r_reloc *r_rel,
5134                     unsigned long value,
5135                     bfd_boolean is_abs_literal)
5136 {
5137   lit->r_rel = *r_rel;
5138   lit->value = value;
5139   lit->is_abs_literal = is_abs_literal;
5140 }
5141
5142
5143 static bfd_boolean
5144 literal_value_equal (const literal_value *src1,
5145                      const literal_value *src2,
5146                      bfd_boolean final_static_link)
5147 {
5148   struct elf_link_hash_entry *h1, *h2;
5149
5150   if (r_reloc_is_const (&src1->r_rel) != r_reloc_is_const (&src2->r_rel))
5151     return FALSE;
5152
5153   if (r_reloc_is_const (&src1->r_rel))
5154     return (src1->value == src2->value);
5155
5156   if (ELF32_R_TYPE (src1->r_rel.rela.r_info)
5157       != ELF32_R_TYPE (src2->r_rel.rela.r_info))
5158     return FALSE;
5159
5160   if (src1->r_rel.target_offset != src2->r_rel.target_offset)
5161     return FALSE;
5162
5163   if (src1->r_rel.virtual_offset != src2->r_rel.virtual_offset)
5164     return FALSE;
5165
5166   if (src1->value != src2->value)
5167     return FALSE;
5168
5169   /* Now check for the same section (if defined) or the same elf_hash
5170      (if undefined or weak).  */
5171   h1 = r_reloc_get_hash_entry (&src1->r_rel);
5172   h2 = r_reloc_get_hash_entry (&src2->r_rel);
5173   if (r_reloc_is_defined (&src1->r_rel)
5174       && (final_static_link
5175           || ((!h1 || h1->root.type != bfd_link_hash_defweak)
5176               && (!h2 || h2->root.type != bfd_link_hash_defweak))))
5177     {
5178       if (r_reloc_get_section (&src1->r_rel)
5179           != r_reloc_get_section (&src2->r_rel))
5180         return FALSE;
5181     }
5182   else
5183     {
5184       /* Require that the hash entries (i.e., symbols) be identical.  */
5185       if (h1 != h2 || h1 == 0)
5186         return FALSE;
5187     }
5188
5189   if (src1->is_abs_literal != src2->is_abs_literal)
5190     return FALSE;
5191
5192   return TRUE;
5193 }
5194
5195
5196 /* Must be power of 2.  */
5197 #define INITIAL_HASH_RELOC_BUCKET_COUNT 1024
5198
5199 static value_map_hash_table *
5200 value_map_hash_table_init (void)
5201 {
5202   value_map_hash_table *values;
5203
5204   values = (value_map_hash_table *)
5205     bfd_zmalloc (sizeof (value_map_hash_table));
5206   values->bucket_count = INITIAL_HASH_RELOC_BUCKET_COUNT;
5207   values->count = 0;
5208   values->buckets = (value_map **)
5209     bfd_zmalloc (sizeof (value_map *) * values->bucket_count);
5210   if (values->buckets == NULL)
5211     {
5212       free (values);
5213       return NULL;
5214     }
5215   values->has_last_loc = FALSE;
5216
5217   return values;
5218 }
5219
5220
5221 static void
5222 value_map_hash_table_delete (value_map_hash_table *table)
5223 {
5224   free (table->buckets);
5225   free (table);
5226 }
5227
5228
5229 static unsigned
5230 hash_bfd_vma (bfd_vma val)
5231 {
5232   return (val >> 2) + (val >> 10);
5233 }
5234
5235
5236 static unsigned
5237 literal_value_hash (const literal_value *src)
5238 {
5239   unsigned hash_val;
5240
5241   hash_val = hash_bfd_vma (src->value);
5242   if (!r_reloc_is_const (&src->r_rel))
5243     {
5244       void *sec_or_hash;
5245
5246       hash_val += hash_bfd_vma (src->is_abs_literal * 1000);
5247       hash_val += hash_bfd_vma (src->r_rel.target_offset);
5248       hash_val += hash_bfd_vma (src->r_rel.virtual_offset);
5249
5250       /* Now check for the same section and the same elf_hash.  */
5251       if (r_reloc_is_defined (&src->r_rel))
5252         sec_or_hash = r_reloc_get_section (&src->r_rel);
5253       else
5254         sec_or_hash = r_reloc_get_hash_entry (&src->r_rel);
5255       hash_val += hash_bfd_vma ((bfd_vma) (size_t) sec_or_hash);
5256     }
5257   return hash_val;
5258 }
5259
5260
5261 /* Check if the specified literal_value has been seen before.  */
5262
5263 static value_map *
5264 value_map_get_cached_value (value_map_hash_table *map,
5265                             const literal_value *val,
5266                             bfd_boolean final_static_link)
5267 {
5268   value_map *map_e;
5269   value_map *bucket;
5270   unsigned idx;
5271
5272   idx = literal_value_hash (val);
5273   idx = idx & (map->bucket_count - 1);
5274   bucket = map->buckets[idx];
5275   for (map_e = bucket; map_e; map_e = map_e->next)
5276     {
5277       if (literal_value_equal (&map_e->val, val, final_static_link))
5278         return map_e;
5279     }
5280   return NULL;
5281 }
5282
5283
5284 /* Record a new literal value.  It is illegal to call this if VALUE
5285    already has an entry here.  */
5286
5287 static value_map *
5288 add_value_map (value_map_hash_table *map,
5289                const literal_value *val,
5290                const r_reloc *loc,
5291                bfd_boolean final_static_link)
5292 {
5293   value_map **bucket_p;
5294   unsigned idx;
5295
5296   value_map *val_e = (value_map *) bfd_zmalloc (sizeof (value_map));
5297   if (val_e == NULL)
5298     {
5299       bfd_set_error (bfd_error_no_memory);
5300       return NULL;
5301     }
5302
5303   BFD_ASSERT (!value_map_get_cached_value (map, val, final_static_link));
5304   val_e->val = *val;
5305   val_e->loc = *loc;
5306
5307   idx = literal_value_hash (val);
5308   idx = idx & (map->bucket_count - 1);
5309   bucket_p = &map->buckets[idx];
5310
5311   val_e->next = *bucket_p;
5312   *bucket_p = val_e;
5313   map->count++;
5314   /* FIXME: Consider resizing the hash table if we get too many entries.  */
5315
5316   return val_e;
5317 }
5318
5319 \f
5320 /* Lists of text actions (ta_) for narrowing, widening, longcall
5321    conversion, space fill, code & literal removal, etc.  */
5322
5323 /* The following text actions are generated:
5324
5325    "ta_remove_insn"         remove an instruction or instructions
5326    "ta_remove_longcall"     convert longcall to call
5327    "ta_convert_longcall"    convert longcall to nop/call
5328    "ta_narrow_insn"         narrow a wide instruction
5329    "ta_widen"               widen a narrow instruction
5330    "ta_fill"                add fill or remove fill
5331       removed < 0 is a fill; branches to the fill address will be
5332         changed to address + fill size (e.g., address - removed)
5333       removed >= 0 branches to the fill address will stay unchanged
5334    "ta_remove_literal"      remove a literal; this action is
5335                             indicated when a literal is removed
5336                             or replaced.
5337    "ta_add_literal"         insert a new literal; this action is
5338                             indicated when a literal has been moved.
5339                             It may use a virtual_offset because
5340                             multiple literals can be placed at the
5341                             same location.
5342
5343    For each of these text actions, we also record the number of bytes
5344    removed by performing the text action.  In the case of a "ta_widen"
5345    or a "ta_fill" that adds space, the removed_bytes will be negative.  */
5346
5347 typedef struct text_action_struct text_action;
5348 typedef struct text_action_list_struct text_action_list;
5349 typedef enum text_action_enum_t text_action_t;
5350
5351 enum text_action_enum_t
5352 {
5353   ta_none,
5354   ta_remove_insn,        /* removed = -size */
5355   ta_remove_longcall,    /* removed = -size */
5356   ta_convert_longcall,   /* removed = 0 */
5357   ta_narrow_insn,        /* removed = -1 */
5358   ta_widen_insn,         /* removed = +1 */
5359   ta_fill,               /* removed = +size */
5360   ta_remove_literal,
5361   ta_add_literal
5362 };
5363
5364
5365 /* Structure for a text action record.  */
5366 struct text_action_struct
5367 {
5368   text_action_t action;
5369   asection *sec;        /* Optional */
5370   bfd_vma offset;
5371   bfd_vma virtual_offset;  /* Zero except for adding literals.  */
5372   int removed_bytes;
5373   literal_value value;  /* Only valid when adding literals.  */
5374 };
5375
5376 struct removal_by_action_entry_struct
5377 {
5378   bfd_vma offset;
5379   int removed;
5380   int eq_removed;
5381   int eq_removed_before_fill;
5382 };
5383 typedef struct removal_by_action_entry_struct removal_by_action_entry;
5384
5385 struct removal_by_action_map_struct
5386 {
5387   unsigned n_entries;
5388   removal_by_action_entry *entry;
5389 };
5390 typedef struct removal_by_action_map_struct removal_by_action_map;
5391
5392
5393 /* List of all of the actions taken on a text section.  */
5394 struct text_action_list_struct
5395 {
5396   unsigned count;
5397   splay_tree tree;
5398   removal_by_action_map map;
5399 };
5400
5401
5402 static text_action *
5403 find_fill_action (text_action_list *l, asection *sec, bfd_vma offset)
5404 {
5405   text_action a;
5406
5407   /* It is not necessary to fill at the end of a section.  */
5408   if (sec->size == offset)
5409     return NULL;
5410
5411   a.offset = offset;
5412   a.action = ta_fill;
5413
5414   splay_tree_node node = splay_tree_lookup (l->tree, (splay_tree_key)&a);
5415   if (node)
5416     return (text_action *)node->value;
5417   return NULL;
5418 }
5419
5420
5421 static int
5422 compute_removed_action_diff (const text_action *ta,
5423                              asection *sec,
5424                              bfd_vma offset,
5425                              int removed,
5426                              int removable_space)
5427 {
5428   int new_removed;
5429   int current_removed = 0;
5430
5431   if (ta)
5432     current_removed = ta->removed_bytes;
5433
5434   BFD_ASSERT (ta == NULL || ta->offset == offset);
5435   BFD_ASSERT (ta == NULL || ta->action == ta_fill);
5436
5437   /* It is not necessary to fill at the end of a section.  Clean this up.  */
5438   if (sec->size == offset)
5439     new_removed = removable_space - 0;
5440   else
5441     {
5442       int space;
5443       int added = -removed - current_removed;
5444       /* Ignore multiples of the section alignment.  */
5445       added = ((1 << sec->alignment_power) - 1) & added;
5446       new_removed = (-added);
5447
5448       /* Modify for removable.  */
5449       space = removable_space - new_removed;
5450       new_removed = (removable_space
5451                      - (((1 << sec->alignment_power) - 1) & space));
5452     }
5453   return (new_removed - current_removed);
5454 }
5455
5456
5457 static void
5458 adjust_fill_action (text_action *ta, int fill_diff)
5459 {
5460   ta->removed_bytes += fill_diff;
5461 }
5462
5463
5464 static int
5465 text_action_compare (splay_tree_key a, splay_tree_key b)
5466 {
5467   text_action *pa = (text_action *)a;
5468   text_action *pb = (text_action *)b;
5469   static const int action_priority[] =
5470     {
5471       [ta_fill] = 0,
5472       [ta_none] = 1,
5473       [ta_convert_longcall] = 2,
5474       [ta_narrow_insn] = 3,
5475       [ta_remove_insn] = 4,
5476       [ta_remove_longcall] = 5,
5477       [ta_remove_literal] = 6,
5478       [ta_widen_insn] = 7,
5479       [ta_add_literal] = 8,
5480     };
5481
5482   if (pa->offset == pb->offset)
5483     {
5484       if (pa->action == pb->action)
5485           return 0;
5486       return action_priority[pa->action] - action_priority[pb->action];
5487     }
5488   else
5489     return pa->offset < pb->offset ? -1 : 1;
5490 }
5491
5492 static text_action *
5493 action_first (text_action_list *action_list)
5494 {
5495   splay_tree_node node = splay_tree_min (action_list->tree);
5496   return node ? (text_action *)node->value : NULL;
5497 }
5498
5499 static text_action *
5500 action_next (text_action_list *action_list, text_action *action)
5501 {
5502   splay_tree_node node = splay_tree_successor (action_list->tree,
5503                                                (splay_tree_key)action);
5504   return node ? (text_action *)node->value : NULL;
5505 }
5506
5507 /* Add a modification action to the text.  For the case of adding or
5508    removing space, modify any current fill and assume that
5509    "unreachable_space" bytes can be freely contracted.  Note that a
5510    negative removed value is a fill.  */
5511
5512 static void
5513 text_action_add (text_action_list *l,
5514                  text_action_t action,
5515                  asection *sec,
5516                  bfd_vma offset,
5517                  int removed)
5518 {
5519   text_action *ta;
5520   text_action a;
5521
5522   /* It is not necessary to fill at the end of a section.  */
5523   if (action == ta_fill && sec->size == offset)
5524     return;
5525
5526   /* It is not necessary to fill 0 bytes.  */
5527   if (action == ta_fill && removed == 0)
5528     return;
5529
5530   a.action = action;
5531   a.offset = offset;
5532
5533   if (action == ta_fill)
5534     {
5535       splay_tree_node node = splay_tree_lookup (l->tree, (splay_tree_key)&a);
5536
5537       if (node)
5538         {
5539           ta = (text_action *)node->value;
5540           ta->removed_bytes += removed;
5541           return;
5542         }
5543     }
5544   else
5545     BFD_ASSERT (splay_tree_lookup (l->tree, (splay_tree_key)&a) == NULL);
5546
5547   ta = (text_action *) bfd_zmalloc (sizeof (text_action));
5548   ta->action = action;
5549   ta->sec = sec;
5550   ta->offset = offset;
5551   ta->removed_bytes = removed;
5552   splay_tree_insert (l->tree, (splay_tree_key)ta, (splay_tree_value)ta);
5553   ++l->count;
5554 }
5555
5556
5557 static void
5558 text_action_add_literal (text_action_list *l,
5559                          text_action_t action,
5560                          const r_reloc *loc,
5561                          const literal_value *value,
5562                          int removed)
5563 {
5564   text_action *ta;
5565   asection *sec = r_reloc_get_section (loc);
5566   bfd_vma offset = loc->target_offset;
5567   bfd_vma virtual_offset = loc->virtual_offset;
5568
5569   BFD_ASSERT (action == ta_add_literal);
5570
5571   /* Create a new record and fill it up.  */
5572   ta = (text_action *) bfd_zmalloc (sizeof (text_action));
5573   ta->action = action;
5574   ta->sec = sec;
5575   ta->offset = offset;
5576   ta->virtual_offset = virtual_offset;
5577   ta->value = *value;
5578   ta->removed_bytes = removed;
5579
5580   BFD_ASSERT (splay_tree_lookup (l->tree, (splay_tree_key)ta) == NULL);
5581   splay_tree_insert (l->tree, (splay_tree_key)ta, (splay_tree_value)ta);
5582   ++l->count;
5583 }
5584
5585
5586 /* Find the total offset adjustment for the relaxations specified by
5587    text_actions, beginning from a particular starting action.  This is
5588    typically used from offset_with_removed_text to search an entire list of
5589    actions, but it may also be called directly when adjusting adjacent offsets
5590    so that each search may begin where the previous one left off.  */
5591
5592 static int
5593 removed_by_actions (text_action_list *action_list,
5594                     text_action **p_start_action,
5595                     bfd_vma offset,
5596                     bfd_boolean before_fill)
5597 {
5598   text_action *r;
5599   int removed = 0;
5600
5601   r = *p_start_action;
5602   if (r)
5603     {
5604       splay_tree_node node = splay_tree_lookup (action_list->tree,
5605                                                 (splay_tree_key)r);
5606       BFD_ASSERT (node != NULL && r == (text_action *)node->value);
5607     }
5608
5609   while (r)
5610     {
5611       if (r->offset > offset)
5612         break;
5613
5614       if (r->offset == offset
5615           && (before_fill || r->action != ta_fill || r->removed_bytes >= 0))
5616         break;
5617
5618       removed += r->removed_bytes;
5619
5620       r = action_next (action_list, r);
5621     }
5622
5623   *p_start_action = r;
5624   return removed;
5625 }
5626
5627
5628 static bfd_vma
5629 offset_with_removed_text (text_action_list *action_list, bfd_vma offset)
5630 {
5631   text_action *r = action_first (action_list);
5632
5633   return offset - removed_by_actions (action_list, &r, offset, FALSE);
5634 }
5635
5636
5637 static unsigned
5638 action_list_count (text_action_list *action_list)
5639 {
5640   return action_list->count;
5641 }
5642
5643 typedef struct map_action_fn_context_struct map_action_fn_context;
5644 struct map_action_fn_context_struct
5645 {
5646   int removed;
5647   removal_by_action_map map;
5648   bfd_boolean eq_complete;
5649 };
5650
5651 static int
5652 map_action_fn (splay_tree_node node, void *p)
5653 {
5654   map_action_fn_context *ctx = p;
5655   text_action *r = (text_action *)node->value;
5656   removal_by_action_entry *ientry = ctx->map.entry + ctx->map.n_entries;
5657
5658   if (ctx->map.n_entries && (ientry - 1)->offset == r->offset)
5659     {
5660       --ientry;
5661     }
5662   else
5663     {
5664       ++ctx->map.n_entries;
5665       ctx->eq_complete = FALSE;
5666       ientry->offset = r->offset;
5667       ientry->eq_removed_before_fill = ctx->removed;
5668     }
5669
5670   if (!ctx->eq_complete)
5671     {
5672       if (r->action != ta_fill || r->removed_bytes >= 0)
5673         {
5674           ientry->eq_removed = ctx->removed;
5675           ctx->eq_complete = TRUE;
5676         }
5677       else
5678         ientry->eq_removed = ctx->removed + r->removed_bytes;
5679     }
5680
5681   ctx->removed += r->removed_bytes;
5682   ientry->removed = ctx->removed;
5683   return 0;
5684 }
5685
5686 static void
5687 map_removal_by_action (text_action_list *action_list)
5688 {
5689   map_action_fn_context ctx;
5690
5691   ctx.removed = 0;
5692   ctx.map.n_entries = 0;
5693   ctx.map.entry = bfd_malloc (action_list_count (action_list) *
5694                               sizeof (removal_by_action_entry));
5695   ctx.eq_complete = FALSE;
5696
5697   splay_tree_foreach (action_list->tree, map_action_fn, &ctx);
5698   action_list->map = ctx.map;
5699 }
5700
5701 static int
5702 removed_by_actions_map (text_action_list *action_list, bfd_vma offset,
5703                         bfd_boolean before_fill)
5704 {
5705   unsigned a, b;
5706
5707   if (!action_list->map.entry)
5708     map_removal_by_action (action_list);
5709
5710   if (!action_list->map.n_entries)
5711     return 0;
5712
5713   a = 0;
5714   b = action_list->map.n_entries;
5715
5716   while (b - a > 1)
5717     {
5718       unsigned c = (a + b) / 2;
5719
5720       if (action_list->map.entry[c].offset <= offset)
5721         a = c;
5722       else
5723         b = c;
5724     }
5725
5726   if (action_list->map.entry[a].offset < offset)
5727     {
5728       return action_list->map.entry[a].removed;
5729     }
5730   else if (action_list->map.entry[a].offset == offset)
5731     {
5732       return before_fill ?
5733         action_list->map.entry[a].eq_removed_before_fill :
5734         action_list->map.entry[a].eq_removed;
5735     }
5736   else
5737     {
5738       return 0;
5739     }
5740 }
5741
5742 static bfd_vma
5743 offset_with_removed_text_map (text_action_list *action_list, bfd_vma offset)
5744 {
5745   int removed = removed_by_actions_map (action_list, offset, FALSE);
5746   return offset - removed;
5747 }
5748
5749
5750 /* The find_insn_action routine will only find non-fill actions.  */
5751
5752 static text_action *
5753 find_insn_action (text_action_list *action_list, bfd_vma offset)
5754 {
5755   static const text_action_t action[] =
5756     {
5757       ta_convert_longcall,
5758       ta_remove_longcall,
5759       ta_widen_insn,
5760       ta_narrow_insn,
5761       ta_remove_insn,
5762     };
5763   text_action a;
5764   unsigned i;
5765
5766   a.offset = offset;
5767   for (i = 0; i < sizeof (action) / sizeof (*action); ++i)
5768     {
5769       splay_tree_node node;
5770
5771       a.action = action[i];
5772       node = splay_tree_lookup (action_list->tree, (splay_tree_key)&a);
5773       if (node)
5774         return (text_action *)node->value;
5775     }
5776   return NULL;
5777 }
5778
5779
5780 #if DEBUG
5781
5782 static void
5783 print_action (FILE *fp, text_action *r)
5784 {
5785   const char *t = "unknown";
5786   switch (r->action)
5787     {
5788     case ta_remove_insn:
5789       t = "remove_insn"; break;
5790     case ta_remove_longcall:
5791       t = "remove_longcall"; break;
5792     case ta_convert_longcall:
5793       t = "convert_longcall"; break;
5794     case ta_narrow_insn:
5795       t = "narrow_insn"; break;
5796     case ta_widen_insn:
5797       t = "widen_insn"; break;
5798     case ta_fill:
5799       t = "fill"; break;
5800     case ta_none:
5801       t = "none"; break;
5802     case ta_remove_literal:
5803       t = "remove_literal"; break;
5804     case ta_add_literal:
5805       t = "add_literal"; break;
5806     }
5807
5808   fprintf (fp, "%s: %s[0x%lx] \"%s\" %d\n",
5809            r->sec->owner->filename,
5810            r->sec->name, (unsigned long) r->offset, t, r->removed_bytes);
5811 }
5812
5813 static int
5814 print_action_list_fn (splay_tree_node node, void *p)
5815 {
5816   text_action *r = (text_action *)node->value;
5817
5818   print_action (p, r);
5819   return 0;
5820 }
5821
5822 static void
5823 print_action_list (FILE *fp, text_action_list *action_list)
5824 {
5825   fprintf (fp, "Text Action\n");
5826   splay_tree_foreach (action_list->tree, print_action_list_fn, fp);
5827 }
5828
5829 #endif /* DEBUG */
5830
5831 \f
5832 /* Lists of literals being coalesced or removed.  */
5833
5834 /* In the usual case, the literal identified by "from" is being
5835    coalesced with another literal identified by "to".  If the literal is
5836    unused and is being removed altogether, "to.abfd" will be NULL.
5837    The removed_literal entries are kept on a per-section list, sorted
5838    by the "from" offset field.  */
5839
5840 typedef struct removed_literal_struct removed_literal;
5841 typedef struct removed_literal_map_entry_struct removed_literal_map_entry;
5842 typedef struct removed_literal_list_struct removed_literal_list;
5843
5844 struct removed_literal_struct
5845 {
5846   r_reloc from;
5847   r_reloc to;
5848   removed_literal *next;
5849 };
5850
5851 struct removed_literal_map_entry_struct
5852 {
5853   bfd_vma addr;
5854   removed_literal *literal;
5855 };
5856
5857 struct removed_literal_list_struct
5858 {
5859   removed_literal *head;
5860   removed_literal *tail;
5861
5862   unsigned n_map;
5863   removed_literal_map_entry *map;
5864 };
5865
5866
5867 /* Record that the literal at "from" is being removed.  If "to" is not
5868    NULL, the "from" literal is being coalesced with the "to" literal.  */
5869
5870 static void
5871 add_removed_literal (removed_literal_list *removed_list,
5872                      const r_reloc *from,
5873                      const r_reloc *to)
5874 {
5875   removed_literal *r, *new_r, *next_r;
5876
5877   new_r = (removed_literal *) bfd_zmalloc (sizeof (removed_literal));
5878
5879   new_r->from = *from;
5880   if (to)
5881     new_r->to = *to;
5882   else
5883     new_r->to.abfd = NULL;
5884   new_r->next = NULL;
5885
5886   r = removed_list->head;
5887   if (r == NULL)
5888     {
5889       removed_list->head = new_r;
5890       removed_list->tail = new_r;
5891     }
5892   /* Special check for common case of append.  */
5893   else if (removed_list->tail->from.target_offset < from->target_offset)
5894     {
5895       removed_list->tail->next = new_r;
5896       removed_list->tail = new_r;
5897     }
5898   else
5899     {
5900       while (r->from.target_offset < from->target_offset && r->next)
5901         {
5902           r = r->next;
5903         }
5904       next_r = r->next;
5905       r->next = new_r;
5906       new_r->next = next_r;
5907       if (next_r == NULL)
5908         removed_list->tail = new_r;
5909     }
5910 }
5911
5912 static void
5913 map_removed_literal (removed_literal_list *removed_list)
5914 {
5915   unsigned n_map = 0;
5916   unsigned i;
5917   removed_literal_map_entry *map = NULL;
5918   removed_literal *r = removed_list->head;
5919
5920   for (i = 0; r; ++i, r = r->next)
5921     {
5922       if (i == n_map)
5923         {
5924           n_map = (n_map * 2) + 2;
5925           map = bfd_realloc (map, n_map * sizeof (*map));
5926         }
5927       map[i].addr = r->from.target_offset;
5928       map[i].literal = r;
5929     }
5930   removed_list->map = map;
5931   removed_list->n_map = i;
5932 }
5933
5934 static int
5935 removed_literal_compare (const void *a, const void *b)
5936 {
5937   const removed_literal_map_entry *pa = a;
5938   const removed_literal_map_entry *pb = b;
5939
5940   if (pa->addr == pb->addr)
5941     return 0;
5942   else
5943     return pa->addr < pb->addr ? -1 : 1;
5944 }
5945
5946 /* Check if the list of removed literals contains an entry for the
5947    given address.  Return the entry if found.  */
5948
5949 static removed_literal *
5950 find_removed_literal (removed_literal_list *removed_list, bfd_vma addr)
5951 {
5952   removed_literal_map_entry *p;
5953   removed_literal *r = NULL;
5954
5955   if (removed_list->map == NULL)
5956     map_removed_literal (removed_list);
5957
5958   p = bsearch (&addr, removed_list->map, removed_list->n_map,
5959                sizeof (*removed_list->map), removed_literal_compare);
5960   if (p)
5961     {
5962       while (p != removed_list->map && (p - 1)->addr == addr)
5963         --p;
5964       r = p->literal;
5965     }
5966   return r;
5967 }
5968
5969
5970 #if DEBUG
5971
5972 static void
5973 print_removed_literals (FILE *fp, removed_literal_list *removed_list)
5974 {
5975   removed_literal *r;
5976   r = removed_list->head;
5977   if (r)
5978     fprintf (fp, "Removed Literals\n");
5979   for (; r != NULL; r = r->next)
5980     {
5981       print_r_reloc (fp, &r->from);
5982       fprintf (fp, " => ");
5983       if (r->to.abfd == NULL)
5984         fprintf (fp, "REMOVED");
5985       else
5986         print_r_reloc (fp, &r->to);
5987       fprintf (fp, "\n");
5988     }
5989 }
5990
5991 #endif /* DEBUG */
5992
5993 \f
5994 /* Per-section data for relaxation.  */
5995
5996 typedef struct reloc_bfd_fix_struct reloc_bfd_fix;
5997
5998 struct xtensa_relax_info_struct
5999 {
6000   bfd_boolean is_relaxable_literal_section;
6001   bfd_boolean is_relaxable_asm_section;
6002   int visited;                          /* Number of times visited.  */
6003
6004   source_reloc *src_relocs;             /* Array[src_count].  */
6005   int src_count;
6006   int src_next;                         /* Next src_relocs entry to assign.  */
6007
6008   removed_literal_list removed_list;
6009   text_action_list action_list;
6010
6011   reloc_bfd_fix *fix_list;
6012   reloc_bfd_fix *fix_array;
6013   unsigned fix_array_count;
6014
6015   /* Support for expanding the reloc array that is stored
6016      in the section structure.  If the relocations have been
6017      reallocated, the newly allocated relocations will be referenced
6018      here along with the actual size allocated.  The relocation
6019      count will always be found in the section structure.  */
6020   Elf_Internal_Rela *allocated_relocs;
6021   unsigned relocs_count;
6022   unsigned allocated_relocs_count;
6023 };
6024
6025 struct elf_xtensa_section_data
6026 {
6027   struct bfd_elf_section_data elf;
6028   xtensa_relax_info relax_info;
6029 };
6030
6031
6032 static bfd_boolean
6033 elf_xtensa_new_section_hook (bfd *abfd, asection *sec)
6034 {
6035   if (!sec->used_by_bfd)
6036     {
6037       struct elf_xtensa_section_data *sdata;
6038       bfd_size_type amt = sizeof (*sdata);
6039
6040       sdata = bfd_zalloc (abfd, amt);
6041       if (sdata == NULL)
6042         return FALSE;
6043       sec->used_by_bfd = sdata;
6044     }
6045
6046   return _bfd_elf_new_section_hook (abfd, sec);
6047 }
6048
6049
6050 static xtensa_relax_info *
6051 get_xtensa_relax_info (asection *sec)
6052 {
6053   struct elf_xtensa_section_data *section_data;
6054
6055   /* No info available if no section or if it is an output section.  */
6056   if (!sec || sec == sec->output_section)
6057     return NULL;
6058
6059   section_data = (struct elf_xtensa_section_data *) elf_section_data (sec);
6060   return &section_data->relax_info;
6061 }
6062
6063
6064 static void
6065 init_xtensa_relax_info (asection *sec)
6066 {
6067   xtensa_relax_info *relax_info = get_xtensa_relax_info (sec);
6068
6069   relax_info->is_relaxable_literal_section = FALSE;
6070   relax_info->is_relaxable_asm_section = FALSE;
6071   relax_info->visited = 0;
6072
6073   relax_info->src_relocs = NULL;
6074   relax_info->src_count = 0;
6075   relax_info->src_next = 0;
6076
6077   relax_info->removed_list.head = NULL;
6078   relax_info->removed_list.tail = NULL;
6079
6080   relax_info->action_list.tree = splay_tree_new (text_action_compare,
6081                                                  NULL, NULL);
6082   relax_info->action_list.map.n_entries = 0;
6083   relax_info->action_list.map.entry = NULL;
6084
6085   relax_info->fix_list = NULL;
6086   relax_info->fix_array = NULL;
6087   relax_info->fix_array_count = 0;
6088
6089   relax_info->allocated_relocs = NULL;
6090   relax_info->relocs_count = 0;
6091   relax_info->allocated_relocs_count = 0;
6092 }
6093
6094 \f
6095 /* Coalescing literals may require a relocation to refer to a section in
6096    a different input file, but the standard relocation information
6097    cannot express that.  Instead, the reloc_bfd_fix structures are used
6098    to "fix" the relocations that refer to sections in other input files.
6099    These structures are kept on per-section lists.  The "src_type" field
6100    records the relocation type in case there are multiple relocations on
6101    the same location.  FIXME: This is ugly; an alternative might be to
6102    add new symbols with the "owner" field to some other input file.  */
6103
6104 struct reloc_bfd_fix_struct
6105 {
6106   asection *src_sec;
6107   bfd_vma src_offset;
6108   unsigned src_type;                    /* Relocation type.  */
6109
6110   asection *target_sec;
6111   bfd_vma target_offset;
6112   bfd_boolean translated;
6113
6114   reloc_bfd_fix *next;
6115 };
6116
6117
6118 static reloc_bfd_fix *
6119 reloc_bfd_fix_init (asection *src_sec,
6120                     bfd_vma src_offset,
6121                     unsigned src_type,
6122                     asection *target_sec,
6123                     bfd_vma target_offset,
6124                     bfd_boolean translated)
6125 {
6126   reloc_bfd_fix *fix;
6127
6128   fix = (reloc_bfd_fix *) bfd_malloc (sizeof (reloc_bfd_fix));
6129   fix->src_sec = src_sec;
6130   fix->src_offset = src_offset;
6131   fix->src_type = src_type;
6132   fix->target_sec = target_sec;
6133   fix->target_offset = target_offset;
6134   fix->translated = translated;
6135
6136   return fix;
6137 }
6138
6139
6140 static void
6141 add_fix (asection *src_sec, reloc_bfd_fix *fix)
6142 {
6143   xtensa_relax_info *relax_info;
6144
6145   relax_info = get_xtensa_relax_info (src_sec);
6146   fix->next = relax_info->fix_list;
6147   relax_info->fix_list = fix;
6148 }
6149
6150
6151 static int
6152 fix_compare (const void *ap, const void *bp)
6153 {
6154   const reloc_bfd_fix *a = (const reloc_bfd_fix *) ap;
6155   const reloc_bfd_fix *b = (const reloc_bfd_fix *) bp;
6156
6157   if (a->src_offset != b->src_offset)
6158     return (a->src_offset - b->src_offset);
6159   return (a->src_type - b->src_type);
6160 }
6161
6162
6163 static void
6164 cache_fix_array (asection *sec)
6165 {
6166   unsigned i, count = 0;
6167   reloc_bfd_fix *r;
6168   xtensa_relax_info *relax_info = get_xtensa_relax_info (sec);
6169
6170   if (relax_info == NULL)
6171     return;
6172   if (relax_info->fix_list == NULL)
6173     return;
6174
6175   for (r = relax_info->fix_list; r != NULL; r = r->next)
6176     count++;
6177
6178   relax_info->fix_array =
6179     (reloc_bfd_fix *) bfd_malloc (sizeof (reloc_bfd_fix) * count);
6180   relax_info->fix_array_count = count;
6181
6182   r = relax_info->fix_list;
6183   for (i = 0; i < count; i++, r = r->next)
6184     {
6185       relax_info->fix_array[count - 1 - i] = *r;
6186       relax_info->fix_array[count - 1 - i].next = NULL;
6187     }
6188
6189   qsort (relax_info->fix_array, relax_info->fix_array_count,
6190          sizeof (reloc_bfd_fix), fix_compare);
6191 }
6192
6193
6194 static reloc_bfd_fix *
6195 get_bfd_fix (asection *sec, bfd_vma offset, unsigned type)
6196 {
6197   xtensa_relax_info *relax_info = get_xtensa_relax_info (sec);
6198   reloc_bfd_fix *rv;
6199   reloc_bfd_fix key;
6200
6201   if (relax_info == NULL)
6202     return NULL;
6203   if (relax_info->fix_list == NULL)
6204     return NULL;
6205
6206   if (relax_info->fix_array == NULL)
6207     cache_fix_array (sec);
6208
6209   key.src_offset = offset;
6210   key.src_type = type;
6211   rv = bsearch (&key, relax_info->fix_array,  relax_info->fix_array_count,
6212                 sizeof (reloc_bfd_fix), fix_compare);
6213   return rv;
6214 }
6215
6216 \f
6217 /* Section caching.  */
6218
6219 typedef struct section_cache_struct section_cache_t;
6220
6221 struct section_cache_struct
6222 {
6223   asection *sec;
6224
6225   bfd_byte *contents;           /* Cache of the section contents.  */
6226   bfd_size_type content_length;
6227
6228   property_table_entry *ptbl;   /* Cache of the section property table.  */
6229   unsigned pte_count;
6230
6231   Elf_Internal_Rela *relocs;    /* Cache of the section relocations.  */
6232   unsigned reloc_count;
6233 };
6234
6235
6236 static void
6237 init_section_cache (section_cache_t *sec_cache)
6238 {
6239   memset (sec_cache, 0, sizeof (*sec_cache));
6240 }
6241
6242
6243 static void
6244 free_section_cache (section_cache_t *sec_cache)
6245 {
6246   if (sec_cache->sec)
6247     {
6248       release_contents (sec_cache->sec, sec_cache->contents);
6249       release_internal_relocs (sec_cache->sec, sec_cache->relocs);
6250       if (sec_cache->ptbl)
6251         free (sec_cache->ptbl);
6252     }
6253 }
6254
6255
6256 static bfd_boolean
6257 section_cache_section (section_cache_t *sec_cache,
6258                        asection *sec,
6259                        struct bfd_link_info *link_info)
6260 {
6261   bfd *abfd;
6262   property_table_entry *prop_table = NULL;
6263   int ptblsize = 0;
6264   bfd_byte *contents = NULL;
6265   Elf_Internal_Rela *internal_relocs = NULL;
6266   bfd_size_type sec_size;
6267
6268   if (sec == NULL)
6269     return FALSE;
6270   if (sec == sec_cache->sec)
6271     return TRUE;
6272
6273   abfd = sec->owner;
6274   sec_size = bfd_get_section_limit (abfd, sec);
6275
6276   /* Get the contents.  */
6277   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
6278   if (contents == NULL && sec_size != 0)
6279     goto err;
6280
6281   /* Get the relocations.  */
6282   internal_relocs = retrieve_internal_relocs (abfd, sec,
6283                                               link_info->keep_memory);
6284
6285   /* Get the entry table.  */
6286   ptblsize = xtensa_read_table_entries (abfd, sec, &prop_table,
6287                                         XTENSA_PROP_SEC_NAME, FALSE);
6288   if (ptblsize < 0)
6289     goto err;
6290
6291   /* Fill in the new section cache.  */
6292   free_section_cache (sec_cache);
6293   init_section_cache (sec_cache);
6294
6295   sec_cache->sec = sec;
6296   sec_cache->contents = contents;
6297   sec_cache->content_length = sec_size;
6298   sec_cache->relocs = internal_relocs;
6299   sec_cache->reloc_count = sec->reloc_count;
6300   sec_cache->pte_count = ptblsize;
6301   sec_cache->ptbl = prop_table;
6302
6303   return TRUE;
6304
6305  err:
6306   release_contents (sec, contents);
6307   release_internal_relocs (sec, internal_relocs);
6308   if (prop_table)
6309     free (prop_table);
6310   return FALSE;
6311 }
6312
6313 \f
6314 /* Extended basic blocks.  */
6315
6316 /* An ebb_struct represents an Extended Basic Block.  Within this
6317    range, we guarantee that all instructions are decodable, the
6318    property table entries are contiguous, and no property table
6319    specifies a segment that cannot have instructions moved.  This
6320    structure contains caches of the contents, property table and
6321    relocations for the specified section for easy use.  The range is
6322    specified by ranges of indices for the byte offset, property table
6323    offsets and relocation offsets.  These must be consistent.  */
6324
6325 typedef struct ebb_struct ebb_t;
6326
6327 struct ebb_struct
6328 {
6329   asection *sec;
6330
6331   bfd_byte *contents;           /* Cache of the section contents.  */
6332   bfd_size_type content_length;
6333
6334   property_table_entry *ptbl;   /* Cache of the section property table.  */
6335   unsigned pte_count;
6336
6337   Elf_Internal_Rela *relocs;    /* Cache of the section relocations.  */
6338   unsigned reloc_count;
6339
6340   bfd_vma start_offset;         /* Offset in section.  */
6341   unsigned start_ptbl_idx;      /* Offset in the property table.  */
6342   unsigned start_reloc_idx;     /* Offset in the relocations.  */
6343
6344   bfd_vma end_offset;
6345   unsigned end_ptbl_idx;
6346   unsigned end_reloc_idx;
6347
6348   bfd_boolean ends_section;     /* Is this the last ebb in a section?  */
6349
6350   /* The unreachable property table at the end of this set of blocks;
6351      NULL if the end is not an unreachable block.  */
6352   property_table_entry *ends_unreachable;
6353 };
6354
6355
6356 enum ebb_target_enum
6357 {
6358   EBB_NO_ALIGN = 0,
6359   EBB_DESIRE_TGT_ALIGN,
6360   EBB_REQUIRE_TGT_ALIGN,
6361   EBB_REQUIRE_LOOP_ALIGN,
6362   EBB_REQUIRE_ALIGN
6363 };
6364
6365
6366 /* proposed_action_struct is similar to the text_action_struct except
6367    that is represents a potential transformation, not one that will
6368    occur.  We build a list of these for an extended basic block
6369    and use them to compute the actual actions desired.  We must be
6370    careful that the entire set of actual actions we perform do not
6371    break any relocations that would fit if the actions were not
6372    performed.  */
6373
6374 typedef struct proposed_action_struct proposed_action;
6375
6376 struct proposed_action_struct
6377 {
6378   enum ebb_target_enum align_type; /* for the target alignment */
6379   bfd_vma alignment_pow;
6380   text_action_t action;
6381   bfd_vma offset;
6382   int removed_bytes;
6383   bfd_boolean do_action; /* If false, then we will not perform the action.  */
6384 };
6385
6386
6387 /* The ebb_constraint_struct keeps a set of proposed actions for an
6388    extended basic block.   */
6389
6390 typedef struct ebb_constraint_struct ebb_constraint;
6391
6392 struct ebb_constraint_struct
6393 {
6394   ebb_t ebb;
6395   bfd_boolean start_movable;
6396
6397   /* Bytes of extra space at the beginning if movable.  */
6398   int start_extra_space;
6399
6400   enum ebb_target_enum start_align;
6401
6402   bfd_boolean end_movable;
6403
6404   /* Bytes of extra space at the end if movable.  */
6405   int end_extra_space;
6406
6407   unsigned action_count;
6408   unsigned action_allocated;
6409
6410   /* Array of proposed actions.  */
6411   proposed_action *actions;
6412
6413   /* Action alignments -- one for each proposed action.  */
6414   enum ebb_target_enum *action_aligns;
6415 };
6416
6417
6418 static void
6419 init_ebb_constraint (ebb_constraint *c)
6420 {
6421   memset (c, 0, sizeof (ebb_constraint));
6422 }
6423
6424
6425 static void
6426 free_ebb_constraint (ebb_constraint *c)
6427 {
6428   if (c->actions)
6429     free (c->actions);
6430 }
6431
6432
6433 static void
6434 init_ebb (ebb_t *ebb,
6435           asection *sec,
6436           bfd_byte *contents,
6437           bfd_size_type content_length,
6438           property_table_entry *prop_table,
6439           unsigned ptblsize,
6440           Elf_Internal_Rela *internal_relocs,
6441           unsigned reloc_count)
6442 {
6443   memset (ebb, 0, sizeof (ebb_t));
6444   ebb->sec = sec;
6445   ebb->contents = contents;
6446   ebb->content_length = content_length;
6447   ebb->ptbl = prop_table;
6448   ebb->pte_count = ptblsize;
6449   ebb->relocs = internal_relocs;
6450   ebb->reloc_count = reloc_count;
6451   ebb->start_offset = 0;
6452   ebb->end_offset = ebb->content_length - 1;
6453   ebb->start_ptbl_idx = 0;
6454   ebb->end_ptbl_idx = ptblsize;
6455   ebb->start_reloc_idx = 0;
6456   ebb->end_reloc_idx = reloc_count;
6457 }
6458
6459
6460 /* Extend the ebb to all decodable contiguous sections.  The algorithm
6461    for building a basic block around an instruction is to push it
6462    forward until we hit the end of a section, an unreachable block or
6463    a block that cannot be transformed.  Then we push it backwards
6464    searching for similar conditions.  */
6465
6466 static bfd_boolean extend_ebb_bounds_forward (ebb_t *);
6467 static bfd_boolean extend_ebb_bounds_backward (ebb_t *);
6468 static bfd_size_type insn_block_decodable_len
6469   (bfd_byte *, bfd_size_type, bfd_vma, bfd_size_type);
6470
6471 static bfd_boolean
6472 extend_ebb_bounds (ebb_t *ebb)
6473 {
6474   if (!extend_ebb_bounds_forward (ebb))
6475     return FALSE;
6476   if (!extend_ebb_bounds_backward (ebb))
6477     return FALSE;
6478   return TRUE;
6479 }
6480
6481
6482 static bfd_boolean
6483 extend_ebb_bounds_forward (ebb_t *ebb)
6484 {
6485   property_table_entry *the_entry, *new_entry;
6486
6487   the_entry = &ebb->ptbl[ebb->end_ptbl_idx];
6488
6489   /* Stop when (1) we cannot decode an instruction, (2) we are at
6490      the end of the property tables, (3) we hit a non-contiguous property
6491      table entry, (4) we hit a NO_TRANSFORM region.  */
6492
6493   while (1)
6494     {
6495       bfd_vma entry_end;
6496       bfd_size_type insn_block_len;
6497
6498       entry_end = the_entry->address - ebb->sec->vma + the_entry->size;
6499       insn_block_len =
6500         insn_block_decodable_len (ebb->contents, ebb->content_length,
6501                                   ebb->end_offset,
6502                                   entry_end - ebb->end_offset);
6503       if (insn_block_len != (entry_end - ebb->end_offset))
6504         {
6505           _bfd_error_handler
6506             /* xgettext:c-format */
6507             (_("%pB(%pA+%#" PRIx64 "): could not decode instruction; "
6508                "possible configuration mismatch"),
6509              ebb->sec->owner, ebb->sec,
6510              (uint64_t) (ebb->end_offset + insn_block_len));
6511           return FALSE;
6512         }
6513       ebb->end_offset += insn_block_len;
6514
6515       if (ebb->end_offset == ebb->sec->size)
6516         ebb->ends_section = TRUE;
6517
6518       /* Update the reloc counter.  */
6519       while (ebb->end_reloc_idx + 1 < ebb->reloc_count
6520              && (ebb->relocs[ebb->end_reloc_idx + 1].r_offset
6521                  < ebb->end_offset))
6522         {
6523           ebb->end_reloc_idx++;
6524         }
6525
6526       if (ebb->end_ptbl_idx + 1 == ebb->pte_count)
6527         return TRUE;
6528
6529       new_entry = &ebb->ptbl[ebb->end_ptbl_idx + 1];
6530       if (((new_entry->flags & XTENSA_PROP_INSN) == 0)
6531           || ((new_entry->flags & XTENSA_PROP_NO_TRANSFORM) != 0)
6532           || ((the_entry->flags & XTENSA_PROP_ALIGN) != 0))
6533         break;
6534
6535       if (the_entry->address + the_entry->size != new_entry->address)
6536         break;
6537
6538       the_entry = new_entry;
6539       ebb->end_ptbl_idx++;
6540     }
6541
6542   /* Quick check for an unreachable or end of file just at the end.  */
6543   if (ebb->end_ptbl_idx + 1 == ebb->pte_count)
6544     {
6545       if (ebb->end_offset == ebb->content_length)
6546         ebb->ends_section = TRUE;
6547     }
6548   else
6549     {
6550       new_entry = &ebb->ptbl[ebb->end_ptbl_idx + 1];
6551       if ((new_entry->flags & XTENSA_PROP_UNREACHABLE) != 0
6552           && the_entry->address + the_entry->size == new_entry->address)
6553         ebb->ends_unreachable = new_entry;
6554     }
6555
6556   /* Any other ending requires exact alignment.  */
6557   return TRUE;
6558 }
6559
6560
6561 static bfd_boolean
6562 extend_ebb_bounds_backward (ebb_t *ebb)
6563 {
6564   property_table_entry *the_entry, *new_entry;
6565
6566   the_entry = &ebb->ptbl[ebb->start_ptbl_idx];
6567
6568   /* Stop when (1) we cannot decode the instructions in the current entry.
6569      (2) we are at the beginning of the property tables, (3) we hit a
6570      non-contiguous property table entry, (4) we hit a NO_TRANSFORM region.  */
6571
6572   while (1)
6573     {
6574       bfd_vma block_begin;
6575       bfd_size_type insn_block_len;
6576
6577       block_begin = the_entry->address - ebb->sec->vma;
6578       insn_block_len =
6579         insn_block_decodable_len (ebb->contents, ebb->content_length,
6580                                   block_begin,
6581                                   ebb->start_offset - block_begin);
6582       if (insn_block_len != ebb->start_offset - block_begin)
6583         {
6584           _bfd_error_handler
6585             /* xgettext:c-format */
6586             (_("%pB(%pA+%#" PRIx64 "): could not decode instruction; "
6587                "possible configuration mismatch"),
6588              ebb->sec->owner, ebb->sec,
6589              (uint64_t) (ebb->end_offset + insn_block_len));
6590           return FALSE;
6591         }
6592       ebb->start_offset -= insn_block_len;
6593
6594       /* Update the reloc counter.  */
6595       while (ebb->start_reloc_idx > 0
6596              && (ebb->relocs[ebb->start_reloc_idx - 1].r_offset
6597                  >= ebb->start_offset))
6598         {
6599           ebb->start_reloc_idx--;
6600         }
6601
6602       if (ebb->start_ptbl_idx == 0)
6603         return TRUE;
6604
6605       new_entry = &ebb->ptbl[ebb->start_ptbl_idx - 1];
6606       if ((new_entry->flags & XTENSA_PROP_INSN) == 0
6607           || ((new_entry->flags & XTENSA_PROP_NO_TRANSFORM) != 0)
6608           || ((new_entry->flags & XTENSA_PROP_ALIGN) != 0))
6609         return TRUE;
6610       if (new_entry->address + new_entry->size != the_entry->address)
6611         return TRUE;
6612
6613       the_entry = new_entry;
6614       ebb->start_ptbl_idx--;
6615     }
6616   return TRUE;
6617 }
6618
6619
6620 static bfd_size_type
6621 insn_block_decodable_len (bfd_byte *contents,
6622                           bfd_size_type content_len,
6623                           bfd_vma block_offset,
6624                           bfd_size_type block_len)
6625 {
6626   bfd_vma offset = block_offset;
6627
6628   while (offset < block_offset + block_len)
6629     {
6630       bfd_size_type insn_len = 0;
6631
6632       insn_len = insn_decode_len (contents, content_len, offset);
6633       if (insn_len == 0)
6634         return (offset - block_offset);
6635       offset += insn_len;
6636     }
6637   return (offset - block_offset);
6638 }
6639
6640
6641 static void
6642 ebb_propose_action (ebb_constraint *c,
6643                     enum ebb_target_enum align_type,
6644                     bfd_vma alignment_pow,
6645                     text_action_t action,
6646                     bfd_vma offset,
6647                     int removed_bytes,
6648                     bfd_boolean do_action)
6649 {
6650   proposed_action *act;
6651
6652   if (c->action_allocated <= c->action_count)
6653     {
6654       unsigned new_allocated, i;
6655       proposed_action *new_actions;
6656
6657       new_allocated = (c->action_count + 2) * 2;
6658       new_actions = (proposed_action *)
6659         bfd_zmalloc (sizeof (proposed_action) * new_allocated);
6660
6661       for (i = 0; i < c->action_count; i++)
6662         new_actions[i] = c->actions[i];
6663       if (c->actions)
6664         free (c->actions);
6665       c->actions = new_actions;
6666       c->action_allocated = new_allocated;
6667     }
6668
6669   act = &c->actions[c->action_count];
6670   act->align_type = align_type;
6671   act->alignment_pow = alignment_pow;
6672   act->action = action;
6673   act->offset = offset;
6674   act->removed_bytes = removed_bytes;
6675   act->do_action = do_action;
6676
6677   c->action_count++;
6678 }
6679
6680 \f
6681 /* Access to internal relocations, section contents and symbols.  */
6682
6683 /* During relaxation, we need to modify relocations, section contents,
6684    and symbol definitions, and we need to keep the original values from
6685    being reloaded from the input files, i.e., we need to "pin" the
6686    modified values in memory.  We also want to continue to observe the
6687    setting of the "keep-memory" flag.  The following functions wrap the
6688    standard BFD functions to take care of this for us.  */
6689
6690 static Elf_Internal_Rela *
6691 retrieve_internal_relocs (bfd *abfd, asection *sec, bfd_boolean keep_memory)
6692 {
6693   Elf_Internal_Rela *internal_relocs;
6694
6695   if ((sec->flags & SEC_LINKER_CREATED) != 0)
6696     return NULL;
6697
6698   internal_relocs = elf_section_data (sec)->relocs;
6699   if (internal_relocs == NULL)
6700     internal_relocs = (_bfd_elf_link_read_relocs
6701                        (abfd, sec, NULL, NULL, keep_memory));
6702   return internal_relocs;
6703 }
6704
6705
6706 static void
6707 pin_internal_relocs (asection *sec, Elf_Internal_Rela *internal_relocs)
6708 {
6709   elf_section_data (sec)->relocs = internal_relocs;
6710 }
6711
6712
6713 static void
6714 release_internal_relocs (asection *sec, Elf_Internal_Rela *internal_relocs)
6715 {
6716   if (internal_relocs
6717       && elf_section_data (sec)->relocs != internal_relocs)
6718     free (internal_relocs);
6719 }
6720
6721
6722 static bfd_byte *
6723 retrieve_contents (bfd *abfd, asection *sec, bfd_boolean keep_memory)
6724 {
6725   bfd_byte *contents;
6726   bfd_size_type sec_size;
6727
6728   sec_size = bfd_get_section_limit (abfd, sec);
6729   contents = elf_section_data (sec)->this_hdr.contents;
6730
6731   if (contents == NULL && sec_size != 0)
6732     {
6733       if (!bfd_malloc_and_get_section (abfd, sec, &contents))
6734         {
6735           if (contents)
6736             free (contents);
6737           return NULL;
6738         }
6739       if (keep_memory)
6740         elf_section_data (sec)->this_hdr.contents = contents;
6741     }
6742   return contents;
6743 }
6744
6745
6746 static void
6747 pin_contents (asection *sec, bfd_byte *contents)
6748 {
6749   elf_section_data (sec)->this_hdr.contents = contents;
6750 }
6751
6752
6753 static void
6754 release_contents (asection *sec, bfd_byte *contents)
6755 {
6756   if (contents && elf_section_data (sec)->this_hdr.contents != contents)
6757     free (contents);
6758 }
6759
6760
6761 static Elf_Internal_Sym *
6762 retrieve_local_syms (bfd *input_bfd)
6763 {
6764   Elf_Internal_Shdr *symtab_hdr;
6765   Elf_Internal_Sym *isymbuf;
6766   size_t locsymcount;
6767
6768   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
6769   locsymcount = symtab_hdr->sh_info;
6770
6771   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
6772   if (isymbuf == NULL && locsymcount != 0)
6773     isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
6774                                     NULL, NULL, NULL);
6775
6776   /* Save the symbols for this input file so they won't be read again.  */
6777   if (isymbuf && isymbuf != (Elf_Internal_Sym *) symtab_hdr->contents)
6778     symtab_hdr->contents = (unsigned char *) isymbuf;
6779
6780   return isymbuf;
6781 }
6782
6783 \f
6784 /* Code for link-time relaxation.  */
6785
6786 /* Initialization for relaxation: */
6787 static bfd_boolean analyze_relocations (struct bfd_link_info *);
6788 static bfd_boolean find_relaxable_sections
6789   (bfd *, asection *, struct bfd_link_info *, bfd_boolean *);
6790 static bfd_boolean collect_source_relocs
6791   (bfd *, asection *, struct bfd_link_info *);
6792 static bfd_boolean is_resolvable_asm_expansion
6793   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *, struct bfd_link_info *,
6794    bfd_boolean *);
6795 static Elf_Internal_Rela *find_associated_l32r_irel
6796   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *, Elf_Internal_Rela *);
6797 static bfd_boolean compute_text_actions
6798   (bfd *, asection *, struct bfd_link_info *);
6799 static bfd_boolean compute_ebb_proposed_actions (ebb_constraint *);
6800 static bfd_boolean compute_ebb_actions (ebb_constraint *);
6801 typedef struct reloc_range_list_struct reloc_range_list;
6802 static bfd_boolean check_section_ebb_pcrels_fit
6803   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *,
6804    reloc_range_list *, const ebb_constraint *,
6805    const xtensa_opcode *);
6806 static bfd_boolean check_section_ebb_reduces (const ebb_constraint *);
6807 static void text_action_add_proposed
6808   (text_action_list *, const ebb_constraint *, asection *);
6809
6810 /* First pass: */
6811 static bfd_boolean compute_removed_literals
6812   (bfd *, asection *, struct bfd_link_info *, value_map_hash_table *);
6813 static Elf_Internal_Rela *get_irel_at_offset
6814   (asection *, Elf_Internal_Rela *, bfd_vma);
6815 static bfd_boolean is_removable_literal
6816   (const source_reloc *, int, const source_reloc *, int, asection *,
6817    property_table_entry *, int);
6818 static bfd_boolean remove_dead_literal
6819   (bfd *, asection *, struct bfd_link_info *, Elf_Internal_Rela *,
6820    Elf_Internal_Rela *, source_reloc *, property_table_entry *, int);
6821 static bfd_boolean identify_literal_placement
6822   (bfd *, asection *, bfd_byte *, struct bfd_link_info *,
6823    value_map_hash_table *, bfd_boolean *, Elf_Internal_Rela *, int,
6824    source_reloc *, property_table_entry *, int, section_cache_t *,
6825    bfd_boolean);
6826 static bfd_boolean relocations_reach (source_reloc *, int, const r_reloc *);
6827 static bfd_boolean coalesce_shared_literal
6828   (asection *, source_reloc *, property_table_entry *, int, value_map *);
6829 static bfd_boolean move_shared_literal
6830   (asection *, struct bfd_link_info *, source_reloc *, property_table_entry *,
6831    int, const r_reloc *, const literal_value *, section_cache_t *);
6832
6833 /* Second pass: */
6834 static bfd_boolean relax_section (bfd *, asection *, struct bfd_link_info *);
6835 static bfd_boolean translate_section_fixes (asection *);
6836 static bfd_boolean translate_reloc_bfd_fix (reloc_bfd_fix *);
6837 static asection *translate_reloc (const r_reloc *, r_reloc *, asection *);
6838 static void shrink_dynamic_reloc_sections
6839   (struct bfd_link_info *, bfd *, asection *, Elf_Internal_Rela *);
6840 static bfd_boolean move_literal
6841   (bfd *, struct bfd_link_info *, asection *, bfd_vma, bfd_byte *,
6842    xtensa_relax_info *, Elf_Internal_Rela **, const literal_value *);
6843 static bfd_boolean relax_property_section
6844   (bfd *, asection *, struct bfd_link_info *);
6845
6846 /* Third pass: */
6847 static bfd_boolean relax_section_symbols (bfd *, asection *);
6848
6849
6850 static bfd_boolean
6851 elf_xtensa_relax_section (bfd *abfd,
6852                           asection *sec,
6853                           struct bfd_link_info *link_info,
6854                           bfd_boolean *again)
6855 {
6856   static value_map_hash_table *values = NULL;
6857   static bfd_boolean relocations_analyzed = FALSE;
6858   xtensa_relax_info *relax_info;
6859
6860   if (!relocations_analyzed)
6861     {
6862       /* Do some overall initialization for relaxation.  */
6863       values = value_map_hash_table_init ();
6864       if (values == NULL)
6865         return FALSE;
6866       relaxing_section = TRUE;
6867       if (!analyze_relocations (link_info))
6868         return FALSE;
6869       relocations_analyzed = TRUE;
6870     }
6871   *again = FALSE;
6872
6873   /* Don't mess with linker-created sections.  */
6874   if ((sec->flags & SEC_LINKER_CREATED) != 0)
6875     return TRUE;
6876
6877   relax_info = get_xtensa_relax_info (sec);
6878   BFD_ASSERT (relax_info != NULL);
6879
6880   switch (relax_info->visited)
6881     {
6882     case 0:
6883       /* Note: It would be nice to fold this pass into
6884          analyze_relocations, but it is important for this step that the
6885          sections be examined in link order.  */
6886       if (!compute_removed_literals (abfd, sec, link_info, values))
6887         return FALSE;
6888       *again = TRUE;
6889       break;
6890
6891     case 1:
6892       if (values)
6893         value_map_hash_table_delete (values);
6894       values = NULL;
6895       if (!relax_section (abfd, sec, link_info))
6896         return FALSE;
6897       *again = TRUE;
6898       break;
6899
6900     case 2:
6901       if (!relax_section_symbols (abfd, sec))
6902         return FALSE;
6903       break;
6904     }
6905
6906   relax_info->visited++;
6907   return TRUE;
6908 }
6909
6910 \f
6911 /* Initialization for relaxation.  */
6912
6913 /* This function is called once at the start of relaxation.  It scans
6914    all the input sections and marks the ones that are relaxable (i.e.,
6915    literal sections with L32R relocations against them), and then
6916    collects source_reloc information for all the relocations against
6917    those relaxable sections.  During this process, it also detects
6918    longcalls, i.e., calls relaxed by the assembler into indirect
6919    calls, that can be optimized back into direct calls.  Within each
6920    extended basic block (ebb) containing an optimized longcall, it
6921    computes a set of "text actions" that can be performed to remove
6922    the L32R associated with the longcall while optionally preserving
6923    branch target alignments.  */
6924
6925 static bfd_boolean
6926 analyze_relocations (struct bfd_link_info *link_info)
6927 {
6928   bfd *abfd;
6929   asection *sec;
6930   bfd_boolean is_relaxable = FALSE;
6931
6932   /* Initialize the per-section relaxation info.  */
6933   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link.next)
6934     for (sec = abfd->sections; sec != NULL; sec = sec->next)
6935       {
6936         init_xtensa_relax_info (sec);
6937       }
6938
6939   /* Mark relaxable sections (and count relocations against each one).  */
6940   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link.next)
6941     for (sec = abfd->sections; sec != NULL; sec = sec->next)
6942       {
6943         if (!find_relaxable_sections (abfd, sec, link_info, &is_relaxable))
6944           return FALSE;
6945       }
6946
6947   /* Bail out if there are no relaxable sections.  */
6948   if (!is_relaxable)
6949     return TRUE;
6950
6951   /* Allocate space for source_relocs.  */
6952   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link.next)
6953     for (sec = abfd->sections; sec != NULL; sec = sec->next)
6954       {
6955         xtensa_relax_info *relax_info;
6956
6957         relax_info = get_xtensa_relax_info (sec);
6958         if (relax_info->is_relaxable_literal_section
6959             || relax_info->is_relaxable_asm_section)
6960           {
6961             relax_info->src_relocs = (source_reloc *)
6962               bfd_malloc (relax_info->src_count * sizeof (source_reloc));
6963           }
6964         else
6965           relax_info->src_count = 0;
6966       }
6967
6968   /* Collect info on relocations against each relaxable section.  */
6969   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link.next)
6970     for (sec = abfd->sections; sec != NULL; sec = sec->next)
6971       {
6972         if (!collect_source_relocs (abfd, sec, link_info))
6973           return FALSE;
6974       }
6975
6976   /* Compute the text actions.  */
6977   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link.next)
6978     for (sec = abfd->sections; sec != NULL; sec = sec->next)
6979       {
6980         if (!compute_text_actions (abfd, sec, link_info))
6981           return FALSE;
6982       }
6983
6984   return TRUE;
6985 }
6986
6987
6988 /* Find all the sections that might be relaxed.  The motivation for
6989    this pass is that collect_source_relocs() needs to record _all_ the
6990    relocations that target each relaxable section.  That is expensive
6991    and unnecessary unless the target section is actually going to be
6992    relaxed.  This pass identifies all such sections by checking if
6993    they have L32Rs pointing to them.  In the process, the total number
6994    of relocations targeting each section is also counted so that we
6995    know how much space to allocate for source_relocs against each
6996    relaxable literal section.  */
6997
6998 static bfd_boolean
6999 find_relaxable_sections (bfd *abfd,
7000                          asection *sec,
7001                          struct bfd_link_info *link_info,
7002                          bfd_boolean *is_relaxable_p)
7003 {
7004   Elf_Internal_Rela *internal_relocs;
7005   bfd_byte *contents;
7006   bfd_boolean ok = TRUE;
7007   unsigned i;
7008   xtensa_relax_info *source_relax_info;
7009   bfd_boolean is_l32r_reloc;
7010
7011   internal_relocs = retrieve_internal_relocs (abfd, sec,
7012                                               link_info->keep_memory);
7013   if (internal_relocs == NULL)
7014     return ok;
7015
7016   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
7017   if (contents == NULL && sec->size != 0)
7018     {
7019       ok = FALSE;
7020       goto error_return;
7021     }
7022
7023   source_relax_info = get_xtensa_relax_info (sec);
7024   for (i = 0; i < sec->reloc_count; i++)
7025     {
7026       Elf_Internal_Rela *irel = &internal_relocs[i];
7027       r_reloc r_rel;
7028       asection *target_sec;
7029       xtensa_relax_info *target_relax_info;
7030
7031       /* If this section has not already been marked as "relaxable", and
7032          if it contains any ASM_EXPAND relocations (marking expanded
7033          longcalls) that can be optimized into direct calls, then mark
7034          the section as "relaxable".  */
7035       if (source_relax_info
7036           && !source_relax_info->is_relaxable_asm_section
7037           && ELF32_R_TYPE (irel->r_info) == R_XTENSA_ASM_EXPAND)
7038         {
7039           bfd_boolean is_reachable = FALSE;
7040           if (is_resolvable_asm_expansion (abfd, sec, contents, irel,
7041                                            link_info, &is_reachable)
7042               && is_reachable)
7043             {
7044               source_relax_info->is_relaxable_asm_section = TRUE;
7045               *is_relaxable_p = TRUE;
7046             }
7047         }
7048
7049       r_reloc_init (&r_rel, abfd, irel, contents,
7050                     bfd_get_section_limit (abfd, sec));
7051
7052       target_sec = r_reloc_get_section (&r_rel);
7053       target_relax_info = get_xtensa_relax_info (target_sec);
7054       if (!target_relax_info)
7055         continue;
7056
7057       /* Count PC-relative operand relocations against the target section.
7058          Note: The conditions tested here must match the conditions under
7059          which init_source_reloc is called in collect_source_relocs().  */
7060       is_l32r_reloc = FALSE;
7061       if (is_operand_relocation (ELF32_R_TYPE (irel->r_info)))
7062         {
7063           xtensa_opcode opcode =
7064             get_relocation_opcode (abfd, sec, contents, irel);
7065           if (opcode != XTENSA_UNDEFINED)
7066             {
7067               is_l32r_reloc = (opcode == get_l32r_opcode ());
7068               if (!is_alt_relocation (ELF32_R_TYPE (irel->r_info))
7069                   || is_l32r_reloc)
7070                 target_relax_info->src_count++;
7071             }
7072         }
7073
7074       if (is_l32r_reloc && r_reloc_is_defined (&r_rel))
7075         {
7076           /* Mark the target section as relaxable.  */
7077           target_relax_info->is_relaxable_literal_section = TRUE;
7078           *is_relaxable_p = TRUE;
7079         }
7080     }
7081
7082  error_return:
7083   release_contents (sec, contents);
7084   release_internal_relocs (sec, internal_relocs);
7085   return ok;
7086 }
7087
7088
7089 /* Record _all_ the relocations that point to relaxable sections, and
7090    get rid of ASM_EXPAND relocs by either converting them to
7091    ASM_SIMPLIFY or by removing them.  */
7092
7093 static bfd_boolean
7094 collect_source_relocs (bfd *abfd,
7095                        asection *sec,
7096                        struct bfd_link_info *link_info)
7097 {
7098   Elf_Internal_Rela *internal_relocs;
7099   bfd_byte *contents;
7100   bfd_boolean ok = TRUE;
7101   unsigned i;
7102   bfd_size_type sec_size;
7103
7104   internal_relocs = retrieve_internal_relocs (abfd, sec,
7105                                               link_info->keep_memory);
7106   if (internal_relocs == NULL)
7107     return ok;
7108
7109   sec_size = bfd_get_section_limit (abfd, sec);
7110   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
7111   if (contents == NULL && sec_size != 0)
7112     {
7113       ok = FALSE;
7114       goto error_return;
7115     }
7116
7117   /* Record relocations against relaxable literal sections.  */
7118   for (i = 0; i < sec->reloc_count; i++)
7119     {
7120       Elf_Internal_Rela *irel = &internal_relocs[i];
7121       r_reloc r_rel;
7122       asection *target_sec;
7123       xtensa_relax_info *target_relax_info;
7124
7125       r_reloc_init (&r_rel, abfd, irel, contents, sec_size);
7126
7127       target_sec = r_reloc_get_section (&r_rel);
7128       target_relax_info = get_xtensa_relax_info (target_sec);
7129
7130       if (target_relax_info
7131           && (target_relax_info->is_relaxable_literal_section
7132               || target_relax_info->is_relaxable_asm_section))
7133         {
7134           xtensa_opcode opcode = XTENSA_UNDEFINED;
7135           int opnd = -1;
7136           bfd_boolean is_abs_literal = FALSE;
7137
7138           if (is_alt_relocation (ELF32_R_TYPE (irel->r_info)))
7139             {
7140               /* None of the current alternate relocs are PC-relative,
7141                  and only PC-relative relocs matter here.  However, we
7142                  still need to record the opcode for literal
7143                  coalescing.  */
7144               opcode = get_relocation_opcode (abfd, sec, contents, irel);
7145               if (opcode == get_l32r_opcode ())
7146                 {
7147                   is_abs_literal = TRUE;
7148                   opnd = 1;
7149                 }
7150               else
7151                 opcode = XTENSA_UNDEFINED;
7152             }
7153           else if (is_operand_relocation (ELF32_R_TYPE (irel->r_info)))
7154             {
7155               opcode = get_relocation_opcode (abfd, sec, contents, irel);
7156               opnd = get_relocation_opnd (opcode, ELF32_R_TYPE (irel->r_info));
7157             }
7158
7159           if (opcode != XTENSA_UNDEFINED)
7160             {
7161               int src_next = target_relax_info->src_next++;
7162               source_reloc *s_reloc = &target_relax_info->src_relocs[src_next];
7163
7164               init_source_reloc (s_reloc, sec, &r_rel, opcode, opnd,
7165                                  is_abs_literal);
7166             }
7167         }
7168     }
7169
7170   /* Now get rid of ASM_EXPAND relocations.  At this point, the
7171      src_relocs array for the target literal section may still be
7172      incomplete, but it must at least contain the entries for the L32R
7173      relocations associated with ASM_EXPANDs because they were just
7174      added in the preceding loop over the relocations.  */
7175
7176   for (i = 0; i < sec->reloc_count; i++)
7177     {
7178       Elf_Internal_Rela *irel = &internal_relocs[i];
7179       bfd_boolean is_reachable;
7180
7181       if (!is_resolvable_asm_expansion (abfd, sec, contents, irel, link_info,
7182                                         &is_reachable))
7183         continue;
7184
7185       if (is_reachable)
7186         {
7187           Elf_Internal_Rela *l32r_irel;
7188           r_reloc r_rel;
7189           asection *target_sec;
7190           xtensa_relax_info *target_relax_info;
7191
7192           /* Mark the source_reloc for the L32R so that it will be
7193              removed in compute_removed_literals(), along with the
7194              associated literal.  */
7195           l32r_irel = find_associated_l32r_irel (abfd, sec, contents,
7196                                                  irel, internal_relocs);
7197           if (l32r_irel == NULL)
7198             continue;
7199
7200           r_reloc_init (&r_rel, abfd, l32r_irel, contents, sec_size);
7201
7202           target_sec = r_reloc_get_section (&r_rel);
7203           target_relax_info = get_xtensa_relax_info (target_sec);
7204
7205           if (target_relax_info
7206               && (target_relax_info->is_relaxable_literal_section
7207                   || target_relax_info->is_relaxable_asm_section))
7208             {
7209               source_reloc *s_reloc;
7210
7211               /* Search the source_relocs for the entry corresponding to
7212                  the l32r_irel.  Note: The src_relocs array is not yet
7213                  sorted, but it wouldn't matter anyway because we're
7214                  searching by source offset instead of target offset.  */
7215               s_reloc = find_source_reloc (target_relax_info->src_relocs,
7216                                            target_relax_info->src_next,
7217                                            sec, l32r_irel);
7218               BFD_ASSERT (s_reloc);
7219               s_reloc->is_null = TRUE;
7220             }
7221
7222           /* Convert this reloc to ASM_SIMPLIFY.  */
7223           irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info),
7224                                        R_XTENSA_ASM_SIMPLIFY);
7225           l32r_irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
7226
7227           pin_internal_relocs (sec, internal_relocs);
7228         }
7229       else
7230         {
7231           /* It is resolvable but doesn't reach.  We resolve now
7232              by eliminating the relocation -- the call will remain
7233              expanded into L32R/CALLX.  */
7234           irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
7235           pin_internal_relocs (sec, internal_relocs);
7236         }
7237     }
7238
7239  error_return:
7240   release_contents (sec, contents);
7241   release_internal_relocs (sec, internal_relocs);
7242   return ok;
7243 }
7244
7245
7246 /* Return TRUE if the asm expansion can be resolved.  Generally it can
7247    be resolved on a final link or when a partial link locates it in the
7248    same section as the target.  Set "is_reachable" flag if the target of
7249    the call is within the range of a direct call, given the current VMA
7250    for this section and the target section.  */
7251
7252 bfd_boolean
7253 is_resolvable_asm_expansion (bfd *abfd,
7254                              asection *sec,
7255                              bfd_byte *contents,
7256                              Elf_Internal_Rela *irel,
7257                              struct bfd_link_info *link_info,
7258                              bfd_boolean *is_reachable_p)
7259 {
7260   asection *target_sec;
7261   asection *s;
7262   bfd_vma first_vma;
7263   bfd_vma last_vma;
7264   unsigned int first_align;
7265   unsigned int adjust;
7266   bfd_vma target_offset;
7267   r_reloc r_rel;
7268   xtensa_opcode opcode, direct_call_opcode;
7269   bfd_vma self_address;
7270   bfd_vma dest_address;
7271   bfd_boolean uses_l32r;
7272   bfd_size_type sec_size;
7273
7274   *is_reachable_p = FALSE;
7275
7276   if (contents == NULL)
7277     return FALSE;
7278
7279   if (ELF32_R_TYPE (irel->r_info) != R_XTENSA_ASM_EXPAND)
7280     return FALSE;
7281
7282   sec_size = bfd_get_section_limit (abfd, sec);
7283   opcode = get_expanded_call_opcode (contents + irel->r_offset,
7284                                      sec_size - irel->r_offset, &uses_l32r);
7285   /* Optimization of longcalls that use CONST16 is not yet implemented.  */
7286   if (!uses_l32r)
7287     return FALSE;
7288
7289   direct_call_opcode = swap_callx_for_call_opcode (opcode);
7290   if (direct_call_opcode == XTENSA_UNDEFINED)
7291     return FALSE;
7292
7293   /* Check and see that the target resolves.  */
7294   r_reloc_init (&r_rel, abfd, irel, contents, sec_size);
7295   if (!r_reloc_is_defined (&r_rel))
7296     return FALSE;
7297
7298   target_sec = r_reloc_get_section (&r_rel);
7299   target_offset = r_rel.target_offset;
7300
7301   /* If the target is in a shared library, then it doesn't reach.  This
7302      isn't supposed to come up because the compiler should never generate
7303      non-PIC calls on systems that use shared libraries, but the linker
7304      shouldn't crash regardless.  */
7305   if (!target_sec->output_section)
7306     return FALSE;
7307
7308   /* For relocatable sections, we can only simplify when the output
7309      section of the target is the same as the output section of the
7310      source.  */
7311   if (bfd_link_relocatable (link_info)
7312       && (target_sec->output_section != sec->output_section
7313           || is_reloc_sym_weak (abfd, irel)))
7314     return FALSE;
7315
7316   if (target_sec->output_section != sec->output_section)
7317     {
7318       /* If the two sections are sufficiently far away that relaxation
7319          might take the call out of range, we can't simplify.  For
7320          example, a positive displacement call into another memory
7321          could get moved to a lower address due to literal removal,
7322          but the destination won't move, and so the displacment might
7323          get larger.
7324
7325          If the displacement is negative, assume the destination could
7326          move as far back as the start of the output section.  The
7327          self_address will be at least as far into the output section
7328          as it is prior to relaxation.
7329
7330          If the displacement is postive, assume the destination will be in
7331          it's pre-relaxed location (because relaxation only makes sections
7332          smaller).  The self_address could go all the way to the beginning
7333          of the output section.  */
7334
7335       dest_address = target_sec->output_section->vma;
7336       self_address = sec->output_section->vma;
7337
7338       if (sec->output_section->vma > target_sec->output_section->vma)
7339         self_address += sec->output_offset + irel->r_offset + 3;
7340       else
7341         dest_address += bfd_get_section_limit (abfd, target_sec->output_section);
7342       /* Call targets should be four-byte aligned.  */
7343       dest_address = (dest_address + 3) & ~3;
7344     }
7345   else
7346     {
7347
7348       self_address = (sec->output_section->vma
7349                       + sec->output_offset + irel->r_offset + 3);
7350       dest_address = (target_sec->output_section->vma
7351                       + target_sec->output_offset + target_offset);
7352     }
7353
7354   /* Adjust addresses with alignments for the worst case to see if call insn
7355      can fit.  Don't relax l32r + callx to call if the target can be out of
7356      range due to alignment.
7357      Caller and target addresses are highest and lowest address.
7358      Search all sections between caller and target, looking for max alignment.
7359      The adjustment is max alignment bytes.  If the alignment at the lowest
7360      address is less than the adjustment, apply the adjustment to highest
7361      address.  */
7362
7363   /* Start from lowest address.
7364      Lowest address aligmnet is from input section.
7365      Initial alignment (adjust) is from input section.  */
7366   if (dest_address > self_address)
7367     {
7368       s = sec->output_section;
7369       last_vma = dest_address;
7370       first_align = sec->alignment_power;
7371       adjust = target_sec->alignment_power;
7372     }
7373   else
7374     {
7375       s = target_sec->output_section;
7376       last_vma = self_address;
7377       first_align = target_sec->alignment_power;
7378       adjust = sec->alignment_power;
7379     }
7380
7381   first_vma = s->vma;
7382
7383   /* Find the largest alignment in output section list.  */
7384   for (; s && s->vma >= first_vma && s->vma <= last_vma ; s = s->next)
7385     {
7386       if (s->alignment_power > adjust)
7387         adjust = s->alignment_power;
7388     }
7389
7390   if (adjust > first_align)
7391     {
7392       /* Alignment may enlarge the range, adjust highest address.  */
7393       adjust = 1 << adjust;
7394       if (dest_address > self_address)
7395         {
7396           dest_address += adjust;
7397         }
7398       else
7399         {
7400           self_address += adjust;
7401         }
7402     }
7403
7404   *is_reachable_p = pcrel_reloc_fits (direct_call_opcode, 0,
7405                                       self_address, dest_address);
7406
7407   if ((self_address >> CALL_SEGMENT_BITS) !=
7408       (dest_address >> CALL_SEGMENT_BITS))
7409     return FALSE;
7410
7411   return TRUE;
7412 }
7413
7414
7415 static Elf_Internal_Rela *
7416 find_associated_l32r_irel (bfd *abfd,
7417                            asection *sec,
7418                            bfd_byte *contents,
7419                            Elf_Internal_Rela *other_irel,
7420                            Elf_Internal_Rela *internal_relocs)
7421 {
7422   unsigned i;
7423
7424   for (i = 0; i < sec->reloc_count; i++)
7425     {
7426       Elf_Internal_Rela *irel = &internal_relocs[i];
7427
7428       if (irel == other_irel)
7429         continue;
7430       if (irel->r_offset != other_irel->r_offset)
7431         continue;
7432       if (is_l32r_relocation (abfd, sec, contents, irel))
7433         return irel;
7434     }
7435
7436   return NULL;
7437 }
7438
7439
7440 static xtensa_opcode *
7441 build_reloc_opcodes (bfd *abfd,
7442                      asection *sec,
7443                      bfd_byte *contents,
7444                      Elf_Internal_Rela *internal_relocs)
7445 {
7446   unsigned i;
7447   xtensa_opcode *reloc_opcodes =
7448     (xtensa_opcode *) bfd_malloc (sizeof (xtensa_opcode) * sec->reloc_count);
7449   for (i = 0; i < sec->reloc_count; i++)
7450     {
7451       Elf_Internal_Rela *irel = &internal_relocs[i];
7452       reloc_opcodes[i] = get_relocation_opcode (abfd, sec, contents, irel);
7453     }
7454   return reloc_opcodes;
7455 }
7456
7457 struct reloc_range_struct
7458 {
7459   bfd_vma addr;
7460   bfd_boolean add; /* TRUE if start of a range, FALSE otherwise.  */
7461   /* Original irel index in the array of relocations for a section.  */
7462   unsigned irel_index;
7463 };
7464 typedef struct reloc_range_struct reloc_range;
7465
7466 typedef struct reloc_range_list_entry_struct reloc_range_list_entry;
7467 struct reloc_range_list_entry_struct
7468 {
7469   reloc_range_list_entry *next;
7470   reloc_range_list_entry *prev;
7471   Elf_Internal_Rela *irel;
7472   xtensa_opcode opcode;
7473   int opnum;
7474 };
7475
7476 struct reloc_range_list_struct
7477 {
7478   /* The rest of the structure is only meaningful when ok is TRUE.  */
7479   bfd_boolean ok;
7480
7481   unsigned n_range; /* Number of range markers.  */
7482   reloc_range *range; /* Sorted range markers.  */
7483
7484   unsigned first; /* Index of a first range element in the list.  */
7485   unsigned last; /* One past index of a last range element in the list.  */
7486
7487   unsigned n_list; /* Number of list elements.  */
7488   reloc_range_list_entry *reloc; /*  */
7489   reloc_range_list_entry list_root;
7490 };
7491
7492 static int
7493 reloc_range_compare (const void *a, const void *b)
7494 {
7495   const reloc_range *ra = a;
7496   const reloc_range *rb = b;
7497
7498   if (ra->addr != rb->addr)
7499     return ra->addr < rb->addr ? -1 : 1;
7500   if (ra->add != rb->add)
7501     return ra->add ? -1 : 1;
7502   return 0;
7503 }
7504
7505 static void
7506 build_reloc_ranges (bfd *abfd, asection *sec,
7507                     bfd_byte *contents,
7508                     Elf_Internal_Rela *internal_relocs,
7509                     xtensa_opcode *reloc_opcodes,
7510                     reloc_range_list *list)
7511 {
7512   unsigned i;
7513   size_t n = 0;
7514   size_t max_n = 0;
7515   reloc_range *ranges = NULL;
7516   reloc_range_list_entry *reloc =
7517     bfd_malloc (sec->reloc_count * sizeof (*reloc));
7518
7519   memset (list, 0, sizeof (*list));
7520   list->ok = TRUE;
7521
7522   for (i = 0; i < sec->reloc_count; i++)
7523     {
7524       Elf_Internal_Rela *irel = &internal_relocs[i];
7525       int r_type = ELF32_R_TYPE (irel->r_info);
7526       reloc_howto_type *howto = &elf_howto_table[r_type];
7527       r_reloc r_rel;
7528
7529       if (r_type == R_XTENSA_ASM_SIMPLIFY
7530           || r_type == R_XTENSA_32_PCREL
7531           || !howto->pc_relative)
7532         continue;
7533
7534       r_reloc_init (&r_rel, abfd, irel, contents,
7535                     bfd_get_section_limit (abfd, sec));
7536
7537       if (r_reloc_get_section (&r_rel) != sec)
7538         continue;
7539
7540       if (n + 2 > max_n)
7541         {
7542           max_n = (max_n + 2) * 2;
7543           ranges = bfd_realloc (ranges, max_n * sizeof (*ranges));
7544         }
7545
7546       ranges[n].addr = irel->r_offset;
7547       ranges[n + 1].addr = r_rel.target_offset;
7548
7549       ranges[n].add = ranges[n].addr < ranges[n + 1].addr;
7550       ranges[n + 1].add = !ranges[n].add;
7551
7552       ranges[n].irel_index = i;
7553       ranges[n + 1].irel_index = i;
7554
7555       n += 2;
7556
7557       reloc[i].irel = irel;
7558
7559       /* Every relocation won't possibly be checked in the optimized version of
7560          check_section_ebb_pcrels_fit, so this needs to be done here.  */
7561       if (is_alt_relocation (ELF32_R_TYPE (irel->r_info)))
7562         {
7563           /* None of the current alternate relocs are PC-relative,
7564              and only PC-relative relocs matter here.  */
7565         }
7566       else
7567         {
7568           xtensa_opcode opcode;
7569           int opnum;
7570
7571           if (reloc_opcodes)
7572             opcode = reloc_opcodes[i];
7573           else
7574             opcode = get_relocation_opcode (abfd, sec, contents, irel);
7575
7576           if (opcode == XTENSA_UNDEFINED)
7577             {
7578               list->ok = FALSE;
7579               break;
7580             }
7581
7582           opnum = get_relocation_opnd (opcode, ELF32_R_TYPE (irel->r_info));
7583           if (opnum == XTENSA_UNDEFINED)
7584             {
7585               list->ok = FALSE;
7586               break;
7587             }
7588
7589           /* Record relocation opcode and opnum as we've calculated them
7590              anyway and they won't change.  */
7591           reloc[i].opcode = opcode;
7592           reloc[i].opnum = opnum;
7593         }
7594     }
7595
7596   if (list->ok)
7597     {
7598       ranges = bfd_realloc (ranges, n * sizeof (*ranges));
7599       qsort (ranges, n, sizeof (*ranges), reloc_range_compare);
7600
7601       list->n_range = n;
7602       list->range = ranges;
7603       list->reloc = reloc;
7604       list->list_root.prev = &list->list_root;
7605       list->list_root.next = &list->list_root;
7606     }
7607   else
7608     {
7609       free (ranges);
7610       free (reloc);
7611     }
7612 }
7613
7614 static void reloc_range_list_append (reloc_range_list *list,
7615                                      unsigned irel_index)
7616 {
7617   reloc_range_list_entry *entry = list->reloc + irel_index;
7618
7619   entry->prev = list->list_root.prev;
7620   entry->next = &list->list_root;
7621   entry->prev->next = entry;
7622   entry->next->prev = entry;
7623   ++list->n_list;
7624 }
7625
7626 static void reloc_range_list_remove (reloc_range_list *list,
7627                                      unsigned irel_index)
7628 {
7629   reloc_range_list_entry *entry = list->reloc + irel_index;
7630
7631   entry->next->prev = entry->prev;
7632   entry->prev->next = entry->next;
7633   --list->n_list;
7634 }
7635
7636 /* Update relocation list object so that it lists all relocations that cross
7637    [first; last] range.  Range bounds should not decrease with successive
7638    invocations.  */
7639 static void reloc_range_list_update_range (reloc_range_list *list,
7640                                            bfd_vma first, bfd_vma last)
7641 {
7642   /* This should not happen: EBBs are iterated from lower addresses to higher.
7643      But even if that happens there's no need to break: just flush current list
7644      and start from scratch.  */
7645   if ((list->last > 0 && list->range[list->last - 1].addr > last) ||
7646       (list->first > 0 && list->range[list->first - 1].addr >= first))
7647     {
7648       list->first = 0;
7649       list->last = 0;
7650       list->n_list = 0;
7651       list->list_root.next = &list->list_root;
7652       list->list_root.prev = &list->list_root;
7653       fprintf (stderr, "%s: move backwards requested\n", __func__);
7654     }
7655
7656   for (; list->last < list->n_range &&
7657        list->range[list->last].addr <= last; ++list->last)
7658     if (list->range[list->last].add)
7659       reloc_range_list_append (list, list->range[list->last].irel_index);
7660
7661   for (; list->first < list->n_range &&
7662        list->range[list->first].addr < first; ++list->first)
7663     if (!list->range[list->first].add)
7664       reloc_range_list_remove (list, list->range[list->first].irel_index);
7665 }
7666
7667 static void free_reloc_range_list (reloc_range_list *list)
7668 {
7669   free (list->range);
7670   free (list->reloc);
7671 }
7672
7673 /* The compute_text_actions function will build a list of potential
7674    transformation actions for code in the extended basic block of each
7675    longcall that is optimized to a direct call.  From this list we
7676    generate a set of actions to actually perform that optimizes for
7677    space and, if not using size_opt, maintains branch target
7678    alignments.
7679
7680    These actions to be performed are placed on a per-section list.
7681    The actual changes are performed by relax_section() in the second
7682    pass.  */
7683
7684 bfd_boolean
7685 compute_text_actions (bfd *abfd,
7686                       asection *sec,
7687                       struct bfd_link_info *link_info)
7688 {
7689   xtensa_opcode *reloc_opcodes = NULL;
7690   xtensa_relax_info *relax_info;
7691   bfd_byte *contents;
7692   Elf_Internal_Rela *internal_relocs;
7693   bfd_boolean ok = TRUE;
7694   unsigned i;
7695   property_table_entry *prop_table = 0;
7696   int ptblsize = 0;
7697   bfd_size_type sec_size;
7698   reloc_range_list relevant_relocs;
7699
7700   relax_info = get_xtensa_relax_info (sec);
7701   BFD_ASSERT (relax_info);
7702   BFD_ASSERT (relax_info->src_next == relax_info->src_count);
7703
7704   /* Do nothing if the section contains no optimized longcalls.  */
7705   if (!relax_info->is_relaxable_asm_section)
7706     return ok;
7707
7708   internal_relocs = retrieve_internal_relocs (abfd, sec,
7709                                               link_info->keep_memory);
7710
7711   if (internal_relocs)
7712     qsort (internal_relocs, sec->reloc_count, sizeof (Elf_Internal_Rela),
7713            internal_reloc_compare);
7714
7715   sec_size = bfd_get_section_limit (abfd, sec);
7716   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
7717   if (contents == NULL && sec_size != 0)
7718     {
7719       ok = FALSE;
7720       goto error_return;
7721     }
7722
7723   ptblsize = xtensa_read_table_entries (abfd, sec, &prop_table,
7724                                         XTENSA_PROP_SEC_NAME, FALSE);
7725   if (ptblsize < 0)
7726     {
7727       ok = FALSE;
7728       goto error_return;
7729     }
7730
7731   /* Precompute the opcode for each relocation.  */
7732   reloc_opcodes = build_reloc_opcodes (abfd, sec, contents, internal_relocs);
7733
7734   build_reloc_ranges (abfd, sec, contents, internal_relocs, reloc_opcodes,
7735                       &relevant_relocs);
7736
7737   for (i = 0; i < sec->reloc_count; i++)
7738     {
7739       Elf_Internal_Rela *irel = &internal_relocs[i];
7740       bfd_vma r_offset;
7741       property_table_entry *the_entry;
7742       int ptbl_idx;
7743       ebb_t *ebb;
7744       ebb_constraint ebb_table;
7745       bfd_size_type simplify_size;
7746
7747       if (irel && ELF32_R_TYPE (irel->r_info) != R_XTENSA_ASM_SIMPLIFY)
7748         continue;
7749       r_offset = irel->r_offset;
7750
7751       simplify_size = get_asm_simplify_size (contents, sec_size, r_offset);
7752       if (simplify_size == 0)
7753         {
7754           _bfd_error_handler
7755             /* xgettext:c-format */
7756             (_("%pB(%pA+%#" PRIx64 "): could not decode instruction for "
7757                "XTENSA_ASM_SIMPLIFY relocation; "
7758                "possible configuration mismatch"),
7759              sec->owner, sec, (uint64_t) r_offset);
7760           continue;
7761         }
7762
7763       /* If the instruction table is not around, then don't do this
7764          relaxation.  */
7765       the_entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
7766                                                   sec->vma + irel->r_offset);
7767       if (the_entry == NULL || XTENSA_NO_NOP_REMOVAL)
7768         {
7769           text_action_add (&relax_info->action_list,
7770                            ta_convert_longcall, sec, r_offset,
7771                            0);
7772           continue;
7773         }
7774
7775       /* If the next longcall happens to be at the same address as an
7776          unreachable section of size 0, then skip forward.  */
7777       ptbl_idx = the_entry - prop_table;
7778       while ((the_entry->flags & XTENSA_PROP_UNREACHABLE)
7779              && the_entry->size == 0
7780              && ptbl_idx + 1 < ptblsize
7781              && (prop_table[ptbl_idx + 1].address
7782                  == prop_table[ptbl_idx].address))
7783         {
7784           ptbl_idx++;
7785           the_entry++;
7786         }
7787
7788       if (the_entry->flags & XTENSA_PROP_NO_TRANSFORM)
7789           /* NO_REORDER is OK */
7790         continue;
7791
7792       init_ebb_constraint (&ebb_table);
7793       ebb = &ebb_table.ebb;
7794       init_ebb (ebb, sec, contents, sec_size, prop_table, ptblsize,
7795                 internal_relocs, sec->reloc_count);
7796       ebb->start_offset = r_offset + simplify_size;
7797       ebb->end_offset = r_offset + simplify_size;
7798       ebb->start_ptbl_idx = ptbl_idx;
7799       ebb->end_ptbl_idx = ptbl_idx;
7800       ebb->start_reloc_idx = i;
7801       ebb->end_reloc_idx = i;
7802
7803       if (!extend_ebb_bounds (ebb)
7804           || !compute_ebb_proposed_actions (&ebb_table)
7805           || !compute_ebb_actions (&ebb_table)
7806           || !check_section_ebb_pcrels_fit (abfd, sec, contents,
7807                                             internal_relocs,
7808                                             &relevant_relocs,
7809                                             &ebb_table, reloc_opcodes)
7810           || !check_section_ebb_reduces (&ebb_table))
7811         {
7812           /* If anything goes wrong or we get unlucky and something does
7813              not fit, with our plan because of expansion between
7814              critical branches, just convert to a NOP.  */
7815
7816           text_action_add (&relax_info->action_list,
7817                            ta_convert_longcall, sec, r_offset, 0);
7818           i = ebb_table.ebb.end_reloc_idx;
7819           free_ebb_constraint (&ebb_table);
7820           continue;
7821         }
7822
7823       text_action_add_proposed (&relax_info->action_list, &ebb_table, sec);
7824
7825       /* Update the index so we do not go looking at the relocations
7826          we have already processed.  */
7827       i = ebb_table.ebb.end_reloc_idx;
7828       free_ebb_constraint (&ebb_table);
7829     }
7830
7831   free_reloc_range_list (&relevant_relocs);
7832
7833 #if DEBUG
7834   if (action_list_count (&relax_info->action_list))
7835     print_action_list (stderr, &relax_info->action_list);
7836 #endif
7837
7838 error_return:
7839   release_contents (sec, contents);
7840   release_internal_relocs (sec, internal_relocs);
7841   if (prop_table)
7842     free (prop_table);
7843   if (reloc_opcodes)
7844     free (reloc_opcodes);
7845
7846   return ok;
7847 }
7848
7849
7850 /* Do not widen an instruction if it is preceeded by a
7851    loop opcode.  It might cause misalignment.  */
7852
7853 static bfd_boolean
7854 prev_instr_is_a_loop (bfd_byte *contents,
7855                       bfd_size_type content_length,
7856                       bfd_size_type offset)
7857 {
7858   xtensa_opcode prev_opcode;
7859
7860   if (offset < 3)
7861     return FALSE;
7862   prev_opcode = insn_decode_opcode (contents, content_length, offset-3, 0);
7863   return (xtensa_opcode_is_loop (xtensa_default_isa, prev_opcode) == 1);
7864 }
7865
7866
7867 /* Find all of the possible actions for an extended basic block.  */
7868
7869 bfd_boolean
7870 compute_ebb_proposed_actions (ebb_constraint *ebb_table)
7871 {
7872   const ebb_t *ebb = &ebb_table->ebb;
7873   unsigned rel_idx = ebb->start_reloc_idx;
7874   property_table_entry *entry, *start_entry, *end_entry;
7875   bfd_vma offset = 0;
7876   xtensa_isa isa = xtensa_default_isa;
7877   xtensa_format fmt;
7878   static xtensa_insnbuf insnbuf = NULL;
7879   static xtensa_insnbuf slotbuf = NULL;
7880
7881   if (insnbuf == NULL)
7882     {
7883       insnbuf = xtensa_insnbuf_alloc (isa);
7884       slotbuf = xtensa_insnbuf_alloc (isa);
7885     }
7886
7887   start_entry = &ebb->ptbl[ebb->start_ptbl_idx];
7888   end_entry = &ebb->ptbl[ebb->end_ptbl_idx];
7889
7890   for (entry = start_entry; entry <= end_entry; entry++)
7891     {
7892       bfd_vma start_offset, end_offset;
7893       bfd_size_type insn_len;
7894
7895       start_offset = entry->address - ebb->sec->vma;
7896       end_offset = entry->address + entry->size - ebb->sec->vma;
7897
7898       if (entry == start_entry)
7899         start_offset = ebb->start_offset;
7900       if (entry == end_entry)
7901         end_offset = ebb->end_offset;
7902       offset = start_offset;
7903
7904       if (offset == entry->address - ebb->sec->vma
7905           && (entry->flags & XTENSA_PROP_INSN_BRANCH_TARGET) != 0)
7906         {
7907           enum ebb_target_enum align_type = EBB_DESIRE_TGT_ALIGN;
7908           BFD_ASSERT (offset != end_offset);
7909           if (offset == end_offset)
7910             return FALSE;
7911
7912           insn_len = insn_decode_len (ebb->contents, ebb->content_length,
7913                                       offset);
7914           if (insn_len == 0)
7915             goto decode_error;
7916
7917           if (check_branch_target_aligned_address (offset, insn_len))
7918             align_type = EBB_REQUIRE_TGT_ALIGN;
7919
7920           ebb_propose_action (ebb_table, align_type, 0,
7921                               ta_none, offset, 0, TRUE);
7922         }
7923
7924       while (offset != end_offset)
7925         {
7926           Elf_Internal_Rela *irel;
7927           xtensa_opcode opcode;
7928
7929           while (rel_idx < ebb->end_reloc_idx
7930                  && (ebb->relocs[rel_idx].r_offset < offset
7931                      || (ebb->relocs[rel_idx].r_offset == offset
7932                          && (ELF32_R_TYPE (ebb->relocs[rel_idx].r_info)
7933                              != R_XTENSA_ASM_SIMPLIFY))))
7934             rel_idx++;
7935
7936           /* Check for longcall.  */
7937           irel = &ebb->relocs[rel_idx];
7938           if (irel->r_offset == offset
7939               && ELF32_R_TYPE (irel->r_info) == R_XTENSA_ASM_SIMPLIFY)
7940             {
7941               bfd_size_type simplify_size;
7942
7943               simplify_size = get_asm_simplify_size (ebb->contents,
7944                                                      ebb->content_length,
7945                                                      irel->r_offset);
7946               if (simplify_size == 0)
7947                 goto decode_error;
7948
7949               ebb_propose_action (ebb_table, EBB_NO_ALIGN, 0,
7950                                   ta_convert_longcall, offset, 0, TRUE);
7951
7952               offset += simplify_size;
7953               continue;
7954             }
7955
7956           if (offset + MIN_INSN_LENGTH > ebb->content_length)
7957             goto decode_error;
7958           xtensa_insnbuf_from_chars (isa, insnbuf, &ebb->contents[offset],
7959                                      ebb->content_length - offset);
7960           fmt = xtensa_format_decode (isa, insnbuf);
7961           if (fmt == XTENSA_UNDEFINED)
7962             goto decode_error;
7963           insn_len = xtensa_format_length (isa, fmt);
7964           if (insn_len == (bfd_size_type) XTENSA_UNDEFINED)
7965             goto decode_error;
7966
7967           if (xtensa_format_num_slots (isa, fmt) != 1)
7968             {
7969               offset += insn_len;
7970               continue;
7971             }
7972
7973           xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf);
7974           opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
7975           if (opcode == XTENSA_UNDEFINED)
7976             goto decode_error;
7977
7978           if ((entry->flags & XTENSA_PROP_INSN_NO_DENSITY) == 0
7979               && (entry->flags & XTENSA_PROP_NO_TRANSFORM) == 0
7980               && can_narrow_instruction (slotbuf, fmt, opcode) != 0)
7981             {
7982               /* Add an instruction narrow action.  */
7983               ebb_propose_action (ebb_table, EBB_NO_ALIGN, 0,
7984                                   ta_narrow_insn, offset, 0, FALSE);
7985             }
7986           else if ((entry->flags & XTENSA_PROP_NO_TRANSFORM) == 0
7987                    && can_widen_instruction (slotbuf, fmt, opcode) != 0
7988                    && ! prev_instr_is_a_loop (ebb->contents,
7989                                               ebb->content_length, offset))
7990             {
7991               /* Add an instruction widen action.  */
7992               ebb_propose_action (ebb_table, EBB_NO_ALIGN, 0,
7993                                   ta_widen_insn, offset, 0, FALSE);
7994             }
7995           else if (xtensa_opcode_is_loop (xtensa_default_isa, opcode) == 1)
7996             {
7997               /* Check for branch targets.  */
7998               ebb_propose_action (ebb_table, EBB_REQUIRE_LOOP_ALIGN, 0,
7999                                   ta_none, offset, 0, TRUE);
8000             }
8001
8002           offset += insn_len;
8003         }
8004     }
8005
8006   if (ebb->ends_unreachable)
8007     {
8008       ebb_propose_action (ebb_table, EBB_NO_ALIGN, 0,
8009                           ta_fill, ebb->end_offset, 0, TRUE);
8010     }
8011
8012   return TRUE;
8013
8014  decode_error:
8015   _bfd_error_handler
8016     /* xgettext:c-format */
8017     (_("%pB(%pA+%#" PRIx64 "): could not decode instruction; "
8018        "possible configuration mismatch"),
8019      ebb->sec->owner, ebb->sec, (uint64_t) offset);
8020   return FALSE;
8021 }
8022
8023
8024 /* After all of the information has collected about the
8025    transformations possible in an EBB, compute the appropriate actions
8026    here in compute_ebb_actions.  We still must check later to make
8027    sure that the actions do not break any relocations.  The algorithm
8028    used here is pretty greedy.  Basically, it removes as many no-ops
8029    as possible so that the end of the EBB has the same alignment
8030    characteristics as the original.  First, it uses narrowing, then
8031    fill space at the end of the EBB, and finally widenings.  If that
8032    does not work, it tries again with one fewer no-op removed.  The
8033    optimization will only be performed if all of the branch targets
8034    that were aligned before transformation are also aligned after the
8035    transformation.
8036
8037    When the size_opt flag is set, ignore the branch target alignments,
8038    narrow all wide instructions, and remove all no-ops unless the end
8039    of the EBB prevents it.  */
8040
8041 bfd_boolean
8042 compute_ebb_actions (ebb_constraint *ebb_table)
8043 {
8044   unsigned i = 0;
8045   unsigned j;
8046   int removed_bytes = 0;
8047   ebb_t *ebb = &ebb_table->ebb;
8048   unsigned seg_idx_start = 0;
8049   unsigned seg_idx_end = 0;
8050
8051   /* We perform this like the assembler relaxation algorithm: Start by
8052      assuming all instructions are narrow and all no-ops removed; then
8053      walk through....  */
8054
8055   /* For each segment of this that has a solid constraint, check to
8056      see if there are any combinations that will keep the constraint.
8057      If so, use it.  */
8058   for (seg_idx_end = 0; seg_idx_end < ebb_table->action_count; seg_idx_end++)
8059     {
8060       bfd_boolean requires_text_end_align = FALSE;
8061       unsigned longcall_count = 0;
8062       unsigned longcall_convert_count = 0;
8063       unsigned narrowable_count = 0;
8064       unsigned narrowable_convert_count = 0;
8065       unsigned widenable_count = 0;
8066       unsigned widenable_convert_count = 0;
8067
8068       proposed_action *action = NULL;
8069       int align = (1 << ebb_table->ebb.sec->alignment_power);
8070
8071       seg_idx_start = seg_idx_end;
8072
8073       for (i = seg_idx_start; i < ebb_table->action_count; i++)
8074         {
8075           action = &ebb_table->actions[i];
8076           if (action->action == ta_convert_longcall)
8077             longcall_count++;
8078           if (action->action == ta_narrow_insn)
8079             narrowable_count++;
8080           if (action->action == ta_widen_insn)
8081             widenable_count++;
8082           if (action->action == ta_fill)
8083             break;
8084           if (action->align_type == EBB_REQUIRE_LOOP_ALIGN)
8085             break;
8086           if (action->align_type == EBB_REQUIRE_TGT_ALIGN
8087               && !elf32xtensa_size_opt)
8088             break;
8089         }
8090       seg_idx_end = i;
8091
8092       if (seg_idx_end == ebb_table->action_count && !ebb->ends_unreachable)
8093         requires_text_end_align = TRUE;
8094
8095       if (elf32xtensa_size_opt && !requires_text_end_align
8096           && action->align_type != EBB_REQUIRE_LOOP_ALIGN
8097           && action->align_type != EBB_REQUIRE_TGT_ALIGN)
8098         {
8099           longcall_convert_count = longcall_count;
8100           narrowable_convert_count = narrowable_count;
8101           widenable_convert_count = 0;
8102         }
8103       else
8104         {
8105           /* There is a constraint.  Convert the max number of longcalls.  */
8106           narrowable_convert_count = 0;
8107           longcall_convert_count = 0;
8108           widenable_convert_count = 0;
8109
8110           for (j = 0; j < longcall_count; j++)
8111             {
8112               int removed = (longcall_count - j) * 3 & (align - 1);
8113               unsigned desire_narrow = (align - removed) & (align - 1);
8114               unsigned desire_widen = removed;
8115               if (desire_narrow <= narrowable_count)
8116                 {
8117                   narrowable_convert_count = desire_narrow;
8118                   narrowable_convert_count +=
8119                     (align * ((narrowable_count - narrowable_convert_count)
8120                               / align));
8121                   longcall_convert_count = (longcall_count - j);
8122                   widenable_convert_count = 0;
8123                   break;
8124                 }
8125               if (desire_widen <= widenable_count && !elf32xtensa_size_opt)
8126                 {
8127                   narrowable_convert_count = 0;
8128                   longcall_convert_count = longcall_count - j;
8129                   widenable_convert_count = desire_widen;
8130                   break;
8131                 }
8132             }
8133         }
8134
8135       /* Now the number of conversions are saved.  Do them.  */
8136       for (i = seg_idx_start; i < seg_idx_end; i++)
8137         {
8138           action = &ebb_table->actions[i];
8139           switch (action->action)
8140             {
8141             case ta_convert_longcall:
8142               if (longcall_convert_count != 0)
8143                 {
8144                   action->action = ta_remove_longcall;
8145                   action->do_action = TRUE;
8146                   action->removed_bytes += 3;
8147                   longcall_convert_count--;
8148                 }
8149               break;
8150             case ta_narrow_insn:
8151               if (narrowable_convert_count != 0)
8152                 {
8153                   action->do_action = TRUE;
8154                   action->removed_bytes += 1;
8155                   narrowable_convert_count--;
8156                 }
8157               break;
8158             case ta_widen_insn:
8159               if (widenable_convert_count != 0)
8160                 {
8161                   action->do_action = TRUE;
8162                   action->removed_bytes -= 1;
8163                   widenable_convert_count--;
8164                 }
8165               break;
8166             default:
8167               break;
8168             }
8169         }
8170     }
8171
8172   /* Now we move on to some local opts.  Try to remove each of the
8173      remaining longcalls.  */
8174
8175   if (ebb_table->ebb.ends_section || ebb_table->ebb.ends_unreachable)
8176     {
8177       removed_bytes = 0;
8178       for (i = 0; i < ebb_table->action_count; i++)
8179         {
8180           int old_removed_bytes = removed_bytes;
8181           proposed_action *action = &ebb_table->actions[i];
8182
8183           if (action->do_action && action->action == ta_convert_longcall)
8184             {
8185               bfd_boolean bad_alignment = FALSE;
8186               removed_bytes += 3;
8187               for (j = i + 1; j < ebb_table->action_count; j++)
8188                 {
8189                   proposed_action *new_action = &ebb_table->actions[j];
8190                   bfd_vma offset = new_action->offset;
8191                   if (new_action->align_type == EBB_REQUIRE_TGT_ALIGN)
8192                     {
8193                       if (!check_branch_target_aligned
8194                           (ebb_table->ebb.contents,
8195                            ebb_table->ebb.content_length,
8196                            offset, offset - removed_bytes))
8197                         {
8198                           bad_alignment = TRUE;
8199                           break;
8200                         }
8201                     }
8202                   if (new_action->align_type == EBB_REQUIRE_LOOP_ALIGN)
8203                     {
8204                       if (!check_loop_aligned (ebb_table->ebb.contents,
8205                                                ebb_table->ebb.content_length,
8206                                                offset,
8207                                                offset - removed_bytes))
8208                         {
8209                           bad_alignment = TRUE;
8210                           break;
8211                         }
8212                     }
8213                   if (new_action->action == ta_narrow_insn
8214                       && !new_action->do_action
8215                       && ebb_table->ebb.sec->alignment_power == 2)
8216                     {
8217                       /* Narrow an instruction and we are done.  */
8218                       new_action->do_action = TRUE;
8219                       new_action->removed_bytes += 1;
8220                       bad_alignment = FALSE;
8221                       break;
8222                     }
8223                   if (new_action->action == ta_widen_insn
8224                       && new_action->do_action
8225                       && ebb_table->ebb.sec->alignment_power == 2)
8226                     {
8227                       /* Narrow an instruction and we are done.  */
8228                       new_action->do_action = FALSE;
8229                       new_action->removed_bytes += 1;
8230                       bad_alignment = FALSE;
8231                       break;
8232                     }
8233                   if (new_action->do_action)
8234                     removed_bytes += new_action->removed_bytes;
8235                 }
8236               if (!bad_alignment)
8237                 {
8238                   action->removed_bytes += 3;
8239                   action->action = ta_remove_longcall;
8240                   action->do_action = TRUE;
8241                 }
8242             }
8243           removed_bytes = old_removed_bytes;
8244           if (action->do_action)
8245             removed_bytes += action->removed_bytes;
8246         }
8247     }
8248
8249   removed_bytes = 0;
8250   for (i = 0; i < ebb_table->action_count; ++i)
8251     {
8252       proposed_action *action = &ebb_table->actions[i];
8253       if (action->do_action)
8254         removed_bytes += action->removed_bytes;
8255     }
8256
8257   if ((removed_bytes % (1 << ebb_table->ebb.sec->alignment_power)) != 0
8258       && ebb->ends_unreachable)
8259     {
8260       proposed_action *action;
8261       int br;
8262       int extra_space;
8263
8264       BFD_ASSERT (ebb_table->action_count != 0);
8265       action = &ebb_table->actions[ebb_table->action_count - 1];
8266       BFD_ASSERT (action->action == ta_fill);
8267       BFD_ASSERT (ebb->ends_unreachable->flags & XTENSA_PROP_UNREACHABLE);
8268
8269       extra_space = xtensa_compute_fill_extra_space (ebb->ends_unreachable);
8270       br = action->removed_bytes + removed_bytes + extra_space;
8271       br = br & ((1 << ebb->sec->alignment_power ) - 1);
8272
8273       action->removed_bytes = extra_space - br;
8274     }
8275   return TRUE;
8276 }
8277
8278
8279 /* The xlate_map is a sorted array of address mappings designed to
8280    answer the offset_with_removed_text() query with a binary search instead
8281    of a linear search through the section's action_list.  */
8282
8283 typedef struct xlate_map_entry xlate_map_entry_t;
8284 typedef struct xlate_map xlate_map_t;
8285
8286 struct xlate_map_entry
8287 {
8288   bfd_vma orig_address;
8289   bfd_vma new_address;
8290   unsigned size;
8291 };
8292
8293 struct xlate_map
8294 {
8295   unsigned entry_count;
8296   xlate_map_entry_t *entry;
8297 };
8298
8299
8300 static int
8301 xlate_compare (const void *a_v, const void *b_v)
8302 {
8303   const xlate_map_entry_t *a = (const xlate_map_entry_t *) a_v;
8304   const xlate_map_entry_t *b = (const xlate_map_entry_t *) b_v;
8305   if (a->orig_address < b->orig_address)
8306     return -1;
8307   if (a->orig_address > (b->orig_address + b->size - 1))
8308     return 1;
8309   return 0;
8310 }
8311
8312
8313 static bfd_vma
8314 xlate_offset_with_removed_text (const xlate_map_t *map,
8315                                 text_action_list *action_list,
8316                                 bfd_vma offset)
8317 {
8318   void *r;
8319   xlate_map_entry_t *e;
8320   struct xlate_map_entry se;
8321
8322   if (map == NULL)
8323     return offset_with_removed_text (action_list, offset);
8324
8325   if (map->entry_count == 0)
8326     return offset;
8327
8328   se.orig_address = offset;
8329   r = bsearch (&se, map->entry, map->entry_count,
8330                sizeof (xlate_map_entry_t), &xlate_compare);
8331   e = (xlate_map_entry_t *) r;
8332
8333   /* There could be a jump past the end of the section,
8334      allow it using the last xlate map entry to translate its address.  */
8335   if (e == NULL)
8336     {
8337       e = map->entry + map->entry_count - 1;
8338       if (xlate_compare (&se, e) <= 0)
8339         e = NULL;
8340     }
8341   BFD_ASSERT (e != NULL);
8342   if (e == NULL)
8343     return offset;
8344   return e->new_address - e->orig_address + offset;
8345 }
8346
8347 typedef struct xlate_map_context_struct xlate_map_context;
8348 struct xlate_map_context_struct
8349 {
8350   xlate_map_t *map;
8351   xlate_map_entry_t *current_entry;
8352   int removed;
8353 };
8354
8355 static int
8356 xlate_map_fn (splay_tree_node node, void *p)
8357 {
8358   text_action *r = (text_action *)node->value;
8359   xlate_map_context *ctx = p;
8360   unsigned orig_size = 0;
8361
8362   switch (r->action)
8363     {
8364     case ta_none:
8365     case ta_remove_insn:
8366     case ta_convert_longcall:
8367     case ta_remove_literal:
8368     case ta_add_literal:
8369       break;
8370     case ta_remove_longcall:
8371       orig_size = 6;
8372       break;
8373     case ta_narrow_insn:
8374       orig_size = 3;
8375       break;
8376     case ta_widen_insn:
8377       orig_size = 2;
8378       break;
8379     case ta_fill:
8380       break;
8381     }
8382   ctx->current_entry->size =
8383     r->offset + orig_size - ctx->current_entry->orig_address;
8384   if (ctx->current_entry->size != 0)
8385     {
8386       ctx->current_entry++;
8387       ctx->map->entry_count++;
8388     }
8389   ctx->current_entry->orig_address = r->offset + orig_size;
8390   ctx->removed += r->removed_bytes;
8391   ctx->current_entry->new_address = r->offset + orig_size - ctx->removed;
8392   ctx->current_entry->size = 0;
8393   return 0;
8394 }
8395
8396 /* Build a binary searchable offset translation map from a section's
8397    action list.  */
8398
8399 static xlate_map_t *
8400 build_xlate_map (asection *sec, xtensa_relax_info *relax_info)
8401 {
8402   text_action_list *action_list = &relax_info->action_list;
8403   unsigned num_actions = 0;
8404   xlate_map_context ctx;
8405
8406   ctx.map = (xlate_map_t *) bfd_malloc (sizeof (xlate_map_t));
8407
8408   if (ctx.map == NULL)
8409     return NULL;
8410
8411   num_actions = action_list_count (action_list);
8412   ctx.map->entry = (xlate_map_entry_t *)
8413     bfd_malloc (sizeof (xlate_map_entry_t) * (num_actions + 1));
8414   if (ctx.map->entry == NULL)
8415     {
8416       free (ctx.map);
8417       return NULL;
8418     }
8419   ctx.map->entry_count = 0;
8420
8421   ctx.removed = 0;
8422   ctx.current_entry = &ctx.map->entry[0];
8423
8424   ctx.current_entry->orig_address = 0;
8425   ctx.current_entry->new_address = 0;
8426   ctx.current_entry->size = 0;
8427
8428   splay_tree_foreach (action_list->tree, xlate_map_fn, &ctx);
8429
8430   ctx.current_entry->size = (bfd_get_section_limit (sec->owner, sec)
8431                              - ctx.current_entry->orig_address);
8432   if (ctx.current_entry->size != 0)
8433     ctx.map->entry_count++;
8434
8435   return ctx.map;
8436 }
8437
8438
8439 /* Free an offset translation map.  */
8440
8441 static void
8442 free_xlate_map (xlate_map_t *map)
8443 {
8444   if (map && map->entry)
8445     free (map->entry);
8446   if (map)
8447     free (map);
8448 }
8449
8450
8451 /* Use check_section_ebb_pcrels_fit to make sure that all of the
8452    relocations in a section will fit if a proposed set of actions
8453    are performed.  */
8454
8455 static bfd_boolean
8456 check_section_ebb_pcrels_fit (bfd *abfd,
8457                               asection *sec,
8458                               bfd_byte *contents,
8459                               Elf_Internal_Rela *internal_relocs,
8460                               reloc_range_list *relevant_relocs,
8461                               const ebb_constraint *constraint,
8462                               const xtensa_opcode *reloc_opcodes)
8463 {
8464   unsigned i, j;
8465   unsigned n = sec->reloc_count;
8466   Elf_Internal_Rela *irel;
8467   xlate_map_t *xmap = NULL;
8468   bfd_boolean ok = TRUE;
8469   xtensa_relax_info *relax_info;
8470   reloc_range_list_entry *entry = NULL;
8471
8472   relax_info = get_xtensa_relax_info (sec);
8473
8474   if (relax_info && sec->reloc_count > 100)
8475     {
8476       xmap = build_xlate_map (sec, relax_info);
8477       /* NULL indicates out of memory, but the slow version
8478          can still be used.  */
8479     }
8480
8481   if (relevant_relocs && constraint->action_count)
8482     {
8483       if (!relevant_relocs->ok)
8484         {
8485           ok = FALSE;
8486           n = 0;
8487         }
8488       else
8489         {
8490           bfd_vma min_offset, max_offset;
8491           min_offset = max_offset = constraint->actions[0].offset;
8492
8493           for (i = 1; i < constraint->action_count; ++i)
8494             {
8495               proposed_action *action = &constraint->actions[i];
8496               bfd_vma offset = action->offset;
8497
8498               if (offset < min_offset)
8499                 min_offset = offset;
8500               if (offset > max_offset)
8501                 max_offset = offset;
8502             }
8503           reloc_range_list_update_range (relevant_relocs, min_offset,
8504                                          max_offset);
8505           n = relevant_relocs->n_list;
8506           entry = &relevant_relocs->list_root;
8507         }
8508     }
8509   else
8510     {
8511       relevant_relocs = NULL;
8512     }
8513
8514   for (i = 0; i < n; i++)
8515     {
8516       r_reloc r_rel;
8517       bfd_vma orig_self_offset, orig_target_offset;
8518       bfd_vma self_offset, target_offset;
8519       int r_type;
8520       reloc_howto_type *howto;
8521       int self_removed_bytes, target_removed_bytes;
8522
8523       if (relevant_relocs)
8524         {
8525           entry = entry->next;
8526           irel = entry->irel;
8527         }
8528       else
8529         {
8530           irel = internal_relocs + i;
8531         }
8532       r_type = ELF32_R_TYPE (irel->r_info);
8533
8534       howto = &elf_howto_table[r_type];
8535       /* We maintain the required invariant: PC-relative relocations
8536          that fit before linking must fit after linking.  Thus we only
8537          need to deal with relocations to the same section that are
8538          PC-relative.  */
8539       if (r_type == R_XTENSA_ASM_SIMPLIFY
8540           || r_type == R_XTENSA_32_PCREL
8541           || !howto->pc_relative)
8542         continue;
8543
8544       r_reloc_init (&r_rel, abfd, irel, contents,
8545                     bfd_get_section_limit (abfd, sec));
8546
8547       if (r_reloc_get_section (&r_rel) != sec)
8548         continue;
8549
8550       orig_self_offset = irel->r_offset;
8551       orig_target_offset = r_rel.target_offset;
8552
8553       self_offset = orig_self_offset;
8554       target_offset = orig_target_offset;
8555
8556       if (relax_info)
8557         {
8558           self_offset =
8559             xlate_offset_with_removed_text (xmap, &relax_info->action_list,
8560                                             orig_self_offset);
8561           target_offset =
8562             xlate_offset_with_removed_text (xmap, &relax_info->action_list,
8563                                             orig_target_offset);
8564         }
8565
8566       self_removed_bytes = 0;
8567       target_removed_bytes = 0;
8568
8569       for (j = 0; j < constraint->action_count; ++j)
8570         {
8571           proposed_action *action = &constraint->actions[j];
8572           bfd_vma offset = action->offset;
8573           int removed_bytes = action->removed_bytes;
8574           if (offset < orig_self_offset
8575               || (offset == orig_self_offset && action->action == ta_fill
8576                   && action->removed_bytes < 0))
8577             self_removed_bytes += removed_bytes;
8578           if (offset < orig_target_offset
8579               || (offset == orig_target_offset && action->action == ta_fill
8580                   && action->removed_bytes < 0))
8581             target_removed_bytes += removed_bytes;
8582         }
8583       self_offset -= self_removed_bytes;
8584       target_offset -= target_removed_bytes;
8585
8586       /* Try to encode it.  Get the operand and check.  */
8587       if (is_alt_relocation (ELF32_R_TYPE (irel->r_info)))
8588         {
8589           /* None of the current alternate relocs are PC-relative,
8590              and only PC-relative relocs matter here.  */
8591         }
8592       else
8593         {
8594           xtensa_opcode opcode;
8595           int opnum;
8596
8597           if (relevant_relocs)
8598             {
8599               opcode = entry->opcode;
8600               opnum = entry->opnum;
8601             }
8602           else
8603             {
8604               if (reloc_opcodes)
8605                 opcode = reloc_opcodes[relevant_relocs ?
8606                   (unsigned)(entry - relevant_relocs->reloc) : i];
8607               else
8608                 opcode = get_relocation_opcode (abfd, sec, contents, irel);
8609               if (opcode == XTENSA_UNDEFINED)
8610                 {
8611                   ok = FALSE;
8612                   break;
8613                 }
8614
8615               opnum = get_relocation_opnd (opcode, ELF32_R_TYPE (irel->r_info));
8616               if (opnum == XTENSA_UNDEFINED)
8617                 {
8618                   ok = FALSE;
8619                   break;
8620                 }
8621             }
8622
8623           if (!pcrel_reloc_fits (opcode, opnum, self_offset, target_offset))
8624             {
8625               ok = FALSE;
8626               break;
8627             }
8628         }
8629     }
8630
8631   if (xmap)
8632     free_xlate_map (xmap);
8633
8634   return ok;
8635 }
8636
8637
8638 static bfd_boolean
8639 check_section_ebb_reduces (const ebb_constraint *constraint)
8640 {
8641   int removed = 0;
8642   unsigned i;
8643
8644   for (i = 0; i < constraint->action_count; i++)
8645     {
8646       const proposed_action *action = &constraint->actions[i];
8647       if (action->do_action)
8648         removed += action->removed_bytes;
8649     }
8650   if (removed < 0)
8651     return FALSE;
8652
8653   return TRUE;
8654 }
8655
8656
8657 void
8658 text_action_add_proposed (text_action_list *l,
8659                           const ebb_constraint *ebb_table,
8660                           asection *sec)
8661 {
8662   unsigned i;
8663
8664   for (i = 0; i < ebb_table->action_count; i++)
8665     {
8666       proposed_action *action = &ebb_table->actions[i];
8667
8668       if (!action->do_action)
8669         continue;
8670       switch (action->action)
8671         {
8672         case ta_remove_insn:
8673         case ta_remove_longcall:
8674         case ta_convert_longcall:
8675         case ta_narrow_insn:
8676         case ta_widen_insn:
8677         case ta_fill:
8678         case ta_remove_literal:
8679           text_action_add (l, action->action, sec, action->offset,
8680                            action->removed_bytes);
8681           break;
8682         case ta_none:
8683           break;
8684         default:
8685           BFD_ASSERT (0);
8686           break;
8687         }
8688     }
8689 }
8690
8691
8692 int
8693 xtensa_compute_fill_extra_space (property_table_entry *entry)
8694 {
8695   int fill_extra_space;
8696
8697   if (!entry)
8698     return 0;
8699
8700   if ((entry->flags & XTENSA_PROP_UNREACHABLE) == 0)
8701     return 0;
8702
8703   fill_extra_space = entry->size;
8704   if ((entry->flags & XTENSA_PROP_ALIGN) != 0)
8705     {
8706       /* Fill bytes for alignment:
8707          (2**n)-1 - (addr + (2**n)-1) & (2**n -1) */
8708       int pow = GET_XTENSA_PROP_ALIGNMENT (entry->flags);
8709       int nsm = (1 << pow) - 1;
8710       bfd_vma addr = entry->address + entry->size;
8711       bfd_vma align_fill = nsm - ((addr + nsm) & nsm);
8712       fill_extra_space += align_fill;
8713     }
8714   return fill_extra_space;
8715 }
8716
8717 \f
8718 /* First relaxation pass.  */
8719
8720 /* If the section contains relaxable literals, check each literal to
8721    see if it has the same value as another literal that has already
8722    been seen, either in the current section or a previous one.  If so,
8723    add an entry to the per-section list of removed literals.  The
8724    actual changes are deferred until the next pass.  */
8725
8726 static bfd_boolean
8727 compute_removed_literals (bfd *abfd,
8728                           asection *sec,
8729                           struct bfd_link_info *link_info,
8730                           value_map_hash_table *values)
8731 {
8732   xtensa_relax_info *relax_info;
8733   bfd_byte *contents;
8734   Elf_Internal_Rela *internal_relocs;
8735   source_reloc *src_relocs, *rel;
8736   bfd_boolean ok = TRUE;
8737   property_table_entry *prop_table = NULL;
8738   int ptblsize;
8739   int i, prev_i;
8740   bfd_boolean last_loc_is_prev = FALSE;
8741   bfd_vma last_target_offset = 0;
8742   section_cache_t target_sec_cache;
8743   bfd_size_type sec_size;
8744
8745   init_section_cache (&target_sec_cache);
8746
8747   /* Do nothing if it is not a relaxable literal section.  */
8748   relax_info = get_xtensa_relax_info (sec);
8749   BFD_ASSERT (relax_info);
8750   if (!relax_info->is_relaxable_literal_section)
8751     return ok;
8752
8753   internal_relocs = retrieve_internal_relocs (abfd, sec,
8754                                               link_info->keep_memory);
8755
8756   sec_size = bfd_get_section_limit (abfd, sec);
8757   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
8758   if (contents == NULL && sec_size != 0)
8759     {
8760       ok = FALSE;
8761       goto error_return;
8762     }
8763
8764   /* Sort the source_relocs by target offset.  */
8765   src_relocs = relax_info->src_relocs;
8766   qsort (src_relocs, relax_info->src_count,
8767          sizeof (source_reloc), source_reloc_compare);
8768   qsort (internal_relocs, sec->reloc_count, sizeof (Elf_Internal_Rela),
8769          internal_reloc_compare);
8770
8771   ptblsize = xtensa_read_table_entries (abfd, sec, &prop_table,
8772                                         XTENSA_PROP_SEC_NAME, FALSE);
8773   if (ptblsize < 0)
8774     {
8775       ok = FALSE;
8776       goto error_return;
8777     }
8778
8779   prev_i = -1;
8780   for (i = 0; i < relax_info->src_count; i++)
8781     {
8782       Elf_Internal_Rela *irel = NULL;
8783
8784       rel = &src_relocs[i];
8785       if (get_l32r_opcode () != rel->opcode)
8786         continue;
8787       irel = get_irel_at_offset (sec, internal_relocs,
8788                                  rel->r_rel.target_offset);
8789
8790       /* If the relocation on this is not a simple R_XTENSA_32 or
8791          R_XTENSA_PLT then do not consider it.  This may happen when
8792          the difference of two symbols is used in a literal.  */
8793       if (irel && (ELF32_R_TYPE (irel->r_info) != R_XTENSA_32
8794                    && ELF32_R_TYPE (irel->r_info) != R_XTENSA_PLT))
8795         continue;
8796
8797       /* If the target_offset for this relocation is the same as the
8798          previous relocation, then we've already considered whether the
8799          literal can be coalesced.  Skip to the next one....  */
8800       if (i != 0 && prev_i != -1
8801           && src_relocs[i-1].r_rel.target_offset == rel->r_rel.target_offset)
8802         continue;
8803       prev_i = i;
8804
8805       if (last_loc_is_prev &&
8806           last_target_offset + 4 != rel->r_rel.target_offset)
8807         last_loc_is_prev = FALSE;
8808
8809       /* Check if the relocation was from an L32R that is being removed
8810          because a CALLX was converted to a direct CALL, and check if
8811          there are no other relocations to the literal.  */
8812       if (is_removable_literal (rel, i, src_relocs, relax_info->src_count,
8813                                 sec, prop_table, ptblsize))
8814         {
8815           if (!remove_dead_literal (abfd, sec, link_info, internal_relocs,
8816                                     irel, rel, prop_table, ptblsize))
8817             {
8818               ok = FALSE;
8819               goto error_return;
8820             }
8821           last_target_offset = rel->r_rel.target_offset;
8822           continue;
8823         }
8824
8825       if (!identify_literal_placement (abfd, sec, contents, link_info,
8826                                        values,
8827                                        &last_loc_is_prev, irel,
8828                                        relax_info->src_count - i, rel,
8829                                        prop_table, ptblsize,
8830                                        &target_sec_cache, rel->is_abs_literal))
8831         {
8832           ok = FALSE;
8833           goto error_return;
8834         }
8835       last_target_offset = rel->r_rel.target_offset;
8836     }
8837
8838 #if DEBUG
8839   print_removed_literals (stderr, &relax_info->removed_list);
8840   print_action_list (stderr, &relax_info->action_list);
8841 #endif /* DEBUG */
8842
8843 error_return:
8844   if (prop_table)
8845     free (prop_table);
8846   free_section_cache (&target_sec_cache);
8847
8848   release_contents (sec, contents);
8849   release_internal_relocs (sec, internal_relocs);
8850   return ok;
8851 }
8852
8853
8854 static Elf_Internal_Rela *
8855 get_irel_at_offset (asection *sec,
8856                     Elf_Internal_Rela *internal_relocs,
8857                     bfd_vma offset)
8858 {
8859   unsigned i;
8860   Elf_Internal_Rela *irel;
8861   unsigned r_type;
8862   Elf_Internal_Rela key;
8863
8864   if (!internal_relocs)
8865     return NULL;
8866
8867   key.r_offset = offset;
8868   irel = bsearch (&key, internal_relocs, sec->reloc_count,
8869                   sizeof (Elf_Internal_Rela), internal_reloc_matches);
8870   if (!irel)
8871     return NULL;
8872
8873   /* bsearch does not guarantee which will be returned if there are
8874      multiple matches.  We need the first that is not an alignment.  */
8875   i = irel - internal_relocs;
8876   while (i > 0)
8877     {
8878       if (internal_relocs[i-1].r_offset != offset)
8879         break;
8880       i--;
8881     }
8882   for ( ; i < sec->reloc_count; i++)
8883     {
8884       irel = &internal_relocs[i];
8885       r_type = ELF32_R_TYPE (irel->r_info);
8886       if (irel->r_offset == offset && r_type != R_XTENSA_NONE)
8887         return irel;
8888     }
8889
8890   return NULL;
8891 }
8892
8893
8894 bfd_boolean
8895 is_removable_literal (const source_reloc *rel,
8896                       int i,
8897                       const source_reloc *src_relocs,
8898                       int src_count,
8899                       asection *sec,
8900                       property_table_entry *prop_table,
8901                       int ptblsize)
8902 {
8903   const source_reloc *curr_rel;
8904   property_table_entry *entry;
8905
8906   if (!rel->is_null)
8907     return FALSE;
8908
8909   entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
8910                                           sec->vma + rel->r_rel.target_offset);
8911   if (entry && (entry->flags & XTENSA_PROP_NO_TRANSFORM))
8912     return FALSE;
8913
8914   for (++i; i < src_count; ++i)
8915     {
8916       curr_rel = &src_relocs[i];
8917       /* If all others have the same target offset....  */
8918       if (curr_rel->r_rel.target_offset != rel->r_rel.target_offset)
8919         return TRUE;
8920
8921       if (!curr_rel->is_null
8922           && !xtensa_is_property_section (curr_rel->source_sec)
8923           && !(curr_rel->source_sec->flags & SEC_DEBUGGING))
8924         return FALSE;
8925     }
8926   return TRUE;
8927 }
8928
8929
8930 bfd_boolean
8931 remove_dead_literal (bfd *abfd,
8932                      asection *sec,
8933                      struct bfd_link_info *link_info,
8934                      Elf_Internal_Rela *internal_relocs,
8935                      Elf_Internal_Rela *irel,
8936                      source_reloc *rel,
8937                      property_table_entry *prop_table,
8938                      int ptblsize)
8939 {
8940   property_table_entry *entry;
8941   xtensa_relax_info *relax_info;
8942
8943   relax_info = get_xtensa_relax_info (sec);
8944   if (!relax_info)
8945     return FALSE;
8946
8947   entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
8948                                           sec->vma + rel->r_rel.target_offset);
8949
8950   /* Mark the unused literal so that it will be removed.  */
8951   add_removed_literal (&relax_info->removed_list, &rel->r_rel, NULL);
8952
8953   text_action_add (&relax_info->action_list,
8954                    ta_remove_literal, sec, rel->r_rel.target_offset, 4);
8955
8956   /* If the section is 4-byte aligned, do not add fill.  */
8957   if (sec->alignment_power > 2)
8958     {
8959       int fill_extra_space;
8960       bfd_vma entry_sec_offset;
8961       text_action *fa;
8962       property_table_entry *the_add_entry;
8963       int removed_diff;
8964
8965       if (entry)
8966         entry_sec_offset = entry->address - sec->vma + entry->size;
8967       else
8968         entry_sec_offset = rel->r_rel.target_offset + 4;
8969
8970       /* If the literal range is at the end of the section,
8971          do not add fill.  */
8972       the_add_entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
8973                                                       entry_sec_offset);
8974       fill_extra_space = xtensa_compute_fill_extra_space (the_add_entry);
8975
8976       fa = find_fill_action (&relax_info->action_list, sec, entry_sec_offset);
8977       removed_diff = compute_removed_action_diff (fa, sec, entry_sec_offset,
8978                                                   -4, fill_extra_space);
8979       if (fa)
8980         adjust_fill_action (fa, removed_diff);
8981       else
8982         text_action_add (&relax_info->action_list,
8983                          ta_fill, sec, entry_sec_offset, removed_diff);
8984     }
8985
8986   /* Zero out the relocation on this literal location.  */
8987   if (irel)
8988     {
8989       if (elf_hash_table (link_info)->dynamic_sections_created)
8990         shrink_dynamic_reloc_sections (link_info, abfd, sec, irel);
8991
8992       irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
8993       pin_internal_relocs (sec, internal_relocs);
8994     }
8995
8996   /* Do not modify "last_loc_is_prev".  */
8997   return TRUE;
8998 }
8999
9000
9001 bfd_boolean
9002 identify_literal_placement (bfd *abfd,
9003                             asection *sec,
9004                             bfd_byte *contents,
9005                             struct bfd_link_info *link_info,
9006                             value_map_hash_table *values,
9007                             bfd_boolean *last_loc_is_prev_p,
9008                             Elf_Internal_Rela *irel,
9009                             int remaining_src_rels,
9010                             source_reloc *rel,
9011                             property_table_entry *prop_table,
9012                             int ptblsize,
9013                             section_cache_t *target_sec_cache,
9014                             bfd_boolean is_abs_literal)
9015 {
9016   literal_value val;
9017   value_map *val_map;
9018   xtensa_relax_info *relax_info;
9019   bfd_boolean literal_placed = FALSE;
9020   r_reloc r_rel;
9021   unsigned long value;
9022   bfd_boolean final_static_link;
9023   bfd_size_type sec_size;
9024
9025   relax_info = get_xtensa_relax_info (sec);
9026   if (!relax_info)
9027     return FALSE;
9028
9029   sec_size = bfd_get_section_limit (abfd, sec);
9030
9031   final_static_link =
9032     (!bfd_link_relocatable (link_info)
9033      && !elf_hash_table (link_info)->dynamic_sections_created);
9034
9035   /* The placement algorithm first checks to see if the literal is
9036      already in the value map.  If so and the value map is reachable
9037      from all uses, then the literal is moved to that location.  If
9038      not, then we identify the last location where a fresh literal was
9039      placed.  If the literal can be safely moved there, then we do so.
9040      If not, then we assume that the literal is not to move and leave
9041      the literal where it is, marking it as the last literal
9042      location.  */
9043
9044   /* Find the literal value.  */
9045   value = 0;
9046   r_reloc_init (&r_rel, abfd, irel, contents, sec_size);
9047   if (!irel)
9048     {
9049       BFD_ASSERT (rel->r_rel.target_offset < sec_size);
9050       value = bfd_get_32 (abfd, contents + rel->r_rel.target_offset);
9051     }
9052   init_literal_value (&val, &r_rel, value, is_abs_literal);
9053
9054   /* Check if we've seen another literal with the same value that
9055      is in the same output section.  */
9056   val_map = value_map_get_cached_value (values, &val, final_static_link);
9057
9058   if (val_map
9059       && (r_reloc_get_section (&val_map->loc)->output_section
9060           == sec->output_section)
9061       && relocations_reach (rel, remaining_src_rels, &val_map->loc)
9062       && coalesce_shared_literal (sec, rel, prop_table, ptblsize, val_map))
9063     {
9064       /* No change to last_loc_is_prev.  */
9065       literal_placed = TRUE;
9066     }
9067
9068   /* For relocatable links, do not try to move literals.  To do it
9069      correctly might increase the number of relocations in an input
9070      section making the default relocatable linking fail.  */
9071   if (!bfd_link_relocatable (link_info) && !literal_placed
9072       && values->has_last_loc && !(*last_loc_is_prev_p))
9073     {
9074       asection *target_sec = r_reloc_get_section (&values->last_loc);
9075       if (target_sec && target_sec->output_section == sec->output_section)
9076         {
9077           /* Increment the virtual offset.  */
9078           r_reloc try_loc = values->last_loc;
9079           try_loc.virtual_offset += 4;
9080
9081           /* There is a last loc that was in the same output section.  */
9082           if (relocations_reach (rel, remaining_src_rels, &try_loc)
9083               && move_shared_literal (sec, link_info, rel,
9084                                       prop_table, ptblsize,
9085                                       &try_loc, &val, target_sec_cache))
9086             {
9087               values->last_loc.virtual_offset += 4;
9088               literal_placed = TRUE;
9089               if (!val_map)
9090                 val_map = add_value_map (values, &val, &try_loc,
9091                                          final_static_link);
9092               else
9093                 val_map->loc = try_loc;
9094             }
9095         }
9096     }
9097
9098   if (!literal_placed)
9099     {
9100       /* Nothing worked, leave the literal alone but update the last loc.  */
9101       values->has_last_loc = TRUE;
9102       values->last_loc = rel->r_rel;
9103       if (!val_map)
9104         val_map = add_value_map (values, &val, &rel->r_rel, final_static_link);
9105       else
9106         val_map->loc = rel->r_rel;
9107       *last_loc_is_prev_p = TRUE;
9108     }
9109
9110   return TRUE;
9111 }
9112
9113
9114 /* Check if the original relocations (presumably on L32R instructions)
9115    identified by reloc[0..N] can be changed to reference the literal
9116    identified by r_rel.  If r_rel is out of range for any of the
9117    original relocations, then we don't want to coalesce the original
9118    literal with the one at r_rel.  We only check reloc[0..N], where the
9119    offsets are all the same as for reloc[0] (i.e., they're all
9120    referencing the same literal) and where N is also bounded by the
9121    number of remaining entries in the "reloc" array.  The "reloc" array
9122    is sorted by target offset so we know all the entries for the same
9123    literal will be contiguous.  */
9124
9125 static bfd_boolean
9126 relocations_reach (source_reloc *reloc,
9127                    int remaining_relocs,
9128                    const r_reloc *r_rel)
9129 {
9130   bfd_vma from_offset, source_address, dest_address;
9131   asection *sec;
9132   int i;
9133
9134   if (!r_reloc_is_defined (r_rel))
9135     return FALSE;
9136
9137   sec = r_reloc_get_section (r_rel);
9138   from_offset = reloc[0].r_rel.target_offset;
9139
9140   for (i = 0; i < remaining_relocs; i++)
9141     {
9142       if (reloc[i].r_rel.target_offset != from_offset)
9143         break;
9144
9145       /* Ignore relocations that have been removed.  */
9146       if (reloc[i].is_null)
9147         continue;
9148
9149       /* The original and new output section for these must be the same
9150          in order to coalesce.  */
9151       if (r_reloc_get_section (&reloc[i].r_rel)->output_section
9152           != sec->output_section)
9153         return FALSE;
9154
9155       /* Absolute literals in the same output section can always be
9156          combined.  */
9157       if (reloc[i].is_abs_literal)
9158         continue;
9159
9160       /* A literal with no PC-relative relocations can be moved anywhere.  */
9161       if (reloc[i].opnd != -1)
9162         {
9163           /* Otherwise, check to see that it fits.  */
9164           source_address = (reloc[i].source_sec->output_section->vma
9165                             + reloc[i].source_sec->output_offset
9166                             + reloc[i].r_rel.rela.r_offset);
9167           dest_address = (sec->output_section->vma
9168                           + sec->output_offset
9169                           + r_rel->target_offset);
9170
9171           if (!pcrel_reloc_fits (reloc[i].opcode, reloc[i].opnd,
9172                                  source_address, dest_address))
9173             return FALSE;
9174         }
9175     }
9176
9177   return TRUE;
9178 }
9179
9180
9181 /* Move a literal to another literal location because it is
9182    the same as the other literal value.  */
9183
9184 static bfd_boolean
9185 coalesce_shared_literal (asection *sec,
9186                          source_reloc *rel,
9187                          property_table_entry *prop_table,
9188                          int ptblsize,
9189                          value_map *val_map)
9190 {
9191   property_table_entry *entry;
9192   text_action *fa;
9193   property_table_entry *the_add_entry;
9194   int removed_diff;
9195   xtensa_relax_info *relax_info;
9196
9197   relax_info = get_xtensa_relax_info (sec);
9198   if (!relax_info)
9199     return FALSE;
9200
9201   entry = elf_xtensa_find_property_entry
9202     (prop_table, ptblsize, sec->vma + rel->r_rel.target_offset);
9203   if (entry && (entry->flags & XTENSA_PROP_NO_TRANSFORM))
9204     return TRUE;
9205
9206   /* Mark that the literal will be coalesced.  */
9207   add_removed_literal (&relax_info->removed_list, &rel->r_rel, &val_map->loc);
9208
9209   text_action_add (&relax_info->action_list,
9210                    ta_remove_literal, sec, rel->r_rel.target_offset, 4);
9211
9212   /* If the section is 4-byte aligned, do not add fill.  */
9213   if (sec->alignment_power > 2)
9214     {
9215       int fill_extra_space;
9216       bfd_vma entry_sec_offset;
9217
9218       if (entry)
9219         entry_sec_offset = entry->address - sec->vma + entry->size;
9220       else
9221         entry_sec_offset = rel->r_rel.target_offset + 4;
9222
9223       /* If the literal range is at the end of the section,
9224          do not add fill.  */
9225       fill_extra_space = 0;
9226       the_add_entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
9227                                                       entry_sec_offset);
9228       if (the_add_entry && (the_add_entry->flags & XTENSA_PROP_UNREACHABLE))
9229         fill_extra_space = the_add_entry->size;
9230
9231       fa = find_fill_action (&relax_info->action_list, sec, entry_sec_offset);
9232       removed_diff = compute_removed_action_diff (fa, sec, entry_sec_offset,
9233                                                   -4, fill_extra_space);
9234       if (fa)
9235         adjust_fill_action (fa, removed_diff);
9236       else
9237         text_action_add (&relax_info->action_list,
9238                          ta_fill, sec, entry_sec_offset, removed_diff);
9239     }
9240
9241   return TRUE;
9242 }
9243
9244
9245 /* Move a literal to another location.  This may actually increase the
9246    total amount of space used because of alignments so we need to do
9247    this carefully.  Also, it may make a branch go out of range.  */
9248
9249 static bfd_boolean
9250 move_shared_literal (asection *sec,
9251                      struct bfd_link_info *link_info,
9252                      source_reloc *rel,
9253                      property_table_entry *prop_table,
9254                      int ptblsize,
9255                      const r_reloc *target_loc,
9256                      const literal_value *lit_value,
9257                      section_cache_t *target_sec_cache)
9258 {
9259   property_table_entry *the_add_entry, *src_entry, *target_entry = NULL;
9260   text_action *fa, *target_fa;
9261   int removed_diff;
9262   xtensa_relax_info *relax_info, *target_relax_info;
9263   asection *target_sec;
9264   ebb_t *ebb;
9265   ebb_constraint ebb_table;
9266   bfd_boolean relocs_fit;
9267
9268   /* If this routine always returns FALSE, the literals that cannot be
9269      coalesced will not be moved.  */
9270   if (elf32xtensa_no_literal_movement)
9271     return FALSE;
9272
9273   relax_info = get_xtensa_relax_info (sec);
9274   if (!relax_info)
9275     return FALSE;
9276
9277   target_sec = r_reloc_get_section (target_loc);
9278   target_relax_info = get_xtensa_relax_info (target_sec);
9279
9280   /* Literals to undefined sections may not be moved because they
9281      must report an error.  */
9282   if (bfd_is_und_section (target_sec))
9283     return FALSE;
9284
9285   src_entry = elf_xtensa_find_property_entry
9286     (prop_table, ptblsize, sec->vma + rel->r_rel.target_offset);
9287
9288   if (!section_cache_section (target_sec_cache, target_sec, link_info))
9289     return FALSE;
9290
9291   target_entry = elf_xtensa_find_property_entry
9292     (target_sec_cache->ptbl, target_sec_cache->pte_count,
9293      target_sec->vma + target_loc->target_offset);
9294
9295   if (!target_entry)
9296     return FALSE;
9297
9298   /* Make sure that we have not broken any branches.  */
9299   relocs_fit = FALSE;
9300
9301   init_ebb_constraint (&ebb_table);
9302   ebb = &ebb_table.ebb;
9303   init_ebb (ebb, target_sec_cache->sec, target_sec_cache->contents,
9304             target_sec_cache->content_length,
9305             target_sec_cache->ptbl, target_sec_cache->pte_count,
9306             target_sec_cache->relocs, target_sec_cache->reloc_count);
9307
9308   /* Propose to add 4 bytes + worst-case alignment size increase to
9309      destination.  */
9310   ebb_propose_action (&ebb_table, EBB_NO_ALIGN, 0,
9311                       ta_fill, target_loc->target_offset,
9312                       -4 - (1 << target_sec->alignment_power), TRUE);
9313
9314   /* Check all of the PC-relative relocations to make sure they still fit.  */
9315   relocs_fit = check_section_ebb_pcrels_fit (target_sec->owner, target_sec,
9316                                              target_sec_cache->contents,
9317                                              target_sec_cache->relocs, NULL,
9318                                              &ebb_table, NULL);
9319
9320   if (!relocs_fit)
9321     return FALSE;
9322
9323   text_action_add_literal (&target_relax_info->action_list,
9324                            ta_add_literal, target_loc, lit_value, -4);
9325
9326   if (target_sec->alignment_power > 2 && target_entry != src_entry)
9327     {
9328       /* May need to add or remove some fill to maintain alignment.  */
9329       int fill_extra_space;
9330       bfd_vma entry_sec_offset;
9331
9332       entry_sec_offset =
9333         target_entry->address - target_sec->vma + target_entry->size;
9334
9335       /* If the literal range is at the end of the section,
9336          do not add fill.  */
9337       fill_extra_space = 0;
9338       the_add_entry =
9339         elf_xtensa_find_property_entry (target_sec_cache->ptbl,
9340                                         target_sec_cache->pte_count,
9341                                         entry_sec_offset);
9342       if (the_add_entry && (the_add_entry->flags & XTENSA_PROP_UNREACHABLE))
9343         fill_extra_space = the_add_entry->size;
9344
9345       target_fa = find_fill_action (&target_relax_info->action_list,
9346                                     target_sec, entry_sec_offset);
9347       removed_diff = compute_removed_action_diff (target_fa, target_sec,
9348                                                   entry_sec_offset, 4,
9349                                                   fill_extra_space);
9350       if (target_fa)
9351         adjust_fill_action (target_fa, removed_diff);
9352       else
9353         text_action_add (&target_relax_info->action_list,
9354                          ta_fill, target_sec, entry_sec_offset, removed_diff);
9355     }
9356
9357   /* Mark that the literal will be moved to the new location.  */
9358   add_removed_literal (&relax_info->removed_list, &rel->r_rel, target_loc);
9359
9360   /* Remove the literal.  */
9361   text_action_add (&relax_info->action_list,
9362                    ta_remove_literal, sec, rel->r_rel.target_offset, 4);
9363
9364   /* If the section is 4-byte aligned, do not add fill.  */
9365   if (sec->alignment_power > 2 && target_entry != src_entry)
9366     {
9367       int fill_extra_space;
9368       bfd_vma entry_sec_offset;
9369
9370       if (src_entry)
9371         entry_sec_offset = src_entry->address - sec->vma + src_entry->size;
9372       else
9373         entry_sec_offset = rel->r_rel.target_offset+4;
9374
9375       /* If the literal range is at the end of the section,
9376          do not add fill.  */
9377       fill_extra_space = 0;
9378       the_add_entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
9379                                                       entry_sec_offset);
9380       if (the_add_entry && (the_add_entry->flags & XTENSA_PROP_UNREACHABLE))
9381         fill_extra_space = the_add_entry->size;
9382
9383       fa = find_fill_action (&relax_info->action_list, sec, entry_sec_offset);
9384       removed_diff = compute_removed_action_diff (fa, sec, entry_sec_offset,
9385                                                   -4, fill_extra_space);
9386       if (fa)
9387         adjust_fill_action (fa, removed_diff);
9388       else
9389         text_action_add (&relax_info->action_list,
9390                          ta_fill, sec, entry_sec_offset, removed_diff);
9391     }
9392
9393   return TRUE;
9394 }
9395
9396 \f
9397 /* Second relaxation pass.  */
9398
9399 static int
9400 action_remove_bytes_fn (splay_tree_node node, void *p)
9401 {
9402   bfd_size_type *final_size = p;
9403   text_action *action = (text_action *)node->value;
9404
9405   *final_size -= action->removed_bytes;
9406   return 0;
9407 }
9408
9409 /* Modify all of the relocations to point to the right spot, and if this
9410    is a relaxable section, delete the unwanted literals and fix the
9411    section size.  */
9412
9413 bfd_boolean
9414 relax_section (bfd *abfd, asection *sec, struct bfd_link_info *link_info)
9415 {
9416   Elf_Internal_Rela *internal_relocs;
9417   xtensa_relax_info *relax_info;
9418   bfd_byte *contents;
9419   bfd_boolean ok = TRUE;
9420   unsigned i;
9421   bfd_boolean rv = FALSE;
9422   bfd_boolean virtual_action;
9423   bfd_size_type sec_size;
9424
9425   sec_size = bfd_get_section_limit (abfd, sec);
9426   relax_info = get_xtensa_relax_info (sec);
9427   BFD_ASSERT (relax_info);
9428
9429   /* First translate any of the fixes that have been added already.  */
9430   translate_section_fixes (sec);
9431
9432   /* Handle property sections (e.g., literal tables) specially.  */
9433   if (xtensa_is_property_section (sec))
9434     {
9435       BFD_ASSERT (!relax_info->is_relaxable_literal_section);
9436       return relax_property_section (abfd, sec, link_info);
9437     }
9438
9439   internal_relocs = retrieve_internal_relocs (abfd, sec,
9440                                               link_info->keep_memory);
9441   if (!internal_relocs && !action_list_count (&relax_info->action_list))
9442     return TRUE;
9443
9444   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
9445   if (contents == NULL && sec_size != 0)
9446     {
9447       ok = FALSE;
9448       goto error_return;
9449     }
9450
9451   if (internal_relocs)
9452     {
9453       for (i = 0; i < sec->reloc_count; i++)
9454         {
9455           Elf_Internal_Rela *irel;
9456           xtensa_relax_info *target_relax_info;
9457           bfd_vma source_offset, old_source_offset;
9458           r_reloc r_rel;
9459           unsigned r_type;
9460           asection *target_sec;
9461
9462           /* Locally change the source address.
9463              Translate the target to the new target address.
9464              If it points to this section and has been removed,
9465              NULLify it.
9466              Write it back.  */
9467
9468           irel = &internal_relocs[i];
9469           source_offset = irel->r_offset;
9470           old_source_offset = source_offset;
9471
9472           r_type = ELF32_R_TYPE (irel->r_info);
9473           r_reloc_init (&r_rel, abfd, irel, contents,
9474                         bfd_get_section_limit (abfd, sec));
9475
9476           /* If this section could have changed then we may need to
9477              change the relocation's offset.  */
9478
9479           if (relax_info->is_relaxable_literal_section
9480               || relax_info->is_relaxable_asm_section)
9481             {
9482               pin_internal_relocs (sec, internal_relocs);
9483
9484               if (r_type != R_XTENSA_NONE
9485                   && find_removed_literal (&relax_info->removed_list,
9486                                            irel->r_offset))
9487                 {
9488                   /* Remove this relocation.  */
9489                   if (elf_hash_table (link_info)->dynamic_sections_created)
9490                     shrink_dynamic_reloc_sections (link_info, abfd, sec, irel);
9491                   irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
9492                   irel->r_offset = offset_with_removed_text_map
9493                     (&relax_info->action_list, irel->r_offset);
9494                   continue;
9495                 }
9496
9497               if (r_type == R_XTENSA_ASM_SIMPLIFY)
9498                 {
9499                   text_action *action =
9500                     find_insn_action (&relax_info->action_list,
9501                                       irel->r_offset);
9502                   if (action && (action->action == ta_convert_longcall
9503                                  || action->action == ta_remove_longcall))
9504                     {
9505                       bfd_reloc_status_type retval;
9506                       char *error_message = NULL;
9507
9508                       retval = contract_asm_expansion (contents, sec_size,
9509                                                        irel, &error_message);
9510                       if (retval != bfd_reloc_ok)
9511                         {
9512                           (*link_info->callbacks->reloc_dangerous)
9513                             (link_info, error_message, abfd, sec,
9514                              irel->r_offset);
9515                           goto error_return;
9516                         }
9517                       /* Update the action so that the code that moves
9518                          the contents will do the right thing.  */
9519                       /* ta_remove_longcall and ta_remove_insn actions are
9520                          grouped together in the tree as well as
9521                          ta_convert_longcall and ta_none, so that changes below
9522                          can be done w/o removing and reinserting action into
9523                          the tree.  */
9524
9525                       if (action->action == ta_remove_longcall)
9526                         action->action = ta_remove_insn;
9527                       else
9528                         action->action = ta_none;
9529                       /* Refresh the info in the r_rel.  */
9530                       r_reloc_init (&r_rel, abfd, irel, contents, sec_size);
9531                       r_type = ELF32_R_TYPE (irel->r_info);
9532                     }
9533                 }
9534
9535               source_offset = offset_with_removed_text_map
9536                 (&relax_info->action_list, irel->r_offset);
9537               irel->r_offset = source_offset;
9538             }
9539
9540           /* If the target section could have changed then
9541              we may need to change the relocation's target offset.  */
9542
9543           target_sec = r_reloc_get_section (&r_rel);
9544
9545           /* For a reference to a discarded section from a DWARF section,
9546              i.e., where action_discarded is PRETEND, the symbol will
9547              eventually be modified to refer to the kept section (at least if
9548              the kept and discarded sections are the same size).  Anticipate
9549              that here and adjust things accordingly.  */
9550           if (! elf_xtensa_ignore_discarded_relocs (sec)
9551               && elf_xtensa_action_discarded (sec) == PRETEND
9552               && sec->sec_info_type != SEC_INFO_TYPE_STABS
9553               && target_sec != NULL
9554               && discarded_section (target_sec))
9555             {
9556               /* It would be natural to call _bfd_elf_check_kept_section
9557                  here, but it's not exported from elflink.c.  It's also a
9558                  fairly expensive check.  Adjusting the relocations to the
9559                  discarded section is fairly harmless; it will only adjust
9560                  some addends and difference values.  If it turns out that
9561                  _bfd_elf_check_kept_section fails later, it won't matter,
9562                  so just compare the section names to find the right group
9563                  member.  */
9564               asection *kept = target_sec->kept_section;
9565               if (kept != NULL)
9566                 {
9567                   if ((kept->flags & SEC_GROUP) != 0)
9568                     {
9569                       asection *first = elf_next_in_group (kept);
9570                       asection *s = first;
9571
9572                       kept = NULL;
9573                       while (s != NULL)
9574                         {
9575                           if (strcmp (s->name, target_sec->name) == 0)
9576                             {
9577                               kept = s;
9578                               break;
9579                             }
9580                           s = elf_next_in_group (s);
9581                           if (s == first)
9582                             break;
9583                         }
9584                     }
9585                 }
9586               if (kept != NULL
9587                   && ((target_sec->rawsize != 0
9588                        ? target_sec->rawsize : target_sec->size)
9589                       == (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9590                 target_sec = kept;
9591             }
9592
9593           target_relax_info = get_xtensa_relax_info (target_sec);
9594           if (target_relax_info
9595               && (target_relax_info->is_relaxable_literal_section
9596                   || target_relax_info->is_relaxable_asm_section))
9597             {
9598               r_reloc new_reloc;
9599               target_sec = translate_reloc (&r_rel, &new_reloc, target_sec);
9600
9601               if (r_type == R_XTENSA_DIFF8
9602                   || r_type == R_XTENSA_DIFF16
9603                   || r_type == R_XTENSA_DIFF32)
9604                 {
9605                   bfd_signed_vma diff_value = 0;
9606                   bfd_vma new_end_offset, diff_mask = 0;
9607
9608                   if (bfd_get_section_limit (abfd, sec) < old_source_offset)
9609                     {
9610                       (*link_info->callbacks->reloc_dangerous)
9611                         (link_info, _("invalid relocation address"),
9612                          abfd, sec, old_source_offset);
9613                       goto error_return;
9614                     }
9615
9616                   switch (r_type)
9617                     {
9618                     case R_XTENSA_DIFF8:
9619                       diff_value =
9620                         bfd_get_signed_8 (abfd, &contents[old_source_offset]);
9621                       break;
9622                     case R_XTENSA_DIFF16:
9623                       diff_value =
9624                         bfd_get_signed_16 (abfd, &contents[old_source_offset]);
9625                       break;
9626                     case R_XTENSA_DIFF32:
9627                       diff_value =
9628                         bfd_get_signed_32 (abfd, &contents[old_source_offset]);
9629                       break;
9630                     }
9631
9632                   new_end_offset = offset_with_removed_text_map
9633                     (&target_relax_info->action_list,
9634                      r_rel.target_offset + diff_value);
9635                   diff_value = new_end_offset - new_reloc.target_offset;
9636
9637                   switch (r_type)
9638                     {
9639                     case R_XTENSA_DIFF8:
9640                       diff_mask = 0x7f;
9641                       bfd_put_signed_8 (abfd, diff_value,
9642                                  &contents[old_source_offset]);
9643                       break;
9644                     case R_XTENSA_DIFF16:
9645                       diff_mask = 0x7fff;
9646                       bfd_put_signed_16 (abfd, diff_value,
9647                                   &contents[old_source_offset]);
9648                       break;
9649                     case R_XTENSA_DIFF32:
9650                       diff_mask = 0x7fffffff;
9651                       bfd_put_signed_32 (abfd, diff_value,
9652                                   &contents[old_source_offset]);
9653                       break;
9654                     }
9655
9656                   /* Check for overflow. Sign bits must be all zeroes or all ones */
9657                   if ((diff_value & ~diff_mask) != 0 &&
9658                       (diff_value & ~diff_mask) != (-1 & ~diff_mask))
9659                     {
9660                       (*link_info->callbacks->reloc_dangerous)
9661                         (link_info, _("overflow after relaxation"),
9662                          abfd, sec, old_source_offset);
9663                       goto error_return;
9664                     }
9665
9666                   pin_contents (sec, contents);
9667                 }
9668
9669               /* If the relocation still references a section in the same
9670                  input file, modify the relocation directly instead of
9671                  adding a "fix" record.  */
9672               if (target_sec->owner == abfd)
9673                 {
9674                   unsigned r_symndx = ELF32_R_SYM (new_reloc.rela.r_info);
9675                   irel->r_info = ELF32_R_INFO (r_symndx, r_type);
9676                   irel->r_addend = new_reloc.rela.r_addend;
9677                   pin_internal_relocs (sec, internal_relocs);
9678                 }
9679               else
9680                 {
9681                   bfd_vma addend_displacement;
9682                   reloc_bfd_fix *fix;
9683
9684                   addend_displacement =
9685                     new_reloc.target_offset + new_reloc.virtual_offset;
9686                   fix = reloc_bfd_fix_init (sec, source_offset, r_type,
9687                                             target_sec,
9688                                             addend_displacement, TRUE);
9689                   add_fix (sec, fix);
9690                 }
9691             }
9692         }
9693     }
9694
9695   if ((relax_info->is_relaxable_literal_section
9696        || relax_info->is_relaxable_asm_section)
9697       && action_list_count (&relax_info->action_list))
9698     {
9699       /* Walk through the planned actions and build up a table
9700          of move, copy and fill records.  Use the move, copy and
9701          fill records to perform the actions once.  */
9702
9703       bfd_size_type final_size, copy_size, orig_insn_size;
9704       bfd_byte *scratch = NULL;
9705       bfd_byte *dup_contents = NULL;
9706       bfd_size_type orig_size = sec->size;
9707       bfd_vma orig_dot = 0;
9708       bfd_vma orig_dot_copied = 0; /* Byte copied already from
9709                                             orig dot in physical memory.  */
9710       bfd_vma orig_dot_vo = 0; /* Virtual offset from orig_dot.  */
9711       bfd_vma dup_dot = 0;
9712
9713       text_action *action;
9714
9715       final_size = sec->size;
9716
9717       splay_tree_foreach (relax_info->action_list.tree,
9718                           action_remove_bytes_fn, &final_size);
9719       scratch = (bfd_byte *) bfd_zmalloc (final_size);
9720       dup_contents = (bfd_byte *) bfd_zmalloc (final_size);
9721
9722       /* The dot is the current fill location.  */
9723 #if DEBUG
9724       print_action_list (stderr, &relax_info->action_list);
9725 #endif
9726
9727       for (action = action_first (&relax_info->action_list); action;
9728            action = action_next (&relax_info->action_list, action))
9729         {
9730           virtual_action = FALSE;
9731           if (action->offset > orig_dot)
9732             {
9733               orig_dot += orig_dot_copied;
9734               orig_dot_copied = 0;
9735               orig_dot_vo = 0;
9736               /* Out of the virtual world.  */
9737             }
9738
9739           if (action->offset > orig_dot)
9740             {
9741               copy_size = action->offset - orig_dot;
9742               memmove (&dup_contents[dup_dot], &contents[orig_dot], copy_size);
9743               orig_dot += copy_size;
9744               dup_dot += copy_size;
9745               BFD_ASSERT (action->offset == orig_dot);
9746             }
9747           else if (action->offset < orig_dot)
9748             {
9749               if (action->action == ta_fill
9750                   && action->offset - action->removed_bytes == orig_dot)
9751                 {
9752                   /* This is OK because the fill only effects the dup_dot.  */
9753                 }
9754               else if (action->action == ta_add_literal)
9755                 {
9756                   /* TBD.  Might need to handle this.  */
9757                 }
9758             }
9759           if (action->offset == orig_dot)
9760             {
9761               if (action->virtual_offset > orig_dot_vo)
9762                 {
9763                   if (orig_dot_vo == 0)
9764                     {
9765                       /* Need to copy virtual_offset bytes.  Probably four.  */
9766                       copy_size = action->virtual_offset - orig_dot_vo;
9767                       memmove (&dup_contents[dup_dot],
9768                                &contents[orig_dot], copy_size);
9769                       orig_dot_copied = copy_size;
9770                       dup_dot += copy_size;
9771                     }
9772                   virtual_action = TRUE;
9773                 }
9774               else
9775                 BFD_ASSERT (action->virtual_offset <= orig_dot_vo);
9776             }
9777           switch (action->action)
9778             {
9779             case ta_remove_literal:
9780             case ta_remove_insn:
9781               BFD_ASSERT (action->removed_bytes >= 0);
9782               orig_dot += action->removed_bytes;
9783               break;
9784
9785             case ta_narrow_insn:
9786               orig_insn_size = 3;
9787               copy_size = 2;
9788               memmove (scratch, &contents[orig_dot], orig_insn_size);
9789               BFD_ASSERT (action->removed_bytes == 1);
9790               rv = narrow_instruction (scratch, final_size, 0);
9791               BFD_ASSERT (rv);
9792               memmove (&dup_contents[dup_dot], scratch, copy_size);
9793               orig_dot += orig_insn_size;
9794               dup_dot += copy_size;
9795               break;
9796
9797             case ta_fill:
9798               if (action->removed_bytes >= 0)
9799                 orig_dot += action->removed_bytes;
9800               else
9801                 {
9802                   /* Already zeroed in dup_contents.  Just bump the
9803                      counters.  */
9804                   dup_dot += (-action->removed_bytes);
9805                 }
9806               break;
9807
9808             case ta_none:
9809               BFD_ASSERT (action->removed_bytes == 0);
9810               break;
9811
9812             case ta_convert_longcall:
9813             case ta_remove_longcall:
9814               /* These will be removed or converted before we get here.  */
9815               BFD_ASSERT (0);
9816               break;
9817
9818             case ta_widen_insn:
9819               orig_insn_size = 2;
9820               copy_size = 3;
9821               memmove (scratch, &contents[orig_dot], orig_insn_size);
9822               BFD_ASSERT (action->removed_bytes == -1);
9823               rv = widen_instruction (scratch, final_size, 0);
9824               BFD_ASSERT (rv);
9825               memmove (&dup_contents[dup_dot], scratch, copy_size);
9826               orig_dot += orig_insn_size;
9827               dup_dot += copy_size;
9828               break;
9829
9830             case ta_add_literal:
9831               orig_insn_size = 0;
9832               copy_size = 4;
9833               BFD_ASSERT (action->removed_bytes == -4);
9834               /* TBD -- place the literal value here and insert
9835                  into the table.  */
9836               memset (&dup_contents[dup_dot], 0, 4);
9837               pin_internal_relocs (sec, internal_relocs);
9838               pin_contents (sec, contents);
9839
9840               if (!move_literal (abfd, link_info, sec, dup_dot, dup_contents,
9841                                  relax_info, &internal_relocs, &action->value))
9842                 goto error_return;
9843
9844               if (virtual_action)
9845                 orig_dot_vo += copy_size;
9846
9847               orig_dot += orig_insn_size;
9848               dup_dot += copy_size;
9849               break;
9850
9851             default:
9852               /* Not implemented yet.  */
9853               BFD_ASSERT (0);
9854               break;
9855             }
9856
9857           BFD_ASSERT (dup_dot <= final_size);
9858           BFD_ASSERT (orig_dot <= orig_size);
9859         }
9860
9861       orig_dot += orig_dot_copied;
9862       orig_dot_copied = 0;
9863
9864       if (orig_dot != orig_size)
9865         {
9866           copy_size = orig_size - orig_dot;
9867           BFD_ASSERT (orig_size > orig_dot);
9868           BFD_ASSERT (dup_dot + copy_size == final_size);
9869           memmove (&dup_contents[dup_dot], &contents[orig_dot], copy_size);
9870           orig_dot += copy_size;
9871           dup_dot += copy_size;
9872         }
9873       BFD_ASSERT (orig_size == orig_dot);
9874       BFD_ASSERT (final_size == dup_dot);
9875
9876       /* Move the dup_contents back.  */
9877       if (final_size > orig_size)
9878         {
9879           /* Contents need to be reallocated.  Swap the dup_contents into
9880              contents.  */
9881           sec->contents = dup_contents;
9882           free (contents);
9883           contents = dup_contents;
9884           pin_contents (sec, contents);
9885         }
9886       else
9887         {
9888           BFD_ASSERT (final_size <= orig_size);
9889           memset (contents, 0, orig_size);
9890           memcpy (contents, dup_contents, final_size);
9891           free (dup_contents);
9892         }
9893       free (scratch);
9894       pin_contents (sec, contents);
9895
9896       if (sec->rawsize == 0)
9897         sec->rawsize = sec->size;
9898       sec->size = final_size;
9899     }
9900
9901  error_return:
9902   release_internal_relocs (sec, internal_relocs);
9903   release_contents (sec, contents);
9904   return ok;
9905 }
9906
9907
9908 static bfd_boolean
9909 translate_section_fixes (asection *sec)
9910 {
9911   xtensa_relax_info *relax_info;
9912   reloc_bfd_fix *r;
9913
9914   relax_info = get_xtensa_relax_info (sec);
9915   if (!relax_info)
9916     return TRUE;
9917
9918   for (r = relax_info->fix_list; r != NULL; r = r->next)
9919     if (!translate_reloc_bfd_fix (r))
9920       return FALSE;
9921
9922   return TRUE;
9923 }
9924
9925
9926 /* Translate a fix given the mapping in the relax info for the target
9927    section.  If it has already been translated, no work is required.  */
9928
9929 static bfd_boolean
9930 translate_reloc_bfd_fix (reloc_bfd_fix *fix)
9931 {
9932   reloc_bfd_fix new_fix;
9933   asection *sec;
9934   xtensa_relax_info *relax_info;
9935   removed_literal *removed;
9936   bfd_vma new_offset, target_offset;
9937
9938   if (fix->translated)
9939     return TRUE;
9940
9941   sec = fix->target_sec;
9942   target_offset = fix->target_offset;
9943
9944   relax_info = get_xtensa_relax_info (sec);
9945   if (!relax_info)
9946     {
9947       fix->translated = TRUE;
9948       return TRUE;
9949     }
9950
9951   new_fix = *fix;
9952
9953   /* The fix does not need to be translated if the section cannot change.  */
9954   if (!relax_info->is_relaxable_literal_section
9955       && !relax_info->is_relaxable_asm_section)
9956     {
9957       fix->translated = TRUE;
9958       return TRUE;
9959     }
9960
9961   /* If the literal has been moved and this relocation was on an
9962      opcode, then the relocation should move to the new literal
9963      location.  Otherwise, the relocation should move within the
9964      section.  */
9965
9966   removed = FALSE;
9967   if (is_operand_relocation (fix->src_type))
9968     {
9969       /* Check if the original relocation is against a literal being
9970          removed.  */
9971       removed = find_removed_literal (&relax_info->removed_list,
9972                                       target_offset);
9973     }
9974
9975   if (removed)
9976     {
9977       asection *new_sec;
9978
9979       /* The fact that there is still a relocation to this literal indicates
9980          that the literal is being coalesced, not simply removed.  */
9981       BFD_ASSERT (removed->to.abfd != NULL);
9982
9983       /* This was moved to some other address (possibly another section).  */
9984       new_sec = r_reloc_get_section (&removed->to);
9985       if (new_sec != sec)
9986         {
9987           sec = new_sec;
9988           relax_info = get_xtensa_relax_info (sec);
9989           if (!relax_info ||
9990               (!relax_info->is_relaxable_literal_section
9991                && !relax_info->is_relaxable_asm_section))
9992             {
9993               target_offset = removed->to.target_offset;
9994               new_fix.target_sec = new_sec;
9995               new_fix.target_offset = target_offset;
9996               new_fix.translated = TRUE;
9997               *fix = new_fix;
9998               return TRUE;
9999             }
10000         }
10001       target_offset = removed->to.target_offset;
10002       new_fix.target_sec = new_sec;
10003     }
10004
10005   /* The target address may have been moved within its section.  */
10006   new_offset = offset_with_removed_text (&relax_info->action_list,
10007                                          target_offset);
10008
10009   new_fix.target_offset = new_offset;
10010   new_fix.target_offset = new_offset;
10011   new_fix.translated = TRUE;
10012   *fix = new_fix;
10013   return TRUE;
10014 }
10015
10016
10017 /* Fix up a relocation to take account of removed literals.  */
10018
10019 static asection *
10020 translate_reloc (const r_reloc *orig_rel, r_reloc *new_rel, asection *sec)
10021 {
10022   xtensa_relax_info *relax_info;
10023   removed_literal *removed;
10024   bfd_vma target_offset, base_offset;
10025
10026   *new_rel = *orig_rel;
10027
10028   if (!r_reloc_is_defined (orig_rel))
10029     return sec ;
10030
10031   relax_info = get_xtensa_relax_info (sec);
10032   BFD_ASSERT (relax_info && (relax_info->is_relaxable_literal_section
10033                              || relax_info->is_relaxable_asm_section));
10034
10035   target_offset = orig_rel->target_offset;
10036
10037   removed = FALSE;
10038   if (is_operand_relocation (ELF32_R_TYPE (orig_rel->rela.r_info)))
10039     {
10040       /* Check if the original relocation is against a literal being
10041          removed.  */
10042       removed = find_removed_literal (&relax_info->removed_list,
10043                                       target_offset);
10044     }
10045   if (removed && removed->to.abfd)
10046     {
10047       asection *new_sec;
10048
10049       /* The fact that there is still a relocation to this literal indicates
10050          that the literal is being coalesced, not simply removed.  */
10051       BFD_ASSERT (removed->to.abfd != NULL);
10052
10053       /* This was moved to some other address
10054          (possibly in another section).  */
10055       *new_rel = removed->to;
10056       new_sec = r_reloc_get_section (new_rel);
10057       if (new_sec != sec)
10058         {
10059           sec = new_sec;
10060           relax_info = get_xtensa_relax_info (sec);
10061           if (!relax_info
10062               || (!relax_info->is_relaxable_literal_section
10063                   && !relax_info->is_relaxable_asm_section))
10064             return sec;
10065         }
10066       target_offset = new_rel->target_offset;
10067     }
10068
10069   /* Find the base offset of the reloc symbol, excluding any addend from the
10070      reloc or from the section contents (for a partial_inplace reloc).  Then
10071      find the adjusted values of the offsets due to relaxation.  The base
10072      offset is needed to determine the change to the reloc's addend; the reloc
10073      addend should not be adjusted due to relaxations located before the base
10074      offset.  */
10075
10076   base_offset = r_reloc_get_target_offset (new_rel) - new_rel->rela.r_addend;
10077   if (base_offset <= target_offset)
10078     {
10079       int base_removed = removed_by_actions_map (&relax_info->action_list,
10080                                                  base_offset, FALSE);
10081       int addend_removed = removed_by_actions_map (&relax_info->action_list,
10082                                                    target_offset, FALSE) -
10083         base_removed;
10084
10085       new_rel->target_offset = target_offset - base_removed - addend_removed;
10086       new_rel->rela.r_addend -= addend_removed;
10087     }
10088   else
10089     {
10090       /* Handle a negative addend.  The base offset comes first.  */
10091       int tgt_removed = removed_by_actions_map (&relax_info->action_list,
10092                                                 target_offset, FALSE);
10093       int addend_removed = removed_by_actions_map (&relax_info->action_list,
10094                                                    base_offset, FALSE) -
10095         tgt_removed;
10096
10097       new_rel->target_offset = target_offset - tgt_removed;
10098       new_rel->rela.r_addend += addend_removed;
10099     }
10100
10101   return sec;
10102 }
10103
10104
10105 /* For dynamic links, there may be a dynamic relocation for each
10106    literal.  The number of dynamic relocations must be computed in
10107    size_dynamic_sections, which occurs before relaxation.  When a
10108    literal is removed, this function checks if there is a corresponding
10109    dynamic relocation and shrinks the size of the appropriate dynamic
10110    relocation section accordingly.  At this point, the contents of the
10111    dynamic relocation sections have not yet been filled in, so there's
10112    nothing else that needs to be done.  */
10113
10114 static void
10115 shrink_dynamic_reloc_sections (struct bfd_link_info *info,
10116                                bfd *abfd,
10117                                asection *input_section,
10118                                Elf_Internal_Rela *rel)
10119 {
10120   struct elf_xtensa_link_hash_table *htab;
10121   Elf_Internal_Shdr *symtab_hdr;
10122   struct elf_link_hash_entry **sym_hashes;
10123   unsigned long r_symndx;
10124   int r_type;
10125   struct elf_link_hash_entry *h;
10126   bfd_boolean dynamic_symbol;
10127
10128   htab = elf_xtensa_hash_table (info);
10129   if (htab == NULL)
10130     return;
10131
10132   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10133   sym_hashes = elf_sym_hashes (abfd);
10134
10135   r_type = ELF32_R_TYPE (rel->r_info);
10136   r_symndx = ELF32_R_SYM (rel->r_info);
10137
10138   if (r_symndx < symtab_hdr->sh_info)
10139     h = NULL;
10140   else
10141     h = sym_hashes[r_symndx - symtab_hdr->sh_info];
10142
10143   dynamic_symbol = elf_xtensa_dynamic_symbol_p (h, info);
10144
10145   if ((r_type == R_XTENSA_32 || r_type == R_XTENSA_PLT)
10146       && (input_section->flags & SEC_ALLOC) != 0
10147       && (dynamic_symbol || bfd_link_pic (info))
10148       && (!h || h->root.type != bfd_link_hash_undefweak
10149           || (dynamic_symbol
10150               && (bfd_link_dll (info) || info->export_dynamic))))
10151     {
10152       asection *srel;
10153       bfd_boolean is_plt = FALSE;
10154
10155       if (dynamic_symbol && r_type == R_XTENSA_PLT)
10156         {
10157           srel = htab->elf.srelplt;
10158           is_plt = TRUE;
10159         }
10160       else
10161         srel = htab->elf.srelgot;
10162
10163       /* Reduce size of the .rela.* section by one reloc.  */
10164       BFD_ASSERT (srel != NULL);
10165       BFD_ASSERT (srel->size >= sizeof (Elf32_External_Rela));
10166       srel->size -= sizeof (Elf32_External_Rela);
10167
10168       if (is_plt)
10169         {
10170           asection *splt, *sgotplt, *srelgot;
10171           int reloc_index, chunk;
10172
10173           /* Find the PLT reloc index of the entry being removed.  This
10174              is computed from the size of ".rela.plt".  It is needed to
10175              figure out which PLT chunk to resize.  Usually "last index
10176              = size - 1" since the index starts at zero, but in this
10177              context, the size has just been decremented so there's no
10178              need to subtract one.  */
10179           reloc_index = srel->size / sizeof (Elf32_External_Rela);
10180
10181           chunk = reloc_index / PLT_ENTRIES_PER_CHUNK;
10182           splt = elf_xtensa_get_plt_section (info, chunk);
10183           sgotplt = elf_xtensa_get_gotplt_section (info, chunk);
10184           BFD_ASSERT (splt != NULL && sgotplt != NULL);
10185
10186           /* Check if an entire PLT chunk has just been eliminated.  */
10187           if (reloc_index % PLT_ENTRIES_PER_CHUNK == 0)
10188             {
10189               /* The two magic GOT entries for that chunk can go away.  */
10190               srelgot = htab->elf.srelgot;
10191               BFD_ASSERT (srelgot != NULL);
10192               srelgot->reloc_count -= 2;
10193               srelgot->size -= 2 * sizeof (Elf32_External_Rela);
10194               sgotplt->size -= 8;
10195
10196               /* There should be only one entry left (and it will be
10197                  removed below).  */
10198               BFD_ASSERT (sgotplt->size == 4);
10199               BFD_ASSERT (splt->size == PLT_ENTRY_SIZE);
10200             }
10201
10202           BFD_ASSERT (sgotplt->size >= 4);
10203           BFD_ASSERT (splt->size >= PLT_ENTRY_SIZE);
10204
10205           sgotplt->size -= 4;
10206           splt->size -= PLT_ENTRY_SIZE;
10207         }
10208     }
10209 }
10210
10211
10212 /* Take an r_rel and move it to another section.  This usually
10213    requires extending the interal_relocation array and pinning it.  If
10214    the original r_rel is from the same BFD, we can complete this here.
10215    Otherwise, we add a fix record to let the final link fix the
10216    appropriate address.  Contents and internal relocations for the
10217    section must be pinned after calling this routine.  */
10218
10219 static bfd_boolean
10220 move_literal (bfd *abfd,
10221               struct bfd_link_info *link_info,
10222               asection *sec,
10223               bfd_vma offset,
10224               bfd_byte *contents,
10225               xtensa_relax_info *relax_info,
10226               Elf_Internal_Rela **internal_relocs_p,
10227               const literal_value *lit)
10228 {
10229   Elf_Internal_Rela *new_relocs = NULL;
10230   size_t new_relocs_count = 0;
10231   Elf_Internal_Rela this_rela;
10232   const r_reloc *r_rel;
10233
10234   r_rel = &lit->r_rel;
10235   BFD_ASSERT (elf_section_data (sec)->relocs == *internal_relocs_p);
10236
10237   if (r_reloc_is_const (r_rel))
10238     bfd_put_32 (abfd, lit->value, contents + offset);
10239   else
10240     {
10241       int r_type;
10242       unsigned i;
10243       reloc_bfd_fix *fix;
10244       unsigned insert_at;
10245
10246       r_type = ELF32_R_TYPE (r_rel->rela.r_info);
10247
10248       /* This is the difficult case.  We have to create a fix up.  */
10249       this_rela.r_offset = offset;
10250       this_rela.r_info = ELF32_R_INFO (0, r_type);
10251       this_rela.r_addend =
10252         r_rel->target_offset - r_reloc_get_target_offset (r_rel);
10253       bfd_put_32 (abfd, lit->value, contents + offset);
10254
10255       /* Currently, we cannot move relocations during a relocatable link.  */
10256       BFD_ASSERT (!bfd_link_relocatable (link_info));
10257       fix = reloc_bfd_fix_init (sec, offset, r_type,
10258                                 r_reloc_get_section (r_rel),
10259                                 r_rel->target_offset + r_rel->virtual_offset,
10260                                 FALSE);
10261       /* We also need to mark that relocations are needed here.  */
10262       sec->flags |= SEC_RELOC;
10263
10264       translate_reloc_bfd_fix (fix);
10265       /* This fix has not yet been translated.  */
10266       add_fix (sec, fix);
10267
10268       /* Add the relocation.  If we have already allocated our own
10269          space for the relocations and we have room for more, then use
10270          it.  Otherwise, allocate new space and move the literals.  */
10271       insert_at = sec->reloc_count;
10272       for (i = 0; i < sec->reloc_count; ++i)
10273         {
10274           if (this_rela.r_offset < (*internal_relocs_p)[i].r_offset)
10275             {
10276               insert_at = i;
10277               break;
10278             }
10279         }
10280
10281       if (*internal_relocs_p != relax_info->allocated_relocs
10282           || sec->reloc_count + 1 > relax_info->allocated_relocs_count)
10283         {
10284           BFD_ASSERT (relax_info->allocated_relocs == NULL
10285                       || sec->reloc_count == relax_info->relocs_count);
10286
10287           if (relax_info->allocated_relocs_count == 0)
10288             new_relocs_count = (sec->reloc_count + 2) * 2;
10289           else
10290             new_relocs_count = (relax_info->allocated_relocs_count + 2) * 2;
10291
10292           new_relocs = (Elf_Internal_Rela *)
10293             bfd_zmalloc (sizeof (Elf_Internal_Rela) * (new_relocs_count));
10294           if (!new_relocs)
10295             return FALSE;
10296
10297           /* We could handle this more quickly by finding the split point.  */
10298           if (insert_at != 0)
10299             memcpy (new_relocs, *internal_relocs_p,
10300                     insert_at * sizeof (Elf_Internal_Rela));
10301
10302           new_relocs[insert_at] = this_rela;
10303
10304           if (insert_at != sec->reloc_count)
10305             memcpy (new_relocs + insert_at + 1,
10306                     (*internal_relocs_p) + insert_at,
10307                     (sec->reloc_count - insert_at)
10308                     * sizeof (Elf_Internal_Rela));
10309
10310           if (*internal_relocs_p != relax_info->allocated_relocs)
10311             {
10312               /* The first time we re-allocate, we can only free the
10313                  old relocs if they were allocated with bfd_malloc.
10314                  This is not true when keep_memory is in effect.  */
10315               if (!link_info->keep_memory)
10316                 free (*internal_relocs_p);
10317             }
10318           else
10319             free (*internal_relocs_p);
10320           relax_info->allocated_relocs = new_relocs;
10321           relax_info->allocated_relocs_count = new_relocs_count;
10322           elf_section_data (sec)->relocs = new_relocs;
10323           sec->reloc_count++;
10324           relax_info->relocs_count = sec->reloc_count;
10325           *internal_relocs_p = new_relocs;
10326         }
10327       else
10328         {
10329           if (insert_at != sec->reloc_count)
10330             {
10331               unsigned idx;
10332               for (idx = sec->reloc_count; idx > insert_at; idx--)
10333                 (*internal_relocs_p)[idx] = (*internal_relocs_p)[idx-1];
10334             }
10335           (*internal_relocs_p)[insert_at] = this_rela;
10336           sec->reloc_count++;
10337           if (relax_info->allocated_relocs)
10338             relax_info->relocs_count = sec->reloc_count;
10339         }
10340     }
10341   return TRUE;
10342 }
10343
10344
10345 /* This is similar to relax_section except that when a target is moved,
10346    we shift addresses up.  We also need to modify the size.  This
10347    algorithm does NOT allow for relocations into the middle of the
10348    property sections.  */
10349
10350 static bfd_boolean
10351 relax_property_section (bfd *abfd,
10352                         asection *sec,
10353                         struct bfd_link_info *link_info)
10354 {
10355   Elf_Internal_Rela *internal_relocs;
10356   bfd_byte *contents;
10357   unsigned i;
10358   bfd_boolean ok = TRUE;
10359   bfd_boolean is_full_prop_section;
10360   size_t last_zfill_target_offset = 0;
10361   asection *last_zfill_target_sec = NULL;
10362   bfd_size_type sec_size;
10363   bfd_size_type entry_size;
10364
10365   sec_size = bfd_get_section_limit (abfd, sec);
10366   internal_relocs = retrieve_internal_relocs (abfd, sec,
10367                                               link_info->keep_memory);
10368   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
10369   if (contents == NULL && sec_size != 0)
10370     {
10371       ok = FALSE;
10372       goto error_return;
10373     }
10374
10375   is_full_prop_section = xtensa_is_proptable_section (sec);
10376   if (is_full_prop_section)
10377     entry_size = 12;
10378   else
10379     entry_size = 8;
10380
10381   if (internal_relocs)
10382     {
10383       for (i = 0; i < sec->reloc_count; i++)
10384         {
10385           Elf_Internal_Rela *irel;
10386           xtensa_relax_info *target_relax_info;
10387           unsigned r_type;
10388           asection *target_sec;
10389           literal_value val;
10390           bfd_byte *size_p, *flags_p;
10391
10392           /* Locally change the source address.
10393              Translate the target to the new target address.
10394              If it points to this section and has been removed, MOVE IT.
10395              Also, don't forget to modify the associated SIZE at
10396              (offset + 4).  */
10397
10398           irel = &internal_relocs[i];
10399           r_type = ELF32_R_TYPE (irel->r_info);
10400           if (r_type == R_XTENSA_NONE)
10401             continue;
10402
10403           /* Find the literal value.  */
10404           r_reloc_init (&val.r_rel, abfd, irel, contents, sec_size);
10405           size_p = &contents[irel->r_offset + 4];
10406           flags_p = NULL;
10407           if (is_full_prop_section)
10408             flags_p = &contents[irel->r_offset + 8];
10409           BFD_ASSERT (irel->r_offset + entry_size <= sec_size);
10410
10411           target_sec = r_reloc_get_section (&val.r_rel);
10412           target_relax_info = get_xtensa_relax_info (target_sec);
10413
10414           if (target_relax_info
10415               && (target_relax_info->is_relaxable_literal_section
10416                   || target_relax_info->is_relaxable_asm_section ))
10417             {
10418               /* Translate the relocation's destination.  */
10419               bfd_vma old_offset = val.r_rel.target_offset;
10420               bfd_vma new_offset;
10421               long old_size, new_size;
10422               int removed_by_old_offset =
10423                 removed_by_actions_map (&target_relax_info->action_list,
10424                                         old_offset, FALSE);
10425               new_offset = old_offset - removed_by_old_offset;
10426
10427               /* Assert that we are not out of bounds.  */
10428               old_size = bfd_get_32 (abfd, size_p);
10429               new_size = old_size;
10430
10431               if (old_size == 0)
10432                 {
10433                   /* Only the first zero-sized unreachable entry is
10434                      allowed to expand.  In this case the new offset
10435                      should be the offset before the fill and the new
10436                      size is the expansion size.  For other zero-sized
10437                      entries the resulting size should be zero with an
10438                      offset before or after the fill address depending
10439                      on whether the expanding unreachable entry
10440                      preceeds it.  */
10441                   if (last_zfill_target_sec == 0
10442                       || last_zfill_target_sec != target_sec
10443                       || last_zfill_target_offset != old_offset)
10444                     {
10445                       bfd_vma new_end_offset = new_offset;
10446
10447                       /* Recompute the new_offset, but this time don't
10448                          include any fill inserted by relaxation.  */
10449                       removed_by_old_offset =
10450                         removed_by_actions_map (&target_relax_info->action_list,
10451                                                 old_offset, TRUE);
10452                       new_offset = old_offset - removed_by_old_offset;
10453
10454                       /* If it is not unreachable and we have not yet
10455                          seen an unreachable at this address, place it
10456                          before the fill address.  */
10457                       if (flags_p && (bfd_get_32 (abfd, flags_p)
10458                                       & XTENSA_PROP_UNREACHABLE) != 0)
10459                         {
10460                           new_size = new_end_offset - new_offset;
10461
10462                           last_zfill_target_sec = target_sec;
10463                           last_zfill_target_offset = old_offset;
10464                         }
10465                     }
10466                 }
10467               else
10468                 {
10469                   int removed_by_old_offset_size =
10470                     removed_by_actions_map (&target_relax_info->action_list,
10471                                             old_offset + old_size, TRUE);
10472                   new_size -= removed_by_old_offset_size - removed_by_old_offset;
10473                 }
10474
10475               if (new_size != old_size)
10476                 {
10477                   bfd_put_32 (abfd, new_size, size_p);
10478                   pin_contents (sec, contents);
10479                 }
10480
10481               if (new_offset != old_offset)
10482                 {
10483                   bfd_vma diff = new_offset - old_offset;
10484                   irel->r_addend += diff;
10485                   pin_internal_relocs (sec, internal_relocs);
10486                 }
10487             }
10488         }
10489     }
10490
10491   /* Combine adjacent property table entries.  This is also done in
10492      finish_dynamic_sections() but at that point it's too late to
10493      reclaim the space in the output section, so we do this twice.  */
10494
10495   if (internal_relocs && (!bfd_link_relocatable (link_info)
10496                           || xtensa_is_littable_section (sec)))
10497     {
10498       Elf_Internal_Rela *last_irel = NULL;
10499       Elf_Internal_Rela *irel, *next_rel, *rel_end;
10500       int removed_bytes = 0;
10501       bfd_vma offset;
10502       flagword predef_flags;
10503
10504       predef_flags = xtensa_get_property_predef_flags (sec);
10505
10506       /* Walk over memory and relocations at the same time.
10507          This REQUIRES that the internal_relocs be sorted by offset.  */
10508       qsort (internal_relocs, sec->reloc_count, sizeof (Elf_Internal_Rela),
10509              internal_reloc_compare);
10510
10511       pin_internal_relocs (sec, internal_relocs);
10512       pin_contents (sec, contents);
10513
10514       next_rel = internal_relocs;
10515       rel_end = internal_relocs + sec->reloc_count;
10516
10517       BFD_ASSERT (sec->size % entry_size == 0);
10518
10519       for (offset = 0; offset < sec->size; offset += entry_size)
10520         {
10521           Elf_Internal_Rela *offset_rel, *extra_rel;
10522           bfd_vma bytes_to_remove, size, actual_offset;
10523           bfd_boolean remove_this_rel;
10524           flagword flags;
10525
10526           /* Find the first relocation for the entry at the current offset.
10527              Adjust the offsets of any extra relocations for the previous
10528              entry.  */
10529           offset_rel = NULL;
10530           if (next_rel)
10531             {
10532               for (irel = next_rel; irel < rel_end; irel++)
10533                 {
10534                   if ((irel->r_offset == offset
10535                        && ELF32_R_TYPE (irel->r_info) != R_XTENSA_NONE)
10536                       || irel->r_offset > offset)
10537                     {
10538                       offset_rel = irel;
10539                       break;
10540                     }
10541                   irel->r_offset -= removed_bytes;
10542                 }
10543             }
10544
10545           /* Find the next relocation (if there are any left).  */
10546           extra_rel = NULL;
10547           if (offset_rel)
10548             {
10549               for (irel = offset_rel + 1; irel < rel_end; irel++)
10550                 {
10551                   if (ELF32_R_TYPE (irel->r_info) != R_XTENSA_NONE)
10552                     {
10553                       extra_rel = irel;
10554                       break;
10555                     }
10556                 }
10557             }
10558
10559           /* Check if there are relocations on the current entry.  There
10560              should usually be a relocation on the offset field.  If there
10561              are relocations on the size or flags, then we can't optimize
10562              this entry.  Also, find the next relocation to examine on the
10563              next iteration.  */
10564           if (offset_rel)
10565             {
10566               if (offset_rel->r_offset >= offset + entry_size)
10567                 {
10568                   next_rel = offset_rel;
10569                   /* There are no relocations on the current entry, but we
10570                      might still be able to remove it if the size is zero.  */
10571                   offset_rel = NULL;
10572                 }
10573               else if (offset_rel->r_offset > offset
10574                        || (extra_rel
10575                            && extra_rel->r_offset < offset + entry_size))
10576                 {
10577                   /* There is a relocation on the size or flags, so we can't
10578                      do anything with this entry.  Continue with the next.  */
10579                   next_rel = offset_rel;
10580                   continue;
10581                 }
10582               else
10583                 {
10584                   BFD_ASSERT (offset_rel->r_offset == offset);
10585                   offset_rel->r_offset -= removed_bytes;
10586                   next_rel = offset_rel + 1;
10587                 }
10588             }
10589           else
10590             next_rel = NULL;
10591
10592           remove_this_rel = FALSE;
10593           bytes_to_remove = 0;
10594           actual_offset = offset - removed_bytes;
10595           size = bfd_get_32 (abfd, &contents[actual_offset + 4]);
10596
10597           if (is_full_prop_section)
10598             flags = bfd_get_32 (abfd, &contents[actual_offset + 8]);
10599           else
10600             flags = predef_flags;
10601
10602           if (size == 0
10603               && (flags & XTENSA_PROP_ALIGN) == 0
10604               && (flags & XTENSA_PROP_UNREACHABLE) == 0)
10605             {
10606               /* Always remove entries with zero size and no alignment.  */
10607               bytes_to_remove = entry_size;
10608               if (offset_rel)
10609                 remove_this_rel = TRUE;
10610             }
10611           else if (offset_rel
10612                    && ELF32_R_TYPE (offset_rel->r_info) == R_XTENSA_32)
10613             {
10614               if (last_irel)
10615                 {
10616                   flagword old_flags;
10617                   bfd_vma old_size =
10618                     bfd_get_32 (abfd, &contents[last_irel->r_offset + 4]);
10619                   bfd_vma old_address =
10620                     (last_irel->r_addend
10621                      + bfd_get_32 (abfd, &contents[last_irel->r_offset]));
10622                   bfd_vma new_address =
10623                     (offset_rel->r_addend
10624                      + bfd_get_32 (abfd, &contents[actual_offset]));
10625                   if (is_full_prop_section)
10626                     old_flags = bfd_get_32
10627                       (abfd, &contents[last_irel->r_offset + 8]);
10628                   else
10629                     old_flags = predef_flags;
10630
10631                   if ((ELF32_R_SYM (offset_rel->r_info)
10632                        == ELF32_R_SYM (last_irel->r_info))
10633                       && old_address + old_size == new_address
10634                       && old_flags == flags
10635                       && (old_flags & XTENSA_PROP_INSN_BRANCH_TARGET) == 0
10636                       && (old_flags & XTENSA_PROP_INSN_LOOP_TARGET) == 0)
10637                     {
10638                       /* Fix the old size.  */
10639                       bfd_put_32 (abfd, old_size + size,
10640                                   &contents[last_irel->r_offset + 4]);
10641                       bytes_to_remove = entry_size;
10642                       remove_this_rel = TRUE;
10643                     }
10644                   else
10645                     last_irel = offset_rel;
10646                 }
10647               else
10648                 last_irel = offset_rel;
10649             }
10650
10651           if (remove_this_rel)
10652             {
10653               offset_rel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
10654               offset_rel->r_offset = 0;
10655             }
10656
10657           if (bytes_to_remove != 0)
10658             {
10659               removed_bytes += bytes_to_remove;
10660               if (offset + bytes_to_remove < sec->size)
10661                 memmove (&contents[actual_offset],
10662                          &contents[actual_offset + bytes_to_remove],
10663                          sec->size - offset - bytes_to_remove);
10664             }
10665         }
10666
10667       if (removed_bytes)
10668         {
10669           /* Fix up any extra relocations on the last entry.  */
10670           for (irel = next_rel; irel < rel_end; irel++)
10671             irel->r_offset -= removed_bytes;
10672
10673           /* Clear the removed bytes.  */
10674           memset (&contents[sec->size - removed_bytes], 0, removed_bytes);
10675
10676           if (sec->rawsize == 0)
10677             sec->rawsize = sec->size;
10678           sec->size -= removed_bytes;
10679
10680           if (xtensa_is_littable_section (sec))
10681             {
10682               asection *sgotloc = elf_xtensa_hash_table (link_info)->sgotloc;
10683               if (sgotloc)
10684                 sgotloc->size -= removed_bytes;
10685             }
10686         }
10687     }
10688
10689  error_return:
10690   release_internal_relocs (sec, internal_relocs);
10691   release_contents (sec, contents);
10692   return ok;
10693 }
10694
10695 \f
10696 /* Third relaxation pass.  */
10697
10698 /* Change symbol values to account for removed literals.  */
10699
10700 bfd_boolean
10701 relax_section_symbols (bfd *abfd, asection *sec)
10702 {
10703   xtensa_relax_info *relax_info;
10704   unsigned int sec_shndx;
10705   Elf_Internal_Shdr *symtab_hdr;
10706   Elf_Internal_Sym *isymbuf;
10707   unsigned i, num_syms, num_locals;
10708
10709   relax_info = get_xtensa_relax_info (sec);
10710   BFD_ASSERT (relax_info);
10711
10712   if (!relax_info->is_relaxable_literal_section
10713       && !relax_info->is_relaxable_asm_section)
10714     return TRUE;
10715
10716   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
10717
10718   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10719   isymbuf = retrieve_local_syms (abfd);
10720
10721   num_syms = symtab_hdr->sh_size / sizeof (Elf32_External_Sym);
10722   num_locals = symtab_hdr->sh_info;
10723
10724   /* Adjust the local symbols defined in this section.  */
10725   for (i = 0; i < num_locals; i++)
10726     {
10727       Elf_Internal_Sym *isym = &isymbuf[i];
10728
10729       if (isym->st_shndx == sec_shndx)
10730         {
10731           bfd_vma orig_addr = isym->st_value;
10732           int removed = removed_by_actions_map (&relax_info->action_list,
10733                                                 orig_addr, FALSE);
10734
10735           isym->st_value -= removed;
10736           if (ELF32_ST_TYPE (isym->st_info) == STT_FUNC)
10737             isym->st_size -=
10738               removed_by_actions_map (&relax_info->action_list,
10739                                       orig_addr + isym->st_size, FALSE) -
10740               removed;
10741         }
10742     }
10743
10744   /* Now adjust the global symbols defined in this section.  */
10745   for (i = 0; i < (num_syms - num_locals); i++)
10746     {
10747       struct elf_link_hash_entry *sym_hash;
10748
10749       sym_hash = elf_sym_hashes (abfd)[i];
10750
10751       if (sym_hash->root.type == bfd_link_hash_warning)
10752         sym_hash = (struct elf_link_hash_entry *) sym_hash->root.u.i.link;
10753
10754       if ((sym_hash->root.type == bfd_link_hash_defined
10755            || sym_hash->root.type == bfd_link_hash_defweak)
10756           && sym_hash->root.u.def.section == sec)
10757         {
10758           bfd_vma orig_addr = sym_hash->root.u.def.value;
10759           int removed = removed_by_actions_map (&relax_info->action_list,
10760                                                 orig_addr, FALSE);
10761
10762           sym_hash->root.u.def.value -= removed;
10763
10764           if (sym_hash->type == STT_FUNC)
10765             sym_hash->size -=
10766               removed_by_actions_map (&relax_info->action_list,
10767                                       orig_addr + sym_hash->size, FALSE) -
10768               removed;
10769         }
10770     }
10771
10772   return TRUE;
10773 }
10774
10775 \f
10776 /* "Fix" handling functions, called while performing relocations.  */
10777
10778 static bfd_boolean
10779 do_fix_for_relocatable_link (Elf_Internal_Rela *rel,
10780                              bfd *input_bfd,
10781                              asection *input_section,
10782                              bfd_byte *contents)
10783 {
10784   r_reloc r_rel;
10785   asection *sec, *old_sec;
10786   bfd_vma old_offset;
10787   int r_type = ELF32_R_TYPE (rel->r_info);
10788   reloc_bfd_fix *fix;
10789
10790   if (r_type == R_XTENSA_NONE)
10791     return TRUE;
10792
10793   fix = get_bfd_fix (input_section, rel->r_offset, r_type);
10794   if (!fix)
10795     return TRUE;
10796
10797   r_reloc_init (&r_rel, input_bfd, rel, contents,
10798                 bfd_get_section_limit (input_bfd, input_section));
10799   old_sec = r_reloc_get_section (&r_rel);
10800   old_offset = r_rel.target_offset;
10801
10802   if (!old_sec || !r_reloc_is_defined (&r_rel))
10803     {
10804       if (r_type != R_XTENSA_ASM_EXPAND)
10805         {
10806           _bfd_error_handler
10807             /* xgettext:c-format */
10808             (_("%pB(%pA+%#" PRIx64 "): unexpected fix for %s relocation"),
10809              input_bfd, input_section, (uint64_t) rel->r_offset,
10810              elf_howto_table[r_type].name);
10811           return FALSE;
10812         }
10813       /* Leave it be.  Resolution will happen in a later stage.  */
10814     }
10815   else
10816     {
10817       sec = fix->target_sec;
10818       rel->r_addend += ((sec->output_offset + fix->target_offset)
10819                         - (old_sec->output_offset + old_offset));
10820     }
10821   return TRUE;
10822 }
10823
10824
10825 static void
10826 do_fix_for_final_link (Elf_Internal_Rela *rel,
10827                        bfd *input_bfd,
10828                        asection *input_section,
10829                        bfd_byte *contents,
10830                        bfd_vma *relocationp)
10831 {
10832   asection *sec;
10833   int r_type = ELF32_R_TYPE (rel->r_info);
10834   reloc_bfd_fix *fix;
10835   bfd_vma fixup_diff;
10836
10837   if (r_type == R_XTENSA_NONE)
10838     return;
10839
10840   fix = get_bfd_fix (input_section, rel->r_offset, r_type);
10841   if (!fix)
10842     return;
10843
10844   sec = fix->target_sec;
10845
10846   fixup_diff = rel->r_addend;
10847   if (elf_howto_table[fix->src_type].partial_inplace)
10848     {
10849       bfd_vma inplace_val;
10850       BFD_ASSERT (fix->src_offset
10851                   < bfd_get_section_limit (input_bfd, input_section));
10852       inplace_val = bfd_get_32 (input_bfd, &contents[fix->src_offset]);
10853       fixup_diff += inplace_val;
10854     }
10855
10856   *relocationp = (sec->output_section->vma
10857                   + sec->output_offset
10858                   + fix->target_offset - fixup_diff);
10859 }
10860
10861 \f
10862 /* Miscellaneous utility functions....  */
10863
10864 static asection *
10865 elf_xtensa_get_plt_section (struct bfd_link_info *info, int chunk)
10866 {
10867   bfd *dynobj;
10868   char plt_name[17];
10869
10870   if (chunk == 0)
10871     return elf_hash_table (info)->splt;
10872
10873   dynobj = elf_hash_table (info)->dynobj;
10874   sprintf (plt_name, ".plt.%u", chunk);
10875   return bfd_get_linker_section (dynobj, plt_name);
10876 }
10877
10878
10879 static asection *
10880 elf_xtensa_get_gotplt_section (struct bfd_link_info *info, int chunk)
10881 {
10882   bfd *dynobj;
10883   char got_name[21];
10884
10885   if (chunk == 0)
10886     return elf_hash_table (info)->sgotplt;
10887
10888   dynobj = elf_hash_table (info)->dynobj;
10889   sprintf (got_name, ".got.plt.%u", chunk);
10890   return bfd_get_linker_section (dynobj, got_name);
10891 }
10892
10893
10894 /* Get the input section for a given symbol index.
10895    If the symbol is:
10896    . a section symbol, return the section;
10897    . a common symbol, return the common section;
10898    . an undefined symbol, return the undefined section;
10899    . an indirect symbol, follow the links;
10900    . an absolute value, return the absolute section.  */
10901
10902 static asection *
10903 get_elf_r_symndx_section (bfd *abfd, unsigned long r_symndx)
10904 {
10905   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10906   asection *target_sec = NULL;
10907   if (r_symndx < symtab_hdr->sh_info)
10908     {
10909       Elf_Internal_Sym *isymbuf;
10910       unsigned int section_index;
10911
10912       isymbuf = retrieve_local_syms (abfd);
10913       section_index = isymbuf[r_symndx].st_shndx;
10914
10915       if (section_index == SHN_UNDEF)
10916         target_sec = bfd_und_section_ptr;
10917       else if (section_index == SHN_ABS)
10918         target_sec = bfd_abs_section_ptr;
10919       else if (section_index == SHN_COMMON)
10920         target_sec = bfd_com_section_ptr;
10921       else
10922         target_sec = bfd_section_from_elf_index (abfd, section_index);
10923     }
10924   else
10925     {
10926       unsigned long indx = r_symndx - symtab_hdr->sh_info;
10927       struct elf_link_hash_entry *h = elf_sym_hashes (abfd)[indx];
10928
10929       while (h->root.type == bfd_link_hash_indirect
10930              || h->root.type == bfd_link_hash_warning)
10931         h = (struct elf_link_hash_entry *) h->root.u.i.link;
10932
10933       switch (h->root.type)
10934         {
10935         case bfd_link_hash_defined:
10936         case  bfd_link_hash_defweak:
10937           target_sec = h->root.u.def.section;
10938           break;
10939         case bfd_link_hash_common:
10940           target_sec = bfd_com_section_ptr;
10941           break;
10942         case bfd_link_hash_undefined:
10943         case bfd_link_hash_undefweak:
10944           target_sec = bfd_und_section_ptr;
10945           break;
10946         default: /* New indirect warning.  */
10947           target_sec = bfd_und_section_ptr;
10948           break;
10949         }
10950     }
10951   return target_sec;
10952 }
10953
10954
10955 static struct elf_link_hash_entry *
10956 get_elf_r_symndx_hash_entry (bfd *abfd, unsigned long r_symndx)
10957 {
10958   unsigned long indx;
10959   struct elf_link_hash_entry *h;
10960   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10961
10962   if (r_symndx < symtab_hdr->sh_info)
10963     return NULL;
10964
10965   indx = r_symndx - symtab_hdr->sh_info;
10966   h = elf_sym_hashes (abfd)[indx];
10967   while (h->root.type == bfd_link_hash_indirect
10968          || h->root.type == bfd_link_hash_warning)
10969     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10970   return h;
10971 }
10972
10973
10974 /* Get the section-relative offset for a symbol number.  */
10975
10976 static bfd_vma
10977 get_elf_r_symndx_offset (bfd *abfd, unsigned long r_symndx)
10978 {
10979   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10980   bfd_vma offset = 0;
10981
10982   if (r_symndx < symtab_hdr->sh_info)
10983     {
10984       Elf_Internal_Sym *isymbuf;
10985       isymbuf = retrieve_local_syms (abfd);
10986       offset = isymbuf[r_symndx].st_value;
10987     }
10988   else
10989     {
10990       unsigned long indx = r_symndx - symtab_hdr->sh_info;
10991       struct elf_link_hash_entry *h =
10992         elf_sym_hashes (abfd)[indx];
10993
10994       while (h->root.type == bfd_link_hash_indirect
10995              || h->root.type == bfd_link_hash_warning)
10996         h = (struct elf_link_hash_entry *) h->root.u.i.link;
10997       if (h->root.type == bfd_link_hash_defined
10998           || h->root.type == bfd_link_hash_defweak)
10999         offset = h->root.u.def.value;
11000     }
11001   return offset;
11002 }
11003
11004
11005 static bfd_boolean
11006 is_reloc_sym_weak (bfd *abfd, Elf_Internal_Rela *rel)
11007 {
11008   unsigned long r_symndx = ELF32_R_SYM (rel->r_info);
11009   struct elf_link_hash_entry *h;
11010
11011   h = get_elf_r_symndx_hash_entry (abfd, r_symndx);
11012   if (h && h->root.type == bfd_link_hash_defweak)
11013     return TRUE;
11014   return FALSE;
11015 }
11016
11017
11018 static bfd_boolean
11019 pcrel_reloc_fits (xtensa_opcode opc,
11020                   int opnd,
11021                   bfd_vma self_address,
11022                   bfd_vma dest_address)
11023 {
11024   xtensa_isa isa = xtensa_default_isa;
11025   uint32 valp = dest_address;
11026   if (xtensa_operand_do_reloc (isa, opc, opnd, &valp, self_address)
11027       || xtensa_operand_encode (isa, opc, opnd, &valp))
11028     return FALSE;
11029   return TRUE;
11030 }
11031
11032
11033 static bfd_boolean
11034 xtensa_is_property_section (asection *sec)
11035 {
11036   if (xtensa_is_insntable_section (sec)
11037       || xtensa_is_littable_section (sec)
11038       || xtensa_is_proptable_section (sec))
11039     return TRUE;
11040
11041   return FALSE;
11042 }
11043
11044
11045 static bfd_boolean
11046 xtensa_is_insntable_section (asection *sec)
11047 {
11048   if (CONST_STRNEQ (sec->name, XTENSA_INSN_SEC_NAME)
11049       || CONST_STRNEQ (sec->name, ".gnu.linkonce.x."))
11050     return TRUE;
11051
11052   return FALSE;
11053 }
11054
11055
11056 static bfd_boolean
11057 xtensa_is_littable_section (asection *sec)
11058 {
11059   if (CONST_STRNEQ (sec->name, XTENSA_LIT_SEC_NAME)
11060       || CONST_STRNEQ (sec->name, ".gnu.linkonce.p."))
11061     return TRUE;
11062
11063   return FALSE;
11064 }
11065
11066
11067 static bfd_boolean
11068 xtensa_is_proptable_section (asection *sec)
11069 {
11070   if (CONST_STRNEQ (sec->name, XTENSA_PROP_SEC_NAME)
11071       || CONST_STRNEQ (sec->name, ".gnu.linkonce.prop."))
11072     return TRUE;
11073
11074   return FALSE;
11075 }
11076
11077
11078 static int
11079 internal_reloc_compare (const void *ap, const void *bp)
11080 {
11081   const Elf_Internal_Rela *a = (const Elf_Internal_Rela *) ap;
11082   const Elf_Internal_Rela *b = (const Elf_Internal_Rela *) bp;
11083
11084   if (a->r_offset != b->r_offset)
11085     return (a->r_offset - b->r_offset);
11086
11087   /* We don't need to sort on these criteria for correctness,
11088      but enforcing a more strict ordering prevents unstable qsort
11089      from behaving differently with different implementations.
11090      Without the code below we get correct but different results
11091      on Solaris 2.7 and 2.8.  We would like to always produce the
11092      same results no matter the host.  */
11093
11094   if (a->r_info != b->r_info)
11095     return (a->r_info - b->r_info);
11096
11097   return (a->r_addend - b->r_addend);
11098 }
11099
11100
11101 static int
11102 internal_reloc_matches (const void *ap, const void *bp)
11103 {
11104   const Elf_Internal_Rela *a = (const Elf_Internal_Rela *) ap;
11105   const Elf_Internal_Rela *b = (const Elf_Internal_Rela *) bp;
11106
11107   /* Check if one entry overlaps with the other; this shouldn't happen
11108      except when searching for a match.  */
11109   return (a->r_offset - b->r_offset);
11110 }
11111
11112
11113 /* Predicate function used to look up a section in a particular group.  */
11114
11115 static bfd_boolean
11116 match_section_group (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, void *inf)
11117 {
11118   const char *gname = inf;
11119   const char *group_name = elf_group_name (sec);
11120
11121   return (group_name == gname
11122           || (group_name != NULL
11123               && gname != NULL
11124               && strcmp (group_name, gname) == 0));
11125 }
11126
11127
11128 static char *
11129 xtensa_add_names (const char *base, const char *suffix)
11130 {
11131   if (suffix)
11132     {
11133       size_t base_len = strlen (base);
11134       size_t suffix_len = strlen (suffix);
11135       char *str = bfd_malloc (base_len + suffix_len + 1);
11136
11137       memcpy (str, base, base_len);
11138       memcpy (str + base_len, suffix, suffix_len + 1);
11139       return str;
11140     }
11141   else
11142     {
11143       return strdup (base);
11144     }
11145 }
11146
11147 static int linkonce_len = sizeof (".gnu.linkonce.") - 1;
11148
11149 static char *
11150 xtensa_property_section_name (asection *sec, const char *base_name,
11151                               bfd_boolean separate_sections)
11152 {
11153   const char *suffix, *group_name;
11154   char *prop_sec_name;
11155
11156   group_name = elf_group_name (sec);
11157   if (group_name)
11158     {
11159       suffix = strrchr (sec->name, '.');
11160       if (suffix == sec->name)
11161         suffix = 0;
11162       prop_sec_name = xtensa_add_names (base_name, suffix);
11163     }
11164   else if (strncmp (sec->name, ".gnu.linkonce.", linkonce_len) == 0)
11165     {
11166       char *linkonce_kind = 0;
11167
11168       if (strcmp (base_name, XTENSA_INSN_SEC_NAME) == 0)
11169         linkonce_kind = "x.";
11170       else if (strcmp (base_name, XTENSA_LIT_SEC_NAME) == 0)
11171         linkonce_kind = "p.";
11172       else if (strcmp (base_name, XTENSA_PROP_SEC_NAME) == 0)
11173         linkonce_kind = "prop.";
11174       else
11175         abort ();
11176
11177       prop_sec_name = (char *) bfd_malloc (strlen (sec->name)
11178                                            + strlen (linkonce_kind) + 1);
11179       memcpy (prop_sec_name, ".gnu.linkonce.", linkonce_len);
11180       strcpy (prop_sec_name + linkonce_len, linkonce_kind);
11181
11182       suffix = sec->name + linkonce_len;
11183       /* For backward compatibility, replace "t." instead of inserting
11184          the new linkonce_kind (but not for "prop" sections).  */
11185       if (CONST_STRNEQ (suffix, "t.") && linkonce_kind[1] == '.')
11186         suffix += 2;
11187       strcat (prop_sec_name + linkonce_len, suffix);
11188     }
11189   else
11190     {
11191       prop_sec_name = xtensa_add_names (base_name,
11192                                         separate_sections ? sec->name : NULL);
11193     }
11194
11195   return prop_sec_name;
11196 }
11197
11198
11199 static asection *
11200 xtensa_get_separate_property_section (asection *sec, const char *base_name,
11201                                       bfd_boolean separate_section)
11202 {
11203   char *prop_sec_name;
11204   asection *prop_sec;
11205
11206   prop_sec_name = xtensa_property_section_name (sec, base_name,
11207                                                 separate_section);
11208   prop_sec = bfd_get_section_by_name_if (sec->owner, prop_sec_name,
11209                                          match_section_group,
11210                                          (void *) elf_group_name (sec));
11211   free (prop_sec_name);
11212   return prop_sec;
11213 }
11214
11215 static asection *
11216 xtensa_get_property_section (asection *sec, const char *base_name)
11217 {
11218   asection *prop_sec;
11219
11220   /* Try individual property section first.  */
11221   prop_sec = xtensa_get_separate_property_section (sec, base_name, TRUE);
11222
11223   /* Refer to a common property section if individual is not present.  */
11224   if (!prop_sec)
11225     prop_sec = xtensa_get_separate_property_section (sec, base_name, FALSE);
11226
11227   return prop_sec;
11228 }
11229
11230
11231 asection *
11232 xtensa_make_property_section (asection *sec, const char *base_name)
11233 {
11234   char *prop_sec_name;
11235   asection *prop_sec;
11236
11237   /* Check if the section already exists.  */
11238   prop_sec_name = xtensa_property_section_name (sec, base_name,
11239                                                 elf32xtensa_separate_props);
11240   prop_sec = bfd_get_section_by_name_if (sec->owner, prop_sec_name,
11241                                          match_section_group,
11242                                          (void *) elf_group_name (sec));
11243   /* If not, create it.  */
11244   if (! prop_sec)
11245     {
11246       flagword flags = (SEC_RELOC | SEC_HAS_CONTENTS | SEC_READONLY);
11247       flags |= (bfd_get_section_flags (sec->owner, sec)
11248                 & (SEC_LINK_ONCE | SEC_LINK_DUPLICATES));
11249
11250       prop_sec = bfd_make_section_anyway_with_flags
11251         (sec->owner, strdup (prop_sec_name), flags);
11252       if (! prop_sec)
11253         return 0;
11254
11255       elf_group_name (prop_sec) = elf_group_name (sec);
11256     }
11257
11258   free (prop_sec_name);
11259   return prop_sec;
11260 }
11261
11262
11263 flagword
11264 xtensa_get_property_predef_flags (asection *sec)
11265 {
11266   if (xtensa_is_insntable_section (sec))
11267     return (XTENSA_PROP_INSN
11268             | XTENSA_PROP_NO_TRANSFORM
11269             | XTENSA_PROP_INSN_NO_REORDER);
11270
11271   if (xtensa_is_littable_section (sec))
11272     return (XTENSA_PROP_LITERAL
11273             | XTENSA_PROP_NO_TRANSFORM
11274             | XTENSA_PROP_INSN_NO_REORDER);
11275
11276   return 0;
11277 }
11278
11279 \f
11280 /* Other functions called directly by the linker.  */
11281
11282 bfd_boolean
11283 xtensa_callback_required_dependence (bfd *abfd,
11284                                      asection *sec,
11285                                      struct bfd_link_info *link_info,
11286                                      deps_callback_t callback,
11287                                      void *closure)
11288 {
11289   Elf_Internal_Rela *internal_relocs;
11290   bfd_byte *contents;
11291   unsigned i;
11292   bfd_boolean ok = TRUE;
11293   bfd_size_type sec_size;
11294
11295   sec_size = bfd_get_section_limit (abfd, sec);
11296
11297   /* ".plt*" sections have no explicit relocations but they contain L32R
11298      instructions that reference the corresponding ".got.plt*" sections.  */
11299   if ((sec->flags & SEC_LINKER_CREATED) != 0
11300       && CONST_STRNEQ (sec->name, ".plt"))
11301     {
11302       asection *sgotplt;
11303
11304       /* Find the corresponding ".got.plt*" section.  */
11305       if (sec->name[4] == '\0')
11306         sgotplt = elf_hash_table (link_info)->sgotplt;
11307       else
11308         {
11309           char got_name[14];
11310           int chunk = 0;
11311
11312           BFD_ASSERT (sec->name[4] == '.');
11313           chunk = strtol (&sec->name[5], NULL, 10);
11314
11315           sprintf (got_name, ".got.plt.%u", chunk);
11316           sgotplt = bfd_get_linker_section (sec->owner, got_name);
11317         }
11318       BFD_ASSERT (sgotplt);
11319
11320       /* Assume worst-case offsets: L32R at the very end of the ".plt"
11321          section referencing a literal at the very beginning of
11322          ".got.plt".  This is very close to the real dependence, anyway.  */
11323       (*callback) (sec, sec_size, sgotplt, 0, closure);
11324     }
11325
11326   /* Only ELF files are supported for Xtensa.  Check here to avoid a segfault
11327      when building uclibc, which runs "ld -b binary /dev/null".  */
11328   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
11329     return ok;
11330
11331   internal_relocs = retrieve_internal_relocs (abfd, sec,
11332                                               link_info->keep_memory);
11333   if (internal_relocs == NULL
11334       || sec->reloc_count == 0)
11335     return ok;
11336
11337   /* Cache the contents for the duration of this scan.  */
11338   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
11339   if (contents == NULL && sec_size != 0)
11340     {
11341       ok = FALSE;
11342       goto error_return;
11343     }
11344
11345   if (!xtensa_default_isa)
11346     xtensa_default_isa = xtensa_isa_init (0, 0);
11347
11348   for (i = 0; i < sec->reloc_count; i++)
11349     {
11350       Elf_Internal_Rela *irel = &internal_relocs[i];
11351       if (is_l32r_relocation (abfd, sec, contents, irel))
11352         {
11353           r_reloc l32r_rel;
11354           asection *target_sec;
11355           bfd_vma target_offset;
11356
11357           r_reloc_init (&l32r_rel, abfd, irel, contents, sec_size);
11358           target_sec = NULL;
11359           target_offset = 0;
11360           /* L32Rs must be local to the input file.  */
11361           if (r_reloc_is_defined (&l32r_rel))
11362             {
11363               target_sec = r_reloc_get_section (&l32r_rel);
11364               target_offset = l32r_rel.target_offset;
11365             }
11366           (*callback) (sec, irel->r_offset, target_sec, target_offset,
11367                        closure);
11368         }
11369     }
11370
11371  error_return:
11372   release_internal_relocs (sec, internal_relocs);
11373   release_contents (sec, contents);
11374   return ok;
11375 }
11376
11377 /* The default literal sections should always be marked as "code" (i.e.,
11378    SHF_EXECINSTR).  This is particularly important for the Linux kernel
11379    module loader so that the literals are not placed after the text.  */
11380 static const struct bfd_elf_special_section elf_xtensa_special_sections[] =
11381 {
11382   { STRING_COMMA_LEN (".fini.literal"), 0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
11383   { STRING_COMMA_LEN (".init.literal"), 0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
11384   { STRING_COMMA_LEN (".literal"),      0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
11385   { STRING_COMMA_LEN (".xtensa.info"),  0, SHT_NOTE,     0 },
11386   { NULL,                       0,      0, 0,            0 }
11387 };
11388 \f
11389 #define ELF_TARGET_ID                   XTENSA_ELF_DATA
11390 #ifndef ELF_ARCH
11391 #define TARGET_LITTLE_SYM               xtensa_elf32_le_vec
11392 #define TARGET_LITTLE_NAME              "elf32-xtensa-le"
11393 #define TARGET_BIG_SYM                  xtensa_elf32_be_vec
11394 #define TARGET_BIG_NAME                 "elf32-xtensa-be"
11395 #define ELF_ARCH                        bfd_arch_xtensa
11396
11397 #define ELF_MACHINE_CODE                EM_XTENSA
11398 #define ELF_MACHINE_ALT1                EM_XTENSA_OLD
11399
11400 #define ELF_MAXPAGESIZE                 0x1000
11401 #endif /* ELF_ARCH */
11402
11403 #define elf_backend_can_gc_sections     1
11404 #define elf_backend_can_refcount        1
11405 #define elf_backend_plt_readonly        1
11406 #define elf_backend_got_header_size     4
11407 #define elf_backend_want_dynbss         0
11408 #define elf_backend_want_got_plt        1
11409 #define elf_backend_dtrel_excludes_plt  1
11410
11411 #define elf_info_to_howto                    elf_xtensa_info_to_howto_rela
11412
11413 #define bfd_elf32_mkobject                   elf_xtensa_mkobject
11414
11415 #define bfd_elf32_bfd_merge_private_bfd_data elf_xtensa_merge_private_bfd_data
11416 #define bfd_elf32_new_section_hook           elf_xtensa_new_section_hook
11417 #define bfd_elf32_bfd_print_private_bfd_data elf_xtensa_print_private_bfd_data
11418 #define bfd_elf32_bfd_relax_section          elf_xtensa_relax_section
11419 #define bfd_elf32_bfd_reloc_type_lookup      elf_xtensa_reloc_type_lookup
11420 #define bfd_elf32_bfd_reloc_name_lookup \
11421   elf_xtensa_reloc_name_lookup
11422 #define bfd_elf32_bfd_set_private_flags      elf_xtensa_set_private_flags
11423 #define bfd_elf32_bfd_link_hash_table_create elf_xtensa_link_hash_table_create
11424
11425 #define elf_backend_adjust_dynamic_symbol    elf_xtensa_adjust_dynamic_symbol
11426 #define elf_backend_check_relocs             elf_xtensa_check_relocs
11427 #define elf_backend_create_dynamic_sections  elf_xtensa_create_dynamic_sections
11428 #define elf_backend_discard_info             elf_xtensa_discard_info
11429 #define elf_backend_ignore_discarded_relocs  elf_xtensa_ignore_discarded_relocs
11430 #define elf_backend_final_write_processing   elf_xtensa_final_write_processing
11431 #define elf_backend_finish_dynamic_sections  elf_xtensa_finish_dynamic_sections
11432 #define elf_backend_finish_dynamic_symbol    elf_xtensa_finish_dynamic_symbol
11433 #define elf_backend_gc_mark_hook             elf_xtensa_gc_mark_hook
11434 #define elf_backend_grok_prstatus            elf_xtensa_grok_prstatus
11435 #define elf_backend_grok_psinfo              elf_xtensa_grok_psinfo
11436 #define elf_backend_hide_symbol              elf_xtensa_hide_symbol
11437 #define elf_backend_object_p                 elf_xtensa_object_p
11438 #define elf_backend_reloc_type_class         elf_xtensa_reloc_type_class
11439 #define elf_backend_relocate_section         elf_xtensa_relocate_section
11440 #define elf_backend_size_dynamic_sections    elf_xtensa_size_dynamic_sections
11441 #define elf_backend_always_size_sections     elf_xtensa_always_size_sections
11442 #define elf_backend_omit_section_dynsym      _bfd_elf_omit_section_dynsym_all
11443 #define elf_backend_special_sections         elf_xtensa_special_sections
11444 #define elf_backend_action_discarded         elf_xtensa_action_discarded
11445 #define elf_backend_copy_indirect_symbol     elf_xtensa_copy_indirect_symbol
11446
11447 #include "elf32-target.h"