Back to index

cell-binutils  2.17cvs20070401
elf32-xtensa.c
Go to the documentation of this file.
00001 /* Xtensa-specific support for 32-bit ELF.
00002    Copyright 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
00003 
00004    This file is part of BFD, the Binary File Descriptor library.
00005 
00006    This program is free software; you can redistribute it and/or
00007    modify it under the terms of the GNU General Public License as
00008    published by the Free Software Foundation; either version 2 of the
00009    License, or (at your option) any later version.
00010 
00011    This program is distributed in the hope that it will be useful, but
00012    WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014    General Public License for more details.
00015 
00016    You should have received a copy of the GNU General Public License
00017    along with this program; if not, write to the Free Software
00018    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
00019    02110-1301, USA.  */
00020 
00021 #include "bfd.h"
00022 #include "sysdep.h"
00023 
00024 #include <stdarg.h>
00025 #include <strings.h>
00026 
00027 #include "bfdlink.h"
00028 #include "libbfd.h"
00029 #include "elf-bfd.h"
00030 #include "elf/xtensa.h"
00031 #include "xtensa-isa.h"
00032 #include "xtensa-config.h"
00033 
00034 #define XTENSA_NO_NOP_REMOVAL 0
00035 
00036 /* Local helper functions.  */
00037 
00038 static bfd_boolean add_extra_plt_sections (struct bfd_link_info *, int);
00039 static char *vsprint_msg (const char *, const char *, int, ...) ATTRIBUTE_PRINTF(2,4);
00040 static bfd_reloc_status_type bfd_elf_xtensa_reloc
00041   (bfd *, arelent *, asymbol *, void *, asection *, bfd *, char **);
00042 static bfd_boolean do_fix_for_relocatable_link
00043   (Elf_Internal_Rela *, bfd *, asection *, bfd_byte *);
00044 static void do_fix_for_final_link
00045   (Elf_Internal_Rela *, bfd *, asection *, bfd_byte *, bfd_vma *);
00046 
00047 /* Local functions to handle Xtensa configurability.  */
00048 
00049 static bfd_boolean is_indirect_call_opcode (xtensa_opcode);
00050 static bfd_boolean is_direct_call_opcode (xtensa_opcode);
00051 static bfd_boolean is_windowed_call_opcode (xtensa_opcode);
00052 static xtensa_opcode get_const16_opcode (void);
00053 static xtensa_opcode get_l32r_opcode (void);
00054 static bfd_vma l32r_offset (bfd_vma, bfd_vma);
00055 static int get_relocation_opnd (xtensa_opcode, int);
00056 static int get_relocation_slot (int);
00057 static xtensa_opcode get_relocation_opcode
00058   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *);
00059 static bfd_boolean is_l32r_relocation
00060   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *);
00061 static bfd_boolean is_alt_relocation (int);
00062 static bfd_boolean is_operand_relocation (int);
00063 static bfd_size_type insn_decode_len
00064   (bfd_byte *, bfd_size_type, bfd_size_type);
00065 static xtensa_opcode insn_decode_opcode
00066   (bfd_byte *, bfd_size_type, bfd_size_type, int);
00067 static bfd_boolean check_branch_target_aligned
00068   (bfd_byte *, bfd_size_type, bfd_vma, bfd_vma);
00069 static bfd_boolean check_loop_aligned
00070   (bfd_byte *, bfd_size_type, bfd_vma, bfd_vma);
00071 static bfd_boolean check_branch_target_aligned_address (bfd_vma, int);
00072 static bfd_size_type get_asm_simplify_size
00073   (bfd_byte *, bfd_size_type, bfd_size_type);
00074 
00075 /* Functions for link-time code simplifications.  */
00076 
00077 static bfd_reloc_status_type elf_xtensa_do_asm_simplify
00078   (bfd_byte *, bfd_vma, bfd_vma, char **);
00079 static bfd_reloc_status_type contract_asm_expansion
00080   (bfd_byte *, bfd_vma, Elf_Internal_Rela *, char **);
00081 static xtensa_opcode swap_callx_for_call_opcode (xtensa_opcode);
00082 static xtensa_opcode get_expanded_call_opcode (bfd_byte *, int, bfd_boolean *);
00083 
00084 /* Access to internal relocations, section contents and symbols.  */
00085 
00086 static Elf_Internal_Rela *retrieve_internal_relocs
00087   (bfd *, asection *, bfd_boolean);
00088 static void pin_internal_relocs (asection *, Elf_Internal_Rela *);
00089 static void release_internal_relocs (asection *, Elf_Internal_Rela *);
00090 static bfd_byte *retrieve_contents (bfd *, asection *, bfd_boolean);
00091 static void pin_contents (asection *, bfd_byte *);
00092 static void release_contents (asection *, bfd_byte *);
00093 static Elf_Internal_Sym *retrieve_local_syms (bfd *);
00094 
00095 /* Miscellaneous utility functions.  */
00096 
00097 static asection *elf_xtensa_get_plt_section (struct bfd_link_info *, int);
00098 static asection *elf_xtensa_get_gotplt_section (struct bfd_link_info *, int);
00099 static asection *get_elf_r_symndx_section (bfd *, unsigned long);
00100 static struct elf_link_hash_entry *get_elf_r_symndx_hash_entry
00101   (bfd *, unsigned long);
00102 static bfd_vma get_elf_r_symndx_offset (bfd *, unsigned long);
00103 static bfd_boolean is_reloc_sym_weak (bfd *, Elf_Internal_Rela *);
00104 static bfd_boolean pcrel_reloc_fits (xtensa_opcode, int, bfd_vma, bfd_vma);
00105 static bfd_boolean xtensa_is_property_section (asection *);
00106 static bfd_boolean xtensa_is_littable_section (asection *);
00107 static int internal_reloc_compare (const void *, const void *);
00108 static int internal_reloc_matches (const void *, const void *);
00109 extern asection *xtensa_get_property_section (asection *, const char *);
00110 static flagword xtensa_get_property_predef_flags (asection *);
00111 
00112 /* Other functions called directly by the linker.  */
00113 
00114 typedef void (*deps_callback_t)
00115   (asection *, bfd_vma, asection *, bfd_vma, void *);
00116 extern bfd_boolean xtensa_callback_required_dependence
00117   (bfd *, asection *, struct bfd_link_info *, deps_callback_t, void *);
00118 
00119 
00120 /* Globally visible flag for choosing size optimization of NOP removal
00121    instead of branch-target-aware minimization for NOP removal.
00122    When nonzero, narrow all instructions and remove all NOPs possible
00123    around longcall expansions.  */
00124 
00125 int elf32xtensa_size_opt;
00126 
00127 
00128 /* The "new_section_hook" is used to set up a per-section
00129    "xtensa_relax_info" data structure with additional information used
00130    during relaxation.  */
00131 
00132 typedef struct xtensa_relax_info_struct xtensa_relax_info;
00133 
00134 
00135 /* The GNU tools do not easily allow extending interfaces to pass around
00136    the pointer to the Xtensa ISA information, so instead we add a global
00137    variable here (in BFD) that can be used by any of the tools that need
00138    this information. */
00139 
00140 xtensa_isa xtensa_default_isa;
00141 
00142 
00143 /* When this is true, relocations may have been modified to refer to
00144    symbols from other input files.  The per-section list of "fix"
00145    records needs to be checked when resolving relocations.  */
00146 
00147 static bfd_boolean relaxing_section = FALSE;
00148 
00149 /* When this is true, during final links, literals that cannot be
00150    coalesced and their relocations may be moved to other sections.  */
00151 
00152 int elf32xtensa_no_literal_movement = 1;
00153 
00154 
00155 static reloc_howto_type elf_howto_table[] =
00156 {
00157   HOWTO (R_XTENSA_NONE, 0, 0, 0, FALSE, 0, complain_overflow_dont,
00158         bfd_elf_xtensa_reloc, "R_XTENSA_NONE",
00159         FALSE, 0, 0, FALSE),
00160   HOWTO (R_XTENSA_32, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
00161         bfd_elf_xtensa_reloc, "R_XTENSA_32",
00162         TRUE, 0xffffffff, 0xffffffff, FALSE),
00163 
00164   /* Replace a 32-bit value with a value from the runtime linker (only
00165      used by linker-generated stub functions).  The r_addend value is
00166      special: 1 means to substitute a pointer to the runtime linker's
00167      dynamic resolver function; 2 means to substitute the link map for
00168      the shared object.  */
00169   HOWTO (R_XTENSA_RTLD, 0, 2, 32, FALSE, 0, complain_overflow_dont,
00170         NULL, "R_XTENSA_RTLD", FALSE, 0, 0, FALSE),
00171 
00172   HOWTO (R_XTENSA_GLOB_DAT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
00173         bfd_elf_generic_reloc, "R_XTENSA_GLOB_DAT",
00174         FALSE, 0, 0xffffffff, FALSE),
00175   HOWTO (R_XTENSA_JMP_SLOT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
00176         bfd_elf_generic_reloc, "R_XTENSA_JMP_SLOT",
00177         FALSE, 0, 0xffffffff, FALSE),
00178   HOWTO (R_XTENSA_RELATIVE, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
00179         bfd_elf_generic_reloc, "R_XTENSA_RELATIVE",
00180         FALSE, 0, 0xffffffff, FALSE),
00181   HOWTO (R_XTENSA_PLT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
00182         bfd_elf_xtensa_reloc, "R_XTENSA_PLT",
00183         FALSE, 0, 0xffffffff, FALSE),
00184 
00185   EMPTY_HOWTO (7),
00186 
00187   /* Old relocations for backward compatibility.  */
00188   HOWTO (R_XTENSA_OP0, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00189         bfd_elf_xtensa_reloc, "R_XTENSA_OP0", FALSE, 0, 0, TRUE),
00190   HOWTO (R_XTENSA_OP1, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00191         bfd_elf_xtensa_reloc, "R_XTENSA_OP1", FALSE, 0, 0, TRUE),
00192   HOWTO (R_XTENSA_OP2, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00193         bfd_elf_xtensa_reloc, "R_XTENSA_OP2", FALSE, 0, 0, TRUE),
00194 
00195   /* Assembly auto-expansion.  */
00196   HOWTO (R_XTENSA_ASM_EXPAND, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00197         bfd_elf_xtensa_reloc, "R_XTENSA_ASM_EXPAND", FALSE, 0, 0, TRUE),
00198   /* Relax assembly auto-expansion.  */
00199   HOWTO (R_XTENSA_ASM_SIMPLIFY, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00200         bfd_elf_xtensa_reloc, "R_XTENSA_ASM_SIMPLIFY", FALSE, 0, 0, TRUE),
00201 
00202   EMPTY_HOWTO (13),
00203   EMPTY_HOWTO (14),
00204 
00205   /* GNU extension to record C++ vtable hierarchy.  */
00206   HOWTO (R_XTENSA_GNU_VTINHERIT, 0, 2, 0, FALSE, 0, complain_overflow_dont,
00207          NULL, "R_XTENSA_GNU_VTINHERIT",
00208         FALSE, 0, 0, FALSE),
00209   /* GNU extension to record C++ vtable member usage.  */
00210   HOWTO (R_XTENSA_GNU_VTENTRY, 0, 2, 0, FALSE, 0, complain_overflow_dont,
00211          _bfd_elf_rel_vtable_reloc_fn, "R_XTENSA_GNU_VTENTRY",
00212         FALSE, 0, 0, FALSE),
00213 
00214   /* Relocations for supporting difference of symbols.  */
00215   HOWTO (R_XTENSA_DIFF8, 0, 0, 8, FALSE, 0, complain_overflow_bitfield,
00216         bfd_elf_xtensa_reloc, "R_XTENSA_DIFF8", FALSE, 0, 0xff, FALSE),
00217   HOWTO (R_XTENSA_DIFF16, 0, 1, 16, FALSE, 0, complain_overflow_bitfield,
00218         bfd_elf_xtensa_reloc, "R_XTENSA_DIFF16", FALSE, 0, 0xffff, FALSE),
00219   HOWTO (R_XTENSA_DIFF32, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
00220         bfd_elf_xtensa_reloc, "R_XTENSA_DIFF32", FALSE, 0, 0xffffffff, FALSE),
00221 
00222   /* General immediate operand relocations.  */
00223   HOWTO (R_XTENSA_SLOT0_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00224         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT0_OP", FALSE, 0, 0, TRUE),
00225   HOWTO (R_XTENSA_SLOT1_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00226         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT1_OP", FALSE, 0, 0, TRUE),
00227   HOWTO (R_XTENSA_SLOT2_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00228         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT2_OP", FALSE, 0, 0, TRUE),
00229   HOWTO (R_XTENSA_SLOT3_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00230         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT3_OP", FALSE, 0, 0, TRUE),
00231   HOWTO (R_XTENSA_SLOT4_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00232         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT4_OP", FALSE, 0, 0, TRUE),
00233   HOWTO (R_XTENSA_SLOT5_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00234         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT5_OP", FALSE, 0, 0, TRUE),
00235   HOWTO (R_XTENSA_SLOT6_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00236         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT6_OP", FALSE, 0, 0, TRUE),
00237   HOWTO (R_XTENSA_SLOT7_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00238         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT7_OP", FALSE, 0, 0, TRUE),
00239   HOWTO (R_XTENSA_SLOT8_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00240         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT8_OP", FALSE, 0, 0, TRUE),
00241   HOWTO (R_XTENSA_SLOT9_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00242         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT9_OP", FALSE, 0, 0, TRUE),
00243   HOWTO (R_XTENSA_SLOT10_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00244         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT10_OP", FALSE, 0, 0, TRUE),
00245   HOWTO (R_XTENSA_SLOT11_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00246         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT11_OP", FALSE, 0, 0, TRUE),
00247   HOWTO (R_XTENSA_SLOT12_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00248         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT12_OP", FALSE, 0, 0, TRUE),
00249   HOWTO (R_XTENSA_SLOT13_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00250         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT13_OP", FALSE, 0, 0, TRUE),
00251   HOWTO (R_XTENSA_SLOT14_OP, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00252         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT14_OP", FALSE, 0, 0, TRUE),
00253 
00254   /* "Alternate" relocations.  The meaning of these is opcode-specific.  */
00255   HOWTO (R_XTENSA_SLOT0_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00256         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT0_ALT", FALSE, 0, 0, TRUE),
00257   HOWTO (R_XTENSA_SLOT1_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00258         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT1_ALT", FALSE, 0, 0, TRUE),
00259   HOWTO (R_XTENSA_SLOT2_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00260         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT2_ALT", FALSE, 0, 0, TRUE),
00261   HOWTO (R_XTENSA_SLOT3_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00262         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT3_ALT", FALSE, 0, 0, TRUE),
00263   HOWTO (R_XTENSA_SLOT4_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00264         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT4_ALT", FALSE, 0, 0, TRUE),
00265   HOWTO (R_XTENSA_SLOT5_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00266         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT5_ALT", FALSE, 0, 0, TRUE),
00267   HOWTO (R_XTENSA_SLOT6_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00268         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT6_ALT", FALSE, 0, 0, TRUE),
00269   HOWTO (R_XTENSA_SLOT7_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00270         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT7_ALT", FALSE, 0, 0, TRUE),
00271   HOWTO (R_XTENSA_SLOT8_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00272         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT8_ALT", FALSE, 0, 0, TRUE),
00273   HOWTO (R_XTENSA_SLOT9_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00274         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT9_ALT", FALSE, 0, 0, TRUE),
00275   HOWTO (R_XTENSA_SLOT10_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00276         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT10_ALT", FALSE, 0, 0, TRUE),
00277   HOWTO (R_XTENSA_SLOT11_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00278         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT11_ALT", FALSE, 0, 0, TRUE),
00279   HOWTO (R_XTENSA_SLOT12_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00280         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT12_ALT", FALSE, 0, 0, TRUE),
00281   HOWTO (R_XTENSA_SLOT13_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00282         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT13_ALT", FALSE, 0, 0, TRUE),
00283   HOWTO (R_XTENSA_SLOT14_ALT, 0, 0, 0, TRUE, 0, complain_overflow_dont,
00284         bfd_elf_xtensa_reloc, "R_XTENSA_SLOT14_ALT", FALSE, 0, 0, TRUE),
00285 };
00286 
00287 #if DEBUG_GEN_RELOC
00288 #define TRACE(str) \
00289   fprintf (stderr, "Xtensa bfd reloc lookup %d (%s)\n", code, str)
00290 #else
00291 #define TRACE(str)
00292 #endif
00293 
00294 static reloc_howto_type *
00295 elf_xtensa_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED,
00296                            bfd_reloc_code_real_type code)
00297 {
00298   switch (code)
00299     {
00300     case BFD_RELOC_NONE:
00301       TRACE ("BFD_RELOC_NONE");
00302       return &elf_howto_table[(unsigned) R_XTENSA_NONE ];
00303 
00304     case BFD_RELOC_32:
00305       TRACE ("BFD_RELOC_32");
00306       return &elf_howto_table[(unsigned) R_XTENSA_32 ];
00307 
00308     case BFD_RELOC_XTENSA_DIFF8:
00309       TRACE ("BFD_RELOC_XTENSA_DIFF8");
00310       return &elf_howto_table[(unsigned) R_XTENSA_DIFF8 ];
00311 
00312     case BFD_RELOC_XTENSA_DIFF16:
00313       TRACE ("BFD_RELOC_XTENSA_DIFF16");
00314       return &elf_howto_table[(unsigned) R_XTENSA_DIFF16 ];
00315 
00316     case BFD_RELOC_XTENSA_DIFF32:
00317       TRACE ("BFD_RELOC_XTENSA_DIFF32");
00318       return &elf_howto_table[(unsigned) R_XTENSA_DIFF32 ];
00319 
00320     case BFD_RELOC_XTENSA_RTLD:
00321       TRACE ("BFD_RELOC_XTENSA_RTLD");
00322       return &elf_howto_table[(unsigned) R_XTENSA_RTLD ];
00323 
00324     case BFD_RELOC_XTENSA_GLOB_DAT:
00325       TRACE ("BFD_RELOC_XTENSA_GLOB_DAT");
00326       return &elf_howto_table[(unsigned) R_XTENSA_GLOB_DAT ];
00327 
00328     case BFD_RELOC_XTENSA_JMP_SLOT:
00329       TRACE ("BFD_RELOC_XTENSA_JMP_SLOT");
00330       return &elf_howto_table[(unsigned) R_XTENSA_JMP_SLOT ];
00331 
00332     case BFD_RELOC_XTENSA_RELATIVE:
00333       TRACE ("BFD_RELOC_XTENSA_RELATIVE");
00334       return &elf_howto_table[(unsigned) R_XTENSA_RELATIVE ];
00335 
00336     case BFD_RELOC_XTENSA_PLT:
00337       TRACE ("BFD_RELOC_XTENSA_PLT");
00338       return &elf_howto_table[(unsigned) R_XTENSA_PLT ];
00339 
00340     case BFD_RELOC_XTENSA_OP0:
00341       TRACE ("BFD_RELOC_XTENSA_OP0");
00342       return &elf_howto_table[(unsigned) R_XTENSA_OP0 ];
00343 
00344     case BFD_RELOC_XTENSA_OP1:
00345       TRACE ("BFD_RELOC_XTENSA_OP1");
00346       return &elf_howto_table[(unsigned) R_XTENSA_OP1 ];
00347 
00348     case BFD_RELOC_XTENSA_OP2:
00349       TRACE ("BFD_RELOC_XTENSA_OP2");
00350       return &elf_howto_table[(unsigned) R_XTENSA_OP2 ];
00351 
00352     case BFD_RELOC_XTENSA_ASM_EXPAND:
00353       TRACE ("BFD_RELOC_XTENSA_ASM_EXPAND");
00354       return &elf_howto_table[(unsigned) R_XTENSA_ASM_EXPAND ];
00355 
00356     case BFD_RELOC_XTENSA_ASM_SIMPLIFY:
00357       TRACE ("BFD_RELOC_XTENSA_ASM_SIMPLIFY");
00358       return &elf_howto_table[(unsigned) R_XTENSA_ASM_SIMPLIFY ];
00359 
00360     case BFD_RELOC_VTABLE_INHERIT:
00361       TRACE ("BFD_RELOC_VTABLE_INHERIT");
00362       return &elf_howto_table[(unsigned) R_XTENSA_GNU_VTINHERIT ];
00363 
00364     case BFD_RELOC_VTABLE_ENTRY:
00365       TRACE ("BFD_RELOC_VTABLE_ENTRY");
00366       return &elf_howto_table[(unsigned) R_XTENSA_GNU_VTENTRY ];
00367 
00368     default:
00369       if (code >= BFD_RELOC_XTENSA_SLOT0_OP
00370          && code <= BFD_RELOC_XTENSA_SLOT14_OP)
00371        {
00372          unsigned n = (R_XTENSA_SLOT0_OP +
00373                      (code - BFD_RELOC_XTENSA_SLOT0_OP));
00374          return &elf_howto_table[n];
00375        }
00376 
00377       if (code >= BFD_RELOC_XTENSA_SLOT0_ALT
00378          && code <= BFD_RELOC_XTENSA_SLOT14_ALT)
00379        {
00380          unsigned n = (R_XTENSA_SLOT0_ALT +
00381                      (code - BFD_RELOC_XTENSA_SLOT0_ALT));
00382          return &elf_howto_table[n];
00383        }
00384 
00385       break;
00386     }
00387 
00388   TRACE ("Unknown");
00389   return NULL;
00390 }
00391 
00392 static reloc_howto_type *
00393 elf_xtensa_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED,
00394                            const char *r_name)
00395 {
00396   unsigned int i;
00397 
00398   for (i = 0; i < sizeof (elf_howto_table) / sizeof (elf_howto_table[0]); i++)
00399     if (elf_howto_table[i].name != NULL
00400        && strcasecmp (elf_howto_table[i].name, r_name) == 0)
00401       return &elf_howto_table[i];
00402 
00403   return NULL;
00404 }
00405 
00406 
00407 /* Given an ELF "rela" relocation, find the corresponding howto and record
00408    it in the BFD internal arelent representation of the relocation.  */
00409 
00410 static void
00411 elf_xtensa_info_to_howto_rela (bfd *abfd ATTRIBUTE_UNUSED,
00412                             arelent *cache_ptr,
00413                             Elf_Internal_Rela *dst)
00414 {
00415   unsigned int r_type = ELF32_R_TYPE (dst->r_info);
00416 
00417   BFD_ASSERT (r_type < (unsigned int) R_XTENSA_max);
00418   cache_ptr->howto = &elf_howto_table[r_type];
00419 }
00420 
00421 
00422 /* Functions for the Xtensa ELF linker.  */
00423 
00424 /* The name of the dynamic interpreter.  This is put in the .interp
00425    section.  */
00426 
00427 #define ELF_DYNAMIC_INTERPRETER "/lib/ld.so"
00428 
00429 /* The size in bytes of an entry in the procedure linkage table.
00430    (This does _not_ include the space for the literals associated with
00431    the PLT entry.) */
00432 
00433 #define PLT_ENTRY_SIZE 16
00434 
00435 /* For _really_ large PLTs, we may need to alternate between literals
00436    and code to keep the literals within the 256K range of the L32R
00437    instructions in the code.  It's unlikely that anyone would ever need
00438    such a big PLT, but an arbitrary limit on the PLT size would be bad.
00439    Thus, we split the PLT into chunks.  Since there's very little
00440    overhead (2 extra literals) for each chunk, the chunk size is kept
00441    small so that the code for handling multiple chunks get used and
00442    tested regularly.  With 254 entries, there are 1K of literals for
00443    each chunk, and that seems like a nice round number.  */
00444 
00445 #define PLT_ENTRIES_PER_CHUNK 254
00446 
00447 /* PLT entries are actually used as stub functions for lazy symbol
00448    resolution.  Once the symbol is resolved, the stub function is never
00449    invoked.  Note: the 32-byte frame size used here cannot be changed
00450    without a corresponding change in the runtime linker.  */
00451 
00452 static const bfd_byte elf_xtensa_be_plt_entry[PLT_ENTRY_SIZE] =
00453 {
00454   0x6c, 0x10, 0x04,  /* entry sp, 32 */
00455   0x18, 0x00, 0x00,  /* l32r  a8, [got entry for rtld's resolver] */
00456   0x1a, 0x00, 0x00,  /* l32r  a10, [got entry for rtld's link map] */
00457   0x1b, 0x00, 0x00,  /* l32r  a11, [literal for reloc index] */
00458   0x0a, 0x80, 0x00,  /* jx    a8 */
00459   0                  /* unused */
00460 };
00461 
00462 static const bfd_byte elf_xtensa_le_plt_entry[PLT_ENTRY_SIZE] =
00463 {
00464   0x36, 0x41, 0x00,  /* entry sp, 32 */
00465   0x81, 0x00, 0x00,  /* l32r  a8, [got entry for rtld's resolver] */
00466   0xa1, 0x00, 0x00,  /* l32r  a10, [got entry for rtld's link map] */
00467   0xb1, 0x00, 0x00,  /* l32r  a11, [literal for reloc index] */
00468   0xa0, 0x08, 0x00,  /* jx    a8 */
00469   0                  /* unused */
00470 };
00471 
00472 /* Xtensa ELF linker hash table.  */
00473 
00474 struct elf_xtensa_link_hash_table
00475 {
00476   struct elf_link_hash_table elf;
00477 
00478   /* Short-cuts to get to dynamic linker sections.  */
00479   asection *sgot;
00480   asection *sgotplt;
00481   asection *srelgot;
00482   asection *splt;
00483   asection *srelplt;
00484   asection *sgotloc;
00485   asection *spltlittbl;
00486 
00487   /* Total count of PLT relocations seen during check_relocs.
00488      The actual PLT code must be split into multiple sections and all
00489      the sections have to be created before size_dynamic_sections,
00490      where we figure out the exact number of PLT entries that will be
00491      needed.  It is OK if this count is an overestimate, e.g., some
00492      relocations may be removed by GC.  */
00493   int plt_reloc_count;
00494 };
00495 
00496 /* Get the Xtensa ELF linker hash table from a link_info structure.  */
00497 
00498 #define elf_xtensa_hash_table(p) \
00499   ((struct elf_xtensa_link_hash_table *) ((p)->hash))
00500 
00501 /* Create an Xtensa ELF linker hash table.  */
00502 
00503 static struct bfd_link_hash_table *
00504 elf_xtensa_link_hash_table_create (bfd *abfd)
00505 {
00506   struct elf_xtensa_link_hash_table *ret;
00507   bfd_size_type amt = sizeof (struct elf_xtensa_link_hash_table);
00508 
00509   ret = bfd_malloc (amt);
00510   if (ret == NULL)
00511     return NULL;
00512 
00513   if (!_bfd_elf_link_hash_table_init (&ret->elf, abfd,
00514                                   _bfd_elf_link_hash_newfunc,
00515                                   sizeof (struct elf_link_hash_entry)))
00516     {
00517       free (ret);
00518       return NULL;
00519     }
00520 
00521   ret->sgot = NULL;
00522   ret->sgotplt = NULL;
00523   ret->srelgot = NULL;
00524   ret->splt = NULL;
00525   ret->srelplt = NULL;
00526   ret->sgotloc = NULL;
00527   ret->spltlittbl = NULL;
00528 
00529   ret->plt_reloc_count = 0;
00530 
00531   return &ret->elf.root;
00532 }
00533 
00534 static inline bfd_boolean
00535 elf_xtensa_dynamic_symbol_p (struct elf_link_hash_entry *h,
00536                           struct bfd_link_info *info)
00537 {
00538   /* Check if we should do dynamic things to this symbol.  The
00539      "ignore_protected" argument need not be set, because Xtensa code
00540      does not require special handling of STV_PROTECTED to make function
00541      pointer comparisons work properly.  The PLT addresses are never
00542      used for function pointers.  */
00543 
00544   return _bfd_elf_dynamic_symbol_p (h, info, 0);
00545 }
00546 
00547 
00548 static int
00549 property_table_compare (const void *ap, const void *bp)
00550 {
00551   const property_table_entry *a = (const property_table_entry *) ap;
00552   const property_table_entry *b = (const property_table_entry *) bp;
00553 
00554   if (a->address == b->address)
00555     {
00556       if (a->size != b->size)
00557        return (a->size - b->size);
00558 
00559       if ((a->flags & XTENSA_PROP_ALIGN) != (b->flags & XTENSA_PROP_ALIGN))
00560        return ((b->flags & XTENSA_PROP_ALIGN)
00561               - (a->flags & XTENSA_PROP_ALIGN));
00562 
00563       if ((a->flags & XTENSA_PROP_ALIGN)
00564          && (GET_XTENSA_PROP_ALIGNMENT (a->flags)
00565              != GET_XTENSA_PROP_ALIGNMENT (b->flags)))
00566        return (GET_XTENSA_PROP_ALIGNMENT (a->flags)
00567               - GET_XTENSA_PROP_ALIGNMENT (b->flags));
00568       
00569       if ((a->flags & XTENSA_PROP_UNREACHABLE)
00570          != (b->flags & XTENSA_PROP_UNREACHABLE))
00571        return ((b->flags & XTENSA_PROP_UNREACHABLE)
00572               - (a->flags & XTENSA_PROP_UNREACHABLE));
00573 
00574       return (a->flags - b->flags);
00575     }
00576 
00577   return (a->address - b->address);
00578 }
00579 
00580 
00581 static int
00582 property_table_matches (const void *ap, const void *bp)
00583 {
00584   const property_table_entry *a = (const property_table_entry *) ap;
00585   const property_table_entry *b = (const property_table_entry *) bp;
00586 
00587   /* Check if one entry overlaps with the other.  */
00588   if ((b->address >= a->address && b->address < (a->address + a->size))
00589       || (a->address >= b->address && a->address < (b->address + b->size)))
00590     return 0;
00591 
00592   return (a->address - b->address);
00593 }
00594 
00595 
00596 /* Get the literal table or property table entries for the given
00597    section.  Sets TABLE_P and returns the number of entries.  On
00598    error, returns a negative value.  */
00599 
00600 static int
00601 xtensa_read_table_entries (bfd *abfd,
00602                         asection *section,
00603                         property_table_entry **table_p,
00604                         const char *sec_name,
00605                         bfd_boolean output_addr)
00606 {
00607   asection *table_section;
00608   bfd_size_type table_size = 0;
00609   bfd_byte *table_data;
00610   property_table_entry *blocks;
00611   int blk, block_count;
00612   bfd_size_type num_records;
00613   Elf_Internal_Rela *internal_relocs;
00614   bfd_vma section_addr;
00615   flagword predef_flags;
00616   bfd_size_type table_entry_size;
00617 
00618   if (!section
00619       || !(section->flags & SEC_ALLOC)
00620       || (section->flags & SEC_DEBUGGING))
00621     {
00622       *table_p = NULL;
00623       return 0;
00624     }
00625 
00626   table_section = xtensa_get_property_section (section, sec_name);
00627   if (table_section)
00628     table_size = table_section->size;
00629 
00630   if (table_size == 0) 
00631     {
00632       *table_p = NULL;
00633       return 0;
00634     }
00635 
00636   predef_flags = xtensa_get_property_predef_flags (table_section);
00637   table_entry_size = 12;
00638   if (predef_flags)
00639     table_entry_size -= 4;
00640 
00641   num_records = table_size / table_entry_size;
00642   table_data = retrieve_contents (abfd, table_section, TRUE);
00643   blocks = (property_table_entry *)
00644     bfd_malloc (num_records * sizeof (property_table_entry));
00645   block_count = 0;
00646 
00647   if (output_addr)
00648     section_addr = section->output_section->vma + section->output_offset;
00649   else
00650     section_addr = section->vma;
00651 
00652   /* If the file has not yet been relocated, process the relocations
00653      and sort out the table entries that apply to the specified section.  */
00654   internal_relocs = retrieve_internal_relocs (abfd, table_section, TRUE);
00655   if (internal_relocs && !table_section->reloc_done)
00656     {
00657       unsigned i;
00658 
00659       for (i = 0; i < table_section->reloc_count; i++)
00660        {
00661          Elf_Internal_Rela *rel = &internal_relocs[i];
00662          unsigned long r_symndx;
00663 
00664          if (ELF32_R_TYPE (rel->r_info) == R_XTENSA_NONE)
00665            continue;
00666 
00667          BFD_ASSERT (ELF32_R_TYPE (rel->r_info) == R_XTENSA_32);
00668          r_symndx = ELF32_R_SYM (rel->r_info);
00669 
00670          if (get_elf_r_symndx_section (abfd, r_symndx) == section)
00671            {
00672              bfd_vma sym_off = get_elf_r_symndx_offset (abfd, r_symndx);
00673              BFD_ASSERT (sym_off == 0);
00674              blocks[block_count].address =
00675               (section_addr + sym_off + rel->r_addend
00676                + bfd_get_32 (abfd, table_data + rel->r_offset));
00677              blocks[block_count].size =
00678               bfd_get_32 (abfd, table_data + rel->r_offset + 4);
00679              if (predef_flags)
00680               blocks[block_count].flags = predef_flags;
00681              else
00682               blocks[block_count].flags =
00683                 bfd_get_32 (abfd, table_data + rel->r_offset + 8);
00684              block_count++;
00685            }
00686        }
00687     }
00688   else
00689     {
00690       /* The file has already been relocated and the addresses are
00691         already in the table.  */
00692       bfd_vma off;
00693       bfd_size_type section_limit = bfd_get_section_limit (abfd, section);
00694 
00695       for (off = 0; off < table_size; off += table_entry_size) 
00696        {
00697          bfd_vma address = bfd_get_32 (abfd, table_data + off);
00698 
00699          if (address >= section_addr
00700              && address < section_addr + section_limit)
00701            {
00702              blocks[block_count].address = address;
00703              blocks[block_count].size =
00704               bfd_get_32 (abfd, table_data + off + 4);
00705              if (predef_flags)
00706               blocks[block_count].flags = predef_flags;
00707              else
00708               blocks[block_count].flags =
00709                 bfd_get_32 (abfd, table_data + off + 8);
00710              block_count++;
00711            }
00712        }
00713     }
00714 
00715   release_contents (table_section, table_data);
00716   release_internal_relocs (table_section, internal_relocs);
00717 
00718   if (block_count > 0)
00719     {
00720       /* Now sort them into address order for easy reference.  */
00721       qsort (blocks, block_count, sizeof (property_table_entry),
00722             property_table_compare);
00723 
00724       /* Check that the table contents are valid.  Problems may occur,
00725          for example, if an unrelocated object file is stripped.  */
00726       for (blk = 1; blk < block_count; blk++)
00727        {
00728          /* The only circumstance where two entries may legitimately
00729             have the same address is when one of them is a zero-size
00730             placeholder to mark a place where fill can be inserted.
00731             The zero-size entry should come first.  */
00732          if (blocks[blk - 1].address == blocks[blk].address &&
00733              blocks[blk - 1].size != 0)
00734            {
00735              (*_bfd_error_handler) (_("%B(%A): invalid property table"),
00736                                  abfd, section);
00737              bfd_set_error (bfd_error_bad_value);
00738              free (blocks);
00739              return -1;
00740            }
00741        }
00742     }
00743 
00744   *table_p = blocks;
00745   return block_count;
00746 }
00747 
00748 
00749 static property_table_entry *
00750 elf_xtensa_find_property_entry (property_table_entry *property_table,
00751                             int property_table_size,
00752                             bfd_vma addr)
00753 {
00754   property_table_entry entry;
00755   property_table_entry *rv;
00756 
00757   if (property_table_size == 0)
00758     return NULL;
00759 
00760   entry.address = addr;
00761   entry.size = 1;
00762   entry.flags = 0;
00763 
00764   rv = bsearch (&entry, property_table, property_table_size,
00765               sizeof (property_table_entry), property_table_matches);
00766   return rv;
00767 }
00768 
00769 
00770 static bfd_boolean
00771 elf_xtensa_in_literal_pool (property_table_entry *lit_table,
00772                          int lit_table_size,
00773                          bfd_vma addr)
00774 {
00775   if (elf_xtensa_find_property_entry (lit_table, lit_table_size, addr))
00776     return TRUE;
00777 
00778   return FALSE;
00779 }
00780 
00781 
00782 /* Look through the relocs for a section during the first phase, and
00783    calculate needed space in the dynamic reloc sections.  */
00784 
00785 static bfd_boolean
00786 elf_xtensa_check_relocs (bfd *abfd,
00787                       struct bfd_link_info *info,
00788                       asection *sec,
00789                       const Elf_Internal_Rela *relocs)
00790 {
00791   struct elf_xtensa_link_hash_table *htab;
00792   Elf_Internal_Shdr *symtab_hdr;
00793   struct elf_link_hash_entry **sym_hashes;
00794   const Elf_Internal_Rela *rel;
00795   const Elf_Internal_Rela *rel_end;
00796 
00797   if (info->relocatable)
00798     return TRUE;
00799 
00800   htab = elf_xtensa_hash_table (info);
00801   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
00802   sym_hashes = elf_sym_hashes (abfd);
00803 
00804   rel_end = relocs + sec->reloc_count;
00805   for (rel = relocs; rel < rel_end; rel++)
00806     {
00807       unsigned int r_type;
00808       unsigned long r_symndx;
00809       struct elf_link_hash_entry *h;
00810 
00811       r_symndx = ELF32_R_SYM (rel->r_info);
00812       r_type = ELF32_R_TYPE (rel->r_info);
00813 
00814       if (r_symndx >= NUM_SHDR_ENTRIES (symtab_hdr))
00815        {
00816          (*_bfd_error_handler) (_("%B: bad symbol index: %d"),
00817                              abfd, r_symndx);
00818          return FALSE;
00819        }
00820 
00821       if (r_symndx < symtab_hdr->sh_info)
00822        h = NULL;
00823       else
00824        {
00825          h = sym_hashes[r_symndx - symtab_hdr->sh_info];
00826          while (h->root.type == bfd_link_hash_indirect
00827                || h->root.type == bfd_link_hash_warning)
00828            h = (struct elf_link_hash_entry *) h->root.u.i.link;
00829        }
00830 
00831       switch (r_type)
00832        {
00833        case R_XTENSA_32:
00834          if (h == NULL)
00835            goto local_literal;
00836 
00837          if ((sec->flags & SEC_ALLOC) != 0)
00838            {
00839              if (h->got.refcount <= 0)
00840               h->got.refcount = 1;
00841              else
00842               h->got.refcount += 1;
00843            }
00844          break;
00845 
00846        case R_XTENSA_PLT:
00847          /* If this relocation is against a local symbol, then it's
00848             exactly the same as a normal local GOT entry.  */
00849          if (h == NULL)
00850            goto local_literal;
00851 
00852          if ((sec->flags & SEC_ALLOC) != 0)
00853            {
00854              if (h->plt.refcount <= 0)
00855               {
00856                 h->needs_plt = 1;
00857                 h->plt.refcount = 1;
00858               }
00859              else
00860               h->plt.refcount += 1;
00861 
00862              /* Keep track of the total PLT relocation count even if we
00863                don't yet know whether the dynamic sections will be
00864                created.  */
00865              htab->plt_reloc_count += 1;
00866 
00867              if (elf_hash_table (info)->dynamic_sections_created)
00868               {
00869                 if (! add_extra_plt_sections (info, htab->plt_reloc_count))
00870                   return FALSE;
00871               }
00872            }
00873          break;
00874 
00875        local_literal:
00876          if ((sec->flags & SEC_ALLOC) != 0)
00877            {
00878              bfd_signed_vma *local_got_refcounts;
00879 
00880              /* This is a global offset table entry for a local symbol.  */
00881              local_got_refcounts = elf_local_got_refcounts (abfd);
00882              if (local_got_refcounts == NULL)
00883               {
00884                 bfd_size_type size;
00885 
00886                 size = symtab_hdr->sh_info;
00887                 size *= sizeof (bfd_signed_vma);
00888                 local_got_refcounts =
00889                   (bfd_signed_vma *) bfd_zalloc (abfd, size);
00890                 if (local_got_refcounts == NULL)
00891                   return FALSE;
00892                 elf_local_got_refcounts (abfd) = local_got_refcounts;
00893               }
00894              local_got_refcounts[r_symndx] += 1;
00895            }
00896          break;
00897 
00898        case R_XTENSA_OP0:
00899        case R_XTENSA_OP1:
00900        case R_XTENSA_OP2:
00901        case R_XTENSA_SLOT0_OP:
00902        case R_XTENSA_SLOT1_OP:
00903        case R_XTENSA_SLOT2_OP:
00904        case R_XTENSA_SLOT3_OP:
00905        case R_XTENSA_SLOT4_OP:
00906        case R_XTENSA_SLOT5_OP:
00907        case R_XTENSA_SLOT6_OP:
00908        case R_XTENSA_SLOT7_OP:
00909        case R_XTENSA_SLOT8_OP:
00910        case R_XTENSA_SLOT9_OP:
00911        case R_XTENSA_SLOT10_OP:
00912        case R_XTENSA_SLOT11_OP:
00913        case R_XTENSA_SLOT12_OP:
00914        case R_XTENSA_SLOT13_OP:
00915        case R_XTENSA_SLOT14_OP:
00916        case R_XTENSA_SLOT0_ALT:
00917        case R_XTENSA_SLOT1_ALT:
00918        case R_XTENSA_SLOT2_ALT:
00919        case R_XTENSA_SLOT3_ALT:
00920        case R_XTENSA_SLOT4_ALT:
00921        case R_XTENSA_SLOT5_ALT:
00922        case R_XTENSA_SLOT6_ALT:
00923        case R_XTENSA_SLOT7_ALT:
00924        case R_XTENSA_SLOT8_ALT:
00925        case R_XTENSA_SLOT9_ALT:
00926        case R_XTENSA_SLOT10_ALT:
00927        case R_XTENSA_SLOT11_ALT:
00928        case R_XTENSA_SLOT12_ALT:
00929        case R_XTENSA_SLOT13_ALT:
00930        case R_XTENSA_SLOT14_ALT:
00931        case R_XTENSA_ASM_EXPAND:
00932        case R_XTENSA_ASM_SIMPLIFY:
00933        case R_XTENSA_DIFF8:
00934        case R_XTENSA_DIFF16:
00935        case R_XTENSA_DIFF32:
00936          /* Nothing to do for these.  */
00937          break;
00938 
00939        case R_XTENSA_GNU_VTINHERIT:
00940          /* This relocation describes the C++ object vtable hierarchy.
00941             Reconstruct it for later use during GC.  */
00942          if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
00943            return FALSE;
00944          break;
00945 
00946        case R_XTENSA_GNU_VTENTRY:
00947          /* This relocation describes which C++ vtable entries are actually
00948             used.  Record for later use during GC.  */
00949          if (!bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_addend))
00950            return FALSE;
00951          break;
00952 
00953        default:
00954          break;
00955        }
00956     }
00957 
00958   return TRUE;
00959 }
00960 
00961 
00962 /* Return the section that should be marked against GC for a given
00963    relocation.  */
00964 
00965 static asection *
00966 elf_xtensa_gc_mark_hook (asection *sec,
00967                       struct bfd_link_info *info,
00968                       Elf_Internal_Rela *rel,
00969                       struct elf_link_hash_entry *h,
00970                       Elf_Internal_Sym *sym)
00971 {
00972   if (h != NULL)
00973     switch (ELF32_R_TYPE (rel->r_info))
00974       {
00975       case R_XTENSA_GNU_VTINHERIT:
00976       case R_XTENSA_GNU_VTENTRY:
00977        return NULL;
00978       }
00979 
00980   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
00981 }
00982 
00983 
00984 /* Update the GOT & PLT entry reference counts
00985    for the section being removed.  */
00986 
00987 static bfd_boolean
00988 elf_xtensa_gc_sweep_hook (bfd *abfd,
00989                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
00990                        asection *sec,
00991                        const Elf_Internal_Rela *relocs)
00992 {
00993   Elf_Internal_Shdr *symtab_hdr;
00994   struct elf_link_hash_entry **sym_hashes;
00995   bfd_signed_vma *local_got_refcounts;
00996   const Elf_Internal_Rela *rel, *relend;
00997 
00998   if ((sec->flags & SEC_ALLOC) == 0)
00999     return TRUE;
01000 
01001   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
01002   sym_hashes = elf_sym_hashes (abfd);
01003   local_got_refcounts = elf_local_got_refcounts (abfd);
01004 
01005   relend = relocs + sec->reloc_count;
01006   for (rel = relocs; rel < relend; rel++)
01007     {
01008       unsigned long r_symndx;
01009       unsigned int r_type;
01010       struct elf_link_hash_entry *h = NULL;
01011 
01012       r_symndx = ELF32_R_SYM (rel->r_info);
01013       if (r_symndx >= symtab_hdr->sh_info)
01014        {
01015          h = sym_hashes[r_symndx - symtab_hdr->sh_info];
01016          while (h->root.type == bfd_link_hash_indirect
01017                || h->root.type == bfd_link_hash_warning)
01018            h = (struct elf_link_hash_entry *) h->root.u.i.link;
01019        }
01020 
01021       r_type = ELF32_R_TYPE (rel->r_info);
01022       switch (r_type)
01023        {
01024        case R_XTENSA_32:
01025          if (h == NULL)
01026            goto local_literal;
01027          if (h->got.refcount > 0)
01028            h->got.refcount--;
01029          break;
01030 
01031        case R_XTENSA_PLT:
01032          if (h == NULL)
01033            goto local_literal;
01034          if (h->plt.refcount > 0)
01035            h->plt.refcount--;
01036          break;
01037 
01038        local_literal:
01039          if (local_got_refcounts[r_symndx] > 0)
01040            local_got_refcounts[r_symndx] -= 1;
01041          break;
01042 
01043        default:
01044          break;
01045        }
01046     }
01047 
01048   return TRUE;
01049 }
01050 
01051 
01052 /* Create all the dynamic sections.  */
01053 
01054 static bfd_boolean
01055 elf_xtensa_create_dynamic_sections (bfd *dynobj, struct bfd_link_info *info)
01056 {
01057   struct elf_xtensa_link_hash_table *htab;
01058   flagword flags, noalloc_flags;
01059 
01060   htab = elf_xtensa_hash_table (info);
01061 
01062   /* First do all the standard stuff.  */
01063   if (! _bfd_elf_create_dynamic_sections (dynobj, info))
01064     return FALSE;
01065   htab->splt = bfd_get_section_by_name (dynobj, ".plt");
01066   htab->srelplt = bfd_get_section_by_name (dynobj, ".rela.plt");
01067   htab->sgot = bfd_get_section_by_name (dynobj, ".got");
01068   htab->sgotplt = bfd_get_section_by_name (dynobj, ".got.plt");
01069 
01070   /* Create any extra PLT sections in case check_relocs has already
01071      been called on all the non-dynamic input files.  */
01072   if (! add_extra_plt_sections (info, htab->plt_reloc_count))
01073     return FALSE;
01074 
01075   noalloc_flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
01076                  | SEC_LINKER_CREATED | SEC_READONLY);
01077   flags = noalloc_flags | SEC_ALLOC | SEC_LOAD;
01078 
01079   /* Mark the ".got.plt" section READONLY.  */
01080   if (htab->sgotplt == NULL
01081       || ! bfd_set_section_flags (dynobj, htab->sgotplt, flags))
01082     return FALSE;
01083 
01084   /* Create ".rela.got".  */
01085   htab->srelgot = bfd_make_section_with_flags (dynobj, ".rela.got", flags);
01086   if (htab->srelgot == NULL
01087       || ! bfd_set_section_alignment (dynobj, htab->srelgot, 2))
01088     return FALSE;
01089 
01090   /* Create ".got.loc" (literal tables for use by dynamic linker).  */
01091   htab->sgotloc = bfd_make_section_with_flags (dynobj, ".got.loc", flags);
01092   if (htab->sgotloc == NULL
01093       || ! bfd_set_section_alignment (dynobj, htab->sgotloc, 2))
01094     return FALSE;
01095 
01096   /* Create ".xt.lit.plt" (literal table for ".got.plt*").  */
01097   htab->spltlittbl = bfd_make_section_with_flags (dynobj, ".xt.lit.plt",
01098                                             noalloc_flags);
01099   if (htab->spltlittbl == NULL
01100       || ! bfd_set_section_alignment (dynobj, htab->spltlittbl, 2))
01101     return FALSE;
01102 
01103   return TRUE;
01104 }
01105 
01106 
01107 static bfd_boolean
01108 add_extra_plt_sections (struct bfd_link_info *info, int count)
01109 {
01110   bfd *dynobj = elf_hash_table (info)->dynobj;
01111   int chunk;
01112 
01113   /* Iterate over all chunks except 0 which uses the standard ".plt" and
01114      ".got.plt" sections.  */
01115   for (chunk = count / PLT_ENTRIES_PER_CHUNK; chunk > 0; chunk--)
01116     {
01117       char *sname;
01118       flagword flags;
01119       asection *s;
01120 
01121       /* Stop when we find a section has already been created.  */
01122       if (elf_xtensa_get_plt_section (info, chunk))
01123        break;
01124 
01125       flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
01126               | SEC_LINKER_CREATED | SEC_READONLY);
01127 
01128       sname = (char *) bfd_malloc (10);
01129       sprintf (sname, ".plt.%u", chunk);
01130       s = bfd_make_section_with_flags (dynobj, sname, flags | SEC_CODE);
01131       if (s == NULL
01132          || ! bfd_set_section_alignment (dynobj, s, 2))
01133        return FALSE;
01134 
01135       sname = (char *) bfd_malloc (14);
01136       sprintf (sname, ".got.plt.%u", chunk);
01137       s = bfd_make_section_with_flags (dynobj, sname, flags);
01138       if (s == NULL
01139          || ! bfd_set_section_alignment (dynobj, s, 2))
01140        return FALSE;
01141     }
01142 
01143   return TRUE;
01144 }
01145 
01146 
01147 /* Adjust a symbol defined by a dynamic object and referenced by a
01148    regular object.  The current definition is in some section of the
01149    dynamic object, but we're not including those sections.  We have to
01150    change the definition to something the rest of the link can
01151    understand.  */
01152 
01153 static bfd_boolean
01154 elf_xtensa_adjust_dynamic_symbol (struct bfd_link_info *info ATTRIBUTE_UNUSED,
01155                               struct elf_link_hash_entry *h)
01156 {
01157   /* If this is a weak symbol, and there is a real definition, the
01158      processor independent code will have arranged for us to see the
01159      real definition first, and we can just use the same value.  */
01160   if (h->u.weakdef)
01161     {
01162       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
01163                 || h->u.weakdef->root.type == bfd_link_hash_defweak);
01164       h->root.u.def.section = h->u.weakdef->root.u.def.section;
01165       h->root.u.def.value = h->u.weakdef->root.u.def.value;
01166       return TRUE;
01167     }
01168 
01169   /* This is a reference to a symbol defined by a dynamic object.  The
01170      reference must go through the GOT, so there's no need for COPY relocs,
01171      .dynbss, etc.  */
01172 
01173   return TRUE;
01174 }
01175 
01176 
01177 static bfd_boolean
01178 elf_xtensa_allocate_dynrelocs (struct elf_link_hash_entry *h, void *arg)
01179 {
01180   struct bfd_link_info *info;
01181   struct elf_xtensa_link_hash_table *htab;
01182   bfd_boolean is_dynamic;
01183 
01184   if (h->root.type == bfd_link_hash_indirect)
01185     return TRUE;
01186 
01187   if (h->root.type == bfd_link_hash_warning)
01188     h = (struct elf_link_hash_entry *) h->root.u.i.link;
01189 
01190   info = (struct bfd_link_info *) arg;
01191   htab = elf_xtensa_hash_table (info);
01192 
01193   is_dynamic = elf_xtensa_dynamic_symbol_p (h, info);
01194 
01195   if (! is_dynamic)
01196     {
01197       if (info->shared)
01198        {
01199          /* For shared objects, there's no need for PLT entries for local
01200             symbols (use RELATIVE relocs instead of JMP_SLOT relocs).  */
01201          if (h->plt.refcount > 0)
01202            {
01203              if (h->got.refcount < 0)
01204               h->got.refcount = 0;
01205              h->got.refcount += h->plt.refcount;
01206              h->plt.refcount = 0;
01207            }
01208        }
01209       else
01210        {
01211          /* Don't need any dynamic relocations at all.  */
01212          h->plt.refcount = 0;
01213          h->got.refcount = 0;
01214        }
01215     }
01216 
01217   if (h->plt.refcount > 0)
01218     htab->srelplt->size += (h->plt.refcount * sizeof (Elf32_External_Rela));
01219 
01220   if (h->got.refcount > 0)
01221     htab->srelgot->size += (h->got.refcount * sizeof (Elf32_External_Rela));
01222 
01223   return TRUE;
01224 }
01225 
01226 
01227 static void
01228 elf_xtensa_allocate_local_got_size (struct bfd_link_info *info)
01229 {
01230   struct elf_xtensa_link_hash_table *htab;
01231   bfd *i;
01232 
01233   htab = elf_xtensa_hash_table (info);
01234 
01235   for (i = info->input_bfds; i; i = i->link_next)
01236     {
01237       bfd_signed_vma *local_got_refcounts;
01238       bfd_size_type j, cnt;
01239       Elf_Internal_Shdr *symtab_hdr;
01240 
01241       local_got_refcounts = elf_local_got_refcounts (i);
01242       if (!local_got_refcounts)
01243        continue;
01244 
01245       symtab_hdr = &elf_tdata (i)->symtab_hdr;
01246       cnt = symtab_hdr->sh_info;
01247 
01248       for (j = 0; j < cnt; ++j)
01249        {
01250          if (local_got_refcounts[j] > 0)
01251            htab->srelgot->size += (local_got_refcounts[j]
01252                                 * sizeof (Elf32_External_Rela));
01253        }
01254     }
01255 }
01256 
01257 
01258 /* Set the sizes of the dynamic sections.  */
01259 
01260 static bfd_boolean
01261 elf_xtensa_size_dynamic_sections (bfd *output_bfd ATTRIBUTE_UNUSED,
01262                               struct bfd_link_info *info)
01263 {
01264   struct elf_xtensa_link_hash_table *htab;
01265   bfd *dynobj, *abfd;
01266   asection *s, *srelplt, *splt, *sgotplt, *srelgot, *spltlittbl, *sgotloc;
01267   bfd_boolean relplt, relgot;
01268   int plt_entries, plt_chunks, chunk;
01269 
01270   plt_entries = 0;
01271   plt_chunks = 0;
01272 
01273   htab = elf_xtensa_hash_table (info);
01274   dynobj = elf_hash_table (info)->dynobj;
01275   if (dynobj == NULL)
01276     abort ();
01277   srelgot = htab->srelgot;
01278   srelplt = htab->srelplt;
01279 
01280   if (elf_hash_table (info)->dynamic_sections_created)
01281     {
01282       BFD_ASSERT (htab->srelgot != NULL
01283                 && htab->srelplt != NULL
01284                 && htab->sgot != NULL
01285                 && htab->spltlittbl != NULL
01286                 && htab->sgotloc != NULL);
01287 
01288       /* Set the contents of the .interp section to the interpreter.  */
01289       if (info->executable)
01290        {
01291          s = bfd_get_section_by_name (dynobj, ".interp");
01292          if (s == NULL)
01293            abort ();
01294          s->size = sizeof ELF_DYNAMIC_INTERPRETER;
01295          s->contents = (unsigned char *) ELF_DYNAMIC_INTERPRETER;
01296        }
01297 
01298       /* Allocate room for one word in ".got".  */
01299       htab->sgot->size = 4;
01300 
01301       /* Allocate space in ".rela.got" for literals that reference global
01302         symbols and space in ".rela.plt" for literals that have PLT
01303         entries.  */
01304       elf_link_hash_traverse (elf_hash_table (info),
01305                            elf_xtensa_allocate_dynrelocs,
01306                            (void *) info);
01307 
01308       /* If we are generating a shared object, we also need space in
01309         ".rela.got" for R_XTENSA_RELATIVE relocs for literals that
01310         reference local symbols.  */
01311       if (info->shared)
01312        elf_xtensa_allocate_local_got_size (info);
01313 
01314       /* Allocate space in ".plt" to match the size of ".rela.plt".  For
01315         each PLT entry, we need the PLT code plus a 4-byte literal.
01316         For each chunk of ".plt", we also need two more 4-byte
01317         literals, two corresponding entries in ".rela.got", and an
01318         8-byte entry in ".xt.lit.plt".  */
01319       spltlittbl = htab->spltlittbl;
01320       plt_entries = srelplt->size / sizeof (Elf32_External_Rela);
01321       plt_chunks =
01322        (plt_entries + PLT_ENTRIES_PER_CHUNK - 1) / PLT_ENTRIES_PER_CHUNK;
01323 
01324       /* Iterate over all the PLT chunks, including any extra sections
01325         created earlier because the initial count of PLT relocations
01326         was an overestimate.  */
01327       for (chunk = 0;
01328           (splt = elf_xtensa_get_plt_section (info, chunk)) != NULL;
01329           chunk++)
01330        {
01331          int chunk_entries;
01332 
01333          sgotplt = elf_xtensa_get_gotplt_section (info, chunk);
01334          BFD_ASSERT (sgotplt != NULL);
01335 
01336          if (chunk < plt_chunks - 1)
01337            chunk_entries = PLT_ENTRIES_PER_CHUNK;
01338          else if (chunk == plt_chunks - 1)
01339            chunk_entries = plt_entries - (chunk * PLT_ENTRIES_PER_CHUNK);
01340          else
01341            chunk_entries = 0;
01342 
01343          if (chunk_entries != 0)
01344            {
01345              sgotplt->size = 4 * (chunk_entries + 2);
01346              splt->size = PLT_ENTRY_SIZE * chunk_entries;
01347              srelgot->size += 2 * sizeof (Elf32_External_Rela);
01348              spltlittbl->size += 8;
01349            }
01350          else
01351            {
01352              sgotplt->size = 0;
01353              splt->size = 0;
01354            }
01355        }
01356 
01357       /* Allocate space in ".got.loc" to match the total size of all the
01358         literal tables.  */
01359       sgotloc = htab->sgotloc;
01360       sgotloc->size = spltlittbl->size;
01361       for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link_next)
01362        {
01363          if (abfd->flags & DYNAMIC)
01364            continue;
01365          for (s = abfd->sections; s != NULL; s = s->next)
01366            {
01367              if (! elf_discarded_section (s)
01368                 && xtensa_is_littable_section (s)
01369                 && s != spltlittbl)
01370               sgotloc->size += s->size;
01371            }
01372        }
01373     }
01374 
01375   /* Allocate memory for dynamic sections.  */
01376   relplt = FALSE;
01377   relgot = FALSE;
01378   for (s = dynobj->sections; s != NULL; s = s->next)
01379     {
01380       const char *name;
01381 
01382       if ((s->flags & SEC_LINKER_CREATED) == 0)
01383        continue;
01384 
01385       /* It's OK to base decisions on the section name, because none
01386         of the dynobj section names depend upon the input files.  */
01387       name = bfd_get_section_name (dynobj, s);
01388 
01389       if (CONST_STRNEQ (name, ".rela"))
01390        {
01391          if (s->size != 0)
01392            {
01393              if (strcmp (name, ".rela.plt") == 0)
01394               relplt = TRUE;
01395              else if (strcmp (name, ".rela.got") == 0)
01396               relgot = TRUE;
01397 
01398              /* We use the reloc_count field as a counter if we need
01399                to copy relocs into the output file.  */
01400              s->reloc_count = 0;
01401            }
01402        }
01403       else if (! CONST_STRNEQ (name, ".plt.")
01404               && ! CONST_STRNEQ (name, ".got.plt.")
01405               && strcmp (name, ".got") != 0
01406               && strcmp (name, ".plt") != 0
01407               && strcmp (name, ".got.plt") != 0
01408               && strcmp (name, ".xt.lit.plt") != 0
01409               && strcmp (name, ".got.loc") != 0)
01410        {
01411          /* It's not one of our sections, so don't allocate space.  */
01412          continue;
01413        }
01414 
01415       if (s->size == 0)
01416        {
01417          /* If we don't need this section, strip it from the output
01418             file.  We must create the ".plt*" and ".got.plt*"
01419             sections in create_dynamic_sections and/or check_relocs
01420             based on a conservative estimate of the PLT relocation
01421             count, because the sections must be created before the
01422             linker maps input sections to output sections.  The
01423             linker does that before size_dynamic_sections, where we
01424             compute the exact size of the PLT, so there may be more
01425             of these sections than are actually needed.  */
01426          s->flags |= SEC_EXCLUDE;
01427        }
01428       else if ((s->flags & SEC_HAS_CONTENTS) != 0)
01429        {
01430          /* Allocate memory for the section contents.  */
01431          s->contents = (bfd_byte *) bfd_zalloc (dynobj, s->size);
01432          if (s->contents == NULL)
01433            return FALSE;
01434        }
01435     }
01436 
01437   if (elf_hash_table (info)->dynamic_sections_created)
01438     {
01439       /* Add the special XTENSA_RTLD relocations now.  The offsets won't be
01440         known until finish_dynamic_sections, but we need to get the relocs
01441         in place before they are sorted.  */
01442       for (chunk = 0; chunk < plt_chunks; chunk++)
01443        {
01444          Elf_Internal_Rela irela;
01445          bfd_byte *loc;
01446 
01447          irela.r_offset = 0;
01448          irela.r_info = ELF32_R_INFO (0, R_XTENSA_RTLD);
01449          irela.r_addend = 0;
01450 
01451          loc = (srelgot->contents
01452                + srelgot->reloc_count * sizeof (Elf32_External_Rela));
01453          bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
01454          bfd_elf32_swap_reloca_out (output_bfd, &irela,
01455                                  loc + sizeof (Elf32_External_Rela));
01456          srelgot->reloc_count += 2;
01457        }
01458 
01459       /* Add some entries to the .dynamic section.  We fill in the
01460         values later, in elf_xtensa_finish_dynamic_sections, but we
01461         must add the entries now so that we get the correct size for
01462         the .dynamic section.  The DT_DEBUG entry is filled in by the
01463         dynamic linker and used by the debugger.  */
01464 #define add_dynamic_entry(TAG, VAL) \
01465   _bfd_elf_add_dynamic_entry (info, TAG, VAL)
01466 
01467       if (info->executable)
01468        {
01469          if (!add_dynamic_entry (DT_DEBUG, 0))
01470            return FALSE;
01471        }
01472 
01473       if (relplt)
01474        {
01475          if (!add_dynamic_entry (DT_PLTGOT, 0)
01476              || !add_dynamic_entry (DT_PLTRELSZ, 0)
01477              || !add_dynamic_entry (DT_PLTREL, DT_RELA)
01478              || !add_dynamic_entry (DT_JMPREL, 0))
01479            return FALSE;
01480        }
01481 
01482       if (relgot)
01483        {
01484          if (!add_dynamic_entry (DT_RELA, 0)
01485              || !add_dynamic_entry (DT_RELASZ, 0)
01486              || !add_dynamic_entry (DT_RELAENT, sizeof (Elf32_External_Rela)))
01487            return FALSE;
01488        }
01489 
01490       if (!add_dynamic_entry (DT_XTENSA_GOT_LOC_OFF, 0)
01491          || !add_dynamic_entry (DT_XTENSA_GOT_LOC_SZ, 0))
01492        return FALSE;
01493     }
01494 #undef add_dynamic_entry
01495 
01496   return TRUE;
01497 }
01498 
01499 
01500 /* Perform the specified relocation.  The instruction at (contents + address)
01501    is modified to set one operand to represent the value in "relocation".  The
01502    operand position is determined by the relocation type recorded in the
01503    howto.  */
01504 
01505 #define CALL_SEGMENT_BITS (30)
01506 #define CALL_SEGMENT_SIZE (1 << CALL_SEGMENT_BITS)
01507 
01508 static bfd_reloc_status_type
01509 elf_xtensa_do_reloc (reloc_howto_type *howto,
01510                    bfd *abfd,
01511                    asection *input_section,
01512                    bfd_vma relocation,
01513                    bfd_byte *contents,
01514                    bfd_vma address,
01515                    bfd_boolean is_weak_undef,
01516                    char **error_message)
01517 {
01518   xtensa_format fmt;
01519   xtensa_opcode opcode;
01520   xtensa_isa isa = xtensa_default_isa;
01521   static xtensa_insnbuf ibuff = NULL;
01522   static xtensa_insnbuf sbuff = NULL;
01523   bfd_vma self_address = 0;
01524   bfd_size_type input_size;
01525   int opnd, slot;
01526   uint32 newval;
01527 
01528   if (!ibuff)
01529     {
01530       ibuff = xtensa_insnbuf_alloc (isa);
01531       sbuff = xtensa_insnbuf_alloc (isa);
01532     }
01533 
01534   input_size = bfd_get_section_limit (abfd, input_section);
01535 
01536   switch (howto->type)
01537     {
01538     case R_XTENSA_NONE:
01539     case R_XTENSA_DIFF8:
01540     case R_XTENSA_DIFF16:
01541     case R_XTENSA_DIFF32:
01542       return bfd_reloc_ok;
01543 
01544     case R_XTENSA_ASM_EXPAND:
01545       if (!is_weak_undef)
01546        {
01547          /* Check for windowed CALL across a 1GB boundary.  */
01548          xtensa_opcode opcode =
01549            get_expanded_call_opcode (contents + address,
01550                                   input_size - address, 0);
01551          if (is_windowed_call_opcode (opcode))
01552            {
01553              self_address = (input_section->output_section->vma
01554                            + input_section->output_offset
01555                            + address);
01556              if ((self_address >> CALL_SEGMENT_BITS)
01557                 != (relocation >> CALL_SEGMENT_BITS)) 
01558               {
01559                 *error_message = "windowed longcall crosses 1GB boundary; "
01560                   "return may fail";
01561                 return bfd_reloc_dangerous;
01562               }
01563            }
01564        }
01565       return bfd_reloc_ok;
01566 
01567     case R_XTENSA_ASM_SIMPLIFY:
01568       {
01569         /* Convert the L32R/CALLX to CALL.  */
01570        bfd_reloc_status_type retval =
01571          elf_xtensa_do_asm_simplify (contents, address, input_size,
01572                                   error_message);
01573        if (retval != bfd_reloc_ok)
01574          return bfd_reloc_dangerous;
01575 
01576        /* The CALL needs to be relocated.  Continue below for that part.  */
01577        address += 3;
01578        howto = &elf_howto_table[(unsigned) R_XTENSA_SLOT0_OP ];
01579       }
01580       break;
01581 
01582     case R_XTENSA_32:
01583     case R_XTENSA_PLT:
01584       {
01585        bfd_vma x;
01586        x = bfd_get_32 (abfd, contents + address);
01587        x = x + relocation;
01588        bfd_put_32 (abfd, x, contents + address);
01589       }
01590       return bfd_reloc_ok;
01591     }
01592 
01593   /* Only instruction slot-specific relocations handled below.... */
01594   slot = get_relocation_slot (howto->type);
01595   if (slot == XTENSA_UNDEFINED)
01596     {
01597       *error_message = "unexpected relocation";
01598       return bfd_reloc_dangerous;
01599     }
01600 
01601   /* Read the instruction into a buffer and decode the opcode.  */
01602   xtensa_insnbuf_from_chars (isa, ibuff, contents + address,
01603                           input_size - address);
01604   fmt = xtensa_format_decode (isa, ibuff);
01605   if (fmt == XTENSA_UNDEFINED)
01606     {
01607       *error_message = "cannot decode instruction format";
01608       return bfd_reloc_dangerous;
01609     }
01610 
01611   xtensa_format_get_slot (isa, fmt, slot, ibuff, sbuff);
01612 
01613   opcode = xtensa_opcode_decode (isa, fmt, slot, sbuff);
01614   if (opcode == XTENSA_UNDEFINED)
01615     {
01616       *error_message = "cannot decode instruction opcode";
01617       return bfd_reloc_dangerous;
01618     }
01619 
01620   /* Check for opcode-specific "alternate" relocations.  */
01621   if (is_alt_relocation (howto->type))
01622     {
01623       if (opcode == get_l32r_opcode ())
01624        {
01625          /* Handle the special-case of non-PC-relative L32R instructions.  */
01626          bfd *output_bfd = input_section->output_section->owner;
01627          asection *lit4_sec = bfd_get_section_by_name (output_bfd, ".lit4");
01628          if (!lit4_sec)
01629            {
01630              *error_message = "relocation references missing .lit4 section";
01631              return bfd_reloc_dangerous;
01632            }
01633          self_address = ((lit4_sec->vma & ~0xfff)
01634                        + 0x40000 - 3); /* -3 to compensate for do_reloc */
01635          newval = relocation;
01636          opnd = 1;
01637        }
01638       else if (opcode == get_const16_opcode ())
01639        {
01640          /* ALT used for high 16 bits.  */
01641          newval = relocation >> 16;
01642          opnd = 1;
01643        }
01644       else
01645        {
01646          /* No other "alternate" relocations currently defined.  */
01647          *error_message = "unexpected relocation";
01648          return bfd_reloc_dangerous;
01649        }
01650     }
01651   else /* Not an "alternate" relocation.... */
01652     {
01653       if (opcode == get_const16_opcode ())
01654        {
01655          newval = relocation & 0xffff;
01656          opnd = 1;
01657        }
01658       else
01659        {
01660          /* ...normal PC-relative relocation.... */
01661 
01662          /* Determine which operand is being relocated.  */
01663          opnd = get_relocation_opnd (opcode, howto->type);
01664          if (opnd == XTENSA_UNDEFINED)
01665            {
01666              *error_message = "unexpected relocation";
01667              return bfd_reloc_dangerous;
01668            }
01669 
01670          if (!howto->pc_relative)
01671            {
01672              *error_message = "expected PC-relative relocation";
01673              return bfd_reloc_dangerous;
01674            }
01675 
01676          /* Calculate the PC address for this instruction.  */
01677          self_address = (input_section->output_section->vma
01678                        + input_section->output_offset
01679                        + address);
01680 
01681          newval = relocation;
01682        }
01683     }
01684 
01685   /* Apply the relocation.  */
01686   if (xtensa_operand_do_reloc (isa, opcode, opnd, &newval, self_address)
01687       || xtensa_operand_encode (isa, opcode, opnd, &newval)
01688       || xtensa_operand_set_field (isa, opcode, opnd, fmt, slot,
01689                                sbuff, newval))
01690     {
01691       const char *opname = xtensa_opcode_name (isa, opcode);
01692       const char *msg;
01693 
01694       msg = "cannot encode";
01695       if (is_direct_call_opcode (opcode))
01696        {
01697          if ((relocation & 0x3) != 0)
01698            msg = "misaligned call target";
01699          else
01700            msg = "call target out of range";
01701        }
01702       else if (opcode == get_l32r_opcode ())
01703        {
01704          if ((relocation & 0x3) != 0)
01705            msg = "misaligned literal target";
01706          else if (is_alt_relocation (howto->type))
01707            msg = "literal target out of range (too many literals)";
01708          else if (self_address > relocation)
01709            msg = "literal target out of range (try using text-section-literals)";
01710          else
01711            msg = "literal placed after use";
01712        }
01713 
01714       *error_message = vsprint_msg (opname, ": %s", strlen (msg) + 2, msg);
01715       return bfd_reloc_dangerous;
01716     }
01717 
01718   /* Check for calls across 1GB boundaries.  */
01719   if (is_direct_call_opcode (opcode)
01720       && is_windowed_call_opcode (opcode))
01721     {
01722       if ((self_address >> CALL_SEGMENT_BITS)
01723          != (relocation >> CALL_SEGMENT_BITS)) 
01724        {
01725          *error_message =
01726            "windowed call crosses 1GB boundary; return may fail";
01727          return bfd_reloc_dangerous;
01728        }
01729     }
01730 
01731   /* Write the modified instruction back out of the buffer.  */
01732   xtensa_format_set_slot (isa, fmt, slot, ibuff, sbuff);
01733   xtensa_insnbuf_to_chars (isa, ibuff, contents + address,
01734                         input_size - address);
01735   return bfd_reloc_ok;
01736 }
01737 
01738 
01739 static char *
01740 vsprint_msg (const char *origmsg, const char *fmt, int arglen, ...)
01741 {
01742   /* To reduce the size of the memory leak,
01743      we only use a single message buffer.  */
01744   static bfd_size_type alloc_size = 0;
01745   static char *message = NULL;
01746   bfd_size_type orig_len, len = 0;
01747   bfd_boolean is_append;
01748 
01749   VA_OPEN (ap, arglen);
01750   VA_FIXEDARG (ap, const char *, origmsg);
01751   
01752   is_append = (origmsg == message);  
01753 
01754   orig_len = strlen (origmsg);
01755   len = orig_len + strlen (fmt) + arglen + 20;
01756   if (len > alloc_size)
01757     {
01758       message = (char *) bfd_realloc (message, len);
01759       alloc_size = len;
01760     }
01761   if (!is_append)
01762     memcpy (message, origmsg, orig_len);
01763   vsprintf (message + orig_len, fmt, ap);
01764   VA_CLOSE (ap);
01765   return message;
01766 }
01767 
01768 
01769 /* This function is registered as the "special_function" in the
01770    Xtensa howto for handling simplify operations.
01771    bfd_perform_relocation / bfd_install_relocation use it to
01772    perform (install) the specified relocation.  Since this replaces the code
01773    in bfd_perform_relocation, it is basically an Xtensa-specific,
01774    stripped-down version of bfd_perform_relocation.  */
01775 
01776 static bfd_reloc_status_type
01777 bfd_elf_xtensa_reloc (bfd *abfd,
01778                     arelent *reloc_entry,
01779                     asymbol *symbol,
01780                     void *data,
01781                     asection *input_section,
01782                     bfd *output_bfd,
01783                     char **error_message)
01784 {
01785   bfd_vma relocation;
01786   bfd_reloc_status_type flag;
01787   bfd_size_type octets = reloc_entry->address * bfd_octets_per_byte (abfd);
01788   bfd_vma output_base = 0;
01789   reloc_howto_type *howto = reloc_entry->howto;
01790   asection *reloc_target_output_section;
01791   bfd_boolean is_weak_undef;
01792 
01793   if (!xtensa_default_isa)
01794     xtensa_default_isa = xtensa_isa_init (0, 0);
01795 
01796   /* ELF relocs are against symbols.  If we are producing relocatable
01797      output, and the reloc is against an external symbol, the resulting
01798      reloc will also be against the same symbol.  In such a case, we
01799      don't want to change anything about the way the reloc is handled,
01800      since it will all be done at final link time.  This test is similar
01801      to what bfd_elf_generic_reloc does except that it lets relocs with
01802      howto->partial_inplace go through even if the addend is non-zero.
01803      (The real problem is that partial_inplace is set for XTENSA_32
01804      relocs to begin with, but that's a long story and there's little we
01805      can do about it now....)  */
01806 
01807   if (output_bfd && (symbol->flags & BSF_SECTION_SYM) == 0)
01808     {
01809       reloc_entry->address += input_section->output_offset;
01810       return bfd_reloc_ok;
01811     }
01812 
01813   /* Is the address of the relocation really within the section?  */
01814   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
01815     return bfd_reloc_outofrange;
01816 
01817   /* Work out which section the relocation is targeted at and the
01818      initial relocation command value.  */
01819 
01820   /* Get symbol value.  (Common symbols are special.)  */
01821   if (bfd_is_com_section (symbol->section))
01822     relocation = 0;
01823   else
01824     relocation = symbol->value;
01825 
01826   reloc_target_output_section = symbol->section->output_section;
01827 
01828   /* Convert input-section-relative symbol value to absolute.  */
01829   if ((output_bfd && !howto->partial_inplace)
01830       || reloc_target_output_section == NULL)
01831     output_base = 0;
01832   else
01833     output_base = reloc_target_output_section->vma;
01834 
01835   relocation += output_base + symbol->section->output_offset;
01836 
01837   /* Add in supplied addend.  */
01838   relocation += reloc_entry->addend;
01839 
01840   /* Here the variable relocation holds the final address of the
01841      symbol we are relocating against, plus any addend.  */
01842   if (output_bfd)
01843     {
01844       if (!howto->partial_inplace)
01845        {
01846          /* This is a partial relocation, and we want to apply the relocation
01847             to the reloc entry rather than the raw data.  Everything except
01848             relocations against section symbols has already been handled
01849             above.  */
01850 
01851          BFD_ASSERT (symbol->flags & BSF_SECTION_SYM);
01852          reloc_entry->addend = relocation;
01853          reloc_entry->address += input_section->output_offset;
01854          return bfd_reloc_ok;
01855        }
01856       else
01857        {
01858          reloc_entry->address += input_section->output_offset;
01859          reloc_entry->addend = 0;
01860        }
01861     }
01862 
01863   is_weak_undef = (bfd_is_und_section (symbol->section)
01864                  && (symbol->flags & BSF_WEAK) != 0);
01865   flag = elf_xtensa_do_reloc (howto, abfd, input_section, relocation,
01866                            (bfd_byte *) data, (bfd_vma) octets,
01867                            is_weak_undef, error_message);
01868 
01869   if (flag == bfd_reloc_dangerous)
01870     {
01871       /* Add the symbol name to the error message.  */
01872       if (! *error_message)
01873        *error_message = "";
01874       *error_message = vsprint_msg (*error_message, ": (%s + 0x%lx)",
01875                                 strlen (symbol->name) + 17,
01876                                 symbol->name,
01877                                 (unsigned long) reloc_entry->addend);
01878     }
01879 
01880   return flag;
01881 }
01882 
01883 
01884 /* Set up an entry in the procedure linkage table.  */
01885 
01886 static bfd_vma
01887 elf_xtensa_create_plt_entry (struct bfd_link_info *info,
01888                           bfd *output_bfd,
01889                           unsigned reloc_index)
01890 {
01891   asection *splt, *sgotplt;
01892   bfd_vma plt_base, got_base;
01893   bfd_vma code_offset, lit_offset;
01894   int chunk;
01895 
01896   chunk = reloc_index / PLT_ENTRIES_PER_CHUNK;
01897   splt = elf_xtensa_get_plt_section (info, chunk);
01898   sgotplt = elf_xtensa_get_gotplt_section (info, chunk);
01899   BFD_ASSERT (splt != NULL && sgotplt != NULL);
01900 
01901   plt_base = splt->output_section->vma + splt->output_offset;
01902   got_base = sgotplt->output_section->vma + sgotplt->output_offset;
01903 
01904   lit_offset = 8 + (reloc_index % PLT_ENTRIES_PER_CHUNK) * 4;
01905   code_offset = (reloc_index % PLT_ENTRIES_PER_CHUNK) * PLT_ENTRY_SIZE;
01906 
01907   /* Fill in the literal entry.  This is the offset of the dynamic
01908      relocation entry.  */
01909   bfd_put_32 (output_bfd, reloc_index * sizeof (Elf32_External_Rela),
01910              sgotplt->contents + lit_offset);
01911 
01912   /* Fill in the entry in the procedure linkage table.  */
01913   memcpy (splt->contents + code_offset,
01914          (bfd_big_endian (output_bfd)
01915           ? elf_xtensa_be_plt_entry
01916           : elf_xtensa_le_plt_entry),
01917          PLT_ENTRY_SIZE);
01918   bfd_put_16 (output_bfd, l32r_offset (got_base + 0,
01919                                    plt_base + code_offset + 3),
01920              splt->contents + code_offset + 4);
01921   bfd_put_16 (output_bfd, l32r_offset (got_base + 4,
01922                                    plt_base + code_offset + 6),
01923              splt->contents + code_offset + 7);
01924   bfd_put_16 (output_bfd, l32r_offset (got_base + lit_offset,
01925                                    plt_base + code_offset + 9),
01926              splt->contents + code_offset + 10);
01927 
01928   return plt_base + code_offset;
01929 }
01930 
01931 
01932 /* Relocate an Xtensa ELF section.  This is invoked by the linker for
01933    both relocatable and final links.  */
01934 
01935 static bfd_boolean
01936 elf_xtensa_relocate_section (bfd *output_bfd,
01937                           struct bfd_link_info *info,
01938                           bfd *input_bfd,
01939                           asection *input_section,
01940                           bfd_byte *contents,
01941                           Elf_Internal_Rela *relocs,
01942                           Elf_Internal_Sym *local_syms,
01943                           asection **local_sections)
01944 {
01945   struct elf_xtensa_link_hash_table *htab;
01946   Elf_Internal_Shdr *symtab_hdr;
01947   Elf_Internal_Rela *rel;
01948   Elf_Internal_Rela *relend;
01949   struct elf_link_hash_entry **sym_hashes;
01950   property_table_entry *lit_table = 0;
01951   int ltblsize = 0;
01952   char *error_message = NULL;
01953   bfd_size_type input_size;
01954 
01955   if (!xtensa_default_isa)
01956     xtensa_default_isa = xtensa_isa_init (0, 0);
01957 
01958   htab = elf_xtensa_hash_table (info);
01959   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
01960   sym_hashes = elf_sym_hashes (input_bfd);
01961 
01962   if (elf_hash_table (info)->dynamic_sections_created)
01963     {
01964       ltblsize = xtensa_read_table_entries (input_bfd, input_section,
01965                                        &lit_table, XTENSA_LIT_SEC_NAME,
01966                                        TRUE);
01967       if (ltblsize < 0)
01968        return FALSE;
01969     }
01970 
01971   input_size = bfd_get_section_limit (input_bfd, input_section);
01972 
01973   rel = relocs;
01974   relend = relocs + input_section->reloc_count;
01975   for (; rel < relend; rel++)
01976     {
01977       int r_type;
01978       reloc_howto_type *howto;
01979       unsigned long r_symndx;
01980       struct elf_link_hash_entry *h;
01981       Elf_Internal_Sym *sym;
01982       asection *sec;
01983       bfd_vma relocation;
01984       bfd_reloc_status_type r;
01985       bfd_boolean is_weak_undef;
01986       bfd_boolean unresolved_reloc;
01987       bfd_boolean warned;
01988 
01989       r_type = ELF32_R_TYPE (rel->r_info);
01990       if (r_type == (int) R_XTENSA_GNU_VTINHERIT
01991          || r_type == (int) R_XTENSA_GNU_VTENTRY)
01992        continue;
01993 
01994       if (r_type < 0 || r_type >= (int) R_XTENSA_max)
01995        {
01996          bfd_set_error (bfd_error_bad_value);
01997          return FALSE;
01998        }
01999       howto = &elf_howto_table[r_type];
02000 
02001       r_symndx = ELF32_R_SYM (rel->r_info);
02002 
02003       h = NULL;
02004       sym = NULL;
02005       sec = NULL;
02006       is_weak_undef = FALSE;
02007       unresolved_reloc = FALSE;
02008       warned = FALSE;
02009 
02010       if (howto->partial_inplace && !info->relocatable)
02011        {
02012          /* Because R_XTENSA_32 was made partial_inplace to fix some
02013             problems with DWARF info in partial links, there may be
02014             an addend stored in the contents.  Take it out of there
02015             and move it back into the addend field of the reloc.  */
02016          rel->r_addend += bfd_get_32 (input_bfd, contents + rel->r_offset);
02017          bfd_put_32 (input_bfd, 0, contents + rel->r_offset);
02018        }
02019 
02020       if (r_symndx < symtab_hdr->sh_info)
02021        {
02022          sym = local_syms + r_symndx;
02023          sec = local_sections[r_symndx];
02024          relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
02025        }
02026       else
02027        {
02028          RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
02029                                r_symndx, symtab_hdr, sym_hashes,
02030                                h, sec, relocation,
02031                                unresolved_reloc, warned);
02032 
02033          if (relocation == 0
02034              && !unresolved_reloc
02035              && h->root.type == bfd_link_hash_undefweak)
02036            is_weak_undef = TRUE;
02037        }
02038 
02039       if (sec != NULL && elf_discarded_section (sec))
02040        {
02041          /* For relocs against symbols from removed linkonce sections,
02042             or sections discarded by a linker script, we just want the
02043             section contents zeroed.  Avoid any special processing.  */
02044          _bfd_clear_contents (howto, input_bfd, contents + rel->r_offset);
02045          rel->r_info = 0;
02046          rel->r_addend = 0;
02047          continue;
02048        }
02049 
02050       if (info->relocatable)
02051        {
02052          /* This is a relocatable link.
02053             1) If the reloc is against a section symbol, adjust
02054             according to the output section.
02055             2) If there is a new target for this relocation,
02056             the new target will be in the same output section.
02057             We adjust the relocation by the output section
02058             difference.  */
02059 
02060          if (relaxing_section)
02061            {
02062              /* Check if this references a section in another input file.  */
02063              if (!do_fix_for_relocatable_link (rel, input_bfd, input_section,
02064                                           contents))
02065               return FALSE;
02066              r_type = ELF32_R_TYPE (rel->r_info);
02067            }
02068 
02069          if (r_type == R_XTENSA_ASM_SIMPLIFY)
02070            {
02071              char *error_message = NULL;
02072              /* Convert ASM_SIMPLIFY into the simpler relocation
02073                so that they never escape a relaxing link.  */
02074              r = contract_asm_expansion (contents, input_size, rel,
02075                                      &error_message);
02076              if (r != bfd_reloc_ok)
02077               {
02078                 if (!((*info->callbacks->reloc_dangerous)
02079                      (info, error_message, input_bfd, input_section,
02080                       rel->r_offset)))
02081                   return FALSE;
02082               }
02083              r_type = ELF32_R_TYPE (rel->r_info);
02084            }
02085 
02086          /* This is a relocatable link, so we don't have to change
02087             anything unless the reloc is against a section symbol,
02088             in which case we have to adjust according to where the
02089             section symbol winds up in the output section.  */
02090          if (r_symndx < symtab_hdr->sh_info)
02091            {
02092              sym = local_syms + r_symndx;
02093              if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
02094               {
02095                 sec = local_sections[r_symndx];
02096                 rel->r_addend += sec->output_offset + sym->st_value;
02097               }
02098            }
02099 
02100          /* If there is an addend with a partial_inplace howto,
02101             then move the addend to the contents.  This is a hack
02102             to work around problems with DWARF in relocatable links
02103             with some previous version of BFD.  Now we can't easily get
02104             rid of the hack without breaking backward compatibility.... */
02105          if (rel->r_addend)
02106            {
02107              howto = &elf_howto_table[r_type];
02108              if (howto->partial_inplace)
02109               {
02110                 r = elf_xtensa_do_reloc (howto, input_bfd, input_section,
02111                                       rel->r_addend, contents,
02112                                       rel->r_offset, FALSE,
02113                                       &error_message);
02114                 if (r != bfd_reloc_ok)
02115                   {
02116                     if (!((*info->callbacks->reloc_dangerous)
02117                          (info, error_message, input_bfd, input_section,
02118                           rel->r_offset)))
02119                      return FALSE;
02120                   }
02121                 rel->r_addend = 0;
02122               }
02123            }
02124 
02125          /* Done with work for relocatable link; continue with next reloc.  */
02126          continue;
02127        }
02128 
02129       /* This is a final link.  */
02130 
02131       if (relaxing_section)
02132        {
02133          /* Check if this references a section in another input file.  */
02134          do_fix_for_final_link (rel, input_bfd, input_section, contents,
02135                              &relocation);
02136 
02137          /* Update some already cached values.  */
02138          r_type = ELF32_R_TYPE (rel->r_info);
02139          howto = &elf_howto_table[r_type];
02140        }
02141 
02142       /* Sanity check the address.  */
02143       if (rel->r_offset >= input_size
02144          && ELF32_R_TYPE (rel->r_info) != R_XTENSA_NONE)
02145        {
02146          (*_bfd_error_handler)
02147            (_("%B(%A+0x%lx): relocation offset out of range (size=0x%x)"),
02148             input_bfd, input_section, rel->r_offset, input_size);
02149          bfd_set_error (bfd_error_bad_value);
02150          return FALSE;
02151        }
02152 
02153       /* Generate dynamic relocations.  */
02154       if (elf_hash_table (info)->dynamic_sections_created)
02155        {
02156          bfd_boolean dynamic_symbol = elf_xtensa_dynamic_symbol_p (h, info);
02157 
02158          if (dynamic_symbol && is_operand_relocation (r_type))
02159            {
02160              /* This is an error.  The symbol's real value won't be known
02161                until runtime and it's likely to be out of range anyway.  */
02162              const char *name = h->root.root.string;
02163              error_message = vsprint_msg ("invalid relocation for dynamic "
02164                                       "symbol", ": %s",
02165                                       strlen (name) + 2, name);
02166              if (!((*info->callbacks->reloc_dangerous)
02167                   (info, error_message, input_bfd, input_section,
02168                    rel->r_offset)))
02169               return FALSE;
02170            }
02171          else if ((r_type == R_XTENSA_32 || r_type == R_XTENSA_PLT)
02172                  && (input_section->flags & SEC_ALLOC) != 0
02173                  && (dynamic_symbol || info->shared))
02174            {
02175              Elf_Internal_Rela outrel;
02176              bfd_byte *loc;
02177              asection *srel;
02178 
02179              if (dynamic_symbol && r_type == R_XTENSA_PLT)
02180               srel = htab->srelplt;
02181              else
02182               srel = htab->srelgot;
02183 
02184              BFD_ASSERT (srel != NULL);
02185 
02186              outrel.r_offset =
02187               _bfd_elf_section_offset (output_bfd, info,
02188                                     input_section, rel->r_offset);
02189 
02190              if ((outrel.r_offset | 1) == (bfd_vma) -1)
02191               memset (&outrel, 0, sizeof outrel);
02192              else
02193               {
02194                 outrel.r_offset += (input_section->output_section->vma
02195                                   + input_section->output_offset);
02196 
02197                 /* Complain if the relocation is in a read-only section
02198                    and not in a literal pool.  */
02199                 if ((input_section->flags & SEC_READONLY) != 0
02200                     && !elf_xtensa_in_literal_pool (lit_table, ltblsize,
02201                                                 outrel.r_offset))
02202                   {
02203                     error_message =
02204                      _("dynamic relocation in read-only section");
02205                     if (!((*info->callbacks->reloc_dangerous)
02206                          (info, error_message, input_bfd, input_section,
02207                           rel->r_offset)))
02208                      return FALSE;
02209                   }
02210 
02211                 if (dynamic_symbol)
02212                   {
02213                     outrel.r_addend = rel->r_addend;
02214                     rel->r_addend = 0;
02215 
02216                     if (r_type == R_XTENSA_32)
02217                      {
02218                        outrel.r_info =
02219                          ELF32_R_INFO (h->dynindx, R_XTENSA_GLOB_DAT);
02220                        relocation = 0;
02221                      }
02222                     else /* r_type == R_XTENSA_PLT */
02223                      {
02224                        outrel.r_info =
02225                          ELF32_R_INFO (h->dynindx, R_XTENSA_JMP_SLOT);
02226 
02227                        /* Create the PLT entry and set the initial
02228                           contents of the literal entry to the address of
02229                           the PLT entry.  */
02230                        relocation =
02231                          elf_xtensa_create_plt_entry (info, output_bfd,
02232                                                   srel->reloc_count);
02233                      }
02234                     unresolved_reloc = FALSE;
02235                   }
02236                 else
02237                   {
02238                     /* Generate a RELATIVE relocation.  */
02239                     outrel.r_info = ELF32_R_INFO (0, R_XTENSA_RELATIVE);
02240                     outrel.r_addend = 0;
02241                   }
02242               }
02243 
02244              loc = (srel->contents
02245                    + srel->reloc_count++ * sizeof (Elf32_External_Rela));
02246              bfd_elf32_swap_reloca_out (output_bfd, &outrel, loc);
02247              BFD_ASSERT (sizeof (Elf32_External_Rela) * srel->reloc_count
02248                        <= srel->size);
02249            }
02250        }
02251 
02252       /* Dynamic relocs are not propagated for SEC_DEBUGGING sections
02253         because such sections are not SEC_ALLOC and thus ld.so will
02254         not process them.  */
02255       if (unresolved_reloc
02256          && !((input_section->flags & SEC_DEBUGGING) != 0
02257               && h->def_dynamic))
02258        {
02259          (*_bfd_error_handler)
02260            (_("%B(%A+0x%lx): unresolvable %s relocation against symbol `%s'"),
02261             input_bfd,
02262             input_section,
02263             (long) rel->r_offset,
02264             howto->name,
02265             h->root.root.string);
02266          return FALSE;
02267        }
02268 
02269       /* There's no point in calling bfd_perform_relocation here.
02270         Just go directly to our "special function".  */
02271       r = elf_xtensa_do_reloc (howto, input_bfd, input_section,
02272                             relocation + rel->r_addend,
02273                             contents, rel->r_offset, is_weak_undef,
02274                             &error_message);
02275 
02276       if (r != bfd_reloc_ok && !warned)
02277        {
02278          const char *name;
02279 
02280          BFD_ASSERT (r == bfd_reloc_dangerous || r == bfd_reloc_other);
02281          BFD_ASSERT (error_message != NULL);
02282 
02283          if (h)
02284            name = h->root.root.string;
02285          else
02286            {
02287              name = bfd_elf_string_from_elf_section
02288               (input_bfd, symtab_hdr->sh_link, sym->st_name);
02289              if (name && *name == '\0')
02290               name = bfd_section_name (input_bfd, sec);
02291            }
02292          if (name)
02293            {
02294              if (rel->r_addend == 0)
02295               error_message = vsprint_msg (error_message, ": %s",
02296                                         strlen (name) + 2, name);
02297              else
02298               error_message = vsprint_msg (error_message, ": (%s+0x%x)",
02299                                         strlen (name) + 22,
02300                                         name, (int)rel->r_addend);
02301            }
02302 
02303          if (!((*info->callbacks->reloc_dangerous)
02304               (info, error_message, input_bfd, input_section,
02305                rel->r_offset)))
02306            return FALSE;
02307        }
02308     }
02309 
02310   if (lit_table)
02311     free (lit_table);
02312 
02313   input_section->reloc_done = TRUE;
02314 
02315   return TRUE;
02316 }
02317 
02318 
02319 /* Finish up dynamic symbol handling.  There's not much to do here since
02320    the PLT and GOT entries are all set up by relocate_section.  */
02321 
02322 static bfd_boolean
02323 elf_xtensa_finish_dynamic_symbol (bfd *output_bfd ATTRIBUTE_UNUSED,
02324                               struct bfd_link_info *info ATTRIBUTE_UNUSED,
02325                               struct elf_link_hash_entry *h,
02326                               Elf_Internal_Sym *sym)
02327 {
02328   if (h->needs_plt && !h->def_regular)
02329     {
02330       /* Mark the symbol as undefined, rather than as defined in
02331         the .plt section.  Leave the value alone.  */
02332       sym->st_shndx = SHN_UNDEF;
02333       /* If the symbol is weak, we do need to clear the value.
02334         Otherwise, the PLT entry would provide a definition for
02335         the symbol even if the symbol wasn't defined anywhere,
02336         and so the symbol would never be NULL.  */
02337       if (!h->ref_regular_nonweak)
02338        sym->st_value = 0;
02339     }
02340 
02341   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
02342   if (strcmp (h->root.root.string, "_DYNAMIC") == 0
02343       || h == elf_hash_table (info)->hgot)
02344     sym->st_shndx = SHN_ABS;
02345 
02346   return TRUE;
02347 }
02348 
02349 
02350 /* Combine adjacent literal table entries in the output.  Adjacent
02351    entries within each input section may have been removed during
02352    relaxation, but we repeat the process here, even though it's too late
02353    to shrink the output section, because it's important to minimize the
02354    number of literal table entries to reduce the start-up work for the
02355    runtime linker.  Returns the number of remaining table entries or -1
02356    on error.  */
02357 
02358 static int
02359 elf_xtensa_combine_prop_entries (bfd *output_bfd,
02360                              asection *sxtlit,
02361                              asection *sgotloc)
02362 {
02363   bfd_byte *contents;
02364   property_table_entry *table;
02365   bfd_size_type section_size, sgotloc_size;
02366   bfd_vma offset;
02367   int n, m, num;
02368 
02369   section_size = sxtlit->size;
02370   BFD_ASSERT (section_size % 8 == 0);
02371   num = section_size / 8;
02372 
02373   sgotloc_size = sgotloc->size;
02374   if (sgotloc_size != section_size)
02375     {
02376       (*_bfd_error_handler)
02377        (_("internal inconsistency in size of .got.loc section"));
02378       return -1;
02379     }
02380 
02381   table = bfd_malloc (num * sizeof (property_table_entry));
02382   if (table == 0)
02383     return -1;
02384 
02385   /* The ".xt.lit.plt" section has the SEC_IN_MEMORY flag set and this
02386      propagates to the output section, where it doesn't really apply and
02387      where it breaks the following call to bfd_malloc_and_get_section.  */
02388   sxtlit->flags &= ~SEC_IN_MEMORY;
02389 
02390   if (!bfd_malloc_and_get_section (output_bfd, sxtlit, &contents))
02391     {
02392       if (contents != 0)
02393        free (contents);
02394       free (table);
02395       return -1;
02396     }
02397 
02398   /* There should never be any relocations left at this point, so this
02399      is quite a bit easier than what is done during relaxation.  */
02400 
02401   /* Copy the raw contents into a property table array and sort it.  */
02402   offset = 0;
02403   for (n = 0; n < num; n++)
02404     {
02405       table[n].address = bfd_get_32 (output_bfd, &contents[offset]);
02406       table[n].size = bfd_get_32 (output_bfd, &contents[offset + 4]);
02407       offset += 8;
02408     }
02409   qsort (table, num, sizeof (property_table_entry), property_table_compare);
02410 
02411   for (n = 0; n < num; n++)
02412     {
02413       bfd_boolean remove = FALSE;
02414 
02415       if (table[n].size == 0)
02416        remove = TRUE;
02417       else if (n > 0 &&
02418               (table[n-1].address + table[n-1].size == table[n].address))
02419        {
02420          table[n-1].size += table[n].size;
02421          remove = TRUE;
02422        }
02423 
02424       if (remove)
02425        {
02426          for (m = n; m < num - 1; m++)
02427            {
02428              table[m].address = table[m+1].address;
02429              table[m].size = table[m+1].size;
02430            }
02431 
02432          n--;
02433          num--;
02434        }
02435     }
02436 
02437   /* Copy the data back to the raw contents.  */
02438   offset = 0;
02439   for (n = 0; n < num; n++)
02440     {
02441       bfd_put_32 (output_bfd, table[n].address, &contents[offset]);
02442       bfd_put_32 (output_bfd, table[n].size, &contents[offset + 4]);
02443       offset += 8;
02444     }
02445 
02446   /* Clear the removed bytes.  */
02447   if ((bfd_size_type) (num * 8) < section_size)
02448     memset (&contents[num * 8], 0, section_size - num * 8);
02449 
02450   if (! bfd_set_section_contents (output_bfd, sxtlit, contents, 0,
02451                               section_size))
02452     return -1;
02453 
02454   /* Copy the contents to ".got.loc".  */
02455   memcpy (sgotloc->contents, contents, section_size);
02456 
02457   free (contents);
02458   free (table);
02459   return num;
02460 }
02461 
02462 
02463 /* Finish up the dynamic sections.  */
02464 
02465 static bfd_boolean
02466 elf_xtensa_finish_dynamic_sections (bfd *output_bfd,
02467                                 struct bfd_link_info *info)
02468 {
02469   struct elf_xtensa_link_hash_table *htab;
02470   bfd *dynobj;
02471   asection *sdyn, *srelplt, *sgot, *sxtlit, *sgotloc;
02472   Elf32_External_Dyn *dyncon, *dynconend;
02473   int num_xtlit_entries;
02474 
02475   if (! elf_hash_table (info)->dynamic_sections_created)
02476     return TRUE;
02477 
02478   htab = elf_xtensa_hash_table (info);
02479   dynobj = elf_hash_table (info)->dynobj;
02480   sdyn = bfd_get_section_by_name (dynobj, ".dynamic");
02481   BFD_ASSERT (sdyn != NULL);
02482 
02483   /* Set the first entry in the global offset table to the address of
02484      the dynamic section.  */
02485   sgot = htab->sgot;
02486   if (sgot)
02487     {
02488       BFD_ASSERT (sgot->size == 4);
02489       if (sdyn == NULL)
02490        bfd_put_32 (output_bfd, 0, sgot->contents);
02491       else
02492        bfd_put_32 (output_bfd,
02493                   sdyn->output_section->vma + sdyn->output_offset,
02494                   sgot->contents);
02495     }
02496 
02497   srelplt = htab->srelplt;
02498   if (srelplt && srelplt->size != 0)
02499     {
02500       asection *sgotplt, *srelgot, *spltlittbl;
02501       int chunk, plt_chunks, plt_entries;
02502       Elf_Internal_Rela irela;
02503       bfd_byte *loc;
02504       unsigned rtld_reloc;
02505 
02506       srelgot = htab->srelgot;
02507       spltlittbl = htab->spltlittbl;
02508       BFD_ASSERT (srelgot != NULL && spltlittbl != NULL);
02509 
02510       /* Find the first XTENSA_RTLD relocation.  Presumably the rest
02511         of them follow immediately after....  */
02512       for (rtld_reloc = 0; rtld_reloc < srelgot->reloc_count; rtld_reloc++)
02513        {
02514          loc = srelgot->contents + rtld_reloc * sizeof (Elf32_External_Rela);
02515          bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
02516          if (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD)
02517            break;
02518        }
02519       BFD_ASSERT (rtld_reloc < srelgot->reloc_count);
02520 
02521       plt_entries = srelplt->size / sizeof (Elf32_External_Rela);
02522       plt_chunks =
02523        (plt_entries + PLT_ENTRIES_PER_CHUNK - 1) / PLT_ENTRIES_PER_CHUNK;
02524 
02525       for (chunk = 0; chunk < plt_chunks; chunk++)
02526        {
02527          int chunk_entries = 0;
02528 
02529          sgotplt = elf_xtensa_get_gotplt_section (info, chunk);
02530          BFD_ASSERT (sgotplt != NULL);
02531 
02532          /* Emit special RTLD relocations for the first two entries in
02533             each chunk of the .got.plt section.  */
02534 
02535          loc = srelgot->contents + rtld_reloc * sizeof (Elf32_External_Rela);
02536          bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
02537          BFD_ASSERT (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD);
02538          irela.r_offset = (sgotplt->output_section->vma
02539                          + sgotplt->output_offset);
02540          irela.r_addend = 1; /* tell rtld to set value to resolver function */
02541          bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
02542          rtld_reloc += 1;
02543          BFD_ASSERT (rtld_reloc <= srelgot->reloc_count);
02544 
02545          /* Next literal immediately follows the first.  */
02546          loc += sizeof (Elf32_External_Rela);
02547          bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
02548          BFD_ASSERT (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD);
02549          irela.r_offset = (sgotplt->output_section->vma
02550                          + sgotplt->output_offset + 4);
02551          /* Tell rtld to set value to object's link map.  */
02552          irela.r_addend = 2;
02553          bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
02554          rtld_reloc += 1;
02555          BFD_ASSERT (rtld_reloc <= srelgot->reloc_count);
02556 
02557          /* Fill in the literal table.  */
02558          if (chunk < plt_chunks - 1)
02559            chunk_entries = PLT_ENTRIES_PER_CHUNK;
02560          else
02561            chunk_entries = plt_entries - (chunk * PLT_ENTRIES_PER_CHUNK);
02562 
02563          BFD_ASSERT ((unsigned) (chunk + 1) * 8 <= spltlittbl->size);
02564          bfd_put_32 (output_bfd,
02565                     sgotplt->output_section->vma + sgotplt->output_offset,
02566                     spltlittbl->contents + (chunk * 8) + 0);
02567          bfd_put_32 (output_bfd,
02568                     8 + (chunk_entries * 4),
02569                     spltlittbl->contents + (chunk * 8) + 4);
02570        }
02571 
02572       /* All the dynamic relocations have been emitted at this point.
02573         Make sure the relocation sections are the correct size.  */
02574       if (srelgot->size != (sizeof (Elf32_External_Rela)
02575                          * srelgot->reloc_count)
02576          || srelplt->size != (sizeof (Elf32_External_Rela)
02577                             * srelplt->reloc_count))
02578        abort ();
02579 
02580      /* The .xt.lit.plt section has just been modified.  This must
02581        happen before the code below which combines adjacent literal
02582        table entries, and the .xt.lit.plt contents have to be forced to
02583        the output here.  */
02584       if (! bfd_set_section_contents (output_bfd,
02585                                   spltlittbl->output_section,
02586                                   spltlittbl->contents,
02587                                   spltlittbl->output_offset,
02588                                   spltlittbl->size))
02589        return FALSE;
02590       /* Clear SEC_HAS_CONTENTS so the contents won't be output again.  */
02591       spltlittbl->flags &= ~SEC_HAS_CONTENTS;
02592     }
02593 
02594   /* Combine adjacent literal table entries.  */
02595   BFD_ASSERT (! info->relocatable);
02596   sxtlit = bfd_get_section_by_name (output_bfd, ".xt.lit");
02597   sgotloc = htab->sgotloc;
02598   BFD_ASSERT (sxtlit && sgotloc);
02599   num_xtlit_entries =
02600     elf_xtensa_combine_prop_entries (output_bfd, sxtlit, sgotloc);
02601   if (num_xtlit_entries < 0)
02602     return FALSE;
02603 
02604   dyncon = (Elf32_External_Dyn *) sdyn->contents;
02605   dynconend = (Elf32_External_Dyn *) (sdyn->contents + sdyn->size);
02606   for (; dyncon < dynconend; dyncon++)
02607     {
02608       Elf_Internal_Dyn dyn;
02609 
02610       bfd_elf32_swap_dyn_in (dynobj, dyncon, &dyn);
02611 
02612       switch (dyn.d_tag)
02613        {
02614        default:
02615          break;
02616 
02617        case DT_XTENSA_GOT_LOC_SZ:
02618          dyn.d_un.d_val = num_xtlit_entries;
02619          break;
02620 
02621        case DT_XTENSA_GOT_LOC_OFF:
02622          dyn.d_un.d_ptr = htab->sgotloc->vma;
02623          break;
02624 
02625        case DT_PLTGOT:
02626          dyn.d_un.d_ptr = htab->sgot->vma;
02627          break;
02628 
02629        case DT_JMPREL:
02630          dyn.d_un.d_ptr = htab->srelplt->vma;
02631          break;
02632 
02633        case DT_PLTRELSZ:
02634          dyn.d_un.d_val = htab->srelplt->size;
02635          break;
02636 
02637        case DT_RELASZ:
02638          /* Adjust RELASZ to not include JMPREL.  This matches what
02639             glibc expects and what is done for several other ELF
02640             targets (e.g., i386, alpha), but the "correct" behavior
02641             seems to be unresolved.  Since the linker script arranges
02642             for .rela.plt to follow all other relocation sections, we
02643             don't have to worry about changing the DT_RELA entry.  */
02644          if (htab->srelplt)
02645            dyn.d_un.d_val -= htab->srelplt->size;
02646          break;
02647        }
02648 
02649       bfd_elf32_swap_dyn_out (output_bfd, &dyn, dyncon);
02650     }
02651 
02652   return TRUE;
02653 }
02654 
02655 
02656 /* Functions for dealing with the e_flags field.  */
02657 
02658 /* Merge backend specific data from an object file to the output
02659    object file when linking.  */
02660 
02661 static bfd_boolean
02662 elf_xtensa_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
02663 {
02664   unsigned out_mach, in_mach;
02665   flagword out_flag, in_flag;
02666 
02667   /* Check if we have the same endianess.  */
02668   if (!_bfd_generic_verify_endian_match (ibfd, obfd))
02669     return FALSE;
02670 
02671   /* Don't even pretend to support mixed-format linking.  */
02672   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
02673       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
02674     return FALSE;
02675 
02676   out_flag = elf_elfheader (obfd)->e_flags;
02677   in_flag = elf_elfheader (ibfd)->e_flags;
02678 
02679   out_mach = out_flag & EF_XTENSA_MACH;
02680   in_mach = in_flag & EF_XTENSA_MACH;
02681   if (out_mach != in_mach)
02682     {
02683       (*_bfd_error_handler)
02684        (_("%B: incompatible machine type. Output is 0x%x. Input is 0x%x"),
02685         ibfd, out_mach, in_mach);
02686       bfd_set_error (bfd_error_wrong_format);
02687       return FALSE;
02688     }
02689 
02690   if (! elf_flags_init (obfd))
02691     {
02692       elf_flags_init (obfd) = TRUE;
02693       elf_elfheader (obfd)->e_flags = in_flag;
02694 
02695       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
02696          && bfd_get_arch_info (obfd)->the_default)
02697        return bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
02698                               bfd_get_mach (ibfd));
02699 
02700       return TRUE;
02701     }
02702 
02703   if ((out_flag & EF_XTENSA_XT_INSN) != (in_flag & EF_XTENSA_XT_INSN)) 
02704     elf_elfheader (obfd)->e_flags &= (~ EF_XTENSA_XT_INSN);
02705 
02706   if ((out_flag & EF_XTENSA_XT_LIT) != (in_flag & EF_XTENSA_XT_LIT)) 
02707     elf_elfheader (obfd)->e_flags &= (~ EF_XTENSA_XT_LIT);
02708 
02709   return TRUE;
02710 }
02711 
02712 
02713 static bfd_boolean
02714 elf_xtensa_set_private_flags (bfd *abfd, flagword flags)
02715 {
02716   BFD_ASSERT (!elf_flags_init (abfd)
02717              || elf_elfheader (abfd)->e_flags == flags);
02718 
02719   elf_elfheader (abfd)->e_flags |= flags;
02720   elf_flags_init (abfd) = TRUE;
02721 
02722   return TRUE;
02723 }
02724 
02725 
02726 static bfd_boolean
02727 elf_xtensa_print_private_bfd_data (bfd *abfd, void *farg)
02728 {
02729   FILE *f = (FILE *) farg;
02730   flagword e_flags = elf_elfheader (abfd)->e_flags;
02731 
02732   fprintf (f, "\nXtensa header:\n");
02733   if ((e_flags & EF_XTENSA_MACH) == E_XTENSA_MACH)
02734     fprintf (f, "\nMachine     = Base\n");
02735   else
02736     fprintf (f, "\nMachine Id  = 0x%x\n", e_flags & EF_XTENSA_MACH);
02737 
02738   fprintf (f, "Insn tables = %s\n",
02739           (e_flags & EF_XTENSA_XT_INSN) ? "true" : "false");
02740 
02741   fprintf (f, "Literal tables = %s\n",
02742           (e_flags & EF_XTENSA_XT_LIT) ? "true" : "false");
02743 
02744   return _bfd_elf_print_private_bfd_data (abfd, farg);
02745 }
02746 
02747 
02748 /* Set the right machine number for an Xtensa ELF file.  */
02749 
02750 static bfd_boolean
02751 elf_xtensa_object_p (bfd *abfd)
02752 {
02753   int mach;
02754   unsigned long arch = elf_elfheader (abfd)->e_flags & EF_XTENSA_MACH;
02755 
02756   switch (arch)
02757     {
02758     case E_XTENSA_MACH:
02759       mach = bfd_mach_xtensa;
02760       break;
02761     default:
02762       return FALSE;
02763     }
02764 
02765   (void) bfd_default_set_arch_mach (abfd, bfd_arch_xtensa, mach);
02766   return TRUE;
02767 }
02768 
02769 
02770 /* The final processing done just before writing out an Xtensa ELF object
02771    file.  This gets the Xtensa architecture right based on the machine
02772    number.  */
02773 
02774 static void
02775 elf_xtensa_final_write_processing (bfd *abfd,
02776                                bfd_boolean linker ATTRIBUTE_UNUSED)
02777 {
02778   int mach;
02779   unsigned long val;
02780 
02781   switch (mach = bfd_get_mach (abfd))
02782     {
02783     case bfd_mach_xtensa:
02784       val = E_XTENSA_MACH;
02785       break;
02786     default:
02787       return;
02788     }
02789 
02790   elf_elfheader (abfd)->e_flags &=  (~ EF_XTENSA_MACH);
02791   elf_elfheader (abfd)->e_flags |= val;
02792 }
02793 
02794 
02795 static enum elf_reloc_type_class
02796 elf_xtensa_reloc_type_class (const Elf_Internal_Rela *rela)
02797 {
02798   switch ((int) ELF32_R_TYPE (rela->r_info))
02799     {
02800     case R_XTENSA_RELATIVE:
02801       return reloc_class_relative;
02802     case R_XTENSA_JMP_SLOT:
02803       return reloc_class_plt;
02804     default:
02805       return reloc_class_normal;
02806     }
02807 }
02808 
02809 
02810 static bfd_boolean
02811 elf_xtensa_discard_info_for_section (bfd *abfd,
02812                                  struct elf_reloc_cookie *cookie,
02813                                  struct bfd_link_info *info,
02814                                  asection *sec)
02815 {
02816   bfd_byte *contents;
02817   bfd_vma section_size;
02818   bfd_vma offset, actual_offset;
02819   size_t removed_bytes = 0;
02820 
02821   section_size = sec->size;
02822   if (section_size == 0 || section_size % 8 != 0)
02823     return FALSE;
02824 
02825   if (sec->output_section
02826       && bfd_is_abs_section (sec->output_section))
02827     return FALSE;
02828 
02829   contents = retrieve_contents (abfd, sec, info->keep_memory);
02830   if (!contents)
02831     return FALSE;
02832 
02833   cookie->rels = retrieve_internal_relocs (abfd, sec, info->keep_memory);
02834   if (!cookie->rels)
02835     {
02836       release_contents (sec, contents);
02837       return FALSE;
02838     }
02839 
02840   cookie->rel = cookie->rels;
02841   cookie->relend = cookie->rels + sec->reloc_count;
02842 
02843   for (offset = 0; offset < section_size; offset += 8)
02844     {
02845       actual_offset = offset - removed_bytes;
02846 
02847       /* The ...symbol_deleted_p function will skip over relocs but it
02848         won't adjust their offsets, so do that here.  */
02849       while (cookie->rel < cookie->relend
02850             && cookie->rel->r_offset < offset)
02851        {
02852          cookie->rel->r_offset -= removed_bytes;
02853          cookie->rel++;
02854        }
02855 
02856       while (cookie->rel < cookie->relend
02857             && cookie->rel->r_offset == offset)
02858        {
02859          if (bfd_elf_reloc_symbol_deleted_p (offset, cookie))
02860            {
02861              /* Remove the table entry.  (If the reloc type is NONE, then
02862                the entry has already been merged with another and deleted
02863                during relaxation.)  */
02864              if (ELF32_R_TYPE (cookie->rel->r_info) != R_XTENSA_NONE)
02865               {
02866                 /* Shift the contents up.  */
02867                 if (offset + 8 < section_size)
02868                   memmove (&contents[actual_offset],
02869                           &contents[actual_offset+8],
02870                           section_size - offset - 8);
02871                 removed_bytes += 8;
02872               }
02873 
02874              /* Remove this relocation.  */
02875              cookie->rel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
02876            }
02877 
02878          /* Adjust the relocation offset for previous removals.  This
02879             should not be done before calling ...symbol_deleted_p
02880             because it might mess up the offset comparisons there.
02881             Make sure the offset doesn't underflow in the case where
02882             the first entry is removed.  */
02883          if (cookie->rel->r_offset >= removed_bytes)
02884            cookie->rel->r_offset -= removed_bytes;
02885          else
02886            cookie->rel->r_offset = 0;
02887 
02888          cookie->rel++;
02889        }
02890     }
02891 
02892   if (removed_bytes != 0)
02893     {
02894       /* Adjust any remaining relocs (shouldn't be any).  */
02895       for (; cookie->rel < cookie->relend; cookie->rel++)
02896        {
02897          if (cookie->rel->r_offset >= removed_bytes)
02898            cookie->rel->r_offset -= removed_bytes;
02899          else
02900            cookie->rel->r_offset = 0;
02901        }
02902 
02903       /* Clear the removed bytes.  */
02904       memset (&contents[section_size - removed_bytes], 0, removed_bytes);
02905 
02906       pin_contents (sec, contents);
02907       pin_internal_relocs (sec, cookie->rels);
02908 
02909       /* Shrink size.  */
02910       sec->size = section_size - removed_bytes;
02911 
02912       if (xtensa_is_littable_section (sec))
02913        {
02914          asection *sgotloc = elf_xtensa_hash_table (info)->sgotloc;
02915          if (sgotloc)
02916            sgotloc->size -= removed_bytes;
02917        }
02918     }
02919   else
02920     {
02921       release_contents (sec, contents);
02922       release_internal_relocs (sec, cookie->rels);
02923     }
02924 
02925   return (removed_bytes != 0);
02926 }
02927 
02928 
02929 static bfd_boolean
02930 elf_xtensa_discard_info (bfd *abfd,
02931                       struct elf_reloc_cookie *cookie,
02932                       struct bfd_link_info *info)
02933 {
02934   asection *sec;
02935   bfd_boolean changed = FALSE;
02936 
02937   for (sec = abfd->sections; sec != NULL; sec = sec->next)
02938     {
02939       if (xtensa_is_property_section (sec))
02940        {
02941          if (elf_xtensa_discard_info_for_section (abfd, cookie, info, sec))
02942            changed = TRUE;
02943        }
02944     }
02945 
02946   return changed;
02947 }
02948 
02949 
02950 static bfd_boolean
02951 elf_xtensa_ignore_discarded_relocs (asection *sec)
02952 {
02953   return xtensa_is_property_section (sec);
02954 }
02955 
02956 
02957 static unsigned int
02958 elf_xtensa_action_discarded (asection *sec)
02959 {
02960   if (strcmp (".xt_except_table", sec->name) == 0)
02961     return 0;
02962 
02963   if (strcmp (".xt_except_desc", sec->name) == 0)
02964     return 0;
02965 
02966   return _bfd_elf_default_action_discarded (sec);
02967 }
02968 
02969 
02970 /* Support for core dump NOTE sections.  */
02971 
02972 static bfd_boolean
02973 elf_xtensa_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
02974 {
02975   int offset;
02976   unsigned int size;
02977 
02978   /* The size for Xtensa is variable, so don't try to recognize the format
02979      based on the size.  Just assume this is GNU/Linux.  */
02980 
02981   /* pr_cursig */
02982   elf_tdata (abfd)->core_signal = bfd_get_16 (abfd, note->descdata + 12);
02983 
02984   /* pr_pid */
02985   elf_tdata (abfd)->core_pid = bfd_get_32 (abfd, note->descdata + 24);
02986 
02987   /* pr_reg */
02988   offset = 72;
02989   size = note->descsz - offset - 4;
02990 
02991   /* Make a ".reg/999" section.  */
02992   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
02993                                      size, note->descpos + offset);
02994 }
02995 
02996 
02997 static bfd_boolean
02998 elf_xtensa_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
02999 {
03000   switch (note->descsz)
03001     {
03002       default:
03003        return FALSE;
03004 
03005       case 128:             /* GNU/Linux elf_prpsinfo */
03006        elf_tdata (abfd)->core_program
03007         = _bfd_elfcore_strndup (abfd, note->descdata + 32, 16);
03008        elf_tdata (abfd)->core_command
03009         = _bfd_elfcore_strndup (abfd, note->descdata + 48, 80);
03010     }
03011 
03012   /* Note that for some reason, a spurious space is tacked
03013      onto the end of the args in some (at least one anyway)
03014      implementations, so strip it off if it exists.  */
03015 
03016   {
03017     char *command = elf_tdata (abfd)->core_command;
03018     int n = strlen (command);
03019 
03020     if (0 < n && command[n - 1] == ' ')
03021       command[n - 1] = '\0';
03022   }
03023 
03024   return TRUE;
03025 }
03026 
03027 
03028 /* Generic Xtensa configurability stuff.  */
03029 
03030 static xtensa_opcode callx0_op = XTENSA_UNDEFINED;
03031 static xtensa_opcode callx4_op = XTENSA_UNDEFINED;
03032 static xtensa_opcode callx8_op = XTENSA_UNDEFINED;
03033 static xtensa_opcode callx12_op = XTENSA_UNDEFINED;
03034 static xtensa_opcode call0_op = XTENSA_UNDEFINED;
03035 static xtensa_opcode call4_op = XTENSA_UNDEFINED;
03036 static xtensa_opcode call8_op = XTENSA_UNDEFINED;
03037 static xtensa_opcode call12_op = XTENSA_UNDEFINED;
03038 
03039 static void
03040 init_call_opcodes (void)
03041 {
03042   if (callx0_op == XTENSA_UNDEFINED)
03043     {
03044       callx0_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx0");
03045       callx4_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx4");
03046       callx8_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx8");
03047       callx12_op = xtensa_opcode_lookup (xtensa_default_isa, "callx12");
03048       call0_op   = xtensa_opcode_lookup (xtensa_default_isa, "call0");
03049       call4_op   = xtensa_opcode_lookup (xtensa_default_isa, "call4");
03050       call8_op   = xtensa_opcode_lookup (xtensa_default_isa, "call8");
03051       call12_op  = xtensa_opcode_lookup (xtensa_default_isa, "call12");
03052     }
03053 }
03054 
03055 
03056 static bfd_boolean
03057 is_indirect_call_opcode (xtensa_opcode opcode)
03058 {
03059   init_call_opcodes ();
03060   return (opcode == callx0_op
03061          || opcode == callx4_op
03062          || opcode == callx8_op
03063          || opcode == callx12_op);
03064 }
03065 
03066 
03067 static bfd_boolean
03068 is_direct_call_opcode (xtensa_opcode opcode)
03069 {
03070   init_call_opcodes ();
03071   return (opcode == call0_op
03072          || opcode == call4_op
03073          || opcode == call8_op
03074          || opcode == call12_op);
03075 }
03076 
03077 
03078 static bfd_boolean
03079 is_windowed_call_opcode (xtensa_opcode opcode)
03080 {
03081   init_call_opcodes ();
03082   return (opcode == call4_op
03083          || opcode == call8_op
03084          || opcode == call12_op
03085          || opcode == callx4_op
03086          || opcode == callx8_op
03087          || opcode == callx12_op);
03088 }
03089 
03090 
03091 static xtensa_opcode
03092 get_const16_opcode (void)
03093 {
03094   static bfd_boolean done_lookup = FALSE;
03095   static xtensa_opcode const16_opcode = XTENSA_UNDEFINED;
03096   if (!done_lookup)
03097     {
03098       const16_opcode = xtensa_opcode_lookup (xtensa_default_isa, "const16");
03099       done_lookup = TRUE;
03100     }
03101   return const16_opcode;
03102 }
03103 
03104 
03105 static xtensa_opcode
03106 get_l32r_opcode (void)
03107 {
03108   static xtensa_opcode l32r_opcode = XTENSA_UNDEFINED;
03109   static bfd_boolean done_lookup = FALSE;
03110 
03111   if (!done_lookup)
03112     {
03113       l32r_opcode = xtensa_opcode_lookup (xtensa_default_isa, "l32r");
03114       done_lookup = TRUE;
03115     }
03116   return l32r_opcode;
03117 }
03118 
03119 
03120 static bfd_vma
03121 l32r_offset (bfd_vma addr, bfd_vma pc)
03122 {
03123   bfd_vma offset;
03124 
03125   offset = addr - ((pc+3) & -4);
03126   BFD_ASSERT ((offset & ((1 << 2) - 1)) == 0);
03127   offset = (signed int) offset >> 2;
03128   BFD_ASSERT ((signed int) offset >> 16 == -1);
03129   return offset;
03130 }
03131 
03132 
03133 static int
03134 get_relocation_opnd (xtensa_opcode opcode, int r_type)
03135 {
03136   xtensa_isa isa = xtensa_default_isa;
03137   int last_immed, last_opnd, opi;
03138 
03139   if (opcode == XTENSA_UNDEFINED)
03140     return XTENSA_UNDEFINED;
03141 
03142   /* Find the last visible PC-relative immediate operand for the opcode.
03143      If there are no PC-relative immediates, then choose the last visible
03144      immediate; otherwise, fail and return XTENSA_UNDEFINED.  */
03145   last_immed = XTENSA_UNDEFINED;
03146   last_opnd = xtensa_opcode_num_operands (isa, opcode);
03147   for (opi = last_opnd - 1; opi >= 0; opi--)
03148     {
03149       if (xtensa_operand_is_visible (isa, opcode, opi) == 0)
03150        continue;
03151       if (xtensa_operand_is_PCrelative (isa, opcode, opi) == 1)
03152        {
03153          last_immed = opi;
03154          break;
03155        }
03156       if (last_immed == XTENSA_UNDEFINED
03157          && xtensa_operand_is_register (isa, opcode, opi) == 0)
03158        last_immed = opi;
03159     }
03160   if (last_immed < 0)
03161     return XTENSA_UNDEFINED;
03162 
03163   /* If the operand number was specified in an old-style relocation,
03164      check for consistency with the operand computed above.  */
03165   if (r_type >= R_XTENSA_OP0 && r_type <= R_XTENSA_OP2)
03166     {
03167       int reloc_opnd = r_type - R_XTENSA_OP0;
03168       if (reloc_opnd != last_immed)
03169        return XTENSA_UNDEFINED;
03170     }
03171 
03172   return last_immed;
03173 }
03174 
03175 
03176 int
03177 get_relocation_slot (int r_type)
03178 {
03179   switch (r_type)
03180     {
03181     case R_XTENSA_OP0:
03182     case R_XTENSA_OP1:
03183     case R_XTENSA_OP2:
03184       return 0;
03185 
03186     default:
03187       if (r_type >= R_XTENSA_SLOT0_OP && r_type <= R_XTENSA_SLOT14_OP)
03188        return r_type - R_XTENSA_SLOT0_OP;
03189       if (r_type >= R_XTENSA_SLOT0_ALT && r_type <= R_XTENSA_SLOT14_ALT)
03190        return r_type - R_XTENSA_SLOT0_ALT;
03191       break;
03192     }
03193 
03194   return XTENSA_UNDEFINED;
03195 }
03196 
03197 
03198 /* Get the opcode for a relocation.  */
03199 
03200 static xtensa_opcode
03201 get_relocation_opcode (bfd *abfd,
03202                      asection *sec,
03203                      bfd_byte *contents,
03204                      Elf_Internal_Rela *irel)
03205 {
03206   static xtensa_insnbuf ibuff = NULL;
03207   static xtensa_insnbuf sbuff = NULL;
03208   xtensa_isa isa = xtensa_default_isa;
03209   xtensa_format fmt;
03210   int slot;
03211 
03212   if (contents == NULL)
03213     return XTENSA_UNDEFINED;
03214 
03215   if (bfd_get_section_limit (abfd, sec) <= irel->r_offset)
03216     return XTENSA_UNDEFINED;
03217 
03218   if (ibuff == NULL)
03219     {
03220       ibuff = xtensa_insnbuf_alloc (isa);
03221       sbuff = xtensa_insnbuf_alloc (isa);
03222     }
03223 
03224   /* Decode the instruction.  */
03225   xtensa_insnbuf_from_chars (isa, ibuff, &contents[irel->r_offset],
03226                           sec->size - irel->r_offset);
03227   fmt = xtensa_format_decode (isa, ibuff);
03228   slot = get_relocation_slot (ELF32_R_TYPE (irel->r_info));
03229   if (slot == XTENSA_UNDEFINED)
03230     return XTENSA_UNDEFINED;
03231   xtensa_format_get_slot (isa, fmt, slot, ibuff, sbuff);
03232   return xtensa_opcode_decode (isa, fmt, slot, sbuff);
03233 }
03234 
03235 
03236 bfd_boolean
03237 is_l32r_relocation (bfd *abfd,
03238                   asection *sec,
03239                   bfd_byte *contents,
03240                   Elf_Internal_Rela *irel)
03241 {
03242   xtensa_opcode opcode;
03243   if (!is_operand_relocation (ELF32_R_TYPE (irel->r_info)))
03244     return FALSE;
03245   opcode = get_relocation_opcode (abfd, sec, contents, irel);
03246   return (opcode == get_l32r_opcode ());
03247 }
03248 
03249 
03250 static bfd_size_type
03251 get_asm_simplify_size (bfd_byte *contents,
03252                      bfd_size_type content_len,
03253                      bfd_size_type offset)
03254 {
03255   bfd_size_type insnlen, size = 0;
03256 
03257   /* Decode the size of the next two instructions.  */
03258   insnlen = insn_decode_len (contents, content_len, offset);
03259   if (insnlen == 0)
03260     return 0;
03261 
03262   size += insnlen;
03263   
03264   insnlen = insn_decode_len (contents, content_len, offset + size);
03265   if (insnlen == 0)
03266     return 0;
03267 
03268   size += insnlen;
03269   return size;
03270 }
03271 
03272 
03273 bfd_boolean
03274 is_alt_relocation (int r_type)
03275 {
03276   return (r_type >= R_XTENSA_SLOT0_ALT
03277          && r_type <= R_XTENSA_SLOT14_ALT);
03278 }
03279 
03280 
03281 bfd_boolean
03282 is_operand_relocation (int r_type)
03283 {
03284   switch (r_type)
03285     {
03286     case R_XTENSA_OP0:
03287     case R_XTENSA_OP1:
03288     case R_XTENSA_OP2:
03289       return TRUE;
03290 
03291     default:
03292       if (r_type >= R_XTENSA_SLOT0_OP && r_type <= R_XTENSA_SLOT14_OP)
03293        return TRUE;
03294       if (r_type >= R_XTENSA_SLOT0_ALT && r_type <= R_XTENSA_SLOT14_ALT)
03295        return TRUE;
03296       break;
03297     }
03298 
03299   return FALSE;
03300 }
03301 
03302       
03303 #define MIN_INSN_LENGTH 2
03304 
03305 /* Return 0 if it fails to decode.  */
03306 
03307 bfd_size_type
03308 insn_decode_len (bfd_byte *contents,
03309                bfd_size_type content_len,
03310                bfd_size_type offset)
03311 {
03312   int insn_len;
03313   xtensa_isa isa = xtensa_default_isa;
03314   xtensa_format fmt;
03315   static xtensa_insnbuf ibuff = NULL;
03316 
03317   if (offset + MIN_INSN_LENGTH > content_len)
03318     return 0;
03319 
03320   if (ibuff == NULL)
03321     ibuff = xtensa_insnbuf_alloc (isa);
03322   xtensa_insnbuf_from_chars (isa, ibuff, &contents[offset],
03323                           content_len - offset);
03324   fmt = xtensa_format_decode (isa, ibuff);
03325   if (fmt == XTENSA_UNDEFINED)
03326     return 0;
03327   insn_len = xtensa_format_length (isa, fmt);
03328   if (insn_len ==  XTENSA_UNDEFINED)
03329     return 0;
03330   return insn_len;
03331 }
03332 
03333 
03334 /* Decode the opcode for a single slot instruction.
03335    Return 0 if it fails to decode or the instruction is multi-slot.  */
03336 
03337 xtensa_opcode
03338 insn_decode_opcode (bfd_byte *contents,
03339                   bfd_size_type content_len,
03340                   bfd_size_type offset,
03341                   int slot)
03342 {
03343   xtensa_isa isa = xtensa_default_isa;
03344   xtensa_format fmt;
03345   static xtensa_insnbuf insnbuf = NULL;
03346   static xtensa_insnbuf slotbuf = NULL;
03347 
03348   if (offset + MIN_INSN_LENGTH > content_len)
03349     return XTENSA_UNDEFINED;
03350 
03351   if (insnbuf == NULL)
03352     {
03353       insnbuf = xtensa_insnbuf_alloc (isa);
03354       slotbuf = xtensa_insnbuf_alloc (isa);
03355     }
03356 
03357   xtensa_insnbuf_from_chars (isa, insnbuf, &contents[offset],
03358                           content_len - offset);
03359   fmt = xtensa_format_decode (isa, insnbuf);
03360   if (fmt == XTENSA_UNDEFINED)
03361     return XTENSA_UNDEFINED;
03362 
03363   if (slot >= xtensa_format_num_slots (isa, fmt))
03364     return XTENSA_UNDEFINED;
03365 
03366   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
03367   return xtensa_opcode_decode (isa, fmt, slot, slotbuf);
03368 }
03369 
03370 
03371 /* The offset is the offset in the contents.
03372    The address is the address of that offset.  */
03373 
03374 static bfd_boolean
03375 check_branch_target_aligned (bfd_byte *contents,
03376                           bfd_size_type content_length,
03377                           bfd_vma offset,
03378                           bfd_vma address)
03379 {
03380   bfd_size_type insn_len = insn_decode_len (contents, content_length, offset);
03381   if (insn_len == 0)
03382     return FALSE;
03383   return check_branch_target_aligned_address (address, insn_len);
03384 }
03385 
03386 
03387 static bfd_boolean
03388 check_loop_aligned (bfd_byte *contents,
03389                   bfd_size_type content_length,
03390                   bfd_vma offset,
03391                   bfd_vma address)
03392 {
03393   bfd_size_type loop_len, insn_len;
03394   xtensa_opcode opcode;
03395 
03396   opcode = insn_decode_opcode (contents, content_length, offset, 0);
03397   if (opcode == XTENSA_UNDEFINED
03398       || xtensa_opcode_is_loop (xtensa_default_isa, opcode) != 1)
03399     {
03400       BFD_ASSERT (FALSE);
03401       return FALSE;
03402     }
03403   
03404   loop_len = insn_decode_len (contents, content_length, offset);
03405   insn_len = insn_decode_len (contents, content_length, offset + loop_len);
03406   if (loop_len == 0 || insn_len == 0)
03407     {
03408       BFD_ASSERT (FALSE);
03409       return FALSE;
03410     }
03411 
03412   return check_branch_target_aligned_address (address + loop_len, insn_len);
03413 }
03414 
03415 
03416 static bfd_boolean
03417 check_branch_target_aligned_address (bfd_vma addr, int len)
03418 {
03419   if (len == 8)
03420     return (addr % 8 == 0);
03421   return ((addr >> 2) == ((addr + len - 1) >> 2));
03422 }
03423 
03424 
03425 /* Instruction widening and narrowing.  */
03426 
03427 /* When FLIX is available we need to access certain instructions only
03428    when they are 16-bit or 24-bit instructions.  This table caches
03429    information about such instructions by walking through all the
03430    opcodes and finding the smallest single-slot format into which each
03431    can be encoded.  */
03432 
03433 static xtensa_format *op_single_fmt_table = NULL;
03434 
03435 
03436 static void
03437 init_op_single_format_table (void)
03438 {
03439   xtensa_isa isa = xtensa_default_isa;
03440   xtensa_insnbuf ibuf;
03441   xtensa_opcode opcode;
03442   xtensa_format fmt;
03443   int num_opcodes;
03444 
03445   if (op_single_fmt_table)
03446     return;
03447 
03448   ibuf = xtensa_insnbuf_alloc (isa);
03449   num_opcodes = xtensa_isa_num_opcodes (isa);
03450 
03451   op_single_fmt_table = (xtensa_format *)
03452     bfd_malloc (sizeof (xtensa_format) * num_opcodes);
03453   for (opcode = 0; opcode < num_opcodes; opcode++)
03454     {
03455       op_single_fmt_table[opcode] = XTENSA_UNDEFINED;
03456       for (fmt = 0; fmt < xtensa_isa_num_formats (isa); fmt++)
03457        {
03458          if (xtensa_format_num_slots (isa, fmt) == 1
03459              && xtensa_opcode_encode (isa, fmt, 0, ibuf, opcode) == 0)
03460            {
03461              xtensa_opcode old_fmt = op_single_fmt_table[opcode];
03462              int fmt_length = xtensa_format_length (isa, fmt);
03463              if (old_fmt == XTENSA_UNDEFINED
03464                 || fmt_length < xtensa_format_length (isa, old_fmt))
03465               op_single_fmt_table[opcode] = fmt;
03466            }
03467        }
03468     }
03469   xtensa_insnbuf_free (isa, ibuf);
03470 }
03471 
03472 
03473 static xtensa_format
03474 get_single_format (xtensa_opcode opcode)
03475 {
03476   init_op_single_format_table ();
03477   return op_single_fmt_table[opcode];
03478 }
03479 
03480 
03481 /* For the set of narrowable instructions we do NOT include the
03482    narrowings beqz -> beqz.n or bnez -> bnez.n because of complexities
03483    involved during linker relaxation that may require these to
03484    re-expand in some conditions.  Also, the narrowing "or" -> mov.n
03485    requires special case code to ensure it only works when op1 == op2.  */
03486 
03487 struct string_pair
03488 {
03489   const char *wide;
03490   const char *narrow;
03491 };
03492 
03493 struct string_pair narrowable[] =
03494 {
03495   { "add", "add.n" },
03496   { "addi", "addi.n" },
03497   { "addmi", "addi.n" },
03498   { "l32i", "l32i.n" },
03499   { "movi", "movi.n" },
03500   { "ret", "ret.n" },
03501   { "retw", "retw.n" },
03502   { "s32i", "s32i.n" },
03503   { "or", "mov.n" } /* special case only when op1 == op2 */
03504 };
03505 
03506 struct string_pair widenable[] =
03507 {
03508   { "add", "add.n" },
03509   { "addi", "addi.n" },
03510   { "addmi", "addi.n" },
03511   { "beqz", "beqz.n" },
03512   { "bnez", "bnez.n" },
03513   { "l32i", "l32i.n" },
03514   { "movi", "movi.n" },
03515   { "ret", "ret.n" },
03516   { "retw", "retw.n" },
03517   { "s32i", "s32i.n" },
03518   { "or", "mov.n" } /* special case only when op1 == op2 */
03519 };
03520 
03521 
03522 /* Check if an instruction can be "narrowed", i.e., changed from a standard
03523    3-byte instruction to a 2-byte "density" instruction.  If it is valid,
03524    return the instruction buffer holding the narrow instruction.  Otherwise,
03525    return 0.  The set of valid narrowing are specified by a string table
03526    but require some special case operand checks in some cases.  */
03527 
03528 static xtensa_insnbuf
03529 can_narrow_instruction (xtensa_insnbuf slotbuf,
03530                      xtensa_format fmt,
03531                      xtensa_opcode opcode)
03532 {
03533   xtensa_isa isa = xtensa_default_isa;
03534   xtensa_format o_fmt;
03535   unsigned opi;
03536 
03537   static xtensa_insnbuf o_insnbuf = NULL;
03538   static xtensa_insnbuf o_slotbuf = NULL;
03539 
03540   if (o_insnbuf == NULL)
03541     {
03542       o_insnbuf = xtensa_insnbuf_alloc (isa);
03543       o_slotbuf = xtensa_insnbuf_alloc (isa);
03544     }
03545 
03546   for (opi = 0; opi < (sizeof (narrowable)/sizeof (struct string_pair)); opi++)
03547     {
03548       bfd_boolean is_or = (strcmp ("or", narrowable[opi].wide) == 0);
03549 
03550       if (opcode == xtensa_opcode_lookup (isa, narrowable[opi].wide))
03551        {
03552          uint32 value, newval;
03553          int i, operand_count, o_operand_count;
03554          xtensa_opcode o_opcode;
03555 
03556          /* Address does not matter in this case.  We might need to
03557             fix it to handle branches/jumps.  */
03558          bfd_vma self_address = 0;
03559 
03560          o_opcode = xtensa_opcode_lookup (isa, narrowable[opi].narrow);
03561          if (o_opcode == XTENSA_UNDEFINED)
03562            return 0;
03563          o_fmt = get_single_format (o_opcode);
03564          if (o_fmt == XTENSA_UNDEFINED)
03565            return 0;
03566 
03567          if (xtensa_format_length (isa, fmt) != 3
03568              || xtensa_format_length (isa, o_fmt) != 2)
03569            return 0;
03570 
03571          xtensa_format_encode (isa, o_fmt, o_insnbuf);
03572          operand_count = xtensa_opcode_num_operands (isa, opcode);
03573          o_operand_count = xtensa_opcode_num_operands (isa, o_opcode);
03574 
03575          if (xtensa_opcode_encode (isa, o_fmt, 0, o_slotbuf, o_opcode) != 0)
03576            return 0;
03577 
03578          if (!is_or)
03579            {
03580              if (xtensa_opcode_num_operands (isa, o_opcode) != operand_count)
03581               return 0;
03582            }
03583          else
03584            {
03585              uint32 rawval0, rawval1, rawval2;
03586 
03587              if (o_operand_count + 1 != operand_count
03588                 || xtensa_operand_get_field (isa, opcode, 0,
03589                                           fmt, 0, slotbuf, &rawval0) != 0
03590                 || xtensa_operand_get_field (isa, opcode, 1,
03591                                           fmt, 0, slotbuf, &rawval1) != 0
03592                 || xtensa_operand_get_field (isa, opcode, 2,
03593                                           fmt, 0, slotbuf, &rawval2) != 0
03594                 || rawval1 != rawval2
03595                 || rawval0 == rawval1 /* it is a nop */)
03596               return 0;
03597            }
03598 
03599          for (i = 0; i < o_operand_count; ++i)
03600            {
03601              if (xtensa_operand_get_field (isa, opcode, i, fmt, 0,
03602                                        slotbuf, &value)
03603                 || xtensa_operand_decode (isa, opcode, i, &value))
03604               return 0;
03605 
03606              /* PC-relative branches need adjustment, but
03607                the PC-rel operand will always have a relocation.  */
03608              newval = value;
03609              if (xtensa_operand_do_reloc (isa, o_opcode, i, &newval,
03610                                       self_address)
03611                 || xtensa_operand_encode (isa, o_opcode, i, &newval)
03612                 || xtensa_operand_set_field (isa, o_opcode, i, o_fmt, 0,
03613                                           o_slotbuf, newval))
03614               return 0;
03615            }
03616 
03617          if (xtensa_format_set_slot (isa, o_fmt, 0, o_insnbuf, o_slotbuf))
03618            return 0;
03619 
03620          return o_insnbuf;
03621        }
03622     }
03623   return 0;
03624 }
03625 
03626 
03627 /* Attempt to narrow an instruction.  If the narrowing is valid, perform
03628    the action in-place directly into the contents and return TRUE.  Otherwise,
03629    the return value is FALSE and the contents are not modified.  */
03630 
03631 static bfd_boolean
03632 narrow_instruction (bfd_byte *contents,
03633                   bfd_size_type content_length,
03634                   bfd_size_type offset)
03635 {
03636   xtensa_opcode opcode;
03637   bfd_size_type insn_len;
03638   xtensa_isa isa = xtensa_default_isa;
03639   xtensa_format fmt;
03640   xtensa_insnbuf o_insnbuf;
03641 
03642   static xtensa_insnbuf insnbuf = NULL;
03643   static xtensa_insnbuf slotbuf = NULL;
03644 
03645   if (insnbuf == NULL)
03646     {
03647       insnbuf = xtensa_insnbuf_alloc (isa);
03648       slotbuf = xtensa_insnbuf_alloc (isa);
03649     }
03650 
03651   BFD_ASSERT (offset < content_length);
03652 
03653   if (content_length < 2)
03654     return FALSE;
03655 
03656   /* We will hand-code a few of these for a little while.
03657      These have all been specified in the assembler aleady.  */
03658   xtensa_insnbuf_from_chars (isa, insnbuf, &contents[offset],
03659                           content_length - offset);
03660   fmt = xtensa_format_decode (isa, insnbuf);
03661   if (xtensa_format_num_slots (isa, fmt) != 1)
03662     return FALSE;
03663 
03664   if (xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf) != 0)
03665     return FALSE;
03666 
03667   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
03668   if (opcode == XTENSA_UNDEFINED)
03669     return FALSE;
03670   insn_len = xtensa_format_length (isa, fmt);
03671   if (insn_len > content_length)
03672     return FALSE;
03673 
03674   o_insnbuf = can_narrow_instruction (slotbuf, fmt, opcode);
03675   if (o_insnbuf)
03676     {
03677       xtensa_insnbuf_to_chars (isa, o_insnbuf, contents + offset,
03678                             content_length - offset);
03679       return TRUE;
03680     }
03681 
03682   return FALSE;
03683 }
03684 
03685 
03686 /* Check if an instruction can be "widened", i.e., changed from a 2-byte
03687    "density" instruction to a standard 3-byte instruction.  If it is valid,
03688    return the instruction buffer holding the wide instruction.  Otherwise,
03689    return 0.  The set of valid widenings are specified by a string table
03690    but require some special case operand checks in some cases.  */
03691 
03692 static xtensa_insnbuf
03693 can_widen_instruction (xtensa_insnbuf slotbuf,
03694                      xtensa_format fmt,
03695                      xtensa_opcode opcode)
03696 {
03697   xtensa_isa isa = xtensa_default_isa;
03698   xtensa_format o_fmt;
03699   unsigned opi;
03700 
03701   static xtensa_insnbuf o_insnbuf = NULL;
03702   static xtensa_insnbuf o_slotbuf = NULL;
03703 
03704   if (o_insnbuf == NULL)
03705     {
03706       o_insnbuf = xtensa_insnbuf_alloc (isa);
03707       o_slotbuf = xtensa_insnbuf_alloc (isa);
03708     }
03709 
03710   for (opi = 0; opi < (sizeof (widenable)/sizeof (struct string_pair)); opi++)
03711     {
03712       bfd_boolean is_or = (strcmp ("or", widenable[opi].wide) == 0);
03713       bfd_boolean is_branch = (strcmp ("beqz", widenable[opi].wide) == 0
03714                             || strcmp ("bnez", widenable[opi].wide) == 0);
03715 
03716       if (opcode == xtensa_opcode_lookup (isa, widenable[opi].narrow))
03717        {
03718          uint32 value, newval;
03719          int i, operand_count, o_operand_count, check_operand_count;
03720          xtensa_opcode o_opcode;
03721 
03722          /* Address does not matter in this case.  We might need to fix it
03723             to handle branches/jumps.  */
03724          bfd_vma self_address = 0;
03725 
03726          o_opcode = xtensa_opcode_lookup (isa, widenable[opi].wide);
03727          if (o_opcode == XTENSA_UNDEFINED)
03728            return 0;
03729          o_fmt = get_single_format (o_opcode);
03730          if (o_fmt == XTENSA_UNDEFINED)
03731            return 0;
03732 
03733          if (xtensa_format_length (isa, fmt) != 2
03734              || xtensa_format_length (isa, o_fmt) != 3)
03735            return 0;
03736 
03737          xtensa_format_encode (isa, o_fmt, o_insnbuf);
03738          operand_count = xtensa_opcode_num_operands (isa, opcode);
03739          o_operand_count = xtensa_opcode_num_operands (isa, o_opcode);
03740          check_operand_count = o_operand_count;
03741 
03742          if (xtensa_opcode_encode (isa, o_fmt, 0, o_slotbuf, o_opcode) != 0)
03743            return 0;
03744 
03745          if (!is_or)
03746            {
03747              if (xtensa_opcode_num_operands (isa, o_opcode) != operand_count)
03748               return 0;
03749            }
03750          else
03751            {
03752              uint32 rawval0, rawval1;
03753 
03754              if (o_operand_count != operand_count + 1
03755                 || xtensa_operand_get_field (isa, opcode, 0,
03756                                           fmt, 0, slotbuf, &rawval0) != 0
03757                 || xtensa_operand_get_field (isa, opcode, 1,
03758                                           fmt, 0, slotbuf, &rawval1) != 0
03759                 || rawval0 == rawval1 /* it is a nop */)
03760               return 0;
03761            }
03762          if (is_branch)
03763            check_operand_count--;
03764 
03765          for (i = 0; i < check_operand_count; i++)
03766            {
03767              int new_i = i;
03768              if (is_or && i == o_operand_count - 1)
03769               new_i = i - 1;
03770              if (xtensa_operand_get_field (isa, opcode, new_i, fmt, 0,
03771                                        slotbuf, &value)
03772                 || xtensa_operand_decode (isa, opcode, new_i, &value))
03773               return 0;
03774 
03775              /* PC-relative branches need adjustment, but
03776                the PC-rel operand will always have a relocation.  */
03777              newval = value;
03778              if (xtensa_operand_do_reloc (isa, o_opcode, i, &newval,
03779                                       self_address)
03780                 || xtensa_operand_encode (isa, o_opcode, i, &newval)
03781                 || xtensa_operand_set_field (isa, o_opcode, i, o_fmt, 0,
03782                                           o_slotbuf, newval))
03783               return 0;
03784            }
03785 
03786          if (xtensa_format_set_slot (isa, o_fmt, 0, o_insnbuf, o_slotbuf))
03787            return 0;
03788 
03789          return o_insnbuf;
03790        }
03791     }
03792   return 0;
03793 }
03794 
03795                      
03796 /* Attempt to widen an instruction.  If the widening is valid, perform
03797    the action in-place directly into the contents and return TRUE.  Otherwise,
03798    the return value is FALSE and the contents are not modified.  */
03799 
03800 static bfd_boolean
03801 widen_instruction (bfd_byte *contents,
03802                  bfd_size_type content_length,
03803                  bfd_size_type offset)
03804 {
03805   xtensa_opcode opcode;
03806   bfd_size_type insn_len;
03807   xtensa_isa isa = xtensa_default_isa;
03808   xtensa_format fmt;
03809   xtensa_insnbuf o_insnbuf;
03810 
03811   static xtensa_insnbuf insnbuf = NULL;
03812   static xtensa_insnbuf slotbuf = NULL;
03813 
03814   if (insnbuf == NULL)
03815     {
03816       insnbuf = xtensa_insnbuf_alloc (isa);
03817       slotbuf = xtensa_insnbuf_alloc (isa);
03818     }
03819 
03820   BFD_ASSERT (offset < content_length);
03821 
03822   if (content_length < 2)
03823     return FALSE;
03824 
03825   /* We will hand-code a few of these for a little while.
03826      These have all been specified in the assembler aleady.  */
03827   xtensa_insnbuf_from_chars (isa, insnbuf, &contents[offset],
03828                           content_length - offset);
03829   fmt = xtensa_format_decode (isa, insnbuf);
03830   if (xtensa_format_num_slots (isa, fmt) != 1)
03831     return FALSE;
03832 
03833   if (xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf) != 0)
03834     return FALSE;
03835 
03836   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
03837   if (opcode == XTENSA_UNDEFINED)
03838     return FALSE;
03839   insn_len = xtensa_format_length (isa, fmt);
03840   if (insn_len > content_length)
03841     return FALSE;
03842 
03843   o_insnbuf = can_widen_instruction (slotbuf, fmt, opcode);
03844   if (o_insnbuf)
03845     {
03846       xtensa_insnbuf_to_chars (isa, o_insnbuf, contents + offset,
03847                             content_length - offset);
03848       return TRUE;
03849     }
03850   return FALSE;
03851 }
03852 
03853 
03854 /* Code for transforming CALLs at link-time.  */
03855 
03856 static bfd_reloc_status_type
03857 elf_xtensa_do_asm_simplify (bfd_byte *contents,
03858                          bfd_vma address,
03859                          bfd_vma content_length,
03860                          char **error_message)
03861 {
03862   static xtensa_insnbuf insnbuf = NULL;
03863   static xtensa_insnbuf slotbuf = NULL;
03864   xtensa_format core_format = XTENSA_UNDEFINED;
03865   xtensa_opcode opcode;
03866   xtensa_opcode direct_call_opcode;
03867   xtensa_isa isa = xtensa_default_isa;
03868   bfd_byte *chbuf = contents + address;
03869   int opn;
03870 
03871   if (insnbuf == NULL)
03872     {
03873       insnbuf = xtensa_insnbuf_alloc (isa);
03874       slotbuf = xtensa_insnbuf_alloc (isa);
03875     }
03876 
03877   if (content_length < address)
03878     {
03879       *error_message = _("Attempt to convert L32R/CALLX to CALL failed");
03880       return bfd_reloc_other;
03881     }
03882 
03883   opcode = get_expanded_call_opcode (chbuf, content_length - address, 0);
03884   direct_call_opcode = swap_callx_for_call_opcode (opcode);
03885   if (direct_call_opcode == XTENSA_UNDEFINED)
03886     {
03887       *error_message = _("Attempt to convert L32R/CALLX to CALL failed");
03888       return bfd_reloc_other;
03889     }
03890   
03891   /* Assemble a NOP ("or a1, a1, a1") into the 0 byte offset.  */
03892   core_format = xtensa_format_lookup (isa, "x24");
03893   opcode = xtensa_opcode_lookup (isa, "or");
03894   xtensa_opcode_encode (isa, core_format, 0, slotbuf, opcode);
03895   for (opn = 0; opn < 3; opn++) 
03896     {
03897       uint32 regno = 1;
03898       xtensa_operand_encode (isa, opcode, opn, &regno);
03899       xtensa_operand_set_field (isa, opcode, opn, core_format, 0,
03900                             slotbuf, regno);
03901     }
03902   xtensa_format_encode (isa, core_format, insnbuf);
03903   xtensa_format_set_slot (isa, core_format, 0, insnbuf, slotbuf);
03904   xtensa_insnbuf_to_chars (isa, insnbuf, chbuf, content_length - address);
03905 
03906   /* Assemble a CALL ("callN 0") into the 3 byte offset.  */
03907   xtensa_opcode_encode (isa, core_format, 0, slotbuf, direct_call_opcode);
03908   xtensa_operand_set_field (isa, opcode, 0, core_format, 0, slotbuf, 0);
03909 
03910   xtensa_format_encode (isa, core_format, insnbuf);
03911   xtensa_format_set_slot (isa, core_format, 0, insnbuf, slotbuf);
03912   xtensa_insnbuf_to_chars (isa, insnbuf, chbuf + 3,
03913                         content_length - address - 3);
03914 
03915   return bfd_reloc_ok;
03916 }
03917 
03918 
03919 static bfd_reloc_status_type
03920 contract_asm_expansion (bfd_byte *contents,
03921                      bfd_vma content_length,
03922                      Elf_Internal_Rela *irel,
03923                      char **error_message)
03924 {
03925   bfd_reloc_status_type retval =
03926     elf_xtensa_do_asm_simplify (contents, irel->r_offset, content_length,
03927                             error_message);
03928 
03929   if (retval != bfd_reloc_ok)
03930     return bfd_reloc_dangerous;
03931 
03932   /* Update the irel->r_offset field so that the right immediate and
03933      the right instruction are modified during the relocation.  */
03934   irel->r_offset += 3;
03935   irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info), R_XTENSA_SLOT0_OP);
03936   return bfd_reloc_ok;
03937 }
03938 
03939 
03940 static xtensa_opcode
03941 swap_callx_for_call_opcode (xtensa_opcode opcode)
03942 {
03943   init_call_opcodes ();
03944 
03945   if (opcode == callx0_op) return call0_op;
03946   if (opcode == callx4_op) return call4_op;
03947   if (opcode == callx8_op) return call8_op;
03948   if (opcode == callx12_op) return call12_op;
03949 
03950   /* Return XTENSA_UNDEFINED if the opcode is not an indirect call.  */
03951   return XTENSA_UNDEFINED;
03952 }
03953 
03954 
03955 /* Check if "buf" is pointing to a "L32R aN; CALLX aN" or "CONST16 aN;
03956    CONST16 aN; CALLX aN" sequence, and if so, return the CALLX opcode.
03957    If not, return XTENSA_UNDEFINED.  */
03958 
03959 #define L32R_TARGET_REG_OPERAND 0
03960 #define CONST16_TARGET_REG_OPERAND 0
03961 #define CALLN_SOURCE_OPERAND 0
03962 
03963 static xtensa_opcode 
03964 get_expanded_call_opcode (bfd_byte *buf, int bufsize, bfd_boolean *p_uses_l32r)
03965 {
03966   static xtensa_insnbuf insnbuf = NULL;
03967   static xtensa_insnbuf slotbuf = NULL;
03968   xtensa_format fmt;
03969   xtensa_opcode opcode;
03970   xtensa_isa isa = xtensa_default_isa;
03971   uint32 regno, const16_regno, call_regno;
03972   int offset = 0;
03973 
03974   if (insnbuf == NULL)
03975     {
03976       insnbuf = xtensa_insnbuf_alloc (isa);
03977       slotbuf = xtensa_insnbuf_alloc (isa);
03978     }
03979 
03980   xtensa_insnbuf_from_chars (isa, insnbuf, buf, bufsize);
03981   fmt = xtensa_format_decode (isa, insnbuf);
03982   if (fmt == XTENSA_UNDEFINED
03983       || xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf))
03984     return XTENSA_UNDEFINED;
03985 
03986   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
03987   if (opcode == XTENSA_UNDEFINED)
03988     return XTENSA_UNDEFINED;
03989 
03990   if (opcode == get_l32r_opcode ())
03991     {
03992       if (p_uses_l32r)
03993        *p_uses_l32r = TRUE;
03994       if (xtensa_operand_get_field (isa, opcode, L32R_TARGET_REG_OPERAND,
03995                                 fmt, 0, slotbuf, &regno)
03996          || xtensa_operand_decode (isa, opcode, L32R_TARGET_REG_OPERAND,
03997                                 &regno))
03998        return XTENSA_UNDEFINED;
03999     }
04000   else if (opcode == get_const16_opcode ())
04001     {
04002       if (p_uses_l32r)
04003        *p_uses_l32r = FALSE;
04004       if (xtensa_operand_get_field (isa, opcode, CONST16_TARGET_REG_OPERAND,
04005                                 fmt, 0, slotbuf, &regno)
04006          || xtensa_operand_decode (isa, opcode, CONST16_TARGET_REG_OPERAND,
04007                                 &regno))
04008        return XTENSA_UNDEFINED;
04009 
04010       /* Check that the next instruction is also CONST16.  */
04011       offset += xtensa_format_length (isa, fmt);
04012       xtensa_insnbuf_from_chars (isa, insnbuf, buf + offset, bufsize - offset);
04013       fmt = xtensa_format_decode (isa, insnbuf);
04014       if (fmt == XTENSA_UNDEFINED
04015          || xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf))
04016        return XTENSA_UNDEFINED;
04017       opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
04018       if (opcode != get_const16_opcode ())
04019        return XTENSA_UNDEFINED;
04020 
04021       if (xtensa_operand_get_field (isa, opcode, CONST16_TARGET_REG_OPERAND,
04022                                 fmt, 0, slotbuf, &const16_regno)
04023          || xtensa_operand_decode (isa, opcode, CONST16_TARGET_REG_OPERAND,
04024                                 &const16_regno)
04025          || const16_regno != regno)
04026        return XTENSA_UNDEFINED;
04027     }
04028   else
04029     return XTENSA_UNDEFINED;
04030 
04031   /* Next instruction should be an CALLXn with operand 0 == regno.  */
04032   offset += xtensa_format_length (isa, fmt);
04033   xtensa_insnbuf_from_chars (isa, insnbuf, buf + offset, bufsize - offset);
04034   fmt = xtensa_format_decode (isa, insnbuf);
04035   if (fmt == XTENSA_UNDEFINED
04036       || xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf))
04037     return XTENSA_UNDEFINED;
04038   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
04039   if (opcode == XTENSA_UNDEFINED 
04040       || !is_indirect_call_opcode (opcode))
04041     return XTENSA_UNDEFINED;
04042 
04043   if (xtensa_operand_get_field (isa, opcode, CALLN_SOURCE_OPERAND,
04044                             fmt, 0, slotbuf, &call_regno)
04045       || xtensa_operand_decode (isa, opcode, CALLN_SOURCE_OPERAND,
04046                             &call_regno))
04047     return XTENSA_UNDEFINED;
04048 
04049   if (call_regno != regno)
04050     return XTENSA_UNDEFINED;
04051 
04052   return opcode;
04053 }
04054 
04055 
04056 /* Data structures used during relaxation.  */
04057 
04058 /* r_reloc: relocation values.  */
04059 
04060 /* Through the relaxation process, we need to keep track of the values
04061    that will result from evaluating relocations.  The standard ELF
04062    relocation structure is not sufficient for this purpose because we're
04063    operating on multiple input files at once, so we need to know which
04064    input file a relocation refers to.  The r_reloc structure thus
04065    records both the input file (bfd) and ELF relocation.
04066 
04067    For efficiency, an r_reloc also contains a "target_offset" field to
04068    cache the target-section-relative offset value that is represented by
04069    the relocation.
04070    
04071    The r_reloc also contains a virtual offset that allows multiple
04072    inserted literals to be placed at the same "address" with
04073    different offsets.  */
04074 
04075 typedef struct r_reloc_struct r_reloc;
04076 
04077 struct r_reloc_struct
04078 {
04079   bfd *abfd;
04080   Elf_Internal_Rela rela;
04081   bfd_vma target_offset;
04082   bfd_vma virtual_offset;
04083 };
04084 
04085 
04086 /* The r_reloc structure is included by value in literal_value, but not
04087    every literal_value has an associated relocation -- some are simple
04088    constants.  In such cases, we set all the fields in the r_reloc
04089    struct to zero.  The r_reloc_is_const function should be used to
04090    detect this case.  */
04091 
04092 static bfd_boolean
04093 r_reloc_is_const (const r_reloc *r_rel)
04094 {
04095   return (r_rel->abfd == NULL);
04096 }
04097 
04098 
04099 static bfd_vma
04100 r_reloc_get_target_offset (const r_reloc *r_rel)
04101 {
04102   bfd_vma target_offset;
04103   unsigned long r_symndx;
04104 
04105   BFD_ASSERT (!r_reloc_is_const (r_rel));
04106   r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
04107   target_offset = get_elf_r_symndx_offset (r_rel->abfd, r_symndx);
04108   return (target_offset + r_rel->rela.r_addend);
04109 }
04110 
04111 
04112 static struct elf_link_hash_entry *
04113 r_reloc_get_hash_entry (const r_reloc *r_rel)
04114 {
04115   unsigned long r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
04116   return get_elf_r_symndx_hash_entry (r_rel->abfd, r_symndx);
04117 }
04118 
04119 
04120 static asection *
04121 r_reloc_get_section (const r_reloc *r_rel)
04122 {
04123   unsigned long r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
04124   return get_elf_r_symndx_section (r_rel->abfd, r_symndx);
04125 }
04126 
04127 
04128 static bfd_boolean
04129 r_reloc_is_defined (const r_reloc *r_rel)
04130 {
04131   asection *sec;
04132   if (r_rel == NULL)
04133     return FALSE;
04134 
04135   sec = r_reloc_get_section (r_rel);
04136   if (sec == bfd_abs_section_ptr
04137       || sec == bfd_com_section_ptr
04138       || sec == bfd_und_section_ptr)
04139     return FALSE;
04140   return TRUE;
04141 }
04142 
04143 
04144 static void
04145 r_reloc_init (r_reloc *r_rel,
04146              bfd *abfd,
04147              Elf_Internal_Rela *irel,
04148              bfd_byte *contents,
04149              bfd_size_type content_length)
04150 {
04151   int r_type;
04152   reloc_howto_type *howto;
04153 
04154   if (irel)
04155     {
04156       r_rel->rela = *irel;
04157       r_rel->abfd = abfd;
04158       r_rel->target_offset = r_reloc_get_target_offset (r_rel);
04159       r_rel->virtual_offset = 0;
04160       r_type = ELF32_R_TYPE (r_rel->rela.r_info);
04161       howto = &elf_howto_table[r_type];
04162       if (howto->partial_inplace)
04163        {
04164          bfd_vma inplace_val;
04165          BFD_ASSERT (r_rel->rela.r_offset < content_length);
04166 
04167          inplace_val = bfd_get_32 (abfd, &contents[r_rel->rela.r_offset]);
04168          r_rel->target_offset += inplace_val;
04169        }
04170     }
04171   else
04172     memset (r_rel, 0, sizeof (r_reloc));
04173 }
04174 
04175 
04176 #if DEBUG
04177 
04178 static void
04179 print_r_reloc (FILE *fp, const r_reloc *r_rel)
04180 {
04181   if (r_reloc_is_defined (r_rel))
04182     {
04183       asection *sec = r_reloc_get_section (r_rel);
04184       fprintf (fp, " %s(%s + ", sec->owner->filename, sec->name);
04185     }
04186   else if (r_reloc_get_hash_entry (r_rel))
04187     fprintf (fp, " %s + ", r_reloc_get_hash_entry (r_rel)->root.root.string);
04188   else
04189     fprintf (fp, " ?? + ");
04190 
04191   fprintf_vma (fp, r_rel->target_offset);
04192   if (r_rel->virtual_offset)
04193     {
04194       fprintf (fp, " + ");
04195       fprintf_vma (fp, r_rel->virtual_offset);
04196     }
04197     
04198   fprintf (fp, ")");
04199 }
04200 
04201 #endif /* DEBUG */
04202 
04203 
04204 /* source_reloc: relocations that reference literals.  */
04205 
04206 /* To determine whether literals can be coalesced, we need to first
04207    record all the relocations that reference the literals.  The
04208    source_reloc structure below is used for this purpose.  The
04209    source_reloc entries are kept in a per-literal-section array, sorted
04210    by offset within the literal section (i.e., target offset).
04211 
04212    The source_sec and r_rel.rela.r_offset fields identify the source of
04213    the relocation.  The r_rel field records the relocation value, i.e.,
04214    the offset of the literal being referenced.  The opnd field is needed
04215    to determine the range of the immediate field to which the relocation
04216    applies, so we can determine whether another literal with the same
04217    value is within range.  The is_null field is true when the relocation
04218    is being removed (e.g., when an L32R is being removed due to a CALLX
04219    that is converted to a direct CALL).  */
04220 
04221 typedef struct source_reloc_struct source_reloc;
04222 
04223 struct source_reloc_struct
04224 {
04225   asection *source_sec;
04226   r_reloc r_rel;
04227   xtensa_opcode opcode;
04228   int opnd;
04229   bfd_boolean is_null;
04230   bfd_boolean is_abs_literal;
04231 };
04232 
04233 
04234 static void
04235 init_source_reloc (source_reloc *reloc,
04236                  asection *source_sec,
04237                  const r_reloc *r_rel,
04238                  xtensa_opcode opcode,
04239                  int opnd,
04240                  bfd_boolean is_abs_literal)
04241 {
04242   reloc->source_sec = source_sec;
04243   reloc->r_rel = *r_rel;
04244   reloc->opcode = opcode;
04245   reloc->opnd = opnd;
04246   reloc->is_null = FALSE;
04247   reloc->is_abs_literal = is_abs_literal;
04248 }
04249 
04250 
04251 /* Find the source_reloc for a particular source offset and relocation
04252    type.  Note that the array is sorted by _target_ offset, so this is
04253    just a linear search.  */
04254 
04255 static source_reloc *
04256 find_source_reloc (source_reloc *src_relocs,
04257                  int src_count,
04258                  asection *sec,
04259                  Elf_Internal_Rela *irel)
04260 {
04261   int i;
04262 
04263   for (i = 0; i < src_count; i++)
04264     {
04265       if (src_relocs[i].source_sec == sec
04266          && src_relocs[i].r_rel.rela.r_offset == irel->r_offset
04267          && (ELF32_R_TYPE (src_relocs[i].r_rel.rela.r_info)
04268              == ELF32_R_TYPE (irel->r_info)))
04269        return &src_relocs[i];
04270     }
04271 
04272   return NULL;
04273 }
04274 
04275 
04276 static int
04277 source_reloc_compare (const void *ap, const void *bp)
04278 {
04279   const source_reloc *a = (const source_reloc *) ap;
04280   const source_reloc *b = (const source_reloc *) bp;
04281 
04282   if (a->r_rel.target_offset != b->r_rel.target_offset)
04283     return (a->r_rel.target_offset - b->r_rel.target_offset);
04284 
04285   /* We don't need to sort on these criteria for correctness,
04286      but enforcing a more strict ordering prevents unstable qsort
04287      from behaving differently with different implementations.
04288      Without the code below we get correct but different results
04289      on Solaris 2.7 and 2.8.  We would like to always produce the
04290      same results no matter the host. */
04291 
04292   if ((!a->is_null) - (!b->is_null))
04293     return ((!a->is_null) - (!b->is_null));
04294   return internal_reloc_compare (&a->r_rel.rela, &b->r_rel.rela);
04295 }
04296 
04297 
04298 /* Literal values and value hash tables.  */
04299 
04300 /* Literals with the same value can be coalesced.  The literal_value
04301    structure records the value of a literal: the "r_rel" field holds the
04302    information from the relocation on the literal (if there is one) and
04303    the "value" field holds the contents of the literal word itself.
04304 
04305    The value_map structure records a literal value along with the
04306    location of a literal holding that value.  The value_map hash table
04307    is indexed by the literal value, so that we can quickly check if a
04308    particular literal value has been seen before and is thus a candidate
04309    for coalescing.  */
04310 
04311 typedef struct literal_value_struct literal_value;
04312 typedef struct value_map_struct value_map;
04313 typedef struct value_map_hash_table_struct value_map_hash_table;
04314 
04315 struct literal_value_struct
04316 {
04317   r_reloc r_rel; 
04318   unsigned long value;
04319   bfd_boolean is_abs_literal;
04320 };
04321 
04322 struct value_map_struct
04323 {
04324   literal_value val;               /* The literal value.  */
04325   r_reloc loc;                            /* Location of the literal.  */
04326   value_map *next;
04327 };
04328 
04329 struct value_map_hash_table_struct
04330 {
04331   unsigned bucket_count;
04332   value_map **buckets;
04333   unsigned count;
04334   bfd_boolean has_last_loc;
04335   r_reloc last_loc;
04336 };
04337 
04338 
04339 static void
04340 init_literal_value (literal_value *lit,
04341                   const r_reloc *r_rel,
04342                   unsigned long value,
04343                   bfd_boolean is_abs_literal)
04344 {
04345   lit->r_rel = *r_rel;
04346   lit->value = value;
04347   lit->is_abs_literal = is_abs_literal;
04348 }
04349 
04350 
04351 static bfd_boolean
04352 literal_value_equal (const literal_value *src1,
04353                    const literal_value *src2,
04354                    bfd_boolean final_static_link)
04355 {
04356   struct elf_link_hash_entry *h1, *h2;
04357 
04358   if (r_reloc_is_const (&src1->r_rel) != r_reloc_is_const (&src2->r_rel)) 
04359     return FALSE;
04360 
04361   if (r_reloc_is_const (&src1->r_rel))
04362     return (src1->value == src2->value);
04363 
04364   if (ELF32_R_TYPE (src1->r_rel.rela.r_info)
04365       != ELF32_R_TYPE (src2->r_rel.rela.r_info))
04366     return FALSE;
04367 
04368   if (src1->r_rel.target_offset != src2->r_rel.target_offset)
04369     return FALSE;
04370    
04371   if (src1->r_rel.virtual_offset != src2->r_rel.virtual_offset)
04372     return FALSE;
04373 
04374   if (src1->value != src2->value)
04375     return FALSE;
04376   
04377   /* Now check for the same section (if defined) or the same elf_hash
04378      (if undefined or weak).  */
04379   h1 = r_reloc_get_hash_entry (&src1->r_rel);
04380   h2 = r_reloc_get_hash_entry (&src2->r_rel);
04381   if (r_reloc_is_defined (&src1->r_rel)
04382       && (final_static_link
04383          || ((!h1 || h1->root.type != bfd_link_hash_defweak)
04384              && (!h2 || h2->root.type != bfd_link_hash_defweak))))
04385     {
04386       if (r_reloc_get_section (&src1->r_rel)
04387          != r_reloc_get_section (&src2->r_rel))
04388        return FALSE;
04389     }
04390   else
04391     {
04392       /* Require that the hash entries (i.e., symbols) be identical.  */
04393       if (h1 != h2 || h1 == 0)
04394        return FALSE;
04395     }
04396 
04397   if (src1->is_abs_literal != src2->is_abs_literal)
04398     return FALSE;
04399 
04400   return TRUE;
04401 }
04402 
04403 
04404 /* Must be power of 2.  */
04405 #define INITIAL_HASH_RELOC_BUCKET_COUNT 1024
04406 
04407 static value_map_hash_table *
04408 value_map_hash_table_init (void)
04409 {
04410   value_map_hash_table *values;
04411 
04412   values = (value_map_hash_table *)
04413     bfd_zmalloc (sizeof (value_map_hash_table));
04414   values->bucket_count = INITIAL_HASH_RELOC_BUCKET_COUNT;
04415   values->count = 0;
04416   values->buckets = (value_map **)
04417     bfd_zmalloc (sizeof (value_map *) * values->bucket_count);
04418   if (values->buckets == NULL) 
04419     {
04420       free (values);
04421       return NULL;
04422     }
04423   values->has_last_loc = FALSE;
04424 
04425   return values;
04426 }
04427 
04428 
04429 static void
04430 value_map_hash_table_delete (value_map_hash_table *table)
04431 {
04432   free (table->buckets);
04433   free (table);
04434 }
04435 
04436 
04437 static unsigned
04438 hash_bfd_vma (bfd_vma val)
04439 {
04440   return (val >> 2) + (val >> 10);
04441 }
04442 
04443 
04444 static unsigned
04445 literal_value_hash (const literal_value *src)
04446 {
04447   unsigned hash_val;
04448 
04449   hash_val = hash_bfd_vma (src->value);
04450   if (!r_reloc_is_const (&src->r_rel))
04451     {
04452       void *sec_or_hash;
04453 
04454       hash_val += hash_bfd_vma (src->is_abs_literal * 1000);
04455       hash_val += hash_bfd_vma (src->r_rel.target_offset);
04456       hash_val += hash_bfd_vma (src->r_rel.virtual_offset);
04457   
04458       /* Now check for the same section and the same elf_hash.  */
04459       if (r_reloc_is_defined (&src->r_rel))
04460        sec_or_hash = r_reloc_get_section (&src->r_rel);
04461       else
04462        sec_or_hash = r_reloc_get_hash_entry (&src->r_rel);
04463       hash_val += hash_bfd_vma ((bfd_vma) (size_t) sec_or_hash);
04464     }
04465   return hash_val;
04466 }
04467 
04468 
04469 /* Check if the specified literal_value has been seen before.  */
04470 
04471 static value_map *
04472 value_map_get_cached_value (value_map_hash_table *map,
04473                          const literal_value *val,
04474                          bfd_boolean final_static_link)
04475 {
04476   value_map *map_e;
04477   value_map *bucket;
04478   unsigned idx;
04479 
04480   idx = literal_value_hash (val);
04481   idx = idx & (map->bucket_count - 1);
04482   bucket = map->buckets[idx];
04483   for (map_e = bucket; map_e; map_e = map_e->next)
04484     {
04485       if (literal_value_equal (&map_e->val, val, final_static_link))
04486        return map_e;
04487     }
04488   return NULL;
04489 }
04490 
04491 
04492 /* Record a new literal value.  It is illegal to call this if VALUE
04493    already has an entry here.  */
04494 
04495 static value_map *
04496 add_value_map (value_map_hash_table *map,
04497               const literal_value *val,
04498               const r_reloc *loc,
04499               bfd_boolean final_static_link)
04500 {
04501   value_map **bucket_p;
04502   unsigned idx;
04503 
04504   value_map *val_e = (value_map *) bfd_zmalloc (sizeof (value_map));
04505   if (val_e == NULL)
04506     {
04507       bfd_set_error (bfd_error_no_memory);
04508       return NULL;
04509     }
04510 
04511   BFD_ASSERT (!value_map_get_cached_value (map, val, final_static_link));
04512   val_e->val = *val;
04513   val_e->loc = *loc;
04514 
04515   idx = literal_value_hash (val);
04516   idx = idx & (map->bucket_count - 1);
04517   bucket_p = &map->buckets[idx];
04518 
04519   val_e->next = *bucket_p;
04520   *bucket_p = val_e;
04521   map->count++;
04522   /* FIXME: Consider resizing the hash table if we get too many entries.  */
04523   
04524   return val_e;
04525 }
04526 
04527 
04528 /* Lists of text actions (ta_) for narrowing, widening, longcall
04529    conversion, space fill, code & literal removal, etc.  */
04530 
04531 /* The following text actions are generated:
04532 
04533    "ta_remove_insn"         remove an instruction or instructions
04534    "ta_remove_longcall"     convert longcall to call
04535    "ta_convert_longcall"    convert longcall to nop/call
04536    "ta_narrow_insn"         narrow a wide instruction
04537    "ta_widen"               widen a narrow instruction
04538    "ta_fill"                add fill or remove fill
04539       removed < 0 is a fill; branches to the fill address will be
04540        changed to address + fill size (e.g., address - removed)
04541       removed >= 0 branches to the fill address will stay unchanged
04542    "ta_remove_literal"      remove a literal; this action is
04543                          indicated when a literal is removed
04544                             or replaced.
04545    "ta_add_literal"         insert a new literal; this action is
04546                             indicated when a literal has been moved.
04547                             It may use a virtual_offset because
04548                          multiple literals can be placed at the
04549                             same location.
04550 
04551    For each of these text actions, we also record the number of bytes
04552    removed by performing the text action.  In the case of a "ta_widen"
04553    or a "ta_fill" that adds space, the removed_bytes will be negative.  */
04554 
04555 typedef struct text_action_struct text_action;
04556 typedef struct text_action_list_struct text_action_list;
04557 typedef enum text_action_enum_t text_action_t;
04558 
04559 enum text_action_enum_t
04560 {
04561   ta_none,
04562   ta_remove_insn,        /* removed = -size */
04563   ta_remove_longcall,    /* removed = -size */
04564   ta_convert_longcall,   /* removed = 0 */
04565   ta_narrow_insn,        /* removed = -1 */
04566   ta_widen_insn,         /* removed = +1 */
04567   ta_fill,               /* removed = +size */
04568   ta_remove_literal,
04569   ta_add_literal
04570 };
04571 
04572 
04573 /* Structure for a text action record.  */
04574 struct text_action_struct
04575 {
04576   text_action_t action;
04577   asection *sec;     /* Optional */
04578   bfd_vma offset;
04579   bfd_vma virtual_offset;  /* Zero except for adding literals.  */
04580   int removed_bytes;
04581   literal_value value;      /* Only valid when adding literals.  */
04582 
04583   text_action *next;
04584 };
04585 
04586 
04587 /* List of all of the actions taken on a text section.  */
04588 struct text_action_list_struct
04589 {
04590   text_action *head;
04591 };
04592 
04593 
04594 static text_action *
04595 find_fill_action (text_action_list *l, asection *sec, bfd_vma offset)
04596 {
04597   text_action **m_p;
04598 
04599   /* It is not necessary to fill at the end of a section.  */
04600   if (sec->size == offset)
04601     return NULL;
04602 
04603   for (m_p = &l->head; *m_p && (*m_p)->offset <= offset; m_p = &(*m_p)->next)
04604     {
04605       text_action *t = *m_p;
04606       /* When the action is another fill at the same address,
04607         just increase the size.  */
04608       if (t->offset == offset && t->action == ta_fill)
04609        return t;
04610     }
04611   return NULL;
04612 }
04613 
04614 
04615 static int
04616 compute_removed_action_diff (const text_action *ta,
04617                           asection *sec,
04618                           bfd_vma offset,
04619                           int removed,
04620                           int removable_space)
04621 {
04622   int new_removed;
04623   int current_removed = 0;
04624 
04625   if (ta)
04626     current_removed = ta->removed_bytes;
04627 
04628   BFD_ASSERT (ta == NULL || ta->offset == offset);
04629   BFD_ASSERT (ta == NULL || ta->action == ta_fill);
04630 
04631   /* It is not necessary to fill at the end of a section.  Clean this up.  */
04632   if (sec->size == offset)
04633     new_removed = removable_space - 0;
04634   else
04635     {
04636       int space;
04637       int added = -removed - current_removed;
04638       /* Ignore multiples of the section alignment.  */
04639       added = ((1 << sec->alignment_power) - 1) & added;
04640       new_removed = (-added);
04641 
04642       /* Modify for removable.  */
04643       space = removable_space - new_removed;
04644       new_removed = (removable_space
04645                    - (((1 << sec->alignment_power) - 1) & space));
04646     }
04647   return (new_removed - current_removed);
04648 }
04649 
04650 
04651 static void
04652 adjust_fill_action (text_action *ta, int fill_diff)
04653 {
04654   ta->removed_bytes += fill_diff;
04655 }
04656 
04657 
04658 /* Add a modification action to the text.  For the case of adding or
04659    removing space, modify any current fill and assume that
04660    "unreachable_space" bytes can be freely contracted.  Note that a
04661    negative removed value is a fill.  */
04662 
04663 static void 
04664 text_action_add (text_action_list *l,
04665                text_action_t action,
04666                asection *sec,
04667                bfd_vma offset,
04668                int removed)
04669 {
04670   text_action **m_p;
04671   text_action *ta;
04672 
04673   /* It is not necessary to fill at the end of a section.  */
04674   if (action == ta_fill && sec->size == offset)
04675     return;
04676 
04677   /* It is not necessary to fill 0 bytes.  */
04678   if (action == ta_fill && removed == 0)
04679     return;
04680 
04681   for (m_p = &l->head; *m_p && (*m_p)->offset <= offset; m_p = &(*m_p)->next)
04682     {
04683       text_action *t = *m_p;
04684       /* When the action is another fill at the same address,
04685         just increase the size.  */
04686       if (t->offset == offset && t->action == ta_fill && action == ta_fill)
04687        {
04688          t->removed_bytes += removed;
04689          return;
04690        }
04691     }
04692 
04693   /* Create a new record and fill it up.  */
04694   ta = (text_action *) bfd_zmalloc (sizeof (text_action));
04695   ta->action = action;
04696   ta->sec = sec;
04697   ta->offset = offset;
04698   ta->removed_bytes = removed;
04699   ta->next = (*m_p);
04700   *m_p = ta;
04701 }
04702 
04703 
04704 static void
04705 text_action_add_literal (text_action_list *l,
04706                       text_action_t action,
04707                       const r_reloc *loc,
04708                       const literal_value *value,
04709                       int removed)
04710 {
04711   text_action **m_p;
04712   text_action *ta;
04713   asection *sec = r_reloc_get_section (loc);
04714   bfd_vma offset = loc->target_offset;
04715   bfd_vma virtual_offset = loc->virtual_offset;
04716 
04717   BFD_ASSERT (action == ta_add_literal);
04718 
04719   for (m_p = &l->head; *m_p != NULL; m_p = &(*m_p)->next)
04720     {
04721       if ((*m_p)->offset > offset
04722          && ((*m_p)->offset != offset
04723              || (*m_p)->virtual_offset > virtual_offset))
04724        break;
04725     }
04726 
04727   /* Create a new record and fill it up.  */
04728   ta = (text_action *) bfd_zmalloc (sizeof (text_action));
04729   ta->action = action;
04730   ta->sec = sec;
04731   ta->offset = offset;
04732   ta->virtual_offset = virtual_offset;
04733   ta->value = *value;
04734   ta->removed_bytes = removed;
04735   ta->next = (*m_p);
04736   *m_p = ta;
04737 }
04738 
04739 
04740 static bfd_vma 
04741 offset_with_removed_text (text_action_list *action_list, bfd_vma offset)
04742 {
04743   text_action *r;
04744   int removed = 0;
04745 
04746   for (r = action_list->head; r && r->offset <= offset; r = r->next)
04747     {
04748       if (r->offset < offset
04749          || (r->action == ta_fill && r->removed_bytes < 0))
04750        removed += r->removed_bytes;
04751     }
04752 
04753   return (offset - removed);
04754 }
04755 
04756 
04757 static unsigned
04758 action_list_count (text_action_list *action_list)
04759 {
04760   text_action *r = action_list->head;
04761   unsigned count = 0;
04762   for (r = action_list->head; r != NULL; r = r->next)
04763     {
04764       count++;
04765     }
04766   return count;
04767 }
04768 
04769 
04770 static bfd_vma
04771 offset_with_removed_text_before_fill (text_action_list *action_list,
04772                                   bfd_vma offset)
04773 {
04774   text_action *r;
04775   int removed = 0;
04776 
04777   for (r = action_list->head; r && r->offset < offset; r = r->next)
04778     removed += r->removed_bytes;
04779 
04780   return (offset - removed);
04781 }
04782 
04783 
04784 /* The find_insn_action routine will only find non-fill actions.  */
04785 
04786 static text_action *
04787 find_insn_action (text_action_list *action_list, bfd_vma offset)
04788 {
04789   text_action *t;
04790   for (t = action_list->head; t; t = t->next)
04791     {
04792       if (t->offset == offset)
04793        {
04794          switch (t->action)
04795            {
04796            case ta_none:
04797            case ta_fill:
04798              break;
04799            case ta_remove_insn:
04800            case ta_remove_longcall:
04801            case ta_convert_longcall:
04802            case ta_narrow_insn:
04803            case ta_widen_insn:
04804              return t;
04805            case ta_remove_literal:
04806            case ta_add_literal:
04807              BFD_ASSERT (0);
04808              break;
04809            }
04810        }
04811     }
04812   return NULL;
04813 }
04814 
04815 
04816 #if DEBUG
04817 
04818 static void
04819 print_action_list (FILE *fp, text_action_list *action_list)
04820 {
04821   text_action *r;
04822 
04823   fprintf (fp, "Text Action\n");
04824   for (r = action_list->head; r != NULL; r = r->next)
04825     {
04826       const char *t = "unknown";
04827       switch (r->action)
04828        {
04829        case ta_remove_insn:
04830          t = "remove_insn"; break;
04831        case ta_remove_longcall:
04832          t = "remove_longcall"; break;
04833        case ta_convert_longcall:
04834          t = "remove_longcall"; break;
04835        case ta_narrow_insn:
04836          t = "narrow_insn"; break;
04837        case ta_widen_insn:
04838          t = "widen_insn"; break;
04839        case ta_fill:
04840          t = "fill"; break;
04841        case ta_none:
04842          t = "none"; break;
04843        case ta_remove_literal:
04844          t = "remove_literal"; break;
04845        case ta_add_literal:
04846          t = "add_literal"; break;
04847        }
04848 
04849       fprintf (fp, "%s: %s[0x%lx] \"%s\" %d\n",
04850               r->sec->owner->filename,
04851               r->sec->name, r->offset, t, r->removed_bytes);
04852     }
04853 }
04854 
04855 #endif /* DEBUG */
04856 
04857 
04858 /* Lists of literals being coalesced or removed.  */
04859 
04860 /* In the usual case, the literal identified by "from" is being
04861    coalesced with another literal identified by "to".  If the literal is
04862    unused and is being removed altogether, "to.abfd" will be NULL.
04863    The removed_literal entries are kept on a per-section list, sorted
04864    by the "from" offset field.  */
04865 
04866 typedef struct removed_literal_struct removed_literal;
04867 typedef struct removed_literal_list_struct removed_literal_list;
04868 
04869 struct removed_literal_struct
04870 {
04871   r_reloc from;
04872   r_reloc to;
04873   removed_literal *next;
04874 };
04875 
04876 struct removed_literal_list_struct
04877 {
04878   removed_literal *head;
04879   removed_literal *tail;
04880 };
04881 
04882 
04883 /* Record that the literal at "from" is being removed.  If "to" is not
04884    NULL, the "from" literal is being coalesced with the "to" literal.  */
04885 
04886 static void
04887 add_removed_literal (removed_literal_list *removed_list,
04888                    const r_reloc *from,
04889                    const r_reloc *to)
04890 {
04891   removed_literal *r, *new_r, *next_r;
04892 
04893   new_r = (removed_literal *) bfd_zmalloc (sizeof (removed_literal));
04894 
04895   new_r->from = *from;
04896   if (to)
04897     new_r->to = *to;
04898   else
04899     new_r->to.abfd = NULL;
04900   new_r->next = NULL;
04901   
04902   r = removed_list->head;
04903   if (r == NULL) 
04904     {
04905       removed_list->head = new_r;
04906       removed_list->tail = new_r;
04907     }
04908   /* Special check for common case of append.  */
04909   else if (removed_list->tail->from.target_offset < from->target_offset)
04910     {
04911       removed_list->tail->next = new_r;
04912       removed_list->tail = new_r;
04913     }
04914   else
04915     {
04916       while (r->from.target_offset < from->target_offset && r->next) 
04917        {
04918          r = r->next;
04919        }
04920       next_r = r->next;
04921       r->next = new_r;
04922       new_r->next = next_r;
04923       if (next_r == NULL)
04924        removed_list->tail = new_r;
04925     }
04926 }
04927 
04928 
04929 /* Check if the list of removed literals contains an entry for the
04930    given address.  Return the entry if found.  */
04931 
04932 static removed_literal *
04933 find_removed_literal (removed_literal_list *removed_list, bfd_vma addr)
04934 {
04935   removed_literal *r = removed_list->head;
04936   while (r && r->from.target_offset < addr)
04937     r = r->next;
04938   if (r && r->from.target_offset == addr)
04939     return r;
04940   return NULL;
04941 }
04942 
04943 
04944 #if DEBUG
04945 
04946 static void
04947 print_removed_literals (FILE *fp, removed_literal_list *removed_list)
04948 {
04949   removed_literal *r;
04950   r = removed_list->head;
04951   if (r)
04952     fprintf (fp, "Removed Literals\n");
04953   for (; r != NULL; r = r->next)
04954     {
04955       print_r_reloc (fp, &r->from);
04956       fprintf (fp, " => ");
04957       if (r->to.abfd == NULL)
04958        fprintf (fp, "REMOVED");
04959       else
04960        print_r_reloc (fp, &r->to);
04961       fprintf (fp, "\n");
04962     }
04963 }
04964 
04965 #endif /* DEBUG */
04966 
04967 
04968 /* Per-section data for relaxation.  */
04969 
04970 typedef struct reloc_bfd_fix_struct reloc_bfd_fix;
04971 
04972 struct xtensa_relax_info_struct
04973 {
04974   bfd_boolean is_relaxable_literal_section;
04975   bfd_boolean is_relaxable_asm_section;
04976   int visited;                            /* Number of times visited.  */
04977 
04978   source_reloc *src_relocs;        /* Array[src_count].  */
04979   int src_count;
04980   int src_next;                           /* Next src_relocs entry to assign.  */
04981 
04982   removed_literal_list removed_list;
04983   text_action_list action_list;
04984 
04985   reloc_bfd_fix *fix_list;
04986   reloc_bfd_fix *fix_array;
04987   unsigned fix_array_count;
04988 
04989   /* Support for expanding the reloc array that is stored
04990      in the section structure.  If the relocations have been
04991      reallocated, the newly allocated relocations will be referenced
04992      here along with the actual size allocated.  The relocation
04993      count will always be found in the section structure.  */
04994   Elf_Internal_Rela *allocated_relocs; 
04995   unsigned relocs_count;
04996   unsigned allocated_relocs_count;
04997 };
04998 
04999 struct elf_xtensa_section_data
05000 {
05001   struct bfd_elf_section_data elf;
05002   xtensa_relax_info relax_info;
05003 };
05004 
05005 
05006 static bfd_boolean
05007 elf_xtensa_new_section_hook (bfd *abfd, asection *sec)
05008 {
05009   if (!sec->used_by_bfd)
05010     {
05011       struct elf_xtensa_section_data *sdata;
05012       bfd_size_type amt = sizeof (*sdata);
05013 
05014       sdata = bfd_zalloc (abfd, amt);
05015       if (sdata == NULL)
05016        return FALSE;
05017       sec->used_by_bfd = sdata;
05018     }
05019 
05020   return _bfd_elf_new_section_hook (abfd, sec);
05021 }
05022 
05023 
05024 static xtensa_relax_info *
05025 get_xtensa_relax_info (asection *sec)
05026 {
05027   struct elf_xtensa_section_data *section_data;
05028 
05029   /* No info available if no section or if it is an output section.  */
05030   if (!sec || sec == sec->output_section)
05031     return NULL;
05032 
05033   section_data = (struct elf_xtensa_section_data *) elf_section_data (sec);
05034   return &section_data->relax_info;
05035 }
05036 
05037 
05038 static void
05039 init_xtensa_relax_info (asection *sec)
05040 {
05041   xtensa_relax_info *relax_info = get_xtensa_relax_info (sec);
05042 
05043   relax_info->is_relaxable_literal_section = FALSE;
05044   relax_info->is_relaxable_asm_section = FALSE;
05045   relax_info->visited = 0;
05046 
05047   relax_info->src_relocs = NULL;
05048   relax_info->src_count = 0;
05049   relax_info->src_next = 0;
05050 
05051   relax_info->removed_list.head = NULL;
05052   relax_info->removed_list.tail = NULL;
05053 
05054   relax_info->action_list.head = NULL;
05055 
05056   relax_info->fix_list = NULL;
05057   relax_info->fix_array = NULL;
05058   relax_info->fix_array_count = 0;
05059 
05060   relax_info->allocated_relocs = NULL; 
05061   relax_info->relocs_count = 0;
05062   relax_info->allocated_relocs_count = 0;
05063 }
05064 
05065 
05066 /* Coalescing literals may require a relocation to refer to a section in
05067    a different input file, but the standard relocation information
05068    cannot express that.  Instead, the reloc_bfd_fix structures are used
05069    to "fix" the relocations that refer to sections in other input files.
05070    These structures are kept on per-section lists.  The "src_type" field
05071    records the relocation type in case there are multiple relocations on
05072    the same location.  FIXME: This is ugly; an alternative might be to
05073    add new symbols with the "owner" field to some other input file.  */
05074 
05075 struct reloc_bfd_fix_struct
05076 {
05077   asection *src_sec;
05078   bfd_vma src_offset;
05079   unsigned src_type;               /* Relocation type.  */
05080   
05081   bfd *target_abfd;
05082   asection *target_sec;
05083   bfd_vma target_offset;
05084   bfd_boolean translated;
05085   
05086   reloc_bfd_fix *next;
05087 };
05088 
05089 
05090 static reloc_bfd_fix *
05091 reloc_bfd_fix_init (asection *src_sec,
05092                   bfd_vma src_offset,
05093                   unsigned src_type,
05094                   bfd *target_abfd,
05095                   asection *target_sec,
05096                   bfd_vma target_offset,
05097                   bfd_boolean translated)
05098 {
05099   reloc_bfd_fix *fix;
05100 
05101   fix = (reloc_bfd_fix *) bfd_malloc (sizeof (reloc_bfd_fix));
05102   fix->src_sec = src_sec;
05103   fix->src_offset = src_offset;
05104   fix->src_type = src_type;
05105   fix->target_abfd = target_abfd;
05106   fix->target_sec = target_sec;
05107   fix->target_offset = target_offset;
05108   fix->translated = translated;
05109 
05110   return fix;
05111 }
05112 
05113 
05114 static void
05115 add_fix (asection *src_sec, reloc_bfd_fix *fix)
05116 {
05117   xtensa_relax_info *relax_info;
05118 
05119   relax_info = get_xtensa_relax_info (src_sec);
05120   fix->next = relax_info->fix_list;
05121   relax_info->fix_list = fix;
05122 }
05123 
05124 
05125 static int
05126 fix_compare (const void *ap, const void *bp)
05127 {
05128   const reloc_bfd_fix *a = (const reloc_bfd_fix *) ap;
05129   const reloc_bfd_fix *b = (const reloc_bfd_fix *) bp;
05130 
05131   if (a->src_offset != b->src_offset)
05132     return (a->src_offset - b->src_offset);
05133   return (a->src_type - b->src_type);
05134 }
05135 
05136 
05137 static void
05138 cache_fix_array (asection *sec)
05139 {
05140   unsigned i, count = 0;
05141   reloc_bfd_fix *r;
05142   xtensa_relax_info *relax_info = get_xtensa_relax_info (sec);
05143 
05144   if (relax_info == NULL)
05145     return;
05146   if (relax_info->fix_list == NULL)
05147     return;
05148 
05149   for (r = relax_info->fix_list; r != NULL; r = r->next)
05150     count++;
05151 
05152   relax_info->fix_array =
05153     (reloc_bfd_fix *) bfd_malloc (sizeof (reloc_bfd_fix) * count);
05154   relax_info->fix_array_count = count;
05155 
05156   r = relax_info->fix_list;
05157   for (i = 0; i < count; i++, r = r->next)
05158     {
05159       relax_info->fix_array[count - 1 - i] = *r;
05160       relax_info->fix_array[count - 1 - i].next = NULL;
05161     }
05162 
05163   qsort (relax_info->fix_array, relax_info->fix_array_count,
05164         sizeof (reloc_bfd_fix), fix_compare);
05165 }
05166 
05167 
05168 static reloc_bfd_fix *
05169 get_bfd_fix (asection *sec, bfd_vma offset, unsigned type)
05170 {
05171   xtensa_relax_info *relax_info = get_xtensa_relax_info (sec);
05172   reloc_bfd_fix *rv;
05173   reloc_bfd_fix key;
05174 
05175   if (relax_info == NULL)
05176     return NULL;
05177   if (relax_info->fix_list == NULL)
05178     return NULL;
05179 
05180   if (relax_info->fix_array == NULL)
05181     cache_fix_array (sec);
05182 
05183   key.src_offset = offset;
05184   key.src_type = type;
05185   rv = bsearch (&key, relax_info->fix_array,  relax_info->fix_array_count,
05186               sizeof (reloc_bfd_fix), fix_compare);
05187   return rv;
05188 }
05189 
05190 
05191 /* Section caching.  */
05192 
05193 typedef struct section_cache_struct section_cache_t;
05194 
05195 struct section_cache_struct
05196 {
05197   asection *sec;
05198 
05199   bfd_byte *contents;              /* Cache of the section contents.  */
05200   bfd_size_type content_length;
05201 
05202   property_table_entry *ptbl;      /* Cache of the section property table.  */
05203   unsigned pte_count;
05204 
05205   Elf_Internal_Rela *relocs;       /* Cache of the section relocations.  */
05206   unsigned reloc_count;
05207 };
05208 
05209 
05210 static void
05211 init_section_cache (section_cache_t *sec_cache)
05212 {
05213   memset (sec_cache, 0, sizeof (*sec_cache));
05214 }
05215 
05216 
05217 static void
05218 clear_section_cache (section_cache_t *sec_cache)
05219 {
05220   if (sec_cache->sec)
05221     {
05222       release_contents (sec_cache->sec, sec_cache->contents);
05223       release_internal_relocs (sec_cache->sec, sec_cache->relocs);
05224       if (sec_cache->ptbl)
05225        free (sec_cache->ptbl);
05226       memset (sec_cache, 0, sizeof (sec_cache));
05227     }
05228 }
05229 
05230 
05231 static bfd_boolean
05232 section_cache_section (section_cache_t *sec_cache,
05233                      asection *sec,
05234                      struct bfd_link_info *link_info)
05235 {
05236   bfd *abfd;
05237   property_table_entry *prop_table = NULL;
05238   int ptblsize = 0;
05239   bfd_byte *contents = NULL;
05240   Elf_Internal_Rela *internal_relocs = NULL;
05241   bfd_size_type sec_size;
05242 
05243   if (sec == NULL)
05244     return FALSE;
05245   if (sec == sec_cache->sec)
05246     return TRUE;
05247 
05248   abfd = sec->owner;
05249   sec_size = bfd_get_section_limit (abfd, sec);
05250 
05251   /* Get the contents.  */
05252   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
05253   if (contents == NULL && sec_size != 0)
05254     goto err;
05255 
05256   /* Get the relocations.  */
05257   internal_relocs = retrieve_internal_relocs (abfd, sec,
05258                                          link_info->keep_memory);
05259 
05260   /* Get the entry table.  */
05261   ptblsize = xtensa_read_table_entries (abfd, sec, &prop_table,
05262                                    XTENSA_PROP_SEC_NAME, FALSE);
05263   if (ptblsize < 0)
05264     goto err;
05265 
05266   /* Fill in the new section cache.  */
05267   clear_section_cache (sec_cache);
05268   memset (sec_cache, 0, sizeof (sec_cache));
05269 
05270   sec_cache->sec = sec;
05271   sec_cache->contents = contents;
05272   sec_cache->content_length = sec_size;
05273   sec_cache->relocs = internal_relocs;
05274   sec_cache->reloc_count = sec->reloc_count;
05275   sec_cache->pte_count = ptblsize;
05276   sec_cache->ptbl = prop_table;
05277 
05278   return TRUE;
05279 
05280  err:
05281   release_contents (sec, contents);
05282   release_internal_relocs (sec, internal_relocs);
05283   if (prop_table)
05284     free (prop_table);
05285   return FALSE;
05286 }
05287 
05288 
05289 /* Extended basic blocks.  */
05290 
05291 /* An ebb_struct represents an Extended Basic Block.  Within this
05292    range, we guarantee that all instructions are decodable, the
05293    property table entries are contiguous, and no property table
05294    specifies a segment that cannot have instructions moved.  This
05295    structure contains caches of the contents, property table and
05296    relocations for the specified section for easy use.  The range is
05297    specified by ranges of indices for the byte offset, property table
05298    offsets and relocation offsets.  These must be consistent.  */
05299 
05300 typedef struct ebb_struct ebb_t;
05301 
05302 struct ebb_struct
05303 {
05304   asection *sec;
05305 
05306   bfd_byte *contents;              /* Cache of the section contents.  */
05307   bfd_size_type content_length;
05308 
05309   property_table_entry *ptbl;      /* Cache of the section property table.  */
05310   unsigned pte_count;
05311 
05312   Elf_Internal_Rela *relocs;       /* Cache of the section relocations.  */
05313   unsigned reloc_count;
05314 
05315   bfd_vma start_offset;            /* Offset in section.  */
05316   unsigned start_ptbl_idx;  /* Offset in the property table.  */
05317   unsigned start_reloc_idx; /* Offset in the relocations.  */
05318 
05319   bfd_vma end_offset;
05320   unsigned end_ptbl_idx;
05321   unsigned end_reloc_idx;
05322 
05323   bfd_boolean ends_section; /* Is this the last ebb in a section?  */
05324 
05325   /* The unreachable property table at the end of this set of blocks;
05326      NULL if the end is not an unreachable block.  */
05327   property_table_entry *ends_unreachable;
05328 };
05329 
05330 
05331 enum ebb_target_enum
05332 {
05333   EBB_NO_ALIGN = 0,
05334   EBB_DESIRE_TGT_ALIGN,
05335   EBB_REQUIRE_TGT_ALIGN,
05336   EBB_REQUIRE_LOOP_ALIGN,
05337   EBB_REQUIRE_ALIGN
05338 };
05339 
05340 
05341 /* proposed_action_struct is similar to the text_action_struct except
05342    that is represents a potential transformation, not one that will
05343    occur.  We build a list of these for an extended basic block
05344    and use them to compute the actual actions desired.  We must be
05345    careful that the entire set of actual actions we perform do not
05346    break any relocations that would fit if the actions were not
05347    performed.  */
05348 
05349 typedef struct proposed_action_struct proposed_action;
05350 
05351 struct proposed_action_struct
05352 {
05353   enum ebb_target_enum align_type; /* for the target alignment */
05354   bfd_vma alignment_pow;
05355   text_action_t action;
05356   bfd_vma offset;
05357   int removed_bytes;
05358   bfd_boolean do_action; /* If false, then we will not perform the action.  */
05359 };
05360 
05361 
05362 /* The ebb_constraint_struct keeps a set of proposed actions for an
05363    extended basic block.   */
05364 
05365 typedef struct ebb_constraint_struct ebb_constraint;
05366 
05367 struct ebb_constraint_struct
05368 {
05369   ebb_t ebb;
05370   bfd_boolean start_movable;
05371 
05372   /* Bytes of extra space at the beginning if movable.  */
05373   int start_extra_space;
05374 
05375   enum ebb_target_enum start_align;
05376 
05377   bfd_boolean end_movable;
05378 
05379   /* Bytes of extra space at the end if movable.  */
05380   int end_extra_space;
05381 
05382   unsigned action_count;
05383   unsigned action_allocated;
05384 
05385   /* Array of proposed actions.  */
05386   proposed_action *actions;
05387 
05388   /* Action alignments -- one for each proposed action.  */
05389   enum ebb_target_enum *action_aligns;
05390 };
05391 
05392 
05393 static void
05394 init_ebb_constraint (ebb_constraint *c)
05395 {
05396   memset (c, 0, sizeof (ebb_constraint));
05397 }
05398 
05399 
05400 static void
05401 free_ebb_constraint (ebb_constraint *c)
05402 {
05403   if (c->actions)
05404     free (c->actions);
05405 }
05406 
05407 
05408 static void
05409 init_ebb (ebb_t *ebb,
05410          asection *sec,
05411          bfd_byte *contents,
05412          bfd_size_type content_length,
05413          property_table_entry *prop_table,
05414          unsigned ptblsize,
05415          Elf_Internal_Rela *internal_relocs,
05416          unsigned reloc_count)
05417 {
05418   memset (ebb, 0, sizeof (ebb_t));
05419   ebb->sec = sec;
05420   ebb->contents = contents;
05421   ebb->content_length = content_length;
05422   ebb->ptbl = prop_table;
05423   ebb->pte_count = ptblsize;
05424   ebb->relocs = internal_relocs;
05425   ebb->reloc_count = reloc_count;
05426   ebb->start_offset = 0;
05427   ebb->end_offset = ebb->content_length - 1;
05428   ebb->start_ptbl_idx = 0;
05429   ebb->end_ptbl_idx = ptblsize;
05430   ebb->start_reloc_idx = 0;
05431   ebb->end_reloc_idx = reloc_count;
05432 }
05433 
05434 
05435 /* Extend the ebb to all decodable contiguous sections.  The algorithm
05436    for building a basic block around an instruction is to push it
05437    forward until we hit the end of a section, an unreachable block or
05438    a block that cannot be transformed.  Then we push it backwards
05439    searching for similar conditions.  */
05440 
05441 static bfd_boolean extend_ebb_bounds_forward (ebb_t *);
05442 static bfd_boolean extend_ebb_bounds_backward (ebb_t *);
05443 static bfd_size_type insn_block_decodable_len
05444   (bfd_byte *, bfd_size_type, bfd_vma, bfd_size_type);
05445 
05446 static bfd_boolean
05447 extend_ebb_bounds (ebb_t *ebb)
05448 {
05449   if (!extend_ebb_bounds_forward (ebb))
05450     return FALSE;
05451   if (!extend_ebb_bounds_backward (ebb))
05452     return FALSE;
05453   return TRUE;
05454 }
05455 
05456 
05457 static bfd_boolean
05458 extend_ebb_bounds_forward (ebb_t *ebb)
05459 {
05460   property_table_entry *the_entry, *new_entry;
05461 
05462   the_entry = &ebb->ptbl[ebb->end_ptbl_idx];
05463 
05464   /* Stop when (1) we cannot decode an instruction, (2) we are at
05465      the end of the property tables, (3) we hit a non-contiguous property
05466      table entry, (4) we hit a NO_TRANSFORM region.  */
05467 
05468   while (1)
05469     {
05470       bfd_vma entry_end;
05471       bfd_size_type insn_block_len;
05472 
05473       entry_end = the_entry->address - ebb->sec->vma + the_entry->size;
05474       insn_block_len =
05475        insn_block_decodable_len (ebb->contents, ebb->content_length,
05476                               ebb->end_offset,
05477                               entry_end - ebb->end_offset);
05478       if (insn_block_len != (entry_end - ebb->end_offset))
05479        {
05480          (*_bfd_error_handler)
05481            (_("%B(%A+0x%lx): could not decode instruction; possible configuration mismatch"),
05482             ebb->sec->owner, ebb->sec, ebb->end_offset + insn_block_len);
05483          return FALSE;
05484        }
05485       ebb->end_offset += insn_block_len;
05486 
05487       if (ebb->end_offset == ebb->sec->size)
05488        ebb->ends_section = TRUE;
05489 
05490       /* Update the reloc counter.  */
05491       while (ebb->end_reloc_idx + 1 < ebb->reloc_count
05492             && (ebb->relocs[ebb->end_reloc_idx + 1].r_offset
05493                < ebb->end_offset))
05494        {
05495          ebb->end_reloc_idx++;
05496        }
05497 
05498       if (ebb->end_ptbl_idx + 1 == ebb->pte_count)
05499        return TRUE;
05500 
05501       new_entry = &ebb->ptbl[ebb->end_ptbl_idx + 1];
05502       if (((new_entry->flags & XTENSA_PROP_INSN) == 0)
05503          || ((new_entry->flags & XTENSA_PROP_INSN_NO_TRANSFORM) != 0)
05504          || ((the_entry->flags & XTENSA_PROP_ALIGN) != 0))
05505        break;
05506 
05507       if (the_entry->address + the_entry->size != new_entry->address)
05508        break;
05509 
05510       the_entry = new_entry;
05511       ebb->end_ptbl_idx++;
05512     }
05513 
05514   /* Quick check for an unreachable or end of file just at the end.  */
05515   if (ebb->end_ptbl_idx + 1 == ebb->pte_count)
05516     {
05517       if (ebb->end_offset == ebb->content_length)
05518        ebb->ends_section = TRUE;
05519     }
05520   else
05521     {
05522       new_entry = &ebb->ptbl[ebb->end_ptbl_idx + 1];
05523       if ((new_entry->flags & XTENSA_PROP_UNREACHABLE) != 0
05524          && the_entry->address + the_entry->size == new_entry->address)
05525        ebb->ends_unreachable = new_entry;
05526     }
05527 
05528   /* Any other ending requires exact alignment.  */
05529   return TRUE;
05530 }
05531 
05532 
05533 static bfd_boolean
05534 extend_ebb_bounds_backward (ebb_t *ebb)
05535 {
05536   property_table_entry *the_entry, *new_entry;
05537 
05538   the_entry = &ebb->ptbl[ebb->start_ptbl_idx];
05539 
05540   /* Stop when (1) we cannot decode the instructions in the current entry.
05541      (2) we are at the beginning of the property tables, (3) we hit a
05542      non-contiguous property table entry, (4) we hit a NO_TRANSFORM region.  */
05543 
05544   while (1)
05545     {
05546       bfd_vma block_begin;
05547       bfd_size_type insn_block_len;
05548 
05549       block_begin = the_entry->address - ebb->sec->vma;
05550       insn_block_len =
05551        insn_block_decodable_len (ebb->contents, ebb->content_length,
05552                               block_begin,
05553                               ebb->start_offset - block_begin);
05554       if (insn_block_len != ebb->start_offset - block_begin)
05555        {
05556          (*_bfd_error_handler)
05557            (_("%B(%A+0x%lx): could not decode instruction; possible configuration mismatch"),
05558             ebb->sec->owner, ebb->sec, ebb->end_offset + insn_block_len);
05559          return FALSE;
05560        }
05561       ebb->start_offset -= insn_block_len;
05562 
05563       /* Update the reloc counter.  */
05564       while (ebb->start_reloc_idx > 0
05565             && (ebb->relocs[ebb->start_reloc_idx - 1].r_offset
05566                >= ebb->start_offset))
05567        {
05568          ebb->start_reloc_idx--;
05569        }
05570 
05571       if (ebb->start_ptbl_idx == 0)
05572        return TRUE;
05573 
05574       new_entry = &ebb->ptbl[ebb->start_ptbl_idx - 1];
05575       if ((new_entry->flags & XTENSA_PROP_INSN) == 0
05576          || ((new_entry->flags & XTENSA_PROP_INSN_NO_TRANSFORM) != 0)
05577          || ((new_entry->flags & XTENSA_PROP_ALIGN) != 0))
05578        return TRUE;
05579       if (new_entry->address + new_entry->size != the_entry->address)
05580        return TRUE;
05581 
05582       the_entry = new_entry;
05583       ebb->start_ptbl_idx--;
05584     }
05585   return TRUE;
05586 }
05587 
05588 
05589 static bfd_size_type
05590 insn_block_decodable_len (bfd_byte *contents,
05591                        bfd_size_type content_len,
05592                        bfd_vma block_offset,
05593                        bfd_size_type block_len)
05594 {
05595   bfd_vma offset = block_offset;
05596 
05597   while (offset < block_offset + block_len)
05598     {
05599       bfd_size_type insn_len = 0;
05600 
05601       insn_len = insn_decode_len (contents, content_len, offset);
05602       if (insn_len == 0)
05603        return (offset - block_offset);
05604       offset += insn_len;
05605     }
05606   return (offset - block_offset);
05607 }
05608 
05609 
05610 static void
05611 ebb_propose_action (ebb_constraint *c,
05612                   enum ebb_target_enum align_type,
05613                   bfd_vma alignment_pow,
05614                   text_action_t action,
05615                   bfd_vma offset,
05616                   int removed_bytes,
05617                   bfd_boolean do_action)
05618 {
05619   proposed_action *act;
05620 
05621   if (c->action_allocated <= c->action_count)
05622     {
05623       unsigned new_allocated, i;
05624       proposed_action *new_actions;
05625 
05626       new_allocated = (c->action_count + 2) * 2;
05627       new_actions = (proposed_action *)
05628        bfd_zmalloc (sizeof (proposed_action) * new_allocated);
05629 
05630       for (i = 0; i < c->action_count; i++)
05631        new_actions[i] = c->actions[i];
05632       if (c->actions)
05633        free (c->actions);
05634       c->actions = new_actions;
05635       c->action_allocated = new_allocated;
05636     }
05637 
05638   act = &c->actions[c->action_count];
05639   act->align_type = align_type;
05640   act->alignment_pow = alignment_pow;
05641   act->action = action;
05642   act->offset = offset;
05643   act->removed_bytes = removed_bytes;
05644   act->do_action = do_action;
05645 
05646   c->action_count++;
05647 }
05648 
05649 
05650 /* Access to internal relocations, section contents and symbols.  */
05651 
05652 /* During relaxation, we need to modify relocations, section contents,
05653    and symbol definitions, and we need to keep the original values from
05654    being reloaded from the input files, i.e., we need to "pin" the
05655    modified values in memory.  We also want to continue to observe the
05656    setting of the "keep-memory" flag.  The following functions wrap the
05657    standard BFD functions to take care of this for us.  */
05658 
05659 static Elf_Internal_Rela *
05660 retrieve_internal_relocs (bfd *abfd, asection *sec, bfd_boolean keep_memory)
05661 {
05662   Elf_Internal_Rela *internal_relocs;
05663 
05664   if ((sec->flags & SEC_LINKER_CREATED) != 0)
05665     return NULL;
05666 
05667   internal_relocs = elf_section_data (sec)->relocs;
05668   if (internal_relocs == NULL)
05669     internal_relocs = (_bfd_elf_link_read_relocs
05670                      (abfd, sec, NULL, NULL, keep_memory));
05671   return internal_relocs;
05672 }
05673 
05674 
05675 static void
05676 pin_internal_relocs (asection *sec, Elf_Internal_Rela *internal_relocs)
05677 {
05678   elf_section_data (sec)->relocs = internal_relocs;
05679 }
05680 
05681 
05682 static void
05683 release_internal_relocs (asection *sec, Elf_Internal_Rela *internal_relocs)
05684 {
05685   if (internal_relocs
05686       && elf_section_data (sec)->relocs != internal_relocs)
05687     free (internal_relocs);
05688 }
05689 
05690 
05691 static bfd_byte *
05692 retrieve_contents (bfd *abfd, asection *sec, bfd_boolean keep_memory)
05693 {
05694   bfd_byte *contents;
05695   bfd_size_type sec_size;
05696 
05697   sec_size = bfd_get_section_limit (abfd, sec);
05698   contents = elf_section_data (sec)->this_hdr.contents;
05699   
05700   if (contents == NULL && sec_size != 0)
05701     {
05702       if (!bfd_malloc_and_get_section (abfd, sec, &contents))
05703        {
05704          if (contents)
05705            free (contents);
05706          return NULL;
05707        }
05708       if (keep_memory) 
05709        elf_section_data (sec)->this_hdr.contents = contents;
05710     }
05711   return contents;
05712 }
05713 
05714 
05715 static void
05716 pin_contents (asection *sec, bfd_byte *contents)
05717 {
05718   elf_section_data (sec)->this_hdr.contents = contents;
05719 }
05720 
05721 
05722 static void
05723 release_contents (asection *sec, bfd_byte *contents)
05724 {
05725   if (contents && elf_section_data (sec)->this_hdr.contents != contents)
05726     free (contents);
05727 }
05728 
05729 
05730 static Elf_Internal_Sym *
05731 retrieve_local_syms (bfd *input_bfd)
05732 {
05733   Elf_Internal_Shdr *symtab_hdr;
05734   Elf_Internal_Sym *isymbuf;
05735   size_t locsymcount;
05736 
05737   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
05738   locsymcount = symtab_hdr->sh_info;
05739 
05740   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
05741   if (isymbuf == NULL && locsymcount != 0)
05742     isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
05743                                 NULL, NULL, NULL);
05744 
05745   /* Save the symbols for this input file so they won't be read again.  */
05746   if (isymbuf && isymbuf != (Elf_Internal_Sym *) symtab_hdr->contents)
05747     symtab_hdr->contents = (unsigned char *) isymbuf;
05748 
05749   return isymbuf;
05750 }
05751 
05752 
05753 /* Code for link-time relaxation.  */
05754 
05755 /* Initialization for relaxation: */
05756 static bfd_boolean analyze_relocations (struct bfd_link_info *);
05757 static bfd_boolean find_relaxable_sections
05758   (bfd *, asection *, struct bfd_link_info *, bfd_boolean *);
05759 static bfd_boolean collect_source_relocs
05760   (bfd *, asection *, struct bfd_link_info *);
05761 static bfd_boolean is_resolvable_asm_expansion
05762   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *, struct bfd_link_info *,
05763    bfd_boolean *);
05764 static Elf_Internal_Rela *find_associated_l32r_irel
05765   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *, Elf_Internal_Rela *);
05766 static bfd_boolean compute_text_actions
05767   (bfd *, asection *, struct bfd_link_info *);
05768 static bfd_boolean compute_ebb_proposed_actions (ebb_constraint *);
05769 static bfd_boolean compute_ebb_actions (ebb_constraint *);
05770 static bfd_boolean check_section_ebb_pcrels_fit
05771   (bfd *, asection *, bfd_byte *, Elf_Internal_Rela *, const ebb_constraint *,
05772    const xtensa_opcode *);
05773 static bfd_boolean check_section_ebb_reduces (const ebb_constraint *);
05774 static void text_action_add_proposed
05775   (text_action_list *, const ebb_constraint *, asection *);
05776 static int compute_fill_extra_space (property_table_entry *);
05777 
05778 /* First pass: */
05779 static bfd_boolean compute_removed_literals
05780   (bfd *, asection *, struct bfd_link_info *, value_map_hash_table *);
05781 static Elf_Internal_Rela *get_irel_at_offset
05782   (asection *, Elf_Internal_Rela *, bfd_vma);
05783 static bfd_boolean is_removable_literal 
05784   (const source_reloc *, int, const source_reloc *, int);
05785 static bfd_boolean remove_dead_literal
05786   (bfd *, asection *, struct bfd_link_info *, Elf_Internal_Rela *,
05787    Elf_Internal_Rela *, source_reloc *, property_table_entry *, int); 
05788 static bfd_boolean identify_literal_placement
05789   (bfd *, asection *, bfd_byte *, struct bfd_link_info *,
05790    value_map_hash_table *, bfd_boolean *, Elf_Internal_Rela *, int,
05791    source_reloc *, property_table_entry *, int, section_cache_t *,
05792    bfd_boolean);
05793 static bfd_boolean relocations_reach (source_reloc *, int, const r_reloc *);
05794 static bfd_boolean coalesce_shared_literal
05795   (asection *, source_reloc *, property_table_entry *, int, value_map *);
05796 static bfd_boolean move_shared_literal
05797   (asection *, struct bfd_link_info *, source_reloc *, property_table_entry *,
05798    int, const r_reloc *, const literal_value *, section_cache_t *);
05799 
05800 /* Second pass: */
05801 static bfd_boolean relax_section (bfd *, asection *, struct bfd_link_info *);
05802 static bfd_boolean translate_section_fixes (asection *);
05803 static bfd_boolean translate_reloc_bfd_fix (reloc_bfd_fix *);
05804 static void translate_reloc (const r_reloc *, r_reloc *);
05805 static void shrink_dynamic_reloc_sections
05806   (struct bfd_link_info *, bfd *, asection *, Elf_Internal_Rela *);
05807 static bfd_boolean move_literal
05808   (bfd *, struct bfd_link_info *, asection *, bfd_vma, bfd_byte *,
05809    xtensa_relax_info *, Elf_Internal_Rela **, const literal_value *);
05810 static bfd_boolean relax_property_section
05811   (bfd *, asection *, struct bfd_link_info *);
05812 
05813 /* Third pass: */
05814 static bfd_boolean relax_section_symbols (bfd *, asection *);
05815 
05816 
05817 static bfd_boolean 
05818 elf_xtensa_relax_section (bfd *abfd,
05819                        asection *sec,
05820                        struct bfd_link_info *link_info,
05821                        bfd_boolean *again)
05822 {
05823   static value_map_hash_table *values = NULL;
05824   static bfd_boolean relocations_analyzed = FALSE;
05825   xtensa_relax_info *relax_info;
05826 
05827   if (!relocations_analyzed)
05828     {
05829       /* Do some overall initialization for relaxation.  */
05830       values = value_map_hash_table_init ();
05831       if (values == NULL)
05832        return FALSE;
05833       relaxing_section = TRUE;
05834       if (!analyze_relocations (link_info))
05835        return FALSE;
05836       relocations_analyzed = TRUE;
05837     }
05838   *again = FALSE;
05839 
05840   /* Don't mess with linker-created sections.  */
05841   if ((sec->flags & SEC_LINKER_CREATED) != 0)
05842     return TRUE;
05843 
05844   relax_info = get_xtensa_relax_info (sec);
05845   BFD_ASSERT (relax_info != NULL);
05846 
05847   switch (relax_info->visited)
05848     {
05849     case 0:
05850       /* Note: It would be nice to fold this pass into
05851         analyze_relocations, but it is important for this step that the
05852         sections be examined in link order.  */
05853       if (!compute_removed_literals (abfd, sec, link_info, values))
05854        return FALSE;
05855       *again = TRUE;
05856       break;
05857 
05858     case 1:
05859       if (values)
05860        value_map_hash_table_delete (values);
05861       values = NULL;
05862       if (!relax_section (abfd, sec, link_info))
05863        return FALSE;
05864       *again = TRUE;
05865       break;
05866 
05867     case 2:
05868       if (!relax_section_symbols (abfd, sec))
05869        return FALSE;
05870       break;
05871     }
05872 
05873   relax_info->visited++;
05874   return TRUE;
05875 }
05876 
05877 
05878 /* Initialization for relaxation.  */
05879 
05880 /* This function is called once at the start of relaxation.  It scans
05881    all the input sections and marks the ones that are relaxable (i.e.,
05882    literal sections with L32R relocations against them), and then
05883    collects source_reloc information for all the relocations against
05884    those relaxable sections.  During this process, it also detects
05885    longcalls, i.e., calls relaxed by the assembler into indirect
05886    calls, that can be optimized back into direct calls.  Within each
05887    extended basic block (ebb) containing an optimized longcall, it
05888    computes a set of "text actions" that can be performed to remove
05889    the L32R associated with the longcall while optionally preserving
05890    branch target alignments.  */
05891 
05892 static bfd_boolean
05893 analyze_relocations (struct bfd_link_info *link_info)
05894 {
05895   bfd *abfd;
05896   asection *sec;
05897   bfd_boolean is_relaxable = FALSE;
05898 
05899   /* Initialize the per-section relaxation info.  */
05900   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
05901     for (sec = abfd->sections; sec != NULL; sec = sec->next)
05902       {
05903        init_xtensa_relax_info (sec);
05904       }
05905 
05906   /* Mark relaxable sections (and count relocations against each one).  */
05907   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
05908     for (sec = abfd->sections; sec != NULL; sec = sec->next)
05909       {
05910        if (!find_relaxable_sections (abfd, sec, link_info, &is_relaxable))
05911          return FALSE;
05912       }
05913 
05914   /* Bail out if there are no relaxable sections.  */
05915   if (!is_relaxable)
05916     return TRUE;
05917 
05918   /* Allocate space for source_relocs.  */
05919   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
05920     for (sec = abfd->sections; sec != NULL; sec = sec->next)
05921       {
05922        xtensa_relax_info *relax_info;
05923 
05924        relax_info = get_xtensa_relax_info (sec);
05925        if (relax_info->is_relaxable_literal_section
05926            || relax_info->is_relaxable_asm_section)
05927          {
05928            relax_info->src_relocs = (source_reloc *)
05929              bfd_malloc (relax_info->src_count * sizeof (source_reloc));
05930          }
05931        else
05932          relax_info->src_count = 0;
05933       }
05934 
05935   /* Collect info on relocations against each relaxable section.  */
05936   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
05937     for (sec = abfd->sections; sec != NULL; sec = sec->next)
05938       {
05939        if (!collect_source_relocs (abfd, sec, link_info))
05940          return FALSE;
05941       }
05942 
05943   /* Compute the text actions.  */
05944   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
05945     for (sec = abfd->sections; sec != NULL; sec = sec->next)
05946       {
05947        if (!compute_text_actions (abfd, sec, link_info))
05948          return FALSE;
05949       }
05950 
05951   return TRUE;
05952 }
05953 
05954 
05955 /* Find all the sections that might be relaxed.  The motivation for
05956    this pass is that collect_source_relocs() needs to record _all_ the
05957    relocations that target each relaxable section.  That is expensive
05958    and unnecessary unless the target section is actually going to be
05959    relaxed.  This pass identifies all such sections by checking if
05960    they have L32Rs pointing to them.  In the process, the total number
05961    of relocations targeting each section is also counted so that we
05962    know how much space to allocate for source_relocs against each
05963    relaxable literal section.  */
05964 
05965 static bfd_boolean
05966 find_relaxable_sections (bfd *abfd,
05967                       asection *sec,
05968                       struct bfd_link_info *link_info,
05969                       bfd_boolean *is_relaxable_p)
05970 {
05971   Elf_Internal_Rela *internal_relocs;
05972   bfd_byte *contents;
05973   bfd_boolean ok = TRUE;
05974   unsigned i;
05975   xtensa_relax_info *source_relax_info;
05976   bfd_boolean is_l32r_reloc;
05977 
05978   internal_relocs = retrieve_internal_relocs (abfd, sec,
05979                                          link_info->keep_memory);
05980   if (internal_relocs == NULL) 
05981     return ok;
05982 
05983   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
05984   if (contents == NULL && sec->size != 0)
05985     {
05986       ok = FALSE;
05987       goto error_return;
05988     }
05989 
05990   source_relax_info = get_xtensa_relax_info (sec);
05991   for (i = 0; i < sec->reloc_count; i++) 
05992     {
05993       Elf_Internal_Rela *irel = &internal_relocs[i];
05994       r_reloc r_rel;
05995       asection *target_sec;
05996       xtensa_relax_info *target_relax_info;
05997 
05998       /* If this section has not already been marked as "relaxable", and
05999         if it contains any ASM_EXPAND relocations (marking expanded
06000         longcalls) that can be optimized into direct calls, then mark
06001         the section as "relaxable".  */
06002       if (source_relax_info
06003          && !source_relax_info->is_relaxable_asm_section
06004          && ELF32_R_TYPE (irel->r_info) == R_XTENSA_ASM_EXPAND)
06005        {
06006          bfd_boolean is_reachable = FALSE;
06007          if (is_resolvable_asm_expansion (abfd, sec, contents, irel,
06008                                       link_info, &is_reachable)
06009              && is_reachable)
06010            {
06011              source_relax_info->is_relaxable_asm_section = TRUE;
06012              *is_relaxable_p = TRUE;
06013            }
06014        }
06015 
06016       r_reloc_init (&r_rel, abfd, irel, contents,
06017                   bfd_get_section_limit (abfd, sec));
06018 
06019       target_sec = r_reloc_get_section (&r_rel);
06020       target_relax_info = get_xtensa_relax_info (target_sec);
06021       if (!target_relax_info)
06022        continue;
06023 
06024       /* Count PC-relative operand relocations against the target section.
06025          Note: The conditions tested here must match the conditions under
06026         which init_source_reloc is called in collect_source_relocs().  */
06027       is_l32r_reloc = FALSE;
06028       if (is_operand_relocation (ELF32_R_TYPE (irel->r_info)))
06029        {
06030          xtensa_opcode opcode =
06031            get_relocation_opcode (abfd, sec, contents, irel);
06032          if (opcode != XTENSA_UNDEFINED)
06033            {
06034              is_l32r_reloc = (opcode == get_l32r_opcode ());
06035              if (!is_alt_relocation (ELF32_R_TYPE (irel->r_info))
06036                 || is_l32r_reloc)
06037               target_relax_info->src_count++;
06038            }
06039        }
06040 
06041       if (is_l32r_reloc && r_reloc_is_defined (&r_rel))
06042        {
06043          /* Mark the target section as relaxable.  */
06044          target_relax_info->is_relaxable_literal_section = TRUE;
06045          *is_relaxable_p = TRUE;
06046        }
06047     }
06048 
06049  error_return:
06050   release_contents (sec, contents);
06051   release_internal_relocs (sec, internal_relocs);
06052   return ok;
06053 }
06054 
06055 
06056 /* Record _all_ the relocations that point to relaxable sections, and
06057    get rid of ASM_EXPAND relocs by either converting them to
06058    ASM_SIMPLIFY or by removing them.  */
06059 
06060 static bfd_boolean
06061 collect_source_relocs (bfd *abfd,
06062                      asection *sec,
06063                      struct bfd_link_info *link_info)
06064 {
06065   Elf_Internal_Rela *internal_relocs;
06066   bfd_byte *contents;
06067   bfd_boolean ok = TRUE;
06068   unsigned i;
06069   bfd_size_type sec_size;
06070 
06071   internal_relocs = retrieve_internal_relocs (abfd, sec, 
06072                                          link_info->keep_memory);
06073   if (internal_relocs == NULL) 
06074     return ok;
06075 
06076   sec_size = bfd_get_section_limit (abfd, sec);
06077   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
06078   if (contents == NULL && sec_size != 0)
06079     {
06080       ok = FALSE;
06081       goto error_return;
06082     }
06083 
06084   /* Record relocations against relaxable literal sections.  */
06085   for (i = 0; i < sec->reloc_count; i++) 
06086     {
06087       Elf_Internal_Rela *irel = &internal_relocs[i];
06088       r_reloc r_rel;
06089       asection *target_sec;
06090       xtensa_relax_info *target_relax_info;
06091 
06092       r_reloc_init (&r_rel, abfd, irel, contents, sec_size);
06093 
06094       target_sec = r_reloc_get_section (&r_rel);
06095       target_relax_info = get_xtensa_relax_info (target_sec);
06096 
06097       if (target_relax_info
06098          && (target_relax_info->is_relaxable_literal_section
06099              || target_relax_info->is_relaxable_asm_section))
06100        {
06101          xtensa_opcode opcode = XTENSA_UNDEFINED;
06102          int opnd = -1;
06103          bfd_boolean is_abs_literal = FALSE;
06104 
06105          if (is_alt_relocation (ELF32_R_TYPE (irel->r_info)))
06106            {
06107              /* None of the current alternate relocs are PC-relative,
06108                and only PC-relative relocs matter here.  However, we
06109                still need to record the opcode for literal
06110                coalescing.  */
06111              opcode = get_relocation_opcode (abfd, sec, contents, irel);
06112              if (opcode == get_l32r_opcode ())
06113               {
06114                 is_abs_literal = TRUE;
06115                 opnd = 1;
06116               }
06117              else
06118               opcode = XTENSA_UNDEFINED;
06119            }
06120          else if (is_operand_relocation (ELF32_R_TYPE (irel->r_info)))
06121            {
06122              opcode = get_relocation_opcode (abfd, sec, contents, irel);
06123              opnd = get_relocation_opnd (opcode, ELF32_R_TYPE (irel->r_info));
06124            }
06125 
06126          if (opcode != XTENSA_UNDEFINED)
06127            {
06128              int src_next = target_relax_info->src_next++;
06129              source_reloc *s_reloc = &target_relax_info->src_relocs[src_next];
06130 
06131              init_source_reloc (s_reloc, sec, &r_rel, opcode, opnd,
06132                              is_abs_literal);
06133            }
06134        }
06135     }
06136 
06137   /* Now get rid of ASM_EXPAND relocations.  At this point, the
06138      src_relocs array for the target literal section may still be
06139      incomplete, but it must at least contain the entries for the L32R
06140      relocations associated with ASM_EXPANDs because they were just
06141      added in the preceding loop over the relocations.  */
06142 
06143   for (i = 0; i < sec->reloc_count; i++) 
06144     {
06145       Elf_Internal_Rela *irel = &internal_relocs[i];
06146       bfd_boolean is_reachable;
06147 
06148       if (!is_resolvable_asm_expansion (abfd, sec, contents, irel, link_info,
06149                                    &is_reachable))
06150        continue;
06151 
06152       if (is_reachable)
06153        {
06154          Elf_Internal_Rela *l32r_irel;
06155          r_reloc r_rel;
06156          asection *target_sec;
06157          xtensa_relax_info *target_relax_info;
06158 
06159          /* Mark the source_reloc for the L32R so that it will be
06160             removed in compute_removed_literals(), along with the
06161             associated literal.  */
06162          l32r_irel = find_associated_l32r_irel (abfd, sec, contents,
06163                                            irel, internal_relocs);
06164          if (l32r_irel == NULL)
06165            continue;
06166 
06167          r_reloc_init (&r_rel, abfd, l32r_irel, contents, sec_size);
06168 
06169          target_sec = r_reloc_get_section (&r_rel);
06170          target_relax_info = get_xtensa_relax_info (target_sec);
06171 
06172          if (target_relax_info
06173              && (target_relax_info->is_relaxable_literal_section
06174                 || target_relax_info->is_relaxable_asm_section))
06175            {
06176              source_reloc *s_reloc;
06177 
06178              /* Search the source_relocs for the entry corresponding to
06179                the l32r_irel.  Note: The src_relocs array is not yet
06180                sorted, but it wouldn't matter anyway because we're
06181                searching by source offset instead of target offset.  */
06182              s_reloc = find_source_reloc (target_relax_info->src_relocs, 
06183                                       target_relax_info->src_next,
06184                                       sec, l32r_irel);
06185              BFD_ASSERT (s_reloc);
06186              s_reloc->is_null = TRUE;
06187            }
06188 
06189          /* Convert this reloc to ASM_SIMPLIFY.  */
06190          irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info),
06191                                    R_XTENSA_ASM_SIMPLIFY);
06192          l32r_irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
06193 
06194          pin_internal_relocs (sec, internal_relocs);
06195        }
06196       else
06197        {
06198          /* It is resolvable but doesn't reach.  We resolve now
06199             by eliminating the relocation -- the call will remain
06200             expanded into L32R/CALLX.  */
06201          irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
06202          pin_internal_relocs (sec, internal_relocs);
06203        }
06204     }
06205 
06206  error_return:
06207   release_contents (sec, contents);
06208   release_internal_relocs (sec, internal_relocs);
06209   return ok;
06210 }
06211 
06212 
06213 /* Return TRUE if the asm expansion can be resolved.  Generally it can
06214    be resolved on a final link or when a partial link locates it in the
06215    same section as the target.  Set "is_reachable" flag if the target of
06216    the call is within the range of a direct call, given the current VMA
06217    for this section and the target section.  */
06218 
06219 bfd_boolean
06220 is_resolvable_asm_expansion (bfd *abfd,
06221                           asection *sec,
06222                           bfd_byte *contents,
06223                           Elf_Internal_Rela *irel,
06224                           struct bfd_link_info *link_info,
06225                           bfd_boolean *is_reachable_p)
06226 {
06227   asection *target_sec;
06228   bfd_vma target_offset;
06229   r_reloc r_rel;
06230   xtensa_opcode opcode, direct_call_opcode;
06231   bfd_vma self_address;
06232   bfd_vma dest_address;
06233   bfd_boolean uses_l32r;
06234   bfd_size_type sec_size;
06235 
06236   *is_reachable_p = FALSE;
06237 
06238   if (contents == NULL)
06239     return FALSE;
06240 
06241   if (ELF32_R_TYPE (irel->r_info) != R_XTENSA_ASM_EXPAND) 
06242     return FALSE;
06243 
06244   sec_size = bfd_get_section_limit (abfd, sec);
06245   opcode = get_expanded_call_opcode (contents + irel->r_offset,
06246                                  sec_size - irel->r_offset, &uses_l32r);
06247   /* Optimization of longcalls that use CONST16 is not yet implemented.  */
06248   if (!uses_l32r)
06249     return FALSE;
06250   
06251   direct_call_opcode = swap_callx_for_call_opcode (opcode);
06252   if (direct_call_opcode == XTENSA_UNDEFINED)
06253     return FALSE;
06254 
06255   /* Check and see that the target resolves.  */
06256   r_reloc_init (&r_rel, abfd, irel, contents, sec_size);
06257   if (!r_reloc_is_defined (&r_rel))
06258     return FALSE;
06259 
06260   target_sec = r_reloc_get_section (&r_rel);
06261   target_offset = r_rel.target_offset;
06262 
06263   /* If the target is in a shared library, then it doesn't reach.  This
06264      isn't supposed to come up because the compiler should never generate
06265      non-PIC calls on systems that use shared libraries, but the linker
06266      shouldn't crash regardless.  */
06267   if (!target_sec->output_section)
06268     return FALSE;
06269       
06270   /* For relocatable sections, we can only simplify when the output
06271      section of the target is the same as the output section of the
06272      source.  */
06273   if (link_info->relocatable
06274       && (target_sec->output_section != sec->output_section
06275          || is_reloc_sym_weak (abfd, irel)))
06276     return FALSE;
06277 
06278   self_address = (sec->output_section->vma
06279                 + sec->output_offset + irel->r_offset + 3);
06280   dest_address = (target_sec->output_section->vma
06281                 + target_sec->output_offset + target_offset);
06282       
06283   *is_reachable_p = pcrel_reloc_fits (direct_call_opcode, 0,
06284                                   self_address, dest_address);
06285 
06286   if ((self_address >> CALL_SEGMENT_BITS) !=
06287       (dest_address >> CALL_SEGMENT_BITS))
06288     return FALSE;
06289 
06290   return TRUE;
06291 }
06292 
06293 
06294 static Elf_Internal_Rela *
06295 find_associated_l32r_irel (bfd *abfd,
06296                         asection *sec,
06297                         bfd_byte *contents,
06298                         Elf_Internal_Rela *other_irel,
06299                         Elf_Internal_Rela *internal_relocs)
06300 {
06301   unsigned i;
06302 
06303   for (i = 0; i < sec->reloc_count; i++) 
06304     {
06305       Elf_Internal_Rela *irel = &internal_relocs[i];
06306 
06307       if (irel == other_irel)
06308        continue;
06309       if (irel->r_offset != other_irel->r_offset)
06310        continue;
06311       if (is_l32r_relocation (abfd, sec, contents, irel))
06312        return irel;
06313     }
06314 
06315   return NULL;
06316 }
06317 
06318 
06319 static xtensa_opcode *
06320 build_reloc_opcodes (bfd *abfd,
06321                    asection *sec,
06322                    bfd_byte *contents,
06323                    Elf_Internal_Rela *internal_relocs)
06324 {
06325   unsigned i;
06326   xtensa_opcode *reloc_opcodes =
06327     (xtensa_opcode *) bfd_malloc (sizeof (xtensa_opcode) * sec->reloc_count);
06328   for (i = 0; i < sec->reloc_count; i++)
06329     {
06330       Elf_Internal_Rela *irel = &internal_relocs[i];
06331       reloc_opcodes[i] = get_relocation_opcode (abfd, sec, contents, irel);
06332     }
06333   return reloc_opcodes;
06334 }
06335 
06336 
06337 /* The compute_text_actions function will build a list of potential
06338    transformation actions for code in the extended basic block of each
06339    longcall that is optimized to a direct call.  From this list we
06340    generate a set of actions to actually perform that optimizes for
06341    space and, if not using size_opt, maintains branch target
06342    alignments.
06343 
06344    These actions to be performed are placed on a per-section list.
06345    The actual changes are performed by relax_section() in the second
06346    pass.  */
06347 
06348 bfd_boolean
06349 compute_text_actions (bfd *abfd,
06350                     asection *sec,
06351                     struct bfd_link_info *link_info)
06352 {
06353   xtensa_opcode *reloc_opcodes = NULL;
06354   xtensa_relax_info *relax_info;
06355   bfd_byte *contents;
06356   Elf_Internal_Rela *internal_relocs;
06357   bfd_boolean ok = TRUE;
06358   unsigned i;
06359   property_table_entry *prop_table = 0;
06360   int ptblsize = 0;
06361   bfd_size_type sec_size;
06362 
06363   relax_info = get_xtensa_relax_info (sec);
06364   BFD_ASSERT (relax_info);
06365   BFD_ASSERT (relax_info->src_next == relax_info->src_count);
06366 
06367   /* Do nothing if the section contains no optimized longcalls.  */
06368   if (!relax_info->is_relaxable_asm_section)
06369     return ok;
06370 
06371   internal_relocs = retrieve_internal_relocs (abfd, sec,
06372                                          link_info->keep_memory);
06373 
06374   if (internal_relocs)
06375     qsort (internal_relocs, sec->reloc_count, sizeof (Elf_Internal_Rela),
06376           internal_reloc_compare);
06377 
06378   sec_size = bfd_get_section_limit (abfd, sec);
06379   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
06380   if (contents == NULL && sec_size != 0)
06381     {
06382       ok = FALSE;
06383       goto error_return;
06384     }
06385 
06386   ptblsize = xtensa_read_table_entries (abfd, sec, &prop_table,
06387                                    XTENSA_PROP_SEC_NAME, FALSE);
06388   if (ptblsize < 0)
06389     {
06390       ok = FALSE;
06391       goto error_return;
06392     }
06393 
06394   for (i = 0; i < sec->reloc_count; i++)
06395     {
06396       Elf_Internal_Rela *irel = &internal_relocs[i];
06397       bfd_vma r_offset;
06398       property_table_entry *the_entry;
06399       int ptbl_idx;
06400       ebb_t *ebb;
06401       ebb_constraint ebb_table;
06402       bfd_size_type simplify_size;
06403 
06404       if (irel && ELF32_R_TYPE (irel->r_info) != R_XTENSA_ASM_SIMPLIFY)
06405        continue;
06406       r_offset = irel->r_offset;
06407 
06408       simplify_size = get_asm_simplify_size (contents, sec_size, r_offset);
06409       if (simplify_size == 0)
06410        {
06411          (*_bfd_error_handler)
06412            (_("%B(%A+0x%lx): could not decode instruction for XTENSA_ASM_SIMPLIFY relocation; possible configuration mismatch"),
06413             sec->owner, sec, r_offset);
06414          continue;
06415        }
06416 
06417       /* If the instruction table is not around, then don't do this
06418         relaxation.  */
06419       the_entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
06420                                             sec->vma + irel->r_offset);
06421       if (the_entry == NULL || XTENSA_NO_NOP_REMOVAL)
06422        {
06423          text_action_add (&relax_info->action_list,
06424                         ta_convert_longcall, sec, r_offset,
06425                         0);
06426          continue;
06427        }
06428 
06429       /* If the next longcall happens to be at the same address as an
06430         unreachable section of size 0, then skip forward.  */
06431       ptbl_idx = the_entry - prop_table;
06432       while ((the_entry->flags & XTENSA_PROP_UNREACHABLE)
06433             && the_entry->size == 0
06434             && ptbl_idx + 1 < ptblsize
06435             && (prop_table[ptbl_idx + 1].address
06436                == prop_table[ptbl_idx].address))
06437        {
06438          ptbl_idx++;
06439          the_entry++;
06440        }
06441 
06442       if (the_entry->flags & XTENSA_PROP_INSN_NO_TRANSFORM)
06443          /* NO_REORDER is OK */
06444        continue;
06445 
06446       init_ebb_constraint (&ebb_table);
06447       ebb = &ebb_table.ebb;
06448       init_ebb (ebb, sec, contents, sec_size, prop_table, ptblsize,
06449               internal_relocs, sec->reloc_count);
06450       ebb->start_offset = r_offset + simplify_size;
06451       ebb->end_offset = r_offset + simplify_size;
06452       ebb->start_ptbl_idx = ptbl_idx;
06453       ebb->end_ptbl_idx = ptbl_idx;
06454       ebb->start_reloc_idx = i;
06455       ebb->end_reloc_idx = i;
06456 
06457       /* Precompute the opcode for each relocation.  */
06458       if (reloc_opcodes == NULL)
06459        reloc_opcodes = build_reloc_opcodes (abfd, sec, contents,
06460                                         internal_relocs);
06461 
06462       if (!extend_ebb_bounds (ebb)
06463          || !compute_ebb_proposed_actions (&ebb_table)
06464          || !compute_ebb_actions (&ebb_table)
06465          || !check_section_ebb_pcrels_fit (abfd, sec, contents,
06466                                        internal_relocs, &ebb_table,
06467                                        reloc_opcodes)
06468          || !check_section_ebb_reduces (&ebb_table))
06469        {
06470          /* If anything goes wrong or we get unlucky and something does
06471             not fit, with our plan because of expansion between
06472             critical branches, just convert to a NOP.  */
06473 
06474          text_action_add (&relax_info->action_list,
06475                         ta_convert_longcall, sec, r_offset, 0);
06476          i = ebb_table.ebb.end_reloc_idx;
06477          free_ebb_constraint (&ebb_table);
06478          continue;
06479        }
06480 
06481       text_action_add_proposed (&relax_info->action_list, &ebb_table, sec);
06482 
06483       /* Update the index so we do not go looking at the relocations
06484         we have already processed.  */
06485       i = ebb_table.ebb.end_reloc_idx;
06486       free_ebb_constraint (&ebb_table);
06487     }
06488 
06489 #if DEBUG
06490   if (relax_info->action_list.head)
06491     print_action_list (stderr, &relax_info->action_list);
06492 #endif
06493 
06494 error_return:
06495   release_contents (sec, contents);
06496   release_internal_relocs (sec, internal_relocs);
06497   if (prop_table)
06498     free (prop_table);
06499   if (reloc_opcodes)
06500     free (reloc_opcodes);
06501 
06502   return ok;
06503 }
06504 
06505 
06506 /* Do not widen an instruction if it is preceeded by a
06507    loop opcode.  It might cause misalignment.  */
06508 
06509 static bfd_boolean
06510 prev_instr_is_a_loop (bfd_byte *contents,
06511                     bfd_size_type content_length,
06512                     bfd_size_type offset)
06513 {
06514   xtensa_opcode prev_opcode;
06515 
06516   if (offset < 3)
06517     return FALSE;
06518   prev_opcode = insn_decode_opcode (contents, content_length, offset-3, 0);
06519   return (xtensa_opcode_is_loop (xtensa_default_isa, prev_opcode) == 1);
06520 } 
06521 
06522 
06523 /* Find all of the possible actions for an extended basic block.  */
06524 
06525 bfd_boolean
06526 compute_ebb_proposed_actions (ebb_constraint *ebb_table)
06527 {
06528   const ebb_t *ebb = &ebb_table->ebb;
06529   unsigned rel_idx = ebb->start_reloc_idx;
06530   property_table_entry *entry, *start_entry, *end_entry;
06531   bfd_vma offset = 0;
06532   xtensa_isa isa = xtensa_default_isa;
06533   xtensa_format fmt;
06534   static xtensa_insnbuf insnbuf = NULL;
06535   static xtensa_insnbuf slotbuf = NULL;
06536 
06537   if (insnbuf == NULL)
06538     {
06539       insnbuf = xtensa_insnbuf_alloc (isa);
06540       slotbuf = xtensa_insnbuf_alloc (isa);
06541     }
06542 
06543   start_entry = &ebb->ptbl[ebb->start_ptbl_idx];
06544   end_entry = &ebb->ptbl[ebb->end_ptbl_idx];
06545 
06546   for (entry = start_entry; entry <= end_entry; entry++)
06547     {
06548       bfd_vma start_offset, end_offset;
06549       bfd_size_type insn_len;
06550 
06551       start_offset = entry->address - ebb->sec->vma;
06552       end_offset = entry->address + entry->size - ebb->sec->vma;
06553 
06554       if (entry == start_entry)
06555        start_offset = ebb->start_offset;
06556       if (entry == end_entry)
06557        end_offset = ebb->end_offset;
06558       offset = start_offset;
06559 
06560       if (offset == entry->address - ebb->sec->vma
06561          && (entry->flags & XTENSA_PROP_INSN_BRANCH_TARGET) != 0)
06562        {
06563          enum ebb_target_enum align_type = EBB_DESIRE_TGT_ALIGN;
06564          BFD_ASSERT (offset != end_offset);
06565          if (offset == end_offset)
06566            return FALSE;
06567 
06568          insn_len = insn_decode_len (ebb->contents, ebb->content_length,
06569                                   offset);
06570          if (insn_len == 0) 
06571            goto decode_error;
06572 
06573          if (check_branch_target_aligned_address (offset, insn_len))
06574            align_type = EBB_REQUIRE_TGT_ALIGN;
06575 
06576          ebb_propose_action (ebb_table, align_type, 0,
06577                            ta_none, offset, 0, TRUE);
06578        }
06579 
06580       while (offset != end_offset)
06581        {
06582          Elf_Internal_Rela *irel;
06583          xtensa_opcode opcode;
06584 
06585          while (rel_idx < ebb->end_reloc_idx
06586                && (ebb->relocs[rel_idx].r_offset < offset
06587                    || (ebb->relocs[rel_idx].r_offset == offset
06588                       && (ELF32_R_TYPE (ebb->relocs[rel_idx].r_info)
06589                           != R_XTENSA_ASM_SIMPLIFY))))
06590            rel_idx++;
06591 
06592          /* Check for longcall.  */
06593          irel = &ebb->relocs[rel_idx];
06594          if (irel->r_offset == offset
06595              && ELF32_R_TYPE (irel->r_info) == R_XTENSA_ASM_SIMPLIFY)
06596            {
06597              bfd_size_type simplify_size;
06598 
06599              simplify_size = get_asm_simplify_size (ebb->contents, 
06600                                                ebb->content_length,
06601                                                irel->r_offset);
06602              if (simplify_size == 0)
06603               goto decode_error;
06604 
06605              ebb_propose_action (ebb_table, EBB_NO_ALIGN, 0,
06606                               ta_convert_longcall, offset, 0, TRUE);
06607              
06608              offset += simplify_size;
06609              continue;
06610            }
06611 
06612          if (offset + MIN_INSN_LENGTH > ebb->content_length)
06613            goto decode_error;
06614          xtensa_insnbuf_from_chars (isa, insnbuf, &ebb->contents[offset],
06615                                  ebb->content_length - offset);
06616          fmt = xtensa_format_decode (isa, insnbuf);
06617          if (fmt == XTENSA_UNDEFINED)
06618            goto decode_error;
06619          insn_len = xtensa_format_length (isa, fmt);
06620          if (insn_len == (bfd_size_type) XTENSA_UNDEFINED)
06621            goto decode_error;
06622 
06623          if (xtensa_format_num_slots (isa, fmt) != 1)
06624            {
06625              offset += insn_len;
06626              continue;
06627            }
06628 
06629          xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf);
06630          opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
06631          if (opcode == XTENSA_UNDEFINED)
06632            goto decode_error;
06633 
06634          if ((entry->flags & XTENSA_PROP_INSN_NO_DENSITY) == 0
06635              && (entry->flags & XTENSA_PROP_INSN_NO_TRANSFORM) == 0
06636              && can_narrow_instruction (slotbuf, fmt, opcode) != 0)
06637            {
06638              /* Add an instruction narrow action.  */
06639              ebb_propose_action (ebb_table, EBB_NO_ALIGN, 0,
06640                               ta_narrow_insn, offset, 0, FALSE);
06641            }
06642          else if ((entry->flags & XTENSA_PROP_INSN_NO_TRANSFORM) == 0
06643                  && can_widen_instruction (slotbuf, fmt, opcode) != 0
06644                  && ! prev_instr_is_a_loop (ebb->contents,
06645                                          ebb->content_length, offset))
06646            {
06647              /* Add an instruction widen action.  */
06648              ebb_propose_action (ebb_table, EBB_NO_ALIGN, 0,
06649                               ta_widen_insn, offset, 0, FALSE);
06650            }
06651          else if (xtensa_opcode_is_loop (xtensa_default_isa, opcode) == 1)
06652            {
06653              /* Check for branch targets.  */
06654              ebb_propose_action (ebb_table, EBB_REQUIRE_LOOP_ALIGN, 0,
06655                               ta_none, offset, 0, TRUE);
06656            }
06657 
06658          offset += insn_len;
06659        }
06660     }
06661 
06662   if (ebb->ends_unreachable)
06663     {
06664       ebb_propose_action (ebb_table, EBB_NO_ALIGN, 0,
06665                        ta_fill, ebb->end_offset, 0, TRUE);
06666     }
06667 
06668   return TRUE;
06669 
06670  decode_error:
06671   (*_bfd_error_handler)
06672     (_("%B(%A+0x%lx): could not decode instruction; possible configuration mismatch"),
06673      ebb->sec->owner, ebb->sec, offset);
06674   return FALSE;
06675 }
06676 
06677 
06678 /* After all of the information has collected about the
06679    transformations possible in an EBB, compute the appropriate actions
06680    here in compute_ebb_actions.  We still must check later to make
06681    sure that the actions do not break any relocations.  The algorithm
06682    used here is pretty greedy.  Basically, it removes as many no-ops
06683    as possible so that the end of the EBB has the same alignment
06684    characteristics as the original.  First, it uses narrowing, then
06685    fill space at the end of the EBB, and finally widenings.  If that
06686    does not work, it tries again with one fewer no-op removed.  The
06687    optimization will only be performed if all of the branch targets
06688    that were aligned before transformation are also aligned after the
06689    transformation.
06690 
06691    When the size_opt flag is set, ignore the branch target alignments,
06692    narrow all wide instructions, and remove all no-ops unless the end
06693    of the EBB prevents it.  */
06694 
06695 bfd_boolean
06696 compute_ebb_actions (ebb_constraint *ebb_table)
06697 {
06698   unsigned i = 0;
06699   unsigned j;
06700   int removed_bytes = 0;
06701   ebb_t *ebb = &ebb_table->ebb;
06702   unsigned seg_idx_start = 0;
06703   unsigned seg_idx_end = 0;
06704 
06705   /* We perform this like the assembler relaxation algorithm: Start by
06706      assuming all instructions are narrow and all no-ops removed; then
06707      walk through....  */
06708 
06709   /* For each segment of this that has a solid constraint, check to
06710      see if there are any combinations that will keep the constraint.
06711      If so, use it.  */
06712   for (seg_idx_end = 0; seg_idx_end < ebb_table->action_count; seg_idx_end++)
06713     {
06714       bfd_boolean requires_text_end_align = FALSE;
06715       unsigned longcall_count = 0;
06716       unsigned longcall_convert_count = 0;
06717       unsigned narrowable_count = 0;
06718       unsigned narrowable_convert_count = 0;
06719       unsigned widenable_count = 0;
06720       unsigned widenable_convert_count = 0;
06721 
06722       proposed_action *action = NULL;
06723       int align = (1 << ebb_table->ebb.sec->alignment_power);
06724 
06725       seg_idx_start = seg_idx_end;
06726 
06727       for (i = seg_idx_start; i < ebb_table->action_count; i++)
06728        {
06729          action = &ebb_table->actions[i];
06730          if (action->action == ta_convert_longcall)
06731            longcall_count++;
06732          if (action->action == ta_narrow_insn)
06733            narrowable_count++;
06734          if (action->action == ta_widen_insn)
06735            widenable_count++;
06736          if (action->action == ta_fill)
06737            break;
06738          if (action->align_type == EBB_REQUIRE_LOOP_ALIGN)
06739            break;
06740          if (action->align_type == EBB_REQUIRE_TGT_ALIGN
06741              && !elf32xtensa_size_opt)
06742            break;
06743        }
06744       seg_idx_end = i;
06745 
06746       if (seg_idx_end == ebb_table->action_count && !ebb->ends_unreachable)
06747        requires_text_end_align = TRUE;
06748 
06749       if (elf32xtensa_size_opt && !requires_text_end_align
06750          && action->align_type != EBB_REQUIRE_LOOP_ALIGN
06751          && action->align_type != EBB_REQUIRE_TGT_ALIGN)
06752        {
06753          longcall_convert_count = longcall_count;
06754          narrowable_convert_count = narrowable_count;
06755          widenable_convert_count = 0;
06756        }
06757       else
06758        {
06759          /* There is a constraint.  Convert the max number of longcalls.  */
06760          narrowable_convert_count = 0;
06761          longcall_convert_count = 0;
06762          widenable_convert_count = 0;
06763 
06764          for (j = 0; j < longcall_count; j++)
06765            {
06766              int removed = (longcall_count - j) * 3 & (align - 1);
06767              unsigned desire_narrow = (align - removed) & (align - 1);
06768              unsigned desire_widen = removed;
06769              if (desire_narrow <= narrowable_count)
06770               {
06771                 narrowable_convert_count = desire_narrow;
06772                 narrowable_convert_count +=
06773                   (align * ((narrowable_count - narrowable_convert_count)
06774                            / align));
06775                 longcall_convert_count = (longcall_count - j);
06776                 widenable_convert_count = 0;
06777                 break;
06778               }
06779              if (desire_widen <= widenable_count && !elf32xtensa_size_opt)
06780               {
06781                 narrowable_convert_count = 0;
06782                 longcall_convert_count = longcall_count - j;
06783                 widenable_convert_count = desire_widen;
06784                 break;
06785               }
06786            }
06787        }
06788 
06789       /* Now the number of conversions are saved.  Do them.  */
06790       for (i = seg_idx_start; i < seg_idx_end; i++)
06791        {
06792          action = &ebb_table->actions[i];
06793          switch (action->action)
06794            {
06795            case ta_convert_longcall:
06796              if (longcall_convert_count != 0)
06797               {
06798                 action->action = ta_remove_longcall;
06799                 action->do_action = TRUE;
06800                 action->removed_bytes += 3;
06801                 longcall_convert_count--;
06802               }
06803              break;
06804            case ta_narrow_insn:
06805              if (narrowable_convert_count != 0)
06806               {
06807                 action->do_action = TRUE;
06808                 action->removed_bytes += 1;
06809                 narrowable_convert_count--;
06810               }
06811              break;
06812            case ta_widen_insn:
06813              if (widenable_convert_count != 0)
06814               {
06815                 action->do_action = TRUE;
06816                 action->removed_bytes -= 1;
06817                 widenable_convert_count--;
06818               }
06819              break;
06820            default:
06821              break;
06822            }
06823        }
06824     }
06825 
06826   /* Now we move on to some local opts.  Try to remove each of the
06827      remaining longcalls.  */
06828 
06829   if (ebb_table->ebb.ends_section || ebb_table->ebb.ends_unreachable)
06830     {
06831       removed_bytes = 0;
06832       for (i = 0; i < ebb_table->action_count; i++)
06833        {
06834          int old_removed_bytes = removed_bytes;
06835          proposed_action *action = &ebb_table->actions[i];
06836 
06837          if (action->do_action && action->action == ta_convert_longcall)
06838            {
06839              bfd_boolean bad_alignment = FALSE;
06840              removed_bytes += 3;
06841              for (j = i + 1; j < ebb_table->action_count; j++)
06842               {
06843                 proposed_action *new_action = &ebb_table->actions[j];
06844                 bfd_vma offset = new_action->offset;
06845                 if (new_action->align_type == EBB_REQUIRE_TGT_ALIGN)
06846                   {
06847                     if (!check_branch_target_aligned
06848                        (ebb_table->ebb.contents,
06849                         ebb_table->ebb.content_length,
06850                         offset, offset - removed_bytes))
06851                      {
06852                        bad_alignment = TRUE;
06853                        break;
06854                      }
06855                   }
06856                 if (new_action->align_type == EBB_REQUIRE_LOOP_ALIGN)
06857                   {
06858                     if (!check_loop_aligned (ebb_table->ebb.contents,
06859                                           ebb_table->ebb.content_length,
06860                                           offset,
06861                                           offset - removed_bytes))
06862                      {
06863                        bad_alignment = TRUE;
06864                        break;
06865                      }
06866                   }
06867                 if (new_action->action == ta_narrow_insn
06868                     && !new_action->do_action
06869                     && ebb_table->ebb.sec->alignment_power == 2)
06870                   {
06871                     /* Narrow an instruction and we are done.  */
06872                     new_action->do_action = TRUE;
06873                     new_action->removed_bytes += 1;
06874                     bad_alignment = FALSE;
06875                     break;
06876                   }
06877                 if (new_action->action == ta_widen_insn
06878                     && new_action->do_action
06879                     && ebb_table->ebb.sec->alignment_power == 2)
06880                   {
06881                     /* Narrow an instruction and we are done.  */
06882                     new_action->do_action = FALSE;
06883                     new_action->removed_bytes += 1;
06884                     bad_alignment = FALSE;
06885                     break;
06886                   }
06887               }
06888              if (!bad_alignment)
06889               {
06890                 action->removed_bytes += 3;
06891                 action->action = ta_remove_longcall;
06892                 action->do_action = TRUE;
06893               }
06894            }
06895          removed_bytes = old_removed_bytes;
06896          if (action->do_action)
06897            removed_bytes += action->removed_bytes;
06898        }
06899     }
06900 
06901   removed_bytes = 0;
06902   for (i = 0; i < ebb_table->action_count; ++i)
06903     {
06904       proposed_action *action = &ebb_table->actions[i];
06905       if (action->do_action)
06906        removed_bytes += action->removed_bytes;
06907     }
06908 
06909   if ((removed_bytes % (1 << ebb_table->ebb.sec->alignment_power)) != 0
06910       && ebb->ends_unreachable)
06911     {
06912       proposed_action *action;
06913       int br;
06914       int extra_space;
06915 
06916       BFD_ASSERT (ebb_table->action_count != 0);
06917       action = &ebb_table->actions[ebb_table->action_count - 1];
06918       BFD_ASSERT (action->action == ta_fill);
06919       BFD_ASSERT (ebb->ends_unreachable->flags & XTENSA_PROP_UNREACHABLE);
06920 
06921       extra_space = compute_fill_extra_space (ebb->ends_unreachable);
06922       br = action->removed_bytes + removed_bytes + extra_space;
06923       br = br & ((1 << ebb->sec->alignment_power ) - 1);
06924 
06925       action->removed_bytes = extra_space - br;
06926     }
06927   return TRUE;
06928 }
06929 
06930 
06931 /* The xlate_map is a sorted array of address mappings designed to
06932    answer the offset_with_removed_text() query with a binary search instead
06933    of a linear search through the section's action_list.  */
06934 
06935 typedef struct xlate_map_entry xlate_map_entry_t;
06936 typedef struct xlate_map xlate_map_t;
06937 
06938 struct xlate_map_entry
06939 {
06940   unsigned orig_address;
06941   unsigned new_address;
06942   unsigned size;
06943 };
06944 
06945 struct xlate_map
06946 {
06947   unsigned entry_count;
06948   xlate_map_entry_t *entry;
06949 };
06950 
06951 
06952 static int 
06953 xlate_compare (const void *a_v, const void *b_v)
06954 {
06955   const xlate_map_entry_t *a = (const xlate_map_entry_t *) a_v;
06956   const xlate_map_entry_t *b = (const xlate_map_entry_t *) b_v;
06957   if (a->orig_address < b->orig_address)
06958     return -1;
06959   if (a->orig_address > (b->orig_address + b->size - 1))
06960     return 1;
06961   return 0;
06962 }
06963 
06964 
06965 static bfd_vma
06966 xlate_offset_with_removed_text (const xlate_map_t *map,
06967                             text_action_list *action_list,
06968                             bfd_vma offset)
06969 {
06970   xlate_map_entry_t tmp;
06971   void *r;
06972   xlate_map_entry_t *e;
06973 
06974   if (map == NULL)
06975     return offset_with_removed_text (action_list, offset);
06976 
06977   if (map->entry_count == 0)
06978     return offset;
06979 
06980   tmp.orig_address = offset;
06981   tmp.new_address = offset;
06982   tmp.size = 1;
06983 
06984   r = bsearch (&offset, map->entry, map->entry_count,
06985               sizeof (xlate_map_entry_t), &xlate_compare);
06986   e = (xlate_map_entry_t *) r;
06987   
06988   BFD_ASSERT (e != NULL);
06989   if (e == NULL)
06990     return offset;
06991   return e->new_address - e->orig_address + offset;
06992 }
06993 
06994 
06995 /* Build a binary searchable offset translation map from a section's
06996    action list.  */
06997 
06998 static xlate_map_t *
06999 build_xlate_map (asection *sec, xtensa_relax_info *relax_info)
07000 {
07001   xlate_map_t *map = (xlate_map_t *) bfd_malloc (sizeof (xlate_map_t));
07002   text_action_list *action_list = &relax_info->action_list;
07003   unsigned num_actions = 0;
07004   text_action *r;
07005   int removed;
07006   xlate_map_entry_t *current_entry;
07007 
07008   if (map == NULL)
07009     return NULL;
07010 
07011   num_actions = action_list_count (action_list);
07012   map->entry = (xlate_map_entry_t *) 
07013     bfd_malloc (sizeof (xlate_map_entry_t) * (num_actions + 1));
07014   if (map->entry == NULL)
07015     {
07016       free (map);
07017       return NULL;
07018     }
07019   map->entry_count = 0;
07020   
07021   removed = 0;
07022   current_entry = &map->entry[0];
07023 
07024   current_entry->orig_address = 0;
07025   current_entry->new_address = 0;
07026   current_entry->size = 0;
07027 
07028   for (r = action_list->head; r != NULL; r = r->next)
07029     {
07030       unsigned orig_size = 0;
07031       switch (r->action)
07032        {
07033        case ta_none:
07034        case ta_remove_insn:
07035        case ta_convert_longcall:
07036        case ta_remove_literal:
07037        case ta_add_literal:
07038          break;
07039        case ta_remove_longcall:
07040          orig_size = 6;
07041          break;
07042        case ta_narrow_insn:
07043          orig_size = 3;
07044          break;
07045        case ta_widen_insn:
07046          orig_size = 2;
07047          break;
07048        case ta_fill:
07049          break;
07050        }
07051       current_entry->size =
07052        r->offset + orig_size - current_entry->orig_address;
07053       if (current_entry->size != 0)
07054        {
07055          current_entry++;
07056          map->entry_count++;
07057        }
07058       current_entry->orig_address = r->offset + orig_size;
07059       removed += r->removed_bytes;
07060       current_entry->new_address = r->offset + orig_size - removed;
07061       current_entry->size = 0;
07062     }
07063 
07064   current_entry->size = (bfd_get_section_limit (sec->owner, sec)
07065                       - current_entry->orig_address);
07066   if (current_entry->size != 0)
07067     map->entry_count++;
07068 
07069   return map;
07070 }
07071 
07072 
07073 /* Free an offset translation map.  */
07074 
07075 static void 
07076 free_xlate_map (xlate_map_t *map)
07077 {
07078   if (map && map->entry)
07079     free (map->entry);
07080   if (map)
07081     free (map);
07082 }
07083 
07084 
07085 /* Use check_section_ebb_pcrels_fit to make sure that all of the
07086    relocations in a section will fit if a proposed set of actions
07087    are performed.  */
07088 
07089 static bfd_boolean
07090 check_section_ebb_pcrels_fit (bfd *abfd,
07091                            asection *sec,
07092                            bfd_byte *contents,
07093                            Elf_Internal_Rela *internal_relocs,
07094                            const ebb_constraint *constraint,
07095                            const xtensa_opcode *reloc_opcodes)
07096 {
07097   unsigned i, j;
07098   Elf_Internal_Rela *irel;
07099   xlate_map_t *xmap = NULL;
07100   bfd_boolean ok = TRUE;
07101   xtensa_relax_info *relax_info;
07102 
07103   relax_info = get_xtensa_relax_info (sec);
07104 
07105   if (relax_info && sec->reloc_count > 100)
07106     {
07107       xmap = build_xlate_map (sec, relax_info);
07108       /* NULL indicates out of memory, but the slow version
07109         can still be used.  */
07110     }
07111 
07112   for (i = 0; i < sec->reloc_count; i++)
07113     {
07114       r_reloc r_rel;
07115       bfd_vma orig_self_offset, orig_target_offset;
07116       bfd_vma self_offset, target_offset;
07117       int r_type;
07118       reloc_howto_type *howto;
07119       int self_removed_bytes, target_removed_bytes;
07120 
07121       irel = &internal_relocs[i];
07122       r_type = ELF32_R_TYPE (irel->r_info);
07123 
07124       howto = &elf_howto_table[r_type];
07125       /* We maintain the required invariant: PC-relative relocations
07126         that fit before linking must fit after linking.  Thus we only
07127         need to deal with relocations to the same section that are
07128         PC-relative.  */
07129       if (ELF32_R_TYPE (irel->r_info) == R_XTENSA_ASM_SIMPLIFY
07130          || !howto->pc_relative)
07131        continue;
07132 
07133       r_reloc_init (&r_rel, abfd, irel, contents,
07134                   bfd_get_section_limit (abfd, sec));
07135 
07136       if (r_reloc_get_section (&r_rel) != sec)
07137        continue;
07138 
07139       orig_self_offset = irel->r_offset;
07140       orig_target_offset = r_rel.target_offset;
07141 
07142       self_offset = orig_self_offset;
07143       target_offset = orig_target_offset;
07144 
07145       if (relax_info)
07146        {
07147          self_offset =
07148            xlate_offset_with_removed_text (xmap, &relax_info->action_list,
07149                                        orig_self_offset);
07150          target_offset =
07151            xlate_offset_with_removed_text (xmap, &relax_info->action_list,
07152                                        orig_target_offset);
07153        }
07154 
07155       self_removed_bytes = 0;
07156       target_removed_bytes = 0;
07157 
07158       for (j = 0; j < constraint->action_count; ++j)
07159        {
07160          proposed_action *action = &constraint->actions[j];
07161          bfd_vma offset = action->offset;
07162          int removed_bytes = action->removed_bytes;
07163          if (offset < orig_self_offset
07164              || (offset == orig_self_offset && action->action == ta_fill
07165                 && action->removed_bytes < 0))
07166            self_removed_bytes += removed_bytes;
07167          if (offset < orig_target_offset
07168              || (offset == orig_target_offset && action->action == ta_fill
07169                 && action->removed_bytes < 0))
07170            target_removed_bytes += removed_bytes;
07171        }
07172       self_offset -= self_removed_bytes;
07173       target_offset -= target_removed_bytes;
07174 
07175       /* Try to encode it.  Get the operand and check.  */
07176       if (is_alt_relocation (ELF32_R_TYPE (irel->r_info)))
07177        {
07178          /* None of the current alternate relocs are PC-relative,
07179             and only PC-relative relocs matter here.  */
07180        }
07181       else
07182        {
07183          xtensa_opcode opcode;
07184          int opnum;
07185 
07186          if (reloc_opcodes)
07187            opcode = reloc_opcodes[i];
07188          else
07189            opcode = get_relocation_opcode (abfd, sec, contents, irel);
07190          if (opcode == XTENSA_UNDEFINED)
07191            {
07192              ok = FALSE;
07193              break;
07194            }
07195 
07196          opnum = get_relocation_opnd (opcode, ELF32_R_TYPE (irel->r_info));
07197          if (opnum == XTENSA_UNDEFINED)
07198            {
07199              ok = FALSE;
07200              break;
07201            }
07202 
07203          if (!pcrel_reloc_fits (opcode, opnum, self_offset, target_offset))
07204            {
07205              ok = FALSE;
07206              break;
07207            }
07208        }
07209     }
07210 
07211   if (xmap)
07212     free_xlate_map (xmap);
07213 
07214   return ok;
07215 }
07216 
07217 
07218 static bfd_boolean
07219 check_section_ebb_reduces (const ebb_constraint *constraint)
07220 {
07221   int removed = 0;
07222   unsigned i;
07223 
07224   for (i = 0; i < constraint->action_count; i++)
07225     {
07226       const proposed_action *action = &constraint->actions[i];
07227       if (action->do_action)
07228        removed += action->removed_bytes;
07229     }
07230   if (removed < 0)
07231     return FALSE;
07232 
07233   return TRUE;
07234 }
07235 
07236 
07237 void
07238 text_action_add_proposed (text_action_list *l,
07239                        const ebb_constraint *ebb_table,
07240                        asection *sec)
07241 {
07242   unsigned i;
07243 
07244   for (i = 0; i < ebb_table->action_count; i++)
07245     {
07246       proposed_action *action = &ebb_table->actions[i];
07247 
07248       if (!action->do_action)
07249        continue;
07250       switch (action->action)
07251        {
07252        case ta_remove_insn:
07253        case ta_remove_longcall:
07254        case ta_convert_longcall:
07255        case ta_narrow_insn:
07256        case ta_widen_insn:
07257        case ta_fill:
07258        case ta_remove_literal:
07259          text_action_add (l, action->action, sec, action->offset,
07260                         action->removed_bytes);
07261          break;
07262        case ta_none:
07263          break;
07264        default:
07265          BFD_ASSERT (0);
07266          break;
07267        }
07268     }
07269 }
07270 
07271 
07272 int
07273 compute_fill_extra_space (property_table_entry *entry)
07274 {
07275   int fill_extra_space;
07276 
07277   if (!entry)
07278     return 0;
07279 
07280   if ((entry->flags & XTENSA_PROP_UNREACHABLE) == 0)
07281     return 0;
07282 
07283   fill_extra_space = entry->size;
07284   if ((entry->flags & XTENSA_PROP_ALIGN) != 0)
07285     {
07286       /* Fill bytes for alignment:
07287         (2**n)-1 - (addr + (2**n)-1) & (2**n -1) */
07288       int pow = GET_XTENSA_PROP_ALIGNMENT (entry->flags);
07289       int nsm = (1 << pow) - 1;
07290       bfd_vma addr = entry->address + entry->size;
07291       bfd_vma align_fill = nsm - ((addr + nsm) & nsm);
07292       fill_extra_space += align_fill;
07293     }
07294   return fill_extra_space;
07295 }
07296 
07297 
07298 /* First relaxation pass.  */
07299 
07300 /* If the section contains relaxable literals, check each literal to
07301    see if it has the same value as another literal that has already
07302    been seen, either in the current section or a previous one.  If so,
07303    add an entry to the per-section list of removed literals.  The
07304    actual changes are deferred until the next pass.  */
07305 
07306 static bfd_boolean 
07307 compute_removed_literals (bfd *abfd,
07308                        asection *sec,
07309                        struct bfd_link_info *link_info,
07310                        value_map_hash_table *values)
07311 {
07312   xtensa_relax_info *relax_info;
07313   bfd_byte *contents;
07314   Elf_Internal_Rela *internal_relocs;
07315   source_reloc *src_relocs, *rel;
07316   bfd_boolean ok = TRUE;
07317   property_table_entry *prop_table = NULL;
07318   int ptblsize;
07319   int i, prev_i;
07320   bfd_boolean last_loc_is_prev = FALSE;
07321   bfd_vma last_target_offset = 0;
07322   section_cache_t target_sec_cache;
07323   bfd_size_type sec_size;
07324 
07325   init_section_cache (&target_sec_cache);
07326 
07327   /* Do nothing if it is not a relaxable literal section.  */
07328   relax_info = get_xtensa_relax_info (sec);
07329   BFD_ASSERT (relax_info);
07330   if (!relax_info->is_relaxable_literal_section)
07331     return ok;
07332 
07333   internal_relocs = retrieve_internal_relocs (abfd, sec, 
07334                                          link_info->keep_memory);
07335 
07336   sec_size = bfd_get_section_limit (abfd, sec);
07337   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
07338   if (contents == NULL && sec_size != 0)
07339     {
07340       ok = FALSE;
07341       goto error_return;
07342     }
07343 
07344   /* Sort the source_relocs by target offset.  */
07345   src_relocs = relax_info->src_relocs;
07346   qsort (src_relocs, relax_info->src_count,
07347         sizeof (source_reloc), source_reloc_compare);
07348   qsort (internal_relocs, sec->reloc_count, sizeof (Elf_Internal_Rela),
07349         internal_reloc_compare);
07350 
07351   ptblsize = xtensa_read_table_entries (abfd, sec, &prop_table,
07352                                    XTENSA_PROP_SEC_NAME, FALSE);
07353   if (ptblsize < 0)
07354     {
07355       ok = FALSE;
07356       goto error_return;
07357     }
07358 
07359   prev_i = -1;
07360   for (i = 0; i < relax_info->src_count; i++)
07361     {
07362       Elf_Internal_Rela *irel = NULL;
07363 
07364       rel = &src_relocs[i];
07365       if (get_l32r_opcode () != rel->opcode)
07366        continue;
07367       irel = get_irel_at_offset (sec, internal_relocs,
07368                              rel->r_rel.target_offset);
07369 
07370       /* If the relocation on this is not a simple R_XTENSA_32 or
07371         R_XTENSA_PLT then do not consider it.  This may happen when
07372         the difference of two symbols is used in a literal.  */
07373       if (irel && (ELF32_R_TYPE (irel->r_info) != R_XTENSA_32
07374                  && ELF32_R_TYPE (irel->r_info) != R_XTENSA_PLT))
07375        continue;
07376 
07377       /* If the target_offset for this relocation is the same as the
07378         previous relocation, then we've already considered whether the
07379         literal can be coalesced.  Skip to the next one....  */
07380       if (i != 0 && prev_i != -1
07381          && src_relocs[i-1].r_rel.target_offset == rel->r_rel.target_offset)
07382        continue;
07383       prev_i = i;
07384 
07385       if (last_loc_is_prev && 
07386          last_target_offset + 4 != rel->r_rel.target_offset)
07387        last_loc_is_prev = FALSE;
07388 
07389       /* Check if the relocation was from an L32R that is being removed
07390         because a CALLX was converted to a direct CALL, and check if
07391         there are no other relocations to the literal.  */
07392       if (is_removable_literal (rel, i, src_relocs, relax_info->src_count))
07393        {
07394          if (!remove_dead_literal (abfd, sec, link_info, internal_relocs,
07395                                 irel, rel, prop_table, ptblsize))
07396            {
07397              ok = FALSE;
07398              goto error_return;
07399            }
07400          last_target_offset = rel->r_rel.target_offset;
07401          continue;
07402        }
07403 
07404       if (!identify_literal_placement (abfd, sec, contents, link_info,
07405                                    values, 
07406                                    &last_loc_is_prev, irel, 
07407                                    relax_info->src_count - i, rel,
07408                                    prop_table, ptblsize,
07409                                    &target_sec_cache, rel->is_abs_literal))
07410        {
07411          ok = FALSE;
07412          goto error_return;
07413        }
07414       last_target_offset = rel->r_rel.target_offset;
07415     }
07416 
07417 #if DEBUG
07418   print_removed_literals (stderr, &relax_info->removed_list);
07419   print_action_list (stderr, &relax_info->action_list);
07420 #endif /* DEBUG */
07421 
07422 error_return:
07423   if (prop_table) free (prop_table);
07424   clear_section_cache (&target_sec_cache);
07425 
07426   release_contents (sec, contents);
07427   release_internal_relocs (sec, internal_relocs);
07428   return ok;
07429 }
07430 
07431 
07432 static Elf_Internal_Rela *
07433 get_irel_at_offset (asection *sec,
07434                   Elf_Internal_Rela *internal_relocs,
07435                   bfd_vma offset)
07436 {
07437   unsigned i;
07438   Elf_Internal_Rela *irel;
07439   unsigned r_type;
07440   Elf_Internal_Rela key;
07441 
07442   if (!internal_relocs) 
07443     return NULL;
07444 
07445   key.r_offset = offset;
07446   irel = bsearch (&key, internal_relocs, sec->reloc_count,
07447                 sizeof (Elf_Internal_Rela), internal_reloc_matches);
07448   if (!irel)
07449     return NULL;
07450 
07451   /* bsearch does not guarantee which will be returned if there are
07452      multiple matches.  We need the first that is not an alignment.  */
07453   i = irel - internal_relocs;
07454   while (i > 0)
07455     {
07456       if (internal_relocs[i-1].r_offset != offset)
07457        break;
07458       i--;
07459     }
07460   for ( ; i < sec->reloc_count; i++)
07461     {
07462       irel = &internal_relocs[i];
07463       r_type = ELF32_R_TYPE (irel->r_info);
07464       if (irel->r_offset == offset && r_type != R_XTENSA_NONE)
07465        return irel;
07466     }
07467 
07468   return NULL;
07469 }
07470 
07471 
07472 bfd_boolean
07473 is_removable_literal (const source_reloc *rel,
07474                     int i,
07475                     const source_reloc *src_relocs,
07476                     int src_count)
07477 {
07478   const source_reloc *curr_rel;
07479   if (!rel->is_null)
07480     return FALSE;
07481   
07482   for (++i; i < src_count; ++i)
07483     {
07484       curr_rel = &src_relocs[i];
07485       /* If all others have the same target offset....  */
07486       if (curr_rel->r_rel.target_offset != rel->r_rel.target_offset)
07487        return TRUE;
07488 
07489       if (!curr_rel->is_null
07490          && !xtensa_is_property_section (curr_rel->source_sec)
07491          && !(curr_rel->source_sec->flags & SEC_DEBUGGING))
07492        return FALSE;
07493     }
07494   return TRUE;
07495 }
07496 
07497 
07498 bfd_boolean 
07499 remove_dead_literal (bfd *abfd,
07500                    asection *sec,
07501                    struct bfd_link_info *link_info,
07502                    Elf_Internal_Rela *internal_relocs,
07503                    Elf_Internal_Rela *irel,
07504                    source_reloc *rel,
07505                    property_table_entry *prop_table,
07506                    int ptblsize)
07507 {
07508   property_table_entry *entry;
07509   xtensa_relax_info *relax_info;
07510 
07511   relax_info = get_xtensa_relax_info (sec);
07512   if (!relax_info)
07513     return FALSE;
07514 
07515   entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
07516                                      sec->vma + rel->r_rel.target_offset);
07517 
07518   /* Mark the unused literal so that it will be removed.  */
07519   add_removed_literal (&relax_info->removed_list, &rel->r_rel, NULL);
07520 
07521   text_action_add (&relax_info->action_list,
07522                  ta_remove_literal, sec, rel->r_rel.target_offset, 4);
07523 
07524   /* If the section is 4-byte aligned, do not add fill.  */
07525   if (sec->alignment_power > 2) 
07526     {
07527       int fill_extra_space;
07528       bfd_vma entry_sec_offset;
07529       text_action *fa;
07530       property_table_entry *the_add_entry;
07531       int removed_diff;
07532 
07533       if (entry)
07534        entry_sec_offset = entry->address - sec->vma + entry->size;
07535       else
07536        entry_sec_offset = rel->r_rel.target_offset + 4;
07537 
07538       /* If the literal range is at the end of the section,
07539         do not add fill.  */
07540       the_add_entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
07541                                                 entry_sec_offset);
07542       fill_extra_space = compute_fill_extra_space (the_add_entry);
07543 
07544       fa = find_fill_action (&relax_info->action_list, sec, entry_sec_offset);
07545       removed_diff = compute_removed_action_diff (fa, sec, entry_sec_offset,
07546                                             -4, fill_extra_space);
07547       if (fa)
07548        adjust_fill_action (fa, removed_diff);
07549       else
07550        text_action_add (&relax_info->action_list,
07551                       ta_fill, sec, entry_sec_offset, removed_diff);
07552     }
07553 
07554   /* Zero out the relocation on this literal location.  */
07555   if (irel)
07556     {
07557       if (elf_hash_table (link_info)->dynamic_sections_created)
07558        shrink_dynamic_reloc_sections (link_info, abfd, sec, irel);
07559 
07560       irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
07561       pin_internal_relocs (sec, internal_relocs);
07562     }
07563 
07564   /* Do not modify "last_loc_is_prev".  */
07565   return TRUE;
07566 }
07567 
07568 
07569 bfd_boolean 
07570 identify_literal_placement (bfd *abfd,
07571                          asection *sec,
07572                          bfd_byte *contents,
07573                          struct bfd_link_info *link_info,
07574                          value_map_hash_table *values,
07575                          bfd_boolean *last_loc_is_prev_p,
07576                          Elf_Internal_Rela *irel,
07577                          int remaining_src_rels,
07578                          source_reloc *rel,
07579                          property_table_entry *prop_table,
07580                          int ptblsize,
07581                          section_cache_t *target_sec_cache,
07582                          bfd_boolean is_abs_literal)
07583 {
07584   literal_value val;
07585   value_map *val_map;
07586   xtensa_relax_info *relax_info;
07587   bfd_boolean literal_placed = FALSE;
07588   r_reloc r_rel;
07589   unsigned long value;
07590   bfd_boolean final_static_link;
07591   bfd_size_type sec_size;
07592 
07593   relax_info = get_xtensa_relax_info (sec);
07594   if (!relax_info)
07595     return FALSE;
07596 
07597   sec_size = bfd_get_section_limit (abfd, sec);
07598 
07599   final_static_link =
07600     (!link_info->relocatable
07601      && !elf_hash_table (link_info)->dynamic_sections_created);
07602 
07603   /* The placement algorithm first checks to see if the literal is
07604      already in the value map.  If so and the value map is reachable
07605      from all uses, then the literal is moved to that location.  If
07606      not, then we identify the last location where a fresh literal was
07607      placed.  If the literal can be safely moved there, then we do so.
07608      If not, then we assume that the literal is not to move and leave
07609      the literal where it is, marking it as the last literal
07610      location.  */
07611 
07612   /* Find the literal value.  */
07613   value = 0;
07614   r_reloc_init (&r_rel, abfd, irel, contents, sec_size);
07615   if (!irel)
07616     {
07617       BFD_ASSERT (rel->r_rel.target_offset < sec_size);
07618       value = bfd_get_32 (abfd, contents + rel->r_rel.target_offset);
07619     }
07620   init_literal_value (&val, &r_rel, value, is_abs_literal);
07621 
07622   /* Check if we've seen another literal with the same value that
07623      is in the same output section.  */
07624   val_map = value_map_get_cached_value (values, &val, final_static_link);
07625 
07626   if (val_map
07627       && (r_reloc_get_section (&val_map->loc)->output_section
07628          == sec->output_section)
07629       && relocations_reach (rel, remaining_src_rels, &val_map->loc)
07630       && coalesce_shared_literal (sec, rel, prop_table, ptblsize, val_map))
07631     {
07632       /* No change to last_loc_is_prev.  */
07633       literal_placed = TRUE;
07634     }
07635 
07636   /* For relocatable links, do not try to move literals.  To do it
07637      correctly might increase the number of relocations in an input
07638      section making the default relocatable linking fail.  */
07639   if (!link_info->relocatable && !literal_placed 
07640       && values->has_last_loc && !(*last_loc_is_prev_p))
07641     {
07642       asection *target_sec = r_reloc_get_section (&values->last_loc);
07643       if (target_sec && target_sec->output_section == sec->output_section)
07644        {
07645          /* Increment the virtual offset.  */
07646          r_reloc try_loc = values->last_loc;
07647          try_loc.virtual_offset += 4;
07648 
07649          /* There is a last loc that was in the same output section.  */
07650          if (relocations_reach (rel, remaining_src_rels, &try_loc)
07651              && move_shared_literal (sec, link_info, rel,
07652                                   prop_table, ptblsize, 
07653                                   &try_loc, &val, target_sec_cache))
07654            {
07655              values->last_loc.virtual_offset += 4;
07656              literal_placed = TRUE;
07657              if (!val_map)
07658               val_map = add_value_map (values, &val, &try_loc,
07659                                     final_static_link);
07660              else
07661               val_map->loc = try_loc;
07662            }
07663        }
07664     }
07665 
07666   if (!literal_placed)
07667     {
07668       /* Nothing worked, leave the literal alone but update the last loc.  */
07669       values->has_last_loc = TRUE;
07670       values->last_loc = rel->r_rel;
07671       if (!val_map)
07672        val_map = add_value_map (values, &val, &rel->r_rel, final_static_link);
07673       else
07674        val_map->loc = rel->r_rel;
07675       *last_loc_is_prev_p = TRUE;
07676     }
07677 
07678   return TRUE;
07679 }
07680 
07681 
07682 /* Check if the original relocations (presumably on L32R instructions)
07683    identified by reloc[0..N] can be changed to reference the literal
07684    identified by r_rel.  If r_rel is out of range for any of the
07685    original relocations, then we don't want to coalesce the original
07686    literal with the one at r_rel.  We only check reloc[0..N], where the
07687    offsets are all the same as for reloc[0] (i.e., they're all
07688    referencing the same literal) and where N is also bounded by the
07689    number of remaining entries in the "reloc" array.  The "reloc" array
07690    is sorted by target offset so we know all the entries for the same
07691    literal will be contiguous.  */
07692 
07693 static bfd_boolean
07694 relocations_reach (source_reloc *reloc,
07695                  int remaining_relocs,
07696                  const r_reloc *r_rel)
07697 {
07698   bfd_vma from_offset, source_address, dest_address;
07699   asection *sec;
07700   int i;
07701 
07702   if (!r_reloc_is_defined (r_rel))
07703     return FALSE;
07704 
07705   sec = r_reloc_get_section (r_rel);
07706   from_offset = reloc[0].r_rel.target_offset;
07707 
07708   for (i = 0; i < remaining_relocs; i++)
07709     {
07710       if (reloc[i].r_rel.target_offset != from_offset)
07711        break;
07712 
07713       /* Ignore relocations that have been removed.  */
07714       if (reloc[i].is_null)
07715        continue;
07716 
07717       /* The original and new output section for these must be the same
07718          in order to coalesce.  */
07719       if (r_reloc_get_section (&reloc[i].r_rel)->output_section
07720          != sec->output_section)
07721        return FALSE;
07722 
07723       /* Absolute literals in the same output section can always be
07724         combined.  */
07725       if (reloc[i].is_abs_literal)
07726        continue;
07727 
07728       /* A literal with no PC-relative relocations can be moved anywhere.  */
07729       if (reloc[i].opnd != -1)
07730        {
07731          /* Otherwise, check to see that it fits.  */
07732          source_address = (reloc[i].source_sec->output_section->vma
07733                          + reloc[i].source_sec->output_offset
07734                          + reloc[i].r_rel.rela.r_offset);
07735          dest_address = (sec->output_section->vma
07736                        + sec->output_offset
07737                        + r_rel->target_offset);
07738 
07739          if (!pcrel_reloc_fits (reloc[i].opcode, reloc[i].opnd,
07740                              source_address, dest_address))
07741            return FALSE;
07742        }
07743     }
07744 
07745   return TRUE;
07746 }
07747 
07748 
07749 /* Move a literal to another literal location because it is
07750    the same as the other literal value.  */
07751 
07752 static bfd_boolean 
07753 coalesce_shared_literal (asection *sec,
07754                       source_reloc *rel,
07755                       property_table_entry *prop_table,
07756                       int ptblsize,
07757                       value_map *val_map)
07758 {
07759   property_table_entry *entry;
07760   text_action *fa;
07761   property_table_entry *the_add_entry;
07762   int removed_diff;
07763   xtensa_relax_info *relax_info;
07764 
07765   relax_info = get_xtensa_relax_info (sec);
07766   if (!relax_info)
07767     return FALSE;
07768 
07769   entry = elf_xtensa_find_property_entry
07770     (prop_table, ptblsize, sec->vma + rel->r_rel.target_offset);
07771   if (entry && (entry->flags & XTENSA_PROP_INSN_NO_TRANSFORM))
07772     return TRUE;
07773 
07774   /* Mark that the literal will be coalesced.  */
07775   add_removed_literal (&relax_info->removed_list, &rel->r_rel, &val_map->loc);
07776 
07777   text_action_add (&relax_info->action_list,
07778                  ta_remove_literal, sec, rel->r_rel.target_offset, 4);
07779 
07780   /* If the section is 4-byte aligned, do not add fill.  */
07781   if (sec->alignment_power > 2) 
07782     {
07783       int fill_extra_space;
07784       bfd_vma entry_sec_offset;
07785 
07786       if (entry)
07787        entry_sec_offset = entry->address - sec->vma + entry->size;
07788       else
07789        entry_sec_offset = rel->r_rel.target_offset + 4;
07790 
07791       /* If the literal range is at the end of the section,
07792         do not add fill.  */
07793       fill_extra_space = 0;
07794       the_add_entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
07795                                                 entry_sec_offset);
07796       if (the_add_entry && (the_add_entry->flags & XTENSA_PROP_UNREACHABLE))
07797        fill_extra_space = the_add_entry->size;
07798 
07799       fa = find_fill_action (&relax_info->action_list, sec, entry_sec_offset);
07800       removed_diff = compute_removed_action_diff (fa, sec, entry_sec_offset,
07801                                             -4, fill_extra_space);
07802       if (fa)
07803        adjust_fill_action (fa, removed_diff);
07804       else
07805        text_action_add (&relax_info->action_list,
07806                       ta_fill, sec, entry_sec_offset, removed_diff);
07807     }
07808 
07809   return TRUE;
07810 }
07811 
07812 
07813 /* Move a literal to another location.  This may actually increase the
07814    total amount of space used because of alignments so we need to do
07815    this carefully.  Also, it may make a branch go out of range.  */
07816 
07817 static bfd_boolean 
07818 move_shared_literal (asection *sec,
07819                    struct bfd_link_info *link_info,
07820                    source_reloc *rel,
07821                    property_table_entry *prop_table,
07822                    int ptblsize,
07823                    const r_reloc *target_loc,
07824                    const literal_value *lit_value,
07825                    section_cache_t *target_sec_cache)
07826 {
07827   property_table_entry *the_add_entry, *src_entry, *target_entry = NULL;
07828   text_action *fa, *target_fa;
07829   int removed_diff;
07830   xtensa_relax_info *relax_info, *target_relax_info;
07831   asection *target_sec;
07832   ebb_t *ebb;
07833   ebb_constraint ebb_table;
07834   bfd_boolean relocs_fit;
07835 
07836   /* If this routine always returns FALSE, the literals that cannot be
07837      coalesced will not be moved.  */
07838   if (elf32xtensa_no_literal_movement)
07839     return FALSE;
07840 
07841   relax_info = get_xtensa_relax_info (sec);
07842   if (!relax_info)
07843     return FALSE;
07844 
07845   target_sec = r_reloc_get_section (target_loc);
07846   target_relax_info = get_xtensa_relax_info (target_sec);
07847 
07848   /* Literals to undefined sections may not be moved because they
07849      must report an error.  */
07850   if (bfd_is_und_section (target_sec))
07851     return FALSE;
07852 
07853   src_entry = elf_xtensa_find_property_entry
07854     (prop_table, ptblsize, sec->vma + rel->r_rel.target_offset);
07855 
07856   if (!section_cache_section (target_sec_cache, target_sec, link_info))
07857     return FALSE;
07858 
07859   target_entry = elf_xtensa_find_property_entry
07860     (target_sec_cache->ptbl, target_sec_cache->pte_count, 
07861      target_sec->vma + target_loc->target_offset);
07862 
07863   if (!target_entry)
07864     return FALSE;
07865 
07866   /* Make sure that we have not broken any branches.  */
07867   relocs_fit = FALSE;
07868 
07869   init_ebb_constraint (&ebb_table);
07870   ebb = &ebb_table.ebb;
07871   init_ebb (ebb, target_sec_cache->sec, target_sec_cache->contents, 
07872            target_sec_cache->content_length,
07873            target_sec_cache->ptbl, target_sec_cache->pte_count,
07874            target_sec_cache->relocs, target_sec_cache->reloc_count);
07875 
07876   /* Propose to add 4 bytes + worst-case alignment size increase to
07877      destination.  */
07878   ebb_propose_action (&ebb_table, EBB_NO_ALIGN, 0,
07879                     ta_fill, target_loc->target_offset,
07880                     -4 - (1 << target_sec->alignment_power), TRUE);
07881 
07882   /* Check all of the PC-relative relocations to make sure they still fit.  */
07883   relocs_fit = check_section_ebb_pcrels_fit (target_sec->owner, target_sec, 
07884                                         target_sec_cache->contents,
07885                                         target_sec_cache->relocs,
07886                                         &ebb_table, NULL);
07887 
07888   if (!relocs_fit) 
07889     return FALSE;
07890 
07891   text_action_add_literal (&target_relax_info->action_list,
07892                         ta_add_literal, target_loc, lit_value, -4);
07893 
07894   if (target_sec->alignment_power > 2 && target_entry != src_entry) 
07895     {
07896       /* May need to add or remove some fill to maintain alignment.  */
07897       int fill_extra_space;
07898       bfd_vma entry_sec_offset;
07899 
07900       entry_sec_offset = 
07901        target_entry->address - target_sec->vma + target_entry->size;
07902 
07903       /* If the literal range is at the end of the section,
07904         do not add fill.  */
07905       fill_extra_space = 0;
07906       the_add_entry =
07907        elf_xtensa_find_property_entry (target_sec_cache->ptbl,
07908                                    target_sec_cache->pte_count,
07909                                    entry_sec_offset);
07910       if (the_add_entry && (the_add_entry->flags & XTENSA_PROP_UNREACHABLE))
07911        fill_extra_space = the_add_entry->size;
07912 
07913       target_fa = find_fill_action (&target_relax_info->action_list,
07914                                 target_sec, entry_sec_offset);
07915       removed_diff = compute_removed_action_diff (target_fa, target_sec,
07916                                             entry_sec_offset, 4,
07917                                             fill_extra_space);
07918       if (target_fa)
07919        adjust_fill_action (target_fa, removed_diff);
07920       else
07921        text_action_add (&target_relax_info->action_list,
07922                       ta_fill, target_sec, entry_sec_offset, removed_diff);
07923     }
07924 
07925   /* Mark that the literal will be moved to the new location.  */
07926   add_removed_literal (&relax_info->removed_list, &rel->r_rel, target_loc);
07927 
07928   /* Remove the literal.  */
07929   text_action_add (&relax_info->action_list,
07930                  ta_remove_literal, sec, rel->r_rel.target_offset, 4);
07931 
07932   /* If the section is 4-byte aligned, do not add fill.  */
07933   if (sec->alignment_power > 2 && target_entry != src_entry) 
07934     {
07935       int fill_extra_space;
07936       bfd_vma entry_sec_offset;
07937 
07938       if (src_entry)
07939        entry_sec_offset = src_entry->address - sec->vma + src_entry->size;
07940       else
07941        entry_sec_offset = rel->r_rel.target_offset+4;
07942 
07943       /* If the literal range is at the end of the section,
07944         do not add fill.  */
07945       fill_extra_space = 0;
07946       the_add_entry = elf_xtensa_find_property_entry (prop_table, ptblsize,
07947                                                 entry_sec_offset);
07948       if (the_add_entry && (the_add_entry->flags & XTENSA_PROP_UNREACHABLE))
07949        fill_extra_space = the_add_entry->size;
07950 
07951       fa = find_fill_action (&relax_info->action_list, sec, entry_sec_offset);
07952       removed_diff = compute_removed_action_diff (fa, sec, entry_sec_offset,
07953                                             -4, fill_extra_space);
07954       if (fa)
07955        adjust_fill_action (fa, removed_diff);
07956       else
07957        text_action_add (&relax_info->action_list,
07958                       ta_fill, sec, entry_sec_offset, removed_diff);
07959     }
07960 
07961   return TRUE;
07962 }
07963 
07964 
07965 /* Second relaxation pass.  */
07966 
07967 /* Modify all of the relocations to point to the right spot, and if this
07968    is a relaxable section, delete the unwanted literals and fix the
07969    section size.  */
07970 
07971 bfd_boolean
07972 relax_section (bfd *abfd, asection *sec, struct bfd_link_info *link_info)
07973 {
07974   Elf_Internal_Rela *internal_relocs;
07975   xtensa_relax_info *relax_info;
07976   bfd_byte *contents;
07977   bfd_boolean ok = TRUE;
07978   unsigned i;
07979   bfd_boolean rv = FALSE;
07980   bfd_boolean virtual_action;
07981   bfd_size_type sec_size;
07982 
07983   sec_size = bfd_get_section_limit (abfd, sec);
07984   relax_info = get_xtensa_relax_info (sec);
07985   BFD_ASSERT (relax_info);
07986 
07987   /* First translate any of the fixes that have been added already.  */
07988   translate_section_fixes (sec);
07989 
07990   /* Handle property sections (e.g., literal tables) specially.  */
07991   if (xtensa_is_property_section (sec))
07992     {
07993       BFD_ASSERT (!relax_info->is_relaxable_literal_section);
07994       return relax_property_section (abfd, sec, link_info);
07995     }
07996 
07997   internal_relocs = retrieve_internal_relocs (abfd, sec, 
07998                                          link_info->keep_memory);
07999   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
08000   if (contents == NULL && sec_size != 0)
08001     {
08002       ok = FALSE;
08003       goto error_return;
08004     }
08005 
08006   if (internal_relocs)
08007     {
08008       for (i = 0; i < sec->reloc_count; i++)
08009        {
08010          Elf_Internal_Rela *irel;
08011          xtensa_relax_info *target_relax_info;
08012          bfd_vma source_offset, old_source_offset;
08013          r_reloc r_rel;
08014          unsigned r_type;
08015          asection *target_sec;
08016 
08017          /* Locally change the source address.
08018             Translate the target to the new target address.
08019             If it points to this section and has been removed,
08020             NULLify it.
08021             Write it back.  */
08022 
08023          irel = &internal_relocs[i];
08024          source_offset = irel->r_offset;
08025          old_source_offset = source_offset;
08026 
08027          r_type = ELF32_R_TYPE (irel->r_info);
08028          r_reloc_init (&r_rel, abfd, irel, contents,
08029                      bfd_get_section_limit (abfd, sec));
08030 
08031          /* If this section could have changed then we may need to
08032             change the relocation's offset.  */
08033 
08034          if (relax_info->is_relaxable_literal_section
08035              || relax_info->is_relaxable_asm_section)
08036            {
08037              if (r_type != R_XTENSA_NONE
08038                 && find_removed_literal (&relax_info->removed_list,
08039                                       irel->r_offset))
08040               {
08041                 /* Remove this relocation.  */
08042                 if (elf_hash_table (link_info)->dynamic_sections_created)
08043                   shrink_dynamic_reloc_sections (link_info, abfd, sec, irel);
08044                 irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
08045                 irel->r_offset = offset_with_removed_text
08046                   (&relax_info->action_list, irel->r_offset);
08047                 pin_internal_relocs (sec, internal_relocs);
08048                 continue;
08049               }
08050 
08051              if (r_type == R_XTENSA_ASM_SIMPLIFY)
08052               {
08053                 text_action *action =
08054                   find_insn_action (&relax_info->action_list,
08055                                   irel->r_offset);
08056                 if (action && (action->action == ta_convert_longcall
08057                              || action->action == ta_remove_longcall))
08058                   {
08059                     bfd_reloc_status_type retval;
08060                     char *error_message = NULL;
08061 
08062                     retval = contract_asm_expansion (contents, sec_size,
08063                                                  irel, &error_message);
08064                     if (retval != bfd_reloc_ok)
08065                      {
08066                        (*link_info->callbacks->reloc_dangerous)
08067                          (link_info, error_message, abfd, sec,
08068                           irel->r_offset);
08069                        goto error_return;
08070                      }
08071                     /* Update the action so that the code that moves
08072                       the contents will do the right thing.  */
08073                     if (action->action == ta_remove_longcall)
08074                      action->action = ta_remove_insn;
08075                     else
08076                      action->action = ta_none;
08077                     /* Refresh the info in the r_rel.  */
08078                     r_reloc_init (&r_rel, abfd, irel, contents, sec_size);
08079                     r_type = ELF32_R_TYPE (irel->r_info);
08080                   }
08081               }
08082 
08083              source_offset = offset_with_removed_text
08084               (&relax_info->action_list, irel->r_offset);
08085              irel->r_offset = source_offset;
08086            }
08087 
08088          /* If the target section could have changed then
08089             we may need to change the relocation's target offset.  */
08090 
08091          target_sec = r_reloc_get_section (&r_rel);
08092          target_relax_info = get_xtensa_relax_info (target_sec);
08093 
08094          if (target_relax_info
08095              && (target_relax_info->is_relaxable_literal_section
08096                 || target_relax_info->is_relaxable_asm_section))
08097            {
08098              r_reloc new_reloc;
08099              reloc_bfd_fix *fix;
08100              bfd_vma addend_displacement;
08101 
08102              translate_reloc (&r_rel, &new_reloc);
08103 
08104              if (r_type == R_XTENSA_DIFF8
08105                 || r_type == R_XTENSA_DIFF16
08106                 || r_type == R_XTENSA_DIFF32)
08107               {
08108                 bfd_vma diff_value = 0, new_end_offset, diff_mask = 0;
08109 
08110                 if (bfd_get_section_limit (abfd, sec) < old_source_offset)
08111                   {
08112                     (*link_info->callbacks->reloc_dangerous)
08113                      (link_info, _("invalid relocation address"),
08114                       abfd, sec, old_source_offset);
08115                     goto error_return;
08116                   }
08117 
08118                 switch (r_type)
08119                   {
08120                   case R_XTENSA_DIFF8:
08121                     diff_value =
08122                      bfd_get_8 (abfd, &contents[old_source_offset]);
08123                     break;
08124                   case R_XTENSA_DIFF16:
08125                     diff_value =
08126                      bfd_get_16 (abfd, &contents[old_source_offset]);
08127                     break;
08128                   case R_XTENSA_DIFF32:
08129                     diff_value =
08130                      bfd_get_32 (abfd, &contents[old_source_offset]);
08131                     break;
08132                   }
08133 
08134                 new_end_offset = offset_with_removed_text
08135                   (&target_relax_info->action_list,
08136                    r_rel.target_offset + diff_value);
08137                 diff_value = new_end_offset - new_reloc.target_offset;
08138 
08139                 switch (r_type)
08140                   {
08141                   case R_XTENSA_DIFF8:
08142                     diff_mask = 0xff;
08143                     bfd_put_8 (abfd, diff_value,
08144                              &contents[old_source_offset]);
08145                     break;
08146                   case R_XTENSA_DIFF16:
08147                     diff_mask = 0xffff;
08148                     bfd_put_16 (abfd, diff_value,
08149                               &contents[old_source_offset]);
08150                     break;
08151                   case R_XTENSA_DIFF32:
08152                     diff_mask = 0xffffffff;
08153                     bfd_put_32 (abfd, diff_value,
08154                               &contents[old_source_offset]);
08155                     break;
08156                   }
08157 
08158                 /* Check for overflow.  */
08159                 if ((diff_value & ~diff_mask) != 0)
08160                   {
08161                     (*link_info->callbacks->reloc_dangerous)
08162                      (link_info, _("overflow after relaxation"),
08163                       abfd, sec, old_source_offset);
08164                     goto error_return;
08165                   }
08166 
08167                 pin_contents (sec, contents);
08168               }
08169 
08170              /* FIXME: If the relocation still references a section in
08171                the same input file, the relocation should be modified
08172                directly instead of adding a "fix" record.  */
08173 
08174              addend_displacement =
08175               new_reloc.target_offset + new_reloc.virtual_offset;
08176 
08177              fix = reloc_bfd_fix_init (sec, source_offset, r_type, 0,
08178                                    r_reloc_get_section (&new_reloc),
08179                                    addend_displacement, TRUE);
08180              add_fix (sec, fix);
08181            }
08182 
08183          pin_internal_relocs (sec, internal_relocs);
08184        }
08185     }
08186 
08187   if ((relax_info->is_relaxable_literal_section
08188        || relax_info->is_relaxable_asm_section)
08189       && relax_info->action_list.head)
08190     {
08191       /* Walk through the planned actions and build up a table
08192         of move, copy and fill records.  Use the move, copy and
08193         fill records to perform the actions once.  */
08194 
08195       bfd_size_type size = sec->size;
08196       int removed = 0;
08197       bfd_size_type final_size, copy_size, orig_insn_size;
08198       bfd_byte *scratch = NULL;
08199       bfd_byte *dup_contents = NULL;
08200       bfd_size_type orig_size = size;
08201       bfd_vma orig_dot = 0;
08202       bfd_vma orig_dot_copied = 0; /* Byte copied already from
08203                                        orig dot in physical memory.  */
08204       bfd_vma orig_dot_vo = 0; /* Virtual offset from orig_dot.  */
08205       bfd_vma dup_dot = 0;
08206 
08207       text_action *action = relax_info->action_list.head;
08208 
08209       final_size = sec->size;
08210       for (action = relax_info->action_list.head; action;
08211           action = action->next)
08212        {
08213          final_size -= action->removed_bytes;
08214        }
08215 
08216       scratch = (bfd_byte *) bfd_zmalloc (final_size);
08217       dup_contents = (bfd_byte *) bfd_zmalloc (final_size);
08218 
08219       /* The dot is the current fill location.  */
08220 #if DEBUG
08221       print_action_list (stderr, &relax_info->action_list);
08222 #endif
08223 
08224       for (action = relax_info->action_list.head; action;
08225           action = action->next)
08226        {
08227          virtual_action = FALSE;
08228          if (action->offset > orig_dot)
08229            {
08230              orig_dot += orig_dot_copied;
08231              orig_dot_copied = 0;
08232              orig_dot_vo = 0;
08233              /* Out of the virtual world.  */
08234            }
08235 
08236          if (action->offset > orig_dot)
08237            {
08238              copy_size = action->offset - orig_dot;
08239              memmove (&dup_contents[dup_dot], &contents[orig_dot], copy_size);
08240              orig_dot += copy_size;
08241              dup_dot += copy_size;
08242              BFD_ASSERT (action->offset == orig_dot);
08243            }
08244          else if (action->offset < orig_dot)
08245            {
08246              if (action->action == ta_fill
08247                 && action->offset - action->removed_bytes == orig_dot)
08248               {
08249                 /* This is OK because the fill only effects the dup_dot.  */
08250               }
08251              else if (action->action == ta_add_literal)
08252               {
08253                 /* TBD.  Might need to handle this.  */
08254               }
08255            }
08256          if (action->offset == orig_dot)
08257            {
08258              if (action->virtual_offset > orig_dot_vo)
08259               {
08260                 if (orig_dot_vo == 0)
08261                   {
08262                     /* Need to copy virtual_offset bytes.  Probably four.  */
08263                     copy_size = action->virtual_offset - orig_dot_vo;
08264                     memmove (&dup_contents[dup_dot],
08265                             &contents[orig_dot], copy_size);
08266                     orig_dot_copied = copy_size;
08267                     dup_dot += copy_size;
08268                   }
08269                 virtual_action = TRUE;
08270               } 
08271              else
08272               BFD_ASSERT (action->virtual_offset <= orig_dot_vo);
08273            }
08274          switch (action->action)
08275            {
08276            case ta_remove_literal:
08277            case ta_remove_insn:
08278              BFD_ASSERT (action->removed_bytes >= 0);
08279              orig_dot += action->removed_bytes;
08280              break;
08281 
08282            case ta_narrow_insn:
08283              orig_insn_size = 3;
08284              copy_size = 2;
08285              memmove (scratch, &contents[orig_dot], orig_insn_size);
08286              BFD_ASSERT (action->removed_bytes == 1);
08287              rv = narrow_instruction (scratch, final_size, 0);
08288              BFD_ASSERT (rv);
08289              memmove (&dup_contents[dup_dot], scratch, copy_size);
08290              orig_dot += orig_insn_size;
08291              dup_dot += copy_size;
08292              break;
08293 
08294            case ta_fill:
08295              if (action->removed_bytes >= 0)
08296               orig_dot += action->removed_bytes;
08297              else
08298               {
08299                 /* Already zeroed in dup_contents.  Just bump the
08300                    counters.  */
08301                 dup_dot += (-action->removed_bytes);
08302               }
08303              break;
08304 
08305            case ta_none:
08306              BFD_ASSERT (action->removed_bytes == 0);
08307              break;
08308 
08309            case ta_convert_longcall:
08310            case ta_remove_longcall:
08311              /* These will be removed or converted before we get here.  */
08312              BFD_ASSERT (0);
08313              break;
08314 
08315            case ta_widen_insn:
08316              orig_insn_size = 2;
08317              copy_size = 3;
08318              memmove (scratch, &contents[orig_dot], orig_insn_size);
08319              BFD_ASSERT (action->removed_bytes == -1);
08320              rv = widen_instruction (scratch, final_size, 0);
08321              BFD_ASSERT (rv);
08322              memmove (&dup_contents[dup_dot], scratch, copy_size);
08323              orig_dot += orig_insn_size;
08324              dup_dot += copy_size;
08325              break;
08326 
08327            case ta_add_literal:
08328              orig_insn_size = 0;
08329              copy_size = 4;
08330              BFD_ASSERT (action->removed_bytes == -4);
08331              /* TBD -- place the literal value here and insert
08332                into the table.  */
08333              memset (&dup_contents[dup_dot], 0, 4);
08334              pin_internal_relocs (sec, internal_relocs);
08335              pin_contents (sec, contents);
08336 
08337              if (!move_literal (abfd, link_info, sec, dup_dot, dup_contents,
08338                              relax_info, &internal_relocs, &action->value))
08339               goto error_return;
08340 
08341              if (virtual_action) 
08342               orig_dot_vo += copy_size;
08343 
08344              orig_dot += orig_insn_size;
08345              dup_dot += copy_size;
08346              break;
08347 
08348            default:
08349              /* Not implemented yet.  */
08350              BFD_ASSERT (0);
08351              break;
08352            }
08353 
08354          size -= action->removed_bytes;
08355          removed += action->removed_bytes;
08356          BFD_ASSERT (dup_dot <= final_size);
08357          BFD_ASSERT (orig_dot <= orig_size);
08358        }
08359 
08360       orig_dot += orig_dot_copied;
08361       orig_dot_copied = 0;
08362 
08363       if (orig_dot != orig_size)
08364        {
08365          copy_size = orig_size - orig_dot;
08366          BFD_ASSERT (orig_size > orig_dot);
08367          BFD_ASSERT (dup_dot + copy_size == final_size);
08368          memmove (&dup_contents[dup_dot], &contents[orig_dot], copy_size);
08369          orig_dot += copy_size;
08370          dup_dot += copy_size;
08371        }
08372       BFD_ASSERT (orig_size == orig_dot);
08373       BFD_ASSERT (final_size == dup_dot);
08374 
08375       /* Move the dup_contents back.  */
08376       if (final_size > orig_size)
08377        {
08378          /* Contents need to be reallocated.  Swap the dup_contents into
08379             contents.  */
08380          sec->contents = dup_contents;
08381          free (contents);
08382          contents = dup_contents;
08383          pin_contents (sec, contents);
08384        }
08385       else
08386        {
08387          BFD_ASSERT (final_size <= orig_size);
08388          memset (contents, 0, orig_size);
08389          memcpy (contents, dup_contents, final_size);
08390          free (dup_contents);
08391        }
08392       free (scratch);
08393       pin_contents (sec, contents);
08394 
08395       sec->size = final_size;
08396     }
08397 
08398  error_return:
08399   release_internal_relocs (sec, internal_relocs);
08400   release_contents (sec, contents);
08401   return ok;
08402 }
08403 
08404 
08405 static bfd_boolean 
08406 translate_section_fixes (asection *sec)
08407 {
08408   xtensa_relax_info *relax_info;
08409   reloc_bfd_fix *r;
08410 
08411   relax_info = get_xtensa_relax_info (sec);
08412   if (!relax_info)
08413     return TRUE;
08414 
08415   for (r = relax_info->fix_list; r != NULL; r = r->next)
08416     if (!translate_reloc_bfd_fix (r))
08417       return FALSE;
08418 
08419   return TRUE;
08420 }
08421 
08422 
08423 /* Translate a fix given the mapping in the relax info for the target
08424    section.  If it has already been translated, no work is required.  */
08425 
08426 static bfd_boolean 
08427 translate_reloc_bfd_fix (reloc_bfd_fix *fix)
08428 {
08429   reloc_bfd_fix new_fix;
08430   asection *sec;
08431   xtensa_relax_info *relax_info;
08432   removed_literal *removed;
08433   bfd_vma new_offset, target_offset;
08434 
08435   if (fix->translated)
08436     return TRUE;
08437 
08438   sec = fix->target_sec;
08439   target_offset = fix->target_offset;
08440 
08441   relax_info = get_xtensa_relax_info (sec);
08442   if (!relax_info)
08443     {
08444       fix->translated = TRUE;
08445       return TRUE;
08446     }
08447 
08448   new_fix = *fix;
08449 
08450   /* The fix does not need to be translated if the section cannot change.  */
08451   if (!relax_info->is_relaxable_literal_section
08452       && !relax_info->is_relaxable_asm_section)
08453     {
08454       fix->translated = TRUE;
08455       return TRUE;
08456     }
08457 
08458   /* If the literal has been moved and this relocation was on an
08459      opcode, then the relocation should move to the new literal
08460      location.  Otherwise, the relocation should move within the
08461      section.  */
08462 
08463   removed = FALSE;
08464   if (is_operand_relocation (fix->src_type))
08465     {
08466       /* Check if the original relocation is against a literal being
08467         removed.  */
08468       removed = find_removed_literal (&relax_info->removed_list,
08469                                   target_offset);
08470     }
08471 
08472   if (removed) 
08473     {
08474       asection *new_sec;
08475 
08476       /* The fact that there is still a relocation to this literal indicates
08477         that the literal is being coalesced, not simply removed.  */
08478       BFD_ASSERT (removed->to.abfd != NULL);
08479 
08480       /* This was moved to some other address (possibly another section).  */
08481       new_sec = r_reloc_get_section (&removed->to);
08482       if (new_sec != sec) 
08483        {
08484          sec = new_sec;
08485          relax_info = get_xtensa_relax_info (sec);
08486          if (!relax_info || 
08487              (!relax_info->is_relaxable_literal_section
08488               && !relax_info->is_relaxable_asm_section))
08489            {
08490              target_offset = removed->to.target_offset;
08491              new_fix.target_sec = new_sec;
08492              new_fix.target_offset = target_offset;
08493              new_fix.translated = TRUE;
08494              *fix = new_fix;
08495              return TRUE;
08496            }
08497        }
08498       target_offset = removed->to.target_offset;
08499       new_fix.target_sec = new_sec;
08500     }
08501 
08502   /* The target address may have been moved within its section.  */
08503   new_offset = offset_with_removed_text (&relax_info->action_list,
08504                                     target_offset);
08505 
08506   new_fix.target_offset = new_offset;
08507   new_fix.target_offset = new_offset;
08508   new_fix.translated = TRUE;
08509   *fix = new_fix;
08510   return TRUE;
08511 }
08512 
08513 
08514 /* Fix up a relocation to take account of removed literals.  */
08515 
08516 static void
08517 translate_reloc (const r_reloc *orig_rel, r_reloc *new_rel)
08518 {
08519   asection *sec;
08520   xtensa_relax_info *relax_info;
08521   removed_literal *removed;
08522   bfd_vma new_offset, target_offset, removed_bytes;
08523 
08524   *new_rel = *orig_rel;
08525 
08526   if (!r_reloc_is_defined (orig_rel))
08527     return;
08528   sec = r_reloc_get_section (orig_rel);
08529 
08530   relax_info = get_xtensa_relax_info (sec);
08531   BFD_ASSERT (relax_info);
08532 
08533   if (!relax_info->is_relaxable_literal_section
08534       && !relax_info->is_relaxable_asm_section)
08535     return;
08536 
08537   target_offset = orig_rel->target_offset;
08538 
08539   removed = FALSE;
08540   if (is_operand_relocation (ELF32_R_TYPE (orig_rel->rela.r_info)))
08541     {
08542       /* Check if the original relocation is against a literal being
08543         removed.  */
08544       removed = find_removed_literal (&relax_info->removed_list,
08545                                   target_offset);
08546     }
08547   if (removed && removed->to.abfd)
08548     {
08549       asection *new_sec;
08550 
08551       /* The fact that there is still a relocation to this literal indicates
08552         that the literal is being coalesced, not simply removed.  */
08553       BFD_ASSERT (removed->to.abfd != NULL);
08554 
08555       /* This was moved to some other address
08556         (possibly in another section).  */
08557       *new_rel = removed->to;
08558       new_sec = r_reloc_get_section (new_rel);
08559       if (new_sec != sec)
08560        {
08561          sec = new_sec;
08562          relax_info = get_xtensa_relax_info (sec);
08563          if (!relax_info
08564              || (!relax_info->is_relaxable_literal_section
08565                 && !relax_info->is_relaxable_asm_section))
08566            return;
08567        }
08568       target_offset = new_rel->target_offset;
08569     }
08570 
08571   /* ...and the target address may have been moved within its section.  */
08572   new_offset = offset_with_removed_text (&relax_info->action_list,
08573                                     target_offset);
08574 
08575   /* Modify the offset and addend.  */
08576   removed_bytes = target_offset - new_offset;
08577   new_rel->target_offset = new_offset;
08578   new_rel->rela.r_addend -= removed_bytes;
08579 }
08580 
08581 
08582 /* For dynamic links, there may be a dynamic relocation for each
08583    literal.  The number of dynamic relocations must be computed in
08584    size_dynamic_sections, which occurs before relaxation.  When a
08585    literal is removed, this function checks if there is a corresponding
08586    dynamic relocation and shrinks the size of the appropriate dynamic
08587    relocation section accordingly.  At this point, the contents of the
08588    dynamic relocation sections have not yet been filled in, so there's
08589    nothing else that needs to be done.  */
08590 
08591 static void
08592 shrink_dynamic_reloc_sections (struct bfd_link_info *info,
08593                             bfd *abfd,
08594                             asection *input_section,
08595                             Elf_Internal_Rela *rel)
08596 {
08597   struct elf_xtensa_link_hash_table *htab;
08598   Elf_Internal_Shdr *symtab_hdr;
08599   struct elf_link_hash_entry **sym_hashes;
08600   unsigned long r_symndx;
08601   int r_type;
08602   struct elf_link_hash_entry *h;
08603   bfd_boolean dynamic_symbol;
08604 
08605   htab = elf_xtensa_hash_table (info);
08606   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
08607   sym_hashes = elf_sym_hashes (abfd);
08608 
08609   r_type = ELF32_R_TYPE (rel->r_info);
08610   r_symndx = ELF32_R_SYM (rel->r_info);
08611 
08612   if (r_symndx < symtab_hdr->sh_info)
08613     h = NULL;
08614   else
08615     h = sym_hashes[r_symndx - symtab_hdr->sh_info];
08616 
08617   dynamic_symbol = elf_xtensa_dynamic_symbol_p (h, info);
08618 
08619   if ((r_type == R_XTENSA_32 || r_type == R_XTENSA_PLT)
08620       && (input_section->flags & SEC_ALLOC) != 0
08621       && (dynamic_symbol || info->shared))
08622     {
08623       asection *srel;
08624       bfd_boolean is_plt = FALSE;
08625 
08626       if (dynamic_symbol && r_type == R_XTENSA_PLT)
08627        {
08628          srel = htab->srelplt;
08629          is_plt = TRUE;
08630        }
08631       else
08632        srel = htab->srelgot;
08633 
08634       /* Reduce size of the .rela.* section by one reloc.  */
08635       BFD_ASSERT (srel != NULL);
08636       BFD_ASSERT (srel->size >= sizeof (Elf32_External_Rela));
08637       srel->size -= sizeof (Elf32_External_Rela);
08638 
08639       if (is_plt)
08640        {
08641          asection *splt, *sgotplt, *srelgot;
08642          int reloc_index, chunk;
08643 
08644          /* Find the PLT reloc index of the entry being removed.  This
08645             is computed from the size of ".rela.plt".  It is needed to
08646             figure out which PLT chunk to resize.  Usually "last index
08647             = size - 1" since the index starts at zero, but in this
08648             context, the size has just been decremented so there's no
08649             need to subtract one.  */
08650          reloc_index = srel->size / sizeof (Elf32_External_Rela);
08651 
08652          chunk = reloc_index / PLT_ENTRIES_PER_CHUNK;
08653          splt = elf_xtensa_get_plt_section (info, chunk);
08654          sgotplt = elf_xtensa_get_gotplt_section (info, chunk);
08655          BFD_ASSERT (splt != NULL && sgotplt != NULL);
08656 
08657          /* Check if an entire PLT chunk has just been eliminated.  */
08658          if (reloc_index % PLT_ENTRIES_PER_CHUNK == 0)
08659            {
08660              /* The two magic GOT entries for that chunk can go away.  */
08661              srelgot = htab->srelgot;
08662              BFD_ASSERT (srelgot != NULL);
08663              srelgot->reloc_count -= 2;
08664              srelgot->size -= 2 * sizeof (Elf32_External_Rela);
08665              sgotplt->size -= 8;
08666 
08667              /* There should be only one entry left (and it will be
08668                removed below).  */
08669              BFD_ASSERT (sgotplt->size == 4);
08670              BFD_ASSERT (splt->size == PLT_ENTRY_SIZE);
08671            }
08672 
08673          BFD_ASSERT (sgotplt->size >= 4);
08674          BFD_ASSERT (splt->size >= PLT_ENTRY_SIZE);
08675 
08676          sgotplt->size -= 4;
08677          splt->size -= PLT_ENTRY_SIZE;
08678        }
08679     }
08680 }
08681 
08682 
08683 /* Take an r_rel and move it to another section.  This usually
08684    requires extending the interal_relocation array and pinning it.  If
08685    the original r_rel is from the same BFD, we can complete this here.
08686    Otherwise, we add a fix record to let the final link fix the
08687    appropriate address.  Contents and internal relocations for the
08688    section must be pinned after calling this routine.  */
08689 
08690 static bfd_boolean
08691 move_literal (bfd *abfd,
08692              struct bfd_link_info *link_info,
08693              asection *sec,
08694              bfd_vma offset,
08695              bfd_byte *contents,
08696              xtensa_relax_info *relax_info,
08697              Elf_Internal_Rela **internal_relocs_p,
08698              const literal_value *lit)
08699 {
08700   Elf_Internal_Rela *new_relocs = NULL;
08701   size_t new_relocs_count = 0;
08702   Elf_Internal_Rela this_rela;
08703   const r_reloc *r_rel;
08704 
08705   r_rel = &lit->r_rel;
08706   BFD_ASSERT (elf_section_data (sec)->relocs == *internal_relocs_p);
08707 
08708   if (r_reloc_is_const (r_rel))
08709     bfd_put_32 (abfd, lit->value, contents + offset);
08710   else
08711     {
08712       int r_type;
08713       unsigned i;
08714       asection *target_sec;
08715       reloc_bfd_fix *fix;
08716       unsigned insert_at;
08717 
08718       r_type = ELF32_R_TYPE (r_rel->rela.r_info);
08719       target_sec = r_reloc_get_section (r_rel);
08720 
08721       /* This is the difficult case.  We have to create a fix up.  */
08722       this_rela.r_offset = offset;
08723       this_rela.r_info = ELF32_R_INFO (0, r_type);
08724       this_rela.r_addend =
08725        r_rel->target_offset - r_reloc_get_target_offset (r_rel);
08726       bfd_put_32 (abfd, lit->value, contents + offset);
08727 
08728       /* Currently, we cannot move relocations during a relocatable link.  */
08729       BFD_ASSERT (!link_info->relocatable);
08730       fix = reloc_bfd_fix_init (sec, offset, r_type, r_rel->abfd,
08731                             r_reloc_get_section (r_rel),
08732                             r_rel->target_offset + r_rel->virtual_offset,
08733                             FALSE);
08734       /* We also need to mark that relocations are needed here.  */
08735       sec->flags |= SEC_RELOC;
08736 
08737       translate_reloc_bfd_fix (fix);
08738       /* This fix has not yet been translated.  */
08739       add_fix (sec, fix);
08740 
08741       /* Add the relocation.  If we have already allocated our own
08742         space for the relocations and we have room for more, then use
08743         it.  Otherwise, allocate new space and move the literals.  */
08744       insert_at = sec->reloc_count;
08745       for (i = 0; i < sec->reloc_count; ++i)
08746        {
08747          if (this_rela.r_offset < (*internal_relocs_p)[i].r_offset)
08748            {
08749              insert_at = i;
08750              break;
08751            }
08752        }
08753 
08754       if (*internal_relocs_p != relax_info->allocated_relocs
08755          || sec->reloc_count + 1 > relax_info->allocated_relocs_count)
08756        {
08757          BFD_ASSERT (relax_info->allocated_relocs == NULL
08758                     || sec->reloc_count == relax_info->relocs_count);
08759 
08760          if (relax_info->allocated_relocs_count == 0) 
08761            new_relocs_count = (sec->reloc_count + 2) * 2;
08762          else
08763            new_relocs_count = (relax_info->allocated_relocs_count + 2) * 2;
08764 
08765          new_relocs = (Elf_Internal_Rela *)
08766            bfd_zmalloc (sizeof (Elf_Internal_Rela) * (new_relocs_count));
08767          if (!new_relocs)
08768            return FALSE;
08769 
08770          /* We could handle this more quickly by finding the split point.  */
08771          if (insert_at != 0)
08772            memcpy (new_relocs, *internal_relocs_p,
08773                   insert_at * sizeof (Elf_Internal_Rela));
08774 
08775          new_relocs[insert_at] = this_rela;
08776 
08777          if (insert_at != sec->reloc_count)
08778            memcpy (new_relocs + insert_at + 1,
08779                   (*internal_relocs_p) + insert_at,
08780                   (sec->reloc_count - insert_at) 
08781                   * sizeof (Elf_Internal_Rela));
08782 
08783          if (*internal_relocs_p != relax_info->allocated_relocs)
08784            {
08785              /* The first time we re-allocate, we can only free the
08786                old relocs if they were allocated with bfd_malloc.
08787                This is not true when keep_memory is in effect.  */
08788              if (!link_info->keep_memory)
08789               free (*internal_relocs_p);
08790            }
08791          else
08792            free (*internal_relocs_p);
08793          relax_info->allocated_relocs = new_relocs;
08794          relax_info->allocated_relocs_count = new_relocs_count;
08795          elf_section_data (sec)->relocs = new_relocs;
08796          sec->reloc_count++;
08797          relax_info->relocs_count = sec->reloc_count;
08798          *internal_relocs_p = new_relocs;
08799        }
08800       else
08801        {
08802          if (insert_at != sec->reloc_count)
08803            {
08804              unsigned idx;
08805              for (idx = sec->reloc_count; idx > insert_at; idx--)
08806               (*internal_relocs_p)[idx] = (*internal_relocs_p)[idx-1];
08807            }
08808          (*internal_relocs_p)[insert_at] = this_rela;
08809          sec->reloc_count++;
08810          if (relax_info->allocated_relocs)
08811            relax_info->relocs_count = sec->reloc_count;
08812        }
08813     }
08814   return TRUE;
08815 }
08816 
08817 
08818 /* This is similar to relax_section except that when a target is moved,
08819    we shift addresses up.  We also need to modify the size.  This
08820    algorithm does NOT allow for relocations into the middle of the
08821    property sections.  */
08822 
08823 static bfd_boolean
08824 relax_property_section (bfd *abfd,
08825                      asection *sec,
08826                      struct bfd_link_info *link_info)
08827 {
08828   Elf_Internal_Rela *internal_relocs;
08829   bfd_byte *contents;
08830   unsigned i, nexti;
08831   bfd_boolean ok = TRUE;
08832   bfd_boolean is_full_prop_section;
08833   size_t last_zfill_target_offset = 0;
08834   asection *last_zfill_target_sec = NULL;
08835   bfd_size_type sec_size;
08836 
08837   sec_size = bfd_get_section_limit (abfd, sec);
08838   internal_relocs = retrieve_internal_relocs (abfd, sec, 
08839                                          link_info->keep_memory);
08840   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
08841   if (contents == NULL && sec_size != 0)
08842     {
08843       ok = FALSE;
08844       goto error_return;
08845     }
08846 
08847   is_full_prop_section =
08848     (   CONST_STRNEQ (sec->name, XTENSA_PROP_SEC_NAME)
08849      || CONST_STRNEQ (sec->name, ".gnu.linkonce.prop."));
08850 
08851   if (internal_relocs)
08852     {
08853       for (i = 0; i < sec->reloc_count; i++)
08854        {
08855          Elf_Internal_Rela *irel;
08856          xtensa_relax_info *target_relax_info;
08857          unsigned r_type;
08858          asection *target_sec;
08859          literal_value val;
08860          bfd_byte *size_p, *flags_p;
08861 
08862          /* Locally change the source address.
08863             Translate the target to the new target address.
08864             If it points to this section and has been removed, MOVE IT.
08865             Also, don't forget to modify the associated SIZE at
08866             (offset + 4).  */
08867 
08868          irel = &internal_relocs[i];
08869          r_type = ELF32_R_TYPE (irel->r_info);
08870          if (r_type == R_XTENSA_NONE)
08871            continue;
08872 
08873          /* Find the literal value.  */
08874          r_reloc_init (&val.r_rel, abfd, irel, contents, sec_size);
08875          size_p = &contents[irel->r_offset + 4];
08876          flags_p = NULL;
08877          if (is_full_prop_section)
08878            {
08879              flags_p = &contents[irel->r_offset + 8];
08880              BFD_ASSERT (irel->r_offset + 12 <= sec_size);
08881            }
08882          else
08883            BFD_ASSERT (irel->r_offset + 8 <= sec_size);
08884 
08885          target_sec = r_reloc_get_section (&val.r_rel);
08886          target_relax_info = get_xtensa_relax_info (target_sec);
08887 
08888          if (target_relax_info
08889              && (target_relax_info->is_relaxable_literal_section
08890                 || target_relax_info->is_relaxable_asm_section ))
08891            {
08892              /* Translate the relocation's destination.  */
08893              bfd_vma new_offset, new_end_offset;
08894              long old_size, new_size;
08895 
08896              new_offset = offset_with_removed_text
08897               (&target_relax_info->action_list, val.r_rel.target_offset);
08898 
08899              /* Assert that we are not out of bounds.  */
08900              old_size = bfd_get_32 (abfd, size_p);
08901 
08902              if (old_size == 0)
08903               {
08904                 /* Only the first zero-sized unreachable entry is
08905                    allowed to expand.  In this case the new offset
08906                    should be the offset before the fill and the new
08907                    size is the expansion size.  For other zero-sized
08908                    entries the resulting size should be zero with an
08909                    offset before or after the fill address depending
08910                    on whether the expanding unreachable entry
08911                    preceeds it.  */
08912                 if (last_zfill_target_sec
08913                     && last_zfill_target_sec == target_sec
08914                     && last_zfill_target_offset == val.r_rel.target_offset)
08915                   new_end_offset = new_offset;
08916                 else
08917                   {
08918                     new_end_offset = new_offset;
08919                     new_offset = offset_with_removed_text_before_fill
08920                      (&target_relax_info->action_list,
08921                       val.r_rel.target_offset);
08922 
08923                     /* If it is not unreachable and we have not yet
08924                       seen an unreachable at this address, place it
08925                       before the fill address.  */
08926                     if (!flags_p
08927                        || (bfd_get_32 (abfd, flags_p)
08928                            & XTENSA_PROP_UNREACHABLE) == 0)
08929                      new_end_offset = new_offset;
08930                     else
08931                      {
08932                        last_zfill_target_sec = target_sec;
08933                        last_zfill_target_offset = val.r_rel.target_offset;
08934                      }
08935                   }
08936               }
08937              else
08938               {
08939                 new_end_offset = offset_with_removed_text_before_fill
08940                   (&target_relax_info->action_list,
08941                    val.r_rel.target_offset + old_size);
08942               }
08943 
08944              new_size = new_end_offset - new_offset;
08945 
08946              if (new_size != old_size)
08947               {
08948                 bfd_put_32 (abfd, new_size, size_p);
08949                 pin_contents (sec, contents);
08950               }
08951 
08952              if (new_offset != val.r_rel.target_offset)
08953               {
08954                 bfd_vma diff = new_offset - val.r_rel.target_offset;
08955                 irel->r_addend += diff;
08956                 pin_internal_relocs (sec, internal_relocs);
08957               }
08958            }
08959        }
08960     }
08961 
08962   /* Combine adjacent property table entries.  This is also done in
08963      finish_dynamic_sections() but at that point it's too late to
08964      reclaim the space in the output section, so we do this twice.  */
08965 
08966   if (internal_relocs && (!link_info->relocatable
08967                        || strcmp (sec->name, XTENSA_LIT_SEC_NAME) == 0))
08968     {
08969       Elf_Internal_Rela *last_irel = NULL;
08970       int removed_bytes = 0;
08971       bfd_vma offset, last_irel_offset;
08972       bfd_vma section_size;
08973       bfd_size_type entry_size;
08974       flagword predef_flags;
08975 
08976       if (is_full_prop_section)
08977        entry_size = 12;
08978       else
08979        entry_size = 8;
08980 
08981       predef_flags = xtensa_get_property_predef_flags (sec);
08982 
08983       /* Walk over memory and irels at the same time.
08984          This REQUIRES that the internal_relocs be sorted by offset.  */
08985       qsort (internal_relocs, sec->reloc_count, sizeof (Elf_Internal_Rela),
08986             internal_reloc_compare);
08987       nexti = 0; /* Index into internal_relocs.  */
08988 
08989       pin_internal_relocs (sec, internal_relocs);
08990       pin_contents (sec, contents);
08991 
08992       last_irel_offset = (bfd_vma) -1;
08993       section_size = sec->size;
08994       BFD_ASSERT (section_size % entry_size == 0);
08995 
08996       for (offset = 0; offset < section_size; offset += entry_size)
08997        {
08998          Elf_Internal_Rela *irel, *next_irel;
08999          bfd_vma bytes_to_remove, size, actual_offset;
09000          bfd_boolean remove_this_irel;
09001          flagword flags;
09002 
09003          irel = NULL;
09004          next_irel = NULL;
09005 
09006          /* Find the next two relocations (if there are that many left),
09007             skipping over any R_XTENSA_NONE relocs.  On entry, "nexti" is
09008             the starting reloc index.  After these two loops, "i"
09009             is the index of the first non-NONE reloc past that starting
09010             index, and "nexti" is the index for the next non-NONE reloc
09011             after "i".  */
09012 
09013          for (i = nexti; i < sec->reloc_count; i++)
09014            {
09015              if (ELF32_R_TYPE (internal_relocs[i].r_info) != R_XTENSA_NONE)
09016               {
09017                 irel = &internal_relocs[i];
09018                 break;
09019               }
09020              internal_relocs[i].r_offset -= removed_bytes;
09021            }
09022 
09023          for (nexti = i + 1; nexti < sec->reloc_count; nexti++)
09024            {
09025              if (ELF32_R_TYPE (internal_relocs[nexti].r_info)
09026                 != R_XTENSA_NONE)
09027               {
09028                 next_irel = &internal_relocs[nexti];
09029                 break;
09030               }
09031              internal_relocs[nexti].r_offset -= removed_bytes;
09032            }
09033 
09034          remove_this_irel = FALSE;
09035          bytes_to_remove = 0;
09036          actual_offset = offset - removed_bytes;
09037          size = bfd_get_32 (abfd, &contents[actual_offset + 4]);
09038 
09039          if (is_full_prop_section) 
09040            flags = bfd_get_32 (abfd, &contents[actual_offset + 8]);
09041          else
09042            flags = predef_flags;
09043 
09044          /* Check that the irels are sorted by offset,
09045             with only one per address.  */
09046          BFD_ASSERT (!irel || (int) irel->r_offset > (int) last_irel_offset); 
09047          BFD_ASSERT (!next_irel || next_irel->r_offset > irel->r_offset);
09048 
09049          /* Make sure there aren't relocs on the size or flag fields.  */
09050          if ((irel && irel->r_offset == offset + 4)
09051              || (is_full_prop_section 
09052                 && irel && irel->r_offset == offset + 8))
09053            {
09054              irel->r_offset -= removed_bytes;
09055              last_irel_offset = irel->r_offset;
09056            }
09057          else if (next_irel && (next_irel->r_offset == offset + 4
09058                              || (is_full_prop_section 
09059                                  && next_irel->r_offset == offset + 8)))
09060            {
09061              nexti += 1;
09062              irel->r_offset -= removed_bytes;
09063              next_irel->r_offset -= removed_bytes;
09064              last_irel_offset = next_irel->r_offset;
09065            }
09066          else if (size == 0 && (flags & XTENSA_PROP_ALIGN) == 0
09067                  && (flags & XTENSA_PROP_UNREACHABLE) == 0)
09068            {
09069              /* Always remove entries with zero size and no alignment.  */
09070              bytes_to_remove = entry_size;
09071              if (irel && irel->r_offset == offset)
09072               {
09073                 remove_this_irel = TRUE;
09074 
09075                 irel->r_offset -= removed_bytes;
09076                 last_irel_offset = irel->r_offset;
09077               }
09078            }
09079          else if (irel && irel->r_offset == offset)
09080            {
09081              if (ELF32_R_TYPE (irel->r_info) == R_XTENSA_32)
09082               {
09083                 if (last_irel)
09084                   {
09085                     flagword old_flags;
09086                     bfd_vma old_size =
09087                      bfd_get_32 (abfd, &contents[last_irel->r_offset + 4]);
09088                     bfd_vma old_address =
09089                      (last_irel->r_addend
09090                       + bfd_get_32 (abfd, &contents[last_irel->r_offset]));
09091                     bfd_vma new_address =
09092                      (irel->r_addend
09093                       + bfd_get_32 (abfd, &contents[actual_offset]));
09094                     if (is_full_prop_section) 
09095                      old_flags = bfd_get_32
09096                        (abfd, &contents[last_irel->r_offset + 8]);
09097                     else
09098                      old_flags = predef_flags;
09099 
09100                     if ((ELF32_R_SYM (irel->r_info)
09101                         == ELF32_R_SYM (last_irel->r_info))
09102                        && old_address + old_size == new_address
09103                        && old_flags == flags
09104                        && (old_flags & XTENSA_PROP_INSN_BRANCH_TARGET) == 0
09105                        && (old_flags & XTENSA_PROP_INSN_LOOP_TARGET) == 0)
09106                      {
09107                        /* Fix the old size.  */
09108                        bfd_put_32 (abfd, old_size + size,
09109                                   &contents[last_irel->r_offset + 4]);
09110                        bytes_to_remove = entry_size;
09111                        remove_this_irel = TRUE;
09112                      }
09113                     else
09114                      last_irel = irel;
09115                   }
09116                 else
09117                   last_irel = irel;
09118               }
09119 
09120              irel->r_offset -= removed_bytes;
09121              last_irel_offset = irel->r_offset;
09122            }
09123 
09124          if (remove_this_irel)
09125            {
09126              irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
09127              irel->r_offset -= bytes_to_remove;
09128            }
09129 
09130          if (bytes_to_remove != 0)
09131            {
09132              removed_bytes += bytes_to_remove;
09133              if (offset + bytes_to_remove < section_size)
09134               memmove (&contents[actual_offset],
09135                       &contents[actual_offset + bytes_to_remove],
09136                       section_size - offset - bytes_to_remove);
09137            }
09138        }
09139 
09140       if (removed_bytes)
09141        {
09142          /* Clear the removed bytes.  */
09143          memset (&contents[section_size - removed_bytes], 0, removed_bytes);
09144 
09145          sec->size = section_size - removed_bytes;
09146 
09147          if (xtensa_is_littable_section (sec))
09148            {
09149              asection *sgotloc = elf_xtensa_hash_table (link_info)->sgotloc;
09150              if (sgotloc)
09151               sgotloc->size -= removed_bytes;
09152            }
09153        }
09154     }
09155 
09156  error_return:
09157   release_internal_relocs (sec, internal_relocs);
09158   release_contents (sec, contents);
09159   return ok;
09160 }
09161 
09162 
09163 /* Third relaxation pass.  */
09164 
09165 /* Change symbol values to account for removed literals.  */
09166 
09167 bfd_boolean
09168 relax_section_symbols (bfd *abfd, asection *sec)
09169 {
09170   xtensa_relax_info *relax_info;
09171   unsigned int sec_shndx;
09172   Elf_Internal_Shdr *symtab_hdr;
09173   Elf_Internal_Sym *isymbuf;
09174   unsigned i, num_syms, num_locals;
09175 
09176   relax_info = get_xtensa_relax_info (sec);
09177   BFD_ASSERT (relax_info);
09178 
09179   if (!relax_info->is_relaxable_literal_section
09180       && !relax_info->is_relaxable_asm_section)
09181     return TRUE;
09182 
09183   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
09184 
09185   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
09186   isymbuf = retrieve_local_syms (abfd);
09187 
09188   num_syms = symtab_hdr->sh_size / sizeof (Elf32_External_Sym);
09189   num_locals = symtab_hdr->sh_info;
09190 
09191   /* Adjust the local symbols defined in this section.  */
09192   for (i = 0; i < num_locals; i++)
09193     {
09194       Elf_Internal_Sym *isym = &isymbuf[i];
09195 
09196       if (isym->st_shndx == sec_shndx)
09197        {
09198          bfd_vma new_address = offset_with_removed_text
09199            (&relax_info->action_list, isym->st_value);
09200          bfd_vma new_size = isym->st_size;
09201 
09202          if (ELF32_ST_TYPE (isym->st_info) == STT_FUNC)
09203            {
09204              bfd_vma new_end = offset_with_removed_text
09205               (&relax_info->action_list, isym->st_value + isym->st_size);
09206              new_size = new_end - new_address;
09207            }
09208 
09209          isym->st_value = new_address;
09210          isym->st_size = new_size;
09211        }
09212     }
09213 
09214   /* Now adjust the global symbols defined in this section.  */
09215   for (i = 0; i < (num_syms - num_locals); i++)
09216     {
09217       struct elf_link_hash_entry *sym_hash;
09218 
09219       sym_hash = elf_sym_hashes (abfd)[i];
09220 
09221       if (sym_hash->root.type == bfd_link_hash_warning)
09222        sym_hash = (struct elf_link_hash_entry *) sym_hash->root.u.i.link;
09223 
09224       if ((sym_hash->root.type == bfd_link_hash_defined
09225           || sym_hash->root.type == bfd_link_hash_defweak)
09226          && sym_hash->root.u.def.section == sec)
09227        {
09228          bfd_vma new_address = offset_with_removed_text
09229            (&relax_info->action_list, sym_hash->root.u.def.value);
09230          bfd_vma new_size = sym_hash->size;
09231 
09232          if (sym_hash->type == STT_FUNC)
09233            {
09234              bfd_vma new_end = offset_with_removed_text
09235               (&relax_info->action_list,
09236                sym_hash->root.u.def.value + sym_hash->size);
09237              new_size = new_end - new_address;
09238            }
09239 
09240          sym_hash->root.u.def.value = new_address;
09241          sym_hash->size = new_size;
09242        }
09243     }
09244 
09245   return TRUE;
09246 }
09247 
09248 
09249 /* "Fix" handling functions, called while performing relocations.  */
09250 
09251 static bfd_boolean
09252 do_fix_for_relocatable_link (Elf_Internal_Rela *rel,
09253                           bfd *input_bfd,
09254                           asection *input_section,
09255                           bfd_byte *contents)
09256 {
09257   r_reloc r_rel;
09258   asection *sec, *old_sec;
09259   bfd_vma old_offset;
09260   int r_type = ELF32_R_TYPE (rel->r_info);
09261   reloc_bfd_fix *fix;
09262 
09263   if (r_type == R_XTENSA_NONE)
09264     return TRUE;
09265 
09266   fix = get_bfd_fix (input_section, rel->r_of