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