Refactor some code for a future change.
[official-gcc.git] / gcc / config / darwin.c
blobe7892617d9d83389aa9953722fe87a31fda41dcb
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.
5 This file is part of GCC.
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.
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.
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/>. */
21 #define IN_TARGET_CODE 1
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "backend.h"
27 #include "target.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "gimple.h"
31 #include "cfghooks.h"
32 #include "df.h"
33 #include "memmodel.h"
34 #include "tm_p.h"
35 #include "stringpool.h"
36 #include "attribs.h"
37 #include "insn-config.h"
38 #include "emit-rtl.h"
39 #include "cgraph.h"
40 #include "lto-streamer.h"
41 #include "output.h"
42 #include "varasm.h"
43 #include "stor-layout.h"
44 #include "explow.h"
45 #include "expr.h"
46 #include "langhooks.h"
47 #include "toplev.h"
48 #include "lto-section-names.h"
49 #include "intl.h"
50 #include "optabs.h"
52 /* Fix and Continue.
54 NOTES:
55 1) this facility requires suitable support from a modified version
56 of GDB, which is not provided on any system after MacOS 10.7/Darwin11.
57 2) There is no support for this in any X86 version of the FSF compiler.
59 Fix and continue was used on some earlier MacOS systems for rapid turn
60 around debugging. When code is compiled with the -mfix-and-continue
61 flag, two changes are made to the generated code that allow the system
62 to do things that it would normally not be able to do easily. These
63 changes allow gdb to load in recompilation of a translation unit that
64 has been changed into a running program and replace existing functions
65 and methods of that translation unit with versions of those functions
66 and methods from the newly compiled translation unit. The new functions
67 access the existing static symbols from the old translation unit, if the
68 symbol existed in the unit to be replaced, and from the new translation
69 unit, otherwise.
71 The changes are to insert 5 nops at the beginning of all functions
72 and to use indirection to get at static symbols. The 5 nops
73 are required by consumers of the generated code. Currently, gdb
74 uses this to patch in a jump to the overriding function, this
75 allows all uses of the old name to forward to the replacement,
76 including existing function pointers and virtual methods. See
77 rs6000_emit_prologue for the code that handles the nop insertions.
79 The added indirection allows gdb to redirect accesses to static
80 symbols from the newly loaded translation unit to the existing
81 symbol, if any. @code{static} symbols are special and are handled by
82 setting the second word in the .non_lazy_symbol_pointer data
83 structure to symbol. See indirect_data for the code that handles
84 the extra indirection, and machopic_output_indirection and its use
85 of MACHO_SYMBOL_FLAG_STATIC for the code that handles @code{static}
86 symbol indirection. */
88 typedef struct GTY(()) cdtor_record {
89 rtx symbol;
90 int priority; /* [con/de]structor priority */
91 int position; /* original position */
92 } cdtor_record;
94 static GTY(()) vec<cdtor_record, va_gc> *ctors = NULL;
95 static GTY(()) vec<cdtor_record, va_gc> *dtors = NULL;
97 /* A flag to determine whether we are running c++ or obj-c++. This has to be
98 settable from non-c-family contexts too (i.e. we can't use the c_dialect_
99 functions). */
100 int darwin_running_cxx;
102 /* Some code-gen now depends on OS major version numbers (at least). */
103 int generating_for_darwin_version ;
105 /* For older linkers we need to emit special sections (marked 'coalesced') for
106 for weak or single-definition items. */
107 static bool ld_uses_coal_sects = false;
109 /* Very old (ld_classic) linkers need a symbol to mark the start of
110 each FDE. */
111 static bool ld_needs_eh_markers = false;
113 /* Section names. */
114 section * darwin_sections[NUM_DARWIN_SECTIONS];
116 /* While we transition to using in-tests instead of ifdef'd code. */
117 #if !HAVE_lo_sum
118 #define gen_macho_high(m,a,b) (a)
119 #define gen_macho_low(m,a,b,c) (a)
120 #endif
122 /* True if we're setting __attribute__ ((ms_struct)). */
123 int darwin_ms_struct = false;
125 /* Earlier versions of Darwin as do not recognize an alignment field in
126 .comm directives, this should be set for versions that allow it. */
127 int emit_aligned_common = false;
129 /* A get_unnamed_section callback used to switch to an ObjC section.
130 DIRECTIVE is as for output_section_asm_op. */
132 static void
133 output_objc_section_asm_op (const void *directive)
135 static bool been_here = false;
137 /* The NeXT ObjC Runtime requires these sections to be present and in
138 order in the object. The code below implements this by emitting
139 a section header for each ObjC section the first time that an ObjC
140 section is requested. */
141 if (! been_here)
143 section *saved_in_section = in_section;
144 static const enum darwin_section_enum tomark[] =
146 /* written, cold -> hot */
147 objc_cat_cls_meth_section,
148 objc_cat_inst_meth_section,
149 objc_string_object_section,
150 objc_constant_string_object_section,
151 objc_selector_refs_section,
152 objc_selector_fixup_section,
153 objc_cls_refs_section,
154 objc_class_section,
155 objc_meta_class_section,
156 /* shared, hot -> cold */
157 objc_cls_meth_section,
158 objc_inst_meth_section,
159 objc_protocol_section,
160 objc_class_names_section,
161 objc_meth_var_types_section,
162 objc_meth_var_names_section,
163 objc_category_section,
164 objc_class_vars_section,
165 objc_instance_vars_section,
166 objc_module_info_section,
167 objc_symbols_section,
169 /* ABI=1 */
170 static const enum darwin_section_enum tomarkv1[] =
172 objc1_protocol_ext_section,
173 objc1_class_ext_section,
174 objc1_prop_list_section
176 /* ABI=2 */
177 static const enum darwin_section_enum tomarkv2[] =
179 objc2_message_refs_section,
180 objc2_classdefs_section,
181 objc2_metadata_section,
182 objc2_classrefs_section,
183 objc2_classlist_section,
184 objc2_categorylist_section,
185 objc2_selector_refs_section,
186 objc2_nonlazy_class_section,
187 objc2_nonlazy_category_section,
188 objc2_protocollist_section,
189 objc2_protocolrefs_section,
190 objc2_super_classrefs_section,
191 objc2_image_info_section,
192 objc2_constant_string_object_section
194 size_t i;
196 been_here = true;
197 if (flag_objc_abi < 2)
199 for (i = 0; i < ARRAY_SIZE (tomark); i++)
200 switch_to_section (darwin_sections[tomark[i]]);
201 if (flag_objc_abi == 1)
202 for (i = 0; i < ARRAY_SIZE (tomarkv1); i++)
203 switch_to_section (darwin_sections[tomarkv1[i]]);
205 else
206 for (i = 0; i < ARRAY_SIZE (tomarkv2); i++)
207 switch_to_section (darwin_sections[tomarkv2[i]]);
208 /* Make sure we don't get varasm.c out of sync with us. */
209 switch_to_section (saved_in_section);
211 output_section_asm_op (directive);
215 /* Private flag applied to disable section-anchors in a particular section. */
216 #define SECTION_NO_ANCHOR SECTION_MACH_DEP
219 /* Implement TARGET_ASM_INIT_SECTIONS. */
221 void
222 darwin_init_sections (void)
224 #define DEF_SECTION(NAME, FLAGS, DIRECTIVE, OBJC) \
225 darwin_sections[NAME] = \
226 get_unnamed_section (FLAGS, (OBJC \
227 ? output_objc_section_asm_op \
228 : output_section_asm_op), \
229 "\t" DIRECTIVE);
230 #include "config/darwin-sections.def"
231 #undef DEF_SECTION
233 readonly_data_section = darwin_sections[const_section];
234 exception_section = darwin_sections[darwin_exception_section];
235 eh_frame_section = darwin_sections[darwin_eh_frame_section];
237 /* If our linker is new enough to coalesce weak symbols, then we
238 can just put picbase_thunks into the text section. */
239 if (! ld_uses_coal_sects )
240 darwin_sections[picbase_thunk_section] = text_section;
244 name_needs_quotes (const char *name)
246 int c;
247 while ((c = *name++) != '\0')
248 if (! ISIDNUM (c)
249 && c != '.' && c != '$' && c != '_' )
250 return 1;
251 return 0;
254 /* Return true if SYM_REF can be used without an indirection. */
256 machopic_symbol_defined_p (rtx sym_ref)
258 if (MACHO_SYMBOL_DEFINED_P (sym_ref))
259 return true;
261 /* If a symbol references local and is not an extern to this
262 file, then the symbol might be able to declared as defined. */
263 if (SYMBOL_REF_LOCAL_P (sym_ref) && ! SYMBOL_REF_EXTERNAL_P (sym_ref))
265 /* If the symbol references a variable and the variable is a
266 common symbol, then this symbol is not defined. */
267 if (MACHO_SYMBOL_VARIABLE_P (sym_ref))
269 tree decl = SYMBOL_REF_DECL (sym_ref);
270 if (!decl)
271 return true;
272 if (DECL_COMMON (decl))
273 return false;
275 return true;
277 return false;
280 /* This module assumes that (const (symbol_ref "foo")) is a legal pic
281 reference, which will not be changed. */
283 enum machopic_addr_class
284 machopic_classify_symbol (rtx sym_ref)
286 bool function_p;
288 function_p = SYMBOL_REF_FUNCTION_P (sym_ref);
289 if (machopic_symbol_defined_p (sym_ref))
290 return (function_p
291 ? MACHOPIC_DEFINED_FUNCTION : MACHOPIC_DEFINED_DATA);
292 else
293 return (function_p
294 ? MACHOPIC_UNDEFINED_FUNCTION : MACHOPIC_UNDEFINED_DATA);
297 #ifndef TARGET_FIX_AND_CONTINUE
298 #define TARGET_FIX_AND_CONTINUE 0
299 #endif
301 /* Indicate when fix-and-continue style code generation is being used
302 and when a reference to data should be indirected so that it can be
303 rebound in a new translation unit to reference the original instance
304 of that data. Symbol names that are for code generation local to
305 the translation unit are bound to the new translation unit;
306 currently this means symbols that begin with L or _OBJC_;
307 otherwise, we indicate that an indirect reference should be made to
308 permit the runtime to rebind new instances of the translation unit
309 to the original instance of the data. */
311 static int
312 indirect_data (rtx sym_ref)
314 int lprefix;
315 const char *name;
317 /* If we aren't generating fix-and-continue code, don't do anything
318 special. */
319 if (TARGET_FIX_AND_CONTINUE == 0)
320 return 0;
322 /* Otherwise, all symbol except symbols that begin with L or _OBJC_
323 are indirected. Symbols that begin with L and _OBJC_ are always
324 bound to the current translation unit as they are used for
325 generated local data of the translation unit. */
327 name = XSTR (sym_ref, 0);
329 lprefix = (((name[0] == '*' || name[0] == '&')
330 && (name[1] == 'L' || (name[1] == '"' && name[2] == 'L')))
331 || (strncmp (name, "_OBJC_", 6) == 0));
333 return ! lprefix;
336 static int
337 machopic_data_defined_p (rtx sym_ref)
339 if (indirect_data (sym_ref))
340 return 0;
342 switch (machopic_classify_symbol (sym_ref))
344 case MACHOPIC_DEFINED_DATA:
345 case MACHOPIC_DEFINED_FUNCTION:
346 return 1;
347 default:
348 return 0;
352 void
353 machopic_define_symbol (rtx mem)
355 rtx sym_ref;
357 gcc_assert (GET_CODE (mem) == MEM);
358 sym_ref = XEXP (mem, 0);
359 SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
362 /* Return either ORIG or:
364 (const:P (unspec:P [ORIG] UNSPEC_MACHOPIC_OFFSET))
366 depending on MACHO_DYNAMIC_NO_PIC_P. */
368 machopic_gen_offset (rtx orig)
370 if (MACHO_DYNAMIC_NO_PIC_P)
371 return orig;
372 else
374 /* Play games to avoid marking the function as needing pic if we
375 are being called as part of the cost-estimation process. */
376 if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
377 crtl->uses_pic_offset_table = 1;
378 orig = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, orig),
379 UNSPEC_MACHOPIC_OFFSET);
380 return gen_rtx_CONST (Pmode, orig);
384 static GTY(()) const char * function_base_func_name = NULL;
385 static GTY(()) unsigned current_pic_label_num = 0;
386 static GTY(()) unsigned emitted_pic_label_num = 0;
388 /* We need to keep one picbase label per function, but (when we emit code
389 to reload the picbase for setjump receiver) we might need to check for
390 a second use. So, only update the picbase label counter when we see a
391 new function. When there's no function decl, we assume that the call is
392 from the x86 stub generation code. */
393 static void
394 update_pic_label_number_if_needed (void)
396 if (current_function_decl)
399 const char *current_name =
400 IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl));
401 if (function_base_func_name != current_name)
403 ++current_pic_label_num;
404 function_base_func_name = current_name;
407 else
409 ++current_pic_label_num;
410 function_base_func_name = "L_machopic_stub_dummy";
414 void
415 machopic_output_function_base_name (FILE *file)
417 /* We should only get here for -fPIC. */
418 gcc_checking_assert (MACHOPIC_PURE);
420 update_pic_label_number_if_needed ();
421 fprintf (file, "L%u$pb", current_pic_label_num);
424 char curr_picbasename[32];
426 const char *
427 machopic_get_function_picbase (void)
429 /* We should only get here for -fPIC. */
430 gcc_checking_assert (MACHOPIC_PURE);
432 update_pic_label_number_if_needed ();
433 snprintf (curr_picbasename, 32, "L%u$pb", current_pic_label_num);
434 return (const char *) curr_picbasename;
437 bool
438 machopic_should_output_picbase_label (void)
440 update_pic_label_number_if_needed ();
442 if (current_pic_label_num == emitted_pic_label_num)
443 return false;
445 emitted_pic_label_num = current_pic_label_num;
446 return true;
449 /* The suffix attached to non-lazy pointer symbols. */
450 #define NON_LAZY_POINTER_SUFFIX "$non_lazy_ptr"
451 /* The suffix attached to stub symbols. */
452 #define STUB_SUFFIX "$stub"
454 typedef struct GTY ((for_user)) machopic_indirection
456 /* The SYMBOL_REF for the entity referenced. */
457 rtx symbol;
458 /* The name of the stub or non-lazy pointer. */
459 const char * ptr_name;
460 /* True iff this entry is for a stub (as opposed to a non-lazy
461 pointer). */
462 bool stub_p;
463 /* True iff this stub or pointer has been referenced. */
464 bool used;
465 /* True iff a non-lazy symbol pointer should be emitted into the .data
466 section, rather than the non-lazy symbol pointers section. The cases
467 for which this occurred seem to have been unintentional, and later
468 toolchains emit all of the indirections to the 'usual' section. We
469 are keeping this in case it is necessary to preserve compatibility with
470 older toolchains. */
471 bool nlsp_in_data_section;
472 } machopic_indirection;
474 struct indirection_hasher : ggc_ptr_hash<machopic_indirection>
476 typedef const char *compare_type;
477 static hashval_t hash (machopic_indirection *);
478 static bool equal (machopic_indirection *, const char *);
481 /* A table mapping stub names and non-lazy pointer names to
482 SYMBOL_REFs for the stubbed-to and pointed-to entities. */
484 static GTY (()) hash_table<indirection_hasher> *machopic_indirections;
486 /* Return a hash value for a SLOT in the indirections hash table. */
488 hashval_t
489 indirection_hasher::hash (machopic_indirection *p)
491 return htab_hash_string (p->ptr_name);
494 /* Returns true if the KEY is the same as that associated with
495 SLOT. */
497 bool
498 indirection_hasher::equal (machopic_indirection *s, const char *k)
500 return strcmp (s->ptr_name, k) == 0;
503 /* Return the name of the non-lazy pointer (if STUB_P is false) or
504 stub (if STUB_B is true) corresponding to the given name.
506 PR71767 - If we have a situation like:
508 global_weak_symbol:
509 ....
510 Lnon_weak_local:
511 ....
513 ld64 will be unable to split this into two atoms (because the "L" makes
514 the second symbol 'invisible'). This means that legitimate direct accesses
515 to the second symbol will appear to be direct accesses to an atom of type
516 weak, global which are not allowed.
518 To avoid this, we make any data-section indirections have a leading 'l'
519 (lower-case L) which has a special meaning: linker can see this and use
520 it to determine atoms, but it is not placed into the final symbol table.
522 Symbols in the non-lazy symbol pointers section (or stubs) do not have this
523 problem because ld64 already knows the size of each entry.
526 const char *
527 machopic_indirection_name (rtx sym_ref, bool stub_p)
529 const char *name = XSTR (sym_ref, 0);
530 tree id = maybe_get_identifier (name);
531 if (id)
533 tree id_orig = id;
535 while (IDENTIFIER_TRANSPARENT_ALIAS (id))
536 id = TREE_CHAIN (id);
537 if (id != id_orig)
538 name = IDENTIFIER_POINTER (id);
541 const char *prefix = user_label_prefix;
542 /* If we are emitting the label 'verbatim' then omit the U_L_P and count
543 the name without the leading '*'. */
544 if (name[0] == '*')
546 prefix = "";
547 ++name;
550 /* Here we are undoing a number of causes that placed some indirections
551 (apparently erroneously) into the .data section. Specifically, some
552 symbols that are ABI mandated indirections and some hidden symbols
553 were being placed there - which cause difficulties with later
554 versions of ld64. Iff (after these checks) some symbol still gets an
555 indirection in the data section, we want to adjust the indirection
556 name to be linker visible to deal with PR71767 (notes above). */
557 bool nlsp_in_data_section =
558 ! MACHO_SYMBOL_MUST_INDIRECT_P (sym_ref)
559 && ! MACHO_SYMBOL_HIDDEN_VIS_P (sym_ref)
560 && (machopic_symbol_defined_p (sym_ref) || SYMBOL_REF_LOCAL_P (sym_ref))
561 && ! indirect_data (sym_ref);
563 const char *suffix = stub_p ? STUB_SUFFIX : NON_LAZY_POINTER_SUFFIX;
564 /* If the indirection is in the data section, let the linker see it. */
565 char L_or_l = (!stub_p && nlsp_in_data_section) ? 'l' : 'L';
566 /* We have mangled symbols with spaces and punctuation which typically
567 need surrounding in quotes for the assembler to consume them. */
568 const char *quote = name_needs_quotes (name) ? "\"" : "";
569 char *buffer = XALLOCAVEC (char, 2 /* strlen ("&L") or ("&l") */
570 + strlen (prefix)
571 + strlen (name)
572 + strlen (suffix)
573 + 2 * strlen (quote)
574 + 1 /* '\0' */);
576 /* Construct the name of the non-lazy pointer or stub. */
577 sprintf (buffer, "&%s%c%s%s%s%s", quote, L_or_l, prefix, name,
578 suffix, quote);
580 if (!machopic_indirections)
581 machopic_indirections = hash_table<indirection_hasher>::create_ggc (37);
583 machopic_indirection **slot
584 = machopic_indirections->find_slot_with_hash (buffer,
585 htab_hash_string (buffer),
586 INSERT);
587 machopic_indirection *p;
588 if (*slot)
589 p = *slot;
590 else
592 p = ggc_alloc<machopic_indirection> ();
593 p->symbol = sym_ref;
594 p->ptr_name = xstrdup (buffer);
595 p->stub_p = stub_p;
596 p->used = false;
597 p->nlsp_in_data_section = nlsp_in_data_section;
598 *slot = p;
601 return p->ptr_name;
604 /* If NAME is the name of a stub or a non-lazy pointer , mark the stub
605 or non-lazy pointer as used -- and mark the object to which the
606 pointer/stub refers as used as well, since the pointer/stub will
607 emit a reference to it. */
609 void
610 machopic_validate_stub_or_non_lazy_ptr (const char *name)
612 machopic_indirection *p
613 = machopic_indirections->find_with_hash (name, htab_hash_string (name));
614 if (p && ! p->used)
616 const char *real_name;
617 tree id;
619 p->used = true;
621 /* Do what output_addr_const will do when we actually call it. */
622 if (SYMBOL_REF_DECL (p->symbol))
623 mark_decl_referenced (SYMBOL_REF_DECL (p->symbol));
625 real_name = targetm.strip_name_encoding (XSTR (p->symbol, 0));
627 id = maybe_get_identifier (real_name);
628 if (id)
629 mark_referenced (id);
633 /* Transform ORIG, which may be any data source, to the corresponding
634 source using indirections. */
637 machopic_indirect_data_reference (rtx orig, rtx reg)
639 rtx ptr_ref = orig;
641 if (! MACHOPIC_INDIRECT)
642 return orig;
644 if (GET_CODE (orig) == SYMBOL_REF)
646 int defined = machopic_data_defined_p (orig);
648 if (defined && MACHO_DYNAMIC_NO_PIC_P)
650 if (DARWIN_PPC)
652 /* Create a new register for CSE opportunities. */
653 rtx hi_reg = (!can_create_pseudo_p () ? reg : gen_reg_rtx (Pmode));
654 emit_insn (gen_macho_high (Pmode, hi_reg, orig));
655 emit_insn (gen_macho_low (Pmode, reg, hi_reg, orig));
656 return reg;
658 else if (DARWIN_X86)
659 return orig;
660 else
661 /* some other cpu -- writeme! */
662 gcc_unreachable ();
664 else if (defined && ! MACHO_SYMBOL_MUST_INDIRECT_P (orig))
666 rtx offset = NULL;
667 if (DARWIN_PPC || HAVE_lo_sum)
668 offset = machopic_gen_offset (orig);
670 if (DARWIN_PPC)
672 rtx hi_sum_reg = (!can_create_pseudo_p ()
673 ? reg
674 : gen_reg_rtx (Pmode));
676 gcc_assert (reg);
678 emit_insn (gen_rtx_SET (hi_sum_reg,
679 gen_rtx_PLUS (Pmode, pic_offset_table_rtx,
680 gen_rtx_HIGH (Pmode, offset))));
681 emit_insn (gen_rtx_SET (reg,
682 gen_rtx_LO_SUM (Pmode, hi_sum_reg,
683 copy_rtx (offset))));
685 orig = reg;
687 else if (HAVE_lo_sum)
689 gcc_assert (reg);
691 emit_insn (gen_rtx_SET (reg, gen_rtx_HIGH (Pmode, offset)));
692 emit_insn (gen_rtx_SET (reg, gen_rtx_LO_SUM (Pmode, reg,
693 copy_rtx (offset))));
694 emit_use (pic_offset_table_rtx);
696 orig = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, reg);
698 return orig;
701 ptr_ref = (gen_rtx_SYMBOL_REF
702 (Pmode,
703 machopic_indirection_name (orig, /*stub_p=*/false)));
705 SYMBOL_REF_DATA (ptr_ref) = SYMBOL_REF_DATA (orig);
706 SYMBOL_REF_FLAGS (ptr_ref) |= MACHO_SYMBOL_FLAG_INDIRECTION;
708 ptr_ref = gen_const_mem (Pmode, ptr_ref);
709 machopic_define_symbol (ptr_ref);
711 if (DARWIN_X86
712 && reg
713 && MACHO_DYNAMIC_NO_PIC_P)
715 emit_insn (gen_rtx_SET (reg, ptr_ref));
716 ptr_ref = reg;
719 return ptr_ref;
721 else if (GET_CODE (orig) == CONST)
723 /* If "(const (plus ...", walk the PLUS and return that result.
724 PLUS processing (below) will restore the "(const ..." if
725 appropriate. */
726 if (GET_CODE (XEXP (orig, 0)) == PLUS)
727 return machopic_indirect_data_reference (XEXP (orig, 0), reg);
728 else
729 return orig;
731 else if (GET_CODE (orig) == MEM)
733 XEXP (ptr_ref, 0) =
734 machopic_indirect_data_reference (XEXP (orig, 0), reg);
735 return ptr_ref;
737 else if (GET_CODE (orig) == PLUS)
739 rtx base, result;
741 /* Legitimize both operands of the PLUS. */
742 base = machopic_indirect_data_reference (XEXP (orig, 0), reg);
743 orig = machopic_indirect_data_reference (XEXP (orig, 1),
744 (base == reg ? 0 : reg));
745 if (MACHOPIC_INDIRECT && (GET_CODE (orig) == CONST_INT))
746 result = plus_constant (Pmode, base, INTVAL (orig));
747 else
748 result = gen_rtx_PLUS (Pmode, base, orig);
750 if (MACHOPIC_JUST_INDIRECT && GET_CODE (base) == MEM)
752 if (reg)
754 emit_move_insn (reg, result);
755 result = reg;
757 else
759 result = force_reg (GET_MODE (result), result);
763 return result;
765 return ptr_ref;
768 /* Transform TARGET (a MEM), which is a function call target, to the
769 corresponding symbol_stub if necessary. Return a new MEM. */
772 machopic_indirect_call_target (rtx target)
774 if (! darwin_symbol_stubs)
775 return target;
777 if (GET_CODE (target) != MEM)
778 return target;
780 if (MACHOPIC_INDIRECT
781 && GET_CODE (XEXP (target, 0)) == SYMBOL_REF
782 && ! MACHO_SYMBOL_DEFINED_P (XEXP (target, 0)))
784 rtx sym_ref = XEXP (target, 0);
785 const char *stub_name = machopic_indirection_name (sym_ref,
786 /*stub_p=*/true);
787 machine_mode mode = GET_MODE (sym_ref);
789 XEXP (target, 0) = gen_rtx_SYMBOL_REF (mode, stub_name);
790 SYMBOL_REF_DATA (XEXP (target, 0)) = SYMBOL_REF_DATA (sym_ref);
791 SYMBOL_REF_FLAGS (XEXP (target, 0)) |= MACHO_SYMBOL_FLAG_INDIRECTION;
792 MEM_READONLY_P (target) = 1;
793 MEM_NOTRAP_P (target) = 1;
796 return target;
800 machopic_legitimize_pic_address (rtx orig, machine_mode mode, rtx reg)
802 rtx pic_ref = orig;
804 if (! MACHOPIC_INDIRECT)
805 return orig;
807 /* First handle a simple SYMBOL_REF or LABEL_REF */
808 if (GET_CODE (orig) == LABEL_REF
809 || GET_CODE (orig) == SYMBOL_REF)
811 /* addr(foo) = &func+(foo-func) */
812 orig = machopic_indirect_data_reference (orig, reg);
814 if (GET_CODE (orig) == PLUS
815 && GET_CODE (XEXP (orig, 0)) == REG)
817 if (reg == 0)
818 return force_reg (mode, orig);
820 emit_move_insn (reg, orig);
821 return reg;
824 if (GET_CODE (orig) == MEM)
826 if (reg == 0)
828 gcc_assert (!lra_in_progress);
829 reg = gen_reg_rtx (Pmode);
832 #if HAVE_lo_sum
833 if (MACHO_DYNAMIC_NO_PIC_P
834 && (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
835 || GET_CODE (XEXP (orig, 0)) == LABEL_REF))
837 #if defined (TARGET_TOC) /* ppc */
838 rtx temp_reg = (!can_create_pseudo_p ()
839 ? reg :
840 gen_reg_rtx (Pmode));
841 rtx asym = XEXP (orig, 0);
842 rtx mem;
844 emit_insn (gen_macho_high (Pmode, temp_reg, asym));
845 mem = gen_const_mem (GET_MODE (orig),
846 gen_rtx_LO_SUM (Pmode, temp_reg,
847 copy_rtx (asym)));
848 emit_insn (gen_rtx_SET (reg, mem));
849 #else
850 /* Some other CPU -- WriteMe! but right now there are no other
851 platforms that can use dynamic-no-pic */
852 gcc_unreachable ();
853 #endif
854 pic_ref = reg;
856 else
857 if (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
858 || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
860 rtx offset = machopic_gen_offset (XEXP (orig, 0));
861 #if defined (TARGET_TOC) /* i.e., PowerPC */
862 /* Generating a new reg may expose opportunities for
863 common subexpression elimination. */
864 rtx hi_sum_reg = (!can_create_pseudo_p ()
865 ? reg
866 : gen_reg_rtx (Pmode));
867 rtx mem;
868 rtx sum;
870 sum = gen_rtx_HIGH (Pmode, offset);
871 if (! MACHO_DYNAMIC_NO_PIC_P)
872 sum = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, sum);
874 emit_insn (gen_rtx_SET (hi_sum_reg, sum));
876 mem = gen_const_mem (GET_MODE (orig),
877 gen_rtx_LO_SUM (Pmode,
878 hi_sum_reg,
879 copy_rtx (offset)));
880 rtx_insn *insn = emit_insn (gen_rtx_SET (reg, mem));
881 set_unique_reg_note (insn, REG_EQUAL, pic_ref);
883 pic_ref = reg;
884 #else
885 emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
887 emit_insn (gen_rtx_SET (reg,
888 gen_rtx_HIGH (Pmode,
889 gen_rtx_CONST (Pmode,
890 offset))));
891 emit_insn (gen_rtx_SET (reg,
892 gen_rtx_LO_SUM (Pmode, reg,
893 gen_rtx_CONST (Pmode,
894 copy_rtx (offset)))));
895 pic_ref = gen_rtx_PLUS (Pmode,
896 pic_offset_table_rtx, reg);
897 #endif
899 else
900 #endif /* HAVE_lo_sum */
902 rtx pic = pic_offset_table_rtx;
903 if (GET_CODE (pic) != REG)
905 emit_move_insn (reg, pic);
906 pic = reg;
908 #if 0
909 emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
910 #endif
912 if (lra_in_progress)
913 df_set_regs_ever_live (REGNO (pic), true);
914 pic_ref = gen_rtx_PLUS (Pmode, pic,
915 machopic_gen_offset (XEXP (orig, 0)));
918 #if !defined (TARGET_TOC)
919 emit_move_insn (reg, pic_ref);
920 pic_ref = gen_const_mem (GET_MODE (orig), reg);
921 #endif
923 else
926 #if HAVE_lo_sum
927 if (GET_CODE (orig) == SYMBOL_REF
928 || GET_CODE (orig) == LABEL_REF)
930 rtx offset = machopic_gen_offset (orig);
931 #if defined (TARGET_TOC) /* i.e., PowerPC */
932 rtx hi_sum_reg;
934 if (reg == 0)
936 gcc_assert (!lra_in_progress);
937 reg = gen_reg_rtx (Pmode);
940 hi_sum_reg = reg;
942 emit_insn (gen_rtx_SET (hi_sum_reg,
943 (MACHO_DYNAMIC_NO_PIC_P)
944 ? gen_rtx_HIGH (Pmode, offset)
945 : gen_rtx_PLUS (Pmode,
946 pic_offset_table_rtx,
947 gen_rtx_HIGH (Pmode,
948 offset))));
949 emit_insn (gen_rtx_SET (reg,
950 gen_rtx_LO_SUM (Pmode,
951 hi_sum_reg,
952 copy_rtx (offset))));
953 pic_ref = reg;
954 #else
955 emit_insn (gen_rtx_SET (reg, gen_rtx_HIGH (Pmode, offset)));
956 emit_insn (gen_rtx_SET (reg,
957 gen_rtx_LO_SUM (Pmode, reg,
958 copy_rtx (offset))));
959 pic_ref = gen_rtx_PLUS (Pmode,
960 pic_offset_table_rtx, reg);
961 #endif
963 else
964 #endif /* HAVE_lo_sum */
966 if (REG_P (orig)
967 || GET_CODE (orig) == SUBREG)
969 return orig;
971 else
973 rtx pic = pic_offset_table_rtx;
974 if (GET_CODE (pic) != REG)
976 emit_move_insn (reg, pic);
977 pic = reg;
979 #if 0
980 emit_use (pic_offset_table_rtx);
981 #endif
982 if (lra_in_progress)
983 df_set_regs_ever_live (REGNO (pic), true);
984 pic_ref = gen_rtx_PLUS (Pmode,
985 pic,
986 machopic_gen_offset (orig));
991 if (GET_CODE (pic_ref) != REG)
993 if (reg != 0)
995 emit_move_insn (reg, pic_ref);
996 return reg;
998 else
1000 return force_reg (mode, pic_ref);
1003 else
1005 return pic_ref;
1008 else if (GET_CODE (orig) == PLUS
1009 && (GET_CODE (XEXP (orig, 0)) == MEM
1010 || GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
1011 || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
1012 && XEXP (orig, 0) != pic_offset_table_rtx
1013 && GET_CODE (XEXP (orig, 1)) != REG)
1016 rtx base;
1017 int is_complex = (GET_CODE (XEXP (orig, 0)) == MEM);
1019 base = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
1020 orig = machopic_legitimize_pic_address (XEXP (orig, 1),
1021 Pmode, (base == reg ? 0 : reg));
1022 if (GET_CODE (orig) == CONST_INT)
1024 pic_ref = plus_constant (Pmode, base, INTVAL (orig));
1025 is_complex = 1;
1027 else
1028 pic_ref = gen_rtx_PLUS (Pmode, base, orig);
1030 if (reg && is_complex)
1032 emit_move_insn (reg, pic_ref);
1033 pic_ref = reg;
1035 /* Likewise, should we set special REG_NOTEs here? */
1037 else if (GET_CODE (orig) == CONST)
1039 return machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
1041 else if (GET_CODE (orig) == MEM
1042 && GET_CODE (XEXP (orig, 0)) == SYMBOL_REF)
1044 rtx addr = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
1045 addr = replace_equiv_address (orig, addr);
1046 emit_move_insn (reg, addr);
1047 pic_ref = reg;
1050 return pic_ref;
1053 /* Callbacks to output the stub or non-lazy pointers.
1054 Each works on the item in *SLOT,if it has been used.
1055 DATA is the FILE* for assembly output.
1056 Called from htab_traverses, invoked from machopic_finish(). */
1059 machopic_output_data_section_indirection (machopic_indirection **slot,
1060 FILE *asm_out_file)
1062 machopic_indirection *p = *slot;
1064 if (!p->used || !p->nlsp_in_data_section)
1065 return 1;
1067 rtx symbol = p->symbol;
1068 /* The original symbol name. */
1069 const char *sym_name = XSTR (symbol, 0);
1070 /* The name of the indirection symbol. */
1071 const char *ptr_name = p->ptr_name;
1073 switch_to_section (data_section);
1074 assemble_align (GET_MODE_ALIGNMENT (Pmode));
1075 assemble_label (asm_out_file, ptr_name);
1076 assemble_integer (gen_rtx_SYMBOL_REF (Pmode, sym_name),
1077 GET_MODE_SIZE (Pmode),
1078 GET_MODE_ALIGNMENT (Pmode), 1);
1080 return 1;
1084 machopic_output_stub_indirection (machopic_indirection **slot,
1085 FILE *asm_out_file)
1087 machopic_indirection *p = *slot;
1089 if (!p->used || !p->stub_p)
1090 return 1;
1092 rtx symbol = p->symbol;
1093 /* The original symbol name. */
1094 const char *sym_name = XSTR (symbol, 0);
1095 /* The name of the stub symbol. */
1096 const char *ptr_name = p->ptr_name;
1098 tree id = maybe_get_identifier (sym_name);
1099 if (id)
1101 tree id_orig = id;
1103 while (IDENTIFIER_TRANSPARENT_ALIAS (id))
1104 id = TREE_CHAIN (id);
1105 if (id != id_orig)
1106 sym_name = IDENTIFIER_POINTER (id);
1109 char *sym = XALLOCAVEC (char, strlen (sym_name) + 2);
1110 if (sym_name[0] == '*' || sym_name[0] == '&')
1111 strcpy (sym, sym_name + 1);
1112 else if (sym_name[0] == '-' || sym_name[0] == '+')
1113 strcpy (sym, sym_name);
1114 else
1115 sprintf (sym, "%s%s", user_label_prefix, sym_name);
1117 char *stub = XALLOCAVEC (char, strlen (ptr_name) + 2);
1118 if (ptr_name[0] == '*' || ptr_name[0] == '&')
1119 strcpy (stub, ptr_name + 1);
1120 else
1121 sprintf (stub, "%s%s", user_label_prefix, ptr_name);
1123 machopic_output_stub (asm_out_file, sym, stub);
1125 return 1;
1129 machopic_output_indirection (machopic_indirection **slot, FILE *asm_out_file)
1131 machopic_indirection *p = *slot;
1133 if (!p->used || p->stub_p || p->nlsp_in_data_section)
1134 return 1;
1136 rtx symbol = p->symbol;
1137 /* The original symbol name. */
1138 const char *sym_name = XSTR (symbol, 0);
1139 /* The nonlazy-stub symbol name. */
1140 const char *ptr_name = p->ptr_name;
1142 switch_to_section (darwin_sections[machopic_nl_symbol_ptr_section]);
1144 /* Mach-O symbols are passed around in code through indirect references and
1145 the original symbol_ref hasn't passed through the generic handling and
1146 reference-catching in output_operand, so we need to manually mark weak
1147 references as such. */
1149 if (SYMBOL_REF_WEAK (symbol))
1151 tree decl = SYMBOL_REF_DECL (symbol);
1152 gcc_checking_assert (DECL_P (decl));
1154 if (decl != NULL_TREE
1155 && DECL_EXTERNAL (decl) && TREE_PUBLIC (decl)
1156 /* Handle only actual external-only definitions, not
1157 e.g. extern inline code or variables for which
1158 storage has been allocated. */
1159 && !TREE_STATIC (decl))
1161 fputs ("\t.weak_reference ", asm_out_file);
1162 assemble_name (asm_out_file, sym_name);
1163 fputc ('\n', asm_out_file);
1167 assemble_name (asm_out_file, ptr_name);
1168 fprintf (asm_out_file, ":\n");
1170 fprintf (asm_out_file, "\t.indirect_symbol ");
1171 assemble_name (asm_out_file, sym_name);
1172 fprintf (asm_out_file, "\n");
1174 /* Variables that are marked with MACHO_SYMBOL_FLAG_STATIC need to
1175 have their symbol name instead of 0 in the second entry of
1176 the non-lazy symbol pointer data structure when they are
1177 defined. This allows the runtime to rebind newer instances
1178 of the translation unit with the original instance of the
1179 symbol. */
1181 rtx init = const0_rtx;
1182 if (MACHO_SYMBOL_STATIC_P (symbol) && machopic_symbol_defined_p (symbol))
1183 init = gen_rtx_SYMBOL_REF (Pmode, sym_name);
1185 assemble_integer (init, GET_MODE_SIZE (Pmode),
1186 GET_MODE_ALIGNMENT (Pmode), 1);
1188 return 1;
1191 static void
1192 machopic_finish (FILE *asm_out_file)
1194 if (!machopic_indirections)
1195 return;
1197 /* First output an symbol indirections that have been placed into .data
1198 (we don't expect these now). */
1199 machopic_indirections->traverse_noresize
1200 <FILE *, machopic_output_data_section_indirection> (asm_out_file);
1202 machopic_indirections->traverse_noresize
1203 <FILE *, machopic_output_stub_indirection> (asm_out_file);
1205 machopic_indirections->traverse_noresize
1206 <FILE *, machopic_output_indirection> (asm_out_file);
1210 machopic_operand_p (rtx op)
1212 if (MACHOPIC_JUST_INDIRECT)
1213 return (GET_CODE (op) == SYMBOL_REF
1214 && machopic_symbol_defined_p (op));
1215 else
1216 return (GET_CODE (op) == CONST
1217 && GET_CODE (XEXP (op, 0)) == UNSPEC
1218 && XINT (XEXP (op, 0), 1) == UNSPEC_MACHOPIC_OFFSET);
1221 /* This function:
1222 computes and caches a series of flags that characterise the symbol's
1223 properties that affect Mach-O code gen (including accidental cases
1224 from older toolchains).
1226 TODO:
1227 Here we also need to do enough analysis to determine if a symbol's
1228 name needs to be made linker-visible. This is more tricky - since
1229 it depends on whether we've previously seen a global weak definition
1230 in the same section.
1233 void
1234 darwin_encode_section_info (tree decl, rtx rtl, int first)
1236 /* Careful not to prod global register variables. */
1237 if (!MEM_P (rtl))
1238 return;
1240 /* Do the standard encoding things first; this sets:
1241 SYMBOL_FLAG_FUNCTION,
1242 SYMBOL_FLAG_LOCAL, (binds_local_p)
1243 TLS_MODEL, SYMBOL_FLAG_SMALL
1244 SYMBOL_FLAG_EXTERNAL. */
1245 default_encode_section_info (decl, rtl, first);
1247 if (! VAR_OR_FUNCTION_DECL_P (decl))
1248 return;
1250 rtx sym_ref = XEXP (rtl, 0);
1251 if (VAR_P (decl))
1252 SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_VARIABLE;
1254 /* Only really common if there's no initialiser. */
1255 bool really_common_p = (DECL_COMMON (decl)
1256 && (DECL_INITIAL (decl) == NULL
1257 || (!in_lto_p
1258 && DECL_INITIAL (decl) == error_mark_node)));
1260 /* For Darwin, if we have specified visibility and it's not the default
1261 that's counted 'hidden'. */
1262 if (DECL_VISIBILITY_SPECIFIED (decl)
1263 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT)
1264 SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_HIDDEN_VIS;
1266 if (!DECL_EXTERNAL (decl)
1267 && (!TREE_PUBLIC (decl) || !DECL_WEAK (decl))
1268 && ! lookup_attribute ("weakref", DECL_ATTRIBUTES (decl))
1269 && ((TREE_STATIC (decl)
1270 && (!DECL_COMMON (decl) || !TREE_PUBLIC (decl)))
1271 || (!DECL_COMMON (decl) && DECL_INITIAL (decl)
1272 && DECL_INITIAL (decl) != error_mark_node)))
1273 SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
1275 if (! TREE_PUBLIC (decl))
1276 SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_STATIC;
1278 /* Short cut check for Darwin 'must indirect' rules. */
1279 if (really_common_p
1280 || (DECL_WEAK (decl) && ! MACHO_SYMBOL_HIDDEN_VIS_P (sym_ref))
1281 || lookup_attribute ("weakref", DECL_ATTRIBUTES (decl)))
1282 SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_MUST_INDIRECT;
1284 #if DARWIN_PPC
1285 /* Objective C V2 (m64) IVAR offset refs from Apple GCC-4.x have an
1286 indirection for m64 code on PPC. Historically, these indirections
1287 also appear in the .data section. */
1288 tree o2meta = lookup_attribute ("OBJC2META", DECL_ATTRIBUTES (decl));
1289 o2meta = o2meta ? TREE_VALUE (o2meta) : NULL_TREE;
1291 if (o2meta && strncmp (IDENTIFIER_POINTER (o2meta), "V2_IVRF",7) == 0)
1292 SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_MUST_INDIRECT;
1293 #endif
1296 void
1297 darwin_mark_decl_preserved (const char *name)
1299 /* Actually we shouldn't mark any local symbol this way, but for now
1300 this only happens with ObjC meta-data. */
1301 if (darwin_label_is_anonymous_local_objc_name (name))
1302 return;
1304 fprintf (asm_out_file, "\t.no_dead_strip ");
1305 assemble_name (asm_out_file, name);
1306 fputc ('\n', asm_out_file);
1309 static section *
1310 darwin_rodata_section (int use_coal, bool zsize, int reloc)
1312 return (use_coal
1313 ? darwin_sections[const_coal_section]
1314 : (zsize ? darwin_sections[zobj_const_section]
1315 : reloc ? darwin_sections[const_data_section]
1316 : darwin_sections[const_section]));
1319 static section *
1320 darwin_mergeable_string_section (tree exp,
1321 unsigned HOST_WIDE_INT align)
1323 /* Darwin's ld expects to see non-writable string literals in the .cstring
1324 section. Later versions of ld check and complain when CFStrings are
1325 enabled. Therefore we shall force the strings into .cstring since we
1326 don't support writable ones anyway. */
1327 if ((darwin_constant_cfstrings || flag_merge_constants)
1328 && TREE_CODE (exp) == STRING_CST
1329 && TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
1330 && align <= 256
1331 && (int_size_in_bytes (TREE_TYPE (exp))
1332 == TREE_STRING_LENGTH (exp))
1333 && ((size_t) TREE_STRING_LENGTH (exp)
1334 == strlen (TREE_STRING_POINTER (exp)) + 1))
1335 return darwin_sections[cstring_section];
1337 if (DARWIN_SECTION_ANCHORS && flag_section_anchors
1338 && TREE_CODE (exp) == STRING_CST
1339 && TREE_STRING_LENGTH (exp) == 0)
1340 return darwin_sections[zobj_const_section];
1342 return readonly_data_section;
1345 #ifndef HAVE_GAS_LITERAL16
1346 #define HAVE_GAS_LITERAL16 0
1347 #endif
1349 static section *
1350 darwin_mergeable_constant_section (tree exp,
1351 unsigned HOST_WIDE_INT align,
1352 bool zsize)
1354 machine_mode mode = DECL_MODE (exp);
1355 unsigned int modesize = GET_MODE_BITSIZE (mode);
1357 if (DARWIN_SECTION_ANCHORS
1358 && flag_section_anchors
1359 && zsize)
1360 return darwin_sections[zobj_const_section];
1362 if (flag_merge_constants
1363 && mode != VOIDmode
1364 && mode != BLKmode
1365 && modesize <= align
1366 && align >= 8
1367 && align <= 256
1368 && (align & (align -1)) == 0)
1370 tree size = TYPE_SIZE_UNIT (TREE_TYPE (exp));
1372 if (TREE_CODE (size) == INTEGER_CST)
1374 if (wi::to_wide (size) == 4)
1375 return darwin_sections[literal4_section];
1376 else if (wi::to_wide (size) == 8)
1377 return darwin_sections[literal8_section];
1378 else if (HAVE_GAS_LITERAL16
1379 && TARGET_64BIT
1380 && wi::to_wide (size) == 16)
1381 return darwin_sections[literal16_section];
1385 return readonly_data_section;
1388 section *
1389 darwin_tm_clone_table_section (void)
1391 return get_named_section (NULL,
1392 "__DATA,__tm_clone_table,regular,no_dead_strip",
1397 machopic_reloc_rw_mask (void)
1399 return MACHOPIC_INDIRECT ? 3 : 0;
1402 /* We have to deal with ObjC/C++ metadata section placement in the common
1403 code, since it will also be called from LTO.
1405 Return metadata attributes, if present (searching for ABI=2 first)
1406 Return NULL_TREE if no such attributes are found. */
1408 static tree
1409 is_objc_metadata (tree decl)
1411 if (DECL_P (decl)
1412 && (TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == CONST_DECL)
1413 && DECL_ATTRIBUTES (decl))
1415 tree meta = lookup_attribute ("OBJC2META", DECL_ATTRIBUTES (decl));
1416 if (meta)
1417 return meta;
1418 meta = lookup_attribute ("OBJC1META", DECL_ATTRIBUTES (decl));
1419 if (meta)
1420 return meta;
1422 return NULL_TREE;
1425 static int classes_seen;
1426 static int objc_metadata_seen;
1428 /* Return the section required for Objective C ABI 2 metadata. */
1429 static section *
1430 darwin_objc2_section (tree decl ATTRIBUTE_UNUSED, tree meta, section * base)
1432 const char *p;
1433 tree ident = TREE_VALUE (meta);
1434 gcc_assert (TREE_CODE (ident) == IDENTIFIER_NODE);
1435 p = IDENTIFIER_POINTER (ident);
1437 gcc_checking_assert (flag_next_runtime == 1 && flag_objc_abi == 2);
1439 objc_metadata_seen = 1;
1441 if (base == data_section)
1442 base = darwin_sections[objc2_metadata_section];
1444 /* Most of the OBJC2 META-data end up in the base section, so check it
1445 first. */
1446 if (!strncmp (p, "V2_BASE", 7))
1447 return base;
1448 else if (!strncmp (p, "V2_STRG", 7))
1449 return darwin_sections[cstring_section];
1451 else if (!strncmp (p, "G2_META", 7) || !strncmp (p, "G2_CLAS", 7))
1452 return darwin_sections[objc2_classdefs_section];
1453 else if (!strncmp (p, "V2_MREF", 7))
1454 return darwin_sections[objc2_message_refs_section];
1455 else if (!strncmp (p, "V2_CLRF", 7))
1456 return darwin_sections[objc2_classrefs_section];
1457 else if (!strncmp (p, "V2_SURF", 7))
1458 return darwin_sections[objc2_super_classrefs_section];
1459 else if (!strncmp (p, "V2_NLCL", 7))
1460 return darwin_sections[objc2_nonlazy_class_section];
1461 else if (!strncmp (p, "V2_CLAB", 7))
1463 classes_seen = 1;
1464 return darwin_sections[objc2_classlist_section];
1466 else if (!strncmp (p, "V2_SRFS", 7))
1467 return darwin_sections[objc2_selector_refs_section];
1468 else if (!strncmp (p, "V2_NLCA", 7))
1469 return darwin_sections[objc2_nonlazy_category_section];
1470 else if (!strncmp (p, "V2_CALA", 7))
1471 return darwin_sections[objc2_categorylist_section];
1473 else if (!strncmp (p, "V2_PLST", 7))
1474 return darwin_sections[objc2_protocollist_section];
1475 else if (!strncmp (p, "V2_PRFS", 7))
1476 return darwin_sections[objc2_protocolrefs_section];
1478 else if (!strncmp (p, "V2_INFO", 7))
1479 return darwin_sections[objc2_image_info_section];
1481 else if (!strncmp (p, "V2_EHTY", 7))
1482 return ld_uses_coal_sects ? darwin_sections[data_coal_section]
1483 : data_section;
1485 else if (!strncmp (p, "V2_CSTR", 7))
1486 return darwin_sections[objc2_constant_string_object_section];
1488 /* Not recognized, default. */
1489 return base;
1492 /* Return the section required for Objective C ABI 0/1 metadata. */
1493 static section *
1494 darwin_objc1_section (tree decl ATTRIBUTE_UNUSED, tree meta, section * base)
1496 const char *p;
1497 tree ident = TREE_VALUE (meta);
1498 gcc_assert (TREE_CODE (ident) == IDENTIFIER_NODE);
1499 p = IDENTIFIER_POINTER (ident);
1501 gcc_checking_assert (flag_next_runtime == 1 && flag_objc_abi < 2);
1503 objc_metadata_seen = 1;
1505 /* String sections first, cos there are lots of strings. */
1506 if (!strncmp (p, "V1_STRG", 7))
1507 return darwin_sections[cstring_section];
1508 else if (!strncmp (p, "V1_CLSN", 7))
1509 return darwin_sections[objc_class_names_section];
1510 else if (!strncmp (p, "V1_METN", 7))
1511 return darwin_sections[objc_meth_var_names_section];
1512 else if (!strncmp (p, "V1_METT", 7))
1513 return darwin_sections[objc_meth_var_types_section];
1515 else if (!strncmp (p, "V1_CLAS", 7))
1517 classes_seen = 1;
1518 return darwin_sections[objc_class_section];
1520 else if (!strncmp (p, "V1_META", 7))
1521 return darwin_sections[objc_meta_class_section];
1522 else if (!strncmp (p, "V1_CATG", 7))
1523 return darwin_sections[objc_category_section];
1524 else if (!strncmp (p, "V1_PROT", 7))
1525 return darwin_sections[objc_protocol_section];
1527 else if (!strncmp (p, "V1_CLCV", 7))
1528 return darwin_sections[objc_class_vars_section];
1529 else if (!strncmp (p, "V1_CLIV", 7))
1530 return darwin_sections[objc_instance_vars_section];
1532 else if (!strncmp (p, "V1_CLCM", 7))
1533 return darwin_sections[objc_cls_meth_section];
1534 else if (!strncmp (p, "V1_CLIM", 7))
1535 return darwin_sections[objc_inst_meth_section];
1536 else if (!strncmp (p, "V1_CACM", 7))
1537 return darwin_sections[objc_cat_cls_meth_section];
1538 else if (!strncmp (p, "V1_CAIM", 7))
1539 return darwin_sections[objc_cat_inst_meth_section];
1540 else if (!strncmp (p, "V1_PNSM", 7))
1541 return darwin_sections[objc_cat_inst_meth_section];
1542 else if (!strncmp (p, "V1_PCLM", 7))
1543 return darwin_sections[objc_cat_cls_meth_section];
1545 else if (!strncmp (p, "V1_CLPR", 7))
1546 return darwin_sections[objc_cat_cls_meth_section];
1547 else if (!strncmp (p, "V1_CAPR", 7))
1548 return darwin_sections[objc_category_section]; /* ??? CHECK me. */
1550 else if (!strncmp (p, "V1_PRFS", 7))
1551 return darwin_sections[objc_cat_cls_meth_section];
1552 else if (!strncmp (p, "V1_CLRF", 7))
1553 return darwin_sections[objc_cls_refs_section];
1554 else if (!strncmp (p, "V1_SRFS", 7))
1555 return darwin_sections[objc_selector_refs_section];
1557 else if (!strncmp (p, "V1_MODU", 7))
1558 return darwin_sections[objc_module_info_section];
1559 else if (!strncmp (p, "V1_SYMT", 7))
1560 return darwin_sections[objc_symbols_section];
1561 else if (!strncmp (p, "V1_INFO", 7))
1562 return darwin_sections[objc_image_info_section];
1564 else if (!strncmp (p, "V1_PLST", 7))
1565 return darwin_sections[objc1_prop_list_section];
1566 else if (!strncmp (p, "V1_PEXT", 7))
1567 return darwin_sections[objc1_protocol_ext_section];
1568 else if (!strncmp (p, "V1_CEXT", 7))
1569 return darwin_sections[objc1_class_ext_section];
1571 else if (!strncmp (p, "V2_CSTR", 7))
1572 return darwin_sections[objc_constant_string_object_section];
1574 return base;
1577 section *
1578 machopic_select_section (tree decl,
1579 int reloc,
1580 unsigned HOST_WIDE_INT align)
1582 bool zsize, one, weak, use_coal, ro;
1583 section *base_section = NULL;
1585 weak = (DECL_P (decl)
1586 && DECL_WEAK (decl)
1587 && !lookup_attribute ("weak_import", DECL_ATTRIBUTES (decl)));
1589 zsize = (DECL_P (decl)
1590 && (TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == CONST_DECL)
1591 && tree_to_uhwi (DECL_SIZE_UNIT (decl)) == 0);
1593 one = DECL_P (decl)
1594 && TREE_CODE (decl) == VAR_DECL
1595 && DECL_COMDAT_GROUP (decl);
1597 use_coal = (weak || one) && ld_uses_coal_sects;
1599 ro = TREE_READONLY (decl) || TREE_CONSTANT (decl) ;
1601 switch (categorize_decl_for_section (decl, reloc))
1603 case SECCAT_TEXT:
1604 gcc_unreachable ();
1605 break;
1607 case SECCAT_RODATA:
1608 case SECCAT_SRODATA:
1609 base_section = darwin_rodata_section (use_coal, zsize, reloc);
1610 break;
1612 case SECCAT_RODATA_MERGE_STR:
1613 base_section = darwin_mergeable_string_section (decl, align);
1614 break;
1616 case SECCAT_RODATA_MERGE_STR_INIT:
1617 base_section = darwin_mergeable_string_section (DECL_INITIAL (decl), align);
1618 break;
1620 case SECCAT_RODATA_MERGE_CONST:
1621 base_section = darwin_mergeable_constant_section (decl, align, zsize);
1622 break;
1624 case SECCAT_DATA:
1625 case SECCAT_DATA_REL:
1626 case SECCAT_DATA_REL_LOCAL:
1627 case SECCAT_DATA_REL_RO:
1628 case SECCAT_DATA_REL_RO_LOCAL:
1629 case SECCAT_SDATA:
1630 case SECCAT_TDATA:
1631 if (use_coal)
1633 if (ro)
1634 base_section = darwin_sections[const_data_coal_section];
1635 else
1636 base_section = darwin_sections[data_coal_section];
1638 else if (DARWIN_SECTION_ANCHORS
1639 && flag_section_anchors
1640 && zsize)
1642 /* If we're doing section anchors, then punt zero-sized objects into
1643 their own sections so that they don't interfere with offset
1644 computation for the remaining vars. This does not need to be done
1645 for stuff in mergeable sections, since these are ineligible for
1646 anchors. */
1647 if (ro)
1648 base_section = darwin_sections[zobj_const_data_section];
1649 else
1650 base_section = darwin_sections[zobj_data_section];
1652 else if (ro)
1653 base_section = darwin_sections[const_data_section];
1654 else
1655 base_section = data_section;
1656 break;
1657 case SECCAT_BSS:
1658 case SECCAT_SBSS:
1659 case SECCAT_TBSS:
1660 if (use_coal)
1661 base_section = darwin_sections[data_coal_section];
1662 else
1664 if (!TREE_PUBLIC (decl))
1665 base_section = lcomm_section;
1666 else if (bss_noswitch_section)
1667 base_section = bss_noswitch_section;
1668 else
1669 base_section = data_section;
1671 break;
1673 default:
1674 gcc_unreachable ();
1677 /* Darwin weird special cases.
1678 a) OBJC Meta-data. */
1679 if (DECL_P (decl)
1680 && (TREE_CODE (decl) == VAR_DECL
1681 || TREE_CODE (decl) == CONST_DECL)
1682 && DECL_ATTRIBUTES (decl))
1684 tree meta = lookup_attribute ("OBJC2META", DECL_ATTRIBUTES (decl));
1685 if (meta)
1686 return darwin_objc2_section (decl, meta, base_section);
1687 meta = lookup_attribute ("OBJC1META", DECL_ATTRIBUTES (decl));
1688 if (meta)
1689 return darwin_objc1_section (decl, meta, base_section);
1690 meta = lookup_attribute ("OBJC1METG", DECL_ATTRIBUTES (decl));
1691 if (meta)
1692 return base_section; /* GNU runtime is happy with it all in one pot. */
1695 /* b) Constant string objects. */
1696 if (TREE_CODE (decl) == CONSTRUCTOR
1697 && TREE_TYPE (decl)
1698 && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
1699 && TYPE_NAME (TREE_TYPE (decl)))
1701 tree name = TYPE_NAME (TREE_TYPE (decl));
1702 if (TREE_CODE (name) == TYPE_DECL)
1703 name = DECL_NAME (name);
1705 if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_ObjCString"))
1707 if (flag_next_runtime)
1709 if (flag_objc_abi == 2)
1710 return darwin_sections[objc2_constant_string_object_section];
1711 else
1712 return darwin_sections[objc_constant_string_object_section];
1714 else
1715 return darwin_sections[objc_string_object_section];
1717 else if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_CFString"))
1718 return darwin_sections[cfstring_constant_object_section];
1719 else
1720 return base_section;
1722 else if (flag_next_runtime
1723 && VAR_P (decl)
1724 && DECL_NAME (decl)
1725 && TREE_CODE (DECL_NAME (decl)) == IDENTIFIER_NODE
1726 && IDENTIFIER_POINTER (DECL_NAME (decl))
1727 && !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)), "_OBJC_", 6))
1728 /* c) legacy meta-data selection was deprecated at 4.6, removed now. */
1729 gcc_unreachable ();
1731 return base_section;
1734 /* This can be called with address expressions as "rtx".
1735 They must go in "const". */
1737 section *
1738 machopic_select_rtx_section (machine_mode mode, rtx x,
1739 unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
1741 if (GET_MODE_SIZE (mode) == 8
1742 && (GET_CODE (x) == CONST_INT
1743 || GET_CODE (x) == CONST_WIDE_INT
1744 || GET_CODE (x) == CONST_DOUBLE))
1745 return darwin_sections[literal8_section];
1746 else if (GET_MODE_SIZE (mode) == 4
1747 && (GET_CODE (x) == CONST_INT
1748 || GET_CODE (x) == CONST_WIDE_INT
1749 || GET_CODE (x) == CONST_DOUBLE))
1750 return darwin_sections[literal4_section];
1751 else if (HAVE_GAS_LITERAL16
1752 && TARGET_64BIT
1753 && GET_MODE_SIZE (mode) == 16
1754 && (GET_CODE (x) == CONST_INT
1755 || GET_CODE (x) == CONST_WIDE_INT
1756 || GET_CODE (x) == CONST_DOUBLE
1757 || GET_CODE (x) == CONST_VECTOR))
1758 return darwin_sections[literal16_section];
1759 else if (MACHOPIC_INDIRECT
1760 && (GET_CODE (x) == SYMBOL_REF
1761 || GET_CODE (x) == CONST
1762 || GET_CODE (x) == LABEL_REF))
1763 return darwin_sections[const_data_section];
1764 else
1765 return darwin_sections[const_section];
1768 void
1769 machopic_asm_out_constructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1771 cdtor_record new_elt = {symbol, priority, vec_safe_length (ctors)};
1773 vec_safe_push (ctors, new_elt);
1775 if (! MACHOPIC_INDIRECT)
1776 fprintf (asm_out_file, ".reference .constructors_used\n");
1779 void
1780 machopic_asm_out_destructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1782 cdtor_record new_elt = {symbol, priority, vec_safe_length (dtors)};
1784 vec_safe_push (dtors, new_elt);
1786 if (! MACHOPIC_INDIRECT)
1787 fprintf (asm_out_file, ".reference .destructors_used\n");
1790 static int
1791 sort_cdtor_records (const void * a, const void * b)
1793 const cdtor_record *cda = (const cdtor_record *)a;
1794 const cdtor_record *cdb = (const cdtor_record *)b;
1795 if (cda->priority > cdb->priority)
1796 return 1;
1797 if (cda->priority < cdb->priority)
1798 return -1;
1799 if (cda->position > cdb->position)
1800 return 1;
1801 if (cda->position < cdb->position)
1802 return -1;
1803 return 0;
1806 static void
1807 finalize_ctors ()
1809 unsigned int i;
1810 cdtor_record *elt;
1812 if (MACHOPIC_INDIRECT)
1813 switch_to_section (darwin_sections[mod_init_section]);
1814 else
1815 switch_to_section (darwin_sections[constructor_section]);
1817 if (vec_safe_length (ctors) > 1)
1818 ctors->qsort (sort_cdtor_records);
1819 FOR_EACH_VEC_SAFE_ELT (ctors, i, elt)
1821 assemble_align (POINTER_SIZE);
1822 assemble_integer (elt->symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1826 static void
1827 finalize_dtors ()
1829 unsigned int i;
1830 cdtor_record *elt;
1832 if (MACHOPIC_INDIRECT)
1833 switch_to_section (darwin_sections[mod_term_section]);
1834 else
1835 switch_to_section (darwin_sections[destructor_section]);
1837 if (vec_safe_length (dtors) > 1)
1838 dtors->qsort (sort_cdtor_records);
1839 FOR_EACH_VEC_SAFE_ELT (dtors, i, elt)
1841 assemble_align (POINTER_SIZE);
1842 assemble_integer (elt->symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1846 void
1847 darwin_globalize_label (FILE *stream, const char *name)
1849 if (!!strncmp (name, "_OBJC_", 6))
1850 default_globalize_label (stream, name);
1853 /* This routine returns non-zero if 'name' starts with the special objective-c
1854 anonymous file-scope static name. It accommodates c++'s mangling of such
1855 symbols (in this case the symbols will have form _ZL{d}*_OBJC_* d=digit). */
1858 darwin_label_is_anonymous_local_objc_name (const char *name)
1860 const unsigned char *p = (const unsigned char *) name;
1861 if (*p != '_')
1862 return 0;
1863 if (p[1] == 'Z' && p[2] == 'L')
1865 p += 3;
1866 while (*p >= '0' && *p <= '9')
1867 p++;
1869 return (!strncmp ((const char *)p, "_OBJC_", 6));
1872 /* LTO support for Mach-O.
1874 This version uses three mach-o sections to encapsulate the (unlimited
1875 number of) lto sections.
1877 __GNU_LTO, __lto_sections contains the concatented GNU LTO section data.
1878 __GNU_LTO, __section_names contains the GNU LTO section names.
1879 __GNU_LTO, __section_index contains an array of values that index these.
1881 Indexed thus:
1882 <section offset from the start of __GNU_LTO, __lto_sections>,
1883 <section length>
1884 <name offset from the start of __GNU_LTO, __section_names,
1885 <name length>.
1887 At present, for both m32 and m64 mach-o files each of these fields is
1888 represented by a uint32_t. This is because, AFAICT, a mach-o object
1889 cannot exceed 4Gb because the section_64 offset field (see below) is 32bits.
1891 uint32_t offset;
1892 "offset An integer specifying the offset to this section in the file." */
1894 /* Count lto section numbers. */
1895 static unsigned int lto_section_num = 0;
1897 /* A vector of information about LTO sections, at present, we only have
1898 the name. TODO: see if we can get the data length somehow. */
1899 typedef struct GTY (()) darwin_lto_section_e {
1900 const char *sectname;
1901 } darwin_lto_section_e ;
1903 static GTY (()) vec<darwin_lto_section_e, va_gc> *lto_section_names;
1905 /* Section wrapper scheme (used here to wrap the unlimited number of LTO
1906 sections into three Mach-O ones).
1907 NOTE: These names MUST be kept in sync with those in
1908 libiberty/simple-object-mach-o. */
1909 #define LTO_SECTS_SECTION "__wrapper_sects"
1910 #define LTO_NAMES_SECTION "__wrapper_names"
1911 #define LTO_INDEX_SECTION "__wrapper_index"
1913 /* File to temporarily store LTO data. This is appended to asm_out_file
1914 in darwin_end_file. */
1915 static FILE *lto_asm_out_file, *saved_asm_out_file;
1916 static char *lto_asm_out_name;
1917 static enum debug_info_levels saved_debug_info_level;
1919 /* Prepare asm_out_file for LTO output. For darwin, this means hiding
1920 asm_out_file and switching to an alternative output file. */
1921 void
1922 darwin_asm_lto_start (void)
1924 gcc_assert (! saved_asm_out_file);
1925 saved_asm_out_file = asm_out_file;
1926 saved_debug_info_level = debug_info_level;
1927 debug_info_level = DINFO_LEVEL_NONE;
1928 if (! lto_asm_out_name)
1929 lto_asm_out_name = make_temp_file (".lto.s");
1930 lto_asm_out_file = fopen (lto_asm_out_name, "a");
1931 if (lto_asm_out_file == NULL)
1932 fatal_error (input_location,
1933 "failed to open temporary file %s for LTO output",
1934 lto_asm_out_name);
1935 asm_out_file = lto_asm_out_file;
1938 /* Restore asm_out_file. */
1939 void
1940 darwin_asm_lto_end (void)
1942 gcc_assert (saved_asm_out_file);
1943 fclose (lto_asm_out_file);
1944 asm_out_file = saved_asm_out_file;
1945 saved_asm_out_file = NULL;
1946 debug_info_level = saved_debug_info_level;
1949 static void
1950 darwin_asm_dwarf_section (const char *name, unsigned int flags,
1951 tree decl, bool is_for_lto);
1953 /* Called for the TARGET_ASM_NAMED_SECTION hook. */
1955 void
1956 darwin_asm_named_section (const char *name,
1957 unsigned int flags,
1958 tree decl ATTRIBUTE_UNUSED)
1960 /* LTO sections go in a special section that encapsulates the (unlimited)
1961 number of GNU LTO sections within a single mach-o one. */
1962 if (strncmp (name, LTO_SECTION_NAME_PREFIX,
1963 strlen (LTO_SECTION_NAME_PREFIX)) == 0)
1965 darwin_lto_section_e e;
1966 /* We expect certain flags to be set... */
1967 gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
1968 == (SECTION_DEBUG | SECTION_NAMED));
1970 /* Switch to our combined section. */
1971 fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
1972 LTO_SEGMENT_NAME, LTO_SECTS_SECTION);
1973 /* Output a label for the start of this sub-section. */
1974 fprintf (asm_out_file, "L_GNU_LTO%d:\t;# %s\n",
1975 lto_section_num, name);
1976 /* We have to jump through hoops to get the values of the intra-section
1977 offsets... */
1978 fprintf (asm_out_file, "\t.set L$gnu$lto$offs%d,L_GNU_LTO%d-L_GNU_LTO0\n",
1979 lto_section_num, lto_section_num);
1980 fprintf (asm_out_file,
1981 "\t.set L$gnu$lto$size%d,L_GNU_LTO%d-L_GNU_LTO%d\n",
1982 lto_section_num, lto_section_num+1, lto_section_num);
1983 lto_section_num++;
1984 e.sectname = xstrdup (name);
1985 /* Keep the names, we'll need to make a table later.
1986 TODO: check that we do not revisit sections, that would break
1987 the assumption of how this is done. */
1988 if (lto_section_names == NULL)
1989 vec_alloc (lto_section_names, 16);
1990 vec_safe_push (lto_section_names, e);
1992 else if (strncmp (name, "__DWARF,", 8) == 0)
1993 darwin_asm_dwarf_section (name, flags, decl, false);
1994 else if (strncmp (name, "__GNU_DWARF_LTO,", 16) == 0)
1995 darwin_asm_dwarf_section (name, flags, decl, true);
1996 else
1997 fprintf (asm_out_file, "\t.section %s\n", name);
2000 void
2001 darwin_unique_section (tree decl ATTRIBUTE_UNUSED, int reloc ATTRIBUTE_UNUSED)
2003 /* Darwin does not use unique sections. */
2006 /* Handle __attribute__ ((apple_kext_compatibility)).
2007 This only applies to darwin kexts for 2.95 compatibility -- it shrinks the
2008 vtable for classes with this attribute (and their descendants) by not
2009 outputting the new 3.0 nondeleting destructor. This means that such
2010 objects CANNOT be allocated on the stack or as globals UNLESS they have
2011 a completely empty `operator delete'.
2012 Luckily, this fits in with the Darwin kext model.
2014 This attribute also disables gcc3's potential overlaying of derived
2015 class data members on the padding at the end of the base class. */
2017 tree
2018 darwin_handle_kext_attribute (tree *node, tree name,
2019 tree args ATTRIBUTE_UNUSED,
2020 int flags ATTRIBUTE_UNUSED,
2021 bool *no_add_attrs)
2023 /* APPLE KEXT stuff -- only applies with pure static C++ code. */
2024 if (! TARGET_KEXTABI)
2026 warning (0, "%qE 2.95 vtable-compatibility attribute applies "
2027 "only when compiling a kext", name);
2029 *no_add_attrs = true;
2031 else if (TREE_CODE (*node) != RECORD_TYPE)
2033 warning (0, "%qE 2.95 vtable-compatibility attribute applies "
2034 "only to C++ classes", name);
2036 *no_add_attrs = true;
2039 return NULL_TREE;
2042 /* Handle a "weak_import" attribute; arguments as in
2043 struct attribute_spec.handler. */
2045 tree
2046 darwin_handle_weak_import_attribute (tree *node, tree name,
2047 tree ARG_UNUSED (args),
2048 int ARG_UNUSED (flags),
2049 bool * no_add_attrs)
2051 if (TREE_CODE (*node) != FUNCTION_DECL && TREE_CODE (*node) != VAR_DECL)
2053 warning (OPT_Wattributes, "%qE attribute ignored",
2054 name);
2055 *no_add_attrs = true;
2057 else
2058 declare_weak (*node);
2060 return NULL_TREE;
2063 /* Emit a label for an FDE, making it global and/or weak if appropriate.
2064 The third parameter is nonzero if this is for exception handling.
2065 The fourth parameter is nonzero if this is just a placeholder for an
2066 FDE that we are omitting. */
2068 void
2069 darwin_emit_unwind_label (FILE *file, tree decl, int for_eh, int empty)
2071 char *lab ;
2072 char buf[32];
2073 static int invok_count = 0;
2074 static tree last_fun_decl = NULL_TREE;
2076 /* Modern linkers can produce distinct FDEs without compiler support. */
2077 if (! for_eh || ! ld_needs_eh_markers)
2078 return;
2080 /* FIXME: This only works when the eh for all sections of a function are
2081 emitted at the same time. If that changes, we would need to use a lookup
2082 table of some form to determine what to do. Also, we should emit the
2083 unadorned label for the partition containing the public label for a
2084 function. This is of limited use, probably, since we do not currently
2085 enable partitioning. */
2086 strcpy (buf, ".eh");
2087 if (decl && TREE_CODE (decl) == FUNCTION_DECL)
2089 if (decl == last_fun_decl)
2091 invok_count++;
2092 snprintf (buf, 31, "$$part$$%d.eh", invok_count);
2094 else
2096 last_fun_decl = decl;
2097 invok_count = 0;
2101 lab = concat (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)), buf, NULL);
2103 if (TREE_PUBLIC (decl))
2105 targetm.asm_out.globalize_label (file, lab);
2106 if (DECL_VISIBILITY (decl) == VISIBILITY_HIDDEN)
2108 fputs ("\t.private_extern ", file);
2109 assemble_name (file, lab);
2110 fputc ('\n', file);
2114 if (DECL_WEAK (decl))
2116 fputs ("\t.weak_definition ", file);
2117 assemble_name (file, lab);
2118 fputc ('\n', file);
2121 assemble_name (file, lab);
2122 if (empty)
2124 fputs (" = 0\n", file);
2126 /* Mark the absolute .eh and .eh1 style labels as needed to
2127 ensure that we don't dead code strip them and keep such
2128 labels from another instantiation point until we can fix this
2129 properly with group comdat support. */
2130 darwin_mark_decl_preserved (lab);
2132 else
2133 fputs (":\n", file);
2135 free (lab);
2138 static GTY(()) unsigned long except_table_label_num;
2140 void
2141 darwin_emit_except_table_label (FILE *file)
2143 char section_start_label[30];
2145 ASM_GENERATE_INTERNAL_LABEL (section_start_label, "GCC_except_table",
2146 except_table_label_num++);
2147 ASM_OUTPUT_LABEL (file, section_start_label);
2150 /* Return, and mark as used, the name of the stub for the mcount function.
2151 Currently, this is only called by X86 code in the expansion of the
2152 FUNCTION_PROFILER macro, when stubs are enabled. */
2154 const char*
2155 machopic_mcount_stub_name (void)
2157 rtx symbol = gen_rtx_SYMBOL_REF (Pmode, "*mcount");
2158 const char *name = machopic_indirection_name (symbol, /*stub_p=*/true);
2159 machopic_validate_stub_or_non_lazy_ptr (name);
2160 return name;
2163 /* Generate a PC-relative reference to a Mach-O non-lazy-symbol. */
2165 void
2166 darwin_non_lazy_pcrel (FILE *file, rtx addr)
2168 const char *nlp_name;
2170 gcc_assert (GET_CODE (addr) == SYMBOL_REF);
2172 nlp_name = machopic_indirection_name (addr, /*stub_p=*/false);
2173 fputs ("\t.long\t", file);
2174 ASM_OUTPUT_LABELREF (file, nlp_name);
2175 fputs ("-.", file);
2178 /* If this is uncommented, details of each allocation will be printed
2179 in the asm right before the actual code. WARNING - this will cause some
2180 test-suite fails (since the printout will contain items that some tests
2181 are not expecting) -- so don't leave it on by default (it bloats the
2182 asm too). */
2183 /*#define DEBUG_DARWIN_MEM_ALLOCATORS*/
2185 /* The first two of these routines are ostensibly just intended to put
2186 names into the asm. However, they are both hijacked in order to ensure
2187 that zero-sized items do not make their way into the output. Consequently,
2188 we also need to make these participate in provisions for dealing with
2189 such items in section anchors. */
2191 /* The implementation of ASM_DECLARE_OBJECT_NAME. */
2192 /* The RTTI data (e.g., __ti4name) is common and public (and static),
2193 but it does need to be referenced via indirect PIC data pointers.
2194 The machopic_define_symbol calls are telling the machopic subsystem
2195 that the name *is* defined in this module, so it doesn't need to
2196 make them indirect. */
2197 void
2198 darwin_asm_declare_object_name (FILE *file,
2199 const char *nam, tree decl)
2201 const char *xname = nam;
2202 unsigned HOST_WIDE_INT size;
2203 bool local_def, weak;
2205 weak = (DECL_P (decl)
2206 && DECL_WEAK (decl)
2207 && !lookup_attribute ("weak_import",
2208 DECL_ATTRIBUTES (decl)));
2210 local_def = DECL_INITIAL (decl) || (TREE_STATIC (decl)
2211 && (!DECL_COMMON (decl)
2212 || !TREE_PUBLIC (decl)));
2214 if (GET_CODE (XEXP (DECL_RTL (decl), 0)) != SYMBOL_REF)
2215 xname = IDENTIFIER_POINTER (DECL_NAME (decl));
2217 if (local_def)
2219 (* targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2220 if (!weak)
2221 machopic_define_symbol (DECL_RTL (decl));
2224 size = tree_to_uhwi (DECL_SIZE_UNIT (decl));
2226 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2227 fprintf (file, "# dadon: %s %s (%llu, %u) local %d weak %d"
2228 " stat %d com %d pub %d t-const %d t-ro %d init %lx\n",
2229 xname, (TREE_CODE (decl) == VAR_DECL?"var":"const"),
2230 (unsigned long long)size, DECL_ALIGN (decl), local_def,
2231 DECL_WEAK (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2232 TREE_PUBLIC (decl), TREE_CONSTANT (decl), TREE_READONLY (decl),
2233 (unsigned long)DECL_INITIAL (decl));
2234 #endif
2236 /* Darwin needs help to support local zero-sized objects.
2237 They must be made at least one byte, and the section containing must be
2238 marked as unsuitable for section-anchors (see storage allocators below).
2240 For non-zero objects this output is handled by varasm.c.
2242 if (!size)
2244 unsigned int l2align = 0;
2246 /* The align must be honored, even for zero-sized. */
2247 if (DECL_ALIGN (decl))
2249 l2align = floor_log2 (DECL_ALIGN (decl) / BITS_PER_UNIT);
2250 fprintf (file, "\t.align\t%u\n", l2align);
2253 ASM_OUTPUT_LABEL (file, xname);
2254 size = 1;
2255 fprintf (file, "\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2257 /* Check that we've correctly picked up the zero-sized item and placed it
2258 properly. */
2259 gcc_assert ((!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
2260 || (in_section
2261 && (in_section->common.flags & SECTION_NO_ANCHOR)));
2263 else
2264 ASM_OUTPUT_LABEL (file, xname);
2267 /* The implementation of ASM_DECLARE_CONSTANT_NAME. */
2268 void
2269 darwin_asm_declare_constant_name (FILE *file, const char *name,
2270 const_tree exp ATTRIBUTE_UNUSED,
2271 HOST_WIDE_INT size)
2273 assemble_label (file, name);
2274 /* As for other items, we need at least one byte. */
2275 if (!size)
2277 fputs ("\t.space\t1\n", file);
2278 /* Check that we've correctly picked up the zero-sized item and placed it
2279 properly. */
2280 gcc_assert ((!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
2281 || (in_section
2282 && (in_section->common.flags & SECTION_NO_ANCHOR)));
2286 /* Darwin storage allocators.
2288 Zerofill sections are desirable for large blank data since, otherwise, these
2289 data bloat objects (PR33210).
2291 However, section anchors don't work in .zerofill sections (one cannot switch
2292 to a zerofill section). Ergo, for Darwin targets using section anchors we need
2293 to put (at least some) data into 'normal' switchable sections.
2295 Here we set a relatively arbitrary value for the size of an object to trigger
2296 zerofill when section anchors are enabled (anything bigger than a page for
2297 current Darwin implementations). FIXME: there ought to be some objective way
2298 to make this choice.
2300 When section anchor are off this is ignored anyway. */
2302 #define BYTES_ZFILL 4096
2304 /* Emit a chunk of data for items coalesced by the linker. */
2305 static void
2306 darwin_emit_weak_or_comdat (FILE *fp, tree decl, const char *name,
2307 unsigned HOST_WIDE_INT size,
2308 bool use_coal,
2309 unsigned int align)
2311 /* Since the sections used here are coalesced, they will not be eligible
2312 for section anchors, and therefore we don't need to break that out.
2313 CHECKME: for modern linker on PowerPC. */
2314 if (TREE_READONLY (decl) || TREE_CONSTANT (decl))
2315 switch_to_section (use_coal ? darwin_sections[const_data_coal_section]
2316 : darwin_sections[const_data_section]);
2317 else
2318 switch_to_section (use_coal ? darwin_sections[data_coal_section]
2319 : data_section);
2321 /* To be consistent, we'll allow darwin_asm_declare_object_name to assemble
2322 the align info for zero-sized items... but do it here otherwise. */
2323 if (size && align)
2324 fprintf (fp, "\t.align\t%d\n", floor_log2 (align / BITS_PER_UNIT));
2326 if (TREE_PUBLIC (decl))
2327 darwin_globalize_label (fp, name);
2329 /* ... and we let it deal with outputting one byte of zero for them too. */
2330 darwin_asm_declare_object_name (fp, name, decl);
2331 if (size)
2332 assemble_zeros (size);
2335 /* Emit a chunk of data for ObjC meta-data that got placed in BSS erroneously. */
2336 static void
2337 darwin_emit_objc_zeroed (FILE *fp, tree decl, const char *name,
2338 unsigned HOST_WIDE_INT size,
2339 unsigned int align, tree meta)
2341 section *ocs = data_section;
2343 if (TREE_PURPOSE (meta) == get_identifier("OBJC2META"))
2344 ocs = darwin_objc2_section (decl, meta, ocs);
2345 else
2346 ocs = darwin_objc1_section (decl, meta, ocs);
2348 switch_to_section (ocs);
2350 /* We shall declare that zero-sized meta-data are not valid (yet). */
2351 gcc_assert (size);
2352 fprintf (fp, "\t.align\t%d\n", floor_log2 (align / BITS_PER_UNIT));
2354 /* ... and we let it deal with outputting one byte of zero for them too. */
2355 darwin_asm_declare_object_name (fp, name, decl);
2356 assemble_zeros (size);
2359 /* This routine emits 'local' storage:
2361 When Section Anchors are off this routine emits .zerofill commands in
2362 sections named for their alignment.
2364 When Section Anchors are on, smaller (non-zero-sized) items are placed in
2365 the .static_data section so that the section anchoring system can see them.
2366 Larger items are still placed in .zerofill sections, addressing PR33210.
2367 The routine has no checking - it is all assumed to be done by the caller.
2369 static void
2370 darwin_emit_local_bss (FILE *fp, tree decl, const char *name,
2371 unsigned HOST_WIDE_INT size,
2372 unsigned int l2align)
2374 /* FIXME: We have a fudge to make this work with Java even when the target does
2375 not use sections anchors -- Java seems to need at least one small item in a
2376 non-zerofill segment. */
2377 if ((DARWIN_SECTION_ANCHORS && flag_section_anchors && size < BYTES_ZFILL)
2378 || (size && size <= 2))
2380 /* Put smaller objects in _static_data, where the section anchors system
2381 can get them.
2382 However, if they are zero-sized punt them to yet a different section
2383 (that is not allowed to participate in anchoring). */
2384 if (!size)
2386 fputs ("\t.section\t__DATA,__zobj_bss\n", fp);
2387 in_section = darwin_sections[zobj_bss_section];
2388 size = 1;
2390 else
2392 fputs ("\t.static_data\n", fp);
2393 in_section = darwin_sections[static_data_section];
2396 if (l2align)
2397 fprintf (fp, "\t.align\t%u\n", l2align);
2399 assemble_name (fp, name);
2400 fprintf (fp, ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2402 else
2404 /* When we are on a non-section anchor target, we can get zero-sized
2405 items here. However, all we need to do is to bump them to one byte
2406 and the section alignment will take care of the rest. */
2407 char secnam[64];
2408 unsigned int flags ;
2409 snprintf (secnam, 64, "__DATA,__%sbss%u", ((size)?"":"zo_"),
2410 (unsigned) l2align);
2411 /* We can't anchor (yet, if ever) in zerofill sections, because we can't
2412 switch to them and emit a label. */
2413 flags = SECTION_BSS|SECTION_WRITE|SECTION_NO_ANCHOR;
2414 in_section = get_section (secnam, flags, NULL);
2415 fprintf (fp, "\t.zerofill %s,", secnam);
2416 assemble_name (fp, name);
2417 if (!size)
2418 size = 1;
2420 if (l2align)
2421 fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED",%u\n",
2422 size, (unsigned) l2align);
2423 else
2424 fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2427 (*targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2428 /* This is defined as a file-scope var, so we know to notify machopic. */
2429 machopic_define_symbol (DECL_RTL (decl));
2432 /* Emit a chunk of common. */
2433 static void
2434 darwin_emit_common (FILE *fp, const char *name,
2435 unsigned HOST_WIDE_INT size, unsigned int align)
2437 unsigned HOST_WIDE_INT rounded;
2438 unsigned int l2align;
2440 /* Earlier systems complain if the alignment exceeds the page size.
2441 The magic number is 4096 * 8 - hard-coded for legacy systems. */
2442 if (!emit_aligned_common && (align > 32768UL))
2443 align = 4096UL; /* In units. */
2444 else
2445 align /= BITS_PER_UNIT;
2447 /* Make sure we have a meaningful align. */
2448 if (!align)
2449 align = 1;
2451 /* For earlier toolchains, we need to emit the var as a rounded size to
2452 tell ld the alignment. */
2453 if (size < align)
2454 rounded = align;
2455 else
2456 rounded = (size + (align-1)) & ~(align-1);
2458 l2align = floor_log2 (align);
2459 gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2461 in_section = comm_section;
2462 /* We mustn't allow multiple public symbols to share an address when using
2463 the normal OSX toolchain. */
2464 if (!size)
2466 /* Put at least one byte. */
2467 size = 1;
2468 /* This section can no longer participate in section anchoring. */
2469 comm_section->common.flags |= SECTION_NO_ANCHOR;
2472 fputs ("\t.comm\t", fp);
2473 assemble_name (fp, name);
2474 fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED,
2475 emit_aligned_common?size:rounded);
2476 if (l2align && emit_aligned_common)
2477 fprintf (fp, ",%u", l2align);
2478 fputs ("\n", fp);
2481 /* Output a var which is all zero - into aligned BSS sections, common, lcomm
2482 or coalescable data sections (for weak or comdat) as appropriate. */
2484 void
2485 darwin_output_aligned_bss (FILE *fp, tree decl, const char *name,
2486 unsigned HOST_WIDE_INT size, unsigned int align)
2488 unsigned int l2align;
2489 bool one, pub, weak;
2490 tree meta;
2492 pub = TREE_PUBLIC (decl);
2493 one = DECL_ONE_ONLY (decl);
2494 weak = (DECL_P (decl)
2495 && DECL_WEAK (decl)
2496 && !lookup_attribute ("weak_import",
2497 DECL_ATTRIBUTES (decl)));
2499 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2500 fprintf (fp, "# albss: %s (%lld,%d) ro %d cst %d stat %d com %d"
2501 " pub %d weak %d one %d init %lx\n",
2502 name, (long long)size, (int)align, TREE_READONLY (decl),
2503 TREE_CONSTANT (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2504 pub, weak, one, (unsigned long)DECL_INITIAL (decl));
2505 #endif
2507 /* ObjC metadata can get put in BSS because varasm.c decides it's BSS
2508 before the target has a chance to comment. */
2509 if ((meta = is_objc_metadata (decl)))
2511 darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2512 return;
2515 /* Check that any initializer is valid. */
2516 gcc_assert ((DECL_INITIAL (decl) == NULL)
2517 || (DECL_INITIAL (decl) == error_mark_node)
2518 || initializer_zerop (DECL_INITIAL (decl)));
2520 gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2521 gcc_assert (!DECL_COMMON (decl));
2523 /* Pick up the correct alignment. */
2524 if (!size || !align)
2525 align = DECL_ALIGN (decl);
2527 l2align = floor_log2 (align / BITS_PER_UNIT);
2528 gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2530 last_assemble_variable_decl = decl;
2532 /* We would rather not have to check this here - but it seems that we might
2533 be passed a decl that should be in coalesced space. */
2534 if (one || weak)
2536 /* Weak or COMDAT objects are put in mergeable sections. */
2537 darwin_emit_weak_or_comdat (fp, decl, name, size,
2538 ld_uses_coal_sects, DECL_ALIGN (decl));
2539 return;
2542 /* If this is not public, then emit according to local rules. */
2543 if (!pub)
2545 darwin_emit_local_bss (fp, decl, name, size, l2align);
2546 return;
2549 /* So we have a public symbol (small item fudge for Java, see above). */
2550 if ((DARWIN_SECTION_ANCHORS && flag_section_anchors && size < BYTES_ZFILL)
2551 || (size && size <= 2))
2553 /* Put smaller objects in data, where the section anchors system can get
2554 them. However, if they are zero-sized punt them to yet a different
2555 section (that is not allowed to participate in anchoring). */
2556 if (!size)
2558 fputs ("\t.section\t__DATA,__zobj_data\n", fp);
2559 in_section = darwin_sections[zobj_data_section];
2560 size = 1;
2562 else
2564 fputs ("\t.data\n", fp);
2565 in_section = data_section;
2568 if (l2align)
2569 fprintf (fp, "\t.align\t%u\n", l2align);
2571 assemble_name (fp, name);
2572 fprintf (fp, ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2574 else
2576 char secnam[64];
2577 unsigned int flags ;
2578 /* When we are on a non-section anchor target, we can get zero-sized
2579 items here. However, all we need to do is to bump them to one byte
2580 and the section alignment will take care of the rest. */
2581 snprintf (secnam, 64, "__DATA,__%spu_bss%u", ((size)?"":"zo_"), l2align);
2583 /* We can't anchor in zerofill sections, because we can't switch
2584 to them and emit a label. */
2585 flags = SECTION_BSS|SECTION_WRITE|SECTION_NO_ANCHOR;
2586 in_section = get_section (secnam, flags, NULL);
2587 fprintf (fp, "\t.zerofill %s,", secnam);
2588 assemble_name (fp, name);
2589 if (!size)
2590 size = 1;
2592 if (l2align)
2593 fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED",%u\n", size, l2align);
2594 else
2595 fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2597 (* targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2600 /* Output a chunk of common, with alignment specified (where the target
2601 supports this). */
2602 void
2603 darwin_asm_output_aligned_decl_common (FILE *fp, tree decl, const char *name,
2604 unsigned HOST_WIDE_INT size,
2605 unsigned int align)
2607 unsigned int l2align;
2608 bool one, weak;
2609 tree meta;
2611 /* No corresponding var. */
2612 if (decl==NULL)
2614 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2615 fprintf (fp, "# adcom: %s (%d,%d) decl=0x0\n", name, (int)size, (int)align);
2616 #endif
2617 darwin_emit_common (fp, name, size, align);
2618 return;
2621 one = DECL_ONE_ONLY (decl);
2622 weak = (DECL_P (decl)
2623 && DECL_WEAK (decl)
2624 && !lookup_attribute ("weak_import",
2625 DECL_ATTRIBUTES (decl)));
2627 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2628 fprintf (fp, "# adcom: %s (%lld,%d) ro %d cst %d stat %d com %d pub %d"
2629 " weak %d one %d init %lx\n",
2630 name, (long long)size, (int)align, TREE_READONLY (decl),
2631 TREE_CONSTANT (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2632 TREE_PUBLIC (decl), weak, one, (unsigned long)DECL_INITIAL (decl));
2633 #endif
2635 /* ObjC metadata can get put in BSS because varasm.c decides it's BSS
2636 before the target has a chance to comment. */
2637 if ((meta = is_objc_metadata (decl)))
2639 darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2640 return;
2643 /* We shouldn't be messing with this if the decl has a section name. */
2644 gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2646 /* We would rather not have to check this here - but it seems that we might
2647 be passed a decl that should be in coalesced space. */
2648 if (one || weak)
2650 /* Weak or COMDAT objects are put in mergable sections. */
2651 darwin_emit_weak_or_comdat (fp, decl, name, size,
2652 ld_uses_coal_sects, DECL_ALIGN (decl));
2653 return;
2656 /* We should only get here for DECL_COMMON, with a zero init (and, in
2657 principle, only for public symbols too - although we deal with local
2658 ones below). */
2660 /* Check the initializer is OK. */
2661 gcc_assert (DECL_COMMON (decl)
2662 && ((DECL_INITIAL (decl) == NULL)
2663 || (DECL_INITIAL (decl) == error_mark_node)
2664 || initializer_zerop (DECL_INITIAL (decl))));
2666 last_assemble_variable_decl = decl;
2668 if (!size || !align)
2669 align = DECL_ALIGN (decl);
2671 l2align = floor_log2 (align / BITS_PER_UNIT);
2672 /* Check we aren't asking for more aligment than the platform allows. */
2673 gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2675 if (TREE_PUBLIC (decl) != 0)
2676 darwin_emit_common (fp, name, size, align);
2677 else
2678 darwin_emit_local_bss (fp, decl, name, size, l2align);
2681 /* Output a chunk of BSS with alignment specfied. */
2682 void
2683 darwin_asm_output_aligned_decl_local (FILE *fp, tree decl, const char *name,
2684 unsigned HOST_WIDE_INT size,
2685 unsigned int align)
2687 unsigned long l2align;
2688 bool one, weak;
2689 tree meta;
2691 one = DECL_ONE_ONLY (decl);
2692 weak = (DECL_P (decl)
2693 && DECL_WEAK (decl)
2694 && !lookup_attribute ("weak_import",
2695 DECL_ATTRIBUTES (decl)));
2697 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2698 fprintf (fp, "# adloc: %s (%lld,%d) ro %d cst %d stat %d one %d pub %d"
2699 " weak %d init %lx\n",
2700 name, (long long)size, (int)align, TREE_READONLY (decl),
2701 TREE_CONSTANT (decl), TREE_STATIC (decl), one, TREE_PUBLIC (decl),
2702 weak , (unsigned long)DECL_INITIAL (decl));
2703 #endif
2705 /* ObjC metadata can get put in BSS because varasm.c decides it's BSS
2706 before the target has a chance to comment. */
2707 if ((meta = is_objc_metadata (decl)))
2709 darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2710 return;
2713 /* We shouldn't be messing with this if the decl has a section name. */
2714 gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2716 /* We would rather not have to check this here - but it seems that we might
2717 be passed a decl that should be in coalesced space. */
2718 if (one || weak)
2720 /* Weak or COMDAT objects are put in mergable sections. */
2721 darwin_emit_weak_or_comdat (fp, decl, name, size,
2722 ld_uses_coal_sects, DECL_ALIGN (decl));
2723 return;
2726 /* .. and it should be suitable for placement in local mem. */
2727 gcc_assert(!TREE_PUBLIC (decl) && !DECL_COMMON (decl));
2728 /* .. and any initializer must be all-zero. */
2729 gcc_assert ((DECL_INITIAL (decl) == NULL)
2730 || (DECL_INITIAL (decl) == error_mark_node)
2731 || initializer_zerop (DECL_INITIAL (decl)));
2733 last_assemble_variable_decl = decl;
2735 if (!size || !align)
2736 align = DECL_ALIGN (decl);
2738 l2align = floor_log2 (align / BITS_PER_UNIT);
2739 gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2741 darwin_emit_local_bss (fp, decl, name, size, l2align);
2744 /* Emit an assembler directive to set visibility for a symbol. The
2745 only supported visibilities are VISIBILITY_DEFAULT and
2746 VISIBILITY_HIDDEN; the latter corresponds to Darwin's "private
2747 extern". There is no MACH-O equivalent of ELF's
2748 VISIBILITY_INTERNAL or VISIBILITY_PROTECTED. */
2750 void
2751 darwin_assemble_visibility (tree decl, int vis)
2753 if (vis == VISIBILITY_DEFAULT)
2755 else if (vis == VISIBILITY_HIDDEN || vis == VISIBILITY_INTERNAL)
2757 fputs ("\t.private_extern ", asm_out_file);
2758 assemble_name (asm_out_file,
2759 (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))));
2760 fputs ("\n", asm_out_file);
2762 else
2763 warning (OPT_Wattributes, "protected visibility attribute "
2764 "not supported in this configuration; ignored");
2767 /* vec used by darwin_asm_dwarf_section.
2768 Maybe a hash tab would be better here - but the intention is that this is
2769 a very short list (fewer than 16 items) and each entry should (ideally,
2770 eventually) only be presented once.
2772 A structure to hold a dwarf debug section used entry. */
2774 typedef struct GTY(()) dwarf_sect_used_entry {
2775 const char *name;
2776 unsigned count;
2778 dwarf_sect_used_entry;
2781 /* A list of used __DWARF sections. */
2782 static GTY (()) vec<dwarf_sect_used_entry, va_gc> *dwarf_sect_names_table;
2784 /* This is called when we are asked to assemble a named section and the
2785 name begins with __DWARF,. We keep a list of the section names (without
2786 the __DWARF, prefix) and use this to emit our required start label on the
2787 first switch to each section. */
2789 static void
2790 darwin_asm_dwarf_section (const char *name, unsigned int flags,
2791 tree ARG_UNUSED (decl), bool is_for_lto)
2793 unsigned i;
2794 int namelen, extra = 0;
2795 const char *sect, *lto_add = "";
2796 char sname[64];
2797 dwarf_sect_used_entry *ref;
2798 bool found = false;
2800 gcc_checking_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
2801 == (SECTION_DEBUG | SECTION_NAMED));
2803 /* We know that the name starts with __DWARF, or __GNU_DAWRF_LTO */
2804 sect = strchr (name, ',') + 1;
2805 namelen = strchr (sect, ',') - sect;
2806 gcc_checking_assert (namelen);
2808 /* The section switch is output as written... */
2809 fprintf (asm_out_file, "\t.section %s\n", name);
2811 /* ... but the string we keep to make section start labels needs
2812 adjustment for lto cases. */
2813 if (is_for_lto)
2815 lto_add = "_lto";
2816 extra = 4;
2819 snprintf (sname, 64, "%.*s%.*s", namelen, sect, extra, lto_add);
2820 namelen += extra;
2822 if (dwarf_sect_names_table == NULL)
2823 vec_alloc (dwarf_sect_names_table, 16);
2824 else
2825 for (i = 0;
2826 dwarf_sect_names_table->iterate (i, &ref);
2827 i++)
2829 if (!ref)
2830 break;
2831 if (!strcmp (ref->name, sname))
2833 found = true;
2834 ref->count++;
2835 break;
2839 if (!found)
2841 dwarf_sect_used_entry e;
2842 fprintf (asm_out_file, "Lsection%.*s:\n", namelen, sname);
2843 e.count = 1;
2844 e.name = xstrdup (sname);
2845 vec_safe_push (dwarf_sect_names_table, e);
2849 /* Output a difference of two labels that will be an assembly time
2850 constant if the two labels are local. (.long lab1-lab2 will be
2851 very different if lab1 is at the boundary between two sections; it
2852 will be relocated according to the second section, not the first,
2853 so one ends up with a difference between labels in different
2854 sections, which is bad in the dwarf2 eh context for instance.) */
2856 static int darwin_dwarf_label_counter;
2858 void
2859 darwin_asm_output_dwarf_delta (FILE *file, int size,
2860 const char *lab1, const char *lab2,
2861 HOST_WIDE_INT offset)
2863 int islocaldiff = (lab1[0] == '*' && lab1[1] == 'L'
2864 && lab2[0] == '*' && lab2[1] == 'L');
2865 const char *directive = (size == 8 ? ".quad" : ".long");
2867 if (islocaldiff)
2868 fprintf (file, "\t.set L$set$%d,", darwin_dwarf_label_counter);
2869 else
2870 fprintf (file, "\t%s\t", directive);
2872 assemble_name_raw (file, lab1);
2873 fprintf (file, "-");
2874 assemble_name_raw (file, lab2);
2875 if (offset != 0)
2876 fprintf (file, "+" HOST_WIDE_INT_PRINT_DEC, offset);
2877 if (islocaldiff)
2878 fprintf (file, "\n\t%s L$set$%d", directive, darwin_dwarf_label_counter++);
2881 /* Output an offset in a DWARF section on Darwin. On Darwin, DWARF section
2882 offsets are not represented using relocs in .o files; either the
2883 section never leaves the .o file, or the linker or other tool is
2884 responsible for parsing the DWARF and updating the offsets. */
2886 void
2887 darwin_asm_output_dwarf_offset (FILE *file, int size, const char * lab,
2888 HOST_WIDE_INT offset, section *base)
2890 char sname[64];
2891 int namelen, extra = 0;
2892 bool is_for_lto;
2893 const char *lto_add = "";
2895 gcc_checking_assert (base->common.flags & SECTION_NAMED);
2896 is_for_lto = strncmp (base->named.name, "__GNU_DWARF_LTO,", 16) == 0;
2897 gcc_checking_assert (is_for_lto
2898 || strncmp (base->named.name, "__DWARF,", 8) == 0);
2899 const char *name = strchr (base->named.name, ',') + 1;
2900 gcc_checking_assert (name);
2902 namelen = strchr (name, ',') - (name);
2903 if (is_for_lto)
2905 lto_add = "_lto";
2906 extra = 4;
2908 snprintf (sname, 64, "*Lsection%.*s%.*s", namelen, name, extra, lto_add);
2909 darwin_asm_output_dwarf_delta (file, size, lab, sname, offset);
2912 /* Called from the within the TARGET_ASM_FILE_START for each target. */
2914 void
2915 darwin_file_start (void)
2917 /* Nothing to do. */
2920 /* Called for the TARGET_ASM_FILE_END hook.
2921 Emit the mach-o pic indirection data, the lto data and, finally a flag
2922 to tell the linker that it can break the file object into sections and
2923 move those around for efficiency. */
2925 void
2926 darwin_file_end (void)
2928 if (!vec_safe_is_empty (ctors))
2929 finalize_ctors ();
2930 if (!vec_safe_is_empty (dtors))
2931 finalize_dtors ();
2933 /* If we are expecting to output NeXT ObjC meta-data, (and we actually see
2934 some) then we output the fix-and-continue marker (Image Info).
2935 This applies to Objective C, Objective C++ and LTO with either language
2936 as part of the input. */
2937 if (flag_next_runtime && objc_metadata_seen)
2939 unsigned int flags = 0;
2940 if (flag_objc_abi >= 2)
2942 flags = 16;
2943 switch_to_section (darwin_sections[objc2_image_info_section]);
2945 else
2946 switch_to_section (darwin_sections[objc_image_info_section]);
2948 ASM_OUTPUT_ALIGN (asm_out_file, 2);
2949 fputs ("L_OBJC_ImageInfo:\n", asm_out_file);
2951 flags |= (flag_replace_objc_classes && classes_seen) ? 1 : 0;
2952 flags |= flag_objc_gc ? 2 : 0;
2954 fprintf (asm_out_file, "\t.long\t0\n\t.long\t%u\n", flags);
2957 machopic_finish (asm_out_file);
2958 if (flag_apple_kext)
2960 /* These sections are only used for kernel code. */
2961 switch_to_section (darwin_sections[constructor_section]);
2962 switch_to_section (darwin_sections[destructor_section]);
2963 ASM_OUTPUT_ALIGN (asm_out_file, 1);
2966 /* If there was LTO assembler output, append it to asm_out_file. */
2967 if (lto_asm_out_name)
2969 int n;
2970 char *buf, *lto_asm_txt;
2972 /* Shouldn't be here if we failed to switch back. */
2973 gcc_assert (! saved_asm_out_file);
2975 lto_asm_out_file = fopen (lto_asm_out_name, "r");
2976 if (lto_asm_out_file == NULL)
2977 fatal_error (input_location,
2978 "failed to open temporary file %s with LTO output",
2979 lto_asm_out_name);
2980 fseek (lto_asm_out_file, 0, SEEK_END);
2981 n = ftell (lto_asm_out_file);
2982 if (n > 0)
2984 fseek (lto_asm_out_file, 0, SEEK_SET);
2985 lto_asm_txt = buf = (char *) xmalloc (n + 1);
2986 while (fgets (lto_asm_txt, n, lto_asm_out_file))
2987 fputs (lto_asm_txt, asm_out_file);
2988 /* Put a termination label. */
2989 fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
2990 LTO_SEGMENT_NAME, LTO_SECTS_SECTION);
2991 fprintf (asm_out_file, "L_GNU_LTO%d:\t;# end of lto\n",
2992 lto_section_num);
2993 /* Make sure our termination label stays in this section. */
2994 fputs ("\t.space\t1\n", asm_out_file);
2997 /* Remove the temporary file. */
2998 fclose (lto_asm_out_file);
2999 unlink_if_ordinary (lto_asm_out_name);
3000 free (lto_asm_out_name);
3003 /* Output the names and indices. */
3004 if (lto_section_names && lto_section_names->length ())
3006 int count;
3007 darwin_lto_section_e *ref;
3008 /* For now, we'll make the offsets 4 bytes and unaligned - we'll fix
3009 the latter up ourselves. */
3010 const char *op = integer_asm_op (4,0);
3012 /* Emit the names. */
3013 fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
3014 LTO_SEGMENT_NAME, LTO_NAMES_SECTION);
3015 FOR_EACH_VEC_ELT (*lto_section_names, count, ref)
3017 fprintf (asm_out_file, "L_GNU_LTO_NAME%d:\n", count);
3018 /* We have to jump through hoops to get the values of the intra-section
3019 offsets... */
3020 fprintf (asm_out_file,
3021 "\t.set L$gnu$lto$noff%d,L_GNU_LTO_NAME%d-L_GNU_LTO_NAME0\n",
3022 count, count);
3023 fprintf (asm_out_file,
3024 "\t.set L$gnu$lto$nsiz%d,L_GNU_LTO_NAME%d-L_GNU_LTO_NAME%d\n",
3025 count, count+1, count);
3026 fprintf (asm_out_file, "\t.asciz\t\"%s\"\n", ref->sectname);
3028 fprintf (asm_out_file, "L_GNU_LTO_NAME%d:\t;# end\n", lto_section_num);
3029 /* make sure our termination label stays in this section. */
3030 fputs ("\t.space\t1\n", asm_out_file);
3032 /* Emit the Index. */
3033 fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
3034 LTO_SEGMENT_NAME, LTO_INDEX_SECTION);
3035 fputs ("\t.align\t2\n", asm_out_file);
3036 fputs ("# Section offset, Section length, Name offset, Name length\n",
3037 asm_out_file);
3038 FOR_EACH_VEC_ELT (*lto_section_names, count, ref)
3040 fprintf (asm_out_file, "%s L$gnu$lto$offs%d\t;# %s\n",
3041 op, count, ref->sectname);
3042 fprintf (asm_out_file, "%s L$gnu$lto$size%d\n", op, count);
3043 fprintf (asm_out_file, "%s L$gnu$lto$noff%d\n", op, count);
3044 fprintf (asm_out_file, "%s L$gnu$lto$nsiz%d\n", op, count);
3048 /* If we have section anchors, then we must prevent the linker from
3049 re-arranging data. */
3050 if (!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
3051 fprintf (asm_out_file, "\t.subsections_via_symbols\n");
3054 /* TODO: Add a language hook for identifying if a decl is a vtable. */
3055 #define DARWIN_VTABLE_P(DECL) 0
3057 /* Cross-module name binding. Darwin does not support overriding
3058 functions at dynamic-link time, except for vtables in kexts. */
3060 bool
3061 darwin_binds_local_p (const_tree decl)
3063 /* We use the "shlib" input to indicate that a symbol should be
3064 considered overridable; only relevant for vtables in kernel modules
3065 on earlier system versions, and with a TODO to complete. */
3066 bool force_overridable = TARGET_KEXTABI && DARWIN_VTABLE_P (decl);
3067 return default_binds_local_p_3 (decl, force_overridable /* shlib */,
3068 false /* weak dominate */,
3069 false /* extern_protected_data */,
3070 false /* common_local_p */);
3073 /* The Darwin's implementation of TARGET_ASM_OUTPUT_ANCHOR. Define the
3074 anchor relative to ".", the current section position. We cannot use
3075 the default one because ASM_OUTPUT_DEF is wrong for Darwin. */
3076 void
3077 darwin_asm_output_anchor (rtx symbol)
3079 fprintf (asm_out_file, "\t.set\t");
3080 assemble_name (asm_out_file, XSTR (symbol, 0));
3081 fprintf (asm_out_file, ", . + " HOST_WIDE_INT_PRINT_DEC "\n",
3082 SYMBOL_REF_BLOCK_OFFSET (symbol));
3085 /* Disable section anchoring on any section containing a zero-sized
3086 object. */
3087 bool
3088 darwin_use_anchors_for_symbol_p (const_rtx symbol)
3090 if (DARWIN_SECTION_ANCHORS && flag_section_anchors)
3092 section *sect;
3093 /* If the section contains a zero-sized object it's ineligible. */
3094 sect = SYMBOL_REF_BLOCK (symbol)->sect;
3095 /* This should have the effect of disabling anchors for vars that follow
3096 any zero-sized one, in a given section. */
3097 if (sect->common.flags & SECTION_NO_ANCHOR)
3098 return false;
3100 /* Also check the normal reasons for suppressing. */
3101 return default_use_anchors_for_symbol_p (symbol);
3103 else
3104 return false;
3107 /* Set the darwin specific attributes on TYPE. */
3108 void
3109 darwin_set_default_type_attributes (tree type)
3111 if (darwin_ms_struct
3112 && TREE_CODE (type) == RECORD_TYPE)
3113 TYPE_ATTRIBUTES (type) = tree_cons (get_identifier ("ms_struct"),
3114 NULL_TREE,
3115 TYPE_ATTRIBUTES (type));
3118 /* True, iff we're generating code for loadable kernel extensions. */
3120 bool
3121 darwin_kextabi_p (void) {
3122 return flag_apple_kext;
3125 void
3126 darwin_override_options (void)
3128 /* Keep track of which (major) version we're generating code for. */
3129 if (darwin_macosx_version_min)
3131 if (strverscmp (darwin_macosx_version_min, "10.6") >= 0)
3132 generating_for_darwin_version = 10;
3133 else if (strverscmp (darwin_macosx_version_min, "10.5") >= 0)
3134 generating_for_darwin_version = 9;
3136 /* Earlier versions are not specifically accounted, until required. */
3139 /* Older Darwin ld could not coalesce weak entities without them being
3140 placed in special sections. */
3141 if (darwin_target_linker
3142 && (strverscmp (darwin_target_linker, MIN_LD64_NO_COAL_SECTS) < 0))
3143 ld_uses_coal_sects = true;
3145 /* In principle, this should be c-family only. However, we really need to
3146 set sensible defaults for LTO as well, since the section selection stuff
3147 should check for correctness re. the ABI. TODO: check and provide the
3148 flags (runtime & ABI) from the lto wrapper). */
3150 /* Unless set, force ABI=2 for NeXT and m64, 0 otherwise. */
3151 if (!global_options_set.x_flag_objc_abi)
3152 global_options.x_flag_objc_abi
3153 = (!flag_next_runtime)
3155 : (TARGET_64BIT ? 2
3156 : (generating_for_darwin_version >= 9) ? 1
3157 : 0);
3159 if (global_options_set.x_flag_objc_abi && flag_next_runtime)
3161 if (TARGET_64BIT && global_options.x_flag_objc_abi != 2)
3162 /* The Objective-C family ABI 2 is the only valid version NeXT/m64. */
3163 error_at (UNKNOWN_LOCATION,
3164 "%<-fobjc-abi-version%> 2 must be used for 64 bit targets"
3165 " with %<-fnext-runtime%>");
3166 else if (!TARGET_64BIT && global_options.x_flag_objc_abi >= 2)
3167 /* ABI versions 0 and 1 are the only valid versions NeXT/m32. */
3168 error_at (UNKNOWN_LOCATION,
3169 "%<-fobjc-abi-version%> %d is not supported for 32 bit"
3170 " targets with %<-fnext-runtime%>",
3171 global_options.x_flag_objc_abi);
3174 /* Don't emit DWARF3/4 unless specifically selected. This is a
3175 workaround for tool bugs. */
3176 if (!global_options_set.x_dwarf_strict)
3177 dwarf_strict = 1;
3178 if (!global_options_set.x_dwarf_version)
3179 dwarf_version = 2;
3181 if (global_options_set.x_dwarf_split_debug_info)
3183 inform (input_location,
3184 "%<-gsplit-dwarf%> is not supported on this platform, ignored");
3185 dwarf_split_debug_info = 0;
3186 global_options_set.x_dwarf_split_debug_info = 0;
3189 /* Do not allow unwind tables to be generated by default for m32.
3190 fnon-call-exceptions will override this, regardless of what we do. */
3191 if (generating_for_darwin_version < 10
3192 && !global_options_set.x_flag_asynchronous_unwind_tables
3193 && !TARGET_64BIT)
3194 global_options.x_flag_asynchronous_unwind_tables = 0;
3196 /* Disable -freorder-blocks-and-partition when unwind tables are being
3197 emitted for Darwin < 9 (OSX 10.5).
3198 The strategy is, "Unless the User has specifically set/unset an unwind
3199 flag we will switch off -freorder-blocks-and-partition when unwind tables
3200 will be generated". If the User specifically sets flags... we assume
3201 (s)he knows why... */
3202 if (generating_for_darwin_version < 9
3203 && global_options_set.x_flag_reorder_blocks_and_partition
3204 && ((global_options.x_flag_exceptions /* User, c++, java */
3205 && !global_options_set.x_flag_exceptions) /* User specified... */
3206 || (global_options.x_flag_unwind_tables
3207 && !global_options_set.x_flag_unwind_tables)
3208 || (global_options.x_flag_non_call_exceptions
3209 && !global_options_set.x_flag_non_call_exceptions)
3210 || (global_options.x_flag_asynchronous_unwind_tables
3211 && !global_options_set.x_flag_asynchronous_unwind_tables)))
3213 inform (input_location,
3214 "%<-freorder-blocks-and-partition%> does not work with "
3215 "exceptions on this architecture");
3216 flag_reorder_blocks_and_partition = 0;
3217 flag_reorder_blocks = 1;
3220 /* FIXME: flag_objc_sjlj_exceptions is no longer needed since there is only
3221 one valid choice of exception scheme for each runtime. */
3222 if (!global_options_set.x_flag_objc_sjlj_exceptions)
3223 global_options.x_flag_objc_sjlj_exceptions =
3224 flag_next_runtime && !TARGET_64BIT;
3226 /* FIXME: and this could be eliminated then too. */
3227 if (!global_options_set.x_flag_exceptions
3228 && flag_objc_exceptions
3229 && TARGET_64BIT)
3230 flag_exceptions = 1;
3232 if (flag_mkernel || flag_apple_kext)
3234 /* -mkernel implies -fapple-kext for C++ */
3235 if (lang_GNU_CXX ())
3236 flag_apple_kext = 1;
3238 flag_no_common = 1;
3240 /* No EH in kexts. */
3241 flag_exceptions = 0;
3242 /* No -fnon-call-exceptions data in kexts. */
3243 flag_non_call_exceptions = 0;
3244 /* so no tables either.. */
3245 flag_unwind_tables = 0;
3246 flag_asynchronous_unwind_tables = 0;
3249 if (flag_var_tracking_uninit == 0
3250 && generating_for_darwin_version >= 9
3251 && (flag_gtoggle ? (debug_info_level == DINFO_LEVEL_NONE)
3252 : (debug_info_level >= DINFO_LEVEL_NORMAL))
3253 && write_symbols == DWARF2_DEBUG)
3254 flag_var_tracking_uninit = flag_var_tracking;
3256 /* Final check on PCI options; for Darwin these are not dependent on the PIE
3257 ones, although PIE does require PIC to support it. */
3258 if (MACHO_DYNAMIC_NO_PIC_P)
3260 if (flag_pic)
3261 warning_at (UNKNOWN_LOCATION, 0,
3262 "%<-mdynamic-no-pic%> overrides %<-fpic%>, %<-fPIC%>,"
3263 " %<-fpie%> or %<-fPIE%>");
3264 flag_pic = 0;
3266 else if (flag_pic == 1
3267 || (flag_pic == 0 && !(flag_mkernel || flag_apple_kext)))
3269 /* Darwin's -fpic is -fPIC.
3270 We only support "static" code in the kernel and kernel exts. */
3271 flag_pic = 2;
3274 /* Linkers >= ld64-62.1 (at least) are capable of making the necessary PIC
3275 indirections and we no longer need to emit pic symbol stubs.
3276 However, if we are generating code for earlier ones (or for use in the
3277 kernel) the stubs might still be required, and this will be set true.
3278 If the user sets it on or off - then that takes precedence.
3280 Linkers that don't need stubs, don't need the EH symbol markers either.
3283 if (!global_options_set.x_darwin_symbol_stubs)
3285 if (darwin_target_linker)
3287 if (strverscmp (darwin_target_linker, MIN_LD64_OMIT_STUBS) < 0)
3289 darwin_symbol_stubs = true;
3290 ld_needs_eh_markers = true;
3293 else if (generating_for_darwin_version < 9)
3295 /* If we don't know the linker version and we're targeting an old
3296 system, we know no better than to assume the use of an earlier
3297 linker. */
3298 darwin_symbol_stubs = true;
3299 ld_needs_eh_markers = true;
3302 else if (DARWIN_X86 && darwin_symbol_stubs && TARGET_64BIT)
3304 inform (input_location,
3305 "%<-mpic-symbol-stubs%> is not required for 64b code (ignored)");
3306 darwin_symbol_stubs = false;
3309 if (generating_for_darwin_version >= 9)
3310 /* Later systems can support aligned common. */
3311 emit_aligned_common = true;
3313 /* The c_dialect...() macros are not available to us here. */
3314 darwin_running_cxx = (strstr (lang_hooks.name, "C++") != 0);
3317 #if DARWIN_PPC
3318 /* Add $LDBL128 suffix to long double builtins for ppc darwin. */
3320 static void
3321 darwin_patch_builtin (enum built_in_function fncode)
3323 tree fn = builtin_decl_explicit (fncode);
3324 tree sym;
3325 char *newname;
3327 if (!fn)
3328 return;
3330 sym = DECL_ASSEMBLER_NAME (fn);
3331 newname = ACONCAT (("_", IDENTIFIER_POINTER (sym), "$LDBL128", NULL));
3333 set_user_assembler_name (fn, newname);
3335 fn = builtin_decl_implicit (fncode);
3336 if (fn)
3337 set_user_assembler_name (fn, newname);
3340 void
3341 darwin_patch_builtins (void)
3343 if (LONG_DOUBLE_TYPE_SIZE != 128)
3344 return;
3346 #define PATCH_BUILTIN(fncode) darwin_patch_builtin (fncode);
3347 #define PATCH_BUILTIN_NO64(fncode) \
3348 if (!TARGET_64BIT) \
3349 darwin_patch_builtin (fncode);
3350 #define PATCH_BUILTIN_VARIADIC(fncode) \
3351 if (!TARGET_64BIT \
3352 && (strverscmp (darwin_macosx_version_min, "10.3.9") >= 0)) \
3353 darwin_patch_builtin (fncode);
3354 #include "darwin-ppc-ldouble-patch.def"
3355 #undef PATCH_BUILTIN
3356 #undef PATCH_BUILTIN_NO64
3357 #undef PATCH_BUILTIN_VARIADIC
3359 #endif
3361 /* CFStrings implementation. */
3362 static GTY(()) tree cfstring_class_reference = NULL_TREE;
3363 static GTY(()) tree cfstring_type_node = NULL_TREE;
3364 static GTY(()) tree ccfstring_type_node = NULL_TREE;
3365 static GTY(()) tree pccfstring_type_node = NULL_TREE;
3366 static GTY(()) tree pcint_type_node = NULL_TREE;
3367 static GTY(()) tree pcchar_type_node = NULL_TREE;
3369 static enum built_in_function darwin_builtin_cfstring;
3371 /* Store all constructed constant CFStrings in a hash table so that
3372 they get uniqued properly. */
3374 typedef struct GTY ((for_user)) cfstring_descriptor {
3375 /* The string literal. */
3376 tree literal;
3377 /* The resulting constant CFString. */
3378 tree constructor;
3379 } cfstring_descriptor;
3381 struct cfstring_hasher : ggc_ptr_hash<cfstring_descriptor>
3383 static hashval_t hash (cfstring_descriptor *);
3384 static bool equal (cfstring_descriptor *, cfstring_descriptor *);
3387 static GTY (()) hash_table<cfstring_hasher> *cfstring_htab;
3389 static tree
3390 add_builtin_field_decl (tree type, const char *name, tree **chain)
3392 tree field = build_decl (BUILTINS_LOCATION, FIELD_DECL,
3393 get_identifier (name), type);
3395 if (*chain != NULL)
3396 **chain = field;
3397 *chain = &DECL_CHAIN (field);
3399 return field;
3402 tree
3403 darwin_init_cfstring_builtins (unsigned builtin_cfstring)
3405 tree cfsfun, fields, pccfstring_ftype_pcchar;
3406 tree *chain = NULL;
3408 darwin_builtin_cfstring =
3409 (enum built_in_function) builtin_cfstring;
3411 /* struct __builtin_CFString {
3412 const int *isa; (will point at
3413 int flags; __CFConstantStringClassReference)
3414 const char *str;
3415 long length;
3416 }; */
3418 pcint_type_node = build_pointer_type
3419 (build_qualified_type (integer_type_node, TYPE_QUAL_CONST));
3421 pcchar_type_node = build_pointer_type
3422 (build_qualified_type (char_type_node, TYPE_QUAL_CONST));
3424 cfstring_type_node = (*lang_hooks.types.make_type) (RECORD_TYPE);
3426 /* Have to build backwards for finish struct. */
3427 fields = add_builtin_field_decl (long_integer_type_node, "length", &chain);
3428 add_builtin_field_decl (pcchar_type_node, "str", &chain);
3429 add_builtin_field_decl (integer_type_node, "flags", &chain);
3430 add_builtin_field_decl (pcint_type_node, "isa", &chain);
3431 finish_builtin_struct (cfstring_type_node, "__builtin_CFString",
3432 fields, NULL_TREE);
3434 /* const struct __builtin_CFstring *
3435 __builtin___CFStringMakeConstantString (const char *); */
3437 ccfstring_type_node = build_qualified_type
3438 (cfstring_type_node, TYPE_QUAL_CONST);
3439 pccfstring_type_node = build_pointer_type (ccfstring_type_node);
3440 pccfstring_ftype_pcchar = build_function_type_list
3441 (pccfstring_type_node, pcchar_type_node, NULL_TREE);
3443 cfsfun = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
3444 get_identifier ("__builtin___CFStringMakeConstantString"),
3445 pccfstring_ftype_pcchar);
3447 TREE_PUBLIC (cfsfun) = 1;
3448 DECL_EXTERNAL (cfsfun) = 1;
3449 DECL_ARTIFICIAL (cfsfun) = 1;
3450 /* Make a lang-specific section - dup_lang_specific_decl makes a new node
3451 in place of the existing, which may be NULL. */
3452 DECL_LANG_SPECIFIC (cfsfun) = NULL;
3453 (*lang_hooks.dup_lang_specific_decl) (cfsfun);
3454 set_decl_built_in_function (cfsfun, BUILT_IN_MD, darwin_builtin_cfstring);
3455 lang_hooks.builtin_function (cfsfun);
3457 /* extern int __CFConstantStringClassReference[]; */
3458 cfstring_class_reference = build_decl (BUILTINS_LOCATION, VAR_DECL,
3459 get_identifier ("__CFConstantStringClassReference"),
3460 build_array_type (integer_type_node, NULL_TREE));
3462 TREE_PUBLIC (cfstring_class_reference) = 1;
3463 DECL_ARTIFICIAL (cfstring_class_reference) = 1;
3464 (*lang_hooks.decls.pushdecl) (cfstring_class_reference);
3465 DECL_EXTERNAL (cfstring_class_reference) = 1;
3466 rest_of_decl_compilation (cfstring_class_reference, 0, 0);
3468 /* Initialize the hash table used to hold the constant CFString objects. */
3469 cfstring_htab = hash_table<cfstring_hasher>::create_ggc (31);
3471 return cfstring_type_node;
3474 tree
3475 darwin_fold_builtin (tree fndecl, int n_args, tree *argp,
3476 bool ARG_UNUSED (ignore))
3478 unsigned int fcode = DECL_MD_FUNCTION_CODE (fndecl);
3480 if (fcode == darwin_builtin_cfstring)
3482 if (!darwin_constant_cfstrings)
3484 error ("built-in function %qD requires the"
3485 " %<-mconstant-cfstrings%> flag", fndecl);
3486 return error_mark_node;
3489 if (n_args != 1)
3491 error ("built-in function %qD takes one argument only", fndecl);
3492 return error_mark_node;
3495 return darwin_build_constant_cfstring (*argp);
3498 return NULL_TREE;
3501 void
3502 darwin_rename_builtins (void)
3504 /* The system ___divdc3 routine in libSystem on darwin10 is not
3505 accurate to 1ulp, ours is, so we avoid ever using the system name
3506 for this routine and instead install a non-conflicting name that
3507 is accurate.
3509 When -ffast-math or -funsafe-math-optimizations is given, we can
3510 use the faster version. */
3511 if (!flag_unsafe_math_optimizations)
3513 enum built_in_function dcode
3514 = (enum built_in_function)(BUILT_IN_COMPLEX_DIV_MIN
3515 + DCmode - MIN_MODE_COMPLEX_FLOAT);
3516 tree fn = builtin_decl_explicit (dcode);
3517 /* Fortran and c call TARGET_INIT_BUILTINS and
3518 TARGET_INIT_LIBFUNCS at different times, so we have to put a
3519 call into each to ensure that at least one of them is called
3520 after build_common_builtin_nodes. A better fix is to add a
3521 new hook to run after build_common_builtin_nodes runs. */
3522 if (fn)
3523 set_user_assembler_name (fn, "___ieee_divdc3");
3524 fn = builtin_decl_implicit (dcode);
3525 if (fn)
3526 set_user_assembler_name (fn, "___ieee_divdc3");
3530 bool
3531 darwin_libc_has_function (enum function_class fn_class)
3533 if (fn_class == function_sincos)
3534 return false;
3535 if (fn_class == function_c99_math_complex
3536 || fn_class == function_c99_misc)
3537 return (TARGET_64BIT
3538 || strverscmp (darwin_macosx_version_min, "10.3") >= 0);
3540 return true;
3543 hashval_t
3544 cfstring_hasher::hash (cfstring_descriptor *ptr)
3546 tree str = ptr->literal;
3547 const unsigned char *p = (const unsigned char *) TREE_STRING_POINTER (str);
3548 int i, len = TREE_STRING_LENGTH (str);
3549 hashval_t h = len;
3551 for (i = 0; i < len; i++)
3552 h = ((h * 613) + p[i]);
3554 return h;
3557 bool
3558 cfstring_hasher::equal (cfstring_descriptor *ptr1, cfstring_descriptor *ptr2)
3560 tree str1 = ptr1->literal;
3561 tree str2 = ptr2->literal;
3562 int len1 = TREE_STRING_LENGTH (str1);
3564 return (len1 == TREE_STRING_LENGTH (str2)
3565 && !memcmp (TREE_STRING_POINTER (str1), TREE_STRING_POINTER (str2),
3566 len1));
3569 tree
3570 darwin_build_constant_cfstring (tree str)
3572 struct cfstring_descriptor *desc, key;
3573 tree addr;
3575 if (!str)
3577 error ("CFString literal is missing");
3578 return error_mark_node;
3581 STRIP_NOPS (str);
3583 if (TREE_CODE (str) == ADDR_EXPR)
3584 str = TREE_OPERAND (str, 0);
3586 if (TREE_CODE (str) != STRING_CST)
3588 error ("CFString literal expression is not a string constant");
3589 return error_mark_node;
3592 /* Perhaps we already constructed a constant CFString just like this one? */
3593 key.literal = str;
3594 cfstring_descriptor **loc = cfstring_htab->find_slot (&key, INSERT);
3595 desc = *loc;
3597 if (!desc)
3599 tree var, constructor, field;
3600 vec<constructor_elt, va_gc> *v = NULL;
3601 int length = TREE_STRING_LENGTH (str) - 1;
3603 if (darwin_warn_nonportable_cfstrings)
3605 const char *s = TREE_STRING_POINTER (str);
3606 int l = 0;
3608 for (l = 0; l < length; l++)
3609 if (!s[l] || !isascii (s[l]))
3611 warning (darwin_warn_nonportable_cfstrings,
3612 s[l] ? G_("non-ASCII character in CFString literal")
3613 : G_("embedded NUL in CFString literal"));
3614 break;
3618 *loc = desc = ggc_cleared_alloc<cfstring_descriptor> ();
3619 desc->literal = str;
3621 /* isa *. */
3622 field = TYPE_FIELDS (ccfstring_type_node);
3623 CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3624 build1 (ADDR_EXPR, TREE_TYPE (field),
3625 cfstring_class_reference));
3626 /* flags */
3627 field = DECL_CHAIN (field);
3628 CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3629 build_int_cst (TREE_TYPE (field), 0x000007c8));
3630 /* string *. */
3631 field = DECL_CHAIN (field);
3632 CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3633 build1 (ADDR_EXPR, TREE_TYPE (field), str));
3634 /* length */
3635 field = DECL_CHAIN (field);
3636 CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3637 build_int_cst (TREE_TYPE (field), length));
3639 constructor = build_constructor (ccfstring_type_node, v);
3640 TREE_READONLY (constructor) = 1;
3641 TREE_CONSTANT (constructor) = 1;
3642 TREE_STATIC (constructor) = 1;
3644 /* Fromage: The C++ flavor of 'build_unary_op' expects constructor nodes
3645 to have the TREE_HAS_CONSTRUCTOR (...) bit set. However, this file is
3646 being built without any knowledge of C++ tree accessors; hence, we shall
3647 use the generic accessor that TREE_HAS_CONSTRUCTOR actually maps to! */
3648 if (darwin_running_cxx)
3649 TREE_LANG_FLAG_4 (constructor) = 1; /* TREE_HAS_CONSTRUCTOR */
3651 /* Create an anonymous global variable for this CFString. */
3652 var = build_decl (input_location, CONST_DECL,
3653 NULL, TREE_TYPE (constructor));
3654 DECL_ARTIFICIAL (var) = 1;
3655 TREE_STATIC (var) = 1;
3656 DECL_INITIAL (var) = constructor;
3657 /* FIXME: This should use a translation_unit_decl to indicate file scope. */
3658 DECL_CONTEXT (var) = NULL_TREE;
3659 desc->constructor = var;
3662 addr = build1 (ADDR_EXPR, pccfstring_type_node, desc->constructor);
3663 TREE_CONSTANT (addr) = 1;
3665 return addr;
3668 bool
3669 darwin_cfstring_p (tree str)
3671 struct cfstring_descriptor key;
3673 if (!str)
3674 return false;
3676 STRIP_NOPS (str);
3678 if (TREE_CODE (str) == ADDR_EXPR)
3679 str = TREE_OPERAND (str, 0);
3681 if (TREE_CODE (str) != STRING_CST)
3682 return false;
3684 key.literal = str;
3685 cfstring_descriptor **loc = cfstring_htab->find_slot (&key, NO_INSERT);
3687 if (loc)
3688 return true;
3690 return false;
3693 void
3694 darwin_enter_string_into_cfstring_table (tree str)
3696 struct cfstring_descriptor key;
3698 key.literal = str;
3699 cfstring_descriptor **loc = cfstring_htab->find_slot (&key, INSERT);
3701 if (!*loc)
3703 *loc = ggc_cleared_alloc<cfstring_descriptor> ();
3704 ((struct cfstring_descriptor *)*loc)->literal = str;
3708 /* Choose named function section based on its frequency. */
3710 section *
3711 darwin_function_section (tree decl, enum node_frequency freq,
3712 bool startup, bool exit)
3714 /* Decide if we need to put this in a coalescable section. */
3715 bool weak = (decl
3716 && DECL_WEAK (decl)
3717 && (!DECL_ATTRIBUTES (decl)
3718 || !lookup_attribute ("weak_import",
3719 DECL_ATTRIBUTES (decl))));
3721 bool use_coal = weak && ld_uses_coal_sects;
3722 /* If there is a specified section name, we should not be trying to
3723 override. */
3724 if (decl && DECL_SECTION_NAME (decl) != NULL)
3725 return get_named_section (decl, NULL, 0);
3727 /* We always put unlikely executed stuff in the cold section. */
3728 if (freq == NODE_FREQUENCY_UNLIKELY_EXECUTED)
3729 return (use_coal) ? darwin_sections[text_cold_coal_section]
3730 : darwin_sections[text_cold_section];
3732 /* If we have LTO *and* feedback information, then let LTO handle
3733 the function ordering, it makes a better job (for normal, hot,
3734 startup and exit - hence the bailout for cold above). */
3735 if (in_lto_p && flag_profile_values)
3736 goto default_function_sections;
3738 /* Non-cold startup code should go to startup subsection. */
3739 if (startup)
3740 return (use_coal) ? darwin_sections[text_startup_coal_section]
3741 : darwin_sections[text_startup_section];
3743 /* Similarly for exit. */
3744 if (exit)
3745 return (use_coal) ? darwin_sections[text_exit_coal_section]
3746 : darwin_sections[text_exit_section];
3748 /* Place hot code. */
3749 if (freq == NODE_FREQUENCY_HOT)
3750 return (use_coal) ? darwin_sections[text_hot_coal_section]
3751 : darwin_sections[text_hot_section];
3753 /* Otherwise, default to the 'normal' non-reordered sections. */
3754 default_function_sections:
3755 return (use_coal) ? darwin_sections[text_coal_section]
3756 : text_section;
3759 #include "gt-darwin.h"