xref: /netbsd-src/external/gpl3/gcc/dist/gcc/config/darwin.cc (revision 0a3071956a3a9fdebdbf7f338cf2d439b45fc728)
1 /* Functions for generic Darwin as target machine for GNU C compiler.
2    Copyright (C) 1989-2022 Free Software Foundation, Inc.
3    Contributed by Apple Computer Inc.
4 
5 This file is part of GCC.
6 
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11 
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20 
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "target.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "df.h"
31 #include "memmodel.h"
32 #include "tm_p.h"
33 #include "stringpool.h"
34 #include "attribs.h"
35 #include "insn-config.h"
36 #include "emit-rtl.h"
37 #include "cgraph.h"
38 #include "lto-streamer.h"
39 #include "output.h"
40 #include "varasm.h"
41 #include "stor-layout.h"
42 #include "explow.h"
43 #include "expr.h"
44 #include "langhooks.h"
45 #include "targhooks.h"
46 #include "toplev.h"
47 #include "lto-section-names.h"
48 #include "intl.h"
49 #include "optabs.h"
50 #include "flags.h"
51 #include "opts.h"
52 
53 /* Fix and Continue.
54 
55    NOTES:
56    1) this facility requires suitable support from a modified version
57    of GDB, which is not provided on any system after MacOS 10.7/Darwin11.
58    2) There is no support for this in any X86 version of the FSF compiler.
59 
60    Fix and continue was used on some earlier MacOS systems for rapid turn
61    around debugging.  When code is compiled with the -mfix-and-continue
62    flag, two changes are made to the generated code that allow the system
63    to do things that it would normally not be able to do easily.  These
64    changes allow gdb to load in recompilation of a translation unit that
65    has been changed into a running program and replace existing functions
66    and methods of that translation unit with versions of those functions
67    and methods from the newly compiled translation unit.  The new functions
68    access the existing static symbols from the old translation unit, if the
69    symbol existed in the unit to be replaced, and from the new translation
70    unit, otherwise.
71 
72    The changes are to insert 5 nops at the beginning of all functions
73    and to use indirection to get at static symbols.  The 5 nops
74    are required by consumers of the generated code.  Currently, gdb
75    uses this to patch in a jump to the overriding function, this
76    allows all uses of the old name to forward to the replacement,
77    including existing function pointers and virtual methods.  See
78    rs6000_emit_prologue for the code that handles the nop insertions.
79 
80    The added indirection allows gdb to redirect accesses to static
81    symbols from the newly loaded translation unit to the existing
82    symbol, if any.  @code{static} symbols are special and are handled by
83    setting the second word in the .non_lazy_symbol_pointer data
84    structure to symbol.  See indirect_data for the code that handles
85    the extra indirection, and machopic_output_indirection and its use
86    of MACHO_SYMBOL_FLAG_STATIC for the code that handles @code{static}
87    symbol indirection.  */
88 
89 typedef struct GTY(()) cdtor_record {
90   rtx symbol;
91   int priority;		/* [con/de]structor priority */
92   int position;		/* original position */
93 } cdtor_record;
94 
95 static GTY(()) vec<cdtor_record, va_gc> *ctors = NULL;
96 static GTY(()) vec<cdtor_record, va_gc> *dtors = NULL;
97 
98 /* A flag to determine whether we are running c++ or obj-c++.  This has to be
99    settable from non-c-family contexts too (i.e. we can't use the c_dialect_
100    functions).  */
101 int darwin_running_cxx;
102 
103 /* Some code-gen now depends on OS major version numbers (at least).  */
104 int generating_for_darwin_version ;
105 
106 /* For older linkers we need to emit special sections (marked 'coalesced') for
107    for weak or single-definition items.  */
108 static bool ld_uses_coal_sects = false;
109 
110 /* Very old (ld_classic) linkers need a symbol to mark the start of
111    each FDE.  */
112 static bool ld_needs_eh_markers = false;
113 
114 /* Emit a section-start symbol for mod init and term sections.  */
115 static bool ld_init_term_start_labels = false;
116 
117 /* The source and version of dsymutil in use.  */
118 #ifndef DSYMUTIL_VERSION
119 # warning Darwin toolchain without a defined dsymutil.
120 # define DSYMUTIL_VERSION DET_UNKNOWN,0,0,0
121 #endif
122 
123 struct {
124   darwin_external_toolchain kind; /* cctools, llvm, clang etc.  */
125   int major; /* version number.  */
126   int minor;
127   int tiny;
128 } dsymutil_version = {DSYMUTIL_VERSION};
129 
130 /* Section names.  */
131 section * darwin_sections[NUM_DARWIN_SECTIONS];
132 
133 /* While we transition to using in-tests instead of ifdef'd code.  */
134 #if !HAVE_lo_sum
135 #define gen_macho_high(m,a,b) (a)
136 #define gen_macho_low(m,a,b,c) (a)
137 #endif
138 
139 /* True if we're setting __attribute__ ((ms_struct)).  */
140 int darwin_ms_struct = false;
141 
142 /* Earlier versions of Darwin as do not recognize an alignment field in
143    .comm directives, this should be set for versions that allow it.  */
144 int emit_aligned_common = false;
145 
146 /* A get_unnamed_section callback used to switch to an ObjC section.
147    DIRECTIVE is as for output_section_asm_op.  */
148 
149 static void
output_objc_section_asm_op(const char * directive)150 output_objc_section_asm_op (const char *directive)
151 {
152   static bool been_here = false;
153 
154   /* The NeXT ObjC Runtime requires these sections to be present and in
155      order in the object.  The code below implements this by emitting
156      a section header for each ObjC section the first time that an ObjC
157      section is requested.  */
158   if (darwin_symbol_stubs && ! been_here)
159     {
160       section *saved_in_section = in_section;
161       static const enum darwin_section_enum tomark[] =
162 	{
163 	  /* written, cold -> hot */
164 	  objc_cat_cls_meth_section,
165 	  objc_cat_inst_meth_section,
166 	  objc_string_object_section,
167 	  objc_constant_string_object_section,
168 	  objc_selector_refs_section,
169 	  objc_selector_fixup_section,
170 	  objc_cls_refs_section,
171 	  objc_class_section,
172 	  objc_meta_class_section,
173 	  /* shared, hot -> cold */
174 	  objc_cls_meth_section,
175 	  objc_inst_meth_section,
176 	  objc_protocol_section,
177 	  objc_class_names_section,
178 	  objc_meth_var_types_section,
179 	  objc_meth_var_names_section,
180 	  objc_category_section,
181 	  objc_class_vars_section,
182 	  objc_instance_vars_section,
183 	  objc_module_info_section,
184 	  objc_symbols_section,
185 	};
186       /* ABI=1 */
187       static const enum darwin_section_enum tomarkv1[] =
188 	{
189 	  objc1_protocol_ext_section,
190 	  objc1_class_ext_section,
191 	  objc1_prop_list_section
192 	} ;
193       /* ABI=2 */
194       static const enum darwin_section_enum tomarkv2[] =
195 	{
196 	  objc2_method_names_section,
197 	  objc2_message_refs_section,
198 	  objc2_selector_refs_section,
199 	  objc2_ivar_section,
200 	  objc2_classdefs_section,
201 	  objc2_metadata_section,
202 	  objc2_classrefs_section,
203 	  objc2_class_names_section,
204 	  objc2_classlist_section,
205 	  objc2_categorylist_section,
206 	  objc2_nonlazy_class_section,
207 	  objc2_nonlazy_category_section,
208 	  objc2_protocollist_section,
209 	  objc2_protocolrefs_section,
210 	  objc2_super_classrefs_section,
211 	  objc2_constant_string_object_section,
212 	  objc2_image_info_section,
213 	} ;
214       size_t i;
215 
216       been_here = true;
217       if (flag_objc_abi < 2)
218 	{
219 	  for (i = 0; i < ARRAY_SIZE (tomark); i++)
220 	    switch_to_section (darwin_sections[tomark[i]]);
221 	  if (flag_objc_abi == 1)
222 	    for (i = 0; i < ARRAY_SIZE (tomarkv1); i++)
223 	      switch_to_section (darwin_sections[tomarkv1[i]]);
224 	}
225       else
226 	for (i = 0; i < ARRAY_SIZE (tomarkv2); i++)
227 	  switch_to_section (darwin_sections[tomarkv2[i]]);
228       /* Make sure we don't get varasm.cc out of sync with us.  */
229       switch_to_section (saved_in_section);
230     }
231   output_section_asm_op (directive);
232 }
233 
234 
235 /* Private flag applied to disable section-anchors in a particular section.  */
236 #define SECTION_NO_ANCHOR SECTION_MACH_DEP
237 
238 
239 /* Implement TARGET_ASM_INIT_SECTIONS.  */
240 
241 void
darwin_init_sections(void)242 darwin_init_sections (void)
243 {
244 #define DEF_SECTION(NAME, FLAGS, DIRECTIVE, OBJC)		\
245   darwin_sections[NAME] =					\
246     get_unnamed_section (FLAGS, (OBJC				\
247 				 ? output_objc_section_asm_op	\
248 				 : output_section_asm_op),	\
249 			 "\t" DIRECTIVE);
250 #include "config/darwin-sections.def"
251 #undef DEF_SECTION
252 
253   readonly_data_section = darwin_sections[const_section];
254   exception_section = darwin_sections[darwin_exception_section];
255   eh_frame_section = darwin_sections[darwin_eh_frame_section];
256 
257   /* If our linker is new enough to coalesce weak symbols, then we
258      can just put picbase_thunks into the text section.  */
259   if (! ld_uses_coal_sects )
260     darwin_sections[picbase_thunk_section] = text_section;
261 }
262 
263 int
name_needs_quotes(const char * name)264 name_needs_quotes (const char *name)
265 {
266   int c;
267   while ((c = *name++) != '\0')
268     if (! ISIDNUM (c)
269 	  && c != '.' && c != '$' && c != '_' )
270       return 1;
271   return 0;
272 }
273 
274 /* Return true if SYM_REF can be used without an indirection.  */
275 int
machopic_symbol_defined_p(rtx sym_ref)276 machopic_symbol_defined_p (rtx sym_ref)
277 {
278   if (MACHO_SYMBOL_DEFINED_P (sym_ref))
279     return true;
280 
281   /* If a symbol references local and is not an extern to this
282      file, then the symbol might be able to declared as defined.  */
283   if (SYMBOL_REF_LOCAL_P (sym_ref) && ! SYMBOL_REF_EXTERNAL_P (sym_ref))
284     {
285       /* If the symbol references a variable and the variable is a
286 	 common symbol, then this symbol is not defined.  */
287       if (MACHO_SYMBOL_VARIABLE_P (sym_ref))
288 	{
289 	  tree decl = SYMBOL_REF_DECL (sym_ref);
290 	  if (!decl)
291 	    return true;
292 	  if (DECL_COMMON (decl))
293 	    return false;
294 	}
295       return true;
296     }
297   return false;
298 }
299 
300 /* This module assumes that (const (symbol_ref "foo")) is a legal pic
301    reference, which will not be changed.  */
302 
303 enum machopic_addr_class
machopic_classify_symbol(rtx sym_ref)304 machopic_classify_symbol (rtx sym_ref)
305 {
306   bool function_p;
307 
308   function_p = SYMBOL_REF_FUNCTION_P (sym_ref);
309   if (machopic_symbol_defined_p (sym_ref))
310     return (function_p
311 	    ? MACHOPIC_DEFINED_FUNCTION : MACHOPIC_DEFINED_DATA);
312   else
313     return (function_p
314 	    ? MACHOPIC_UNDEFINED_FUNCTION : MACHOPIC_UNDEFINED_DATA);
315 }
316 
317 #ifndef TARGET_FIX_AND_CONTINUE
318 #define TARGET_FIX_AND_CONTINUE 0
319 #endif
320 
321 /* Indicate when fix-and-continue style code generation is being used
322    and when a reference to data should be indirected so that it can be
323    rebound in a new translation unit to reference the original instance
324    of that data.  Symbol names that are for code generation local to
325    the translation unit are bound to the new translation unit;
326    currently this means symbols that begin with L or _OBJC_;
327    otherwise, we indicate that an indirect reference should be made to
328    permit the runtime to rebind new instances of the translation unit
329    to the original instance of the data.  */
330 
331 static int
indirect_data(rtx sym_ref)332 indirect_data (rtx sym_ref)
333 {
334   int lprefix;
335   const char *name;
336 
337   /* If we aren't generating fix-and-continue code, don't do anything
338      special.  */
339   if (TARGET_FIX_AND_CONTINUE == 0)
340     return 0;
341 
342   /* Otherwise, all symbol except symbols that begin with L or _OBJC_
343      are indirected.  Symbols that begin with L and _OBJC_ are always
344      bound to the current translation unit as they are used for
345      generated local data of the translation unit.  */
346 
347   name = XSTR (sym_ref, 0);
348 
349   lprefix = (((name[0] == '*' || name[0] == '&')
350               && (name[1] == 'L' || (name[1] == '"' && name[2] == 'L')))
351 	     || (startswith (name, "_OBJC_")));
352 
353   return ! lprefix;
354 }
355 
356 static int
machopic_data_defined_p(rtx sym_ref)357 machopic_data_defined_p (rtx sym_ref)
358 {
359   if (indirect_data (sym_ref))
360     return 0;
361 
362   switch (machopic_classify_symbol (sym_ref))
363     {
364     case MACHOPIC_DEFINED_DATA:
365     case MACHOPIC_DEFINED_FUNCTION:
366       return 1;
367     default:
368       return 0;
369     }
370 }
371 
372 void
machopic_define_symbol(rtx mem)373 machopic_define_symbol (rtx mem)
374 {
375   rtx sym_ref;
376 
377   gcc_assert (GET_CODE (mem) == MEM);
378   sym_ref = XEXP (mem, 0);
379   SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
380 }
381 
382 /* Return either ORIG or:
383 
384      (const:P (unspec:P [ORIG] UNSPEC_MACHOPIC_OFFSET))
385 
386    depending on MACHO_DYNAMIC_NO_PIC_P.  */
387 rtx
machopic_gen_offset(rtx orig)388 machopic_gen_offset (rtx orig)
389 {
390   if (MACHO_DYNAMIC_NO_PIC_P)
391     return orig;
392   else
393     {
394       /* Play games to avoid marking the function as needing pic if we
395 	 are being called as part of the cost-estimation process.  */
396       if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
397 	crtl->uses_pic_offset_table = 1;
398       orig = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, orig),
399 			     UNSPEC_MACHOPIC_OFFSET);
400       return gen_rtx_CONST (Pmode, orig);
401     }
402 }
403 
404 static GTY(()) const char * function_base_func_name = NULL;
405 static GTY(()) unsigned current_pic_label_num = 0;
406 static GTY(()) unsigned emitted_pic_label_num = 0;
407 
408 /* We need to keep one picbase label per function, but (when we emit code
409    to reload the picbase for setjump receiver) we might need to check for
410    a second use.  So, only update the picbase label counter when we see a
411    new function.  When there's no function decl, we assume that the call is
412    from the x86 stub generation code.  */
413 static void
update_pic_label_number_if_needed(void)414 update_pic_label_number_if_needed (void)
415 {
416   if (current_function_decl)
417     {
418 
419       const char *current_name =
420 	IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl));
421       if (function_base_func_name != current_name)
422 	{
423 	  ++current_pic_label_num;
424 	  function_base_func_name = current_name;
425 	}
426     }
427   else
428     {
429       ++current_pic_label_num;
430       function_base_func_name = "L_machopic_stub_dummy";
431     }
432 }
433 
434 void
machopic_output_function_base_name(FILE * file)435 machopic_output_function_base_name (FILE *file)
436 {
437   /* We should only get here for -fPIC.  */
438   gcc_checking_assert (MACHOPIC_PURE);
439 
440   update_pic_label_number_if_needed ();
441   fprintf (file, "L%u$pb", current_pic_label_num);
442 }
443 
444 char curr_picbasename[32];
445 
446 const char *
machopic_get_function_picbase(void)447 machopic_get_function_picbase (void)
448 {
449   /* We should only get here for -fPIC.  */
450   gcc_checking_assert (MACHOPIC_PURE);
451 
452   update_pic_label_number_if_needed ();
453   snprintf (curr_picbasename, 32, "L%u$pb", current_pic_label_num);
454   return (const char *) curr_picbasename;
455 }
456 
457 bool
machopic_should_output_picbase_label(void)458 machopic_should_output_picbase_label (void)
459 {
460   update_pic_label_number_if_needed ();
461 
462   if (current_pic_label_num == emitted_pic_label_num)
463     return false;
464 
465   emitted_pic_label_num = current_pic_label_num;
466   return true;
467 }
468 
469 /* The suffix attached to non-lazy pointer symbols.  */
470 #define NON_LAZY_POINTER_SUFFIX "$non_lazy_ptr"
471 /* The suffix attached to stub symbols.  */
472 #define STUB_SUFFIX "$stub"
473 
474 typedef struct GTY ((for_user)) machopic_indirection
475 {
476   /* The SYMBOL_REF for the entity referenced.  */
477   rtx symbol;
478   /* The name of the stub or non-lazy pointer.  */
479   const char * ptr_name;
480   /* True iff this entry is for a stub (as opposed to a non-lazy
481      pointer).  */
482   bool stub_p;
483   /* True iff this stub or pointer has been referenced.  */
484   bool used;
485   /* True iff a non-lazy symbol pointer should be emitted into the .data
486      section, rather than the non-lazy symbol pointers section.  The cases
487      for which this occurred seem to have been unintentional, and later
488      toolchains emit all of the indirections to the 'usual' section.  We
489      are keeping this in case it is necessary to preserve compatibility with
490      older toolchains.  */
491   bool nlsp_in_data_section;
492 } machopic_indirection;
493 
494 struct indirection_hasher : ggc_ptr_hash<machopic_indirection>
495 {
496   typedef const char *compare_type;
497   static hashval_t hash (machopic_indirection *);
498   static bool equal (machopic_indirection *, const char *);
499 };
500 
501 /* A table mapping stub names and non-lazy pointer names to
502    SYMBOL_REFs for the stubbed-to and pointed-to entities.  */
503 
504 static GTY (()) hash_table<indirection_hasher> *machopic_indirections;
505 
506 /* Return a hash value for a SLOT in the indirections hash table.  */
507 
508 hashval_t
hash(machopic_indirection * p)509 indirection_hasher::hash (machopic_indirection *p)
510 {
511   return htab_hash_string (p->ptr_name);
512 }
513 
514 /* Returns true if the KEY is the same as that associated with
515    SLOT.  */
516 
517 bool
equal(machopic_indirection * s,const char * k)518 indirection_hasher::equal (machopic_indirection *s, const char *k)
519 {
520   return strcmp (s->ptr_name, k) == 0;
521 }
522 
523 /* Return the name of the non-lazy pointer (if STUB_P is false) or
524    stub (if STUB_B is true) corresponding to the given name.
525 
526   PR71767 - If we have a situation like:
527 
528 global_weak_symbol:
529   ....
530 Lnon_weak_local:
531   ....
532 
533   ld64 will be unable to split this into two atoms (because the "L" makes
534   the second symbol 'invisible').  This means that legitimate direct accesses
535   to the second symbol will appear to be direct accesses to an atom of type
536   weak, global which are not allowed.
537 
538   To avoid this, we make any data-section indirections have a leading 'l'
539   (lower-case L) which has a special meaning: linker can see this and use
540   it to determine  atoms, but it is not placed into the final symbol table.
541 
542   Symbols in the non-lazy symbol pointers section (or stubs) do not have this
543   problem because ld64 already knows the size of each entry.
544 */
545 
546 const char *
machopic_indirection_name(rtx sym_ref,bool stub_p)547 machopic_indirection_name (rtx sym_ref, bool stub_p)
548 {
549   const char *name = XSTR (sym_ref, 0);
550   tree id = maybe_get_identifier (name);
551   if (id)
552     {
553       tree id_orig = id;
554 
555       while (IDENTIFIER_TRANSPARENT_ALIAS (id))
556 	id = TREE_CHAIN (id);
557       if (id != id_orig)
558 	name = IDENTIFIER_POINTER (id);
559     }
560 
561   const char *prefix = user_label_prefix;
562   /* If we are emitting the label 'verbatim' then omit the U_L_P and count
563      the name without the leading '*'.  */
564   if (name[0] == '*')
565     {
566       prefix = "";
567       ++name;
568     }
569 
570   /* Here we are undoing a number of causes that placed some indirections
571      (apparently erroneously) into the .data section.  Specifically, some
572      symbols that are ABI mandated indirections and some hidden symbols
573      were being placed there - which cause difficulties with later
574      versions of ld64.  Iff (after these checks) some symbol still gets an
575      indirection in the data section, we want to adjust the indirection
576      name to be linker visible to deal with PR71767 (notes above).  */
577   bool nlsp_in_data_section =
578        ! MACHO_SYMBOL_MUST_INDIRECT_P (sym_ref)
579     && ! MACHO_SYMBOL_HIDDEN_VIS_P (sym_ref)
580     && (machopic_symbol_defined_p (sym_ref) || SYMBOL_REF_LOCAL_P (sym_ref))
581     && ! indirect_data (sym_ref);
582 
583   const char *suffix = stub_p ? STUB_SUFFIX : NON_LAZY_POINTER_SUFFIX;
584   /* If the indirection is in the data section, let the linker see it.  */
585   char L_or_l = (!stub_p && nlsp_in_data_section) ? 'l' : 'L';
586   /* We have mangled symbols with spaces and punctuation which typically
587      need surrounding in quotes for the assembler to consume them.  */
588   const char *quote = name_needs_quotes (name) ? "\"" : "";
589   char *buffer = XALLOCAVEC (char, 2  /* strlen ("&L") or ("&l") */
590 			     + strlen (prefix)
591 			     + strlen (name)
592 			     + strlen (suffix)
593 			     + 2 * strlen (quote)
594 			     + 1 /* '\0' */);
595 
596   /* Construct the name of the non-lazy pointer or stub.  */
597   sprintf (buffer, "&%s%c%s%s%s%s", quote, L_or_l, prefix, name,
598 	   suffix, quote);
599 
600   if (!machopic_indirections)
601     machopic_indirections = hash_table<indirection_hasher>::create_ggc (37);
602 
603   machopic_indirection **slot
604     = machopic_indirections->find_slot_with_hash (buffer,
605 						  htab_hash_string (buffer),
606 						  INSERT);
607   machopic_indirection *p;
608   if (*slot)
609     p = *slot;
610   else
611     {
612       p = ggc_alloc<machopic_indirection> ();
613       p->symbol = sym_ref;
614       p->ptr_name = xstrdup (buffer);
615       p->stub_p = stub_p;
616       p->used = false;
617       p->nlsp_in_data_section = nlsp_in_data_section;
618       *slot = p;
619     }
620 
621   return p->ptr_name;
622 }
623 
624 /* If NAME is the name of a stub or a non-lazy pointer , mark the stub
625    or non-lazy pointer as used -- and mark the object to which the
626    pointer/stub refers as used as well, since the pointer/stub will
627    emit a reference to it.  */
628 
629 void
machopic_validate_stub_or_non_lazy_ptr(const char * name)630 machopic_validate_stub_or_non_lazy_ptr (const char *name)
631 {
632   machopic_indirection *p
633     = machopic_indirections->find_with_hash (name, htab_hash_string (name));
634   if (p && ! p->used)
635     {
636       const char *real_name;
637       tree id;
638 
639       p->used = true;
640 
641       /* Do what output_addr_const will do when we actually call it.  */
642       if (SYMBOL_REF_DECL (p->symbol))
643 	mark_decl_referenced (SYMBOL_REF_DECL (p->symbol));
644 
645       real_name = targetm.strip_name_encoding (XSTR (p->symbol, 0));
646 
647       id = maybe_get_identifier (real_name);
648       if (id)
649 	mark_referenced (id);
650     }
651 }
652 
653 /* Transform ORIG, which may be any data source, to the corresponding
654    source using indirections.  */
655 
656 rtx
machopic_indirect_data_reference(rtx orig,rtx reg)657 machopic_indirect_data_reference (rtx orig, rtx reg)
658 {
659   rtx ptr_ref = orig;
660 
661   if (! MACHOPIC_INDIRECT)
662     return orig;
663 
664   if (GET_CODE (orig) == SYMBOL_REF)
665     {
666       int defined = machopic_data_defined_p (orig);
667 
668       if (defined && MACHO_DYNAMIC_NO_PIC_P)
669 	{
670 	  if (DARWIN_PPC)
671 	    {
672 	  /* Create a new register for CSE opportunities.  */
673 	  rtx hi_reg = (!can_create_pseudo_p () ? reg : gen_reg_rtx (Pmode));
674 	  emit_insn (gen_macho_high (Pmode, hi_reg, orig));
675 	  emit_insn (gen_macho_low (Pmode, reg, hi_reg, orig));
676 	      return reg;
677  	    }
678 	  else if (DARWIN_X86)
679 	    return orig;
680 	  else
681 	   /* some other cpu -- writeme!  */
682 	   gcc_unreachable ();
683 	}
684       else if (defined && ! MACHO_SYMBOL_MUST_INDIRECT_P (orig))
685 	{
686 	  rtx offset = NULL;
687 	  if (DARWIN_PPC || HAVE_lo_sum)
688 	    offset = machopic_gen_offset (orig);
689 
690 	  if (DARWIN_PPC)
691 	    {
692 	  rtx hi_sum_reg = (!can_create_pseudo_p ()
693 			    ? reg
694 			    : gen_reg_rtx (Pmode));
695 
696 	  gcc_assert (reg);
697 
698 	  emit_insn (gen_rtx_SET (hi_sum_reg,
699 			      gen_rtx_PLUS (Pmode, pic_offset_table_rtx,
700 				       gen_rtx_HIGH (Pmode, offset))));
701 	  emit_insn (gen_rtx_SET (reg,
702 				  gen_rtx_LO_SUM (Pmode, hi_sum_reg,
703 						  copy_rtx (offset))));
704 
705 	  orig = reg;
706 	    }
707 	  else if (HAVE_lo_sum)
708 	    {
709 	  gcc_assert (reg);
710 
711 	  emit_insn (gen_rtx_SET (reg, gen_rtx_HIGH (Pmode, offset)));
712 	  emit_insn (gen_rtx_SET (reg, gen_rtx_LO_SUM (Pmode, reg,
713 						       copy_rtx (offset))));
714 	  emit_use (pic_offset_table_rtx);
715 
716 	  orig = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, reg);
717 	    }
718 	  return orig;
719 	}
720 
721       ptr_ref = (gen_rtx_SYMBOL_REF
722 		 (Pmode,
723 		  machopic_indirection_name (orig, /*stub_p=*/false)));
724 
725       SYMBOL_REF_DATA (ptr_ref) = SYMBOL_REF_DATA (orig);
726       SYMBOL_REF_FLAGS (ptr_ref) |= MACHO_SYMBOL_FLAG_INDIRECTION;
727 
728       ptr_ref = gen_const_mem (Pmode, ptr_ref);
729       machopic_define_symbol (ptr_ref);
730 
731       if (DARWIN_X86
732           && reg
733           && MACHO_DYNAMIC_NO_PIC_P)
734 	{
735 	    emit_insn (gen_rtx_SET (reg, ptr_ref));
736 	    ptr_ref = reg;
737 	}
738 
739       return ptr_ref;
740     }
741   else if (GET_CODE (orig) == CONST)
742     {
743       /* If "(const (plus ...", walk the PLUS and return that result.
744 	 PLUS processing (below) will restore the "(const ..." if
745 	 appropriate.  */
746       if (GET_CODE (XEXP (orig, 0)) == PLUS)
747 	return machopic_indirect_data_reference (XEXP (orig, 0), reg);
748       else
749 	return orig;
750     }
751   else if (GET_CODE (orig) == MEM)
752     {
753       XEXP (ptr_ref, 0) =
754 		machopic_indirect_data_reference (XEXP (orig, 0), reg);
755       return ptr_ref;
756     }
757   else if (GET_CODE (orig) == PLUS)
758     {
759       rtx base, result;
760 
761       /* Legitimize both operands of the PLUS.  */
762       base = machopic_indirect_data_reference (XEXP (orig, 0), reg);
763       orig = machopic_indirect_data_reference (XEXP (orig, 1),
764 					       (base == reg ? 0 : reg));
765       if (MACHOPIC_INDIRECT && (GET_CODE (orig) == CONST_INT))
766 	result = plus_constant (Pmode, base, INTVAL (orig));
767       else
768 	result = gen_rtx_PLUS (Pmode, base, orig);
769 
770       if (MACHOPIC_JUST_INDIRECT && GET_CODE (base) == MEM)
771 	{
772 	  if (reg)
773 	    {
774 	      emit_move_insn (reg, result);
775 	      result = reg;
776 	    }
777 	  else
778 	    {
779 	      result = force_reg (GET_MODE (result), result);
780 	    }
781 	}
782 
783       return result;
784     }
785   return ptr_ref;
786 }
787 
788 /* Transform TARGET (a MEM), which is a function call target, to the
789    corresponding symbol_stub if necessary.  Return a new MEM.  */
790 
791 rtx
machopic_indirect_call_target(rtx target)792 machopic_indirect_call_target (rtx target)
793 {
794   if (! darwin_symbol_stubs)
795     return target;
796 
797   if (GET_CODE (target) != MEM)
798     return target;
799 
800   if (MACHOPIC_INDIRECT
801       && GET_CODE (XEXP (target, 0)) == SYMBOL_REF
802       && ! MACHO_SYMBOL_DEFINED_P (XEXP (target, 0)))
803     {
804       rtx sym_ref = XEXP (target, 0);
805       const char *stub_name = machopic_indirection_name (sym_ref,
806 							 /*stub_p=*/true);
807       machine_mode mode = GET_MODE (sym_ref);
808 
809       XEXP (target, 0) = gen_rtx_SYMBOL_REF (mode, stub_name);
810       SYMBOL_REF_DATA (XEXP (target, 0)) = SYMBOL_REF_DATA (sym_ref);
811       SYMBOL_REF_FLAGS (XEXP (target, 0)) |= MACHO_SYMBOL_FLAG_INDIRECTION;
812       MEM_READONLY_P (target) = 1;
813       MEM_NOTRAP_P (target) = 1;
814     }
815 
816   return target;
817 }
818 
819 rtx
machopic_legitimize_pic_address(rtx orig,machine_mode mode,rtx reg)820 machopic_legitimize_pic_address (rtx orig, machine_mode mode, rtx reg)
821 {
822   rtx pic_ref = orig;
823 
824   if (! MACHOPIC_INDIRECT)
825     return orig;
826 
827   /* First handle a simple SYMBOL_REF or LABEL_REF */
828   if (GET_CODE (orig) == LABEL_REF
829       || GET_CODE (orig) == SYMBOL_REF)
830     {
831       /* addr(foo) = &func+(foo-func) */
832       orig = machopic_indirect_data_reference (orig, reg);
833 
834       if (GET_CODE (orig) == PLUS
835 	  && GET_CODE (XEXP (orig, 0)) == REG)
836 	{
837 	  if (reg == 0)
838 	    return force_reg (mode, orig);
839 
840 	  emit_move_insn (reg, orig);
841 	  return reg;
842 	}
843 
844       if (GET_CODE (orig) == MEM)
845 	{
846 	  if (reg == 0)
847 	    {
848 	      gcc_assert (!lra_in_progress);
849 	      reg = gen_reg_rtx (Pmode);
850 	    }
851 
852 #if HAVE_lo_sum
853 	  if (MACHO_DYNAMIC_NO_PIC_P
854 	      && (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
855 		  || GET_CODE (XEXP (orig, 0)) == LABEL_REF))
856 	    {
857 #if defined (TARGET_TOC)	/* ppc  */
858 	      rtx temp_reg = (!can_create_pseudo_p ()
859 			      ? reg :
860 			      gen_reg_rtx (Pmode));
861 	      rtx asym = XEXP (orig, 0);
862 	      rtx mem;
863 
864 	      emit_insn (gen_macho_high (Pmode, temp_reg, asym));
865 	      mem = gen_const_mem (GET_MODE (orig),
866 				   gen_rtx_LO_SUM (Pmode, temp_reg,
867 						   copy_rtx (asym)));
868 	      emit_insn (gen_rtx_SET (reg, mem));
869 #else
870 	      /* Some other CPU -- WriteMe! but right now there are no other
871 		 platforms that can use dynamic-no-pic  */
872 	      gcc_unreachable ();
873 #endif
874 	      pic_ref = reg;
875 	    }
876 	  else
877 	  if (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
878 	      || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
879 	    {
880 	      rtx offset = machopic_gen_offset (XEXP (orig, 0));
881 #if defined (TARGET_TOC) /* i.e., PowerPC */
882 	      /* Generating a new reg may expose opportunities for
883 		 common subexpression elimination.  */
884               rtx hi_sum_reg = (!can_create_pseudo_p ()
885 				? reg
886 				: gen_reg_rtx (Pmode));
887 	      rtx mem;
888 	      rtx sum;
889 
890 	      sum = gen_rtx_HIGH (Pmode, offset);
891 	      if (! MACHO_DYNAMIC_NO_PIC_P)
892 		sum = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, sum);
893 
894 	      emit_insn (gen_rtx_SET (hi_sum_reg, sum));
895 
896 	      mem = gen_const_mem (GET_MODE (orig),
897 				  gen_rtx_LO_SUM (Pmode,
898 						  hi_sum_reg,
899 						  copy_rtx (offset)));
900 	      rtx_insn *insn = emit_insn (gen_rtx_SET (reg, mem));
901 	      set_unique_reg_note (insn, REG_EQUAL, pic_ref);
902 
903 	      pic_ref = reg;
904 #else
905 	      emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
906 
907 	      emit_insn (gen_rtx_SET (reg,
908 				      gen_rtx_HIGH (Pmode,
909 						    gen_rtx_CONST (Pmode,
910 								   offset))));
911 	      emit_insn (gen_rtx_SET (reg,
912 				  gen_rtx_LO_SUM (Pmode, reg,
913 					   gen_rtx_CONST (Pmode,
914 						   	  copy_rtx (offset)))));
915 	      pic_ref = gen_rtx_PLUS (Pmode,
916 				      pic_offset_table_rtx, reg);
917 #endif
918 	    }
919 	  else
920 #endif  /* HAVE_lo_sum */
921 	    {
922 	      rtx pic = pic_offset_table_rtx;
923 	      if (GET_CODE (pic) != REG)
924 		{
925 		  emit_move_insn (reg, pic);
926 		  pic = reg;
927 		}
928 
929 	      if (lra_in_progress && HARD_REGISTER_P (pic))
930 		df_set_regs_ever_live (REGNO (pic), true);
931 	      pic_ref = gen_rtx_PLUS (Pmode, pic,
932 				      machopic_gen_offset (XEXP (orig, 0)));
933 	    }
934 
935 #if !defined (TARGET_TOC)
936 	  emit_move_insn (reg, pic_ref);
937 	  pic_ref = gen_const_mem (GET_MODE (orig), reg);
938 #endif
939 	}
940       else
941 	{
942 
943 #if HAVE_lo_sum
944 	  if (GET_CODE (orig) == SYMBOL_REF
945 	      || GET_CODE (orig) == LABEL_REF)
946 	    {
947 	      rtx offset = machopic_gen_offset (orig);
948 #if defined (TARGET_TOC) /* i.e., PowerPC */
949               rtx hi_sum_reg;
950 
951 	      if (reg == 0)
952 		{
953 		  gcc_assert (!lra_in_progress);
954 		  reg = gen_reg_rtx (Pmode);
955 		}
956 
957 	      hi_sum_reg = reg;
958 
959 	      emit_insn (gen_rtx_SET (hi_sum_reg,
960 				      (MACHO_DYNAMIC_NO_PIC_P)
961 				      ? gen_rtx_HIGH (Pmode, offset)
962 				      : gen_rtx_PLUS (Pmode,
963 						      pic_offset_table_rtx,
964 						      gen_rtx_HIGH (Pmode,
965 								    offset))));
966 	      emit_insn (gen_rtx_SET (reg,
967 				      gen_rtx_LO_SUM (Pmode,
968 						      hi_sum_reg,
969 						      copy_rtx (offset))));
970 	      pic_ref = reg;
971 #else
972 	      emit_insn (gen_rtx_SET (reg, gen_rtx_HIGH (Pmode, offset)));
973 	      emit_insn (gen_rtx_SET (reg,
974 				      gen_rtx_LO_SUM (Pmode, reg,
975 						      copy_rtx (offset))));
976 	      pic_ref = gen_rtx_PLUS (Pmode,
977 				      pic_offset_table_rtx, reg);
978 #endif
979 	    }
980 	  else
981 #endif  /*  HAVE_lo_sum  */
982 	    {
983 	      if (REG_P (orig)
984 	          || GET_CODE (orig) == SUBREG)
985 		{
986 		  return orig;
987 		}
988 	      else
989 		{
990 		  rtx pic = pic_offset_table_rtx;
991 		  if (GET_CODE (pic) != REG)
992 		    {
993 		      emit_move_insn (reg, pic);
994 		      pic = reg;
995 		    }
996 
997 		  if (lra_in_progress && HARD_REGISTER_P (pic))
998 		    df_set_regs_ever_live (REGNO (pic), true);
999 		  pic_ref = gen_rtx_PLUS (Pmode,
1000 					  pic,
1001 					  machopic_gen_offset (orig));
1002 		}
1003 	    }
1004 	}
1005 
1006       if (GET_CODE (pic_ref) != REG)
1007 	{
1008 	  if (reg != 0)
1009 	    {
1010 	      emit_move_insn (reg, pic_ref);
1011 	      return reg;
1012 	    }
1013 	  else
1014 	    {
1015 	      return force_reg (mode, pic_ref);
1016 	    }
1017 	}
1018       else
1019 	{
1020 	  return pic_ref;
1021 	}
1022     }
1023   else if (GET_CODE (orig) == PLUS
1024 	   && (GET_CODE (XEXP (orig, 0)) == MEM
1025 	       || GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
1026 	       || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
1027 	   && XEXP (orig, 0) != pic_offset_table_rtx
1028 	   && GET_CODE (XEXP (orig, 1)) != REG)
1029 
1030     {
1031       rtx base;
1032       int is_complex = (GET_CODE (XEXP (orig, 0)) == MEM);
1033 
1034       base = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
1035       orig = machopic_legitimize_pic_address (XEXP (orig, 1),
1036 					      Pmode, (base == reg ? 0 : reg));
1037       if (GET_CODE (orig) == CONST_INT)
1038 	{
1039 	  pic_ref = plus_constant (Pmode, base, INTVAL (orig));
1040 	  is_complex = 1;
1041 	}
1042       else
1043 	pic_ref = gen_rtx_PLUS (Pmode, base, orig);
1044 
1045       if (reg && is_complex)
1046 	{
1047 	  emit_move_insn (reg, pic_ref);
1048 	  pic_ref = reg;
1049 	}
1050       /* Likewise, should we set special REG_NOTEs here?  */
1051     }
1052   else if (GET_CODE (orig) == CONST)
1053     {
1054       return machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
1055     }
1056   else if (GET_CODE (orig) == MEM
1057 	   && GET_CODE (XEXP (orig, 0)) == SYMBOL_REF)
1058     {
1059       rtx addr = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
1060       addr = replace_equiv_address (orig, addr);
1061       emit_move_insn (reg, addr);
1062       pic_ref = reg;
1063     }
1064 
1065   return pic_ref;
1066 }
1067 
1068 /* Callbacks to output the stub or non-lazy pointers.
1069    Each works on the item in *SLOT,if it has been used.
1070    DATA is the FILE* for assembly output.
1071    Called from htab_traverses, invoked from machopic_finish().  */
1072 
1073 int
machopic_output_data_section_indirection(machopic_indirection ** slot,FILE * out_file)1074 machopic_output_data_section_indirection (machopic_indirection **slot,
1075 					  FILE *out_file)
1076 {
1077   machopic_indirection *p = *slot;
1078 
1079   if (!p->used || !p->nlsp_in_data_section)
1080     return 1;
1081 
1082   rtx symbol = p->symbol;
1083   /* The original symbol name.  */
1084   const char *sym_name = XSTR (symbol, 0);
1085   /* The name of the indirection symbol.  */
1086   const char *ptr_name = p->ptr_name;
1087 
1088   switch_to_section (data_section);
1089   assemble_align (GET_MODE_ALIGNMENT (Pmode));
1090   assemble_label (out_file, ptr_name);
1091   assemble_integer (gen_rtx_SYMBOL_REF (Pmode, sym_name),
1092 		    GET_MODE_SIZE (Pmode),
1093 		    GET_MODE_ALIGNMENT (Pmode), 1);
1094 
1095   return 1;
1096 }
1097 
1098 int
machopic_output_stub_indirection(machopic_indirection ** slot,FILE * out_file)1099 machopic_output_stub_indirection (machopic_indirection **slot,
1100 				  FILE *out_file)
1101 {
1102   machopic_indirection *p = *slot;
1103 
1104   if (!p->used || !p->stub_p)
1105     return 1;
1106 
1107   rtx symbol = p->symbol;
1108   /* The original symbol name.  */
1109   const char *sym_name = XSTR (symbol, 0);
1110   /* The name of the stub symbol.  */
1111   const char *ptr_name = p->ptr_name;
1112 
1113   tree id = maybe_get_identifier (sym_name);
1114   if (id)
1115     {
1116       tree id_orig = id;
1117 
1118       while (IDENTIFIER_TRANSPARENT_ALIAS (id))
1119 	id = TREE_CHAIN (id);
1120       if (id != id_orig)
1121 	sym_name = IDENTIFIER_POINTER (id);
1122     }
1123 
1124   char *sym = XALLOCAVEC (char, strlen (sym_name) + 2);
1125   if (sym_name[0] == '*' || sym_name[0] == '&')
1126     strcpy (sym, sym_name + 1);
1127   else if (sym_name[0] == '-' || sym_name[0] == '+')
1128     strcpy (sym, sym_name);
1129   else
1130     sprintf (sym, "%s%s", user_label_prefix, sym_name);
1131 
1132   char *stub = XALLOCAVEC (char, strlen (ptr_name) + 2);
1133   if (ptr_name[0] == '*' || ptr_name[0] == '&')
1134     strcpy (stub, ptr_name + 1);
1135   else
1136     sprintf (stub, "%s%s", user_label_prefix, ptr_name);
1137 
1138   machopic_output_stub (out_file, sym, stub);
1139 
1140   return 1;
1141 }
1142 
1143 int
machopic_output_indirection(machopic_indirection ** slot,FILE * out_file)1144 machopic_output_indirection (machopic_indirection **slot, FILE *out_file)
1145 {
1146   machopic_indirection *p = *slot;
1147 
1148   if (!p->used || p->stub_p || p->nlsp_in_data_section)
1149     return 1;
1150 
1151   rtx symbol = p->symbol;
1152   /* The original symbol name.  */
1153   const char *sym_name = XSTR (symbol, 0);
1154   /* The nonlazy-stub symbol name.  */
1155   const char *ptr_name = p->ptr_name;
1156 
1157   switch_to_section (darwin_sections[machopic_nl_symbol_ptr_section]);
1158 
1159   /* Mach-O symbols are passed around in code through indirect references and
1160      the original symbol_ref hasn't passed through the generic handling and
1161      reference-catching in output_operand, so we need to manually mark weak
1162      references as such.  */
1163 
1164   if (SYMBOL_REF_WEAK (symbol))
1165     {
1166       tree decl = SYMBOL_REF_DECL (symbol);
1167       gcc_checking_assert (DECL_P (decl));
1168 
1169       if (decl != NULL_TREE
1170 	  && DECL_EXTERNAL (decl) && TREE_PUBLIC (decl)
1171 	  /* Handle only actual external-only definitions, not
1172 	     e.g. extern inline code or variables for which
1173 	     storage has been allocated.  */
1174 	  && !TREE_STATIC (decl))
1175 	{
1176 	  fputs ("\t.weak_reference ", out_file);
1177 	  assemble_name (out_file, sym_name);
1178 	  fputc ('\n', out_file);
1179 	}
1180     }
1181 
1182   assemble_name (out_file, ptr_name);
1183   fprintf (out_file, ":\n");
1184 
1185   fprintf (out_file, "\t.indirect_symbol ");
1186   assemble_name (out_file, sym_name);
1187   fprintf (out_file, "\n");
1188 
1189   /* Variables that are marked with MACHO_SYMBOL_FLAG_STATIC need to
1190      have their symbol name instead of 0 in the second entry of
1191      the non-lazy symbol pointer data structure when they are
1192      defined.  This allows the runtime to rebind newer instances
1193      of the translation unit with the original instance of the
1194      symbol.  */
1195 
1196   rtx init = const0_rtx;
1197   if (MACHO_SYMBOL_STATIC_P (symbol) && machopic_symbol_defined_p (symbol))
1198     init = gen_rtx_SYMBOL_REF (Pmode, sym_name);
1199 
1200   assemble_integer (init, GET_MODE_SIZE (Pmode),
1201 		    GET_MODE_ALIGNMENT (Pmode), 1);
1202 
1203   return 1;
1204 }
1205 
1206 static void
machopic_finish(FILE * out_file)1207 machopic_finish (FILE *out_file)
1208 {
1209   if (!machopic_indirections)
1210     return;
1211 
1212   /* First output an symbol indirections that have been placed into .data
1213      (we don't expect these now).  */
1214   machopic_indirections->traverse_noresize
1215     <FILE *, machopic_output_data_section_indirection> (out_file);
1216 
1217   machopic_indirections->traverse_noresize
1218     <FILE *, machopic_output_stub_indirection> (out_file);
1219 
1220   machopic_indirections->traverse_noresize
1221     <FILE *, machopic_output_indirection> (out_file);
1222 }
1223 
1224 int
machopic_operand_p(rtx op)1225 machopic_operand_p (rtx op)
1226 {
1227   if (MACHOPIC_JUST_INDIRECT)
1228     return (GET_CODE (op) == SYMBOL_REF
1229 	    && machopic_symbol_defined_p (op));
1230   else
1231     return (GET_CODE (op) == CONST
1232 	    && GET_CODE (XEXP (op, 0)) == UNSPEC
1233 	    && XINT (XEXP (op, 0), 1) == UNSPEC_MACHOPIC_OFFSET);
1234 }
1235 
1236 /* This function:
1237    computes and caches a series of flags that characterise the symbol's
1238    properties that affect Mach-O code gen (including accidental cases
1239    from older toolchains).
1240 
1241    TODO:
1242    Here we also need to do enough analysis to determine if a symbol's
1243    name needs to be made linker-visible.  This is more tricky - since
1244    it depends on whether we've previously seen a global weak definition
1245    in the same section.
1246    */
1247 
1248 void
darwin_encode_section_info(tree decl,rtx rtl,int first)1249 darwin_encode_section_info (tree decl, rtx rtl, int first)
1250 {
1251   /* Careful not to prod global register variables.  */
1252   if (!MEM_P (rtl))
1253     return;
1254 
1255   /* Do the standard encoding things first; this sets:
1256      SYMBOL_FLAG_FUNCTION,
1257      SYMBOL_FLAG_LOCAL, (binds_local_p)
1258      TLS_MODEL, SYMBOL_FLAG_SMALL
1259      SYMBOL_FLAG_EXTERNAL.  */
1260   default_encode_section_info (decl, rtl, first);
1261 
1262   if (! VAR_OR_FUNCTION_DECL_P (decl))
1263     return;
1264 
1265   rtx sym_ref = XEXP (rtl, 0);
1266   if (VAR_P (decl))
1267     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_VARIABLE;
1268 
1269   /* Only really common if there's no initialiser.  */
1270   bool really_common_p = (DECL_COMMON (decl)
1271 			  && (DECL_INITIAL (decl) == NULL
1272 			      || (!in_lto_p
1273 				  && DECL_INITIAL (decl) == error_mark_node)));
1274 
1275   /* For Darwin, if we have specified visibility and it's not the default
1276      that's counted 'hidden'.  */
1277   if (DECL_VISIBILITY_SPECIFIED (decl)
1278       && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT)
1279     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_HIDDEN_VIS;
1280 
1281   if (!DECL_EXTERNAL (decl)
1282       && (!TREE_PUBLIC (decl) || !DECL_WEAK (decl))
1283       && ! lookup_attribute ("weakref", DECL_ATTRIBUTES (decl))
1284       && ((TREE_STATIC (decl)
1285 	   && (!DECL_COMMON (decl) || !TREE_PUBLIC (decl)))
1286 	  || (!DECL_COMMON (decl) && DECL_INITIAL (decl)
1287 	      && DECL_INITIAL (decl) != error_mark_node)))
1288     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
1289 
1290   if (! TREE_PUBLIC (decl))
1291     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_STATIC;
1292 
1293   /* Short cut check for Darwin 'must indirect' rules.  */
1294   if (really_common_p
1295       || (DECL_WEAK (decl) && ! MACHO_SYMBOL_HIDDEN_VIS_P (sym_ref))
1296       || lookup_attribute ("weakref", DECL_ATTRIBUTES (decl)))
1297      SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_MUST_INDIRECT;
1298 
1299 #if DARWIN_PPC
1300   /* Objective C V2 (m64) IVAR offset refs from Apple GCC-4.x have an
1301      indirection for m64 code on PPC.  Historically, these indirections
1302      also appear in the .data section.  */
1303   tree o2meta = lookup_attribute ("OBJC2META", DECL_ATTRIBUTES (decl));
1304   o2meta = o2meta ? TREE_VALUE (o2meta) : NULL_TREE;
1305 
1306   if (o2meta && startswith (IDENTIFIER_POINTER (o2meta), "V2_IVRF"))
1307     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_MUST_INDIRECT;
1308 #endif
1309 }
1310 
1311 void
darwin_mark_decl_preserved(const char * name)1312 darwin_mark_decl_preserved (const char *name)
1313 {
1314   /* Actually we shouldn't mark any local symbol this way, but for now
1315      this only happens with ObjC meta-data.  */
1316   if (darwin_label_is_anonymous_local_objc_name (name))
1317     return;
1318 
1319   fprintf (asm_out_file, "\t.no_dead_strip ");
1320   assemble_name (asm_out_file, name);
1321   fputc ('\n', asm_out_file);
1322 }
1323 
1324 static section *
darwin_rodata_section(int use_coal,bool zsize,int reloc)1325 darwin_rodata_section (int use_coal, bool zsize, int reloc)
1326 {
1327   return (use_coal
1328 	  ? darwin_sections[const_coal_section]
1329 	  : (zsize ? darwin_sections[zobj_const_section]
1330 		   : reloc ? darwin_sections[const_data_section]
1331 			   : darwin_sections[const_section]));
1332 }
1333 
1334 static section *
darwin_mergeable_string_section(tree exp,unsigned HOST_WIDE_INT align)1335 darwin_mergeable_string_section (tree exp,
1336 				 unsigned HOST_WIDE_INT align)
1337 {
1338   /* Darwin's ld expects to see non-writable string literals in the .cstring
1339      section.  Later versions of ld check and complain when CFStrings are
1340      enabled.  Therefore we shall force the strings into .cstring since we
1341      don't support writable ones anyway.  */
1342   if ((darwin_constant_cfstrings || flag_merge_constants)
1343       && TREE_CODE (exp) == STRING_CST
1344       && TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
1345       && align <= 256
1346       && (int_size_in_bytes (TREE_TYPE (exp))
1347 	  == TREE_STRING_LENGTH (exp))
1348       && ((size_t) TREE_STRING_LENGTH (exp)
1349 	  == strlen (TREE_STRING_POINTER (exp)) + 1))
1350     return darwin_sections[cstring_section];
1351 
1352   if (DARWIN_SECTION_ANCHORS && flag_section_anchors
1353       && TREE_CODE (exp) == STRING_CST
1354       && TREE_STRING_LENGTH (exp) == 0)
1355     return darwin_sections[zobj_const_section];
1356 
1357   return readonly_data_section;
1358 }
1359 
1360 #ifndef HAVE_GAS_LITERAL16
1361 #define HAVE_GAS_LITERAL16 0
1362 #endif
1363 
1364 static section *
darwin_mergeable_constant_section(tree exp,unsigned HOST_WIDE_INT align,bool zsize)1365 darwin_mergeable_constant_section (tree exp,
1366 				   unsigned HOST_WIDE_INT align,
1367 				   bool zsize)
1368 {
1369   if (zsize)
1370     return darwin_sections[zobj_const_section];
1371 
1372   machine_mode mode = DECL_MODE (exp);
1373   if (!flag_merge_constants
1374       || mode == VOIDmode
1375       || mode == BLKmode
1376       || align < 8
1377       || align > 256
1378       || (align & (align -1)) != 0)
1379     return readonly_data_section;
1380 
1381   /* This will ICE if the mode is not a constant size, but that is reasonable,
1382      since one cannot put a variable-sized thing into a constant section, we
1383      shouldn't be trying.  */
1384   const unsigned int modesize = GET_MODE_BITSIZE (mode).to_constant ();
1385 
1386   if (modesize > align)
1387     return readonly_data_section;
1388 
1389   tree size = TYPE_SIZE_UNIT (TREE_TYPE (exp));
1390 
1391   if (TREE_CODE (size) != INTEGER_CST)
1392     return readonly_data_section;
1393 
1394   unsigned isize = TREE_INT_CST_LOW (size);
1395   if (isize == 4)
1396     return darwin_sections[literal4_section];
1397   else if (isize == 8)
1398     return darwin_sections[literal8_section];
1399   else if (HAVE_GAS_LITERAL16
1400 	   && TARGET_64BIT
1401 	   && isize == 16)
1402     return darwin_sections[literal16_section];
1403 
1404   return readonly_data_section;
1405 }
1406 
1407 section *
darwin_tm_clone_table_section(void)1408 darwin_tm_clone_table_section (void)
1409 {
1410   return get_named_section (NULL,
1411 			    "__DATA,__tm_clone_table,regular,no_dead_strip",
1412 			    3);
1413 }
1414 
1415 int
machopic_reloc_rw_mask(void)1416 machopic_reloc_rw_mask (void)
1417 {
1418   return MACHOPIC_INDIRECT ? 3 : 0;
1419 }
1420 
1421 /* We have to deal with ObjC/C++ metadata section placement in the common
1422    code, since it will also be called from LTO.
1423 
1424    Return metadata attributes, if present (searching for ABI=2 first)
1425    Return NULL_TREE if no such attributes are found.  */
1426 
1427 static tree
is_objc_metadata(tree decl)1428 is_objc_metadata (tree decl)
1429 {
1430   if (DECL_P (decl)
1431       && (TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == CONST_DECL)
1432       && DECL_ATTRIBUTES (decl))
1433     {
1434       tree meta = lookup_attribute ("OBJC2META", DECL_ATTRIBUTES (decl));
1435       if (meta)
1436 	return meta;
1437       meta = lookup_attribute ("OBJC1META", DECL_ATTRIBUTES (decl));
1438       if (meta)
1439 	return meta;
1440     }
1441   return NULL_TREE;
1442 }
1443 
1444 static int classes_seen;
1445 static int objc_metadata_seen;
1446 
1447 /* Return the section required for Objective C ABI 2 metadata.  */
1448 static section *
darwin_objc2_section(tree decl ATTRIBUTE_UNUSED,tree meta,section * base)1449 darwin_objc2_section (tree decl ATTRIBUTE_UNUSED, tree meta, section * base)
1450 {
1451   const char *p;
1452   tree ident = TREE_VALUE (meta);
1453   gcc_assert (TREE_CODE (ident) == IDENTIFIER_NODE);
1454   p = IDENTIFIER_POINTER (ident);
1455 
1456   gcc_checking_assert (flag_next_runtime >= 1 && flag_objc_abi == 2);
1457 
1458   objc_metadata_seen = 1;
1459 
1460   if (base == data_section)
1461     base = darwin_sections[objc2_metadata_section];
1462 
1463   /* Most of the OBJC2 META-data end up in the base section, so check it
1464      first.  */
1465   if      (startswith (p, "V2_BASE"))
1466     return base;
1467   else if (startswith (p, "V2_CNAM"))
1468     return darwin_sections[objc2_class_names_section];
1469   else if (startswith (p, "V2_MNAM"))
1470     return darwin_sections[objc2_method_names_section];
1471   else if (startswith (p, "V2_MTYP"))
1472     return darwin_sections[objc2_method_types_section];
1473   else if (startswith (p, "V2_STRG"))
1474     return darwin_sections[cstring_section];
1475 
1476   else if (startswith (p, "G2_META") || startswith (p, "G2_CLAS"))
1477     return darwin_sections[objc2_classdefs_section];
1478   else if (startswith (p, "V2_PCOL"))
1479     return ld_uses_coal_sects ? darwin_sections[data_coal_section]
1480 			      : darwin_sections[objc2_data_section];
1481   else if (startswith (p, "V2_MREF"))
1482     return darwin_sections[objc2_message_refs_section];
1483   else if (startswith (p, "V2_CLRF"))
1484     return darwin_sections[objc2_classrefs_section];
1485   else if (startswith (p, "V2_SURF"))
1486     return darwin_sections[objc2_super_classrefs_section];
1487   else if (startswith (p, "V2_NLCL"))
1488     return darwin_sections[objc2_nonlazy_class_section];
1489   else if (startswith (p, "V2_CLAB"))
1490     {
1491       classes_seen = 1;
1492       return darwin_sections[objc2_classlist_section];
1493     }
1494   else if (startswith (p, "V2_SRFS"))
1495     return darwin_sections[objc2_selector_refs_section];
1496   else if (startswith (p, "V2_NLCA"))
1497     return darwin_sections[objc2_nonlazy_category_section];
1498   else if (startswith (p, "V2_CALA"))
1499     return darwin_sections[objc2_categorylist_section];
1500 
1501   else if (startswith (p, "V2_PLST"))
1502     return darwin_sections[objc2_protocollist_section];
1503   else if (startswith (p, "V2_PRFS"))
1504     return darwin_sections[objc2_protocolrefs_section];
1505 
1506   else if (startswith (p, "V2_INFO"))
1507     return darwin_sections[objc2_image_info_section];
1508 
1509   else if (startswith (p, "V2_EHTY"))
1510     return ld_uses_coal_sects ? darwin_sections[data_coal_section]
1511                               : data_section;
1512 
1513   else if (startswith (p, "V2_CSTR"))
1514     return darwin_sections[objc2_constant_string_object_section];
1515 
1516   else if (startswith (p, "V2_IVRF"))
1517     return darwin_sections[objc2_ivar_section];
1518 
1519   /* Not recognized, default.  */
1520   return base;
1521 }
1522 
1523 /* Return the section required for Objective C ABI 0/1 metadata.  */
1524 static section *
darwin_objc1_section(tree decl ATTRIBUTE_UNUSED,tree meta,section * base)1525 darwin_objc1_section (tree decl ATTRIBUTE_UNUSED, tree meta, section * base)
1526 {
1527   const char *p;
1528   tree ident = TREE_VALUE (meta);
1529   gcc_assert (TREE_CODE (ident) == IDENTIFIER_NODE);
1530   p = IDENTIFIER_POINTER (ident);
1531 
1532   gcc_checking_assert (flag_next_runtime >= 1 && flag_objc_abi < 2);
1533 
1534   objc_metadata_seen = 1;
1535 
1536   /* String sections first, cos there are lots of strings.  */
1537   if      (startswith (p, "V1_STRG"))
1538     return darwin_sections[cstring_section];
1539   else if (startswith (p, "V1_CLSN"))
1540     return darwin_sections[objc_class_names_section];
1541   else if (startswith (p, "V1_METN"))
1542     return darwin_sections[objc_meth_var_names_section];
1543   else if (startswith (p, "V1_METT"))
1544     return darwin_sections[objc_meth_var_types_section];
1545 
1546   else if (startswith (p, "V1_CLAS"))
1547     {
1548       classes_seen = 1;
1549       return darwin_sections[objc_class_section];
1550     }
1551   else if (startswith (p, "V1_META"))
1552     return darwin_sections[objc_meta_class_section];
1553   else if (startswith (p, "V1_CATG"))
1554     return darwin_sections[objc_category_section];
1555   else if (startswith (p, "V1_PROT"))
1556     return darwin_sections[objc_protocol_section];
1557 
1558   else if (startswith (p, "V1_CLCV"))
1559     return darwin_sections[objc_class_vars_section];
1560   else if (startswith (p, "V1_CLIV"))
1561     return darwin_sections[objc_instance_vars_section];
1562 
1563   else if (startswith (p, "V1_CLCM"))
1564     return darwin_sections[objc_cls_meth_section];
1565   else if (startswith (p, "V1_CLIM"))
1566     return darwin_sections[objc_inst_meth_section];
1567   else if (startswith (p, "V1_CACM"))
1568     return darwin_sections[objc_cat_cls_meth_section];
1569   else if (startswith (p, "V1_CAIM"))
1570     return darwin_sections[objc_cat_inst_meth_section];
1571   else if (startswith (p, "V1_PNSM"))
1572     return darwin_sections[objc_cat_inst_meth_section];
1573   else if (startswith (p, "V1_PCLM"))
1574     return darwin_sections[objc_cat_cls_meth_section];
1575 
1576   else if (startswith (p, "V1_CLPR"))
1577     return darwin_sections[objc_cat_cls_meth_section];
1578   else if (startswith (p, "V1_CAPR"))
1579     return darwin_sections[objc_category_section]; /* ??? CHECK me.  */
1580 
1581   else if (startswith (p, "V1_PRFS"))
1582     return darwin_sections[objc_cat_cls_meth_section];
1583   else if (startswith (p, "V1_CLRF"))
1584     return darwin_sections[objc_cls_refs_section];
1585   else if (startswith (p, "V1_SRFS"))
1586     return darwin_sections[objc_selector_refs_section];
1587 
1588   else if (startswith (p, "V1_MODU"))
1589     return darwin_sections[objc_module_info_section];
1590   else if (startswith (p, "V1_SYMT"))
1591     return darwin_sections[objc_symbols_section];
1592   else if (startswith (p, "V1_INFO"))
1593     return darwin_sections[objc_image_info_section];
1594 
1595   else if (startswith (p, "V1_PLST"))
1596     return darwin_sections[objc1_prop_list_section];
1597   else if (startswith (p, "V1_PEXT"))
1598     return darwin_sections[objc1_protocol_ext_section];
1599   else if (startswith (p, "V1_CEXT"))
1600     return darwin_sections[objc1_class_ext_section];
1601 
1602   else if (startswith (p, "V1_CSTR"))
1603     return darwin_sections[objc_constant_string_object_section];
1604 
1605   return base;
1606 }
1607 
1608 section *
machopic_select_section(tree decl,int reloc,unsigned HOST_WIDE_INT align)1609 machopic_select_section (tree decl,
1610 			 int reloc,
1611 			 unsigned HOST_WIDE_INT align)
1612 {
1613   bool zsize, one, weak, use_coal, ro;
1614   section *base_section = NULL;
1615 
1616   weak = (DECL_P (decl)
1617 	  && DECL_WEAK (decl)
1618 	  && !lookup_attribute ("weak_import", DECL_ATTRIBUTES (decl)));
1619 
1620   /* Darwin pads zero-sized objects with at least one byte, so that the ld64
1621      atom model is preserved (objects must have distinct regions starting with
1622      a unique linker-visible symbol).
1623      In order to support section anchors, we need to move objects with zero
1624      size into sections which are marked as "no section anchors"; the padded
1625      objects, obviously, have real sizes that differ from their DECL sizes.  */
1626   zsize = DARWIN_SECTION_ANCHORS && flag_section_anchors;
1627 
1628   /* In the streaming of LTO symbol data, we might have a situation where the
1629      var is incomplete or layout not finished (DECL_SIZE_UNIT is NULL_TREE).
1630      We cannot tell if it is zero-sized then, but we can get the section
1631      category correct so that nm reports the right kind of section
1632      (e.g. BSS c.f. data).  */
1633   zsize = (zsize
1634 	   && DECL_P (decl)
1635 	   && (TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == CONST_DECL)
1636 	   && DECL_SIZE_UNIT (decl)
1637 	   && tree_to_uhwi (DECL_SIZE_UNIT (decl)) == 0);
1638 
1639   one = DECL_P (decl)
1640 	&& TREE_CODE (decl) == VAR_DECL
1641 	&& DECL_COMDAT_GROUP (decl);
1642 
1643   use_coal = (weak || one) && ld_uses_coal_sects;
1644 
1645   ro = TREE_READONLY (decl) || TREE_CONSTANT (decl) ;
1646 
1647   switch (categorize_decl_for_section (decl, reloc))
1648     {
1649     case SECCAT_TEXT:
1650       gcc_unreachable ();
1651       break;
1652 
1653     case SECCAT_RODATA:
1654     case SECCAT_SRODATA:
1655       base_section = darwin_rodata_section (use_coal, zsize, reloc);
1656       break;
1657 
1658     case SECCAT_RODATA_MERGE_STR:
1659       base_section = darwin_mergeable_string_section (decl, align);
1660       break;
1661 
1662     case SECCAT_RODATA_MERGE_STR_INIT:
1663       base_section = darwin_mergeable_string_section (DECL_INITIAL (decl), align);
1664       break;
1665 
1666     case SECCAT_RODATA_MERGE_CONST:
1667       base_section =  darwin_mergeable_constant_section (decl, align, zsize);
1668       break;
1669 
1670     case SECCAT_DATA:
1671     case SECCAT_DATA_REL:
1672     case SECCAT_DATA_REL_LOCAL:
1673     case SECCAT_DATA_REL_RO:
1674     case SECCAT_DATA_REL_RO_LOCAL:
1675     case SECCAT_SDATA:
1676     case SECCAT_TDATA:
1677       if (use_coal)
1678 	{
1679 	  if (ro)
1680 	    base_section = darwin_sections[const_data_coal_section];
1681 	  else
1682 	    base_section = darwin_sections[data_coal_section];
1683 	}
1684       else if (zsize)
1685 	{
1686 	  /* If we're doing section anchors, then punt zero-sized objects into
1687 	     their own sections so that they don't interfere with offset
1688 	     computation for the remaining vars.  */
1689 	  if (ro)
1690 	    base_section = darwin_sections[zobj_const_data_section];
1691 	  else
1692 	    base_section = darwin_sections[zobj_data_section];
1693 	}
1694       else if (ro)
1695 	{
1696 	  if (VAR_P (decl) && TREE_TYPE (decl)
1697 	      && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
1698 	      && DECL_NAME (decl)
1699 	      && strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
1700 			  "__anon_cfstring", 15) == 0)
1701 	   base_section = darwin_sections[cfstring_constant_object_section];
1702 	  else
1703 	    base_section = darwin_sections[const_data_section];
1704 	}
1705       else
1706 	base_section = data_section;
1707       break;
1708     case SECCAT_BSS:
1709     case SECCAT_SBSS:
1710     case SECCAT_TBSS:
1711       if (use_coal)
1712 	base_section = darwin_sections[data_coal_section];
1713       else
1714 	{
1715 	  if (!TREE_PUBLIC (decl))
1716 	    base_section = lcomm_section;
1717 	  else if (bss_noswitch_section)
1718 	    base_section = bss_noswitch_section;
1719 	  else
1720 	    base_section = data_section;
1721 	}
1722       break;
1723 
1724     default:
1725       gcc_unreachable ();
1726     }
1727 
1728   /* Darwin weird special cases.
1729      a) OBJC Meta-data. */
1730   if (DECL_P (decl)
1731       && (TREE_CODE (decl) == VAR_DECL
1732 	  || TREE_CODE (decl) == CONST_DECL)
1733       && DECL_ATTRIBUTES (decl))
1734     {
1735       tree meta = lookup_attribute ("OBJC2META", DECL_ATTRIBUTES (decl));
1736       if (meta)
1737 	return darwin_objc2_section (decl, meta, base_section);
1738       meta = lookup_attribute ("OBJC1META", DECL_ATTRIBUTES (decl));
1739       if (meta)
1740 	return darwin_objc1_section (decl, meta, base_section);
1741       meta = lookup_attribute ("OBJC1METG", DECL_ATTRIBUTES (decl));
1742       if (meta)
1743 	return base_section; /* GNU runtime is happy with it all in one pot.  */
1744     }
1745 
1746   /* b) Constructors for constant NSstring [but not CFString] objects.  */
1747   if (TREE_CODE (decl) == CONSTRUCTOR
1748       && TREE_TYPE (decl)
1749       && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
1750       && TYPE_NAME (TREE_TYPE (decl)))
1751     {
1752       tree name = TYPE_NAME (TREE_TYPE (decl));
1753       if (TREE_CODE (name) == TYPE_DECL)
1754         name = DECL_NAME (name);
1755 
1756       if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_ObjCString"))
1757 	{
1758 	  if (flag_next_runtime)
1759 	    {
1760 	      if (flag_objc_abi == 2)
1761 		return darwin_sections[objc2_constant_string_object_section];
1762 	      else
1763 		return darwin_sections[objc_constant_string_object_section];
1764 	    }
1765 	  else
1766 	    return darwin_sections[objc_string_object_section];
1767 	}
1768       else if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_CFString"))
1769 	{
1770 	  /* We should have handled __anon_cfstrings above.  */
1771 	  gcc_checking_assert (0);
1772 	  return darwin_sections[cfstring_constant_object_section];
1773 	}
1774       else
1775 	return base_section;
1776     }
1777   else if (flag_next_runtime
1778 	   && VAR_P (decl)
1779 	   && DECL_NAME (decl)
1780 	   && TREE_CODE (DECL_NAME (decl)) == IDENTIFIER_NODE
1781 	   && IDENTIFIER_POINTER (DECL_NAME (decl))
1782 	   && startswith (IDENTIFIER_POINTER (DECL_NAME (decl)), "_OBJC_"))
1783     /* c) legacy meta-data selection was deprecated at 4.6, removed now.  */
1784     gcc_unreachable ();
1785 
1786   return base_section;
1787 }
1788 
1789 /* This can be called with address expressions as "rtx".
1790    They must go in "const".  */
1791 
1792 section *
machopic_select_rtx_section(machine_mode mode,rtx x,unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)1793 machopic_select_rtx_section (machine_mode mode, rtx x,
1794 			     unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
1795 {
1796   if (known_eq (GET_MODE_SIZE (mode), 8)
1797       && (GET_CODE (x) == CONST_INT
1798 	  || GET_CODE (x) == CONST_WIDE_INT
1799 	  || GET_CODE (x) == CONST_DOUBLE))
1800     return darwin_sections[literal8_section];
1801   else if (known_eq (GET_MODE_SIZE (mode), 4)
1802 	   && (GET_CODE (x) == CONST_INT
1803 	       || GET_CODE (x) == CONST_WIDE_INT
1804 	       || GET_CODE (x) == CONST_DOUBLE))
1805     return darwin_sections[literal4_section];
1806   else if (HAVE_GAS_LITERAL16
1807 	   && TARGET_64BIT
1808 	   && known_eq (GET_MODE_SIZE (mode), 16)
1809 	   && (GET_CODE (x) == CONST_INT
1810 	       || GET_CODE (x) == CONST_WIDE_INT
1811 	       || GET_CODE (x) == CONST_DOUBLE
1812 	       || GET_CODE (x) == CONST_VECTOR))
1813     return darwin_sections[literal16_section];
1814   else if (MACHOPIC_INDIRECT
1815 	   && (GET_CODE (x) == SYMBOL_REF
1816 	       || GET_CODE (x) == CONST
1817 	       || GET_CODE (x) == LABEL_REF))
1818     return darwin_sections[const_data_section];
1819   else
1820     return darwin_sections[const_section];
1821 }
1822 
1823 void
machopic_asm_out_constructor(rtx symbol,int priority ATTRIBUTE_UNUSED)1824 machopic_asm_out_constructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1825 {
1826   cdtor_record new_elt = {symbol, priority, vec_safe_length (ctors)};
1827 
1828   vec_safe_push (ctors, new_elt);
1829 
1830   if (! MACHOPIC_INDIRECT)
1831     fprintf (asm_out_file, ".reference .constructors_used\n");
1832 }
1833 
1834 void
machopic_asm_out_destructor(rtx symbol,int priority ATTRIBUTE_UNUSED)1835 machopic_asm_out_destructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1836 {
1837   cdtor_record new_elt = {symbol, priority, vec_safe_length (dtors)};
1838 
1839   vec_safe_push (dtors, new_elt);
1840 
1841   if (! MACHOPIC_INDIRECT)
1842     fprintf (asm_out_file, ".reference .destructors_used\n");
1843 }
1844 
1845 static int
sort_cdtor_records(const void * a,const void * b)1846 sort_cdtor_records (const void * a, const void * b)
1847 {
1848   const cdtor_record *cda = (const cdtor_record *)a;
1849   const cdtor_record *cdb = (const cdtor_record *)b;
1850   if (cda->priority > cdb->priority)
1851     return 1;
1852   if (cda->priority < cdb->priority)
1853     return -1;
1854   if (cda->position > cdb->position)
1855     return 1;
1856   if (cda->position < cdb->position)
1857     return -1;
1858   return 0;
1859 }
1860 
1861 static void
finalize_ctors()1862 finalize_ctors ()
1863 {
1864   unsigned int i;
1865   cdtor_record *elt;
1866 
1867   if (MACHOPIC_INDIRECT)
1868     switch_to_section (darwin_sections[mod_init_section]);
1869   else
1870     switch_to_section (darwin_sections[constructor_section]);
1871 
1872   /* Where needed, provide a linker-visible section-start symbol so that we
1873      have stable output between debug and non-debug.  */
1874   if (ld_init_term_start_labels)
1875     fputs (MACHOPIC_INDIRECT ? "_Mod.init:\n" : "_CTOR.sect:\n", asm_out_file);
1876 
1877   if (vec_safe_length (ctors) > 1)
1878     ctors->qsort (sort_cdtor_records);
1879   FOR_EACH_VEC_SAFE_ELT (ctors, i, elt)
1880     {
1881       assemble_align (POINTER_SIZE);
1882       assemble_integer (elt->symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1883     }
1884 }
1885 
1886 static void
finalize_dtors()1887 finalize_dtors ()
1888 {
1889   unsigned int i;
1890   cdtor_record *elt;
1891 
1892   if (MACHOPIC_INDIRECT)
1893     switch_to_section (darwin_sections[mod_term_section]);
1894   else
1895     switch_to_section (darwin_sections[destructor_section]);
1896 
1897   /* Where needed, provide a linker-visible section-start symbol so that we
1898      have stable output between debug and non-debug.  */
1899   if (ld_init_term_start_labels)
1900     fputs (MACHOPIC_INDIRECT ? "_Mod.term:\n" : "_DTOR.sect:\n", asm_out_file);
1901 
1902   if (vec_safe_length (dtors) > 1)
1903     dtors->qsort (sort_cdtor_records);
1904   FOR_EACH_VEC_SAFE_ELT (dtors, i, elt)
1905     {
1906       assemble_align (POINTER_SIZE);
1907       assemble_integer (elt->symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1908     }
1909 }
1910 
1911 void
darwin_globalize_label(FILE * stream,const char * name)1912 darwin_globalize_label (FILE *stream, const char *name)
1913 {
1914   if (!startswith (name, "_OBJC_"))
1915     default_globalize_label (stream, name);
1916   /* We have some Objective C cases that need to be global, but only on newer
1917      OS versions.  */
1918   if (flag_objc_abi < 2 || flag_next_runtime < 100700)
1919     return;
1920   if (startswith (name+6, "LabelPro"))
1921     default_globalize_label (stream, name);
1922   if (startswith (name+6, "Protocol_"))
1923     default_globalize_label (stream, name);
1924 }
1925 
1926 /* This routine returns non-zero if 'name' starts with the special objective-c
1927    anonymous file-scope static name.  It accommodates c++'s mangling of such
1928    symbols (in this case the symbols will have form _ZL{d}*_OBJC_* d=digit).  */
1929 
1930 int
darwin_label_is_anonymous_local_objc_name(const char * name)1931 darwin_label_is_anonymous_local_objc_name (const char *name)
1932 {
1933   const unsigned char *p = (const unsigned char *) name;
1934   if (*p != '_')
1935     return 0;
1936   if (p[1] == 'Z' && p[2] == 'L')
1937   {
1938     p += 3;
1939     while (*p >= '0' && *p <= '9')
1940       p++;
1941   }
1942   if (!startswith ((const char *)p, "_OBJC_"))
1943     return false;
1944 
1945   /* We need some of the objective c meta-data symbols to be visible to the
1946      linker (when the target OS version is newer).  FIXME: this is horrible,
1947      we need a better mechanism.  */
1948 
1949   if (flag_objc_abi < 2 || flag_next_runtime < 100700)
1950     return true;
1951 
1952   p += 6;
1953   if (startswith ((const char *)p, "ClassRef"))
1954     return false;
1955   else if (startswith ((const char *)p, "SelRef"))
1956     return false;
1957   else if (startswith ((const char *)p, "Category"))
1958     {
1959       if (p[8] == '_' || p[8] == 'I' || p[8] == 'P' || p[8] == 'C' )
1960 	return false;
1961       return true;
1962     }
1963   else if (startswith ((const char *)p, "ClassMethods"))
1964     return false;
1965   else if (startswith ((const char *)p, "ClassProtocols"))
1966     return false;
1967   else if (startswith ((const char *)p, "Instance"))
1968     {
1969       if (p[8] == 'I' || p[8] == 'M')
1970 	return false;
1971       return true;
1972     }
1973   else if (startswith ((const char *)p, "CLASS_RO"))
1974     return false;
1975   else if (startswith ((const char *)p, "METACLASS_RO"))
1976     return false;
1977   else if (startswith ((const char *)p, "Protocol"))
1978     {
1979       if (p[8] == '_' || p[8] == 'I' || p[8] == 'P'
1980 	  || p[8] == 'M' || p[8] == 'C' || p[8] == 'O')
1981 	return false;
1982       return true;
1983     }
1984   else if (startswith ((const char *)p, "LabelPro"))
1985     return false;
1986   return true;
1987 }
1988 
1989 /* LTO support for Mach-O.
1990 
1991    This version uses three mach-o sections to encapsulate the (unlimited
1992    number of) lto sections.
1993 
1994    __GNU_LTO, __lto_sections  contains the concatented GNU LTO section data.
1995    __GNU_LTO, __section_names contains the GNU LTO section names.
1996    __GNU_LTO, __section_index contains an array of values that index these.
1997 
1998    Indexed thus:
1999      <section offset from the start of __GNU_LTO, __lto_sections>,
2000      <section length>
2001      <name offset from the start of __GNU_LTO, __section_names,
2002      <name length>.
2003 
2004    At present, for both m32 and m64 mach-o files each of these fields is
2005    represented  by a uint32_t.  This is because, AFAICT, a mach-o object
2006    cannot exceed 4Gb because the section_64 offset field (see below) is 32bits.
2007 
2008     uint32_t offset;
2009    "offset  An integer specifying the offset to this section in the file."  */
2010 
2011 /* Count lto section numbers.  */
2012 static unsigned int lto_section_num = 0;
2013 
2014 /* A vector of information about LTO sections, at present, we only have
2015    the name.  TODO: see if we can get the data length somehow.  */
2016 typedef struct GTY (()) darwin_lto_section_e {
2017   const char *sectname;
2018 } darwin_lto_section_e ;
2019 
2020 static GTY (()) vec<darwin_lto_section_e, va_gc> *lto_section_names;
2021 
2022 /* Section wrapper scheme (used here to wrap the unlimited number of LTO
2023    sections into three Mach-O ones).
2024    NOTE: These names MUST be kept in sync with those in
2025 	 libiberty/simple-object-mach-o.  */
2026 #define LTO_SECTS_SECTION "__wrapper_sects"
2027 #define LTO_NAMES_SECTION "__wrapper_names"
2028 #define LTO_INDEX_SECTION "__wrapper_index"
2029 
2030 /* File to temporarily store LTO data.  This is appended to asm_out_file
2031    in darwin_end_file.  */
2032 static FILE *lto_asm_out_file, *saved_asm_out_file;
2033 static char *lto_asm_out_name;
2034 static enum debug_info_levels saved_debug_info_level;
2035 
2036 /* Prepare asm_out_file for LTO output.  For darwin, this means hiding
2037    asm_out_file and switching to an alternative output file.  */
2038 void
darwin_asm_lto_start(void)2039 darwin_asm_lto_start (void)
2040 {
2041   gcc_assert (! saved_asm_out_file);
2042   saved_asm_out_file = asm_out_file;
2043   saved_debug_info_level = debug_info_level;
2044   debug_info_level = DINFO_LEVEL_NONE;
2045   if (! lto_asm_out_name)
2046     lto_asm_out_name = make_temp_file (".lto.s");
2047   lto_asm_out_file = fopen (lto_asm_out_name, "a");
2048   if (lto_asm_out_file == NULL)
2049     fatal_error (input_location,
2050 		 "failed to open temporary file %s for LTO output",
2051 		 lto_asm_out_name);
2052   asm_out_file = lto_asm_out_file;
2053 }
2054 
2055 /* Restore asm_out_file.  */
2056 void
darwin_asm_lto_end(void)2057 darwin_asm_lto_end (void)
2058 {
2059   gcc_assert (saved_asm_out_file);
2060   fclose (lto_asm_out_file);
2061   asm_out_file = saved_asm_out_file;
2062   saved_asm_out_file = NULL;
2063   debug_info_level = saved_debug_info_level;
2064 }
2065 
2066 static void
2067 darwin_asm_dwarf_section (const char *name, unsigned int flags,
2068 			  tree decl, bool is_for_lto);
2069 
2070 /*  Called for the TARGET_ASM_NAMED_SECTION hook.  */
2071 
2072 void
darwin_asm_named_section(const char * name,unsigned int flags,tree decl ATTRIBUTE_UNUSED)2073 darwin_asm_named_section (const char *name,
2074 			  unsigned int flags,
2075 			  tree decl ATTRIBUTE_UNUSED)
2076 {
2077   /* LTO sections go in a special section that encapsulates the (unlimited)
2078      number of GNU LTO sections within a single mach-o one.  */
2079   if (startswith (name, LTO_SECTION_NAME_PREFIX))
2080     {
2081       darwin_lto_section_e e;
2082       /* We expect certain flags to be set...  */
2083       gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
2084 		  == (SECTION_DEBUG | SECTION_NAMED));
2085 
2086       /* Switch to our combined section.  */
2087       fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
2088 	       LTO_SEGMENT_NAME, LTO_SECTS_SECTION);
2089       /* Output a label for the start of this sub-section.  */
2090       fprintf (asm_out_file, "L_GNU_LTO%d:\t;# %s\n",
2091 	       lto_section_num, name);
2092       /* We have to jump through hoops to get the values of the intra-section
2093          offsets... */
2094       fprintf (asm_out_file, "\t.set L$gnu$lto$offs%d,L_GNU_LTO%d-L_GNU_LTO0\n",
2095 	       lto_section_num, lto_section_num);
2096       fprintf (asm_out_file,
2097 	       "\t.set L$gnu$lto$size%d,L_GNU_LTO%d-L_GNU_LTO%d\n",
2098 	       lto_section_num, lto_section_num+1, lto_section_num);
2099       lto_section_num++;
2100       e.sectname = xstrdup (name);
2101       /* Keep the names, we'll need to make a table later.
2102          TODO: check that we do not revisit sections, that would break
2103          the assumption of how this is done.  */
2104       if (lto_section_names == NULL)
2105         vec_alloc (lto_section_names, 16);
2106       vec_safe_push (lto_section_names, e);
2107    }
2108   else if (startswith (name, "__DWARF,"))
2109     darwin_asm_dwarf_section (name, flags, decl, false);
2110   else if (startswith (name, "__GNU_DWARF_LTO,"))
2111     darwin_asm_dwarf_section (name, flags, decl, true);
2112   else
2113     fprintf (asm_out_file, "\t.section %s\n", name);
2114 }
2115 
2116 void
darwin_unique_section(tree decl ATTRIBUTE_UNUSED,int reloc ATTRIBUTE_UNUSED)2117 darwin_unique_section (tree decl ATTRIBUTE_UNUSED, int reloc ATTRIBUTE_UNUSED)
2118 {
2119   /* Darwin does not use unique sections.  */
2120 }
2121 
2122 /* Handle __attribute__ ((apple_kext_compatibility)).
2123    This only applies to darwin kexts for 2.95 compatibility -- it shrinks the
2124    vtable for classes with this attribute (and their descendants) by not
2125    outputting the new 3.0 nondeleting destructor.  This means that such
2126    objects CANNOT be allocated on the stack or as globals UNLESS they have
2127    a completely empty `operator delete'.
2128    Luckily, this fits in with the Darwin kext model.
2129 
2130    This attribute also disables gcc3's potential overlaying of derived
2131    class data members on the padding at the end of the base class.  */
2132 
2133 tree
darwin_handle_kext_attribute(tree * node,tree name,tree args ATTRIBUTE_UNUSED,int flags ATTRIBUTE_UNUSED,bool * no_add_attrs)2134 darwin_handle_kext_attribute (tree *node, tree name,
2135 			      tree args ATTRIBUTE_UNUSED,
2136 			      int flags ATTRIBUTE_UNUSED,
2137 			      bool *no_add_attrs)
2138 {
2139   /* APPLE KEXT stuff -- only applies with pure static C++ code.  */
2140   if (! TARGET_KEXTABI)
2141     {
2142       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
2143 	       "only when compiling a kext", name);
2144 
2145       *no_add_attrs = true;
2146     }
2147   else if (TREE_CODE (*node) != RECORD_TYPE)
2148     {
2149       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
2150 	       "only to C++ classes", name);
2151 
2152       *no_add_attrs = true;
2153     }
2154 
2155   return NULL_TREE;
2156 }
2157 
2158 /* Handle a "weak_import" attribute; arguments as in
2159    struct attribute_spec.handler.  */
2160 
2161 tree
darwin_handle_weak_import_attribute(tree * node,tree name,tree ARG_UNUSED (args),int ARG_UNUSED (flags),bool * no_add_attrs)2162 darwin_handle_weak_import_attribute (tree *node, tree name,
2163 				     tree ARG_UNUSED (args),
2164 				     int ARG_UNUSED (flags),
2165 				     bool * no_add_attrs)
2166 {
2167   if (TREE_CODE (*node) != FUNCTION_DECL && TREE_CODE (*node) != VAR_DECL)
2168     {
2169       warning (OPT_Wattributes, "%qE attribute ignored",
2170 	       name);
2171       *no_add_attrs = true;
2172     }
2173   else
2174     declare_weak (*node);
2175 
2176   return NULL_TREE;
2177 }
2178 
2179 /* Emit a label for an FDE, making it global and/or weak if appropriate.
2180    The third parameter is nonzero if this is for exception handling.
2181    The fourth parameter is nonzero if this is just a placeholder for an
2182    FDE that we are omitting. */
2183 
2184 void
darwin_emit_unwind_label(FILE * file,tree decl,int for_eh,int empty)2185 darwin_emit_unwind_label (FILE *file, tree decl, int for_eh, int empty)
2186 {
2187   char *lab ;
2188   char buf[32];
2189   static int invok_count = 0;
2190   static tree last_fun_decl = NULL_TREE;
2191 
2192   /* Modern linkers can produce distinct FDEs without compiler support.  */
2193   if (! for_eh || ! ld_needs_eh_markers)
2194     return;
2195 
2196   /* FIXME: This only works when the eh for all sections of a function are
2197      emitted at the same time.  If that changes, we would need to use a lookup
2198      table of some form to determine what to do.  Also, we should emit the
2199      unadorned label for the partition containing the public label for a
2200      function.  This is of limited use, probably, since we do not currently
2201      enable partitioning.  */
2202   strcpy (buf, ".eh");
2203   if (decl && TREE_CODE (decl) == FUNCTION_DECL)
2204     {
2205       if (decl == last_fun_decl)
2206         {
2207 	  invok_count++;
2208 	  snprintf (buf, 31, "$$part$$%d.eh", invok_count);
2209 	}
2210       else
2211 	{
2212 	  last_fun_decl = decl;
2213 	  invok_count = 0;
2214 	}
2215     }
2216 
2217   lab = concat (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)), buf, NULL);
2218 
2219   if (TREE_PUBLIC (decl))
2220     {
2221       targetm.asm_out.globalize_label (file, lab);
2222       if (DECL_VISIBILITY (decl) == VISIBILITY_HIDDEN)
2223 	{
2224 	  fputs ("\t.private_extern ", file);
2225 	  assemble_name (file, lab);
2226 	  fputc ('\n', file);
2227 	}
2228     }
2229 
2230   if (DECL_WEAK (decl))
2231     {
2232       fputs ("\t.weak_definition ", file);
2233       assemble_name (file, lab);
2234       fputc ('\n', file);
2235     }
2236 
2237   assemble_name (file, lab);
2238   if (empty)
2239     {
2240       fputs (" = 0\n", file);
2241 
2242       /* Mark the absolute .eh and .eh1 style labels as needed to
2243 	 ensure that we don't dead code strip them and keep such
2244 	 labels from another instantiation point until we can fix this
2245 	 properly with group comdat support.  */
2246       darwin_mark_decl_preserved (lab);
2247     }
2248   else
2249     fputs (":\n", file);
2250 
2251   free (lab);
2252 }
2253 
2254 static GTY(()) unsigned long except_table_label_num;
2255 
2256 void
darwin_emit_except_table_label(FILE * file)2257 darwin_emit_except_table_label (FILE *file)
2258 {
2259   char section_start_label[30];
2260 
2261   fputs ("\t.p2align\t2\n", file);
2262   ASM_GENERATE_INTERNAL_LABEL (section_start_label, "GCC_except_table",
2263 			       except_table_label_num++);
2264   ASM_OUTPUT_LABEL (file, section_start_label);
2265 }
2266 
2267 rtx
darwin_make_eh_symbol_indirect(rtx orig,bool ARG_UNUSED (pubvis))2268 darwin_make_eh_symbol_indirect (rtx orig, bool ARG_UNUSED (pubvis))
2269 {
2270   if (DARWIN_PPC == 0 && TARGET_64BIT)
2271     return orig;
2272 
2273   return gen_rtx_SYMBOL_REF (Pmode,
2274 			     machopic_indirection_name (orig,
2275 							/*stub_p=*/false));
2276 }
2277 
2278 /* The unwinders in earlier Darwin versions are based on an old version
2279    of libgcc_s and need current frame address stateto be reset after a
2280    DW_CFA_restore_state recovers the register values.  */
2281 
2282 bool
darwin_should_restore_cfa_state(void)2283 darwin_should_restore_cfa_state (void)
2284 {
2285   return generating_for_darwin_version <= 10;
2286 }
2287 
2288 /* Return, and mark as used, the name of the stub for the mcount function.
2289    Currently, this is only called by X86 code in the expansion of the
2290    FUNCTION_PROFILER macro, when stubs are enabled.  */
2291 
2292 const char*
machopic_mcount_stub_name(void)2293 machopic_mcount_stub_name (void)
2294 {
2295   rtx symbol = gen_rtx_SYMBOL_REF (Pmode, "*mcount");
2296   const char *name = machopic_indirection_name (symbol, /*stub_p=*/true);
2297   machopic_validate_stub_or_non_lazy_ptr (name);
2298   return name;
2299 }
2300 
2301 /* Generate a PC-relative reference to a Mach-O non-lazy-symbol.  */
2302 
2303 void
darwin_non_lazy_pcrel(FILE * file,rtx addr)2304 darwin_non_lazy_pcrel (FILE *file, rtx addr)
2305 {
2306   const char *nlp_name;
2307 
2308   gcc_assert (GET_CODE (addr) == SYMBOL_REF);
2309 
2310   nlp_name = machopic_indirection_name (addr, /*stub_p=*/false);
2311   fputs ("\t.long\t", file);
2312   ASM_OUTPUT_LABELREF (file, nlp_name);
2313   fputs ("-.", file);
2314 }
2315 
2316 /* If this is uncommented, details of each allocation will be printed
2317    in the asm right before the actual code.  WARNING - this will cause some
2318    test-suite fails (since the printout will contain items that some tests
2319    are not expecting) -- so don't leave it on by default (it bloats the
2320    asm too).  */
2321 /*#define DEBUG_DARWIN_MEM_ALLOCATORS*/
2322 
2323 /* The first two of these routines are ostensibly just intended to put
2324    names into the asm.  However, they are both hijacked in order to ensure
2325    that zero-sized items do not make their way into the output.  Consequently,
2326    we also need to make these participate in provisions for dealing with
2327    such items in section anchors.  */
2328 
2329 /* The implementation of ASM_DECLARE_OBJECT_NAME.  */
2330 /* The RTTI data (e.g., __ti4name) is common and public (and static),
2331    but it does need to be referenced via indirect PIC data pointers.
2332    The machopic_define_symbol calls are telling the machopic subsystem
2333    that the name *is* defined in this module, so it doesn't need to
2334    make them indirect.  */
2335 void
darwin_asm_declare_object_name(FILE * file,const char * nam,tree decl)2336 darwin_asm_declare_object_name (FILE *file,
2337 				const char *nam, tree decl)
2338 {
2339   const char *xname = nam;
2340   unsigned HOST_WIDE_INT size;
2341   bool local_def, weak;
2342 
2343   weak = (DECL_P (decl)
2344 	  && DECL_WEAK (decl)
2345 	  && !lookup_attribute ("weak_import",
2346 				 DECL_ATTRIBUTES (decl)));
2347 
2348   local_def = DECL_INITIAL (decl) || (TREE_STATIC (decl)
2349 				      && (!DECL_COMMON (decl)
2350 					  || !TREE_PUBLIC (decl)));
2351 
2352   if (GET_CODE (XEXP (DECL_RTL (decl), 0)) != SYMBOL_REF)
2353     xname = IDENTIFIER_POINTER (DECL_NAME (decl));
2354 
2355   if (local_def)
2356     {
2357       (* targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2358       if (!weak)
2359 	machopic_define_symbol (DECL_RTL (decl));
2360     }
2361 
2362   size = tree_to_uhwi (DECL_SIZE_UNIT (decl));
2363 
2364 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2365 fprintf (file, "# dadon: %s %s (%llu, %u) local %d weak %d"
2366 	       " stat %d com %d pub %d t-const %d t-ro %d init %lx\n",
2367 	xname, (TREE_CODE (decl) == VAR_DECL?"var":"const"),
2368 	(unsigned long long)size, DECL_ALIGN (decl), local_def,
2369 	DECL_WEAK (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2370 	TREE_PUBLIC (decl), TREE_CONSTANT (decl), TREE_READONLY (decl),
2371 	(unsigned long)DECL_INITIAL (decl));
2372 #endif
2373 
2374   /* Darwin needs help to support local zero-sized objects.
2375      They must be made at least one byte, and the section containing must be
2376      marked as unsuitable for section-anchors (see storage allocators below).
2377 
2378      For non-zero objects this output is handled by varasm.cc.
2379   */
2380   if (!size)
2381     {
2382       unsigned int l2align = 0;
2383 
2384       /* The align must be honored, even for zero-sized.  */
2385       if (DECL_ALIGN (decl))
2386 	{
2387 	  l2align = floor_log2 (DECL_ALIGN (decl) / BITS_PER_UNIT);
2388 	  fprintf (file, "\t.align\t%u\n", l2align);
2389 	}
2390 
2391       ASM_OUTPUT_LABEL (file, xname);
2392       size = 1;
2393       fprintf (file, "\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2394 
2395       /* Check that we've correctly picked up the zero-sized item and placed it
2396          properly.  */
2397       gcc_assert ((!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
2398 		  || (in_section
2399 		      && (in_section->common.flags & SECTION_NO_ANCHOR)));
2400     }
2401   else
2402     ASM_OUTPUT_LABEL (file, xname);
2403 }
2404 
2405 /* The implementation of ASM_DECLARE_CONSTANT_NAME.  */
2406 void
darwin_asm_declare_constant_name(FILE * file,const char * name,const_tree exp ATTRIBUTE_UNUSED,HOST_WIDE_INT size)2407 darwin_asm_declare_constant_name (FILE *file, const char *name,
2408 				  const_tree exp ATTRIBUTE_UNUSED,
2409 				  HOST_WIDE_INT size)
2410 {
2411   assemble_label (file, name);
2412   /* As for other items, we need at least one byte.  */
2413   if (!size)
2414     {
2415       fputs ("\t.space\t1\n", file);
2416       /* Check that we've correctly picked up the zero-sized item and placed it
2417          properly.  */
2418       gcc_assert ((!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
2419 		  || (in_section
2420 		      && (in_section->common.flags & SECTION_NO_ANCHOR)));
2421     }
2422 }
2423 
2424 /* Darwin storage allocators.
2425 
2426    Zerofill sections are desirable for large blank data since, otherwise, these
2427    data bloat objects (PR33210).
2428 
2429    However, section anchors don't work in .zerofill sections (one cannot switch
2430    to a zerofill section).  Ergo, for Darwin targets using section anchors we need
2431    to put (at least some) data into 'normal' switchable sections.
2432 
2433    Here we set a relatively arbitrary value for the size of an object to trigger
2434    zerofill when section anchors are enabled (anything bigger than a page for
2435    current Darwin implementations).  FIXME: there ought to be some objective way
2436    to make this choice.
2437 
2438    When section anchor are off this is ignored anyway.  */
2439 
2440 #define BYTES_ZFILL 4096
2441 
2442 /* Emit a chunk of data for items coalesced by the linker.  */
2443 static void
darwin_emit_weak_or_comdat(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,bool use_coal,unsigned int align)2444 darwin_emit_weak_or_comdat (FILE *fp, tree decl, const char *name,
2445 				  unsigned HOST_WIDE_INT size,
2446 				  bool use_coal,
2447 				  unsigned int align)
2448 {
2449   /* Since the sections used here are coalesced, they will not be eligible
2450      for section anchors, and therefore we don't need to break that out.
2451      CHECKME: for modern linker on PowerPC.  */
2452  if (TREE_READONLY (decl) || TREE_CONSTANT (decl))
2453     switch_to_section (use_coal ? darwin_sections[const_data_coal_section]
2454 				: darwin_sections[const_data_section]);
2455   else
2456     switch_to_section (use_coal ? darwin_sections[data_coal_section]
2457 				: data_section);
2458 
2459   /* To be consistent, we'll allow darwin_asm_declare_object_name to assemble
2460      the align info for zero-sized items... but do it here otherwise.  */
2461   if (size && align)
2462     fprintf (fp, "\t.align\t%d\n", floor_log2 (align / BITS_PER_UNIT));
2463 
2464   if (TREE_PUBLIC (decl))
2465     darwin_globalize_label (fp, name);
2466 
2467   /* ... and we let it deal with outputting one byte of zero for them too.  */
2468   darwin_asm_declare_object_name (fp, name, decl);
2469   if (size)
2470     assemble_zeros (size);
2471 }
2472 
2473 /* Emit a chunk of data for ObjC meta-data that got placed in BSS erroneously.  */
2474 static void
darwin_emit_objc_zeroed(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align,tree meta)2475 darwin_emit_objc_zeroed (FILE *fp, tree decl, const char *name,
2476 				  unsigned HOST_WIDE_INT size,
2477 				  unsigned int align, tree meta)
2478 {
2479   section *ocs = data_section;
2480 
2481   if (TREE_PURPOSE (meta) == get_identifier("OBJC2META"))
2482     ocs = darwin_objc2_section (decl, meta, ocs);
2483   else
2484     ocs = darwin_objc1_section (decl, meta, ocs);
2485 
2486   switch_to_section (ocs);
2487 
2488   /* We shall declare that zero-sized meta-data are not valid (yet).  */
2489   gcc_assert (size);
2490   fprintf (fp, "\t.align\t%d\n", floor_log2 (align / BITS_PER_UNIT));
2491 
2492   /* ... and we let it deal with outputting one byte of zero for them too.  */
2493   darwin_asm_declare_object_name (fp, name, decl);
2494   assemble_zeros (size);
2495 }
2496 
2497 /* This routine emits 'local' storage:
2498 
2499    When Section Anchors are off this routine emits .zerofill commands in
2500    sections named for their alignment.
2501 
2502    When Section Anchors are on, smaller (non-zero-sized) items are placed in
2503    the .static_data section so that the section anchoring system can see them.
2504    Larger items are still placed in .zerofill sections, addressing PR33210.
2505    The routine has no checking - it is all assumed to be done by the caller.
2506 */
2507 static void
darwin_emit_local_bss(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int l2align)2508 darwin_emit_local_bss (FILE *fp, tree decl, const char *name,
2509 			unsigned HOST_WIDE_INT size,
2510 			unsigned int l2align)
2511 {
2512    if (DARWIN_SECTION_ANCHORS && flag_section_anchors && size < BYTES_ZFILL)
2513     {
2514       /* Put smaller objects in _static_data, where the section anchors system
2515 	 can get them.
2516 	 However, if they are zero-sized punt them to yet a different section
2517 	 (that is not allowed to participate in anchoring).  */
2518       if (!size)
2519 	{
2520 	  fputs ("\t.section\t__DATA,__zobj_bss\n", fp);
2521 	  in_section = darwin_sections[zobj_bss_section];
2522 	  size = 1;
2523 	}
2524       else
2525 	{
2526 	  fputs ("\t.static_data\n", fp);
2527 	  in_section = darwin_sections[static_data_section];
2528 	}
2529 
2530       if (l2align)
2531 	fprintf (fp, "\t.align\t%u\n", l2align);
2532 
2533       assemble_name (fp, name);
2534       fprintf (fp, ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2535     }
2536   else
2537     {
2538       /* When we are on a non-section anchor target (or not using section
2539 	 anchors, we can get zero-sized items here.  However, all we need to
2540 	 do is to bump them to one byte and the section alignment will take
2541 	 care of the rest.  */
2542       char secnam[64];
2543       snprintf (secnam, 64, "__DATA,__bss");
2544       unsigned int flags = SECTION_BSS|SECTION_WRITE|SECTION_NO_ANCHOR;
2545       in_section = get_section (secnam, flags, NULL);
2546       fprintf (fp, "\t.zerofill %s,", secnam);
2547       assemble_name (fp, name);
2548       if (!size)
2549 	size = 1;
2550 
2551       if (l2align)
2552 	fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED",%u\n",
2553 		 size, (unsigned) l2align);
2554       else
2555 	fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED",0\n", size);
2556     }
2557 
2558   (*targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2559   /* This is defined as a file-scope var, so we know to notify machopic.  */
2560   machopic_define_symbol (DECL_RTL (decl));
2561 }
2562 
2563 /* Emit a chunk of common.  */
2564 static void
darwin_emit_common(FILE * fp,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2565 darwin_emit_common (FILE *fp, const char *name,
2566 		    unsigned HOST_WIDE_INT size, unsigned int align)
2567 {
2568   unsigned HOST_WIDE_INT rounded;
2569   unsigned int l2align;
2570 
2571   /* Earlier systems complain if the alignment exceeds the page size.
2572      The magic number is 4096 * 8 - hard-coded for legacy systems.  */
2573   if (!emit_aligned_common && (align > 32768UL))
2574     align = 4096UL; /* In units.  */
2575   else
2576     align /= BITS_PER_UNIT;
2577 
2578   /* Make sure we have a meaningful align.  */
2579   if (!align)
2580     align = 1;
2581 
2582   /* For earlier toolchains, we need to emit the var as a rounded size to
2583      tell ld the alignment.  */
2584   if (size < align)
2585     rounded = align;
2586   else
2587     rounded = (size + (align-1)) & ~(align-1);
2588 
2589   l2align = floor_log2 (align);
2590 
2591   in_section = comm_section;
2592   /* We mustn't allow multiple public symbols to share an address when using
2593      the normal OSX toolchain.  */
2594   if (!size)
2595     {
2596       /* Put at least one byte.  */
2597       size = 1;
2598       /* This section can no longer participate in section anchoring.  */
2599       comm_section->common.flags |= SECTION_NO_ANCHOR;
2600     }
2601 
2602   fputs ("\t.comm\t", fp);
2603   assemble_name (fp, name);
2604   fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED,
2605 	   emit_aligned_common?size:rounded);
2606   if (l2align && emit_aligned_common)
2607     fprintf (fp, ",%u", l2align);
2608   fputs ("\n", fp);
2609 }
2610 
2611 /* Output a var which is all zero - into aligned BSS sections, common, lcomm
2612    or coalescable data sections (for weak or comdat) as appropriate.  */
2613 
2614 void
darwin_output_aligned_bss(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2615 darwin_output_aligned_bss (FILE *fp, tree decl, const char *name,
2616 			  unsigned HOST_WIDE_INT size, unsigned int align)
2617 {
2618   unsigned int l2align;
2619   bool one, pub, weak;
2620   tree meta;
2621 
2622   pub = TREE_PUBLIC (decl);
2623   one = DECL_ONE_ONLY (decl);
2624   weak = (DECL_P (decl)
2625 	  && DECL_WEAK (decl)
2626 	  && !lookup_attribute ("weak_import",
2627 				 DECL_ATTRIBUTES (decl)));
2628 
2629 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2630 fprintf (fp, "# albss: %s (%lld,%d) ro %d cst %d stat %d com %d"
2631 	     " pub %d weak %d one %d init %lx\n",
2632 	name, (long long)size, (int)align, TREE_READONLY (decl),
2633 	TREE_CONSTANT (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2634 	pub, weak, one, (unsigned long)DECL_INITIAL (decl));
2635 #endif
2636 
2637   /* ObjC metadata can get put in BSS because varasm.cc decides it's BSS
2638      before the target has a chance to comment.  */
2639   if ((meta = is_objc_metadata (decl)))
2640     {
2641       darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2642       return;
2643     }
2644 
2645   /* Check that any initializer is valid.  */
2646   gcc_assert ((DECL_INITIAL (decl) == NULL)
2647 	       || (DECL_INITIAL (decl) == error_mark_node)
2648 	       || initializer_zerop (DECL_INITIAL (decl)));
2649 
2650   gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2651   gcc_assert (!DECL_COMMON (decl));
2652 
2653   /*  Pick up the correct alignment.  */
2654   if (!size || !align)
2655     align = DECL_ALIGN (decl);
2656 
2657   l2align = floor_log2 (align / BITS_PER_UNIT);
2658   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2659 
2660   last_assemble_variable_decl = decl;
2661 
2662   /* We would rather not have to check this here - but it seems that we might
2663      be passed a decl that should be in coalesced space.  */
2664   if (one || weak)
2665     {
2666       /* Weak or COMDAT objects are put in mergeable sections.  */
2667       darwin_emit_weak_or_comdat (fp, decl, name, size,
2668 				  ld_uses_coal_sects, DECL_ALIGN (decl));
2669       return;
2670     }
2671 
2672   /* If this is not public, then emit according to local rules.  */
2673   if (!pub)
2674     {
2675       darwin_emit_local_bss (fp, decl, name, size, l2align);
2676       return;
2677     }
2678 
2679   /* So we have a public symbol.  */
2680   if (DARWIN_SECTION_ANCHORS && flag_section_anchors && size < BYTES_ZFILL)
2681     {
2682       /* Put smaller objects in data, where the section anchors system can get
2683 	 them.  However, if they are zero-sized punt them to yet a different
2684 	 section (that is not allowed to participate in anchoring).  */
2685       if (!size)
2686 	{
2687 	  fputs ("\t.section\t__DATA,__zobj_data\n", fp);
2688 	  in_section = darwin_sections[zobj_data_section];
2689 	  size = 1;
2690 	}
2691       else
2692 	{
2693 	  fputs ("\t.data\n", fp);
2694 	  in_section = data_section;
2695 	}
2696 
2697       if (l2align)
2698 	fprintf (fp, "\t.align\t%u\n", l2align);
2699 
2700       assemble_name (fp, name);
2701       fprintf (fp, ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2702     }
2703   else
2704     {
2705       /* Section anchors not in use.  */
2706       unsigned int flags = SECTION_BSS|SECTION_WRITE|SECTION_NO_ANCHOR;
2707       char secnam[64];
2708       snprintf (secnam, 64, "__DATA,__common");
2709       in_section = get_section (secnam, flags, NULL);
2710       fprintf (fp, "\t.zerofill %s,", secnam);
2711       assemble_name (fp, name);
2712       if (!size)
2713 	size = 1;
2714 
2715       if (l2align)
2716 	fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED",%u\n", size, l2align);
2717       else
2718 	fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED",0\n", size);
2719     }
2720   (* targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2721 }
2722 
2723 /* Output a chunk of common, with alignment specified (where the target
2724    supports this).  */
2725 void
darwin_asm_output_aligned_decl_common(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2726 darwin_asm_output_aligned_decl_common (FILE *fp, tree decl, const char *name,
2727 				       unsigned HOST_WIDE_INT size,
2728 				       unsigned int align)
2729 {
2730   unsigned int l2align;
2731   bool one, weak;
2732   tree meta;
2733 
2734   /* No corresponding var.  */
2735   if (decl==NULL)
2736     {
2737 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2738 fprintf (fp, "# adcom: %s (%d,%d) decl=0x0\n", name, (int)size, (int)align);
2739 #endif
2740      /* Common variables are limited to a maximum alignment of 2^15.  */
2741       if (align > 32768)
2742 	error_at (UNKNOWN_LOCATION, "common variables must have an alignment"
2743 		  " of 32678 or less");
2744       darwin_emit_common (fp, name, size, align);
2745       return;
2746     }
2747 
2748   one = DECL_ONE_ONLY (decl);
2749   weak = (DECL_P (decl)
2750 	  && DECL_WEAK (decl)
2751 	  && !lookup_attribute ("weak_import",
2752 				 DECL_ATTRIBUTES (decl)));
2753 
2754 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2755 fprintf (fp, "# adcom: %s (%lld,%d) ro %d cst %d stat %d com %d pub %d"
2756 	     " weak %d one %d init %lx\n",
2757 	name,  (long long)size, (int)align, TREE_READONLY (decl),
2758 	TREE_CONSTANT (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2759 	TREE_PUBLIC (decl), weak, one, (unsigned long)DECL_INITIAL (decl));
2760 #endif
2761 
2762   /* ObjC metadata can get put in BSS because varasm.cc decides it's BSS
2763      before the target has a chance to comment.  */
2764   if ((meta = is_objc_metadata (decl)))
2765     {
2766       darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2767       return;
2768     }
2769 
2770   /* We shouldn't be messing with this if the decl has a section name.  */
2771   gcc_checking_assert (DECL_SECTION_NAME (decl) == NULL);
2772 
2773   /* We would rather not have to check this here - but it seems that we might
2774      be passed a decl that should be in coalesced space.  */
2775   if (one || weak)
2776     {
2777       /* Weak or COMDAT objects are put in mergable sections.  */
2778       darwin_emit_weak_or_comdat (fp, decl, name, size,
2779 				  ld_uses_coal_sects, DECL_ALIGN (decl));
2780       return;
2781     }
2782 
2783   /* We should only get here for DECL_COMMON, with a zero init (and, in
2784      principle, only for public symbols too - although we deal with local
2785      ones below).  */
2786 
2787   /* Check the initializer is OK.  */
2788   gcc_assert (DECL_COMMON (decl)
2789 	      && ((DECL_INITIAL (decl) == NULL)
2790 	       || (DECL_INITIAL (decl) == error_mark_node)
2791 	       || initializer_zerop (DECL_INITIAL (decl))));
2792 
2793   last_assemble_variable_decl = decl;
2794 
2795   if (!size || !align)
2796     align = DECL_ALIGN (decl);
2797 
2798   l2align = floor_log2 (align / BITS_PER_UNIT);
2799   /* Check we aren't asking for more aligment than the platform allows.  */
2800   gcc_checking_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2801 
2802   if (TREE_PUBLIC (decl) != 0)
2803     {
2804       /* Common variables are limited to a maximum alignment of 2^15.  */
2805       if (l2align > 15)
2806 	error_at (DECL_SOURCE_LOCATION (decl), "common variables must have"
2807 		  " an alignment of 32678 or less");
2808       darwin_emit_common (fp, name, size, align);
2809     }
2810   else
2811     darwin_emit_local_bss (fp, decl, name, size, l2align);
2812 }
2813 
2814 /* Output a chunk of BSS with alignment specfied.  */
2815 void
darwin_asm_output_aligned_decl_local(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2816 darwin_asm_output_aligned_decl_local (FILE *fp, tree decl, const char *name,
2817 				      unsigned HOST_WIDE_INT size,
2818 				      unsigned int align)
2819 {
2820   unsigned long l2align;
2821   bool one, weak;
2822   tree meta;
2823 
2824   one = DECL_ONE_ONLY (decl);
2825   weak = (DECL_P (decl)
2826 	  && DECL_WEAK (decl)
2827 	  && !lookup_attribute ("weak_import",
2828 				 DECL_ATTRIBUTES (decl)));
2829 
2830 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2831 fprintf (fp, "# adloc: %s (%lld,%d) ro %d cst %d stat %d one %d pub %d"
2832 	     " weak %d init %lx\n",
2833 	name, (long long)size, (int)align, TREE_READONLY (decl),
2834 	TREE_CONSTANT (decl), TREE_STATIC (decl), one, TREE_PUBLIC (decl),
2835 	weak , (unsigned long)DECL_INITIAL (decl));
2836 #endif
2837 
2838   /* ObjC metadata can get put in BSS because varasm.cc decides it's BSS
2839      before the target has a chance to comment.  */
2840   if ((meta = is_objc_metadata (decl)))
2841     {
2842       darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2843       return;
2844     }
2845 
2846   /* We shouldn't be messing with this if the decl has a section name.  */
2847   gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2848 
2849   /* We would rather not have to check this here - but it seems that we might
2850      be passed a decl that should be in coalesced space.  */
2851   if (one || weak)
2852     {
2853       /* Weak or COMDAT objects are put in mergable sections.  */
2854       darwin_emit_weak_or_comdat (fp, decl, name, size,
2855 				  ld_uses_coal_sects, DECL_ALIGN (decl));
2856       return;
2857     }
2858 
2859   /* .. and it should be suitable for placement in local mem.  */
2860   gcc_assert(!TREE_PUBLIC (decl) && !DECL_COMMON (decl));
2861   /* .. and any initializer must be all-zero.  */
2862   gcc_assert ((DECL_INITIAL (decl) == NULL)
2863 	       || (DECL_INITIAL (decl) == error_mark_node)
2864 	       || initializer_zerop (DECL_INITIAL (decl)));
2865 
2866   last_assemble_variable_decl = decl;
2867 
2868   if (!size || !align)
2869     align = DECL_ALIGN (decl);
2870 
2871   l2align = floor_log2 (align / BITS_PER_UNIT);
2872   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2873 
2874   darwin_emit_local_bss (fp, decl, name, size, l2align);
2875 }
2876 
2877 /* Emit an assembler directive to set visibility for a symbol.  The
2878    only supported visibilities are VISIBILITY_DEFAULT and
2879    VISIBILITY_HIDDEN; the latter corresponds to Darwin's "private
2880    extern".  There is no MACH-O equivalent of ELF's
2881    VISIBILITY_INTERNAL or VISIBILITY_PROTECTED. */
2882 
2883 void
darwin_assemble_visibility(tree decl,int vis)2884 darwin_assemble_visibility (tree decl, int vis)
2885 {
2886   if (vis == VISIBILITY_DEFAULT)
2887     ;
2888   else if (vis == VISIBILITY_HIDDEN || vis == VISIBILITY_INTERNAL)
2889     {
2890       fputs ("\t.private_extern ", asm_out_file);
2891       assemble_name (asm_out_file,
2892 		     (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))));
2893       fputs ("\n", asm_out_file);
2894     }
2895   else
2896     warning (OPT_Wattributes, "protected visibility attribute "
2897 	     "not supported in this configuration; ignored");
2898 }
2899 
2900 /* vec used by darwin_asm_dwarf_section.
2901    Maybe a hash tab would be better here - but the intention is that this is
2902    a very short list (fewer than 16 items) and each entry should (ideally,
2903    eventually) only be presented once.
2904 
2905    A structure to hold a dwarf debug section used entry.  */
2906 
2907 typedef struct GTY(()) dwarf_sect_used_entry {
2908   const char *name;
2909   unsigned count;
2910 }
2911 dwarf_sect_used_entry;
2912 
2913 
2914 /* A list of used __DWARF sections.  */
2915 static GTY (()) vec<dwarf_sect_used_entry, va_gc> *dwarf_sect_names_table;
2916 
2917 /* This is called when we are asked to assemble a named section and the
2918    name begins with __DWARF,.  We keep a list of the section names (without
2919    the __DWARF, prefix) and use this to emit our required start label on the
2920    first switch to each section.  */
2921 
2922 static void
darwin_asm_dwarf_section(const char * name,unsigned int flags,tree ARG_UNUSED (decl),bool is_for_lto)2923 darwin_asm_dwarf_section (const char *name, unsigned int flags,
2924 			  tree ARG_UNUSED (decl), bool is_for_lto)
2925 {
2926   unsigned i;
2927   int namelen, extra = 0;
2928   const char *sect, *lto_add = "";
2929   char sname[64];
2930   dwarf_sect_used_entry *ref;
2931   bool found = false;
2932 
2933   gcc_checking_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
2934 			== (SECTION_DEBUG | SECTION_NAMED));
2935 
2936   /* We know that the name starts with __DWARF, or __GNU_DAWRF_LTO  */
2937   sect = strchr (name, ',') + 1;
2938   namelen = strchr (sect, ',') - sect;
2939   gcc_checking_assert (namelen);
2940 
2941   /* The section switch is output as written...  */
2942   fprintf (asm_out_file, "\t.section %s\n", name);
2943 
2944   /* ... but the string we keep to make section start labels needs
2945      adjustment for lto cases.  */
2946   if (is_for_lto)
2947     {
2948       lto_add = "_lto";
2949       extra = 4;
2950     }
2951 
2952   snprintf (sname, 64, "%.*s%.*s", namelen, sect, extra, lto_add);
2953   namelen += extra;
2954 
2955   if (dwarf_sect_names_table == NULL)
2956     vec_alloc (dwarf_sect_names_table, 16);
2957   else
2958     for (i = 0;
2959 	 dwarf_sect_names_table->iterate (i, &ref);
2960 	 i++)
2961       {
2962 	if (!ref)
2963 	  break;
2964 	if (!strcmp (ref->name, sname))
2965 	  {
2966 	    found = true;
2967 	    ref->count++;
2968 	    break;
2969 	  }
2970       }
2971 
2972   if (!found)
2973     {
2974       dwarf_sect_used_entry e;
2975       fprintf (asm_out_file, "Lsection%.*s:\n", namelen, sname);
2976       e.count = 1;
2977       e.name = xstrdup (sname);
2978       vec_safe_push (dwarf_sect_names_table, e);
2979     }
2980 }
2981 
2982 /* Output a difference of two labels that will be an assembly time
2983    constant if the two labels are local.  (.long lab1-lab2 will be
2984    very different if lab1 is at the boundary between two sections; it
2985    will be relocated according to the second section, not the first,
2986    so one ends up with a difference between labels in different
2987    sections, which is bad in the dwarf2 eh context for instance.)  */
2988 
2989 static int darwin_dwarf_label_counter;
2990 
2991 void
darwin_asm_output_dwarf_delta(FILE * file,int size,const char * lab1,const char * lab2,HOST_WIDE_INT offset)2992 darwin_asm_output_dwarf_delta (FILE *file, int size,
2993 			       const char *lab1, const char *lab2,
2994 			       HOST_WIDE_INT offset)
2995 {
2996   int islocaldiff = (lab1[0] == '*' && lab1[1] == 'L'
2997 		     && lab2[0] == '*' && lab2[1] == 'L');
2998   const char *directive = (size == 8 ? ".quad" : ".long");
2999 
3000   if (islocaldiff)
3001     fprintf (file, "\t.set L$set$%d,", darwin_dwarf_label_counter);
3002   else
3003     fprintf (file, "\t%s\t", directive);
3004 
3005   assemble_name_raw (file, lab1);
3006   fprintf (file, "-");
3007   assemble_name_raw (file, lab2);
3008   if (offset != 0)
3009     fprintf (file, "+" HOST_WIDE_INT_PRINT_DEC, offset);
3010   if (islocaldiff)
3011     fprintf (file, "\n\t%s L$set$%d", directive, darwin_dwarf_label_counter++);
3012 }
3013 
3014 /* Output an offset in a DWARF section on Darwin.  On Darwin, DWARF section
3015    offsets are not represented using relocs in .o files; either the
3016    section never leaves the .o file, or the linker or other tool is
3017    responsible for parsing the DWARF and updating the offsets.  */
3018 
3019 void
darwin_asm_output_dwarf_offset(FILE * file,int size,const char * lab,HOST_WIDE_INT offset,section * base)3020 darwin_asm_output_dwarf_offset (FILE *file, int size, const char * lab,
3021 				HOST_WIDE_INT offset, section *base)
3022 {
3023   char sname[64];
3024   int namelen, extra = 0;
3025   bool is_for_lto;
3026   const char *lto_add = "";
3027 
3028   gcc_checking_assert (base->common.flags & SECTION_NAMED);
3029   is_for_lto = startswith (base->named.name, "__GNU_DWARF_LTO,");
3030   gcc_checking_assert (is_for_lto
3031 		       || startswith (base->named.name, "__DWARF,"));
3032   const char *name = strchr (base->named.name, ',') + 1;
3033   gcc_checking_assert (name);
3034 
3035   namelen = strchr (name, ',') - (name);
3036   if (is_for_lto)
3037     {
3038       lto_add = "_lto";
3039       extra = 4;
3040     }
3041   snprintf (sname, 64, "*Lsection%.*s%.*s", namelen, name, extra, lto_add);
3042   darwin_asm_output_dwarf_delta (file, size, lab, sname, offset);
3043 }
3044 
3045 /* Called from the within the TARGET_ASM_FILE_START for each target.  */
3046 
3047 void
darwin_file_start(void)3048 darwin_file_start (void)
3049 {
3050 #ifdef HAVE_AS_MMACOSX_VERSION_MIN_OPTION
3051   /* This should not happen with a well-formed command line, but the user could
3052      invoke cc1* directly without it.  */
3053   if (!darwin_macosx_version_min)
3054     return;
3055   /* This assumes that the version passed has been validated in the driver.  */
3056   unsigned maj, min, tiny;
3057   int count = sscanf (darwin_macosx_version_min, "%u.%u.%u", &maj, &min, &tiny);
3058   if (count < 0)
3059     return;
3060   if (count < 3)
3061     tiny = 0;
3062   if (count < 2)
3063     min = 0;
3064   const char *directive;
3065 #ifdef HAVE_AS_MACOS_BUILD_VERSION
3066   /* We only handle macos, so far.  */
3067   if (generating_for_darwin_version >= 18)
3068     directive = "build_version macos, ";
3069   else
3070 #endif
3071     directive = "macosx_version_min ";
3072   if (count > 2 && tiny != 0)
3073     fprintf (asm_out_file, "\t.%s %u, %u, %u\n", directive, maj, min, tiny);
3074   else if (count > 1)
3075     fprintf (asm_out_file, "\t.%s %u, %u\n", directive, maj, min);
3076   else
3077      fprintf (asm_out_file, "\t.%s %u, 0\n", directive, maj);
3078 #endif
3079 }
3080 
3081 /* Called for the TARGET_ASM_FILE_END hook.
3082    Emit the mach-o pic indirection data, the lto data and, finally a flag
3083    to tell the linker that it can break the file object into sections and
3084    move those around for efficiency.  */
3085 
3086 void
darwin_file_end(void)3087 darwin_file_end (void)
3088 {
3089   if (!vec_safe_is_empty (ctors))
3090     finalize_ctors ();
3091   if (!vec_safe_is_empty (dtors))
3092     finalize_dtors ();
3093 
3094   /* If we are expecting to output NeXT ObjC meta-data, (and we actually see
3095      some) then we output the fix-and-continue marker (Image Info).
3096      This applies to Objective C, Objective C++ and LTO with either language
3097      as part of the input.  */
3098   if (flag_next_runtime && objc_metadata_seen)
3099     {
3100       unsigned int flags = 0;
3101       if (flag_objc_abi >= 2)
3102 	{
3103 	  flags = 16;
3104           switch_to_section (darwin_sections[objc2_image_info_section]);
3105 	}
3106       else
3107 	switch_to_section (darwin_sections[objc_image_info_section]);
3108 
3109       ASM_OUTPUT_ALIGN (asm_out_file, 2);
3110       fputs ("L_OBJC_ImageInfo:\n", asm_out_file);
3111 
3112       flags |= (flag_replace_objc_classes && classes_seen) ? 1 : 0;
3113       flags |= flag_objc_gc ? 2 : 0;
3114 
3115       fprintf (asm_out_file, "\t.long\t0\n\t.long\t%u\n", flags);
3116      }
3117 
3118   machopic_finish (asm_out_file);
3119   if (flag_apple_kext)
3120     {
3121       /* These sections are only used for kernel code.  */
3122       switch_to_section (darwin_sections[constructor_section]);
3123       switch_to_section (darwin_sections[destructor_section]);
3124       ASM_OUTPUT_ALIGN (asm_out_file, 1);
3125     }
3126 
3127   /* If there was LTO assembler output, append it to asm_out_file.  */
3128   if (lto_asm_out_name)
3129     {
3130       int n;
3131       char *buf, *lto_asm_txt;
3132 
3133       /* Shouldn't be here if we failed to switch back.  */
3134       gcc_assert (! saved_asm_out_file);
3135 
3136       lto_asm_out_file = fopen (lto_asm_out_name, "r");
3137       if (lto_asm_out_file == NULL)
3138 	fatal_error (input_location,
3139 		     "failed to open temporary file %s with LTO output",
3140 		     lto_asm_out_name);
3141       fseek (lto_asm_out_file, 0, SEEK_END);
3142       n = ftell (lto_asm_out_file);
3143       if (n > 0)
3144         {
3145 	  fseek (lto_asm_out_file, 0, SEEK_SET);
3146 	  lto_asm_txt = buf = (char *) xmalloc (n + 1);
3147 	  while (fgets (lto_asm_txt, n, lto_asm_out_file))
3148 	    fputs (lto_asm_txt, asm_out_file);
3149 	  /* Put a termination label.  */
3150 	  fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
3151 		   LTO_SEGMENT_NAME, LTO_SECTS_SECTION);
3152 	  fprintf (asm_out_file, "L_GNU_LTO%d:\t;# end of lto\n",
3153 		   lto_section_num);
3154 	  /* Make sure our termination label stays in this section.  */
3155 	  fputs ("\t.space\t1\n", asm_out_file);
3156 	}
3157 
3158       /* Remove the temporary file.  */
3159       fclose (lto_asm_out_file);
3160       unlink_if_ordinary (lto_asm_out_name);
3161       free (lto_asm_out_name);
3162     }
3163 
3164   /* Output the names and indices.  */
3165   if (lto_section_names && lto_section_names->length ())
3166     {
3167       int count;
3168       darwin_lto_section_e *ref;
3169       /* For now, we'll make the offsets 4 bytes and unaligned - we'll fix
3170          the latter up ourselves.  */
3171       const char *op = integer_asm_op (4,0);
3172 
3173       /* Emit the names.  */
3174       fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
3175 	       LTO_SEGMENT_NAME, LTO_NAMES_SECTION);
3176       FOR_EACH_VEC_ELT (*lto_section_names, count, ref)
3177 	{
3178 	  fprintf (asm_out_file, "L_GNU_LTO_NAME%d:\n", count);
3179          /* We have to jump through hoops to get the values of the intra-section
3180             offsets... */
3181 	  fprintf (asm_out_file,
3182 		   "\t.set L$gnu$lto$noff%d,L_GNU_LTO_NAME%d-L_GNU_LTO_NAME0\n",
3183 		   count, count);
3184 	  fprintf (asm_out_file,
3185 		   "\t.set L$gnu$lto$nsiz%d,L_GNU_LTO_NAME%d-L_GNU_LTO_NAME%d\n",
3186 		   count, count+1, count);
3187 	  fprintf (asm_out_file, "\t.asciz\t\"%s\"\n", ref->sectname);
3188 	}
3189       fprintf (asm_out_file, "L_GNU_LTO_NAME%d:\t;# end\n", lto_section_num);
3190       /* make sure our termination label stays in this section.  */
3191       fputs ("\t.space\t1\n", asm_out_file);
3192 
3193       /* Emit the Index.  */
3194       fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
3195 	       LTO_SEGMENT_NAME, LTO_INDEX_SECTION);
3196       fputs ("\t.align\t2\n", asm_out_file);
3197       fputs ("# Section offset, Section length, Name offset, Name length\n",
3198 	     asm_out_file);
3199       FOR_EACH_VEC_ELT (*lto_section_names, count, ref)
3200 	{
3201 	  fprintf (asm_out_file, "%s L$gnu$lto$offs%d\t;# %s\n",
3202 		   op, count, ref->sectname);
3203 	  fprintf (asm_out_file, "%s L$gnu$lto$size%d\n", op, count);
3204 	  fprintf (asm_out_file, "%s L$gnu$lto$noff%d\n", op, count);
3205 	  fprintf (asm_out_file, "%s L$gnu$lto$nsiz%d\n", op, count);
3206 	}
3207     }
3208 
3209   /* If we have section anchors, then we must prevent the linker from
3210      re-arranging data.  */
3211   if (!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
3212     fprintf (asm_out_file, "\t.subsections_via_symbols\n");
3213 
3214   /* We rely on this being NULL at the start of compilation; reset it here
3215      so that JIT can reuse a context.  */
3216   if (dwarf_sect_names_table != NULL)
3217     {
3218       dwarf_sect_names_table->truncate (0);
3219       dwarf_sect_names_table = NULL;
3220     }
3221 }
3222 
3223 /* TODO: Add a language hook for identifying if a decl is a vtable.  */
3224 #define DARWIN_VTABLE_P(DECL) 0
3225 
3226 /* Cross-module name binding.  Darwin does not support overriding
3227    functions at dynamic-link time, except for vtables in kexts.  */
3228 
3229 bool
darwin_binds_local_p(const_tree decl)3230 darwin_binds_local_p (const_tree decl)
3231 {
3232   /* We use the "shlib" input to indicate that a symbol should be
3233      considered overridable; only relevant for vtables in kernel modules
3234      on earlier system versions, and with a TODO to complete.  */
3235   bool force_overridable = TARGET_KEXTABI && DARWIN_VTABLE_P (decl);
3236   return default_binds_local_p_3 (decl, force_overridable /* shlib */,
3237 				  false /* weak dominate */,
3238 				  false /* extern_protected_data */,
3239 				  false /* common_local_p */);
3240 }
3241 
3242 /* The Darwin's implementation of TARGET_ASM_OUTPUT_ANCHOR.  Define the
3243    anchor relative to ".", the current section position.  We cannot use
3244    the default one because ASM_OUTPUT_DEF is wrong for Darwin.  */
3245 void
darwin_asm_output_anchor(rtx symbol)3246 darwin_asm_output_anchor (rtx symbol)
3247 {
3248   fprintf (asm_out_file, "\t.set\t");
3249   assemble_name (asm_out_file, XSTR (symbol, 0));
3250   fprintf (asm_out_file, ", . + " HOST_WIDE_INT_PRINT_DEC "\n",
3251 	   SYMBOL_REF_BLOCK_OFFSET (symbol));
3252 }
3253 
3254 /* Disable section anchoring on any section containing a zero-sized
3255    object.  */
3256 bool
darwin_use_anchors_for_symbol_p(const_rtx symbol)3257 darwin_use_anchors_for_symbol_p (const_rtx symbol)
3258 {
3259   if (DARWIN_SECTION_ANCHORS && flag_section_anchors)
3260     {
3261       section *sect;
3262       /* If the section contains a zero-sized object it's ineligible.  */
3263       sect = SYMBOL_REF_BLOCK (symbol)->sect;
3264       /* This should have the effect of disabling anchors for vars that follow
3265          any zero-sized one, in a given section.  */
3266       if (sect->common.flags & SECTION_NO_ANCHOR)
3267 	return false;
3268 
3269       /* Also check the normal reasons for suppressing.  */
3270       return default_use_anchors_for_symbol_p (symbol);
3271     }
3272   else
3273     return false;
3274 }
3275 
3276 /* Set the darwin specific attributes on TYPE.  */
3277 void
darwin_set_default_type_attributes(tree type)3278 darwin_set_default_type_attributes (tree type)
3279 {
3280   if (darwin_ms_struct
3281       && TREE_CODE (type) == RECORD_TYPE)
3282     TYPE_ATTRIBUTES (type) = tree_cons (get_identifier ("ms_struct"),
3283                                         NULL_TREE,
3284                                         TYPE_ATTRIBUTES (type));
3285 }
3286 
3287 /* True, iff we're generating code for loadable kernel extensions.  */
3288 
3289 bool
darwin_kextabi_p(void)3290 darwin_kextabi_p (void) {
3291   return flag_apple_kext;
3292 }
3293 
3294 void
darwin_override_options(void)3295 darwin_override_options (void)
3296 {
3297   /* Keep track of which (major) version we're generating code for.  */
3298   if (darwin_macosx_version_min)
3299     {
3300       if (strverscmp (darwin_macosx_version_min, "10.14") >= 0)
3301 	generating_for_darwin_version = 18;
3302       else if (strverscmp (darwin_macosx_version_min, "10.8") >= 0)
3303 	generating_for_darwin_version = 12;
3304       else if (strverscmp (darwin_macosx_version_min, "10.7") >= 0)
3305 	generating_for_darwin_version = 11;
3306       else if (strverscmp (darwin_macosx_version_min, "10.6") >= 0)
3307 	generating_for_darwin_version = 10;
3308       else if (strverscmp (darwin_macosx_version_min, "10.5") >= 0)
3309 	generating_for_darwin_version = 9;
3310       else if (strverscmp (darwin_macosx_version_min, "10.4") >= 0)
3311 	generating_for_darwin_version = 8;
3312 
3313       /* Earlier versions are not specifically accounted, until required.  */
3314     }
3315 
3316   /* Some codegen needs to account for the capabilities of the target
3317      linker.  */
3318   if (darwin_target_linker)
3319     {
3320       /* Older Darwin ld could not coalesce weak entities without them being
3321 	 placed in special sections.  */
3322       if (strverscmp (darwin_target_linker, MIN_LD64_NO_COAL_SECTS) < 0)
3323 	ld_uses_coal_sects = true;
3324 
3325       /* Some newer assemblers emit section start temp symbols for mod init
3326 	 and term sections if there is no suitable symbol present already.
3327 	 The temp symbols are linker visible and therefore appear in the
3328 	 symbol tables.  Since the temp symbol number can vary when debug is
3329 	 enabled, that causes compare-debug fails.  The solution is to provide
3330 	 a stable linker-visible symbol.  */
3331       if (strverscmp (darwin_target_linker,
3332 		      MIN_LD64_INIT_TERM_START_LABELS) >= 0)
3333 	ld_init_term_start_labels = true;
3334     }
3335 
3336   /* In principle, this should be c-family only.  However, we really need to
3337      set sensible defaults for LTO as well, since the section selection stuff
3338      should check for correctness re. the ABI.  TODO: check and provide the
3339      flags (runtime & ABI) from the lto wrapper).  */
3340 
3341   /* At present, make a hard update to the runtime version based on the target
3342      OS version.  */
3343   if (flag_next_runtime)
3344     {
3345       if (generating_for_darwin_version > 10)
3346 	flag_next_runtime = 100705;
3347       else if (generating_for_darwin_version > 9)
3348 	flag_next_runtime = 100608;
3349       else if (generating_for_darwin_version > 8)
3350 	flag_next_runtime = 100508;
3351       else
3352 	flag_next_runtime = 100000;
3353     }
3354 
3355   /* Unless set, force ABI=2 for NeXT and m64, 0 otherwise.  */
3356   if (!OPTION_SET_P (flag_objc_abi))
3357     global_options.x_flag_objc_abi
3358 	= (!flag_next_runtime)
3359 		? 0
3360 		: (TARGET_64BIT ? 2
3361 				: (generating_for_darwin_version >= 9) ? 1
3362 								       : 0);
3363 
3364   if (OPTION_SET_P (flag_objc_abi) && flag_next_runtime)
3365     {
3366       if (TARGET_64BIT && global_options.x_flag_objc_abi != 2)
3367 	/* The Objective-C family ABI 2 is the only valid version NeXT/m64.  */
3368 	error_at (UNKNOWN_LOCATION,
3369 		  "%<-fobjc-abi-version%> 2 must be used for 64 bit targets"
3370 		  " with %<-fnext-runtime%>");
3371       else if (!TARGET_64BIT && global_options.x_flag_objc_abi >= 2)
3372 	/* ABI versions 0 and 1 are the only valid versions NeXT/m32.  */
3373 	error_at (UNKNOWN_LOCATION,
3374 		  "%<-fobjc-abi-version%> %d is not supported for 32 bit"
3375 		  " targets with %<-fnext-runtime%>",
3376 		  global_options.x_flag_objc_abi);
3377     }
3378 
3379   if (!OPTION_SET_P (dwarf_version))
3380     {
3381       /* External toolchains based on LLVM or clang 7+ have support for
3382 	 dwarf-4.  */
3383       if ((dsymutil_version.kind == LLVM && dsymutil_version.major >= 7)
3384 	  || (dsymutil_version.kind == CLANG && dsymutil_version.major >= 700))
3385 	dwarf_version = 4;
3386       else if (dsymutil_version.kind == DWARFUTILS
3387 	       && dsymutil_version.major >= 121)
3388 	dwarf_version = 3;  /* From XC 6.4.  */
3389       else
3390 	dwarf_version = 2;  /* Older cannot safely exceed dwarf-2.  */
3391     }
3392 
3393   if (OPTION_SET_P (dwarf_split_debug_info) && dwarf_split_debug_info)
3394     {
3395       inform (input_location,
3396 	      "%<-gsplit-dwarf%> is not supported on this platform, ignored");
3397       dwarf_split_debug_info = 0;
3398       OPTION_SET_P (dwarf_split_debug_info) = 0;
3399     }
3400 
3401   /* Cases where dsymutil will exclude files with .macinfo sections; we are
3402      better off forcing the debug level to 2 than completely excluding the
3403      files.  If strict dwarf is set, then emit the macinfo anyway.  */
3404   if (debug_info_level == DINFO_LEVEL_VERBOSE
3405       && (!OPTION_SET_P (dwarf_strict) || dwarf_strict == 0)
3406       && ((dsymutil_version.kind == CLANG && dsymutil_version.major >= 1500)
3407 	  || (dsymutil_version.kind == LLVM && dsymutil_version.major >= 15)))
3408     {
3409       inform (input_location,
3410 	      "%<-g3%> is not supported by the debug linker in use (set to 2)");
3411       debug_info_level = DINFO_LEVEL_NORMAL;
3412     }
3413 
3414   /* Limit DWARF to the chosen version, the linker and debug linker might not
3415      be able to consume newer structures.  */
3416   if (!OPTION_SET_P (dwarf_strict))
3417     dwarf_strict = 1;
3418 
3419   /* Do not allow unwind tables to be generated by default for m32.
3420      fnon-call-exceptions will override this, regardless of what we do.  */
3421   if (generating_for_darwin_version < 10
3422       && !OPTION_SET_P (flag_asynchronous_unwind_tables)
3423       && !TARGET_64BIT)
3424     global_options.x_flag_asynchronous_unwind_tables = 0;
3425 
3426    /* Disable -freorder-blocks-and-partition when unwind tables are being
3427       emitted for Darwin < 9 (OSX 10.5).
3428       The strategy is, "Unless the user has specifically set/unset an unwind
3429       flag we will switch off -freorder-blocks-and-partition when unwind tables
3430       will be generated".  If the user specifically sets flags, we have to
3431       assume they know why.  */
3432    if (generating_for_darwin_version < 9
3433        && OPTION_SET_P (flag_reorder_blocks_and_partition)
3434        && flag_reorder_blocks_and_partition
3435        && ((global_options.x_flag_exceptions 		/* User, c++, java */
3436 	    && !OPTION_SET_P (flag_exceptions)) 	/* User specified... */
3437 	   || (global_options.x_flag_unwind_tables
3438 	       && !OPTION_SET_P (flag_unwind_tables))
3439 	   || (global_options.x_flag_non_call_exceptions
3440 	       && !OPTION_SET_P (flag_non_call_exceptions))
3441 	   || (global_options.x_flag_asynchronous_unwind_tables
3442 	       && !OPTION_SET_P (flag_asynchronous_unwind_tables))))
3443     {
3444       inform (input_location,
3445 	      "%<-freorder-blocks-and-partition%> does not work with "
3446 	      "exceptions on this architecture");
3447       flag_reorder_blocks_and_partition = 0;
3448       flag_reorder_blocks = 1;
3449     }
3450 
3451     /* FIXME: flag_objc_sjlj_exceptions is no longer needed since there is only
3452        one valid choice of exception scheme for each runtime.  */
3453     if (!OPTION_SET_P (flag_objc_sjlj_exceptions))
3454       global_options.x_flag_objc_sjlj_exceptions =
3455 				flag_next_runtime && !TARGET_64BIT;
3456 
3457     /* FIXME: and this could be eliminated then too.  */
3458     if (!OPTION_SET_P (flag_exceptions)
3459 	&& flag_objc_exceptions
3460 	&& TARGET_64BIT)
3461       flag_exceptions = 1;
3462 
3463   if (flag_mkernel || flag_apple_kext)
3464     {
3465       /* -mkernel implies -fapple-kext for C++ */
3466       if (lang_GNU_CXX ())
3467 	flag_apple_kext = 1;
3468 
3469       flag_no_common = 1;
3470 
3471       /* No EH in kexts.  */
3472       flag_exceptions = 0;
3473       /* No -fnon-call-exceptions data in kexts.  */
3474       flag_non_call_exceptions = 0;
3475       /* so no tables either.. */
3476       flag_unwind_tables = 0;
3477       flag_asynchronous_unwind_tables = 0;
3478     }
3479 
3480   if (flag_var_tracking_uninit == 0
3481       && generating_for_darwin_version >= 9
3482       && (flag_gtoggle ? (debug_info_level == DINFO_LEVEL_NONE)
3483       : (debug_info_level >= DINFO_LEVEL_NORMAL))
3484       && dwarf_debuginfo_p ())
3485     flag_var_tracking_uninit = flag_var_tracking;
3486 
3487   if (OPTION_SET_P (flag_pie) && flag_pie)
3488     {
3489       /* This is a little complicated, to match Xcode tools.
3490 	 For Darwin, PIE requires PIC codegen, but otherwise is only a link-
3491 	 time change.  For almost all Darwin, we do not report __PIE__; the
3492 	 exception is Darwin12-17 and for 32b only.  */
3493       flag_pie = generating_for_darwin_version >= 12 && !TARGET_64BIT ? 2 : 0;
3494       flag_pic = 2; /* We always set this.  */
3495     }
3496 
3497   /* Final check on PIC options.  */
3498   if (MACHO_DYNAMIC_NO_PIC_P)
3499     {
3500       if (flag_pic)
3501 	warning_at (UNKNOWN_LOCATION, 0,
3502 		 "%<-mdynamic-no-pic%> overrides %<-fpic%>, %<-fPIC%>,"
3503 		 " %<-fpie%> or %<-fPIE%>");
3504       flag_pic = 0;
3505     }
3506   else if (flag_pic == 1
3507 	   || (flag_pic == 0 && !(flag_mkernel || flag_apple_kext)))
3508     {
3509       /* Darwin's -fpic is -fPIC.
3510 	 We only support "static" code in the kernel and kernel exts.  */
3511       flag_pic = 2;
3512     }
3513 
3514   /* Linkers >= ld64-62.1 (at least) are capable of making the necessary PIC
3515      indirections and we no longer need to emit pic symbol stubs.
3516      However, if we are generating code for earlier ones (or for use in the
3517      kernel) the stubs might still be required, and this will be set true.
3518      If the user sets it on or off - then that takes precedence.
3519 
3520      Linkers that don't need stubs, don't need the EH symbol markers either.
3521   */
3522 
3523   if (!OPTION_SET_P (darwin_symbol_stubs))
3524     {
3525       if (darwin_target_linker)
3526 	{
3527 	  if (strverscmp (darwin_target_linker, MIN_LD64_OMIT_STUBS) < 0)
3528 	    {
3529 	      darwin_symbol_stubs = true;
3530 	      ld_needs_eh_markers = true;
3531 	    }
3532 	}
3533       else if (generating_for_darwin_version < 9)
3534 	{
3535 	  /* If we don't know the linker version and we're targeting an old
3536 	     system, we know no better than to assume the use of an earlier
3537 	     linker.  */
3538 	  darwin_symbol_stubs = true;
3539 	  ld_needs_eh_markers = true;
3540 	}
3541     }
3542   else if (DARWIN_X86 && darwin_symbol_stubs && TARGET_64BIT)
3543     {
3544       inform (input_location,
3545 	      "%<-mpic-symbol-stubs%> is not required for 64-bit code "
3546 	      "(ignored)");
3547       darwin_symbol_stubs = false;
3548     }
3549 
3550   if (generating_for_darwin_version >= 9)
3551     /* Later systems can support aligned common.  */
3552     emit_aligned_common = true;
3553 
3554   /* The c_dialect...() macros are not available to us here.  */
3555   darwin_running_cxx = (strstr (lang_hooks.name, "C++") != 0);
3556 }
3557 
3558 #if DARWIN_PPC
3559 /* Add $LDBL128 suffix to long double builtins for ppc darwin.  */
3560 
3561 static void
darwin_patch_builtin(enum built_in_function fncode)3562 darwin_patch_builtin (enum built_in_function fncode)
3563 {
3564   tree fn = builtin_decl_explicit (fncode);
3565   tree sym;
3566   char *newname;
3567 
3568   if (!fn)
3569     return;
3570 
3571   sym = DECL_ASSEMBLER_NAME (fn);
3572   newname = ACONCAT (("_", IDENTIFIER_POINTER (sym), "$LDBL128", NULL));
3573 
3574   set_user_assembler_name (fn, newname);
3575 
3576   fn = builtin_decl_implicit (fncode);
3577   if (fn)
3578     set_user_assembler_name (fn, newname);
3579 }
3580 
3581 void
darwin_patch_builtins(void)3582 darwin_patch_builtins (void)
3583 {
3584   if (LONG_DOUBLE_TYPE_SIZE != 128)
3585     return;
3586 
3587 #define PATCH_BUILTIN(fncode) darwin_patch_builtin (fncode);
3588 #define PATCH_BUILTIN_NO64(fncode)		\
3589   if (!TARGET_64BIT)				\
3590     darwin_patch_builtin (fncode);
3591 #define PATCH_BUILTIN_VARIADIC(fncode)				  \
3592   if (!TARGET_64BIT						  \
3593       && (strverscmp (darwin_macosx_version_min, "10.3.9") >= 0)) \
3594     darwin_patch_builtin (fncode);
3595 #include "darwin-ppc-ldouble-patch.def"
3596 #undef PATCH_BUILTIN
3597 #undef PATCH_BUILTIN_NO64
3598 #undef PATCH_BUILTIN_VARIADIC
3599 }
3600 #endif
3601 
3602 void
darwin_rename_builtins(void)3603 darwin_rename_builtins (void)
3604 {
3605 }
3606 
3607 /* Implementation for the TARGET_LIBC_HAS_FUNCTION hook.  */
3608 
3609 bool
darwin_libc_has_function(enum function_class fn_class,tree type ATTRIBUTE_UNUSED)3610 darwin_libc_has_function (enum function_class fn_class,
3611 			  tree type ATTRIBUTE_UNUSED)
3612 {
3613   if (fn_class == function_sincos && darwin_macosx_version_min)
3614     return (strverscmp (darwin_macosx_version_min, "10.9") >= 0);
3615 #if DARWIN_PPC && SUPPORT_DARWIN_LEGACY
3616   if (fn_class == function_c99_math_complex
3617       || fn_class == function_c99_misc)
3618     return (TARGET_64BIT
3619 	    || (darwin_macosx_version_min &&
3620 		strverscmp (darwin_macosx_version_min, "10.3") >= 0));
3621 #endif
3622   return default_libc_has_function (fn_class, type);
3623 }
3624 
3625 /*  CFStrings implementation.  */
3626 static GTY(()) tree cfstring_class_reference = NULL_TREE;
3627 static GTY(()) tree cfstring_type_node = NULL_TREE;
3628 static GTY(()) tree ccfstring_type_node = NULL_TREE;
3629 static GTY(()) tree pccfstring_type_node = NULL_TREE;
3630 static GTY(()) tree pcint_type_node = NULL_TREE;
3631 static GTY(()) tree pcchar_type_node = NULL_TREE;
3632 
3633 static enum built_in_function darwin_builtin_cfstring;
3634 
3635 /* Store all constructed constant CFStrings in a hash table so that
3636    they get uniqued properly.  */
3637 
3638 typedef struct GTY ((for_user)) cfstring_descriptor {
3639   /* The string literal.  */
3640   tree literal;
3641   /* The resulting constant CFString.  */
3642   tree ccf_str;
3643 } cfstring_descriptor;
3644 
3645 struct cfstring_hasher : ggc_ptr_hash<cfstring_descriptor>
3646 {
3647   static hashval_t hash (cfstring_descriptor *);
3648   static bool equal (cfstring_descriptor *, cfstring_descriptor *);
3649 };
3650 
3651 static GTY (()) hash_table<cfstring_hasher> *cfstring_htab;
3652 
3653 static tree
add_builtin_field_decl(tree type,const char * name,tree ** chain)3654 add_builtin_field_decl (tree type, const char *name, tree **chain)
3655 {
3656   tree field = build_decl (BUILTINS_LOCATION, FIELD_DECL,
3657 			    get_identifier (name), type);
3658 
3659   if (*chain != NULL)
3660     **chain = field;
3661   *chain = &DECL_CHAIN (field);
3662 
3663   return field;
3664 }
3665 
3666 tree
darwin_init_cfstring_builtins(unsigned builtin_cfstring)3667 darwin_init_cfstring_builtins (unsigned builtin_cfstring)
3668 {
3669   tree cfsfun, fields, pccfstring_ftype_pcchar;
3670   tree *chain = NULL;
3671 
3672   darwin_builtin_cfstring =
3673     (enum built_in_function) builtin_cfstring;
3674 
3675   /* struct __builtin_CFString {
3676        const int *isa;		(will point at
3677        int flags;		 __CFConstantStringClassReference)
3678        const char *str;
3679        long length;
3680      };  */
3681 
3682   pcint_type_node = build_pointer_type
3683 		   (build_qualified_type (integer_type_node, TYPE_QUAL_CONST));
3684 
3685   pcchar_type_node = build_pointer_type
3686 		   (build_qualified_type (char_type_node, TYPE_QUAL_CONST));
3687 
3688   cfstring_type_node = (*lang_hooks.types.make_type) (RECORD_TYPE);
3689 
3690   /* Have to build backwards for finish struct.  */
3691   fields = add_builtin_field_decl (long_integer_type_node, "length", &chain);
3692   add_builtin_field_decl (pcchar_type_node, "str", &chain);
3693   add_builtin_field_decl (integer_type_node, "flags", &chain);
3694   add_builtin_field_decl (pcint_type_node, "isa", &chain);
3695   finish_builtin_struct (cfstring_type_node, "__builtin_CFString",
3696 			 fields, NULL_TREE);
3697 
3698   /* const struct __builtin_CFstring *
3699      __builtin___CFStringMakeConstantString (const char *); */
3700 
3701   ccfstring_type_node = build_qualified_type
3702 			(cfstring_type_node, TYPE_QUAL_CONST);
3703   pccfstring_type_node = build_pointer_type (ccfstring_type_node);
3704   pccfstring_ftype_pcchar = build_function_type_list
3705 			(pccfstring_type_node, pcchar_type_node, NULL_TREE);
3706 
3707   cfsfun  = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
3708 			get_identifier ("__builtin___CFStringMakeConstantString"),
3709 			pccfstring_ftype_pcchar);
3710 
3711   TREE_PUBLIC (cfsfun) = 1;
3712   DECL_EXTERNAL (cfsfun) = 1;
3713   DECL_ARTIFICIAL (cfsfun) = 1;
3714   /* Make a lang-specific section - dup_lang_specific_decl makes a new node
3715      in place of the existing, which may be NULL.  */
3716   DECL_LANG_SPECIFIC (cfsfun) = NULL;
3717   lang_hooks.dup_lang_specific_decl (cfsfun);
3718   set_decl_built_in_function (cfsfun, BUILT_IN_MD, darwin_builtin_cfstring);
3719   lang_hooks.builtin_function (cfsfun);
3720 
3721   /* extern int __CFConstantStringClassReference[];  */
3722   cfstring_class_reference = build_decl (BUILTINS_LOCATION, VAR_DECL,
3723 		 get_identifier ("__CFConstantStringClassReference"),
3724 		 build_array_type (integer_type_node, NULL_TREE));
3725 
3726   TREE_PUBLIC (cfstring_class_reference) = 1;
3727   DECL_ARTIFICIAL (cfstring_class_reference) = 1;
3728   lang_hooks.decls.pushdecl (cfstring_class_reference);
3729   DECL_EXTERNAL (cfstring_class_reference) = 1;
3730   rest_of_decl_compilation (cfstring_class_reference, 0, 0);
3731 
3732   /* Initialize the hash table used to hold the constant CFString objects.  */
3733   cfstring_htab = hash_table<cfstring_hasher>::create_ggc (31);
3734 
3735   return cfstring_type_node;
3736 }
3737 
3738 tree
darwin_fold_builtin(tree fndecl,int n_args,tree * argp,bool ARG_UNUSED (ignore))3739 darwin_fold_builtin (tree fndecl, int n_args, tree *argp,
3740 		     bool ARG_UNUSED (ignore))
3741 {
3742   int fcode = DECL_MD_FUNCTION_CODE (fndecl);
3743 
3744   if (fcode == darwin_builtin_cfstring)
3745     {
3746       if (!darwin_constant_cfstrings)
3747 	{
3748 	  error ("built-in function %qD requires the"
3749 		 " %<-mconstant-cfstrings%> flag", fndecl);
3750 	  return error_mark_node;
3751 	}
3752 
3753       if (n_args != 1)
3754 	{
3755 	  error ("built-in function %qD takes one argument only", fndecl);
3756 	  return error_mark_node;
3757 	}
3758 
3759       return darwin_build_constant_cfstring (*argp);
3760     }
3761 
3762   return NULL_TREE;
3763 }
3764 
3765 hashval_t
hash(cfstring_descriptor * ptr)3766 cfstring_hasher::hash (cfstring_descriptor *ptr)
3767 {
3768   tree str = ptr->literal;
3769   const unsigned char *p = (const unsigned char *) TREE_STRING_POINTER (str);
3770   int i, len = TREE_STRING_LENGTH (str);
3771   hashval_t h = len;
3772 
3773   for (i = 0; i < len; i++)
3774     h = ((h * 613) + p[i]);
3775 
3776   return h;
3777 }
3778 
3779 bool
equal(cfstring_descriptor * ptr1,cfstring_descriptor * ptr2)3780 cfstring_hasher::equal (cfstring_descriptor *ptr1, cfstring_descriptor *ptr2)
3781 {
3782   tree str1 = ptr1->literal;
3783   tree str2 = ptr2->literal;
3784   int len1 = TREE_STRING_LENGTH (str1);
3785 
3786   return (len1 == TREE_STRING_LENGTH (str2)
3787 	  && !memcmp (TREE_STRING_POINTER (str1), TREE_STRING_POINTER (str2),
3788 		      len1));
3789 }
3790 
3791 tree
darwin_build_constant_cfstring(tree str)3792 darwin_build_constant_cfstring (tree str)
3793 {
3794   struct cfstring_descriptor *desc, key;
3795   tree addr;
3796 
3797   if (!str)
3798     {
3799       error ("CFString literal is missing");
3800       return error_mark_node;
3801     }
3802 
3803   STRIP_NOPS (str);
3804 
3805   if (TREE_CODE (str) == ADDR_EXPR)
3806     str = TREE_OPERAND (str, 0);
3807 
3808   if (TREE_CODE (str) != STRING_CST)
3809     {
3810       error ("CFString literal expression is not a string constant");
3811       return error_mark_node;
3812     }
3813 
3814   /* Perhaps we already constructed a constant CFString just like this one? */
3815   key.literal = str;
3816   cfstring_descriptor **loc = cfstring_htab->find_slot (&key, INSERT);
3817   desc = *loc;
3818 
3819   if (!desc)
3820     {
3821       tree var, constructor, field;
3822       vec<constructor_elt, va_gc> *v = NULL;
3823       int length = TREE_STRING_LENGTH (str) - 1;
3824 
3825       if (darwin_warn_nonportable_cfstrings)
3826 	{
3827 	  const char *s = TREE_STRING_POINTER (str);
3828 	  int l = 0;
3829 
3830 	  for (l = 0; l < length; l++)
3831 	    if (!s[l] || !isascii (s[l]))
3832 	      {
3833 		warning (darwin_warn_nonportable_cfstrings,
3834 			 s[l] ? G_("non-ASCII character in CFString literal")
3835 			      : G_("embedded NUL in CFString literal"));
3836 		break;
3837 	      }
3838 	}
3839 
3840       *loc = desc = ggc_cleared_alloc<cfstring_descriptor> ();
3841       desc->literal = str;
3842 
3843       /* isa *. */
3844       field = TYPE_FIELDS (ccfstring_type_node);
3845       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3846 			     build1 (ADDR_EXPR,  TREE_TYPE (field),
3847 				     cfstring_class_reference));
3848       /* flags */
3849       field = DECL_CHAIN (field);
3850       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3851 			     build_int_cst (TREE_TYPE (field), 0x000007c8));
3852       /* string *. */
3853       field = DECL_CHAIN (field);
3854       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3855 			     build1 (ADDR_EXPR, TREE_TYPE (field), str));
3856       /* length */
3857       field = DECL_CHAIN (field);
3858       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3859 			     build_int_cst (TREE_TYPE (field), length));
3860 
3861       constructor = build_constructor (ccfstring_type_node, v);
3862       TREE_READONLY (constructor) = true;
3863       TREE_CONSTANT (constructor) = true;
3864       TREE_STATIC (constructor) = true;
3865 
3866       /* This file is being built without any knowledge of C++ tree accessors;
3867 	 hence, we shall use the generic accessor to set TREE_HAS_CONSTRUCTOR.
3868 	 ??? Is this actually used any more? */
3869       if (darwin_running_cxx)
3870 	TREE_LANG_FLAG_4 (constructor) = 1;  /* TREE_HAS_CONSTRUCTOR  */
3871 
3872       /* Create an anonymous global variable for this CFString.  */
3873       var = build_decl (input_location, VAR_DECL,
3874 			NULL, TREE_TYPE (constructor));
3875       char *name = xasprintf ("__anon_cfstring.%u", DECL_UID (var));
3876       DECL_NAME (var) = get_identifier (name);
3877       free (name);
3878       DECL_ARTIFICIAL (var) = true;
3879       TREE_STATIC (var) = true;
3880       TREE_READONLY (var) = true;
3881       TREE_CONSTANT (var) = true;
3882       DECL_INITIAL (var) = constructor;
3883       /* global namespace.  */
3884       DECL_CONTEXT (var) = NULL_TREE;
3885       DECL_INITIAL (var) = constructor;
3886       DECL_USER_ALIGN (var) = 1;
3887       lang_hooks.decls.pushdecl (var);
3888       rest_of_decl_compilation (var, 1, 0);
3889       desc->ccf_str = var;
3890     }
3891 
3892   addr = build1 (ADDR_EXPR, pccfstring_type_node, desc->ccf_str);
3893   TREE_CONSTANT (addr) = 1;
3894 
3895   return addr;
3896 }
3897 
3898 bool
darwin_cfstring_p(tree str)3899 darwin_cfstring_p (tree str)
3900 {
3901   struct cfstring_descriptor key;
3902 
3903   if (!str)
3904     return false;
3905 
3906   STRIP_NOPS (str);
3907 
3908   if (TREE_CODE (str) == ADDR_EXPR)
3909     str = TREE_OPERAND (str, 0);
3910 
3911   if (TREE_CODE (str) != STRING_CST)
3912     return false;
3913 
3914   key.literal = str;
3915   cfstring_descriptor **loc = cfstring_htab->find_slot (&key, NO_INSERT);
3916 
3917   if (loc)
3918     return true;
3919 
3920   return false;
3921 }
3922 
3923 void
darwin_enter_string_into_cfstring_table(tree str)3924 darwin_enter_string_into_cfstring_table (tree str)
3925 {
3926   struct cfstring_descriptor key;
3927 
3928   key.literal = str;
3929   cfstring_descriptor **loc = cfstring_htab->find_slot (&key, INSERT);
3930 
3931   if (!*loc)
3932     {
3933       *loc = ggc_cleared_alloc<cfstring_descriptor> ();
3934       ((struct cfstring_descriptor *)*loc)->literal = str;
3935     }
3936 }
3937 
3938 /* Choose named function section based on its frequency.  */
3939 
3940 section *
darwin_function_section(tree decl,enum node_frequency freq,bool startup,bool exit)3941 darwin_function_section (tree decl, enum node_frequency freq,
3942 			  bool startup, bool exit)
3943 {
3944   /* Decide if we need to put this in a coalescable section.  */
3945   bool weak = (decl
3946 	       && DECL_WEAK (decl)
3947 	       && (!DECL_ATTRIBUTES (decl)
3948 		   || !lookup_attribute ("weak_import",
3949 					  DECL_ATTRIBUTES (decl))));
3950 
3951   bool use_coal = weak && ld_uses_coal_sects;
3952   /* If there is a specified section name, we should not be trying to
3953      override.  */
3954   if (decl && DECL_SECTION_NAME (decl) != NULL)
3955     return get_named_section (decl, NULL, 0);
3956 
3957   /* We always put unlikely executed stuff in the cold section; we have to put
3958      this ahead of the global init section, since partitioning within a section
3959      breaks some assumptions made in the DWARF handling.  */
3960   if (freq == NODE_FREQUENCY_UNLIKELY_EXECUTED)
3961     return (use_coal) ? darwin_sections[text_cold_coal_section]
3962 		      : darwin_sections[text_cold_section];
3963 
3964   /* Intercept functions in global init; these are placed in separate sections.
3965      FIXME: there should be some neater way to do this, FIXME we should be able
3966      to partition within a section.  */
3967   if (DECL_NAME (decl)
3968       && (startswith (IDENTIFIER_POINTER (DECL_NAME (decl)), "_GLOBAL__sub_I")
3969 	  || startswith (IDENTIFIER_POINTER (DECL_NAME (decl)),
3970 			 "__static_initialization_and_destruction")))
3971     return  darwin_sections[static_init_section];
3972 
3973   /* If we have LTO *and* feedback information, then let LTO handle
3974      the function ordering, it makes a better job (for normal, hot,
3975      startup and exit - hence the bailout for cold above).  */
3976   if (in_lto_p && flag_profile_values)
3977     goto default_function_sections;
3978 
3979   /* Non-cold startup code should go to startup subsection.  */
3980   if (startup)
3981     return (use_coal) ? darwin_sections[text_startup_coal_section]
3982 		      : darwin_sections[text_startup_section];
3983 
3984   /* Similarly for exit.  */
3985   if (exit)
3986     return (use_coal) ? darwin_sections[text_exit_coal_section]
3987 		      : darwin_sections[text_exit_section];
3988 
3989   /* Place hot code.  */
3990   if (freq == NODE_FREQUENCY_HOT)
3991     return (use_coal) ? darwin_sections[text_hot_coal_section]
3992 		      : darwin_sections[text_hot_section];
3993 
3994   /* Otherwise, default to the 'normal' non-reordered sections.  */
3995 default_function_sections:
3996   return (use_coal) ? darwin_sections[text_coal_section]
3997 		    : text_section;
3998 }
3999 
4000 #include "gt-darwin.h"
4001