OSDN Git Service

gcc:
[pf3gnuchains/gcc-fork.git] / gcc / config / darwin.c
1 /* Functions for generic Darwin as target machine for GNU C compiler.
2    Copyright (C) 1989, 1990, 1991, 1992, 1993, 2000, 2001, 2002, 2003, 2004,
3    2005, 2006, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5    Contributed by Apple Computer Inc.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "rtl.h"
28 #include "regs.h"
29 #include "hard-reg-set.h"
30 #include "insn-config.h"
31 #include "conditions.h"
32 #include "insn-flags.h"
33 #include "output.h"
34 #include "insn-attr.h"
35 #include "flags.h"
36 #include "tree.h"
37 #include "expr.h"
38 #include "reload.h"
39 #include "function.h"
40 #include "ggc.h"
41 #include "langhooks.h"
42 #include "target.h"
43 #include "tm_p.h"
44 #include "diagnostic-core.h"
45 #include "toplev.h"
46 #include "hashtab.h"
47 #include "df.h"
48 #include "debug.h"
49 #include "obstack.h"
50 #include "lto-streamer.h"
51
52 /* Darwin supports a feature called fix-and-continue, which is used
53    for rapid turn around debugging.  When code is compiled with the
54    -mfix-and-continue flag, two changes are made to the generated code
55    that allow the system to do things that it would normally not be
56    able to do easily.  These changes allow gdb to load in
57    recompilation of a translation unit that has been changed into a
58    running program and replace existing functions and methods of that
59    translation unit with versions of those functions and methods
60    from the newly compiled translation unit.  The new functions access
61    the existing static symbols from the old translation unit, if the
62    symbol existed in the unit to be replaced, and from the new
63    translation unit, otherwise.
64
65    The changes are to insert 5 nops at the beginning of all functions
66    and to use indirection to get at static symbols.  The 5 nops
67    are required by consumers of the generated code.  Currently, gdb
68    uses this to patch in a jump to the overriding function, this
69    allows all uses of the old name to forward to the replacement,
70    including existing function pointers and virtual methods.  See
71    rs6000_emit_prologue for the code that handles the nop insertions.
72
73    The added indirection allows gdb to redirect accesses to static
74    symbols from the newly loaded translation unit to the existing
75    symbol, if any.  @code{static} symbols are special and are handled by
76    setting the second word in the .non_lazy_symbol_pointer data
77    structure to symbol.  See indirect_data for the code that handles
78    the extra indirection, and machopic_output_indirection and its use
79    of MACHO_SYMBOL_STATIC for the code that handles @code{static}
80    symbol indirection.  */
81
82 /* For darwin >= 9  (OSX 10.5) the linker is capable of making the necessary
83    branch islands and we no longer need to emit darwin stubs.
84    However, if we are generating code for earlier systems (or for use in the 
85    kernel) the stubs might still be required, and this will be set true.  */
86 int darwin_emit_branch_islands = false;
87
88 /* A flag to determine whether we are running c++ or obj-c++.  This has to be
89    settable from non-c-family contexts too (i.e. we can't use the c_dialect_
90    functions).  */
91 int darwin_running_cxx;
92
93 /* Section names.  */
94 section * darwin_sections[NUM_DARWIN_SECTIONS];
95
96 /* While we transition to using in-tests instead of ifdef'd code.  */
97 #ifndef HAVE_lo_sum
98 #define HAVE_lo_sum 0
99 #define gen_macho_high(a,b) (a)
100 #define gen_macho_low(a,b,c) (a)
101 #endif
102
103 /* True if we're setting __attribute__ ((ms_struct)).  */
104 int darwin_ms_struct = false;
105
106 /* Earlier versions of Darwin as do not recognize an alignment field in 
107    .comm directives, this should be set for versions that allow it.  */
108 int emit_aligned_common = false;
109
110 /* A get_unnamed_section callback used to switch to an ObjC section.
111    DIRECTIVE is as for output_section_asm_op.  */
112
113 static void
114 output_objc_section_asm_op (const void *directive)
115 {
116   static bool been_here = false;
117
118   /* The NeXT ObjC Runtime requires these sections to be present and in 
119      order in the object.  The code below implements this by emitting 
120      a section header for each ObjC section the first time that an ObjC
121      section is requested.  */
122   if (! been_here)
123     {
124       section *saved_in_section = in_section;
125       static const enum darwin_section_enum tomark[] =
126         {
127           /* written, cold -> hot */
128           objc_cat_cls_meth_section,
129           objc_cat_inst_meth_section,
130           objc_string_object_section,
131           objc_constant_string_object_section,
132           objc_selector_refs_section,
133           objc_selector_fixup_section,
134           objc_cls_refs_section,
135           objc_class_section,
136           objc_meta_class_section,
137           /* shared, hot -> cold */
138           objc_cls_meth_section,
139           objc_inst_meth_section,
140           objc_protocol_section,
141           objc_class_names_section,
142           objc_meth_var_types_section,
143           objc_meth_var_names_section,
144           objc_category_section,
145           objc_class_vars_section,
146           objc_instance_vars_section,
147           objc_module_info_section,
148           objc_symbols_section
149         };
150       size_t i;
151
152       been_here = true;
153       for (i = 0; i < ARRAY_SIZE (tomark); i++)
154         switch_to_section (darwin_sections[tomark[i]]);
155       switch_to_section (saved_in_section);
156     }
157   output_section_asm_op (directive);
158 }
159
160 /* Implement TARGET_ASM_INIT_SECTIONS.  */
161
162 void
163 darwin_init_sections (void)
164 {
165 #define DEF_SECTION(NAME, FLAGS, DIRECTIVE, OBJC)               \
166   darwin_sections[NAME] =                                       \
167     get_unnamed_section (FLAGS, (OBJC                           \
168                                  ? output_objc_section_asm_op   \
169                                  : output_section_asm_op),      \
170                          "\t" DIRECTIVE);
171 #include "config/darwin-sections.def"
172 #undef DEF_SECTION
173
174   readonly_data_section = darwin_sections[const_section];
175   exception_section = darwin_sections[darwin_exception_section];
176   eh_frame_section = darwin_sections[darwin_eh_frame_section];
177
178   /* Make sure that there is no conflict between the 'no anchor' section
179      flag declared in darwin.h and the section flags declared in output.h.  */
180   gcc_assert (SECTION_NO_ANCHOR > SECTION_MACH_DEP);
181 }
182
183 int
184 name_needs_quotes (const char *name)
185 {
186   int c;
187   while ((c = *name++) != '\0')
188     if (! ISIDNUM (c) 
189           && c != '.' && c != '$' && c != '_' )
190       return 1;
191   return 0;
192 }
193
194 /* Return true if SYM_REF can be used without an indirection.  */
195 int
196 machopic_symbol_defined_p (rtx sym_ref)
197 {
198   if (SYMBOL_REF_FLAGS (sym_ref) & MACHO_SYMBOL_FLAG_DEFINED)
199     return true;
200
201   /* If a symbol references local and is not an extern to this
202      file, then the symbol might be able to declared as defined.  */
203   if (SYMBOL_REF_LOCAL_P (sym_ref) && ! SYMBOL_REF_EXTERNAL_P (sym_ref))
204     {
205       /* If the symbol references a variable and the variable is a
206          common symbol, then this symbol is not defined.  */
207       if (SYMBOL_REF_FLAGS (sym_ref) & MACHO_SYMBOL_FLAG_VARIABLE)
208         {
209           tree decl = SYMBOL_REF_DECL (sym_ref);
210           if (!decl)
211             return true;
212           if (DECL_COMMON (decl))
213             return false;
214         }
215       return true;
216     }
217   return false;
218 }
219
220 /* This module assumes that (const (symbol_ref "foo")) is a legal pic
221    reference, which will not be changed.  */
222
223 enum machopic_addr_class
224 machopic_classify_symbol (rtx sym_ref)
225 {
226   bool function_p;
227
228   function_p = SYMBOL_REF_FUNCTION_P (sym_ref);
229   if (machopic_symbol_defined_p (sym_ref))
230     return (function_p
231             ? MACHOPIC_DEFINED_FUNCTION : MACHOPIC_DEFINED_DATA);
232   else
233     return (function_p
234             ? MACHOPIC_UNDEFINED_FUNCTION : MACHOPIC_UNDEFINED_DATA);
235 }
236
237 #ifndef TARGET_FIX_AND_CONTINUE
238 #define TARGET_FIX_AND_CONTINUE 0
239 #endif
240
241 /* Indicate when fix-and-continue style code generation is being used
242    and when a reference to data should be indirected so that it can be
243    rebound in a new translation unit to reference the original instance
244    of that data.  Symbol names that are for code generation local to
245    the translation unit are bound to the new translation unit;
246    currently this means symbols that begin with L or _OBJC_;
247    otherwise, we indicate that an indirect reference should be made to
248    permit the runtime to rebind new instances of the translation unit
249    to the original instance of the data.  */
250
251 static int
252 indirect_data (rtx sym_ref)
253 {
254   int lprefix;
255   const char *name;
256
257   /* If we aren't generating fix-and-continue code, don't do anything
258      special.  */
259   if (TARGET_FIX_AND_CONTINUE == 0)
260     return 0;
261
262   /* Otherwise, all symbol except symbols that begin with L or _OBJC_
263      are indirected.  Symbols that begin with L and _OBJC_ are always
264      bound to the current translation unit as they are used for
265      generated local data of the translation unit.  */
266
267   name = XSTR (sym_ref, 0);
268
269   lprefix = (((name[0] == '*' || name[0] == '&')
270               && (name[1] == 'L' || (name[1] == '"' && name[2] == 'L')))
271              || (strncmp (name, "_OBJC_", 6) == 0));
272
273   return ! lprefix;
274 }
275
276
277 static int
278 machopic_data_defined_p (rtx sym_ref)
279 {
280   if (indirect_data (sym_ref))
281     return 0;
282
283   switch (machopic_classify_symbol (sym_ref))
284     {
285     case MACHOPIC_DEFINED_DATA:
286     case MACHOPIC_DEFINED_FUNCTION:
287       return 1;
288     default:
289       return 0;
290     }
291 }
292
293 void
294 machopic_define_symbol (rtx mem)
295 {
296   rtx sym_ref;
297
298   gcc_assert (GET_CODE (mem) == MEM);
299   sym_ref = XEXP (mem, 0);
300   SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
301 }
302
303 /* Return either ORIG or:
304
305      (const:P (unspec:P [ORIG] UNSPEC_MACHOPIC_OFFSET))
306
307    depending on MACHO_DYNAMIC_NO_PIC_P.  */
308 rtx
309 machopic_gen_offset (rtx orig)
310 {
311   if (MACHO_DYNAMIC_NO_PIC_P)
312     return orig;
313   else
314     {
315       /* Play games to avoid marking the function as needing pic if we
316          are being called as part of the cost-estimation process.  */
317       if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
318         crtl->uses_pic_offset_table = 1;
319       orig = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, orig),
320                              UNSPEC_MACHOPIC_OFFSET);
321       return gen_rtx_CONST (Pmode, orig);
322     }
323 }
324
325 static GTY(()) const char * function_base_func_name;
326 static GTY(()) int current_pic_label_num;
327
328 void
329 machopic_output_function_base_name (FILE *file)
330 {
331   const char *current_name;
332
333   /* If dynamic-no-pic is on, we should not get here.  */
334   gcc_assert (!MACHO_DYNAMIC_NO_PIC_P);
335   /* When we are generating _get_pc thunks within stubs, there is no current
336      function.  */
337   if (current_function_decl)
338     {
339       current_name =
340         IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl));
341       if (function_base_func_name != current_name)
342         {
343           ++current_pic_label_num;
344           function_base_func_name = current_name;
345         }
346     }
347   else
348     {
349       ++current_pic_label_num;
350       function_base_func_name = "L_machopic_stub_dummy";
351     }
352   fprintf (file, "L%011d$pb", current_pic_label_num);
353 }
354
355 /* The suffix attached to non-lazy pointer symbols.  */
356 #define NON_LAZY_POINTER_SUFFIX "$non_lazy_ptr"
357 /* The suffix attached to stub symbols.  */
358 #define STUB_SUFFIX "$stub"
359
360 typedef struct GTY (()) machopic_indirection
361 {
362   /* The SYMBOL_REF for the entity referenced.  */
363   rtx symbol;
364   /* The name of the stub or non-lazy pointer.  */
365   const char * ptr_name;
366   /* True iff this entry is for a stub (as opposed to a non-lazy
367      pointer).  */
368   bool stub_p;
369   /* True iff this stub or pointer pointer has been referenced.  */
370   bool used;
371 } machopic_indirection;
372
373 /* A table mapping stub names and non-lazy pointer names to
374    SYMBOL_REFs for the stubbed-to and pointed-to entities.  */
375
376 static GTY ((param_is (struct machopic_indirection))) htab_t
377   machopic_indirections;
378
379 /* Return a hash value for a SLOT in the indirections hash table.  */
380
381 static hashval_t
382 machopic_indirection_hash (const void *slot)
383 {
384   const machopic_indirection *p = (const machopic_indirection *) slot;
385   return htab_hash_string (p->ptr_name);
386 }
387
388 /* Returns true if the KEY is the same as that associated with
389    SLOT.  */
390
391 static int
392 machopic_indirection_eq (const void *slot, const void *key)
393 {
394   return strcmp (((const machopic_indirection *) slot)->ptr_name,
395                  (const char *) key) == 0;
396 }
397
398 /* Return the name of the non-lazy pointer (if STUB_P is false) or
399    stub (if STUB_B is true) corresponding to the given name.  */
400
401 const char *
402 machopic_indirection_name (rtx sym_ref, bool stub_p)
403 {
404   char *buffer;
405   const char *name = XSTR (sym_ref, 0);
406   size_t namelen = strlen (name);
407   machopic_indirection *p;
408   void ** slot;
409   bool needs_quotes;
410   const char *suffix;
411   const char *prefix = user_label_prefix;
412   const char *quote = "";
413   tree id;
414
415   id = maybe_get_identifier (name);
416   if (id)
417     {
418       tree id_orig = id;
419
420       while (IDENTIFIER_TRANSPARENT_ALIAS (id))
421         id = TREE_CHAIN (id);
422       if (id != id_orig)
423         {
424           name = IDENTIFIER_POINTER (id);
425           namelen = strlen (name);
426         }
427     }
428
429   if (name[0] == '*')
430     {
431       prefix = "";
432       ++name;
433       --namelen;
434     }
435
436   needs_quotes = name_needs_quotes (name);
437   if (needs_quotes)
438     {
439       quote = "\"";
440     }
441
442   if (stub_p)
443     suffix = STUB_SUFFIX;
444   else
445     suffix = NON_LAZY_POINTER_SUFFIX;
446
447   buffer = XALLOCAVEC (char, strlen ("&L")
448                    + strlen (prefix)
449                    + namelen
450                    + strlen (suffix)
451                    + 2 * strlen (quote)
452                    + 1 /* '\0' */);
453
454   /* Construct the name of the non-lazy pointer or stub.  */
455   sprintf (buffer, "&%sL%s%s%s%s", quote, prefix, name, suffix, quote);
456
457   if (!machopic_indirections)
458     machopic_indirections = htab_create_ggc (37,
459                                              machopic_indirection_hash,
460                                              machopic_indirection_eq,
461                                              /*htab_del=*/NULL);
462
463   slot = htab_find_slot_with_hash (machopic_indirections, buffer,
464                                    htab_hash_string (buffer), INSERT);
465   if (*slot)
466     {
467       p = (machopic_indirection *) *slot;
468     }
469   else
470     {
471       p = ggc_alloc_machopic_indirection ();
472       p->symbol = sym_ref;
473       p->ptr_name = xstrdup (buffer);
474       p->stub_p = stub_p;
475       p->used = false;
476       *slot = p;
477     }
478
479   return p->ptr_name;
480 }
481
482 /* Return the name of the stub for the mcount function.  */
483
484 const char*
485 machopic_mcount_stub_name (void)
486 {
487   rtx symbol = gen_rtx_SYMBOL_REF (Pmode, "*mcount");
488   return machopic_indirection_name (symbol, /*stub_p=*/true);
489 }
490
491 /* If NAME is the name of a stub or a non-lazy pointer , mark the stub
492    or non-lazy pointer as used -- and mark the object to which the
493    pointer/stub refers as used as well, since the pointer/stub will
494    emit a reference to it.  */
495
496 void
497 machopic_validate_stub_or_non_lazy_ptr (const char *name)
498 {
499   machopic_indirection *p;
500
501   p = ((machopic_indirection *)
502        (htab_find_with_hash (machopic_indirections, name,
503                              htab_hash_string (name))));
504   if (p && ! p->used)
505     {
506       const char *real_name;
507       tree id;
508
509       p->used = true;
510
511       /* Do what output_addr_const will do when we actually call it.  */
512       if (SYMBOL_REF_DECL (p->symbol))
513         mark_decl_referenced (SYMBOL_REF_DECL (p->symbol));
514
515       real_name = targetm.strip_name_encoding (XSTR (p->symbol, 0));
516
517       id = maybe_get_identifier (real_name);
518       if (id)
519         mark_referenced (id);
520     }
521 }
522
523 /* Transform ORIG, which may be any data source, to the corresponding
524    source using indirections.  */
525
526 rtx
527 machopic_indirect_data_reference (rtx orig, rtx reg)
528 {
529   rtx ptr_ref = orig;
530
531   if (! MACHOPIC_INDIRECT)
532     return orig;
533
534   if (GET_CODE (orig) == SYMBOL_REF)
535     {
536       int defined = machopic_data_defined_p (orig);
537
538       if (defined && MACHO_DYNAMIC_NO_PIC_P)
539         {
540           if (DARWIN_PPC)
541             {
542           /* Create a new register for CSE opportunities.  */
543           rtx hi_reg = (!can_create_pseudo_p () ? reg : gen_reg_rtx (Pmode));
544           emit_insn (gen_macho_high (hi_reg, orig));
545           emit_insn (gen_macho_low (reg, hi_reg, orig));
546               return reg;
547             }
548           else if (DARWIN_X86)
549             return orig;
550           else
551            /* some other cpu -- writeme!  */
552            gcc_unreachable ();
553         }
554       else if (defined)
555         {
556           rtx offset = NULL;
557           if (DARWIN_PPC || HAVE_lo_sum)
558             offset = machopic_gen_offset (orig);
559
560           if (DARWIN_PPC)
561             {
562           rtx hi_sum_reg = (!can_create_pseudo_p ()
563                             ? reg
564                             : gen_reg_rtx (Pmode));
565
566           gcc_assert (reg);
567
568           emit_insn (gen_rtx_SET (Pmode, hi_sum_reg,
569                               gen_rtx_PLUS (Pmode, pic_offset_table_rtx,
570                                        gen_rtx_HIGH (Pmode, offset))));
571           emit_insn (gen_rtx_SET (Pmode, reg,
572                                   gen_rtx_LO_SUM (Pmode, hi_sum_reg,
573                                                   copy_rtx (offset))));
574
575           orig = reg;
576             }
577           else if (HAVE_lo_sum)
578             {
579           gcc_assert (reg);
580
581           emit_insn (gen_rtx_SET (VOIDmode, reg,
582                                   gen_rtx_HIGH (Pmode, offset)));
583           emit_insn (gen_rtx_SET (VOIDmode, reg,
584                                   gen_rtx_LO_SUM (Pmode, reg,
585                                                   copy_rtx (offset))));
586           emit_use (pic_offset_table_rtx);
587
588           orig = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, reg);
589             }
590           return orig;
591         }
592
593       ptr_ref = (gen_rtx_SYMBOL_REF
594                  (Pmode,
595                   machopic_indirection_name (orig, /*stub_p=*/false)));
596
597       SYMBOL_REF_DATA (ptr_ref) = SYMBOL_REF_DATA (orig);
598
599       ptr_ref = gen_const_mem (Pmode, ptr_ref);
600       machopic_define_symbol (ptr_ref);
601
602       if (DARWIN_X86 
603           && reg 
604           && MACHO_DYNAMIC_NO_PIC_P)
605         {
606             emit_insn (gen_rtx_SET (Pmode, reg, ptr_ref));
607             ptr_ref = reg;
608         }
609
610       return ptr_ref;
611     }
612   else if (GET_CODE (orig) == CONST)
613     {
614       /* If "(const (plus ...", walk the PLUS and return that result.
615          PLUS processing (below) will restore the "(const ..." if
616          appropriate.  */
617       if (GET_CODE (XEXP (orig, 0)) == PLUS)
618         return machopic_indirect_data_reference (XEXP (orig, 0), reg);
619       else 
620         return orig;
621     }
622   else if (GET_CODE (orig) == MEM)
623     {
624       XEXP (ptr_ref, 0) = 
625                 machopic_indirect_data_reference (XEXP (orig, 0), reg);
626       return ptr_ref;
627     }
628   else if (GET_CODE (orig) == PLUS)
629     {
630       rtx base, result;
631       /* When the target is i386, this code prevents crashes due to the
632         compiler's ignorance on how to move the PIC base register to
633         other registers.  (The reload phase sometimes introduces such
634         insns.)  */
635       if (GET_CODE (XEXP (orig, 0)) == REG
636            && REGNO (XEXP (orig, 0)) == PIC_OFFSET_TABLE_REGNUM
637            /* Prevent the same register from being erroneously used
638               as both the base and index registers.  */
639            && (DARWIN_X86 && (GET_CODE (XEXP (orig, 1)) == CONST))
640            && reg)
641         {
642           emit_move_insn (reg, XEXP (orig, 0));
643           XEXP (ptr_ref, 0) = reg;
644           return ptr_ref;
645         }
646
647       /* Legitimize both operands of the PLUS.  */
648       base = machopic_indirect_data_reference (XEXP (orig, 0), reg);
649       orig = machopic_indirect_data_reference (XEXP (orig, 1),
650                                                (base == reg ? 0 : reg));
651       if (MACHOPIC_INDIRECT && (GET_CODE (orig) == CONST_INT))
652         result = plus_constant (base, INTVAL (orig));
653       else
654         result = gen_rtx_PLUS (Pmode, base, orig);
655
656       if (MACHOPIC_JUST_INDIRECT && GET_CODE (base) == MEM)
657         {
658           if (reg)
659             {
660               emit_move_insn (reg, result);
661               result = reg;
662             }
663           else
664             {
665               result = force_reg (GET_MODE (result), result);
666             }
667         }
668
669       return result;
670     }
671   return ptr_ref;
672 }
673
674 /* Transform TARGET (a MEM), which is a function call target, to the
675    corresponding symbol_stub if necessary.  Return a new MEM.  */
676
677 rtx
678 machopic_indirect_call_target (rtx target)
679 {
680   if (! darwin_emit_branch_islands)
681     return target;
682
683   if (GET_CODE (target) != MEM)
684     return target;
685
686   if (MACHOPIC_INDIRECT
687       && GET_CODE (XEXP (target, 0)) == SYMBOL_REF
688       && !(SYMBOL_REF_FLAGS (XEXP (target, 0))
689            & MACHO_SYMBOL_FLAG_DEFINED))
690     {
691       rtx sym_ref = XEXP (target, 0);
692       const char *stub_name = machopic_indirection_name (sym_ref,
693                                                          /*stub_p=*/true);
694       enum machine_mode mode = GET_MODE (sym_ref);
695
696       XEXP (target, 0) = gen_rtx_SYMBOL_REF (mode, stub_name);
697       SYMBOL_REF_DATA (XEXP (target, 0)) = SYMBOL_REF_DATA (sym_ref);
698       MEM_READONLY_P (target) = 1;
699       MEM_NOTRAP_P (target) = 1;
700     }
701
702   return target;
703 }
704
705 rtx
706 machopic_legitimize_pic_address (rtx orig, enum machine_mode mode, rtx reg)
707 {
708   rtx pic_ref = orig;
709
710   if (! MACHOPIC_INDIRECT)
711     return orig;
712
713   /* First handle a simple SYMBOL_REF or LABEL_REF */
714   if (GET_CODE (orig) == LABEL_REF
715       || (GET_CODE (orig) == SYMBOL_REF
716           ))
717     {
718       /* addr(foo) = &func+(foo-func) */
719       orig = machopic_indirect_data_reference (orig, reg);
720
721       if (GET_CODE (orig) == PLUS
722           && GET_CODE (XEXP (orig, 0)) == REG)
723         {
724           if (reg == 0)
725             return force_reg (mode, orig);
726
727           emit_move_insn (reg, orig);
728           return reg;
729         }
730
731       if (GET_CODE (orig) == MEM)
732         {
733           if (reg == 0)
734             {
735               gcc_assert (!reload_in_progress);
736               reg = gen_reg_rtx (Pmode);
737             }
738
739 #if HAVE_lo_sum
740           if (MACHO_DYNAMIC_NO_PIC_P
741               && (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
742                   || GET_CODE (XEXP (orig, 0)) == LABEL_REF))
743             {
744 #if defined (TARGET_TOC)        /* ppc  */
745               rtx temp_reg = (!can_create_pseudo_p ()
746                               ? reg :
747                               gen_reg_rtx (Pmode));
748               rtx asym = XEXP (orig, 0);
749               rtx mem;
750
751               emit_insn (gen_macho_high (temp_reg, asym));
752               mem = gen_const_mem (GET_MODE (orig),
753                                    gen_rtx_LO_SUM (Pmode, temp_reg,
754                                                    copy_rtx (asym)));
755               emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
756 #else
757               /* Some other CPU -- WriteMe! but right now there are no other
758                  platforms that can use dynamic-no-pic  */
759               gcc_unreachable ();
760 #endif
761               pic_ref = reg;
762             }
763           else
764           if (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
765               || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
766             {
767               rtx offset = machopic_gen_offset (XEXP (orig, 0));
768 #if defined (TARGET_TOC) /* i.e., PowerPC */
769               /* Generating a new reg may expose opportunities for
770                  common subexpression elimination.  */
771               rtx hi_sum_reg = (!can_create_pseudo_p ()
772                                 ? reg
773                                 : gen_reg_rtx (Pmode));
774               rtx mem;
775               rtx insn;
776               rtx sum;
777
778               sum = gen_rtx_HIGH (Pmode, offset);
779               if (! MACHO_DYNAMIC_NO_PIC_P)
780                 sum = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, sum);
781
782               emit_insn (gen_rtx_SET (Pmode, hi_sum_reg, sum));
783
784               mem = gen_const_mem (GET_MODE (orig),
785                                   gen_rtx_LO_SUM (Pmode,
786                                                   hi_sum_reg,
787                                                   copy_rtx (offset)));
788               insn = emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
789               set_unique_reg_note (insn, REG_EQUAL, pic_ref);
790
791               pic_ref = reg;
792 #else
793               emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
794
795               emit_insn (gen_rtx_SET (VOIDmode, reg,
796                                       gen_rtx_HIGH (Pmode,
797                                                     gen_rtx_CONST (Pmode,
798                                                                    offset))));
799               emit_insn (gen_rtx_SET (VOIDmode, reg,
800                                   gen_rtx_LO_SUM (Pmode, reg,
801                                            gen_rtx_CONST (Pmode,
802                                                           copy_rtx (offset)))));
803               pic_ref = gen_rtx_PLUS (Pmode,
804                                       pic_offset_table_rtx, reg);
805 #endif
806             }
807           else
808 #endif  /* HAVE_lo_sum */
809             {
810               rtx pic = pic_offset_table_rtx;
811               if (GET_CODE (pic) != REG)
812                 {
813                   emit_move_insn (reg, pic);
814                   pic = reg;
815                 }
816 #if 0
817               emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
818 #endif
819
820               if (reload_in_progress)
821                 df_set_regs_ever_live (REGNO (pic), true);
822               pic_ref = gen_rtx_PLUS (Pmode, pic,
823                                       machopic_gen_offset (XEXP (orig, 0)));
824             }
825
826 #if !defined (TARGET_TOC)
827           emit_move_insn (reg, pic_ref);
828           pic_ref = gen_const_mem (GET_MODE (orig), reg);
829 #endif
830         }
831       else
832         {
833
834 #if HAVE_lo_sum
835           if (GET_CODE (orig) == SYMBOL_REF
836               || GET_CODE (orig) == LABEL_REF)
837             {
838               rtx offset = machopic_gen_offset (orig);
839 #if defined (TARGET_TOC) /* i.e., PowerPC */
840               rtx hi_sum_reg;
841
842               if (reg == 0)
843                 {
844                   gcc_assert (!reload_in_progress);
845                   reg = gen_reg_rtx (Pmode);
846                 }
847
848               hi_sum_reg = reg;
849
850               emit_insn (gen_rtx_SET (Pmode, hi_sum_reg,
851                                       (MACHO_DYNAMIC_NO_PIC_P)
852                                       ? gen_rtx_HIGH (Pmode, offset)
853                                       : gen_rtx_PLUS (Pmode,
854                                                       pic_offset_table_rtx,
855                                                       gen_rtx_HIGH (Pmode,
856                                                                     offset))));
857               emit_insn (gen_rtx_SET (VOIDmode, reg,
858                                       gen_rtx_LO_SUM (Pmode,
859                                                       hi_sum_reg,
860                                                       copy_rtx (offset))));
861               pic_ref = reg;
862 #else
863               emit_insn (gen_rtx_SET (VOIDmode, reg,
864                                       gen_rtx_HIGH (Pmode, offset)));
865               emit_insn (gen_rtx_SET (VOIDmode, reg,
866                                       gen_rtx_LO_SUM (Pmode, reg,
867                                                       copy_rtx (offset))));
868               pic_ref = gen_rtx_PLUS (Pmode,
869                                       pic_offset_table_rtx, reg);
870 #endif
871             }
872           else
873 #endif  /*  HAVE_lo_sum  */
874             {
875               if (REG_P (orig)
876                   || GET_CODE (orig) == SUBREG)
877                 {
878                   return orig;
879                 }
880               else
881                 {
882                   rtx pic = pic_offset_table_rtx;
883                   if (GET_CODE (pic) != REG)
884                     {
885                       emit_move_insn (reg, pic);
886                       pic = reg;
887                     }
888 #if 0
889                   emit_use (pic_offset_table_rtx);
890 #endif
891                   if (reload_in_progress)
892                     df_set_regs_ever_live (REGNO (pic), true);
893                   pic_ref = gen_rtx_PLUS (Pmode,
894                                           pic,
895                                           machopic_gen_offset (orig));
896                 }
897             }
898         }
899
900       if (GET_CODE (pic_ref) != REG)
901         {
902           if (reg != 0)
903             {
904               emit_move_insn (reg, pic_ref);
905               return reg;
906             }
907           else
908             {
909               return force_reg (mode, pic_ref);
910             }
911         }
912       else
913         {
914           return pic_ref;
915         }
916     }
917
918   else if (GET_CODE (orig) == SYMBOL_REF)
919     return orig;
920
921   else if (GET_CODE (orig) == PLUS
922            && (GET_CODE (XEXP (orig, 0)) == MEM
923                || GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
924                || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
925            && XEXP (orig, 0) != pic_offset_table_rtx
926            && GET_CODE (XEXP (orig, 1)) != REG)
927
928     {
929       rtx base;
930       int is_complex = (GET_CODE (XEXP (orig, 0)) == MEM);
931
932       base = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
933       orig = machopic_legitimize_pic_address (XEXP (orig, 1),
934                                               Pmode, (base == reg ? 0 : reg));
935       if (GET_CODE (orig) == CONST_INT)
936         {
937           pic_ref = plus_constant (base, INTVAL (orig));
938           is_complex = 1;
939         }
940       else
941         pic_ref = gen_rtx_PLUS (Pmode, base, orig);
942
943       if (reg && is_complex)
944         {
945           emit_move_insn (reg, pic_ref);
946           pic_ref = reg;
947         }
948       /* Likewise, should we set special REG_NOTEs here?  */
949     }
950
951   else if (GET_CODE (orig) == CONST)
952     {
953       return machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
954     }
955
956   else if (GET_CODE (orig) == MEM
957            && GET_CODE (XEXP (orig, 0)) == SYMBOL_REF)
958     {
959       rtx addr = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
960       addr = replace_equiv_address (orig, addr);
961       emit_move_insn (reg, addr);
962       pic_ref = reg;
963     }
964
965   return pic_ref;
966 }
967
968 /* Output the stub or non-lazy pointer in *SLOT, if it has been used.
969    DATA is the FILE* for assembly output.  Called from
970    htab_traverse.  */
971
972 static int
973 machopic_output_indirection (void **slot, void *data)
974 {
975   machopic_indirection *p = *((machopic_indirection **) slot);
976   FILE *asm_out_file = (FILE *) data;
977   rtx symbol;
978   const char *sym_name;
979   const char *ptr_name;
980
981   if (!p->used)
982     return 1;
983
984   symbol = p->symbol;
985   sym_name = XSTR (symbol, 0);
986   ptr_name = p->ptr_name;
987
988   if (p->stub_p)
989     {
990       char *sym;
991       char *stub;
992       tree id;
993
994       id = maybe_get_identifier (sym_name);
995       if (id)
996         {
997           tree id_orig = id;
998
999           while (IDENTIFIER_TRANSPARENT_ALIAS (id))
1000             id = TREE_CHAIN (id);
1001           if (id != id_orig)
1002             sym_name = IDENTIFIER_POINTER (id);
1003         }
1004
1005       sym = XALLOCAVEC (char, strlen (sym_name) + 2);
1006       if (sym_name[0] == '*' || sym_name[0] == '&')
1007         strcpy (sym, sym_name + 1);
1008       else if (sym_name[0] == '-' || sym_name[0] == '+')
1009         strcpy (sym, sym_name);
1010       else
1011         sprintf (sym, "%s%s", user_label_prefix, sym_name);
1012
1013       stub = XALLOCAVEC (char, strlen (ptr_name) + 2);
1014       if (ptr_name[0] == '*' || ptr_name[0] == '&')
1015         strcpy (stub, ptr_name + 1);
1016       else
1017         sprintf (stub, "%s%s", user_label_prefix, ptr_name);
1018
1019       machopic_output_stub (asm_out_file, sym, stub);
1020     }
1021   else if (! indirect_data (symbol)
1022            && (machopic_symbol_defined_p (symbol)
1023                || SYMBOL_REF_LOCAL_P (symbol)))
1024     {
1025       switch_to_section (data_section);
1026       assemble_align (GET_MODE_ALIGNMENT (Pmode));
1027       assemble_label (asm_out_file, ptr_name);
1028       assemble_integer (gen_rtx_SYMBOL_REF (Pmode, sym_name),
1029                         GET_MODE_SIZE (Pmode),
1030                         GET_MODE_ALIGNMENT (Pmode), 1);
1031     }
1032   else
1033     {
1034       rtx init = const0_rtx;
1035
1036       switch_to_section (darwin_sections[machopic_nl_symbol_ptr_section]);
1037
1038       /* Mach-O symbols are passed around in code through indirect
1039          references and the original symbol_ref hasn't passed through
1040          the generic handling and reference-catching in
1041          output_operand, so we need to manually mark weak references
1042          as such.  */
1043       if (SYMBOL_REF_WEAK (symbol))
1044         {
1045           tree decl = SYMBOL_REF_DECL (symbol);
1046           gcc_assert (DECL_P (decl));
1047
1048           if (decl != NULL_TREE
1049               && DECL_EXTERNAL (decl) && TREE_PUBLIC (decl)
1050               /* Handle only actual external-only definitions, not
1051                  e.g. extern inline code or variables for which
1052                  storage has been allocated.  */
1053               && !TREE_STATIC (decl))
1054             {
1055               fputs ("\t.weak_reference ", asm_out_file);
1056               assemble_name (asm_out_file, sym_name);
1057               fputc ('\n', asm_out_file);
1058             }
1059         }
1060
1061       assemble_name (asm_out_file, ptr_name);
1062       fprintf (asm_out_file, ":\n");
1063
1064       fprintf (asm_out_file, "\t.indirect_symbol ");
1065       assemble_name (asm_out_file, sym_name);
1066       fprintf (asm_out_file, "\n");
1067
1068       /* Variables that are marked with MACHO_SYMBOL_STATIC need to
1069          have their symbol name instead of 0 in the second entry of
1070          the non-lazy symbol pointer data structure when they are
1071          defined.  This allows the runtime to rebind newer instances
1072          of the translation unit with the original instance of the
1073          symbol.  */
1074
1075       if ((SYMBOL_REF_FLAGS (symbol) & MACHO_SYMBOL_STATIC)
1076           && machopic_symbol_defined_p (symbol))
1077         init = gen_rtx_SYMBOL_REF (Pmode, sym_name);
1078
1079       assemble_integer (init, GET_MODE_SIZE (Pmode),
1080                         GET_MODE_ALIGNMENT (Pmode), 1);
1081     }
1082
1083   return 1;
1084 }
1085
1086 void
1087 machopic_finish (FILE *asm_out_file)
1088 {
1089   if (machopic_indirections)
1090     htab_traverse_noresize (machopic_indirections,
1091                             machopic_output_indirection,
1092                             asm_out_file);
1093 }
1094
1095 int
1096 machopic_operand_p (rtx op)
1097 {
1098   if (MACHOPIC_JUST_INDIRECT)
1099     return (GET_CODE (op) == SYMBOL_REF
1100             && machopic_symbol_defined_p (op));
1101   else
1102     return (GET_CODE (op) == CONST
1103             && GET_CODE (XEXP (op, 0)) == UNSPEC
1104             && XINT (XEXP (op, 0), 1) == UNSPEC_MACHOPIC_OFFSET);
1105 }
1106
1107 /* This function records whether a given name corresponds to a defined
1108    or undefined function or variable, for machopic_classify_ident to
1109    use later.  */
1110
1111 void
1112 darwin_encode_section_info (tree decl, rtx rtl, int first ATTRIBUTE_UNUSED)
1113 {
1114   rtx sym_ref;
1115
1116   /* Do the standard encoding things first.  */
1117   default_encode_section_info (decl, rtl, first);
1118
1119   if (TREE_CODE (decl) != FUNCTION_DECL && TREE_CODE (decl) != VAR_DECL)
1120     return;
1121
1122   sym_ref = XEXP (rtl, 0);
1123   if (TREE_CODE (decl) == VAR_DECL)
1124     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_VARIABLE;
1125
1126   if (!DECL_EXTERNAL (decl)
1127       && (!TREE_PUBLIC (decl) || !DECL_WEAK (decl))
1128       && ! lookup_attribute ("weakref", DECL_ATTRIBUTES (decl))
1129       && ((TREE_STATIC (decl)
1130            && (!DECL_COMMON (decl) || !TREE_PUBLIC (decl)))
1131           || (!DECL_COMMON (decl) && DECL_INITIAL (decl)
1132               && DECL_INITIAL (decl) != error_mark_node)))
1133     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
1134
1135   if (! TREE_PUBLIC (decl))
1136     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_STATIC;
1137 }
1138
1139 void
1140 darwin_mark_decl_preserved (const char *name)
1141 {
1142   fprintf (asm_out_file, "\t.no_dead_strip ");
1143   assemble_name (asm_out_file, name);
1144   fputc ('\n', asm_out_file);
1145 }
1146
1147 static section *
1148 darwin_text_section (int reloc, int weak)
1149 {
1150   if (reloc)
1151     return (weak
1152             ? darwin_sections[text_unlikely_coal_section]
1153             : unlikely_text_section ());
1154   else
1155     return (weak
1156             ? darwin_sections[text_coal_section]
1157             : text_section);
1158 }
1159
1160 static section *
1161 darwin_rodata_section (int weak, bool zsize)
1162 {
1163   return (weak
1164           ? darwin_sections[const_coal_section]
1165           : (zsize ? darwin_sections[zobj_const_section]
1166                    : darwin_sections[const_section]));
1167 }
1168
1169 static section *
1170 darwin_mergeable_string_section (tree exp,
1171                                  unsigned HOST_WIDE_INT align)
1172 {
1173   if (flag_merge_constants
1174       && TREE_CODE (exp) == STRING_CST
1175       && TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
1176       && align <= 256
1177       && (int_size_in_bytes (TREE_TYPE (exp))
1178           == TREE_STRING_LENGTH (exp))
1179       && ((size_t) TREE_STRING_LENGTH (exp)
1180           == strlen (TREE_STRING_POINTER (exp)) + 1))
1181     return darwin_sections[cstring_section];
1182
1183   if (DARWIN_SECTION_ANCHORS && flag_section_anchors
1184       && TREE_CODE (exp) == STRING_CST
1185       && TREE_STRING_LENGTH (exp) == 0)
1186     return darwin_sections[zobj_const_section];
1187
1188   return readonly_data_section;
1189 }
1190
1191 #ifndef HAVE_GAS_LITERAL16
1192 #define HAVE_GAS_LITERAL16 0
1193 #endif
1194
1195 static section *
1196 darwin_mergeable_constant_section (tree exp,
1197                                    unsigned HOST_WIDE_INT align,
1198                                    bool zsize)
1199 {
1200   enum machine_mode mode = DECL_MODE (exp);
1201   unsigned int modesize = GET_MODE_BITSIZE (mode);
1202
1203   if (DARWIN_SECTION_ANCHORS 
1204       && flag_section_anchors 
1205       && zsize)
1206     return darwin_sections[zobj_const_section];
1207
1208   if (flag_merge_constants
1209       && mode != VOIDmode
1210       && mode != BLKmode
1211       && modesize <= align
1212       && align >= 8
1213       && align <= 256
1214       && (align & (align -1)) == 0)
1215     {
1216       tree size = TYPE_SIZE_UNIT (TREE_TYPE (exp));
1217
1218       if (TREE_CODE (size) == INTEGER_CST
1219           && TREE_INT_CST_LOW (size) == 4
1220           && TREE_INT_CST_HIGH (size) == 0)
1221         return darwin_sections[literal4_section];
1222       else if (TREE_CODE (size) == INTEGER_CST
1223                && TREE_INT_CST_LOW (size) == 8
1224                && TREE_INT_CST_HIGH (size) == 0)
1225         return darwin_sections[literal8_section];
1226       else if (HAVE_GAS_LITERAL16
1227                && TARGET_64BIT
1228                && TREE_CODE (size) == INTEGER_CST
1229                && TREE_INT_CST_LOW (size) == 16
1230                && TREE_INT_CST_HIGH (size) == 0)
1231         return darwin_sections[literal16_section];
1232       else
1233         return readonly_data_section;
1234     }
1235
1236   return readonly_data_section;
1237 }
1238
1239 int
1240 machopic_reloc_rw_mask (void)
1241 {
1242   return MACHOPIC_INDIRECT ? 3 : 0;
1243 }
1244
1245 section *
1246 machopic_select_section (tree decl,
1247                          int reloc,
1248                          unsigned HOST_WIDE_INT align)
1249 {
1250   bool zsize, one, weak, ro;
1251   section *base_section = NULL;
1252
1253   weak = (DECL_P (decl)
1254           && DECL_WEAK (decl)
1255           && !lookup_attribute ("weak_import", DECL_ATTRIBUTES (decl)));
1256
1257   zsize = (DECL_P (decl) 
1258            && (TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == CONST_DECL) 
1259            && tree_low_cst (DECL_SIZE_UNIT (decl), 1) == 0);
1260
1261   one = DECL_P (decl) 
1262         && TREE_CODE (decl) == VAR_DECL 
1263         && DECL_ONE_ONLY (decl);
1264
1265   ro = TREE_READONLY (decl) || TREE_CONSTANT (decl) ;
1266
1267   switch (categorize_decl_for_section (decl, reloc))
1268     {
1269     case SECCAT_TEXT:
1270       {
1271         struct cgraph_node *node;
1272         if (decl && TREE_CODE (decl) == FUNCTION_DECL
1273             && (node = cgraph_get_node (decl)) != NULL)
1274           base_section = darwin_function_section (decl,
1275                                                   node->frequency,
1276                                                   node->only_called_at_startup,
1277                                                   node->only_called_at_exit);
1278         if (!base_section)
1279           base_section = darwin_text_section (reloc, weak);
1280       }
1281       break;
1282
1283     case SECCAT_RODATA:
1284     case SECCAT_SRODATA:
1285       base_section = darwin_rodata_section (weak, zsize);
1286       break;
1287
1288     case SECCAT_RODATA_MERGE_STR:
1289       base_section = darwin_mergeable_string_section (decl, align);
1290       break;
1291
1292     case SECCAT_RODATA_MERGE_STR_INIT:
1293       base_section = darwin_mergeable_string_section (DECL_INITIAL (decl), align);
1294       break;
1295
1296     case SECCAT_RODATA_MERGE_CONST:
1297       base_section =  darwin_mergeable_constant_section (decl, align, zsize);
1298       break;
1299
1300     case SECCAT_DATA:
1301     case SECCAT_DATA_REL:
1302     case SECCAT_DATA_REL_LOCAL:
1303     case SECCAT_DATA_REL_RO:
1304     case SECCAT_DATA_REL_RO_LOCAL:
1305     case SECCAT_SDATA:
1306     case SECCAT_TDATA:
1307       if (weak || one)
1308         {
1309           if (ro)
1310             base_section = darwin_sections[const_data_coal_section];
1311           else 
1312             base_section = darwin_sections[data_coal_section];
1313         }
1314       else if (DARWIN_SECTION_ANCHORS 
1315                && flag_section_anchors
1316                && zsize)
1317         {
1318           /* If we're doing section anchors, then punt zero-sized objects into
1319              their own sections so that they don't interfere with offset
1320              computation for the remaining vars.  This does not need to be done
1321              for stuff in mergeable sections, since these are ineligible for 
1322              anchors.  */
1323           if (ro)
1324             base_section = darwin_sections[zobj_const_data_section];
1325           else
1326             base_section = darwin_sections[zobj_data_section];
1327         }
1328       else if (ro)
1329         base_section = darwin_sections[const_data_section];
1330       else
1331         base_section = data_section;
1332       break;
1333     case SECCAT_BSS:
1334     case SECCAT_SBSS:
1335     case SECCAT_TBSS:
1336       if (weak || one) 
1337         base_section = darwin_sections[data_coal_section];
1338       else
1339         {
1340           if (!TREE_PUBLIC (decl))
1341             base_section = lcomm_section;
1342           else if (bss_noswitch_section)
1343             base_section = bss_noswitch_section;
1344           else
1345             base_section = data_section;
1346         }
1347       break;
1348
1349     default:
1350       gcc_unreachable ();
1351     }
1352
1353   /* Darwin weird special cases.  */
1354   if (TREE_CODE (decl) == CONSTRUCTOR
1355       && TREE_TYPE (decl)
1356       && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
1357       && TYPE_NAME (TREE_TYPE (decl)))
1358     {
1359       tree name = TYPE_NAME (TREE_TYPE (decl));
1360       if (TREE_CODE (name) == TYPE_DECL)
1361         name = DECL_NAME (name);
1362
1363       if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_ObjCString"))
1364         {
1365           if (flag_next_runtime)
1366             return darwin_sections[objc_constant_string_object_section];
1367           else
1368             return darwin_sections[objc_string_object_section];
1369         }
1370       else if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_CFString"))
1371         return darwin_sections[cfstring_constant_object_section];
1372       else
1373         return base_section;
1374     }
1375   else if (TREE_CODE (decl) == VAR_DECL
1376            && DECL_NAME (decl)
1377            && TREE_CODE (DECL_NAME (decl)) == IDENTIFIER_NODE
1378            && IDENTIFIER_POINTER (DECL_NAME (decl))
1379            && !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)), "_OBJC_", 6))
1380     {
1381       const char *name = IDENTIFIER_POINTER (DECL_NAME (decl));
1382
1383       /* We shall assert that zero-sized objects are an error in ObjC 
1384          meta-data.  */
1385       gcc_assert (tree_low_cst (DECL_SIZE_UNIT (decl), 1) != 0);
1386       if (!strncmp (name, "_OBJC_CLASS_METHODS_", 20))
1387         return darwin_sections[objc_cls_meth_section];
1388       else if (!strncmp (name, "_OBJC_INSTANCE_METHODS_", 23))
1389         return darwin_sections[objc_inst_meth_section];
1390       else if (!strncmp (name, "_OBJC_CATEGORY_CLASS_METHODS_", 29))
1391         return darwin_sections[objc_cat_cls_meth_section];
1392       else if (!strncmp (name, "_OBJC_CATEGORY_INSTANCE_METHODS_", 32))
1393         return darwin_sections[objc_cat_inst_meth_section];
1394       else if (!strncmp (name, "_OBJC_CLASS_VARIABLES_", 22))
1395         return darwin_sections[objc_class_vars_section];
1396       else if (!strncmp (name, "_OBJC_INSTANCE_VARIABLES_", 25))
1397         return darwin_sections[objc_instance_vars_section];
1398       else if (!strncmp (name, "_OBJC_CLASS_PROTOCOLS_", 22))
1399         return darwin_sections[objc_cat_cls_meth_section];
1400       else if (!strncmp (name, "_OBJC_CLASS_NAME_", 17))
1401         return darwin_sections[objc_class_names_section];
1402       else if (!strncmp (name, "_OBJC_METH_VAR_NAME_", 20))
1403         return darwin_sections[objc_meth_var_names_section];
1404       else if (!strncmp (name, "_OBJC_METH_VAR_TYPE_", 20))
1405         return darwin_sections[objc_meth_var_types_section];
1406       else if (!strncmp (name, "_OBJC_CLASS_REFERENCES", 22))
1407         return darwin_sections[objc_cls_refs_section];
1408       else if (!strncmp (name, "_OBJC_CLASS_", 12))
1409         return darwin_sections[objc_class_section];
1410       else if (!strncmp (name, "_OBJC_METACLASS_", 16))
1411         return darwin_sections[objc_meta_class_section];
1412       else if (!strncmp (name, "_OBJC_CATEGORY_", 15))
1413         return darwin_sections[objc_category_section];
1414       else if (!strncmp (name, "_OBJC_SELECTOR_REFERENCES", 25))
1415         return darwin_sections[objc_selector_refs_section];
1416       else if (!strncmp (name, "_OBJC_SELECTOR_FIXUP", 20))
1417         return darwin_sections[objc_selector_fixup_section];
1418       else if (!strncmp (name, "_OBJC_SYMBOLS", 13))
1419         return darwin_sections[objc_symbols_section];
1420       else if (!strncmp (name, "_OBJC_MODULES", 13))
1421         return darwin_sections[objc_module_info_section];
1422       else if (!strncmp (name, "_OBJC_IMAGE_INFO", 16))
1423         return darwin_sections[objc_image_info_section];
1424       else if (!strncmp (name, "_OBJC_PROTOCOL_INSTANCE_METHODS_", 32))
1425         return darwin_sections[objc_cat_inst_meth_section];
1426       else if (!strncmp (name, "_OBJC_PROTOCOL_CLASS_METHODS_", 29))
1427         return darwin_sections[objc_cat_cls_meth_section];
1428       else if (!strncmp (name, "_OBJC_PROTOCOL_REFS_", 20))
1429         return darwin_sections[objc_cat_cls_meth_section];
1430       else if (!strncmp (name, "_OBJC_PROTOCOL_", 15))
1431         return darwin_sections[objc_protocol_section];
1432       else
1433         return base_section;
1434     }
1435
1436   return base_section;
1437 }
1438
1439 /* This can be called with address expressions as "rtx".
1440    They must go in "const".  */
1441
1442 section *
1443 machopic_select_rtx_section (enum machine_mode mode, rtx x,
1444                              unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
1445 {
1446   if (GET_MODE_SIZE (mode) == 8
1447       && (GET_CODE (x) == CONST_INT
1448           || GET_CODE (x) == CONST_DOUBLE))
1449     return darwin_sections[literal8_section];
1450   else if (GET_MODE_SIZE (mode) == 4
1451            && (GET_CODE (x) == CONST_INT
1452                || GET_CODE (x) == CONST_DOUBLE))
1453     return darwin_sections[literal4_section];
1454   else if (HAVE_GAS_LITERAL16
1455            && TARGET_64BIT
1456            && GET_MODE_SIZE (mode) == 16
1457            && (GET_CODE (x) == CONST_INT
1458                || GET_CODE (x) == CONST_DOUBLE
1459                || GET_CODE (x) == CONST_VECTOR))
1460     return darwin_sections[literal16_section];
1461   else if (MACHOPIC_INDIRECT
1462            && (GET_CODE (x) == SYMBOL_REF
1463                || GET_CODE (x) == CONST
1464                || GET_CODE (x) == LABEL_REF))
1465     return darwin_sections[const_data_section];
1466   else
1467     return darwin_sections[const_section];
1468 }
1469
1470 void
1471 machopic_asm_out_constructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1472 {
1473   if (MACHOPIC_INDIRECT)
1474     switch_to_section (darwin_sections[mod_init_section]);
1475   else
1476     switch_to_section (darwin_sections[constructor_section]);
1477   assemble_align (POINTER_SIZE);
1478   assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1479
1480   if (! MACHOPIC_INDIRECT)
1481     fprintf (asm_out_file, ".reference .constructors_used\n");
1482 }
1483
1484 void
1485 machopic_asm_out_destructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1486 {
1487   if (MACHOPIC_INDIRECT)
1488     switch_to_section (darwin_sections[mod_term_section]);
1489   else
1490     switch_to_section (darwin_sections[destructor_section]);
1491   assemble_align (POINTER_SIZE);
1492   assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1493
1494   if (! MACHOPIC_INDIRECT)
1495     fprintf (asm_out_file, ".reference .destructors_used\n");
1496 }
1497
1498 void
1499 darwin_globalize_label (FILE *stream, const char *name)
1500 {
1501   if (!!strncmp (name, "_OBJC_", 6))
1502     default_globalize_label (stream, name);
1503 }
1504
1505 /* This routine returns non-zero if 'name' starts with the special objective-c 
1506    anonymous file-scope static name.  It accommodates c++'s mangling of such 
1507    symbols (in this case the symbols will have form _ZL{d}*_OBJC_* d=digit).  */
1508    
1509 int 
1510 darwin_label_is_anonymous_local_objc_name (const char *name)
1511 {
1512   const unsigned char *p = (const unsigned char *) name;
1513   if (*p != '_')
1514     return 0;
1515   if (p[1] == 'Z' && p[2] == 'L')
1516   {
1517     p += 3;
1518     while (*p >= '0' && *p <= '9')
1519       p++;
1520   }
1521   return (!strncmp ((const char *)p, "_OBJC_", 6));
1522 }
1523
1524 /* LTO support for Mach-O.  */
1525
1526 /* Section names for LTO sections.  */
1527 static unsigned int lto_section_names_offset = 0;
1528
1529 /* This is the obstack which we use to allocate the many strings.  */
1530 static struct obstack lto_section_names_obstack;
1531
1532 /* Segment name for LTO sections.  */
1533 #define LTO_SEGMENT_NAME "__GNU_LTO"
1534
1535 /* Section name for LTO section names section.  */
1536 #define LTO_NAMES_SECTION "__section_names"
1537
1538 /* File to temporarily store LTO data.  This is appended to asm_out_file
1539    in darwin_end_file.  */
1540 static FILE *lto_asm_out_file, *saved_asm_out_file;
1541 static char *lto_asm_out_name;
1542
1543 /* Prepare asm_out_file for LTO output.  For darwin, this means hiding
1544    asm_out_file and switching to an alternative output file.  */
1545 void
1546 darwin_asm_lto_start (void)
1547 {
1548   gcc_assert (! saved_asm_out_file);
1549   saved_asm_out_file = asm_out_file;
1550   if (! lto_asm_out_name)
1551     lto_asm_out_name = make_temp_file (".lto.s");
1552   lto_asm_out_file = fopen (lto_asm_out_name, "a");
1553   if (lto_asm_out_file == NULL)
1554     fatal_error ("failed to open temporary file %s for LTO output",
1555                  lto_asm_out_name);
1556   asm_out_file = lto_asm_out_file;
1557 }
1558
1559 /* Restore asm_out_file.  */
1560 void
1561 darwin_asm_lto_end (void)
1562 {
1563   gcc_assert (saved_asm_out_file);
1564   fclose (lto_asm_out_file);
1565   asm_out_file = saved_asm_out_file;
1566   saved_asm_out_file = NULL;
1567 }
1568
1569 static void
1570 darwin_asm_dwarf_section (const char *name, unsigned int flags, tree decl);
1571
1572 /*  Called for the TARGET_ASM_NAMED_SECTION hook.  */
1573
1574 void
1575 darwin_asm_named_section (const char *name,
1576                           unsigned int flags,
1577                           tree decl ATTRIBUTE_UNUSED)
1578 {
1579   /* LTO sections go in a special segment __GNU_LTO.  We want to replace the
1580      section name with something we can use to represent arbitrary-length
1581      names (section names in Mach-O are at most 16 characters long).  */
1582   if (strncmp (name, LTO_SECTION_NAME_PREFIX,
1583                strlen (LTO_SECTION_NAME_PREFIX)) == 0)
1584     {
1585       /* We expect certain flags to be set...  */
1586       gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
1587                   == (SECTION_DEBUG | SECTION_NAMED));
1588
1589       /* Add the section name to the things to output when we end the
1590          current assembler output file.
1591          This is all not very efficient, but that doesn't matter -- this
1592          shouldn't be a hot path in the compiler...  */
1593       obstack_1grow (&lto_section_names_obstack, '\t');
1594       obstack_grow (&lto_section_names_obstack, ".ascii ", 7);
1595       obstack_1grow (&lto_section_names_obstack, '"');
1596       obstack_grow (&lto_section_names_obstack, name, strlen (name));
1597       obstack_grow (&lto_section_names_obstack, "\\0\"\n", 4);
1598
1599       /* Output the dummy section name.  */
1600       fprintf (asm_out_file, "\t# %s\n", name);
1601       fprintf (asm_out_file, "\t.section %s,__%08X,regular,debug\n",
1602                LTO_SEGMENT_NAME, lto_section_names_offset);
1603
1604       /* Update the offset for the next section name.  Make sure we stay
1605          within reasonable length.  */  
1606       lto_section_names_offset += strlen (name) + 1;
1607       gcc_assert (lto_section_names_offset > 0
1608                   && lto_section_names_offset < ((unsigned) 1 << 31));
1609     }
1610   else if (strncmp (name, "__DWARF,", 8) == 0)
1611     darwin_asm_dwarf_section (name, flags, decl);
1612   else
1613     fprintf (asm_out_file, "\t.section %s\n", name);
1614 }
1615
1616 void
1617 darwin_unique_section (tree decl ATTRIBUTE_UNUSED, int reloc ATTRIBUTE_UNUSED)
1618 {
1619   /* Darwin does not use unique sections.  */
1620 }
1621
1622 /* Handle __attribute__ ((apple_kext_compatibility)).
1623    This only applies to darwin kexts for 2.95 compatibility -- it shrinks the
1624    vtable for classes with this attribute (and their descendants) by not
1625    outputting the new 3.0 nondeleting destructor.  This means that such
1626    objects CANNOT be allocated on the stack or as globals UNLESS they have
1627    a completely empty `operator delete'.
1628    Luckily, this fits in with the Darwin kext model.
1629
1630    This attribute also disables gcc3's potential overlaying of derived
1631    class data members on the padding at the end of the base class.  */
1632
1633 tree
1634 darwin_handle_kext_attribute (tree *node, tree name,
1635                               tree args ATTRIBUTE_UNUSED,
1636                               int flags ATTRIBUTE_UNUSED,
1637                               bool *no_add_attrs)
1638 {
1639   /* APPLE KEXT stuff -- only applies with pure static C++ code.  */
1640   if (! TARGET_KEXTABI)
1641     {
1642       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
1643                "only when compiling a kext", name);
1644
1645       *no_add_attrs = true;
1646     }
1647   else if (TREE_CODE (*node) != RECORD_TYPE)
1648     {
1649       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
1650                "only to C++ classes", name);
1651
1652       *no_add_attrs = true;
1653     }
1654
1655   return NULL_TREE;
1656 }
1657
1658 /* Handle a "weak_import" attribute; arguments as in
1659    struct attribute_spec.handler.  */
1660
1661 tree
1662 darwin_handle_weak_import_attribute (tree *node, tree name,
1663                                      tree ARG_UNUSED (args),
1664                                      int ARG_UNUSED (flags),
1665                                      bool * no_add_attrs)
1666 {
1667   if (TREE_CODE (*node) != FUNCTION_DECL && TREE_CODE (*node) != VAR_DECL)
1668     {
1669       warning (OPT_Wattributes, "%qE attribute ignored",
1670                name);
1671       *no_add_attrs = true;
1672     }
1673   else
1674     declare_weak (*node);
1675
1676   return NULL_TREE;
1677 }
1678
1679 /* Emit a label for an FDE, making it global and/or weak if appropriate.
1680    The third parameter is nonzero if this is for exception handling.
1681    The fourth parameter is nonzero if this is just a placeholder for an
1682    FDE that we are omitting. */
1683
1684 void
1685 darwin_emit_unwind_label (FILE *file, tree decl, int for_eh, int empty)
1686 {
1687   char *lab;
1688
1689   if (! for_eh)
1690     return;
1691
1692   lab = concat (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)), ".eh", NULL);
1693
1694   if (TREE_PUBLIC (decl))
1695     {
1696       targetm.asm_out.globalize_label (file, lab);
1697       if (DECL_VISIBILITY (decl) == VISIBILITY_HIDDEN)
1698         {
1699           fputs ("\t.private_extern ", file);
1700           assemble_name (file, lab);
1701           fputc ('\n', file);
1702         }
1703     }
1704
1705   if (DECL_WEAK (decl))
1706     {
1707       fputs ("\t.weak_definition ", file);
1708       assemble_name (file, lab);
1709       fputc ('\n', file);
1710     }
1711
1712   assemble_name (file, lab);
1713   if (empty)
1714     {
1715       fputs (" = 0\n", file);
1716
1717       /* Mark the absolute .eh and .eh1 style labels as needed to
1718          ensure that we don't dead code strip them and keep such
1719          labels from another instantiation point until we can fix this
1720          properly with group comdat support.  */
1721       darwin_mark_decl_preserved (lab);
1722     }
1723   else
1724     fputs (":\n", file);
1725
1726   free (lab);
1727 }
1728
1729 static GTY(()) unsigned long except_table_label_num;
1730
1731 void
1732 darwin_emit_except_table_label (FILE *file)
1733 {
1734   char section_start_label[30];
1735
1736   ASM_GENERATE_INTERNAL_LABEL (section_start_label, "GCC_except_table",
1737                                except_table_label_num++);
1738   ASM_OUTPUT_LABEL (file, section_start_label);
1739 }
1740 /* Generate a PC-relative reference to a Mach-O non-lazy-symbol.  */
1741
1742 void
1743 darwin_non_lazy_pcrel (FILE *file, rtx addr)
1744 {
1745   const char *nlp_name;
1746
1747   gcc_assert (GET_CODE (addr) == SYMBOL_REF);
1748
1749   nlp_name = machopic_indirection_name (addr, /*stub_p=*/false);
1750   fputs ("\t.long\t", file);
1751   ASM_OUTPUT_LABELREF (file, nlp_name);
1752   fputs ("-.", file);
1753 }
1754
1755 /* If this is uncommented, details of each allocation will be printed
1756    in the asm right before the actual code.  WARNING - this will cause some
1757    test-suite fails (since the printout will contain items that some tests
1758    are not expecting) -- so don't leave it on by default (it bloats the
1759    asm too).  */
1760 /*#define DEBUG_DARWIN_MEM_ALLOCATORS*/
1761
1762 /* The first two of these routines are ostensibly just intended to put
1763    names into the asm.  However, they are both hijacked in order to ensure
1764    that zero-sized items do not make their way into the output.  Consequently,
1765    we also need to make these participate in provisions for dealing with
1766    such items in section anchors.  */
1767
1768 /* The implementation of ASM_DECLARE_OBJECT_NAME.  */
1769 /* The RTTI data (e.g., __ti4name) is common and public (and static),
1770    but it does need to be referenced via indirect PIC data pointers.
1771    The machopic_define_symbol calls are telling the machopic subsystem
1772    that the name *is* defined in this module, so it doesn't need to
1773    make them indirect.  */
1774 void 
1775 darwin_asm_declare_object_name (FILE *file, 
1776                                 const char *nam, tree decl)
1777 {
1778   const char *xname = nam;
1779   unsigned HOST_WIDE_INT size;
1780   bool local_def, weak;
1781
1782   weak = (DECL_P (decl)
1783           && DECL_WEAK (decl)
1784           && !lookup_attribute ("weak_import", 
1785                                  DECL_ATTRIBUTES (decl)));
1786
1787   local_def = DECL_INITIAL (decl) || (TREE_STATIC (decl) 
1788                                       && (!DECL_COMMON (decl) 
1789                                           || !TREE_PUBLIC (decl)));
1790
1791   if (GET_CODE (XEXP (DECL_RTL (decl), 0)) != SYMBOL_REF)
1792     xname = IDENTIFIER_POINTER (DECL_NAME (decl));
1793
1794   if (local_def)
1795     {
1796       (* targetm.encode_section_info) (decl, DECL_RTL (decl), false);
1797       if (!weak)
1798         machopic_define_symbol (DECL_RTL (decl));
1799     }
1800
1801   size = tree_low_cst (DECL_SIZE_UNIT (decl), 1);
1802
1803 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
1804 fprintf (file, "# dadon: %s %s (%llu, %u) local %d weak %d"
1805                " stat %d com %d pub %d t-const %d t-ro %d init %lx\n",
1806         xname, (TREE_CODE (decl) == VAR_DECL?"var":"const"), 
1807         (unsigned long long)size, DECL_ALIGN (decl), local_def, 
1808         DECL_WEAK (decl), TREE_STATIC (decl), DECL_COMMON (decl),
1809         TREE_PUBLIC (decl), TREE_CONSTANT (decl), TREE_READONLY (decl),
1810         (unsigned long)DECL_INITIAL (decl)); 
1811 #endif
1812
1813   /* Darwin needs help to support local zero-sized objects. 
1814      They must be made at least one byte, and the section containing must be
1815      marked as unsuitable for section-anchors (see storage allocators below).
1816      
1817      For non-zero objects this output is handled by varasm.c.
1818   */
1819   if (!size)
1820     {
1821       unsigned int l2align = 0;
1822
1823       /* The align must be honored, even for zero-sized.  */
1824       if (DECL_ALIGN (decl))
1825         {
1826           l2align = floor_log2 (DECL_ALIGN (decl) / BITS_PER_UNIT);
1827           fprintf (file, "\t.align\t%u\n", l2align);
1828         }
1829
1830       ASM_OUTPUT_LABEL (file, xname);
1831       size = 1;
1832       fprintf (file, "\t.space\t"HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
1833
1834       /* Check that we've correctly picked up the zero-sized item and placed it
1835          properly.  */
1836       gcc_assert ((!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
1837                   || (in_section 
1838                       && (in_section->common.flags & SECTION_NO_ANCHOR)));
1839     }
1840   else
1841     ASM_OUTPUT_LABEL (file, xname);
1842 }
1843
1844 /* The implementation of ASM_DECLARE_CONSTANT_NAME.  */
1845 void
1846 darwin_asm_declare_constant_name (FILE *file, const char *name,
1847                                   const_tree exp ATTRIBUTE_UNUSED,
1848                                   HOST_WIDE_INT size)
1849 {
1850   assemble_label (file, name);
1851   /* As for other items, we need at least one byte.  */
1852   if (!size)
1853     {
1854       fputs ("\t.space\t1\n", file);
1855       /* Check that we've correctly picked up the zero-sized item and placed it
1856          properly.  */
1857       gcc_assert ((!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
1858                   || (in_section 
1859                       && (in_section->common.flags & SECTION_NO_ANCHOR)));
1860     }
1861 }
1862
1863 /* Darwin storage allocators.
1864
1865    Zerofill sections are desirable for large blank data since, otherwise, these
1866    data bloat objects (PR33210).
1867
1868    However, section anchors don't work in .zerofill sections (one cannot switch
1869    to a zerofill section).  Ergo, for Darwin targets using section anchors we need
1870    to put (at least some) data into 'normal' switchable sections.
1871
1872    Here we set a relatively arbitrary value for the size of an object to trigger
1873    zerofill when section anchors are enabled (anything bigger than a page for
1874    current Darwin implementations).  FIXME: there ought to be some objective way
1875    to make this choice.
1876
1877    When section anchor are off this is ignored anyway.  */
1878
1879 #define BYTES_ZFILL 4096
1880
1881 /* Emit a chunk of data for items coalesced by the linker.  */
1882 static void
1883 darwin_emit_weak_or_comdat (FILE *fp, tree decl, const char *name,
1884                                   unsigned HOST_WIDE_INT size, 
1885                                   unsigned int align)
1886 {
1887   /* Since the sections used here are coalesed, they will not be eligible
1888      for section anchors, and therefore we don't need to break that out.  */
1889  if (TREE_READONLY (decl) || TREE_CONSTANT (decl))
1890     switch_to_section (darwin_sections[const_data_coal_section]);
1891   else
1892     switch_to_section (darwin_sections[data_coal_section]);
1893
1894   /* To be consistent, we'll allow darwin_asm_declare_object_name to assemble
1895      the align info for zero-sized items... but do it here otherwise.  */
1896   if (size && align)
1897     fprintf (fp, "\t.align\t%d\n", floor_log2 (align / BITS_PER_UNIT));
1898
1899   if (TREE_PUBLIC (decl))
1900     darwin_globalize_label (fp, name);
1901
1902   /* ... and we let it deal with outputting one byte of zero for them too.  */ 
1903   darwin_asm_declare_object_name (fp, name, decl);
1904   if (size)
1905     assemble_zeros (size);
1906 }
1907
1908 /* This routine emits 'local' storage:
1909
1910    When Section Anchors are off this routine emits .zerofill commands in 
1911    sections named for their alignment.
1912
1913    When Section Anchors are on, smaller (non-zero-sized) items are placed in
1914    the .static_data section so that the section anchoring system can see them.
1915    Larger items are still placed in .zerofill sections, addressing PR33210.
1916    The routine has no checking - it is all assumed to be done by the caller.
1917 */
1918 static void
1919 darwin_emit_local_bss (FILE *fp, tree decl, const char *name, 
1920                         unsigned HOST_WIDE_INT size, 
1921                         unsigned int l2align)
1922 {
1923    /* FIXME: We have a fudge to make this work with Java even when the target does
1924    not use sections anchors -- Java seems to need at least one small item in a
1925    non-zerofill segment.   */
1926    if ((DARWIN_SECTION_ANCHORS && flag_section_anchors && size < BYTES_ZFILL)
1927        || (size && size <= 2))
1928     {
1929       /* Put smaller objects in _static_data, where the section anchors system
1930          can get them.
1931          However, if they are zero-sized punt them to yet a different section
1932          (that is not allowed to participate in anchoring).  */
1933       if (!size)
1934         {
1935           fputs ("\t.section\t__DATA,__zobj_bss\n", fp);
1936           in_section = darwin_sections[zobj_bss_section];
1937           size = 1;
1938         }
1939       else
1940         {
1941           fputs ("\t.static_data\n", fp);
1942           in_section = darwin_sections[static_data_section];
1943         }
1944
1945       if (l2align)
1946         fprintf (fp, "\t.align\t%u\n", l2align);
1947
1948       assemble_name (fp, name);        
1949       fprintf (fp, ":\n\t.space\t"HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
1950     }
1951   else 
1952     {
1953       /* When we are on a non-section anchor target, we can get zero-sized
1954          items here.  However, all we need to do is to bump them to one byte
1955          and the section alignment will take care of the rest.  */
1956       char secnam[64];
1957       unsigned int flags ;
1958       snprintf (secnam, 64, "__DATA,__%sbss%u", ((size)?"":"zo_"), 
1959                                                 (unsigned) l2align);
1960       /* We can't anchor (yet, if ever) in zerofill sections, because we can't
1961          switch to them and emit a label.  */
1962       flags = SECTION_BSS|SECTION_WRITE|SECTION_NO_ANCHOR;
1963       in_section = get_section (secnam, flags, NULL);
1964       fprintf (fp, "\t.zerofill %s,", secnam);
1965       assemble_name (fp, name);
1966       if (!size)
1967         size = 1;
1968
1969       if (l2align)
1970         fprintf (fp, ","HOST_WIDE_INT_PRINT_UNSIGNED",%u\n",
1971                  size, (unsigned) l2align);
1972       else
1973         fprintf (fp, ","HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
1974     }
1975
1976   (*targetm.encode_section_info) (decl, DECL_RTL (decl), false);
1977   /* This is defined as a file-scope var, so we know to notify machopic.  */
1978   machopic_define_symbol (DECL_RTL (decl));
1979 }
1980
1981 /* Emit a chunk of common.  */
1982 static void
1983 darwin_emit_common (FILE *fp, const char *name,
1984                     unsigned HOST_WIDE_INT size, unsigned int align) 
1985 {
1986   unsigned HOST_WIDE_INT rounded;
1987   unsigned int l2align;
1988
1989   /* Earlier systems complain if the alignment exceeds the page size. 
1990      The magic number is 4096 * 8 - hard-coded for legacy systems.  */
1991   if (!emit_aligned_common && (align > 32768UL))
1992     align = 4096UL; /* In units.  */
1993   else
1994     align /= BITS_PER_UNIT;
1995
1996   /* Make sure we have a meaningful align.  */
1997   if (!align)
1998     align = 1;
1999
2000   /* For earlier toolchains, we need to emit the var as a rounded size to 
2001      tell ld the alignment.  */
2002   if (size < align) 
2003     rounded = align;
2004   else
2005     rounded = (size + (align-1)) & ~(align-1);
2006
2007   l2align = floor_log2 (align);
2008   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2009
2010   in_section = comm_section;
2011   /* We mustn't allow multiple public symbols to share an address when using
2012      the normal OSX toolchain.  */
2013   if (!size)
2014     {
2015       /* Put at least one byte.  */
2016       size = 1;
2017       /* This section can no longer participate in section anchoring.  */
2018       comm_section->common.flags |= SECTION_NO_ANCHOR;
2019     }
2020
2021   fputs ("\t.comm\t", fp);
2022   assemble_name (fp, name);
2023   fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED, 
2024            emit_aligned_common?size:rounded);
2025   if (l2align && emit_aligned_common)
2026     fprintf (fp, ",%u", l2align);
2027   fputs ("\n", fp);
2028 }
2029
2030 /* Output a var which is all zero - into aligned BSS sections, common, lcomm
2031    or coalescable data sections (for weak or comdat) as appropriate.  */
2032
2033 void
2034 darwin_output_aligned_bss (FILE *fp, tree decl, const char *name,
2035                           unsigned HOST_WIDE_INT size, unsigned int align)
2036 {
2037   unsigned int l2align;
2038   bool one, pub, weak;
2039
2040   pub = TREE_PUBLIC (decl);
2041   one = DECL_ONE_ONLY (decl);
2042   weak = (DECL_P (decl)
2043           && DECL_WEAK (decl)
2044           && !lookup_attribute ("weak_import", 
2045                                  DECL_ATTRIBUTES (decl)));
2046
2047 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2048 fprintf (fp, "# albss: %s (%lld,%d) ro %d cst %d stat %d com %d"
2049              " pub %d weak %d one %d init %lx\n",
2050         name, (long long)size, (int)align, TREE_READONLY (decl), 
2051         TREE_CONSTANT (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2052         pub, weak, one, (unsigned long)DECL_INITIAL (decl)); 
2053 #endif
2054
2055   /* Check that any initializer is valid.  */
2056   gcc_assert ((DECL_INITIAL (decl) == NULL) 
2057                || (DECL_INITIAL (decl) == error_mark_node) 
2058                || initializer_zerop (DECL_INITIAL (decl)));
2059
2060   gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2061   gcc_assert (!DECL_COMMON (decl));
2062
2063   /*  Pick up the correct alignment.  */
2064   if (!size || !align)
2065     align = DECL_ALIGN (decl);
2066
2067   l2align = floor_log2 (align / BITS_PER_UNIT);
2068   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2069   
2070   last_assemble_variable_decl = decl;
2071
2072   /* We would rather not have to check this here - but it seems that we might
2073      be passed a decl that should be in coalesced space.  */
2074   if (one || weak)
2075     {
2076       /* Weak or COMDAT objects are put in mergeable sections.  */
2077       darwin_emit_weak_or_comdat (fp, decl, name, size, 
2078                                         DECL_ALIGN (decl));
2079       return;
2080     } 
2081
2082   /* If this is not public, then emit according to local rules.  */
2083   if (!pub)
2084     {
2085       darwin_emit_local_bss (fp, decl, name, size, l2align);    
2086       return;
2087     }
2088
2089   /* So we have a public symbol (small item fudge for Java, see above).  */
2090   if ((DARWIN_SECTION_ANCHORS && flag_section_anchors && size < BYTES_ZFILL) 
2091        || (size && size <= 2))
2092     {
2093       /* Put smaller objects in data, where the section anchors system can get
2094          them.  However, if they are zero-sized punt them to yet a different 
2095          section (that is not allowed to participate in anchoring).  */
2096       if (!size)
2097         {
2098           fputs ("\t.section\t__DATA,__zobj_data\n", fp);
2099           in_section = darwin_sections[zobj_data_section];
2100           size = 1;
2101         }
2102       else
2103         {
2104           fputs ("\t.data\n", fp);
2105           in_section = data_section;
2106         }
2107
2108       if (l2align)
2109         fprintf (fp, "\t.align\t%u\n", l2align);
2110
2111       assemble_name (fp, name);
2112       fprintf (fp, ":\n\t.space\t"HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2113     }
2114   else 
2115     {
2116       char secnam[64];
2117       unsigned int flags ;
2118       /* When we are on a non-section anchor target, we can get zero-sized
2119          items here.  However, all we need to do is to bump them to one byte
2120          and the section alignment will take care of the rest.  */
2121       snprintf (secnam, 64, "__DATA,__%spu_bss%u", ((size)?"":"zo_"), l2align);
2122
2123       /* We can't anchor in zerofill sections, because we can't switch
2124          to them and emit a label.  */
2125       flags = SECTION_BSS|SECTION_WRITE|SECTION_NO_ANCHOR;
2126       in_section = get_section (secnam, flags, NULL);
2127       fprintf (fp, "\t.zerofill %s,", secnam);
2128       assemble_name (fp, name);
2129       if (!size)
2130         size = 1;
2131
2132       if (l2align)
2133         fprintf (fp, ","HOST_WIDE_INT_PRINT_UNSIGNED",%u\n", size, l2align);
2134       else
2135         fprintf (fp, ","HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2136     }
2137   (* targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2138 }
2139
2140 /* Output a chunk of common, with alignment specified (where the target
2141    supports this).  */
2142 void
2143 darwin_asm_output_aligned_decl_common (FILE *fp, tree decl, const char *name,
2144                                        unsigned HOST_WIDE_INT size, 
2145                                        unsigned int align)
2146 {
2147   unsigned int l2align;
2148   bool one, weak;
2149   /* No corresponding var.  */
2150   if (decl==NULL)
2151     {
2152 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2153 fprintf (fp, "# adcom: %s (%d,%d) decl=0x0\n", name, (int)size, (int)align); 
2154 #endif
2155       darwin_emit_common (fp, name, size, align);
2156       return;
2157     }
2158
2159   one = DECL_ONE_ONLY (decl);
2160   weak = (DECL_P (decl)
2161           && DECL_WEAK (decl)
2162           && !lookup_attribute ("weak_import", 
2163                                  DECL_ATTRIBUTES (decl)));
2164
2165 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2166 fprintf (fp, "# adcom: %s (%lld,%d) ro %d cst %d stat %d com %d pub %d"
2167              " weak %d one %d init %lx\n",
2168         name,  (long long)size, (int)align, TREE_READONLY (decl), 
2169         TREE_CONSTANT (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2170         TREE_PUBLIC (decl), weak, one, (unsigned long)DECL_INITIAL (decl)); 
2171 #endif
2172
2173   /* We shouldn't be messing with this if the decl has a section name.  */
2174   gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2175
2176   /* We would rather not have to check this here - but it seems that we might
2177      be passed a decl that should be in coalesced space.  */
2178   if (one || weak)
2179     {
2180       /* Weak or COMDAT objects are put in mergable sections.  */
2181       darwin_emit_weak_or_comdat (fp, decl, name, size, 
2182                                         DECL_ALIGN (decl));
2183       return;
2184     } 
2185
2186   /* We should only get here for DECL_COMMON, with a zero init (and, in 
2187      principle, only for public symbols too - although we deal with local
2188      ones below).  */
2189
2190   /* Check the initializer is OK.  */
2191   gcc_assert (DECL_COMMON (decl) 
2192               && ((DECL_INITIAL (decl) == NULL) 
2193                || (DECL_INITIAL (decl) == error_mark_node) 
2194                || initializer_zerop (DECL_INITIAL (decl))));
2195
2196   last_assemble_variable_decl = decl;
2197
2198   if (!size || !align) 
2199     align = DECL_ALIGN (decl);
2200
2201   l2align = floor_log2 (align / BITS_PER_UNIT);
2202   /* Check we aren't asking for more aligment than the platform allows.  */
2203   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2204
2205   if (TREE_PUBLIC (decl) != 0)
2206     darwin_emit_common (fp, name, size, align);
2207   else
2208     darwin_emit_local_bss (fp, decl, name, size, l2align);      
2209 }
2210
2211 /* Output a chunk of BSS with alignment specfied.  */
2212 void
2213 darwin_asm_output_aligned_decl_local (FILE *fp, tree decl, const char *name, 
2214                                       unsigned HOST_WIDE_INT size, 
2215                                       unsigned int align)
2216 {
2217   unsigned long l2align;
2218   bool one, weak;
2219
2220   one = DECL_ONE_ONLY (decl);
2221   weak = (DECL_P (decl)
2222           && DECL_WEAK (decl)
2223           && !lookup_attribute ("weak_import", 
2224                                  DECL_ATTRIBUTES (decl)));
2225
2226 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2227 fprintf (fp, "# adloc: %s (%lld,%d) ro %d cst %d stat %d one %d pub %d"
2228              " weak %d init %lx\n",
2229         name, (long long)size, (int)align, TREE_READONLY (decl), 
2230         TREE_CONSTANT (decl), TREE_STATIC (decl), one, TREE_PUBLIC (decl),
2231         weak , (unsigned long)DECL_INITIAL (decl)); 
2232 #endif
2233
2234   /* We shouldn't be messing with this if the decl has a section name.  */
2235   gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2236
2237   /* We would rather not have to check this here - but it seems that we might
2238      be passed a decl that should be in coalesced space.  */
2239   if (one || weak)
2240     {
2241       /* Weak or COMDAT objects are put in mergable sections.  */
2242       darwin_emit_weak_or_comdat (fp, decl, name, size, 
2243                                         DECL_ALIGN (decl));
2244       return;
2245     } 
2246
2247   /* .. and it should be suitable for placement in local mem.  */
2248   gcc_assert(!TREE_PUBLIC (decl) && !DECL_COMMON (decl));
2249   /* .. and any initializer must be all-zero.  */
2250   gcc_assert ((DECL_INITIAL (decl) == NULL) 
2251                || (DECL_INITIAL (decl) == error_mark_node) 
2252                || initializer_zerop (DECL_INITIAL (decl)));
2253
2254   last_assemble_variable_decl = decl;
2255
2256   if (!size || !align)
2257     align = DECL_ALIGN (decl);
2258
2259   l2align = floor_log2 (align / BITS_PER_UNIT);
2260   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2261
2262   darwin_emit_local_bss (fp, decl, name, size, l2align);
2263 }
2264
2265 /* Emit an assembler directive to set visibility for a symbol.  The
2266    only supported visibilities are VISIBILITY_DEFAULT and
2267    VISIBILITY_HIDDEN; the latter corresponds to Darwin's "private
2268    extern".  There is no MACH-O equivalent of ELF's
2269    VISIBILITY_INTERNAL or VISIBILITY_PROTECTED. */
2270
2271 void
2272 darwin_assemble_visibility (tree decl, int vis)
2273 {
2274   if (vis == VISIBILITY_DEFAULT)
2275     ;
2276   else if (vis == VISIBILITY_HIDDEN)
2277     {
2278       fputs ("\t.private_extern ", asm_out_file);
2279       assemble_name (asm_out_file,
2280                      (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))));
2281       fputs ("\n", asm_out_file);
2282     }
2283   else
2284     warning (OPT_Wattributes, "internal and protected visibility attributes "
2285              "not supported in this configuration; ignored");
2286 }
2287
2288 /* VEC Used by darwin_asm_dwarf_section.
2289    Maybe a hash tab would be better here - but the intention is that this is
2290    a very short list (fewer than 16 items) and each entry should (ideally, 
2291    eventually) only be presented once.
2292
2293    A structure to hold a dwarf debug section used entry.  */
2294
2295 typedef struct GTY(()) dwarf_sect_used_entry {
2296   const char *name;
2297   unsigned count;
2298 }
2299 dwarf_sect_used_entry;
2300
2301 DEF_VEC_O(dwarf_sect_used_entry);
2302 DEF_VEC_ALLOC_O(dwarf_sect_used_entry, gc);
2303
2304 /* A list of used __DWARF sections.  */
2305 static GTY (()) VEC (dwarf_sect_used_entry, gc) * dwarf_sect_names_table;
2306
2307 /* This is called when we are asked to assemble a named section and the 
2308    name begins with __DWARF,.  We keep a list of the section names (without
2309    the __DWARF, prefix) and use this to emit our required start label on the
2310    first switch to each section.  */
2311
2312 static void
2313 darwin_asm_dwarf_section (const char *name, unsigned int flags,
2314                           tree ARG_UNUSED (decl))
2315 {
2316   unsigned i;
2317   int namelen;
2318   const char * sname;
2319   dwarf_sect_used_entry *ref;
2320   bool found = false;
2321   gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
2322                     == (SECTION_DEBUG | SECTION_NAMED));
2323   /* We know that the name starts with __DWARF,  */
2324   sname = name + 8;
2325   namelen = strchr (sname, ',') - sname;
2326   gcc_assert (namelen);
2327   if (dwarf_sect_names_table == NULL)
2328     dwarf_sect_names_table = VEC_alloc (dwarf_sect_used_entry, gc, 16);
2329   else
2330     for (i = 0; 
2331          VEC_iterate (dwarf_sect_used_entry, dwarf_sect_names_table, i, ref);
2332          i++)
2333       {
2334         if (!ref)
2335           break;
2336         if (!strcmp (ref->name, sname))
2337           {
2338             found = true;
2339             ref->count++;
2340             break;
2341           }
2342       }
2343
2344   fprintf (asm_out_file, "\t.section %s\n", name);
2345   if (!found)
2346     {
2347       dwarf_sect_used_entry e;
2348       fprintf (asm_out_file, "Lsection%.*s:\n", namelen, sname);
2349       e.count = 1;
2350       e.name = xstrdup (sname);
2351       VEC_safe_push (dwarf_sect_used_entry, gc, dwarf_sect_names_table, &e);
2352     }
2353 }
2354
2355 /* Output a difference of two labels that will be an assembly time
2356    constant if the two labels are local.  (.long lab1-lab2 will be
2357    very different if lab1 is at the boundary between two sections; it
2358    will be relocated according to the second section, not the first,
2359    so one ends up with a difference between labels in different
2360    sections, which is bad in the dwarf2 eh context for instance.)  */
2361
2362 static int darwin_dwarf_label_counter;
2363
2364 void
2365 darwin_asm_output_dwarf_delta (FILE *file, int size,
2366                                const char *lab1, const char *lab2)
2367 {
2368   int islocaldiff = (lab1[0] == '*' && lab1[1] == 'L'
2369                      && lab2[0] == '*' && lab2[1] == 'L');
2370   const char *directive = (size == 8 ? ".quad" : ".long");
2371
2372   if (islocaldiff)
2373     fprintf (file, "\t.set L$set$%d,", darwin_dwarf_label_counter);
2374   else
2375     fprintf (file, "\t%s\t", directive);
2376
2377   assemble_name_raw (file, lab1);
2378   fprintf (file, "-");
2379   assemble_name_raw (file, lab2);
2380   if (islocaldiff)
2381     fprintf (file, "\n\t%s L$set$%d", directive, darwin_dwarf_label_counter++);
2382 }
2383
2384 /* Output an offset in a DWARF section on Darwin.  On Darwin, DWARF section
2385    offsets are not represented using relocs in .o files; either the
2386    section never leaves the .o file, or the linker or other tool is
2387    responsible for parsing the DWARF and updating the offsets.  */
2388
2389 void
2390 darwin_asm_output_dwarf_offset (FILE *file, int size, const char * lab,
2391                                 section *base)
2392 {
2393   char sname[64];
2394   int namelen;
2395
2396   gcc_assert (base->common.flags & SECTION_NAMED);
2397   gcc_assert (strncmp (base->named.name, "__DWARF,", 8) == 0);
2398   gcc_assert (strchr (base->named.name + 8, ','));
2399
2400   namelen = strchr (base->named.name + 8, ',') - (base->named.name + 8);
2401   sprintf (sname, "*Lsection%.*s", namelen, base->named.name + 8);
2402   darwin_asm_output_dwarf_delta (file, size, lab, sname);
2403 }
2404
2405 /* Called from the within the TARGET_ASM_FILE_START for each target. 
2406   Initialize the stuff we need for LTO long section names support.  */
2407
2408 void
2409 darwin_file_start (void)
2410 {
2411   /* We fill this obstack with the complete section text for the lto section
2412      names to write in darwin_file_end.  */
2413   obstack_init (&lto_section_names_obstack);
2414   lto_section_names_offset = 0;
2415 }
2416
2417 /* Called for the TARGET_ASM_FILE_END hook.
2418    Emit the mach-o pic indirection data, the lto data and, finally a flag
2419    to tell the linker that it can break the file object into sections and
2420    move those around for efficiency.  */
2421
2422 void
2423 darwin_file_end (void)
2424 {
2425   const char *lto_section_names;
2426
2427   machopic_finish (asm_out_file);
2428   if (strcmp (lang_hooks.name, "GNU C++") == 0)
2429     {
2430       switch_to_section (darwin_sections[constructor_section]);
2431       switch_to_section (darwin_sections[destructor_section]);
2432       ASM_OUTPUT_ALIGN (asm_out_file, 1);
2433     }
2434
2435   /* If there was LTO assembler output, append it to asm_out_file.  */
2436   if (lto_asm_out_name)
2437     {
2438       int n;
2439       char *buf, *lto_asm_txt;
2440
2441       /* Shouldn't be here if we failed to switch back.  */
2442       gcc_assert (! saved_asm_out_file);
2443
2444       lto_asm_out_file = fopen (lto_asm_out_name, "r");
2445       if (lto_asm_out_file == NULL)
2446         fatal_error ("failed to open temporary file %s with LTO output",
2447                      lto_asm_out_name);
2448       fseek (lto_asm_out_file, 0, SEEK_END);
2449       n = ftell (lto_asm_out_file);
2450       if (n > 0)
2451         {
2452           fseek (lto_asm_out_file, 0, SEEK_SET);
2453           lto_asm_txt = buf = (char *) xmalloc (n + 1);
2454           while (fgets (lto_asm_txt, n, lto_asm_out_file))
2455             fputs (lto_asm_txt, asm_out_file);
2456         }
2457
2458       /* Remove the temporary file.  */
2459       fclose (lto_asm_out_file);
2460       unlink_if_ordinary (lto_asm_out_name);
2461       free (lto_asm_out_name);
2462     }
2463
2464   /* Finish the LTO section names obstack.  Don't output anything if
2465      there are no recorded section names.  */
2466   obstack_1grow (&lto_section_names_obstack, '\0');
2467   lto_section_names = XOBFINISH (&lto_section_names_obstack, const char *);
2468   if (strlen (lto_section_names) > 0)
2469     {
2470       fprintf (asm_out_file,
2471                "\t.section %s,%s,regular,debug\n",
2472                LTO_SEGMENT_NAME, LTO_NAMES_SECTION);
2473       fprintf (asm_out_file,
2474                "\t# Section names in %s are offsets into this table\n",
2475                LTO_SEGMENT_NAME);
2476       fprintf (asm_out_file, "%s\n", lto_section_names);
2477     }
2478   obstack_free (&lto_section_names_obstack, NULL);
2479
2480   /* If we have section anchors, then we must prevent the linker from
2481      re-arranging data.  */
2482   if (!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
2483     fprintf (asm_out_file, "\t.subsections_via_symbols\n");
2484 }
2485
2486 /* TODO: Add a language hook for identifying if a decl is a vtable.  */
2487 #define DARWIN_VTABLE_P(DECL) 0
2488
2489 /* Cross-module name binding.  Darwin does not support overriding
2490    functions at dynamic-link time, except for vtables in kexts.  */
2491
2492 bool
2493 darwin_binds_local_p (const_tree decl)
2494 {
2495   return default_binds_local_p_1 (decl,
2496                                   TARGET_KEXTABI && DARWIN_VTABLE_P (decl));
2497 }
2498
2499 /* The Darwin's implementation of TARGET_ASM_OUTPUT_ANCHOR.  Define the
2500    anchor relative to ".", the current section position.  We cannot use
2501    the default one because ASM_OUTPUT_DEF is wrong for Darwin.  */
2502 void
2503 darwin_asm_output_anchor (rtx symbol)
2504 {
2505   fprintf (asm_out_file, "\t.set\t");
2506   assemble_name (asm_out_file, XSTR (symbol, 0));
2507   fprintf (asm_out_file, ", . + " HOST_WIDE_INT_PRINT_DEC "\n",
2508            SYMBOL_REF_BLOCK_OFFSET (symbol));
2509 }
2510
2511 /* Disable section anchoring on any section containing a zero-sized 
2512    object.  */
2513 bool
2514 darwin_use_anchors_for_symbol_p (const_rtx symbol)
2515 {
2516   if (DARWIN_SECTION_ANCHORS && flag_section_anchors) 
2517     {
2518       section *sect;
2519       /* If the section contains a zero-sized object it's ineligible.  */
2520       sect = SYMBOL_REF_BLOCK (symbol)->sect;
2521       /* This should have the effect of disabling anchors for vars that follow
2522          any zero-sized one, in a given section.  */     
2523       if (sect->common.flags & SECTION_NO_ANCHOR)
2524         return false;
2525
2526         /* Also check the normal reasons for suppressing.  */
2527         return default_use_anchors_for_symbol_p (symbol);
2528     }
2529   else
2530     return false;
2531 }
2532
2533 /* Set the darwin specific attributes on TYPE.  */
2534 void
2535 darwin_set_default_type_attributes (tree type)
2536 {
2537   if (darwin_ms_struct
2538       && TREE_CODE (type) == RECORD_TYPE)
2539     TYPE_ATTRIBUTES (type) = tree_cons (get_identifier ("ms_struct"),
2540                                         NULL_TREE,
2541                                         TYPE_ATTRIBUTES (type));
2542 }
2543
2544 /* True, iff we're generating code for loadable kernel extensions.  */
2545
2546 bool
2547 darwin_kextabi_p (void) {
2548   return flag_apple_kext;
2549 }
2550
2551 void
2552 darwin_override_options (void)
2553 {
2554   bool darwin9plus = (darwin_macosx_version_min
2555                       && strverscmp (darwin_macosx_version_min, "10.5") >= 0);
2556
2557   /* Don't emit DWARF3/4 unless specifically selected.  This is a 
2558      workaround for tool bugs.  */
2559   if (!global_options_set.x_dwarf_strict) 
2560     dwarf_strict = 1;
2561
2562   /* Disable -freorder-blocks-and-partition for darwin_emit_unwind_label.  */
2563   if (flag_reorder_blocks_and_partition 
2564       && (targetm.asm_out.emit_unwind_label == darwin_emit_unwind_label))
2565     {
2566       inform (input_location,
2567               "-freorder-blocks-and-partition does not work with exceptions "
2568               "on this architecture");
2569       flag_reorder_blocks_and_partition = 0;
2570       flag_reorder_blocks = 1;
2571     }
2572
2573   if (flag_mkernel || flag_apple_kext)
2574     {
2575       /* -mkernel implies -fapple-kext for C++ */
2576       if (strcmp (lang_hooks.name, "GNU C++") == 0)
2577         flag_apple_kext = 1;
2578
2579       flag_no_common = 1;
2580
2581       /* No EH in kexts.  */
2582       flag_exceptions = 0;
2583       /* No -fnon-call-exceptions data in kexts.  */
2584       flag_non_call_exceptions = 0;
2585       /* so no tables either.. */
2586       flag_unwind_tables = 0;
2587       flag_asynchronous_unwind_tables = 0;
2588       /* We still need to emit branch islands for kernel context.  */
2589       darwin_emit_branch_islands = true;
2590     }
2591
2592   if (flag_var_tracking
2593       && darwin9plus
2594       && debug_info_level >= DINFO_LEVEL_NORMAL
2595       && debug_hooks->var_location != do_nothing_debug_hooks.var_location)
2596     flag_var_tracking_uninit = 1;
2597
2598   if (MACHO_DYNAMIC_NO_PIC_P)
2599     {
2600       if (flag_pic)
2601         warning (0, "-mdynamic-no-pic overrides -fpic or -fPIC");
2602       flag_pic = 0;
2603     }
2604   else if (flag_pic == 1)
2605     {
2606       /* Darwin's -fpic is -fPIC.  */
2607       flag_pic = 2;
2608     }
2609
2610   /* It is assumed that branch island stubs are needed for earlier systems.  */
2611   if (!darwin9plus)
2612     darwin_emit_branch_islands = true;
2613   else
2614     emit_aligned_common = true; /* Later systems can support aligned common.  */
2615
2616   /* The c_dialect...() macros are not available to us here.  */
2617   darwin_running_cxx = (strstr (lang_hooks.name, "C++") != 0);
2618 }
2619
2620 /* Add $LDBL128 suffix to long double builtins.  */
2621
2622 static void
2623 darwin_patch_builtin (int fncode)
2624 {
2625   tree fn = built_in_decls[fncode];
2626   tree sym;
2627   char *newname;
2628
2629   if (!fn)
2630     return;
2631
2632   sym = DECL_ASSEMBLER_NAME (fn);
2633   newname = ACONCAT (("_", IDENTIFIER_POINTER (sym), "$LDBL128", NULL));
2634
2635   set_user_assembler_name (fn, newname);
2636
2637   fn = implicit_built_in_decls[fncode];
2638   if (fn)
2639     set_user_assembler_name (fn, newname);
2640 }
2641
2642 void
2643 darwin_patch_builtins (void)
2644 {
2645   if (LONG_DOUBLE_TYPE_SIZE != 128)
2646     return;
2647
2648 #define PATCH_BUILTIN(fncode) darwin_patch_builtin (fncode);
2649 #define PATCH_BUILTIN_NO64(fncode)              \
2650   if (!TARGET_64BIT)                            \
2651     darwin_patch_builtin (fncode);
2652 #define PATCH_BUILTIN_VARIADIC(fncode)                            \
2653   if (!TARGET_64BIT                                               \
2654       && (strverscmp (darwin_macosx_version_min, "10.3.9") >= 0)) \
2655     darwin_patch_builtin (fncode);
2656 #include "darwin-ppc-ldouble-patch.def"
2657 #undef PATCH_BUILTIN
2658 #undef PATCH_BUILTIN_NO64
2659 #undef PATCH_BUILTIN_VARIADIC
2660 }
2661
2662 /*  CFStrings implementation.  */
2663 static GTY(()) tree cfstring_class_reference = NULL_TREE;
2664 static GTY(()) tree cfstring_type_node = NULL_TREE;
2665 static GTY(()) tree ccfstring_type_node = NULL_TREE;
2666 static GTY(()) tree pccfstring_type_node = NULL_TREE;
2667 static GTY(()) tree pcint_type_node = NULL_TREE;
2668 static GTY(()) tree pcchar_type_node = NULL_TREE;
2669
2670 static enum built_in_function DARWIN_BUILTIN_CFSTRINGMAKECONSTANTSTRING;
2671
2672 /* Store all constructed constant CFStrings in a hash table so that
2673    they get uniqued properly.  */
2674
2675 typedef struct GTY (()) cfstring_descriptor {
2676   /* The string literal.  */
2677   tree literal;
2678   /* The resulting constant CFString.  */
2679   tree constructor;
2680 } cfstring_descriptor;
2681
2682 static GTY ((param_is (struct cfstring_descriptor))) htab_t cfstring_htab;
2683
2684 static hashval_t cfstring_hash (const void *);
2685 static int cfstring_eq (const void *, const void *);
2686
2687 static tree
2688 add_builtin_field_decl (tree type, const char *name, tree **chain)
2689 {
2690   tree field = build_decl (BUILTINS_LOCATION, FIELD_DECL, 
2691                             get_identifier (name), type);
2692
2693   if (*chain != NULL)
2694     **chain = field;
2695   *chain = &DECL_CHAIN (field);
2696
2697   return field;
2698 }
2699
2700 void
2701 darwin_init_cfstring_builtins (unsigned first_avail)
2702 {
2703   tree cfsfun, fields, pccfstring_ftype_pcchar;
2704   tree *chain = NULL;
2705
2706   DARWIN_BUILTIN_CFSTRINGMAKECONSTANTSTRING = 
2707                         (enum built_in_function) first_avail;
2708   
2709   /* struct __builtin_CFString {
2710        const int *isa;          (will point at
2711        int flags;                __CFConstantStringClassReference)
2712        const char *str;
2713        long length;
2714      };  */
2715
2716   pcint_type_node = build_pointer_type 
2717                    (build_qualified_type (integer_type_node, TYPE_QUAL_CONST));
2718
2719   pcchar_type_node = build_pointer_type 
2720                    (build_qualified_type (char_type_node, TYPE_QUAL_CONST));
2721
2722   cfstring_type_node = (*lang_hooks.types.make_type) (RECORD_TYPE);
2723
2724   /* Have to build backwards for finish struct.  */
2725   fields = add_builtin_field_decl (long_integer_type_node, "length", &chain);
2726   add_builtin_field_decl (pcchar_type_node, "str", &chain);
2727   add_builtin_field_decl (integer_type_node, "flags", &chain);
2728   add_builtin_field_decl (pcint_type_node, "isa", &chain);
2729   finish_builtin_struct (cfstring_type_node, "__builtin_CFString",
2730                          fields, NULL_TREE);
2731
2732   /* const struct __builtin_CFstring *
2733      __builtin___CFStringMakeConstantString (const char *); */
2734
2735   ccfstring_type_node = build_qualified_type 
2736                         (cfstring_type_node, TYPE_QUAL_CONST);
2737   pccfstring_type_node = build_pointer_type (ccfstring_type_node);
2738   pccfstring_ftype_pcchar = build_function_type_list 
2739                         (pccfstring_type_node, pcchar_type_node, NULL_TREE);
2740
2741   cfsfun  = build_decl (BUILTINS_LOCATION, FUNCTION_DECL, 
2742                         get_identifier ("__builtin___CFStringMakeConstantString"),
2743                         pccfstring_ftype_pcchar);
2744
2745   TREE_PUBLIC (cfsfun) = 1;
2746   DECL_EXTERNAL (cfsfun) = 1;
2747   DECL_ARTIFICIAL (cfsfun) = 1;
2748   /* Make a lang-specific section - dup_lang_specific_decl makes a new node
2749      in place of the existing, which may be NULL.  */
2750   DECL_LANG_SPECIFIC (cfsfun) = NULL;
2751   (*lang_hooks.dup_lang_specific_decl) (cfsfun);
2752   DECL_BUILT_IN_CLASS (cfsfun) = BUILT_IN_MD;
2753   DECL_FUNCTION_CODE (cfsfun) = DARWIN_BUILTIN_CFSTRINGMAKECONSTANTSTRING;
2754   lang_hooks.builtin_function (cfsfun);
2755
2756   /* extern int __CFConstantStringClassReference[];  */
2757   cfstring_class_reference = build_decl (BUILTINS_LOCATION, VAR_DECL,
2758                  get_identifier ("__CFConstantStringClassReference"),
2759                  build_array_type (integer_type_node, NULL_TREE));
2760
2761   TREE_PUBLIC (cfstring_class_reference) = 1;
2762   DECL_ARTIFICIAL (cfstring_class_reference) = 1;
2763   (*lang_hooks.decls.pushdecl) (cfstring_class_reference);
2764   DECL_EXTERNAL (cfstring_class_reference) = 1;
2765   rest_of_decl_compilation (cfstring_class_reference, 0, 0);
2766   
2767   /* Initialize the hash table used to hold the constant CFString objects.  */
2768   cfstring_htab = htab_create_ggc (31, cfstring_hash, cfstring_eq, NULL);
2769 }
2770
2771 tree
2772 darwin_fold_builtin (tree fndecl, int n_args, tree *argp, 
2773                      bool ARG_UNUSED (ignore))
2774 {
2775   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
2776   
2777   if (fcode == DARWIN_BUILTIN_CFSTRINGMAKECONSTANTSTRING)
2778     {
2779       if (!darwin_constant_cfstrings)
2780         {
2781           error ("built-in function %qD requires the" 
2782                  " %<-mconstant-cfstrings%> flag", fndecl);
2783           return error_mark_node;
2784         }
2785
2786       if (n_args != 1)
2787         {
2788           error ("built-in function %qD takes one argument only", fndecl);
2789           return error_mark_node;
2790         }
2791
2792       return darwin_build_constant_cfstring (*argp);
2793     }
2794
2795   return NULL_TREE;
2796 }
2797
2798 static hashval_t
2799 cfstring_hash (const void *ptr)
2800 {
2801   tree str = ((const struct cfstring_descriptor *)ptr)->literal;
2802   const unsigned char *p = (const unsigned char *) TREE_STRING_POINTER (str);
2803   int i, len = TREE_STRING_LENGTH (str);
2804   hashval_t h = len;
2805
2806   for (i = 0; i < len; i++)
2807     h = ((h * 613) + p[i]);
2808
2809   return h;
2810 }
2811
2812 static int
2813 cfstring_eq (const void *ptr1, const void *ptr2)
2814 {
2815   tree str1 = ((const struct cfstring_descriptor *)ptr1)->literal;
2816   tree str2 = ((const struct cfstring_descriptor *)ptr2)->literal;
2817   int len1 = TREE_STRING_LENGTH (str1);
2818
2819   return (len1 == TREE_STRING_LENGTH (str2)
2820           && !memcmp (TREE_STRING_POINTER (str1), TREE_STRING_POINTER (str2),
2821                       len1));
2822 }
2823
2824 tree
2825 darwin_build_constant_cfstring (tree str)
2826 {
2827   struct cfstring_descriptor *desc, key;
2828   void **loc;
2829   tree addr;
2830
2831   if (!str)
2832     {
2833       error ("CFString literal is missing");
2834       return error_mark_node;
2835     }
2836
2837   STRIP_NOPS (str);
2838
2839   if (TREE_CODE (str) == ADDR_EXPR)
2840     str = TREE_OPERAND (str, 0);
2841
2842   if (TREE_CODE (str) != STRING_CST)
2843     {
2844       error ("CFString literal expression is not a string constant");
2845       return error_mark_node;
2846     }
2847
2848   /* Perhaps we already constructed a constant CFString just like this one? */
2849   key.literal = str;
2850   loc = htab_find_slot (cfstring_htab, &key, INSERT);
2851   desc = (struct cfstring_descriptor *) *loc;
2852
2853   if (!desc)
2854     {
2855       tree var, constructor, field;
2856       VEC(constructor_elt,gc) *v = NULL;
2857       int length = TREE_STRING_LENGTH (str) - 1;
2858
2859       if (darwin_warn_nonportable_cfstrings)
2860         {
2861           const char *s = TREE_STRING_POINTER (str);
2862           int l = 0;
2863
2864           for (l = 0; l < length; l++)
2865             if (!s[l] || !isascii (s[l]))
2866               {
2867                 warning (darwin_warn_nonportable_cfstrings, "%s in CFString literal",
2868                          s[l] ? "non-ASCII character" : "embedded NUL");
2869                 break;
2870               }
2871         }
2872
2873       *loc = desc = ggc_alloc_cleared_cfstring_descriptor ();
2874       desc->literal = str;
2875
2876       /* isa *. */
2877       field = TYPE_FIELDS (ccfstring_type_node);
2878       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE, 
2879                              build1 (ADDR_EXPR,  TREE_TYPE (field),  
2880                                      cfstring_class_reference));
2881       /* flags */
2882       field = DECL_CHAIN (field);
2883       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE, 
2884                              build_int_cst (TREE_TYPE (field), 0x000007c8));
2885       /* string *. */
2886       field = DECL_CHAIN (field);
2887       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
2888                              build1 (ADDR_EXPR, TREE_TYPE (field), str));
2889       /* length */
2890       field = DECL_CHAIN (field);
2891       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
2892                              build_int_cst (TREE_TYPE (field), length));
2893
2894       constructor = build_constructor (ccfstring_type_node, v);
2895       TREE_READONLY (constructor) = 1;
2896       TREE_CONSTANT (constructor) = 1;
2897       TREE_STATIC (constructor) = 1;
2898
2899       /* Fromage: The C++ flavor of 'build_unary_op' expects constructor nodes
2900          to have the TREE_HAS_CONSTRUCTOR (...) bit set.  However, this file is
2901          being built without any knowledge of C++ tree accessors; hence, we shall
2902          use the generic accessor that TREE_HAS_CONSTRUCTOR actually maps to!  */
2903       if (darwin_running_cxx)
2904         TREE_LANG_FLAG_4 (constructor) = 1;  /* TREE_HAS_CONSTRUCTOR  */
2905
2906       /* Create an anonymous global variable for this CFString.  */
2907       var = build_decl (input_location, CONST_DECL, 
2908                         NULL, TREE_TYPE (constructor));
2909       DECL_ARTIFICIAL (var) = 1;
2910       TREE_STATIC (var) = 1;
2911       DECL_INITIAL (var) = constructor;
2912       /* FIXME: This should use a translation_unit_decl to indicate file scope.  */
2913       DECL_CONTEXT (var) = NULL_TREE;
2914       desc->constructor = var;
2915     }
2916
2917   addr = build1 (ADDR_EXPR, pccfstring_type_node, desc->constructor);
2918   TREE_CONSTANT (addr) = 1;
2919
2920   return addr;
2921 }
2922
2923 bool
2924 darwin_cfstring_p (tree str)
2925 {
2926   struct cfstring_descriptor key;
2927   void **loc;
2928
2929   if (!str)
2930     return false;
2931
2932   STRIP_NOPS (str);
2933
2934   if (TREE_CODE (str) == ADDR_EXPR)
2935     str = TREE_OPERAND (str, 0);
2936
2937   if (TREE_CODE (str) != STRING_CST)
2938     return false;
2939
2940   key.literal = str;
2941   loc = htab_find_slot (cfstring_htab, &key, NO_INSERT);
2942   
2943   if (loc)
2944     return true;
2945
2946   return false;
2947 }
2948
2949 void
2950 darwin_enter_string_into_cfstring_table (tree str)
2951 {
2952   struct cfstring_descriptor key;
2953   void **loc;
2954
2955   key.literal = str;
2956   loc = htab_find_slot (cfstring_htab, &key, INSERT);
2957
2958   if (!*loc)
2959     {
2960       *loc = ggc_alloc_cleared_cfstring_descriptor ();
2961       ((struct cfstring_descriptor *)*loc)->literal = str;
2962     }
2963 }
2964
2965 /* Choose named function section based on its frequency.  */
2966
2967 section *
2968 darwin_function_section (tree decl, enum node_frequency freq,
2969                           bool startup, bool exit)
2970 {
2971   /* Startup code should go to startup subsection unless it is
2972      unlikely executed (this happens especially with function splitting
2973      where we can split away unnecesary parts of static constructors.  */
2974   if (startup && freq != NODE_FREQUENCY_UNLIKELY_EXECUTED)
2975     return get_named_text_section
2976              (decl, "__TEXT,__startup,regular,pure_instructions", "_startup");
2977
2978   /* Similarly for exit.  */
2979   if (exit && freq != NODE_FREQUENCY_UNLIKELY_EXECUTED)
2980     return get_named_text_section (decl,
2981                                    "__TEXT,__exit,regular,pure_instructions",
2982                                    "_exit");
2983
2984   /* Group cold functions together, similarly for hot code.  */
2985   switch (freq)
2986     {
2987       case NODE_FREQUENCY_UNLIKELY_EXECUTED:
2988         return get_named_text_section
2989                  (decl,
2990                   "__TEXT,__unlikely,regular,pure_instructions", "_unlikely");
2991       case NODE_FREQUENCY_HOT:
2992         return get_named_text_section
2993                  (decl, "__TEXT,__hot,regular,pure_instructions", "_hot");
2994       default:
2995         return NULL;
2996     }
2997 }
2998
2999 #include "gt-darwin.h"