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