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