OSDN Git Service

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