OSDN Git Service

2010-11-13 Tobias Burnus <burnus@net-b.de>
[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 "c-tree.h"
45 #include "c-lang.h"
46 #include "diagnostic-core.h"
47 #include "toplev.h"
48 #include "hashtab.h"
49 #include "df.h"
50 #include "debug.h"
51 #include "obstack.h"
52 #include "lto-streamer.h"
53
54 /* Darwin supports a feature called fix-and-continue, which is used
55    for rapid turn around debugging.  When code is compiled with the
56    -mfix-and-continue flag, two changes are made to the generated code
57    that allow the system to do things that it would normally not be
58    able to do easily.  These changes allow gdb to load in
59    recompilation of a translation unit that has been changed into a
60    running program and replace existing functions and methods of that
61    translation unit with versions of those functions and methods
62    from the newly compiled translation unit.  The new functions access
63    the existing static symbols from the old translation unit, if the
64    symbol existed in the unit to be replaced, and from the new
65    translation unit, otherwise.
66
67    The changes are to insert 5 nops at the beginning of all functions
68    and to use indirection to get at static symbols.  The 5 nops
69    are required by consumers of the generated code.  Currently, gdb
70    uses this to patch in a jump to the overriding function, this
71    allows all uses of the old name to forward to the replacement,
72    including existing function pointers and virtual methods.  See
73    rs6000_emit_prologue for the code that handles the nop insertions.
74
75    The added indirection allows gdb to redirect accesses to static
76    symbols from the newly loaded translation unit to the existing
77    symbol, if any.  @code{static} symbols are special and are handled by
78    setting the second word in the .non_lazy_symbol_pointer data
79    structure to symbol.  See indirect_data for the code that handles
80    the extra indirection, and machopic_output_indirection and its use
81    of MACHO_SYMBOL_STATIC for the code that handles @code{static}
82    symbol indirection.  */
83
84 /* For darwin >= 9  (OSX 10.5) the linker is capable of making the necessary
85    branch islands and we no longer need to emit darwin stubs.
86    However, if we are generating code for earlier systems (or for use in the 
87    kernel) the stubs might still be required, and this will be set true.  */
88 int darwin_emit_branch_islands = false;
89
90 /* A flag to determine whether we are running c++ or obj-c++.  This has to be
91    settable from non-c-family contexts too (i.e. we can't use the c_dialect_
92    functions).  */
93 int darwin_running_cxx;
94
95 /* Section names.  */
96 section * darwin_sections[NUM_DARWIN_SECTIONS];
97
98 /* While we transition to using in-tests instead of ifdef'd code.  */
99 #ifndef HAVE_lo_sum
100 #define HAVE_lo_sum 0
101 #define gen_macho_high(a,b) (a)
102 #define gen_macho_low(a,b,c) (a)
103 #endif
104
105 /* True if we're setting __attribute__ ((ms_struct)).  */
106 int darwin_ms_struct = false;
107
108 /* A get_unnamed_section callback used to switch to an ObjC section.
109    DIRECTIVE is as for output_section_asm_op.  */
110
111 static void
112 output_objc_section_asm_op (const void *directive)
113 {
114   static bool been_here = false;
115
116   /* The NeXT ObjC Runtime requires these sections to be present and in 
117      order in the object.  The code below implements this by emitting 
118      a section header for each ObjC section the first time that an ObjC
119      section is requested.  */
120   if (! been_here)
121     {
122       section *saved_in_section = in_section;
123       static const enum darwin_section_enum tomark[] =
124         {
125           /* written, cold -> hot */
126           objc_cat_cls_meth_section,
127           objc_cat_inst_meth_section,
128           objc_string_object_section,
129           objc_constant_string_object_section,
130           objc_selector_refs_section,
131           objc_selector_fixup_section,
132           objc_cls_refs_section,
133           objc_class_section,
134           objc_meta_class_section,
135           /* shared, hot -> cold */
136           objc_cls_meth_section,
137           objc_inst_meth_section,
138           objc_protocol_section,
139           objc_class_names_section,
140           objc_meth_var_types_section,
141           objc_meth_var_names_section,
142           objc_category_section,
143           objc_class_vars_section,
144           objc_instance_vars_section,
145           objc_module_info_section,
146           objc_symbols_section
147         };
148       size_t i;
149
150       been_here = true;
151       for (i = 0; i < ARRAY_SIZE (tomark); i++)
152         switch_to_section (darwin_sections[tomark[i]]);
153       switch_to_section (saved_in_section);
154     }
155   output_section_asm_op (directive);
156 }
157
158 /* Implement TARGET_ASM_INIT_SECTIONS.  */
159
160 void
161 darwin_init_sections (void)
162 {
163 #define DEF_SECTION(NAME, FLAGS, DIRECTIVE, OBJC)               \
164   darwin_sections[NAME] =                                       \
165     get_unnamed_section (FLAGS, (OBJC                           \
166                                  ? output_objc_section_asm_op   \
167                                  : output_section_asm_op),      \
168                          "\t" DIRECTIVE);
169 #include "config/darwin-sections.def"
170 #undef DEF_SECTION
171
172   readonly_data_section = darwin_sections[const_section];
173   exception_section = darwin_sections[darwin_exception_section];
174   eh_frame_section = darwin_sections[darwin_eh_frame_section];
175 }
176
177 int
178 name_needs_quotes (const char *name)
179 {
180   int c;
181   while ((c = *name++) != '\0')
182     if (! ISIDNUM (c) 
183           && c != '.' && c != '$' && c != '_' )
184       return 1;
185   return 0;
186 }
187
188 /* Return true if SYM_REF can be used without an indirection.  */
189 int
190 machopic_symbol_defined_p (rtx sym_ref)
191 {
192   if (SYMBOL_REF_FLAGS (sym_ref) & MACHO_SYMBOL_FLAG_DEFINED)
193     return true;
194
195   /* If a symbol references local and is not an extern to this
196      file, then the symbol might be able to declared as defined.  */
197   if (SYMBOL_REF_LOCAL_P (sym_ref) && ! SYMBOL_REF_EXTERNAL_P (sym_ref))
198     {
199       /* If the symbol references a variable and the variable is a
200          common symbol, then this symbol is not defined.  */
201       if (SYMBOL_REF_FLAGS (sym_ref) & MACHO_SYMBOL_FLAG_VARIABLE)
202         {
203           tree decl = SYMBOL_REF_DECL (sym_ref);
204           if (!decl)
205             return true;
206           if (DECL_COMMON (decl))
207             return false;
208         }
209       return true;
210     }
211   return false;
212 }
213
214 /* This module assumes that (const (symbol_ref "foo")) is a legal pic
215    reference, which will not be changed.  */
216
217 enum machopic_addr_class
218 machopic_classify_symbol (rtx sym_ref)
219 {
220   bool function_p;
221
222   function_p = SYMBOL_REF_FUNCTION_P (sym_ref);
223   if (machopic_symbol_defined_p (sym_ref))
224     return (function_p
225             ? MACHOPIC_DEFINED_FUNCTION : MACHOPIC_DEFINED_DATA);
226   else
227     return (function_p
228             ? MACHOPIC_UNDEFINED_FUNCTION : MACHOPIC_UNDEFINED_DATA);
229 }
230
231 #ifndef TARGET_FIX_AND_CONTINUE
232 #define TARGET_FIX_AND_CONTINUE 0
233 #endif
234
235 /* Indicate when fix-and-continue style code generation is being used
236    and when a reference to data should be indirected so that it can be
237    rebound in a new translation unit to reference the original instance
238    of that data.  Symbol names that are for code generation local to
239    the translation unit are bound to the new translation unit;
240    currently this means symbols that begin with L or _OBJC_;
241    otherwise, we indicate that an indirect reference should be made to
242    permit the runtime to rebind new instances of the translation unit
243    to the original instance of the data.  */
244
245 static int
246 indirect_data (rtx sym_ref)
247 {
248   int lprefix;
249   const char *name;
250
251   /* If we aren't generating fix-and-continue code, don't do anything
252      special.  */
253   if (TARGET_FIX_AND_CONTINUE == 0)
254     return 0;
255
256   /* Otherwise, all symbol except symbols that begin with L or _OBJC_
257      are indirected.  Symbols that begin with L and _OBJC_ are always
258      bound to the current translation unit as they are used for
259      generated local data of the translation unit.  */
260
261   name = XSTR (sym_ref, 0);
262
263   lprefix = (((name[0] == '*' || name[0] == '&')
264               && (name[1] == 'L' || (name[1] == '"' && name[2] == 'L')))
265              || (strncmp (name, "_OBJC_", 6) == 0));
266
267   return ! lprefix;
268 }
269
270
271 static int
272 machopic_data_defined_p (rtx sym_ref)
273 {
274   if (indirect_data (sym_ref))
275     return 0;
276
277   switch (machopic_classify_symbol (sym_ref))
278     {
279     case MACHOPIC_DEFINED_DATA:
280     case MACHOPIC_DEFINED_FUNCTION:
281       return 1;
282     default:
283       return 0;
284     }
285 }
286
287 void
288 machopic_define_symbol (rtx mem)
289 {
290   rtx sym_ref;
291
292   gcc_assert (GET_CODE (mem) == MEM);
293   sym_ref = XEXP (mem, 0);
294   SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
295 }
296
297 /* Return either ORIG or:
298
299      (const:P (unspec:P [ORIG] UNSPEC_MACHOPIC_OFFSET))
300
301    depending on MACHO_DYNAMIC_NO_PIC_P.  */
302 rtx
303 machopic_gen_offset (rtx orig)
304 {
305   if (MACHO_DYNAMIC_NO_PIC_P)
306     return orig;
307   else
308     {
309       /* Play games to avoid marking the function as needing pic if we
310          are being called as part of the cost-estimation process.  */
311       if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
312         crtl->uses_pic_offset_table = 1;
313       orig = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, orig),
314                              UNSPEC_MACHOPIC_OFFSET);
315       return gen_rtx_CONST (Pmode, orig);
316     }
317 }
318
319 static GTY(()) const char * function_base_func_name;
320 static GTY(()) int current_pic_label_num;
321
322 void
323 machopic_output_function_base_name (FILE *file)
324 {
325   const char *current_name;
326
327   /* If dynamic-no-pic is on, we should not get here.  */
328   gcc_assert (!MACHO_DYNAMIC_NO_PIC_P);
329   /* When we are generating _get_pc thunks within stubs, there is no current
330      function.  */
331   if (current_function_decl)
332     {
333       current_name =
334         IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl));
335       if (function_base_func_name != current_name)
336         {
337           ++current_pic_label_num;
338           function_base_func_name = current_name;
339         }
340     }
341   else
342     {
343       ++current_pic_label_num;
344       function_base_func_name = "L_machopic_stub_dummy";
345     }
346   fprintf (file, "L%011d$pb", current_pic_label_num);
347 }
348
349 /* The suffix attached to non-lazy pointer symbols.  */
350 #define NON_LAZY_POINTER_SUFFIX "$non_lazy_ptr"
351 /* The suffix attached to stub symbols.  */
352 #define STUB_SUFFIX "$stub"
353
354 typedef struct GTY (()) machopic_indirection
355 {
356   /* The SYMBOL_REF for the entity referenced.  */
357   rtx symbol;
358   /* The name of the stub or non-lazy pointer.  */
359   const char * ptr_name;
360   /* True iff this entry is for a stub (as opposed to a non-lazy
361      pointer).  */
362   bool stub_p;
363   /* True iff this stub or pointer pointer has been referenced.  */
364   bool used;
365 } machopic_indirection;
366
367 /* A table mapping stub names and non-lazy pointer names to
368    SYMBOL_REFs for the stubbed-to and pointed-to entities.  */
369
370 static GTY ((param_is (struct machopic_indirection))) htab_t
371   machopic_indirections;
372
373 /* Return a hash value for a SLOT in the indirections hash table.  */
374
375 static hashval_t
376 machopic_indirection_hash (const void *slot)
377 {
378   const machopic_indirection *p = (const machopic_indirection *) slot;
379   return htab_hash_string (p->ptr_name);
380 }
381
382 /* Returns true if the KEY is the same as that associated with
383    SLOT.  */
384
385 static int
386 machopic_indirection_eq (const void *slot, const void *key)
387 {
388   return strcmp (((const machopic_indirection *) slot)->ptr_name,
389                  (const char *) key) == 0;
390 }
391
392 /* Return the name of the non-lazy pointer (if STUB_P is false) or
393    stub (if STUB_B is true) corresponding to the given name.  */
394
395 const char *
396 machopic_indirection_name (rtx sym_ref, bool stub_p)
397 {
398   char *buffer;
399   const char *name = XSTR (sym_ref, 0);
400   size_t namelen = strlen (name);
401   machopic_indirection *p;
402   void ** slot;
403   bool needs_quotes;
404   const char *suffix;
405   const char *prefix = user_label_prefix;
406   const char *quote = "";
407   tree id;
408
409   id = maybe_get_identifier (name);
410   if (id)
411     {
412       tree id_orig = id;
413
414       while (IDENTIFIER_TRANSPARENT_ALIAS (id))
415         id = TREE_CHAIN (id);
416       if (id != id_orig)
417         {
418           name = IDENTIFIER_POINTER (id);
419           namelen = strlen (name);
420         }
421     }
422
423   if (name[0] == '*')
424     {
425       prefix = "";
426       ++name;
427       --namelen;
428     }
429
430   needs_quotes = name_needs_quotes (name);
431   if (needs_quotes)
432     {
433       quote = "\"";
434     }
435
436   if (stub_p)
437     suffix = STUB_SUFFIX;
438   else
439     suffix = NON_LAZY_POINTER_SUFFIX;
440
441   buffer = XALLOCAVEC (char, strlen ("&L")
442                    + strlen (prefix)
443                    + namelen
444                    + strlen (suffix)
445                    + 2 * strlen (quote)
446                    + 1 /* '\0' */);
447
448   /* Construct the name of the non-lazy pointer or stub.  */
449   sprintf (buffer, "&%sL%s%s%s%s", quote, prefix, name, suffix, quote);
450
451   if (!machopic_indirections)
452     machopic_indirections = htab_create_ggc (37,
453                                              machopic_indirection_hash,
454                                              machopic_indirection_eq,
455                                              /*htab_del=*/NULL);
456
457   slot = htab_find_slot_with_hash (machopic_indirections, buffer,
458                                    htab_hash_string (buffer), INSERT);
459   if (*slot)
460     {
461       p = (machopic_indirection *) *slot;
462     }
463   else
464     {
465       p = ggc_alloc_machopic_indirection ();
466       p->symbol = sym_ref;
467       p->ptr_name = xstrdup (buffer);
468       p->stub_p = stub_p;
469       p->used = false;
470       *slot = p;
471     }
472
473   return p->ptr_name;
474 }
475
476 /* Return the name of the stub for the mcount function.  */
477
478 const char*
479 machopic_mcount_stub_name (void)
480 {
481   rtx symbol = gen_rtx_SYMBOL_REF (Pmode, "*mcount");
482   return machopic_indirection_name (symbol, /*stub_p=*/true);
483 }
484
485 /* If NAME is the name of a stub or a non-lazy pointer , mark the stub
486    or non-lazy pointer as used -- and mark the object to which the
487    pointer/stub refers as used as well, since the pointer/stub will
488    emit a reference to it.  */
489
490 void
491 machopic_validate_stub_or_non_lazy_ptr (const char *name)
492 {
493   machopic_indirection *p;
494
495   p = ((machopic_indirection *)
496        (htab_find_with_hash (machopic_indirections, name,
497                              htab_hash_string (name))));
498   if (p && ! p->used)
499     {
500       const char *real_name;
501       tree id;
502
503       p->used = true;
504
505       /* Do what output_addr_const will do when we actually call it.  */
506       if (SYMBOL_REF_DECL (p->symbol))
507         mark_decl_referenced (SYMBOL_REF_DECL (p->symbol));
508
509       real_name = targetm.strip_name_encoding (XSTR (p->symbol, 0));
510
511       id = maybe_get_identifier (real_name);
512       if (id)
513         mark_referenced (id);
514     }
515 }
516
517 /* Transform ORIG, which may be any data source, to the corresponding
518    source using indirections.  */
519
520 rtx
521 machopic_indirect_data_reference (rtx orig, rtx reg)
522 {
523   rtx ptr_ref = orig;
524
525   if (! MACHOPIC_INDIRECT)
526     return orig;
527
528   if (GET_CODE (orig) == SYMBOL_REF)
529     {
530       int defined = machopic_data_defined_p (orig);
531
532       if (defined && MACHO_DYNAMIC_NO_PIC_P)
533         {
534           if (DARWIN_PPC)
535             {
536           /* Create a new register for CSE opportunities.  */
537           rtx hi_reg = (!can_create_pseudo_p () ? reg : gen_reg_rtx (Pmode));
538           emit_insn (gen_macho_high (hi_reg, orig));
539           emit_insn (gen_macho_low (reg, hi_reg, orig));
540               return reg;
541             }
542           else if (DARWIN_X86)
543             return orig;
544           else
545            /* some other cpu -- writeme!  */
546            gcc_unreachable ();
547         }
548       else if (defined)
549         {
550           rtx offset = NULL;
551           if (DARWIN_PPC || HAVE_lo_sum)
552             offset = machopic_gen_offset (orig);
553
554           if (DARWIN_PPC)
555             {
556           rtx hi_sum_reg = (!can_create_pseudo_p ()
557                             ? reg
558                             : gen_reg_rtx (Pmode));
559
560           gcc_assert (reg);
561
562           emit_insn (gen_rtx_SET (Pmode, hi_sum_reg,
563                               gen_rtx_PLUS (Pmode, pic_offset_table_rtx,
564                                        gen_rtx_HIGH (Pmode, offset))));
565           emit_insn (gen_rtx_SET (Pmode, reg,
566                                   gen_rtx_LO_SUM (Pmode, hi_sum_reg,
567                                                   copy_rtx (offset))));
568
569           orig = reg;
570             }
571           else if (HAVE_lo_sum)
572             {
573           gcc_assert (reg);
574
575           emit_insn (gen_rtx_SET (VOIDmode, reg,
576                                   gen_rtx_HIGH (Pmode, offset)));
577           emit_insn (gen_rtx_SET (VOIDmode, reg,
578                                   gen_rtx_LO_SUM (Pmode, reg,
579                                                   copy_rtx (offset))));
580           emit_use (pic_offset_table_rtx);
581
582           orig = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, reg);
583             }
584           return orig;
585         }
586
587       ptr_ref = (gen_rtx_SYMBOL_REF
588                  (Pmode,
589                   machopic_indirection_name (orig, /*stub_p=*/false)));
590
591       SYMBOL_REF_DATA (ptr_ref) = SYMBOL_REF_DATA (orig);
592
593       ptr_ref = gen_const_mem (Pmode, ptr_ref);
594       machopic_define_symbol (ptr_ref);
595
596       if (DARWIN_X86 
597           && reg 
598           && MACHO_DYNAMIC_NO_PIC_P)
599         {
600             emit_insn (gen_rtx_SET (Pmode, reg, ptr_ref));
601             ptr_ref = reg;
602         }
603
604       return ptr_ref;
605     }
606   else if (GET_CODE (orig) == CONST)
607     {
608       /* If "(const (plus ...", walk the PLUS and return that result.
609          PLUS processing (below) will restore the "(const ..." if
610          appropriate.  */
611       if (GET_CODE (XEXP (orig, 0)) == PLUS)
612         return machopic_indirect_data_reference (XEXP (orig, 0), reg);
613       else 
614         return orig;
615     }
616   else if (GET_CODE (orig) == MEM)
617     {
618       XEXP (ptr_ref, 0) = 
619                 machopic_indirect_data_reference (XEXP (orig, 0), reg);
620       return ptr_ref;
621     }
622   else if (GET_CODE (orig) == PLUS)
623     {
624       rtx base, result;
625       /* When the target is i386, this code prevents crashes due to the
626         compiler's ignorance on how to move the PIC base register to
627         other registers.  (The reload phase sometimes introduces such
628         insns.)  */
629       if (GET_CODE (XEXP (orig, 0)) == REG
630            && REGNO (XEXP (orig, 0)) == PIC_OFFSET_TABLE_REGNUM
631            /* Prevent the same register from being erroneously used
632               as both the base and index registers.  */
633            && (DARWIN_X86 && (GET_CODE (XEXP (orig, 1)) == CONST))
634            && reg)
635         {
636           emit_move_insn (reg, XEXP (orig, 0));
637           XEXP (ptr_ref, 0) = reg;
638           return ptr_ref;
639         }
640
641       /* Legitimize both operands of the PLUS.  */
642       base = machopic_indirect_data_reference (XEXP (orig, 0), reg);
643       orig = machopic_indirect_data_reference (XEXP (orig, 1),
644                                                (base == reg ? 0 : reg));
645       if (MACHOPIC_INDIRECT && (GET_CODE (orig) == CONST_INT))
646         result = plus_constant (base, INTVAL (orig));
647       else
648         result = gen_rtx_PLUS (Pmode, base, orig);
649
650       if (MACHOPIC_JUST_INDIRECT && GET_CODE (base) == MEM)
651         {
652           if (reg)
653             {
654               emit_move_insn (reg, result);
655               result = reg;
656             }
657           else
658             {
659               result = force_reg (GET_MODE (result), result);
660             }
661         }
662
663       return result;
664     }
665   return ptr_ref;
666 }
667
668 /* Transform TARGET (a MEM), which is a function call target, to the
669    corresponding symbol_stub if necessary.  Return a new MEM.  */
670
671 rtx
672 machopic_indirect_call_target (rtx target)
673 {
674   if (! darwin_emit_branch_islands)
675     return target;
676
677   if (GET_CODE (target) != MEM)
678     return target;
679
680   if (MACHOPIC_INDIRECT
681       && GET_CODE (XEXP (target, 0)) == SYMBOL_REF
682       && !(SYMBOL_REF_FLAGS (XEXP (target, 0))
683            & MACHO_SYMBOL_FLAG_DEFINED))
684     {
685       rtx sym_ref = XEXP (target, 0);
686       const char *stub_name = machopic_indirection_name (sym_ref,
687                                                          /*stub_p=*/true);
688       enum machine_mode mode = GET_MODE (sym_ref);
689
690       XEXP (target, 0) = gen_rtx_SYMBOL_REF (mode, stub_name);
691       SYMBOL_REF_DATA (XEXP (target, 0)) = SYMBOL_REF_DATA (sym_ref);
692       MEM_READONLY_P (target) = 1;
693       MEM_NOTRAP_P (target) = 1;
694     }
695
696   return target;
697 }
698
699 rtx
700 machopic_legitimize_pic_address (rtx orig, enum machine_mode mode, rtx reg)
701 {
702   rtx pic_ref = orig;
703
704   if (! MACHOPIC_INDIRECT)
705     return orig;
706
707   /* First handle a simple SYMBOL_REF or LABEL_REF */
708   if (GET_CODE (orig) == LABEL_REF
709       || (GET_CODE (orig) == SYMBOL_REF
710           ))
711     {
712       /* addr(foo) = &func+(foo-func) */
713       orig = machopic_indirect_data_reference (orig, reg);
714
715       if (GET_CODE (orig) == PLUS
716           && GET_CODE (XEXP (orig, 0)) == REG)
717         {
718           if (reg == 0)
719             return force_reg (mode, orig);
720
721           emit_move_insn (reg, orig);
722           return reg;
723         }
724
725       if (GET_CODE (orig) == MEM)
726         {
727           if (reg == 0)
728             {
729               gcc_assert (!reload_in_progress);
730               reg = gen_reg_rtx (Pmode);
731             }
732
733 #if HAVE_lo_sum
734           if (MACHO_DYNAMIC_NO_PIC_P
735               && (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
736                   || GET_CODE (XEXP (orig, 0)) == LABEL_REF))
737             {
738 #if defined (TARGET_TOC)        /* ppc  */
739               rtx temp_reg = (!can_create_pseudo_p ()
740                               ? reg :
741                               gen_reg_rtx (Pmode));
742               rtx asym = XEXP (orig, 0);
743               rtx mem;
744
745               emit_insn (gen_macho_high (temp_reg, asym));
746               mem = gen_const_mem (GET_MODE (orig),
747                                    gen_rtx_LO_SUM (Pmode, temp_reg,
748                                                    copy_rtx (asym)));
749               emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
750 #else
751               /* Some other CPU -- WriteMe! but right now there are no other
752                  platforms that can use dynamic-no-pic  */
753               gcc_unreachable ();
754 #endif
755               pic_ref = reg;
756             }
757           else
758           if (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
759               || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
760             {
761               rtx offset = machopic_gen_offset (XEXP (orig, 0));
762 #if defined (TARGET_TOC) /* i.e., PowerPC */
763               /* Generating a new reg may expose opportunities for
764                  common subexpression elimination.  */
765               rtx hi_sum_reg = (!can_create_pseudo_p ()
766                                 ? reg
767                                 : gen_reg_rtx (Pmode));
768               rtx mem;
769               rtx insn;
770               rtx sum;
771
772               sum = gen_rtx_HIGH (Pmode, offset);
773               if (! MACHO_DYNAMIC_NO_PIC_P)
774                 sum = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, sum);
775
776               emit_insn (gen_rtx_SET (Pmode, hi_sum_reg, sum));
777
778               mem = gen_const_mem (GET_MODE (orig),
779                                   gen_rtx_LO_SUM (Pmode,
780                                                   hi_sum_reg,
781                                                   copy_rtx (offset)));
782               insn = emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
783               set_unique_reg_note (insn, REG_EQUAL, pic_ref);
784
785               pic_ref = reg;
786 #else
787               emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
788
789               emit_insn (gen_rtx_SET (VOIDmode, reg,
790                                       gen_rtx_HIGH (Pmode,
791                                                     gen_rtx_CONST (Pmode,
792                                                                    offset))));
793               emit_insn (gen_rtx_SET (VOIDmode, reg,
794                                   gen_rtx_LO_SUM (Pmode, reg,
795                                            gen_rtx_CONST (Pmode,
796                                                           copy_rtx (offset)))));
797               pic_ref = gen_rtx_PLUS (Pmode,
798                                       pic_offset_table_rtx, reg);
799 #endif
800             }
801           else
802 #endif  /* HAVE_lo_sum */
803             {
804               rtx pic = pic_offset_table_rtx;
805               if (GET_CODE (pic) != REG)
806                 {
807                   emit_move_insn (reg, pic);
808                   pic = reg;
809                 }
810 #if 0
811               emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
812 #endif
813
814               if (reload_in_progress)
815                 df_set_regs_ever_live (REGNO (pic), true);
816               pic_ref = gen_rtx_PLUS (Pmode, pic,
817                                       machopic_gen_offset (XEXP (orig, 0)));
818             }
819
820 #if !defined (TARGET_TOC)
821           emit_move_insn (reg, pic_ref);
822           pic_ref = gen_const_mem (GET_MODE (orig), reg);
823 #endif
824         }
825       else
826         {
827
828 #if HAVE_lo_sum
829           if (GET_CODE (orig) == SYMBOL_REF
830               || GET_CODE (orig) == LABEL_REF)
831             {
832               rtx offset = machopic_gen_offset (orig);
833 #if defined (TARGET_TOC) /* i.e., PowerPC */
834               rtx hi_sum_reg;
835
836               if (reg == 0)
837                 {
838                   gcc_assert (!reload_in_progress);
839                   reg = gen_reg_rtx (Pmode);
840                 }
841
842               hi_sum_reg = reg;
843
844               emit_insn (gen_rtx_SET (Pmode, hi_sum_reg,
845                                       (MACHO_DYNAMIC_NO_PIC_P)
846                                       ? gen_rtx_HIGH (Pmode, offset)
847                                       : gen_rtx_PLUS (Pmode,
848                                                       pic_offset_table_rtx,
849                                                       gen_rtx_HIGH (Pmode,
850                                                                     offset))));
851               emit_insn (gen_rtx_SET (VOIDmode, reg,
852                                       gen_rtx_LO_SUM (Pmode,
853                                                       hi_sum_reg,
854                                                       copy_rtx (offset))));
855               pic_ref = reg;
856 #else
857               emit_insn (gen_rtx_SET (VOIDmode, reg,
858                                       gen_rtx_HIGH (Pmode, offset)));
859               emit_insn (gen_rtx_SET (VOIDmode, reg,
860                                       gen_rtx_LO_SUM (Pmode, reg,
861                                                       copy_rtx (offset))));
862               pic_ref = gen_rtx_PLUS (Pmode,
863                                       pic_offset_table_rtx, reg);
864 #endif
865             }
866           else
867 #endif  /*  HAVE_lo_sum  */
868             {
869               if (REG_P (orig)
870                   || GET_CODE (orig) == SUBREG)
871                 {
872                   return orig;
873                 }
874               else
875                 {
876                   rtx pic = pic_offset_table_rtx;
877                   if (GET_CODE (pic) != REG)
878                     {
879                       emit_move_insn (reg, pic);
880                       pic = reg;
881                     }
882 #if 0
883                   emit_use (pic_offset_table_rtx);
884 #endif
885                   if (reload_in_progress)
886                     df_set_regs_ever_live (REGNO (pic), true);
887                   pic_ref = gen_rtx_PLUS (Pmode,
888                                           pic,
889                                           machopic_gen_offset (orig));
890                 }
891             }
892         }
893
894       if (GET_CODE (pic_ref) != REG)
895         {
896           if (reg != 0)
897             {
898               emit_move_insn (reg, pic_ref);
899               return reg;
900             }
901           else
902             {
903               return force_reg (mode, pic_ref);
904             }
905         }
906       else
907         {
908           return pic_ref;
909         }
910     }
911
912   else if (GET_CODE (orig) == SYMBOL_REF)
913     return orig;
914
915   else if (GET_CODE (orig) == PLUS
916            && (GET_CODE (XEXP (orig, 0)) == MEM
917                || GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
918                || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
919            && XEXP (orig, 0) != pic_offset_table_rtx
920            && GET_CODE (XEXP (orig, 1)) != REG)
921
922     {
923       rtx base;
924       int is_complex = (GET_CODE (XEXP (orig, 0)) == MEM);
925
926       base = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
927       orig = machopic_legitimize_pic_address (XEXP (orig, 1),
928                                               Pmode, (base == reg ? 0 : reg));
929       if (GET_CODE (orig) == CONST_INT)
930         {
931           pic_ref = plus_constant (base, INTVAL (orig));
932           is_complex = 1;
933         }
934       else
935         pic_ref = gen_rtx_PLUS (Pmode, base, orig);
936
937       if (reg && is_complex)
938         {
939           emit_move_insn (reg, pic_ref);
940           pic_ref = reg;
941         }
942       /* Likewise, should we set special REG_NOTEs here?  */
943     }
944
945   else if (GET_CODE (orig) == CONST)
946     {
947       return machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
948     }
949
950   else if (GET_CODE (orig) == MEM
951            && GET_CODE (XEXP (orig, 0)) == SYMBOL_REF)
952     {
953       rtx addr = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
954       addr = replace_equiv_address (orig, addr);
955       emit_move_insn (reg, addr);
956       pic_ref = reg;
957     }
958
959   return pic_ref;
960 }
961
962 /* Output the stub or non-lazy pointer in *SLOT, if it has been used.
963    DATA is the FILE* for assembly output.  Called from
964    htab_traverse.  */
965
966 static int
967 machopic_output_indirection (void **slot, void *data)
968 {
969   machopic_indirection *p = *((machopic_indirection **) slot);
970   FILE *asm_out_file = (FILE *) data;
971   rtx symbol;
972   const char *sym_name;
973   const char *ptr_name;
974
975   if (!p->used)
976     return 1;
977
978   symbol = p->symbol;
979   sym_name = XSTR (symbol, 0);
980   ptr_name = p->ptr_name;
981
982   if (p->stub_p)
983     {
984       char *sym;
985       char *stub;
986       tree id;
987
988       id = maybe_get_identifier (sym_name);
989       if (id)
990         {
991           tree id_orig = id;
992
993           while (IDENTIFIER_TRANSPARENT_ALIAS (id))
994             id = TREE_CHAIN (id);
995           if (id != id_orig)
996             sym_name = IDENTIFIER_POINTER (id);
997         }
998
999       sym = XALLOCAVEC (char, strlen (sym_name) + 2);
1000       if (sym_name[0] == '*' || sym_name[0] == '&')
1001         strcpy (sym, sym_name + 1);
1002       else if (sym_name[0] == '-' || sym_name[0] == '+')
1003         strcpy (sym, sym_name);
1004       else
1005         sprintf (sym, "%s%s", user_label_prefix, sym_name);
1006
1007       stub = XALLOCAVEC (char, strlen (ptr_name) + 2);
1008       if (ptr_name[0] == '*' || ptr_name[0] == '&')
1009         strcpy (stub, ptr_name + 1);
1010       else
1011         sprintf (stub, "%s%s", user_label_prefix, ptr_name);
1012
1013       machopic_output_stub (asm_out_file, sym, stub);
1014     }
1015   else if (! indirect_data (symbol)
1016            && (machopic_symbol_defined_p (symbol)
1017                || SYMBOL_REF_LOCAL_P (symbol)))
1018     {
1019       switch_to_section (data_section);
1020       assemble_align (GET_MODE_ALIGNMENT (Pmode));
1021       assemble_label (asm_out_file, ptr_name);
1022       assemble_integer (gen_rtx_SYMBOL_REF (Pmode, sym_name),
1023                         GET_MODE_SIZE (Pmode),
1024                         GET_MODE_ALIGNMENT (Pmode), 1);
1025     }
1026   else
1027     {
1028       rtx init = const0_rtx;
1029
1030       switch_to_section (darwin_sections[machopic_nl_symbol_ptr_section]);
1031
1032       /* Mach-O symbols are passed around in code through indirect
1033          references and the original symbol_ref hasn't passed through
1034          the generic handling and reference-catching in
1035          output_operand, so we need to manually mark weak references
1036          as such.  */
1037       if (SYMBOL_REF_WEAK (symbol))
1038         {
1039           tree decl = SYMBOL_REF_DECL (symbol);
1040           gcc_assert (DECL_P (decl));
1041
1042           if (decl != NULL_TREE
1043               && DECL_EXTERNAL (decl) && TREE_PUBLIC (decl)
1044               /* Handle only actual external-only definitions, not
1045                  e.g. extern inline code or variables for which
1046                  storage has been allocated.  */
1047               && !TREE_STATIC (decl))
1048             {
1049               fputs ("\t.weak_reference ", asm_out_file);
1050               assemble_name (asm_out_file, sym_name);
1051               fputc ('\n', asm_out_file);
1052             }
1053         }
1054
1055       assemble_name (asm_out_file, ptr_name);
1056       fprintf (asm_out_file, ":\n");
1057
1058       fprintf (asm_out_file, "\t.indirect_symbol ");
1059       assemble_name (asm_out_file, sym_name);
1060       fprintf (asm_out_file, "\n");
1061
1062       /* Variables that are marked with MACHO_SYMBOL_STATIC need to
1063          have their symbol name instead of 0 in the second entry of
1064          the non-lazy symbol pointer data structure when they are
1065          defined.  This allows the runtime to rebind newer instances
1066          of the translation unit with the original instance of the
1067          symbol.  */
1068
1069       if ((SYMBOL_REF_FLAGS (symbol) & MACHO_SYMBOL_STATIC)
1070           && machopic_symbol_defined_p (symbol))
1071         init = gen_rtx_SYMBOL_REF (Pmode, sym_name);
1072
1073       assemble_integer (init, GET_MODE_SIZE (Pmode),
1074                         GET_MODE_ALIGNMENT (Pmode), 1);
1075     }
1076
1077   return 1;
1078 }
1079
1080 void
1081 machopic_finish (FILE *asm_out_file)
1082 {
1083   if (machopic_indirections)
1084     htab_traverse_noresize (machopic_indirections,
1085                             machopic_output_indirection,
1086                             asm_out_file);
1087 }
1088
1089 int
1090 machopic_operand_p (rtx op)
1091 {
1092   if (MACHOPIC_JUST_INDIRECT)
1093     return (GET_CODE (op) == SYMBOL_REF
1094             && machopic_symbol_defined_p (op));
1095   else
1096     return (GET_CODE (op) == CONST
1097             && GET_CODE (XEXP (op, 0)) == UNSPEC
1098             && XINT (XEXP (op, 0), 1) == UNSPEC_MACHOPIC_OFFSET);
1099 }
1100
1101 /* This function records whether a given name corresponds to a defined
1102    or undefined function or variable, for machopic_classify_ident to
1103    use later.  */
1104
1105 void
1106 darwin_encode_section_info (tree decl, rtx rtl, int first ATTRIBUTE_UNUSED)
1107 {
1108   rtx sym_ref;
1109
1110   /* Do the standard encoding things first.  */
1111   default_encode_section_info (decl, rtl, first);
1112
1113   if (TREE_CODE (decl) != FUNCTION_DECL && TREE_CODE (decl) != VAR_DECL)
1114     return;
1115
1116   sym_ref = XEXP (rtl, 0);
1117   if (TREE_CODE (decl) == VAR_DECL)
1118     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_VARIABLE;
1119
1120   if (!DECL_EXTERNAL (decl)
1121       && (!TREE_PUBLIC (decl) || !DECL_WEAK (decl))
1122       && ! lookup_attribute ("weakref", DECL_ATTRIBUTES (decl))
1123       && ((TREE_STATIC (decl)
1124            && (!DECL_COMMON (decl) || !TREE_PUBLIC (decl)))
1125           || (!DECL_COMMON (decl) && DECL_INITIAL (decl)
1126               && DECL_INITIAL (decl) != error_mark_node)))
1127     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
1128
1129   if (! TREE_PUBLIC (decl))
1130     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_STATIC;
1131 }
1132
1133 void
1134 darwin_mark_decl_preserved (const char *name)
1135 {
1136   fprintf (asm_out_file, "\t.no_dead_strip ");
1137   assemble_name (asm_out_file, name);
1138   fputc ('\n', asm_out_file);
1139 }
1140
1141 static section *
1142 darwin_text_section (int reloc, int weak)
1143 {
1144   if (reloc)
1145     return (weak
1146             ? darwin_sections[text_unlikely_coal_section]
1147             : unlikely_text_section ());
1148   else
1149     return (weak
1150             ? darwin_sections[text_coal_section]
1151             : text_section);
1152 }
1153
1154 static section *
1155 darwin_rodata_section (int weak)
1156 {
1157   return (weak
1158           ? darwin_sections[const_coal_section]
1159           : darwin_sections[const_section]);
1160 }
1161
1162 static section *
1163 darwin_mergeable_string_section (tree exp,
1164                                  unsigned HOST_WIDE_INT align)
1165 {
1166   if (flag_merge_constants
1167       && TREE_CODE (exp) == STRING_CST
1168       && TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
1169       && align <= 256
1170       && (int_size_in_bytes (TREE_TYPE (exp))
1171           == TREE_STRING_LENGTH (exp))
1172       && ((size_t) TREE_STRING_LENGTH (exp)
1173           == strlen (TREE_STRING_POINTER (exp)) + 1))
1174     return darwin_sections[cstring_section];
1175
1176   return readonly_data_section;
1177 }
1178
1179 #ifndef HAVE_GAS_LITERAL16
1180 #define HAVE_GAS_LITERAL16 0
1181 #endif
1182
1183 static section *
1184 darwin_mergeable_constant_section (tree exp,
1185                                    unsigned HOST_WIDE_INT align)
1186 {
1187   enum machine_mode mode = DECL_MODE (exp);
1188   unsigned int modesize = GET_MODE_BITSIZE (mode);
1189
1190   if (flag_merge_constants
1191       && mode != VOIDmode
1192       && mode != BLKmode
1193       && modesize <= align
1194       && align >= 8
1195       && align <= 256
1196       && (align & (align -1)) == 0)
1197     {
1198       tree size = TYPE_SIZE_UNIT (TREE_TYPE (exp));
1199
1200       if (TREE_CODE (size) == INTEGER_CST
1201           && TREE_INT_CST_LOW (size) == 4
1202           && TREE_INT_CST_HIGH (size) == 0)
1203         return darwin_sections[literal4_section];
1204       else if (TREE_CODE (size) == INTEGER_CST
1205                && TREE_INT_CST_LOW (size) == 8
1206                && TREE_INT_CST_HIGH (size) == 0)
1207         return darwin_sections[literal8_section];
1208       else if (HAVE_GAS_LITERAL16
1209                && TARGET_64BIT
1210                && TREE_CODE (size) == INTEGER_CST
1211                && TREE_INT_CST_LOW (size) == 16
1212                && TREE_INT_CST_HIGH (size) == 0)
1213         return darwin_sections[literal16_section];
1214       else
1215         return readonly_data_section;
1216     }
1217
1218   return readonly_data_section;
1219 }
1220
1221 int
1222 machopic_reloc_rw_mask (void)
1223 {
1224   return MACHOPIC_INDIRECT ? 3 : 0;
1225 }
1226
1227 section *
1228 machopic_select_section (tree decl,
1229                          int reloc,
1230                          unsigned HOST_WIDE_INT align)
1231 {
1232   bool weak = (DECL_P (decl)
1233                && DECL_WEAK (decl)
1234                && !lookup_attribute ("weak_import",
1235                                      DECL_ATTRIBUTES (decl)));
1236   section *base_section;
1237
1238   switch (categorize_decl_for_section (decl, reloc))
1239     {
1240     case SECCAT_TEXT:
1241       base_section = darwin_text_section (reloc, weak);
1242       break;
1243
1244     case SECCAT_RODATA:
1245     case SECCAT_SRODATA:
1246       base_section = darwin_rodata_section (weak);
1247       break;
1248
1249     case SECCAT_RODATA_MERGE_STR:
1250       base_section = darwin_mergeable_string_section (decl, align);
1251       break;
1252
1253     case SECCAT_RODATA_MERGE_STR_INIT:
1254       base_section = darwin_mergeable_string_section (DECL_INITIAL (decl), align);
1255       break;
1256
1257     case SECCAT_RODATA_MERGE_CONST:
1258       base_section =  darwin_mergeable_constant_section (decl, align);
1259       break;
1260
1261     case SECCAT_DATA:
1262     case SECCAT_DATA_REL:
1263     case SECCAT_DATA_REL_LOCAL:
1264     case SECCAT_DATA_REL_RO:
1265     case SECCAT_DATA_REL_RO_LOCAL:
1266     case SECCAT_SDATA:
1267     case SECCAT_TDATA:
1268     case SECCAT_BSS:
1269     case SECCAT_SBSS:
1270     case SECCAT_TBSS:
1271       if (TREE_READONLY (decl) || TREE_CONSTANT (decl))
1272         base_section = weak ? darwin_sections[const_data_coal_section]
1273                             : darwin_sections[const_data_section];
1274       else
1275         base_section = weak ? darwin_sections[data_coal_section] : data_section;
1276       break;
1277
1278     default:
1279       gcc_unreachable ();
1280     }
1281
1282   /* Darwin weird special cases.  */
1283   if (TREE_CODE (decl) == CONSTRUCTOR
1284       && TREE_TYPE (decl)
1285       && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
1286       && TYPE_NAME (TREE_TYPE (decl)))
1287     {
1288       tree name = TYPE_NAME (TREE_TYPE (decl));
1289       if (TREE_CODE (name) == TYPE_DECL)
1290         name = DECL_NAME (name);
1291
1292       if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_ObjCString"))
1293         {
1294           if (flag_next_runtime)
1295             return darwin_sections[objc_constant_string_object_section];
1296           else
1297             return darwin_sections[objc_string_object_section];
1298         }
1299       else if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_CFString"))
1300         return darwin_sections[cfstring_constant_object_section];
1301       else
1302         return base_section;
1303     }
1304   else if (TREE_CODE (decl) == VAR_DECL
1305            && DECL_NAME (decl)
1306            && TREE_CODE (DECL_NAME (decl)) == IDENTIFIER_NODE
1307            && IDENTIFIER_POINTER (DECL_NAME (decl))
1308            && !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)), "_OBJC_", 6))
1309     {
1310       const char *name = IDENTIFIER_POINTER (DECL_NAME (decl));
1311
1312       if (!strncmp (name, "_OBJC_CLASS_METHODS_", 20))
1313         return darwin_sections[objc_cls_meth_section];
1314       else if (!strncmp (name, "_OBJC_INSTANCE_METHODS_", 23))
1315         return darwin_sections[objc_inst_meth_section];
1316       else if (!strncmp (name, "_OBJC_CATEGORY_CLASS_METHODS_", 20))
1317         return darwin_sections[objc_cat_cls_meth_section];
1318       else if (!strncmp (name, "_OBJC_CATEGORY_INSTANCE_METHODS_", 23))
1319         return darwin_sections[objc_cat_inst_meth_section];
1320       else if (!strncmp (name, "_OBJC_CLASS_VARIABLES_", 22))
1321         return darwin_sections[objc_class_vars_section];
1322       else if (!strncmp (name, "_OBJC_INSTANCE_VARIABLES_", 25))
1323         return darwin_sections[objc_instance_vars_section];
1324       else if (!strncmp (name, "_OBJC_CLASS_PROTOCOLS_", 22))
1325         return darwin_sections[objc_cat_cls_meth_section];
1326       else if (!strncmp (name, "_OBJC_CLASS_NAME_", 17))
1327         return darwin_sections[objc_class_names_section];
1328       else if (!strncmp (name, "_OBJC_METH_VAR_NAME_", 20))
1329         return darwin_sections[objc_meth_var_names_section];
1330       else if (!strncmp (name, "_OBJC_METH_VAR_TYPE_", 20))
1331         return darwin_sections[objc_meth_var_types_section];
1332       else if (!strncmp (name, "_OBJC_CLASS_REFERENCES", 22))
1333         return darwin_sections[objc_cls_refs_section];
1334       else if (!strncmp (name, "_OBJC_CLASS_", 12))
1335         return darwin_sections[objc_class_section];
1336       else if (!strncmp (name, "_OBJC_METACLASS_", 16))
1337         return darwin_sections[objc_meta_class_section];
1338       else if (!strncmp (name, "_OBJC_CATEGORY_", 15))
1339         return darwin_sections[objc_category_section];
1340       else if (!strncmp (name, "_OBJC_SELECTOR_REFERENCES", 25))
1341         return darwin_sections[objc_selector_refs_section];
1342       else if (!strncmp (name, "_OBJC_SELECTOR_FIXUP", 20))
1343         return darwin_sections[objc_selector_fixup_section];
1344       else if (!strncmp (name, "_OBJC_SYMBOLS", 13))
1345         return darwin_sections[objc_symbols_section];
1346       else if (!strncmp (name, "_OBJC_MODULES", 13))
1347         return darwin_sections[objc_module_info_section];
1348       else if (!strncmp (name, "_OBJC_IMAGE_INFO", 16))
1349         return darwin_sections[objc_image_info_section];
1350       else if (!strncmp (name, "_OBJC_PROTOCOL_INSTANCE_METHODS_", 32))
1351         return darwin_sections[objc_cat_inst_meth_section];
1352       else if (!strncmp (name, "_OBJC_PROTOCOL_CLASS_METHODS_", 29))
1353         return darwin_sections[objc_cat_cls_meth_section];
1354       else if (!strncmp (name, "_OBJC_PROTOCOL_REFS_", 20))
1355         return darwin_sections[objc_cat_cls_meth_section];
1356       else if (!strncmp (name, "_OBJC_PROTOCOL_", 15))
1357         return darwin_sections[objc_protocol_section];
1358       else
1359         return base_section;
1360     }
1361
1362   return base_section;
1363 }
1364
1365 /* This can be called with address expressions as "rtx".
1366    They must go in "const".  */
1367
1368 section *
1369 machopic_select_rtx_section (enum machine_mode mode, rtx x,
1370                              unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
1371 {
1372   if (GET_MODE_SIZE (mode) == 8
1373       && (GET_CODE (x) == CONST_INT
1374           || GET_CODE (x) == CONST_DOUBLE))
1375     return darwin_sections[literal8_section];
1376   else if (GET_MODE_SIZE (mode) == 4
1377            && (GET_CODE (x) == CONST_INT
1378                || GET_CODE (x) == CONST_DOUBLE))
1379     return darwin_sections[literal4_section];
1380   else if (HAVE_GAS_LITERAL16
1381            && TARGET_64BIT
1382            && GET_MODE_SIZE (mode) == 16
1383            && (GET_CODE (x) == CONST_INT
1384                || GET_CODE (x) == CONST_DOUBLE
1385                || GET_CODE (x) == CONST_VECTOR))
1386     return darwin_sections[literal16_section];
1387   else if (MACHOPIC_INDIRECT
1388            && (GET_CODE (x) == SYMBOL_REF
1389                || GET_CODE (x) == CONST
1390                || GET_CODE (x) == LABEL_REF))
1391     return darwin_sections[const_data_section];
1392   else
1393     return darwin_sections[const_section];
1394 }
1395
1396 void
1397 machopic_asm_out_constructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1398 {
1399   if (MACHOPIC_INDIRECT)
1400     switch_to_section (darwin_sections[mod_init_section]);
1401   else
1402     switch_to_section (darwin_sections[constructor_section]);
1403   assemble_align (POINTER_SIZE);
1404   assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1405
1406   if (! MACHOPIC_INDIRECT)
1407     fprintf (asm_out_file, ".reference .constructors_used\n");
1408 }
1409
1410 void
1411 machopic_asm_out_destructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1412 {
1413   if (MACHOPIC_INDIRECT)
1414     switch_to_section (darwin_sections[mod_term_section]);
1415   else
1416     switch_to_section (darwin_sections[destructor_section]);
1417   assemble_align (POINTER_SIZE);
1418   assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1419
1420   if (! MACHOPIC_INDIRECT)
1421     fprintf (asm_out_file, ".reference .destructors_used\n");
1422 }
1423
1424 void
1425 darwin_globalize_label (FILE *stream, const char *name)
1426 {
1427   if (!!strncmp (name, "_OBJC_", 6))
1428     default_globalize_label (stream, name);
1429 }
1430
1431 /* This routine returns non-zero if 'name' starts with the special objective-c 
1432    anonymous file-scope static name.  It accommodates c++'s mangling of such 
1433    symbols (in this case the symbols will have form _ZL{d}*_OBJC_* d=digit).  */
1434    
1435 int 
1436 darwin_label_is_anonymous_local_objc_name (const char *name)
1437 {
1438   const unsigned char *p = (const unsigned char *) name;
1439   if (*p != '_')
1440     return 0;
1441   if (p[1] == 'Z' && p[2] == 'L')
1442   {
1443     p += 3;
1444     while (*p >= '0' && *p <= '9')
1445       p++;
1446   }
1447   return (!strncmp ((const char *)p, "_OBJC_", 6));
1448 }
1449
1450 /* LTO support for Mach-O.  */
1451
1452 /* Section names for LTO sections.  */
1453 static unsigned int lto_section_names_offset = 0;
1454
1455 /* This is the obstack which we use to allocate the many strings.  */
1456 static struct obstack lto_section_names_obstack;
1457
1458 /* Segment name for LTO sections.  */
1459 #define LTO_SEGMENT_NAME "__GNU_LTO"
1460
1461 /* Section name for LTO section names section.  */
1462 #define LTO_NAMES_SECTION "__section_names"
1463
1464 /* File to temporarily store LTO data.  This is appended to asm_out_file
1465    in darwin_end_file.  */
1466 static FILE *lto_asm_out_file, *saved_asm_out_file;
1467 static char *lto_asm_out_name;
1468
1469 /* Prepare asm_out_file for LTO output.  For darwin, this means hiding
1470    asm_out_file and switching to an alternative output file.  */
1471 void
1472 darwin_asm_lto_start (void)
1473 {
1474   gcc_assert (! saved_asm_out_file);
1475   saved_asm_out_file = asm_out_file;
1476   if (! lto_asm_out_name)
1477     lto_asm_out_name = make_temp_file (".lto.s");
1478   lto_asm_out_file = fopen (lto_asm_out_name, "a");
1479   if (lto_asm_out_file == NULL)
1480     fatal_error ("failed to open temporary file %s for LTO output",
1481                  lto_asm_out_name);
1482   asm_out_file = lto_asm_out_file;
1483 }
1484
1485 /* Restore asm_out_file.  */
1486 void
1487 darwin_asm_lto_end (void)
1488 {
1489   gcc_assert (saved_asm_out_file);
1490   fclose (lto_asm_out_file);
1491   asm_out_file = saved_asm_out_file;
1492   saved_asm_out_file = NULL;
1493 }
1494
1495 static void
1496 darwin_asm_dwarf_section (const char *name, unsigned int flags, tree decl);
1497
1498 /*  Called for the TARGET_ASM_NAMED_SECTION hook.  */
1499
1500 void
1501 darwin_asm_named_section (const char *name,
1502                           unsigned int flags,
1503                           tree decl ATTRIBUTE_UNUSED)
1504 {
1505   /* LTO sections go in a special segment __GNU_LTO.  We want to replace the
1506      section name with something we can use to represent arbitrary-length
1507      names (section names in Mach-O are at most 16 characters long).  */
1508   if (strncmp (name, LTO_SECTION_NAME_PREFIX,
1509                strlen (LTO_SECTION_NAME_PREFIX)) == 0)
1510     {
1511       /* We expect certain flags to be set...  */
1512       gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
1513                   == (SECTION_DEBUG | SECTION_NAMED));
1514
1515       /* Add the section name to the things to output when we end the
1516          current assembler output file.
1517          This is all not very efficient, but that doesn't matter -- this
1518          shouldn't be a hot path in the compiler...  */
1519       obstack_1grow (&lto_section_names_obstack, '\t');
1520       obstack_grow (&lto_section_names_obstack, ".ascii ", 7);
1521       obstack_1grow (&lto_section_names_obstack, '"');
1522       obstack_grow (&lto_section_names_obstack, name, strlen (name));
1523       obstack_grow (&lto_section_names_obstack, "\\0\"\n", 4);
1524
1525       /* Output the dummy section name.  */
1526       fprintf (asm_out_file, "\t# %s\n", name);
1527       fprintf (asm_out_file, "\t.section %s,__%08X,regular,debug\n",
1528                LTO_SEGMENT_NAME, lto_section_names_offset);
1529
1530       /* Update the offset for the next section name.  Make sure we stay
1531          within reasonable length.  */  
1532       lto_section_names_offset += strlen (name) + 1;
1533       gcc_assert (lto_section_names_offset > 0
1534                   && lto_section_names_offset < ((unsigned) 1 << 31));
1535     }
1536   else if (strncmp (name, "__DWARF,", 8) == 0)
1537     darwin_asm_dwarf_section (name, flags, decl);
1538   else
1539     fprintf (asm_out_file, "\t.section %s\n", name);
1540 }
1541
1542 void
1543 darwin_unique_section (tree decl ATTRIBUTE_UNUSED, int reloc ATTRIBUTE_UNUSED)
1544 {
1545   /* Darwin does not use unique sections.  */
1546 }
1547
1548 /* Handle __attribute__ ((apple_kext_compatibility)).
1549    This only applies to darwin kexts for 2.95 compatibility -- it shrinks the
1550    vtable for classes with this attribute (and their descendants) by not
1551    outputting the new 3.0 nondeleting destructor.  This means that such
1552    objects CANNOT be allocated on the stack or as globals UNLESS they have
1553    a completely empty `operator delete'.
1554    Luckily, this fits in with the Darwin kext model.
1555
1556    This attribute also disables gcc3's potential overlaying of derived
1557    class data members on the padding at the end of the base class.  */
1558
1559 tree
1560 darwin_handle_kext_attribute (tree *node, tree name,
1561                               tree args ATTRIBUTE_UNUSED,
1562                               int flags ATTRIBUTE_UNUSED,
1563                               bool *no_add_attrs)
1564 {
1565   /* APPLE KEXT stuff -- only applies with pure static C++ code.  */
1566   if (! TARGET_KEXTABI)
1567     {
1568       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
1569                "only when compiling a kext", name);
1570
1571       *no_add_attrs = true;
1572     }
1573   else if (TREE_CODE (*node) != RECORD_TYPE)
1574     {
1575       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
1576                "only to C++ classes", name);
1577
1578       *no_add_attrs = true;
1579     }
1580
1581   return NULL_TREE;
1582 }
1583
1584 /* Handle a "weak_import" attribute; arguments as in
1585    struct attribute_spec.handler.  */
1586
1587 tree
1588 darwin_handle_weak_import_attribute (tree *node, tree name,
1589                                      tree ARG_UNUSED (args),
1590                                      int ARG_UNUSED (flags),
1591                                      bool * no_add_attrs)
1592 {
1593   if (TREE_CODE (*node) != FUNCTION_DECL && TREE_CODE (*node) != VAR_DECL)
1594     {
1595       warning (OPT_Wattributes, "%qE attribute ignored",
1596                name);
1597       *no_add_attrs = true;
1598     }
1599   else
1600     declare_weak (*node);
1601
1602   return NULL_TREE;
1603 }
1604
1605 /* Emit a label for an FDE, making it global and/or weak if appropriate.
1606    The third parameter is nonzero if this is for exception handling.
1607    The fourth parameter is nonzero if this is just a placeholder for an
1608    FDE that we are omitting. */
1609
1610 void
1611 darwin_emit_unwind_label (FILE *file, tree decl, int for_eh, int empty)
1612 {
1613   char *lab;
1614
1615   if (! for_eh)
1616     return;
1617
1618   lab = concat (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)), ".eh", NULL);
1619
1620   if (TREE_PUBLIC (decl))
1621     {
1622       targetm.asm_out.globalize_label (file, lab);
1623       if (DECL_VISIBILITY (decl) == VISIBILITY_HIDDEN)
1624         {
1625           fputs ("\t.private_extern ", file);
1626           assemble_name (file, lab);
1627           fputc ('\n', file);
1628         }
1629     }
1630
1631   if (DECL_WEAK (decl))
1632     {
1633       fputs ("\t.weak_definition ", file);
1634       assemble_name (file, lab);
1635       fputc ('\n', file);
1636     }
1637
1638   assemble_name (file, lab);
1639   if (empty)
1640     {
1641       fputs (" = 0\n", file);
1642
1643       /* Mark the absolute .eh and .eh1 style labels as needed to
1644          ensure that we don't dead code strip them and keep such
1645          labels from another instantiation point until we can fix this
1646          properly with group comdat support.  */
1647       darwin_mark_decl_preserved (lab);
1648     }
1649   else
1650     fputs (":\n", file);
1651
1652   free (lab);
1653 }
1654
1655 static GTY(()) unsigned long except_table_label_num;
1656
1657 void
1658 darwin_emit_except_table_label (FILE *file)
1659 {
1660   char section_start_label[30];
1661
1662   ASM_GENERATE_INTERNAL_LABEL (section_start_label, "GCC_except_table",
1663                                except_table_label_num++);
1664   ASM_OUTPUT_LABEL (file, section_start_label);
1665 }
1666 /* Generate a PC-relative reference to a Mach-O non-lazy-symbol.  */
1667
1668 void
1669 darwin_non_lazy_pcrel (FILE *file, rtx addr)
1670 {
1671   const char *nlp_name;
1672
1673   gcc_assert (GET_CODE (addr) == SYMBOL_REF);
1674
1675   nlp_name = machopic_indirection_name (addr, /*stub_p=*/false);
1676   fputs ("\t.long\t", file);
1677   ASM_OUTPUT_LABELREF (file, nlp_name);
1678   fputs ("-.", file);
1679 }
1680
1681 /* The implementation of ASM_DECLARE_CONSTANT_NAME.  */
1682
1683 void
1684 darwin_asm_declare_constant_name (FILE *file, const char *name,
1685                                   const_tree exp ATTRIBUTE_UNUSED,
1686                                   HOST_WIDE_INT size)
1687 {
1688   assemble_label (file, name);
1689
1690   /* Darwin doesn't support zero-size objects, so give them a byte.  */
1691   if ((size) == 0)
1692     assemble_zeros (1);
1693 }
1694
1695 /* Emit an assembler directive to set visibility for a symbol.  The
1696    only supported visibilities are VISIBILITY_DEFAULT and
1697    VISIBILITY_HIDDEN; the latter corresponds to Darwin's "private
1698    extern".  There is no MACH-O equivalent of ELF's
1699    VISIBILITY_INTERNAL or VISIBILITY_PROTECTED. */
1700
1701 void
1702 darwin_assemble_visibility (tree decl, int vis)
1703 {
1704   if (vis == VISIBILITY_DEFAULT)
1705     ;
1706   else if (vis == VISIBILITY_HIDDEN)
1707     {
1708       fputs ("\t.private_extern ", asm_out_file);
1709       assemble_name (asm_out_file,
1710                      (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))));
1711       fputs ("\n", asm_out_file);
1712     }
1713   else
1714     warning (OPT_Wattributes, "internal and protected visibility attributes "
1715              "not supported in this configuration; ignored");
1716 }
1717
1718 /* VEC Used by darwin_asm_dwarf_section.
1719    Maybe a hash tab would be better here - but the intention is that this is
1720    a very short list (fewer than 16 items) and each entry should (ideally, 
1721    eventually) only be presented once.
1722
1723    A structure to hold a dwarf debug section used entry.  */
1724
1725 typedef struct GTY(()) dwarf_sect_used_entry {
1726   const char *name;
1727   unsigned count;
1728 }
1729 dwarf_sect_used_entry;
1730
1731 DEF_VEC_O(dwarf_sect_used_entry);
1732 DEF_VEC_ALLOC_O(dwarf_sect_used_entry, gc);
1733
1734 /* A list of used __DWARF sections.  */
1735 static GTY (()) VEC (dwarf_sect_used_entry, gc) * dwarf_sect_names_table;
1736
1737 /* This is called when we are asked to assemble a named section and the 
1738    name begins with __DWARF,.  We keep a list of the section names (without
1739    the __DWARF, prefix) and use this to emit our required start label on the
1740    first switch to each section.  */
1741
1742 static void
1743 darwin_asm_dwarf_section (const char *name, unsigned int flags,
1744                           tree ARG_UNUSED (decl))
1745 {
1746   unsigned i;
1747   int namelen;
1748   const char * sname;
1749   dwarf_sect_used_entry *ref;
1750   bool found = false;
1751   gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
1752                     == (SECTION_DEBUG | SECTION_NAMED));
1753   /* We know that the name starts with __DWARF,  */
1754   sname = name + 8;
1755   namelen = strchr (sname, ',') - sname;
1756   gcc_assert (namelen);
1757   if (dwarf_sect_names_table == NULL)
1758     dwarf_sect_names_table = VEC_alloc (dwarf_sect_used_entry, gc, 16);
1759   else
1760     for (i = 0; 
1761          VEC_iterate (dwarf_sect_used_entry, dwarf_sect_names_table, i, ref);
1762          i++)
1763       {
1764         if (!ref)
1765           break;
1766         if (!strcmp (ref->name, sname))
1767           {
1768             found = true;
1769             ref->count++;
1770             break;
1771           }
1772       }
1773
1774   fprintf (asm_out_file, "\t.section %s\n", name);
1775   if (!found)
1776     {
1777       dwarf_sect_used_entry e;
1778       fprintf (asm_out_file, "Lsection%.*s:\n", namelen, sname);
1779       e.count = 1;
1780       e.name = xstrdup (sname);
1781       VEC_safe_push (dwarf_sect_used_entry, gc, dwarf_sect_names_table, &e);
1782     }
1783 }
1784
1785 /* Output a difference of two labels that will be an assembly time
1786    constant if the two labels are local.  (.long lab1-lab2 will be
1787    very different if lab1 is at the boundary between two sections; it
1788    will be relocated according to the second section, not the first,
1789    so one ends up with a difference between labels in different
1790    sections, which is bad in the dwarf2 eh context for instance.)  */
1791
1792 static int darwin_dwarf_label_counter;
1793
1794 void
1795 darwin_asm_output_dwarf_delta (FILE *file, int size,
1796                                const char *lab1, const char *lab2)
1797 {
1798   int islocaldiff = (lab1[0] == '*' && lab1[1] == 'L'
1799                      && lab2[0] == '*' && lab2[1] == 'L');
1800   const char *directive = (size == 8 ? ".quad" : ".long");
1801
1802   if (islocaldiff)
1803     fprintf (file, "\t.set L$set$%d,", darwin_dwarf_label_counter);
1804   else
1805     fprintf (file, "\t%s\t", directive);
1806   assemble_name_raw (file, lab1);
1807   fprintf (file, "-");
1808   assemble_name_raw (file, lab2);
1809   if (islocaldiff)
1810     fprintf (file, "\n\t%s L$set$%d", directive, darwin_dwarf_label_counter++);
1811 }
1812
1813 /* Output an offset in a DWARF section on Darwin.  On Darwin, DWARF section
1814    offsets are not represented using relocs in .o files; either the
1815    section never leaves the .o file, or the linker or other tool is
1816    responsible for parsing the DWARF and updating the offsets.  */
1817
1818 void
1819 darwin_asm_output_dwarf_offset (FILE *file, int size, const char * lab,
1820                                 section *base)
1821 {
1822   char sname[64];
1823   int namelen;
1824
1825   gcc_assert (base->common.flags & SECTION_NAMED);
1826   gcc_assert (strncmp (base->named.name, "__DWARF,", 8) == 0);
1827   gcc_assert (strchr (base->named.name + 8, ','));
1828
1829   namelen = strchr (base->named.name + 8, ',') - (base->named.name + 8);
1830   sprintf (sname, "*Lsection%.*s", namelen, base->named.name + 8);
1831   darwin_asm_output_dwarf_delta (file, size, lab, sname);
1832 }
1833
1834 /* Called from the within the TARGET_ASM_FILE_START for each target. 
1835   Initialize the stuff we need for LTO long section names support.  */
1836
1837 void
1838 darwin_file_start (void)
1839 {
1840   /* We fill this obstack with the complete section text for the lto section
1841      names to write in darwin_file_end.  */
1842   obstack_init (&lto_section_names_obstack);
1843   lto_section_names_offset = 0;
1844 }
1845
1846 /* Called for the TARGET_ASM_FILE_END hook.
1847    Emit the mach-o pic indirection data, the lto data and, finally a flag
1848    to tell the linker that it can break the file object into sections and
1849    move those around for efficiency.  */
1850
1851 void
1852 darwin_file_end (void)
1853 {
1854   const char *lto_section_names;
1855
1856   machopic_finish (asm_out_file);
1857   if (strcmp (lang_hooks.name, "GNU C++") == 0)
1858     {
1859       switch_to_section (darwin_sections[constructor_section]);
1860       switch_to_section (darwin_sections[destructor_section]);
1861       ASM_OUTPUT_ALIGN (asm_out_file, 1);
1862     }
1863
1864   /* If there was LTO assembler output, append it to asm_out_file.  */
1865   if (lto_asm_out_name)
1866     {
1867       int n;
1868       char *buf, *lto_asm_txt;
1869
1870       /* Shouldn't be here if we failed to switch back.  */
1871       gcc_assert (! saved_asm_out_file);
1872
1873       lto_asm_out_file = fopen (lto_asm_out_name, "r");
1874       if (lto_asm_out_file == NULL)
1875         fatal_error ("failed to open temporary file %s with LTO output",
1876                      lto_asm_out_name);
1877       fseek (lto_asm_out_file, 0, SEEK_END);
1878       n = ftell (lto_asm_out_file);
1879       if (n > 0)
1880         {
1881           fseek (lto_asm_out_file, 0, SEEK_SET);
1882           lto_asm_txt = buf = (char *) xmalloc (n + 1);
1883           while (fgets (lto_asm_txt, n, lto_asm_out_file))
1884             fputs (lto_asm_txt, asm_out_file);
1885         }
1886
1887       /* Remove the temporary file.  */
1888       fclose (lto_asm_out_file);
1889       unlink_if_ordinary (lto_asm_out_name);
1890       free (lto_asm_out_name);
1891     }
1892
1893   /* Finish the LTO section names obstack.  Don't output anything if
1894      there are no recorded section names.  */
1895   obstack_1grow (&lto_section_names_obstack, '\0');
1896   lto_section_names = XOBFINISH (&lto_section_names_obstack, const char *);
1897   if (strlen (lto_section_names) > 0)
1898     {
1899       fprintf (asm_out_file,
1900                "\t.section %s,%s,regular,debug\n",
1901                LTO_SEGMENT_NAME, LTO_NAMES_SECTION);
1902       fprintf (asm_out_file,
1903                "\t# Section names in %s are offsets into this table\n",
1904                LTO_SEGMENT_NAME);
1905       fprintf (asm_out_file, "%s\n", lto_section_names);
1906     }
1907   obstack_free (&lto_section_names_obstack, NULL);
1908
1909   fprintf (asm_out_file, "\t.subsections_via_symbols\n");
1910 }
1911
1912 /* TODO: Add a language hook for identifying if a decl is a vtable.  */
1913 #define DARWIN_VTABLE_P(DECL) 0
1914
1915 /* Cross-module name binding.  Darwin does not support overriding
1916    functions at dynamic-link time, except for vtables in kexts.  */
1917
1918 bool
1919 darwin_binds_local_p (const_tree decl)
1920 {
1921   return default_binds_local_p_1 (decl,
1922                                   TARGET_KEXTABI && DARWIN_VTABLE_P (decl));
1923 }
1924
1925 #if 0
1926 /* See TARGET_ASM_OUTPUT_ANCHOR for why we can't do this yet.  */
1927 /* The Darwin's implementation of TARGET_ASM_OUTPUT_ANCHOR.  Define the
1928    anchor relative to ".", the current section position.  We cannot use
1929    the default one because ASM_OUTPUT_DEF is wrong for Darwin.  */
1930
1931 void
1932 darwin_asm_output_anchor (rtx symbol)
1933 {
1934   fprintf (asm_out_file, "\t.set\t");
1935   assemble_name (asm_out_file, XSTR (symbol, 0));
1936   fprintf (asm_out_file, ", . + " HOST_WIDE_INT_PRINT_DEC "\n",
1937            SYMBOL_REF_BLOCK_OFFSET (symbol));
1938 }
1939 #endif
1940
1941 /* Set the darwin specific attributes on TYPE.  */
1942 void
1943 darwin_set_default_type_attributes (tree type)
1944 {
1945   if (darwin_ms_struct
1946       && TREE_CODE (type) == RECORD_TYPE)
1947     TYPE_ATTRIBUTES (type) = tree_cons (get_identifier ("ms_struct"),
1948                                         NULL_TREE,
1949                                         TYPE_ATTRIBUTES (type));
1950 }
1951
1952 /* True, iff we're generating code for loadable kernel extensions.  */
1953
1954 bool
1955 darwin_kextabi_p (void) {
1956   return flag_apple_kext;
1957 }
1958
1959 void
1960 darwin_override_options (void)
1961 {
1962   /* Don't emit DWARF3/4 unless specifically selected.  This is a 
1963      workaround for tool bugs.  */
1964   if (dwarf_strict < 0) 
1965     dwarf_strict = 1;
1966
1967   /* Disable -freorder-blocks-and-partition for darwin_emit_unwind_label.  */
1968   if (flag_reorder_blocks_and_partition 
1969       && (targetm.asm_out.emit_unwind_label == darwin_emit_unwind_label))
1970     {
1971       inform (input_location,
1972               "-freorder-blocks-and-partition does not work with exceptions "
1973               "on this architecture");
1974       flag_reorder_blocks_and_partition = 0;
1975       flag_reorder_blocks = 1;
1976     }
1977
1978   if (flag_mkernel || flag_apple_kext)
1979     {
1980       /* -mkernel implies -fapple-kext for C++ */
1981       if (strcmp (lang_hooks.name, "GNU C++") == 0)
1982         flag_apple_kext = 1;
1983
1984       flag_no_common = 1;
1985
1986       /* No EH in kexts.  */
1987       flag_exceptions = 0;
1988       /* No -fnon-call-exceptions data in kexts.  */
1989       flag_non_call_exceptions = 0;
1990       /* We still need to emit branch islands for kernel context.  */
1991       darwin_emit_branch_islands = true;
1992     }
1993   if (flag_var_tracking
1994       && strverscmp (darwin_macosx_version_min, "10.5") >= 0
1995       && debug_info_level >= DINFO_LEVEL_NORMAL
1996       && debug_hooks->var_location != do_nothing_debug_hooks.var_location)
1997     flag_var_tracking_uninit = 1;
1998
1999   if (MACHO_DYNAMIC_NO_PIC_P)
2000     {
2001       if (flag_pic)
2002         warning (0, "-mdynamic-no-pic overrides -fpic or -fPIC");
2003       flag_pic = 0;
2004     }
2005   else if (flag_pic == 1)
2006     {
2007       /* Darwin's -fpic is -fPIC.  */
2008       flag_pic = 2;
2009     }
2010
2011   /* It is assumed that branch island stubs are needed for earlier systems.  */
2012   if (darwin_macosx_version_min
2013       && strverscmp (darwin_macosx_version_min, "10.5") < 0)
2014     darwin_emit_branch_islands = true;
2015
2016   /* The c_dialect...() macros are not available to us here.  */
2017   darwin_running_cxx = (strstr (lang_hooks.name, "C++") != 0);
2018 }
2019
2020 /* Add $LDBL128 suffix to long double builtins.  */
2021
2022 static void
2023 darwin_patch_builtin (int fncode)
2024 {
2025   tree fn = built_in_decls[fncode];
2026   tree sym;
2027   char *newname;
2028
2029   if (!fn)
2030     return;
2031
2032   sym = DECL_ASSEMBLER_NAME (fn);
2033   newname = ACONCAT (("_", IDENTIFIER_POINTER (sym), "$LDBL128", NULL));
2034
2035   set_user_assembler_name (fn, newname);
2036
2037   fn = implicit_built_in_decls[fncode];
2038   if (fn)
2039     set_user_assembler_name (fn, newname);
2040 }
2041
2042 void
2043 darwin_patch_builtins (void)
2044 {
2045   if (LONG_DOUBLE_TYPE_SIZE != 128)
2046     return;
2047
2048 #define PATCH_BUILTIN(fncode) darwin_patch_builtin (fncode);
2049 #define PATCH_BUILTIN_NO64(fncode)              \
2050   if (!TARGET_64BIT)                            \
2051     darwin_patch_builtin (fncode);
2052 #define PATCH_BUILTIN_VARIADIC(fncode)                            \
2053   if (!TARGET_64BIT                                               \
2054       && (strverscmp (darwin_macosx_version_min, "10.3.9") >= 0)) \
2055     darwin_patch_builtin (fncode);
2056 #include "darwin-ppc-ldouble-patch.def"
2057 #undef PATCH_BUILTIN
2058 #undef PATCH_BUILTIN_NO64
2059 #undef PATCH_BUILTIN_VARIADIC
2060 }
2061
2062 /*  CFStrings implementation.  */
2063 static GTY(()) tree cfstring_class_reference = NULL_TREE;
2064 static GTY(()) tree cfstring_type_node = NULL_TREE;
2065 static GTY(()) tree ccfstring_type_node = NULL_TREE;
2066 static GTY(()) tree pccfstring_type_node = NULL_TREE;
2067 static GTY(()) tree pcint_type_node = NULL_TREE;
2068 static GTY(()) tree pcchar_type_node = NULL_TREE;
2069
2070 static enum built_in_function DARWIN_BUILTIN_CFSTRINGMAKECONSTANTSTRING;
2071
2072 /* Store all constructed constant CFStrings in a hash table so that
2073    they get uniqued properly.  */
2074
2075 typedef struct GTY (()) cfstring_descriptor {
2076   /* The string literal.  */
2077   tree literal;
2078   /* The resulting constant CFString.  */
2079   tree constructor;
2080 } cfstring_descriptor;
2081
2082 static GTY ((param_is (struct cfstring_descriptor))) htab_t cfstring_htab;
2083
2084 static hashval_t cfstring_hash (const void *);
2085 static int cfstring_eq (const void *, const void *);
2086
2087 static tree
2088 add_builtin_field_decl (tree type, const char *name, tree **chain)
2089 {
2090   tree field = build_decl (BUILTINS_LOCATION, FIELD_DECL, 
2091                             get_identifier (name), type);
2092
2093   if (*chain != NULL)
2094     **chain = field;
2095   *chain = &DECL_CHAIN (field);
2096
2097   return field;
2098 }
2099
2100 void
2101 darwin_init_cfstring_builtins (unsigned first_avail)
2102 {
2103   tree cfsfun, fields, pccfstring_ftype_pcchar;
2104   tree *chain = NULL;
2105
2106   DARWIN_BUILTIN_CFSTRINGMAKECONSTANTSTRING = 
2107                         (enum built_in_function) first_avail;
2108   
2109   /* struct __builtin_CFString {
2110        const int *isa;          (will point at
2111        int flags;                __CFConstantStringClassReference)
2112        const char *str;
2113        long length;
2114      };  */
2115
2116   pcint_type_node = build_pointer_type 
2117                    (build_qualified_type (integer_type_node, TYPE_QUAL_CONST));
2118
2119   pcchar_type_node = build_pointer_type 
2120                    (build_qualified_type (char_type_node, TYPE_QUAL_CONST));
2121
2122   cfstring_type_node = (*lang_hooks.types.make_type) (RECORD_TYPE);
2123
2124   /* Have to build backwards for finish struct.  */
2125   fields = add_builtin_field_decl (long_integer_type_node, "length", &chain);
2126   add_builtin_field_decl (pcchar_type_node, "str", &chain);
2127   add_builtin_field_decl (integer_type_node, "flags", &chain);
2128   add_builtin_field_decl (pcint_type_node, "isa", &chain);
2129   finish_builtin_struct (cfstring_type_node, "__builtin_CFString",
2130                          fields, NULL_TREE);
2131
2132   /* const struct __builtin_CFstring *
2133      __builtin___CFStringMakeConstantString (const char *); */
2134
2135   ccfstring_type_node = build_qualified_type 
2136                         (cfstring_type_node, TYPE_QUAL_CONST);
2137   pccfstring_type_node = build_pointer_type (ccfstring_type_node);
2138   pccfstring_ftype_pcchar = build_function_type_list 
2139                         (pccfstring_type_node, pcchar_type_node, NULL_TREE);
2140
2141   cfsfun  = build_decl (BUILTINS_LOCATION, FUNCTION_DECL, 
2142                         get_identifier ("__builtin___CFStringMakeConstantString"),
2143                         pccfstring_ftype_pcchar);
2144
2145   TREE_PUBLIC (cfsfun) = 1;
2146   DECL_EXTERNAL (cfsfun) = 1;
2147   DECL_ARTIFICIAL (cfsfun) = 1;
2148   /* Make a lang-specific section - dup_lang_specific_decl makes a new node
2149      in place of the existing, which may be NULL.  */
2150   DECL_LANG_SPECIFIC (cfsfun) = NULL;
2151   (*lang_hooks.dup_lang_specific_decl) (cfsfun);
2152   DECL_BUILT_IN_CLASS (cfsfun) = BUILT_IN_MD;
2153   DECL_FUNCTION_CODE (cfsfun) = DARWIN_BUILTIN_CFSTRINGMAKECONSTANTSTRING;
2154   lang_hooks.builtin_function (cfsfun);
2155
2156   /* extern int __CFConstantStringClassReference[];  */
2157   cfstring_class_reference = build_decl (BUILTINS_LOCATION, VAR_DECL,
2158                  get_identifier ("__CFConstantStringClassReference"),
2159                  build_array_type (integer_type_node, NULL_TREE));
2160
2161   TREE_PUBLIC (cfstring_class_reference) = 1;
2162   DECL_ARTIFICIAL (cfstring_class_reference) = 1;
2163   (*lang_hooks.decls.pushdecl) (cfstring_class_reference);
2164   DECL_EXTERNAL (cfstring_class_reference) = 1;
2165   rest_of_decl_compilation (cfstring_class_reference, 0, 0);
2166   
2167   /* Initialize the hash table used to hold the constant CFString objects.  */
2168   cfstring_htab = htab_create_ggc (31, cfstring_hash, cfstring_eq, NULL);
2169 }
2170
2171 tree
2172 darwin_fold_builtin (tree fndecl, int n_args, tree *argp, 
2173                      bool ARG_UNUSED (ignore))
2174 {
2175   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
2176   
2177   if (fcode == DARWIN_BUILTIN_CFSTRINGMAKECONSTANTSTRING)
2178     {
2179       if (!darwin_constant_cfstrings)
2180         {
2181           error ("built-in function %qD requires the" 
2182                  " %<-mconstant-cfstrings%> flag", fndecl);
2183           return error_mark_node;
2184         }
2185
2186       if (n_args != 1)
2187         {
2188           error ("built-in function %qD takes one argument only", fndecl);
2189           return error_mark_node;
2190         }
2191
2192       return darwin_build_constant_cfstring (*argp);
2193     }
2194
2195   return NULL_TREE;
2196 }
2197
2198 static hashval_t
2199 cfstring_hash (const void *ptr)
2200 {
2201   tree str = ((const struct cfstring_descriptor *)ptr)->literal;
2202   const unsigned char *p = (const unsigned char *) TREE_STRING_POINTER (str);
2203   int i, len = TREE_STRING_LENGTH (str);
2204   hashval_t h = len;
2205
2206   for (i = 0; i < len; i++)
2207     h = ((h * 613) + p[i]);
2208
2209   return h;
2210 }
2211
2212 static int
2213 cfstring_eq (const void *ptr1, const void *ptr2)
2214 {
2215   tree str1 = ((const struct cfstring_descriptor *)ptr1)->literal;
2216   tree str2 = ((const struct cfstring_descriptor *)ptr2)->literal;
2217   int len1 = TREE_STRING_LENGTH (str1);
2218
2219   return (len1 == TREE_STRING_LENGTH (str2)
2220           && !memcmp (TREE_STRING_POINTER (str1), TREE_STRING_POINTER (str2),
2221                       len1));
2222 }
2223
2224 tree
2225 darwin_build_constant_cfstring (tree str)
2226 {
2227   struct cfstring_descriptor *desc, key;
2228   void **loc;
2229   tree addr;
2230
2231   if (!str)
2232     {
2233       error ("CFString literal is missing");
2234       return error_mark_node;
2235     }
2236
2237   STRIP_NOPS (str);
2238
2239   if (TREE_CODE (str) == ADDR_EXPR)
2240     str = TREE_OPERAND (str, 0);
2241
2242   if (TREE_CODE (str) != STRING_CST)
2243     {
2244       error ("CFString literal expression is not a string constant");
2245       return error_mark_node;
2246     }
2247
2248   /* Perhaps we already constructed a constant CFString just like this one? */
2249   key.literal = str;
2250   loc = htab_find_slot (cfstring_htab, &key, INSERT);
2251   desc = (struct cfstring_descriptor *) *loc;
2252
2253   if (!desc)
2254     {
2255       tree var, constructor, field;
2256       VEC(constructor_elt,gc) *v = NULL;
2257       int length = TREE_STRING_LENGTH (str) - 1;
2258
2259       if (darwin_warn_nonportable_cfstrings)
2260         {
2261           const char *s = TREE_STRING_POINTER (str);
2262           int l = 0;
2263
2264           for (l = 0; l < length; l++)
2265             if (!s[l] || !isascii (s[l]))
2266               {
2267                 warning (darwin_warn_nonportable_cfstrings, "%s in CFString literal",
2268                          s[l] ? "non-ASCII character" : "embedded NUL");
2269                 break;
2270               }
2271         }
2272
2273       *loc = desc = ggc_alloc_cleared_cfstring_descriptor ();
2274       desc->literal = str;
2275
2276       /* isa *. */
2277       field = TYPE_FIELDS (ccfstring_type_node);
2278       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE, 
2279                              build1 (ADDR_EXPR,  TREE_TYPE (field),  
2280                                      cfstring_class_reference));
2281       /* flags */
2282       field = DECL_CHAIN (field);
2283       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE, 
2284                              build_int_cst (TREE_TYPE (field), 0x000007c8));
2285       /* string *. */
2286       field = DECL_CHAIN (field);
2287       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
2288                              build1 (ADDR_EXPR, TREE_TYPE (field), str));
2289       /* length */
2290       field = DECL_CHAIN (field);
2291       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
2292                              build_int_cst (TREE_TYPE (field), length));
2293
2294       constructor = build_constructor (ccfstring_type_node, v);
2295       TREE_READONLY (constructor) = 1;
2296       TREE_CONSTANT (constructor) = 1;
2297       TREE_STATIC (constructor) = 1;
2298
2299       /* Fromage: The C++ flavor of 'build_unary_op' expects constructor nodes
2300          to have the TREE_HAS_CONSTRUCTOR (...) bit set.  However, this file is
2301          being built without any knowledge of C++ tree accessors; hence, we shall
2302          use the generic accessor that TREE_HAS_CONSTRUCTOR actually maps to!  */
2303       if (darwin_running_cxx)
2304         TREE_LANG_FLAG_4 (constructor) = 1;  /* TREE_HAS_CONSTRUCTOR  */
2305
2306       /* Create an anonymous global variable for this CFString.  */
2307       var = build_decl (input_location, CONST_DECL, 
2308                         NULL, TREE_TYPE (constructor));
2309       DECL_ARTIFICIAL (var) = 1;
2310       TREE_STATIC (var) = 1;
2311       DECL_INITIAL (var) = constructor;
2312       /* FIXME: This should use a translation_unit_decl to indicate file scope.  */
2313       DECL_CONTEXT (var) = NULL_TREE;
2314       desc->constructor = var;
2315     }
2316
2317   addr = build1 (ADDR_EXPR, pccfstring_type_node, desc->constructor);
2318   TREE_CONSTANT (addr) = 1;
2319
2320   return addr;
2321 }
2322
2323 bool
2324 darwin_cfstring_p (tree str)
2325 {
2326   struct cfstring_descriptor key;
2327   void **loc;
2328
2329   if (!str)
2330     return false;
2331
2332   STRIP_NOPS (str);
2333
2334   if (TREE_CODE (str) == ADDR_EXPR)
2335     str = TREE_OPERAND (str, 0);
2336
2337   if (TREE_CODE (str) != STRING_CST)
2338     return false;
2339
2340   key.literal = str;
2341   loc = htab_find_slot (cfstring_htab, &key, NO_INSERT);
2342   
2343   if (loc)
2344     return true;
2345
2346   return false;
2347 }
2348
2349 void
2350 darwin_enter_string_into_cfstring_table (tree str)
2351 {
2352   struct cfstring_descriptor key;
2353   void **loc;
2354
2355   key.literal = str;
2356   loc = htab_find_slot (cfstring_htab, &key, INSERT);
2357
2358   if (!*loc)
2359     {
2360       *loc = ggc_alloc_cleared_cfstring_descriptor ();
2361       ((struct cfstring_descriptor *)*loc)->literal = str;
2362     }
2363 }
2364
2365 #include "gt-darwin.h"