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