Minor edits.
[platform/upstream/gcc.git] / gcc / lto / lto.c
1 /* Top-level LTO routines.
2    Copyright (C) 2009-2017 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 "tm.h"
25 #include "function.h"
26 #include "bitmap.h"
27 #include "basic-block.h"
28 #include "tree.h"
29 #include "gimple.h"
30 #include "cfghooks.h"
31 #include "alloc-pool.h"
32 #include "tree-pass.h"
33 #include "tree-streamer.h"
34 #include "cgraph.h"
35 #include "opts.h"
36 #include "toplev.h"
37 #include "stor-layout.h"
38 #include "symbol-summary.h"
39 #include "tree-vrp.h"
40 #include "ipa-prop.h"
41 #include "common.h"
42 #include "debug.h"
43 #include "lto.h"
44 #include "lto-section-names.h"
45 #include "splay-tree.h"
46 #include "lto-partition.h"
47 #include "context.h"
48 #include "pass_manager.h"
49 #include "ipa-fnsummary.h"
50 #include "params.h"
51 #include "ipa-utils.h"
52 #include "gomp-constants.h"
53 #include "lto-symtab.h"
54 #include "stringpool.h"
55 #include "fold-const.h"
56 #include "attribs.h"
57
58
59 /* Number of parallel tasks to run, -1 if we want to use GNU Make jobserver.  */
60 static int lto_parallelism;
61
62 static GTY(()) tree first_personality_decl;
63
64 static GTY(()) const unsigned char *lto_mode_identity_table;
65
66 /* Returns a hash code for P.  */
67
68 static hashval_t
69 hash_name (const void *p)
70 {
71   const struct lto_section_slot *ds = (const struct lto_section_slot *) p;
72   return (hashval_t) htab_hash_string (ds->name);
73 }
74
75
76 /* Returns nonzero if P1 and P2 are equal.  */
77
78 static int
79 eq_name (const void *p1, const void *p2)
80 {
81   const struct lto_section_slot *s1 =
82     (const struct lto_section_slot *) p1;
83   const struct lto_section_slot *s2 =
84     (const struct lto_section_slot *) p2;
85
86   return strcmp (s1->name, s2->name) == 0;
87 }
88
89 /* Free lto_section_slot */
90
91 static void
92 free_with_string (void *arg)
93 {
94   struct lto_section_slot *s = (struct lto_section_slot *)arg;
95
96   free (CONST_CAST (char *, s->name));
97   free (arg);
98 }
99
100 /* Create section hash table */
101
102 htab_t 
103 lto_obj_create_section_hash_table (void)
104 {
105   return htab_create (37, hash_name, eq_name, free_with_string);
106 }
107
108 /* Delete an allocated integer KEY in the splay tree.  */
109
110 static void
111 lto_splay_tree_delete_id (splay_tree_key key)
112 {
113   free ((void *) key);
114 }
115
116 /* Compare splay tree node ids A and B.  */
117
118 static int
119 lto_splay_tree_compare_ids (splay_tree_key a, splay_tree_key b)
120 {
121   unsigned HOST_WIDE_INT ai;
122   unsigned HOST_WIDE_INT bi;
123
124   ai = *(unsigned HOST_WIDE_INT *) a;
125   bi = *(unsigned HOST_WIDE_INT *) b;
126
127   if (ai < bi)
128     return -1;
129   else if (ai > bi)
130     return 1;
131   return 0;
132 }
133
134 /* Look up splay tree node by ID in splay tree T.  */
135
136 static splay_tree_node
137 lto_splay_tree_lookup (splay_tree t, unsigned HOST_WIDE_INT id)
138 {
139   return splay_tree_lookup (t, (splay_tree_key) &id);
140 }
141
142 /* Check if KEY has ID.  */
143
144 static bool
145 lto_splay_tree_id_equal_p (splay_tree_key key, unsigned HOST_WIDE_INT id)
146 {
147   return *(unsigned HOST_WIDE_INT *) key == id;
148 }
149
150 /* Insert a splay tree node into tree T with ID as key and FILE_DATA as value. 
151    The ID is allocated separately because we need HOST_WIDE_INTs which may
152    be wider than a splay_tree_key. */
153
154 static void
155 lto_splay_tree_insert (splay_tree t, unsigned HOST_WIDE_INT id,
156                        struct lto_file_decl_data *file_data)
157 {
158   unsigned HOST_WIDE_INT *idp = XCNEW (unsigned HOST_WIDE_INT);
159   *idp = id;
160   splay_tree_insert (t, (splay_tree_key) idp, (splay_tree_value) file_data);
161 }
162
163 /* Create a splay tree.  */
164
165 static splay_tree
166 lto_splay_tree_new (void)
167 {
168   return splay_tree_new (lto_splay_tree_compare_ids,
169                          lto_splay_tree_delete_id,
170                          NULL);
171 }
172
173 /* Return true when NODE has a clone that is analyzed (i.e. we need
174    to load its body even if the node itself is not needed).  */
175
176 static bool
177 has_analyzed_clone_p (struct cgraph_node *node)
178 {
179   struct cgraph_node *orig = node;
180   node = node->clones;
181   if (node)
182     while (node != orig)
183       {
184         if (node->analyzed)
185           return true;
186         if (node->clones)
187           node = node->clones;
188         else if (node->next_sibling_clone)
189           node = node->next_sibling_clone;
190         else
191           {
192             while (node != orig && !node->next_sibling_clone)
193               node = node->clone_of;
194             if (node != orig)
195               node = node->next_sibling_clone;
196           }
197       }
198   return false;
199 }
200
201 /* Read the function body for the function associated with NODE.  */
202
203 static void
204 lto_materialize_function (struct cgraph_node *node)
205 {
206   tree decl;
207
208   decl = node->decl;
209   /* Read in functions with body (analyzed nodes)
210      and also functions that are needed to produce virtual clones.  */
211   if ((node->has_gimple_body_p () && node->analyzed)
212       || node->used_as_abstract_origin
213       || has_analyzed_clone_p (node))
214     {
215       /* Clones don't need to be read.  */
216       if (node->clone_of)
217         return;
218       if (DECL_FUNCTION_PERSONALITY (decl) && !first_personality_decl)
219         first_personality_decl = DECL_FUNCTION_PERSONALITY (decl);
220     }
221
222   /* Let the middle end know about the function.  */
223   rest_of_decl_compilation (decl, 1, 0);
224 }
225
226
227 /* Decode the content of memory pointed to by DATA in the in decl
228    state object STATE. DATA_IN points to a data_in structure for
229    decoding. Return the address after the decoded object in the
230    input.  */
231
232 static const uint32_t *
233 lto_read_in_decl_state (struct data_in *data_in, const uint32_t *data,
234                         struct lto_in_decl_state *state)
235 {
236   uint32_t ix;
237   tree decl;
238   uint32_t i, j;
239
240   ix = *data++;
241   state->compressed = ix & 1;
242   ix /= 2;
243   decl = streamer_tree_cache_get_tree (data_in->reader_cache, ix);
244   if (!VAR_OR_FUNCTION_DECL_P (decl))
245     {
246       gcc_assert (decl == void_type_node);
247       decl = NULL_TREE;
248     }
249   state->fn_decl = decl;
250
251   for (i = 0; i < LTO_N_DECL_STREAMS; i++)
252     {
253       uint32_t size = *data++;
254       vec<tree, va_gc> *decls = NULL;
255       vec_alloc (decls, size);
256
257       for (j = 0; j < size; j++)
258         vec_safe_push (decls,
259                        streamer_tree_cache_get_tree (data_in->reader_cache,
260                                                      data[j]));
261
262       state->streams[i] = decls;
263       data += size;
264     }
265
266   return data;
267 }
268
269
270 /* Global canonical type table.  */
271 static htab_t gimple_canonical_types;
272 static hash_map<const_tree, hashval_t> *canonical_type_hash_cache;
273 static unsigned long num_canonical_type_hash_entries;
274 static unsigned long num_canonical_type_hash_queries;
275
276 static void iterative_hash_canonical_type (tree type, inchash::hash &hstate);
277 static hashval_t gimple_canonical_type_hash (const void *p);
278 static void gimple_register_canonical_type_1 (tree t, hashval_t hash);
279
280 /* Returning a hash value for gimple type TYPE.
281
282    The hash value returned is equal for types considered compatible
283    by gimple_canonical_types_compatible_p.  */
284
285 static hashval_t
286 hash_canonical_type (tree type)
287 {
288   inchash::hash hstate;
289   enum tree_code code;
290
291   /* We compute alias sets only for types that needs them.
292      Be sure we do not recurse to something else as we can not hash incomplete
293      types in a way they would have same hash value as compatible complete
294      types.  */
295   gcc_checking_assert (type_with_alias_set_p (type));
296
297   /* Combine a few common features of types so that types are grouped into
298      smaller sets; when searching for existing matching types to merge,
299      only existing types having the same features as the new type will be
300      checked.  */
301   code = tree_code_for_canonical_type_merging (TREE_CODE (type));
302   hstate.add_int (code);
303   hstate.add_int (TYPE_MODE (type));
304
305   /* Incorporate common features of numerical types.  */
306   if (INTEGRAL_TYPE_P (type)
307       || SCALAR_FLOAT_TYPE_P (type)
308       || FIXED_POINT_TYPE_P (type)
309       || TREE_CODE (type) == OFFSET_TYPE
310       || POINTER_TYPE_P (type))
311     {
312       hstate.add_int (TYPE_PRECISION (type));
313       if (!type_with_interoperable_signedness (type))
314         hstate.add_int (TYPE_UNSIGNED (type));
315     }
316
317   if (VECTOR_TYPE_P (type))
318     {
319       hstate.add_int (TYPE_VECTOR_SUBPARTS (type));
320       hstate.add_int (TYPE_UNSIGNED (type));
321     }
322
323   if (TREE_CODE (type) == COMPLEX_TYPE)
324     hstate.add_int (TYPE_UNSIGNED (type));
325
326   /* Fortran's C_SIGNED_CHAR is !TYPE_STRING_FLAG but needs to be
327      interoperable with "signed char".  Unless all frontends are revisited to
328      agree on these types, we must ignore the flag completely.  */
329
330   /* Fortran standard define C_PTR type that is compatible with every
331      C pointer.  For this reason we need to glob all pointers into one.
332      Still pointers in different address spaces are not compatible.  */
333   if (POINTER_TYPE_P (type))
334     hstate.add_int (TYPE_ADDR_SPACE (TREE_TYPE (type)));
335
336   /* For array types hash the domain bounds and the string flag.  */
337   if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
338     {
339       hstate.add_int (TYPE_STRING_FLAG (type));
340       /* OMP lowering can introduce error_mark_node in place of
341          random local decls in types.  */
342       if (TYPE_MIN_VALUE (TYPE_DOMAIN (type)) != error_mark_node)
343         inchash::add_expr (TYPE_MIN_VALUE (TYPE_DOMAIN (type)), hstate);
344       if (TYPE_MAX_VALUE (TYPE_DOMAIN (type)) != error_mark_node)
345         inchash::add_expr (TYPE_MAX_VALUE (TYPE_DOMAIN (type)), hstate);
346     }
347
348   /* Recurse for aggregates with a single element type.  */
349   if (TREE_CODE (type) == ARRAY_TYPE
350       || TREE_CODE (type) == COMPLEX_TYPE
351       || TREE_CODE (type) == VECTOR_TYPE)
352     iterative_hash_canonical_type (TREE_TYPE (type), hstate);
353
354   /* Incorporate function return and argument types.  */
355   if (TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == METHOD_TYPE)
356     {
357       unsigned na;
358       tree p;
359
360       iterative_hash_canonical_type (TREE_TYPE (type), hstate);
361
362       for (p = TYPE_ARG_TYPES (type), na = 0; p; p = TREE_CHAIN (p))
363         {
364           iterative_hash_canonical_type (TREE_VALUE (p), hstate);
365           na++;
366         }
367
368       hstate.add_int (na);
369     }
370
371   if (RECORD_OR_UNION_TYPE_P (type))
372     {
373       unsigned nf;
374       tree f;
375
376       for (f = TYPE_FIELDS (type), nf = 0; f; f = TREE_CHAIN (f))
377         if (TREE_CODE (f) == FIELD_DECL
378             && (! DECL_SIZE (f)
379                 || ! integer_zerop (DECL_SIZE (f))))
380           {
381             iterative_hash_canonical_type (TREE_TYPE (f), hstate);
382             nf++;
383           }
384
385       hstate.add_int (nf);
386     }
387
388   return hstate.end();
389 }
390
391 /* Returning a hash value for gimple type TYPE combined with VAL.  */
392
393 static void
394 iterative_hash_canonical_type (tree type, inchash::hash &hstate)
395 {
396   hashval_t v;
397
398   /* All type variants have same TYPE_CANONICAL.  */
399   type = TYPE_MAIN_VARIANT (type);
400
401   if (!canonical_type_used_p (type))
402     v = hash_canonical_type (type);
403   /* An already processed type.  */
404   else if (TYPE_CANONICAL (type))
405     {
406       type = TYPE_CANONICAL (type);
407       v = gimple_canonical_type_hash (type);
408     }
409   else
410     {
411       /* Canonical types should not be able to form SCCs by design, this
412          recursion is just because we do not register canonical types in
413          optimal order.  To avoid quadratic behavior also register the
414          type here.  */
415       v = hash_canonical_type (type);
416       gimple_register_canonical_type_1 (type, v);
417     }
418   hstate.add_int (v);
419 }
420
421 /* Returns the hash for a canonical type P.  */
422
423 static hashval_t
424 gimple_canonical_type_hash (const void *p)
425 {
426   num_canonical_type_hash_queries++;
427   hashval_t *slot = canonical_type_hash_cache->get ((const_tree) p);
428   gcc_assert (slot != NULL);
429   return *slot;
430 }
431
432
433
434 /* Returns nonzero if P1 and P2 are equal.  */
435
436 static int
437 gimple_canonical_type_eq (const void *p1, const void *p2)
438 {
439   const_tree t1 = (const_tree) p1;
440   const_tree t2 = (const_tree) p2;
441   return gimple_canonical_types_compatible_p (CONST_CAST_TREE (t1),
442                                               CONST_CAST_TREE (t2));
443 }
444
445 /* Main worker for gimple_register_canonical_type.  */
446
447 static void
448 gimple_register_canonical_type_1 (tree t, hashval_t hash)
449 {
450   void **slot;
451
452   gcc_checking_assert (TYPE_P (t) && !TYPE_CANONICAL (t)
453                        && type_with_alias_set_p (t)
454                        && canonical_type_used_p (t));
455
456   slot = htab_find_slot_with_hash (gimple_canonical_types, t, hash, INSERT);
457   if (*slot)
458     {
459       tree new_type = (tree)(*slot);
460       gcc_checking_assert (new_type != t);
461       TYPE_CANONICAL (t) = new_type;
462     }
463   else
464     {
465       TYPE_CANONICAL (t) = t;
466       *slot = (void *) t;
467       /* Cache the just computed hash value.  */
468       num_canonical_type_hash_entries++;
469       bool existed_p = canonical_type_hash_cache->put (t, hash);
470       gcc_assert (!existed_p);
471     }
472 }
473
474 /* Register type T in the global type table gimple_types and set
475    TYPE_CANONICAL of T accordingly.
476    This is used by LTO to merge structurally equivalent types for
477    type-based aliasing purposes across different TUs and languages.
478
479    ???  This merging does not exactly match how the tree.c middle-end
480    functions will assign TYPE_CANONICAL when new types are created
481    during optimization (which at least happens for pointer and array
482    types).  */
483
484 static void
485 gimple_register_canonical_type (tree t)
486 {
487   if (TYPE_CANONICAL (t) || !type_with_alias_set_p (t)
488       || !canonical_type_used_p (t))
489     return;
490
491   /* Canonical types are same among all complete variants.  */
492   if (TYPE_CANONICAL (TYPE_MAIN_VARIANT (t)))
493     TYPE_CANONICAL (t) = TYPE_CANONICAL (TYPE_MAIN_VARIANT (t));
494   else
495     {
496       gimple_register_canonical_type_1 (TYPE_MAIN_VARIANT (t),
497                                         hash_canonical_type (TYPE_MAIN_VARIANT (t)));
498       TYPE_CANONICAL (t) = TYPE_CANONICAL (TYPE_MAIN_VARIANT (t));
499     }
500 }
501
502 /* Re-compute TYPE_CANONICAL for NODE and related types.  */
503
504 static void
505 lto_register_canonical_types (tree node, bool first_p)
506 {
507   if (!node
508       || !TYPE_P (node))
509     return;
510
511   if (first_p)
512     TYPE_CANONICAL (node) = NULL_TREE;
513
514   if (POINTER_TYPE_P (node)
515       || TREE_CODE (node) == COMPLEX_TYPE
516       || TREE_CODE (node) == ARRAY_TYPE)
517     lto_register_canonical_types (TREE_TYPE (node), first_p);
518
519  if (!first_p) 
520     gimple_register_canonical_type (node);
521 }
522
523
524 /* Remember trees that contains references to declarations.  */
525 static GTY(()) vec <tree, va_gc> *tree_with_vars;
526
527 #define CHECK_VAR(tt) \
528   do \
529     { \
530       if ((tt) && VAR_OR_FUNCTION_DECL_P (tt) \
531           && (TREE_PUBLIC (tt) || DECL_EXTERNAL (tt))) \
532         return true; \
533     } while (0)
534
535 #define CHECK_NO_VAR(tt) \
536   gcc_checking_assert (!(tt) || !VAR_OR_FUNCTION_DECL_P (tt))
537
538 /* Check presence of pointers to decls in fields of a tree_typed T.  */
539
540 static inline bool
541 mentions_vars_p_typed (tree t)
542 {
543   CHECK_NO_VAR (TREE_TYPE (t));
544   return false;
545 }
546
547 /* Check presence of pointers to decls in fields of a tree_common T.  */
548
549 static inline bool
550 mentions_vars_p_common (tree t)
551 {
552   if (mentions_vars_p_typed (t))
553     return true;
554   CHECK_NO_VAR (TREE_CHAIN (t));
555   return false;
556 }
557
558 /* Check presence of pointers to decls in fields of a decl_minimal T.  */
559
560 static inline bool
561 mentions_vars_p_decl_minimal (tree t)
562 {
563   if (mentions_vars_p_common (t))
564     return true;
565   CHECK_NO_VAR (DECL_NAME (t));
566   CHECK_VAR (DECL_CONTEXT (t));
567   return false;
568 }
569
570 /* Check presence of pointers to decls in fields of a decl_common T.  */
571
572 static inline bool
573 mentions_vars_p_decl_common (tree t)
574 {
575   if (mentions_vars_p_decl_minimal (t))
576     return true;
577   CHECK_VAR (DECL_SIZE (t));
578   CHECK_VAR (DECL_SIZE_UNIT (t));
579   CHECK_VAR (DECL_INITIAL (t));
580   CHECK_NO_VAR (DECL_ATTRIBUTES (t));
581   CHECK_VAR (DECL_ABSTRACT_ORIGIN (t));
582   return false;
583 }
584
585 /* Check presence of pointers to decls in fields of a decl_with_vis T.  */
586
587 static inline bool
588 mentions_vars_p_decl_with_vis (tree t)
589 {
590   if (mentions_vars_p_decl_common (t))
591     return true;
592
593   /* Accessor macro has side-effects, use field-name here. */
594   CHECK_NO_VAR (t->decl_with_vis.assembler_name);
595   return false;
596 }
597
598 /* Check presence of pointers to decls in fields of a decl_non_common T.  */
599
600 static inline bool
601 mentions_vars_p_decl_non_common (tree t)
602 {
603   if (mentions_vars_p_decl_with_vis (t))
604     return true;
605   CHECK_NO_VAR (DECL_RESULT_FLD (t));
606   return false;
607 }
608
609 /* Check presence of pointers to decls in fields of a decl_non_common T.  */
610
611 static bool
612 mentions_vars_p_function (tree t)
613 {
614   if (mentions_vars_p_decl_non_common (t))
615     return true;
616   CHECK_NO_VAR (DECL_ARGUMENTS (t));
617   CHECK_NO_VAR (DECL_VINDEX (t));
618   CHECK_VAR (DECL_FUNCTION_PERSONALITY (t));
619   return false;
620 }
621
622 /* Check presence of pointers to decls in fields of a field_decl T.  */
623
624 static bool
625 mentions_vars_p_field_decl (tree t)
626 {
627   if (mentions_vars_p_decl_common (t))
628     return true;
629   CHECK_VAR (DECL_FIELD_OFFSET (t));
630   CHECK_NO_VAR (DECL_BIT_FIELD_TYPE (t));
631   CHECK_NO_VAR (DECL_QUALIFIER (t));
632   CHECK_NO_VAR (DECL_FIELD_BIT_OFFSET (t));
633   CHECK_NO_VAR (DECL_FCONTEXT (t));
634   return false;
635 }
636
637 /* Check presence of pointers to decls in fields of a type T.  */
638
639 static bool
640 mentions_vars_p_type (tree t)
641 {
642   if (mentions_vars_p_common (t))
643     return true;
644   CHECK_NO_VAR (TYPE_CACHED_VALUES (t));
645   CHECK_VAR (TYPE_SIZE (t));
646   CHECK_VAR (TYPE_SIZE_UNIT (t));
647   CHECK_NO_VAR (TYPE_ATTRIBUTES (t));
648   CHECK_NO_VAR (TYPE_NAME (t));
649
650   CHECK_VAR (TYPE_MIN_VALUE_RAW (t));
651   CHECK_VAR (TYPE_MAX_VALUE_RAW (t));
652
653   /* Accessor is for derived node types only. */
654   CHECK_NO_VAR (TYPE_LANG_SLOT_1 (t));
655
656   CHECK_VAR (TYPE_CONTEXT (t));
657   CHECK_NO_VAR (TYPE_CANONICAL (t));
658   CHECK_NO_VAR (TYPE_MAIN_VARIANT (t));
659   CHECK_NO_VAR (TYPE_NEXT_VARIANT (t));
660   return false;
661 }
662
663 /* Check presence of pointers to decls in fields of a BINFO T.  */
664
665 static bool
666 mentions_vars_p_binfo (tree t)
667 {
668   unsigned HOST_WIDE_INT i, n;
669
670   if (mentions_vars_p_common (t))
671     return true;
672   CHECK_VAR (BINFO_VTABLE (t));
673   CHECK_NO_VAR (BINFO_OFFSET (t));
674   CHECK_NO_VAR (BINFO_VIRTUALS (t));
675   CHECK_NO_VAR (BINFO_VPTR_FIELD (t));
676   n = vec_safe_length (BINFO_BASE_ACCESSES (t));
677   for (i = 0; i < n; i++)
678     CHECK_NO_VAR (BINFO_BASE_ACCESS (t, i));
679   /* Do not walk BINFO_INHERITANCE_CHAIN, BINFO_SUBVTT_INDEX
680      and BINFO_VPTR_INDEX; these are used by C++ FE only.  */
681   n = BINFO_N_BASE_BINFOS (t);
682   for (i = 0; i < n; i++)
683     CHECK_NO_VAR (BINFO_BASE_BINFO (t, i));
684   return false;
685 }
686
687 /* Check presence of pointers to decls in fields of a CONSTRUCTOR T.  */
688
689 static bool
690 mentions_vars_p_constructor (tree t)
691 {
692   unsigned HOST_WIDE_INT idx;
693   constructor_elt *ce;
694
695   if (mentions_vars_p_typed (t))
696     return true;
697
698   for (idx = 0; vec_safe_iterate (CONSTRUCTOR_ELTS (t), idx, &ce); idx++)
699     {
700       CHECK_NO_VAR (ce->index);
701       CHECK_VAR (ce->value);
702     }
703   return false;
704 }
705
706 /* Check presence of pointers to decls in fields of an expression tree T.  */
707
708 static bool
709 mentions_vars_p_expr (tree t)
710 {
711   int i;
712   if (mentions_vars_p_typed (t))
713     return true;
714   for (i = TREE_OPERAND_LENGTH (t) - 1; i >= 0; --i)
715     CHECK_VAR (TREE_OPERAND (t, i));
716   return false;
717 }
718
719 /* Check presence of pointers to decls in fields of an OMP_CLAUSE T.  */
720
721 static bool
722 mentions_vars_p_omp_clause (tree t)
723 {
724   int i;
725   if (mentions_vars_p_common (t))
726     return true;
727   for (i = omp_clause_num_ops[OMP_CLAUSE_CODE (t)] - 1; i >= 0; --i)
728     CHECK_VAR (OMP_CLAUSE_OPERAND (t, i));
729   return false;
730 }
731
732 /* Check presence of pointers to decls that needs later fixup in T.  */
733
734 static bool
735 mentions_vars_p (tree t)
736 {
737   switch (TREE_CODE (t))
738     {
739     case IDENTIFIER_NODE:
740       break;
741
742     case TREE_LIST:
743       CHECK_VAR (TREE_VALUE (t));
744       CHECK_VAR (TREE_PURPOSE (t));
745       CHECK_NO_VAR (TREE_CHAIN (t));
746       break;
747
748     case FIELD_DECL:
749       return mentions_vars_p_field_decl (t);
750
751     case LABEL_DECL:
752     case CONST_DECL:
753     case PARM_DECL:
754     case RESULT_DECL:
755     case IMPORTED_DECL:
756     case NAMESPACE_DECL:
757     case NAMELIST_DECL:
758       return mentions_vars_p_decl_common (t);
759
760     case VAR_DECL:
761       return mentions_vars_p_decl_with_vis (t);
762
763     case TYPE_DECL:
764       return mentions_vars_p_decl_non_common (t);
765
766     case FUNCTION_DECL:
767       return mentions_vars_p_function (t);
768
769     case TREE_BINFO:
770       return mentions_vars_p_binfo (t);
771
772     case PLACEHOLDER_EXPR:
773       return mentions_vars_p_common (t);
774
775     case BLOCK:
776     case TRANSLATION_UNIT_DECL:
777     case OPTIMIZATION_NODE:
778     case TARGET_OPTION_NODE:
779       break;
780
781     case CONSTRUCTOR:
782       return mentions_vars_p_constructor (t);
783
784     case OMP_CLAUSE:
785       return mentions_vars_p_omp_clause (t);
786
787     default:
788       if (TYPE_P (t))
789         {
790           if (mentions_vars_p_type (t))
791             return true;
792         }
793       else if (EXPR_P (t))
794         {
795           if (mentions_vars_p_expr (t))
796             return true;
797         }
798       else if (CONSTANT_CLASS_P (t))
799         CHECK_NO_VAR (TREE_TYPE (t));
800       else
801         gcc_unreachable ();
802     }
803   return false;
804 }
805
806
807 /* Return the resolution for the decl with index INDEX from DATA_IN. */
808
809 static enum ld_plugin_symbol_resolution
810 get_resolution (struct data_in *data_in, unsigned index)
811 {
812   if (data_in->globals_resolution.exists ())
813     {
814       ld_plugin_symbol_resolution_t ret;
815       /* We can have references to not emitted functions in
816          DECL_FUNCTION_PERSONALITY at least.  So we can and have
817          to indeed return LDPR_UNKNOWN in some cases.   */
818       if (data_in->globals_resolution.length () <= index)
819         return LDPR_UNKNOWN;
820       ret = data_in->globals_resolution[index];
821       return ret;
822     }
823   else
824     /* Delay resolution finding until decl merging.  */
825     return LDPR_UNKNOWN;
826 }
827
828 /* We need to record resolutions until symbol table is read.  */
829 static void
830 register_resolution (struct lto_file_decl_data *file_data, tree decl,
831                      enum ld_plugin_symbol_resolution resolution)
832 {
833   if (resolution == LDPR_UNKNOWN)
834     return;
835   if (!file_data->resolution_map)
836     file_data->resolution_map
837       = new hash_map<tree, ld_plugin_symbol_resolution>;
838   file_data->resolution_map->put (decl, resolution);
839 }
840
841 /* Register DECL with the global symbol table and change its
842    name if necessary to avoid name clashes for static globals across
843    different files.  */
844
845 static void
846 lto_register_var_decl_in_symtab (struct data_in *data_in, tree decl,
847                                  unsigned ix)
848 {
849   tree context;
850
851   /* Variable has file scope, not local.  */
852   if (!TREE_PUBLIC (decl)
853       && !((context = decl_function_context (decl))
854            && auto_var_in_fn_p (decl, context)))
855     rest_of_decl_compilation (decl, 1, 0);
856
857   /* If this variable has already been declared, queue the
858      declaration for merging.  */
859   if (TREE_PUBLIC (decl))
860     register_resolution (data_in->file_data,
861                          decl, get_resolution (data_in, ix));
862 }
863
864
865 /* Register DECL with the global symbol table and change its
866    name if necessary to avoid name clashes for static globals across
867    different files.  DATA_IN contains descriptors and tables for the
868    file being read.  */
869
870 static void
871 lto_register_function_decl_in_symtab (struct data_in *data_in, tree decl,
872                                       unsigned ix)
873 {
874   /* If this variable has already been declared, queue the
875      declaration for merging.  */
876   if (TREE_PUBLIC (decl) && !DECL_ABSTRACT_P (decl))
877     register_resolution (data_in->file_data,
878                          decl, get_resolution (data_in, ix));
879 }
880
881
882 /* For the type T re-materialize it in the type variant list and
883    the pointer/reference-to chains.  */
884
885 static void
886 lto_fixup_prevailing_type (tree t)
887 {
888   /* The following re-creates proper variant lists while fixing up
889      the variant leaders.  We do not stream TYPE_NEXT_VARIANT so the
890      variant list state before fixup is broken.  */
891
892   /* If we are not our own variant leader link us into our new leaders
893      variant list.  */
894   if (TYPE_MAIN_VARIANT (t) != t)
895     {
896       tree mv = TYPE_MAIN_VARIANT (t);
897       TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (mv);
898       TYPE_NEXT_VARIANT (mv) = t;
899     }
900
901   /* The following reconstructs the pointer chains
902      of the new pointed-to type if we are a main variant.  We do
903      not stream those so they are broken before fixup.  */
904   if (TREE_CODE (t) == POINTER_TYPE
905       && TYPE_MAIN_VARIANT (t) == t)
906     {
907       TYPE_NEXT_PTR_TO (t) = TYPE_POINTER_TO (TREE_TYPE (t));
908       TYPE_POINTER_TO (TREE_TYPE (t)) = t;
909     }
910   else if (TREE_CODE (t) == REFERENCE_TYPE
911            && TYPE_MAIN_VARIANT (t) == t)
912     {
913       TYPE_NEXT_REF_TO (t) = TYPE_REFERENCE_TO (TREE_TYPE (t));
914       TYPE_REFERENCE_TO (TREE_TYPE (t)) = t;
915     }
916 }
917
918
919 /* We keep prevailing tree SCCs in a hashtable with manual collision
920    handling (in case all hashes compare the same) and keep the colliding
921    entries in the tree_scc->next chain.  */
922
923 struct tree_scc
924 {
925   tree_scc *next;
926   /* Hash of the whole SCC.  */
927   hashval_t hash;
928   /* Number of trees in the SCC.  */
929   unsigned len;
930   /* Number of possible entries into the SCC (tree nodes [0..entry_len-1]
931      which share the same individual tree hash).  */
932   unsigned entry_len;
933   /* The members of the SCC.
934      We only need to remember the first entry node candidate for prevailing
935      SCCs (but of course have access to all entries for SCCs we are
936      processing).
937      ???  For prevailing SCCs we really only need hash and the first
938      entry candidate, but that's too awkward to implement.  */
939   tree entries[1];
940 };
941
942 struct tree_scc_hasher : nofree_ptr_hash <tree_scc>
943 {
944   static inline hashval_t hash (const tree_scc *);
945   static inline bool equal (const tree_scc *, const tree_scc *);
946 };
947
948 hashval_t
949 tree_scc_hasher::hash (const tree_scc *scc)
950 {
951   return scc->hash;
952 }
953
954 bool
955 tree_scc_hasher::equal (const tree_scc *scc1, const tree_scc *scc2)
956 {
957   if (scc1->hash != scc2->hash
958       || scc1->len != scc2->len
959       || scc1->entry_len != scc2->entry_len)
960     return false;
961   return true;
962 }
963
964 static hash_table<tree_scc_hasher> *tree_scc_hash;
965 static struct obstack tree_scc_hash_obstack;
966
967 static unsigned long num_merged_types;
968 static unsigned long num_prevailing_types;
969 static unsigned long num_type_scc_trees;
970 static unsigned long total_scc_size;
971 static unsigned long num_sccs_read;
972 static unsigned long total_scc_size_merged;
973 static unsigned long num_sccs_merged;
974 static unsigned long num_scc_compares;
975 static unsigned long num_scc_compare_collisions;
976
977
978 /* Compare the two entries T1 and T2 of two SCCs that are possibly equal,
979    recursing through in-SCC tree edges.  Returns true if the SCCs entered
980    through T1 and T2 are equal and fills in *MAP with the pairs of
981    SCC entries we visited, starting with (*MAP)[0] = T1 and (*MAP)[1] = T2.  */
982
983 static bool
984 compare_tree_sccs_1 (tree t1, tree t2, tree **map)
985 {
986   enum tree_code code;
987
988   /* Mark already visited nodes.  */
989   TREE_ASM_WRITTEN (t2) = 1;
990
991   /* Push the pair onto map.  */
992   (*map)[0] = t1;
993   (*map)[1] = t2;
994   *map = *map + 2;
995
996   /* Compare value-fields.  */
997 #define compare_values(X) \
998   do { \
999     if (X(t1) != X(t2)) \
1000       return false; \
1001   } while (0)
1002
1003   compare_values (TREE_CODE);
1004   code = TREE_CODE (t1);
1005
1006   if (!TYPE_P (t1))
1007     {
1008       compare_values (TREE_SIDE_EFFECTS);
1009       compare_values (TREE_CONSTANT);
1010       compare_values (TREE_READONLY);
1011       compare_values (TREE_PUBLIC);
1012     }
1013   compare_values (TREE_ADDRESSABLE);
1014   compare_values (TREE_THIS_VOLATILE);
1015   if (DECL_P (t1))
1016     compare_values (DECL_UNSIGNED);
1017   else if (TYPE_P (t1))
1018     compare_values (TYPE_UNSIGNED);
1019   if (TYPE_P (t1))
1020     compare_values (TYPE_ARTIFICIAL);
1021   else
1022     compare_values (TREE_NO_WARNING);
1023   compare_values (TREE_NOTHROW);
1024   compare_values (TREE_STATIC);
1025   if (code != TREE_BINFO)
1026     compare_values (TREE_PRIVATE);
1027   compare_values (TREE_PROTECTED);
1028   compare_values (TREE_DEPRECATED);
1029   if (TYPE_P (t1))
1030     {
1031       if (AGGREGATE_TYPE_P (t1))
1032         compare_values (TYPE_REVERSE_STORAGE_ORDER);
1033       else
1034         compare_values (TYPE_SATURATING);
1035       compare_values (TYPE_ADDR_SPACE);
1036     }
1037   else if (code == SSA_NAME)
1038     compare_values (SSA_NAME_IS_DEFAULT_DEF);
1039
1040   if (CODE_CONTAINS_STRUCT (code, TS_INT_CST))
1041     {
1042       if (!wi::eq_p (t1, t2))
1043         return false;
1044     }
1045
1046   if (CODE_CONTAINS_STRUCT (code, TS_REAL_CST))
1047     {
1048       /* ???  No suitable compare routine available.  */
1049       REAL_VALUE_TYPE r1 = TREE_REAL_CST (t1);
1050       REAL_VALUE_TYPE r2 = TREE_REAL_CST (t2);
1051       if (r1.cl != r2.cl
1052           || r1.decimal != r2.decimal
1053           || r1.sign != r2.sign
1054           || r1.signalling != r2.signalling
1055           || r1.canonical != r2.canonical
1056           || r1.uexp != r2.uexp)
1057         return false;
1058       for (unsigned i = 0; i < SIGSZ; ++i)
1059         if (r1.sig[i] != r2.sig[i])
1060           return false;
1061     }
1062
1063   if (CODE_CONTAINS_STRUCT (code, TS_FIXED_CST))
1064     if (!fixed_compare (EQ_EXPR,
1065                         TREE_FIXED_CST_PTR (t1), TREE_FIXED_CST_PTR (t2)))
1066       return false;
1067
1068   if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
1069     {
1070       compare_values (DECL_MODE);
1071       compare_values (DECL_NONLOCAL);
1072       compare_values (DECL_VIRTUAL_P);
1073       compare_values (DECL_IGNORED_P);
1074       compare_values (DECL_ABSTRACT_P);
1075       compare_values (DECL_ARTIFICIAL);
1076       compare_values (DECL_USER_ALIGN);
1077       compare_values (DECL_PRESERVE_P);
1078       compare_values (DECL_EXTERNAL);
1079       compare_values (DECL_GIMPLE_REG_P);
1080       compare_values (DECL_ALIGN);
1081       if (code == LABEL_DECL)
1082         {
1083           compare_values (EH_LANDING_PAD_NR);
1084           compare_values (LABEL_DECL_UID);
1085         }
1086       else if (code == FIELD_DECL)
1087         {
1088           compare_values (DECL_PACKED);
1089           compare_values (DECL_NONADDRESSABLE_P);
1090           compare_values (DECL_OFFSET_ALIGN);
1091         }
1092       else if (code == VAR_DECL)
1093         {
1094           compare_values (DECL_HAS_DEBUG_EXPR_P);
1095           compare_values (DECL_NONLOCAL_FRAME);
1096         }
1097       if (code == RESULT_DECL
1098           || code == PARM_DECL
1099           || code == VAR_DECL)
1100         {
1101           compare_values (DECL_BY_REFERENCE);
1102           if (code == VAR_DECL
1103               || code == PARM_DECL)
1104             compare_values (DECL_HAS_VALUE_EXPR_P);
1105         }
1106     }
1107
1108   if (CODE_CONTAINS_STRUCT (code, TS_DECL_WRTL))
1109     compare_values (DECL_REGISTER);
1110
1111   if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
1112     {
1113       compare_values (DECL_COMMON);
1114       compare_values (DECL_DLLIMPORT_P);
1115       compare_values (DECL_WEAK);
1116       compare_values (DECL_SEEN_IN_BIND_EXPR_P);
1117       compare_values (DECL_COMDAT);
1118       compare_values (DECL_VISIBILITY);
1119       compare_values (DECL_VISIBILITY_SPECIFIED);
1120       if (code == VAR_DECL)
1121         {
1122           compare_values (DECL_HARD_REGISTER);
1123           /* DECL_IN_TEXT_SECTION is set during final asm output only.  */
1124           compare_values (DECL_IN_CONSTANT_POOL);
1125         }
1126     }
1127
1128   if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
1129     {
1130       compare_values (DECL_BUILT_IN_CLASS);
1131       compare_values (DECL_STATIC_CONSTRUCTOR);
1132       compare_values (DECL_STATIC_DESTRUCTOR);
1133       compare_values (DECL_UNINLINABLE);
1134       compare_values (DECL_POSSIBLY_INLINED);
1135       compare_values (DECL_IS_NOVOPS);
1136       compare_values (DECL_IS_RETURNS_TWICE);
1137       compare_values (DECL_IS_MALLOC);
1138       compare_values (DECL_IS_OPERATOR_NEW);
1139       compare_values (DECL_DECLARED_INLINE_P);
1140       compare_values (DECL_STATIC_CHAIN);
1141       compare_values (DECL_NO_INLINE_WARNING_P);
1142       compare_values (DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT);
1143       compare_values (DECL_NO_LIMIT_STACK);
1144       compare_values (DECL_DISREGARD_INLINE_LIMITS);
1145       compare_values (DECL_PURE_P);
1146       compare_values (DECL_LOOPING_CONST_OR_PURE_P);
1147       compare_values (DECL_FINAL_P);
1148       compare_values (DECL_CXX_CONSTRUCTOR_P);
1149       compare_values (DECL_CXX_DESTRUCTOR_P);
1150       if (DECL_BUILT_IN_CLASS (t1) != NOT_BUILT_IN)
1151         compare_values (DECL_FUNCTION_CODE);
1152     }
1153
1154   if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
1155     {
1156       compare_values (TYPE_MODE);
1157       compare_values (TYPE_STRING_FLAG);
1158       compare_values (TYPE_NEEDS_CONSTRUCTING);
1159       if (RECORD_OR_UNION_TYPE_P (t1))
1160         {
1161           compare_values (TYPE_TRANSPARENT_AGGR);
1162           compare_values (TYPE_FINAL_P);
1163         }
1164       else if (code == ARRAY_TYPE)
1165         compare_values (TYPE_NONALIASED_COMPONENT);
1166       if (AGGREGATE_TYPE_P (t1))
1167         compare_values (TYPE_TYPELESS_STORAGE);
1168       compare_values (TYPE_PACKED);
1169       compare_values (TYPE_RESTRICT);
1170       compare_values (TYPE_USER_ALIGN);
1171       compare_values (TYPE_READONLY);
1172       compare_values (TYPE_PRECISION);
1173       compare_values (TYPE_ALIGN);
1174       /* Do not compare TYPE_ALIAS_SET.  Doing so introduce ordering issues
1175          with calls to get_alias_set which may initialize it for streamed
1176          in types.  */
1177     }
1178
1179   /* We don't want to compare locations, so there is nothing do compare
1180      for TS_EXP.  */
1181
1182   /* BLOCKs are function local and we don't merge anything there, so
1183      simply refuse to merge.  */
1184   if (CODE_CONTAINS_STRUCT (code, TS_BLOCK))
1185     return false;
1186
1187   if (CODE_CONTAINS_STRUCT (code, TS_TRANSLATION_UNIT_DECL))
1188     if (strcmp (TRANSLATION_UNIT_LANGUAGE (t1),
1189                 TRANSLATION_UNIT_LANGUAGE (t2)) != 0)
1190       return false;
1191
1192   if (CODE_CONTAINS_STRUCT (code, TS_TARGET_OPTION))
1193     if (!cl_target_option_eq (TREE_TARGET_OPTION (t1), TREE_TARGET_OPTION (t2)))
1194       return false;
1195
1196   if (CODE_CONTAINS_STRUCT (code, TS_OPTIMIZATION))
1197     if (memcmp (TREE_OPTIMIZATION (t1), TREE_OPTIMIZATION (t2),
1198                 sizeof (struct cl_optimization)) != 0)
1199       return false;
1200
1201   if (CODE_CONTAINS_STRUCT (code, TS_BINFO))
1202     if (vec_safe_length (BINFO_BASE_ACCESSES (t1))
1203         != vec_safe_length (BINFO_BASE_ACCESSES (t2)))
1204       return false;
1205
1206   if (CODE_CONTAINS_STRUCT (code, TS_CONSTRUCTOR))
1207     compare_values (CONSTRUCTOR_NELTS);
1208
1209   if (CODE_CONTAINS_STRUCT (code, TS_IDENTIFIER))
1210     if (IDENTIFIER_LENGTH (t1) != IDENTIFIER_LENGTH (t2)
1211         || memcmp (IDENTIFIER_POINTER (t1), IDENTIFIER_POINTER (t2),
1212                    IDENTIFIER_LENGTH (t1)) != 0)
1213       return false;
1214
1215   if (CODE_CONTAINS_STRUCT (code, TS_STRING))
1216     if (TREE_STRING_LENGTH (t1) != TREE_STRING_LENGTH (t2)
1217         || memcmp (TREE_STRING_POINTER (t1), TREE_STRING_POINTER (t2),
1218                    TREE_STRING_LENGTH (t1)) != 0)
1219       return false;
1220
1221   if (code == OMP_CLAUSE)
1222     {
1223       compare_values (OMP_CLAUSE_CODE);
1224       switch (OMP_CLAUSE_CODE (t1))
1225         {
1226         case OMP_CLAUSE_DEFAULT:
1227           compare_values (OMP_CLAUSE_DEFAULT_KIND);
1228           break;
1229         case OMP_CLAUSE_SCHEDULE:
1230           compare_values (OMP_CLAUSE_SCHEDULE_KIND);
1231           break;
1232         case OMP_CLAUSE_DEPEND:
1233           compare_values (OMP_CLAUSE_DEPEND_KIND);
1234           break;
1235         case OMP_CLAUSE_MAP:
1236           compare_values (OMP_CLAUSE_MAP_KIND);
1237           break;
1238         case OMP_CLAUSE_PROC_BIND:
1239           compare_values (OMP_CLAUSE_PROC_BIND_KIND);
1240           break;
1241         case OMP_CLAUSE_REDUCTION:
1242           compare_values (OMP_CLAUSE_REDUCTION_CODE);
1243           compare_values (OMP_CLAUSE_REDUCTION_GIMPLE_INIT);
1244           compare_values (OMP_CLAUSE_REDUCTION_GIMPLE_MERGE);
1245           break;
1246         default:
1247           break;
1248         }
1249     }
1250
1251 #undef compare_values
1252
1253
1254   /* Compare pointer fields.  */
1255
1256   /* Recurse.  Search & Replaced from DFS_write_tree_body.
1257      Folding the early checks into the compare_tree_edges recursion
1258      macro makes debugging way quicker as you are able to break on
1259      compare_tree_sccs_1 and simply finish until a call returns false
1260      to spot the SCC members with the difference.  */
1261 #define compare_tree_edges(E1, E2) \
1262   do { \
1263     tree t1_ = (E1), t2_ = (E2); \
1264     if (t1_ != t2_ \
1265         && (!t1_ || !t2_ \
1266             || !TREE_VISITED (t2_) \
1267             || (!TREE_ASM_WRITTEN (t2_) \
1268                 && !compare_tree_sccs_1 (t1_, t2_, map)))) \
1269       return false; \
1270     /* Only non-NULL trees outside of the SCC may compare equal.  */ \
1271     gcc_checking_assert (t1_ != t2_ || (!t2_ || !TREE_VISITED (t2_))); \
1272   } while (0)
1273
1274   if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
1275     {
1276       if (code != IDENTIFIER_NODE)
1277         compare_tree_edges (TREE_TYPE (t1), TREE_TYPE (t2));
1278     }
1279
1280   if (CODE_CONTAINS_STRUCT (code, TS_VECTOR))
1281     {
1282       unsigned i;
1283       /* Note that the number of elements for EXPR has already been emitted
1284          in EXPR's header (see streamer_write_tree_header).  */
1285       for (i = 0; i < VECTOR_CST_NELTS (t1); ++i)
1286         compare_tree_edges (VECTOR_CST_ELT (t1, i), VECTOR_CST_ELT (t2, i));
1287     }
1288
1289   if (CODE_CONTAINS_STRUCT (code, TS_COMPLEX))
1290     {
1291       compare_tree_edges (TREE_REALPART (t1), TREE_REALPART (t2));
1292       compare_tree_edges (TREE_IMAGPART (t1), TREE_IMAGPART (t2));
1293     }
1294
1295   if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
1296     {
1297       compare_tree_edges (DECL_NAME (t1), DECL_NAME (t2));
1298       /* ???  Global decls from different TUs have non-matching
1299          TRANSLATION_UNIT_DECLs.  Only consider a small set of
1300          decls equivalent, we should not end up merging others.  */
1301       if ((code == TYPE_DECL
1302            || code == NAMESPACE_DECL
1303            || code == IMPORTED_DECL
1304            || code == CONST_DECL
1305            || (VAR_OR_FUNCTION_DECL_P (t1)
1306                && (TREE_PUBLIC (t1) || DECL_EXTERNAL (t1))))
1307           && DECL_FILE_SCOPE_P (t1) && DECL_FILE_SCOPE_P (t2))
1308         ;
1309       else
1310         compare_tree_edges (DECL_CONTEXT (t1), DECL_CONTEXT (t2));
1311     }
1312
1313   if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
1314     {
1315       compare_tree_edges (DECL_SIZE (t1), DECL_SIZE (t2));
1316       compare_tree_edges (DECL_SIZE_UNIT (t1), DECL_SIZE_UNIT (t2));
1317       compare_tree_edges (DECL_ATTRIBUTES (t1), DECL_ATTRIBUTES (t2));
1318       compare_tree_edges (DECL_ABSTRACT_ORIGIN (t1), DECL_ABSTRACT_ORIGIN (t2));
1319       if ((code == VAR_DECL
1320            || code == PARM_DECL)
1321           && DECL_HAS_VALUE_EXPR_P (t1))
1322         compare_tree_edges (DECL_VALUE_EXPR (t1), DECL_VALUE_EXPR (t2));
1323       if (code == VAR_DECL
1324           && DECL_HAS_DEBUG_EXPR_P (t1))
1325         compare_tree_edges (DECL_DEBUG_EXPR (t1), DECL_DEBUG_EXPR (t2));
1326       /* LTO specific edges.  */
1327       if (code != FUNCTION_DECL
1328           && code != TRANSLATION_UNIT_DECL)
1329         compare_tree_edges (DECL_INITIAL (t1), DECL_INITIAL (t2));
1330     }
1331
1332   if (CODE_CONTAINS_STRUCT (code, TS_DECL_NON_COMMON))
1333     {
1334       if (code == FUNCTION_DECL)
1335         {
1336           tree a1, a2;
1337           for (a1 = DECL_ARGUMENTS (t1), a2 = DECL_ARGUMENTS (t2);
1338                a1 || a2;
1339                a1 = TREE_CHAIN (a1), a2 = TREE_CHAIN (a2))
1340             compare_tree_edges (a1, a2);
1341           compare_tree_edges (DECL_RESULT (t1), DECL_RESULT (t2));
1342         }
1343       else if (code == TYPE_DECL)
1344         compare_tree_edges (DECL_ORIGINAL_TYPE (t1), DECL_ORIGINAL_TYPE (t2));
1345     }
1346
1347   if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
1348     {
1349       /* Make sure we don't inadvertently set the assembler name.  */
1350       if (DECL_ASSEMBLER_NAME_SET_P (t1))
1351         compare_tree_edges (DECL_ASSEMBLER_NAME (t1),
1352                             DECL_ASSEMBLER_NAME (t2));
1353     }
1354
1355   if (CODE_CONTAINS_STRUCT (code, TS_FIELD_DECL))
1356     {
1357       compare_tree_edges (DECL_FIELD_OFFSET (t1), DECL_FIELD_OFFSET (t2));
1358       compare_tree_edges (DECL_BIT_FIELD_TYPE (t1), DECL_BIT_FIELD_TYPE (t2));
1359       compare_tree_edges (DECL_BIT_FIELD_REPRESENTATIVE (t1),
1360                           DECL_BIT_FIELD_REPRESENTATIVE (t2));
1361       compare_tree_edges (DECL_FIELD_BIT_OFFSET (t1),
1362                           DECL_FIELD_BIT_OFFSET (t2));
1363       compare_tree_edges (DECL_FCONTEXT (t1), DECL_FCONTEXT (t2));
1364     }
1365
1366   if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
1367     {
1368       compare_tree_edges (DECL_FUNCTION_PERSONALITY (t1),
1369                           DECL_FUNCTION_PERSONALITY (t2));
1370       compare_tree_edges (DECL_VINDEX (t1), DECL_VINDEX (t2));
1371       compare_tree_edges (DECL_FUNCTION_SPECIFIC_TARGET (t1),
1372                           DECL_FUNCTION_SPECIFIC_TARGET (t2));
1373       compare_tree_edges (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (t1),
1374                           DECL_FUNCTION_SPECIFIC_OPTIMIZATION (t2));
1375     }
1376
1377   if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
1378     {
1379       compare_tree_edges (TYPE_SIZE (t1), TYPE_SIZE (t2));
1380       compare_tree_edges (TYPE_SIZE_UNIT (t1), TYPE_SIZE_UNIT (t2));
1381       compare_tree_edges (TYPE_ATTRIBUTES (t1), TYPE_ATTRIBUTES (t2));
1382       compare_tree_edges (TYPE_NAME (t1), TYPE_NAME (t2));
1383       /* Do not compare TYPE_POINTER_TO or TYPE_REFERENCE_TO.  They will be
1384          reconstructed during fixup.  */
1385       /* Do not compare TYPE_NEXT_VARIANT, we reconstruct the variant lists
1386          during fixup.  */
1387       compare_tree_edges (TYPE_MAIN_VARIANT (t1), TYPE_MAIN_VARIANT (t2));
1388       /* ???  Global types from different TUs have non-matching
1389          TRANSLATION_UNIT_DECLs.  Still merge them if they are otherwise
1390          equal.  */
1391       if (TYPE_FILE_SCOPE_P (t1) && TYPE_FILE_SCOPE_P (t2))
1392         ;
1393       else
1394         compare_tree_edges (TYPE_CONTEXT (t1), TYPE_CONTEXT (t2));
1395       /* TYPE_CANONICAL is re-computed during type merging, so do not
1396          compare it here.  */
1397       compare_tree_edges (TYPE_STUB_DECL (t1), TYPE_STUB_DECL (t2));
1398     }
1399
1400   if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
1401     {
1402       if (code == ENUMERAL_TYPE)
1403         compare_tree_edges (TYPE_VALUES (t1), TYPE_VALUES (t2));
1404       else if (code == ARRAY_TYPE)
1405         compare_tree_edges (TYPE_DOMAIN (t1), TYPE_DOMAIN (t2));
1406       else if (RECORD_OR_UNION_TYPE_P (t1))
1407         {
1408           tree f1, f2;
1409           for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2);
1410                f1 || f2;
1411                f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2))
1412             compare_tree_edges (f1, f2);
1413         }
1414       else if (code == FUNCTION_TYPE
1415                || code == METHOD_TYPE)
1416         compare_tree_edges (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2));
1417
1418       if (!POINTER_TYPE_P (t1))
1419         compare_tree_edges (TYPE_MIN_VALUE_RAW (t1), TYPE_MIN_VALUE_RAW (t2));
1420       compare_tree_edges (TYPE_MAX_VALUE_RAW (t1), TYPE_MAX_VALUE_RAW (t2));
1421     }
1422
1423   if (CODE_CONTAINS_STRUCT (code, TS_LIST))
1424     {
1425       compare_tree_edges (TREE_PURPOSE (t1), TREE_PURPOSE (t2));
1426       compare_tree_edges (TREE_VALUE (t1), TREE_VALUE (t2));
1427       compare_tree_edges (TREE_CHAIN (t1), TREE_CHAIN (t2));
1428     }
1429
1430   if (CODE_CONTAINS_STRUCT (code, TS_VEC))
1431     for (int i = 0; i < TREE_VEC_LENGTH (t1); i++)
1432       compare_tree_edges (TREE_VEC_ELT (t1, i), TREE_VEC_ELT (t2, i));
1433
1434   if (CODE_CONTAINS_STRUCT (code, TS_EXP))
1435     {
1436       for (int i = 0; i < TREE_OPERAND_LENGTH (t1); i++)
1437         compare_tree_edges (TREE_OPERAND (t1, i),
1438                             TREE_OPERAND (t2, i));
1439
1440       /* BLOCKs are function local and we don't merge anything there.  */
1441       if (TREE_BLOCK (t1) || TREE_BLOCK (t2))
1442         return false;
1443     }
1444
1445   if (CODE_CONTAINS_STRUCT (code, TS_BINFO))
1446     {
1447       unsigned i;
1448       tree t;
1449       /* Lengths have already been compared above.  */
1450       FOR_EACH_VEC_ELT (*BINFO_BASE_BINFOS (t1), i, t)
1451         compare_tree_edges (t, BINFO_BASE_BINFO (t2, i));
1452       FOR_EACH_VEC_SAFE_ELT (BINFO_BASE_ACCESSES (t1), i, t)
1453         compare_tree_edges (t, BINFO_BASE_ACCESS (t2, i));
1454       compare_tree_edges (BINFO_OFFSET (t1), BINFO_OFFSET (t2));
1455       compare_tree_edges (BINFO_VTABLE (t1), BINFO_VTABLE (t2));
1456       compare_tree_edges (BINFO_VPTR_FIELD (t1), BINFO_VPTR_FIELD (t2));
1457       /* Do not walk BINFO_INHERITANCE_CHAIN, BINFO_SUBVTT_INDEX
1458          and BINFO_VPTR_INDEX; these are used by C++ FE only.  */
1459     }
1460
1461   if (CODE_CONTAINS_STRUCT (code, TS_CONSTRUCTOR))
1462     {
1463       unsigned i;
1464       tree index, value;
1465       /* Lengths have already been compared above.  */
1466       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t1), i, index, value)
1467         {
1468           compare_tree_edges (index, CONSTRUCTOR_ELT (t2, i)->index);
1469           compare_tree_edges (value, CONSTRUCTOR_ELT (t2, i)->value);
1470         }
1471     }
1472
1473   if (code == OMP_CLAUSE)
1474     {
1475       int i;
1476
1477       for (i = 0; i < omp_clause_num_ops[OMP_CLAUSE_CODE (t1)]; i++)
1478         compare_tree_edges (OMP_CLAUSE_OPERAND (t1, i),
1479                             OMP_CLAUSE_OPERAND (t2, i));
1480       compare_tree_edges (OMP_CLAUSE_CHAIN (t1), OMP_CLAUSE_CHAIN (t2));
1481     }
1482
1483 #undef compare_tree_edges
1484
1485   return true;
1486 }
1487
1488 /* Compare the tree scc SCC to the prevailing candidate PSCC, filling
1489    out MAP if they are equal.  */
1490
1491 static bool
1492 compare_tree_sccs (tree_scc *pscc, tree_scc *scc,
1493                    tree *map)
1494 {
1495   /* Assume SCC entry hashes are sorted after their cardinality.  Which
1496      means we can simply take the first n-tuple of equal hashes
1497      (which is recorded as entry_len) and do n SCC entry candidate
1498      comparisons.  */
1499   for (unsigned i = 0; i < pscc->entry_len; ++i)
1500     {
1501       tree *mapp = map;
1502       num_scc_compare_collisions++;
1503       if (compare_tree_sccs_1 (pscc->entries[0], scc->entries[i], &mapp))
1504         {
1505           /* Equal - no need to reset TREE_VISITED or TREE_ASM_WRITTEN
1506              on the scc as all trees will be freed.  */
1507           return true;
1508         }
1509       /* Reset TREE_ASM_WRITTEN on scc for the next compare or in case
1510          the SCC prevails.  */
1511       for (unsigned j = 0; j < scc->len; ++j)
1512         TREE_ASM_WRITTEN (scc->entries[j]) = 0;
1513     }
1514
1515   return false;
1516 }
1517
1518 /* QSort sort function to sort a map of two pointers after the 2nd
1519    pointer.  */
1520
1521 static int
1522 cmp_tree (const void *p1_, const void *p2_)
1523 {
1524   tree *p1 = (tree *)(const_cast<void *>(p1_));
1525   tree *p2 = (tree *)(const_cast<void *>(p2_));
1526   if (p1[1] == p2[1])
1527     return 0;
1528   return ((uintptr_t)p1[1] < (uintptr_t)p2[1]) ? -1 : 1;
1529 }
1530
1531 /* Try to unify the SCC with nodes FROM to FROM + LEN in CACHE and
1532    hash value SCC_HASH with an already recorded SCC.  Return true if
1533    that was successful, otherwise return false.  */
1534
1535 static bool
1536 unify_scc (struct data_in *data_in, unsigned from,
1537            unsigned len, unsigned scc_entry_len, hashval_t scc_hash)
1538 {
1539   bool unified_p = false;
1540   struct streamer_tree_cache_d *cache = data_in->reader_cache;
1541   tree_scc *scc
1542     = (tree_scc *) alloca (sizeof (tree_scc) + (len - 1) * sizeof (tree));
1543   scc->next = NULL;
1544   scc->hash = scc_hash;
1545   scc->len = len;
1546   scc->entry_len = scc_entry_len;
1547   for (unsigned i = 0; i < len; ++i)
1548     {
1549       tree t = streamer_tree_cache_get_tree (cache, from + i);
1550       scc->entries[i] = t;
1551       /* Do not merge SCCs with local entities inside them.  Also do
1552          not merge TRANSLATION_UNIT_DECLs.  */
1553       if (TREE_CODE (t) == TRANSLATION_UNIT_DECL
1554           || (VAR_OR_FUNCTION_DECL_P (t)
1555               && !(TREE_PUBLIC (t) || DECL_EXTERNAL (t)))
1556           || TREE_CODE (t) == LABEL_DECL)
1557         {
1558           /* Avoid doing any work for these cases and do not worry to
1559              record the SCCs for further merging.  */
1560           return false;
1561         }
1562     }
1563
1564   /* Look for the list of candidate SCCs to compare against.  */
1565   tree_scc **slot;
1566   slot = tree_scc_hash->find_slot_with_hash (scc, scc_hash, INSERT);
1567   if (*slot)
1568     {
1569       /* Try unifying against each candidate.  */
1570       num_scc_compares++;
1571
1572       /* Set TREE_VISITED on the scc so we can easily identify tree nodes
1573          outside of the scc when following tree edges.  Make sure
1574          that TREE_ASM_WRITTEN is unset so we can use it as 2nd bit
1575          to track whether we visited the SCC member during the compare.
1576          We cannot use TREE_VISITED on the pscc members as the extended
1577          scc and pscc can overlap.  */
1578       for (unsigned i = 0; i < scc->len; ++i)
1579         {
1580           TREE_VISITED (scc->entries[i]) = 1;
1581           gcc_checking_assert (!TREE_ASM_WRITTEN (scc->entries[i]));
1582         }
1583
1584       tree *map = XALLOCAVEC (tree, 2 * len);
1585       for (tree_scc *pscc = *slot; pscc; pscc = pscc->next)
1586         {
1587           if (!compare_tree_sccs (pscc, scc, map))
1588             continue;
1589
1590           /* Found an equal SCC.  */
1591           unified_p = true;
1592           num_scc_compare_collisions--;
1593           num_sccs_merged++;
1594           total_scc_size_merged += len;
1595
1596           if (flag_checking)
1597             for (unsigned i = 0; i < len; ++i)
1598               {
1599                 tree t = map[2*i+1];
1600                 enum tree_code code = TREE_CODE (t);
1601                 /* IDENTIFIER_NODEs should be singletons and are merged by the
1602                    streamer.  The others should be singletons, too, and we
1603                    should not merge them in any way.  */
1604                 gcc_assert (code != TRANSLATION_UNIT_DECL
1605                             && code != IDENTIFIER_NODE);
1606               }
1607
1608           /* Fixup the streamer cache with the prevailing nodes according
1609              to the tree node mapping computed by compare_tree_sccs.  */
1610           if (len == 1)
1611             streamer_tree_cache_replace_tree (cache, pscc->entries[0], from);
1612           else
1613             {
1614               tree *map2 = XALLOCAVEC (tree, 2 * len);
1615               for (unsigned i = 0; i < len; ++i)
1616                 {
1617                   map2[i*2] = (tree)(uintptr_t)(from + i);
1618                   map2[i*2+1] = scc->entries[i];
1619                 }
1620               qsort (map2, len, 2 * sizeof (tree), cmp_tree);
1621               qsort (map, len, 2 * sizeof (tree), cmp_tree);
1622               for (unsigned i = 0; i < len; ++i)
1623                 streamer_tree_cache_replace_tree (cache, map[2*i],
1624                                                   (uintptr_t)map2[2*i]);
1625             }
1626
1627           /* Free the tree nodes from the read SCC.  */
1628           data_in->location_cache.revert_location_cache ();
1629           for (unsigned i = 0; i < len; ++i)
1630             {
1631               if (TYPE_P (scc->entries[i]))
1632                 num_merged_types++;
1633               free_node (scc->entries[i]);
1634             }
1635
1636           /* Drop DIE references.  */
1637           dref_queue.truncate (0);
1638
1639           break;
1640         }
1641
1642       /* Reset TREE_VISITED if we didn't unify the SCC with another.  */
1643       if (!unified_p)
1644         for (unsigned i = 0; i < scc->len; ++i)
1645           TREE_VISITED (scc->entries[i]) = 0;
1646     }
1647
1648   /* If we didn't unify it to any candidate duplicate the relevant
1649      pieces to permanent storage and link it into the chain.  */
1650   if (!unified_p)
1651     {
1652       tree_scc *pscc
1653         = XOBNEWVAR (&tree_scc_hash_obstack, tree_scc, sizeof (tree_scc));
1654       memcpy (pscc, scc, sizeof (tree_scc));
1655       pscc->next = (*slot);
1656       *slot = pscc;
1657     }
1658   return unified_p;
1659 }
1660
1661
1662 /* Read all the symbols from buffer DATA, using descriptors in DECL_DATA.
1663    RESOLUTIONS is the set of symbols picked by the linker (read from the
1664    resolution file when the linker plugin is being used).  */
1665
1666 static void
1667 lto_read_decls (struct lto_file_decl_data *decl_data, const void *data,
1668                 vec<ld_plugin_symbol_resolution_t> resolutions)
1669 {
1670   const struct lto_decl_header *header = (const struct lto_decl_header *) data;
1671   const int decl_offset = sizeof (struct lto_decl_header);
1672   const int main_offset = decl_offset + header->decl_state_size;
1673   const int string_offset = main_offset + header->main_size;
1674   struct data_in *data_in;
1675   unsigned int i;
1676   const uint32_t *data_ptr, *data_end;
1677   uint32_t num_decl_states;
1678
1679   lto_input_block ib_main ((const char *) data + main_offset,
1680                            header->main_size, decl_data->mode_table);
1681
1682   data_in = lto_data_in_create (decl_data, (const char *) data + string_offset,
1683                                 header->string_size, resolutions);
1684
1685   /* We do not uniquify the pre-loaded cache entries, those are middle-end
1686      internal types that should not be merged.  */
1687
1688   /* Read the global declarations and types.  */
1689   while (ib_main.p < ib_main.len)
1690     {
1691       tree t;
1692       unsigned from = data_in->reader_cache->nodes.length ();
1693       /* Read and uniquify SCCs as in the input stream.  */
1694       enum LTO_tags tag = streamer_read_record_start (&ib_main);
1695       if (tag == LTO_tree_scc)
1696         {
1697           unsigned len_;
1698           unsigned scc_entry_len;
1699           hashval_t scc_hash = lto_input_scc (&ib_main, data_in, &len_,
1700                                               &scc_entry_len);
1701           unsigned len = data_in->reader_cache->nodes.length () - from;
1702           gcc_assert (len == len_);
1703
1704           total_scc_size += len;
1705           num_sccs_read++;
1706
1707           /* We have the special case of size-1 SCCs that are pre-merged
1708              by means of identifier and string sharing for example.
1709              ???  Maybe we should avoid streaming those as SCCs.  */
1710           tree first = streamer_tree_cache_get_tree (data_in->reader_cache,
1711                                                      from);
1712           if (len == 1
1713               && (TREE_CODE (first) == IDENTIFIER_NODE
1714                   || TREE_CODE (first) == INTEGER_CST))
1715             continue;
1716
1717           /* Try to unify the SCC with already existing ones.  */
1718           if (!flag_ltrans
1719               && unify_scc (data_in, from,
1720                             len, scc_entry_len, scc_hash))
1721             continue;
1722
1723           /* Tree merging failed, mark entries in location cache as
1724              permanent.  */
1725           data_in->location_cache.accept_location_cache ();
1726
1727           bool seen_type = false;
1728           for (unsigned i = 0; i < len; ++i)
1729             {
1730               tree t = streamer_tree_cache_get_tree (data_in->reader_cache,
1731                                                      from + i);
1732               /* Reconstruct the type variant and pointer-to/reference-to
1733                  chains.  */
1734               if (TYPE_P (t))
1735                 {
1736                   seen_type = true;
1737                   num_prevailing_types++;
1738                   lto_fixup_prevailing_type (t);
1739                 }
1740               /* Compute the canonical type of all types.
1741                  ???  Should be able to assert that !TYPE_CANONICAL.  */
1742               if (TYPE_P (t) && !TYPE_CANONICAL (t))
1743                 {
1744                   gimple_register_canonical_type (t);
1745                   if (odr_type_p (t))
1746                     register_odr_type (t);
1747                 }
1748               /* Link shared INTEGER_CSTs into TYPE_CACHED_VALUEs of its
1749                  type which is also member of this SCC.  */
1750               if (TREE_CODE (t) == INTEGER_CST
1751                   && !TREE_OVERFLOW (t))
1752                 cache_integer_cst (t);
1753               if (!flag_ltrans)
1754                 {
1755                   /* Register variables and functions with the
1756                      symbol table.  */
1757                   if (TREE_CODE (t) == VAR_DECL)
1758                     lto_register_var_decl_in_symtab (data_in, t, from + i);
1759                   else if (TREE_CODE (t) == FUNCTION_DECL
1760                            && !DECL_BUILT_IN (t))
1761                     lto_register_function_decl_in_symtab (data_in, t, from + i);
1762                   /* Scan the tree for references to global functions or
1763                      variables and record those for later fixup.  */
1764                   if (mentions_vars_p (t))
1765                     vec_safe_push (tree_with_vars, t);
1766                 }
1767             }
1768
1769           /* Register DECLs with the debuginfo machinery.  */
1770           while (!dref_queue.is_empty ())
1771             {
1772               dref_entry e = dref_queue.pop ();
1773               debug_hooks->register_external_die (e.decl, e.sym, e.off);
1774             }
1775
1776           if (seen_type)
1777             num_type_scc_trees += len;
1778         }
1779       else
1780         {
1781           /* Pickle stray references.  */
1782           t = lto_input_tree_1 (&ib_main, data_in, tag, 0);
1783           gcc_assert (t && data_in->reader_cache->nodes.length () == from);
1784         }
1785     }
1786   data_in->location_cache.apply_location_cache ();
1787
1788   /* Read in lto_in_decl_state objects.  */
1789   data_ptr = (const uint32_t *) ((const char*) data + decl_offset); 
1790   data_end =
1791      (const uint32_t *) ((const char*) data_ptr + header->decl_state_size);
1792   num_decl_states = *data_ptr++;
1793   
1794   gcc_assert (num_decl_states > 0);
1795   decl_data->global_decl_state = lto_new_in_decl_state ();
1796   data_ptr = lto_read_in_decl_state (data_in, data_ptr,
1797                                      decl_data->global_decl_state);
1798
1799   /* Read in per-function decl states and enter them in hash table.  */
1800   decl_data->function_decl_states =
1801     hash_table<decl_state_hasher>::create_ggc (37);
1802
1803   for (i = 1; i < num_decl_states; i++)
1804     {
1805       struct lto_in_decl_state *state = lto_new_in_decl_state ();
1806
1807       data_ptr = lto_read_in_decl_state (data_in, data_ptr, state);
1808       lto_in_decl_state **slot
1809         = decl_data->function_decl_states->find_slot (state, INSERT);
1810       gcc_assert (*slot == NULL);
1811       *slot = state;
1812     }
1813
1814   if (data_ptr != data_end)
1815     internal_error ("bytecode stream: garbage at the end of symbols section");
1816
1817   /* Set the current decl state to be the global state. */
1818   decl_data->current_decl_state = decl_data->global_decl_state;
1819
1820   lto_data_in_delete (data_in);
1821 }
1822
1823 /* Custom version of strtoll, which is not portable.  */
1824
1825 static int64_t
1826 lto_parse_hex (const char *p)
1827 {
1828   int64_t ret = 0;
1829
1830   for (; *p != '\0'; ++p)
1831     {
1832       char c = *p;
1833       unsigned char part;
1834       ret <<= 4;
1835       if (c >= '0' && c <= '9')
1836         part = c - '0';
1837       else if (c >= 'a' && c <= 'f')
1838         part = c - 'a' + 10;
1839       else if (c >= 'A' && c <= 'F')
1840         part = c - 'A' + 10;
1841       else
1842         internal_error ("could not parse hex number");
1843       ret |= part;
1844     }
1845
1846   return ret;
1847 }
1848
1849 /* Read resolution for file named FILE_NAME. The resolution is read from
1850    RESOLUTION. */
1851
1852 static void
1853 lto_resolution_read (splay_tree file_ids, FILE *resolution, lto_file *file)
1854 {
1855   /* We require that objects in the resolution file are in the same
1856      order as the lto1 command line. */
1857   unsigned int name_len;
1858   char *obj_name;
1859   unsigned int num_symbols;
1860   unsigned int i;
1861   struct lto_file_decl_data *file_data;
1862   splay_tree_node nd = NULL; 
1863
1864   if (!resolution)
1865     return;
1866
1867   name_len = strlen (file->filename);
1868   obj_name = XNEWVEC (char, name_len + 1);
1869   fscanf (resolution, " ");   /* Read white space. */
1870
1871   fread (obj_name, sizeof (char), name_len, resolution);
1872   obj_name[name_len] = '\0';
1873   if (filename_cmp (obj_name, file->filename) != 0)
1874     internal_error ("unexpected file name %s in linker resolution file. "
1875                     "Expected %s", obj_name, file->filename);
1876   if (file->offset != 0)
1877     {
1878       int t;
1879       char offset_p[17];
1880       int64_t offset;
1881       t = fscanf (resolution, "@0x%16s", offset_p);
1882       if (t != 1)
1883         internal_error ("could not parse file offset");
1884       offset = lto_parse_hex (offset_p);
1885       if (offset != file->offset)
1886         internal_error ("unexpected offset");
1887     }
1888
1889   free (obj_name);
1890
1891   fscanf (resolution, "%u", &num_symbols);
1892
1893   for (i = 0; i < num_symbols; i++)
1894     {
1895       int t;
1896       unsigned index;
1897       unsigned HOST_WIDE_INT id;
1898       char r_str[27];
1899       enum ld_plugin_symbol_resolution r = (enum ld_plugin_symbol_resolution) 0;
1900       unsigned int j;
1901       unsigned int lto_resolution_str_len =
1902         sizeof (lto_resolution_str) / sizeof (char *);
1903       res_pair rp;
1904
1905       t = fscanf (resolution, "%u " HOST_WIDE_INT_PRINT_HEX_PURE " %26s %*[^\n]\n", 
1906                   &index, &id, r_str);
1907       if (t != 3)
1908         internal_error ("invalid line in the resolution file");
1909
1910       for (j = 0; j < lto_resolution_str_len; j++)
1911         {
1912           if (strcmp (lto_resolution_str[j], r_str) == 0)
1913             {
1914               r = (enum ld_plugin_symbol_resolution) j;
1915               break;
1916             }
1917         }
1918       if (j == lto_resolution_str_len)
1919         internal_error ("invalid resolution in the resolution file");
1920
1921       if (!(nd && lto_splay_tree_id_equal_p (nd->key, id)))
1922         {
1923           nd = lto_splay_tree_lookup (file_ids, id);
1924           if (nd == NULL)
1925             internal_error ("resolution sub id %wx not in object file", id);
1926         }
1927
1928       file_data = (struct lto_file_decl_data *)nd->value;
1929       /* The indexes are very sparse. To save memory save them in a compact
1930          format that is only unpacked later when the subfile is processed. */
1931       rp.res = r;
1932       rp.index = index;
1933       file_data->respairs.safe_push (rp);
1934       if (file_data->max_index < index)
1935         file_data->max_index = index;
1936     }
1937 }
1938
1939 /* List of file_decl_datas */
1940 struct file_data_list
1941   {
1942     struct lto_file_decl_data *first, *last;
1943   };
1944
1945 /* Is the name for a id'ed LTO section? */
1946
1947 static int 
1948 lto_section_with_id (const char *name, unsigned HOST_WIDE_INT *id)
1949 {
1950   const char *s;
1951
1952   if (strncmp (name, section_name_prefix, strlen (section_name_prefix)))
1953     return 0;
1954   s = strrchr (name, '.');
1955   if (!s)
1956     return 0;
1957   /* If the section is not suffixed with an ID return.  */
1958   if ((size_t)(s - name) == strlen (section_name_prefix))
1959     return 0;
1960   return sscanf (s, "." HOST_WIDE_INT_PRINT_HEX_PURE, id) == 1;
1961 }
1962
1963 /* Create file_data of each sub file id */
1964
1965 static int 
1966 create_subid_section_table (struct lto_section_slot *ls, splay_tree file_ids,
1967                             struct file_data_list *list)
1968 {
1969   struct lto_section_slot s_slot, *new_slot;
1970   unsigned HOST_WIDE_INT id;
1971   splay_tree_node nd;
1972   void **hash_slot;
1973   char *new_name;
1974   struct lto_file_decl_data *file_data;
1975
1976   if (!lto_section_with_id (ls->name, &id))
1977     return 1;
1978   
1979   /* Find hash table of sub module id */
1980   nd = lto_splay_tree_lookup (file_ids, id);
1981   if (nd != NULL)
1982     {
1983       file_data = (struct lto_file_decl_data *)nd->value;
1984     }
1985   else
1986     {
1987       file_data = ggc_alloc<lto_file_decl_data> ();
1988       memset(file_data, 0, sizeof (struct lto_file_decl_data));
1989       file_data->id = id;
1990       file_data->section_hash_table = lto_obj_create_section_hash_table ();;
1991       lto_splay_tree_insert (file_ids, id, file_data);
1992
1993       /* Maintain list in linker order */
1994       if (!list->first)
1995         list->first = file_data;
1996       if (list->last)
1997         list->last->next = file_data;
1998       list->last = file_data;
1999     }
2000
2001   /* Copy section into sub module hash table */
2002   new_name = XDUPVEC (char, ls->name, strlen (ls->name) + 1);
2003   s_slot.name = new_name;
2004   hash_slot = htab_find_slot (file_data->section_hash_table, &s_slot, INSERT);
2005   gcc_assert (*hash_slot == NULL);
2006
2007   new_slot = XDUP (struct lto_section_slot, ls);
2008   new_slot->name = new_name;
2009   *hash_slot = new_slot;
2010   return 1;
2011 }
2012
2013 /* Read declarations and other initializations for a FILE_DATA. */
2014
2015 static void
2016 lto_file_finalize (struct lto_file_decl_data *file_data, lto_file *file)
2017 {
2018   const char *data;
2019   size_t len;
2020   vec<ld_plugin_symbol_resolution_t>
2021         resolutions = vNULL;
2022   int i;
2023   res_pair *rp;
2024
2025   /* Create vector for fast access of resolution. We do this lazily
2026      to save memory. */ 
2027   resolutions.safe_grow_cleared (file_data->max_index + 1);
2028   for (i = 0; file_data->respairs.iterate (i, &rp); i++)
2029     resolutions[rp->index] = rp->res;
2030   file_data->respairs.release ();
2031
2032   file_data->renaming_hash_table = lto_create_renaming_table ();
2033   file_data->file_name = file->filename;
2034 #ifdef ACCEL_COMPILER
2035   lto_input_mode_table (file_data);
2036 #else
2037   file_data->mode_table = lto_mode_identity_table;
2038 #endif
2039   data = lto_get_section_data (file_data, LTO_section_decls, NULL, &len);
2040   if (data == NULL)
2041     {
2042       internal_error ("cannot read LTO decls from %s", file_data->file_name);
2043       return;
2044     }
2045   /* Frees resolutions */
2046   lto_read_decls (file_data, data, resolutions);
2047   lto_free_section_data (file_data, LTO_section_decls, NULL, data, len);
2048 }
2049
2050 /* Finalize FILE_DATA in FILE and increase COUNT. */
2051
2052 static int 
2053 lto_create_files_from_ids (lto_file *file, struct lto_file_decl_data *file_data,
2054                            int *count)
2055 {
2056   lto_file_finalize (file_data, file);
2057   if (symtab->dump_file)
2058     fprintf (symtab->dump_file,
2059              "Creating file %s with sub id " HOST_WIDE_INT_PRINT_HEX "\n",
2060              file_data->file_name, file_data->id);
2061   (*count)++;
2062   return 0;
2063 }
2064
2065 /* Generate a TREE representation for all types and external decls
2066    entities in FILE.  
2067
2068    Read all of the globals out of the file.  Then read the cgraph
2069    and process the .o index into the cgraph nodes so that it can open
2070    the .o file to load the functions and ipa information.   */
2071
2072 static struct lto_file_decl_data *
2073 lto_file_read (lto_file *file, FILE *resolution_file, int *count)
2074 {
2075   struct lto_file_decl_data *file_data = NULL;
2076   splay_tree file_ids;
2077   htab_t section_hash_table;
2078   struct lto_section_slot *section;
2079   struct file_data_list file_list;
2080   struct lto_section_list section_list;
2081  
2082   memset (&section_list, 0, sizeof (struct lto_section_list)); 
2083   section_hash_table = lto_obj_build_section_table (file, &section_list);
2084
2085   /* Find all sub modules in the object and put their sections into new hash
2086      tables in a splay tree. */
2087   file_ids = lto_splay_tree_new ();
2088   memset (&file_list, 0, sizeof (struct file_data_list));
2089   for (section = section_list.first; section != NULL; section = section->next)
2090     create_subid_section_table (section, file_ids, &file_list);
2091
2092   /* Add resolutions to file ids */
2093   lto_resolution_read (file_ids, resolution_file, file);
2094
2095   /* Finalize each lto file for each submodule in the merged object */
2096   for (file_data = file_list.first; file_data != NULL; file_data = file_data->next)
2097     lto_create_files_from_ids (file, file_data, count);
2098  
2099   splay_tree_delete (file_ids);
2100   htab_delete (section_hash_table);
2101
2102   return file_list.first;
2103 }
2104
2105 #if HAVE_MMAP_FILE && HAVE_SYSCONF && defined _SC_PAGE_SIZE
2106 #define LTO_MMAP_IO 1
2107 #endif
2108
2109 #if LTO_MMAP_IO
2110 /* Page size of machine is used for mmap and munmap calls.  */
2111 static size_t page_mask;
2112 #endif
2113
2114 /* Get the section data of length LEN from FILENAME starting at
2115    OFFSET.  The data segment must be freed by the caller when the
2116    caller is finished.  Returns NULL if all was not well.  */
2117
2118 static char *
2119 lto_read_section_data (struct lto_file_decl_data *file_data,
2120                        intptr_t offset, size_t len)
2121 {
2122   char *result;
2123   static int fd = -1;
2124   static char *fd_name;
2125 #if LTO_MMAP_IO
2126   intptr_t computed_len;
2127   intptr_t computed_offset;
2128   intptr_t diff;
2129 #endif
2130
2131   /* Keep a single-entry file-descriptor cache.  The last file we
2132      touched will get closed at exit.
2133      ???  Eventually we want to add a more sophisticated larger cache
2134      or rather fix function body streaming to not stream them in
2135      practically random order.  */
2136   if (fd != -1
2137       && filename_cmp (fd_name, file_data->file_name) != 0)
2138     {
2139       free (fd_name);
2140       close (fd);
2141       fd = -1;
2142     }
2143   if (fd == -1)
2144     {
2145       fd = open (file_data->file_name, O_RDONLY|O_BINARY);
2146       if (fd == -1)
2147         {
2148           fatal_error (input_location, "Cannot open %s", file_data->file_name);
2149           return NULL;
2150         }
2151       fd_name = xstrdup (file_data->file_name);
2152     }
2153
2154 #if LTO_MMAP_IO
2155   if (!page_mask)
2156     {
2157       size_t page_size = sysconf (_SC_PAGE_SIZE);
2158       page_mask = ~(page_size - 1);
2159     }
2160
2161   computed_offset = offset & page_mask;
2162   diff = offset - computed_offset;
2163   computed_len = len + diff;
2164
2165   result = (char *) mmap (NULL, computed_len, PROT_READ, MAP_PRIVATE,
2166                           fd, computed_offset);
2167   if (result == MAP_FAILED)
2168     {
2169       fatal_error (input_location, "Cannot map %s", file_data->file_name);
2170       return NULL;
2171     }
2172
2173   return result + diff;
2174 #else
2175   result = (char *) xmalloc (len);
2176   if (lseek (fd, offset, SEEK_SET) != offset
2177       || read (fd, result, len) != (ssize_t) len)
2178     {
2179       free (result);
2180       fatal_error (input_location, "Cannot read %s", file_data->file_name);
2181       result = NULL;
2182     }
2183 #ifdef __MINGW32__
2184   /* Native windows doesn't supports delayed unlink on opened file. So
2185      we close file here again. This produces higher I/O load, but at least
2186      it prevents to have dangling file handles preventing unlink.  */
2187   free (fd_name);
2188   fd_name = NULL;
2189   close (fd);
2190   fd = -1;
2191 #endif
2192   return result;
2193 #endif
2194 }    
2195
2196
2197 /* Get the section data from FILE_DATA of SECTION_TYPE with NAME.
2198    NAME will be NULL unless the section type is for a function
2199    body.  */
2200
2201 static const char *
2202 get_section_data (struct lto_file_decl_data *file_data,
2203                       enum lto_section_type section_type,
2204                       const char *name,
2205                       size_t *len)
2206 {
2207   htab_t section_hash_table = file_data->section_hash_table;
2208   struct lto_section_slot *f_slot;
2209   struct lto_section_slot s_slot;
2210   const char *section_name = lto_get_section_name (section_type, name, file_data);
2211   char *data = NULL;
2212
2213   *len = 0;
2214   s_slot.name = section_name;
2215   f_slot = (struct lto_section_slot *) htab_find (section_hash_table, &s_slot);
2216   if (f_slot)
2217     {
2218       data = lto_read_section_data (file_data, f_slot->start, f_slot->len);
2219       *len = f_slot->len;
2220     }
2221
2222   free (CONST_CAST (char *, section_name));
2223   return data;
2224 }
2225
2226
2227 /* Free the section data from FILE_DATA of SECTION_TYPE with NAME that
2228    starts at OFFSET and has LEN bytes.  */
2229
2230 static void
2231 free_section_data (struct lto_file_decl_data *file_data ATTRIBUTE_UNUSED,
2232                    enum lto_section_type section_type ATTRIBUTE_UNUSED,
2233                    const char *name ATTRIBUTE_UNUSED,
2234                    const char *offset, size_t len ATTRIBUTE_UNUSED)
2235 {
2236 #if LTO_MMAP_IO
2237   intptr_t computed_len;
2238   intptr_t computed_offset;
2239   intptr_t diff;
2240 #endif
2241
2242 #if LTO_MMAP_IO
2243   computed_offset = ((intptr_t) offset) & page_mask;
2244   diff = (intptr_t) offset - computed_offset;
2245   computed_len = len + diff;
2246
2247   munmap ((caddr_t) computed_offset, computed_len);
2248 #else
2249   free (CONST_CAST(char *, offset));
2250 #endif
2251 }
2252
2253 static lto_file *current_lto_file;
2254
2255 /* Helper for qsort; compare partitions and return one with smaller size.
2256    We sort from greatest to smallest so parallel build doesn't stale on the
2257    longest compilation being executed too late.  */
2258
2259 static int
2260 cmp_partitions_size (const void *a, const void *b)
2261 {
2262   const struct ltrans_partition_def *pa
2263      = *(struct ltrans_partition_def *const *)a;
2264   const struct ltrans_partition_def *pb
2265      = *(struct ltrans_partition_def *const *)b;
2266   return pb->insns - pa->insns;
2267 }
2268
2269 /* Helper for qsort; compare partitions and return one with smaller order.  */
2270
2271 static int
2272 cmp_partitions_order (const void *a, const void *b)
2273 {
2274   const struct ltrans_partition_def *pa
2275      = *(struct ltrans_partition_def *const *)a;
2276   const struct ltrans_partition_def *pb
2277      = *(struct ltrans_partition_def *const *)b;
2278   int ordera = -1, orderb = -1;
2279
2280   if (lto_symtab_encoder_size (pa->encoder))
2281     ordera = lto_symtab_encoder_deref (pa->encoder, 0)->order;
2282   if (lto_symtab_encoder_size (pb->encoder))
2283     orderb = lto_symtab_encoder_deref (pb->encoder, 0)->order;
2284   return orderb - ordera;
2285 }
2286
2287 /* Actually stream out ENCODER into TEMP_FILENAME.  */
2288
2289 static void
2290 do_stream_out (char *temp_filename, lto_symtab_encoder_t encoder)
2291 {
2292   lto_file *file = lto_obj_file_open (temp_filename, true);
2293   if (!file)
2294     fatal_error (input_location, "lto_obj_file_open() failed");
2295   lto_set_current_out_file (file);
2296
2297   ipa_write_optimization_summaries (encoder);
2298
2299   free (CONST_CAST (char *, file->filename));
2300
2301   lto_set_current_out_file (NULL);
2302   lto_obj_file_close (file);
2303   free (file);
2304 }
2305
2306 /* Wait for forked process and signal errors.  */
2307 #ifdef HAVE_WORKING_FORK
2308 static void
2309 wait_for_child ()
2310 {
2311   int status;
2312   do
2313     {
2314 #ifndef WCONTINUED
2315 #define WCONTINUED 0
2316 #endif
2317       int w = waitpid (0, &status, WUNTRACED | WCONTINUED);
2318       if (w == -1)
2319         fatal_error (input_location, "waitpid failed");
2320
2321       if (WIFEXITED (status) && WEXITSTATUS (status))
2322         fatal_error (input_location, "streaming subprocess failed");
2323       else if (WIFSIGNALED (status))
2324         fatal_error (input_location,
2325                      "streaming subprocess was killed by signal");
2326     }
2327   while (!WIFEXITED (status) && !WIFSIGNALED (status));
2328 }
2329 #endif
2330
2331 /* Stream out ENCODER into TEMP_FILENAME
2332    Fork if that seems to help.  */
2333
2334 static void
2335 stream_out (char *temp_filename, lto_symtab_encoder_t encoder,
2336             bool ARG_UNUSED (last))
2337 {
2338 #ifdef HAVE_WORKING_FORK
2339   static int nruns;
2340
2341   if (lto_parallelism <= 1)
2342     {
2343       do_stream_out (temp_filename, encoder);
2344       return;
2345     }
2346
2347   /* Do not run more than LTO_PARALLELISM streamings
2348      FIXME: we ignore limits on jobserver.  */
2349   if (lto_parallelism > 0 && nruns >= lto_parallelism)
2350     {
2351       wait_for_child ();
2352       nruns --;
2353     }
2354   /* If this is not the last parallel partition, execute new
2355      streaming process.  */
2356   if (!last)
2357     {
2358       pid_t cpid = fork ();
2359
2360       if (!cpid)
2361         {
2362           setproctitle ("lto1-wpa-streaming");
2363           do_stream_out (temp_filename, encoder);
2364           exit (0);
2365         }
2366       /* Fork failed; lets do the job ourseleves.  */
2367       else if (cpid == -1)
2368         do_stream_out (temp_filename, encoder);
2369       else
2370         nruns++;
2371     }
2372   /* Last partition; stream it and wait for all children to die.  */
2373   else
2374     {
2375       int i;
2376       do_stream_out (temp_filename, encoder);
2377       for (i = 0; i < nruns; i++)
2378         wait_for_child ();
2379     }
2380   asm_nodes_output = true;
2381 #else
2382   do_stream_out (temp_filename, encoder);
2383 #endif
2384 }
2385
2386 /* Write all output files in WPA mode and the file with the list of
2387    LTRANS units.  */
2388
2389 static void
2390 lto_wpa_write_files (void)
2391 {
2392   unsigned i, n_sets;
2393   ltrans_partition part;
2394   FILE *ltrans_output_list_stream;
2395   char *temp_filename;
2396   vec <char *>temp_filenames = vNULL;
2397   size_t blen;
2398
2399   /* Open the LTRANS output list.  */
2400   if (!ltrans_output_list)
2401     fatal_error (input_location, "no LTRANS output list filename provided");
2402
2403   timevar_push (TV_WHOPR_WPA);
2404
2405   FOR_EACH_VEC_ELT (ltrans_partitions, i, part)
2406     lto_stats.num_output_symtab_nodes += lto_symtab_encoder_size (part->encoder);
2407
2408   timevar_pop (TV_WHOPR_WPA);
2409
2410   timevar_push (TV_WHOPR_WPA_IO);
2411
2412   /* Generate a prefix for the LTRANS unit files.  */
2413   blen = strlen (ltrans_output_list);
2414   temp_filename = (char *) xmalloc (blen + sizeof ("2147483648.o"));
2415   strcpy (temp_filename, ltrans_output_list);
2416   if (blen > sizeof (".out")
2417       && strcmp (temp_filename + blen - sizeof (".out") + 1,
2418                  ".out") == 0)
2419     temp_filename[blen - sizeof (".out") + 1] = '\0';
2420   blen = strlen (temp_filename);
2421
2422   n_sets = ltrans_partitions.length ();
2423
2424   /* Sort partitions by size so small ones are compiled last.
2425      FIXME: Even when not reordering we may want to output one list for parallel make
2426      and other for final link command.  */
2427
2428   if (!flag_profile_reorder_functions || !flag_profile_use)
2429     ltrans_partitions.qsort (flag_toplevel_reorder
2430                            ? cmp_partitions_size
2431                            : cmp_partitions_order);
2432
2433   for (i = 0; i < n_sets; i++)
2434     {
2435       ltrans_partition part = ltrans_partitions[i];
2436
2437       /* Write all the nodes in SET.  */
2438       sprintf (temp_filename + blen, "%u.o", i);
2439
2440       if (!quiet_flag)
2441         fprintf (stderr, " %s (%s %i insns)", temp_filename, part->name, part->insns);
2442       if (symtab->dump_file)
2443         {
2444           lto_symtab_encoder_iterator lsei;
2445           
2446           fprintf (symtab->dump_file, "Writing partition %s to file %s, %i insns\n",
2447                    part->name, temp_filename, part->insns);
2448           fprintf (symtab->dump_file, "  Symbols in partition: ");
2449           for (lsei = lsei_start_in_partition (part->encoder); !lsei_end_p (lsei);
2450                lsei_next_in_partition (&lsei))
2451             {
2452               symtab_node *node = lsei_node (lsei);
2453               fprintf (symtab->dump_file, "%s ", node->asm_name ());
2454             }
2455           fprintf (symtab->dump_file, "\n  Symbols in boundary: ");
2456           for (lsei = lsei_start (part->encoder); !lsei_end_p (lsei);
2457                lsei_next (&lsei))
2458             {
2459               symtab_node *node = lsei_node (lsei);
2460               if (!lto_symtab_encoder_in_partition_p (part->encoder, node))
2461                 {
2462                   fprintf (symtab->dump_file, "%s ", node->asm_name ());
2463                   cgraph_node *cnode = dyn_cast <cgraph_node *> (node);
2464                   if (cnode
2465                       && lto_symtab_encoder_encode_body_p (part->encoder, cnode))
2466                     fprintf (symtab->dump_file, "(body included)");
2467                   else
2468                     {
2469                       varpool_node *vnode = dyn_cast <varpool_node *> (node);
2470                       if (vnode
2471                           && lto_symtab_encoder_encode_initializer_p (part->encoder, vnode))
2472                         fprintf (symtab->dump_file, "(initializer included)");
2473                     }
2474                 }
2475             }
2476           fprintf (symtab->dump_file, "\n");
2477         }
2478       gcc_checking_assert (lto_symtab_encoder_size (part->encoder) || !i);
2479
2480       stream_out (temp_filename, part->encoder, i == n_sets - 1);
2481
2482       part->encoder = NULL;
2483
2484       temp_filenames.safe_push (xstrdup (temp_filename));
2485     }
2486   ltrans_output_list_stream = fopen (ltrans_output_list, "w");
2487   if (ltrans_output_list_stream == NULL)
2488     fatal_error (input_location,
2489                  "opening LTRANS output list %s: %m", ltrans_output_list);
2490   for (i = 0; i < n_sets; i++)
2491     {
2492       unsigned int len = strlen (temp_filenames[i]);
2493       if (fwrite (temp_filenames[i], 1, len, ltrans_output_list_stream) < len
2494           || fwrite ("\n", 1, 1, ltrans_output_list_stream) < 1)
2495         fatal_error (input_location, "writing to LTRANS output list %s: %m",
2496                      ltrans_output_list);
2497      free (temp_filenames[i]);
2498     }
2499   temp_filenames.release();
2500
2501   lto_stats.num_output_files += n_sets;
2502
2503   /* Close the LTRANS output list.  */
2504   if (fclose (ltrans_output_list_stream))
2505     fatal_error (input_location,
2506                  "closing LTRANS output list %s: %m", ltrans_output_list);
2507
2508   free_ltrans_partitions();
2509   free (temp_filename);
2510
2511   timevar_pop (TV_WHOPR_WPA_IO);
2512 }
2513
2514
2515 /* If TT is a variable or function decl replace it with its
2516    prevailing variant.  */
2517 #define LTO_SET_PREVAIL(tt) \
2518   do {\
2519     if ((tt) && VAR_OR_FUNCTION_DECL_P (tt) \
2520         && (TREE_PUBLIC (tt) || DECL_EXTERNAL (tt))) \
2521       { \
2522         tt = lto_symtab_prevailing_decl (tt); \
2523         fixed = true; \
2524       } \
2525   } while (0)
2526
2527 /* Ensure that TT isn't a replacable var of function decl.  */
2528 #define LTO_NO_PREVAIL(tt) \
2529   gcc_checking_assert (!(tt) || !VAR_OR_FUNCTION_DECL_P (tt))
2530
2531 /* Given a tree T replace all fields referring to variables or functions
2532    with their prevailing variant.  */
2533 static void
2534 lto_fixup_prevailing_decls (tree t)
2535 {
2536   enum tree_code code = TREE_CODE (t);
2537   bool fixed = false;
2538
2539   gcc_checking_assert (code != TREE_BINFO);
2540   LTO_NO_PREVAIL (TREE_TYPE (t));
2541   if (CODE_CONTAINS_STRUCT (code, TS_COMMON)
2542       /* lto_symtab_prevail_decl use TREE_CHAIN to link to the prevailing decl.
2543          in the case T is a prevailed declaration we would ICE here. */
2544       && !VAR_OR_FUNCTION_DECL_P (t))
2545     LTO_NO_PREVAIL (TREE_CHAIN (t));
2546   if (DECL_P (t))
2547     {
2548       LTO_NO_PREVAIL (DECL_NAME (t));
2549       LTO_SET_PREVAIL (DECL_CONTEXT (t));
2550       if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
2551         {
2552           LTO_SET_PREVAIL (DECL_SIZE (t));
2553           LTO_SET_PREVAIL (DECL_SIZE_UNIT (t));
2554           LTO_SET_PREVAIL (DECL_INITIAL (t));
2555           LTO_NO_PREVAIL (DECL_ATTRIBUTES (t));
2556           LTO_SET_PREVAIL (DECL_ABSTRACT_ORIGIN (t));
2557         }
2558       if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
2559         {
2560           LTO_NO_PREVAIL (t->decl_with_vis.assembler_name);
2561         }
2562       if (CODE_CONTAINS_STRUCT (code, TS_DECL_NON_COMMON))
2563         {
2564           LTO_NO_PREVAIL (DECL_RESULT_FLD (t));
2565         }
2566       if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
2567         {
2568           LTO_NO_PREVAIL (DECL_ARGUMENTS (t));
2569           LTO_SET_PREVAIL (DECL_FUNCTION_PERSONALITY (t));
2570           LTO_NO_PREVAIL (DECL_VINDEX (t));
2571         }
2572       if (CODE_CONTAINS_STRUCT (code, TS_FIELD_DECL))
2573         {
2574           LTO_SET_PREVAIL (DECL_FIELD_OFFSET (t));
2575           LTO_NO_PREVAIL (DECL_BIT_FIELD_TYPE (t));
2576           LTO_NO_PREVAIL (DECL_QUALIFIER (t));
2577           LTO_NO_PREVAIL (DECL_FIELD_BIT_OFFSET (t));
2578           LTO_NO_PREVAIL (DECL_FCONTEXT (t));
2579         }
2580     }
2581   else if (TYPE_P (t))
2582     {
2583       LTO_NO_PREVAIL (TYPE_CACHED_VALUES (t));
2584       LTO_SET_PREVAIL (TYPE_SIZE (t));
2585       LTO_SET_PREVAIL (TYPE_SIZE_UNIT (t));
2586       LTO_NO_PREVAIL (TYPE_ATTRIBUTES (t));
2587       LTO_NO_PREVAIL (TYPE_NAME (t));
2588
2589       LTO_SET_PREVAIL (TYPE_MIN_VALUE_RAW (t));
2590       LTO_SET_PREVAIL (TYPE_MAX_VALUE_RAW (t));
2591       LTO_NO_PREVAIL (TYPE_LANG_SLOT_1 (t));
2592
2593       LTO_SET_PREVAIL (TYPE_CONTEXT (t));
2594
2595       LTO_NO_PREVAIL (TYPE_CANONICAL (t));
2596       LTO_NO_PREVAIL (TYPE_MAIN_VARIANT (t));
2597       LTO_NO_PREVAIL (TYPE_NEXT_VARIANT (t));
2598     }
2599   else if (EXPR_P (t))
2600     {
2601       int i;
2602       for (i = TREE_OPERAND_LENGTH (t) - 1; i >= 0; --i)
2603         LTO_SET_PREVAIL (TREE_OPERAND (t, i));
2604     }
2605   else if (TREE_CODE (t) == CONSTRUCTOR)
2606     {
2607       unsigned i;
2608       tree val;
2609       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
2610         LTO_SET_PREVAIL (val);
2611     }
2612   else
2613     {
2614       switch (code)
2615         {
2616         case TREE_LIST:
2617           LTO_SET_PREVAIL (TREE_VALUE (t));
2618           LTO_SET_PREVAIL (TREE_PURPOSE (t));
2619           LTO_NO_PREVAIL (TREE_PURPOSE (t));
2620           break;
2621         default:
2622           gcc_unreachable ();
2623         }
2624     }
2625   /* If we fixed nothing, then we missed something seen by
2626      mentions_vars_p.  */
2627   gcc_checking_assert (fixed);
2628 }
2629 #undef LTO_SET_PREVAIL
2630 #undef LTO_NO_PREVAIL
2631
2632 /* Helper function of lto_fixup_decls. Walks the var and fn streams in STATE,
2633    replaces var and function decls with the corresponding prevailing def.  */
2634
2635 static void
2636 lto_fixup_state (struct lto_in_decl_state *state)
2637 {
2638   unsigned i, si;
2639
2640   /* Although we only want to replace FUNCTION_DECLs and VAR_DECLs,
2641      we still need to walk from all DECLs to find the reachable
2642      FUNCTION_DECLs and VAR_DECLs.  */
2643   for (si = 0; si < LTO_N_DECL_STREAMS; si++)
2644     {
2645       vec<tree, va_gc> *trees = state->streams[si];
2646       for (i = 0; i < vec_safe_length (trees); i++)
2647         {
2648           tree t = (*trees)[i];
2649           if (flag_checking && TYPE_P (t))
2650             verify_type (t);
2651           if (VAR_OR_FUNCTION_DECL_P (t)
2652               && (TREE_PUBLIC (t) || DECL_EXTERNAL (t)))
2653             (*trees)[i] = lto_symtab_prevailing_decl (t);
2654         }
2655     }
2656 }
2657
2658 /* Fix the decls from all FILES. Replaces each decl with the corresponding
2659    prevailing one.  */
2660
2661 static void
2662 lto_fixup_decls (struct lto_file_decl_data **files)
2663 {
2664   unsigned int i;
2665   tree t;
2666
2667   if (tree_with_vars)
2668     FOR_EACH_VEC_ELT ((*tree_with_vars), i, t)
2669       lto_fixup_prevailing_decls (t);
2670
2671   for (i = 0; files[i]; i++)
2672     {
2673       struct lto_file_decl_data *file = files[i];
2674       struct lto_in_decl_state *state = file->global_decl_state;
2675       lto_fixup_state (state);
2676
2677       hash_table<decl_state_hasher>::iterator iter;
2678       lto_in_decl_state *elt;
2679       FOR_EACH_HASH_TABLE_ELEMENT (*file->function_decl_states, elt,
2680                                    lto_in_decl_state *, iter)
2681         lto_fixup_state (elt);
2682     }
2683 }
2684
2685 static GTY((length ("lto_stats.num_input_files + 1"))) struct lto_file_decl_data **all_file_decl_data;
2686
2687 /* Turn file datas for sub files into a single array, so that they look
2688    like separate files for further passes. */
2689
2690 static void
2691 lto_flatten_files (struct lto_file_decl_data **orig, int count, int last_file_ix)
2692 {
2693   struct lto_file_decl_data *n, *next;
2694   int i, k;
2695
2696   lto_stats.num_input_files = count;
2697   all_file_decl_data
2698     = ggc_cleared_vec_alloc<lto_file_decl_data_ptr> (count + 1);
2699   /* Set the hooks so that all of the ipa passes can read in their data.  */
2700   lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data);
2701   for (i = 0, k = 0; i < last_file_ix; i++) 
2702     {
2703       for (n = orig[i]; n != NULL; n = next)
2704         {
2705           all_file_decl_data[k++] = n;
2706           next = n->next;
2707           n->next = NULL;
2708         }
2709     }
2710   all_file_decl_data[k] = NULL;
2711   gcc_assert (k == count);
2712 }
2713
2714 /* Input file data before flattening (i.e. splitting them to subfiles to support
2715    incremental linking.  */
2716 static int real_file_count;
2717 static GTY((length ("real_file_count + 1"))) struct lto_file_decl_data **real_file_decl_data;
2718
2719 static void print_lto_report_1 (void);
2720
2721 /* Read all the symbols from the input files FNAMES.  NFILES is the
2722    number of files requested in the command line.  Instantiate a
2723    global call graph by aggregating all the sub-graphs found in each
2724    file.  */
2725
2726 static void
2727 read_cgraph_and_symbols (unsigned nfiles, const char **fnames)
2728 {
2729   unsigned int i, last_file_ix;
2730   FILE *resolution;
2731   int count = 0;
2732   struct lto_file_decl_data **decl_data;
2733   symtab_node *snode;
2734
2735   symtab->initialize ();
2736
2737   timevar_push (TV_IPA_LTO_DECL_IN);
2738
2739 #ifdef ACCEL_COMPILER
2740   section_name_prefix = OFFLOAD_SECTION_NAME_PREFIX;
2741   lto_stream_offload_p = true;
2742 #endif
2743
2744   real_file_decl_data
2745     = decl_data = ggc_cleared_vec_alloc<lto_file_decl_data_ptr> (nfiles + 1);
2746   real_file_count = nfiles;
2747
2748   /* Read the resolution file.  */
2749   resolution = NULL;
2750   if (resolution_file_name)
2751     {
2752       int t;
2753       unsigned num_objects;
2754
2755       resolution = fopen (resolution_file_name, "r");
2756       if (resolution == NULL)
2757         fatal_error (input_location,
2758                      "could not open symbol resolution file: %m");
2759
2760       t = fscanf (resolution, "%u", &num_objects);
2761       gcc_assert (t == 1);
2762
2763       /* True, since the plugin splits the archives.  */
2764       gcc_assert (num_objects == nfiles);
2765     }
2766   symtab->state = LTO_STREAMING;
2767
2768   canonical_type_hash_cache = new hash_map<const_tree, hashval_t> (251);
2769   gimple_canonical_types = htab_create (16381, gimple_canonical_type_hash,
2770                                         gimple_canonical_type_eq, NULL);
2771   gcc_obstack_init (&tree_scc_hash_obstack);
2772   tree_scc_hash = new hash_table<tree_scc_hasher> (4096);
2773
2774   /* Register the common node types with the canonical type machinery so
2775      we properly share alias-sets across languages and TUs.  Do not
2776      expose the common nodes as type merge target - those that should be
2777      are already exposed so by pre-loading the LTO streamer caches.
2778      Do two passes - first clear TYPE_CANONICAL and then re-compute it.  */
2779   for (i = 0; i < itk_none; ++i)
2780     lto_register_canonical_types (integer_types[i], true);
2781   for (i = 0; i < stk_type_kind_last; ++i)
2782     lto_register_canonical_types (sizetype_tab[i], true);
2783   for (i = 0; i < TI_MAX; ++i)
2784     lto_register_canonical_types (global_trees[i], true);
2785   for (i = 0; i < itk_none; ++i)
2786     lto_register_canonical_types (integer_types[i], false);
2787   for (i = 0; i < stk_type_kind_last; ++i)
2788     lto_register_canonical_types (sizetype_tab[i], false);
2789   for (i = 0; i < TI_MAX; ++i)
2790     lto_register_canonical_types (global_trees[i], false);
2791
2792   if (!quiet_flag)
2793     fprintf (stderr, "Reading object files:");
2794
2795   /* Read all of the object files specified on the command line.  */
2796   for (i = 0, last_file_ix = 0; i < nfiles; ++i)
2797     {
2798       struct lto_file_decl_data *file_data = NULL;
2799       if (!quiet_flag)
2800         {
2801           fprintf (stderr, " %s", fnames[i]);
2802           fflush (stderr);
2803         }
2804
2805       current_lto_file = lto_obj_file_open (fnames[i], false);
2806       if (!current_lto_file)
2807         break;
2808
2809       file_data = lto_file_read (current_lto_file, resolution, &count);
2810       if (!file_data)
2811         {
2812           lto_obj_file_close (current_lto_file);
2813           free (current_lto_file);
2814           current_lto_file = NULL;
2815           break;
2816         }
2817
2818       decl_data[last_file_ix++] = file_data;
2819
2820       lto_obj_file_close (current_lto_file);
2821       free (current_lto_file);
2822       current_lto_file = NULL;
2823     }
2824
2825   lto_flatten_files (decl_data, count, last_file_ix);
2826   lto_stats.num_input_files = count;
2827   ggc_free(decl_data);
2828   real_file_decl_data = NULL;
2829
2830   if (resolution_file_name)
2831     fclose (resolution);
2832
2833   /* Show the LTO report before launching LTRANS.  */
2834   if (flag_lto_report || (flag_wpa && flag_lto_report_wpa))
2835     print_lto_report_1 ();
2836
2837   /* Free gimple type merging datastructures.  */
2838   delete tree_scc_hash;
2839   tree_scc_hash = NULL;
2840   obstack_free (&tree_scc_hash_obstack, NULL);
2841   htab_delete (gimple_canonical_types);
2842   gimple_canonical_types = NULL;
2843   delete canonical_type_hash_cache;
2844   canonical_type_hash_cache = NULL;
2845
2846   /* At this stage we know that majority of GGC memory is reachable.  
2847      Growing the limits prevents unnecesary invocation of GGC.  */
2848   ggc_grow ();
2849   ggc_collect ();
2850
2851   /* Set the hooks so that all of the ipa passes can read in their data.  */
2852   lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data);
2853
2854   timevar_pop (TV_IPA_LTO_DECL_IN);
2855
2856   if (!quiet_flag)
2857     fprintf (stderr, "\nReading the callgraph\n");
2858
2859   timevar_push (TV_IPA_LTO_CGRAPH_IO);
2860   /* Read the symtab.  */
2861   input_symtab ();
2862
2863   input_offload_tables (!flag_ltrans);
2864
2865   /* Store resolutions into the symbol table.  */
2866
2867   ld_plugin_symbol_resolution_t *res;
2868   FOR_EACH_SYMBOL (snode)
2869     if (snode->real_symbol_p ()
2870         && snode->lto_file_data
2871         && snode->lto_file_data->resolution_map
2872         && (res = snode->lto_file_data->resolution_map->get (snode->decl)))
2873       snode->resolution = *res;
2874   for (i = 0; all_file_decl_data[i]; i++)
2875     if (all_file_decl_data[i]->resolution_map)
2876       {
2877         delete all_file_decl_data[i]->resolution_map;
2878         all_file_decl_data[i]->resolution_map = NULL;
2879       }
2880   
2881   timevar_pop (TV_IPA_LTO_CGRAPH_IO);
2882
2883   if (!quiet_flag)
2884     fprintf (stderr, "Merging declarations\n");
2885
2886   timevar_push (TV_IPA_LTO_DECL_MERGE);
2887   /* Merge global decls.  In ltrans mode we read merged cgraph, we do not
2888      need to care about resolving symbols again, we only need to replace
2889      duplicated declarations read from the callgraph and from function
2890      sections.  */
2891   if (!flag_ltrans)
2892     {
2893       lto_symtab_merge_decls ();
2894
2895       /* If there were errors during symbol merging bail out, we have no
2896          good way to recover here.  */
2897       if (seen_error ())
2898         fatal_error (input_location,
2899                      "errors during merging of translation units");
2900
2901       /* Fixup all decls.  */
2902       lto_fixup_decls (all_file_decl_data);
2903     }
2904   if (tree_with_vars)
2905     ggc_free (tree_with_vars);
2906   tree_with_vars = NULL;
2907   ggc_collect ();
2908
2909   timevar_pop (TV_IPA_LTO_DECL_MERGE);
2910   /* Each pass will set the appropriate timer.  */
2911
2912   if (!quiet_flag)
2913     fprintf (stderr, "Reading summaries\n");
2914
2915   /* Read the IPA summary data.  */
2916   if (flag_ltrans)
2917     ipa_read_optimization_summaries ();
2918   else
2919     ipa_read_summaries ();
2920
2921   for (i = 0; all_file_decl_data[i]; i++)
2922     {
2923       gcc_assert (all_file_decl_data[i]->symtab_node_encoder);
2924       lto_symtab_encoder_delete (all_file_decl_data[i]->symtab_node_encoder);
2925       all_file_decl_data[i]->symtab_node_encoder = NULL;
2926       lto_free_function_in_decl_state (all_file_decl_data[i]->global_decl_state);
2927       all_file_decl_data[i]->global_decl_state = NULL;
2928       all_file_decl_data[i]->current_decl_state = NULL; 
2929     }
2930
2931   /* Finally merge the cgraph according to the decl merging decisions.  */
2932   timevar_push (TV_IPA_LTO_CGRAPH_MERGE);
2933   if (symtab->dump_file)
2934     {
2935       fprintf (symtab->dump_file, "Before merging:\n");
2936       symtab->dump (symtab->dump_file);
2937     }
2938   if (!flag_ltrans)
2939     {
2940       lto_symtab_merge_symbols ();
2941       /* Removal of unreachable symbols is needed to make verify_symtab to pass;
2942          we are still having duplicated comdat groups containing local statics.
2943          We could also just remove them while merging.  */
2944       symtab->remove_unreachable_nodes (dump_file);
2945     }
2946   ggc_collect ();
2947   symtab->state = IPA_SSA;
2948   /* FIXME: Technically all node removals happening here are useless, because
2949      WPA should not stream them.  */
2950   if (flag_ltrans)
2951     symtab->remove_unreachable_nodes (dump_file);
2952
2953   timevar_pop (TV_IPA_LTO_CGRAPH_MERGE);
2954
2955   /* Indicate that the cgraph is built and ready.  */
2956   symtab->function_flags_ready = true;
2957
2958   ggc_free (all_file_decl_data);
2959   all_file_decl_data = NULL;
2960 }
2961
2962
2963 /* Materialize all the bodies for all the nodes in the callgraph.  */
2964
2965 static void
2966 materialize_cgraph (void)
2967 {
2968   struct cgraph_node *node; 
2969   timevar_id_t lto_timer;
2970
2971   if (!quiet_flag)
2972     fprintf (stderr,
2973              flag_wpa ? "Materializing decls:" : "Reading function bodies:");
2974
2975
2976   FOR_EACH_FUNCTION (node)
2977     {
2978       if (node->lto_file_data)
2979         {
2980           lto_materialize_function (node);
2981           lto_stats.num_input_cgraph_nodes++;
2982         }
2983     }
2984
2985
2986   /* Start the appropriate timer depending on the mode that we are
2987      operating in.  */
2988   lto_timer = (flag_wpa) ? TV_WHOPR_WPA
2989               : (flag_ltrans) ? TV_WHOPR_LTRANS
2990               : TV_LTO;
2991   timevar_push (lto_timer);
2992
2993   current_function_decl = NULL;
2994   set_cfun (NULL);
2995
2996   if (!quiet_flag)
2997     fprintf (stderr, "\n");
2998
2999   timevar_pop (lto_timer);
3000 }
3001
3002
3003 /* Show various memory usage statistics related to LTO.  */
3004 static void
3005 print_lto_report_1 (void)
3006 {
3007   const char *pfx = (flag_lto) ? "LTO" : (flag_wpa) ? "WPA" : "LTRANS";
3008   fprintf (stderr, "%s statistics\n", pfx);
3009
3010   fprintf (stderr, "[%s] read %lu SCCs of average size %f\n",
3011            pfx, num_sccs_read, total_scc_size / (double)num_sccs_read);
3012   fprintf (stderr, "[%s] %lu tree bodies read in total\n", pfx, total_scc_size);
3013   if (flag_wpa && tree_scc_hash)
3014     {
3015       fprintf (stderr, "[%s] tree SCC table: size %ld, %ld elements, "
3016                "collision ratio: %f\n", pfx,
3017                (long) tree_scc_hash->size (),
3018                (long) tree_scc_hash->elements (),
3019                tree_scc_hash->collisions ());
3020       hash_table<tree_scc_hasher>::iterator hiter;
3021       tree_scc *scc, *max_scc = NULL;
3022       unsigned max_length = 0;
3023       FOR_EACH_HASH_TABLE_ELEMENT (*tree_scc_hash, scc, x, hiter)
3024         {
3025           unsigned length = 0;
3026           tree_scc *s = scc;
3027           for (; s; s = s->next)
3028             length++;
3029           if (length > max_length)
3030             {
3031               max_length = length;
3032               max_scc = scc;
3033             }
3034         }
3035       fprintf (stderr, "[%s] tree SCC max chain length %u (size %u)\n",
3036                pfx, max_length, max_scc->len);
3037       fprintf (stderr, "[%s] Compared %lu SCCs, %lu collisions (%f)\n", pfx,
3038                num_scc_compares, num_scc_compare_collisions,
3039                num_scc_compare_collisions / (double) num_scc_compares);
3040       fprintf (stderr, "[%s] Merged %lu SCCs\n", pfx, num_sccs_merged);
3041       fprintf (stderr, "[%s] Merged %lu tree bodies\n", pfx,
3042                total_scc_size_merged);
3043       fprintf (stderr, "[%s] Merged %lu types\n", pfx, num_merged_types);
3044       fprintf (stderr, "[%s] %lu types prevailed (%lu associated trees)\n",
3045                pfx, num_prevailing_types, num_type_scc_trees);
3046       fprintf (stderr, "[%s] GIMPLE canonical type table: size %ld, "
3047                "%ld elements, %ld searches, %ld collisions (ratio: %f)\n", pfx,
3048                (long) htab_size (gimple_canonical_types),
3049                (long) htab_elements (gimple_canonical_types),
3050                (long) gimple_canonical_types->searches,
3051                (long) gimple_canonical_types->collisions,
3052                htab_collisions (gimple_canonical_types));
3053       fprintf (stderr, "[%s] GIMPLE canonical type pointer-map: "
3054                "%lu elements, %ld searches\n", pfx,
3055                num_canonical_type_hash_entries,
3056                num_canonical_type_hash_queries);
3057     }
3058
3059   print_lto_report (pfx);
3060 }
3061
3062 /* Perform whole program analysis (WPA) on the callgraph and write out the
3063    optimization plan.  */
3064
3065 static void
3066 do_whole_program_analysis (void)
3067 {
3068   symtab_node *node;
3069
3070   lto_parallelism = 1;
3071
3072   /* TODO: jobserver communicatoin is not supported, yet.  */
3073   if (!strcmp (flag_wpa, "jobserver"))
3074     lto_parallelism = -1;
3075   else
3076     {
3077       lto_parallelism = atoi (flag_wpa);
3078       if (lto_parallelism <= 0)
3079         lto_parallelism = 0;
3080     }
3081
3082   timevar_start (TV_PHASE_OPT_GEN);
3083
3084   /* Note that since we are in WPA mode, materialize_cgraph will not
3085      actually read in all the function bodies.  It only materializes
3086      the decls and cgraph nodes so that analysis can be performed.  */
3087   materialize_cgraph ();
3088
3089   /* Reading in the cgraph uses different timers, start timing WPA now.  */
3090   timevar_push (TV_WHOPR_WPA);
3091
3092   if (pre_ipa_mem_report)
3093     {
3094       fprintf (stderr, "Memory consumption before IPA\n");
3095       dump_memory_report (false);
3096     }
3097
3098   symtab->function_flags_ready = true;
3099
3100   if (symtab->dump_file)
3101     symtab->dump (symtab->dump_file);
3102   bitmap_obstack_initialize (NULL);
3103   symtab->state = IPA_SSA;
3104
3105   execute_ipa_pass_list (g->get_passes ()->all_regular_ipa_passes);
3106
3107   /* When WPA analysis raises errors, do not bother to output anything.  */
3108   if (seen_error ())
3109     return;
3110
3111   if (symtab->dump_file)
3112     {
3113       fprintf (symtab->dump_file, "Optimized ");
3114       symtab->dump (symtab->dump_file);
3115     }
3116
3117   symtab_node::checking_verify_symtab_nodes ();
3118   bitmap_obstack_release (NULL);
3119
3120   /* We are about to launch the final LTRANS phase, stop the WPA timer.  */
3121   timevar_pop (TV_WHOPR_WPA);
3122
3123   timevar_push (TV_WHOPR_PARTITIONING);
3124   if (flag_lto_partition == LTO_PARTITION_1TO1)
3125     lto_1_to_1_map ();
3126   else if (flag_lto_partition == LTO_PARTITION_MAX)
3127     lto_max_map ();
3128   else if (flag_lto_partition == LTO_PARTITION_ONE)
3129     lto_balanced_map (1, INT_MAX);
3130   else if (flag_lto_partition == LTO_PARTITION_BALANCED)
3131     lto_balanced_map (PARAM_VALUE (PARAM_LTO_PARTITIONS),
3132                       PARAM_VALUE (MAX_PARTITION_SIZE));
3133   else
3134     gcc_unreachable ();
3135
3136   /* Inline summaries are needed for balanced partitioning.  Free them now so
3137      the memory can be used for streamer caches.  */
3138   ipa_free_fn_summary ();
3139
3140   /* AUX pointers are used by partitioning code to bookkeep number of
3141      partitions symbol is in.  This is no longer needed.  */
3142   FOR_EACH_SYMBOL (node)
3143     node->aux = NULL;
3144
3145   lto_stats.num_cgraph_partitions += ltrans_partitions.length ();
3146
3147   /* Find out statics that need to be promoted
3148      to globals with hidden visibility because they are accessed from multiple
3149      partitions.  */
3150   lto_promote_cross_file_statics ();
3151   timevar_pop (TV_WHOPR_PARTITIONING);
3152
3153   timevar_stop (TV_PHASE_OPT_GEN);
3154
3155   /* Collect a last time - in lto_wpa_write_files we may end up forking
3156      with the idea that this doesn't increase memory usage.  So we
3157      absoultely do not want to collect after that.  */
3158   ggc_collect ();
3159
3160   timevar_start (TV_PHASE_STREAM_OUT);
3161   if (!quiet_flag)
3162     {
3163       fprintf (stderr, "\nStreaming out");
3164       fflush (stderr);
3165     }
3166   lto_wpa_write_files ();
3167   if (!quiet_flag)
3168     fprintf (stderr, "\n");
3169   timevar_stop (TV_PHASE_STREAM_OUT);
3170
3171   if (post_ipa_mem_report)
3172     {
3173       fprintf (stderr, "Memory consumption after IPA\n");
3174       dump_memory_report (false);
3175     }
3176
3177   /* Show the LTO report before launching LTRANS.  */
3178   if (flag_lto_report || (flag_wpa && flag_lto_report_wpa))
3179     print_lto_report_1 ();
3180   if (mem_report_wpa)
3181     dump_memory_report (true);
3182 }
3183
3184
3185 static GTY(()) tree lto_eh_personality_decl;
3186
3187 /* Return the LTO personality function decl.  */
3188
3189 tree
3190 lto_eh_personality (void)
3191 {
3192   if (!lto_eh_personality_decl)
3193     {
3194       /* Use the first personality DECL for our personality if we don't
3195          support multiple ones.  This ensures that we don't artificially
3196          create the need for them in a single-language program.  */
3197       if (first_personality_decl && !dwarf2out_do_cfi_asm ())
3198         lto_eh_personality_decl = first_personality_decl;
3199       else
3200         lto_eh_personality_decl = lhd_gcc_personality ();
3201     }
3202
3203   return lto_eh_personality_decl;
3204 }
3205
3206 /* Set the process name based on the LTO mode. */
3207
3208 static void 
3209 lto_process_name (void)
3210 {
3211   if (flag_lto)
3212     setproctitle ("lto1-lto");
3213   if (flag_wpa)
3214     setproctitle ("lto1-wpa");
3215   if (flag_ltrans)
3216     setproctitle ("lto1-ltrans");
3217 }
3218
3219
3220 /* Initialize the LTO front end.  */
3221
3222 static void
3223 lto_init (void)
3224 {
3225   lto_process_name ();
3226   lto_streamer_hooks_init ();
3227   lto_reader_init ();
3228   lto_set_in_hooks (NULL, get_section_data, free_section_data);
3229   memset (&lto_stats, 0, sizeof (lto_stats));
3230   bitmap_obstack_initialize (NULL);
3231   gimple_register_cfg_hooks ();
3232 #ifndef ACCEL_COMPILER
3233   unsigned char *table
3234     = ggc_vec_alloc<unsigned char> (MAX_MACHINE_MODE);
3235   for (int m = 0; m < MAX_MACHINE_MODE; m++)
3236     table[m] = m;
3237   lto_mode_identity_table = table;
3238 #endif
3239 }
3240
3241 /* Create artificial pointers for "omp declare target link" vars.  */
3242
3243 static void
3244 offload_handle_link_vars (void)
3245 {
3246 #ifdef ACCEL_COMPILER
3247   varpool_node *var;
3248   FOR_EACH_VARIABLE (var)
3249     if (lookup_attribute ("omp declare target link",
3250                           DECL_ATTRIBUTES (var->decl)))
3251       {
3252         tree type = build_pointer_type (TREE_TYPE (var->decl));
3253         tree link_ptr_var = make_node (VAR_DECL);
3254         TREE_TYPE (link_ptr_var) = type;
3255         TREE_USED (link_ptr_var) = 1;
3256         TREE_STATIC (link_ptr_var) = 1;
3257         SET_DECL_MODE (link_ptr_var, TYPE_MODE (type));
3258         DECL_SIZE (link_ptr_var) = TYPE_SIZE (type);
3259         DECL_SIZE_UNIT (link_ptr_var) = TYPE_SIZE_UNIT (type);
3260         DECL_ARTIFICIAL (link_ptr_var) = 1;
3261         tree var_name = DECL_ASSEMBLER_NAME (var->decl);
3262         char *new_name
3263           = ACONCAT ((IDENTIFIER_POINTER (var_name), "_linkptr", NULL));
3264         DECL_NAME (link_ptr_var) = get_identifier (new_name);
3265         SET_DECL_ASSEMBLER_NAME (link_ptr_var, DECL_NAME (link_ptr_var));
3266         SET_DECL_VALUE_EXPR (var->decl, build_simple_mem_ref (link_ptr_var));
3267         DECL_HAS_VALUE_EXPR_P (var->decl) = 1;
3268       }
3269 #endif
3270 }
3271
3272
3273 /* Main entry point for the GIMPLE front end.  This front end has
3274    three main personalities:
3275
3276    - LTO (-flto).  All the object files on the command line are
3277      loaded in memory and processed as a single translation unit.
3278      This is the traditional link-time optimization behavior.
3279
3280    - WPA (-fwpa).  Only the callgraph and summary information for
3281      files in the command file are loaded.  A single callgraph
3282      (without function bodies) is instantiated for the whole set of
3283      files.  IPA passes are only allowed to analyze the call graph
3284      and make transformation decisions.  The callgraph is
3285      partitioned, each partition is written to a new object file
3286      together with the transformation decisions.
3287
3288    - LTRANS (-fltrans).  Similar to -flto but it prevents the IPA
3289      summary files from running again.  Since WPA computed summary
3290      information and decided what transformations to apply, LTRANS
3291      simply applies them.  */
3292
3293 void
3294 lto_main (void)
3295 {
3296   /* LTO is called as a front end, even though it is not a front end.
3297      Because it is called as a front end, TV_PHASE_PARSING and
3298      TV_PARSE_GLOBAL are active, and we need to turn them off while
3299      doing LTO.  Later we turn them back on so they are active up in
3300      toplev.c.  */
3301   timevar_pop (TV_PARSE_GLOBAL);
3302   timevar_stop (TV_PHASE_PARSING);
3303
3304   timevar_start (TV_PHASE_SETUP);
3305
3306   /* Initialize the LTO front end.  */
3307   lto_init ();
3308
3309   timevar_stop (TV_PHASE_SETUP);
3310   timevar_start (TV_PHASE_STREAM_IN);
3311
3312   /* Read all the symbols and call graph from all the files in the
3313      command line.  */
3314   read_cgraph_and_symbols (num_in_fnames, in_fnames);
3315
3316   timevar_stop (TV_PHASE_STREAM_IN);
3317
3318   if (!seen_error ())
3319     {
3320       offload_handle_link_vars ();
3321
3322       /* If WPA is enabled analyze the whole call graph and create an
3323          optimization plan.  Otherwise, read in all the function
3324          bodies and continue with optimization.  */
3325       if (flag_wpa)
3326         do_whole_program_analysis ();
3327       else
3328         {
3329           timevar_start (TV_PHASE_OPT_GEN);
3330
3331           materialize_cgraph ();
3332           if (!flag_ltrans)
3333             lto_promote_statics_nonwpa ();
3334
3335           /* Annotate the CU DIE and mark the early debug phase as finished.  */
3336           debug_hooks->early_finish ("<artificial>");
3337
3338           /* Let the middle end know that we have read and merged all of
3339              the input files.  */ 
3340           symtab->compile ();
3341
3342           timevar_stop (TV_PHASE_OPT_GEN);
3343
3344           /* FIXME lto, if the processes spawned by WPA fail, we miss
3345              the chance to print WPA's report, so WPA will call
3346              print_lto_report before launching LTRANS.  If LTRANS was
3347              launched directly by the driver we would not need to do
3348              this.  */
3349           if (flag_lto_report || (flag_wpa && flag_lto_report_wpa))
3350             print_lto_report_1 ();
3351         }
3352     }
3353
3354   /* Here we make LTO pretend to be a parser.  */
3355   timevar_start (TV_PHASE_PARSING);
3356   timevar_push (TV_PARSE_GLOBAL);
3357 }
3358
3359 #include "gt-lto-lto.h"