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