OSDN Git Service

* gcc.dg/lto/ipareference2_0.c: New file.
[pf3gnuchains/gcc-fork.git] / gcc / lto / lto.c
1 /* Top-level LTO routines.
2    Copyright 2009, 2010 Free Software Foundation, Inc.
3    Contributed by CodeSourcery, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "opts.h"
25 #include "toplev.h"
26 #include "tree.h"
27 #include "diagnostic.h"
28 #include "tm.h"
29 #include "libiberty.h"
30 #include "cgraph.h"
31 #include "ggc.h"
32 #include "tree-ssa-operands.h"
33 #include "tree-pass.h"
34 #include "langhooks.h"
35 #include "vec.h"
36 #include "bitmap.h"
37 #include "pointer-set.h"
38 #include "ipa-prop.h"
39 #include "common.h"
40 #include "timevar.h"
41 #include "gimple.h"
42 #include "lto.h"
43 #include "lto-tree.h"
44 #include "lto-streamer.h"
45
46 /* This needs to be included after config.h.  Otherwise, _GNU_SOURCE will not
47    be defined in time to set __USE_GNU in the system headers, and strsignal
48    will not be declared.  */
49 #if HAVE_MMAP_FILE
50 #include <sys/mman.h>
51 #endif
52
53 /* Handle opening elf files on hosts, such as Windows, that may use 
54    text file handling that will break binary access.  */
55
56 #ifndef O_BINARY
57 # define O_BINARY 0
58 #endif
59
60
61 DEF_VEC_P(bitmap);
62 DEF_VEC_ALLOC_P(bitmap,heap);
63
64 /* Read the constructors and inits.  */
65
66 static void
67 lto_materialize_constructors_and_inits (struct lto_file_decl_data * file_data)
68 {
69   size_t len;
70   const char *data = lto_get_section_data (file_data, 
71                                            LTO_section_static_initializer,
72                                            NULL, &len);
73   lto_input_constructors_and_inits (file_data, data);
74   lto_free_section_data (file_data, LTO_section_static_initializer, NULL,
75                          data, len);
76 }
77
78 /* Read the function body for the function associated with NODE if possible.  */
79
80 static void
81 lto_materialize_function (struct cgraph_node *node)
82 {
83   tree decl;
84   struct lto_file_decl_data *file_data;
85   const char *data, *name;
86   size_t len;
87
88   /* Ignore clone nodes.  Read the body only from the original one.
89      We may find clone nodes during LTRANS after WPA has made inlining
90      decisions.  */
91   if (node->clone_of)
92     return;
93
94   decl = node->decl;
95   file_data = node->local.lto_file_data;
96   name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)); 
97
98   /* We may have renamed the declaration, e.g., a static function.  */
99   name = lto_get_decl_name_mapping (file_data, name);
100
101   data = lto_get_section_data (file_data, LTO_section_function_body,
102                                name, &len);
103   if (data)
104     {
105       gcc_assert (!DECL_IS_BUILTIN (decl));
106
107       /* This function has a definition.  */
108       TREE_STATIC (decl) = 1;
109
110       gcc_assert (DECL_STRUCT_FUNCTION (decl) == NULL);
111
112       /* Load the function body only if not operating in WPA mode.  In
113          WPA mode, the body of the function is not needed.  */
114       if (!flag_wpa)
115         {
116          allocate_struct_function (decl, false);
117           announce_function (node->decl);
118           lto_input_function_body (file_data, decl, data);
119           lto_stats.num_function_bodies++;
120         }
121
122       lto_free_section_data (file_data, LTO_section_function_body, name,
123                              data, len);
124       if (!flag_wpa)
125         ggc_collect ();
126     }
127   else
128     DECL_EXTERNAL (decl) = 1;
129
130   /* Let the middle end know about the function.  */
131   rest_of_decl_compilation (decl, 1, 0);
132 }
133
134
135 /* Decode the content of memory pointed to by DATA in the the
136    in decl state object STATE. DATA_IN points to a data_in structure for
137    decoding. Return the address after the decoded object in the input.  */
138
139 static const uint32_t *
140 lto_read_in_decl_state (struct data_in *data_in, const uint32_t *data,
141                         struct lto_in_decl_state *state)
142 {
143   uint32_t ix;
144   tree decl;
145   uint32_t i, j;
146   
147   ix = *data++;
148   decl = lto_streamer_cache_get (data_in->reader_cache, (int) ix);
149   if (TREE_CODE (decl) != FUNCTION_DECL)
150     {
151       gcc_assert (decl == void_type_node);
152       decl = NULL_TREE;
153     }
154   state->fn_decl = decl;
155
156   for (i = 0; i < LTO_N_DECL_STREAMS; i++)
157     {
158       uint32_t size = *data++;
159       tree *decls = GGC_NEWVEC (tree, size);
160
161       for (j = 0; j < size; j++)
162         {
163           decls[j] = lto_streamer_cache_get (data_in->reader_cache, data[j]);
164
165           /* Register every type in the global type table.  If the
166              type existed already, use the existing type.  */
167           if (TYPE_P (decls[j]))
168             decls[j] = gimple_register_type (decls[j]);
169         }
170
171       state->streams[i].size = size;
172       state->streams[i].trees = decls;
173       data += size;
174     }
175
176   return data;
177 }
178
179
180 /* Read all the symbols from buffer DATA, using descriptors in DECL_DATA.
181    RESOLUTIONS is the set of symbols picked by the linker (read from the
182    resolution file when the linker plugin is being used).  */
183
184 static void
185 lto_read_decls (struct lto_file_decl_data *decl_data, const void *data,
186                 VEC(ld_plugin_symbol_resolution_t,heap) *resolutions)
187 {
188   const struct lto_decl_header *header = (const struct lto_decl_header *) data;
189   const int32_t decl_offset = sizeof (struct lto_decl_header);
190   const int32_t main_offset = decl_offset + header->decl_state_size;
191   const int32_t string_offset = main_offset + header->main_size;
192   struct lto_input_block ib_main;
193   struct data_in *data_in;
194   unsigned int i;
195   const uint32_t *data_ptr, *data_end;
196   uint32_t num_decl_states;
197
198   LTO_INIT_INPUT_BLOCK (ib_main, (const char *) data + main_offset, 0,
199                         header->main_size);
200
201   data_in = lto_data_in_create (decl_data, (const char *) data + string_offset,
202                                 header->string_size, resolutions);
203
204   /* Read the global declarations and types.  */
205   while (ib_main.p < ib_main.len)
206     {
207       tree t = lto_input_tree (&ib_main, data_in);
208       gcc_assert (t && ib_main.p <= ib_main.len);
209     }
210
211   /* Read in lto_in_decl_state objects.  */
212   data_ptr = (const uint32_t *) ((const char*) data + decl_offset); 
213   data_end =
214      (const uint32_t *) ((const char*) data_ptr + header->decl_state_size);
215   num_decl_states = *data_ptr++;
216   
217   gcc_assert (num_decl_states > 0);
218   decl_data->global_decl_state = lto_new_in_decl_state ();
219   data_ptr = lto_read_in_decl_state (data_in, data_ptr,
220                                      decl_data->global_decl_state);
221
222   /* Read in per-function decl states and enter them in hash table.  */
223   decl_data->function_decl_states =
224     htab_create_ggc (37, lto_hash_in_decl_state, lto_eq_in_decl_state, NULL);
225
226   for (i = 1; i < num_decl_states; i++)
227     {
228       struct lto_in_decl_state *state = lto_new_in_decl_state ();
229       void **slot;
230
231       data_ptr = lto_read_in_decl_state (data_in, data_ptr, state);
232       slot = htab_find_slot (decl_data->function_decl_states, state, INSERT);
233       gcc_assert (*slot == NULL);
234       *slot = state;
235     }
236
237   if (data_ptr != data_end)
238     internal_error ("bytecode stream: garbage at the end of symbols section");
239   
240   /* Set the current decl state to be the global state. */
241   decl_data->current_decl_state = decl_data->global_decl_state;
242
243   lto_data_in_delete (data_in);
244 }
245
246 /* strtoll is not portable. */
247 int64_t
248 lto_parse_hex (const char *p) {
249   uint64_t ret = 0;
250   for (; *p != '\0'; ++p)
251     {
252       char c = *p;
253       unsigned char part;
254       ret <<= 4;
255       if (c >= '0' && c <= '9')
256         part = c - '0';
257       else if (c >= 'a' && c <= 'f')
258         part = c - 'a' + 10;
259       else if (c >= 'A' && c <= 'F')
260         part = c - 'A' + 10;
261       else
262         internal_error ("could not parse hex number");
263       ret |= part;
264     }
265   return ret;
266 }
267
268 /* Read resolution for file named FILE_NAME. The resolution is read from
269    RESOLUTION. An array with the symbol resolution is returned. The array
270    size is written to SIZE. */
271
272 static VEC(ld_plugin_symbol_resolution_t,heap) *
273 lto_resolution_read (FILE *resolution, lto_file *file)
274 {
275   /* We require that objects in the resolution file are in the same
276      order as the lto1 command line. */
277   unsigned int name_len;
278   char *obj_name;
279   unsigned int num_symbols;
280   unsigned int i;
281   VEC(ld_plugin_symbol_resolution_t,heap) *ret = NULL;
282   unsigned max_index = 0;
283
284   if (!resolution)
285     return NULL;
286
287   name_len = strlen (file->filename);
288   obj_name = XNEWVEC (char, name_len + 1);
289   fscanf (resolution, " ");   /* Read white space. */
290
291   fread (obj_name, sizeof (char), name_len, resolution);
292   obj_name[name_len] = '\0';
293   if (strcmp (obj_name, file->filename) != 0)
294     internal_error ("unexpected file name %s in linker resolution file. "
295                     "Expected %s", obj_name, file->filename);
296   if (file->offset != 0)
297     {
298       int t;
299       char offset_p[17];
300       int64_t offset;
301       t = fscanf (resolution, "@0x%16s", offset_p);
302       if (t != 1)
303         internal_error ("could not parse file offset");
304       offset = lto_parse_hex (offset_p);
305       if (offset != file->offset)
306         internal_error ("unexpected offset");
307     }
308
309   free (obj_name);
310
311   fscanf (resolution, "%u", &num_symbols);
312
313   for (i = 0; i < num_symbols; i++)
314     {
315       int t;
316       unsigned index;
317       char r_str[27];
318       enum ld_plugin_symbol_resolution r;
319       unsigned int j;
320       unsigned int lto_resolution_str_len =
321         sizeof (lto_resolution_str) / sizeof (char *);
322
323       t = fscanf (resolution, "%u %26s %*[^\n]\n", &index, r_str);
324       if (t != 2)
325         internal_error ("Invalid line in the resolution file.");
326       if (index > max_index)
327         max_index = index;
328
329       for (j = 0; j < lto_resolution_str_len; j++)
330         {
331           if (strcmp (lto_resolution_str[j], r_str) == 0)
332             {
333               r = (enum ld_plugin_symbol_resolution) j;
334               break;
335             }
336         }
337       if (j == lto_resolution_str_len)
338         internal_error ("Invalid resolution in the resolution file.");
339
340       VEC_safe_grow_cleared (ld_plugin_symbol_resolution_t, heap, ret,
341                              max_index + 1);
342       VEC_replace (ld_plugin_symbol_resolution_t, ret, index, r);
343     }
344
345   return ret;
346 }
347
348 /* Generate a TREE representation for all types and external decls
349    entities in FILE.  
350
351    Read all of the globals out of the file.  Then read the cgraph
352    and process the .o index into the cgraph nodes so that it can open
353    the .o file to load the functions and ipa information.   */
354
355 static struct lto_file_decl_data *
356 lto_file_read (lto_file *file, FILE *resolution_file)
357 {
358   struct lto_file_decl_data *file_data;
359   const char *data;
360   size_t len;
361   VEC(ld_plugin_symbol_resolution_t,heap) *resolutions;
362   
363   resolutions = lto_resolution_read (resolution_file, file);
364
365   file_data = GGC_NEW (struct lto_file_decl_data);
366   file_data->file_name = file->filename;
367   file_data->section_hash_table = lto_obj_build_section_table (file);
368   file_data->renaming_hash_table = lto_create_renaming_table ();
369
370   data = lto_get_section_data (file_data, LTO_section_decls, NULL, &len);
371   lto_read_decls (file_data, data, resolutions);
372   lto_free_section_data (file_data, LTO_section_decls, NULL, data, len);
373
374   return file_data;
375 }
376
377 #if HAVE_MMAP_FILE && HAVE_SYSCONF && defined _SC_PAGE_SIZE
378 #define LTO_MMAP_IO 1
379 #endif
380
381 #if LTO_MMAP_IO
382 /* Page size of machine is used for mmap and munmap calls.  */
383 static size_t page_mask;
384 #endif
385
386 /* Get the section data of length LEN from FILENAME starting at
387    OFFSET.  The data segment must be freed by the caller when the
388    caller is finished.  Returns NULL if all was not well.  */
389
390 static char *
391 lto_read_section_data (struct lto_file_decl_data *file_data,
392                        intptr_t offset, size_t len)
393 {
394   char *result;
395   static int fd = -1;
396   static char *fd_name;
397 #if LTO_MMAP_IO
398   intptr_t computed_len;
399   intptr_t computed_offset;
400   intptr_t diff;
401 #endif
402
403   /* Keep a single-entry file-descriptor cache.  The last file we
404      touched will get closed at exit.
405      ???  Eventually we want to add a more sophisticated larger cache
406      or rather fix function body streaming to not stream them in
407      practically random order.  */
408   if (fd != -1
409       && strcmp (fd_name, file_data->file_name) != 0)
410     {
411       free (fd_name);
412       close (fd);
413       fd = -1;
414     }
415   if (fd == -1)
416     {
417       fd_name = xstrdup (file_data->file_name);
418       fd = open (file_data->file_name, O_RDONLY|O_BINARY);
419       if (fd == -1)
420         return NULL;
421     }
422
423 #if LTO_MMAP_IO
424   if (!page_mask)
425     {
426       size_t page_size = sysconf (_SC_PAGE_SIZE);
427       page_mask = ~(page_size - 1);
428     }
429
430   computed_offset = offset & page_mask;
431   diff = offset - computed_offset;
432   computed_len = len + diff;
433
434   result = (char *) mmap (NULL, computed_len, PROT_READ, MAP_PRIVATE,
435                           fd, computed_offset);
436   if (result == MAP_FAILED)
437     return NULL;
438
439   return result + diff;
440 #else
441   result = (char *) xmalloc (len);
442   if (lseek (fd, offset, SEEK_SET) != offset
443       || read (fd, result, len) != (ssize_t) len)
444     {
445       free (result);
446       return NULL;
447     }
448
449   return result;
450 #endif
451 }    
452
453
454 /* Get the section data from FILE_DATA of SECTION_TYPE with NAME.
455    NAME will be NULL unless the section type is for a function
456    body.  */
457
458 static const char *
459 get_section_data (struct lto_file_decl_data *file_data,
460                       enum lto_section_type section_type,
461                       const char *name,
462                       size_t *len)
463 {
464   htab_t section_hash_table = file_data->section_hash_table;
465   struct lto_section_slot *f_slot;
466   struct lto_section_slot s_slot;
467   const char *section_name = lto_get_section_name (section_type, name);
468   char *data = NULL;
469
470   *len = 0;
471   s_slot.name = section_name;
472   f_slot = (struct lto_section_slot *) htab_find (section_hash_table, &s_slot);
473   if (f_slot)
474     {
475       data = lto_read_section_data (file_data, f_slot->start, f_slot->len);
476       *len = f_slot->len;
477     }
478
479   free (CONST_CAST (char *, section_name));
480   return data;
481 }
482
483
484 /* Free the section data from FILE_DATA of SECTION_TYPE with NAME that
485    starts at OFFSET and has LEN bytes.  */
486
487 static void
488 free_section_data (struct lto_file_decl_data *file_data ATTRIBUTE_UNUSED,
489                    enum lto_section_type section_type ATTRIBUTE_UNUSED,
490                    const char *name ATTRIBUTE_UNUSED,
491                    const char *offset, size_t len ATTRIBUTE_UNUSED)
492 {
493 #if LTO_MMAP_IO
494   intptr_t computed_len;
495   intptr_t computed_offset;
496   intptr_t diff;
497 #endif
498
499 #if LTO_MMAP_IO
500   computed_offset = ((intptr_t) offset) & page_mask;
501   diff = (intptr_t) offset - computed_offset;
502   computed_len = len + diff;
503
504   munmap ((caddr_t) computed_offset, computed_len);
505 #else
506   free (CONST_CAST(char *, offset));
507 #endif
508 }
509
510 /* Vector of all cgraph node sets. */
511 static GTY (()) VEC(cgraph_node_set, gc) *lto_cgraph_node_sets;
512 static GTY (()) VEC(varpool_node_set, gc) *lto_varpool_node_sets;
513
514
515 /* Group cgrah nodes by input files.  This is used mainly for testing
516    right now.  */
517
518 static void
519 lto_1_to_1_map (void)
520 {
521   struct cgraph_node *node;
522   struct varpool_node *vnode;
523   struct lto_file_decl_data *file_data;
524   struct pointer_map_t *pmap;
525   struct pointer_map_t *vpmap;
526   cgraph_node_set set;
527   varpool_node_set vset;
528   void **slot;
529
530   timevar_push (TV_WHOPR_WPA);
531
532   lto_cgraph_node_sets = VEC_alloc (cgraph_node_set, gc, 1);
533   lto_varpool_node_sets = VEC_alloc (varpool_node_set, gc, 1);
534
535   pmap = pointer_map_create ();
536   vpmap = pointer_map_create ();
537
538   for (node = cgraph_nodes; node; node = node->next)
539     {
540       /* We will get proper partition based on function they are inlined to.  */
541       if (node->global.inlined_to)
542         continue;
543       /* Nodes without a body do not need partitioning.  */
544       if (!node->analyzed)
545         continue;
546
547       file_data = node->local.lto_file_data;
548       gcc_assert (!node->same_body_alias && file_data);
549
550       slot = pointer_map_contains (pmap, file_data);
551       if (slot)
552         set = (cgraph_node_set) *slot;
553       else
554         {
555           set = cgraph_node_set_new ();
556           slot = pointer_map_insert (pmap, file_data);
557           *slot = set;
558           VEC_safe_push (cgraph_node_set, gc, lto_cgraph_node_sets, set);
559           vset = varpool_node_set_new ();
560           slot = pointer_map_insert (vpmap, file_data);
561           *slot = vset;
562           VEC_safe_push (varpool_node_set, gc, lto_varpool_node_sets, vset);
563         }
564
565       cgraph_node_set_add (set, node);
566     }
567
568   for (vnode = varpool_nodes; vnode; vnode = vnode->next)
569     {
570       if (vnode->alias || !vnode->needed)
571         continue;
572       slot = pointer_map_contains (vpmap, file_data);
573       if (slot)
574         vset = (varpool_node_set) *slot;
575       else
576         {
577           set = cgraph_node_set_new ();
578           slot = pointer_map_insert (pmap, file_data);
579           *slot = set;
580           VEC_safe_push (cgraph_node_set, gc, lto_cgraph_node_sets, set);
581           vset = varpool_node_set_new ();
582           slot = pointer_map_insert (vpmap, file_data);
583           *slot = vset;
584           VEC_safe_push (varpool_node_set, gc, lto_varpool_node_sets, vset);
585         }
586
587       varpool_node_set_add (vset, vnode);
588     }
589
590   /* If the cgraph is empty, create one cgraph node set so that there is still
591      an output file for any variables that need to be exported in a DSO.  */
592   if (!lto_cgraph_node_sets)
593     {
594       set = cgraph_node_set_new ();
595       VEC_safe_push (cgraph_node_set, gc, lto_cgraph_node_sets, set);
596       vset = varpool_node_set_new ();
597       VEC_safe_push (varpool_node_set, gc, lto_varpool_node_sets, vset);
598     }
599
600   pointer_map_destroy (pmap);
601   pointer_map_destroy (vpmap);
602
603   timevar_pop (TV_WHOPR_WPA);
604
605   lto_stats.num_cgraph_partitions += VEC_length (cgraph_node_set, 
606                                                  lto_cgraph_node_sets);
607 }
608
609
610 /* Add inlined clone NODE and its master clone to SET, if NODE itself has
611    inlined callees, recursively add the callees.  */
612
613 static void
614 lto_add_inline_clones (cgraph_node_set set, struct cgraph_node *node,
615                        bitmap original_decls)
616 {
617    struct cgraph_node *callee;
618    struct cgraph_edge *edge;
619
620    cgraph_node_set_add (set, node);
621
622    /* Check to see if NODE has any inlined callee.  */
623    for (edge = node->callees; edge != NULL; edge = edge->next_callee)
624      {
625         callee = edge->callee;
626         if (callee->global.inlined_to != NULL)
627           lto_add_inline_clones (set, callee, original_decls);
628      }
629 }
630
631 /* Compute the transitive closure of inlining of SET based on the
632    information in the callgraph.  Returns a bitmap of decls that have
633    been inlined into SET indexed by UID.  */
634
635 static void
636 lto_add_all_inlinees (cgraph_node_set set)
637 {
638   cgraph_node_set_iterator csi;
639   struct cgraph_node *node;
640   bitmap original_nodes = lto_bitmap_alloc ();
641   bitmap original_decls = lto_bitmap_alloc ();
642   bool changed;
643
644   /* We are going to iterate SET while adding to it, mark all original
645      nodes so that we only add node inlined to original nodes.  */
646   for (csi = csi_start (set); !csi_end_p (csi); csi_next (&csi))
647     {
648       bitmap_set_bit (original_nodes, csi_node (csi)->uid);
649       bitmap_set_bit (original_decls, DECL_UID (csi_node (csi)->decl));
650     }
651
652   /* Some of the original nodes might not be needed anymore.  
653      Remove them.  */
654   do
655     {
656       changed = false;
657       for (csi = csi_start (set); !csi_end_p (csi); csi_next (&csi))
658         {
659           struct cgraph_node *inlined_to;
660           node = csi_node (csi);
661
662           /* NODE was not inlined.  We still need it.  */
663           if (!node->global.inlined_to)
664             continue;
665
666           inlined_to = node->global.inlined_to;
667
668           /* NODE should have only one caller.  */
669           gcc_assert (!node->callers->next_caller);
670
671           if (!bitmap_bit_p (original_nodes, inlined_to->uid))
672             {
673               bitmap_clear_bit (original_nodes, node->uid);
674               cgraph_node_set_remove (set, node);
675               changed = true;
676             }
677         }
678     }
679   while (changed);
680
681  /* Transitively add to SET all the inline clones for every node that
682     has been inlined.  */
683  for (csi = csi_start (set); !csi_end_p (csi); csi_next (&csi))
684    {
685      node = csi_node (csi);
686      if (bitmap_bit_p (original_nodes, node->uid))
687       lto_add_inline_clones (set, node, original_decls);
688    }
689
690   lto_bitmap_free (original_nodes);
691   lto_bitmap_free (original_decls);
692 }
693
694 /* Promote variable VNODE to be static.  */
695
696 static bool
697 promote_var (struct varpool_node *vnode)
698 {
699   if (TREE_PUBLIC (vnode->decl) || DECL_EXTERNAL (vnode->decl))
700     return false;
701   gcc_assert (flag_wpa);
702   TREE_PUBLIC (vnode->decl) = 1;
703   DECL_VISIBILITY (vnode->decl) = VISIBILITY_HIDDEN;
704   return true;
705 }
706
707 /* Promote function NODE to be static.  */
708
709 static bool
710 promote_fn (struct cgraph_node *node)
711 {
712   gcc_assert (flag_wpa);
713   if (TREE_PUBLIC (node->decl) || DECL_EXTERNAL (node->decl))
714     return false;
715   TREE_PUBLIC (node->decl) = 1;
716   DECL_VISIBILITY (node->decl) = VISIBILITY_HIDDEN;
717   if (node->same_body)
718     {
719       struct cgraph_node *alias;
720       for (alias = node->same_body;
721            alias; alias = alias->next)
722         {
723           TREE_PUBLIC (alias->decl) = 1;
724           DECL_VISIBILITY (alias->decl) = VISIBILITY_HIDDEN;
725         }
726     }
727   return true;
728 }
729
730 /* Find out all static decls that need to be promoted to global because
731    of cross file sharing.  This function must be run in the WPA mode after
732    all inlinees are added.  */
733
734 static void
735 lto_promote_cross_file_statics (void)
736 {
737   struct varpool_node *vnode;
738   unsigned i, n_sets;
739   cgraph_node_set set;
740   varpool_node_set vset;
741   cgraph_node_set_iterator csi;
742   varpool_node_set_iterator vsi;
743   VEC(varpool_node_ptr, heap) *promoted_initializers = NULL;
744   struct pointer_set_t *inserted = pointer_set_create ();
745
746   gcc_assert (flag_wpa);
747
748   n_sets = VEC_length (cgraph_node_set, lto_cgraph_node_sets);
749   for (i = 0; i < n_sets; i++)
750     {
751       set = VEC_index (cgraph_node_set, lto_cgraph_node_sets, i);
752       vset = VEC_index (varpool_node_set, lto_varpool_node_sets, i);
753
754       /* If node has either address taken (and we have no clue from where)
755          or it is called from other partition, it needs to be globalized.  */
756       for (csi = csi_start (set); !csi_end_p (csi); csi_next (&csi))
757         {
758           struct cgraph_node *node = csi_node (csi);
759           if (node->local.externally_visible)
760             continue;
761           if (node->global.inlined_to)
762             continue;
763           if (!DECL_EXTERNAL (node->decl)
764               && (referenced_from_other_partition_p (&node->ref_list, set, vset)
765                   || reachable_from_other_partition_p (node, set)))
766             promote_fn (node);
767         }
768       for (vsi = vsi_start (vset); !vsi_end_p (vsi); vsi_next (&vsi))
769         {
770           vnode = vsi_node (vsi);
771           /* Constant pool references use internal labels and thus can not
772              be made global.  It is sensible to keep those ltrans local to
773              allow better optimization.  */
774           if (!DECL_IN_CONSTANT_POOL (vnode->decl)
775              && !vnode->externally_visible && vnode->analyzed
776              && referenced_from_other_partition_p (&vnode->ref_list,
777                                                    set, vset))
778             promote_var (vnode);
779         }
780
781       /* We export initializers of read-only var into each partition
782          referencing it.  Folding might take declarations from the
783          initializers and use it; so everything referenced from the
784          initializers needs can be accessed from this partition after
785          folding.
786
787          This means that we need to promote all variables and functions
788          referenced from all initializers from readonly vars referenced
789          from this partition that are not in this partition.
790          This needs to be done recursively.  */
791       for (vnode = varpool_nodes; vnode; vnode = vnode->next)
792         if ((TREE_READONLY (vnode->decl) || DECL_IN_CONSTANT_POOL (vnode->decl))
793             && DECL_INITIAL (vnode->decl)
794             && !varpool_node_in_set_p (vnode, vset)
795             && referenced_from_this_partition_p (&vnode->ref_list, set, vset)
796             && !pointer_set_insert (inserted, vnode))
797         VEC_safe_push (varpool_node_ptr, heap, promoted_initializers, vnode);
798       while (!VEC_empty (varpool_node_ptr, promoted_initializers))
799         {
800           int i;
801           struct ipa_ref *ref;
802
803           vnode = VEC_pop (varpool_node_ptr, promoted_initializers);
804           for (i = 0; ipa_ref_list_reference_iterate (&vnode->ref_list, i, ref); i++)
805             {
806               if (ref->refered_type == IPA_REF_CGRAPH)
807                 {
808                   struct cgraph_node *n = ipa_ref_node (ref);
809                   gcc_assert (!n->global.inlined_to);
810                   if (!n->local.externally_visible
811                       && !cgraph_node_in_set_p (n, set))
812                     promote_fn (n);
813                 }
814               else
815                 {
816                   struct varpool_node *v = ipa_ref_varpool_node (ref);
817                   if (varpool_node_in_set_p (v, vset))
818                     continue;
819                   /* Constant pool references use internal labels and thus can not
820                      be made global.  It is sensible to keep those ltrans local to
821                      allow better optimization.  */
822                   if (DECL_IN_CONSTANT_POOL (v->decl))
823                     {
824                       if (!pointer_set_insert (inserted, vnode))
825                         VEC_safe_push (varpool_node_ptr, heap,
826                                        promoted_initializers, v);
827                     }
828                   else if (!DECL_IN_CONSTANT_POOL (v->decl)
829                            && !v->externally_visible && v->analyzed)
830                     {
831                       if (promote_var (v)
832                           && DECL_INITIAL (v->decl) && TREE_READONLY (v->decl)
833                           && !pointer_set_insert (inserted, vnode))
834                         VEC_safe_push (varpool_node_ptr, heap,
835                                        promoted_initializers, v);
836                     }
837                 }
838             }
839         }
840     }
841   pointer_set_destroy (inserted);
842 }
843
844
845 /* Given a file name FNAME, return a string with FNAME prefixed with '*'.  */
846
847 static char *
848 prefix_name_with_star (const char *fname)
849 {
850   char *star_fname;
851   size_t len;
852   
853   len = strlen (fname) + 1 + 1;
854   star_fname = XNEWVEC (char, len);
855   snprintf (star_fname, len, "*%s", fname);
856
857   return star_fname;
858 }
859
860
861 /* Return a copy of FNAME without the .o extension.  */
862
863 static char *
864 strip_extension (const char *fname)
865 {
866   char *s = XNEWVEC (char, strlen (fname) - 2 + 1);
867   gcc_assert (strstr (fname, ".o"));
868   snprintf (s, strlen (fname) - 2 + 1, "%s", fname);
869
870   return s;
871 }
872
873
874 /* Return a file name associated with cgraph node set SET.  This may
875    be a new temporary file name if SET needs to be processed by
876    LTRANS, or the original file name if all the nodes in SET belong to
877    the same input file.  */
878
879 static char *
880 get_filename_for_set (cgraph_node_set set)
881 {
882   char *fname = NULL;
883   static const size_t max_fname_len = 100;
884
885   /* Create a new temporary file to store SET.  To facilitate
886      debugging, use file names from SET as part of the new
887      temporary file name.  */
888   cgraph_node_set_iterator si;
889   struct pointer_set_t *pset = pointer_set_create ();
890   for (si = csi_start (set); !csi_end_p (si); csi_next (&si))
891     {
892       struct cgraph_node *n = csi_node (si);
893       const char *node_fname;
894       char *f;
895
896       /* Don't use the same file name more than once.  */
897       if (pointer_set_insert (pset, n->local.lto_file_data))
898         continue;
899
900       /* The first file name found in SET determines the output
901          directory.  For the remaining files, we use their
902          base names.  */
903       node_fname = n->local.lto_file_data->file_name;
904       if (fname == NULL)
905         {
906           fname = strip_extension (node_fname);
907           continue;
908         }
909
910       f = strip_extension (lbasename (node_fname));
911
912       /* If the new name causes an excessively long file name,
913          make the last component "___" to indicate overflow.  */
914       if (strlen (fname) + strlen (f) > max_fname_len - 3)
915         {
916           fname = reconcat (fname, fname, "___", NULL);
917           break;
918         }
919       else
920         {
921           fname = reconcat (fname, fname, "_", f, NULL);
922           free (f);
923         }
924     }
925
926   pointer_set_destroy (pset);
927
928   if (!fname)
929     {
930       /* Since SET does not need to be processed by LTRANS, use
931          the original file name and mark it with a '*' prefix so that
932          lto_execute_ltrans knows not to process it.  */
933       cgraph_node_set_iterator si = csi_start (set);
934       struct cgraph_node *first = csi_node (si);
935       fname = prefix_name_with_star (first->local.lto_file_data->file_name);
936     }
937   else
938     {
939       /* Add the extension .wpa.o to indicate that this file has been
940          produced by WPA.  */
941       fname = reconcat (fname, fname, ".wpa.o", NULL);
942       gcc_assert (fname);
943     }
944
945   return fname;
946 }
947
948 static lto_file *current_lto_file;
949
950
951 /* Write all output files in WPA mode.  Returns a NULL-terminated array of
952    output file names.  */
953
954 static char **
955 lto_wpa_write_files (void)
956 {
957   char **output_files;
958   unsigned i, n_sets, last_out_file_ix, num_out_files;
959   lto_file *file;
960   cgraph_node_set set;
961   varpool_node_set vset;
962
963   timevar_push (TV_WHOPR_WPA);
964
965   /* Include all inlined functions and determine what sets need to be
966      compiled by LTRANS.  After this loop, only those sets that
967      contain callgraph nodes from more than one file will need to be
968      compiled by LTRANS.  */
969   for (i = 0; VEC_iterate (cgraph_node_set, lto_cgraph_node_sets, i, set); i++)
970     {
971       lto_add_all_inlinees (set);
972       lto_stats.num_output_cgraph_nodes += VEC_length (cgraph_node_ptr,
973                                                        set->nodes);
974     }
975
976   /* After adding all inlinees, find out statics that need to be promoted
977      to globals because of cross-file inlining.  */
978   lto_promote_cross_file_statics ();
979
980   timevar_pop (TV_WHOPR_WPA);
981
982   timevar_push (TV_WHOPR_WPA_IO);
983
984   /* The number of output files depends on the number of input files
985      and how many callgraph node sets we create.  Reserve enough space
986      for the maximum of these two.  */
987   num_out_files = MAX (VEC_length (cgraph_node_set, lto_cgraph_node_sets),
988                        num_in_fnames);
989   output_files = XNEWVEC (char *, num_out_files + 1);
990
991   n_sets = VEC_length (cgraph_node_set, lto_cgraph_node_sets);
992   for (i = 0; i < n_sets; i++)
993     {
994       char *temp_filename;
995
996       set = VEC_index (cgraph_node_set, lto_cgraph_node_sets, i);
997       vset = VEC_index (varpool_node_set, lto_varpool_node_sets, i);
998       temp_filename = get_filename_for_set (set);
999       output_files[i] = temp_filename;
1000
1001       if (cgraph_node_set_nonempty_p (set) || varpool_node_set_nonempty_p (vset))
1002         {
1003           /* Write all the nodes in SET to TEMP_FILENAME.  */
1004           file = lto_obj_file_open (temp_filename, true);
1005           if (!file)
1006             fatal_error ("lto_obj_file_open() failed");
1007
1008           if (!quiet_flag)
1009             fprintf (stderr, " %s", temp_filename);
1010
1011           lto_set_current_out_file (file);
1012
1013           ipa_write_optimization_summaries (set, vset);
1014
1015           lto_set_current_out_file (NULL);
1016           lto_obj_file_close (file);
1017         }
1018     }
1019
1020   last_out_file_ix = n_sets;
1021
1022   lto_stats.num_output_files += n_sets;
1023
1024   output_files[last_out_file_ix] = NULL;
1025
1026   timevar_pop (TV_WHOPR_WPA_IO);
1027
1028   return output_files;
1029 }
1030
1031 /* Perform local transformations (LTRANS) on the files in the NULL-terminated
1032    FILES array.  These should have been written previously by
1033    lto_wpa_write_files ().  Transformations are performed via executing
1034    COLLECT_GCC for reach file.  */
1035
1036 static void
1037 lto_write_ltrans_list (char *const *files)
1038 {
1039   FILE *ltrans_output_list_stream = NULL;
1040   unsigned i;
1041
1042   /* Open the LTRANS output list.  */
1043   if (!ltrans_output_list)
1044     error ("no LTRANS output filename provided");
1045
1046   ltrans_output_list_stream = fopen (ltrans_output_list, "w");
1047   if (ltrans_output_list_stream == NULL)
1048     error ("opening LTRANS output list %s: %m", ltrans_output_list);
1049
1050   for (i = 0; files[i]; ++i)
1051     {
1052       size_t len;
1053
1054       len = strlen (files[i]);
1055       if (fwrite (files[i], 1, len, ltrans_output_list_stream) < len
1056           || fwrite ("\n", 1, 1, ltrans_output_list_stream) < 1)
1057         error ("writing to LTRANS output list %s: %m",
1058                ltrans_output_list);
1059     }
1060
1061   /* Close the LTRANS output list.  */
1062   if (fclose (ltrans_output_list_stream))
1063     error ("closing LTRANS output list %s: %m", ltrans_output_list);
1064 }
1065
1066
1067 typedef struct {
1068   struct pointer_set_t *seen;
1069 } lto_fixup_data_t;
1070
1071 #define LTO_FIXUP_SUBTREE(t) \
1072   do \
1073     walk_tree (&(t), lto_fixup_tree, data, NULL); \
1074   while (0)
1075
1076 #define LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE(t) \
1077   do \
1078     { \
1079       if (t) \
1080         (t) = gimple_register_type (t); \
1081       walk_tree (&(t), lto_fixup_tree, data, NULL); \
1082     } \
1083   while (0)
1084
1085 static tree lto_fixup_tree (tree *, int *, void *);
1086
1087 /* Return true if T does not need to be fixed up recursively.  */
1088
1089 static inline bool
1090 no_fixup_p (tree t)
1091 {
1092   return (t == NULL
1093           || CONSTANT_CLASS_P (t)
1094           || TREE_CODE (t) == IDENTIFIER_NODE);
1095 }
1096
1097 /* Fix up fields of a tree_common T.  DATA points to fix-up states.  */
1098
1099 static void
1100 lto_fixup_common (tree t, void *data)
1101 {
1102   /* The following re-creates the TYPE_REFERENCE_TO and TYPE_POINTER_TO
1103      lists.  We do not stream TYPE_REFERENCE_TO, TYPE_POINTER_TO or
1104      TYPE_NEXT_PTR_TO and TYPE_NEXT_REF_TO.
1105      First remove us from any pointer list we are on.  */
1106   if (TREE_CODE (t) == POINTER_TYPE)
1107     {
1108       if (TYPE_POINTER_TO (TREE_TYPE (t)) == t)
1109         TYPE_POINTER_TO (TREE_TYPE (t)) = TYPE_NEXT_PTR_TO (t);
1110       else
1111         {
1112           tree tem = TYPE_POINTER_TO (TREE_TYPE (t));
1113           while (tem && TYPE_NEXT_PTR_TO (tem) != t)
1114             tem = TYPE_NEXT_PTR_TO (tem);
1115           if (tem)
1116             TYPE_NEXT_PTR_TO (tem) = TYPE_NEXT_PTR_TO (t);
1117         }
1118       TYPE_NEXT_PTR_TO (t) = NULL_TREE;
1119     }
1120   else if (TREE_CODE (t) == REFERENCE_TYPE)
1121     {
1122       if (TYPE_REFERENCE_TO (TREE_TYPE (t)) == t)
1123         TYPE_REFERENCE_TO (TREE_TYPE (t)) = TYPE_NEXT_REF_TO (t);
1124       else
1125         {
1126           tree tem = TYPE_REFERENCE_TO (TREE_TYPE (t));
1127           while (tem && TYPE_NEXT_REF_TO (tem) != t)
1128             tem = TYPE_NEXT_REF_TO (tem);
1129           if (tem)
1130             TYPE_NEXT_REF_TO (tem) = TYPE_NEXT_REF_TO (t);
1131         }
1132       TYPE_NEXT_REF_TO (t) = NULL_TREE;
1133     }
1134
1135   /* Fixup our type.  */
1136   LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TREE_TYPE (t));
1137
1138   /* Second put us on the list of pointers of the new pointed-to type
1139      if we are a main variant.  This is done in lto_fixup_type after
1140      fixing up our main variant.  */
1141
1142   /* This is not very efficient because we cannot do tail-recursion with
1143      a long chain of trees. */
1144   LTO_FIXUP_SUBTREE (TREE_CHAIN (t));
1145 }
1146
1147 /* Fix up fields of a decl_minimal T.  DATA points to fix-up states.  */
1148
1149 static void
1150 lto_fixup_decl_minimal (tree t, void *data)
1151 {
1152   lto_fixup_common (t, data);
1153   LTO_FIXUP_SUBTREE (DECL_NAME (t));
1154   LTO_FIXUP_SUBTREE (DECL_CONTEXT (t));
1155 }
1156
1157 /* Fix up fields of a decl_common T.  DATA points to fix-up states.  */
1158
1159 static void
1160 lto_fixup_decl_common (tree t, void *data)
1161 {
1162   lto_fixup_decl_minimal (t, data);
1163   LTO_FIXUP_SUBTREE (DECL_SIZE (t));
1164   LTO_FIXUP_SUBTREE (DECL_SIZE_UNIT (t));
1165   LTO_FIXUP_SUBTREE (DECL_INITIAL (t));
1166   LTO_FIXUP_SUBTREE (DECL_ATTRIBUTES (t));
1167   LTO_FIXUP_SUBTREE (DECL_ABSTRACT_ORIGIN (t));
1168 }
1169
1170 /* Fix up fields of a decl_with_vis T.  DATA points to fix-up states.  */
1171
1172 static void
1173 lto_fixup_decl_with_vis (tree t, void *data)
1174 {
1175   lto_fixup_decl_common (t, data);
1176
1177   /* Accessor macro has side-effects, use field-name here. */
1178   LTO_FIXUP_SUBTREE (t->decl_with_vis.assembler_name);
1179
1180   gcc_assert (no_fixup_p (DECL_SECTION_NAME (t)));
1181 }
1182
1183 /* Fix up fields of a decl_non_common T.  DATA points to fix-up states.  */
1184
1185 static void
1186 lto_fixup_decl_non_common (tree t, void *data)
1187 {
1188   lto_fixup_decl_with_vis (t, data);
1189   LTO_FIXUP_SUBTREE (DECL_ARGUMENT_FLD (t));
1190   LTO_FIXUP_SUBTREE (DECL_RESULT_FLD (t));
1191   LTO_FIXUP_SUBTREE (DECL_VINDEX (t));
1192
1193   /* SAVED_TREE should not cleared by now.  Also no accessor for base type. */
1194   gcc_assert (no_fixup_p (t->decl_non_common.saved_tree));
1195 }
1196
1197 /* Fix up fields of a decl_non_common T.  DATA points to fix-up states.  */
1198
1199 static void
1200 lto_fixup_function (tree t, void *data)
1201 {
1202   lto_fixup_decl_non_common (t, data);
1203   LTO_FIXUP_SUBTREE (DECL_FUNCTION_PERSONALITY (t));
1204 }
1205
1206 /* Fix up fields of a field_decl T.  DATA points to fix-up states.  */
1207
1208 static void
1209 lto_fixup_field_decl (tree t, void *data)
1210 {
1211   lto_fixup_decl_common (t, data);
1212   LTO_FIXUP_SUBTREE (DECL_FIELD_OFFSET (t));
1213   LTO_FIXUP_SUBTREE (DECL_BIT_FIELD_TYPE (t));
1214   LTO_FIXUP_SUBTREE (DECL_QUALIFIER (t));
1215   gcc_assert (no_fixup_p (DECL_FIELD_BIT_OFFSET (t)));
1216   LTO_FIXUP_SUBTREE (DECL_FCONTEXT (t));
1217 }
1218
1219 /* Fix up fields of a type T.  DATA points to fix-up states.  */
1220
1221 static void
1222 lto_fixup_type (tree t, void *data)
1223 {
1224   tree tem, mv;
1225
1226   lto_fixup_common (t, data);
1227   LTO_FIXUP_SUBTREE (TYPE_CACHED_VALUES (t));
1228   LTO_FIXUP_SUBTREE (TYPE_SIZE (t));
1229   LTO_FIXUP_SUBTREE (TYPE_SIZE_UNIT (t));
1230   LTO_FIXUP_SUBTREE (TYPE_ATTRIBUTES (t));
1231   LTO_FIXUP_SUBTREE (TYPE_NAME (t));
1232
1233   /* Accessors are for derived node types only. */
1234   if (!POINTER_TYPE_P (t))
1235     LTO_FIXUP_SUBTREE (t->type.minval);
1236   LTO_FIXUP_SUBTREE (t->type.maxval);
1237
1238   /* Accessor is for derived node types only. */
1239   LTO_FIXUP_SUBTREE (t->type.binfo);
1240
1241   if (TYPE_CONTEXT (t))
1242     {
1243       if (TYPE_P (TYPE_CONTEXT (t)))
1244         LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TYPE_CONTEXT (t));
1245       else
1246         LTO_FIXUP_SUBTREE (TYPE_CONTEXT (t));
1247     }
1248   LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TYPE_CANONICAL (t));
1249
1250   /* The following re-creates proper variant lists while fixing up
1251      the variant leaders.  We do not stream TYPE_NEXT_VARIANT so the
1252      variant list state before fixup is broken.  */
1253
1254   /* Remove us from our main variant list if we are not the variant leader.  */
1255   if (TYPE_MAIN_VARIANT (t) != t)
1256     {
1257       tem = TYPE_MAIN_VARIANT (t);
1258       while (tem && TYPE_NEXT_VARIANT (tem) != t)
1259         tem = TYPE_NEXT_VARIANT (tem);
1260       if (tem)
1261         TYPE_NEXT_VARIANT (tem) = TYPE_NEXT_VARIANT (t);
1262       TYPE_NEXT_VARIANT (t) = NULL_TREE;
1263     }
1264
1265   /* Query our new main variant.  */
1266   mv = gimple_register_type (TYPE_MAIN_VARIANT (t));
1267
1268   /* If we were the variant leader and we get replaced ourselves drop
1269      all variants from our list.  */
1270   if (TYPE_MAIN_VARIANT (t) == t
1271       && mv != t)
1272     {
1273       tem = t;
1274       while (tem)
1275         {
1276           tree tem2 = TYPE_NEXT_VARIANT (tem);
1277           TYPE_NEXT_VARIANT (tem) = NULL_TREE;
1278           tem = tem2;
1279         }
1280     }
1281
1282   /* If we are not our own variant leader link us into our new leaders
1283      variant list.  */
1284   if (mv != t)
1285     {
1286       TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (mv);
1287       TYPE_NEXT_VARIANT (mv) = t;
1288     }
1289
1290   /* Finally adjust our main variant and fix it up.  */
1291   TYPE_MAIN_VARIANT (t) = mv;
1292   LTO_FIXUP_SUBTREE (TYPE_MAIN_VARIANT (t));
1293
1294   /* As the second step of reconstructing the pointer chains put us
1295      on the list of pointers of the new pointed-to type
1296      if we are a main variant.  See lto_fixup_common for the first step.  */
1297   if (TREE_CODE (t) == POINTER_TYPE
1298       && TYPE_MAIN_VARIANT (t) == t)
1299     {
1300       TYPE_NEXT_PTR_TO (t) = TYPE_POINTER_TO (TREE_TYPE (t));
1301       TYPE_POINTER_TO (TREE_TYPE (t)) = t;
1302     }
1303   else if (TREE_CODE (t) == REFERENCE_TYPE
1304            && TYPE_MAIN_VARIANT (t) == t)
1305     {
1306       TYPE_NEXT_REF_TO (t) = TYPE_REFERENCE_TO (TREE_TYPE (t));
1307       TYPE_REFERENCE_TO (TREE_TYPE (t)) = t;
1308     }
1309 }
1310
1311 /* Fix up fields of a BINFO T.  DATA points to fix-up states.  */
1312
1313 static void
1314 lto_fixup_binfo (tree t, void *data)
1315 {
1316   unsigned HOST_WIDE_INT i, n;
1317   tree base, saved_base;
1318
1319   lto_fixup_common (t, data);
1320   gcc_assert (no_fixup_p (BINFO_OFFSET (t)));
1321   LTO_FIXUP_SUBTREE (BINFO_VTABLE (t));
1322   LTO_FIXUP_SUBTREE (BINFO_VIRTUALS (t));
1323   LTO_FIXUP_SUBTREE (BINFO_VPTR_FIELD (t));
1324   n = VEC_length (tree, BINFO_BASE_ACCESSES (t));
1325   for (i = 0; i < n; i++)
1326     {
1327       saved_base = base = BINFO_BASE_ACCESS (t, i);
1328       LTO_FIXUP_SUBTREE (base);
1329       if (base != saved_base)
1330         VEC_replace (tree, BINFO_BASE_ACCESSES (t), i, base);
1331     }
1332   LTO_FIXUP_SUBTREE (BINFO_INHERITANCE_CHAIN (t));
1333   LTO_FIXUP_SUBTREE (BINFO_SUBVTT_INDEX (t));
1334   LTO_FIXUP_SUBTREE (BINFO_VPTR_INDEX (t));
1335   n = BINFO_N_BASE_BINFOS (t);
1336   for (i = 0; i < n; i++)
1337     {
1338       saved_base = base = BINFO_BASE_BINFO (t, i);
1339       LTO_FIXUP_SUBTREE (base);
1340       if (base != saved_base)
1341         VEC_replace (tree, BINFO_BASE_BINFOS (t), i, base);
1342     }
1343 }
1344
1345 /* Fix up fields of a CONSTRUCTOR T.  DATA points to fix-up states.  */
1346
1347 static void
1348 lto_fixup_constructor (tree t, void *data)
1349 {
1350   unsigned HOST_WIDE_INT idx;
1351   constructor_elt *ce;
1352
1353   LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TREE_TYPE (t));
1354
1355   for (idx = 0;
1356        VEC_iterate(constructor_elt, CONSTRUCTOR_ELTS (t), idx, ce);
1357        idx++)
1358     {
1359       LTO_FIXUP_SUBTREE (ce->index);
1360       LTO_FIXUP_SUBTREE (ce->value);
1361     }
1362 }
1363
1364 /* A walk_tree callback used by lto_fixup_state. TP is the pointer to the
1365    current tree. WALK_SUBTREES indicates if the subtrees will be walked.
1366    DATA is a pointer set to record visited nodes. */
1367
1368 static tree
1369 lto_fixup_tree (tree *tp, int *walk_subtrees, void *data)
1370 {
1371   tree t;
1372   lto_fixup_data_t *fixup_data = (lto_fixup_data_t *) data;
1373   tree prevailing;
1374
1375   t = *tp;
1376   *walk_subtrees = 0;
1377   if (!t || pointer_set_contains (fixup_data->seen, t))
1378     return NULL;
1379
1380   if (TREE_CODE (t) == VAR_DECL || TREE_CODE (t) == FUNCTION_DECL)
1381     {
1382       prevailing = lto_symtab_prevailing_decl (t);
1383
1384       if (t != prevailing)
1385         {
1386            /* Also replace t with prevailing defintion.  We don't want to
1387               insert the other defintion in the seen set as we want to
1388               replace all instances of it.  */
1389           *tp = prevailing;
1390           t = prevailing;
1391         }
1392     }
1393   else if (TYPE_P (t))
1394     {
1395       /* Replace t with the prevailing type.  We don't want to insert the
1396          other type in the seen set as we want to replace all instances of it.  */
1397       t = gimple_register_type (t);
1398       *tp = t;
1399     }
1400
1401   if (pointer_set_insert (fixup_data->seen, t))
1402     return NULL;
1403
1404   /* walk_tree does not visit all reachable nodes that need to be fixed up.
1405      Hence we do special processing here for those kind of nodes. */
1406   switch (TREE_CODE (t))
1407     {
1408     case FIELD_DECL:
1409       lto_fixup_field_decl (t, data);
1410       break;
1411
1412     case LABEL_DECL:
1413     case CONST_DECL:
1414     case PARM_DECL:
1415     case RESULT_DECL:
1416     case IMPORTED_DECL:
1417       lto_fixup_decl_common (t, data);
1418       break;
1419
1420     case VAR_DECL:
1421       lto_fixup_decl_with_vis (t, data);
1422       break;    
1423
1424     case TYPE_DECL:
1425       lto_fixup_decl_non_common (t, data);
1426       break;
1427
1428     case FUNCTION_DECL:
1429       lto_fixup_function (t, data);
1430       break;
1431
1432     case TREE_BINFO:
1433       lto_fixup_binfo (t, data);
1434       break;
1435
1436     default:
1437       if (TYPE_P (t))
1438         lto_fixup_type (t, data);
1439       else if (TREE_CODE (t) == CONSTRUCTOR)
1440         lto_fixup_constructor (t, data);
1441       else if (CONSTANT_CLASS_P (t))
1442         LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TREE_TYPE (t));
1443       else if (EXPR_P (t))
1444         {
1445           /* walk_tree only handles TREE_OPERANDs. Do the rest here.  */
1446           lto_fixup_common (t, data);
1447           LTO_FIXUP_SUBTREE (t->exp.block);
1448           *walk_subtrees = 1;
1449         }
1450       else
1451         {
1452           /* Let walk_tree handle sub-trees.  */
1453           *walk_subtrees = 1;
1454         }
1455     }
1456
1457   return NULL;
1458 }
1459
1460 /* Helper function of lto_fixup_decls. Walks the var and fn streams in STATE,
1461    replaces var and function decls with the corresponding prevailing def and
1462    records the old decl in the free-list in DATA. We also record visted nodes
1463    in the seen-set in DATA to avoid multiple visit for nodes that need not
1464    to be replaced.  */
1465
1466 static void
1467 lto_fixup_state (struct lto_in_decl_state *state, lto_fixup_data_t *data)
1468 {
1469   unsigned i, si;
1470   struct lto_tree_ref_table *table;
1471
1472   /* Although we only want to replace FUNCTION_DECLs and VAR_DECLs,
1473      we still need to walk from all DECLs to find the reachable
1474      FUNCTION_DECLs and VAR_DECLs.  */
1475   for (si = 0; si < LTO_N_DECL_STREAMS; si++)
1476     {
1477       table = &state->streams[si];
1478       for (i = 0; i < table->size; i++)
1479         walk_tree (table->trees + i, lto_fixup_tree, data, NULL);
1480     }
1481 }
1482
1483 /* A callback of htab_traverse. Just extract a state from SLOT and the
1484    lto_fixup_data_t object from AUX and calls lto_fixup_state. */
1485
1486 static int
1487 lto_fixup_state_aux (void **slot, void *aux)
1488 {
1489   struct lto_in_decl_state *state = (struct lto_in_decl_state *) *slot;
1490   lto_fixup_state (state, (lto_fixup_data_t *) aux);
1491   return 1;
1492 }
1493
1494 /* Fix the decls from all FILES. Replaces each decl with the corresponding
1495    prevailing one.  */
1496
1497 static void
1498 lto_fixup_decls (struct lto_file_decl_data **files)
1499 {
1500   unsigned int i;
1501   tree decl;
1502   struct pointer_set_t *seen = pointer_set_create ();
1503   lto_fixup_data_t data;
1504
1505   data.seen = seen;
1506   for (i = 0; files[i]; i++)
1507     {
1508       struct lto_file_decl_data *file = files[i];
1509       struct lto_in_decl_state *state = file->global_decl_state;
1510       lto_fixup_state (state, &data);
1511
1512       htab_traverse (file->function_decl_states, lto_fixup_state_aux, &data);
1513     }
1514
1515   for (i = 0; VEC_iterate (tree, lto_global_var_decls, i, decl); i++)
1516     {
1517       tree saved_decl = decl;
1518       walk_tree (&decl, lto_fixup_tree, &data, NULL);
1519       if (decl != saved_decl)
1520         VEC_replace (tree, lto_global_var_decls, i, decl);
1521     }
1522
1523   pointer_set_destroy (seen);
1524 }
1525
1526 /* Read the options saved from each file in the command line.  Called
1527    from lang_hooks.post_options which is called by process_options
1528    right before all the options are used to initialize the compiler.
1529    This assumes that decode_options has already run, so the
1530    num_in_fnames and in_fnames are properly set.
1531
1532    Note that this assumes that all the files had been compiled with
1533    the same options, which is not a good assumption.  In general,
1534    options ought to be read from all the files in the set and merged.
1535    However, it is still unclear what the merge rules should be.  */
1536
1537 void
1538 lto_read_all_file_options (void)
1539 {
1540   size_t i;
1541
1542   /* Clear any file options currently saved.  */
1543   lto_clear_file_options ();
1544
1545   /* Set the hooks to read ELF sections.  */
1546   lto_set_in_hooks (NULL, get_section_data, free_section_data);
1547
1548   for (i = 0; i < num_in_fnames; i++)
1549     {
1550       struct lto_file_decl_data *file_data;
1551       lto_file *file = lto_obj_file_open (in_fnames[i], false);
1552       if (!file)
1553         break;
1554
1555       file_data = XCNEW (struct lto_file_decl_data);
1556       file_data->file_name = file->filename;
1557       file_data->section_hash_table = lto_obj_build_section_table (file);
1558
1559       lto_read_file_options (file_data);
1560
1561       lto_obj_file_close (file);
1562       htab_delete (file_data->section_hash_table);
1563       free (file_data);
1564     }
1565
1566   /* Apply globally the options read from all the files.  */
1567   lto_reissue_options ();
1568 }
1569
1570 static GTY((length ("lto_stats.num_input_files + 1"))) struct lto_file_decl_data **all_file_decl_data;
1571
1572 /* Read all the symbols from the input files FNAMES.  NFILES is the
1573    number of files requested in the command line.  Instantiate a
1574    global call graph by aggregating all the sub-graphs found in each
1575    file.  */
1576
1577 static void
1578 read_cgraph_and_symbols (unsigned nfiles, const char **fnames)
1579 {
1580   unsigned int i, last_file_ix;
1581   FILE *resolution;
1582   struct cgraph_node *node;
1583
1584   lto_stats.num_input_files = nfiles;
1585
1586   timevar_push (TV_IPA_LTO_DECL_IO);
1587
1588   /* Set the hooks so that all of the ipa passes can read in their data.  */
1589   all_file_decl_data = GGC_CNEWVEC (struct lto_file_decl_data *, nfiles + 1);
1590   lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data);
1591
1592   /* Read the resolution file.  */
1593   resolution = NULL;
1594   if (resolution_file_name)
1595     {
1596       int t;
1597       unsigned num_objects;
1598
1599       resolution = fopen (resolution_file_name, "r");
1600       if (resolution == NULL)
1601         fatal_error ("could not open symbol resolution file: %s",
1602                      xstrerror (errno));
1603
1604       t = fscanf (resolution, "%u", &num_objects);
1605       gcc_assert (t == 1);
1606
1607       /* True, since the plugin splits the archives.  */
1608       gcc_assert (num_objects == nfiles);
1609     }
1610
1611   if (!quiet_flag)
1612     fprintf (stderr, "Reading object files:");
1613
1614   /* Read all of the object files specified on the command line.  */
1615   for (i = 0, last_file_ix = 0; i < nfiles; ++i)
1616     {
1617       struct lto_file_decl_data *file_data = NULL;
1618       if (!quiet_flag)
1619         {
1620           fprintf (stderr, " %s", fnames[i]);
1621           fflush (stderr);
1622         }
1623
1624       current_lto_file = lto_obj_file_open (fnames[i], false);
1625       if (!current_lto_file)
1626         break;
1627
1628       file_data = lto_file_read (current_lto_file, resolution);
1629       if (!file_data)
1630         break;
1631
1632       all_file_decl_data[last_file_ix++] = file_data;
1633
1634       lto_obj_file_close (current_lto_file);
1635       current_lto_file = NULL;
1636       ggc_collect ();
1637     }
1638
1639   if (resolution_file_name)
1640     fclose (resolution);
1641
1642   all_file_decl_data[last_file_ix] = NULL;
1643
1644   /* Set the hooks so that all of the ipa passes can read in their data.  */
1645   lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data);
1646
1647   timevar_pop (TV_IPA_LTO_DECL_IO);
1648
1649   if (!quiet_flag)
1650     fprintf (stderr, "\nReading the callgraph\n");
1651
1652   timevar_push (TV_IPA_LTO_CGRAPH_IO);
1653   /* Read the callgraph.  */
1654   input_cgraph ();
1655   timevar_pop (TV_IPA_LTO_CGRAPH_IO);
1656
1657   if (!quiet_flag)
1658     fprintf (stderr, "Merging declarations\n");
1659
1660   timevar_push (TV_IPA_LTO_DECL_MERGE);
1661   /* Merge global decls.  */
1662   lto_symtab_merge_decls ();
1663
1664   /* Fixup all decls and types and free the type hash tables.  */
1665   lto_fixup_decls (all_file_decl_data);
1666   free_gimple_type_tables ();
1667   ggc_collect ();
1668
1669   timevar_pop (TV_IPA_LTO_DECL_MERGE);
1670   /* Each pass will set the appropriate timer.  */
1671
1672   if (!quiet_flag)
1673     fprintf (stderr, "Reading summaries\n");
1674
1675   /* Read the IPA summary data.  */
1676   if (flag_ltrans)
1677     ipa_read_optimization_summaries ();
1678   else
1679     ipa_read_summaries ();
1680
1681   /* Finally merge the cgraph according to the decl merging decisions.  */
1682   timevar_push (TV_IPA_LTO_CGRAPH_MERGE);
1683   lto_symtab_merge_cgraph_nodes ();
1684   ggc_collect ();
1685
1686   if (flag_ltrans)
1687     for (node = cgraph_nodes; node; node = node->next)
1688       {
1689         /* FIXME: ipa_transforms_to_apply holds list of passes that have optimization
1690            summaries computed and needs to apply changes.  At the moment WHOPR only
1691            supports inlining, so we can push it here by hand.  In future we need to stream
1692            this field into ltrans compilation.  */
1693         if (node->analyzed)
1694           VEC_safe_push (ipa_opt_pass, heap,
1695                          node->ipa_transforms_to_apply,
1696                          (ipa_opt_pass)&pass_ipa_inline);
1697       }
1698   lto_symtab_free ();
1699
1700   timevar_pop (TV_IPA_LTO_CGRAPH_MERGE);
1701
1702   timevar_push (TV_IPA_LTO_DECL_INIT_IO);
1703
1704   /* FIXME lto. This loop needs to be changed to use the pass manager to
1705      call the ipa passes directly.  */
1706   if (!errorcount)
1707     for (i = 0; i < last_file_ix; i++)
1708       {
1709         struct lto_file_decl_data *file_data = all_file_decl_data [i];
1710         lto_materialize_constructors_and_inits (file_data);
1711       }
1712
1713   /* Indicate that the cgraph is built and ready.  */
1714   cgraph_function_flags_ready = true;
1715
1716   timevar_pop (TV_IPA_LTO_DECL_INIT_IO);
1717   ggc_free (all_file_decl_data);
1718   all_file_decl_data = NULL;
1719 }
1720
1721
1722 /* Materialize all the bodies for all the nodes in the callgraph.  */
1723
1724 static void
1725 materialize_cgraph (void)
1726 {
1727   tree decl;
1728   struct cgraph_node *node; 
1729   unsigned i;
1730   timevar_id_t lto_timer;
1731
1732   if (!quiet_flag)
1733     fprintf (stderr,
1734              flag_wpa ? "Materializing decls:" : "Reading function bodies:");
1735
1736
1737   /* Now that we have input the cgraph, we need to clear all of the aux
1738      nodes and read the functions if we are not running in WPA mode.  */
1739   timevar_push (TV_IPA_LTO_GIMPLE_IO);
1740
1741   for (node = cgraph_nodes; node; node = node->next)
1742     {
1743       /* Some cgraph nodes get created on the fly, and they don't need
1744          to be materialized.  For instance, nodes for nested functions
1745          where the parent function was not streamed out or builtin
1746          functions.  Additionally, builtin functions should not be
1747          materialized and may, in fact, cause confusion because there
1748          may be a regular function in the file whose assembler name
1749          matches that of the function.
1750          See gcc.c-torture/execute/20030125-1.c and
1751          gcc.c-torture/execute/921215-1.c.  */
1752       if (node->local.lto_file_data
1753           && !DECL_IS_BUILTIN (node->decl))
1754         {
1755           lto_materialize_function (node);
1756           lto_stats.num_input_cgraph_nodes++;
1757         }
1758     }
1759
1760   timevar_pop (TV_IPA_LTO_GIMPLE_IO);
1761
1762   /* Start the appropriate timer depending on the mode that we are
1763      operating in.  */
1764   lto_timer = (flag_wpa) ? TV_WHOPR_WPA
1765               : (flag_ltrans) ? TV_WHOPR_LTRANS
1766               : TV_LTO;
1767   timevar_push (lto_timer);
1768
1769   current_function_decl = NULL;
1770   set_cfun (NULL);
1771
1772   /* Inform the middle end about the global variables we have seen.  */
1773   for (i = 0; VEC_iterate (tree, lto_global_var_decls, i, decl); i++)
1774     rest_of_decl_compilation (decl, 1, 0);
1775
1776   if (!quiet_flag)
1777     fprintf (stderr, "\n");
1778
1779   timevar_pop (lto_timer);
1780 }
1781
1782
1783 /* Perform whole program analysis (WPA) on the callgraph and write out the
1784    optimization plan.  */
1785
1786 static void
1787 do_whole_program_analysis (void)
1788 {
1789   char **output_files;
1790
1791   /* Note that since we are in WPA mode, materialize_cgraph will not
1792      actually read in all the function bodies.  It only materializes
1793      the decls and cgraph nodes so that analysis can be performed.  */
1794   materialize_cgraph ();
1795
1796   /* Reading in the cgraph uses different timers, start timing WPA now.  */
1797   timevar_push (TV_WHOPR_WPA);
1798
1799   if (pre_ipa_mem_report)
1800     {
1801       fprintf (stderr, "Memory consumption before IPA\n");
1802       dump_memory_report (false);
1803     }
1804
1805   cgraph_function_flags_ready = true;
1806   bitmap_obstack_initialize (NULL);
1807   ipa_register_cgraph_hooks ();
1808   cgraph_state = CGRAPH_STATE_IPA_SSA;
1809
1810   execute_ipa_pass_list (all_regular_ipa_passes);
1811
1812   verify_cgraph ();
1813   bitmap_obstack_release (NULL);
1814
1815   /* We are about to launch the final LTRANS phase, stop the WPA timer.  */
1816   timevar_pop (TV_WHOPR_WPA);
1817
1818   lto_1_to_1_map ();
1819
1820   if (!quiet_flag)
1821     {
1822       fprintf (stderr, "\nStreaming out");
1823       fflush (stderr);
1824     }
1825   output_files = lto_wpa_write_files ();
1826   ggc_collect ();
1827   if (!quiet_flag)
1828     fprintf (stderr, "\n");
1829
1830   if (post_ipa_mem_report)
1831     {
1832       fprintf (stderr, "Memory consumption after IPA\n");
1833       dump_memory_report (false);
1834     }
1835
1836   /* Show the LTO report before launching LTRANS.  */
1837   if (flag_lto_report)
1838     print_lto_report ();
1839
1840   lto_write_ltrans_list (output_files);
1841
1842   XDELETEVEC (output_files);
1843 }
1844
1845
1846 /* Main entry point for the GIMPLE front end.  This front end has
1847    three main personalities:
1848
1849    - LTO (-flto).  All the object files on the command line are
1850      loaded in memory and processed as a single translation unit.
1851      This is the traditional link-time optimization behavior.
1852
1853    - WPA (-fwpa).  Only the callgraph and summary information for
1854      files in the command file are loaded.  A single callgraph
1855      (without function bodies) is instantiated for the whole set of
1856      files.  IPA passes are only allowed to analyze the call graph
1857      and make transformation decisions.  The callgraph is
1858      partitioned, each partition is written to a new object file
1859      together with the transformation decisions.
1860
1861    - LTRANS (-fltrans).  Similar to -flto but it prevents the IPA
1862      summary files from running again.  Since WPA computed summary
1863      information and decided what transformations to apply, LTRANS
1864      simply applies them.  */
1865
1866 void
1867 lto_main (int debug_p ATTRIBUTE_UNUSED)
1868 {
1869   lto_init_reader ();
1870
1871   /* Read all the symbols and call graph from all the files in the
1872      command line.  */
1873   read_cgraph_and_symbols (num_in_fnames, in_fnames);
1874
1875   if (!errorcount)
1876     {
1877       /* If WPA is enabled analyze the whole call graph and create an
1878          optimization plan.  Otherwise, read in all the function
1879          bodies and continue with optimization.  */
1880       if (flag_wpa)
1881         do_whole_program_analysis ();
1882       else
1883         {
1884           materialize_cgraph ();
1885
1886           /* Let the middle end know that we have read and merged all of
1887              the input files.  */ 
1888           cgraph_optimize ();
1889
1890           /* FIXME lto, if the processes spawned by WPA fail, we miss
1891              the chance to print WPA's report, so WPA will call
1892              print_lto_report before launching LTRANS.  If LTRANS was
1893              launched directly by the driver we would not need to do
1894              this.  */
1895           if (flag_lto_report)
1896             print_lto_report ();
1897         }
1898     }
1899 }
1900
1901 #include "gt-lto-lto.h"