Support --localedir, --datarootdir and --datadir
[external/binutils.git] / gold / powerpc.cc
1 // powerpc.cc -- powerpc target support for gold.
2
3 // Copyright (C) 2008-2017 Free Software Foundation, Inc.
4 // Written by David S. Miller <davem@davemloft.net>
5 //        and David Edelsohn <edelsohn@gnu.org>
6
7 // This file is part of gold.
8
9 // This program is free software; you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation; either version 3 of the License, or
12 // (at your option) any later version.
13
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 // GNU General Public License for more details.
18
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
22 // MA 02110-1301, USA.
23
24 #include "gold.h"
25
26 #include <set>
27 #include <algorithm>
28 #include "elfcpp.h"
29 #include "dwarf.h"
30 #include "parameters.h"
31 #include "reloc.h"
32 #include "powerpc.h"
33 #include "object.h"
34 #include "symtab.h"
35 #include "layout.h"
36 #include "output.h"
37 #include "copy-relocs.h"
38 #include "target.h"
39 #include "target-reloc.h"
40 #include "target-select.h"
41 #include "tls.h"
42 #include "errors.h"
43 #include "gc.h"
44
45 namespace
46 {
47
48 using namespace gold;
49
50 template<int size, bool big_endian>
51 class Output_data_plt_powerpc;
52
53 template<int size, bool big_endian>
54 class Output_data_brlt_powerpc;
55
56 template<int size, bool big_endian>
57 class Output_data_got_powerpc;
58
59 template<int size, bool big_endian>
60 class Output_data_glink;
61
62 template<int size, bool big_endian>
63 class Stub_table;
64
65 template<int size, bool big_endian>
66 class Output_data_save_res;
67
68 template<int size, bool big_endian>
69 class Target_powerpc;
70
71 struct Stub_table_owner
72 {
73   Stub_table_owner()
74     : output_section(NULL), owner(NULL)
75   { }
76
77   Output_section* output_section;
78   const Output_section::Input_section* owner;
79 };
80
81 inline bool
82 is_branch_reloc(unsigned int r_type);
83
84 // Counter incremented on every Powerpc_relobj constructed.
85 static uint32_t object_id = 0;
86
87 template<int size, bool big_endian>
88 class Powerpc_relobj : public Sized_relobj_file<size, big_endian>
89 {
90 public:
91   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
92   typedef Unordered_set<Section_id, Section_id_hash> Section_refs;
93   typedef Unordered_map<Address, Section_refs> Access_from;
94
95   Powerpc_relobj(const std::string& name, Input_file* input_file, off_t offset,
96                  const typename elfcpp::Ehdr<size, big_endian>& ehdr)
97     : Sized_relobj_file<size, big_endian>(name, input_file, offset, ehdr),
98       uniq_(object_id++), special_(0), relatoc_(0), toc_(0),
99       has_small_toc_reloc_(false), opd_valid_(false),
100       e_flags_(ehdr.get_e_flags()), no_toc_opt_(), opd_ent_(),
101       access_from_map_(), has14_(), stub_table_index_(), st_other_()
102   {
103     this->set_abiversion(0);
104   }
105
106   ~Powerpc_relobj()
107   { }
108
109   // Read the symbols then set up st_other vector.
110   void
111   do_read_symbols(Read_symbols_data*);
112
113   // Arrange to always relocate .toc first.
114   virtual void
115   do_relocate_sections(
116       const Symbol_table* symtab, const Layout* layout,
117       const unsigned char* pshdrs, Output_file* of,
118       typename Sized_relobj_file<size, big_endian>::Views* pviews);
119
120   // The .toc section index.
121   unsigned int
122   toc_shndx() const
123   {
124     return this->toc_;
125   }
126
127   // Mark .toc entry at OFF as not optimizable.
128   void
129   set_no_toc_opt(Address off)
130   {
131     if (this->no_toc_opt_.empty())
132       this->no_toc_opt_.resize(this->section_size(this->toc_shndx())
133                                / (size / 8));
134     off /= size / 8;
135     if (off < this->no_toc_opt_.size())
136       this->no_toc_opt_[off] = true;
137   }
138
139   // Mark the entire .toc as not optimizable.
140   void
141   set_no_toc_opt()
142   {
143     this->no_toc_opt_.resize(1);
144     this->no_toc_opt_[0] = true;
145   }
146
147   // Return true if code using the .toc entry at OFF should not be edited.
148   bool
149   no_toc_opt(Address off) const
150   {
151     if (this->no_toc_opt_.empty())
152       return false;
153     off /= size / 8;
154     if (off >= this->no_toc_opt_.size())
155       return true;
156     return this->no_toc_opt_[off];
157   }
158
159   // The .got2 section shndx.
160   unsigned int
161   got2_shndx() const
162   {
163     if (size == 32)
164       return this->special_;
165     else
166       return 0;
167   }
168
169   // The .opd section shndx.
170   unsigned int
171   opd_shndx() const
172   {
173     if (size == 32)
174       return 0;
175     else
176       return this->special_;
177   }
178
179   // Init OPD entry arrays.
180   void
181   init_opd(size_t opd_size)
182   {
183     size_t count = this->opd_ent_ndx(opd_size);
184     this->opd_ent_.resize(count);
185   }
186
187   // Return section and offset of function entry for .opd + R_OFF.
188   unsigned int
189   get_opd_ent(Address r_off, Address* value = NULL) const
190   {
191     size_t ndx = this->opd_ent_ndx(r_off);
192     gold_assert(ndx < this->opd_ent_.size());
193     gold_assert(this->opd_ent_[ndx].shndx != 0);
194     if (value != NULL)
195       *value = this->opd_ent_[ndx].off;
196     return this->opd_ent_[ndx].shndx;
197   }
198
199   // Set section and offset of function entry for .opd + R_OFF.
200   void
201   set_opd_ent(Address r_off, unsigned int shndx, Address value)
202   {
203     size_t ndx = this->opd_ent_ndx(r_off);
204     gold_assert(ndx < this->opd_ent_.size());
205     this->opd_ent_[ndx].shndx = shndx;
206     this->opd_ent_[ndx].off = value;
207   }
208
209   // Return discard flag for .opd + R_OFF.
210   bool
211   get_opd_discard(Address r_off) const
212   {
213     size_t ndx = this->opd_ent_ndx(r_off);
214     gold_assert(ndx < this->opd_ent_.size());
215     return this->opd_ent_[ndx].discard;
216   }
217
218   // Set discard flag for .opd + R_OFF.
219   void
220   set_opd_discard(Address r_off)
221   {
222     size_t ndx = this->opd_ent_ndx(r_off);
223     gold_assert(ndx < this->opd_ent_.size());
224     this->opd_ent_[ndx].discard = true;
225   }
226
227   bool
228   opd_valid() const
229   { return this->opd_valid_; }
230
231   void
232   set_opd_valid()
233   { this->opd_valid_ = true; }
234
235   // Examine .rela.opd to build info about function entry points.
236   void
237   scan_opd_relocs(size_t reloc_count,
238                   const unsigned char* prelocs,
239                   const unsigned char* plocal_syms);
240
241   // Returns true if a code sequence loading a TOC entry can be
242   // converted into code calculating a TOC pointer relative offset.
243   bool
244   make_toc_relative(Target_powerpc<size, big_endian>* target,
245                     Address* value);
246
247   // Perform the Sized_relobj_file method, then set up opd info from
248   // .opd relocs.
249   void
250   do_read_relocs(Read_relocs_data*);
251
252   bool
253   do_find_special_sections(Read_symbols_data* sd);
254
255   // Adjust this local symbol value.  Return false if the symbol
256   // should be discarded from the output file.
257   bool
258   do_adjust_local_symbol(Symbol_value<size>* lv) const
259   {
260     if (size == 64 && this->opd_shndx() != 0)
261       {
262         bool is_ordinary;
263         if (lv->input_shndx(&is_ordinary) != this->opd_shndx())
264           return true;
265         if (this->get_opd_discard(lv->input_value()))
266           return false;
267       }
268     return true;
269   }
270
271   Access_from*
272   access_from_map()
273   { return &this->access_from_map_; }
274
275   // Add a reference from SRC_OBJ, SRC_INDX to this object's .opd
276   // section at DST_OFF.
277   void
278   add_reference(Relobj* src_obj,
279                 unsigned int src_indx,
280                 typename elfcpp::Elf_types<size>::Elf_Addr dst_off)
281   {
282     Section_id src_id(src_obj, src_indx);
283     this->access_from_map_[dst_off].insert(src_id);
284   }
285
286   // Add a reference to the code section specified by the .opd entry
287   // at DST_OFF
288   void
289   add_gc_mark(typename elfcpp::Elf_types<size>::Elf_Addr dst_off)
290   {
291     size_t ndx = this->opd_ent_ndx(dst_off);
292     if (ndx >= this->opd_ent_.size())
293       this->opd_ent_.resize(ndx + 1);
294     this->opd_ent_[ndx].gc_mark = true;
295   }
296
297   void
298   process_gc_mark(Symbol_table* symtab)
299   {
300     for (size_t i = 0; i < this->opd_ent_.size(); i++)
301       if (this->opd_ent_[i].gc_mark)
302         {
303           unsigned int shndx = this->opd_ent_[i].shndx;
304           symtab->gc()->worklist().push_back(Section_id(this, shndx));
305         }
306   }
307
308   // Return offset in output GOT section that this object will use
309   // as a TOC pointer.  Won't be just a constant with multi-toc support.
310   Address
311   toc_base_offset() const
312   { return 0x8000; }
313
314   void
315   set_has_small_toc_reloc()
316   { has_small_toc_reloc_ = true; }
317
318   bool
319   has_small_toc_reloc() const
320   { return has_small_toc_reloc_; }
321
322   void
323   set_has_14bit_branch(unsigned int shndx)
324   {
325     if (shndx >= this->has14_.size())
326       this->has14_.resize(shndx + 1);
327     this->has14_[shndx] = true;
328   }
329
330   bool
331   has_14bit_branch(unsigned int shndx) const
332   { return shndx < this->has14_.size() && this->has14_[shndx];  }
333
334   void
335   set_stub_table(unsigned int shndx, unsigned int stub_index)
336   {
337     if (shndx >= this->stub_table_index_.size())
338       this->stub_table_index_.resize(shndx + 1, -1);
339     this->stub_table_index_[shndx] = stub_index;
340   }
341
342   Stub_table<size, big_endian>*
343   stub_table(unsigned int shndx)
344   {
345     if (shndx < this->stub_table_index_.size())
346       {
347         Target_powerpc<size, big_endian>* target
348           = static_cast<Target_powerpc<size, big_endian>*>(
349               parameters->sized_target<size, big_endian>());
350         unsigned int indx = this->stub_table_index_[shndx];
351         if (indx < target->stub_tables().size())
352           return target->stub_tables()[indx];
353       }
354     return NULL;
355   }
356
357   void
358   clear_stub_table()
359   {
360     this->stub_table_index_.clear();
361   }
362
363   uint32_t
364   uniq() const
365   { return this->uniq_; }
366
367   int
368   abiversion() const
369   { return this->e_flags_ & elfcpp::EF_PPC64_ABI; }
370
371   // Set ABI version for input and output
372   void
373   set_abiversion(int ver);
374
375   unsigned int
376   st_other (unsigned int symndx) const
377   {
378     return this->st_other_[symndx];
379   }
380
381   unsigned int
382   ppc64_local_entry_offset(const Symbol* sym) const
383   { return elfcpp::ppc64_decode_local_entry(sym->nonvis() >> 3); }
384
385   unsigned int
386   ppc64_local_entry_offset(unsigned int symndx) const
387   { return elfcpp::ppc64_decode_local_entry(this->st_other_[symndx] >> 5); }
388
389 private:
390   struct Opd_ent
391   {
392     unsigned int shndx;
393     bool discard : 1;
394     bool gc_mark : 1;
395     Address off;
396   };
397
398   // Return index into opd_ent_ array for .opd entry at OFF.
399   // .opd entries are 24 bytes long, but they can be spaced 16 bytes
400   // apart when the language doesn't use the last 8-byte word, the
401   // environment pointer.  Thus dividing the entry section offset by
402   // 16 will give an index into opd_ent_ that works for either layout
403   // of .opd.  (It leaves some elements of the vector unused when .opd
404   // entries are spaced 24 bytes apart, but we don't know the spacing
405   // until relocations are processed, and in any case it is possible
406   // for an object to have some entries spaced 16 bytes apart and
407   // others 24 bytes apart.)
408   size_t
409   opd_ent_ndx(size_t off) const
410   { return off >> 4;}
411
412   // Per object unique identifier
413   uint32_t uniq_;
414
415   // For 32-bit the .got2 section shdnx, for 64-bit the .opd section shndx.
416   unsigned int special_;
417
418   // For 64-bit the .rela.toc and .toc section shdnx.
419   unsigned int relatoc_;
420   unsigned int toc_;
421
422   // For 64-bit, whether this object uses small model relocs to access
423   // the toc.
424   bool has_small_toc_reloc_;
425
426   // Set at the start of gc_process_relocs, when we know opd_ent_
427   // vector is valid.  The flag could be made atomic and set in
428   // do_read_relocs with memory_order_release and then tested with
429   // memory_order_acquire, potentially resulting in fewer entries in
430   // access_from_map_.
431   bool opd_valid_;
432
433   // Header e_flags
434   elfcpp::Elf_Word e_flags_;
435
436   // For 64-bit, an array with one entry per 64-bit word in the .toc
437   // section, set if accesses using that word cannot be optimised.
438   std::vector<bool> no_toc_opt_;
439
440   // The first 8-byte word of an OPD entry gives the address of the
441   // entry point of the function.  Relocatable object files have a
442   // relocation on this word.  The following vector records the
443   // section and offset specified by these relocations.
444   std::vector<Opd_ent> opd_ent_;
445
446   // References made to this object's .opd section when running
447   // gc_process_relocs for another object, before the opd_ent_ vector
448   // is valid for this object.
449   Access_from access_from_map_;
450
451   // Whether input section has a 14-bit branch reloc.
452   std::vector<bool> has14_;
453
454   // The stub table to use for a given input section.
455   std::vector<unsigned int> stub_table_index_;
456
457   // ELF st_other field for local symbols.
458   std::vector<unsigned char> st_other_;
459 };
460
461 template<int size, bool big_endian>
462 class Powerpc_dynobj : public Sized_dynobj<size, big_endian>
463 {
464 public:
465   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
466
467   Powerpc_dynobj(const std::string& name, Input_file* input_file, off_t offset,
468                  const typename elfcpp::Ehdr<size, big_endian>& ehdr)
469     : Sized_dynobj<size, big_endian>(name, input_file, offset, ehdr),
470       opd_shndx_(0), e_flags_(ehdr.get_e_flags()), opd_ent_()
471   {
472     this->set_abiversion(0);
473   }
474
475   ~Powerpc_dynobj()
476   { }
477
478   // Call Sized_dynobj::do_read_symbols to read the symbols then
479   // read .opd from a dynamic object, filling in opd_ent_ vector,
480   void
481   do_read_symbols(Read_symbols_data*);
482
483   // The .opd section shndx.
484   unsigned int
485   opd_shndx() const
486   {
487     return this->opd_shndx_;
488   }
489
490   // The .opd section address.
491   Address
492   opd_address() const
493   {
494     return this->opd_address_;
495   }
496
497   // Init OPD entry arrays.
498   void
499   init_opd(size_t opd_size)
500   {
501     size_t count = this->opd_ent_ndx(opd_size);
502     this->opd_ent_.resize(count);
503   }
504
505   // Return section and offset of function entry for .opd + R_OFF.
506   unsigned int
507   get_opd_ent(Address r_off, Address* value = NULL) const
508   {
509     size_t ndx = this->opd_ent_ndx(r_off);
510     gold_assert(ndx < this->opd_ent_.size());
511     gold_assert(this->opd_ent_[ndx].shndx != 0);
512     if (value != NULL)
513       *value = this->opd_ent_[ndx].off;
514     return this->opd_ent_[ndx].shndx;
515   }
516
517   // Set section and offset of function entry for .opd + R_OFF.
518   void
519   set_opd_ent(Address r_off, unsigned int shndx, Address value)
520   {
521     size_t ndx = this->opd_ent_ndx(r_off);
522     gold_assert(ndx < this->opd_ent_.size());
523     this->opd_ent_[ndx].shndx = shndx;
524     this->opd_ent_[ndx].off = value;
525   }
526
527   int
528   abiversion() const
529   { return this->e_flags_ & elfcpp::EF_PPC64_ABI; }
530
531   // Set ABI version for input and output.
532   void
533   set_abiversion(int ver);
534
535 private:
536   // Used to specify extent of executable sections.
537   struct Sec_info
538   {
539     Sec_info(Address start_, Address len_, unsigned int shndx_)
540       : start(start_), len(len_), shndx(shndx_)
541     { }
542
543     bool
544     operator<(const Sec_info& that) const
545     { return this->start < that.start; }
546
547     Address start;
548     Address len;
549     unsigned int shndx;
550   };
551
552   struct Opd_ent
553   {
554     unsigned int shndx;
555     Address off;
556   };
557
558   // Return index into opd_ent_ array for .opd entry at OFF.
559   size_t
560   opd_ent_ndx(size_t off) const
561   { return off >> 4;}
562
563   // For 64-bit the .opd section shndx and address.
564   unsigned int opd_shndx_;
565   Address opd_address_;
566
567   // Header e_flags
568   elfcpp::Elf_Word e_flags_;
569
570   // The first 8-byte word of an OPD entry gives the address of the
571   // entry point of the function.  Records the section and offset
572   // corresponding to the address.  Note that in dynamic objects,
573   // offset is *not* relative to the section.
574   std::vector<Opd_ent> opd_ent_;
575 };
576
577 // Powerpc_copy_relocs class.  Needed to peek at dynamic relocs the
578 // base class will emit.
579
580 template<int sh_type, int size, bool big_endian>
581 class Powerpc_copy_relocs : public Copy_relocs<sh_type, size, big_endian>
582 {
583  public:
584   Powerpc_copy_relocs()
585     : Copy_relocs<sh_type, size, big_endian>(elfcpp::R_POWERPC_COPY)
586   { }
587
588   // Emit any saved relocations which turn out to be needed.  This is
589   // called after all the relocs have been scanned.
590   void
591   emit(Output_data_reloc<sh_type, true, size, big_endian>*);
592 };
593
594 template<int size, bool big_endian>
595 class Target_powerpc : public Sized_target<size, big_endian>
596 {
597  public:
598   typedef
599     Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian> Reloc_section;
600   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
601   typedef typename elfcpp::Elf_types<size>::Elf_Swxword Signed_address;
602   typedef Unordered_set<Symbol_location, Symbol_location_hash> Tocsave_loc;
603   static const Address invalid_address = static_cast<Address>(0) - 1;
604   // Offset of tp and dtp pointers from start of TLS block.
605   static const Address tp_offset = 0x7000;
606   static const Address dtp_offset = 0x8000;
607
608   Target_powerpc()
609     : Sized_target<size, big_endian>(&powerpc_info),
610       got_(NULL), plt_(NULL), iplt_(NULL), brlt_section_(NULL),
611       glink_(NULL), rela_dyn_(NULL), copy_relocs_(),
612       tlsld_got_offset_(-1U),
613       stub_tables_(), branch_lookup_table_(), branch_info_(), tocsave_loc_(),
614       plt_thread_safe_(false), plt_localentry0_(false),
615       plt_localentry0_init_(false), has_localentry0_(false),
616       has_tls_get_addr_opt_(false),
617       relax_failed_(false), relax_fail_count_(0),
618       stub_group_size_(0), savres_section_(0),
619       tls_get_addr_(NULL), tls_get_addr_opt_(NULL)
620   {
621   }
622
623   // Process the relocations to determine unreferenced sections for
624   // garbage collection.
625   void
626   gc_process_relocs(Symbol_table* symtab,
627                     Layout* layout,
628                     Sized_relobj_file<size, big_endian>* object,
629                     unsigned int data_shndx,
630                     unsigned int sh_type,
631                     const unsigned char* prelocs,
632                     size_t reloc_count,
633                     Output_section* output_section,
634                     bool needs_special_offset_handling,
635                     size_t local_symbol_count,
636                     const unsigned char* plocal_symbols);
637
638   // Scan the relocations to look for symbol adjustments.
639   void
640   scan_relocs(Symbol_table* symtab,
641               Layout* layout,
642               Sized_relobj_file<size, big_endian>* object,
643               unsigned int data_shndx,
644               unsigned int sh_type,
645               const unsigned char* prelocs,
646               size_t reloc_count,
647               Output_section* output_section,
648               bool needs_special_offset_handling,
649               size_t local_symbol_count,
650               const unsigned char* plocal_symbols);
651
652   // Map input .toc section to output .got section.
653   const char*
654   do_output_section_name(const Relobj*, const char* name, size_t* plen) const
655   {
656     if (size == 64 && strcmp(name, ".toc") == 0)
657       {
658         *plen = 4;
659         return ".got";
660       }
661     return NULL;
662   }
663
664   // Provide linker defined save/restore functions.
665   void
666   define_save_restore_funcs(Layout*, Symbol_table*);
667
668   // No stubs unless a final link.
669   bool
670   do_may_relax() const
671   { return !parameters->options().relocatable(); }
672
673   bool
674   do_relax(int, const Input_objects*, Symbol_table*, Layout*, const Task*);
675
676   void
677   do_plt_fde_location(const Output_data*, unsigned char*,
678                       uint64_t*, off_t*) const;
679
680   // Stash info about branches, for stub generation.
681   void
682   push_branch(Powerpc_relobj<size, big_endian>* ppc_object,
683               unsigned int data_shndx, Address r_offset,
684               unsigned int r_type, unsigned int r_sym, Address addend)
685   {
686     Branch_info info(ppc_object, data_shndx, r_offset, r_type, r_sym, addend);
687     this->branch_info_.push_back(info);
688     if (r_type == elfcpp::R_POWERPC_REL14
689         || r_type == elfcpp::R_POWERPC_REL14_BRTAKEN
690         || r_type == elfcpp::R_POWERPC_REL14_BRNTAKEN)
691       ppc_object->set_has_14bit_branch(data_shndx);
692   }
693
694   // Return whether the last branch is a plt call, and if so, mark the
695   // branch as having an R_PPC64_TOCSAVE.
696   bool
697   mark_pltcall(Powerpc_relobj<size, big_endian>* ppc_object,
698                unsigned int data_shndx, Address r_offset, Symbol_table* symtab)
699   {
700     return (size == 64
701             && !this->branch_info_.empty()
702             && this->branch_info_.back().mark_pltcall(ppc_object, data_shndx,
703                                                       r_offset, this, symtab));
704   }
705
706   // Say the given location, that of a nop in a function prologue with
707   // an R_PPC64_TOCSAVE reloc, will be used to save r2.
708   // R_PPC64_TOCSAVE relocs on nops following calls point at this nop.
709   void
710   add_tocsave(Powerpc_relobj<size, big_endian>* ppc_object,
711               unsigned int shndx, Address offset)
712   {
713     Symbol_location loc;
714     loc.object = ppc_object;
715     loc.shndx = shndx;
716     loc.offset = offset;
717     this->tocsave_loc_.insert(loc);
718   }
719
720   // Accessor
721   const Tocsave_loc
722   tocsave_loc() const
723   {
724     return this->tocsave_loc_;
725   }
726
727   void
728   do_define_standard_symbols(Symbol_table*, Layout*);
729
730   // Finalize the sections.
731   void
732   do_finalize_sections(Layout*, const Input_objects*, Symbol_table*);
733
734   // Return the value to use for a dynamic which requires special
735   // treatment.
736   uint64_t
737   do_dynsym_value(const Symbol*) const;
738
739   // Return the PLT address to use for a local symbol.
740   uint64_t
741   do_plt_address_for_local(const Relobj*, unsigned int) const;
742
743   // Return the PLT address to use for a global symbol.
744   uint64_t
745   do_plt_address_for_global(const Symbol*) const;
746
747   // Return the offset to use for the GOT_INDX'th got entry which is
748   // for a local tls symbol specified by OBJECT, SYMNDX.
749   int64_t
750   do_tls_offset_for_local(const Relobj* object,
751                           unsigned int symndx,
752                           unsigned int got_indx) const;
753
754   // Return the offset to use for the GOT_INDX'th got entry which is
755   // for global tls symbol GSYM.
756   int64_t
757   do_tls_offset_for_global(Symbol* gsym, unsigned int got_indx) const;
758
759   void
760   do_function_location(Symbol_location*) const;
761
762   bool
763   do_can_check_for_function_pointers() const
764   { return true; }
765
766   // Adjust -fsplit-stack code which calls non-split-stack code.
767   void
768   do_calls_non_split(Relobj* object, unsigned int shndx,
769                      section_offset_type fnoffset, section_size_type fnsize,
770                      const unsigned char* prelocs, size_t reloc_count,
771                      unsigned char* view, section_size_type view_size,
772                      std::string* from, std::string* to) const;
773
774   // Relocate a section.
775   void
776   relocate_section(const Relocate_info<size, big_endian>*,
777                    unsigned int sh_type,
778                    const unsigned char* prelocs,
779                    size_t reloc_count,
780                    Output_section* output_section,
781                    bool needs_special_offset_handling,
782                    unsigned char* view,
783                    Address view_address,
784                    section_size_type view_size,
785                    const Reloc_symbol_changes*);
786
787   // Scan the relocs during a relocatable link.
788   void
789   scan_relocatable_relocs(Symbol_table* symtab,
790                           Layout* layout,
791                           Sized_relobj_file<size, big_endian>* object,
792                           unsigned int data_shndx,
793                           unsigned int sh_type,
794                           const unsigned char* prelocs,
795                           size_t reloc_count,
796                           Output_section* output_section,
797                           bool needs_special_offset_handling,
798                           size_t local_symbol_count,
799                           const unsigned char* plocal_symbols,
800                           Relocatable_relocs*);
801
802   // Scan the relocs for --emit-relocs.
803   void
804   emit_relocs_scan(Symbol_table* symtab,
805                    Layout* layout,
806                    Sized_relobj_file<size, big_endian>* object,
807                    unsigned int data_shndx,
808                    unsigned int sh_type,
809                    const unsigned char* prelocs,
810                    size_t reloc_count,
811                    Output_section* output_section,
812                    bool needs_special_offset_handling,
813                    size_t local_symbol_count,
814                    const unsigned char* plocal_syms,
815                    Relocatable_relocs* rr);
816
817   // Emit relocations for a section.
818   void
819   relocate_relocs(const Relocate_info<size, big_endian>*,
820                   unsigned int sh_type,
821                   const unsigned char* prelocs,
822                   size_t reloc_count,
823                   Output_section* output_section,
824                   typename elfcpp::Elf_types<size>::Elf_Off
825                     offset_in_output_section,
826                   unsigned char*,
827                   Address view_address,
828                   section_size_type,
829                   unsigned char* reloc_view,
830                   section_size_type reloc_view_size);
831
832   // Return whether SYM is defined by the ABI.
833   bool
834   do_is_defined_by_abi(const Symbol* sym) const
835   {
836     return strcmp(sym->name(), "__tls_get_addr") == 0;
837   }
838
839   // Return the size of the GOT section.
840   section_size_type
841   got_size() const
842   {
843     gold_assert(this->got_ != NULL);
844     return this->got_->data_size();
845   }
846
847   // Get the PLT section.
848   const Output_data_plt_powerpc<size, big_endian>*
849   plt_section() const
850   {
851     gold_assert(this->plt_ != NULL);
852     return this->plt_;
853   }
854
855   // Get the IPLT section.
856   const Output_data_plt_powerpc<size, big_endian>*
857   iplt_section() const
858   {
859     gold_assert(this->iplt_ != NULL);
860     return this->iplt_;
861   }
862
863   // Get the .glink section.
864   const Output_data_glink<size, big_endian>*
865   glink_section() const
866   {
867     gold_assert(this->glink_ != NULL);
868     return this->glink_;
869   }
870
871   Output_data_glink<size, big_endian>*
872   glink_section()
873   {
874     gold_assert(this->glink_ != NULL);
875     return this->glink_;
876   }
877
878   bool has_glink() const
879   { return this->glink_ != NULL; }
880
881   // Get the GOT section.
882   const Output_data_got_powerpc<size, big_endian>*
883   got_section() const
884   {
885     gold_assert(this->got_ != NULL);
886     return this->got_;
887   }
888
889   // Get the GOT section, creating it if necessary.
890   Output_data_got_powerpc<size, big_endian>*
891   got_section(Symbol_table*, Layout*);
892
893   Object*
894   do_make_elf_object(const std::string&, Input_file*, off_t,
895                      const elfcpp::Ehdr<size, big_endian>&);
896
897   // Return the number of entries in the GOT.
898   unsigned int
899   got_entry_count() const
900   {
901     if (this->got_ == NULL)
902       return 0;
903     return this->got_size() / (size / 8);
904   }
905
906   // Return the number of entries in the PLT.
907   unsigned int
908   plt_entry_count() const;
909
910   // Return the offset of the first non-reserved PLT entry.
911   unsigned int
912   first_plt_entry_offset() const
913   {
914     if (size == 32)
915       return 0;
916     if (this->abiversion() >= 2)
917       return 16;
918     return 24;
919   }
920
921   // Return the size of each PLT entry.
922   unsigned int
923   plt_entry_size() const
924   {
925     if (size == 32)
926       return 4;
927     if (this->abiversion() >= 2)
928       return 8;
929     return 24;
930   }
931
932   Output_data_save_res<size, big_endian>*
933   savres_section() const
934   {
935     return this->savres_section_;
936   }
937
938   // Add any special sections for this symbol to the gc work list.
939   // For powerpc64, this adds the code section of a function
940   // descriptor.
941   void
942   do_gc_mark_symbol(Symbol_table* symtab, Symbol* sym) const;
943
944   // Handle target specific gc actions when adding a gc reference from
945   // SRC_OBJ, SRC_SHNDX to a location specified by DST_OBJ, DST_SHNDX
946   // and DST_OFF.  For powerpc64, this adds a referenc to the code
947   // section of a function descriptor.
948   void
949   do_gc_add_reference(Symbol_table* symtab,
950                       Relobj* src_obj,
951                       unsigned int src_shndx,
952                       Relobj* dst_obj,
953                       unsigned int dst_shndx,
954                       Address dst_off) const;
955
956   typedef std::vector<Stub_table<size, big_endian>*> Stub_tables;
957   const Stub_tables&
958   stub_tables() const
959   { return this->stub_tables_; }
960
961   const Output_data_brlt_powerpc<size, big_endian>*
962   brlt_section() const
963   { return this->brlt_section_; }
964
965   void
966   add_branch_lookup_table(Address to)
967   {
968     unsigned int off = this->branch_lookup_table_.size() * (size / 8);
969     this->branch_lookup_table_.insert(std::make_pair(to, off));
970   }
971
972   Address
973   find_branch_lookup_table(Address to)
974   {
975     typename Branch_lookup_table::const_iterator p
976       = this->branch_lookup_table_.find(to);
977     return p == this->branch_lookup_table_.end() ? invalid_address : p->second;
978   }
979
980   void
981   write_branch_lookup_table(unsigned char *oview)
982   {
983     for (typename Branch_lookup_table::const_iterator p
984            = this->branch_lookup_table_.begin();
985          p != this->branch_lookup_table_.end();
986          ++p)
987       {
988         elfcpp::Swap<size, big_endian>::writeval(oview + p->second, p->first);
989       }
990   }
991
992   // Wrapper used after relax to define a local symbol in output data,
993   // from the end if value < 0.
994   void
995   define_local(Symbol_table* symtab, const char* name,
996                Output_data* od, Address value, unsigned int symsize)
997   {
998     Symbol* sym
999       = symtab->define_in_output_data(name, NULL, Symbol_table::PREDEFINED,
1000                                       od, value, symsize, elfcpp::STT_NOTYPE,
1001                                       elfcpp::STB_LOCAL, elfcpp::STV_HIDDEN, 0,
1002                                       static_cast<Signed_address>(value) < 0,
1003                                       false);
1004     // We are creating this symbol late, so need to fix up things
1005     // done early in Layout::finalize.
1006     sym->set_dynsym_index(-1U);
1007   }
1008
1009   bool
1010   plt_thread_safe() const
1011   { return this->plt_thread_safe_; }
1012
1013   bool
1014   plt_localentry0() const
1015   { return this->plt_localentry0_; }
1016
1017   void
1018   set_has_localentry0()
1019   {
1020     this->has_localentry0_ = true;
1021   }
1022
1023   bool
1024   is_elfv2_localentry0(const Symbol* gsym) const
1025   {
1026     return (size == 64
1027             && this->abiversion() >= 2
1028             && this->plt_localentry0()
1029             && gsym->type() == elfcpp::STT_FUNC
1030             && gsym->is_defined()
1031             && gsym->nonvis() >> 3 == 0
1032             && !gsym->non_zero_localentry());
1033   }
1034
1035   bool
1036   is_elfv2_localentry0(const Sized_relobj_file<size, big_endian>* object,
1037                        unsigned int r_sym) const
1038   {
1039     const Powerpc_relobj<size, big_endian>* ppc_object
1040       = static_cast<const Powerpc_relobj<size, big_endian>*>(object);
1041
1042     if (size == 64
1043         && this->abiversion() >= 2
1044         && this->plt_localentry0()
1045         && ppc_object->st_other(r_sym) >> 5 == 0)
1046       {
1047         const Symbol_value<size>* psymval = object->local_symbol(r_sym);
1048         bool is_ordinary;
1049         if (!psymval->is_ifunc_symbol()
1050             && psymval->input_shndx(&is_ordinary) != elfcpp::SHN_UNDEF
1051             && is_ordinary)
1052           return true;
1053       }
1054     return false;
1055   }
1056
1057   // Remember any symbols seen with non-zero localentry, even those
1058   // not providing a definition
1059   bool
1060   resolve(Symbol* to, const elfcpp::Sym<size, big_endian>& sym, Object*,
1061           const char*)
1062   {
1063     if (size == 64)
1064       {
1065         unsigned char st_other = sym.get_st_other();
1066         if ((st_other & elfcpp::STO_PPC64_LOCAL_MASK) != 0)
1067           to->set_non_zero_localentry();
1068       }
1069     // We haven't resolved anything, continue normal processing.
1070     return false;
1071   }
1072
1073   int
1074   abiversion() const
1075   { return this->processor_specific_flags() & elfcpp::EF_PPC64_ABI; }
1076
1077   void
1078   set_abiversion(int ver)
1079   {
1080     elfcpp::Elf_Word flags = this->processor_specific_flags();
1081     flags &= ~elfcpp::EF_PPC64_ABI;
1082     flags |= ver & elfcpp::EF_PPC64_ABI;
1083     this->set_processor_specific_flags(flags);
1084   }
1085
1086   Symbol*
1087   tls_get_addr_opt() const
1088   { return this->tls_get_addr_opt_; }
1089
1090   Symbol*
1091   tls_get_addr() const
1092   { return this->tls_get_addr_; }
1093
1094   // If optimizing __tls_get_addr calls, whether this is the
1095   // "__tls_get_addr" symbol.
1096   bool
1097   is_tls_get_addr_opt(const Symbol* gsym) const
1098   {
1099     return this->tls_get_addr_opt_ && (gsym == this->tls_get_addr_
1100                                        || gsym == this->tls_get_addr_opt_);
1101   }
1102
1103   bool
1104   replace_tls_get_addr(const Symbol* gsym) const
1105   { return this->tls_get_addr_opt_ && gsym == this->tls_get_addr_; }
1106
1107   void
1108   set_has_tls_get_addr_opt()
1109   { this->has_tls_get_addr_opt_ = true; }
1110
1111   // Offset to toc save stack slot
1112   int
1113   stk_toc() const
1114   { return this->abiversion() < 2 ? 40 : 24; }
1115
1116   // Offset to linker save stack slot.  ELFv2 doesn't have a linker word,
1117   // so use the CR save slot.  Used only by __tls_get_addr call stub,
1118   // relying on __tls_get_addr not saving CR itself.
1119   int
1120   stk_linker() const
1121   { return this->abiversion() < 2 ? 32 : 8; }
1122
1123  private:
1124
1125   class Track_tls
1126   {
1127   public:
1128     enum Tls_get_addr
1129     {
1130       NOT_EXPECTED = 0,
1131       EXPECTED = 1,
1132       SKIP = 2,
1133       NORMAL = 3
1134     };
1135
1136     Track_tls()
1137       : tls_get_addr_state_(NOT_EXPECTED),
1138         relinfo_(NULL), relnum_(0), r_offset_(0)
1139     { }
1140
1141     ~Track_tls()
1142     {
1143       if (this->tls_get_addr_state_ != NOT_EXPECTED)
1144         this->missing();
1145     }
1146
1147     void
1148     missing(void)
1149     {
1150       if (this->relinfo_ != NULL)
1151         gold_error_at_location(this->relinfo_, this->relnum_, this->r_offset_,
1152                                _("missing expected __tls_get_addr call"));
1153     }
1154
1155     void
1156     expect_tls_get_addr_call(
1157         const Relocate_info<size, big_endian>* relinfo,
1158         size_t relnum,
1159         Address r_offset)
1160     {
1161       this->tls_get_addr_state_ = EXPECTED;
1162       this->relinfo_ = relinfo;
1163       this->relnum_ = relnum;
1164       this->r_offset_ = r_offset;
1165     }
1166
1167     void
1168     expect_tls_get_addr_call()
1169     { this->tls_get_addr_state_ = EXPECTED; }
1170
1171     void
1172     skip_next_tls_get_addr_call()
1173     {this->tls_get_addr_state_ = SKIP; }
1174
1175     Tls_get_addr
1176     maybe_skip_tls_get_addr_call(Target_powerpc<size, big_endian>* target,
1177                                  unsigned int r_type, const Symbol* gsym)
1178     {
1179       bool is_tls_call = ((r_type == elfcpp::R_POWERPC_REL24
1180                            || r_type == elfcpp::R_PPC_PLTREL24)
1181                           && gsym != NULL
1182                           && (gsym == target->tls_get_addr()
1183                               || gsym == target->tls_get_addr_opt()));
1184       Tls_get_addr last_tls = this->tls_get_addr_state_;
1185       this->tls_get_addr_state_ = NOT_EXPECTED;
1186       if (is_tls_call && last_tls != EXPECTED)
1187         return last_tls;
1188       else if (!is_tls_call && last_tls != NOT_EXPECTED)
1189         {
1190           this->missing();
1191           return EXPECTED;
1192         }
1193       return NORMAL;
1194     }
1195
1196   private:
1197     // What we're up to regarding calls to __tls_get_addr.
1198     // On powerpc, the branch and link insn making a call to
1199     // __tls_get_addr is marked with a relocation, R_PPC64_TLSGD,
1200     // R_PPC64_TLSLD, R_PPC_TLSGD or R_PPC_TLSLD, in addition to the
1201     // usual R_POWERPC_REL24 or R_PPC_PLTREL25 relocation on a call.
1202     // The marker relocation always comes first, and has the same
1203     // symbol as the reloc on the insn setting up the __tls_get_addr
1204     // argument.  This ties the arg setup insn with the call insn,
1205     // allowing ld to safely optimize away the call.  We check that
1206     // every call to __tls_get_addr has a marker relocation, and that
1207     // every marker relocation is on a call to __tls_get_addr.
1208     Tls_get_addr tls_get_addr_state_;
1209     // Info about the last reloc for error message.
1210     const Relocate_info<size, big_endian>* relinfo_;
1211     size_t relnum_;
1212     Address r_offset_;
1213   };
1214
1215   // The class which scans relocations.
1216   class Scan : protected Track_tls
1217   {
1218   public:
1219     typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
1220
1221     Scan()
1222       : Track_tls(), issued_non_pic_error_(false)
1223     { }
1224
1225     static inline int
1226     get_reference_flags(unsigned int r_type, const Target_powerpc* target);
1227
1228     inline void
1229     local(Symbol_table* symtab, Layout* layout, Target_powerpc* target,
1230           Sized_relobj_file<size, big_endian>* object,
1231           unsigned int data_shndx,
1232           Output_section* output_section,
1233           const elfcpp::Rela<size, big_endian>& reloc, unsigned int r_type,
1234           const elfcpp::Sym<size, big_endian>& lsym,
1235           bool is_discarded);
1236
1237     inline void
1238     global(Symbol_table* symtab, Layout* layout, Target_powerpc* target,
1239            Sized_relobj_file<size, big_endian>* object,
1240            unsigned int data_shndx,
1241            Output_section* output_section,
1242            const elfcpp::Rela<size, big_endian>& reloc, unsigned int r_type,
1243            Symbol* gsym);
1244
1245     inline bool
1246     local_reloc_may_be_function_pointer(Symbol_table* , Layout* ,
1247                                         Target_powerpc* ,
1248                                         Sized_relobj_file<size, big_endian>* relobj,
1249                                         unsigned int ,
1250                                         Output_section* ,
1251                                         const elfcpp::Rela<size, big_endian>& ,
1252                                         unsigned int r_type,
1253                                         const elfcpp::Sym<size, big_endian>&)
1254     {
1255       // PowerPC64 .opd is not folded, so any identical function text
1256       // may be folded and we'll still keep function addresses distinct.
1257       // That means no reloc is of concern here.
1258       if (size == 64)
1259         {
1260           Powerpc_relobj<size, big_endian>* ppcobj = static_cast
1261             <Powerpc_relobj<size, big_endian>*>(relobj);
1262           if (ppcobj->abiversion() == 1)
1263             return false;
1264         }
1265       // For 32-bit and ELFv2, conservatively assume anything but calls to
1266       // function code might be taking the address of the function.
1267       return !is_branch_reloc(r_type);
1268     }
1269
1270     inline bool
1271     global_reloc_may_be_function_pointer(Symbol_table* , Layout* ,
1272                                          Target_powerpc* ,
1273                                          Sized_relobj_file<size, big_endian>* relobj,
1274                                          unsigned int ,
1275                                          Output_section* ,
1276                                          const elfcpp::Rela<size, big_endian>& ,
1277                                          unsigned int r_type,
1278                                          Symbol*)
1279     {
1280       // As above.
1281       if (size == 64)
1282         {
1283           Powerpc_relobj<size, big_endian>* ppcobj = static_cast
1284             <Powerpc_relobj<size, big_endian>*>(relobj);
1285           if (ppcobj->abiversion() == 1)
1286             return false;
1287         }
1288       return !is_branch_reloc(r_type);
1289     }
1290
1291     static bool
1292     reloc_needs_plt_for_ifunc(Target_powerpc<size, big_endian>* target,
1293                               Sized_relobj_file<size, big_endian>* object,
1294                               unsigned int r_type, bool report_err);
1295
1296   private:
1297     static void
1298     unsupported_reloc_local(Sized_relobj_file<size, big_endian>*,
1299                             unsigned int r_type);
1300
1301     static void
1302     unsupported_reloc_global(Sized_relobj_file<size, big_endian>*,
1303                              unsigned int r_type, Symbol*);
1304
1305     static void
1306     generate_tls_call(Symbol_table* symtab, Layout* layout,
1307                       Target_powerpc* target);
1308
1309     void
1310     check_non_pic(Relobj*, unsigned int r_type);
1311
1312     // Whether we have issued an error about a non-PIC compilation.
1313     bool issued_non_pic_error_;
1314   };
1315
1316   bool
1317   symval_for_branch(const Symbol_table* symtab,
1318                     const Sized_symbol<size>* gsym,
1319                     Powerpc_relobj<size, big_endian>* object,
1320                     Address *value, unsigned int *dest_shndx);
1321
1322   // The class which implements relocation.
1323   class Relocate : protected Track_tls
1324   {
1325    public:
1326     // Use 'at' branch hints when true, 'y' when false.
1327     // FIXME maybe: set this with an option.
1328     static const bool is_isa_v2 = true;
1329
1330     Relocate()
1331       : Track_tls()
1332     { }
1333
1334     // Do a relocation.  Return false if the caller should not issue
1335     // any warnings about this relocation.
1336     inline bool
1337     relocate(const Relocate_info<size, big_endian>*, unsigned int,
1338              Target_powerpc*, Output_section*, size_t, const unsigned char*,
1339              const Sized_symbol<size>*, const Symbol_value<size>*,
1340              unsigned char*, typename elfcpp::Elf_types<size>::Elf_Addr,
1341              section_size_type);
1342   };
1343
1344   class Relocate_comdat_behavior
1345   {
1346    public:
1347     // Decide what the linker should do for relocations that refer to
1348     // discarded comdat sections.
1349     inline Comdat_behavior
1350     get(const char* name)
1351     {
1352       gold::Default_comdat_behavior default_behavior;
1353       Comdat_behavior ret = default_behavior.get(name);
1354       if (ret == CB_WARNING)
1355         {
1356           if (size == 32
1357               && (strcmp(name, ".fixup") == 0
1358                   || strcmp(name, ".got2") == 0))
1359             ret = CB_IGNORE;
1360           if (size == 64
1361               && (strcmp(name, ".opd") == 0
1362                   || strcmp(name, ".toc") == 0
1363                   || strcmp(name, ".toc1") == 0))
1364             ret = CB_IGNORE;
1365         }
1366       return ret;
1367     }
1368   };
1369
1370   // Optimize the TLS relocation type based on what we know about the
1371   // symbol.  IS_FINAL is true if the final address of this symbol is
1372   // known at link time.
1373
1374   tls::Tls_optimization
1375   optimize_tls_gd(bool is_final)
1376   {
1377     // If we are generating a shared library, then we can't do anything
1378     // in the linker.
1379     if (parameters->options().shared()
1380         || !parameters->options().tls_optimize())
1381       return tls::TLSOPT_NONE;
1382
1383     if (!is_final)
1384       return tls::TLSOPT_TO_IE;
1385     return tls::TLSOPT_TO_LE;
1386   }
1387
1388   tls::Tls_optimization
1389   optimize_tls_ld()
1390   {
1391     if (parameters->options().shared()
1392         || !parameters->options().tls_optimize())
1393       return tls::TLSOPT_NONE;
1394
1395     return tls::TLSOPT_TO_LE;
1396   }
1397
1398   tls::Tls_optimization
1399   optimize_tls_ie(bool is_final)
1400   {
1401     if (!is_final
1402         || parameters->options().shared()
1403         || !parameters->options().tls_optimize())
1404       return tls::TLSOPT_NONE;
1405
1406     return tls::TLSOPT_TO_LE;
1407   }
1408
1409   // Create glink.
1410   void
1411   make_glink_section(Layout*);
1412
1413   // Create the PLT section.
1414   void
1415   make_plt_section(Symbol_table*, Layout*);
1416
1417   void
1418   make_iplt_section(Symbol_table*, Layout*);
1419
1420   void
1421   make_brlt_section(Layout*);
1422
1423   // Create a PLT entry for a global symbol.
1424   void
1425   make_plt_entry(Symbol_table*, Layout*, Symbol*);
1426
1427   // Create a PLT entry for a local IFUNC symbol.
1428   void
1429   make_local_ifunc_plt_entry(Symbol_table*, Layout*,
1430                              Sized_relobj_file<size, big_endian>*,
1431                              unsigned int);
1432
1433
1434   // Create a GOT entry for local dynamic __tls_get_addr.
1435   unsigned int
1436   tlsld_got_offset(Symbol_table* symtab, Layout* layout,
1437                    Sized_relobj_file<size, big_endian>* object);
1438
1439   unsigned int
1440   tlsld_got_offset() const
1441   {
1442     return this->tlsld_got_offset_;
1443   }
1444
1445   // Get the dynamic reloc section, creating it if necessary.
1446   Reloc_section*
1447   rela_dyn_section(Layout*);
1448
1449   // Similarly, but for ifunc symbols get the one for ifunc.
1450   Reloc_section*
1451   rela_dyn_section(Symbol_table*, Layout*, bool for_ifunc);
1452
1453   // Copy a relocation against a global symbol.
1454   void
1455   copy_reloc(Symbol_table* symtab, Layout* layout,
1456              Sized_relobj_file<size, big_endian>* object,
1457              unsigned int shndx, Output_section* output_section,
1458              Symbol* sym, const elfcpp::Rela<size, big_endian>& reloc)
1459   {
1460     unsigned int r_type = elfcpp::elf_r_type<size>(reloc.get_r_info());
1461     this->copy_relocs_.copy_reloc(symtab, layout,
1462                                   symtab->get_sized_symbol<size>(sym),
1463                                   object, shndx, output_section,
1464                                   r_type, reloc.get_r_offset(),
1465                                   reloc.get_r_addend(),
1466                                   this->rela_dyn_section(layout));
1467   }
1468
1469   // Look over all the input sections, deciding where to place stubs.
1470   void
1471   group_sections(Layout*, const Task*, bool);
1472
1473   // Sort output sections by address.
1474   struct Sort_sections
1475   {
1476     bool
1477     operator()(const Output_section* sec1, const Output_section* sec2)
1478     { return sec1->address() < sec2->address(); }
1479   };
1480
1481   class Branch_info
1482   {
1483    public:
1484     Branch_info(Powerpc_relobj<size, big_endian>* ppc_object,
1485                 unsigned int data_shndx,
1486                 Address r_offset,
1487                 unsigned int r_type,
1488                 unsigned int r_sym,
1489                 Address addend)
1490       : object_(ppc_object), shndx_(data_shndx), offset_(r_offset),
1491         r_type_(r_type), tocsave_ (0), r_sym_(r_sym), addend_(addend)
1492     { }
1493
1494     ~Branch_info()
1495     { }
1496
1497     // Return whether this branch is going via a plt call stub, and if
1498     // so, mark it as having an R_PPC64_TOCSAVE.
1499     bool
1500     mark_pltcall(Powerpc_relobj<size, big_endian>* ppc_object,
1501                  unsigned int shndx, Address offset,
1502                  Target_powerpc* target, Symbol_table* symtab);
1503
1504     // If this branch needs a plt call stub, or a long branch stub, make one.
1505     bool
1506     make_stub(Stub_table<size, big_endian>*,
1507               Stub_table<size, big_endian>*,
1508               Symbol_table*) const;
1509
1510    private:
1511     // The branch location..
1512     Powerpc_relobj<size, big_endian>* object_;
1513     unsigned int shndx_;
1514     Address offset_;
1515     // ..and the branch type and destination.
1516     unsigned int r_type_ : 31;
1517     unsigned int tocsave_ : 1;
1518     unsigned int r_sym_;
1519     Address addend_;
1520   };
1521
1522   // Information about this specific target which we pass to the
1523   // general Target structure.
1524   static Target::Target_info powerpc_info;
1525
1526   // The types of GOT entries needed for this platform.
1527   // These values are exposed to the ABI in an incremental link.
1528   // Do not renumber existing values without changing the version
1529   // number of the .gnu_incremental_inputs section.
1530   enum Got_type
1531   {
1532     GOT_TYPE_STANDARD,
1533     GOT_TYPE_TLSGD,     // double entry for @got@tlsgd
1534     GOT_TYPE_DTPREL,    // entry for @got@dtprel
1535     GOT_TYPE_TPREL      // entry for @got@tprel
1536   };
1537
1538   // The GOT section.
1539   Output_data_got_powerpc<size, big_endian>* got_;
1540   // The PLT section.  This is a container for a table of addresses,
1541   // and their relocations.  Each address in the PLT has a dynamic
1542   // relocation (R_*_JMP_SLOT) and each address will have a
1543   // corresponding entry in .glink for lazy resolution of the PLT.
1544   // ppc32 initialises the PLT to point at the .glink entry, while
1545   // ppc64 leaves this to ld.so.  To make a call via the PLT, the
1546   // linker adds a stub that loads the PLT entry into ctr then
1547   // branches to ctr.  There may be more than one stub for each PLT
1548   // entry.  DT_JMPREL points at the first PLT dynamic relocation and
1549   // DT_PLTRELSZ gives the total size of PLT dynamic relocations.
1550   Output_data_plt_powerpc<size, big_endian>* plt_;
1551   // The IPLT section.  Like plt_, this is a container for a table of
1552   // addresses and their relocations, specifically for STT_GNU_IFUNC
1553   // functions that resolve locally (STT_GNU_IFUNC functions that
1554   // don't resolve locally go in PLT).  Unlike plt_, these have no
1555   // entry in .glink for lazy resolution, and the relocation section
1556   // does not have a 1-1 correspondence with IPLT addresses.  In fact,
1557   // the relocation section may contain relocations against
1558   // STT_GNU_IFUNC symbols at locations outside of IPLT.  The
1559   // relocation section will appear at the end of other dynamic
1560   // relocations, so that ld.so applies these relocations after other
1561   // dynamic relocations.  In a static executable, the relocation
1562   // section is emitted and marked with __rela_iplt_start and
1563   // __rela_iplt_end symbols.
1564   Output_data_plt_powerpc<size, big_endian>* iplt_;
1565   // Section holding long branch destinations.
1566   Output_data_brlt_powerpc<size, big_endian>* brlt_section_;
1567   // The .glink section.
1568   Output_data_glink<size, big_endian>* glink_;
1569   // The dynamic reloc section.
1570   Reloc_section* rela_dyn_;
1571   // Relocs saved to avoid a COPY reloc.
1572   Powerpc_copy_relocs<elfcpp::SHT_RELA, size, big_endian> copy_relocs_;
1573   // Offset of the GOT entry for local dynamic __tls_get_addr calls.
1574   unsigned int tlsld_got_offset_;
1575
1576   Stub_tables stub_tables_;
1577   typedef Unordered_map<Address, unsigned int> Branch_lookup_table;
1578   Branch_lookup_table branch_lookup_table_;
1579
1580   typedef std::vector<Branch_info> Branches;
1581   Branches branch_info_;
1582   Tocsave_loc tocsave_loc_;
1583
1584   bool plt_thread_safe_;
1585   bool plt_localentry0_;
1586   bool plt_localentry0_init_;
1587   bool has_localentry0_;
1588   bool has_tls_get_addr_opt_;
1589
1590   bool relax_failed_;
1591   int relax_fail_count_;
1592   int32_t stub_group_size_;
1593
1594   Output_data_save_res<size, big_endian> *savres_section_;
1595
1596   // The "__tls_get_addr" symbol, if present
1597   Symbol* tls_get_addr_;
1598   // If optimizing __tls_get_addr calls, the "__tls_get_addr_opt" symbol.
1599   Symbol* tls_get_addr_opt_;
1600 };
1601
1602 template<>
1603 Target::Target_info Target_powerpc<32, true>::powerpc_info =
1604 {
1605   32,                   // size
1606   true,                 // is_big_endian
1607   elfcpp::EM_PPC,       // machine_code
1608   false,                // has_make_symbol
1609   false,                // has_resolve
1610   false,                // has_code_fill
1611   true,                 // is_default_stack_executable
1612   false,                // can_icf_inline_merge_sections
1613   '\0',                 // wrap_char
1614   "/usr/lib/ld.so.1",   // dynamic_linker
1615   0x10000000,           // default_text_segment_address
1616   64 * 1024,            // abi_pagesize (overridable by -z max-page-size)
1617   4 * 1024,             // common_pagesize (overridable by -z common-page-size)
1618   false,                // isolate_execinstr
1619   0,                    // rosegment_gap
1620   elfcpp::SHN_UNDEF,    // small_common_shndx
1621   elfcpp::SHN_UNDEF,    // large_common_shndx
1622   0,                    // small_common_section_flags
1623   0,                    // large_common_section_flags
1624   NULL,                 // attributes_section
1625   NULL,                 // attributes_vendor
1626   "_start",             // entry_symbol_name
1627   32,                   // hash_entry_size
1628 };
1629
1630 template<>
1631 Target::Target_info Target_powerpc<32, false>::powerpc_info =
1632 {
1633   32,                   // size
1634   false,                // is_big_endian
1635   elfcpp::EM_PPC,       // machine_code
1636   false,                // has_make_symbol
1637   false,                // has_resolve
1638   false,                // has_code_fill
1639   true,                 // is_default_stack_executable
1640   false,                // can_icf_inline_merge_sections
1641   '\0',                 // wrap_char
1642   "/usr/lib/ld.so.1",   // dynamic_linker
1643   0x10000000,           // default_text_segment_address
1644   64 * 1024,            // abi_pagesize (overridable by -z max-page-size)
1645   4 * 1024,             // common_pagesize (overridable by -z common-page-size)
1646   false,                // isolate_execinstr
1647   0,                    // rosegment_gap
1648   elfcpp::SHN_UNDEF,    // small_common_shndx
1649   elfcpp::SHN_UNDEF,    // large_common_shndx
1650   0,                    // small_common_section_flags
1651   0,                    // large_common_section_flags
1652   NULL,                 // attributes_section
1653   NULL,                 // attributes_vendor
1654   "_start",             // entry_symbol_name
1655   32,                   // hash_entry_size
1656 };
1657
1658 template<>
1659 Target::Target_info Target_powerpc<64, true>::powerpc_info =
1660 {
1661   64,                   // size
1662   true,                 // is_big_endian
1663   elfcpp::EM_PPC64,     // machine_code
1664   false,                // has_make_symbol
1665   true,                 // has_resolve
1666   false,                // has_code_fill
1667   false,                // is_default_stack_executable
1668   false,                // can_icf_inline_merge_sections
1669   '\0',                 // wrap_char
1670   "/usr/lib/ld.so.1",   // dynamic_linker
1671   0x10000000,           // default_text_segment_address
1672   64 * 1024,            // abi_pagesize (overridable by -z max-page-size)
1673   4 * 1024,             // common_pagesize (overridable by -z common-page-size)
1674   false,                // isolate_execinstr
1675   0,                    // rosegment_gap
1676   elfcpp::SHN_UNDEF,    // small_common_shndx
1677   elfcpp::SHN_UNDEF,    // large_common_shndx
1678   0,                    // small_common_section_flags
1679   0,                    // large_common_section_flags
1680   NULL,                 // attributes_section
1681   NULL,                 // attributes_vendor
1682   "_start",             // entry_symbol_name
1683   32,                   // hash_entry_size
1684 };
1685
1686 template<>
1687 Target::Target_info Target_powerpc<64, false>::powerpc_info =
1688 {
1689   64,                   // size
1690   false,                // is_big_endian
1691   elfcpp::EM_PPC64,     // machine_code
1692   false,                // has_make_symbol
1693   true,                 // has_resolve
1694   false,                // has_code_fill
1695   false,                // is_default_stack_executable
1696   false,                // can_icf_inline_merge_sections
1697   '\0',                 // wrap_char
1698   "/usr/lib/ld.so.1",   // dynamic_linker
1699   0x10000000,           // default_text_segment_address
1700   64 * 1024,            // abi_pagesize (overridable by -z max-page-size)
1701   4 * 1024,             // common_pagesize (overridable by -z common-page-size)
1702   false,                // isolate_execinstr
1703   0,                    // rosegment_gap
1704   elfcpp::SHN_UNDEF,    // small_common_shndx
1705   elfcpp::SHN_UNDEF,    // large_common_shndx
1706   0,                    // small_common_section_flags
1707   0,                    // large_common_section_flags
1708   NULL,                 // attributes_section
1709   NULL,                 // attributes_vendor
1710   "_start",             // entry_symbol_name
1711   32,                   // hash_entry_size
1712 };
1713
1714 inline bool
1715 is_branch_reloc(unsigned int r_type)
1716 {
1717   return (r_type == elfcpp::R_POWERPC_REL24
1718           || r_type == elfcpp::R_PPC_PLTREL24
1719           || r_type == elfcpp::R_PPC_LOCAL24PC
1720           || r_type == elfcpp::R_POWERPC_REL14
1721           || r_type == elfcpp::R_POWERPC_REL14_BRTAKEN
1722           || r_type == elfcpp::R_POWERPC_REL14_BRNTAKEN
1723           || r_type == elfcpp::R_POWERPC_ADDR24
1724           || r_type == elfcpp::R_POWERPC_ADDR14
1725           || r_type == elfcpp::R_POWERPC_ADDR14_BRTAKEN
1726           || r_type == elfcpp::R_POWERPC_ADDR14_BRNTAKEN);
1727 }
1728
1729 // If INSN is an opcode that may be used with an @tls operand, return
1730 // the transformed insn for TLS optimisation, otherwise return 0.  If
1731 // REG is non-zero only match an insn with RB or RA equal to REG.
1732 uint32_t
1733 at_tls_transform(uint32_t insn, unsigned int reg)
1734 {
1735   if ((insn & (0x3f << 26)) != 31 << 26)
1736     return 0;
1737
1738   unsigned int rtra;
1739   if (reg == 0 || ((insn >> 11) & 0x1f) == reg)
1740     rtra = insn & ((1 << 26) - (1 << 16));
1741   else if (((insn >> 16) & 0x1f) == reg)
1742     rtra = (insn & (0x1f << 21)) | ((insn & (0x1f << 11)) << 5);
1743   else
1744     return 0;
1745
1746   if ((insn & (0x3ff << 1)) == 266 << 1)
1747     // add -> addi
1748     insn = 14 << 26;
1749   else if ((insn & (0x1f << 1)) == 23 << 1
1750            && ((insn & (0x1f << 6)) < 14 << 6
1751                || ((insn & (0x1f << 6)) >= 16 << 6
1752                    && (insn & (0x1f << 6)) < 24 << 6)))
1753     // load and store indexed -> dform
1754     insn = (32 | ((insn >> 6) & 0x1f)) << 26;
1755   else if ((insn & (((0x1a << 5) | 0x1f) << 1)) == 21 << 1)
1756     // ldx, ldux, stdx, stdux -> ld, ldu, std, stdu
1757     insn = ((58 | ((insn >> 6) & 4)) << 26) | ((insn >> 6) & 1);
1758   else if ((insn & (((0x1f << 5) | 0x1f) << 1)) == 341 << 1)
1759     // lwax -> lwa
1760     insn = (58 << 26) | 2;
1761   else
1762     return 0;
1763   insn |= rtra;
1764   return insn;
1765 }
1766
1767
1768 template<int size, bool big_endian>
1769 class Powerpc_relocate_functions
1770 {
1771 public:
1772   enum Overflow_check
1773   {
1774     CHECK_NONE,
1775     CHECK_SIGNED,
1776     CHECK_UNSIGNED,
1777     CHECK_BITFIELD,
1778     CHECK_LOW_INSN,
1779     CHECK_HIGH_INSN
1780   };
1781
1782   enum Status
1783   {
1784     STATUS_OK,
1785     STATUS_OVERFLOW
1786   };
1787
1788 private:
1789   typedef Powerpc_relocate_functions<size, big_endian> This;
1790   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
1791   typedef typename elfcpp::Elf_types<size>::Elf_Swxword SignedAddress;
1792
1793   template<int valsize>
1794   static inline bool
1795   has_overflow_signed(Address value)
1796   {
1797     // limit = 1 << (valsize - 1) without shift count exceeding size of type
1798     Address limit = static_cast<Address>(1) << ((valsize - 1) >> 1);
1799     limit <<= ((valsize - 1) >> 1);
1800     limit <<= ((valsize - 1) - 2 * ((valsize - 1) >> 1));
1801     return value + limit > (limit << 1) - 1;
1802   }
1803
1804   template<int valsize>
1805   static inline bool
1806   has_overflow_unsigned(Address value)
1807   {
1808     Address limit = static_cast<Address>(1) << ((valsize - 1) >> 1);
1809     limit <<= ((valsize - 1) >> 1);
1810     limit <<= ((valsize - 1) - 2 * ((valsize - 1) >> 1));
1811     return value > (limit << 1) - 1;
1812   }
1813
1814   template<int valsize>
1815   static inline bool
1816   has_overflow_bitfield(Address value)
1817   {
1818     return (has_overflow_unsigned<valsize>(value)
1819             && has_overflow_signed<valsize>(value));
1820   }
1821
1822   template<int valsize>
1823   static inline Status
1824   overflowed(Address value, Overflow_check overflow)
1825   {
1826     if (overflow == CHECK_SIGNED)
1827       {
1828         if (has_overflow_signed<valsize>(value))
1829           return STATUS_OVERFLOW;
1830       }
1831     else if (overflow == CHECK_UNSIGNED)
1832       {
1833         if (has_overflow_unsigned<valsize>(value))
1834           return STATUS_OVERFLOW;
1835       }
1836     else if (overflow == CHECK_BITFIELD)
1837       {
1838         if (has_overflow_bitfield<valsize>(value))
1839           return STATUS_OVERFLOW;
1840       }
1841     return STATUS_OK;
1842   }
1843
1844   // Do a simple RELA relocation
1845   template<int fieldsize, int valsize>
1846   static inline Status
1847   rela(unsigned char* view, Address value, Overflow_check overflow)
1848   {
1849     typedef typename elfcpp::Swap<fieldsize, big_endian>::Valtype Valtype;
1850     Valtype* wv = reinterpret_cast<Valtype*>(view);
1851     elfcpp::Swap<fieldsize, big_endian>::writeval(wv, value);
1852     return overflowed<valsize>(value, overflow);
1853   }
1854
1855   template<int fieldsize, int valsize>
1856   static inline Status
1857   rela(unsigned char* view,
1858        unsigned int right_shift,
1859        typename elfcpp::Valtype_base<fieldsize>::Valtype dst_mask,
1860        Address value,
1861        Overflow_check overflow)
1862   {
1863     typedef typename elfcpp::Swap<fieldsize, big_endian>::Valtype Valtype;
1864     Valtype* wv = reinterpret_cast<Valtype*>(view);
1865     Valtype val = elfcpp::Swap<fieldsize, big_endian>::readval(wv);
1866     Valtype reloc = value >> right_shift;
1867     val &= ~dst_mask;
1868     reloc &= dst_mask;
1869     elfcpp::Swap<fieldsize, big_endian>::writeval(wv, val | reloc);
1870     return overflowed<valsize>(value >> right_shift, overflow);
1871   }
1872
1873   // Do a simple RELA relocation, unaligned.
1874   template<int fieldsize, int valsize>
1875   static inline Status
1876   rela_ua(unsigned char* view, Address value, Overflow_check overflow)
1877   {
1878     elfcpp::Swap_unaligned<fieldsize, big_endian>::writeval(view, value);
1879     return overflowed<valsize>(value, overflow);
1880   }
1881
1882   template<int fieldsize, int valsize>
1883   static inline Status
1884   rela_ua(unsigned char* view,
1885           unsigned int right_shift,
1886           typename elfcpp::Valtype_base<fieldsize>::Valtype dst_mask,
1887           Address value,
1888           Overflow_check overflow)
1889   {
1890     typedef typename elfcpp::Swap_unaligned<fieldsize, big_endian>::Valtype
1891       Valtype;
1892     Valtype val = elfcpp::Swap<fieldsize, big_endian>::readval(view);
1893     Valtype reloc = value >> right_shift;
1894     val &= ~dst_mask;
1895     reloc &= dst_mask;
1896     elfcpp::Swap_unaligned<fieldsize, big_endian>::writeval(view, val | reloc);
1897     return overflowed<valsize>(value >> right_shift, overflow);
1898   }
1899
1900 public:
1901   // R_PPC64_ADDR64: (Symbol + Addend)
1902   static inline void
1903   addr64(unsigned char* view, Address value)
1904   { This::template rela<64,64>(view, value, CHECK_NONE); }
1905
1906   // R_PPC64_UADDR64: (Symbol + Addend) unaligned
1907   static inline void
1908   addr64_u(unsigned char* view, Address value)
1909   { This::template rela_ua<64,64>(view, value, CHECK_NONE); }
1910
1911   // R_POWERPC_ADDR32: (Symbol + Addend)
1912   static inline Status
1913   addr32(unsigned char* view, Address value, Overflow_check overflow)
1914   { return This::template rela<32,32>(view, value, overflow); }
1915
1916   // R_POWERPC_UADDR32: (Symbol + Addend) unaligned
1917   static inline Status
1918   addr32_u(unsigned char* view, Address value, Overflow_check overflow)
1919   { return This::template rela_ua<32,32>(view, value, overflow); }
1920
1921   // R_POWERPC_ADDR24: (Symbol + Addend) & 0x3fffffc
1922   static inline Status
1923   addr24(unsigned char* view, Address value, Overflow_check overflow)
1924   {
1925     Status stat = This::template rela<32,26>(view, 0, 0x03fffffc,
1926                                              value, overflow);
1927     if (overflow != CHECK_NONE && (value & 3) != 0)
1928       stat = STATUS_OVERFLOW;
1929     return stat;
1930   }
1931
1932   // R_POWERPC_ADDR16: (Symbol + Addend) & 0xffff
1933   static inline Status
1934   addr16(unsigned char* view, Address value, Overflow_check overflow)
1935   { return This::template rela<16,16>(view, value, overflow); }
1936
1937   // R_POWERPC_ADDR16: (Symbol + Addend) & 0xffff, unaligned
1938   static inline Status
1939   addr16_u(unsigned char* view, Address value, Overflow_check overflow)
1940   { return This::template rela_ua<16,16>(view, value, overflow); }
1941
1942   // R_POWERPC_ADDR16_DS: (Symbol + Addend) & 0xfffc
1943   static inline Status
1944   addr16_ds(unsigned char* view, Address value, Overflow_check overflow)
1945   {
1946     Status stat = This::template rela<16,16>(view, 0, 0xfffc, value, overflow);
1947     if ((value & 3) != 0)
1948       stat = STATUS_OVERFLOW;
1949     return stat;
1950   }
1951
1952   // R_POWERPC_ADDR16_DQ: (Symbol + Addend) & 0xfff0
1953   static inline Status
1954   addr16_dq(unsigned char* view, Address value, Overflow_check overflow)
1955   {
1956     Status stat = This::template rela<16,16>(view, 0, 0xfff0, value, overflow);
1957     if ((value & 15) != 0)
1958       stat = STATUS_OVERFLOW;
1959     return stat;
1960   }
1961
1962   // R_POWERPC_ADDR16_HI: ((Symbol + Addend) >> 16) & 0xffff
1963   static inline void
1964   addr16_hi(unsigned char* view, Address value)
1965   { This::template rela<16,16>(view, 16, 0xffff, value, CHECK_NONE); }
1966
1967   // R_POWERPC_ADDR16_HA: ((Symbol + Addend + 0x8000) >> 16) & 0xffff
1968   static inline void
1969   addr16_ha(unsigned char* view, Address value)
1970   { This::addr16_hi(view, value + 0x8000); }
1971
1972   // R_POWERPC_ADDR16_HIGHER: ((Symbol + Addend) >> 32) & 0xffff
1973   static inline void
1974   addr16_hi2(unsigned char* view, Address value)
1975   { This::template rela<16,16>(view, 32, 0xffff, value, CHECK_NONE); }
1976
1977   // R_POWERPC_ADDR16_HIGHERA: ((Symbol + Addend + 0x8000) >> 32) & 0xffff
1978   static inline void
1979   addr16_ha2(unsigned char* view, Address value)
1980   { This::addr16_hi2(view, value + 0x8000); }
1981
1982   // R_POWERPC_ADDR16_HIGHEST: ((Symbol + Addend) >> 48) & 0xffff
1983   static inline void
1984   addr16_hi3(unsigned char* view, Address value)
1985   { This::template rela<16,16>(view, 48, 0xffff, value, CHECK_NONE); }
1986
1987   // R_POWERPC_ADDR16_HIGHESTA: ((Symbol + Addend + 0x8000) >> 48) & 0xffff
1988   static inline void
1989   addr16_ha3(unsigned char* view, Address value)
1990   { This::addr16_hi3(view, value + 0x8000); }
1991
1992   // R_POWERPC_ADDR14: (Symbol + Addend) & 0xfffc
1993   static inline Status
1994   addr14(unsigned char* view, Address value, Overflow_check overflow)
1995   {
1996     Status stat = This::template rela<32,16>(view, 0, 0xfffc, value, overflow);
1997     if (overflow != CHECK_NONE && (value & 3) != 0)
1998       stat = STATUS_OVERFLOW;
1999     return stat;
2000   }
2001
2002   // R_POWERPC_REL16DX_HA
2003   static inline Status
2004   addr16dx_ha(unsigned char *view, Address value, Overflow_check overflow)
2005   {
2006     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
2007     Valtype* wv = reinterpret_cast<Valtype*>(view);
2008     Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
2009     value += 0x8000;
2010     value = static_cast<SignedAddress>(value) >> 16;
2011     val |= (value & 0xffc1) | ((value & 0x3e) << 15);
2012     elfcpp::Swap<32, big_endian>::writeval(wv, val);
2013     return overflowed<16>(value, overflow);
2014   }
2015 };
2016
2017 // Set ABI version for input and output.
2018
2019 template<int size, bool big_endian>
2020 void
2021 Powerpc_relobj<size, big_endian>::set_abiversion(int ver)
2022 {
2023   this->e_flags_ |= ver;
2024   if (this->abiversion() != 0)
2025     {
2026       Target_powerpc<size, big_endian>* target =
2027         static_cast<Target_powerpc<size, big_endian>*>(
2028            parameters->sized_target<size, big_endian>());
2029       if (target->abiversion() == 0)
2030         target->set_abiversion(this->abiversion());
2031       else if (target->abiversion() != this->abiversion())
2032         gold_error(_("%s: ABI version %d is not compatible "
2033                      "with ABI version %d output"),
2034                    this->name().c_str(),
2035                    this->abiversion(), target->abiversion());
2036
2037     }
2038 }
2039
2040 // Stash away the index of .got2, .opd, .rela.toc, and .toc in a
2041 // relocatable object, if such sections exists.
2042
2043 template<int size, bool big_endian>
2044 bool
2045 Powerpc_relobj<size, big_endian>::do_find_special_sections(
2046     Read_symbols_data* sd)
2047 {
2048   const unsigned char* const pshdrs = sd->section_headers->data();
2049   const unsigned char* namesu = sd->section_names->data();
2050   const char* names = reinterpret_cast<const char*>(namesu);
2051   section_size_type names_size = sd->section_names_size;
2052   const unsigned char* s;
2053
2054   s = this->template find_shdr<size, big_endian>(pshdrs,
2055                                                  size == 32 ? ".got2" : ".opd",
2056                                                  names, names_size, NULL);
2057   if (s != NULL)
2058     {
2059       unsigned int ndx = (s - pshdrs) / elfcpp::Elf_sizes<size>::shdr_size;
2060       this->special_ = ndx;
2061       if (size == 64)
2062         {
2063           if (this->abiversion() == 0)
2064             this->set_abiversion(1);
2065           else if (this->abiversion() > 1)
2066             gold_error(_("%s: .opd invalid in abiv%d"),
2067                        this->name().c_str(), this->abiversion());
2068         }
2069     }
2070   if (size == 64)
2071     {
2072       s = this->template find_shdr<size, big_endian>(pshdrs, ".rela.toc",
2073                                                      names, names_size, NULL);
2074       if (s != NULL)
2075         {
2076           unsigned int ndx = (s - pshdrs) / elfcpp::Elf_sizes<size>::shdr_size;
2077           this->relatoc_ = ndx;
2078           typename elfcpp::Shdr<size, big_endian> shdr(s);
2079           this->toc_ = this->adjust_shndx(shdr.get_sh_info());
2080         }
2081     }
2082   return Sized_relobj_file<size, big_endian>::do_find_special_sections(sd);
2083 }
2084
2085 // Examine .rela.opd to build info about function entry points.
2086
2087 template<int size, bool big_endian>
2088 void
2089 Powerpc_relobj<size, big_endian>::scan_opd_relocs(
2090     size_t reloc_count,
2091     const unsigned char* prelocs,
2092     const unsigned char* plocal_syms)
2093 {
2094   if (size == 64)
2095     {
2096       typedef typename elfcpp::Rela<size, big_endian> Reltype;
2097       const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
2098       const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
2099       Address expected_off = 0;
2100       bool regular = true;
2101       unsigned int opd_ent_size = 0;
2102
2103       for (size_t i = 0; i < reloc_count; ++i, prelocs += reloc_size)
2104         {
2105           Reltype reloc(prelocs);
2106           typename elfcpp::Elf_types<size>::Elf_WXword r_info
2107             = reloc.get_r_info();
2108           unsigned int r_type = elfcpp::elf_r_type<size>(r_info);
2109           if (r_type == elfcpp::R_PPC64_ADDR64)
2110             {
2111               unsigned int r_sym = elfcpp::elf_r_sym<size>(r_info);
2112               typename elfcpp::Elf_types<size>::Elf_Addr value;
2113               bool is_ordinary;
2114               unsigned int shndx;
2115               if (r_sym < this->local_symbol_count())
2116                 {
2117                   typename elfcpp::Sym<size, big_endian>
2118                     lsym(plocal_syms + r_sym * sym_size);
2119                   shndx = lsym.get_st_shndx();
2120                   shndx = this->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
2121                   value = lsym.get_st_value();
2122                 }
2123               else
2124                 shndx = this->symbol_section_and_value(r_sym, &value,
2125                                                        &is_ordinary);
2126               this->set_opd_ent(reloc.get_r_offset(), shndx,
2127                                 value + reloc.get_r_addend());
2128               if (i == 2)
2129                 {
2130                   expected_off = reloc.get_r_offset();
2131                   opd_ent_size = expected_off;
2132                 }
2133               else if (expected_off != reloc.get_r_offset())
2134                 regular = false;
2135               expected_off += opd_ent_size;
2136             }
2137           else if (r_type == elfcpp::R_PPC64_TOC)
2138             {
2139               if (expected_off - opd_ent_size + 8 != reloc.get_r_offset())
2140                 regular = false;
2141             }
2142           else
2143             {
2144               gold_warning(_("%s: unexpected reloc type %u in .opd section"),
2145                            this->name().c_str(), r_type);
2146               regular = false;
2147             }
2148         }
2149       if (reloc_count <= 2)
2150         opd_ent_size = this->section_size(this->opd_shndx());
2151       if (opd_ent_size != 24 && opd_ent_size != 16)
2152         regular = false;
2153       if (!regular)
2154         {
2155           gold_warning(_("%s: .opd is not a regular array of opd entries"),
2156                        this->name().c_str());
2157           opd_ent_size = 0;
2158         }
2159     }
2160 }
2161
2162 // Returns true if a code sequence loading the TOC entry at VALUE
2163 // relative to the TOC pointer can be converted into code calculating
2164 // a TOC pointer relative offset.
2165 // If so, the TOC pointer relative offset is stored to VALUE.
2166
2167 template<int size, bool big_endian>
2168 bool
2169 Powerpc_relobj<size, big_endian>::make_toc_relative(
2170     Target_powerpc<size, big_endian>* target,
2171     Address* value)
2172 {
2173   if (size != 64)
2174     return false;
2175
2176   // With -mcmodel=medium code it is quite possible to have
2177   // toc-relative relocs referring to objects outside the TOC.
2178   // Don't try to look at a non-existent TOC.
2179   if (this->toc_shndx() == 0)
2180     return false;
2181
2182   // Convert VALUE back to an address by adding got_base (see below),
2183   // then to an offset in the TOC by subtracting the TOC output
2184   // section address and the TOC output offset.  Since this TOC output
2185   // section and the got output section are one and the same, we can
2186   // omit adding and subtracting the output section address.
2187   Address off = (*value + this->toc_base_offset()
2188                  - this->output_section_offset(this->toc_shndx()));
2189   // Is this offset in the TOC?  -mcmodel=medium code may be using
2190   // TOC relative access to variables outside the TOC.  Those of
2191   // course can't be optimized.  We also don't try to optimize code
2192   // that is using a different object's TOC.
2193   if (off >= this->section_size(this->toc_shndx()))
2194     return false;
2195
2196   if (this->no_toc_opt(off))
2197     return false;
2198
2199   section_size_type vlen;
2200   unsigned char* view = this->get_output_view(this->toc_shndx(), &vlen);
2201   Address addr = elfcpp::Swap<size, big_endian>::readval(view + off);
2202   // The TOC pointer
2203   Address got_base = (target->got_section()->output_section()->address()
2204                       + this->toc_base_offset());
2205   addr -= got_base;
2206   if (addr + (uint64_t) 0x80008000 >= (uint64_t) 1 << 32)
2207     return false;
2208
2209   *value = addr;
2210   return true;
2211 }
2212
2213 // Perform the Sized_relobj_file method, then set up opd info from
2214 // .opd relocs.
2215
2216 template<int size, bool big_endian>
2217 void
2218 Powerpc_relobj<size, big_endian>::do_read_relocs(Read_relocs_data* rd)
2219 {
2220   Sized_relobj_file<size, big_endian>::do_read_relocs(rd);
2221   if (size == 64)
2222     {
2223       for (Read_relocs_data::Relocs_list::iterator p = rd->relocs.begin();
2224            p != rd->relocs.end();
2225            ++p)
2226         {
2227           if (p->data_shndx == this->opd_shndx())
2228             {
2229               uint64_t opd_size = this->section_size(this->opd_shndx());
2230               gold_assert(opd_size == static_cast<size_t>(opd_size));
2231               if (opd_size != 0)
2232                 {
2233                   this->init_opd(opd_size);
2234                   this->scan_opd_relocs(p->reloc_count, p->contents->data(),
2235                                         rd->local_symbols->data());
2236                 }
2237               break;
2238             }
2239         }
2240     }
2241 }
2242
2243 // Read the symbols then set up st_other vector.
2244
2245 template<int size, bool big_endian>
2246 void
2247 Powerpc_relobj<size, big_endian>::do_read_symbols(Read_symbols_data* sd)
2248 {
2249   this->base_read_symbols(sd);
2250   if (size == 64)
2251     {
2252       const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
2253       const unsigned char* const pshdrs = sd->section_headers->data();
2254       const unsigned int loccount = this->do_local_symbol_count();
2255       if (loccount != 0)
2256         {
2257           this->st_other_.resize(loccount);
2258           const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
2259           off_t locsize = loccount * sym_size;
2260           const unsigned int symtab_shndx = this->symtab_shndx();
2261           const unsigned char *psymtab = pshdrs + symtab_shndx * shdr_size;
2262           typename elfcpp::Shdr<size, big_endian> shdr(psymtab);
2263           const unsigned char* psyms = this->get_view(shdr.get_sh_offset(),
2264                                                       locsize, true, false);
2265           psyms += sym_size;
2266           for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
2267             {
2268               elfcpp::Sym<size, big_endian> sym(psyms);
2269               unsigned char st_other = sym.get_st_other();
2270               this->st_other_[i] = st_other;
2271               if ((st_other & elfcpp::STO_PPC64_LOCAL_MASK) != 0)
2272                 {
2273                   if (this->abiversion() == 0)
2274                     this->set_abiversion(2);
2275                   else if (this->abiversion() < 2)
2276                     gold_error(_("%s: local symbol %d has invalid st_other"
2277                                  " for ABI version 1"),
2278                                this->name().c_str(), i);
2279                 }
2280             }
2281         }
2282     }
2283 }
2284
2285 template<int size, bool big_endian>
2286 void
2287 Powerpc_dynobj<size, big_endian>::set_abiversion(int ver)
2288 {
2289   this->e_flags_ |= ver;
2290   if (this->abiversion() != 0)
2291     {
2292       Target_powerpc<size, big_endian>* target =
2293         static_cast<Target_powerpc<size, big_endian>*>(
2294           parameters->sized_target<size, big_endian>());
2295       if (target->abiversion() == 0)
2296         target->set_abiversion(this->abiversion());
2297       else if (target->abiversion() != this->abiversion())
2298         gold_error(_("%s: ABI version %d is not compatible "
2299                      "with ABI version %d output"),
2300                    this->name().c_str(),
2301                    this->abiversion(), target->abiversion());
2302
2303     }
2304 }
2305
2306 // Call Sized_dynobj::base_read_symbols to read the symbols then
2307 // read .opd from a dynamic object, filling in opd_ent_ vector,
2308
2309 template<int size, bool big_endian>
2310 void
2311 Powerpc_dynobj<size, big_endian>::do_read_symbols(Read_symbols_data* sd)
2312 {
2313   this->base_read_symbols(sd);
2314   if (size == 64)
2315     {
2316       const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
2317       const unsigned char* const pshdrs = sd->section_headers->data();
2318       const unsigned char* namesu = sd->section_names->data();
2319       const char* names = reinterpret_cast<const char*>(namesu);
2320       const unsigned char* s = NULL;
2321       const unsigned char* opd;
2322       section_size_type opd_size;
2323
2324       // Find and read .opd section.
2325       while (1)
2326         {
2327           s = this->template find_shdr<size, big_endian>(pshdrs, ".opd", names,
2328                                                          sd->section_names_size,
2329                                                          s);
2330           if (s == NULL)
2331             return;
2332
2333           typename elfcpp::Shdr<size, big_endian> shdr(s);
2334           if (shdr.get_sh_type() == elfcpp::SHT_PROGBITS
2335               && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0)
2336             {
2337               if (this->abiversion() == 0)
2338                 this->set_abiversion(1);
2339               else if (this->abiversion() > 1)
2340                 gold_error(_("%s: .opd invalid in abiv%d"),
2341                            this->name().c_str(), this->abiversion());
2342
2343               this->opd_shndx_ = (s - pshdrs) / shdr_size;
2344               this->opd_address_ = shdr.get_sh_addr();
2345               opd_size = convert_to_section_size_type(shdr.get_sh_size());
2346               opd = this->get_view(shdr.get_sh_offset(), opd_size,
2347                                    true, false);
2348               break;
2349             }
2350         }
2351
2352       // Build set of executable sections.
2353       // Using a set is probably overkill.  There is likely to be only
2354       // a few executable sections, typically .init, .text and .fini,
2355       // and they are generally grouped together.
2356       typedef std::set<Sec_info> Exec_sections;
2357       Exec_sections exec_sections;
2358       s = pshdrs;
2359       for (unsigned int i = 1; i < this->shnum(); ++i, s += shdr_size)
2360         {
2361           typename elfcpp::Shdr<size, big_endian> shdr(s);
2362           if (shdr.get_sh_type() == elfcpp::SHT_PROGBITS
2363               && ((shdr.get_sh_flags()
2364                    & (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
2365                   == (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
2366               && shdr.get_sh_size() != 0)
2367             {
2368               exec_sections.insert(Sec_info(shdr.get_sh_addr(),
2369                                             shdr.get_sh_size(), i));
2370             }
2371         }
2372       if (exec_sections.empty())
2373         return;
2374
2375       // Look over the OPD entries.  This is complicated by the fact
2376       // that some binaries will use two-word entries while others
2377       // will use the standard three-word entries.  In most cases
2378       // the third word (the environment pointer for languages like
2379       // Pascal) is unused and will be zero.  If the third word is
2380       // used it should not be pointing into executable sections,
2381       // I think.
2382       this->init_opd(opd_size);
2383       for (const unsigned char* p = opd; p < opd + opd_size; p += 8)
2384         {
2385           typedef typename elfcpp::Swap<64, big_endian>::Valtype Valtype;
2386           const Valtype* valp = reinterpret_cast<const Valtype*>(p);
2387           Valtype val = elfcpp::Swap<64, big_endian>::readval(valp);
2388           if (val == 0)
2389             // Chances are that this is the third word of an OPD entry.
2390             continue;
2391           typename Exec_sections::const_iterator e
2392             = exec_sections.upper_bound(Sec_info(val, 0, 0));
2393           if (e != exec_sections.begin())
2394             {
2395               --e;
2396               if (e->start <= val && val < e->start + e->len)
2397                 {
2398                   // We have an address in an executable section.
2399                   // VAL ought to be the function entry, set it up.
2400                   this->set_opd_ent(p - opd, e->shndx, val);
2401                   // Skip second word of OPD entry, the TOC pointer.
2402                   p += 8;
2403                 }
2404             }
2405           // If we didn't match any executable sections, we likely
2406           // have a non-zero third word in the OPD entry.
2407         }
2408     }
2409 }
2410
2411 // Relocate sections.
2412
2413 template<int size, bool big_endian>
2414 void
2415 Powerpc_relobj<size, big_endian>::do_relocate_sections(
2416     const Symbol_table* symtab, const Layout* layout,
2417     const unsigned char* pshdrs, Output_file* of,
2418     typename Sized_relobj_file<size, big_endian>::Views* pviews)
2419 {
2420   unsigned int start = 1;
2421   if (size == 64
2422       && this->relatoc_ != 0
2423       && !parameters->options().relocatable())
2424     {
2425       // Relocate .toc first.
2426       this->relocate_section_range(symtab, layout, pshdrs, of, pviews,
2427                                    this->relatoc_, this->relatoc_);
2428       this->relocate_section_range(symtab, layout, pshdrs, of, pviews,
2429                                    1, this->relatoc_ - 1);
2430       start = this->relatoc_ + 1;
2431     }
2432   this->relocate_section_range(symtab, layout, pshdrs, of, pviews,
2433                                start, this->shnum() - 1);
2434 }
2435
2436 // Set up some symbols.
2437
2438 template<int size, bool big_endian>
2439 void
2440 Target_powerpc<size, big_endian>::do_define_standard_symbols(
2441     Symbol_table* symtab,
2442     Layout* layout)
2443 {
2444   if (size == 32)
2445     {
2446       // Define _GLOBAL_OFFSET_TABLE_ to ensure it isn't seen as
2447       // undefined when scanning relocs (and thus requires
2448       // non-relative dynamic relocs).  The proper value will be
2449       // updated later.
2450       Symbol *gotsym = symtab->lookup("_GLOBAL_OFFSET_TABLE_", NULL);
2451       if (gotsym != NULL && gotsym->is_undefined())
2452         {
2453           Target_powerpc<size, big_endian>* target =
2454             static_cast<Target_powerpc<size, big_endian>*>(
2455                 parameters->sized_target<size, big_endian>());
2456           Output_data_got_powerpc<size, big_endian>* got
2457             = target->got_section(symtab, layout);
2458           symtab->define_in_output_data("_GLOBAL_OFFSET_TABLE_", NULL,
2459                                         Symbol_table::PREDEFINED,
2460                                         got, 0, 0,
2461                                         elfcpp::STT_OBJECT,
2462                                         elfcpp::STB_LOCAL,
2463                                         elfcpp::STV_HIDDEN, 0,
2464                                         false, false);
2465         }
2466
2467       // Define _SDA_BASE_ at the start of the .sdata section + 32768.
2468       Symbol *sdasym = symtab->lookup("_SDA_BASE_", NULL);
2469       if (sdasym != NULL && sdasym->is_undefined())
2470         {
2471           Output_data_space* sdata = new Output_data_space(4, "** sdata");
2472           Output_section* os
2473             = layout->add_output_section_data(".sdata", 0,
2474                                               elfcpp::SHF_ALLOC
2475                                               | elfcpp::SHF_WRITE,
2476                                               sdata, ORDER_SMALL_DATA, false);
2477           symtab->define_in_output_data("_SDA_BASE_", NULL,
2478                                         Symbol_table::PREDEFINED,
2479                                         os, 32768, 0, elfcpp::STT_OBJECT,
2480                                         elfcpp::STB_LOCAL, elfcpp::STV_HIDDEN,
2481                                         0, false, false);
2482         }
2483     }
2484   else
2485     {
2486       // Define .TOC. as for 32-bit _GLOBAL_OFFSET_TABLE_
2487       Symbol *gotsym = symtab->lookup(".TOC.", NULL);
2488       if (gotsym != NULL && gotsym->is_undefined())
2489         {
2490           Target_powerpc<size, big_endian>* target =
2491             static_cast<Target_powerpc<size, big_endian>*>(
2492                 parameters->sized_target<size, big_endian>());
2493           Output_data_got_powerpc<size, big_endian>* got
2494             = target->got_section(symtab, layout);
2495           symtab->define_in_output_data(".TOC.", NULL,
2496                                         Symbol_table::PREDEFINED,
2497                                         got, 0x8000, 0,
2498                                         elfcpp::STT_OBJECT,
2499                                         elfcpp::STB_LOCAL,
2500                                         elfcpp::STV_HIDDEN, 0,
2501                                         false, false);
2502         }
2503     }
2504
2505   this->tls_get_addr_ = symtab->lookup("__tls_get_addr");
2506   if (parameters->options().tls_get_addr_optimize()
2507       && this->tls_get_addr_ != NULL
2508       && this->tls_get_addr_->in_reg())
2509     this->tls_get_addr_opt_ = symtab->lookup("__tls_get_addr_opt");
2510   if (this->tls_get_addr_opt_ != NULL)
2511     {
2512       if (this->tls_get_addr_->is_undefined()
2513           || this->tls_get_addr_->is_from_dynobj())
2514         {
2515           // Make it seem as if references to __tls_get_addr are
2516           // really to __tls_get_addr_opt, so the latter symbol is
2517           // made dynamic, not the former.
2518           this->tls_get_addr_->clear_in_reg();
2519           this->tls_get_addr_opt_->set_in_reg();
2520         }
2521       // We have a non-dynamic definition for __tls_get_addr.
2522       // Make __tls_get_addr_opt the same, if it does not already have
2523       // a non-dynamic definition.
2524       else if (this->tls_get_addr_opt_->is_undefined()
2525                || this->tls_get_addr_opt_->is_from_dynobj())
2526         {
2527           Sized_symbol<size>* from
2528             = static_cast<Sized_symbol<size>*>(this->tls_get_addr_);
2529           Sized_symbol<size>* to
2530             = static_cast<Sized_symbol<size>*>(this->tls_get_addr_opt_);
2531           symtab->clone<size>(to, from);
2532         }
2533     }
2534 }
2535
2536 // Set up PowerPC target specific relobj.
2537
2538 template<int size, bool big_endian>
2539 Object*
2540 Target_powerpc<size, big_endian>::do_make_elf_object(
2541     const std::string& name,
2542     Input_file* input_file,
2543     off_t offset, const elfcpp::Ehdr<size, big_endian>& ehdr)
2544 {
2545   int et = ehdr.get_e_type();
2546   // ET_EXEC files are valid input for --just-symbols/-R,
2547   // and we treat them as relocatable objects.
2548   if (et == elfcpp::ET_REL
2549       || (et == elfcpp::ET_EXEC && input_file->just_symbols()))
2550     {
2551       Powerpc_relobj<size, big_endian>* obj =
2552         new Powerpc_relobj<size, big_endian>(name, input_file, offset, ehdr);
2553       obj->setup();
2554       return obj;
2555     }
2556   else if (et == elfcpp::ET_DYN)
2557     {
2558       Powerpc_dynobj<size, big_endian>* obj =
2559         new Powerpc_dynobj<size, big_endian>(name, input_file, offset, ehdr);
2560       obj->setup();
2561       return obj;
2562     }
2563   else
2564     {
2565       gold_error(_("%s: unsupported ELF file type %d"), name.c_str(), et);
2566       return NULL;
2567     }
2568 }
2569
2570 template<int size, bool big_endian>
2571 class Output_data_got_powerpc : public Output_data_got<size, big_endian>
2572 {
2573 public:
2574   typedef typename elfcpp::Elf_types<size>::Elf_Addr Valtype;
2575   typedef Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian> Rela_dyn;
2576
2577   Output_data_got_powerpc(Symbol_table* symtab, Layout* layout)
2578     : Output_data_got<size, big_endian>(),
2579       symtab_(symtab), layout_(layout),
2580       header_ent_cnt_(size == 32 ? 3 : 1),
2581       header_index_(size == 32 ? 0x2000 : 0)
2582   {
2583     if (size == 64)
2584       this->set_addralign(256);
2585   }
2586
2587   // Override all the Output_data_got methods we use so as to first call
2588   // reserve_ent().
2589   bool
2590   add_global(Symbol* gsym, unsigned int got_type)
2591   {
2592     this->reserve_ent();
2593     return Output_data_got<size, big_endian>::add_global(gsym, got_type);
2594   }
2595
2596   bool
2597   add_global_plt(Symbol* gsym, unsigned int got_type)
2598   {
2599     this->reserve_ent();
2600     return Output_data_got<size, big_endian>::add_global_plt(gsym, got_type);
2601   }
2602
2603   bool
2604   add_global_tls(Symbol* gsym, unsigned int got_type)
2605   { return this->add_global_plt(gsym, got_type); }
2606
2607   void
2608   add_global_with_rel(Symbol* gsym, unsigned int got_type,
2609                       Output_data_reloc_generic* rel_dyn, unsigned int r_type)
2610   {
2611     this->reserve_ent();
2612     Output_data_got<size, big_endian>::
2613       add_global_with_rel(gsym, got_type, rel_dyn, r_type);
2614   }
2615
2616   void
2617   add_global_pair_with_rel(Symbol* gsym, unsigned int got_type,
2618                            Output_data_reloc_generic* rel_dyn,
2619                            unsigned int r_type_1, unsigned int r_type_2)
2620   {
2621     if (gsym->has_got_offset(got_type))
2622       return;
2623
2624     this->reserve_ent(2);
2625     Output_data_got<size, big_endian>::
2626       add_global_pair_with_rel(gsym, got_type, rel_dyn, r_type_1, r_type_2);
2627   }
2628
2629   bool
2630   add_local(Relobj* object, unsigned int sym_index, unsigned int got_type)
2631   {
2632     this->reserve_ent();
2633     return Output_data_got<size, big_endian>::add_local(object, sym_index,
2634                                                         got_type);
2635   }
2636
2637   bool
2638   add_local_plt(Relobj* object, unsigned int sym_index, unsigned int got_type)
2639   {
2640     this->reserve_ent();
2641     return Output_data_got<size, big_endian>::add_local_plt(object, sym_index,
2642                                                             got_type);
2643   }
2644
2645   bool
2646   add_local_tls(Relobj* object, unsigned int sym_index, unsigned int got_type)
2647   { return this->add_local_plt(object, sym_index, got_type); }
2648
2649   void
2650   add_local_tls_pair(Relobj* object, unsigned int sym_index,
2651                      unsigned int got_type,
2652                      Output_data_reloc_generic* rel_dyn,
2653                      unsigned int r_type)
2654   {
2655     if (object->local_has_got_offset(sym_index, got_type))
2656       return;
2657
2658     this->reserve_ent(2);
2659     Output_data_got<size, big_endian>::
2660       add_local_tls_pair(object, sym_index, got_type, rel_dyn, r_type);
2661   }
2662
2663   unsigned int
2664   add_constant(Valtype constant)
2665   {
2666     this->reserve_ent();
2667     return Output_data_got<size, big_endian>::add_constant(constant);
2668   }
2669
2670   unsigned int
2671   add_constant_pair(Valtype c1, Valtype c2)
2672   {
2673     this->reserve_ent(2);
2674     return Output_data_got<size, big_endian>::add_constant_pair(c1, c2);
2675   }
2676
2677   // Offset of _GLOBAL_OFFSET_TABLE_.
2678   unsigned int
2679   g_o_t() const
2680   {
2681     return this->got_offset(this->header_index_);
2682   }
2683
2684   // Offset of base used to access the GOT/TOC.
2685   // The got/toc pointer reg will be set to this value.
2686   Valtype
2687   got_base_offset(const Powerpc_relobj<size, big_endian>* object) const
2688   {
2689     if (size == 32)
2690       return this->g_o_t();
2691     else
2692       return (this->output_section()->address()
2693               + object->toc_base_offset()
2694               - this->address());
2695   }
2696
2697   // Ensure our GOT has a header.
2698   void
2699   set_final_data_size()
2700   {
2701     if (this->header_ent_cnt_ != 0)
2702       this->make_header();
2703     Output_data_got<size, big_endian>::set_final_data_size();
2704   }
2705
2706   // First word of GOT header needs some values that are not
2707   // handled by Output_data_got so poke them in here.
2708   // For 32-bit, address of .dynamic, for 64-bit, address of TOCbase.
2709   void
2710   do_write(Output_file* of)
2711   {
2712     Valtype val = 0;
2713     if (size == 32 && this->layout_->dynamic_data() != NULL)
2714       val = this->layout_->dynamic_section()->address();
2715     if (size == 64)
2716       val = this->output_section()->address() + 0x8000;
2717     this->replace_constant(this->header_index_, val);
2718     Output_data_got<size, big_endian>::do_write(of);
2719   }
2720
2721 private:
2722   void
2723   reserve_ent(unsigned int cnt = 1)
2724   {
2725     if (this->header_ent_cnt_ == 0)
2726       return;
2727     if (this->num_entries() + cnt > this->header_index_)
2728       this->make_header();
2729   }
2730
2731   void
2732   make_header()
2733   {
2734     this->header_ent_cnt_ = 0;
2735     this->header_index_ = this->num_entries();
2736     if (size == 32)
2737       {
2738         Output_data_got<size, big_endian>::add_constant(0);
2739         Output_data_got<size, big_endian>::add_constant(0);
2740         Output_data_got<size, big_endian>::add_constant(0);
2741
2742         // Define _GLOBAL_OFFSET_TABLE_ at the header
2743         Symbol *gotsym = this->symtab_->lookup("_GLOBAL_OFFSET_TABLE_", NULL);
2744         if (gotsym != NULL)
2745           {
2746             Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(gotsym);
2747             sym->set_value(this->g_o_t());
2748           }
2749         else
2750           this->symtab_->define_in_output_data("_GLOBAL_OFFSET_TABLE_", NULL,
2751                                                Symbol_table::PREDEFINED,
2752                                                this, this->g_o_t(), 0,
2753                                                elfcpp::STT_OBJECT,
2754                                                elfcpp::STB_LOCAL,
2755                                                elfcpp::STV_HIDDEN, 0,
2756                                                false, false);
2757       }
2758     else
2759       Output_data_got<size, big_endian>::add_constant(0);
2760   }
2761
2762   // Stashed pointers.
2763   Symbol_table* symtab_;
2764   Layout* layout_;
2765
2766   // GOT header size.
2767   unsigned int header_ent_cnt_;
2768   // GOT header index.
2769   unsigned int header_index_;
2770 };
2771
2772 // Get the GOT section, creating it if necessary.
2773
2774 template<int size, bool big_endian>
2775 Output_data_got_powerpc<size, big_endian>*
2776 Target_powerpc<size, big_endian>::got_section(Symbol_table* symtab,
2777                                               Layout* layout)
2778 {
2779   if (this->got_ == NULL)
2780     {
2781       gold_assert(symtab != NULL && layout != NULL);
2782
2783       this->got_
2784         = new Output_data_got_powerpc<size, big_endian>(symtab, layout);
2785
2786       layout->add_output_section_data(".got", elfcpp::SHT_PROGBITS,
2787                                       elfcpp::SHF_ALLOC | elfcpp::SHF_WRITE,
2788                                       this->got_, ORDER_DATA, false);
2789     }
2790
2791   return this->got_;
2792 }
2793
2794 // Get the dynamic reloc section, creating it if necessary.
2795
2796 template<int size, bool big_endian>
2797 typename Target_powerpc<size, big_endian>::Reloc_section*
2798 Target_powerpc<size, big_endian>::rela_dyn_section(Layout* layout)
2799 {
2800   if (this->rela_dyn_ == NULL)
2801     {
2802       gold_assert(layout != NULL);
2803       this->rela_dyn_ = new Reloc_section(parameters->options().combreloc());
2804       layout->add_output_section_data(".rela.dyn", elfcpp::SHT_RELA,
2805                                       elfcpp::SHF_ALLOC, this->rela_dyn_,
2806                                       ORDER_DYNAMIC_RELOCS, false);
2807     }
2808   return this->rela_dyn_;
2809 }
2810
2811 // Similarly, but for ifunc symbols get the one for ifunc.
2812
2813 template<int size, bool big_endian>
2814 typename Target_powerpc<size, big_endian>::Reloc_section*
2815 Target_powerpc<size, big_endian>::rela_dyn_section(Symbol_table* symtab,
2816                                                    Layout* layout,
2817                                                    bool for_ifunc)
2818 {
2819   if (!for_ifunc)
2820     return this->rela_dyn_section(layout);
2821
2822   if (this->iplt_ == NULL)
2823     this->make_iplt_section(symtab, layout);
2824   return this->iplt_->rel_plt();
2825 }
2826
2827 class Stub_control
2828 {
2829  public:
2830   // Determine the stub group size.  The group size is the absolute
2831   // value of the parameter --stub-group-size.  If --stub-group-size
2832   // is passed a negative value, we restrict stubs to be always after
2833   // the stubbed branches.
2834   Stub_control(int32_t size, bool no_size_errors, bool multi_os)
2835     : stub_group_size_(abs(size)), stubs_always_after_branch_(size < 0),
2836       suppress_size_errors_(no_size_errors), multi_os_(multi_os),
2837       state_(NO_GROUP), group_size_(0), group_start_addr_(0),
2838       owner_(NULL), output_section_(NULL)
2839   {
2840   }
2841
2842   // Return true iff input section can be handled by current stub
2843   // group.
2844   bool
2845   can_add_to_stub_group(Output_section* o,
2846                         const Output_section::Input_section* i,
2847                         bool has14);
2848
2849   const Output_section::Input_section*
2850   owner()
2851   { return owner_; }
2852
2853   Output_section*
2854   output_section()
2855   { return output_section_; }
2856
2857   void
2858   set_output_and_owner(Output_section* o,
2859                        const Output_section::Input_section* i)
2860   {
2861     this->output_section_ = o;
2862     this->owner_ = i;
2863   }
2864
2865  private:
2866   typedef enum
2867   {
2868     // Initial state.
2869     NO_GROUP,
2870     // Adding group sections before the stubs.
2871     FINDING_STUB_SECTION,
2872     // Adding group sections after the stubs.
2873     HAS_STUB_SECTION
2874   } State;
2875
2876   uint32_t stub_group_size_;
2877   bool stubs_always_after_branch_;
2878   bool suppress_size_errors_;
2879   // True if a stub group can serve multiple output sections.
2880   bool multi_os_;
2881   State state_;
2882   // Current max size of group.  Starts at stub_group_size_ but is
2883   // reduced to stub_group_size_/1024 on seeing a section with
2884   // external conditional branches.
2885   uint32_t group_size_;
2886   uint64_t group_start_addr_;
2887   // owner_ and output_section_ specify the section to which stubs are
2888   // attached.  The stubs are placed at the end of this section.
2889   const Output_section::Input_section* owner_;
2890   Output_section* output_section_;
2891 };
2892
2893 // Return true iff input section can be handled by current stub
2894 // group.  Sections are presented to this function in order,
2895 // so the first section is the head of the group.
2896
2897 bool
2898 Stub_control::can_add_to_stub_group(Output_section* o,
2899                                     const Output_section::Input_section* i,
2900                                     bool has14)
2901 {
2902   bool whole_sec = o->order() == ORDER_INIT || o->order() == ORDER_FINI;
2903   uint64_t this_size;
2904   uint64_t start_addr = o->address();
2905
2906   if (whole_sec)
2907     // .init and .fini sections are pasted together to form a single
2908     // function.  We can't be adding stubs in the middle of the function.
2909     this_size = o->data_size();
2910   else
2911     {
2912       start_addr += i->relobj()->output_section_offset(i->shndx());
2913       this_size = i->data_size();
2914     }
2915
2916   uint64_t end_addr = start_addr + this_size;
2917   uint32_t group_size = this->stub_group_size_;
2918   if (has14)
2919     this->group_size_ = group_size = group_size >> 10;
2920
2921   if (this_size > group_size && !this->suppress_size_errors_)
2922     gold_warning(_("%s:%s exceeds group size"),
2923                  i->relobj()->name().c_str(),
2924                  i->relobj()->section_name(i->shndx()).c_str());
2925
2926   gold_debug(DEBUG_TARGET, "maybe add%s %s:%s size=%#llx total=%#llx",
2927              has14 ? " 14bit" : "",
2928              i->relobj()->name().c_str(),
2929              i->relobj()->section_name(i->shndx()).c_str(),
2930              (long long) this_size,
2931              (this->state_ == NO_GROUP
2932               ? this_size
2933               : (long long) end_addr - this->group_start_addr_));
2934
2935   if (this->state_ == NO_GROUP)
2936     {
2937       // Only here on very first use of Stub_control
2938       this->owner_ = i;
2939       this->output_section_ = o;
2940       this->state_ = FINDING_STUB_SECTION;
2941       this->group_size_ = group_size;
2942       this->group_start_addr_ = start_addr;
2943       return true;
2944     }
2945   else if (!this->multi_os_ && this->output_section_ != o)
2946     ;
2947   else if (this->state_ == HAS_STUB_SECTION)
2948     {
2949       // Can we add this section, which is after the stubs, to the
2950       // group?
2951       if (end_addr - this->group_start_addr_ <= this->group_size_)
2952         return true;
2953     }
2954   else if (this->state_ == FINDING_STUB_SECTION)
2955     {
2956       if ((whole_sec && this->output_section_ == o)
2957           || end_addr - this->group_start_addr_ <= this->group_size_)
2958         {
2959           // Stubs are added at the end of "owner_".
2960           this->owner_ = i;
2961           this->output_section_ = o;
2962           return true;
2963         }
2964       // The group before the stubs has reached maximum size.
2965       // Now see about adding sections after the stubs to the
2966       // group.  If the current section has a 14-bit branch and
2967       // the group before the stubs exceeds group_size_ (because
2968       // they didn't have 14-bit branches), don't add sections
2969       // after the stubs:  The size of stubs for such a large
2970       // group may exceed the reach of a 14-bit branch.
2971       if (!this->stubs_always_after_branch_
2972           && this_size <= this->group_size_
2973           && start_addr - this->group_start_addr_ <= this->group_size_)
2974         {
2975           gold_debug(DEBUG_TARGET, "adding after stubs");
2976           this->state_ = HAS_STUB_SECTION;
2977           this->group_start_addr_ = start_addr;
2978           return true;
2979         }
2980     }
2981   else
2982     gold_unreachable();
2983
2984   gold_debug(DEBUG_TARGET,
2985              !this->multi_os_ && this->output_section_ != o
2986              ? "nope, new output section\n"
2987              : "nope, didn't fit\n");
2988
2989   // The section fails to fit in the current group.  Set up a few
2990   // things for the next group.  owner_ and output_section_ will be
2991   // set later after we've retrieved those values for the current
2992   // group.
2993   this->state_ = FINDING_STUB_SECTION;
2994   this->group_size_ = group_size;
2995   this->group_start_addr_ = start_addr;
2996   return false;
2997 }
2998
2999 // Look over all the input sections, deciding where to place stubs.
3000
3001 template<int size, bool big_endian>
3002 void
3003 Target_powerpc<size, big_endian>::group_sections(Layout* layout,
3004                                                  const Task*,
3005                                                  bool no_size_errors)
3006 {
3007   Stub_control stub_control(this->stub_group_size_, no_size_errors,
3008                             parameters->options().stub_group_multi());
3009
3010   // Group input sections and insert stub table
3011   Stub_table_owner* table_owner = NULL;
3012   std::vector<Stub_table_owner*> tables;
3013   Layout::Section_list section_list;
3014   layout->get_executable_sections(&section_list);
3015   std::stable_sort(section_list.begin(), section_list.end(), Sort_sections());
3016   for (Layout::Section_list::iterator o = section_list.begin();
3017        o != section_list.end();
3018        ++o)
3019     {
3020       typedef Output_section::Input_section_list Input_section_list;
3021       for (Input_section_list::const_iterator i
3022              = (*o)->input_sections().begin();
3023            i != (*o)->input_sections().end();
3024            ++i)
3025         {
3026           if (i->is_input_section()
3027               || i->is_relaxed_input_section())
3028             {
3029               Powerpc_relobj<size, big_endian>* ppcobj = static_cast
3030                 <Powerpc_relobj<size, big_endian>*>(i->relobj());
3031               bool has14 = ppcobj->has_14bit_branch(i->shndx());
3032               if (!stub_control.can_add_to_stub_group(*o, &*i, has14))
3033                 {
3034                   table_owner->output_section = stub_control.output_section();
3035                   table_owner->owner = stub_control.owner();
3036                   stub_control.set_output_and_owner(*o, &*i);
3037                   table_owner = NULL;
3038                 }
3039               if (table_owner == NULL)
3040                 {
3041                   table_owner = new Stub_table_owner;
3042                   tables.push_back(table_owner);
3043                 }
3044               ppcobj->set_stub_table(i->shndx(), tables.size() - 1);
3045             }
3046         }
3047     }
3048   if (table_owner != NULL)
3049     {
3050       table_owner->output_section = stub_control.output_section();
3051       table_owner->owner = stub_control.owner();;
3052     }
3053   for (typename std::vector<Stub_table_owner*>::iterator t = tables.begin();
3054        t != tables.end();
3055        ++t)
3056     {
3057       Stub_table<size, big_endian>* stub_table;
3058
3059       if ((*t)->owner->is_input_section())
3060         stub_table = new Stub_table<size, big_endian>(this,
3061                                                       (*t)->output_section,
3062                                                       (*t)->owner,
3063                                                       this->stub_tables_.size());
3064       else if ((*t)->owner->is_relaxed_input_section())
3065         stub_table = static_cast<Stub_table<size, big_endian>*>(
3066                         (*t)->owner->relaxed_input_section());
3067       else
3068         gold_unreachable();
3069       this->stub_tables_.push_back(stub_table);
3070       delete *t;
3071     }
3072 }
3073
3074 static unsigned long
3075 max_branch_delta (unsigned int r_type)
3076 {
3077   if (r_type == elfcpp::R_POWERPC_REL14
3078       || r_type == elfcpp::R_POWERPC_REL14_BRTAKEN
3079       || r_type == elfcpp::R_POWERPC_REL14_BRNTAKEN)
3080     return 1L << 15;
3081   if (r_type == elfcpp::R_POWERPC_REL24
3082       || r_type == elfcpp::R_PPC_PLTREL24
3083       || r_type == elfcpp::R_PPC_LOCAL24PC)
3084     return 1L << 25;
3085   return 0;
3086 }
3087
3088 // Return whether this branch is going via a plt call stub.
3089
3090 template<int size, bool big_endian>
3091 bool
3092 Target_powerpc<size, big_endian>::Branch_info::mark_pltcall(
3093     Powerpc_relobj<size, big_endian>* ppc_object,
3094     unsigned int shndx,
3095     Address offset,
3096     Target_powerpc* target,
3097     Symbol_table* symtab)
3098 {
3099   if (this->object_ != ppc_object
3100       || this->shndx_ != shndx
3101       || this->offset_ != offset)
3102     return false;
3103
3104   Symbol* sym = this->object_->global_symbol(this->r_sym_);
3105   if (target->replace_tls_get_addr(sym))
3106     sym = target->tls_get_addr_opt();
3107   if (sym != NULL && sym->is_forwarder())
3108     sym = symtab->resolve_forwards(sym);
3109   const Sized_symbol<size>* gsym = static_cast<const Sized_symbol<size>*>(sym);
3110   if (gsym != NULL
3111       ? (gsym->use_plt_offset(Scan::get_reference_flags(this->r_type_, target))
3112          && !target->is_elfv2_localentry0(gsym))
3113       : (this->object_->local_has_plt_offset(this->r_sym_)
3114          && !target->is_elfv2_localentry0(this->object_, this->r_sym_)))
3115     {
3116       this->tocsave_ = 1;
3117       return true;
3118     }
3119   return false;
3120 }
3121
3122 // If this branch needs a plt call stub, or a long branch stub, make one.
3123
3124 template<int size, bool big_endian>
3125 bool
3126 Target_powerpc<size, big_endian>::Branch_info::make_stub(
3127     Stub_table<size, big_endian>* stub_table,
3128     Stub_table<size, big_endian>* ifunc_stub_table,
3129     Symbol_table* symtab) const
3130 {
3131   Symbol* sym = this->object_->global_symbol(this->r_sym_);
3132   Target_powerpc<size, big_endian>* target =
3133     static_cast<Target_powerpc<size, big_endian>*>(
3134       parameters->sized_target<size, big_endian>());
3135   if (target->replace_tls_get_addr(sym))
3136     sym = target->tls_get_addr_opt();
3137   if (sym != NULL && sym->is_forwarder())
3138     sym = symtab->resolve_forwards(sym);
3139   const Sized_symbol<size>* gsym = static_cast<const Sized_symbol<size>*>(sym);
3140   bool ok = true;
3141
3142   if (gsym != NULL
3143       ? gsym->use_plt_offset(Scan::get_reference_flags(this->r_type_, target))
3144       : this->object_->local_has_plt_offset(this->r_sym_))
3145     {
3146       if (size == 64
3147           && gsym != NULL
3148           && target->abiversion() >= 2
3149           && !parameters->options().output_is_position_independent()
3150           && !is_branch_reloc(this->r_type_))
3151         target->glink_section()->add_global_entry(gsym);
3152       else
3153         {
3154           if (stub_table == NULL
3155               && !(size == 32
3156                    && gsym != NULL
3157                    && !parameters->options().output_is_position_independent()
3158                    && !is_branch_reloc(this->r_type_)))
3159             stub_table = this->object_->stub_table(this->shndx_);
3160           if (stub_table == NULL)
3161             {
3162               // This is a ref from a data section to an ifunc symbol,
3163               // or a non-branch reloc for which we always want to use
3164               // one set of stubs for resolving function addresses.
3165               stub_table = ifunc_stub_table;
3166             }
3167           gold_assert(stub_table != NULL);
3168           Address from = this->object_->get_output_section_offset(this->shndx_);
3169           if (from != invalid_address)
3170             from += (this->object_->output_section(this->shndx_)->address()
3171                      + this->offset_);
3172           if (gsym != NULL)
3173             ok = stub_table->add_plt_call_entry(from,
3174                                                 this->object_, gsym,
3175                                                 this->r_type_, this->addend_,
3176                                                 this->tocsave_);
3177           else
3178             ok = stub_table->add_plt_call_entry(from,
3179                                                 this->object_, this->r_sym_,
3180                                                 this->r_type_, this->addend_,
3181                                                 this->tocsave_);
3182         }
3183     }
3184   else
3185     {
3186       Address max_branch_offset = max_branch_delta(this->r_type_);
3187       if (max_branch_offset == 0)
3188         return true;
3189       Address from = this->object_->get_output_section_offset(this->shndx_);
3190       gold_assert(from != invalid_address);
3191       from += (this->object_->output_section(this->shndx_)->address()
3192                + this->offset_);
3193       Address to;
3194       if (gsym != NULL)
3195         {
3196           switch (gsym->source())
3197             {
3198             case Symbol::FROM_OBJECT:
3199               {
3200                 Object* symobj = gsym->object();
3201                 if (symobj->is_dynamic()
3202                     || symobj->pluginobj() != NULL)
3203                   return true;
3204                 bool is_ordinary;
3205                 unsigned int shndx = gsym->shndx(&is_ordinary);
3206                 if (shndx == elfcpp::SHN_UNDEF)
3207                   return true;
3208               }
3209               break;
3210
3211             case Symbol::IS_UNDEFINED:
3212               return true;
3213
3214             default:
3215               break;
3216             }
3217           Symbol_table::Compute_final_value_status status;
3218           to = symtab->compute_final_value<size>(gsym, &status);
3219           if (status != Symbol_table::CFVS_OK)
3220             return true;
3221           if (size == 64)
3222             to += this->object_->ppc64_local_entry_offset(gsym);
3223         }
3224       else
3225         {
3226           const Symbol_value<size>* psymval
3227             = this->object_->local_symbol(this->r_sym_);
3228           Symbol_value<size> symval;
3229           if (psymval->is_section_symbol())
3230             symval.set_is_section_symbol();
3231           typedef Sized_relobj_file<size, big_endian> ObjType;
3232           typename ObjType::Compute_final_local_value_status status
3233             = this->object_->compute_final_local_value(this->r_sym_, psymval,
3234                                                        &symval, symtab);
3235           if (status != ObjType::CFLV_OK
3236               || !symval.has_output_value())
3237             return true;
3238           to = symval.value(this->object_, 0);
3239           if (size == 64)
3240             to += this->object_->ppc64_local_entry_offset(this->r_sym_);
3241         }
3242       if (!(size == 32 && this->r_type_ == elfcpp::R_PPC_PLTREL24))
3243         to += this->addend_;
3244       if (stub_table == NULL)
3245         stub_table = this->object_->stub_table(this->shndx_);
3246       if (size == 64 && target->abiversion() < 2)
3247         {
3248           unsigned int dest_shndx;
3249           if (!target->symval_for_branch(symtab, gsym, this->object_,
3250                                          &to, &dest_shndx))
3251             return true;
3252         }
3253       Address delta = to - from;
3254       if (delta + max_branch_offset >= 2 * max_branch_offset)
3255         {
3256           if (stub_table == NULL)
3257             {
3258               gold_warning(_("%s:%s: branch in non-executable section,"
3259                              " no long branch stub for you"),
3260                            this->object_->name().c_str(),
3261                            this->object_->section_name(this->shndx_).c_str());
3262               return true;
3263             }
3264           bool save_res = (size == 64
3265                            && gsym != NULL
3266                            && gsym->source() == Symbol::IN_OUTPUT_DATA
3267                            && gsym->output_data() == target->savres_section());
3268           ok = stub_table->add_long_branch_entry(this->object_,
3269                                                  this->r_type_,
3270                                                  from, to, save_res);
3271         }
3272     }
3273   if (!ok)
3274     gold_debug(DEBUG_TARGET,
3275                "branch at %s:%s+%#lx\n"
3276                "can't reach stub attached to %s:%s",
3277                this->object_->name().c_str(),
3278                this->object_->section_name(this->shndx_).c_str(),
3279                (unsigned long) this->offset_,
3280                stub_table->relobj()->name().c_str(),
3281                stub_table->relobj()->section_name(stub_table->shndx()).c_str());
3282
3283   return ok;
3284 }
3285
3286 // Relaxation hook.  This is where we do stub generation.
3287
3288 template<int size, bool big_endian>
3289 bool
3290 Target_powerpc<size, big_endian>::do_relax(int pass,
3291                                            const Input_objects*,
3292                                            Symbol_table* symtab,
3293                                            Layout* layout,
3294                                            const Task* task)
3295 {
3296   unsigned int prev_brlt_size = 0;
3297   if (pass == 1)
3298     {
3299       bool thread_safe
3300         = this->abiversion() < 2 && parameters->options().plt_thread_safe();
3301       if (size == 64
3302           && this->abiversion() < 2
3303           && !thread_safe
3304           && !parameters->options().user_set_plt_thread_safe())
3305         {
3306           static const char* const thread_starter[] =
3307             {
3308               "pthread_create",
3309               /* libstdc++ */
3310               "_ZNSt6thread15_M_start_threadESt10shared_ptrINS_10_Impl_baseEE",
3311               /* librt */
3312               "aio_init", "aio_read", "aio_write", "aio_fsync", "lio_listio",
3313               "mq_notify", "create_timer",
3314               /* libanl */
3315               "getaddrinfo_a",
3316               /* libgomp */
3317               "GOMP_parallel",
3318               "GOMP_parallel_start",
3319               "GOMP_parallel_loop_static",
3320               "GOMP_parallel_loop_static_start",
3321               "GOMP_parallel_loop_dynamic",
3322               "GOMP_parallel_loop_dynamic_start",
3323               "GOMP_parallel_loop_guided",
3324               "GOMP_parallel_loop_guided_start",
3325               "GOMP_parallel_loop_runtime",
3326               "GOMP_parallel_loop_runtime_start",
3327               "GOMP_parallel_sections",
3328               "GOMP_parallel_sections_start",
3329               /* libgo */
3330               "__go_go",
3331             };
3332
3333           if (parameters->options().shared())
3334             thread_safe = true;
3335           else
3336             {
3337               for (unsigned int i = 0;
3338                    i < sizeof(thread_starter) / sizeof(thread_starter[0]);
3339                    i++)
3340                 {
3341                   Symbol* sym = symtab->lookup(thread_starter[i], NULL);
3342                   thread_safe = (sym != NULL
3343                                  && sym->in_reg()
3344                                  && sym->in_real_elf());
3345                   if (thread_safe)
3346                     break;
3347                 }
3348             }
3349         }
3350       this->plt_thread_safe_ = thread_safe;
3351     }
3352
3353   if (pass == 1)
3354     {
3355       this->stub_group_size_ = parameters->options().stub_group_size();
3356       bool no_size_errors = true;
3357       if (this->stub_group_size_ == 1)
3358         this->stub_group_size_ = 0x1c00000;
3359       else if (this->stub_group_size_ == -1)
3360         this->stub_group_size_ = -0x1e00000;
3361       else
3362         no_size_errors = false;
3363       this->group_sections(layout, task, no_size_errors);
3364     }
3365   else if (this->relax_failed_ && this->relax_fail_count_ < 3)
3366     {
3367       this->branch_lookup_table_.clear();
3368       for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3369            p != this->stub_tables_.end();
3370            ++p)
3371         {
3372           (*p)->clear_stubs(true);
3373         }
3374       this->stub_tables_.clear();
3375       this->stub_group_size_ = this->stub_group_size_ / 4 * 3;
3376       gold_info(_("%s: stub group size is too large; retrying with %#x"),
3377                 program_name, this->stub_group_size_);
3378       this->group_sections(layout, task, true);
3379     }
3380
3381   // We need address of stub tables valid for make_stub.
3382   for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3383        p != this->stub_tables_.end();
3384        ++p)
3385     {
3386       const Powerpc_relobj<size, big_endian>* object
3387         = static_cast<const Powerpc_relobj<size, big_endian>*>((*p)->relobj());
3388       Address off = object->get_output_section_offset((*p)->shndx());
3389       gold_assert(off != invalid_address);
3390       Output_section* os = (*p)->output_section();
3391       (*p)->set_address_and_size(os, off);
3392     }
3393
3394   if (pass != 1)
3395     {
3396       // Clear plt call stubs, long branch stubs and branch lookup table.
3397       prev_brlt_size = this->branch_lookup_table_.size();
3398       this->branch_lookup_table_.clear();
3399       for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3400            p != this->stub_tables_.end();
3401            ++p)
3402         {
3403           (*p)->clear_stubs(false);
3404         }
3405     }
3406
3407   // Build all the stubs.
3408   this->relax_failed_ = false;
3409   Stub_table<size, big_endian>* ifunc_stub_table
3410     = this->stub_tables_.size() == 0 ? NULL : this->stub_tables_[0];
3411   Stub_table<size, big_endian>* one_stub_table
3412     = this->stub_tables_.size() != 1 ? NULL : ifunc_stub_table;
3413   for (typename Branches::const_iterator b = this->branch_info_.begin();
3414        b != this->branch_info_.end();
3415        b++)
3416     {
3417       if (!b->make_stub(one_stub_table, ifunc_stub_table, symtab)
3418           && !this->relax_failed_)
3419         {
3420           this->relax_failed_ = true;
3421           this->relax_fail_count_++;
3422           if (this->relax_fail_count_ < 3)
3423             return true;
3424         }
3425     }
3426
3427   // Did anything change size?
3428   unsigned int num_huge_branches = this->branch_lookup_table_.size();
3429   bool again = num_huge_branches != prev_brlt_size;
3430   if (size == 64 && num_huge_branches != 0)
3431     this->make_brlt_section(layout);
3432   if (size == 64 && again)
3433     this->brlt_section_->set_current_size(num_huge_branches);
3434
3435   for (typename Stub_tables::reverse_iterator p = this->stub_tables_.rbegin();
3436        p != this->stub_tables_.rend();
3437        ++p)
3438     (*p)->remove_eh_frame(layout);
3439
3440   for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3441        p != this->stub_tables_.end();
3442        ++p)
3443     (*p)->add_eh_frame(layout);
3444
3445   typedef Unordered_set<Output_section*> Output_sections;
3446   Output_sections os_need_update;
3447   for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3448        p != this->stub_tables_.end();
3449        ++p)
3450     {
3451       if ((*p)->size_update())
3452         {
3453           again = true;
3454           os_need_update.insert((*p)->output_section());
3455         }
3456     }
3457
3458   // Set output section offsets for all input sections in an output
3459   // section that just changed size.  Anything past the stubs will
3460   // need updating.
3461   for (typename Output_sections::iterator p = os_need_update.begin();
3462        p != os_need_update.end();
3463        p++)
3464     {
3465       Output_section* os = *p;
3466       Address off = 0;
3467       typedef Output_section::Input_section_list Input_section_list;
3468       for (Input_section_list::const_iterator i = os->input_sections().begin();
3469            i != os->input_sections().end();
3470            ++i)
3471         {
3472           off = align_address(off, i->addralign());
3473           if (i->is_input_section() || i->is_relaxed_input_section())
3474             i->relobj()->set_section_offset(i->shndx(), off);
3475           if (i->is_relaxed_input_section())
3476             {
3477               Stub_table<size, big_endian>* stub_table
3478                 = static_cast<Stub_table<size, big_endian>*>(
3479                     i->relaxed_input_section());
3480               Address stub_table_size = stub_table->set_address_and_size(os, off);
3481               off += stub_table_size;
3482               // After a few iterations, set current stub table size
3483               // as min size threshold, so later stub tables can only
3484               // grow in size.
3485               if (pass >= 4)
3486                 stub_table->set_min_size_threshold(stub_table_size);
3487             }
3488           else
3489             off += i->data_size();
3490         }
3491       // If .branch_lt is part of this output section, then we have
3492       // just done the offset adjustment.
3493       os->clear_section_offsets_need_adjustment();
3494     }
3495
3496   if (size == 64
3497       && !again
3498       && num_huge_branches != 0
3499       && parameters->options().output_is_position_independent())
3500     {
3501       // Fill in the BRLT relocs.
3502       this->brlt_section_->reset_brlt_sizes();
3503       for (typename Branch_lookup_table::const_iterator p
3504              = this->branch_lookup_table_.begin();
3505            p != this->branch_lookup_table_.end();
3506            ++p)
3507         {
3508           this->brlt_section_->add_reloc(p->first, p->second);
3509         }
3510       this->brlt_section_->finalize_brlt_sizes();
3511     }
3512
3513   if (!again
3514       && (parameters->options().user_set_emit_stub_syms()
3515           ? parameters->options().emit_stub_syms()
3516           : (size == 64
3517              || parameters->options().output_is_position_independent()
3518              || parameters->options().emit_relocs())))
3519     {
3520       for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3521            p != this->stub_tables_.end();
3522            ++p)
3523         (*p)->define_stub_syms(symtab);
3524
3525       if (this->glink_ != NULL)
3526         {
3527           int stub_size = this->glink_->pltresolve_size;
3528           Address value = -stub_size;
3529           if (size == 64)
3530             {
3531               value = 8;
3532               stub_size -= 8;
3533             }
3534           this->define_local(symtab, "__glink_PLTresolve",
3535                              this->glink_, value, stub_size);
3536
3537           if (size != 64)
3538             this->define_local(symtab, "__glink", this->glink_, 0, 0);
3539         }
3540     }
3541
3542   return again;
3543 }
3544
3545 template<int size, bool big_endian>
3546 void
3547 Target_powerpc<size, big_endian>::do_plt_fde_location(const Output_data* plt,
3548                                                       unsigned char* oview,
3549                                                       uint64_t* paddress,
3550                                                       off_t* plen) const
3551 {
3552   uint64_t address = plt->address();
3553   off_t len = plt->data_size();
3554
3555   if (plt == this->glink_)
3556     {
3557       // See Output_data_glink::do_write() for glink contents.
3558       if (len == 0)
3559         {
3560           gold_assert(parameters->doing_static_link());
3561           // Static linking may need stubs, to support ifunc and long
3562           // branches.  We need to create an output section for
3563           // .eh_frame early in the link process, to have a place to
3564           // attach stub .eh_frame info.  We also need to have
3565           // registered a CIE that matches the stub CIE.  Both of
3566           // these requirements are satisfied by creating an FDE and
3567           // CIE for .glink, even though static linking will leave
3568           // .glink zero length.
3569           // ??? Hopefully generating an FDE with a zero address range
3570           // won't confuse anything that consumes .eh_frame info.
3571         }
3572       else if (size == 64)
3573         {
3574           // There is one word before __glink_PLTresolve
3575           address += 8;
3576           len -= 8;
3577         }
3578       else if (parameters->options().output_is_position_independent())
3579         {
3580           // There are two FDEs for a position independent glink.
3581           // The first covers the branch table, the second
3582           // __glink_PLTresolve at the end of glink.
3583           off_t resolve_size = this->glink_->pltresolve_size;
3584           if (oview[9] == elfcpp::DW_CFA_nop)
3585             len -= resolve_size;
3586           else
3587             {
3588               address += len - resolve_size;
3589               len = resolve_size;
3590             }
3591         }
3592     }
3593   else
3594     {
3595       // Must be a stub table.
3596       const Stub_table<size, big_endian>* stub_table
3597         = static_cast<const Stub_table<size, big_endian>*>(plt);
3598       uint64_t stub_address = stub_table->stub_address();
3599       len -= stub_address - address;
3600       address = stub_address;
3601     }
3602
3603   *paddress = address;
3604   *plen = len;
3605 }
3606
3607 // A class to handle the PLT data.
3608
3609 template<int size, bool big_endian>
3610 class Output_data_plt_powerpc : public Output_section_data_build
3611 {
3612  public:
3613   typedef Output_data_reloc<elfcpp::SHT_RELA, true,
3614                             size, big_endian> Reloc_section;
3615
3616   Output_data_plt_powerpc(Target_powerpc<size, big_endian>* targ,
3617                           Reloc_section* plt_rel,
3618                           const char* name)
3619     : Output_section_data_build(size == 32 ? 4 : 8),
3620       rel_(plt_rel),
3621       targ_(targ),
3622       name_(name)
3623   { }
3624
3625   // Add an entry to the PLT.
3626   void
3627   add_entry(Symbol*);
3628
3629   void
3630   add_ifunc_entry(Symbol*);
3631
3632   void
3633   add_local_ifunc_entry(Sized_relobj_file<size, big_endian>*, unsigned int);
3634
3635   // Return the .rela.plt section data.
3636   Reloc_section*
3637   rel_plt() const
3638   {
3639     return this->rel_;
3640   }
3641
3642   // Return the number of PLT entries.
3643   unsigned int
3644   entry_count() const
3645   {
3646     if (this->current_data_size() == 0)
3647       return 0;
3648     return ((this->current_data_size() - this->first_plt_entry_offset())
3649             / this->plt_entry_size());
3650   }
3651
3652  protected:
3653   void
3654   do_adjust_output_section(Output_section* os)
3655   {
3656     os->set_entsize(0);
3657   }
3658
3659   // Write to a map file.
3660   void
3661   do_print_to_mapfile(Mapfile* mapfile) const
3662   { mapfile->print_output_data(this, this->name_); }
3663
3664  private:
3665   // Return the offset of the first non-reserved PLT entry.
3666   unsigned int
3667   first_plt_entry_offset() const
3668   {
3669     // IPLT has no reserved entry.
3670     if (this->name_[3] == 'I')
3671       return 0;
3672     return this->targ_->first_plt_entry_offset();
3673   }
3674
3675   // Return the size of each PLT entry.
3676   unsigned int
3677   plt_entry_size() const
3678   {
3679     return this->targ_->plt_entry_size();
3680   }
3681
3682   // Write out the PLT data.
3683   void
3684   do_write(Output_file*);
3685
3686   // The reloc section.
3687   Reloc_section* rel_;
3688   // Allows access to .glink for do_write.
3689   Target_powerpc<size, big_endian>* targ_;
3690   // What to report in map file.
3691   const char *name_;
3692 };
3693
3694 // Add an entry to the PLT.
3695
3696 template<int size, bool big_endian>
3697 void
3698 Output_data_plt_powerpc<size, big_endian>::add_entry(Symbol* gsym)
3699 {
3700   if (!gsym->has_plt_offset())
3701     {
3702       section_size_type off = this->current_data_size();
3703       if (off == 0)
3704         off += this->first_plt_entry_offset();
3705       gsym->set_plt_offset(off);
3706       gsym->set_needs_dynsym_entry();
3707       unsigned int dynrel = elfcpp::R_POWERPC_JMP_SLOT;
3708       this->rel_->add_global(gsym, dynrel, this, off, 0);
3709       off += this->plt_entry_size();
3710       this->set_current_data_size(off);
3711     }
3712 }
3713
3714 // Add an entry for a global ifunc symbol that resolves locally, to the IPLT.
3715
3716 template<int size, bool big_endian>
3717 void
3718 Output_data_plt_powerpc<size, big_endian>::add_ifunc_entry(Symbol* gsym)
3719 {
3720   if (!gsym->has_plt_offset())
3721     {
3722       section_size_type off = this->current_data_size();
3723       gsym->set_plt_offset(off);
3724       unsigned int dynrel = elfcpp::R_POWERPC_IRELATIVE;
3725       if (size == 64 && this->targ_->abiversion() < 2)
3726         dynrel = elfcpp::R_PPC64_JMP_IREL;
3727       this->rel_->add_symbolless_global_addend(gsym, dynrel, this, off, 0);
3728       off += this->plt_entry_size();
3729       this->set_current_data_size(off);
3730     }
3731 }
3732
3733 // Add an entry for a local ifunc symbol to the IPLT.
3734
3735 template<int size, bool big_endian>
3736 void
3737 Output_data_plt_powerpc<size, big_endian>::add_local_ifunc_entry(
3738     Sized_relobj_file<size, big_endian>* relobj,
3739     unsigned int local_sym_index)
3740 {
3741   if (!relobj->local_has_plt_offset(local_sym_index))
3742     {
3743       section_size_type off = this->current_data_size();
3744       relobj->set_local_plt_offset(local_sym_index, off);
3745       unsigned int dynrel = elfcpp::R_POWERPC_IRELATIVE;
3746       if (size == 64 && this->targ_->abiversion() < 2)
3747         dynrel = elfcpp::R_PPC64_JMP_IREL;
3748       this->rel_->add_symbolless_local_addend(relobj, local_sym_index, dynrel,
3749                                               this, off, 0);
3750       off += this->plt_entry_size();
3751       this->set_current_data_size(off);
3752     }
3753 }
3754
3755 static const uint32_t add_0_11_11       = 0x7c0b5a14;
3756 static const uint32_t add_2_2_11        = 0x7c425a14;
3757 static const uint32_t add_2_2_12        = 0x7c426214;
3758 static const uint32_t add_3_3_2         = 0x7c631214;
3759 static const uint32_t add_3_3_13        = 0x7c636a14;
3760 static const uint32_t add_3_12_2        = 0x7c6c1214;
3761 static const uint32_t add_3_12_13       = 0x7c6c6a14;
3762 static const uint32_t add_11_0_11       = 0x7d605a14;
3763 static const uint32_t add_11_2_11       = 0x7d625a14;
3764 static const uint32_t add_11_11_2       = 0x7d6b1214;
3765 static const uint32_t addi_0_12         = 0x380c0000;
3766 static const uint32_t addi_2_2          = 0x38420000;
3767 static const uint32_t addi_3_3          = 0x38630000;
3768 static const uint32_t addi_11_11        = 0x396b0000;
3769 static const uint32_t addi_12_1         = 0x39810000;
3770 static const uint32_t addi_12_12        = 0x398c0000;
3771 static const uint32_t addis_0_2         = 0x3c020000;
3772 static const uint32_t addis_0_13        = 0x3c0d0000;
3773 static const uint32_t addis_2_12        = 0x3c4c0000;
3774 static const uint32_t addis_11_2        = 0x3d620000;
3775 static const uint32_t addis_11_11       = 0x3d6b0000;
3776 static const uint32_t addis_11_30       = 0x3d7e0000;
3777 static const uint32_t addis_12_1        = 0x3d810000;
3778 static const uint32_t addis_12_2        = 0x3d820000;
3779 static const uint32_t addis_12_12       = 0x3d8c0000;
3780 static const uint32_t b                 = 0x48000000;
3781 static const uint32_t bcl_20_31         = 0x429f0005;
3782 static const uint32_t bctr              = 0x4e800420;
3783 static const uint32_t bctrl             = 0x4e800421;
3784 static const uint32_t beqlr             = 0x4d820020;
3785 static const uint32_t blr               = 0x4e800020;
3786 static const uint32_t bnectr_p4         = 0x4ce20420;
3787 static const uint32_t cmpld_7_12_0      = 0x7fac0040;
3788 static const uint32_t cmpldi_2_0        = 0x28220000;
3789 static const uint32_t cmpdi_11_0        = 0x2c2b0000;
3790 static const uint32_t cmpwi_11_0        = 0x2c0b0000;
3791 static const uint32_t cror_15_15_15     = 0x4def7b82;
3792 static const uint32_t cror_31_31_31     = 0x4ffffb82;
3793 static const uint32_t ld_0_1            = 0xe8010000;
3794 static const uint32_t ld_0_12           = 0xe80c0000;
3795 static const uint32_t ld_2_1            = 0xe8410000;
3796 static const uint32_t ld_2_2            = 0xe8420000;
3797 static const uint32_t ld_2_11           = 0xe84b0000;
3798 static const uint32_t ld_2_12           = 0xe84c0000;
3799 static const uint32_t ld_11_1           = 0xe9610000;
3800 static const uint32_t ld_11_2           = 0xe9620000;
3801 static const uint32_t ld_11_3           = 0xe9630000;
3802 static const uint32_t ld_11_11          = 0xe96b0000;
3803 static const uint32_t ld_12_2           = 0xe9820000;
3804 static const uint32_t ld_12_3           = 0xe9830000;
3805 static const uint32_t ld_12_11          = 0xe98b0000;
3806 static const uint32_t ld_12_12          = 0xe98c0000;
3807 static const uint32_t lfd_0_1           = 0xc8010000;
3808 static const uint32_t li_0_0            = 0x38000000;
3809 static const uint32_t li_12_0           = 0x39800000;
3810 static const uint32_t lis_0             = 0x3c000000;
3811 static const uint32_t lis_2             = 0x3c400000;
3812 static const uint32_t lis_11            = 0x3d600000;
3813 static const uint32_t lis_12            = 0x3d800000;
3814 static const uint32_t lvx_0_12_0        = 0x7c0c00ce;
3815 static const uint32_t lwz_0_12          = 0x800c0000;
3816 static const uint32_t lwz_11_3          = 0x81630000;
3817 static const uint32_t lwz_11_11         = 0x816b0000;
3818 static const uint32_t lwz_11_30         = 0x817e0000;
3819 static const uint32_t lwz_12_3          = 0x81830000;
3820 static const uint32_t lwz_12_12         = 0x818c0000;
3821 static const uint32_t lwzu_0_12         = 0x840c0000;
3822 static const uint32_t mflr_0            = 0x7c0802a6;
3823 static const uint32_t mflr_11           = 0x7d6802a6;
3824 static const uint32_t mflr_12           = 0x7d8802a6;
3825 static const uint32_t mr_0_3            = 0x7c601b78;
3826 static const uint32_t mr_3_0            = 0x7c030378;
3827 static const uint32_t mtctr_0           = 0x7c0903a6;
3828 static const uint32_t mtctr_11          = 0x7d6903a6;
3829 static const uint32_t mtctr_12          = 0x7d8903a6;
3830 static const uint32_t mtlr_0            = 0x7c0803a6;
3831 static const uint32_t mtlr_11           = 0x7d6803a6;
3832 static const uint32_t mtlr_12           = 0x7d8803a6;
3833 static const uint32_t nop               = 0x60000000;
3834 static const uint32_t ori_0_0_0         = 0x60000000;
3835 static const uint32_t srdi_0_0_2        = 0x7800f082;
3836 static const uint32_t std_0_1           = 0xf8010000;
3837 static const uint32_t std_0_12          = 0xf80c0000;
3838 static const uint32_t std_2_1           = 0xf8410000;
3839 static const uint32_t std_11_1          = 0xf9610000;
3840 static const uint32_t stfd_0_1          = 0xd8010000;
3841 static const uint32_t stvx_0_12_0       = 0x7c0c01ce;
3842 static const uint32_t sub_11_11_12      = 0x7d6c5850;
3843 static const uint32_t sub_12_12_11      = 0x7d8b6050;
3844 static const uint32_t xor_2_12_12       = 0x7d826278;
3845 static const uint32_t xor_11_12_12      = 0x7d8b6278;
3846
3847 // Write out the PLT.
3848
3849 template<int size, bool big_endian>
3850 void
3851 Output_data_plt_powerpc<size, big_endian>::do_write(Output_file* of)
3852 {
3853   if (size == 32 && this->name_[3] != 'I')
3854     {
3855       const section_size_type offset = this->offset();
3856       const section_size_type oview_size
3857         = convert_to_section_size_type(this->data_size());
3858       unsigned char* const oview = of->get_output_view(offset, oview_size);
3859       unsigned char* pov = oview;
3860       unsigned char* endpov = oview + oview_size;
3861
3862       // The address of the .glink branch table
3863       const Output_data_glink<size, big_endian>* glink
3864         = this->targ_->glink_section();
3865       elfcpp::Elf_types<32>::Elf_Addr branch_tab = glink->address();
3866
3867       while (pov < endpov)
3868         {
3869           elfcpp::Swap<32, big_endian>::writeval(pov, branch_tab);
3870           pov += 4;
3871           branch_tab += 4;
3872         }
3873
3874       of->write_output_view(offset, oview_size, oview);
3875     }
3876 }
3877
3878 // Create the PLT section.
3879
3880 template<int size, bool big_endian>
3881 void
3882 Target_powerpc<size, big_endian>::make_plt_section(Symbol_table* symtab,
3883                                                    Layout* layout)
3884 {
3885   if (this->plt_ == NULL)
3886     {
3887       if (this->got_ == NULL)
3888         this->got_section(symtab, layout);
3889
3890       if (this->glink_ == NULL)
3891         make_glink_section(layout);
3892
3893       // Ensure that .rela.dyn always appears before .rela.plt  This is
3894       // necessary due to how, on PowerPC and some other targets, .rela.dyn
3895       // needs to include .rela.plt in its range.
3896       this->rela_dyn_section(layout);
3897
3898       Reloc_section* plt_rel = new Reloc_section(false);
3899       layout->add_output_section_data(".rela.plt", elfcpp::SHT_RELA,
3900                                       elfcpp::SHF_ALLOC, plt_rel,
3901                                       ORDER_DYNAMIC_PLT_RELOCS, false);
3902       this->plt_
3903         = new Output_data_plt_powerpc<size, big_endian>(this, plt_rel,
3904                                                         "** PLT");
3905       layout->add_output_section_data(".plt",
3906                                       (size == 32
3907                                        ? elfcpp::SHT_PROGBITS
3908                                        : elfcpp::SHT_NOBITS),
3909                                       elfcpp::SHF_ALLOC | elfcpp::SHF_WRITE,
3910                                       this->plt_,
3911                                       (size == 32
3912                                        ? ORDER_SMALL_DATA
3913                                        : ORDER_SMALL_BSS),
3914                                       false);
3915
3916       Output_section* rela_plt_os = plt_rel->output_section();
3917       rela_plt_os->set_info_section(this->plt_->output_section());
3918     }
3919 }
3920
3921 // Create the IPLT section.
3922
3923 template<int size, bool big_endian>
3924 void
3925 Target_powerpc<size, big_endian>::make_iplt_section(Symbol_table* symtab,
3926                                                     Layout* layout)
3927 {
3928   if (this->iplt_ == NULL)
3929     {
3930       this->make_plt_section(symtab, layout);
3931
3932       Reloc_section* iplt_rel = new Reloc_section(false);
3933       if (this->rela_dyn_->output_section())
3934         this->rela_dyn_->output_section()->add_output_section_data(iplt_rel);
3935       this->iplt_
3936         = new Output_data_plt_powerpc<size, big_endian>(this, iplt_rel,
3937                                                         "** IPLT");
3938       if (this->plt_->output_section())
3939         this->plt_->output_section()->add_output_section_data(this->iplt_);
3940     }
3941 }
3942
3943 // A section for huge long branch addresses, similar to plt section.
3944
3945 template<int size, bool big_endian>
3946 class Output_data_brlt_powerpc : public Output_section_data_build
3947 {
3948  public:
3949   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
3950   typedef Output_data_reloc<elfcpp::SHT_RELA, true,
3951                             size, big_endian> Reloc_section;
3952
3953   Output_data_brlt_powerpc(Target_powerpc<size, big_endian>* targ,
3954                            Reloc_section* brlt_rel)
3955     : Output_section_data_build(size == 32 ? 4 : 8),
3956       rel_(brlt_rel),
3957       targ_(targ)
3958   { }
3959
3960   void
3961   reset_brlt_sizes()
3962   {
3963     this->reset_data_size();
3964     this->rel_->reset_data_size();
3965   }
3966
3967   void
3968   finalize_brlt_sizes()
3969   {
3970     this->finalize_data_size();
3971     this->rel_->finalize_data_size();
3972   }
3973
3974   // Add a reloc for an entry in the BRLT.
3975   void
3976   add_reloc(Address to, unsigned int off)
3977   { this->rel_->add_relative(elfcpp::R_POWERPC_RELATIVE, this, off, to); }
3978
3979   // Update section and reloc section size.
3980   void
3981   set_current_size(unsigned int num_branches)
3982   {
3983     this->reset_address_and_file_offset();
3984     this->set_current_data_size(num_branches * 16);
3985     this->finalize_data_size();
3986     Output_section* os = this->output_section();
3987     os->set_section_offsets_need_adjustment();
3988     if (this->rel_ != NULL)
3989       {
3990         const unsigned int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
3991         this->rel_->reset_address_and_file_offset();
3992         this->rel_->set_current_data_size(num_branches * reloc_size);
3993         this->rel_->finalize_data_size();
3994         Output_section* os = this->rel_->output_section();
3995         os->set_section_offsets_need_adjustment();
3996       }
3997   }
3998
3999  protected:
4000   void
4001   do_adjust_output_section(Output_section* os)
4002   {
4003     os->set_entsize(0);
4004   }
4005
4006   // Write to a map file.
4007   void
4008   do_print_to_mapfile(Mapfile* mapfile) const
4009   { mapfile->print_output_data(this, "** BRLT"); }
4010
4011  private:
4012   // Write out the BRLT data.
4013   void
4014   do_write(Output_file*);
4015
4016   // The reloc section.
4017   Reloc_section* rel_;
4018   Target_powerpc<size, big_endian>* targ_;
4019 };
4020
4021 // Make the branch lookup table section.
4022
4023 template<int size, bool big_endian>
4024 void
4025 Target_powerpc<size, big_endian>::make_brlt_section(Layout* layout)
4026 {
4027   if (size == 64 && this->brlt_section_ == NULL)
4028     {
4029       Reloc_section* brlt_rel = NULL;
4030       bool is_pic = parameters->options().output_is_position_independent();
4031       if (is_pic)
4032         {
4033           // When PIC we can't fill in .branch_lt (like .plt it can be
4034           // a bss style section) but must initialise at runtime via
4035           // dynamic relocations.
4036           this->rela_dyn_section(layout);
4037           brlt_rel = new Reloc_section(false);
4038           if (this->rela_dyn_->output_section())
4039             this->rela_dyn_->output_section()
4040               ->add_output_section_data(brlt_rel);
4041         }
4042       this->brlt_section_
4043         = new Output_data_brlt_powerpc<size, big_endian>(this, brlt_rel);
4044       if (this->plt_ && is_pic && this->plt_->output_section())
4045         this->plt_->output_section()
4046           ->add_output_section_data(this->brlt_section_);
4047       else
4048         layout->add_output_section_data(".branch_lt",
4049                                         (is_pic ? elfcpp::SHT_NOBITS
4050                                          : elfcpp::SHT_PROGBITS),
4051                                         elfcpp::SHF_ALLOC | elfcpp::SHF_WRITE,
4052                                         this->brlt_section_,
4053                                         (is_pic ? ORDER_SMALL_BSS
4054                                          : ORDER_SMALL_DATA),
4055                                         false);
4056     }
4057 }
4058
4059 // Write out .branch_lt when non-PIC.
4060
4061 template<int size, bool big_endian>
4062 void
4063 Output_data_brlt_powerpc<size, big_endian>::do_write(Output_file* of)
4064 {
4065   if (size == 64 && !parameters->options().output_is_position_independent())
4066     {
4067       const section_size_type offset = this->offset();
4068       const section_size_type oview_size
4069         = convert_to_section_size_type(this->data_size());
4070       unsigned char* const oview = of->get_output_view(offset, oview_size);
4071
4072       this->targ_->write_branch_lookup_table(oview);
4073       of->write_output_view(offset, oview_size, oview);
4074     }
4075 }
4076
4077 static inline uint32_t
4078 l(uint32_t a)
4079 {
4080   return a & 0xffff;
4081 }
4082
4083 static inline uint32_t
4084 hi(uint32_t a)
4085 {
4086   return l(a >> 16);
4087 }
4088
4089 static inline uint32_t
4090 ha(uint32_t a)
4091 {
4092   return hi(a + 0x8000);
4093 }
4094
4095 template<int size>
4096 struct Eh_cie
4097 {
4098   static const unsigned char eh_frame_cie[12];
4099 };
4100
4101 template<int size>
4102 const unsigned char Eh_cie<size>::eh_frame_cie[] =
4103 {
4104   1,                                    // CIE version.
4105   'z', 'R', 0,                          // Augmentation string.
4106   4,                                    // Code alignment.
4107   0x80 - size / 8 ,                     // Data alignment.
4108   65,                                   // RA reg.
4109   1,                                    // Augmentation size.
4110   (elfcpp::DW_EH_PE_pcrel
4111    | elfcpp::DW_EH_PE_sdata4),          // FDE encoding.
4112   elfcpp::DW_CFA_def_cfa, 1, 0          // def_cfa: r1 offset 0.
4113 };
4114
4115 // Describe __glink_PLTresolve use of LR, 64-bit version ABIv1.
4116 static const unsigned char glink_eh_frame_fde_64v1[] =
4117 {
4118   0, 0, 0, 0,                           // Replaced with offset to .glink.
4119   0, 0, 0, 0,                           // Replaced with size of .glink.
4120   0,                                    // Augmentation size.
4121   elfcpp::DW_CFA_advance_loc + 1,
4122   elfcpp::DW_CFA_register, 65, 12,
4123   elfcpp::DW_CFA_advance_loc + 5,
4124   elfcpp::DW_CFA_restore_extended, 65
4125 };
4126
4127 // Describe __glink_PLTresolve use of LR, 64-bit version ABIv2.
4128 static const unsigned char glink_eh_frame_fde_64v2[] =
4129 {
4130   0, 0, 0, 0,                           // Replaced with offset to .glink.
4131   0, 0, 0, 0,                           // Replaced with size of .glink.
4132   0,                                    // Augmentation size.
4133   elfcpp::DW_CFA_advance_loc + 1,
4134   elfcpp::DW_CFA_register, 65, 0,
4135   elfcpp::DW_CFA_advance_loc + 7,
4136   elfcpp::DW_CFA_restore_extended, 65
4137 };
4138
4139 // Describe __glink_PLTresolve use of LR, 32-bit version.
4140 static const unsigned char glink_eh_frame_fde_32[] =
4141 {
4142   0, 0, 0, 0,                           // Replaced with offset to .glink.
4143   0, 0, 0, 0,                           // Replaced with size of .glink.
4144   0,                                    // Augmentation size.
4145   elfcpp::DW_CFA_advance_loc + 2,
4146   elfcpp::DW_CFA_register, 65, 0,
4147   elfcpp::DW_CFA_advance_loc + 4,
4148   elfcpp::DW_CFA_restore_extended, 65
4149 };
4150
4151 static const unsigned char default_fde[] =
4152 {
4153   0, 0, 0, 0,                           // Replaced with offset to stubs.
4154   0, 0, 0, 0,                           // Replaced with size of stubs.
4155   0,                                    // Augmentation size.
4156   elfcpp::DW_CFA_nop,                   // Pad.
4157   elfcpp::DW_CFA_nop,
4158   elfcpp::DW_CFA_nop
4159 };
4160
4161 template<bool big_endian>
4162 static inline void
4163 write_insn(unsigned char* p, uint32_t v)
4164 {
4165   elfcpp::Swap<32, big_endian>::writeval(p, v);
4166 }
4167
4168 // Stub_table holds information about plt and long branch stubs.
4169 // Stubs are built in an area following some input section determined
4170 // by group_sections().  This input section is converted to a relaxed
4171 // input section allowing it to be resized to accommodate the stubs
4172
4173 template<int size, bool big_endian>
4174 class Stub_table : public Output_relaxed_input_section
4175 {
4176  public:
4177   struct Plt_stub_ent
4178   {
4179     Plt_stub_ent(unsigned int off, unsigned int indx)
4180       : off_(off), indx_(indx), r2save_(0), localentry0_(0)
4181     { }
4182
4183     unsigned int off_;
4184     unsigned int indx_ : 30;
4185     unsigned int r2save_ : 1;
4186     unsigned int localentry0_ : 1;
4187   };
4188   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
4189   static const Address invalid_address = static_cast<Address>(0) - 1;
4190
4191   Stub_table(Target_powerpc<size, big_endian>* targ,
4192              Output_section* output_section,
4193              const Output_section::Input_section* owner,
4194              uint32_t id)
4195     : Output_relaxed_input_section(owner->relobj(), owner->shndx(),
4196                                    owner->relobj()
4197                                    ->section_addralign(owner->shndx())),
4198       targ_(targ), plt_call_stubs_(), long_branch_stubs_(),
4199       orig_data_size_(owner->current_data_size()),
4200       plt_size_(0), last_plt_size_(0),
4201       branch_size_(0), last_branch_size_(0), min_size_threshold_(0),
4202       need_save_res_(false), uniq_(id), tls_get_addr_opt_bctrl_(-1u),
4203       plt_fde_len_(0)
4204   {
4205     this->set_output_section(output_section);
4206
4207     std::vector<Output_relaxed_input_section*> new_relaxed;
4208     new_relaxed.push_back(this);
4209     output_section->convert_input_sections_to_relaxed_sections(new_relaxed);
4210   }
4211
4212   // Add a plt call stub.
4213   bool
4214   add_plt_call_entry(Address,
4215                      const Sized_relobj_file<size, big_endian>*,
4216                      const Symbol*,
4217                      unsigned int,
4218                      Address,
4219                      bool);
4220
4221   bool
4222   add_plt_call_entry(Address,
4223                      const Sized_relobj_file<size, big_endian>*,
4224                      unsigned int,
4225                      unsigned int,
4226                      Address,
4227                      bool);
4228
4229   // Find a given plt call stub.
4230   const Plt_stub_ent*
4231   find_plt_call_entry(const Symbol*) const;
4232
4233   const Plt_stub_ent*
4234   find_plt_call_entry(const Sized_relobj_file<size, big_endian>*,
4235                       unsigned int) const;
4236
4237   const Plt_stub_ent*
4238   find_plt_call_entry(const Sized_relobj_file<size, big_endian>*,
4239                       const Symbol*,
4240                       unsigned int,
4241                       Address) const;
4242
4243   const Plt_stub_ent*
4244   find_plt_call_entry(const Sized_relobj_file<size, big_endian>*,
4245                       unsigned int,
4246                       unsigned int,
4247                       Address) const;
4248
4249   // Add a long branch stub.
4250   bool
4251   add_long_branch_entry(const Powerpc_relobj<size, big_endian>*,
4252                         unsigned int, Address, Address, bool);
4253
4254   Address
4255   find_long_branch_entry(const Powerpc_relobj<size, big_endian>*,
4256                          Address) const;
4257
4258   bool
4259   can_reach_stub(Address from, unsigned int off, unsigned int r_type)
4260   {
4261     Address max_branch_offset = max_branch_delta(r_type);
4262     if (max_branch_offset == 0)
4263       return true;
4264     gold_assert(from != invalid_address);
4265     Address loc = off + this->stub_address();
4266     return loc - from + max_branch_offset < 2 * max_branch_offset;
4267   }
4268
4269   void
4270   clear_stubs(bool all)
4271   {
4272     this->plt_call_stubs_.clear();
4273     this->plt_size_ = 0;
4274     this->long_branch_stubs_.clear();
4275     this->branch_size_ = 0;
4276     this->need_save_res_ = false;
4277     if (all)
4278       {
4279         this->last_plt_size_ = 0;
4280         this->last_branch_size_ = 0;
4281       }
4282   }
4283
4284   Address
4285   set_address_and_size(const Output_section* os, Address off)
4286   {
4287     Address start_off = off;
4288     off += this->orig_data_size_;
4289     Address my_size = this->plt_size_ + this->branch_size_;
4290     if (this->need_save_res_)
4291       my_size += this->targ_->savres_section()->data_size();
4292     if (my_size != 0)
4293       off = align_address(off, this->stub_align());
4294     // Include original section size and alignment padding in size
4295     my_size += off - start_off;
4296     // Ensure new size is always larger than min size
4297     // threshold. Alignment requirement is included in "my_size", so
4298     // increase "my_size" does not invalidate alignment.
4299     if (my_size < this->min_size_threshold_)
4300       my_size = this->min_size_threshold_;
4301     this->reset_address_and_file_offset();
4302     this->set_current_data_size(my_size);
4303     this->set_address_and_file_offset(os->address() + start_off,
4304                                       os->offset() + start_off);
4305     return my_size;
4306   }
4307
4308   Address
4309   stub_address() const
4310   {
4311     return align_address(this->address() + this->orig_data_size_,
4312                          this->stub_align());
4313   }
4314
4315   Address
4316   stub_offset() const
4317   {
4318     return align_address(this->offset() + this->orig_data_size_,
4319                          this->stub_align());
4320   }
4321
4322   section_size_type
4323   plt_size() const
4324   { return this->plt_size_; }
4325
4326   void
4327   set_min_size_threshold(Address min_size)
4328   { this->min_size_threshold_ = min_size; }
4329
4330   void
4331   define_stub_syms(Symbol_table*);
4332
4333   bool
4334   size_update()
4335   {
4336     Output_section* os = this->output_section();
4337     if (os->addralign() < this->stub_align())
4338       {
4339         os->set_addralign(this->stub_align());
4340         // FIXME: get rid of the insane checkpointing.
4341         // We can't increase alignment of the input section to which
4342         // stubs are attached;  The input section may be .init which
4343         // is pasted together with other .init sections to form a
4344         // function.  Aligning might insert zero padding resulting in
4345         // sigill.  However we do need to increase alignment of the
4346         // output section so that the align_address() on offset in
4347         // set_address_and_size() adds the same padding as the
4348         // align_address() on address in stub_address().
4349         // What's more, we need this alignment for the layout done in
4350         // relaxation_loop_body() so that the output section starts at
4351         // a suitably aligned address.
4352         os->checkpoint_set_addralign(this->stub_align());
4353       }
4354     if (this->last_plt_size_ != this->plt_size_
4355         || this->last_branch_size_ != this->branch_size_)
4356       {
4357         this->last_plt_size_ = this->plt_size_;
4358         this->last_branch_size_ = this->branch_size_;
4359         return true;
4360       }
4361     return false;
4362   }
4363
4364   // Generate a suitable FDE to describe code in this stub group.
4365   void
4366   init_plt_fde();
4367
4368   // Add .eh_frame info for this stub section.
4369   void
4370   add_eh_frame(Layout* layout);
4371
4372   // Remove .eh_frame info for this stub section.
4373   void
4374   remove_eh_frame(Layout* layout);
4375
4376   Target_powerpc<size, big_endian>*
4377   targ() const
4378   { return targ_; }
4379
4380  private:
4381   class Plt_stub_key;
4382   class Plt_stub_key_hash;
4383   typedef Unordered_map<Plt_stub_key, Plt_stub_ent,
4384                         Plt_stub_key_hash> Plt_stub_entries;
4385   class Branch_stub_ent;
4386   class Branch_stub_ent_hash;
4387   typedef Unordered_map<Branch_stub_ent, unsigned int,
4388                         Branch_stub_ent_hash> Branch_stub_entries;
4389
4390   // Alignment of stub section.
4391   unsigned int
4392   stub_align() const
4393   {
4394     if (size == 32)
4395       return 16;
4396     unsigned int min_align = 32;
4397     unsigned int user_align = 1 << parameters->options().plt_align();
4398     return std::max(user_align, min_align);
4399   }
4400
4401   // Return the plt offset for the given call stub.
4402   Address
4403   plt_off(typename Plt_stub_entries::const_iterator p, bool* is_iplt) const
4404   {
4405     const Symbol* gsym = p->first.sym_;
4406     if (gsym != NULL)
4407       {
4408         *is_iplt = (gsym->type() == elfcpp::STT_GNU_IFUNC
4409                     && gsym->can_use_relative_reloc(false));
4410         return gsym->plt_offset();
4411       }
4412     else
4413       {
4414         *is_iplt = true;
4415         const Sized_relobj_file<size, big_endian>* relobj = p->first.object_;
4416         unsigned int local_sym_index = p->first.locsym_;
4417         return relobj->local_plt_offset(local_sym_index);
4418       }
4419   }
4420
4421   // Size of a given plt call stub.
4422   unsigned int
4423   plt_call_size(typename Plt_stub_entries::const_iterator p) const
4424   {
4425     if (size == 32)
4426       {
4427         const Symbol* gsym = p->first.sym_;
4428         if (this->targ_->is_tls_get_addr_opt(gsym))
4429           return 12 * 4;
4430         return 4 * 4;
4431       }
4432
4433     bool is_iplt;
4434     Address plt_addr = this->plt_off(p, &is_iplt);
4435     if (is_iplt)
4436       plt_addr += this->targ_->iplt_section()->address();
4437     else
4438       plt_addr += this->targ_->plt_section()->address();
4439     Address got_addr = this->targ_->got_section()->output_section()->address();
4440     const Powerpc_relobj<size, big_endian>* ppcobj = static_cast
4441       <const Powerpc_relobj<size, big_endian>*>(p->first.object_);
4442     got_addr += ppcobj->toc_base_offset();
4443     Address off = plt_addr - got_addr;
4444     unsigned int bytes = 4 * 4 + 4 * (ha(off) != 0);
4445     const Symbol* gsym = p->first.sym_;
4446     if (this->targ_->is_tls_get_addr_opt(gsym))
4447       bytes += 13 * 4;
4448     if (this->targ_->abiversion() < 2)
4449       {
4450         bool static_chain = parameters->options().plt_static_chain();
4451         bool thread_safe = this->targ_->plt_thread_safe();
4452         bytes += (4
4453                   + 4 * static_chain
4454                   + 8 * thread_safe
4455                   + 4 * (ha(off + 8 + 8 * static_chain) != ha(off)));
4456       }
4457     return bytes;
4458   }
4459
4460   unsigned int
4461   plt_call_align(unsigned int bytes) const
4462   {
4463     unsigned int align = 1 << parameters->options().plt_align();
4464     if (align > 1)
4465       bytes = (bytes + align - 1) & -align;
4466     return bytes;
4467   }
4468
4469   // Return long branch stub size.
4470   unsigned int
4471   branch_stub_size(typename Branch_stub_entries::const_iterator p)
4472   {
4473     Address loc = this->stub_address() + this->last_plt_size_ + p->second;
4474     if (p->first.dest_ - loc + (1 << 25) < 2 << 25)
4475       return 4;
4476     if (size == 64 || !parameters->options().output_is_position_independent())
4477       return 16;
4478     return 32;
4479   }
4480
4481   // Write out stubs.
4482   void
4483   do_write(Output_file*);
4484
4485   // Plt call stub keys.
4486   class Plt_stub_key
4487   {
4488   public:
4489     Plt_stub_key(const Symbol* sym)
4490       : sym_(sym), object_(0), addend_(0), locsym_(0)
4491     { }
4492
4493     Plt_stub_key(const Sized_relobj_file<size, big_endian>* object,
4494                  unsigned int locsym_index)
4495       : sym_(NULL), object_(object), addend_(0), locsym_(locsym_index)
4496     { }
4497
4498     Plt_stub_key(const Sized_relobj_file<size, big_endian>* object,
4499                  const Symbol* sym,
4500                  unsigned int r_type,
4501                  Address addend)
4502       : sym_(sym), object_(0), addend_(0), locsym_(0)
4503     {
4504       if (size != 32)
4505         this->addend_ = addend;
4506       else if (parameters->options().output_is_position_independent()
4507                && r_type == elfcpp::R_PPC_PLTREL24)
4508         {
4509           this->addend_ = addend;
4510           if (this->addend_ >= 32768)
4511             this->object_ = object;
4512         }
4513     }
4514
4515     Plt_stub_key(const Sized_relobj_file<size, big_endian>* object,
4516                  unsigned int locsym_index,
4517                  unsigned int r_type,
4518                  Address addend)
4519       : sym_(NULL), object_(object), addend_(0), locsym_(locsym_index)
4520     {
4521       if (size != 32)
4522         this->addend_ = addend;
4523       else if (parameters->options().output_is_position_independent()
4524                && r_type == elfcpp::R_PPC_PLTREL24)
4525         this->addend_ = addend;
4526     }
4527
4528     bool operator==(const Plt_stub_key& that) const
4529     {
4530       return (this->sym_ == that.sym_
4531               && this->object_ == that.object_
4532               && this->addend_ == that.addend_
4533               && this->locsym_ == that.locsym_);
4534     }
4535
4536     const Symbol* sym_;
4537     const Sized_relobj_file<size, big_endian>* object_;
4538     typename elfcpp::Elf_types<size>::Elf_Addr addend_;
4539     unsigned int locsym_;
4540   };
4541
4542   class Plt_stub_key_hash
4543   {
4544   public:
4545     size_t operator()(const Plt_stub_key& ent) const
4546     {
4547       return (reinterpret_cast<uintptr_t>(ent.sym_)
4548               ^ reinterpret_cast<uintptr_t>(ent.object_)
4549               ^ ent.addend_
4550               ^ ent.locsym_);
4551     }
4552   };
4553
4554   // Long branch stub keys.
4555   class Branch_stub_ent
4556   {
4557   public:
4558     Branch_stub_ent(const Powerpc_relobj<size, big_endian>* obj,
4559                     Address to, bool save_res)
4560       : dest_(to), toc_base_off_(0), save_res_(save_res)
4561     {
4562       if (size == 64)
4563         toc_base_off_ = obj->toc_base_offset();
4564     }
4565
4566     bool operator==(const Branch_stub_ent& that) const
4567     {
4568       return (this->dest_ == that.dest_
4569               && (size == 32
4570                   || this->toc_base_off_ == that.toc_base_off_));
4571     }
4572
4573     Address dest_;
4574     unsigned int toc_base_off_;
4575     bool save_res_;
4576   };
4577
4578   class Branch_stub_ent_hash
4579   {
4580   public:
4581     size_t operator()(const Branch_stub_ent& ent) const
4582     { return ent.dest_ ^ ent.toc_base_off_; }
4583   };
4584
4585   // In a sane world this would be a global.
4586   Target_powerpc<size, big_endian>* targ_;
4587   // Map sym/object/addend to stub offset.
4588   Plt_stub_entries plt_call_stubs_;
4589   // Map destination address to stub offset.
4590   Branch_stub_entries long_branch_stubs_;
4591   // size of input section
4592   section_size_type orig_data_size_;
4593   // size of stubs
4594   section_size_type plt_size_, last_plt_size_, branch_size_, last_branch_size_;
4595   // Some rare cases cause (PR/20529) fluctuation in stub table
4596   // size, which leads to an endless relax loop. This is to be fixed
4597   // by, after the first few iterations, allowing only increase of
4598   // stub table size. This variable sets the minimal possible size of
4599   // a stub table, it is zero for the first few iterations, then
4600   // increases monotonically.
4601   Address min_size_threshold_;
4602   // Set if this stub group needs a copy of out-of-line register
4603   // save/restore functions.
4604   bool need_save_res_;
4605   // Per stub table unique identifier.
4606   uint32_t uniq_;
4607   // The bctrl in the __tls_get_addr_opt stub, if present.
4608   unsigned int tls_get_addr_opt_bctrl_;
4609   // FDE unwind info for this stub group.
4610   unsigned int plt_fde_len_;
4611   unsigned char plt_fde_[20];
4612 };
4613
4614 // Add a plt call stub, if we do not already have one for this
4615 // sym/object/addend combo.
4616
4617 template<int size, bool big_endian>
4618 bool
4619 Stub_table<size, big_endian>::add_plt_call_entry(
4620     Address from,
4621     const Sized_relobj_file<size, big_endian>* object,
4622     const Symbol* gsym,
4623     unsigned int r_type,
4624     Address addend,
4625     bool tocsave)
4626 {
4627   Plt_stub_key key(object, gsym, r_type, addend);
4628   Plt_stub_ent ent(this->plt_size_, this->plt_call_stubs_.size());
4629   std::pair<typename Plt_stub_entries::iterator, bool> p
4630     = this->plt_call_stubs_.insert(std::make_pair(key, ent));
4631   if (p.second)
4632     {
4633       this->plt_size_ = ent.off_ + this->plt_call_size(p.first);
4634       if (size == 64
4635           && this->targ_->is_elfv2_localentry0(gsym))
4636         {
4637           p.first->second.localentry0_ = 1;
4638           this->targ_->set_has_localentry0();
4639         }
4640       if (this->targ_->is_tls_get_addr_opt(gsym))
4641         {
4642           this->targ_->set_has_tls_get_addr_opt();
4643           this->tls_get_addr_opt_bctrl_ = this->plt_size_ - 5 * 4;
4644         }
4645       this->plt_size_ = this->plt_call_align(this->plt_size_);
4646     }
4647   if (size == 64
4648       && !tocsave
4649       && !p.first->second.localentry0_)
4650     p.first->second.r2save_ = 1;
4651   return this->can_reach_stub(from, ent.off_, r_type);
4652 }
4653
4654 template<int size, bool big_endian>
4655 bool
4656 Stub_table<size, big_endian>::add_plt_call_entry(
4657     Address from,
4658     const Sized_relobj_file<size, big_endian>* object,
4659     unsigned int locsym_index,
4660     unsigned int r_type,
4661     Address addend,
4662     bool tocsave)
4663 {
4664   Plt_stub_key key(object, locsym_index, r_type, addend);
4665   Plt_stub_ent ent(this->plt_size_, this->plt_call_stubs_.size());
4666   std::pair<typename Plt_stub_entries::iterator, bool> p
4667     = this->plt_call_stubs_.insert(std::make_pair(key, ent));
4668   if (p.second)
4669     {
4670       this->plt_size_ = ent.off_ + this->plt_call_size(p.first);
4671       this->plt_size_ = this->plt_call_align(this->plt_size_);
4672       if (size == 64
4673           && this->targ_->is_elfv2_localentry0(object, locsym_index))
4674         {
4675           p.first->second.localentry0_ = 1;
4676           this->targ_->set_has_localentry0();
4677         }
4678     }
4679   if (size == 64
4680       && !tocsave
4681       && !p.first->second.localentry0_)
4682     p.first->second.r2save_ = 1;
4683   return this->can_reach_stub(from, ent.off_, r_type);
4684 }
4685
4686 // Find a plt call stub.
4687
4688 template<int size, bool big_endian>
4689 const typename Stub_table<size, big_endian>::Plt_stub_ent*
4690 Stub_table<size, big_endian>::find_plt_call_entry(
4691     const Sized_relobj_file<size, big_endian>* object,
4692     const Symbol* gsym,
4693     unsigned int r_type,
4694     Address addend) const
4695 {
4696   Plt_stub_key key(object, gsym, r_type, addend);
4697   typename Plt_stub_entries::const_iterator p = this->plt_call_stubs_.find(key);
4698   if (p == this->plt_call_stubs_.end())
4699     return NULL;
4700   return &p->second;
4701 }
4702
4703 template<int size, bool big_endian>
4704 const typename Stub_table<size, big_endian>::Plt_stub_ent*
4705 Stub_table<size, big_endian>::find_plt_call_entry(const Symbol* gsym) const
4706 {
4707   Plt_stub_key key(gsym);
4708   typename Plt_stub_entries::const_iterator p = this->plt_call_stubs_.find(key);
4709   if (p == this->plt_call_stubs_.end())
4710     return NULL;
4711   return &p->second;
4712 }
4713
4714 template<int size, bool big_endian>
4715 const typename Stub_table<size, big_endian>::Plt_stub_ent*
4716 Stub_table<size, big_endian>::find_plt_call_entry(
4717     const Sized_relobj_file<size, big_endian>* object,
4718     unsigned int locsym_index,
4719     unsigned int r_type,
4720     Address addend) const
4721 {
4722   Plt_stub_key key(object, locsym_index, r_type, addend);
4723   typename Plt_stub_entries::const_iterator p = this->plt_call_stubs_.find(key);
4724   if (p == this->plt_call_stubs_.end())
4725     return NULL;
4726   return &p->second;
4727 }
4728
4729 template<int size, bool big_endian>
4730 const typename Stub_table<size, big_endian>::Plt_stub_ent*
4731 Stub_table<size, big_endian>::find_plt_call_entry(
4732     const Sized_relobj_file<size, big_endian>* object,
4733     unsigned int locsym_index) const
4734 {
4735   Plt_stub_key key(object, locsym_index);
4736   typename Plt_stub_entries::const_iterator p = this->plt_call_stubs_.find(key);
4737   if (p == this->plt_call_stubs_.end())
4738     return NULL;
4739   return &p->second;
4740 }
4741
4742 // Add a long branch stub if we don't already have one to given
4743 // destination.
4744
4745 template<int size, bool big_endian>
4746 bool
4747 Stub_table<size, big_endian>::add_long_branch_entry(
4748     const Powerpc_relobj<size, big_endian>* object,
4749     unsigned int r_type,
4750     Address from,
4751     Address to,
4752     bool save_res)
4753 {
4754   Branch_stub_ent ent(object, to, save_res);
4755   Address off = this->branch_size_;
4756   std::pair<typename Branch_stub_entries::iterator, bool> p
4757     = this->long_branch_stubs_.insert(std::make_pair(ent, off));
4758   if (p.second)
4759     {
4760       if (save_res)
4761         this->need_save_res_ = true;
4762       else
4763         {
4764           unsigned int stub_size = this->branch_stub_size(p.first);
4765           this->branch_size_ = off + stub_size;
4766           if (size == 64 && stub_size != 4)
4767             this->targ_->add_branch_lookup_table(to);
4768         }
4769     }
4770   return this->can_reach_stub(from, off, r_type);
4771 }
4772
4773 // Find long branch stub offset.
4774
4775 template<int size, bool big_endian>
4776 typename Stub_table<size, big_endian>::Address
4777 Stub_table<size, big_endian>::find_long_branch_entry(
4778     const Powerpc_relobj<size, big_endian>* object,
4779     Address to) const
4780 {
4781   Branch_stub_ent ent(object, to, false);
4782   typename Branch_stub_entries::const_iterator p
4783     = this->long_branch_stubs_.find(ent);
4784   if (p == this->long_branch_stubs_.end())
4785     return invalid_address;
4786   if (p->first.save_res_)
4787     return to - this->targ_->savres_section()->address() + this->branch_size_;
4788   return p->second;
4789 }
4790
4791 // Generate a suitable FDE to describe code in this stub group.
4792 // The __tls_get_addr_opt call stub needs to describe where it saves
4793 // LR, to support exceptions that might be thrown from __tls_get_addr.
4794
4795 template<int size, bool big_endian>
4796 void
4797 Stub_table<size, big_endian>::init_plt_fde()
4798 {
4799   unsigned char* p = this->plt_fde_;
4800   // offset pcrel sdata4, size udata4, and augmentation size byte.
4801   memset (p, 0, 9);
4802   p += 9;
4803   if (this->tls_get_addr_opt_bctrl_ != -1u)
4804     {
4805       unsigned int to_bctrl = this->tls_get_addr_opt_bctrl_ / 4;
4806       if (to_bctrl < 64)
4807         *p++ = elfcpp::DW_CFA_advance_loc + to_bctrl;
4808       else if (to_bctrl < 256)
4809         {
4810           *p++ = elfcpp::DW_CFA_advance_loc1;
4811           *p++ = to_bctrl;
4812         }
4813       else if (to_bctrl < 65536)
4814         {
4815           *p++ = elfcpp::DW_CFA_advance_loc2;
4816           elfcpp::Swap<16, big_endian>::writeval(p, to_bctrl);
4817           p += 2;
4818         }
4819       else
4820         {
4821           *p++ = elfcpp::DW_CFA_advance_loc4;
4822           elfcpp::Swap<32, big_endian>::writeval(p, to_bctrl);
4823           p += 4;
4824         }
4825       *p++ = elfcpp::DW_CFA_offset_extended_sf;
4826       *p++ = 65;
4827       *p++ = -(this->targ_->stk_linker() / 8) & 0x7f;
4828       *p++ = elfcpp::DW_CFA_advance_loc + 4;
4829       *p++ = elfcpp::DW_CFA_restore_extended;
4830       *p++ = 65;
4831     }
4832   this->plt_fde_len_ = p - this->plt_fde_;
4833 }
4834
4835 // Add .eh_frame info for this stub section.  Unlike other linker
4836 // generated .eh_frame this is added late in the link, because we
4837 // only want the .eh_frame info if this particular stub section is
4838 // non-empty.
4839
4840 template<int size, bool big_endian>
4841 void
4842 Stub_table<size, big_endian>::add_eh_frame(Layout* layout)
4843 {
4844   if (!parameters->options().ld_generated_unwind_info())
4845     return;
4846
4847   // Since we add stub .eh_frame info late, it must be placed
4848   // after all other linker generated .eh_frame info so that
4849   // merge mapping need not be updated for input sections.
4850   // There is no provision to use a different CIE to that used
4851   // by .glink.
4852   if (!this->targ_->has_glink())
4853     return;
4854
4855   if (this->plt_size_ + this->branch_size_ + this->need_save_res_ == 0)
4856     return;
4857
4858   this->init_plt_fde();
4859   layout->add_eh_frame_for_plt(this,
4860                                Eh_cie<size>::eh_frame_cie,
4861                                sizeof (Eh_cie<size>::eh_frame_cie),
4862                                this->plt_fde_, this->plt_fde_len_);
4863 }
4864
4865 template<int size, bool big_endian>
4866 void
4867 Stub_table<size, big_endian>::remove_eh_frame(Layout* layout)
4868 {
4869   if (this->plt_fde_len_ != 0)
4870     {
4871       layout->remove_eh_frame_for_plt(this,
4872                                       Eh_cie<size>::eh_frame_cie,
4873                                       sizeof (Eh_cie<size>::eh_frame_cie),
4874                                       this->plt_fde_, this->plt_fde_len_);
4875       this->plt_fde_len_ = 0;
4876     }
4877 }
4878
4879 // A class to handle .glink.
4880
4881 template<int size, bool big_endian>
4882 class Output_data_glink : public Output_section_data
4883 {
4884  public:
4885   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
4886   static const Address invalid_address = static_cast<Address>(0) - 1;
4887   static const int pltresolve_size = 16*4;
4888
4889   Output_data_glink(Target_powerpc<size, big_endian>* targ)
4890     : Output_section_data(16), targ_(targ), global_entry_stubs_(),
4891       end_branch_table_(), ge_size_(0)
4892   { }
4893
4894   void
4895   add_eh_frame(Layout* layout);
4896
4897   void
4898   add_global_entry(const Symbol*);
4899
4900   Address
4901   find_global_entry(const Symbol*) const;
4902
4903   Address
4904   global_entry_address() const
4905   {
4906     gold_assert(this->is_data_size_valid());
4907     unsigned int global_entry_off = (this->end_branch_table_ + 15) & -16;
4908     return this->address() + global_entry_off;
4909   }
4910
4911  protected:
4912   // Write to a map file.
4913   void
4914   do_print_to_mapfile(Mapfile* mapfile) const
4915   { mapfile->print_output_data(this, _("** glink")); }
4916
4917  private:
4918   void
4919   set_final_data_size();
4920
4921   // Write out .glink
4922   void
4923   do_write(Output_file*);
4924
4925   // Allows access to .got and .plt for do_write.
4926   Target_powerpc<size, big_endian>* targ_;
4927
4928   // Map sym to stub offset.
4929   typedef Unordered_map<const Symbol*, unsigned int> Global_entry_stub_entries;
4930   Global_entry_stub_entries global_entry_stubs_;
4931
4932   unsigned int end_branch_table_, ge_size_;
4933 };
4934
4935 template<int size, bool big_endian>
4936 void
4937 Output_data_glink<size, big_endian>::add_eh_frame(Layout* layout)
4938 {
4939   if (!parameters->options().ld_generated_unwind_info())
4940     return;
4941
4942   if (size == 64)
4943     {
4944       if (this->targ_->abiversion() < 2)
4945         layout->add_eh_frame_for_plt(this,
4946                                      Eh_cie<64>::eh_frame_cie,
4947                                      sizeof (Eh_cie<64>::eh_frame_cie),
4948                                      glink_eh_frame_fde_64v1,
4949                                      sizeof (glink_eh_frame_fde_64v1));
4950       else
4951         layout->add_eh_frame_for_plt(this,
4952                                      Eh_cie<64>::eh_frame_cie,
4953                                      sizeof (Eh_cie<64>::eh_frame_cie),
4954                                      glink_eh_frame_fde_64v2,
4955                                      sizeof (glink_eh_frame_fde_64v2));
4956     }
4957   else
4958     {
4959       // 32-bit .glink can use the default since the CIE return
4960       // address reg, LR, is valid.
4961       layout->add_eh_frame_for_plt(this,
4962                                    Eh_cie<32>::eh_frame_cie,
4963                                    sizeof (Eh_cie<32>::eh_frame_cie),
4964                                    default_fde,
4965                                    sizeof (default_fde));
4966       // Except where LR is used in a PIC __glink_PLTresolve.
4967       if (parameters->options().output_is_position_independent())
4968         layout->add_eh_frame_for_plt(this,
4969                                      Eh_cie<32>::eh_frame_cie,
4970                                      sizeof (Eh_cie<32>::eh_frame_cie),
4971                                      glink_eh_frame_fde_32,
4972                                      sizeof (glink_eh_frame_fde_32));
4973     }
4974 }
4975
4976 template<int size, bool big_endian>
4977 void
4978 Output_data_glink<size, big_endian>::add_global_entry(const Symbol* gsym)
4979 {
4980   std::pair<typename Global_entry_stub_entries::iterator, bool> p
4981     = this->global_entry_stubs_.insert(std::make_pair(gsym, this->ge_size_));
4982   if (p.second)
4983     this->ge_size_ += 16;
4984 }
4985
4986 template<int size, bool big_endian>
4987 typename Output_data_glink<size, big_endian>::Address
4988 Output_data_glink<size, big_endian>::find_global_entry(const Symbol* gsym) const
4989 {
4990   typename Global_entry_stub_entries::const_iterator p
4991     = this->global_entry_stubs_.find(gsym);
4992   return p == this->global_entry_stubs_.end() ? invalid_address : p->second;
4993 }
4994
4995 template<int size, bool big_endian>
4996 void
4997 Output_data_glink<size, big_endian>::set_final_data_size()
4998 {
4999   unsigned int count = this->targ_->plt_entry_count();
5000   section_size_type total = 0;
5001
5002   if (count != 0)
5003     {
5004       if (size == 32)
5005         {
5006           // space for branch table
5007           total += 4 * (count - 1);
5008
5009           total += -total & 15;
5010           total += this->pltresolve_size;
5011         }
5012       else
5013         {
5014           total += this->pltresolve_size;
5015
5016           // space for branch table
5017           total += 4 * count;
5018           if (this->targ_->abiversion() < 2)
5019             {
5020               total += 4 * count;
5021               if (count > 0x8000)
5022                 total += 4 * (count - 0x8000);
5023             }
5024         }
5025     }
5026   this->end_branch_table_ = total;
5027   total = (total + 15) & -16;
5028   total += this->ge_size_;
5029
5030   this->set_data_size(total);
5031 }
5032
5033 // Define symbols on stubs, identifying the stub.
5034
5035 template<int size, bool big_endian>
5036 void
5037 Stub_table<size, big_endian>::define_stub_syms(Symbol_table* symtab)
5038 {
5039   if (!this->plt_call_stubs_.empty())
5040     {
5041       // The key for the plt call stub hash table includes addresses,
5042       // therefore traversal order depends on those addresses, which
5043       // can change between runs if gold is a PIE.  Unfortunately the
5044       // output .symtab ordering depends on the order in which symbols
5045       // are added to the linker symtab.  We want reproducible output
5046       // so must sort the call stub symbols.
5047       typedef typename Plt_stub_entries::const_iterator plt_iter;
5048       std::vector<plt_iter> sorted;
5049       sorted.resize(this->plt_call_stubs_.size());
5050
5051       for (plt_iter cs = this->plt_call_stubs_.begin();
5052            cs != this->plt_call_stubs_.end();
5053            ++cs)
5054         sorted[cs->second.indx_] = cs;
5055
5056       for (unsigned int i = 0; i < this->plt_call_stubs_.size(); ++i)
5057         {
5058           plt_iter cs = sorted[i];
5059           char add[10];
5060           add[0] = 0;
5061           if (cs->first.addend_ != 0)
5062             sprintf(add, "+%x", static_cast<uint32_t>(cs->first.addend_));
5063           char obj[10];
5064           obj[0] = 0;
5065           if (cs->first.object_)
5066             {
5067               const Powerpc_relobj<size, big_endian>* ppcobj = static_cast
5068                 <const Powerpc_relobj<size, big_endian>*>(cs->first.object_);
5069               sprintf(obj, "%x:", ppcobj->uniq());
5070             }
5071           char localname[9];
5072           const char *symname;
5073           if (cs->first.sym_ == NULL)
5074             {
5075               sprintf(localname, "%x", cs->first.locsym_);
5076               symname = localname;
5077             }
5078           else if (this->targ_->is_tls_get_addr_opt(cs->first.sym_))
5079             symname = this->targ_->tls_get_addr_opt()->name();
5080           else
5081             symname = cs->first.sym_->name();
5082           char* name = new char[8 + 10 + strlen(obj) + strlen(symname) + strlen(add) + 1];
5083           sprintf(name, "%08x.plt_call.%s%s%s", this->uniq_, obj, symname, add);
5084           Address value
5085             = this->stub_address() - this->address() + cs->second.off_;
5086           unsigned int stub_size = this->plt_call_align(this->plt_call_size(cs));
5087           this->targ_->define_local(symtab, name, this, value, stub_size);
5088         }
5089     }
5090
5091   typedef typename Branch_stub_entries::const_iterator branch_iter;
5092   for (branch_iter bs = this->long_branch_stubs_.begin();
5093        bs != this->long_branch_stubs_.end();
5094        ++bs)
5095     {
5096       if (bs->first.save_res_)
5097         continue;
5098
5099       char* name = new char[8 + 13 + 16 + 1];
5100       sprintf(name, "%08x.long_branch.%llx", this->uniq_,
5101               static_cast<unsigned long long>(bs->first.dest_));
5102       Address value = (this->stub_address() - this->address()
5103                        + this->plt_size_ + bs->second);
5104       unsigned int stub_size = this->branch_stub_size(bs);
5105       this->targ_->define_local(symtab, name, this, value, stub_size);
5106     }
5107 }
5108
5109 // Write out plt and long branch stub code.
5110
5111 template<int size, bool big_endian>
5112 void
5113 Stub_table<size, big_endian>::do_write(Output_file* of)
5114 {
5115   if (this->plt_call_stubs_.empty()
5116       && this->long_branch_stubs_.empty())
5117     return;
5118
5119   const section_size_type start_off = this->offset();
5120   const section_size_type off = this->stub_offset();
5121   const section_size_type oview_size =
5122     convert_to_section_size_type(this->data_size() - (off - start_off));
5123   unsigned char* const oview = of->get_output_view(off, oview_size);
5124   unsigned char* p;
5125
5126   if (size == 64)
5127     {
5128       const Output_data_got_powerpc<size, big_endian>* got
5129         = this->targ_->got_section();
5130       Address got_os_addr = got->output_section()->address();
5131
5132       if (!this->plt_call_stubs_.empty())
5133         {
5134           // The base address of the .plt section.
5135           Address plt_base = this->targ_->plt_section()->address();
5136           Address iplt_base = invalid_address;
5137
5138           // Write out plt call stubs.
5139           typename Plt_stub_entries::const_iterator cs;
5140           for (cs = this->plt_call_stubs_.begin();
5141                cs != this->plt_call_stubs_.end();
5142                ++cs)
5143             {
5144               bool is_iplt;
5145               Address pltoff = this->plt_off(cs, &is_iplt);
5146               Address plt_addr = pltoff;
5147               if (is_iplt)
5148                 {
5149                   if (iplt_base == invalid_address)
5150                     iplt_base = this->targ_->iplt_section()->address();
5151                   plt_addr += iplt_base;
5152                 }
5153               else
5154                 plt_addr += plt_base;
5155               const Powerpc_relobj<size, big_endian>* ppcobj = static_cast
5156                 <const Powerpc_relobj<size, big_endian>*>(cs->first.object_);
5157               Address got_addr = got_os_addr + ppcobj->toc_base_offset();
5158               Address off = plt_addr - got_addr;
5159
5160               if (off + 0x80008000 > 0xffffffff || (off & 7) != 0)
5161                 gold_error(_("%s: linkage table error against `%s'"),
5162                            cs->first.object_->name().c_str(),
5163                            cs->first.sym_->demangled_name().c_str());
5164
5165               bool plt_load_toc = this->targ_->abiversion() < 2;
5166               bool static_chain
5167                 = plt_load_toc && parameters->options().plt_static_chain();
5168               bool thread_safe
5169                 = plt_load_toc && this->targ_->plt_thread_safe();
5170               bool use_fake_dep = false;
5171               Address cmp_branch_off = 0;
5172               if (thread_safe)
5173                 {
5174                   unsigned int pltindex
5175                     = ((pltoff - this->targ_->first_plt_entry_offset())
5176                        / this->targ_->plt_entry_size());
5177                   Address glinkoff
5178                     = (this->targ_->glink_section()->pltresolve_size
5179                        + pltindex * 8);
5180                   if (pltindex > 32768)
5181                     glinkoff += (pltindex - 32768) * 4;
5182                   Address to
5183                     = this->targ_->glink_section()->address() + glinkoff;
5184                   Address from
5185                     = (this->stub_address() + cs->second.off_ + 20
5186                        + 4 * cs->second.r2save_
5187                        + 4 * (ha(off) != 0)
5188                        + 4 * (ha(off + 8 + 8 * static_chain) != ha(off))
5189                        + 4 * static_chain);
5190                   cmp_branch_off = to - from;
5191                   use_fake_dep = cmp_branch_off + (1 << 25) >= (1 << 26);
5192                 }
5193
5194               p = oview + cs->second.off_;
5195               const Symbol* gsym = cs->first.sym_;
5196               if (this->targ_->is_tls_get_addr_opt(gsym))
5197                 {
5198                   write_insn<big_endian>(p, ld_11_3 + 0);
5199                   p += 4;
5200                   write_insn<big_endian>(p, ld_12_3 + 8);
5201                   p += 4;
5202                   write_insn<big_endian>(p, mr_0_3);
5203                   p += 4;
5204                   write_insn<big_endian>(p, cmpdi_11_0);
5205                   p += 4;
5206                   write_insn<big_endian>(p, add_3_12_13);
5207                   p += 4;
5208                   write_insn<big_endian>(p, beqlr);
5209                   p += 4;
5210                   write_insn<big_endian>(p, mr_3_0);
5211                   p += 4;
5212                   if (!cs->second.localentry0_)
5213                     {
5214                       write_insn<big_endian>(p, mflr_11);
5215                       p += 4;
5216                       write_insn<big_endian>(p, (std_11_1
5217                                                  + this->targ_->stk_linker()));
5218                       p += 4;
5219                     }
5220                   use_fake_dep = thread_safe;
5221                 }
5222               if (ha(off) != 0)
5223                 {
5224                   if (cs->second.r2save_)
5225                     {
5226                       write_insn<big_endian>(p,
5227                                              std_2_1 + this->targ_->stk_toc());
5228                       p += 4;
5229                     }
5230                   if (plt_load_toc)
5231                     {
5232                       write_insn<big_endian>(p, addis_11_2 + ha(off));
5233                       p += 4;
5234                       write_insn<big_endian>(p, ld_12_11 + l(off));
5235                       p += 4;
5236                     }
5237                   else
5238                     {
5239                       write_insn<big_endian>(p, addis_12_2 + ha(off));
5240                       p += 4;
5241                       write_insn<big_endian>(p, ld_12_12 + l(off));
5242                       p += 4;
5243                     }
5244                   if (plt_load_toc
5245                       && ha(off + 8 + 8 * static_chain) != ha(off))
5246                     {
5247                       write_insn<big_endian>(p, addi_11_11 + l(off));
5248                       p += 4;
5249                       off = 0;
5250                     }
5251                   write_insn<big_endian>(p, mtctr_12);
5252                   p += 4;
5253                   if (plt_load_toc)
5254                     {
5255                       if (use_fake_dep)
5256                         {
5257                           write_insn<big_endian>(p, xor_2_12_12);
5258                           p += 4;
5259                           write_insn<big_endian>(p, add_11_11_2);
5260                           p += 4;
5261                         }
5262                       write_insn<big_endian>(p, ld_2_11 + l(off + 8));
5263                       p += 4;
5264                       if (static_chain)
5265                         {
5266                           write_insn<big_endian>(p, ld_11_11 + l(off + 16));
5267                           p += 4;
5268                         }
5269                     }
5270                 }
5271               else
5272                 {
5273                   if (cs->second.r2save_)
5274                     {
5275                       write_insn<big_endian>(p,
5276                                              std_2_1 + this->targ_->stk_toc());
5277                       p += 4;
5278                     }
5279                   write_insn<big_endian>(p, ld_12_2 + l(off));
5280                   p += 4;
5281                   if (plt_load_toc
5282                       && ha(off + 8 + 8 * static_chain) != ha(off))
5283                     {
5284                       write_insn<big_endian>(p, addi_2_2 + l(off));
5285                       p += 4;
5286                       off = 0;
5287                     }
5288                   write_insn<big_endian>(p, mtctr_12);
5289                   p += 4;
5290                   if (plt_load_toc)
5291                     {
5292                       if (use_fake_dep)
5293                         {
5294                           write_insn<big_endian>(p, xor_11_12_12);
5295                           p += 4;
5296                           write_insn<big_endian>(p, add_2_2_11);
5297                           p += 4;
5298                         }
5299                       if (static_chain)
5300                         {
5301                           write_insn<big_endian>(p, ld_11_2 + l(off + 16));
5302                           p += 4;
5303                         }
5304                       write_insn<big_endian>(p, ld_2_2 + l(off + 8));
5305                       p += 4;
5306                     }
5307                 }
5308               if (!cs->second.localentry0_
5309                   && this->targ_->is_tls_get_addr_opt(gsym))
5310                 {
5311                   write_insn<big_endian>(p, bctrl);
5312                   p += 4;
5313                   write_insn<big_endian>(p, ld_2_1 + this->targ_->stk_toc());
5314                   p += 4;
5315                   write_insn<big_endian>(p, ld_11_1 + this->targ_->stk_linker());
5316                   p += 4;
5317                   write_insn<big_endian>(p, mtlr_11);
5318                   p += 4;
5319                   write_insn<big_endian>(p, blr);
5320                 }
5321               else if (thread_safe && !use_fake_dep)
5322                 {
5323                   write_insn<big_endian>(p, cmpldi_2_0);
5324                   p += 4;
5325                   write_insn<big_endian>(p, bnectr_p4);
5326                   p += 4;
5327                   write_insn<big_endian>(p, b | (cmp_branch_off & 0x3fffffc));
5328                 }
5329               else
5330                 write_insn<big_endian>(p, bctr);
5331             }
5332         }
5333
5334       // Write out long branch stubs.
5335       typename Branch_stub_entries::const_iterator bs;
5336       for (bs = this->long_branch_stubs_.begin();
5337            bs != this->long_branch_stubs_.end();
5338            ++bs)
5339         {
5340           if (bs->first.save_res_)
5341             continue;
5342           p = oview + this->plt_size_ + bs->second;
5343           Address loc = this->stub_address() + this->plt_size_ + bs->second;
5344           Address delta = bs->first.dest_ - loc;
5345           if (delta + (1 << 25) < 2 << 25)
5346             write_insn<big_endian>(p, b | (delta & 0x3fffffc));
5347           else
5348             {
5349               Address brlt_addr
5350                 = this->targ_->find_branch_lookup_table(bs->first.dest_);
5351               gold_assert(brlt_addr != invalid_address);
5352               brlt_addr += this->targ_->brlt_section()->address();
5353               Address got_addr = got_os_addr + bs->first.toc_base_off_;
5354               Address brltoff = brlt_addr - got_addr;
5355               if (ha(brltoff) == 0)
5356                 {
5357                   write_insn<big_endian>(p, ld_12_2 + l(brltoff)),      p += 4;
5358                 }
5359               else
5360                 {
5361                   write_insn<big_endian>(p, addis_12_2 + ha(brltoff)),  p += 4;
5362                   write_insn<big_endian>(p, ld_12_12 + l(brltoff)),     p += 4;
5363                 }
5364               write_insn<big_endian>(p, mtctr_12),                      p += 4;
5365               write_insn<big_endian>(p, bctr);
5366             }
5367         }
5368     }
5369   else
5370     {
5371       if (!this->plt_call_stubs_.empty())
5372         {
5373           // The base address of the .plt section.
5374           Address plt_base = this->targ_->plt_section()->address();
5375           Address iplt_base = invalid_address;
5376           // The address of _GLOBAL_OFFSET_TABLE_.
5377           Address g_o_t = invalid_address;
5378
5379           // Write out plt call stubs.
5380           typename Plt_stub_entries::const_iterator cs;
5381           for (cs = this->plt_call_stubs_.begin();
5382                cs != this->plt_call_stubs_.end();
5383                ++cs)
5384             {
5385               bool is_iplt;
5386               Address plt_addr = this->plt_off(cs, &is_iplt);
5387               if (is_iplt)
5388                 {
5389                   if (iplt_base == invalid_address)
5390                     iplt_base = this->targ_->iplt_section()->address();
5391                   plt_addr += iplt_base;
5392                 }
5393               else
5394                 plt_addr += plt_base;
5395
5396               p = oview + cs->second.off_;
5397               const Symbol* gsym = cs->first.sym_;
5398               if (this->targ_->is_tls_get_addr_opt(gsym))
5399                 {
5400                   write_insn<big_endian>(p, lwz_11_3 + 0);
5401                   p += 4;
5402                   write_insn<big_endian>(p, lwz_12_3 + 4);
5403                   p += 4;
5404                   write_insn<big_endian>(p, mr_0_3);
5405                   p += 4;
5406                   write_insn<big_endian>(p, cmpwi_11_0);
5407                   p += 4;
5408                   write_insn<big_endian>(p, add_3_12_2);
5409                   p += 4;
5410                   write_insn<big_endian>(p, beqlr);
5411                   p += 4;
5412                   write_insn<big_endian>(p, mr_3_0);
5413                   p += 4;
5414                   write_insn<big_endian>(p, nop);
5415                   p += 4;
5416                 }
5417               if (parameters->options().output_is_position_independent())
5418                 {
5419                   Address got_addr;
5420                   const Powerpc_relobj<size, big_endian>* ppcobj
5421                     = (static_cast<const Powerpc_relobj<size, big_endian>*>
5422                        (cs->first.object_));
5423                   if (ppcobj != NULL && cs->first.addend_ >= 32768)
5424                     {
5425                       unsigned int got2 = ppcobj->got2_shndx();
5426                       got_addr = ppcobj->get_output_section_offset(got2);
5427                       gold_assert(got_addr != invalid_address);
5428                       got_addr += (ppcobj->output_section(got2)->address()
5429                                    + cs->first.addend_);
5430                     }
5431                   else
5432                     {
5433                       if (g_o_t == invalid_address)
5434                         {
5435                           const Output_data_got_powerpc<size, big_endian>* got
5436                             = this->targ_->got_section();
5437                           g_o_t = got->address() + got->g_o_t();
5438                         }
5439                       got_addr = g_o_t;
5440                     }
5441
5442                   Address off = plt_addr - got_addr;
5443                   if (ha(off) == 0)
5444                     {
5445                       write_insn<big_endian>(p +  0, lwz_11_30 + l(off));
5446                       write_insn<big_endian>(p +  4, mtctr_11);
5447                       write_insn<big_endian>(p +  8, bctr);
5448                     }
5449                   else
5450                     {
5451                       write_insn<big_endian>(p +  0, addis_11_30 + ha(off));
5452                       write_insn<big_endian>(p +  4, lwz_11_11 + l(off));
5453                       write_insn<big_endian>(p +  8, mtctr_11);
5454                       write_insn<big_endian>(p + 12, bctr);
5455                     }
5456                 }
5457               else
5458                 {
5459                   write_insn<big_endian>(p +  0, lis_11 + ha(plt_addr));
5460                   write_insn<big_endian>(p +  4, lwz_11_11 + l(plt_addr));
5461                   write_insn<big_endian>(p +  8, mtctr_11);
5462                   write_insn<big_endian>(p + 12, bctr);
5463                 }
5464             }
5465         }
5466
5467       // Write out long branch stubs.
5468       typename Branch_stub_entries::const_iterator bs;
5469       for (bs = this->long_branch_stubs_.begin();
5470            bs != this->long_branch_stubs_.end();
5471            ++bs)
5472         {
5473           if (bs->first.save_res_)
5474             continue;
5475           p = oview + this->plt_size_ + bs->second;
5476           Address loc = this->stub_address() + this->plt_size_ + bs->second;
5477           Address delta = bs->first.dest_ - loc;
5478           if (delta + (1 << 25) < 2 << 25)
5479             write_insn<big_endian>(p, b | (delta & 0x3fffffc));
5480           else if (!parameters->options().output_is_position_independent())
5481             {
5482               write_insn<big_endian>(p +  0, lis_12 + ha(bs->first.dest_));
5483               write_insn<big_endian>(p +  4, addi_12_12 + l(bs->first.dest_));
5484               write_insn<big_endian>(p +  8, mtctr_12);
5485               write_insn<big_endian>(p + 12, bctr);
5486             }
5487           else
5488             {
5489               delta -= 8;
5490               write_insn<big_endian>(p +  0, mflr_0);
5491               write_insn<big_endian>(p +  4, bcl_20_31);
5492               write_insn<big_endian>(p +  8, mflr_12);
5493               write_insn<big_endian>(p + 12, addis_12_12 + ha(delta));
5494               write_insn<big_endian>(p + 16, addi_12_12 + l(delta));
5495               write_insn<big_endian>(p + 20, mtlr_0);
5496               write_insn<big_endian>(p + 24, mtctr_12);
5497               write_insn<big_endian>(p + 28, bctr);
5498             }
5499         }
5500     }
5501   if (this->need_save_res_)
5502     {
5503       p = oview + this->plt_size_ + this->branch_size_;
5504       memcpy (p, this->targ_->savres_section()->contents(),
5505               this->targ_->savres_section()->data_size());
5506     }
5507 }
5508
5509 // Write out .glink.
5510
5511 template<int size, bool big_endian>
5512 void
5513 Output_data_glink<size, big_endian>::do_write(Output_file* of)
5514 {
5515   const section_size_type off = this->offset();
5516   const section_size_type oview_size =
5517     convert_to_section_size_type(this->data_size());
5518   unsigned char* const oview = of->get_output_view(off, oview_size);
5519   unsigned char* p;
5520
5521   // The base address of the .plt section.
5522   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
5523   Address plt_base = this->targ_->plt_section()->address();
5524
5525   if (size == 64)
5526     {
5527       if (this->end_branch_table_ != 0)
5528         {
5529           // Write pltresolve stub.
5530           p = oview;
5531           Address after_bcl = this->address() + 16;
5532           Address pltoff = plt_base - after_bcl;
5533
5534           elfcpp::Swap<64, big_endian>::writeval(p, pltoff),    p += 8;
5535
5536           if (this->targ_->abiversion() < 2)
5537             {
5538               write_insn<big_endian>(p, mflr_12),               p += 4;
5539               write_insn<big_endian>(p, bcl_20_31),             p += 4;
5540               write_insn<big_endian>(p, mflr_11),               p += 4;
5541               write_insn<big_endian>(p, ld_2_11 + l(-16)),      p += 4;
5542               write_insn<big_endian>(p, mtlr_12),               p += 4;
5543               write_insn<big_endian>(p, add_11_2_11),           p += 4;
5544               write_insn<big_endian>(p, ld_12_11 + 0),          p += 4;
5545               write_insn<big_endian>(p, ld_2_11 + 8),           p += 4;
5546               write_insn<big_endian>(p, mtctr_12),              p += 4;
5547               write_insn<big_endian>(p, ld_11_11 + 16),         p += 4;
5548             }
5549           else
5550             {
5551               write_insn<big_endian>(p, mflr_0),                p += 4;
5552               write_insn<big_endian>(p, bcl_20_31),             p += 4;
5553               write_insn<big_endian>(p, mflr_11),               p += 4;
5554               write_insn<big_endian>(p, std_2_1 + 24),          p += 4;
5555               write_insn<big_endian>(p, ld_2_11 + l(-16)),      p += 4;
5556               write_insn<big_endian>(p, mtlr_0),                p += 4;
5557               write_insn<big_endian>(p, sub_12_12_11),          p += 4;
5558               write_insn<big_endian>(p, add_11_2_11),           p += 4;
5559               write_insn<big_endian>(p, addi_0_12 + l(-48)),    p += 4;
5560               write_insn<big_endian>(p, ld_12_11 + 0),          p += 4;
5561               write_insn<big_endian>(p, srdi_0_0_2),            p += 4;
5562               write_insn<big_endian>(p, mtctr_12),              p += 4;
5563               write_insn<big_endian>(p, ld_11_11 + 8),          p += 4;
5564             }
5565           write_insn<big_endian>(p, bctr),                      p += 4;
5566           while (p < oview + this->pltresolve_size)
5567             write_insn<big_endian>(p, nop), p += 4;
5568
5569           // Write lazy link call stubs.
5570           uint32_t indx = 0;
5571           while (p < oview + this->end_branch_table_)
5572             {
5573               if (this->targ_->abiversion() < 2)
5574                 {
5575                   if (indx < 0x8000)
5576                     {
5577                       write_insn<big_endian>(p, li_0_0 + indx),         p += 4;
5578                     }
5579                   else
5580                     {
5581                       write_insn<big_endian>(p, lis_0 + hi(indx)),      p += 4;
5582                       write_insn<big_endian>(p, ori_0_0_0 + l(indx)),   p += 4;
5583                     }
5584                 }
5585               uint32_t branch_off = 8 - (p - oview);
5586               write_insn<big_endian>(p, b + (branch_off & 0x3fffffc)),  p += 4;
5587               indx++;
5588             }
5589         }
5590
5591       Address plt_base = this->targ_->plt_section()->address();
5592       Address iplt_base = invalid_address;
5593       unsigned int global_entry_off = (this->end_branch_table_ + 15) & -16;
5594       Address global_entry_base = this->address() + global_entry_off;
5595       typename Global_entry_stub_entries::const_iterator ge;
5596       for (ge = this->global_entry_stubs_.begin();
5597            ge != this->global_entry_stubs_.end();
5598            ++ge)
5599         {
5600           p = oview + global_entry_off + ge->second;
5601           Address plt_addr = ge->first->plt_offset();
5602           if (ge->first->type() == elfcpp::STT_GNU_IFUNC
5603               && ge->first->can_use_relative_reloc(false))
5604             {
5605               if (iplt_base == invalid_address)
5606                 iplt_base = this->targ_->iplt_section()->address();
5607               plt_addr += iplt_base;
5608             }
5609           else
5610             plt_addr += plt_base;
5611           Address my_addr = global_entry_base + ge->second;
5612           Address off = plt_addr - my_addr;
5613
5614           if (off + 0x80008000 > 0xffffffff || (off & 3) != 0)
5615             gold_error(_("%s: linkage table error against `%s'"),
5616                        ge->first->object()->name().c_str(),
5617                        ge->first->demangled_name().c_str());
5618
5619           write_insn<big_endian>(p, addis_12_12 + ha(off)),     p += 4;
5620           write_insn<big_endian>(p, ld_12_12 + l(off)),         p += 4;
5621           write_insn<big_endian>(p, mtctr_12),                  p += 4;
5622           write_insn<big_endian>(p, bctr);
5623         }
5624     }
5625   else
5626     {
5627       const Output_data_got_powerpc<size, big_endian>* got
5628         = this->targ_->got_section();
5629       // The address of _GLOBAL_OFFSET_TABLE_.
5630       Address g_o_t = got->address() + got->g_o_t();
5631
5632       // Write out pltresolve branch table.
5633       p = oview;
5634       unsigned int the_end = oview_size - this->pltresolve_size;
5635       unsigned char* end_p = oview + the_end;
5636       while (p < end_p - 8 * 4)
5637         write_insn<big_endian>(p, b + end_p - p), p += 4;
5638       while (p < end_p)
5639         write_insn<big_endian>(p, nop), p += 4;
5640
5641       // Write out pltresolve call stub.
5642       if (parameters->options().output_is_position_independent())
5643         {
5644           Address res0_off = 0;
5645           Address after_bcl_off = the_end + 12;
5646           Address bcl_res0 = after_bcl_off - res0_off;
5647
5648           write_insn<big_endian>(p +  0, addis_11_11 + ha(bcl_res0));
5649           write_insn<big_endian>(p +  4, mflr_0);
5650           write_insn<big_endian>(p +  8, bcl_20_31);
5651           write_insn<big_endian>(p + 12, addi_11_11 + l(bcl_res0));
5652           write_insn<big_endian>(p + 16, mflr_12);
5653           write_insn<big_endian>(p + 20, mtlr_0);
5654           write_insn<big_endian>(p + 24, sub_11_11_12);
5655
5656           Address got_bcl = g_o_t + 4 - (after_bcl_off + this->address());
5657
5658           write_insn<big_endian>(p + 28, addis_12_12 + ha(got_bcl));
5659           if (ha(got_bcl) == ha(got_bcl + 4))
5660             {
5661               write_insn<big_endian>(p + 32, lwz_0_12 + l(got_bcl));
5662               write_insn<big_endian>(p + 36, lwz_12_12 + l(got_bcl + 4));
5663             }
5664           else
5665             {
5666               write_insn<big_endian>(p + 32, lwzu_0_12 + l(got_bcl));
5667               write_insn<big_endian>(p + 36, lwz_12_12 + 4);
5668             }
5669           write_insn<big_endian>(p + 40, mtctr_0);
5670           write_insn<big_endian>(p + 44, add_0_11_11);
5671           write_insn<big_endian>(p + 48, add_11_0_11);
5672           write_insn<big_endian>(p + 52, bctr);
5673           write_insn<big_endian>(p + 56, nop);
5674           write_insn<big_endian>(p + 60, nop);
5675         }
5676       else
5677         {
5678           Address res0 = this->address();
5679
5680           write_insn<big_endian>(p + 0, lis_12 + ha(g_o_t + 4));
5681           write_insn<big_endian>(p + 4, addis_11_11 + ha(-res0));
5682           if (ha(g_o_t + 4) == ha(g_o_t + 8))
5683             write_insn<big_endian>(p + 8, lwz_0_12 + l(g_o_t + 4));
5684           else
5685             write_insn<big_endian>(p + 8, lwzu_0_12 + l(g_o_t + 4));
5686           write_insn<big_endian>(p + 12, addi_11_11 + l(-res0));
5687           write_insn<big_endian>(p + 16, mtctr_0);
5688           write_insn<big_endian>(p + 20, add_0_11_11);
5689           if (ha(g_o_t + 4) == ha(g_o_t + 8))
5690             write_insn<big_endian>(p + 24, lwz_12_12 + l(g_o_t + 8));
5691           else
5692             write_insn<big_endian>(p + 24, lwz_12_12 + 4);
5693           write_insn<big_endian>(p + 28, add_11_0_11);
5694           write_insn<big_endian>(p + 32, bctr);
5695           write_insn<big_endian>(p + 36, nop);
5696           write_insn<big_endian>(p + 40, nop);
5697           write_insn<big_endian>(p + 44, nop);
5698           write_insn<big_endian>(p + 48, nop);
5699           write_insn<big_endian>(p + 52, nop);
5700           write_insn<big_endian>(p + 56, nop);
5701           write_insn<big_endian>(p + 60, nop);
5702         }
5703       p += 64;
5704     }
5705
5706   of->write_output_view(off, oview_size, oview);
5707 }
5708
5709
5710 // A class to handle linker generated save/restore functions.
5711
5712 template<int size, bool big_endian>
5713 class Output_data_save_res : public Output_section_data_build
5714 {
5715  public:
5716   Output_data_save_res(Symbol_table* symtab);
5717
5718   const unsigned char*
5719   contents() const
5720   {
5721     return contents_;
5722   }
5723
5724  protected:
5725   // Write to a map file.
5726   void
5727   do_print_to_mapfile(Mapfile* mapfile) const
5728   { mapfile->print_output_data(this, _("** save/restore")); }
5729
5730   void
5731   do_write(Output_file*);
5732
5733  private:
5734   // The maximum size of save/restore contents.
5735   static const unsigned int savres_max = 218*4;
5736
5737   void
5738   savres_define(Symbol_table* symtab,
5739                 const char *name,
5740                 unsigned int lo, unsigned int hi,
5741                 unsigned char* write_ent(unsigned char*, int),
5742                 unsigned char* write_tail(unsigned char*, int));
5743
5744   unsigned char *contents_;
5745 };
5746
5747 template<bool big_endian>
5748 static unsigned char*
5749 savegpr0(unsigned char* p, int r)
5750 {
5751   uint32_t insn = std_0_1 + (r << 21) + (1 << 16) - (32 - r) * 8;
5752   write_insn<big_endian>(p, insn);
5753   return p + 4;
5754 }
5755
5756 template<bool big_endian>
5757 static unsigned char*
5758 savegpr0_tail(unsigned char* p, int r)
5759 {
5760   p = savegpr0<big_endian>(p, r);
5761   uint32_t insn = std_0_1 + 16;
5762   write_insn<big_endian>(p, insn);
5763   p = p + 4;
5764   write_insn<big_endian>(p, blr);
5765   return p + 4;
5766 }
5767
5768 template<bool big_endian>
5769 static unsigned char*
5770 restgpr0(unsigned char* p, int r)
5771 {
5772   uint32_t insn = ld_0_1 + (r << 21) + (1 << 16) - (32 - r) * 8;
5773   write_insn<big_endian>(p, insn);
5774   return p + 4;
5775 }
5776
5777 template<bool big_endian>
5778 static unsigned char*
5779 restgpr0_tail(unsigned char* p, int r)
5780 {
5781   uint32_t insn = ld_0_1 + 16;
5782   write_insn<big_endian>(p, insn);
5783   p = p + 4;
5784   p = restgpr0<big_endian>(p, r);
5785   write_insn<big_endian>(p, mtlr_0);
5786   p = p + 4;
5787   if (r == 29)
5788     {
5789       p = restgpr0<big_endian>(p, 30);
5790       p = restgpr0<big_endian>(p, 31);
5791     }
5792   write_insn<big_endian>(p, blr);
5793   return p + 4;
5794 }
5795
5796 template<bool big_endian>
5797 static unsigned char*
5798 savegpr1(unsigned char* p, int r)
5799 {
5800   uint32_t insn = std_0_12 + (r << 21) + (1 << 16) - (32 - r) * 8;
5801   write_insn<big_endian>(p, insn);
5802   return p + 4;
5803 }
5804
5805 template<bool big_endian>
5806 static unsigned char*
5807 savegpr1_tail(unsigned char* p, int r)
5808 {
5809   p = savegpr1<big_endian>(p, r);
5810   write_insn<big_endian>(p, blr);
5811   return p + 4;
5812 }
5813
5814 template<bool big_endian>
5815 static unsigned char*
5816 restgpr1(unsigned char* p, int r)
5817 {
5818   uint32_t insn = ld_0_12 + (r << 21) + (1 << 16) - (32 - r) * 8;
5819   write_insn<big_endian>(p, insn);
5820   return p + 4;
5821 }
5822
5823 template<bool big_endian>
5824 static unsigned char*
5825 restgpr1_tail(unsigned char* p, int r)
5826 {
5827   p = restgpr1<big_endian>(p, r);
5828   write_insn<big_endian>(p, blr);
5829   return p + 4;
5830 }
5831
5832 template<bool big_endian>
5833 static unsigned char*
5834 savefpr(unsigned char* p, int r)
5835 {
5836   uint32_t insn = stfd_0_1 + (r << 21) + (1 << 16) - (32 - r) * 8;
5837   write_insn<big_endian>(p, insn);
5838   return p + 4;
5839 }
5840
5841 template<bool big_endian>
5842 static unsigned char*
5843 savefpr0_tail(unsigned char* p, int r)
5844 {
5845   p = savefpr<big_endian>(p, r);
5846   write_insn<big_endian>(p, std_0_1 + 16);
5847   p = p + 4;
5848   write_insn<big_endian>(p, blr);
5849   return p + 4;
5850 }
5851
5852 template<bool big_endian>
5853 static unsigned char*
5854 restfpr(unsigned char* p, int r)
5855 {
5856   uint32_t insn = lfd_0_1 + (r << 21) + (1 << 16) - (32 - r) * 8;
5857   write_insn<big_endian>(p, insn);
5858   return p + 4;
5859 }
5860
5861 template<bool big_endian>
5862 static unsigned char*
5863 restfpr0_tail(unsigned char* p, int r)
5864 {
5865   write_insn<big_endian>(p, ld_0_1 + 16);
5866   p = p + 4;
5867   p = restfpr<big_endian>(p, r);
5868   write_insn<big_endian>(p, mtlr_0);
5869   p = p + 4;
5870   if (r == 29)
5871     {
5872       p = restfpr<big_endian>(p, 30);
5873       p = restfpr<big_endian>(p, 31);
5874     }
5875   write_insn<big_endian>(p, blr);
5876   return p + 4;
5877 }
5878
5879 template<bool big_endian>
5880 static unsigned char*
5881 savefpr1_tail(unsigned char* p, int r)
5882 {
5883   p = savefpr<big_endian>(p, r);
5884   write_insn<big_endian>(p, blr);
5885   return p + 4;
5886 }
5887
5888 template<bool big_endian>
5889 static unsigned char*
5890 restfpr1_tail(unsigned char* p, int r)
5891 {
5892   p = restfpr<big_endian>(p, r);
5893   write_insn<big_endian>(p, blr);
5894   return p + 4;
5895 }
5896
5897 template<bool big_endian>
5898 static unsigned char*
5899 savevr(unsigned char* p, int r)
5900 {
5901   uint32_t insn = li_12_0 + (1 << 16) - (32 - r) * 16;
5902   write_insn<big_endian>(p, insn);
5903   p = p + 4;
5904   insn = stvx_0_12_0 + (r << 21);
5905   write_insn<big_endian>(p, insn);
5906   return p + 4;
5907 }
5908
5909 template<bool big_endian>
5910 static unsigned char*
5911 savevr_tail(unsigned char* p, int r)
5912 {
5913   p = savevr<big_endian>(p, r);
5914   write_insn<big_endian>(p, blr);
5915   return p + 4;
5916 }
5917
5918 template<bool big_endian>
5919 static unsigned char*
5920 restvr(unsigned char* p, int r)
5921 {
5922   uint32_t insn = li_12_0 + (1 << 16) - (32 - r) * 16;
5923   write_insn<big_endian>(p, insn);
5924   p = p + 4;
5925   insn = lvx_0_12_0 + (r << 21);
5926   write_insn<big_endian>(p, insn);
5927   return p + 4;
5928 }
5929
5930 template<bool big_endian>
5931 static unsigned char*
5932 restvr_tail(unsigned char* p, int r)
5933 {
5934   p = restvr<big_endian>(p, r);
5935   write_insn<big_endian>(p, blr);
5936   return p + 4;
5937 }
5938
5939
5940 template<int size, bool big_endian>
5941 Output_data_save_res<size, big_endian>::Output_data_save_res(
5942     Symbol_table* symtab)
5943   : Output_section_data_build(4),
5944     contents_(NULL)
5945 {
5946   this->savres_define(symtab,
5947                       "_savegpr0_", 14, 31,
5948                       savegpr0<big_endian>, savegpr0_tail<big_endian>);
5949   this->savres_define(symtab,
5950                       "_restgpr0_", 14, 29,
5951                       restgpr0<big_endian>, restgpr0_tail<big_endian>);
5952   this->savres_define(symtab,
5953                       "_restgpr0_", 30, 31,
5954                       restgpr0<big_endian>, restgpr0_tail<big_endian>);
5955   this->savres_define(symtab,
5956                       "_savegpr1_", 14, 31,
5957                       savegpr1<big_endian>, savegpr1_tail<big_endian>);
5958   this->savres_define(symtab,
5959                       "_restgpr1_", 14, 31,
5960                       restgpr1<big_endian>, restgpr1_tail<big_endian>);
5961   this->savres_define(symtab,
5962                       "_savefpr_", 14, 31,
5963                       savefpr<big_endian>, savefpr0_tail<big_endian>);
5964   this->savres_define(symtab,
5965                       "_restfpr_", 14, 29,
5966                       restfpr<big_endian>, restfpr0_tail<big_endian>);
5967   this->savres_define(symtab,
5968                       "_restfpr_", 30, 31,
5969                       restfpr<big_endian>, restfpr0_tail<big_endian>);
5970   this->savres_define(symtab,
5971                       "._savef", 14, 31,
5972                       savefpr<big_endian>, savefpr1_tail<big_endian>);
5973   this->savres_define(symtab,
5974                       "._restf", 14, 31,
5975                       restfpr<big_endian>, restfpr1_tail<big_endian>);
5976   this->savres_define(symtab,
5977                       "_savevr_", 20, 31,
5978                       savevr<big_endian>, savevr_tail<big_endian>);
5979   this->savres_define(symtab,
5980                       "_restvr_", 20, 31,
5981                       restvr<big_endian>, restvr_tail<big_endian>);
5982 }
5983
5984 template<int size, bool big_endian>
5985 void
5986 Output_data_save_res<size, big_endian>::savres_define(
5987     Symbol_table* symtab,
5988     const char *name,
5989     unsigned int lo, unsigned int hi,
5990     unsigned char* write_ent(unsigned char*, int),
5991     unsigned char* write_tail(unsigned char*, int))
5992 {
5993   size_t len = strlen(name);
5994   bool writing = false;
5995   char sym[16];
5996
5997   memcpy(sym, name, len);
5998   sym[len + 2] = 0;
5999
6000   for (unsigned int i = lo; i <= hi; i++)
6001     {
6002       sym[len + 0] = i / 10 + '0';
6003       sym[len + 1] = i % 10 + '0';
6004       Symbol* gsym = symtab->lookup(sym);
6005       bool refd = gsym != NULL && gsym->is_undefined();
6006       writing = writing || refd;
6007       if (writing)
6008         {
6009           if (this->contents_ == NULL)
6010             this->contents_ = new unsigned char[this->savres_max];
6011
6012           section_size_type value = this->current_data_size();
6013           unsigned char* p = this->contents_ + value;
6014           if (i != hi)
6015             p = write_ent(p, i);
6016           else
6017             p = write_tail(p, i);
6018           section_size_type cur_size = p - this->contents_;
6019           this->set_current_data_size(cur_size);
6020           if (refd)
6021             symtab->define_in_output_data(sym, NULL, Symbol_table::PREDEFINED,
6022                                           this, value, cur_size - value,
6023                                           elfcpp::STT_FUNC, elfcpp::STB_GLOBAL,
6024                                           elfcpp::STV_HIDDEN, 0, false, false);
6025         }
6026     }
6027 }
6028
6029 // Write out save/restore.
6030
6031 template<int size, bool big_endian>
6032 void
6033 Output_data_save_res<size, big_endian>::do_write(Output_file* of)
6034 {
6035   const section_size_type off = this->offset();
6036   const section_size_type oview_size =
6037     convert_to_section_size_type(this->data_size());
6038   unsigned char* const oview = of->get_output_view(off, oview_size);
6039   memcpy(oview, this->contents_, oview_size);
6040   of->write_output_view(off, oview_size, oview);
6041 }
6042
6043
6044 // Create the glink section.
6045
6046 template<int size, bool big_endian>
6047 void
6048 Target_powerpc<size, big_endian>::make_glink_section(Layout* layout)
6049 {
6050   if (this->glink_ == NULL)
6051     {
6052       this->glink_ = new Output_data_glink<size, big_endian>(this);
6053       this->glink_->add_eh_frame(layout);
6054       layout->add_output_section_data(".text", elfcpp::SHT_PROGBITS,
6055                                       elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR,
6056                                       this->glink_, ORDER_TEXT, false);
6057     }
6058 }
6059
6060 // Create a PLT entry for a global symbol.
6061
6062 template<int size, bool big_endian>
6063 void
6064 Target_powerpc<size, big_endian>::make_plt_entry(Symbol_table* symtab,
6065                                                  Layout* layout,
6066                                                  Symbol* gsym)
6067 {
6068   if (gsym->type() == elfcpp::STT_GNU_IFUNC
6069       && gsym->can_use_relative_reloc(false))
6070     {
6071       if (this->iplt_ == NULL)
6072         this->make_iplt_section(symtab, layout);
6073       this->iplt_->add_ifunc_entry(gsym);
6074     }
6075   else
6076     {
6077       if (this->plt_ == NULL)
6078         this->make_plt_section(symtab, layout);
6079       this->plt_->add_entry(gsym);
6080     }
6081 }
6082
6083 // Make a PLT entry for a local STT_GNU_IFUNC symbol.
6084
6085 template<int size, bool big_endian>
6086 void
6087 Target_powerpc<size, big_endian>::make_local_ifunc_plt_entry(
6088     Symbol_table* symtab,
6089     Layout* layout,
6090     Sized_relobj_file<size, big_endian>* relobj,
6091     unsigned int r_sym)
6092 {
6093   if (this->iplt_ == NULL)
6094     this->make_iplt_section(symtab, layout);
6095   this->iplt_->add_local_ifunc_entry(relobj, r_sym);
6096 }
6097
6098 // Return the number of entries in the PLT.
6099
6100 template<int size, bool big_endian>
6101 unsigned int
6102 Target_powerpc<size, big_endian>::plt_entry_count() const
6103 {
6104   if (this->plt_ == NULL)
6105     return 0;
6106   return this->plt_->entry_count();
6107 }
6108
6109 // Create a GOT entry for local dynamic __tls_get_addr calls.
6110
6111 template<int size, bool big_endian>
6112 unsigned int
6113 Target_powerpc<size, big_endian>::tlsld_got_offset(
6114     Symbol_table* symtab,
6115     Layout* layout,
6116     Sized_relobj_file<size, big_endian>* object)
6117 {
6118   if (this->tlsld_got_offset_ == -1U)
6119     {
6120       gold_assert(symtab != NULL && layout != NULL && object != NULL);
6121       Reloc_section* rela_dyn = this->rela_dyn_section(layout);
6122       Output_data_got_powerpc<size, big_endian>* got
6123         = this->got_section(symtab, layout);
6124       unsigned int got_offset = got->add_constant_pair(0, 0);
6125       rela_dyn->add_local(object, 0, elfcpp::R_POWERPC_DTPMOD, got,
6126                           got_offset, 0);
6127       this->tlsld_got_offset_ = got_offset;
6128     }
6129   return this->tlsld_got_offset_;
6130 }
6131
6132 // Get the Reference_flags for a particular relocation.
6133
6134 template<int size, bool big_endian>
6135 int
6136 Target_powerpc<size, big_endian>::Scan::get_reference_flags(
6137     unsigned int r_type,
6138     const Target_powerpc* target)
6139 {
6140   int ref = 0;
6141
6142   switch (r_type)
6143     {
6144     case elfcpp::R_POWERPC_NONE:
6145     case elfcpp::R_POWERPC_GNU_VTINHERIT:
6146     case elfcpp::R_POWERPC_GNU_VTENTRY:
6147     case elfcpp::R_PPC64_TOC:
6148       // No symbol reference.
6149       break;
6150
6151     case elfcpp::R_PPC64_ADDR64:
6152     case elfcpp::R_PPC64_UADDR64:
6153     case elfcpp::R_POWERPC_ADDR32:
6154     case elfcpp::R_POWERPC_UADDR32:
6155     case elfcpp::R_POWERPC_ADDR16:
6156     case elfcpp::R_POWERPC_UADDR16:
6157     case elfcpp::R_POWERPC_ADDR16_LO:
6158     case elfcpp::R_POWERPC_ADDR16_HI:
6159     case elfcpp::R_POWERPC_ADDR16_HA:
6160       ref = Symbol::ABSOLUTE_REF;
6161       break;
6162
6163     case elfcpp::R_POWERPC_ADDR24:
6164     case elfcpp::R_POWERPC_ADDR14:
6165     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
6166     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
6167       ref = Symbol::FUNCTION_CALL | Symbol::ABSOLUTE_REF;
6168       break;
6169
6170     case elfcpp::R_PPC64_REL64:
6171     case elfcpp::R_POWERPC_REL32:
6172     case elfcpp::R_PPC_LOCAL24PC:
6173     case elfcpp::R_POWERPC_REL16:
6174     case elfcpp::R_POWERPC_REL16_LO:
6175     case elfcpp::R_POWERPC_REL16_HI:
6176     case elfcpp::R_POWERPC_REL16_HA:
6177       ref = Symbol::RELATIVE_REF;
6178       break;
6179
6180     case elfcpp::R_POWERPC_REL24:
6181     case elfcpp::R_PPC_PLTREL24:
6182     case elfcpp::R_POWERPC_REL14:
6183     case elfcpp::R_POWERPC_REL14_BRTAKEN:
6184     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
6185       ref = Symbol::FUNCTION_CALL | Symbol::RELATIVE_REF;
6186       break;
6187
6188     case elfcpp::R_POWERPC_GOT16:
6189     case elfcpp::R_POWERPC_GOT16_LO:
6190     case elfcpp::R_POWERPC_GOT16_HI:
6191     case elfcpp::R_POWERPC_GOT16_HA:
6192     case elfcpp::R_PPC64_GOT16_DS:
6193     case elfcpp::R_PPC64_GOT16_LO_DS:
6194     case elfcpp::R_PPC64_TOC16:
6195     case elfcpp::R_PPC64_TOC16_LO:
6196     case elfcpp::R_PPC64_TOC16_HI:
6197     case elfcpp::R_PPC64_TOC16_HA:
6198     case elfcpp::R_PPC64_TOC16_DS:
6199     case elfcpp::R_PPC64_TOC16_LO_DS:
6200       ref = Symbol::RELATIVE_REF;
6201       break;
6202
6203     case elfcpp::R_POWERPC_GOT_TPREL16:
6204     case elfcpp::R_POWERPC_TLS:
6205       ref = Symbol::TLS_REF;
6206       break;
6207
6208     case elfcpp::R_POWERPC_COPY:
6209     case elfcpp::R_POWERPC_GLOB_DAT:
6210     case elfcpp::R_POWERPC_JMP_SLOT:
6211     case elfcpp::R_POWERPC_RELATIVE:
6212     case elfcpp::R_POWERPC_DTPMOD:
6213     default:
6214       // Not expected.  We will give an error later.
6215       break;
6216     }
6217
6218   if (size == 64 && target->abiversion() < 2)
6219     ref |= Symbol::FUNC_DESC_ABI;
6220   return ref;
6221 }
6222
6223 // Report an unsupported relocation against a local symbol.
6224
6225 template<int size, bool big_endian>
6226 void
6227 Target_powerpc<size, big_endian>::Scan::unsupported_reloc_local(
6228     Sized_relobj_file<size, big_endian>* object,
6229     unsigned int r_type)
6230 {
6231   gold_error(_("%s: unsupported reloc %u against local symbol"),
6232              object->name().c_str(), r_type);
6233 }
6234
6235 // We are about to emit a dynamic relocation of type R_TYPE.  If the
6236 // dynamic linker does not support it, issue an error.
6237
6238 template<int size, bool big_endian>
6239 void
6240 Target_powerpc<size, big_endian>::Scan::check_non_pic(Relobj* object,
6241                                                       unsigned int r_type)
6242 {
6243   gold_assert(r_type != elfcpp::R_POWERPC_NONE);
6244
6245   // These are the relocation types supported by glibc for both 32-bit
6246   // and 64-bit powerpc.
6247   switch (r_type)
6248     {
6249     case elfcpp::R_POWERPC_NONE:
6250     case elfcpp::R_POWERPC_RELATIVE:
6251     case elfcpp::R_POWERPC_GLOB_DAT:
6252     case elfcpp::R_POWERPC_DTPMOD:
6253     case elfcpp::R_POWERPC_DTPREL:
6254     case elfcpp::R_POWERPC_TPREL:
6255     case elfcpp::R_POWERPC_JMP_SLOT:
6256     case elfcpp::R_POWERPC_COPY:
6257     case elfcpp::R_POWERPC_IRELATIVE:
6258     case elfcpp::R_POWERPC_ADDR32:
6259     case elfcpp::R_POWERPC_UADDR32:
6260     case elfcpp::R_POWERPC_ADDR24:
6261     case elfcpp::R_POWERPC_ADDR16:
6262     case elfcpp::R_POWERPC_UADDR16:
6263     case elfcpp::R_POWERPC_ADDR16_LO:
6264     case elfcpp::R_POWERPC_ADDR16_HI:
6265     case elfcpp::R_POWERPC_ADDR16_HA:
6266     case elfcpp::R_POWERPC_ADDR14:
6267     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
6268     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
6269     case elfcpp::R_POWERPC_REL32:
6270     case elfcpp::R_POWERPC_REL24:
6271     case elfcpp::R_POWERPC_TPREL16:
6272     case elfcpp::R_POWERPC_TPREL16_LO:
6273     case elfcpp::R_POWERPC_TPREL16_HI:
6274     case elfcpp::R_POWERPC_TPREL16_HA:
6275       return;
6276
6277     default:
6278       break;
6279     }
6280
6281   if (size == 64)
6282     {
6283       switch (r_type)
6284         {
6285           // These are the relocation types supported only on 64-bit.
6286         case elfcpp::R_PPC64_ADDR64:
6287         case elfcpp::R_PPC64_UADDR64:
6288         case elfcpp::R_PPC64_JMP_IREL:
6289         case elfcpp::R_PPC64_ADDR16_DS:
6290         case elfcpp::R_PPC64_ADDR16_LO_DS:
6291         case elfcpp::R_PPC64_ADDR16_HIGH:
6292         case elfcpp::R_PPC64_ADDR16_HIGHA:
6293         case elfcpp::R_PPC64_ADDR16_HIGHER:
6294         case elfcpp::R_PPC64_ADDR16_HIGHEST:
6295         case elfcpp::R_PPC64_ADDR16_HIGHERA:
6296         case elfcpp::R_PPC64_ADDR16_HIGHESTA:
6297         case elfcpp::R_PPC64_REL64:
6298         case elfcpp::R_POWERPC_ADDR30:
6299         case elfcpp::R_PPC64_TPREL16_DS:
6300         case elfcpp::R_PPC64_TPREL16_LO_DS:
6301         case elfcpp::R_PPC64_TPREL16_HIGH:
6302         case elfcpp::R_PPC64_TPREL16_HIGHA:
6303         case elfcpp::R_PPC64_TPREL16_HIGHER:
6304         case elfcpp::R_PPC64_TPREL16_HIGHEST:
6305         case elfcpp::R_PPC64_TPREL16_HIGHERA:
6306         case elfcpp::R_PPC64_TPREL16_HIGHESTA:
6307           return;
6308
6309         default:
6310           break;
6311         }
6312     }
6313   else
6314     {
6315       switch (r_type)
6316         {
6317           // These are the relocation types supported only on 32-bit.
6318           // ??? glibc ld.so doesn't need to support these.
6319         case elfcpp::R_POWERPC_DTPREL16:
6320         case elfcpp::R_POWERPC_DTPREL16_LO:
6321         case elfcpp::R_POWERPC_DTPREL16_HI:
6322         case elfcpp::R_POWERPC_DTPREL16_HA:
6323           return;
6324
6325         default:
6326           break;
6327         }
6328     }
6329
6330   // This prevents us from issuing more than one error per reloc
6331   // section.  But we can still wind up issuing more than one
6332   // error per object file.
6333   if (this->issued_non_pic_error_)
6334     return;
6335   gold_assert(parameters->options().output_is_position_independent());
6336   object->error(_("requires unsupported dynamic reloc; "
6337                   "recompile with -fPIC"));
6338   this->issued_non_pic_error_ = true;
6339   return;
6340 }
6341
6342 // Return whether we need to make a PLT entry for a relocation of the
6343 // given type against a STT_GNU_IFUNC symbol.
6344
6345 template<int size, bool big_endian>
6346 bool
6347 Target_powerpc<size, big_endian>::Scan::reloc_needs_plt_for_ifunc(
6348      Target_powerpc<size, big_endian>* target,
6349      Sized_relobj_file<size, big_endian>* object,
6350      unsigned int r_type,
6351      bool report_err)
6352 {
6353   // In non-pic code any reference will resolve to the plt call stub
6354   // for the ifunc symbol.
6355   if ((size == 32 || target->abiversion() >= 2)
6356       && !parameters->options().output_is_position_independent())
6357     return true;
6358
6359   switch (r_type)
6360     {
6361     // Word size refs from data sections are OK, but don't need a PLT entry.
6362     case elfcpp::R_POWERPC_ADDR32:
6363     case elfcpp::R_POWERPC_UADDR32:
6364       if (size == 32)
6365         return false;
6366       break;
6367
6368     case elfcpp::R_PPC64_ADDR64:
6369     case elfcpp::R_PPC64_UADDR64:
6370       if (size == 64)
6371         return false;
6372       break;
6373
6374     // GOT refs are good, but also don't need a PLT entry.
6375     case elfcpp::R_POWERPC_GOT16:
6376     case elfcpp::R_POWERPC_GOT16_LO:
6377     case elfcpp::R_POWERPC_GOT16_HI:
6378     case elfcpp::R_POWERPC_GOT16_HA:
6379     case elfcpp::R_PPC64_GOT16_DS:
6380     case elfcpp::R_PPC64_GOT16_LO_DS:
6381       return false;
6382
6383     // Function calls are good, and these do need a PLT entry.
6384     case elfcpp::R_POWERPC_ADDR24:
6385     case elfcpp::R_POWERPC_ADDR14:
6386     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
6387     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
6388     case elfcpp::R_POWERPC_REL24:
6389     case elfcpp::R_PPC_PLTREL24:
6390     case elfcpp::R_POWERPC_REL14:
6391     case elfcpp::R_POWERPC_REL14_BRTAKEN:
6392     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
6393       return true;
6394
6395     default:
6396       break;
6397     }
6398
6399   // Anything else is a problem.
6400   // If we are building a static executable, the libc startup function
6401   // responsible for applying indirect function relocations is going
6402   // to complain about the reloc type.
6403   // If we are building a dynamic executable, we will have a text
6404   // relocation.  The dynamic loader will set the text segment
6405   // writable and non-executable to apply text relocations.  So we'll
6406   // segfault when trying to run the indirection function to resolve
6407   // the reloc.
6408   if (report_err)
6409     gold_error(_("%s: unsupported reloc %u for IFUNC symbol"),
6410                object->name().c_str(), r_type);
6411   return false;
6412 }
6413
6414 // Return TRUE iff INSN is one we expect on a _LO variety toc/got
6415 // reloc.
6416
6417 static bool
6418 ok_lo_toc_insn(uint32_t insn, unsigned int r_type)
6419 {
6420   return ((insn & (0x3f << 26)) == 12u << 26 /* addic */
6421           || (insn & (0x3f << 26)) == 14u << 26 /* addi */
6422           || (insn & (0x3f << 26)) == 32u << 26 /* lwz */
6423           || (insn & (0x3f << 26)) == 34u << 26 /* lbz */
6424           || (insn & (0x3f << 26)) == 36u << 26 /* stw */
6425           || (insn & (0x3f << 26)) == 38u << 26 /* stb */
6426           || (insn & (0x3f << 26)) == 40u << 26 /* lhz */
6427           || (insn & (0x3f << 26)) == 42u << 26 /* lha */
6428           || (insn & (0x3f << 26)) == 44u << 26 /* sth */
6429           || (insn & (0x3f << 26)) == 46u << 26 /* lmw */
6430           || (insn & (0x3f << 26)) == 47u << 26 /* stmw */
6431           || (insn & (0x3f << 26)) == 48u << 26 /* lfs */
6432           || (insn & (0x3f << 26)) == 50u << 26 /* lfd */
6433           || (insn & (0x3f << 26)) == 52u << 26 /* stfs */
6434           || (insn & (0x3f << 26)) == 54u << 26 /* stfd */
6435           || (insn & (0x3f << 26)) == 56u << 26 /* lq,lfq */
6436           || ((insn & (0x3f << 26)) == 57u << 26 /* lxsd,lxssp,lfdp */
6437               /* Exclude lfqu by testing reloc.  If relocs are ever
6438                  defined for the reduced D field in psq_lu then those
6439                  will need testing too.  */
6440               && r_type != elfcpp::R_PPC64_TOC16_LO
6441               && r_type != elfcpp::R_POWERPC_GOT16_LO)
6442           || ((insn & (0x3f << 26)) == 58u << 26 /* ld,lwa */
6443               && (insn & 1) == 0)
6444           || (insn & (0x3f << 26)) == 60u << 26 /* stfq */
6445           || ((insn & (0x3f << 26)) == 61u << 26 /* lxv,stx{v,sd,ssp},stfdp */
6446               /* Exclude stfqu.  psq_stu as above for psq_lu.  */
6447               && r_type != elfcpp::R_PPC64_TOC16_LO
6448               && r_type != elfcpp::R_POWERPC_GOT16_LO)
6449           || ((insn & (0x3f << 26)) == 62u << 26 /* std,stq */
6450               && (insn & 1) == 0));
6451 }
6452
6453 // Scan a relocation for a local symbol.
6454
6455 template<int size, bool big_endian>
6456 inline void
6457 Target_powerpc<size, big_endian>::Scan::local(
6458     Symbol_table* symtab,
6459     Layout* layout,
6460     Target_powerpc<size, big_endian>* target,
6461     Sized_relobj_file<size, big_endian>* object,
6462     unsigned int data_shndx,
6463     Output_section* output_section,
6464     const elfcpp::Rela<size, big_endian>& reloc,
6465     unsigned int r_type,
6466     const elfcpp::Sym<size, big_endian>& lsym,
6467     bool is_discarded)
6468 {
6469   this->maybe_skip_tls_get_addr_call(target, r_type, NULL);
6470
6471   if ((size == 64 && r_type == elfcpp::R_PPC64_TLSGD)
6472       || (size == 32 && r_type == elfcpp::R_PPC_TLSGD))
6473     {
6474       this->expect_tls_get_addr_call();
6475       const tls::Tls_optimization tls_type = target->optimize_tls_gd(true);
6476       if (tls_type != tls::TLSOPT_NONE)
6477         this->skip_next_tls_get_addr_call();
6478     }
6479   else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSLD)
6480            || (size == 32 && r_type == elfcpp::R_PPC_TLSLD))
6481     {
6482       this->expect_tls_get_addr_call();
6483       const tls::Tls_optimization tls_type = target->optimize_tls_ld();
6484       if (tls_type != tls::TLSOPT_NONE)
6485         this->skip_next_tls_get_addr_call();
6486     }
6487
6488   Powerpc_relobj<size, big_endian>* ppc_object
6489     = static_cast<Powerpc_relobj<size, big_endian>*>(object);
6490
6491   if (is_discarded)
6492     {
6493       if (size == 64
6494           && data_shndx == ppc_object->opd_shndx()
6495           && r_type == elfcpp::R_PPC64_ADDR64)
6496         ppc_object->set_opd_discard(reloc.get_r_offset());
6497       return;
6498     }
6499
6500   // A local STT_GNU_IFUNC symbol may require a PLT entry.
6501   bool is_ifunc = lsym.get_st_type() == elfcpp::STT_GNU_IFUNC;
6502   if (is_ifunc && this->reloc_needs_plt_for_ifunc(target, object, r_type, true))
6503     {
6504       unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6505       target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
6506                           r_type, r_sym, reloc.get_r_addend());
6507       target->make_local_ifunc_plt_entry(symtab, layout, object, r_sym);
6508     }
6509
6510   switch (r_type)
6511     {
6512     case elfcpp::R_POWERPC_NONE:
6513     case elfcpp::R_POWERPC_GNU_VTINHERIT:
6514     case elfcpp::R_POWERPC_GNU_VTENTRY:
6515     case elfcpp::R_POWERPC_TLS:
6516     case elfcpp::R_PPC64_ENTRY:
6517       break;
6518
6519     case elfcpp::R_PPC64_TOC:
6520       {
6521         Output_data_got_powerpc<size, big_endian>* got
6522           = target->got_section(symtab, layout);
6523         if (parameters->options().output_is_position_independent())
6524           {
6525             Address off = reloc.get_r_offset();
6526             if (size == 64
6527                 && target->abiversion() < 2
6528                 && data_shndx == ppc_object->opd_shndx()
6529                 && ppc_object->get_opd_discard(off - 8))
6530               break;
6531
6532             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6533             Powerpc_relobj<size, big_endian>* symobj = ppc_object;
6534             rela_dyn->add_output_section_relative(got->output_section(),
6535                                                   elfcpp::R_POWERPC_RELATIVE,
6536                                                   output_section,
6537                                                   object, data_shndx, off,
6538                                                   symobj->toc_base_offset());
6539           }
6540       }
6541       break;
6542
6543     case elfcpp::R_PPC64_ADDR64:
6544     case elfcpp::R_PPC64_UADDR64:
6545     case elfcpp::R_POWERPC_ADDR32:
6546     case elfcpp::R_POWERPC_UADDR32:
6547     case elfcpp::R_POWERPC_ADDR24:
6548     case elfcpp::R_POWERPC_ADDR16:
6549     case elfcpp::R_POWERPC_ADDR16_LO:
6550     case elfcpp::R_POWERPC_ADDR16_HI:
6551     case elfcpp::R_POWERPC_ADDR16_HA:
6552     case elfcpp::R_POWERPC_UADDR16:
6553     case elfcpp::R_PPC64_ADDR16_HIGH:
6554     case elfcpp::R_PPC64_ADDR16_HIGHA:
6555     case elfcpp::R_PPC64_ADDR16_HIGHER:
6556     case elfcpp::R_PPC64_ADDR16_HIGHERA:
6557     case elfcpp::R_PPC64_ADDR16_HIGHEST:
6558     case elfcpp::R_PPC64_ADDR16_HIGHESTA:
6559     case elfcpp::R_PPC64_ADDR16_DS:
6560     case elfcpp::R_PPC64_ADDR16_LO_DS:
6561     case elfcpp::R_POWERPC_ADDR14:
6562     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
6563     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
6564       // If building a shared library (or a position-independent
6565       // executable), we need to create a dynamic relocation for
6566       // this location.
6567       if (parameters->options().output_is_position_independent()
6568           || (size == 64 && is_ifunc && target->abiversion() < 2))
6569         {
6570           Reloc_section* rela_dyn = target->rela_dyn_section(symtab, layout,
6571                                                              is_ifunc);
6572           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6573           if ((size == 32 && r_type == elfcpp::R_POWERPC_ADDR32)
6574               || (size == 64 && r_type == elfcpp::R_PPC64_ADDR64))
6575             {
6576               unsigned int dynrel = (is_ifunc ? elfcpp::R_POWERPC_IRELATIVE
6577                                      : elfcpp::R_POWERPC_RELATIVE);
6578               rela_dyn->add_local_relative(object, r_sym, dynrel,
6579                                            output_section, data_shndx,
6580                                            reloc.get_r_offset(),
6581                                            reloc.get_r_addend(), false);
6582             }
6583           else if (lsym.get_st_type() != elfcpp::STT_SECTION)
6584             {
6585               check_non_pic(object, r_type);
6586               rela_dyn->add_local(object, r_sym, r_type, output_section,
6587                                   data_shndx, reloc.get_r_offset(),
6588                                   reloc.get_r_addend());
6589             }
6590           else
6591             {
6592               gold_assert(lsym.get_st_value() == 0);
6593               unsigned int shndx = lsym.get_st_shndx();
6594               bool is_ordinary;
6595               shndx = object->adjust_sym_shndx(r_sym, shndx,
6596                                                &is_ordinary);
6597               if (!is_ordinary)
6598                 object->error(_("section symbol %u has bad shndx %u"),
6599                               r_sym, shndx);
6600               else
6601                 rela_dyn->add_local_section(object, shndx, r_type,
6602                                             output_section, data_shndx,
6603                                             reloc.get_r_offset());
6604             }
6605         }
6606       break;
6607
6608     case elfcpp::R_POWERPC_REL24:
6609     case elfcpp::R_PPC_PLTREL24:
6610     case elfcpp::R_PPC_LOCAL24PC:
6611     case elfcpp::R_POWERPC_REL14:
6612     case elfcpp::R_POWERPC_REL14_BRTAKEN:
6613     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
6614       if (!is_ifunc)
6615         {
6616           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6617           target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
6618                               r_type, r_sym, reloc.get_r_addend());
6619         }
6620       break;
6621
6622     case elfcpp::R_PPC64_TOCSAVE:
6623       // R_PPC64_TOCSAVE follows a call instruction to indicate the
6624       // caller has already saved r2 and thus a plt call stub need not
6625       // save r2.
6626       if (size == 64
6627           && target->mark_pltcall(ppc_object, data_shndx,
6628                                   reloc.get_r_offset() - 4, symtab))
6629         {
6630           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6631           unsigned int shndx = lsym.get_st_shndx();
6632           bool is_ordinary;
6633           shndx = object->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
6634           if (!is_ordinary)
6635             object->error(_("tocsave symbol %u has bad shndx %u"),
6636                           r_sym, shndx);
6637           else
6638             target->add_tocsave(ppc_object, shndx,
6639                                 lsym.get_st_value() + reloc.get_r_addend());
6640         }
6641       break;
6642
6643     case elfcpp::R_PPC64_REL64:
6644     case elfcpp::R_POWERPC_REL32:
6645     case elfcpp::R_POWERPC_REL16:
6646     case elfcpp::R_POWERPC_REL16_LO:
6647     case elfcpp::R_POWERPC_REL16_HI:
6648     case elfcpp::R_POWERPC_REL16_HA:
6649     case elfcpp::R_POWERPC_REL16DX_HA:
6650     case elfcpp::R_POWERPC_SECTOFF:
6651     case elfcpp::R_POWERPC_SECTOFF_LO:
6652     case elfcpp::R_POWERPC_SECTOFF_HI:
6653     case elfcpp::R_POWERPC_SECTOFF_HA:
6654     case elfcpp::R_PPC64_SECTOFF_DS:
6655     case elfcpp::R_PPC64_SECTOFF_LO_DS:
6656     case elfcpp::R_POWERPC_TPREL16:
6657     case elfcpp::R_POWERPC_TPREL16_LO:
6658     case elfcpp::R_POWERPC_TPREL16_HI:
6659     case elfcpp::R_POWERPC_TPREL16_HA:
6660     case elfcpp::R_PPC64_TPREL16_DS:
6661     case elfcpp::R_PPC64_TPREL16_LO_DS:
6662     case elfcpp::R_PPC64_TPREL16_HIGH:
6663     case elfcpp::R_PPC64_TPREL16_HIGHA:
6664     case elfcpp::R_PPC64_TPREL16_HIGHER:
6665     case elfcpp::R_PPC64_TPREL16_HIGHERA:
6666     case elfcpp::R_PPC64_TPREL16_HIGHEST:
6667     case elfcpp::R_PPC64_TPREL16_HIGHESTA:
6668     case elfcpp::R_POWERPC_DTPREL16:
6669     case elfcpp::R_POWERPC_DTPREL16_LO:
6670     case elfcpp::R_POWERPC_DTPREL16_HI:
6671     case elfcpp::R_POWERPC_DTPREL16_HA:
6672     case elfcpp::R_PPC64_DTPREL16_DS:
6673     case elfcpp::R_PPC64_DTPREL16_LO_DS:
6674     case elfcpp::R_PPC64_DTPREL16_HIGH:
6675     case elfcpp::R_PPC64_DTPREL16_HIGHA:
6676     case elfcpp::R_PPC64_DTPREL16_HIGHER:
6677     case elfcpp::R_PPC64_DTPREL16_HIGHERA:
6678     case elfcpp::R_PPC64_DTPREL16_HIGHEST:
6679     case elfcpp::R_PPC64_DTPREL16_HIGHESTA:
6680     case elfcpp::R_PPC64_TLSGD:
6681     case elfcpp::R_PPC64_TLSLD:
6682     case elfcpp::R_PPC64_ADDR64_LOCAL:
6683       break;
6684
6685     case elfcpp::R_POWERPC_GOT16:
6686     case elfcpp::R_POWERPC_GOT16_LO:
6687     case elfcpp::R_POWERPC_GOT16_HI:
6688     case elfcpp::R_POWERPC_GOT16_HA:
6689     case elfcpp::R_PPC64_GOT16_DS:
6690     case elfcpp::R_PPC64_GOT16_LO_DS:
6691       {
6692         // The symbol requires a GOT entry.
6693         Output_data_got_powerpc<size, big_endian>* got
6694           = target->got_section(symtab, layout);
6695         unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6696
6697         if (!parameters->options().output_is_position_independent())
6698           {
6699             if (is_ifunc
6700                 && (size == 32 || target->abiversion() >= 2))
6701               got->add_local_plt(object, r_sym, GOT_TYPE_STANDARD);
6702             else
6703               got->add_local(object, r_sym, GOT_TYPE_STANDARD);
6704           }
6705         else if (!object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD))
6706           {
6707             // If we are generating a shared object or a pie, this
6708             // symbol's GOT entry will be set by a dynamic relocation.
6709             unsigned int off;
6710             off = got->add_constant(0);
6711             object->set_local_got_offset(r_sym, GOT_TYPE_STANDARD, off);
6712
6713             Reloc_section* rela_dyn = target->rela_dyn_section(symtab, layout,
6714                                                                is_ifunc);
6715             unsigned int dynrel = (is_ifunc ? elfcpp::R_POWERPC_IRELATIVE
6716                                    : elfcpp::R_POWERPC_RELATIVE);
6717             rela_dyn->add_local_relative(object, r_sym, dynrel,
6718                                          got, off, 0, false);
6719           }
6720       }
6721       break;
6722
6723     case elfcpp::R_PPC64_TOC16:
6724     case elfcpp::R_PPC64_TOC16_LO:
6725     case elfcpp::R_PPC64_TOC16_HI:
6726     case elfcpp::R_PPC64_TOC16_HA:
6727     case elfcpp::R_PPC64_TOC16_DS:
6728     case elfcpp::R_PPC64_TOC16_LO_DS:
6729       // We need a GOT section.
6730       target->got_section(symtab, layout);
6731       break;
6732
6733     case elfcpp::R_POWERPC_GOT_TLSGD16:
6734     case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
6735     case elfcpp::R_POWERPC_GOT_TLSGD16_HI:
6736     case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
6737       {
6738         const tls::Tls_optimization tls_type = target->optimize_tls_gd(true);
6739         if (tls_type == tls::TLSOPT_NONE)
6740           {
6741             Output_data_got_powerpc<size, big_endian>* got
6742               = target->got_section(symtab, layout);
6743             unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6744             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6745             got->add_local_tls_pair(object, r_sym, GOT_TYPE_TLSGD,
6746                                     rela_dyn, elfcpp::R_POWERPC_DTPMOD);
6747           }
6748         else if (tls_type == tls::TLSOPT_TO_LE)
6749           {
6750             // no GOT relocs needed for Local Exec.
6751           }
6752         else
6753           gold_unreachable();
6754       }
6755       break;
6756
6757     case elfcpp::R_POWERPC_GOT_TLSLD16:
6758     case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
6759     case elfcpp::R_POWERPC_GOT_TLSLD16_HI:
6760     case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
6761       {
6762         const tls::Tls_optimization tls_type = target->optimize_tls_ld();
6763         if (tls_type == tls::TLSOPT_NONE)
6764           target->tlsld_got_offset(symtab, layout, object);
6765         else if (tls_type == tls::TLSOPT_TO_LE)
6766           {
6767             // no GOT relocs needed for Local Exec.
6768             if (parameters->options().emit_relocs())
6769               {
6770                 Output_section* os = layout->tls_segment()->first_section();
6771                 gold_assert(os != NULL);
6772                 os->set_needs_symtab_index();
6773               }
6774           }
6775         else
6776           gold_unreachable();
6777       }
6778       break;
6779
6780     case elfcpp::R_POWERPC_GOT_DTPREL16:
6781     case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
6782     case elfcpp::R_POWERPC_GOT_DTPREL16_HI:
6783     case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
6784       {
6785         Output_data_got_powerpc<size, big_endian>* got
6786           = target->got_section(symtab, layout);
6787         unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6788         got->add_local_tls(object, r_sym, GOT_TYPE_DTPREL);
6789       }
6790       break;
6791
6792     case elfcpp::R_POWERPC_GOT_TPREL16:
6793     case elfcpp::R_POWERPC_GOT_TPREL16_LO:
6794     case elfcpp::R_POWERPC_GOT_TPREL16_HI:
6795     case elfcpp::R_POWERPC_GOT_TPREL16_HA:
6796       {
6797         const tls::Tls_optimization tls_type = target->optimize_tls_ie(true);
6798         if (tls_type == tls::TLSOPT_NONE)
6799           {
6800             unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6801             if (!object->local_has_got_offset(r_sym, GOT_TYPE_TPREL))
6802               {
6803                 Output_data_got_powerpc<size, big_endian>* got
6804                   = target->got_section(symtab, layout);
6805                 unsigned int off = got->add_constant(0);
6806                 object->set_local_got_offset(r_sym, GOT_TYPE_TPREL, off);
6807
6808                 Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6809                 rela_dyn->add_symbolless_local_addend(object, r_sym,
6810                                                       elfcpp::R_POWERPC_TPREL,
6811                                                       got, off, 0);
6812               }
6813           }
6814         else if (tls_type == tls::TLSOPT_TO_LE)
6815           {
6816             // no GOT relocs needed for Local Exec.
6817           }
6818         else
6819           gold_unreachable();
6820       }
6821       break;
6822
6823     default:
6824       unsupported_reloc_local(object, r_type);
6825       break;
6826     }
6827
6828   if (size == 64
6829       && parameters->options().toc_optimize())
6830     {
6831       if (data_shndx == ppc_object->toc_shndx())
6832         {
6833           bool ok = true;
6834           if (r_type != elfcpp::R_PPC64_ADDR64
6835               || (is_ifunc && target->abiversion() < 2))
6836             ok = false;
6837           else if (parameters->options().output_is_position_independent())
6838             {
6839               if (is_ifunc)
6840                 ok = false;
6841               else
6842                 {
6843                   unsigned int shndx = lsym.get_st_shndx();
6844                   if (shndx >= elfcpp::SHN_LORESERVE
6845                       && shndx != elfcpp::SHN_XINDEX)
6846                     ok = false;
6847                 }
6848             }
6849           if (!ok)
6850             ppc_object->set_no_toc_opt(reloc.get_r_offset());
6851         }
6852
6853       enum {no_check, check_lo, check_ha} insn_check;
6854       switch (r_type)
6855         {
6856         default:
6857           insn_check = no_check;
6858           break;
6859
6860         case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
6861         case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
6862         case elfcpp::R_POWERPC_GOT_TPREL16_HA:
6863         case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
6864         case elfcpp::R_POWERPC_GOT16_HA:
6865         case elfcpp::R_PPC64_TOC16_HA:
6866           insn_check = check_ha;
6867           break;
6868
6869         case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
6870         case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
6871         case elfcpp::R_POWERPC_GOT_TPREL16_LO:
6872         case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
6873         case elfcpp::R_POWERPC_GOT16_LO:
6874         case elfcpp::R_PPC64_GOT16_LO_DS:
6875         case elfcpp::R_PPC64_TOC16_LO:
6876         case elfcpp::R_PPC64_TOC16_LO_DS:
6877           insn_check = check_lo;
6878           break;
6879         }
6880
6881       section_size_type slen;
6882       const unsigned char* view = NULL;
6883       if (insn_check != no_check)
6884         {
6885           view = ppc_object->section_contents(data_shndx, &slen, false);
6886           section_size_type off =
6887             convert_to_section_size_type(reloc.get_r_offset()) & -4;
6888           if (off < slen)
6889             {
6890               uint32_t insn = elfcpp::Swap<32, big_endian>::readval(view + off);
6891               if (insn_check == check_lo
6892                   ? !ok_lo_toc_insn(insn, r_type)
6893                   : ((insn & ((0x3f << 26) | 0x1f << 16))
6894                      != ((15u << 26) | (2 << 16)) /* addis rt,2,imm */))
6895                 {
6896                   ppc_object->set_no_toc_opt();
6897                   gold_warning(_("%s: toc optimization is not supported "
6898                                  "for %#08x instruction"),
6899                                ppc_object->name().c_str(), insn);
6900                 }
6901             }
6902         }
6903
6904       switch (r_type)
6905         {
6906         default:
6907           break;
6908         case elfcpp::R_PPC64_TOC16:
6909         case elfcpp::R_PPC64_TOC16_LO:
6910         case elfcpp::R_PPC64_TOC16_HI:
6911         case elfcpp::R_PPC64_TOC16_HA:
6912         case elfcpp::R_PPC64_TOC16_DS:
6913         case elfcpp::R_PPC64_TOC16_LO_DS:
6914           unsigned int shndx = lsym.get_st_shndx();
6915           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6916           bool is_ordinary;
6917           shndx = ppc_object->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
6918           if (is_ordinary && shndx == ppc_object->toc_shndx())
6919             {
6920               Address dst_off = lsym.get_st_value() + reloc.get_r_addend();
6921               if (dst_off < ppc_object->section_size(shndx))
6922                 {
6923                   bool ok = false;
6924                   if (r_type == elfcpp::R_PPC64_TOC16_HA)
6925                     ok = true;
6926                   else if (r_type == elfcpp::R_PPC64_TOC16_LO_DS)
6927                     {
6928                       // Need to check that the insn is a ld
6929                       if (!view)
6930                         view = ppc_object->section_contents(data_shndx,
6931                                                             &slen,
6932                                                             false);
6933                       section_size_type off =
6934                         (convert_to_section_size_type(reloc.get_r_offset())
6935                          + (big_endian ? -2 : 3));
6936                       if (off < slen
6937                           && (view[off] & (0x3f << 2)) == 58u << 2)
6938                         ok = true;
6939                     }
6940                   if (!ok)
6941                     ppc_object->set_no_toc_opt(dst_off);
6942                 }
6943             }
6944           break;
6945         }
6946     }
6947
6948   if (size == 32)
6949     {
6950       switch (r_type)
6951         {
6952         case elfcpp::R_POWERPC_REL32:
6953           if (ppc_object->got2_shndx() != 0
6954               && parameters->options().output_is_position_independent())
6955             {
6956               unsigned int shndx = lsym.get_st_shndx();
6957               unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6958               bool is_ordinary;
6959               shndx = ppc_object->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
6960               if (is_ordinary && shndx == ppc_object->got2_shndx()
6961                   && (ppc_object->section_flags(data_shndx)
6962                       & elfcpp::SHF_EXECINSTR) != 0)
6963                 gold_error(_("%s: unsupported -mbss-plt code"),
6964                            ppc_object->name().c_str());
6965             }
6966           break;
6967         default:
6968           break;
6969         }
6970     }
6971
6972   switch (r_type)
6973     {
6974     case elfcpp::R_POWERPC_GOT_TLSLD16:
6975     case elfcpp::R_POWERPC_GOT_TLSGD16:
6976     case elfcpp::R_POWERPC_GOT_TPREL16:
6977     case elfcpp::R_POWERPC_GOT_DTPREL16:
6978     case elfcpp::R_POWERPC_GOT16:
6979     case elfcpp::R_PPC64_GOT16_DS:
6980     case elfcpp::R_PPC64_TOC16:
6981     case elfcpp::R_PPC64_TOC16_DS:
6982       ppc_object->set_has_small_toc_reloc();
6983     default:
6984       break;
6985     }
6986 }
6987
6988 // Report an unsupported relocation against a global symbol.
6989
6990 template<int size, bool big_endian>
6991 void
6992 Target_powerpc<size, big_endian>::Scan::unsupported_reloc_global(
6993     Sized_relobj_file<size, big_endian>* object,
6994     unsigned int r_type,
6995     Symbol* gsym)
6996 {
6997   gold_error(_("%s: unsupported reloc %u against global symbol %s"),
6998              object->name().c_str(), r_type, gsym->demangled_name().c_str());
6999 }
7000
7001 // Scan a relocation for a global symbol.
7002
7003 template<int size, bool big_endian>
7004 inline void
7005 Target_powerpc<size, big_endian>::Scan::global(
7006     Symbol_table* symtab,
7007     Layout* layout,
7008     Target_powerpc<size, big_endian>* target,
7009     Sized_relobj_file<size, big_endian>* object,
7010     unsigned int data_shndx,
7011     Output_section* output_section,
7012     const elfcpp::Rela<size, big_endian>& reloc,
7013     unsigned int r_type,
7014     Symbol* gsym)
7015 {
7016   if (this->maybe_skip_tls_get_addr_call(target, r_type, gsym)
7017       == Track_tls::SKIP)
7018     return;
7019
7020   if (target->replace_tls_get_addr(gsym))
7021     // Change a __tls_get_addr reference to __tls_get_addr_opt
7022     // so dynamic relocs are emitted against the latter symbol.
7023     gsym = target->tls_get_addr_opt();
7024
7025   if ((size == 64 && r_type == elfcpp::R_PPC64_TLSGD)
7026       || (size == 32 && r_type == elfcpp::R_PPC_TLSGD))
7027     {
7028       this->expect_tls_get_addr_call();
7029       const bool final = gsym->final_value_is_known();
7030       const tls::Tls_optimization tls_type = target->optimize_tls_gd(final);
7031       if (tls_type != tls::TLSOPT_NONE)
7032         this->skip_next_tls_get_addr_call();
7033     }
7034   else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSLD)
7035            || (size == 32 && r_type == elfcpp::R_PPC_TLSLD))
7036     {
7037       this->expect_tls_get_addr_call();
7038       const tls::Tls_optimization tls_type = target->optimize_tls_ld();
7039       if (tls_type != tls::TLSOPT_NONE)
7040         this->skip_next_tls_get_addr_call();
7041     }
7042
7043   Powerpc_relobj<size, big_endian>* ppc_object
7044     = static_cast<Powerpc_relobj<size, big_endian>*>(object);
7045
7046   // A STT_GNU_IFUNC symbol may require a PLT entry.
7047   bool is_ifunc = gsym->type() == elfcpp::STT_GNU_IFUNC;
7048   bool pushed_ifunc = false;
7049   if (is_ifunc && this->reloc_needs_plt_for_ifunc(target, object, r_type, true))
7050     {
7051       unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
7052       target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
7053                           r_type, r_sym, reloc.get_r_addend());
7054       target->make_plt_entry(symtab, layout, gsym);
7055       pushed_ifunc = true;
7056     }
7057
7058   switch (r_type)
7059     {
7060     case elfcpp::R_POWERPC_NONE:
7061     case elfcpp::R_POWERPC_GNU_VTINHERIT:
7062     case elfcpp::R_POWERPC_GNU_VTENTRY:
7063     case elfcpp::R_PPC_LOCAL24PC:
7064     case elfcpp::R_POWERPC_TLS:
7065     case elfcpp::R_PPC64_ENTRY:
7066       break;
7067
7068     case elfcpp::R_PPC64_TOC:
7069       {
7070         Output_data_got_powerpc<size, big_endian>* got
7071           = target->got_section(symtab, layout);
7072         if (parameters->options().output_is_position_independent())
7073           {
7074             Address off = reloc.get_r_offset();
7075             if (size == 64
7076                 && data_shndx == ppc_object->opd_shndx()
7077                 && ppc_object->get_opd_discard(off - 8))
7078               break;
7079
7080             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
7081             Powerpc_relobj<size, big_endian>* symobj = ppc_object;
7082             if (data_shndx != ppc_object->opd_shndx())
7083               symobj = static_cast
7084                 <Powerpc_relobj<size, big_endian>*>(gsym->object());
7085             rela_dyn->add_output_section_relative(got->output_section(),
7086                                                   elfcpp::R_POWERPC_RELATIVE,
7087                                                   output_section,
7088                                                   object, data_shndx, off,
7089                                                   symobj->toc_base_offset());
7090           }
7091       }
7092       break;
7093
7094     case elfcpp::R_PPC64_ADDR64:
7095       if (size == 64
7096           && target->abiversion() < 2
7097           && data_shndx == ppc_object->opd_shndx()
7098           && (gsym->is_defined_in_discarded_section()
7099               || gsym->object() != object))
7100         {
7101           ppc_object->set_opd_discard(reloc.get_r_offset());
7102           break;
7103         }
7104       // Fall through.
7105     case elfcpp::R_PPC64_UADDR64:
7106     case elfcpp::R_POWERPC_ADDR32:
7107     case elfcpp::R_POWERPC_UADDR32:
7108     case elfcpp::R_POWERPC_ADDR24:
7109     case elfcpp::R_POWERPC_ADDR16:
7110     case elfcpp::R_POWERPC_ADDR16_LO:
7111     case elfcpp::R_POWERPC_ADDR16_HI:
7112     case elfcpp::R_POWERPC_ADDR16_HA:
7113     case elfcpp::R_POWERPC_UADDR16:
7114     case elfcpp::R_PPC64_ADDR16_HIGH:
7115     case elfcpp::R_PPC64_ADDR16_HIGHA:
7116     case elfcpp::R_PPC64_ADDR16_HIGHER:
7117     case elfcpp::R_PPC64_ADDR16_HIGHERA:
7118     case elfcpp::R_PPC64_ADDR16_HIGHEST:
7119     case elfcpp::R_PPC64_ADDR16_HIGHESTA:
7120     case elfcpp::R_PPC64_ADDR16_DS:
7121     case elfcpp::R_PPC64_ADDR16_LO_DS:
7122     case elfcpp::R_POWERPC_ADDR14:
7123     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
7124     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
7125       {
7126         // Make a PLT entry if necessary.
7127         if (gsym->needs_plt_entry())
7128           {
7129             // Since this is not a PC-relative relocation, we may be
7130             // taking the address of a function. In that case we need to
7131             // set the entry in the dynamic symbol table to the address of
7132             // the PLT call stub.
7133             bool need_ifunc_plt = false;
7134             if ((size == 32 || target->abiversion() >= 2)
7135                 && gsym->is_from_dynobj()
7136                 && !parameters->options().output_is_position_independent())
7137               {
7138                 gsym->set_needs_dynsym_value();
7139                 need_ifunc_plt = true;
7140               }
7141             if (!is_ifunc || (!pushed_ifunc && need_ifunc_plt))
7142               {
7143                 unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
7144                 target->push_branch(ppc_object, data_shndx,
7145                                     reloc.get_r_offset(), r_type, r_sym,
7146                                     reloc.get_r_addend());
7147                 target->make_plt_entry(symtab, layout, gsym);
7148               }
7149           }
7150         // Make a dynamic relocation if necessary.
7151         if (gsym->needs_dynamic_reloc(Scan::get_reference_flags(r_type, target))
7152             || (size == 64 && is_ifunc && target->abiversion() < 2))
7153           {
7154             if (!parameters->options().output_is_position_independent()
7155                 && gsym->may_need_copy_reloc())
7156               {
7157                 target->copy_reloc(symtab, layout, object,
7158                                    data_shndx, output_section, gsym, reloc);
7159               }
7160             else if ((((size == 32
7161                         && r_type == elfcpp::R_POWERPC_ADDR32)
7162                        || (size == 64
7163                            && r_type == elfcpp::R_PPC64_ADDR64
7164                            && target->abiversion() >= 2))
7165                       && gsym->can_use_relative_reloc(false)
7166                       && !(gsym->visibility() == elfcpp::STV_PROTECTED
7167                            && parameters->options().shared()))
7168                      || (size == 64
7169                          && r_type == elfcpp::R_PPC64_ADDR64
7170                          && target->abiversion() < 2
7171                          && (gsym->can_use_relative_reloc(false)
7172                              || data_shndx == ppc_object->opd_shndx())))
7173               {
7174                 Reloc_section* rela_dyn
7175                   = target->rela_dyn_section(symtab, layout, is_ifunc);
7176                 unsigned int dynrel = (is_ifunc ? elfcpp::R_POWERPC_IRELATIVE
7177                                        : elfcpp::R_POWERPC_RELATIVE);
7178                 rela_dyn->add_symbolless_global_addend(
7179                     gsym, dynrel, output_section, object, data_shndx,
7180                     reloc.get_r_offset(), reloc.get_r_addend());
7181               }
7182             else
7183               {
7184                 Reloc_section* rela_dyn
7185                   = target->rela_dyn_section(symtab, layout, is_ifunc);
7186                 check_non_pic(object, r_type);
7187                 rela_dyn->add_global(gsym, r_type, output_section,
7188                                      object, data_shndx,
7189                                      reloc.get_r_offset(),
7190                                      reloc.get_r_addend());
7191
7192                 if (size == 64
7193                     && parameters->options().toc_optimize()
7194                     && data_shndx == ppc_object->toc_shndx())
7195                   ppc_object->set_no_toc_opt(reloc.get_r_offset());
7196               }
7197           }
7198       }
7199       break;
7200
7201     case elfcpp::R_PPC_PLTREL24:
7202     case elfcpp::R_POWERPC_REL24:
7203       if (!is_ifunc)
7204         {
7205           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
7206           target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
7207                               r_type, r_sym, reloc.get_r_addend());
7208           if (gsym->needs_plt_entry()
7209               || (!gsym->final_value_is_known()
7210                   && (gsym->is_undefined()
7211                       || gsym->is_from_dynobj()
7212                       || gsym->is_preemptible())))
7213             target->make_plt_entry(symtab, layout, gsym);
7214         }
7215       // Fall through.
7216
7217     case elfcpp::R_PPC64_REL64:
7218     case elfcpp::R_POWERPC_REL32:
7219       // Make a dynamic relocation if necessary.
7220       if (gsym->needs_dynamic_reloc(Scan::get_reference_flags(r_type, target)))
7221         {
7222           if (!parameters->options().output_is_position_independent()
7223               && gsym->may_need_copy_reloc())
7224             {
7225               target->copy_reloc(symtab, layout, object,
7226                                  data_shndx, output_section, gsym,
7227                                  reloc);
7228             }
7229           else
7230             {
7231               Reloc_section* rela_dyn
7232                 = target->rela_dyn_section(symtab, layout, is_ifunc);
7233               check_non_pic(object, r_type);
7234               rela_dyn->add_global(gsym, r_type, output_section, object,
7235                                    data_shndx, reloc.get_r_offset(),
7236                                    reloc.get_r_addend());
7237             }
7238         }
7239       break;
7240
7241     case elfcpp::R_POWERPC_REL14:
7242     case elfcpp::R_POWERPC_REL14_BRTAKEN:
7243     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
7244       if (!is_ifunc)
7245         {
7246           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
7247           target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
7248                               r_type, r_sym, reloc.get_r_addend());
7249         }
7250       break;
7251
7252     case elfcpp::R_PPC64_TOCSAVE:
7253       // R_PPC64_TOCSAVE follows a call instruction to indicate the
7254       // caller has already saved r2 and thus a plt call stub need not
7255       // save r2.
7256       if (size == 64
7257           && target->mark_pltcall(ppc_object, data_shndx,
7258                                   reloc.get_r_offset() - 4, symtab))
7259         {
7260           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
7261           bool is_ordinary;
7262           unsigned int shndx = gsym->shndx(&is_ordinary);
7263           if (!is_ordinary)
7264             object->error(_("tocsave symbol %u has bad shndx %u"),
7265                           r_sym, shndx);
7266           else
7267             {
7268               Sized_symbol<size>* sym = symtab->get_sized_symbol<size>(gsym);
7269               target->add_tocsave(ppc_object, shndx,
7270                                   sym->value() + reloc.get_r_addend());
7271             }
7272         }
7273       break;
7274
7275     case elfcpp::R_POWERPC_REL16:
7276     case elfcpp::R_POWERPC_REL16_LO:
7277     case elfcpp::R_POWERPC_REL16_HI:
7278     case elfcpp::R_POWERPC_REL16_HA:
7279     case elfcpp::R_POWERPC_REL16DX_HA:
7280     case elfcpp::R_POWERPC_SECTOFF:
7281     case elfcpp::R_POWERPC_SECTOFF_LO:
7282     case elfcpp::R_POWERPC_SECTOFF_HI:
7283     case elfcpp::R_POWERPC_SECTOFF_HA:
7284     case elfcpp::R_PPC64_SECTOFF_DS:
7285     case elfcpp::R_PPC64_SECTOFF_LO_DS:
7286     case elfcpp::R_POWERPC_TPREL16:
7287     case elfcpp::R_POWERPC_TPREL16_LO:
7288     case elfcpp::R_POWERPC_TPREL16_HI:
7289     case elfcpp::R_POWERPC_TPREL16_HA:
7290     case elfcpp::R_PPC64_TPREL16_DS:
7291     case elfcpp::R_PPC64_TPREL16_LO_DS:
7292     case elfcpp::R_PPC64_TPREL16_HIGH:
7293     case elfcpp::R_PPC64_TPREL16_HIGHA:
7294     case elfcpp::R_PPC64_TPREL16_HIGHER:
7295     case elfcpp::R_PPC64_TPREL16_HIGHERA:
7296     case elfcpp::R_PPC64_TPREL16_HIGHEST:
7297     case elfcpp::R_PPC64_TPREL16_HIGHESTA:
7298     case elfcpp::R_POWERPC_DTPREL16:
7299     case elfcpp::R_POWERPC_DTPREL16_LO:
7300     case elfcpp::R_POWERPC_DTPREL16_HI:
7301     case elfcpp::R_POWERPC_DTPREL16_HA:
7302     case elfcpp::R_PPC64_DTPREL16_DS:
7303     case elfcpp::R_PPC64_DTPREL16_LO_DS:
7304     case elfcpp::R_PPC64_DTPREL16_HIGH:
7305     case elfcpp::R_PPC64_DTPREL16_HIGHA:
7306     case elfcpp::R_PPC64_DTPREL16_HIGHER:
7307     case elfcpp::R_PPC64_DTPREL16_HIGHERA:
7308     case elfcpp::R_PPC64_DTPREL16_HIGHEST:
7309     case elfcpp::R_PPC64_DTPREL16_HIGHESTA:
7310     case elfcpp::R_PPC64_TLSGD:
7311     case elfcpp::R_PPC64_TLSLD:
7312     case elfcpp::R_PPC64_ADDR64_LOCAL:
7313       break;
7314
7315     case elfcpp::R_POWERPC_GOT16:
7316     case elfcpp::R_POWERPC_GOT16_LO:
7317     case elfcpp::R_POWERPC_GOT16_HI:
7318     case elfcpp::R_POWERPC_GOT16_HA:
7319     case elfcpp::R_PPC64_GOT16_DS:
7320     case elfcpp::R_PPC64_GOT16_LO_DS:
7321       {
7322         // The symbol requires a GOT entry.
7323         Output_data_got_powerpc<size, big_endian>* got;
7324
7325         got = target->got_section(symtab, layout);
7326         if (gsym->final_value_is_known())
7327           {
7328             if (is_ifunc
7329                 && (size == 32 || target->abiversion() >= 2))
7330               got->add_global_plt(gsym, GOT_TYPE_STANDARD);
7331             else
7332               got->add_global(gsym, GOT_TYPE_STANDARD);
7333           }
7334         else if (!gsym->has_got_offset(GOT_TYPE_STANDARD))
7335           {
7336             // If we are generating a shared object or a pie, this
7337             // symbol's GOT entry will be set by a dynamic relocation.
7338             unsigned int off = got->add_constant(0);
7339             gsym->set_got_offset(GOT_TYPE_STANDARD, off);
7340
7341             Reloc_section* rela_dyn
7342               = target->rela_dyn_section(symtab, layout, is_ifunc);
7343
7344             if (gsym->can_use_relative_reloc(false)
7345                 && !((size == 32
7346                       || target->abiversion() >= 2)
7347                      && gsym->visibility() == elfcpp::STV_PROTECTED
7348                      && parameters->options().shared()))
7349               {
7350                 unsigned int dynrel = (is_ifunc ? elfcpp::R_POWERPC_IRELATIVE
7351                                        : elfcpp::R_POWERPC_RELATIVE);
7352                 rela_dyn->add_global_relative(gsym, dynrel, got, off, 0, false);
7353               }
7354             else
7355               {
7356                 unsigned int dynrel = elfcpp::R_POWERPC_GLOB_DAT;
7357                 rela_dyn->add_global(gsym, dynrel, got, off, 0);
7358               }
7359           }
7360       }
7361       break;
7362
7363     case elfcpp::R_PPC64_TOC16:
7364     case elfcpp::R_PPC64_TOC16_LO:
7365     case elfcpp::R_PPC64_TOC16_HI:
7366     case elfcpp::R_PPC64_TOC16_HA:
7367     case elfcpp::R_PPC64_TOC16_DS:
7368     case elfcpp::R_PPC64_TOC16_LO_DS:
7369       // We need a GOT section.
7370       target->got_section(symtab, layout);
7371       break;
7372
7373     case elfcpp::R_POWERPC_GOT_TLSGD16:
7374     case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
7375     case elfcpp::R_POWERPC_GOT_TLSGD16_HI:
7376     case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
7377       {
7378         const bool final = gsym->final_value_is_known();
7379         const tls::Tls_optimization tls_type = target->optimize_tls_gd(final);
7380         if (tls_type == tls::TLSOPT_NONE)
7381           {
7382             Output_data_got_powerpc<size, big_endian>* got
7383               = target->got_section(symtab, layout);
7384             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
7385             got->add_global_pair_with_rel(gsym, GOT_TYPE_TLSGD, rela_dyn,
7386                                           elfcpp::R_POWERPC_DTPMOD,
7387                                           elfcpp::R_POWERPC_DTPREL);
7388           }
7389         else if (tls_type == tls::TLSOPT_TO_IE)
7390           {
7391             if (!gsym->has_got_offset(GOT_TYPE_TPREL))
7392               {
7393                 Output_data_got_powerpc<size, big_endian>* got
7394                   = target->got_section(symtab, layout);
7395                 Reloc_section* rela_dyn = target->rela_dyn_section(layout);
7396                 if (gsym->is_undefined()
7397                     || gsym->is_from_dynobj())
7398                   {
7399                     got->add_global_with_rel(gsym, GOT_TYPE_TPREL, rela_dyn,
7400                                              elfcpp::R_POWERPC_TPREL);
7401                   }
7402                 else
7403                   {
7404                     unsigned int off = got->add_constant(0);
7405                     gsym->set_got_offset(GOT_TYPE_TPREL, off);
7406                     unsigned int dynrel = elfcpp::R_POWERPC_TPREL;
7407                     rela_dyn->add_symbolless_global_addend(gsym, dynrel,
7408                                                            got, off, 0);
7409                   }
7410               }
7411           }
7412         else if (tls_type == tls::TLSOPT_TO_LE)
7413           {
7414             // no GOT relocs needed for Local Exec.
7415           }
7416         else
7417           gold_unreachable();
7418       }
7419       break;
7420
7421     case elfcpp::R_POWERPC_GOT_TLSLD16:
7422     case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
7423     case elfcpp::R_POWERPC_GOT_TLSLD16_HI:
7424     case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
7425       {
7426         const tls::Tls_optimization tls_type = target->optimize_tls_ld();
7427         if (tls_type == tls::TLSOPT_NONE)
7428           target->tlsld_got_offset(symtab, layout, object);
7429         else if (tls_type == tls::TLSOPT_TO_LE)
7430           {
7431             // no GOT relocs needed for Local Exec.
7432             if (parameters->options().emit_relocs())
7433               {
7434                 Output_section* os = layout->tls_segment()->first_section();
7435                 gold_assert(os != NULL);
7436                 os->set_needs_symtab_index();
7437               }
7438           }
7439         else
7440           gold_unreachable();
7441       }
7442       break;
7443
7444     case elfcpp::R_POWERPC_GOT_DTPREL16:
7445     case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
7446     case elfcpp::R_POWERPC_GOT_DTPREL16_HI:
7447     case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
7448       {
7449         Output_data_got_powerpc<size, big_endian>* got
7450           = target->got_section(symtab, layout);
7451         if (!gsym->final_value_is_known()
7452             && (gsym->is_from_dynobj()
7453                 || gsym->is_undefined()
7454                 || gsym->is_preemptible()))
7455           got->add_global_with_rel(gsym, GOT_TYPE_DTPREL,
7456                                    target->rela_dyn_section(layout),
7457                                    elfcpp::R_POWERPC_DTPREL);
7458         else
7459           got->add_global_tls(gsym, GOT_TYPE_DTPREL);
7460       }
7461       break;
7462
7463     case elfcpp::R_POWERPC_GOT_TPREL16:
7464     case elfcpp::R_POWERPC_GOT_TPREL16_LO:
7465     case elfcpp::R_POWERPC_GOT_TPREL16_HI:
7466     case elfcpp::R_POWERPC_GOT_TPREL16_HA:
7467       {
7468         const bool final = gsym->final_value_is_known();
7469         const tls::Tls_optimization tls_type = target->optimize_tls_ie(final);
7470         if (tls_type == tls::TLSOPT_NONE)
7471           {
7472             if (!gsym->has_got_offset(GOT_TYPE_TPREL))
7473               {
7474                 Output_data_got_powerpc<size, big_endian>* got
7475                   = target->got_section(symtab, layout);
7476                 Reloc_section* rela_dyn = target->rela_dyn_section(layout);
7477                 if (gsym->is_undefined()
7478                     || gsym->is_from_dynobj())
7479                   {
7480                     got->add_global_with_rel(gsym, GOT_TYPE_TPREL, rela_dyn,
7481                                              elfcpp::R_POWERPC_TPREL);
7482                   }
7483                 else
7484                   {
7485                     unsigned int off = got->add_constant(0);
7486                     gsym->set_got_offset(GOT_TYPE_TPREL, off);
7487                     unsigned int dynrel = elfcpp::R_POWERPC_TPREL;
7488                     rela_dyn->add_symbolless_global_addend(gsym, dynrel,
7489                                                            got, off, 0);
7490                   }
7491               }
7492           }
7493         else if (tls_type == tls::TLSOPT_TO_LE)
7494           {
7495             // no GOT relocs needed for Local Exec.
7496           }
7497         else
7498           gold_unreachable();
7499       }
7500       break;
7501
7502     default:
7503       unsupported_reloc_global(object, r_type, gsym);
7504       break;
7505     }
7506
7507   if (size == 64
7508       && parameters->options().toc_optimize())
7509     {
7510       if (data_shndx == ppc_object->toc_shndx())
7511         {
7512           bool ok = true;
7513           if (r_type != elfcpp::R_PPC64_ADDR64
7514               || (is_ifunc && target->abiversion() < 2))
7515             ok = false;
7516           else if (parameters->options().output_is_position_independent()
7517                    && (is_ifunc || gsym->is_absolute() || gsym->is_undefined()))
7518             ok = false;
7519           if (!ok)
7520             ppc_object->set_no_toc_opt(reloc.get_r_offset());
7521         }
7522
7523       enum {no_check, check_lo, check_ha} insn_check;
7524       switch (r_type)
7525         {
7526         default:
7527           insn_check = no_check;
7528           break;
7529
7530         case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
7531         case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
7532         case elfcpp::R_POWERPC_GOT_TPREL16_HA:
7533         case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
7534         case elfcpp::R_POWERPC_GOT16_HA:
7535         case elfcpp::R_PPC64_TOC16_HA:
7536           insn_check = check_ha;
7537           break;
7538
7539         case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
7540         case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
7541         case elfcpp::R_POWERPC_GOT_TPREL16_LO:
7542         case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
7543         case elfcpp::R_POWERPC_GOT16_LO:
7544         case elfcpp::R_PPC64_GOT16_LO_DS:
7545         case elfcpp::R_PPC64_TOC16_LO:
7546         case elfcpp::R_PPC64_TOC16_LO_DS:
7547           insn_check = check_lo;
7548           break;
7549         }
7550
7551       section_size_type slen;
7552       const unsigned char* view = NULL;
7553       if (insn_check != no_check)
7554         {
7555           view = ppc_object->section_contents(data_shndx, &slen, false);
7556           section_size_type off =
7557             convert_to_section_size_type(reloc.get_r_offset()) & -4;
7558           if (off < slen)
7559             {
7560               uint32_t insn = elfcpp::Swap<32, big_endian>::readval(view + off);
7561               if (insn_check == check_lo
7562                   ? !ok_lo_toc_insn(insn, r_type)
7563                   : ((insn & ((0x3f << 26) | 0x1f << 16))
7564                      != ((15u << 26) | (2 << 16)) /* addis rt,2,imm */))
7565                 {
7566                   ppc_object->set_no_toc_opt();
7567                   gold_warning(_("%s: toc optimization is not supported "
7568                                  "for %#08x instruction"),
7569                                ppc_object->name().c_str(), insn);
7570                 }
7571             }
7572         }
7573
7574       switch (r_type)
7575         {
7576         default:
7577           break;
7578         case elfcpp::R_PPC64_TOC16:
7579         case elfcpp::R_PPC64_TOC16_LO:
7580         case elfcpp::R_PPC64_TOC16_HI:
7581         case elfcpp::R_PPC64_TOC16_HA:
7582         case elfcpp::R_PPC64_TOC16_DS:
7583         case elfcpp::R_PPC64_TOC16_LO_DS:
7584           if (gsym->source() == Symbol::FROM_OBJECT
7585               && !gsym->object()->is_dynamic())
7586             {
7587               Powerpc_relobj<size, big_endian>* sym_object
7588                 = static_cast<Powerpc_relobj<size, big_endian>*>(gsym->object());
7589               bool is_ordinary;
7590               unsigned int shndx = gsym->shndx(&is_ordinary);
7591               if (shndx == sym_object->toc_shndx())
7592                 {
7593                   Sized_symbol<size>* sym = symtab->get_sized_symbol<size>(gsym);
7594                   Address dst_off = sym->value() + reloc.get_r_addend();
7595                   if (dst_off < sym_object->section_size(shndx))
7596                     {
7597                       bool ok = false;
7598                       if (r_type == elfcpp::R_PPC64_TOC16_HA)
7599                         ok = true;
7600                       else if (r_type == elfcpp::R_PPC64_TOC16_LO_DS)
7601                         {
7602                           // Need to check that the insn is a ld
7603                           if (!view)
7604                             view = ppc_object->section_contents(data_shndx,
7605                                                                 &slen,
7606                                                                 false);
7607                           section_size_type off =
7608                             (convert_to_section_size_type(reloc.get_r_offset())
7609                              + (big_endian ? -2 : 3));
7610                           if (off < slen
7611                               && (view[off] & (0x3f << 2)) == (58u << 2))
7612                             ok = true;
7613                         }
7614                       if (!ok)
7615                         sym_object->set_no_toc_opt(dst_off);
7616                     }
7617                 }
7618             }
7619           break;
7620         }
7621     }
7622
7623   if (size == 32)
7624     {
7625       switch (r_type)
7626         {
7627         case elfcpp::R_PPC_LOCAL24PC:
7628           if (strcmp(gsym->name(), "_GLOBAL_OFFSET_TABLE_") == 0)
7629             gold_error(_("%s: unsupported -mbss-plt code"),
7630                        ppc_object->name().c_str());
7631           break;
7632         default:
7633           break;
7634         }
7635     }
7636
7637   switch (r_type)
7638     {
7639     case elfcpp::R_POWERPC_GOT_TLSLD16:
7640     case elfcpp::R_POWERPC_GOT_TLSGD16:
7641     case elfcpp::R_POWERPC_GOT_TPREL16:
7642     case elfcpp::R_POWERPC_GOT_DTPREL16:
7643     case elfcpp::R_POWERPC_GOT16:
7644     case elfcpp::R_PPC64_GOT16_DS:
7645     case elfcpp::R_PPC64_TOC16:
7646     case elfcpp::R_PPC64_TOC16_DS:
7647       ppc_object->set_has_small_toc_reloc();
7648     default:
7649       break;
7650     }
7651 }
7652
7653 // Process relocations for gc.
7654
7655 template<int size, bool big_endian>
7656 void
7657 Target_powerpc<size, big_endian>::gc_process_relocs(
7658     Symbol_table* symtab,
7659     Layout* layout,
7660     Sized_relobj_file<size, big_endian>* object,
7661     unsigned int data_shndx,
7662     unsigned int,
7663     const unsigned char* prelocs,
7664     size_t reloc_count,
7665     Output_section* output_section,
7666     bool needs_special_offset_handling,
7667     size_t local_symbol_count,
7668     const unsigned char* plocal_symbols)
7669 {
7670   typedef Target_powerpc<size, big_endian> Powerpc;
7671   typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
7672       Classify_reloc;
7673
7674   Powerpc_relobj<size, big_endian>* ppc_object
7675     = static_cast<Powerpc_relobj<size, big_endian>*>(object);
7676   if (size == 64)
7677     ppc_object->set_opd_valid();
7678   if (size == 64 && data_shndx == ppc_object->opd_shndx())
7679     {
7680       typename Powerpc_relobj<size, big_endian>::Access_from::iterator p;
7681       for (p = ppc_object->access_from_map()->begin();
7682            p != ppc_object->access_from_map()->end();
7683            ++p)
7684         {
7685           Address dst_off = p->first;
7686           unsigned int dst_indx = ppc_object->get_opd_ent(dst_off);
7687           typename Powerpc_relobj<size, big_endian>::Section_refs::iterator s;
7688           for (s = p->second.begin(); s != p->second.end(); ++s)
7689             {
7690               Relobj* src_obj = s->first;
7691               unsigned int src_indx = s->second;
7692               symtab->gc()->add_reference(src_obj, src_indx,
7693                                           ppc_object, dst_indx);
7694             }
7695           p->second.clear();
7696         }
7697       ppc_object->access_from_map()->clear();
7698       ppc_object->process_gc_mark(symtab);
7699       // Don't look at .opd relocs as .opd will reference everything.
7700       return;
7701     }
7702
7703   gold::gc_process_relocs<size, big_endian, Powerpc, Scan, Classify_reloc>(
7704     symtab,
7705     layout,
7706     this,
7707     object,
7708     data_shndx,
7709     prelocs,
7710     reloc_count,
7711     output_section,
7712     needs_special_offset_handling,
7713     local_symbol_count,
7714     plocal_symbols);
7715 }
7716
7717 // Handle target specific gc actions when adding a gc reference from
7718 // SRC_OBJ, SRC_SHNDX to a location specified by DST_OBJ, DST_SHNDX
7719 // and DST_OFF.  For powerpc64, this adds a referenc to the code
7720 // section of a function descriptor.
7721
7722 template<int size, bool big_endian>
7723 void
7724 Target_powerpc<size, big_endian>::do_gc_add_reference(
7725     Symbol_table* symtab,
7726     Relobj* src_obj,
7727     unsigned int src_shndx,
7728     Relobj* dst_obj,
7729     unsigned int dst_shndx,
7730     Address dst_off) const
7731 {
7732   if (size != 64 || dst_obj->is_dynamic())
7733     return;
7734
7735   Powerpc_relobj<size, big_endian>* ppc_object
7736     = static_cast<Powerpc_relobj<size, big_endian>*>(dst_obj);
7737   if (dst_shndx != 0 && dst_shndx == ppc_object->opd_shndx())
7738     {
7739       if (ppc_object->opd_valid())
7740         {
7741           dst_shndx = ppc_object->get_opd_ent(dst_off);
7742           symtab->gc()->add_reference(src_obj, src_shndx, dst_obj, dst_shndx);
7743         }
7744       else
7745         {
7746           // If we haven't run scan_opd_relocs, we must delay
7747           // processing this function descriptor reference.
7748           ppc_object->add_reference(src_obj, src_shndx, dst_off);
7749         }
7750     }
7751 }
7752
7753 // Add any special sections for this symbol to the gc work list.
7754 // For powerpc64, this adds the code section of a function
7755 // descriptor.
7756
7757 template<int size, bool big_endian>
7758 void
7759 Target_powerpc<size, big_endian>::do_gc_mark_symbol(
7760     Symbol_table* symtab,
7761     Symbol* sym) const
7762 {
7763   if (size == 64)
7764     {
7765       Powerpc_relobj<size, big_endian>* ppc_object
7766         = static_cast<Powerpc_relobj<size, big_endian>*>(sym->object());
7767       bool is_ordinary;
7768       unsigned int shndx = sym->shndx(&is_ordinary);
7769       if (is_ordinary && shndx != 0 && shndx == ppc_object->opd_shndx())
7770         {
7771           Sized_symbol<size>* gsym = symtab->get_sized_symbol<size>(sym);
7772           Address dst_off = gsym->value();
7773           if (ppc_object->opd_valid())
7774             {
7775               unsigned int dst_indx = ppc_object->get_opd_ent(dst_off);
7776               symtab->gc()->worklist().push_back(Section_id(ppc_object,
7777                                                             dst_indx));
7778             }
7779           else
7780             ppc_object->add_gc_mark(dst_off);
7781         }
7782     }
7783 }
7784
7785 // For a symbol location in .opd, set LOC to the location of the
7786 // function entry.
7787
7788 template<int size, bool big_endian>
7789 void
7790 Target_powerpc<size, big_endian>::do_function_location(
7791     Symbol_location* loc) const
7792 {
7793   if (size == 64 && loc->shndx != 0)
7794     {
7795       if (loc->object->is_dynamic())
7796         {
7797           Powerpc_dynobj<size, big_endian>* ppc_object
7798             = static_cast<Powerpc_dynobj<size, big_endian>*>(loc->object);
7799           if (loc->shndx == ppc_object->opd_shndx())
7800             {
7801               Address dest_off;
7802               Address off = loc->offset - ppc_object->opd_address();
7803               loc->shndx = ppc_object->get_opd_ent(off, &dest_off);
7804               loc->offset = dest_off;
7805             }
7806         }
7807       else
7808         {
7809           const Powerpc_relobj<size, big_endian>* ppc_object
7810             = static_cast<const Powerpc_relobj<size, big_endian>*>(loc->object);
7811           if (loc->shndx == ppc_object->opd_shndx())
7812             {
7813               Address dest_off;
7814               loc->shndx = ppc_object->get_opd_ent(loc->offset, &dest_off);
7815               loc->offset = dest_off;
7816             }
7817         }
7818     }
7819 }
7820
7821 // FNOFFSET in section SHNDX in OBJECT is the start of a function
7822 // compiled with -fsplit-stack.  The function calls non-split-stack
7823 // code.  Change the function to ensure it has enough stack space to
7824 // call some random function.
7825
7826 template<int size, bool big_endian>
7827 void
7828 Target_powerpc<size, big_endian>::do_calls_non_split(
7829     Relobj* object,
7830     unsigned int shndx,
7831     section_offset_type fnoffset,
7832     section_size_type fnsize,
7833     const unsigned char* prelocs,
7834     size_t reloc_count,
7835     unsigned char* view,
7836     section_size_type view_size,
7837     std::string* from,
7838     std::string* to) const
7839 {
7840   // 32-bit not supported.
7841   if (size == 32)
7842     {
7843       // warn
7844       Target::do_calls_non_split(object, shndx, fnoffset, fnsize,
7845                                  prelocs, reloc_count, view, view_size,
7846                                  from, to);
7847       return;
7848     }
7849
7850   // The function always starts with
7851   //    ld %r0,-0x7000-64(%r13)  # tcbhead_t.__private_ss
7852   //    addis %r12,%r1,-allocate@ha
7853   //    addi %r12,%r12,-allocate@l
7854   //    cmpld %r12,%r0
7855   // but note that the addis or addi may be replaced with a nop
7856
7857   unsigned char *entry = view + fnoffset;
7858   uint32_t insn = elfcpp::Swap<32, big_endian>::readval(entry);
7859
7860   if ((insn & 0xffff0000) == addis_2_12)
7861     {
7862       /* Skip ELFv2 global entry code.  */
7863       entry += 8;
7864       insn = elfcpp::Swap<32, big_endian>::readval(entry);
7865     }
7866
7867   unsigned char *pinsn = entry;
7868   bool ok = false;
7869   const uint32_t ld_private_ss = 0xe80d8fc0;
7870   if (insn == ld_private_ss)
7871     {
7872       int32_t allocate = 0;
7873       while (1)
7874         {
7875           pinsn += 4;
7876           insn = elfcpp::Swap<32, big_endian>::readval(pinsn);
7877           if ((insn & 0xffff0000) == addis_12_1)
7878             allocate += (insn & 0xffff) << 16;
7879           else if ((insn & 0xffff0000) == addi_12_1
7880                    || (insn & 0xffff0000) == addi_12_12)
7881             allocate += ((insn & 0xffff) ^ 0x8000) - 0x8000;
7882           else if (insn != nop)
7883             break;
7884         }
7885       if (insn == cmpld_7_12_0 && pinsn == entry + 12)
7886         {
7887           int extra = parameters->options().split_stack_adjust_size();
7888           allocate -= extra;
7889           if (allocate >= 0 || extra < 0)
7890             {
7891               object->error(_("split-stack stack size overflow at "
7892                               "section %u offset %0zx"),
7893                             shndx, static_cast<size_t>(fnoffset));
7894               return;
7895             }
7896           pinsn = entry + 4;
7897           insn = addis_12_1 | (((allocate + 0x8000) >> 16) & 0xffff);
7898           if (insn != addis_12_1)
7899             {
7900               elfcpp::Swap<32, big_endian>::writeval(pinsn, insn);
7901               pinsn += 4;
7902               insn = addi_12_12 | (allocate & 0xffff);
7903               if (insn != addi_12_12)
7904                 {
7905                   elfcpp::Swap<32, big_endian>::writeval(pinsn, insn);
7906                   pinsn += 4;
7907                 }
7908             }
7909           else
7910             {
7911               insn = addi_12_1 | (allocate & 0xffff);
7912               elfcpp::Swap<32, big_endian>::writeval(pinsn, insn);
7913               pinsn += 4;
7914             }
7915           if (pinsn != entry + 12)
7916             elfcpp::Swap<32, big_endian>::writeval(pinsn, nop);
7917
7918           ok = true;
7919         }
7920     }
7921
7922   if (!ok)
7923     {
7924       if (!object->has_no_split_stack())
7925         object->error(_("failed to match split-stack sequence at "
7926                         "section %u offset %0zx"),
7927                       shndx, static_cast<size_t>(fnoffset));
7928     }
7929 }
7930
7931 // Scan relocations for a section.
7932
7933 template<int size, bool big_endian>
7934 void
7935 Target_powerpc<size, big_endian>::scan_relocs(
7936     Symbol_table* symtab,
7937     Layout* layout,
7938     Sized_relobj_file<size, big_endian>* object,
7939     unsigned int data_shndx,
7940     unsigned int sh_type,
7941     const unsigned char* prelocs,
7942     size_t reloc_count,
7943     Output_section* output_section,
7944     bool needs_special_offset_handling,
7945     size_t local_symbol_count,
7946     const unsigned char* plocal_symbols)
7947 {
7948   typedef Target_powerpc<size, big_endian> Powerpc;
7949   typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
7950       Classify_reloc;
7951
7952   if (!this->plt_localentry0_init_)
7953     {
7954       bool plt_localentry0 = false;
7955       if (size == 64
7956           && this->abiversion() >= 2)
7957         {
7958           if (parameters->options().user_set_plt_localentry())
7959             plt_localentry0 = parameters->options().plt_localentry();
7960           if (plt_localentry0
7961               && symtab->lookup("GLIBC_2.26", NULL) == NULL)
7962             gold_warning(_("--plt-localentry is especially dangerous without "
7963                            "ld.so support to detect ABI violations"));
7964         }
7965       this->plt_localentry0_ = plt_localentry0;
7966       this->plt_localentry0_init_ = true;
7967     }
7968
7969   if (sh_type == elfcpp::SHT_REL)
7970     {
7971       gold_error(_("%s: unsupported REL reloc section"),
7972                  object->name().c_str());
7973       return;
7974     }
7975
7976   gold::scan_relocs<size, big_endian, Powerpc, Scan, Classify_reloc>(
7977     symtab,
7978     layout,
7979     this,
7980     object,
7981     data_shndx,
7982     prelocs,
7983     reloc_count,
7984     output_section,
7985     needs_special_offset_handling,
7986     local_symbol_count,
7987     plocal_symbols);
7988 }
7989
7990 // Functor class for processing the global symbol table.
7991 // Removes symbols defined on discarded opd entries.
7992
7993 template<bool big_endian>
7994 class Global_symbol_visitor_opd
7995 {
7996  public:
7997   Global_symbol_visitor_opd()
7998   { }
7999
8000   void
8001   operator()(Sized_symbol<64>* sym)
8002   {
8003     if (sym->has_symtab_index()
8004         || sym->source() != Symbol::FROM_OBJECT
8005         || !sym->in_real_elf())
8006       return;
8007
8008     if (sym->object()->is_dynamic())
8009       return;
8010
8011     Powerpc_relobj<64, big_endian>* symobj
8012       = static_cast<Powerpc_relobj<64, big_endian>*>(sym->object());
8013     if (symobj->opd_shndx() == 0)
8014       return;
8015
8016     bool is_ordinary;
8017     unsigned int shndx = sym->shndx(&is_ordinary);
8018     if (shndx == symobj->opd_shndx()
8019         && symobj->get_opd_discard(sym->value()))
8020       {
8021         sym->set_undefined();
8022         sym->set_visibility(elfcpp::STV_DEFAULT);
8023         sym->set_is_defined_in_discarded_section();
8024         sym->set_symtab_index(-1U);
8025       }
8026   }
8027 };
8028
8029 template<int size, bool big_endian>
8030 void
8031 Target_powerpc<size, big_endian>::define_save_restore_funcs(
8032     Layout* layout,
8033     Symbol_table* symtab)
8034 {
8035   if (size == 64)
8036     {
8037       Output_data_save_res<size, big_endian>* savres
8038         = new Output_data_save_res<size, big_endian>(symtab);
8039       this->savres_section_ = savres;
8040       layout->add_output_section_data(".text", elfcpp::SHT_PROGBITS,
8041                                       elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR,
8042                                       savres, ORDER_TEXT, false);
8043     }
8044 }
8045
8046 // Sort linker created .got section first (for the header), then input
8047 // sections belonging to files using small model code.
8048
8049 template<bool big_endian>
8050 class Sort_toc_sections
8051 {
8052  public:
8053   bool
8054   operator()(const Output_section::Input_section& is1,
8055              const Output_section::Input_section& is2) const
8056   {
8057     if (!is1.is_input_section() && is2.is_input_section())
8058       return true;
8059     bool small1
8060       = (is1.is_input_section()
8061          && (static_cast<const Powerpc_relobj<64, big_endian>*>(is1.relobj())
8062              ->has_small_toc_reloc()));
8063     bool small2
8064       = (is2.is_input_section()
8065          && (static_cast<const Powerpc_relobj<64, big_endian>*>(is2.relobj())
8066              ->has_small_toc_reloc()));
8067     return small1 && !small2;
8068   }
8069 };
8070
8071 // Finalize the sections.
8072
8073 template<int size, bool big_endian>
8074 void
8075 Target_powerpc<size, big_endian>::do_finalize_sections(
8076     Layout* layout,
8077     const Input_objects*,
8078     Symbol_table* symtab)
8079 {
8080   if (parameters->doing_static_link())
8081     {
8082       // At least some versions of glibc elf-init.o have a strong
8083       // reference to __rela_iplt marker syms.  A weak ref would be
8084       // better..
8085       if (this->iplt_ != NULL)
8086         {
8087           Reloc_section* rel = this->iplt_->rel_plt();
8088           symtab->define_in_output_data("__rela_iplt_start", NULL,
8089                                         Symbol_table::PREDEFINED, rel, 0, 0,
8090                                         elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
8091                                         elfcpp::STV_HIDDEN, 0, false, true);
8092           symtab->define_in_output_data("__rela_iplt_end", NULL,
8093                                         Symbol_table::PREDEFINED, rel, 0, 0,
8094                                         elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
8095                                         elfcpp::STV_HIDDEN, 0, true, true);
8096         }
8097       else
8098         {
8099           symtab->define_as_constant("__rela_iplt_start", NULL,
8100                                      Symbol_table::PREDEFINED, 0, 0,
8101                                      elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
8102                                      elfcpp::STV_HIDDEN, 0, true, false);
8103           symtab->define_as_constant("__rela_iplt_end", NULL,
8104                                      Symbol_table::PREDEFINED, 0, 0,
8105                                      elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
8106                                      elfcpp::STV_HIDDEN, 0, true, false);
8107         }
8108     }
8109
8110   if (size == 64)
8111     {
8112       typedef Global_symbol_visitor_opd<big_endian> Symbol_visitor;
8113       symtab->for_all_symbols<64, Symbol_visitor>(Symbol_visitor());
8114
8115       if (!parameters->options().relocatable())
8116         {
8117           this->define_save_restore_funcs(layout, symtab);
8118
8119           // Annoyingly, we need to make these sections now whether or
8120           // not we need them.  If we delay until do_relax then we
8121           // need to mess with the relaxation machinery checkpointing.
8122           this->got_section(symtab, layout);
8123           this->make_brlt_section(layout);
8124
8125           if (parameters->options().toc_sort())
8126             {
8127               Output_section* os = this->got_->output_section();
8128               if (os != NULL && os->input_sections().size() > 1)
8129                 std::stable_sort(os->input_sections().begin(),
8130                                  os->input_sections().end(),
8131                                  Sort_toc_sections<big_endian>());
8132             }
8133         }
8134     }
8135
8136   // Fill in some more dynamic tags.
8137   Output_data_dynamic* odyn = layout->dynamic_data();
8138   if (odyn != NULL)
8139     {
8140       const Reloc_section* rel_plt = (this->plt_ == NULL
8141                                       ? NULL
8142                                       : this->plt_->rel_plt());
8143       layout->add_target_dynamic_tags(false, this->plt_, rel_plt,
8144                                       this->rela_dyn_, true, size == 32);
8145
8146       if (size == 32)
8147         {
8148           if (this->got_ != NULL)
8149             {
8150               this->got_->finalize_data_size();
8151               odyn->add_section_plus_offset(elfcpp::DT_PPC_GOT,
8152                                             this->got_, this->got_->g_o_t());
8153             }
8154           if (this->has_tls_get_addr_opt_)
8155             odyn->add_constant(elfcpp::DT_PPC_OPT, elfcpp::PPC_OPT_TLS);
8156         }
8157       else
8158         {
8159           if (this->glink_ != NULL)
8160             {
8161               this->glink_->finalize_data_size();
8162               odyn->add_section_plus_offset(elfcpp::DT_PPC64_GLINK,
8163                                             this->glink_,
8164                                             (this->glink_->pltresolve_size
8165                                              - 32));
8166             }
8167           if (this->has_localentry0_ || this->has_tls_get_addr_opt_)
8168             odyn->add_constant(elfcpp::DT_PPC64_OPT,
8169                                ((this->has_localentry0_
8170                                  ? elfcpp::PPC64_OPT_LOCALENTRY : 0)
8171                                 | (this->has_tls_get_addr_opt_
8172                                    ? elfcpp::PPC64_OPT_TLS : 0)));
8173         }
8174     }
8175
8176   // Emit any relocs we saved in an attempt to avoid generating COPY
8177   // relocs.
8178   if (this->copy_relocs_.any_saved_relocs())
8179     this->copy_relocs_.emit(this->rela_dyn_section(layout));
8180 }
8181
8182 // Emit any saved relocs, and mark toc entries using any of these
8183 // relocs as not optimizable.
8184
8185 template<int sh_type, int size, bool big_endian>
8186 void
8187 Powerpc_copy_relocs<sh_type, size, big_endian>::emit(
8188     Output_data_reloc<sh_type, true, size, big_endian>* reloc_section)
8189 {
8190   if (size == 64
8191       && parameters->options().toc_optimize())
8192     {
8193       for (typename Copy_relocs<sh_type, size, big_endian>::
8194              Copy_reloc_entries::iterator p = this->entries_.begin();
8195            p != this->entries_.end();
8196            ++p)
8197         {
8198           typename Copy_relocs<sh_type, size, big_endian>::Copy_reloc_entry&
8199             entry = *p;
8200
8201           // If the symbol is no longer defined in a dynamic object,
8202           // then we emitted a COPY relocation.  If it is still
8203           // dynamic then we'll need dynamic relocations and thus
8204           // can't optimize toc entries.
8205           if (entry.sym_->is_from_dynobj())
8206             {
8207               Powerpc_relobj<size, big_endian>* ppc_object
8208                 = static_cast<Powerpc_relobj<size, big_endian>*>(entry.relobj_);
8209               if (entry.shndx_ == ppc_object->toc_shndx())
8210                 ppc_object->set_no_toc_opt(entry.address_);
8211             }
8212         }
8213     }
8214
8215   Copy_relocs<sh_type, size, big_endian>::emit(reloc_section);
8216 }
8217
8218 // Return the value to use for a branch relocation.
8219
8220 template<int size, bool big_endian>
8221 bool
8222 Target_powerpc<size, big_endian>::symval_for_branch(
8223     const Symbol_table* symtab,
8224     const Sized_symbol<size>* gsym,
8225     Powerpc_relobj<size, big_endian>* object,
8226     Address *value,
8227     unsigned int *dest_shndx)
8228 {
8229   if (size == 32 || this->abiversion() >= 2)
8230     gold_unreachable();
8231   *dest_shndx = 0;
8232
8233   // If the symbol is defined in an opd section, ie. is a function
8234   // descriptor, use the function descriptor code entry address
8235   Powerpc_relobj<size, big_endian>* symobj = object;
8236   if (gsym != NULL
8237       && (gsym->source() != Symbol::FROM_OBJECT
8238           || gsym->object()->is_dynamic()))
8239     return true;
8240   if (gsym != NULL)
8241     symobj = static_cast<Powerpc_relobj<size, big_endian>*>(gsym->object());
8242   unsigned int shndx = symobj->opd_shndx();
8243   if (shndx == 0)
8244     return true;
8245   Address opd_addr = symobj->get_output_section_offset(shndx);
8246   if (opd_addr == invalid_address)
8247     return true;
8248   opd_addr += symobj->output_section_address(shndx);
8249   if (*value >= opd_addr && *value < opd_addr + symobj->section_size(shndx))
8250     {
8251       Address sec_off;
8252       *dest_shndx = symobj->get_opd_ent(*value - opd_addr, &sec_off);
8253       if (symtab->is_section_folded(symobj, *dest_shndx))
8254         {
8255           Section_id folded
8256             = symtab->icf()->get_folded_section(symobj, *dest_shndx);
8257           symobj = static_cast<Powerpc_relobj<size, big_endian>*>(folded.first);
8258           *dest_shndx = folded.second;
8259         }
8260       Address sec_addr = symobj->get_output_section_offset(*dest_shndx);
8261       if (sec_addr == invalid_address)
8262         return false;
8263
8264       sec_addr += symobj->output_section(*dest_shndx)->address();
8265       *value = sec_addr + sec_off;
8266     }
8267   return true;
8268 }
8269
8270 // Perform a relocation.
8271
8272 template<int size, bool big_endian>
8273 inline bool
8274 Target_powerpc<size, big_endian>::Relocate::relocate(
8275     const Relocate_info<size, big_endian>* relinfo,
8276     unsigned int,
8277     Target_powerpc* target,
8278     Output_section* os,
8279     size_t relnum,
8280     const unsigned char* preloc,
8281     const Sized_symbol<size>* gsym,
8282     const Symbol_value<size>* psymval,
8283     unsigned char* view,
8284     Address address,
8285     section_size_type view_size)
8286 {
8287   if (view == NULL)
8288     return true;
8289
8290   if (target->replace_tls_get_addr(gsym))
8291     gsym = static_cast<const Sized_symbol<size>*>(target->tls_get_addr_opt());
8292
8293   const elfcpp::Rela<size, big_endian> rela(preloc);
8294   unsigned int r_type = elfcpp::elf_r_type<size>(rela.get_r_info());
8295   switch (this->maybe_skip_tls_get_addr_call(target, r_type, gsym))
8296     {
8297     case Track_tls::NOT_EXPECTED:
8298       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
8299                              _("__tls_get_addr call lacks marker reloc"));
8300       break;
8301     case Track_tls::EXPECTED:
8302       // We have already complained.
8303       break;
8304     case Track_tls::SKIP:
8305       return true;
8306     case Track_tls::NORMAL:
8307       break;
8308     }
8309
8310   typedef Powerpc_relocate_functions<size, big_endian> Reloc;
8311   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insn;
8312   typedef typename elfcpp::Rela<size, big_endian> Reltype;
8313   // Offset from start of insn to d-field reloc.
8314   const int d_offset = big_endian ? 2 : 0;
8315
8316   Powerpc_relobj<size, big_endian>* const object
8317     = static_cast<Powerpc_relobj<size, big_endian>*>(relinfo->object);
8318   Address value = 0;
8319   bool has_stub_value = false;
8320   bool localentry0 = false;
8321   unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
8322   if ((gsym != NULL
8323        ? gsym->use_plt_offset(Scan::get_reference_flags(r_type, target))
8324        : object->local_has_plt_offset(r_sym))
8325       && (!psymval->is_ifunc_symbol()
8326           || Scan::reloc_needs_plt_for_ifunc(target, object, r_type, false)))
8327     {
8328       if (size == 64
8329           && gsym != NULL
8330           && target->abiversion() >= 2
8331           && !parameters->options().output_is_position_independent()
8332           && !is_branch_reloc(r_type))
8333         {
8334           Address off = target->glink_section()->find_global_entry(gsym);
8335           if (off != invalid_address)
8336             {
8337               value = target->glink_section()->global_entry_address() + off;
8338               has_stub_value = true;
8339             }
8340         }
8341       else
8342         {
8343           Stub_table<size, big_endian>* stub_table = NULL;
8344           if (target->stub_tables().size() == 1)
8345             stub_table = target->stub_tables()[0];
8346           if (stub_table == NULL
8347               && !(size == 32
8348                    && gsym != NULL
8349                    && !parameters->options().output_is_position_independent()
8350                    && !is_branch_reloc(r_type)))
8351             stub_table = object->stub_table(relinfo->data_shndx);
8352           if (stub_table == NULL)
8353             {
8354               // This is a ref from a data section to an ifunc symbol,
8355               // or a non-branch reloc for which we always want to use
8356               // one set of stubs for resolving function addresses.
8357               if (target->stub_tables().size() != 0)
8358                 stub_table = target->stub_tables()[0];
8359             }
8360           if (stub_table != NULL)
8361             {
8362               const typename Stub_table<size, big_endian>::Plt_stub_ent* ent;
8363               if (gsym != NULL)
8364                 ent = stub_table->find_plt_call_entry(object, gsym, r_type,
8365                                                       rela.get_r_addend());
8366               else
8367                 ent = stub_table->find_plt_call_entry(object, r_sym, r_type,
8368                                                       rela.get_r_addend());
8369               if (ent != NULL)
8370                 {
8371                   value = stub_table->stub_address() + ent->off_;
8372                   const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
8373                   elfcpp::Shdr<size, big_endian> shdr(relinfo->reloc_shdr);
8374                   size_t reloc_count = shdr.get_sh_size() / reloc_size;
8375                   if (size == 64
8376                       && ent->r2save_
8377                       && relnum + 1 < reloc_count)
8378                     {
8379                       Reltype next_rela(preloc + reloc_size);
8380                       if (elfcpp::elf_r_type<size>(next_rela.get_r_info())
8381                           == elfcpp::R_PPC64_TOCSAVE
8382                           && next_rela.get_r_offset() == rela.get_r_offset() + 4)
8383                         value += 4;
8384                     }
8385                   localentry0 = ent->localentry0_;
8386                   has_stub_value = true;
8387                 }
8388             }
8389         }
8390       // We don't care too much about bogus debug references to
8391       // non-local functions, but otherwise there had better be a plt
8392       // call stub or global entry stub as appropriate.
8393       gold_assert(has_stub_value || !(os->flags() & elfcpp::SHF_ALLOC));
8394     }
8395
8396   if (r_type == elfcpp::R_POWERPC_GOT16
8397       || r_type == elfcpp::R_POWERPC_GOT16_LO
8398       || r_type == elfcpp::R_POWERPC_GOT16_HI
8399       || r_type == elfcpp::R_POWERPC_GOT16_HA
8400       || r_type == elfcpp::R_PPC64_GOT16_DS
8401       || r_type == elfcpp::R_PPC64_GOT16_LO_DS)
8402     {
8403       if (gsym != NULL)
8404         {
8405           gold_assert(gsym->has_got_offset(GOT_TYPE_STANDARD));
8406           value = gsym->got_offset(GOT_TYPE_STANDARD);
8407         }
8408       else
8409         {
8410           gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD));
8411           value = object->local_got_offset(r_sym, GOT_TYPE_STANDARD);
8412         }
8413       value -= target->got_section()->got_base_offset(object);
8414     }
8415   else if (r_type == elfcpp::R_PPC64_TOC)
8416     {
8417       value = (target->got_section()->output_section()->address()
8418                + object->toc_base_offset());
8419     }
8420   else if (gsym != NULL
8421            && (r_type == elfcpp::R_POWERPC_REL24
8422                || r_type == elfcpp::R_PPC_PLTREL24)
8423            && has_stub_value)
8424     {
8425       if (size == 64)
8426         {
8427           typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
8428           Valtype* wv = reinterpret_cast<Valtype*>(view);
8429           bool can_plt_call = localentry0 || target->is_tls_get_addr_opt(gsym);
8430           if (!can_plt_call && rela.get_r_offset() + 8 <= view_size)
8431             {
8432               Valtype insn = elfcpp::Swap<32, big_endian>::readval(wv);
8433               Valtype insn2 = elfcpp::Swap<32, big_endian>::readval(wv + 1);
8434               if ((insn & 1) != 0
8435                   && (insn2 == nop
8436                       || insn2 == cror_15_15_15 || insn2 == cror_31_31_31))
8437                 {
8438                   elfcpp::Swap<32, big_endian>::
8439                     writeval(wv + 1, ld_2_1 + target->stk_toc());
8440                   can_plt_call = true;
8441                 }
8442             }
8443           if (!can_plt_call)
8444             {
8445               // If we don't have a branch and link followed by a nop,
8446               // we can't go via the plt because there is no place to
8447               // put a toc restoring instruction.
8448               // Unless we know we won't be returning.
8449               if (strcmp(gsym->name(), "__libc_start_main") == 0)
8450                 can_plt_call = true;
8451             }
8452           if (!can_plt_call)
8453             {
8454               // g++ as of 20130507 emits self-calls without a
8455               // following nop.  This is arguably wrong since we have
8456               // conflicting information.  On the one hand a global
8457               // symbol and on the other a local call sequence, but
8458               // don't error for this special case.
8459               // It isn't possible to cheaply verify we have exactly
8460               // such a call.  Allow all calls to the same section.
8461               bool ok = false;
8462               Address code = value;
8463               if (gsym->source() == Symbol::FROM_OBJECT
8464                   && gsym->object() == object)
8465                 {
8466                   unsigned int dest_shndx = 0;
8467                   if (target->abiversion() < 2)
8468                     {
8469                       Address addend = rela.get_r_addend();
8470                       code = psymval->value(object, addend);
8471                       target->symval_for_branch(relinfo->symtab, gsym, object,
8472                                                 &code, &dest_shndx);
8473                     }
8474                   bool is_ordinary;
8475                   if (dest_shndx == 0)
8476                     dest_shndx = gsym->shndx(&is_ordinary);
8477                   ok = dest_shndx == relinfo->data_shndx;
8478                 }
8479               if (!ok)
8480                 {
8481                   gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
8482                                          _("call lacks nop, can't restore toc; "
8483                                            "recompile with -fPIC"));
8484                   value = code;
8485                 }
8486             }
8487         }
8488     }
8489   else if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
8490            || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO
8491            || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_HI
8492            || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_HA)
8493     {
8494       // First instruction of a global dynamic sequence, arg setup insn.
8495       const bool final = gsym == NULL || gsym->final_value_is_known();
8496       const tls::Tls_optimization tls_type = target->optimize_tls_gd(final);
8497       enum Got_type got_type = GOT_TYPE_STANDARD;
8498       if (tls_type == tls::TLSOPT_NONE)
8499         got_type = GOT_TYPE_TLSGD;
8500       else if (tls_type == tls::TLSOPT_TO_IE)
8501         got_type = GOT_TYPE_TPREL;
8502       if (got_type != GOT_TYPE_STANDARD)
8503         {
8504           if (gsym != NULL)
8505             {
8506               gold_assert(gsym->has_got_offset(got_type));
8507               value = gsym->got_offset(got_type);
8508             }
8509           else
8510             {
8511               gold_assert(object->local_has_got_offset(r_sym, got_type));
8512               value = object->local_got_offset(r_sym, got_type);
8513             }
8514           value -= target->got_section()->got_base_offset(object);
8515         }
8516       if (tls_type == tls::TLSOPT_TO_IE)
8517         {
8518           if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
8519               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO)
8520             {
8521               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8522               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8523               insn &= (1 << 26) - (1 << 16); // extract rt,ra from addi
8524               if (size == 32)
8525                 insn |= 32 << 26; // lwz
8526               else
8527                 insn |= 58 << 26; // ld
8528               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8529             }
8530           r_type += (elfcpp::R_POWERPC_GOT_TPREL16
8531                      - elfcpp::R_POWERPC_GOT_TLSGD16);
8532         }
8533       else if (tls_type == tls::TLSOPT_TO_LE)
8534         {
8535           if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
8536               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO)
8537             {
8538               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8539               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8540               insn &= (1 << 26) - (1 << 21); // extract rt
8541               if (size == 32)
8542                 insn |= addis_0_2;
8543               else
8544                 insn |= addis_0_13;
8545               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8546               r_type = elfcpp::R_POWERPC_TPREL16_HA;
8547               value = psymval->value(object, rela.get_r_addend());
8548             }
8549           else
8550             {
8551               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8552               Insn insn = nop;
8553               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8554               r_type = elfcpp::R_POWERPC_NONE;
8555             }
8556         }
8557     }
8558   else if (r_type == elfcpp::R_POWERPC_GOT_TLSLD16
8559            || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_LO
8560            || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_HI
8561            || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_HA)
8562     {
8563       // First instruction of a local dynamic sequence, arg setup insn.
8564       const tls::Tls_optimization tls_type = target->optimize_tls_ld();
8565       if (tls_type == tls::TLSOPT_NONE)
8566         {
8567           value = target->tlsld_got_offset();
8568           value -= target->got_section()->got_base_offset(object);
8569         }
8570       else
8571         {
8572           gold_assert(tls_type == tls::TLSOPT_TO_LE);
8573           if (r_type == elfcpp::R_POWERPC_GOT_TLSLD16
8574               || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_LO)
8575             {
8576               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8577               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8578               insn &= (1 << 26) - (1 << 21); // extract rt
8579               if (size == 32)
8580                 insn |= addis_0_2;
8581               else
8582                 insn |= addis_0_13;
8583               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8584               r_type = elfcpp::R_POWERPC_TPREL16_HA;
8585               value = dtp_offset;
8586             }
8587           else
8588             {
8589               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8590               Insn insn = nop;
8591               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8592               r_type = elfcpp::R_POWERPC_NONE;
8593             }
8594         }
8595     }
8596   else if (r_type == elfcpp::R_POWERPC_GOT_DTPREL16
8597            || r_type == elfcpp::R_POWERPC_GOT_DTPREL16_LO
8598            || r_type == elfcpp::R_POWERPC_GOT_DTPREL16_HI
8599            || r_type == elfcpp::R_POWERPC_GOT_DTPREL16_HA)
8600     {
8601       // Accesses relative to a local dynamic sequence address,
8602       // no optimisation here.
8603       if (gsym != NULL)
8604         {
8605           gold_assert(gsym->has_got_offset(GOT_TYPE_DTPREL));
8606           value = gsym->got_offset(GOT_TYPE_DTPREL);
8607         }
8608       else
8609         {
8610           gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_DTPREL));
8611           value = object->local_got_offset(r_sym, GOT_TYPE_DTPREL);
8612         }
8613       value -= target->got_section()->got_base_offset(object);
8614     }
8615   else if (r_type == elfcpp::R_POWERPC_GOT_TPREL16
8616            || r_type == elfcpp::R_POWERPC_GOT_TPREL16_LO
8617            || r_type == elfcpp::R_POWERPC_GOT_TPREL16_HI
8618            || r_type == elfcpp::R_POWERPC_GOT_TPREL16_HA)
8619     {
8620       // First instruction of initial exec sequence.
8621       const bool final = gsym == NULL || gsym->final_value_is_known();
8622       const tls::Tls_optimization tls_type = target->optimize_tls_ie(final);
8623       if (tls_type == tls::TLSOPT_NONE)
8624         {
8625           if (gsym != NULL)
8626             {
8627               gold_assert(gsym->has_got_offset(GOT_TYPE_TPREL));
8628               value = gsym->got_offset(GOT_TYPE_TPREL);
8629             }
8630           else
8631             {
8632               gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_TPREL));
8633               value = object->local_got_offset(r_sym, GOT_TYPE_TPREL);
8634             }
8635           value -= target->got_section()->got_base_offset(object);
8636         }
8637       else
8638         {
8639           gold_assert(tls_type == tls::TLSOPT_TO_LE);
8640           if (r_type == elfcpp::R_POWERPC_GOT_TPREL16
8641               || r_type == elfcpp::R_POWERPC_GOT_TPREL16_LO)
8642             {
8643               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8644               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8645               insn &= (1 << 26) - (1 << 21); // extract rt from ld
8646               if (size == 32)
8647                 insn |= addis_0_2;
8648               else
8649                 insn |= addis_0_13;
8650               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8651               r_type = elfcpp::R_POWERPC_TPREL16_HA;
8652               value = psymval->value(object, rela.get_r_addend());
8653             }
8654           else
8655             {
8656               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8657               Insn insn = nop;
8658               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8659               r_type = elfcpp::R_POWERPC_NONE;
8660             }
8661         }
8662     }
8663   else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSGD)
8664            || (size == 32 && r_type == elfcpp::R_PPC_TLSGD))
8665     {
8666       // Second instruction of a global dynamic sequence,
8667       // the __tls_get_addr call
8668       this->expect_tls_get_addr_call(relinfo, relnum, rela.get_r_offset());
8669       const bool final = gsym == NULL || gsym->final_value_is_known();
8670       const tls::Tls_optimization tls_type = target->optimize_tls_gd(final);
8671       if (tls_type != tls::TLSOPT_NONE)
8672         {
8673           if (tls_type == tls::TLSOPT_TO_IE)
8674             {
8675               Insn* iview = reinterpret_cast<Insn*>(view);
8676               Insn insn = add_3_3_13;
8677               if (size == 32)
8678                 insn = add_3_3_2;
8679               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8680               r_type = elfcpp::R_POWERPC_NONE;
8681             }
8682           else
8683             {
8684               Insn* iview = reinterpret_cast<Insn*>(view);
8685               Insn insn = addi_3_3;
8686               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8687               r_type = elfcpp::R_POWERPC_TPREL16_LO;
8688               view += d_offset;
8689               value = psymval->value(object, rela.get_r_addend());
8690             }
8691           this->skip_next_tls_get_addr_call();
8692         }
8693     }
8694   else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSLD)
8695            || (size == 32 && r_type == elfcpp::R_PPC_TLSLD))
8696     {
8697       // Second instruction of a local dynamic sequence,
8698       // the __tls_get_addr call
8699       this->expect_tls_get_addr_call(relinfo, relnum, rela.get_r_offset());
8700       const tls::Tls_optimization tls_type = target->optimize_tls_ld();
8701       if (tls_type == tls::TLSOPT_TO_LE)
8702         {
8703           Insn* iview = reinterpret_cast<Insn*>(view);
8704           Insn insn = addi_3_3;
8705           elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8706           this->skip_next_tls_get_addr_call();
8707           r_type = elfcpp::R_POWERPC_TPREL16_LO;
8708           view += d_offset;
8709           value = dtp_offset;
8710         }
8711     }
8712   else if (r_type == elfcpp::R_POWERPC_TLS)
8713     {
8714       // Second instruction of an initial exec sequence
8715       const bool final = gsym == NULL || gsym->final_value_is_known();
8716       const tls::Tls_optimization tls_type = target->optimize_tls_ie(final);
8717       if (tls_type == tls::TLSOPT_TO_LE)
8718         {
8719           Insn* iview = reinterpret_cast<Insn*>(view);
8720           Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8721           unsigned int reg = size == 32 ? 2 : 13;
8722           insn = at_tls_transform(insn, reg);
8723           gold_assert(insn != 0);
8724           elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8725           r_type = elfcpp::R_POWERPC_TPREL16_LO;
8726           view += d_offset;
8727           value = psymval->value(object, rela.get_r_addend());
8728         }
8729     }
8730   else if (!has_stub_value)
8731     {
8732       Address addend = 0;
8733       if (!(size == 32 && r_type == elfcpp::R_PPC_PLTREL24))
8734         addend = rela.get_r_addend();
8735       value = psymval->value(object, addend);
8736       if (size == 64 && is_branch_reloc(r_type))
8737         {
8738           if (target->abiversion() >= 2)
8739             {
8740               if (gsym != NULL)
8741                 value += object->ppc64_local_entry_offset(gsym);
8742               else
8743                 value += object->ppc64_local_entry_offset(r_sym);
8744             }
8745           else
8746             {
8747               unsigned int dest_shndx;
8748               target->symval_for_branch(relinfo->symtab, gsym, object,
8749                                         &value, &dest_shndx);
8750             }
8751         }
8752       Address max_branch_offset = max_branch_delta(r_type);
8753       if (max_branch_offset != 0
8754           && value - address + max_branch_offset >= 2 * max_branch_offset)
8755         {
8756           Stub_table<size, big_endian>* stub_table
8757             = object->stub_table(relinfo->data_shndx);
8758           if (stub_table != NULL)
8759             {
8760               Address off = stub_table->find_long_branch_entry(object, value);
8761               if (off != invalid_address)
8762                 {
8763                   value = (stub_table->stub_address() + stub_table->plt_size()
8764                            + off);
8765                   has_stub_value = true;
8766                 }
8767             }
8768         }
8769     }
8770
8771   switch (r_type)
8772     {
8773     case elfcpp::R_PPC64_REL64:
8774     case elfcpp::R_POWERPC_REL32:
8775     case elfcpp::R_POWERPC_REL24:
8776     case elfcpp::R_PPC_PLTREL24:
8777     case elfcpp::R_PPC_LOCAL24PC:
8778     case elfcpp::R_POWERPC_REL16:
8779     case elfcpp::R_POWERPC_REL16_LO:
8780     case elfcpp::R_POWERPC_REL16_HI:
8781     case elfcpp::R_POWERPC_REL16_HA:
8782     case elfcpp::R_POWERPC_REL16DX_HA:
8783     case elfcpp::R_POWERPC_REL14:
8784     case elfcpp::R_POWERPC_REL14_BRTAKEN:
8785     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
8786       value -= address;
8787       break;
8788
8789     case elfcpp::R_PPC64_TOC16:
8790     case elfcpp::R_PPC64_TOC16_LO:
8791     case elfcpp::R_PPC64_TOC16_HI:
8792     case elfcpp::R_PPC64_TOC16_HA:
8793     case elfcpp::R_PPC64_TOC16_DS:
8794     case elfcpp::R_PPC64_TOC16_LO_DS:
8795       // Subtract the TOC base address.
8796       value -= (target->got_section()->output_section()->address()
8797                 + object->toc_base_offset());
8798       break;
8799
8800     case elfcpp::R_POWERPC_SECTOFF:
8801     case elfcpp::R_POWERPC_SECTOFF_LO:
8802     case elfcpp::R_POWERPC_SECTOFF_HI:
8803     case elfcpp::R_POWERPC_SECTOFF_HA:
8804     case elfcpp::R_PPC64_SECTOFF_DS:
8805     case elfcpp::R_PPC64_SECTOFF_LO_DS:
8806       if (os != NULL)
8807         value -= os->address();
8808       break;
8809
8810     case elfcpp::R_PPC64_TPREL16_DS:
8811     case elfcpp::R_PPC64_TPREL16_LO_DS:
8812     case elfcpp::R_PPC64_TPREL16_HIGH:
8813     case elfcpp::R_PPC64_TPREL16_HIGHA:
8814       if (size != 64)
8815         // R_PPC_TLSGD, R_PPC_TLSLD, R_PPC_EMB_RELST_LO, R_PPC_EMB_RELST_HI
8816         break;
8817       // Fall through.
8818     case elfcpp::R_POWERPC_TPREL16:
8819     case elfcpp::R_POWERPC_TPREL16_LO:
8820     case elfcpp::R_POWERPC_TPREL16_HI:
8821     case elfcpp::R_POWERPC_TPREL16_HA:
8822     case elfcpp::R_POWERPC_TPREL:
8823     case elfcpp::R_PPC64_TPREL16_HIGHER:
8824     case elfcpp::R_PPC64_TPREL16_HIGHERA:
8825     case elfcpp::R_PPC64_TPREL16_HIGHEST:
8826     case elfcpp::R_PPC64_TPREL16_HIGHESTA:
8827       // tls symbol values are relative to tls_segment()->vaddr()
8828       value -= tp_offset;
8829       break;
8830
8831     case elfcpp::R_PPC64_DTPREL16_DS:
8832     case elfcpp::R_PPC64_DTPREL16_LO_DS:
8833     case elfcpp::R_PPC64_DTPREL16_HIGHER:
8834     case elfcpp::R_PPC64_DTPREL16_HIGHERA:
8835     case elfcpp::R_PPC64_DTPREL16_HIGHEST:
8836     case elfcpp::R_PPC64_DTPREL16_HIGHESTA:
8837       if (size != 64)
8838         // R_PPC_EMB_NADDR32, R_PPC_EMB_NADDR16, R_PPC_EMB_NADDR16_LO
8839         // R_PPC_EMB_NADDR16_HI, R_PPC_EMB_NADDR16_HA, R_PPC_EMB_SDAI16
8840         break;
8841       // Fall through.
8842     case elfcpp::R_POWERPC_DTPREL16:
8843     case elfcpp::R_POWERPC_DTPREL16_LO:
8844     case elfcpp::R_POWERPC_DTPREL16_HI:
8845     case elfcpp::R_POWERPC_DTPREL16_HA:
8846     case elfcpp::R_POWERPC_DTPREL:
8847     case elfcpp::R_PPC64_DTPREL16_HIGH:
8848     case elfcpp::R_PPC64_DTPREL16_HIGHA:
8849       // tls symbol values are relative to tls_segment()->vaddr()
8850       value -= dtp_offset;
8851       break;
8852
8853     case elfcpp::R_PPC64_ADDR64_LOCAL:
8854       if (gsym != NULL)
8855         value += object->ppc64_local_entry_offset(gsym);
8856       else
8857         value += object->ppc64_local_entry_offset(r_sym);
8858       break;
8859
8860     default:
8861       break;
8862     }
8863
8864   Insn branch_bit = 0;
8865   switch (r_type)
8866     {
8867     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
8868     case elfcpp::R_POWERPC_REL14_BRTAKEN:
8869       branch_bit = 1 << 21;
8870       // Fall through.
8871     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
8872     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
8873       {
8874         Insn* iview = reinterpret_cast<Insn*>(view);
8875         Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8876         insn &= ~(1 << 21);
8877         insn |= branch_bit;
8878         if (this->is_isa_v2)
8879           {
8880             // Set 'a' bit.  This is 0b00010 in BO field for branch
8881             // on CR(BI) insns (BO == 001at or 011at), and 0b01000
8882             // for branch on CTR insns (BO == 1a00t or 1a01t).
8883             if ((insn & (0x14 << 21)) == (0x04 << 21))
8884               insn |= 0x02 << 21;
8885             else if ((insn & (0x14 << 21)) == (0x10 << 21))
8886               insn |= 0x08 << 21;
8887             else
8888               break;
8889           }
8890         else
8891           {
8892             // Invert 'y' bit if not the default.
8893             if (static_cast<Signed_address>(value) < 0)
8894               insn ^= 1 << 21;
8895           }
8896         elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8897       }
8898       break;
8899
8900     default:
8901       break;
8902     }
8903
8904   if (size == 64)
8905     {
8906       switch (r_type)
8907         {
8908         default:
8909           break;
8910
8911           // Multi-instruction sequences that access the GOT/TOC can
8912           // be optimized, eg.
8913           //     addis ra,r2,x@got@ha; ld rb,x@got@l(ra);
8914           // to  addis ra,r2,x@toc@ha; addi rb,ra,x@toc@l;
8915           // and
8916           //     addis ra,r2,0; addi rb,ra,x@toc@l;
8917           // to  nop;           addi rb,r2,x@toc;
8918           // FIXME: the @got sequence shown above is not yet
8919           // optimized.  Note that gcc as of 2017-01-07 doesn't use
8920           // the ELF @got relocs except for TLS, instead using the
8921           // PowerOpen variant of a compiler managed GOT (called TOC).
8922           // The PowerOpen TOC sequence equivalent to the first
8923           // example is optimized.
8924         case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
8925         case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
8926         case elfcpp::R_POWERPC_GOT_TPREL16_HA:
8927         case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
8928         case elfcpp::R_POWERPC_GOT16_HA:
8929         case elfcpp::R_PPC64_TOC16_HA:
8930           if (parameters->options().toc_optimize())
8931             {
8932               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8933               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8934               if (r_type == elfcpp::R_PPC64_TOC16_HA
8935                   && object->make_toc_relative(target, &value))
8936                 {
8937                   gold_assert((insn & ((0x3f << 26) | 0x1f << 16))
8938                               == ((15u << 26) | (2 << 16)));
8939                 }
8940               if (((insn & ((0x3f << 26) | 0x1f << 16))
8941                    == ((15u << 26) | (2 << 16)) /* addis rt,2,imm */)
8942                   && value + 0x8000 < 0x10000)
8943                 {
8944                   elfcpp::Swap<32, big_endian>::writeval(iview, nop);
8945                   return true;
8946                 }
8947             }
8948           break;
8949
8950         case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
8951         case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
8952         case elfcpp::R_POWERPC_GOT_TPREL16_LO:
8953         case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
8954         case elfcpp::R_POWERPC_GOT16_LO:
8955         case elfcpp::R_PPC64_GOT16_LO_DS:
8956         case elfcpp::R_PPC64_TOC16_LO:
8957         case elfcpp::R_PPC64_TOC16_LO_DS:
8958           if (parameters->options().toc_optimize())
8959             {
8960               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8961               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8962               bool changed = false;
8963               if (r_type == elfcpp::R_PPC64_TOC16_LO_DS
8964                   && object->make_toc_relative(target, &value))
8965                 {
8966                   gold_assert ((insn & (0x3f << 26)) == 58u << 26 /* ld */);
8967                   insn ^= (14u << 26) ^ (58u << 26);
8968                   r_type = elfcpp::R_PPC64_TOC16_LO;
8969                   changed = true;
8970                 }
8971               if (ok_lo_toc_insn(insn, r_type)
8972                   && value + 0x8000 < 0x10000)
8973                 {
8974                   if ((insn & (0x3f << 26)) == 12u << 26 /* addic */)
8975                     {
8976                       // Transform addic to addi when we change reg.
8977                       insn &= ~((0x3f << 26) | (0x1f << 16));
8978                       insn |= (14u << 26) | (2 << 16);
8979                     }
8980                   else
8981                     {
8982                       insn &= ~(0x1f << 16);
8983                       insn |= 2 << 16;
8984                     }
8985                   changed = true;
8986                 }
8987               if (changed)
8988                 elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8989             }
8990           break;
8991
8992         case elfcpp::R_POWERPC_TPREL16_HA:
8993           if (parameters->options().tls_optimize() && value + 0x8000 < 0x10000)
8994             {
8995               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8996               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8997               if ((insn & ((0x3f << 26) | 0x1f << 16))
8998                   != ((15u << 26) | ((size == 32 ? 2 : 13) << 16)))
8999                 ;
9000               else
9001                 {
9002                   elfcpp::Swap<32, big_endian>::writeval(iview, nop);
9003                   return true;
9004                 }
9005             }
9006           break;
9007
9008         case elfcpp::R_PPC64_TPREL16_LO_DS:
9009           if (size == 32)
9010             // R_PPC_TLSGD, R_PPC_TLSLD
9011             break;
9012           // Fall through.
9013         case elfcpp::R_POWERPC_TPREL16_LO:
9014           if (parameters->options().tls_optimize() && value + 0x8000 < 0x10000)
9015             {
9016               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
9017               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
9018               insn &= ~(0x1f << 16);
9019               insn |= (size == 32 ? 2 : 13) << 16;
9020               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
9021             }
9022           break;
9023
9024         case elfcpp::R_PPC64_ENTRY:
9025           value = (target->got_section()->output_section()->address()
9026                    + object->toc_base_offset());
9027           if (value + 0x80008000 <= 0xffffffff
9028               && !parameters->options().output_is_position_independent())
9029             {
9030               Insn* iview = reinterpret_cast<Insn*>(view);
9031               Insn insn1 = elfcpp::Swap<32, big_endian>::readval(iview);
9032               Insn insn2 = elfcpp::Swap<32, big_endian>::readval(iview + 1);
9033
9034               if ((insn1 & ~0xfffc) == ld_2_12
9035                   && insn2 == add_2_2_12)
9036                 {
9037                   insn1 = lis_2 + ha(value);
9038                   elfcpp::Swap<32, big_endian>::writeval(iview, insn1);
9039                   insn2 = addi_2_2 + l(value);
9040                   elfcpp::Swap<32, big_endian>::writeval(iview + 1, insn2);
9041                   return true;
9042                 }
9043             }
9044           else
9045             {
9046               value -= address;
9047               if (value + 0x80008000 <= 0xffffffff)
9048                 {
9049                   Insn* iview = reinterpret_cast<Insn*>(view);
9050                   Insn insn1 = elfcpp::Swap<32, big_endian>::readval(iview);
9051                   Insn insn2 = elfcpp::Swap<32, big_endian>::readval(iview + 1);
9052
9053                   if ((insn1 & ~0xfffc) == ld_2_12
9054                       && insn2 == add_2_2_12)
9055                     {
9056                       insn1 = addis_2_12 + ha(value);
9057                       elfcpp::Swap<32, big_endian>::writeval(iview, insn1);
9058                       insn2 = addi_2_2 + l(value);
9059                       elfcpp::Swap<32, big_endian>::writeval(iview + 1, insn2);
9060                       return true;
9061                     }
9062                 }
9063             }
9064           break;
9065
9066         case elfcpp::R_POWERPC_REL16_LO:
9067           // If we are generating a non-PIC executable, edit
9068           //    0:      addis 2,12,.TOC.-0b@ha
9069           //            addi 2,2,.TOC.-0b@l
9070           // used by ELFv2 global entry points to set up r2, to
9071           //            lis 2,.TOC.@ha
9072           //            addi 2,2,.TOC.@l
9073           // if .TOC. is in range.  */
9074           if (value + address - 4 + 0x80008000 <= 0xffffffff
9075               && relnum != 0
9076               && preloc != NULL
9077               && target->abiversion() >= 2
9078               && !parameters->options().output_is_position_independent()
9079               && rela.get_r_addend() == d_offset + 4
9080               && gsym != NULL
9081               && strcmp(gsym->name(), ".TOC.") == 0)
9082             {
9083               const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
9084               Reltype prev_rela(preloc - reloc_size);
9085               if ((prev_rela.get_r_info()
9086                    == elfcpp::elf_r_info<size>(r_sym,
9087                                                elfcpp::R_POWERPC_REL16_HA))
9088                   && prev_rela.get_r_offset() + 4 == rela.get_r_offset()
9089                   && prev_rela.get_r_addend() + 4 == rela.get_r_addend())
9090                 {
9091                   Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
9092                   Insn insn1 = elfcpp::Swap<32, big_endian>::readval(iview - 1);
9093                   Insn insn2 = elfcpp::Swap<32, big_endian>::readval(iview);
9094
9095                   if ((insn1 & 0xffff0000) == addis_2_12
9096                       && (insn2 & 0xffff0000) == addi_2_2)
9097                     {
9098                       insn1 = lis_2 + ha(value + address - 4);
9099                       elfcpp::Swap<32, big_endian>::writeval(iview - 1, insn1);
9100                       insn2 = addi_2_2 + l(value + address - 4);
9101                       elfcpp::Swap<32, big_endian>::writeval(iview, insn2);
9102                       if (relinfo->rr)
9103                         {
9104                           relinfo->rr->set_strategy(relnum - 1,
9105                                                     Relocatable_relocs::RELOC_SPECIAL);
9106                           relinfo->rr->set_strategy(relnum,
9107                                                     Relocatable_relocs::RELOC_SPECIAL);
9108                         }
9109                       return true;
9110                     }
9111                 }
9112             }
9113           break;
9114         }
9115     }
9116
9117   typename Reloc::Overflow_check overflow = Reloc::CHECK_NONE;
9118   elfcpp::Shdr<size, big_endian> shdr(relinfo->data_shdr);
9119   switch (r_type)
9120     {
9121     case elfcpp::R_POWERPC_ADDR32:
9122     case elfcpp::R_POWERPC_UADDR32:
9123       if (size == 64)
9124         overflow = Reloc::CHECK_BITFIELD;
9125       break;
9126
9127     case elfcpp::R_POWERPC_REL32:
9128     case elfcpp::R_POWERPC_REL16DX_HA:
9129       if (size == 64)
9130         overflow = Reloc::CHECK_SIGNED;
9131       break;
9132
9133     case elfcpp::R_POWERPC_UADDR16:
9134       overflow = Reloc::CHECK_BITFIELD;
9135       break;
9136
9137     case elfcpp::R_POWERPC_ADDR16:
9138       // We really should have three separate relocations,
9139       // one for 16-bit data, one for insns with 16-bit signed fields,
9140       // and one for insns with 16-bit unsigned fields.
9141       overflow = Reloc::CHECK_BITFIELD;
9142       if ((shdr.get_sh_flags() & elfcpp::SHF_EXECINSTR) != 0)
9143         overflow = Reloc::CHECK_LOW_INSN;
9144       break;
9145
9146     case elfcpp::R_POWERPC_ADDR16_HI:
9147     case elfcpp::R_POWERPC_ADDR16_HA:
9148     case elfcpp::R_POWERPC_GOT16_HI:
9149     case elfcpp::R_POWERPC_GOT16_HA:
9150     case elfcpp::R_POWERPC_PLT16_HI:
9151     case elfcpp::R_POWERPC_PLT16_HA:
9152     case elfcpp::R_POWERPC_SECTOFF_HI:
9153     case elfcpp::R_POWERPC_SECTOFF_HA:
9154     case elfcpp::R_PPC64_TOC16_HI:
9155     case elfcpp::R_PPC64_TOC16_HA:
9156     case elfcpp::R_PPC64_PLTGOT16_HI:
9157     case elfcpp::R_PPC64_PLTGOT16_HA:
9158     case elfcpp::R_POWERPC_TPREL16_HI:
9159     case elfcpp::R_POWERPC_TPREL16_HA:
9160     case elfcpp::R_POWERPC_DTPREL16_HI:
9161     case elfcpp::R_POWERPC_DTPREL16_HA:
9162     case elfcpp::R_POWERPC_GOT_TLSGD16_HI:
9163     case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
9164     case elfcpp::R_POWERPC_GOT_TLSLD16_HI:
9165     case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
9166     case elfcpp::R_POWERPC_GOT_TPREL16_HI:
9167     case elfcpp::R_POWERPC_GOT_TPREL16_HA:
9168     case elfcpp::R_POWERPC_GOT_DTPREL16_HI:
9169     case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
9170     case elfcpp::R_POWERPC_REL16_HI:
9171     case elfcpp::R_POWERPC_REL16_HA:
9172       if (size != 32)
9173         overflow = Reloc::CHECK_HIGH_INSN;
9174       break;
9175
9176     case elfcpp::R_POWERPC_REL16:
9177     case elfcpp::R_PPC64_TOC16:
9178     case elfcpp::R_POWERPC_GOT16:
9179     case elfcpp::R_POWERPC_SECTOFF:
9180     case elfcpp::R_POWERPC_TPREL16:
9181     case elfcpp::R_POWERPC_DTPREL16:
9182     case elfcpp::R_POWERPC_GOT_TLSGD16:
9183     case elfcpp::R_POWERPC_GOT_TLSLD16:
9184     case elfcpp::R_POWERPC_GOT_TPREL16:
9185     case elfcpp::R_POWERPC_GOT_DTPREL16:
9186       overflow = Reloc::CHECK_LOW_INSN;
9187       break;
9188
9189     case elfcpp::R_POWERPC_ADDR24:
9190     case elfcpp::R_POWERPC_ADDR14:
9191     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
9192     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
9193     case elfcpp::R_PPC64_ADDR16_DS:
9194     case elfcpp::R_POWERPC_REL24:
9195     case elfcpp::R_PPC_PLTREL24:
9196     case elfcpp::R_PPC_LOCAL24PC:
9197     case elfcpp::R_PPC64_TPREL16_DS:
9198     case elfcpp::R_PPC64_DTPREL16_DS:
9199     case elfcpp::R_PPC64_TOC16_DS:
9200     case elfcpp::R_PPC64_GOT16_DS:
9201     case elfcpp::R_PPC64_SECTOFF_DS:
9202     case elfcpp::R_POWERPC_REL14:
9203     case elfcpp::R_POWERPC_REL14_BRTAKEN:
9204     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
9205       overflow = Reloc::CHECK_SIGNED;
9206       break;
9207     }
9208
9209   Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
9210   Insn insn = 0;
9211
9212   if (overflow == Reloc::CHECK_LOW_INSN
9213       || overflow == Reloc::CHECK_HIGH_INSN)
9214     {
9215       insn = elfcpp::Swap<32, big_endian>::readval(iview);
9216
9217       if ((insn & (0x3f << 26)) == 10u << 26 /* cmpli */)
9218         overflow = Reloc::CHECK_BITFIELD;
9219       else if (overflow == Reloc::CHECK_LOW_INSN
9220                ? ((insn & (0x3f << 26)) == 28u << 26 /* andi */
9221                   || (insn & (0x3f << 26)) == 24u << 26 /* ori */
9222                   || (insn & (0x3f << 26)) == 26u << 26 /* xori */)
9223                : ((insn & (0x3f << 26)) == 29u << 26 /* andis */
9224                   || (insn & (0x3f << 26)) == 25u << 26 /* oris */
9225                   || (insn & (0x3f << 26)) == 27u << 26 /* xoris */))
9226         overflow = Reloc::CHECK_UNSIGNED;
9227       else
9228         overflow = Reloc::CHECK_SIGNED;
9229     }
9230
9231   bool maybe_dq_reloc = false;
9232   typename Powerpc_relocate_functions<size, big_endian>::Status status
9233     = Powerpc_relocate_functions<size, big_endian>::STATUS_OK;
9234   switch (r_type)
9235     {
9236     case elfcpp::R_POWERPC_NONE:
9237     case elfcpp::R_POWERPC_TLS:
9238     case elfcpp::R_POWERPC_GNU_VTINHERIT:
9239     case elfcpp::R_POWERPC_GNU_VTENTRY:
9240       break;
9241
9242     case elfcpp::R_PPC64_ADDR64:
9243     case elfcpp::R_PPC64_REL64:
9244     case elfcpp::R_PPC64_TOC:
9245     case elfcpp::R_PPC64_ADDR64_LOCAL:
9246       Reloc::addr64(view, value);
9247       break;
9248
9249     case elfcpp::R_POWERPC_TPREL:
9250     case elfcpp::R_POWERPC_DTPREL:
9251       if (size == 64)
9252         Reloc::addr64(view, value);
9253       else
9254         status = Reloc::addr32(view, value, overflow);
9255       break;
9256
9257     case elfcpp::R_PPC64_UADDR64:
9258       Reloc::addr64_u(view, value);
9259       break;
9260
9261     case elfcpp::R_POWERPC_ADDR32:
9262       status = Reloc::addr32(view, value, overflow);
9263       break;
9264
9265     case elfcpp::R_POWERPC_REL32:
9266     case elfcpp::R_POWERPC_UADDR32:
9267       status = Reloc::addr32_u(view, value, overflow);
9268       break;
9269
9270     case elfcpp::R_POWERPC_ADDR24:
9271     case elfcpp::R_POWERPC_REL24:
9272     case elfcpp::R_PPC_PLTREL24:
9273     case elfcpp::R_PPC_LOCAL24PC:
9274       status = Reloc::addr24(view, value, overflow);
9275       break;
9276
9277     case elfcpp::R_POWERPC_GOT_DTPREL16:
9278     case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
9279     case elfcpp::R_POWERPC_GOT_TPREL16:
9280     case elfcpp::R_POWERPC_GOT_TPREL16_LO:
9281       if (size == 64)
9282         {
9283           // On ppc64 these are all ds form
9284           maybe_dq_reloc = true;
9285           break;
9286         }
9287       // Fall through.
9288     case elfcpp::R_POWERPC_ADDR16:
9289     case elfcpp::R_POWERPC_REL16:
9290     case elfcpp::R_PPC64_TOC16:
9291     case elfcpp::R_POWERPC_GOT16:
9292     case elfcpp::R_POWERPC_SECTOFF:
9293     case elfcpp::R_POWERPC_TPREL16:
9294     case elfcpp::R_POWERPC_DTPREL16:
9295     case elfcpp::R_POWERPC_GOT_TLSGD16:
9296     case elfcpp::R_POWERPC_GOT_TLSLD16:
9297     case elfcpp::R_POWERPC_ADDR16_LO:
9298     case elfcpp::R_POWERPC_REL16_LO:
9299     case elfcpp::R_PPC64_TOC16_LO:
9300     case elfcpp::R_POWERPC_GOT16_LO:
9301     case elfcpp::R_POWERPC_SECTOFF_LO:
9302     case elfcpp::R_POWERPC_TPREL16_LO:
9303     case elfcpp::R_POWERPC_DTPREL16_LO:
9304     case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
9305     case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
9306       if (size == 64)
9307         status = Reloc::addr16(view, value, overflow);
9308       else
9309         maybe_dq_reloc = true;
9310       break;
9311
9312     case elfcpp::R_POWERPC_UADDR16:
9313       status = Reloc::addr16_u(view, value, overflow);
9314       break;
9315
9316     case elfcpp::R_PPC64_ADDR16_HIGH:
9317     case elfcpp::R_PPC64_TPREL16_HIGH:
9318     case elfcpp::R_PPC64_DTPREL16_HIGH:
9319       if (size == 32)
9320         // R_PPC_EMB_MRKREF, R_PPC_EMB_RELST_LO, R_PPC_EMB_RELST_HA
9321         goto unsupp;
9322       // Fall through.
9323     case elfcpp::R_POWERPC_ADDR16_HI:
9324     case elfcpp::R_POWERPC_REL16_HI:
9325     case elfcpp::R_PPC64_TOC16_HI:
9326     case elfcpp::R_POWERPC_GOT16_HI:
9327     case elfcpp::R_POWERPC_SECTOFF_HI:
9328     case elfcpp::R_POWERPC_TPREL16_HI:
9329     case elfcpp::R_POWERPC_DTPREL16_HI:
9330     case elfcpp::R_POWERPC_GOT_TLSGD16_HI:
9331     case elfcpp::R_POWERPC_GOT_TLSLD16_HI:
9332     case elfcpp::R_POWERPC_GOT_TPREL16_HI:
9333     case elfcpp::R_POWERPC_GOT_DTPREL16_HI:
9334       Reloc::addr16_hi(view, value);
9335       break;
9336
9337     case elfcpp::R_PPC64_ADDR16_HIGHA:
9338     case elfcpp::R_PPC64_TPREL16_HIGHA:
9339     case elfcpp::R_PPC64_DTPREL16_HIGHA:
9340       if (size == 32)
9341         // R_PPC_EMB_RELSEC16, R_PPC_EMB_RELST_HI, R_PPC_EMB_BIT_FLD
9342         goto unsupp;
9343       // Fall through.
9344     case elfcpp::R_POWERPC_ADDR16_HA:
9345     case elfcpp::R_POWERPC_REL16_HA:
9346     case elfcpp::R_PPC64_TOC16_HA:
9347     case elfcpp::R_POWERPC_GOT16_HA:
9348     case elfcpp::R_POWERPC_SECTOFF_HA:
9349     case elfcpp::R_POWERPC_TPREL16_HA:
9350     case elfcpp::R_POWERPC_DTPREL16_HA:
9351     case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
9352     case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
9353     case elfcpp::R_POWERPC_GOT_TPREL16_HA:
9354     case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
9355       Reloc::addr16_ha(view, value);
9356       break;
9357
9358     case elfcpp::R_POWERPC_REL16DX_HA:
9359       status = Reloc::addr16dx_ha(view, value, overflow);
9360       break;
9361
9362     case elfcpp::R_PPC64_DTPREL16_HIGHER:
9363       if (size == 32)
9364         // R_PPC_EMB_NADDR16_LO
9365         goto unsupp;
9366       // Fall through.
9367     case elfcpp::R_PPC64_ADDR16_HIGHER:
9368     case elfcpp::R_PPC64_TPREL16_HIGHER:
9369       Reloc::addr16_hi2(view, value);
9370       break;
9371
9372     case elfcpp::R_PPC64_DTPREL16_HIGHERA:
9373       if (size == 32)
9374         // R_PPC_EMB_NADDR16_HI
9375         goto unsupp;
9376       // Fall through.
9377     case elfcpp::R_PPC64_ADDR16_HIGHERA:
9378     case elfcpp::R_PPC64_TPREL16_HIGHERA:
9379       Reloc::addr16_ha2(view, value);
9380       break;
9381
9382     case elfcpp::R_PPC64_DTPREL16_HIGHEST:
9383       if (size == 32)
9384         // R_PPC_EMB_NADDR16_HA
9385         goto unsupp;
9386       // Fall through.
9387     case elfcpp::R_PPC64_ADDR16_HIGHEST:
9388     case elfcpp::R_PPC64_TPREL16_HIGHEST:
9389       Reloc::addr16_hi3(view, value);
9390       break;
9391
9392     case elfcpp::R_PPC64_DTPREL16_HIGHESTA:
9393       if (size == 32)
9394         // R_PPC_EMB_SDAI16
9395         goto unsupp;
9396       // Fall through.
9397     case elfcpp::R_PPC64_ADDR16_HIGHESTA:
9398     case elfcpp::R_PPC64_TPREL16_HIGHESTA:
9399       Reloc::addr16_ha3(view, value);
9400       break;
9401
9402     case elfcpp::R_PPC64_DTPREL16_DS:
9403     case elfcpp::R_PPC64_DTPREL16_LO_DS:
9404       if (size == 32)
9405         // R_PPC_EMB_NADDR32, R_PPC_EMB_NADDR16
9406         goto unsupp;
9407       // Fall through.
9408     case elfcpp::R_PPC64_TPREL16_DS:
9409     case elfcpp::R_PPC64_TPREL16_LO_DS:
9410       if (size == 32)
9411         // R_PPC_TLSGD, R_PPC_TLSLD
9412         break;
9413       // Fall through.
9414     case elfcpp::R_PPC64_ADDR16_DS:
9415     case elfcpp::R_PPC64_ADDR16_LO_DS:
9416     case elfcpp::R_PPC64_TOC16_DS:
9417     case elfcpp::R_PPC64_TOC16_LO_DS:
9418     case elfcpp::R_PPC64_GOT16_DS:
9419     case elfcpp::R_PPC64_GOT16_LO_DS:
9420     case elfcpp::R_PPC64_SECTOFF_DS:
9421     case elfcpp::R_PPC64_SECTOFF_LO_DS:
9422       maybe_dq_reloc = true;
9423       break;
9424
9425     case elfcpp::R_POWERPC_ADDR14:
9426     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
9427     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
9428     case elfcpp::R_POWERPC_REL14:
9429     case elfcpp::R_POWERPC_REL14_BRTAKEN:
9430     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
9431       status = Reloc::addr14(view, value, overflow);
9432       break;
9433
9434     case elfcpp::R_POWERPC_COPY:
9435     case elfcpp::R_POWERPC_GLOB_DAT:
9436     case elfcpp::R_POWERPC_JMP_SLOT:
9437     case elfcpp::R_POWERPC_RELATIVE:
9438     case elfcpp::R_POWERPC_DTPMOD:
9439     case elfcpp::R_PPC64_JMP_IREL:
9440     case elfcpp::R_POWERPC_IRELATIVE:
9441       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
9442                              _("unexpected reloc %u in object file"),
9443                              r_type);
9444       break;
9445
9446     case elfcpp::R_PPC64_TOCSAVE:
9447       if (size == 32)
9448         // R_PPC_EMB_SDA21
9449         goto unsupp;
9450       else
9451         {
9452           Symbol_location loc;
9453           loc.object = relinfo->object;
9454           loc.shndx = relinfo->data_shndx;
9455           loc.offset = rela.get_r_offset();
9456           Tocsave_loc::const_iterator p = target->tocsave_loc().find(loc);
9457           if (p != target->tocsave_loc().end())
9458             {
9459               // If we've generated plt calls using this tocsave, then
9460               // the nop needs to be changed to save r2.
9461               Insn* iview = reinterpret_cast<Insn*>(view);
9462               if (elfcpp::Swap<32, big_endian>::readval(iview) == nop)
9463                 elfcpp::Swap<32, big_endian>::
9464                   writeval(iview, std_2_1 + target->stk_toc());
9465             }
9466         }
9467       break;
9468
9469     case elfcpp::R_PPC_EMB_SDA2I16:
9470     case elfcpp::R_PPC_EMB_SDA2REL:
9471       if (size == 32)
9472         goto unsupp;
9473       // R_PPC64_TLSGD, R_PPC64_TLSLD
9474       break;
9475
9476     case elfcpp::R_POWERPC_PLT32:
9477     case elfcpp::R_POWERPC_PLTREL32:
9478     case elfcpp::R_POWERPC_PLT16_LO:
9479     case elfcpp::R_POWERPC_PLT16_HI:
9480     case elfcpp::R_POWERPC_PLT16_HA:
9481     case elfcpp::R_PPC_SDAREL16:
9482     case elfcpp::R_POWERPC_ADDR30:
9483     case elfcpp::R_PPC64_PLT64:
9484     case elfcpp::R_PPC64_PLTREL64:
9485     case elfcpp::R_PPC64_PLTGOT16:
9486     case elfcpp::R_PPC64_PLTGOT16_LO:
9487     case elfcpp::R_PPC64_PLTGOT16_HI:
9488     case elfcpp::R_PPC64_PLTGOT16_HA:
9489     case elfcpp::R_PPC64_PLT16_LO_DS:
9490     case elfcpp::R_PPC64_PLTGOT16_DS:
9491     case elfcpp::R_PPC64_PLTGOT16_LO_DS:
9492     case elfcpp::R_PPC_EMB_RELSDA:
9493     case elfcpp::R_PPC_TOC16:
9494     default:
9495     unsupp:
9496       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
9497                              _("unsupported reloc %u"),
9498                              r_type);
9499       break;
9500     }
9501
9502   if (maybe_dq_reloc)
9503     {
9504       if (insn == 0)
9505         insn = elfcpp::Swap<32, big_endian>::readval(iview);
9506
9507       if ((insn & (0x3f << 26)) == 56u << 26 /* lq */
9508           || ((insn & (0x3f << 26)) == (61u << 26) /* lxv, stxv */
9509               && (insn & 3) == 1))
9510         status = Reloc::addr16_dq(view, value, overflow);
9511       else if (size == 64
9512                || (insn & (0x3f << 26)) == 58u << 26 /* ld,ldu,lwa */
9513                || (insn & (0x3f << 26)) == 62u << 26 /* std,stdu,stq */
9514                || (insn & (0x3f << 26)) == 57u << 26 /* lfdp */
9515                || (insn & (0x3f << 26)) == 61u << 26 /* stfdp */)
9516         status = Reloc::addr16_ds(view, value, overflow);
9517       else
9518         status = Reloc::addr16(view, value, overflow);
9519     }
9520
9521   if (status != Powerpc_relocate_functions<size, big_endian>::STATUS_OK
9522       && (has_stub_value
9523           || !(gsym != NULL
9524                && gsym->is_undefined()
9525                && is_branch_reloc(r_type))))
9526     {
9527       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
9528                              _("relocation overflow"));
9529       if (has_stub_value)
9530         gold_info(_("try relinking with a smaller --stub-group-size"));
9531     }
9532
9533   return true;
9534 }
9535
9536 // Relocate section data.
9537
9538 template<int size, bool big_endian>
9539 void
9540 Target_powerpc<size, big_endian>::relocate_section(
9541     const Relocate_info<size, big_endian>* relinfo,
9542     unsigned int sh_type,
9543     const unsigned char* prelocs,
9544     size_t reloc_count,
9545     Output_section* output_section,
9546     bool needs_special_offset_handling,
9547     unsigned char* view,
9548     Address address,
9549     section_size_type view_size,
9550     const Reloc_symbol_changes* reloc_symbol_changes)
9551 {
9552   typedef Target_powerpc<size, big_endian> Powerpc;
9553   typedef typename Target_powerpc<size, big_endian>::Relocate Powerpc_relocate;
9554   typedef typename Target_powerpc<size, big_endian>::Relocate_comdat_behavior
9555     Powerpc_comdat_behavior;
9556   typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
9557       Classify_reloc;
9558
9559   gold_assert(sh_type == elfcpp::SHT_RELA);
9560
9561   gold::relocate_section<size, big_endian, Powerpc, Powerpc_relocate,
9562                          Powerpc_comdat_behavior, Classify_reloc>(
9563     relinfo,
9564     this,
9565     prelocs,
9566     reloc_count,
9567     output_section,
9568     needs_special_offset_handling,
9569     view,
9570     address,
9571     view_size,
9572     reloc_symbol_changes);
9573 }
9574
9575 template<int size, bool big_endian>
9576 class Powerpc_scan_relocatable_reloc
9577 {
9578 public:
9579   typedef typename elfcpp::Rela<size, big_endian> Reltype;
9580   static const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
9581   static const int sh_type = elfcpp::SHT_RELA;
9582
9583   // Return the symbol referred to by the relocation.
9584   static inline unsigned int
9585   get_r_sym(const Reltype* reloc)
9586   { return elfcpp::elf_r_sym<size>(reloc->get_r_info()); }
9587
9588   // Return the type of the relocation.
9589   static inline unsigned int
9590   get_r_type(const Reltype* reloc)
9591   { return elfcpp::elf_r_type<size>(reloc->get_r_info()); }
9592
9593   // Return the strategy to use for a local symbol which is not a
9594   // section symbol, given the relocation type.
9595   inline Relocatable_relocs::Reloc_strategy
9596   local_non_section_strategy(unsigned int r_type, Relobj*, unsigned int r_sym)
9597   {
9598     if (r_type == 0 && r_sym == 0)
9599       return Relocatable_relocs::RELOC_DISCARD;
9600     return Relocatable_relocs::RELOC_COPY;
9601   }
9602
9603   // Return the strategy to use for a local symbol which is a section
9604   // symbol, given the relocation type.
9605   inline Relocatable_relocs::Reloc_strategy
9606   local_section_strategy(unsigned int, Relobj*)
9607   {
9608     return Relocatable_relocs::RELOC_ADJUST_FOR_SECTION_RELA;
9609   }
9610
9611   // Return the strategy to use for a global symbol, given the
9612   // relocation type, the object, and the symbol index.
9613   inline Relocatable_relocs::Reloc_strategy
9614   global_strategy(unsigned int r_type, Relobj*, unsigned int)
9615   {
9616     if (r_type == elfcpp::R_PPC_PLTREL24)
9617       return Relocatable_relocs::RELOC_SPECIAL;
9618     return Relocatable_relocs::RELOC_COPY;
9619   }
9620 };
9621
9622 // Scan the relocs during a relocatable link.
9623
9624 template<int size, bool big_endian>
9625 void
9626 Target_powerpc<size, big_endian>::scan_relocatable_relocs(
9627     Symbol_table* symtab,
9628     Layout* layout,
9629     Sized_relobj_file<size, big_endian>* object,
9630     unsigned int data_shndx,
9631     unsigned int sh_type,
9632     const unsigned char* prelocs,
9633     size_t reloc_count,
9634     Output_section* output_section,
9635     bool needs_special_offset_handling,
9636     size_t local_symbol_count,
9637     const unsigned char* plocal_symbols,
9638     Relocatable_relocs* rr)
9639 {
9640   typedef Powerpc_scan_relocatable_reloc<size, big_endian> Scan_strategy;
9641
9642   gold_assert(sh_type == elfcpp::SHT_RELA);
9643
9644   gold::scan_relocatable_relocs<size, big_endian, Scan_strategy>(
9645     symtab,
9646     layout,
9647     object,
9648     data_shndx,
9649     prelocs,
9650     reloc_count,
9651     output_section,
9652     needs_special_offset_handling,
9653     local_symbol_count,
9654     plocal_symbols,
9655     rr);
9656 }
9657
9658 // Scan the relocs for --emit-relocs.
9659
9660 template<int size, bool big_endian>
9661 void
9662 Target_powerpc<size, big_endian>::emit_relocs_scan(
9663     Symbol_table* symtab,
9664     Layout* layout,
9665     Sized_relobj_file<size, big_endian>* object,
9666     unsigned int data_shndx,
9667     unsigned int sh_type,
9668     const unsigned char* prelocs,
9669     size_t reloc_count,
9670     Output_section* output_section,
9671     bool needs_special_offset_handling,
9672     size_t local_symbol_count,
9673     const unsigned char* plocal_syms,
9674     Relocatable_relocs* rr)
9675 {
9676   typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
9677       Classify_reloc;
9678   typedef gold::Default_emit_relocs_strategy<Classify_reloc>
9679       Emit_relocs_strategy;
9680
9681   gold_assert(sh_type == elfcpp::SHT_RELA);
9682
9683   gold::scan_relocatable_relocs<size, big_endian, Emit_relocs_strategy>(
9684     symtab,
9685     layout,
9686     object,
9687     data_shndx,
9688     prelocs,
9689     reloc_count,
9690     output_section,
9691     needs_special_offset_handling,
9692     local_symbol_count,
9693     plocal_syms,
9694     rr);
9695 }
9696
9697 // Emit relocations for a section.
9698 // This is a modified version of the function by the same name in
9699 // target-reloc.h.  Using relocate_special_relocatable for
9700 // R_PPC_PLTREL24 would require duplication of the entire body of the
9701 // loop, so we may as well duplicate the whole thing.
9702
9703 template<int size, bool big_endian>
9704 void
9705 Target_powerpc<size, big_endian>::relocate_relocs(
9706     const Relocate_info<size, big_endian>* relinfo,
9707     unsigned int sh_type,
9708     const unsigned char* prelocs,
9709     size_t reloc_count,
9710     Output_section* output_section,
9711     typename elfcpp::Elf_types<size>::Elf_Off offset_in_output_section,
9712     unsigned char*,
9713     Address view_address,
9714     section_size_type,
9715     unsigned char* reloc_view,
9716     section_size_type reloc_view_size)
9717 {
9718   gold_assert(sh_type == elfcpp::SHT_RELA);
9719
9720   typedef typename elfcpp::Rela<size, big_endian> Reltype;
9721   typedef typename elfcpp::Rela_write<size, big_endian> Reltype_write;
9722   const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
9723   // Offset from start of insn to d-field reloc.
9724   const int d_offset = big_endian ? 2 : 0;
9725
9726   Powerpc_relobj<size, big_endian>* const object
9727     = static_cast<Powerpc_relobj<size, big_endian>*>(relinfo->object);
9728   const unsigned int local_count = object->local_symbol_count();
9729   unsigned int got2_shndx = object->got2_shndx();
9730   Address got2_addend = 0;
9731   if (got2_shndx != 0)
9732     {
9733       got2_addend = object->get_output_section_offset(got2_shndx);
9734       gold_assert(got2_addend != invalid_address);
9735     }
9736
9737   const bool relocatable = parameters->options().relocatable();
9738
9739   unsigned char* pwrite = reloc_view;
9740   bool zap_next = false;
9741   for (size_t i = 0; i < reloc_count; ++i, prelocs += reloc_size)
9742     {
9743       Relocatable_relocs::Reloc_strategy strategy = relinfo->rr->strategy(i);
9744       if (strategy == Relocatable_relocs::RELOC_DISCARD)
9745         continue;
9746
9747       Reltype reloc(prelocs);
9748       Reltype_write reloc_write(pwrite);
9749
9750       Address offset = reloc.get_r_offset();
9751       typename elfcpp::Elf_types<size>::Elf_WXword r_info = reloc.get_r_info();
9752       unsigned int r_sym = elfcpp::elf_r_sym<size>(r_info);
9753       unsigned int r_type = elfcpp::elf_r_type<size>(r_info);
9754       const unsigned int orig_r_sym = r_sym;
9755       typename elfcpp::Elf_types<size>::Elf_Swxword addend
9756         = reloc.get_r_addend();
9757       const Symbol* gsym = NULL;
9758
9759       if (zap_next)
9760         {
9761           // We could arrange to discard these and other relocs for
9762           // tls optimised sequences in the strategy methods, but for
9763           // now do as BFD ld does.
9764           r_type = elfcpp::R_POWERPC_NONE;
9765           zap_next = false;
9766         }
9767
9768       // Get the new symbol index.
9769       Output_section* os = NULL;
9770       if (r_sym < local_count)
9771         {
9772           switch (strategy)
9773             {
9774             case Relocatable_relocs::RELOC_COPY:
9775             case Relocatable_relocs::RELOC_SPECIAL:
9776               if (r_sym != 0)
9777                 {
9778                   r_sym = object->symtab_index(r_sym);
9779                   gold_assert(r_sym != -1U);
9780                 }
9781               break;
9782
9783             case Relocatable_relocs::RELOC_ADJUST_FOR_SECTION_RELA:
9784               {
9785                 // We are adjusting a section symbol.  We need to find
9786                 // the symbol table index of the section symbol for
9787                 // the output section corresponding to input section
9788                 // in which this symbol is defined.
9789                 gold_assert(r_sym < local_count);
9790                 bool is_ordinary;
9791                 unsigned int shndx =
9792                   object->local_symbol_input_shndx(r_sym, &is_ordinary);
9793                 gold_assert(is_ordinary);
9794                 os = object->output_section(shndx);
9795                 gold_assert(os != NULL);
9796                 gold_assert(os->needs_symtab_index());
9797                 r_sym = os->symtab_index();
9798               }
9799               break;
9800
9801             default:
9802               gold_unreachable();
9803             }
9804         }
9805       else
9806         {
9807           gsym = object->global_symbol(r_sym);
9808           gold_assert(gsym != NULL);
9809           if (gsym->is_forwarder())
9810             gsym = relinfo->symtab->resolve_forwards(gsym);
9811
9812           gold_assert(gsym->has_symtab_index());
9813           r_sym = gsym->symtab_index();
9814         }
9815
9816       // Get the new offset--the location in the output section where
9817       // this relocation should be applied.
9818       if (static_cast<Address>(offset_in_output_section) != invalid_address)
9819         offset += offset_in_output_section;
9820       else
9821         {
9822           section_offset_type sot_offset =
9823             convert_types<section_offset_type, Address>(offset);
9824           section_offset_type new_sot_offset =
9825             output_section->output_offset(object, relinfo->data_shndx,
9826                                           sot_offset);
9827           gold_assert(new_sot_offset != -1);
9828           offset = new_sot_offset;
9829         }
9830
9831       // In an object file, r_offset is an offset within the section.
9832       // In an executable or dynamic object, generated by
9833       // --emit-relocs, r_offset is an absolute address.
9834       if (!relocatable)
9835         {
9836           offset += view_address;
9837           if (static_cast<Address>(offset_in_output_section) != invalid_address)
9838             offset -= offset_in_output_section;
9839         }
9840
9841       // Handle the reloc addend based on the strategy.
9842       if (strategy == Relocatable_relocs::RELOC_COPY)
9843         ;
9844       else if (strategy == Relocatable_relocs::RELOC_ADJUST_FOR_SECTION_RELA)
9845         {
9846           const Symbol_value<size>* psymval = object->local_symbol(orig_r_sym);
9847           addend = psymval->value(object, addend);
9848           // In a relocatable link, the symbol value is relative to
9849           // the start of the output section. For a non-relocatable
9850           // link, we need to adjust the addend.
9851           if (!relocatable)
9852             {
9853               gold_assert(os != NULL);
9854               addend -= os->address();
9855             }
9856         }
9857       else if (strategy == Relocatable_relocs::RELOC_SPECIAL)
9858         {
9859           if (size == 32)
9860             {
9861               if (addend >= 32768)
9862                 addend += got2_addend;
9863             }
9864           else if (r_type == elfcpp::R_POWERPC_REL16_HA)
9865             {
9866               r_type = elfcpp::R_POWERPC_ADDR16_HA;
9867               addend -= d_offset;
9868             }
9869           else if (r_type == elfcpp::R_POWERPC_REL16_LO)
9870             {
9871               r_type = elfcpp::R_POWERPC_ADDR16_LO;
9872               addend -= d_offset + 4;
9873             }
9874         }
9875       else
9876         gold_unreachable();
9877
9878       if (!relocatable)
9879         {
9880           if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
9881               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO
9882               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_HI
9883               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_HA)
9884             {
9885               // First instruction of a global dynamic sequence,
9886               // arg setup insn.
9887               const bool final = gsym == NULL || gsym->final_value_is_known();
9888               switch (this->optimize_tls_gd(final))
9889                 {
9890                 case tls::TLSOPT_TO_IE:
9891                   r_type += (elfcpp::R_POWERPC_GOT_TPREL16
9892                              - elfcpp::R_POWERPC_GOT_TLSGD16);
9893                   break;
9894                 case tls::TLSOPT_TO_LE:
9895                   if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
9896                       || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO)
9897                     r_type = elfcpp::R_POWERPC_TPREL16_HA;
9898                   else
9899                     {
9900                       r_type = elfcpp::R_POWERPC_NONE;
9901                       offset -= d_offset;
9902                     }
9903                   break;
9904                 default:
9905                   break;
9906                 }
9907             }
9908           else if (r_type == elfcpp::R_POWERPC_GOT_TLSLD16
9909                    || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_LO
9910                    || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_HI
9911                    || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_HA)
9912             {
9913               // First instruction of a local dynamic sequence,
9914               // arg setup insn.
9915               if (this->optimize_tls_ld() == tls::TLSOPT_TO_LE)
9916                 {
9917                   if (r_type == elfcpp::R_POWERPC_GOT_TLSLD16
9918                       || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_LO)
9919                     {
9920                       r_type = elfcpp::R_POWERPC_TPREL16_HA;
9921                       const Output_section* os = relinfo->layout->tls_segment()
9922                         ->first_section();
9923                       gold_assert(os != NULL);
9924                       gold_assert(os->needs_symtab_index());
9925                       r_sym = os->symtab_index();
9926                       addend = dtp_offset;
9927                     }
9928                   else
9929                     {
9930                       r_type = elfcpp::R_POWERPC_NONE;
9931                       offset -= d_offset;
9932                     }
9933                 }
9934             }
9935           else if (r_type == elfcpp::R_POWERPC_GOT_TPREL16
9936                    || r_type == elfcpp::R_POWERPC_GOT_TPREL16_LO
9937                    || r_type == elfcpp::R_POWERPC_GOT_TPREL16_HI
9938                    || r_type == elfcpp::R_POWERPC_GOT_TPREL16_HA)
9939             {
9940               // First instruction of initial exec sequence.
9941               const bool final = gsym == NULL || gsym->final_value_is_known();
9942               if (this->optimize_tls_ie(final) == tls::TLSOPT_TO_LE)
9943                 {
9944                   if (r_type == elfcpp::R_POWERPC_GOT_TPREL16
9945                       || r_type == elfcpp::R_POWERPC_GOT_TPREL16_LO)
9946                     r_type = elfcpp::R_POWERPC_TPREL16_HA;
9947                   else
9948                     {
9949                       r_type = elfcpp::R_POWERPC_NONE;
9950                       offset -= d_offset;
9951                     }
9952                 }
9953             }
9954           else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSGD)
9955                    || (size == 32 && r_type == elfcpp::R_PPC_TLSGD))
9956             {
9957               // Second instruction of a global dynamic sequence,
9958               // the __tls_get_addr call
9959               const bool final = gsym == NULL || gsym->final_value_is_known();
9960               switch (this->optimize_tls_gd(final))
9961                 {
9962                 case tls::TLSOPT_TO_IE:
9963                   r_type = elfcpp::R_POWERPC_NONE;
9964                   zap_next = true;
9965                   break;
9966                 case tls::TLSOPT_TO_LE:
9967                   r_type = elfcpp::R_POWERPC_TPREL16_LO;
9968                   offset += d_offset;
9969                   zap_next = true;
9970                   break;
9971                 default:
9972                   break;
9973                 }
9974             }
9975           else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSLD)
9976                    || (size == 32 && r_type == elfcpp::R_PPC_TLSLD))
9977             {
9978               // Second instruction of a local dynamic sequence,
9979               // the __tls_get_addr call
9980               if (this->optimize_tls_ld() == tls::TLSOPT_TO_LE)
9981                 {
9982                   const Output_section* os = relinfo->layout->tls_segment()
9983                     ->first_section();
9984                   gold_assert(os != NULL);
9985                   gold_assert(os->needs_symtab_index());
9986                   r_sym = os->symtab_index();
9987                   addend = dtp_offset;
9988                   r_type = elfcpp::R_POWERPC_TPREL16_LO;
9989                   offset += d_offset;
9990                   zap_next = true;
9991                 }
9992             }
9993           else if (r_type == elfcpp::R_POWERPC_TLS)
9994             {
9995               // Second instruction of an initial exec sequence
9996               const bool final = gsym == NULL || gsym->final_value_is_known();
9997               if (this->optimize_tls_ie(final) == tls::TLSOPT_TO_LE)
9998                 {
9999                   r_type = elfcpp::R_POWERPC_TPREL16_LO;
10000                   offset += d_offset;
10001                 }
10002             }
10003         }
10004
10005       reloc_write.put_r_offset(offset);
10006       reloc_write.put_r_info(elfcpp::elf_r_info<size>(r_sym, r_type));
10007       reloc_write.put_r_addend(addend);
10008
10009       pwrite += reloc_size;
10010     }
10011
10012   gold_assert(static_cast<section_size_type>(pwrite - reloc_view)
10013               == reloc_view_size);
10014 }
10015
10016 // Return the value to use for a dynamic symbol which requires special
10017 // treatment.  This is how we support equality comparisons of function
10018 // pointers across shared library boundaries, as described in the
10019 // processor specific ABI supplement.
10020
10021 template<int size, bool big_endian>
10022 uint64_t
10023 Target_powerpc<size, big_endian>::do_dynsym_value(const Symbol* gsym) const
10024 {
10025   if (size == 32)
10026     {
10027       gold_assert(gsym->is_from_dynobj() && gsym->has_plt_offset());
10028       for (typename Stub_tables::const_iterator p = this->stub_tables_.begin();
10029            p != this->stub_tables_.end();
10030            ++p)
10031         {
10032           const typename Stub_table<size, big_endian>::Plt_stub_ent* ent
10033             = (*p)->find_plt_call_entry(gsym);
10034           if (ent != NULL)
10035             return (*p)->stub_address() + ent->off_;
10036         }
10037     }
10038   else if (this->abiversion() >= 2)
10039     {
10040       Address off = this->glink_section()->find_global_entry(gsym);
10041       if (off != invalid_address)
10042         return this->glink_section()->global_entry_address() + off;
10043     }
10044   gold_unreachable();
10045 }
10046
10047 // Return the PLT address to use for a local symbol.
10048 template<int size, bool big_endian>
10049 uint64_t
10050 Target_powerpc<size, big_endian>::do_plt_address_for_local(
10051     const Relobj* object,
10052     unsigned int symndx) const
10053 {
10054   if (size == 32)
10055     {
10056       const Sized_relobj<size, big_endian>* relobj
10057         = static_cast<const Sized_relobj<size, big_endian>*>(object);
10058       for (typename Stub_tables::const_iterator p = this->stub_tables_.begin();
10059            p != this->stub_tables_.end();
10060            ++p)
10061         {
10062           const typename Stub_table<size, big_endian>::Plt_stub_ent* ent
10063             = (*p)->find_plt_call_entry(relobj->sized_relobj(), symndx);
10064           if (ent != NULL)
10065             return (*p)->stub_address() + ent->off_;
10066         }
10067     }
10068   gold_unreachable();
10069 }
10070
10071 // Return the PLT address to use for a global symbol.
10072 template<int size, bool big_endian>
10073 uint64_t
10074 Target_powerpc<size, big_endian>::do_plt_address_for_global(
10075     const Symbol* gsym) const
10076 {
10077   if (size == 32)
10078     {
10079       for (typename Stub_tables::const_iterator p = this->stub_tables_.begin();
10080            p != this->stub_tables_.end();
10081            ++p)
10082         {
10083           const typename Stub_table<size, big_endian>::Plt_stub_ent* ent
10084             = (*p)->find_plt_call_entry(gsym);
10085           if (ent != NULL)
10086             return (*p)->stub_address() + ent->off_;
10087         }
10088     }
10089   else if (this->abiversion() >= 2)
10090     {
10091       Address off = this->glink_section()->find_global_entry(gsym);
10092       if (off != invalid_address)
10093         return this->glink_section()->global_entry_address() + off;
10094     }
10095   gold_unreachable();
10096 }
10097
10098 // Return the offset to use for the GOT_INDX'th got entry which is
10099 // for a local tls symbol specified by OBJECT, SYMNDX.
10100 template<int size, bool big_endian>
10101 int64_t
10102 Target_powerpc<size, big_endian>::do_tls_offset_for_local(
10103     const Relobj* object,
10104     unsigned int symndx,
10105     unsigned int got_indx) const
10106 {
10107   const Powerpc_relobj<size, big_endian>* ppc_object
10108     = static_cast<const Powerpc_relobj<size, big_endian>*>(object);
10109   if (ppc_object->local_symbol(symndx)->is_tls_symbol())
10110     {
10111       for (Got_type got_type = GOT_TYPE_TLSGD;
10112            got_type <= GOT_TYPE_TPREL;
10113            got_type = Got_type(got_type + 1))
10114         if (ppc_object->local_has_got_offset(symndx, got_type))
10115           {
10116             unsigned int off = ppc_object->local_got_offset(symndx, got_type);
10117             if (got_type == GOT_TYPE_TLSGD)
10118               off += size / 8;
10119             if (off == got_indx * (size / 8))
10120               {
10121                 if (got_type == GOT_TYPE_TPREL)
10122                   return -tp_offset;
10123                 else
10124                   return -dtp_offset;
10125               }
10126           }
10127     }
10128   gold_unreachable();
10129 }
10130
10131 // Return the offset to use for the GOT_INDX'th got entry which is
10132 // for global tls symbol GSYM.
10133 template<int size, bool big_endian>
10134 int64_t
10135 Target_powerpc<size, big_endian>::do_tls_offset_for_global(
10136     Symbol* gsym,
10137     unsigned int got_indx) const
10138 {
10139   if (gsym->type() == elfcpp::STT_TLS)
10140     {
10141       for (Got_type got_type = GOT_TYPE_TLSGD;
10142            got_type <= GOT_TYPE_TPREL;
10143            got_type = Got_type(got_type + 1))
10144         if (gsym->has_got_offset(got_type))
10145           {
10146             unsigned int off = gsym->got_offset(got_type);
10147             if (got_type == GOT_TYPE_TLSGD)
10148               off += size / 8;
10149             if (off == got_indx * (size / 8))
10150               {
10151                 if (got_type == GOT_TYPE_TPREL)
10152                   return -tp_offset;
10153                 else
10154                   return -dtp_offset;
10155               }
10156           }
10157     }
10158   gold_unreachable();
10159 }
10160
10161 // The selector for powerpc object files.
10162
10163 template<int size, bool big_endian>
10164 class Target_selector_powerpc : public Target_selector
10165 {
10166 public:
10167   Target_selector_powerpc()
10168     : Target_selector(size == 64 ? elfcpp::EM_PPC64 : elfcpp::EM_PPC,
10169                       size, big_endian,
10170                       (size == 64
10171                        ? (big_endian ? "elf64-powerpc" : "elf64-powerpcle")
10172                        : (big_endian ? "elf32-powerpc" : "elf32-powerpcle")),
10173                       (size == 64
10174                        ? (big_endian ? "elf64ppc" : "elf64lppc")
10175                        : (big_endian ? "elf32ppc" : "elf32lppc")))
10176   { }
10177
10178   virtual Target*
10179   do_instantiate_target()
10180   { return new Target_powerpc<size, big_endian>(); }
10181 };
10182
10183 Target_selector_powerpc<32, true> target_selector_ppc32;
10184 Target_selector_powerpc<32, false> target_selector_ppc32le;
10185 Target_selector_powerpc<64, true> target_selector_ppc64;
10186 Target_selector_powerpc<64, false> target_selector_ppc64le;
10187
10188 // Instantiate these constants for -O0
10189 template<int size, bool big_endian>
10190 const int Output_data_glink<size, big_endian>::pltresolve_size;
10191 template<int size, bool big_endian>
10192 const typename Output_data_glink<size, big_endian>::Address
10193   Output_data_glink<size, big_endian>::invalid_address;
10194 template<int size, bool big_endian>
10195 const typename Stub_table<size, big_endian>::Address
10196   Stub_table<size, big_endian>::invalid_address;
10197 template<int size, bool big_endian>
10198 const typename Target_powerpc<size, big_endian>::Address
10199   Target_powerpc<size, big_endian>::invalid_address;
10200
10201 } // End anonymous namespace.