x86: Support x86 Zhaoxin PadLock XMODX instructions
[binutils-gdb.git] / ld / emultempl / xtensaelf.em
blob027b7732d2df37fbd08f1899f78c8df44e2695ff
1 # This shell script emits a C file. -*- C -*-
2 #   Copyright (C) 2003-2025 Free Software Foundation, Inc.
4 # This file is part of the GNU Binutils.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19 # MA 02110-1301, USA.
22 # This file is sourced from elf.em, and defines extra xtensa-elf
23 # specific routines.
25 fragment <<EOF
27 #include <xtensa-dynconfig.h>
28 #include "../bfd/elf-bfd.h"
29 #include "elf/xtensa.h"
30 #include "bfd.h"
32 /* Provide default values for new configuration settings.  */
33 #ifndef XTHAL_ABI_UNDEFINED
34 #define XTHAL_ABI_UNDEFINED -1
35 #endif
37 static void xtensa_wild_group_interleave (lang_statement_union_type *);
38 static void xtensa_colocate_output_literals (lang_statement_union_type *);
39 static void xtensa_strip_inconsistent_linkonce_sections
40   (lang_statement_list_type *);
42 extern int elf32xtensa_size_opt;
43 extern int elf32xtensa_no_literal_movement;
44 extern int elf32xtensa_abi;
46 /* This number is irrelevant until we turn on use_literal_pages */
47 static bfd_vma xtensa_page_power = 12; /* 4K pages.  */
49 /* To force a page break between literals and text, change
50    xtensa_use_literal_pages to "true".  */
51 static bool xtensa_use_literal_pages = false;
53 #define EXTRA_VALIDATION 0
55 /* Xtensa ABI.
56    This option is defined in BDF library.  */
57 extern int elf32xtensa_abi;
60 static char *
61 elf_xtensa_choose_target (int argc ATTRIBUTE_UNUSED,
62                           char **argv ATTRIBUTE_UNUSED)
64   if (XCHAL_HAVE_BE)
65     return "${BIG_OUTPUT_FORMAT}";
66   else
67     return "${LITTLE_OUTPUT_FORMAT}";
71 static void
72 elf_xtensa_before_parse (void)
74   /* Just call the default hook.... Tensilica's version of this function
75      does some other work that isn't relevant here.  */
76   gld${EMULATION_NAME}_before_parse ();
80 static void
81 remove_section (bfd *abfd, asection *os)
83   asection **spp;
84   for (spp = &abfd->sections; *spp; spp = &(*spp)->next)
85     if (*spp == os)
86       {
87         *spp = os->next;
88         os->owner->section_count--;
89         break;
90       }
94 static bool
95 replace_insn_sec_with_prop_sec (bfd *abfd,
96                                 const char *insn_sec_name,
97                                 const char *prop_sec_name,
98                                 char **error_message)
100   asection *insn_sec;
101   asection *prop_sec;
102   bfd_byte *prop_contents = NULL;
103   bfd_byte *insn_contents = NULL;
104   unsigned entry_count;
105   unsigned entry;
106   Elf_Internal_Shdr *rel_hdr;
107   Elf_Internal_Rela *internal_relocs = NULL;
108   unsigned reloc_count;
110   *error_message = "";
111   insn_sec = bfd_get_section_by_name (abfd, insn_sec_name);
112   if (insn_sec == NULL)
113     return true;
114   entry_count = insn_sec->size / 8;
116   prop_sec = bfd_get_section_by_name (abfd, prop_sec_name);
117   if (prop_sec != NULL && insn_sec != NULL)
118     {
119       *error_message = _("file already has property tables");
120       return false;
121     }
123   if (insn_sec->size != 0)
124     {
125       insn_contents = (bfd_byte *) xmalloc (insn_sec->size);
126       if (! bfd_get_section_contents (abfd, insn_sec, insn_contents,
127                                       (file_ptr) 0, insn_sec->size))
128         {
129           *error_message = _("failed to read section contents");
130           goto cleanup;
131         }
132     }
134   /* Create a property table section for it.  */
135   prop_sec_name = strdup (prop_sec_name);
136   prop_sec = bfd_make_section_with_flags
137     (abfd, prop_sec_name, bfd_section_flags (insn_sec));
138   if (prop_sec == NULL
139       || !bfd_set_section_alignment (prop_sec, 2))
140     {
141       *error_message = _("could not create new section");
142       goto cleanup;
143     }
145   prop_sec->size = entry_count * 12;
146   prop_contents = (bfd_byte *) bfd_zalloc (abfd, prop_sec->size);
147   elf_section_data (prop_sec)->this_hdr.contents = prop_contents;
149   /* The entry size and size must be set to allow the linker to compute
150      the number of relocations since it does not use reloc_count.  */
151   rel_hdr = _bfd_elf_single_rel_hdr (prop_sec);
152   rel_hdr->sh_entsize = sizeof (Elf32_External_Rela);
153   rel_hdr->sh_size = _bfd_elf_single_rel_hdr (insn_sec)->sh_size;
155   if (prop_contents == NULL && prop_sec->size != 0)
156     {
157       *error_message = _("could not allocate section contents");
158       goto cleanup;
159     }
161   /* Read the relocations.  */
162   reloc_count = insn_sec->reloc_count;
163   if (reloc_count != 0)
164     {
165       /* If there is already an internal_reloc, then save it so that the
166          read_relocs function freshly allocates a copy.  */
167       Elf_Internal_Rela *saved_relocs = elf_section_data (insn_sec)->relocs;
169       elf_section_data (insn_sec)->relocs = NULL;
170       internal_relocs =
171         _bfd_elf_link_read_relocs (abfd, insn_sec, NULL, NULL, false);
172       elf_section_data (insn_sec)->relocs = saved_relocs;
174       if (internal_relocs == NULL)
175         {
176           *error_message = _("out of memory");
177           goto cleanup;
178         }
179     }
181   /* Create a relocation section for the property section.  */
182   if (internal_relocs != NULL)
183     {
184       elf_section_data (prop_sec)->relocs = internal_relocs;
185       prop_sec->reloc_count = reloc_count;
186     }
188   /* Now copy each insn table entry to the prop table entry with
189      appropriate flags.  */
190   for (entry = 0; entry < entry_count; ++entry)
191     {
192       unsigned value;
193       unsigned flags = (XTENSA_PROP_INSN | XTENSA_PROP_NO_TRANSFORM
194                         | XTENSA_PROP_INSN_NO_REORDER);
195       value = bfd_get_32 (abfd, insn_contents + entry * 8 + 0);
196       bfd_put_32 (abfd, value, prop_contents + entry * 12 + 0);
197       value = bfd_get_32 (abfd, insn_contents + entry * 8 + 4);
198       bfd_put_32 (abfd, value, prop_contents + entry * 12 + 4);
199       bfd_put_32 (abfd, flags, prop_contents + entry * 12 + 8);
200     }
202   /* Now copy all of the relocations.  Change offsets for the
203      instruction table section to offsets in the property table
204      section.  */
205   if (internal_relocs)
206     {
207       unsigned i;
209       for (i = 0; i < reloc_count; i++)
210         {
211           Elf_Internal_Rela *rela;
212           unsigned r_offset;
214           rela = &internal_relocs[i];
216           /* If this relocation is to the .xt.insn section,
217              change the section number and the offset.  */
218           r_offset = rela->r_offset;
219           r_offset += 4 * (r_offset / 8);
220           rela->r_offset = r_offset;
221         }
222     }
224   remove_section (abfd, insn_sec);
226   free (insn_contents);
228   return true;
230  cleanup:
231   if (prop_sec && prop_sec->owner)
232     remove_section (abfd, prop_sec);
233   free (insn_contents);
235   return false;
239 #define PROP_SEC_BASE_NAME ".xt.prop"
240 #define INSN_SEC_BASE_NAME ".xt.insn"
241 #define LINKONCE_SEC_OLD_TEXT_BASE_NAME ".gnu.linkonce.x."
244 static void
245 replace_instruction_table_sections (bfd *abfd, asection *sec)
247   char *message = "";
248   const char *insn_sec_name = NULL;
249   char *prop_sec_name = NULL;
250   char *owned_prop_sec_name = NULL;
251   const char *sec_name;
253   sec_name = bfd_section_name (sec);
254   if (strcmp (sec_name, INSN_SEC_BASE_NAME) == 0)
255     {
256       insn_sec_name = INSN_SEC_BASE_NAME;
257       prop_sec_name = PROP_SEC_BASE_NAME;
258     }
259   else if (startswith (sec_name, LINKONCE_SEC_OLD_TEXT_BASE_NAME))
260     {
261       insn_sec_name = sec_name;
262       owned_prop_sec_name = (char *) xmalloc (strlen (sec_name) + 20);
263       prop_sec_name = owned_prop_sec_name;
264       strcpy (prop_sec_name, ".gnu.linkonce.prop.t.");
265       strcat (prop_sec_name,
266               sec_name + strlen (LINKONCE_SEC_OLD_TEXT_BASE_NAME));
267     }
268   if (insn_sec_name != NULL)
269     {
270       if (! replace_insn_sec_with_prop_sec (abfd, insn_sec_name, prop_sec_name,
271                                             &message))
272         {
273           einfo (_("%P: warning: failed to convert %s table in %pB (%s); subsequent disassembly may be incomplete\n"),
274                  insn_sec_name, abfd, message);
275         }
276     }
277   free (owned_prop_sec_name);
281 /* This is called after all input sections have been opened to convert
282    instruction tables (.xt.insn, gnu.linkonce.x.*) tables into property
283    tables (.xt.prop) before any section placement.  */
285 static void
286 elf_xtensa_after_open (void)
288   /* First call the ELF version.  */
289   gld${EMULATION_NAME}_after_open ();
291   /* Now search the input files looking for instruction table sections.  */
292   LANG_FOR_EACH_INPUT_STATEMENT (f)
293     {
294       asection *sec = f->the_bfd->sections;
295       asection *next_sec;
297       /* Do not use bfd_map_over_sections here since we are removing
298          sections as we iterate.  */
299       while (sec != NULL)
300         {
301           next_sec = sec->next;
302           replace_instruction_table_sections (f->the_bfd, sec);
303           sec = next_sec;
304         }
305     }
309 static bool
310 xt_config_info_unpack_and_check (char *data,
311                                  bool *pmismatch,
312                                  char **pmsg)
314   char *d, *key;
315   int num;
317   *pmismatch = false;
319   d = data;
320   while (*d)
321     {
322       key = d;
323       d = strchr (d, '=');
324       if (! d)
325         goto error;
327       /* Overwrite the equal sign.  */
328       *d++ = 0;
330       /* Check if this is a quoted string or a number.  */
331       if (*d == '"')
332         {
333           /* No string values are currently checked by LD;
334              just skip over the quotes.  */
335           d++;
336           d = strchr (d, '"');
337           if (! d)
338             goto error;
339           /* Overwrite the trailing quote.  */
340           *d++ = 0;
341         }
342       else
343         {
344           if (*d == 0)
345             goto error;
346           num = strtoul (d, &d, 0);
348           if (! strcmp (key, "ABI"))
349             {
350               if (elf32xtensa_abi == XTHAL_ABI_UNDEFINED)
351                 {
352                   elf32xtensa_abi = num;
353                 }
354               else if (num != elf32xtensa_abi)
355                 {
356                   *pmismatch = true;
357                   *pmsg = "ABI does not match";
358                 }
359             }
360           else if (! strcmp (key, "USE_ABSOLUTE_LITERALS"))
361             {
362               if (num != XSHAL_USE_ABSOLUTE_LITERALS)
363                 {
364                   *pmismatch = true;
365                   *pmsg = "incompatible use of the Extended L32R option";
366                 }
367             }
368         }
370       if (*d++ != '\n')
371         goto error;
372     }
374   return true;
376  error:
377   return false;
381 #define XTINFO_NAME "Xtensa_Info"
382 #define XTINFO_NAMESZ 12
383 #define XTINFO_TYPE 1
385 static void
386 check_xtensa_info (bfd *abfd, asection *info_sec)
388   char *data, *errmsg = "";
389   bool mismatch;
391   data = xmalloc (info_sec->size);
392   if (! bfd_get_section_contents (abfd, info_sec, data, 0, info_sec->size))
393     fatal (_("%P: %pB: cannot read contents of section %pA\n"), abfd, info_sec);
395   if (info_sec->size > 24
396       && info_sec->size >= 24 + bfd_get_32 (abfd, data + 4)
397       && bfd_get_32 (abfd, data + 0) == XTINFO_NAMESZ
398       && bfd_get_32 (abfd, data + 8) == XTINFO_TYPE
399       && strcmp (data + 12, XTINFO_NAME) == 0
400       && xt_config_info_unpack_and_check (data + 12 + XTINFO_NAMESZ,
401                                           &mismatch, &errmsg))
402     {
403       if (mismatch)
404         einfo (_("%P: %pB: warning: incompatible Xtensa configuration (%s)\n"),
405                abfd, errmsg);
406     }
407   else
408     einfo (_("%P: %pB: warning: cannot parse .xtensa.info section\n"), abfd);
410   free (data);
414 /* This is called after the sections have been attached to output
415    sections, but before any sizes or addresses have been set.  */
417 static void
418 elf_xtensa_before_allocation (void)
420   asection *info_sec, *first_info_sec;
421   bfd *first_bfd;
422   bool is_big_endian = XCHAL_HAVE_BE;
424   /* Check that the output endianness matches the Xtensa
425      configuration.  The BFD library always includes both big and
426      little endian target vectors for Xtensa, but it only supports the
427      detailed instruction encode/decode operations (such as are
428      required to process relocations) for the selected Xtensa
429      configuration.  */
431   if (is_big_endian
432       && link_info.output_bfd->xvec->byteorder == BFD_ENDIAN_LITTLE)
433     {
434       fatal (_("%P: little endian output does not match "
435                "Xtensa configuration\n"));
436     }
437   if (!is_big_endian
438       && link_info.output_bfd->xvec->byteorder == BFD_ENDIAN_BIG)
439     {
440       fatal (_("%P: big endian output does not match "
441                "Xtensa configuration\n"));
442     }
444   /* Keep track of the first input .xtensa.info section, and as a fallback,
445      the first input bfd where a .xtensa.info section could be created.
446      After the input .xtensa.info has been checked, the contents of the
447      first one will be replaced with the output .xtensa.info table.  */
448   first_info_sec = 0;
449   first_bfd = 0;
451   LANG_FOR_EACH_INPUT_STATEMENT (f)
452     {
453       /* Check that the endianness for each input file matches the output.
454          The merge_private_bfd_data hook has already reported any mismatches
455          as errors, but those errors are not fatal.  At this point, we
456          cannot go any further if there are any mismatches.  */
457       if ((is_big_endian && f->the_bfd->xvec->byteorder == BFD_ENDIAN_LITTLE)
458           || (!is_big_endian && f->the_bfd->xvec->byteorder == BFD_ENDIAN_BIG))
459         fatal (_("%P: cross-endian linking for %pB not supported\n"),
460                f->the_bfd);
462       if (! first_bfd)
463         first_bfd = f->the_bfd;
465       info_sec = bfd_get_section_by_name (f->the_bfd, ".xtensa.info");
466       if (! info_sec)
467         continue;
469       if (! first_info_sec)
470         first_info_sec = info_sec;
472       /* Unpack the .xtensa.info section and check it against the current
473          Xtensa configuration.  */
474       check_xtensa_info (f->the_bfd, info_sec);
476       /* Do not include this copy of .xtensa.info in the output.  */
477       info_sec->size = 0;
478       info_sec->flags |= SEC_EXCLUDE;
479     }
481   /* Reuse the first .xtensa.info input section to hold the output
482      .xtensa.info; or, if none were found, create a new section in the
483      first input bfd (assuming there is one).  */
484   info_sec = first_info_sec;
485   if (! info_sec && first_bfd)
486     {
487       info_sec = bfd_make_section_with_flags (first_bfd, ".xtensa.info",
488                                               SEC_HAS_CONTENTS | SEC_READONLY);
489       if (! info_sec)
490         fatal (_("%P: failed to create .xtensa.info section\n"));
491     }
492   if (info_sec)
493     {
494       int xtensa_info_size;
495       char data[100];
497       info_sec->flags &= ~SEC_EXCLUDE;
498       info_sec->flags |= SEC_IN_MEMORY;
500       xtensa_info_size
501         = 1 + sprintf (data, "USE_ABSOLUTE_LITERALS=%d\nABI=%d\n",
502                        XSHAL_USE_ABSOLUTE_LITERALS, xtensa_abi_choice ());
504       /* Add enough null terminators to pad to a word boundary.  */
505       do
506         data[xtensa_info_size++] = 0;
507       while ((xtensa_info_size & 3) != 0);
509       info_sec->size = 12 + XTINFO_NAMESZ + xtensa_info_size;
510       info_sec->contents = xmalloc (info_sec->size);
511       bfd_put_32 (info_sec->owner, XTINFO_NAMESZ, info_sec->contents + 0);
512       bfd_put_32 (info_sec->owner, xtensa_info_size, info_sec->contents + 4);
513       bfd_put_32 (info_sec->owner, XTINFO_TYPE, info_sec->contents + 8);
514       memcpy (info_sec->contents + 12, XTINFO_NAME, XTINFO_NAMESZ);
515       memcpy (info_sec->contents + 12 + XTINFO_NAMESZ, data, xtensa_info_size);
516     }
518   /* Enable relaxation by default if the "--no-relax" option was not
519      specified.  This is done here instead of in the before_parse hook
520      because there is a check in main() to prohibit use of --relax and
521      -r together and that combination should be allowed for Xtensa.  */
522   if (RELAXATION_DISABLED_BY_DEFAULT)
523     ENABLE_RELAXATION;
525   xtensa_strip_inconsistent_linkonce_sections (stat_ptr);
527   gld${EMULATION_NAME}_before_allocation ();
529   xtensa_wild_group_interleave (stat_ptr->head);
531   if (RELAXATION_ENABLED)
532     xtensa_colocate_output_literals (stat_ptr->head);
534   /* TBD: We need to force the page alignments to here and only do
535      them as needed for the entire output section.  Finally, if this
536      is a relocatable link then we need to add alignment notes so
537      that the literals can be separated later.  */
541 typedef struct wildcard_list section_name_list;
543 typedef struct reloc_deps_e_t reloc_deps_e;
544 typedef struct reloc_deps_section_t reloc_deps_section;
545 typedef struct reloc_deps_graph_t reloc_deps_graph;
548 struct reloc_deps_e_t
550   asection *src; /* Contains l32rs.  */
551   asection *tgt; /* Contains literals.  */
552   reloc_deps_e *next;
555 /* Place these in the userdata field.  */
556 struct reloc_deps_section_t
558   reloc_deps_e *preds;
559   reloc_deps_e *succs;
560   bool is_only_literal;
564 struct reloc_deps_graph_t
566   size_t count;
567   size_t size;
568   asection **sections;
571 static void xtensa_layout_wild
572   (const reloc_deps_graph *, lang_wild_statement_type *);
574 typedef void (*deps_callback_t) (asection *, /* src_sec */
575                                  bfd_vma,    /* src_offset */
576                                  asection *, /* target_sec */
577                                  bfd_vma,    /* target_offset */
578                                  void *);    /* closure */
580 extern bool xtensa_callback_required_dependence
581   (bfd *, asection *, struct bfd_link_info *, deps_callback_t, void *);
582 static void xtensa_ldlang_clear_addresses (lang_statement_union_type *);
583 static bool ld_local_file_relocations_fit
584   (lang_statement_union_type *, const reloc_deps_graph *);
585 static bfd_vma ld_assign_relative_paged_dot
586   (bfd_vma, lang_statement_union_type *, const reloc_deps_graph *,
587    bool);
588 static bfd_vma ld_xtensa_insert_page_offsets
589   (bfd_vma, lang_statement_union_type *, reloc_deps_graph *, bool);
590 #if EXTRA_VALIDATION
591 static size_t ld_count_children (lang_statement_union_type *);
592 #endif
594 extern lang_statement_list_type constructor_list;
596 static reloc_deps_section *
597 xtensa_get_section_deps (const reloc_deps_graph *deps ATTRIBUTE_UNUSED,
598                          asection *sec)
600   /* We have a separate function for this so that
601      we could in the future keep a completely independent
602      structure that maps a section to its dependence edges.
603      For now, we place these in the sec->userdata field.
604      This doesn't clash with ldlang.c use of userdata for output
605      sections, and during map output for input sections, since the
606      xtensa use is only for input sections and only extant in
607      before_allocation.  */
608   reloc_deps_section *sec_deps = bfd_section_userdata (sec);
609   return sec_deps;
612 static void
613 xtensa_set_section_deps (const reloc_deps_graph *deps ATTRIBUTE_UNUSED,
614                          asection *sec,
615                          reloc_deps_section *deps_section)
617   bfd_set_section_userdata (sec, deps_section);
621 /* This is used to keep a list of all of the sections participating in
622    the graph so we can clean them up quickly.  */
624 static void
625 xtensa_append_section_deps (reloc_deps_graph *deps, asection *sec)
627   if (deps->size <= deps->count)
628     {
629       asection **new_sections;
630       size_t i;
631       size_t new_size;
633       new_size = deps->size * 2;
634       if (new_size == 0)
635         new_size = 20;
637       new_sections = xmalloc (sizeof (asection *) * new_size);
638       memset (new_sections, 0, sizeof (asection *) * new_size);
639       for (i = 0; i < deps->count; i++)
640         {
641           new_sections[i] = deps->sections[i];
642         }
643       free (deps->sections);
644       deps->sections = new_sections;
645       deps->size = new_size;
646     }
647   deps->sections[deps->count] = sec;
648   deps->count++;
652 static void
653 free_reloc_deps_graph (reloc_deps_graph *deps)
655   size_t i;
656   for (i = 0; i < deps->count; i++)
657     {
658       asection *sec = deps->sections[i];
659       reloc_deps_section *sec_deps;
660       sec_deps = xtensa_get_section_deps (deps, sec);
661       if (sec_deps)
662         {
663           reloc_deps_e *next;
664           while (sec_deps->succs != NULL)
665             {
666               next = sec_deps->succs->next;
667               free (sec_deps->succs);
668               sec_deps->succs = next;
669             }
671           while (sec_deps->preds != NULL)
672             {
673               next = sec_deps->preds->next;
674               free (sec_deps->preds);
675               sec_deps->preds = next;
676             }
677           free (sec_deps);
678         }
679       xtensa_set_section_deps (deps, sec, NULL);
680     }
681   free (deps->sections);
682   free (deps);
686 static bool
687 section_is_source (const reloc_deps_graph *deps ATTRIBUTE_UNUSED,
688                    lang_statement_union_type *s)
690   asection *sec;
691   const reloc_deps_section *sec_deps;
693   if (s->header.type != lang_input_section_enum)
694     return false;
695   sec = s->input_section.section;
697   sec_deps = xtensa_get_section_deps (deps, sec);
698   return sec_deps && sec_deps->succs != NULL;
702 static bool
703 section_is_target (const reloc_deps_graph *deps ATTRIBUTE_UNUSED,
704                    lang_statement_union_type *s)
706   asection *sec;
707   const reloc_deps_section *sec_deps;
709   if (s->header.type != lang_input_section_enum)
710     return false;
711   sec = s->input_section.section;
713   sec_deps = xtensa_get_section_deps (deps, sec);
714   return sec_deps && sec_deps->preds != NULL;
718 static bool
719 section_is_source_or_target (const reloc_deps_graph *deps ATTRIBUTE_UNUSED,
720                              lang_statement_union_type *s)
722   return (section_is_source (deps, s)
723           || section_is_target (deps, s));
727 typedef struct xtensa_ld_iter_stack_t xtensa_ld_iter_stack;
728 typedef struct xtensa_ld_iter_t xtensa_ld_iter;
730 struct xtensa_ld_iter_t
732   lang_statement_union_type *parent;    /* Parent of the list.  */
733   lang_statement_list_type *l;          /* List that holds it.  */
734   lang_statement_union_type **loc;      /* Place in the list.  */
737 struct xtensa_ld_iter_stack_t
739   xtensa_ld_iter iterloc;               /* List that hold it.  */
741   xtensa_ld_iter_stack *next;           /* Next in the stack.  */
742   xtensa_ld_iter_stack *prev;           /* Back pointer for stack.  */
746 static void
747 ld_xtensa_move_section_after (xtensa_ld_iter *to, xtensa_ld_iter *current)
749   lang_statement_union_type *to_next;
750   lang_statement_union_type *current_next;
751   lang_statement_union_type **e;
753 #if EXTRA_VALIDATION
754   size_t old_to_count, new_to_count;
755   size_t old_current_count, new_current_count;
756 #endif
758   if (to == current)
759     return;
761 #if EXTRA_VALIDATION
762   old_to_count = ld_count_children (to->parent);
763   old_current_count = ld_count_children (current->parent);
764 #endif
766   to_next = *(to->loc);
767   current_next = (*current->loc)->header.next;
769   *(to->loc) = *(current->loc);
771   *(current->loc) = current_next;
772   (*(to->loc))->header.next = to_next;
774   /* reset "to" list tail */
775   for (e = &to->l->head; *e != NULL; e = &(*e)->header.next)
776     ;
777   to->l->tail = e;
779   /* reset "current" list tail */
780   for (e = &current->l->head; *e != NULL; e = &(*e)->header.next)
781     ;
782   current->l->tail = e;
784 #if EXTRA_VALIDATION
785   new_to_count = ld_count_children (to->parent);
786   new_current_count = ld_count_children (current->parent);
788   ASSERT ((old_to_count + old_current_count)
789           == (new_to_count + new_current_count));
790 #endif
794 /* Can only be called with lang_statements that have lists.  Returns
795    FALSE if the list is empty.  */
797 static bool
798 iter_stack_empty (xtensa_ld_iter_stack **stack_p)
800   return *stack_p == NULL;
804 static bool
805 iter_stack_push (xtensa_ld_iter_stack **stack_p,
806                  lang_statement_union_type *parent)
808   xtensa_ld_iter_stack *stack;
809   lang_statement_list_type *l = NULL;
811   switch (parent->header.type)
812     {
813     case lang_output_section_statement_enum:
814       l = &parent->output_section_statement.children;
815       break;
816     case lang_wild_statement_enum:
817       l = &parent->wild_statement.children;
818       break;
819     case lang_group_statement_enum:
820       l = &parent->group_statement.children;
821       break;
822     default:
823       ASSERT (0);
824       return false;
825     }
827   /* Empty. do not push.  */
828   if (l->tail == &l->head)
829     return false;
831   stack = xmalloc (sizeof (xtensa_ld_iter_stack));
832   memset (stack, 0, sizeof (xtensa_ld_iter_stack));
833   stack->iterloc.parent = parent;
834   stack->iterloc.l = l;
835   stack->iterloc.loc = &l->head;
837   stack->next = *stack_p;
838   stack->prev = NULL;
839   if (*stack_p != NULL)
840     (*stack_p)->prev = stack;
841   *stack_p = stack;
842   return true;
846 static void
847 iter_stack_pop (xtensa_ld_iter_stack **stack_p)
849   xtensa_ld_iter_stack *stack;
851   stack = *stack_p;
853   if (stack == NULL)
854     {
855       ASSERT (stack != NULL);
856       return;
857     }
859   if (stack->next != NULL)
860     stack->next->prev = NULL;
862   *stack_p = stack->next;
863   free (stack);
867 /* This MUST be called if, during iteration, the user changes the
868    underlying structure.  It will check for a NULL current and advance
869    accordingly.  */
871 static void
872 iter_stack_update (xtensa_ld_iter_stack **stack_p)
874   if (!iter_stack_empty (stack_p)
875       && (*(*stack_p)->iterloc.loc) == NULL)
876     {
877       iter_stack_pop (stack_p);
879       while (!iter_stack_empty (stack_p)
880              && ((*(*stack_p)->iterloc.loc)->header.next == NULL))
881         {
882           iter_stack_pop (stack_p);
883         }
884       if (!iter_stack_empty (stack_p))
885         (*stack_p)->iterloc.loc = &(*(*stack_p)->iterloc.loc)->header.next;
886     }
890 static void
891 iter_stack_next (xtensa_ld_iter_stack **stack_p)
893   xtensa_ld_iter_stack *stack;
894   lang_statement_union_type *current;
895   stack = *stack_p;
897   current = *stack->iterloc.loc;
898   /* If we are on the first element.  */
899   if (current != NULL)
900     {
901       switch (current->header.type)
902         {
903         case lang_output_section_statement_enum:
904         case lang_wild_statement_enum:
905         case lang_group_statement_enum:
906           /* If the list if not empty, we are done.  */
907           if (iter_stack_push (stack_p, *stack->iterloc.loc))
908             return;
909           /* Otherwise increment the pointer as normal.  */
910           break;
911         default:
912           break;
913         }
914     }
916   while (!iter_stack_empty (stack_p)
917          && ((*(*stack_p)->iterloc.loc)->header.next == NULL))
918     {
919       iter_stack_pop (stack_p);
920     }
921   if (!iter_stack_empty (stack_p))
922     (*stack_p)->iterloc.loc = &(*(*stack_p)->iterloc.loc)->header.next;
926 static lang_statement_union_type *
927 iter_stack_current (xtensa_ld_iter_stack **stack_p)
929   return *((*stack_p)->iterloc.loc);
933 /* The iter stack is a preorder.  */
935 static void
936 iter_stack_create (xtensa_ld_iter_stack **stack_p,
937                    lang_statement_union_type *parent)
939   iter_stack_push (stack_p, parent);
943 static void
944 iter_stack_copy_current (xtensa_ld_iter_stack **stack_p, xtensa_ld_iter *front)
946   *front = (*stack_p)->iterloc;
950 static void
951 xtensa_colocate_literals (reloc_deps_graph *deps,
952                           lang_statement_union_type *statement)
954   /* Keep a stack of pointers to control iteration through the contours.  */
955   xtensa_ld_iter_stack *stack = NULL;
956   xtensa_ld_iter_stack **stack_p = &stack;
958   xtensa_ld_iter front;  /* Location where new insertion should occur.  */
959   xtensa_ld_iter *front_p = NULL;
961   xtensa_ld_iter current; /* Location we are checking.  */
962   xtensa_ld_iter *current_p = NULL;
963   bool in_literals = false;
965   if (deps->count == 0)
966     return;
968   iter_stack_create (stack_p, statement);
970   while (!iter_stack_empty (stack_p))
971     {
972       bool skip_increment = false;
973       lang_statement_union_type *l = iter_stack_current (stack_p);
975       switch (l->header.type)
976         {
977         case lang_assignment_statement_enum:
978           /* Any assignment statement should block reordering across it.  */
979           front_p = NULL;
980           in_literals = false;
981           break;
983         case lang_input_section_enum:
984           if (front_p == NULL)
985             {
986               in_literals = (section_is_target (deps, l)
987                              && !section_is_source (deps, l));
988               if (in_literals)
989                 {
990                   front_p = &front;
991                   iter_stack_copy_current (stack_p, front_p);
992                 }
993             }
994           else
995             {
996               bool is_target;
997               current_p = &current;
998               iter_stack_copy_current (stack_p, current_p);
999               is_target = (section_is_target (deps, l)
1000                            && !section_is_source (deps, l));
1002               if (in_literals)
1003                 {
1004                   iter_stack_copy_current (stack_p, front_p);
1005                   if (!is_target)
1006                     in_literals = false;
1007                 }
1008               else
1009                 {
1010                   if (is_target)
1011                     {
1012                       /* Try to insert in place.  */
1013                       ld_xtensa_move_section_after (front_p, current_p);
1014                       ld_assign_relative_paged_dot (0x100000,
1015                                                     statement,
1016                                                     deps,
1017                                                     xtensa_use_literal_pages);
1019                       /* We use this code because it's already written.  */
1020                       if (!ld_local_file_relocations_fit (statement, deps))
1021                         {
1022                           /* Move it back.  */
1023                           ld_xtensa_move_section_after (current_p, front_p);
1024                           /* Reset the literal placement.  */
1025                           iter_stack_copy_current (stack_p, front_p);
1026                         }
1027                       else
1028                         {
1029                           /* Move front pointer up by one.  */
1030                           front_p->loc = &(*front_p->loc)->header.next;
1032                           /* Do not increment the current pointer.  */
1033                           skip_increment = true;
1034                         }
1035                     }
1036                 }
1037             }
1038           break;
1039         default:
1040           break;
1041         }
1043       if (!skip_increment)
1044         iter_stack_next (stack_p);
1045       else
1046         /* Be careful to update the stack_p if it now is a null.  */
1047         iter_stack_update (stack_p);
1048     }
1050   lang_for_each_statement_worker (xtensa_ldlang_clear_addresses, statement);
1054 static void
1055 xtensa_move_dependencies_to_front (reloc_deps_graph *deps,
1056                                    lang_wild_statement_type *w)
1058   /* Keep a front pointer and a current pointer.  */
1059   lang_statement_union_type **front;
1060   lang_statement_union_type **current;
1062   /* Walk to the end of the targets.  */
1063   for (front = &w->children.head;
1064        (*front != NULL) && section_is_source_or_target (deps, *front);
1065        front = &(*front)->header.next)
1066     ;
1068   if (*front == NULL)
1069     return;
1071   current = &(*front)->header.next;
1072   while (*current != NULL)
1073     {
1074       if (section_is_source_or_target (deps, *current))
1075         {
1076           /* Insert in place.  */
1077           xtensa_ld_iter front_iter;
1078           xtensa_ld_iter current_iter;
1080           front_iter.parent = (lang_statement_union_type *) w;
1081           front_iter.l = &w->children;
1082           front_iter.loc = front;
1084           current_iter.parent = (lang_statement_union_type *) w;
1085           current_iter.l = &w->children;
1086           current_iter.loc = current;
1088           ld_xtensa_move_section_after (&front_iter, &current_iter);
1089           front = &(*front)->header.next;
1090         }
1091       else
1092         {
1093           current = &(*current)->header.next;
1094         }
1095     }
1099 static bool
1100 deps_has_sec_edge (const reloc_deps_graph *deps, asection *src, asection *tgt)
1102   const reloc_deps_section *sec_deps;
1103   const reloc_deps_e *sec_deps_e;
1105   sec_deps = xtensa_get_section_deps (deps, src);
1106   if (sec_deps == NULL)
1107     return false;
1109   for (sec_deps_e = sec_deps->succs;
1110        sec_deps_e != NULL;
1111        sec_deps_e = sec_deps_e->next)
1112     {
1113       ASSERT (sec_deps_e->src == src);
1114       if (sec_deps_e->tgt == tgt)
1115         return true;
1116     }
1117   return false;
1121 static bool
1122 deps_has_edge (const reloc_deps_graph *deps,
1123                lang_statement_union_type *src,
1124                lang_statement_union_type *tgt)
1126   if (!section_is_source (deps, src))
1127     return false;
1128   if (!section_is_target (deps, tgt))
1129     return false;
1131   if (src->header.type != lang_input_section_enum)
1132     return false;
1133   if (tgt->header.type != lang_input_section_enum)
1134     return false;
1136   return deps_has_sec_edge (deps, src->input_section.section,
1137                             tgt->input_section.section);
1141 static void
1142 add_deps_edge (reloc_deps_graph *deps, asection *src_sec, asection *tgt_sec)
1144   reloc_deps_section *src_sec_deps;
1145   reloc_deps_section *tgt_sec_deps;
1147   reloc_deps_e *src_edge;
1148   reloc_deps_e *tgt_edge;
1150   if (deps_has_sec_edge (deps, src_sec, tgt_sec))
1151     return;
1153   src_sec_deps = xtensa_get_section_deps (deps, src_sec);
1154   if (src_sec_deps == NULL)
1155     {
1156       /* Add a section.  */
1157       src_sec_deps = xmalloc (sizeof (reloc_deps_section));
1158       memset (src_sec_deps, 0, sizeof (reloc_deps_section));
1159       src_sec_deps->is_only_literal = 0;
1160       src_sec_deps->preds = NULL;
1161       src_sec_deps->succs = NULL;
1162       xtensa_set_section_deps (deps, src_sec, src_sec_deps);
1163       xtensa_append_section_deps (deps, src_sec);
1164     }
1166   tgt_sec_deps = xtensa_get_section_deps (deps, tgt_sec);
1167   if (tgt_sec_deps == NULL)
1168     {
1169       /* Add a section.  */
1170       tgt_sec_deps = xmalloc (sizeof (reloc_deps_section));
1171       memset (tgt_sec_deps, 0, sizeof (reloc_deps_section));
1172       tgt_sec_deps->is_only_literal = 0;
1173       tgt_sec_deps->preds = NULL;
1174       tgt_sec_deps->succs = NULL;
1175       xtensa_set_section_deps (deps, tgt_sec, tgt_sec_deps);
1176       xtensa_append_section_deps (deps, tgt_sec);
1177     }
1179   /* Add the edges.  */
1180   src_edge = xmalloc (sizeof (reloc_deps_e));
1181   memset (src_edge, 0, sizeof (reloc_deps_e));
1182   src_edge->src = src_sec;
1183   src_edge->tgt = tgt_sec;
1184   src_edge->next = src_sec_deps->succs;
1185   src_sec_deps->succs = src_edge;
1187   tgt_edge = xmalloc (sizeof (reloc_deps_e));
1188   memset (tgt_edge, 0, sizeof (reloc_deps_e));
1189   tgt_edge->src = src_sec;
1190   tgt_edge->tgt = tgt_sec;
1191   tgt_edge->next = tgt_sec_deps->preds;
1192   tgt_sec_deps->preds = tgt_edge;
1196 static void
1197 build_deps_graph_callback (asection *src_sec,
1198                            bfd_vma src_offset ATTRIBUTE_UNUSED,
1199                            asection *target_sec,
1200                            bfd_vma target_offset ATTRIBUTE_UNUSED,
1201                            void *closure)
1203   reloc_deps_graph *deps = closure;
1205   /* If the target is defined.  */
1206   if (target_sec != NULL)
1207     add_deps_edge (deps, src_sec, target_sec);
1211 static reloc_deps_graph *
1212 ld_build_required_section_dependence (lang_statement_union_type *s)
1214   reloc_deps_graph *deps;
1215   xtensa_ld_iter_stack *stack = NULL;
1217   deps = xmalloc (sizeof (reloc_deps_graph));
1218   deps->sections = NULL;
1219   deps->count = 0;
1220   deps->size = 0;
1222   for (iter_stack_create (&stack, s);
1223        !iter_stack_empty (&stack);
1224        iter_stack_next (&stack))
1225     {
1226       lang_statement_union_type *l = iter_stack_current (&stack);
1228       if (l == NULL && link_info.non_contiguous_regions)
1229         fatal (_("%P: Relaxation not supported with "
1230                  "--enable-non-contiguous-regions.\n"));
1232       if (l->header.type == lang_input_section_enum)
1233         {
1234           lang_input_section_type *input;
1235           input = &l->input_section;
1236           xtensa_callback_required_dependence (input->section->owner,
1237                                                input->section,
1238                                                &link_info,
1239                                                /* Use the same closure.  */
1240                                                build_deps_graph_callback,
1241                                                deps);
1242         }
1243     }
1244   return deps;
1248 #if EXTRA_VALIDATION
1249 static size_t
1250 ld_count_children (lang_statement_union_type *s)
1252   size_t count = 0;
1253   xtensa_ld_iter_stack *stack = NULL;
1254   for (iter_stack_create (&stack, s);
1255        !iter_stack_empty (&stack);
1256        iter_stack_next (&stack))
1257     {
1258       lang_statement_union_type *l = iter_stack_current (&stack);
1259       ASSERT (l != NULL);
1260       count++;
1261     }
1262   return count;
1264 #endif /* EXTRA_VALIDATION */
1267 /* Check if a particular section is included in the link.  This will only
1268    be true for one instance of a particular linkonce section.  */
1270 static bool input_section_found = false;
1271 static asection *input_section_target = NULL;
1273 static void
1274 input_section_linked_worker (lang_statement_union_type *statement)
1276   if ((statement->header.type == lang_input_section_enum
1277        && (statement->input_section.section == input_section_target)))
1278     input_section_found = true;
1281 static bool
1282 input_section_linked (asection *sec)
1284   input_section_found = false;
1285   input_section_target = sec;
1286   lang_for_each_statement_worker (input_section_linked_worker, stat_ptr->head);
1287   return input_section_found;
1291 /* Strip out any linkonce property tables or XCC exception tables where the
1292    associated linkonce text is from a different object file.  Normally,
1293    a matching set of linkonce sections is taken from the same object file,
1294    but sometimes the files are compiled differently so that some of the
1295    linkonce sections are not present in all files.  Stripping the
1296    inconsistent sections like this is not completely robust -- a much
1297    better solution is to use comdat groups.  */
1299 static int linkonce_len = sizeof (".gnu.linkonce.") - 1;
1301 static bool
1302 is_inconsistent_linkonce_section (asection *sec)
1304   bfd *abfd = sec->owner;
1305   const char *sec_name = bfd_section_name (sec);
1306   const char *name;
1308   if ((bfd_section_flags (sec) & SEC_LINK_ONCE) == 0
1309       || strncmp (sec_name, ".gnu.linkonce.", linkonce_len) != 0)
1310     return false;
1312   /* Check if this is an Xtensa property section or an exception table
1313      for Tensilica's XCC compiler.  */
1314   name = sec_name + linkonce_len;
1315   if (startswith (name, "prop."))
1316     name = strchr (name + 5, '.') ? strchr (name + 5, '.') + 1 : name + 5;
1317   else if (name[1] == '.'
1318            && (name[0] == 'p' || name[0] == 'e' || name[0] == 'h'))
1319     name += 2;
1320   else
1321     name = 0;
1323   if (name)
1324     {
1325       char *dep_sec_name = xmalloc (strlen (sec_name) + 1);
1326       asection *dep_sec;
1328       /* Get the associated linkonce text section and check if it is
1329          included in the link.  If not, this section is inconsistent
1330          and should be stripped.  */
1331       strcpy (dep_sec_name, ".gnu.linkonce.t.");
1332       strcat (dep_sec_name, name);
1333       dep_sec = bfd_get_section_by_name (abfd, dep_sec_name);
1334       if (dep_sec == NULL || ! input_section_linked (dep_sec))
1335         {
1336           free (dep_sec_name);
1337           return true;
1338         }
1339       free (dep_sec_name);
1340     }
1342   return false;
1346 static void
1347 xtensa_strip_inconsistent_linkonce_sections (lang_statement_list_type *slist)
1349   lang_statement_union_type **s_p = &slist->head;
1350   while (*s_p)
1351     {
1352       lang_statement_union_type *s = *s_p;
1353       lang_statement_union_type *s_next = (*s_p)->header.next;
1355       switch (s->header.type)
1356         {
1357         case lang_input_section_enum:
1358           if (is_inconsistent_linkonce_section (s->input_section.section))
1359             {
1360               s->input_section.section->output_section = bfd_abs_section_ptr;
1361               *s_p = s_next;
1362               continue;
1363             }
1364           break;
1366         case lang_constructors_statement_enum:
1367           xtensa_strip_inconsistent_linkonce_sections (&constructor_list);
1368           break;
1370         case lang_output_section_statement_enum:
1371           if (s->output_section_statement.children.head)
1372             xtensa_strip_inconsistent_linkonce_sections
1373               (&s->output_section_statement.children);
1374           break;
1376         case lang_wild_statement_enum:
1377           xtensa_strip_inconsistent_linkonce_sections
1378             (&s->wild_statement.children);
1379           break;
1381         case lang_group_statement_enum:
1382           xtensa_strip_inconsistent_linkonce_sections
1383             (&s->group_statement.children);
1384           break;
1386         case lang_data_statement_enum:
1387         case lang_reloc_statement_enum:
1388         case lang_object_symbols_statement_enum:
1389         case lang_output_statement_enum:
1390         case lang_target_statement_enum:
1391         case lang_input_statement_enum:
1392         case lang_assignment_statement_enum:
1393         case lang_padding_statement_enum:
1394         case lang_address_statement_enum:
1395         case lang_fill_statement_enum:
1396           break;
1398         default:
1399           FAIL ();
1400           break;
1401         }
1403       s_p = &(*s_p)->header.next;
1404     }
1406   /* Reset the tail of the list, in case the last entry was removed.  */
1407   if (s_p != slist->tail)
1408     slist->tail = s_p;
1412 static void
1413 xtensa_wild_group_interleave_callback (lang_statement_union_type *statement)
1415   lang_wild_statement_type *w;
1416   reloc_deps_graph *deps;
1417   if (statement->header.type == lang_wild_statement_enum)
1418     {
1419 #if EXTRA_VALIDATION
1420       size_t old_child_count;
1421       size_t new_child_count;
1422 #endif
1423       bool no_reorder;
1425       w = &statement->wild_statement;
1427       no_reorder = false;
1429       /* If it has 0 or 1 section bound, then do not reorder.  */
1430       if (w->children.head == NULL
1431           || (w->children.head->header.type == lang_input_section_enum
1432               && w->children.head->header.next == NULL))
1433         no_reorder = true;
1435       if (w->filenames_sorted)
1436         no_reorder = true;
1438       /* Check for sorting in a section list wildcard spec as well.  */
1439       if (!no_reorder)
1440         {
1441           struct wildcard_list *l;
1442           for (l = w->section_list; l != NULL; l = l->next)
1443             {
1444               if (l->spec.sorted == by_name)
1445                 {
1446                   no_reorder = true;
1447                   break;
1448                 }
1449             }
1450         }
1452       /* Special case until the NOREORDER linker directive is supported:
1453          *(.init) output sections and *(.fini) specs may NOT be reordered.  */
1455       /* Check for sorting in a section list wildcard spec as well.  */
1456       if (!no_reorder)
1457         {
1458           struct wildcard_list *l;
1459           for (l = w->section_list; l != NULL; l = l->next)
1460             {
1461               if (l->spec.name
1462                   && ((strcmp (".init", l->spec.name) == 0)
1463                       || (strcmp (".fini", l->spec.name) == 0)))
1464                 {
1465                   no_reorder = true;
1466                   break;
1467                 }
1468             }
1469         }
1471 #if EXTRA_VALIDATION
1472       old_child_count = ld_count_children (statement);
1473 #endif
1475       /* It is now officially a target.  Build the graph of source
1476          section -> target section (kept as a list of edges).  */
1477       deps = ld_build_required_section_dependence (statement);
1479       /* If this wildcard does not reorder....  */
1480       if (!no_reorder && deps->count != 0)
1481         {
1482           /* First check for reverse dependences.  Fix if possible.  */
1483           xtensa_layout_wild (deps, w);
1485           xtensa_move_dependencies_to_front (deps, w);
1486 #if EXTRA_VALIDATION
1487           new_child_count = ld_count_children (statement);
1488           ASSERT (new_child_count == old_child_count);
1489 #endif
1491           xtensa_colocate_literals (deps, statement);
1493 #if EXTRA_VALIDATION
1494           new_child_count = ld_count_children (statement);
1495           ASSERT (new_child_count == old_child_count);
1496 #endif
1497         }
1499       /* Clean up.  */
1500       free_reloc_deps_graph (deps);
1501     }
1505 static void
1506 xtensa_wild_group_interleave (lang_statement_union_type *s)
1508   lang_for_each_statement_worker (xtensa_wild_group_interleave_callback, s);
1512 static void
1513 xtensa_layout_wild (const reloc_deps_graph *deps, lang_wild_statement_type *w)
1515   /* If it does not fit initially, we need to do this step.  Move all
1516      of the wild literal sections to a new list, then move each of
1517      them back in just before the first section they depend on.  */
1518   lang_statement_union_type **s_p;
1519 #if EXTRA_VALIDATION
1520   size_t old_count, new_count;
1521   size_t ct1, ct2;
1522 #endif
1524   lang_wild_statement_type literal_wild;
1525   literal_wild.header.next = NULL;
1526   literal_wild.header.type = lang_wild_statement_enum;
1527   literal_wild.filename = NULL;
1528   literal_wild.filenames_sorted = false;
1529   literal_wild.section_list = NULL;
1530   literal_wild.keep_sections = false;
1531   literal_wild.children.head = NULL;
1532   literal_wild.children.tail = &literal_wild.children.head;
1534 #if EXTRA_VALIDATION
1535   old_count = ld_count_children ((lang_statement_union_type*) w);
1536 #endif
1538   s_p = &w->children.head;
1539   while (*s_p != NULL)
1540     {
1541       lang_statement_union_type *l = *s_p;
1542       if (l->header.type == lang_input_section_enum)
1543         {
1544           if (section_is_target (deps, l)
1545               && ! section_is_source (deps, l))
1546             {
1547               /* Detach.  */
1548               *s_p = l->header.next;
1549               if (*s_p == NULL)
1550                 w->children.tail = s_p;
1551               l->header.next = NULL;
1553               /* Append.  */
1554               *literal_wild.children.tail = l;
1555               literal_wild.children.tail = &l->header.next;
1556               continue;
1557             }
1558         }
1559       s_p = &(*s_p)->header.next;
1560     }
1562 #if EXTRA_VALIDATION
1563   ct1 = ld_count_children ((lang_statement_union_type*) w);
1564   ct2 = ld_count_children ((lang_statement_union_type*) &literal_wild);
1566   ASSERT (old_count == (ct1 + ct2));
1567 #endif
1569   /* Now place them back in front of their dependent sections.  */
1571   while (literal_wild.children.head != NULL)
1572     {
1573       lang_statement_union_type *lit = literal_wild.children.head;
1574       bool placed = false;
1576 #if EXTRA_VALIDATION
1577       ASSERT (ct2 > 0);
1578       ct2--;
1579 #endif
1581       /* Detach.  */
1582       literal_wild.children.head = lit->header.next;
1583       if (literal_wild.children.head == NULL)
1584         literal_wild.children.tail = &literal_wild.children.head;
1585       lit->header.next = NULL;
1587       /* Find a spot to place it.  */
1588       for (s_p = &w->children.head; *s_p != NULL; s_p = &(*s_p)->header.next)
1589         {
1590           lang_statement_union_type *src = *s_p;
1591           if (deps_has_edge (deps, src, lit))
1592             {
1593               /* Place it here.  */
1594               lit->header.next = *s_p;
1595               *s_p = lit;
1596               placed = true;
1597               break;
1598             }
1599         }
1601       if (!placed)
1602         {
1603           /* Put it at the end.  */
1604           *w->children.tail = lit;
1605           w->children.tail = &lit->header.next;
1606         }
1607     }
1609 #if EXTRA_VALIDATION
1610   new_count = ld_count_children ((lang_statement_union_type*) w);
1611   ASSERT (new_count == old_count);
1612 #endif
1616 static void
1617 xtensa_colocate_output_literals_callback (lang_statement_union_type *statement)
1619   reloc_deps_graph *deps;
1620   if (statement->header.type == lang_output_section_statement_enum)
1621     {
1622       /* Now, we walk over the contours of the output section statement.
1624          First we build the literal section dependences as before.
1626          At the first uniquely_literal section, we mark it as a good
1627          spot to place other literals.  Continue walking (and counting
1628          sizes) until we find the next literal section.  If this
1629          section can be moved to the first one, then we move it.  If
1630          we every find a modification of ".", start over.  If we find
1631          a labeling of the current location, start over.  Finally, at
1632          the end, if we require page alignment, add page alignments.  */
1634 #if EXTRA_VALIDATION
1635       size_t old_child_count;
1636       size_t new_child_count;
1637 #endif
1638       bool no_reorder = false;
1640 #if EXTRA_VALIDATION
1641       old_child_count = ld_count_children (statement);
1642 #endif
1644       /* It is now officially a target.  Build the graph of source
1645          section -> target section (kept as a list of edges).  */
1647       deps = ld_build_required_section_dependence (statement);
1649       /* If this wildcard does not reorder....  */
1650       if (!no_reorder)
1651         {
1652           /* First check for reverse dependences.  Fix if possible.  */
1653           xtensa_colocate_literals (deps, statement);
1655 #if EXTRA_VALIDATION
1656           new_child_count = ld_count_children (statement);
1657           ASSERT (new_child_count == old_child_count);
1658 #endif
1659         }
1661       /* Insert align/offset assignment statement.  */
1662       if (xtensa_use_literal_pages)
1663         {
1664           ld_xtensa_insert_page_offsets (0, statement, deps,
1665                                          xtensa_use_literal_pages);
1666           lang_for_each_statement_worker (xtensa_ldlang_clear_addresses,
1667                                           statement);
1668         }
1670       /* Clean up.  */
1671       free_reloc_deps_graph (deps);
1672     }
1676 static void
1677 xtensa_colocate_output_literals (lang_statement_union_type *s)
1679   lang_for_each_statement_worker (xtensa_colocate_output_literals_callback, s);
1683 static void
1684 xtensa_ldlang_clear_addresses (lang_statement_union_type *statement)
1686   switch (statement->header.type)
1687     {
1688     case lang_input_section_enum:
1689       {
1690         asection *bfd_section = statement->input_section.section;
1691         bfd_section->output_offset = 0;
1692       }
1693       break;
1694     default:
1695       break;
1696     }
1700 static bfd_vma
1701 ld_assign_relative_paged_dot (bfd_vma dot,
1702                               lang_statement_union_type *s,
1703                               const reloc_deps_graph *deps ATTRIBUTE_UNUSED,
1704                               bool lit_align)
1706   /* Walk through all of the input statements in this wild statement
1707      assign dot to all of them.  */
1709   xtensa_ld_iter_stack *stack = NULL;
1710   xtensa_ld_iter_stack **stack_p = &stack;
1712   bool first_section = false;
1713   bool in_literals = false;
1715   for (iter_stack_create (stack_p, s);
1716        !iter_stack_empty (stack_p);
1717        iter_stack_next (stack_p))
1718     {
1719       lang_statement_union_type *l = iter_stack_current (stack_p);
1721       switch (l->header.type)
1722         {
1723         case lang_input_section_enum:
1724           {
1725             asection *section = l->input_section.section;
1726             size_t align_pow = section->alignment_power;
1727             bool do_xtensa_alignment = false;
1729             if (lit_align)
1730               {
1731                 bool sec_is_target = section_is_target (deps, l);
1732                 bool sec_is_source = section_is_source (deps, l);
1734                 if (section->size != 0
1735                     && (first_section
1736                         || (in_literals && !sec_is_target)
1737                         || (!in_literals && sec_is_target)))
1738                   {
1739                     do_xtensa_alignment = true;
1740                   }
1741                 first_section = false;
1742                 if (section->size != 0)
1743                   in_literals = (sec_is_target && !sec_is_source);
1744               }
1746             if (do_xtensa_alignment && xtensa_page_power != 0)
1747               dot += (1 << xtensa_page_power);
1749             dot = align_power (dot, align_pow);
1750             section->output_offset = dot;
1751             dot += section->size;
1752           }
1753           break;
1754         case lang_fill_statement_enum:
1755           dot += l->fill_statement.size;
1756           break;
1757         case lang_padding_statement_enum:
1758           dot += l->padding_statement.size;
1759           break;
1760         default:
1761           break;
1762         }
1763     }
1764   return dot;
1768 static bool
1769 ld_local_file_relocations_fit (lang_statement_union_type *statement,
1770                                const reloc_deps_graph *deps ATTRIBUTE_UNUSED)
1772   /* Walk over all of the dependencies that we identified and make
1773      sure that IF the source and target are here (addr != 0):
1774      1) target addr < source addr
1775      2) (roundup(source + source_size, 4) - rounddown(target, 4))
1776         < (256K - (1 << bad align))
1777      Need a worst-case proof....  */
1779   xtensa_ld_iter_stack *stack = NULL;
1780   xtensa_ld_iter_stack **stack_p = &stack;
1781   size_t max_align_power = 0;
1782   size_t align_penalty = 256;
1783   reloc_deps_e *e;
1784   size_t i;
1786   /* Find the worst-case alignment requirement for this set of statements.  */
1787   for (iter_stack_create (stack_p, statement);
1788        !iter_stack_empty (stack_p);
1789        iter_stack_next (stack_p))
1790     {
1791       lang_statement_union_type *l = iter_stack_current (stack_p);
1792       if (l->header.type == lang_input_section_enum)
1793         {
1794           lang_input_section_type *input = &l->input_section;
1795           asection *section = input->section;
1796           if (section->alignment_power > max_align_power)
1797             max_align_power = section->alignment_power;
1798         }
1799     }
1801   /* Now check that everything fits.  */
1802   for (i = 0; i < deps->count; i++)
1803     {
1804       asection *sec = deps->sections[i];
1805       const reloc_deps_section *deps_section =
1806         xtensa_get_section_deps (deps, sec);
1807       if (deps_section)
1808         {
1809           /* We choose to walk through the successors.  */
1810           for (e = deps_section->succs; e != NULL; e = e->next)
1811             {
1812               if (e->src != e->tgt
1813                   && e->src->output_section == e->tgt->output_section
1814                   && e->src->output_offset != 0
1815                   && e->tgt->output_offset != 0)
1816                 {
1817                   bfd_vma l32r_addr =
1818                     align_power (e->src->output_offset + e->src->size, 2);
1819                   bfd_vma target_addr = e->tgt->output_offset & ~3;
1820                   if (l32r_addr < target_addr)
1821                     {
1822                       fflush (stdout);
1823                       fprintf (stderr, "Warning: "
1824                                "l32r target section before l32r\n");
1825                       fflush (stderr);
1826                       return false;
1827                     }
1829                   if (l32r_addr - target_addr > 256 * 1024 - align_penalty)
1830                     return false;
1831                 }
1832             }
1833         }
1834     }
1836   return true;
1840 static bfd_vma
1841 ld_xtensa_insert_page_offsets (bfd_vma dot,
1842                                lang_statement_union_type *s,
1843                                reloc_deps_graph *deps,
1844                                bool lit_align)
1846   xtensa_ld_iter_stack *stack = NULL;
1847   xtensa_ld_iter_stack **stack_p = &stack;
1849   bool first_section = false;
1850   bool in_literals = false;
1852   if (!lit_align)
1853     return false;
1855   for (iter_stack_create (stack_p, s);
1856        !iter_stack_empty (stack_p);
1857        iter_stack_next (stack_p))
1858     {
1859       lang_statement_union_type *l = iter_stack_current (stack_p);
1861       switch (l->header.type)
1862         {
1863         case lang_input_section_enum:
1864           {
1865             asection *section = l->input_section.section;
1866             bool do_xtensa_alignment = false;
1868             if (lit_align)
1869               {
1870                 if (section->size != 0
1871                     && (first_section
1872                         || (in_literals && !section_is_target (deps, l))
1873                         || (!in_literals && section_is_target (deps, l))))
1874                   {
1875                     do_xtensa_alignment = true;
1876                   }
1877                 first_section = false;
1878                 if (section->size != 0)
1879                   {
1880                     in_literals = (section_is_target (deps, l)
1881                                    && !section_is_source (deps, l));
1882                   }
1883               }
1885             if (do_xtensa_alignment && xtensa_page_power != 0)
1886               {
1887                 /* Create an expression that increments the current address,
1888                    i.e., "dot", by (1 << xtensa_align_power).  */
1889                 etree_type *name_op = exp_nameop (NAME, ".");
1890                 etree_type *addend_op = exp_intop (1 << xtensa_page_power);
1891                 etree_type *add_op = exp_binop ('+', name_op, addend_op);
1892                 etree_type *assign_op = exp_assign (".", add_op, false);
1894                 lang_assignment_statement_type *assign_stmt;
1895                 lang_statement_union_type *assign_union;
1896                 lang_statement_list_type tmplist;
1898                 /* There is hidden state in "lang_add_assignment".  It
1899                    appends the new assignment statement to the stat_ptr
1900                    list.  Thus, we swap it before and after the call.  */
1902                 lang_list_init (&tmplist);
1903                 push_stat_ptr (&tmplist);
1904                 /* Warning: side effect; statement appended to stat_ptr.  */
1905                 assign_stmt = lang_add_assignment (assign_op);
1906                 assign_union = (lang_statement_union_type *) assign_stmt;
1907                 pop_stat_ptr ();
1909                 assign_union->header.next = l;
1910                 *(*stack_p)->iterloc.loc = assign_union;
1911                 iter_stack_next (stack_p);
1912               }
1913           }
1914           break;
1915         default:
1916           break;
1917         }
1918     }
1919   return dot;
1924 # Define some shell vars to insert bits of code into the standard ELF
1925 # parse_args and list_options functions.
1927 PARSE_AND_LIST_LONGOPTS='
1928   { "size-opt", no_argument, NULL, OPTION_OPT_SIZEOPT},
1929   { "literal-movement", no_argument, NULL, OPTION_LITERAL_MOVEMENT},
1930   { "no-literal-movement", no_argument, NULL, OPTION_NO_LITERAL_MOVEMENT},
1931   { "abi-windowed", no_argument, NULL, OPTION_ABI_WINDOWED},
1932   { "abi-call0", no_argument, NULL, OPTION_ABI_CALL0},
1935 PARSE_AND_LIST_OPTIONS='
1936   fprintf (file, _("\
1937   --size-opt                  When relaxing longcalls, prefer size\n\
1938                                 optimization over branch target alignment\n"));
1939   fprintf (file, _("\
1940   --abi-windowed              Choose windowed ABI for the output object\n"));
1941   fprintf (file, _("\
1942   --abi-call0                 Choose call0 ABI for the output object\n"));
1945 PARSE_AND_LIST_ARGS_CASES='
1946     case OPTION_OPT_SIZEOPT:
1947       elf32xtensa_size_opt = 1;
1948       break;
1949     case OPTION_LITERAL_MOVEMENT:
1950       elf32xtensa_no_literal_movement = 0;
1951       break;
1952     case OPTION_NO_LITERAL_MOVEMENT:
1953       elf32xtensa_no_literal_movement = 1;
1954       break;
1955     case OPTION_ABI_WINDOWED:
1956       elf32xtensa_abi = XTHAL_ABI_WINDOWED;
1957       break;
1958     case OPTION_ABI_CALL0:
1959       elf32xtensa_abi = XTHAL_ABI_CALL0;
1960       break;
1963 # Replace some of the standard ELF functions with our own versions.
1965 LDEMUL_BEFORE_PARSE=elf_xtensa_before_parse
1966 LDEMUL_AFTER_OPEN=elf_xtensa_after_open
1967 LDEMUL_CHOOSE_TARGET=elf_xtensa_choose_target
1968 LDEMUL_BEFORE_ALLOCATION=elf_xtensa_before_allocation