Debian Codegraph @

gcc/cp/module.cc

raw
1 /* C++ modules. Experimental!
2 Copyright (C) 2017-2025 Free Software Foundation, Inc.
3 Written by Nathan Sidwell <[email protected]> while at FaceBook
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 /* Comments in this file have a non-negligible chance of being wrong
22 or at least inaccurate. Due to (a) my misunderstanding, (b)
23 ambiguities that I have interpretted differently to original intent
24 (c) changes in the specification, (d) my poor wording, (e) source
25 changes. */
26
27 /* (Incomplete) Design Notes
28
29 A hash table contains all module names. Imported modules are
30 present in a modules array, which by construction places an
31 import's dependencies before the import itself. The single
32 exception is the current TU, which always occupies slot zero (even
33 when it is not a module).
34
35 Imported decls occupy an entity_ary, an array of binding_slots, indexed
36 by importing module and index within that module. A flat index is
37 used, as each module reserves a contiguous range of indices.
38 Initially each slot indicates the CMI section containing the
39 streamed decl. When the decl is imported it will point to the decl
40 itself.
41
42 Additionally each imported decl is mapped in the entity_map via its
43 DECL_UID to the flat index in the entity_ary. Thus we can locate
44 the index for any imported decl by using this map and then
45 de-flattening the index via a binary seach of the module vector.
46 Cross-module references are by (remapped) module number and
47 module-local index.
48
49 Each importable DECL contains several flags. The simple set are
50 DECL_MODULE_EXPORT_P, DECL_MODULE_PURVIEW_P, DECL_MODULE_ATTACH_P
51 and DECL_MODULE_IMPORT_P. The first indicates whether it is
52 exported, the second whether it is in module or header-unit
53 purview. The third indicates it is attached to the named module in
54 whose purview it resides and the fourth indicates whether it was an
55 import into this TU or not. DECL_MODULE_ATTACH_P will be false for
56 all decls in a header-unit, and for those in a named module inside
57 a linkage declaration.
58
59 The more detailed flags are DECL_MODULE_PARTITION_P,
60 DECL_MODULE_ENTITY_P. The first is set in a primary interface unit
61 on decls that were read from module partitions (these will have
62 DECL_MODULE_IMPORT_P set too). Such decls will be streamed out to
63 the primary's CMI. DECL_MODULE_ENTITY_P is set when an entity is
64 imported, even if it matched a non-imported entity. Such a decl
65 will not have DECL_MODULE_IMPORT_P set, even though it has an entry
66 in the entity map and array.
67
68 Header units are module-like.
69
70 For namespace-scope lookup, the decls for a particular module are
71 held located in a sparse array hanging off the binding of the name.
72 This is partitioned into two: a few fixed slots at the start
73 followed by the sparse slots afterwards. By construction we only
74 need to append new slots to the end -- there is never a need to
75 insert in the middle. The fixed slots are MODULE_SLOT_CURRENT for
76 the current TU (regardless of whether it is a module or not),
77 MODULE_SLOT_GLOBAL and MODULE_SLOT_PARTITION. These latter two
78 slots are used for merging entities across the global module and
79 module partitions respectively. MODULE_SLOT_PARTITION is only
80 present in a module. Neither of those two slots is searched during
81 name lookup -- they are internal use only. This vector is created
82 lazily once we require it, if there is only a declaration from the
83 current TU, a regular binding is present. It is converted on
84 demand.
85
86 OPTIMIZATION: Outside of the current TU, we only need ADL to work.
87 We could optimize regular lookup for the current TU by glomming all
88 the visible decls on its slot. Perhaps wait until design is a
89 little more settled though.
90
91 There is only one instance of each extern-linkage namespace. It
92 appears in every module slot that makes it visible. It also
93 appears in MODULE_SLOT_GLOBAL. (It is an ODR violation if they
94 collide with some other global module entity.) We also have an
95 optimization that shares the slot for adjacent modules that declare
96 the same such namespace.
97
98 A module interface compilation produces a Compiled Module Interface
99 (CMI). The format used is Encapsulated Lazy Records Of Numbered
100 Declarations, which is essentially ELF's section encapsulation. (As
101 all good nerds are aware, Elrond is half Elf.) Some sections are
102 named, and contain information about the module as a whole (indices
103 etc), and other sections are referenced by number. Although I
104 don't defend against actively hostile CMIs, there is some
105 checksumming involved to verify data integrity. When dumping out
106 an interface, we generate a graph of all the
107 independently-redeclarable DECLS that are needed, and the decls
108 they reference. From that we determine the strongly connected
109 components (SCC) within this TU. Each SCC is dumped to a separate
110 numbered section of the CMI. We generate a binding table section,
111 mapping each namespace&name to a defining section. This allows
112 lazy loading.
113
114 Lazy loading employs mmap to map a read-only image of the CMI.
115 It thus only occupies address space and is paged in on demand,
116 backed by the CMI file itself. If mmap is unavailable, regular
117 FILEIO is used. Also, there's a bespoke ELF reader/writer here,
118 which implements just the section table and sections (including
119 string sections) of a 32-bit ELF in host byte-order. You can of
120 course inspect it with readelf. I figured 32-bit is sufficient,
121 for a single module. I detect running out of section numbers, but
122 do not implement the ELF overflow mechanism. At least you'll get
123 an error if that happens.
124
125 We do not separate declarations and definitions. My guess is that
126 if you refer to the declaration, you'll also need the definition
127 (template body, inline function, class definition etc). But this
128 does mean we can get larger SCCs than if we separated them. It is
129 unclear whether this is a win or not.
130
131 Notice that we embed section indices into the contents of other
132 sections. Thus random manipulation of the CMI file by ELF tools
133 may well break it. The kosher way would probably be to introduce
134 indirection via section symbols, but that would require defining a
135 relocation type.
136
137 Notice that lazy loading of one module's decls can cause lazy
138 loading of other decls in the same or another module. Clearly we
139 want to avoid loops. In a correct program there can be no loops in
140 the module dependency graph, and the above-mentioned SCC algorithm
141 places all intra-module circular dependencies in the same SCC. It
142 also orders the SCCs wrt each other, so dependent SCCs come first.
143 As we load dependent modules first, we know there can be no
144 reference to a higher-numbered module, and because we write out
145 dependent SCCs first, likewise for SCCs within the module. This
146 allows us to immediately detect broken references. When loading,
147 we must ensure the rest of the compiler doesn't cause some
148 unconnected load to occur (for instance, instantiate a template).
149
150 Classes used:
151
152 dumper - logger
153
154 data - buffer
155
156 bytes_in : data - scalar reader
157 bytes_out : data - scalar writer
158
159 bytes_in::bits_in - bit stream reader
160 bytes_out::bits_out - bit stream writer
161
162 elf - ELROND format
163 elf_in : elf - ELROND reader
164 elf_out : elf - ELROND writer
165
166 trees_in : bytes_in - tree reader
167 trees_out : bytes_out - tree writer
168
169 depset - dependency set
170 depset::hash - hash table of depsets
171 depset::tarjan - SCC determinator
172
173 uidset<T> - set T's related to a UID
174 uidset<T>::hash hash table of uidset<T>
175
176 loc_spans - location map data
177
178 module_state - module object
179
180 slurping - data needed during loading
181
182 macro_import - imported macro data
183 macro_export - exported macro data
184
185 The ELROND objects use mmap, for both reading and writing. If mmap
186 is unavailable, fileno IO is used to read and write blocks of data.
187
188 The mapper object uses fileno IO to communicate with the server or
189 program. */
190
191 /* In expermental (trunk) sources, MODULE_VERSION is a #define passed
192 in from the Makefile. It records the modification date of the
193 source directory -- that's the only way to stay sane. In release
194 sources, we (plan to) use the compiler's major.minor versioning.
195 While the format might not change between at minor versions, it
196 seems simplest to tie the two together. There's no concept of
197 inter-version compatibility. */
198 #define IS_EXPERIMENTAL(V) ((V) >= (1U << 20))
199 #define MODULE_MAJOR(V) ((V) / 10000)
200 #define MODULE_MINOR(V) ((V) % 10000)
201 #define EXPERIMENT(A,B) (IS_EXPERIMENTAL (MODULE_VERSION) ? (A) : (B))
202 #ifndef MODULE_VERSION
203 #include "bversion.h"
204 #define MODULE_VERSION (BUILDING_GCC_MAJOR * 10000U + BUILDING_GCC_MINOR)
205 #elif !IS_EXPERIMENTAL (MODULE_VERSION)
206 #error "This is not the version I was looking for."
207 #endif
208
209 #define _DEFAULT_SOURCE 1 /* To get TZ field of struct tm, if available. */
210 #include "config.h"
211 #define INCLUDE_STRING
212 #define INCLUDE_VECTOR
213 #include "system.h"
214 #include "coretypes.h"
215 #include "cp-tree.h"
216 #include "timevar.h"
217 #include "stringpool.h"
218 #include "dumpfile.h"
219 #include "bitmap.h"
220 #include "cgraph.h"
221 #include "varasm.h"
222 #include "tree-iterator.h"
223 #include "cpplib.h"
224 #include "mkdeps.h"
225 #include "incpath.h"
226 #include "libiberty.h"
227 #include "stor-layout.h"
228 #include "version.h"
229 #include "tree-diagnostic.h"
230 #include "toplev.h"
231 #include "opts.h"
232 #include "attribs.h"
233 #include "intl.h"
234 #include "langhooks.h"
235 /* This TU doesn't need or want to see the networking. */
236 #define CODY_NETWORKING 0
237 #include "mapper-client.h"
238 #include <zlib.h> // for crc32, crc32_combine
239
240 #if 0 // 1 for testing no mmap
241 #define MAPPED_READING 0
242 #define MAPPED_WRITING 0
243 #else
244 #if HAVE_MMAP_FILE && HAVE_MUNMAP && HAVE_MSYNC
245 /* mmap, munmap, msync. */
246 #define MAPPED_READING 1
247 #if HAVE_SYSCONF && defined (_SC_PAGE_SIZE)
248 /* sysconf (_SC_PAGE_SIZE), ftruncate */
249 /* posix_fallocate used if available. */
250 #define MAPPED_WRITING 1
251 #else
252 #define MAPPED_WRITING 0
253 #endif
254 #else
255 #define MAPPED_READING 0
256 #define MAPPED_WRITING 0
257 #endif
258 #endif
259
260 /* Some open(2) flag differences, what a colourful world it is! */
261 #if defined (O_CLOEXEC)
262 // OK
263 #elif defined (_O_NOINHERIT)
264 /* Windows' _O_NOINHERIT matches O_CLOEXEC flag */
265 #define O_CLOEXEC _O_NOINHERIT
266 #else
267 #define O_CLOEXEC 0
268 #endif
269 #if defined (O_BINARY)
270 // Ok?
271 #elif defined (_O_BINARY)
272 /* Windows' open(2) call defaults to text! */
273 #define O_BINARY _O_BINARY
274 #else
275 #define O_BINARY 0
276 #endif
277
278 static inline cpp_hashnode *cpp_node (tree id)
279 {
280 return CPP_HASHNODE (GCC_IDENT_TO_HT_IDENT (id));
281 }
282
283 static inline tree identifier (const cpp_hashnode *node)
284 {
285 /* HT_NODE() expands to node->ident that HT_IDENT_TO_GCC_IDENT()
286 then subtracts a nonzero constant, deriving a pointer to
287 a different member than ident. That's strictly undefined
288 and detected by -Warray-bounds. Suppress it. See PR 101372. */
289 #pragma GCC diagnostic push
290 #pragma GCC diagnostic ignored "-Warray-bounds"
291 return HT_IDENT_TO_GCC_IDENT (HT_NODE (const_cast<cpp_hashnode *> (node)));
292 #pragma GCC diagnostic pop
293 }
294
295 /* Id for dumping module information. */
296 int module_dump_id;
297
298 /* We have a special module owner. */
299 #define MODULE_UNKNOWN (~0U) /* Not yet known. */
300
301 /* Prefix for section names. */
302 #define MOD_SNAME_PFX ".gnu.c++"
303
304 /* Format a version for user consumption. */
305
306 typedef char verstr_t[32];
307 static void
308 version2string (unsigned version, verstr_t &out)
309 {
310 unsigned major = MODULE_MAJOR (version);
311 unsigned minor = MODULE_MINOR (version);
312
313 if (IS_EXPERIMENTAL (version))
314 sprintf (out, "%04u/%02u/%02u-%02u:%02u%s",
315 2000 + major / 10000, (major / 100) % 100, (major % 100),
316 minor / 100, minor % 100,
317 EXPERIMENT ("", " (experimental)"));
318 else
319 sprintf (out, "%u.%u", major, minor);
320 }
321
322 /* Include files to note translation for. */
323 static vec<const char *, va_heap, vl_embed> *note_includes;
324
325 /* Modules to note CMI pathames. */
326 static vec<const char *, va_heap, vl_embed> *note_cmis;
327
328 /* Traits to hash an arbitrary pointer. Entries are not deletable,
329 and removal is a noop (removal needed upon destruction). */
330 template <typename T>
331 struct nodel_ptr_hash : pointer_hash<T>, typed_noop_remove <T *> {
332 /* Nothing is deletable. Everything is insertable. */
333 static bool is_deleted (T *) { return false; }
334 static void mark_deleted (T *) { gcc_unreachable (); }
335 };
336
337 /* Map from pointer to signed integer. */
338 typedef simple_hashmap_traits<nodel_ptr_hash<void>, int> ptr_int_traits;
339 typedef hash_map<void *,signed,ptr_int_traits> ptr_int_hash_map;
340
341 /********************************************************************/
342 /* Basic streaming & ELF. Serialization is usually via mmap. For
343 writing we slide a buffer over the output file, syncing it
344 approproiately. For reading we simply map the whole file (as a
345 file-backed read-only map -- it's just address space, leaving the
346 OS pager to deal with getting the data to us). Some buffers need
347 to be more conventional malloc'd contents. */
348
349 /* Variable length buffer. */
350
351 namespace {
352
353 constexpr line_map_uint_t loc_one = 1;
354
355 class data {
356 public:
357 class allocator {
358 public:
359 /* Tools tend to moan if the dtor's not virtual. */
360 virtual ~allocator () {}
361
362 public:
363 void grow (data &obj, unsigned needed, bool exact);
364 void shrink (data &obj);
365
366 public:
367 virtual char *grow (char *ptr, unsigned needed);
368 virtual void shrink (char *ptr);
369 };
370
371 public:
372 char *buffer; /* Buffer being transferred. */
373 /* Although size_t would be the usual size, we know we never get
374 more than 4GB of buffer -- because that's the limit of the
375 encapsulation format. And if you need bigger imports, you're
376 doing it wrong. */
377 unsigned size; /* Allocated size of buffer. */
378 unsigned pos; /* Position in buffer. */
379
380 public:
381 data ()
382 :buffer (NULL), size (0), pos (0)
383 {
384 }
385 ~data ()
386 {
387 /* Make sure the derived and/or using class know what they're
388 doing. */
389 gcc_checking_assert (!buffer);
390 }
391
392 protected:
393 char *use (unsigned count)
394 {
395 if (size < pos + count)
396 return NULL;
397 char *res = &buffer[pos];
398 pos += count;
399 return res;
400 }
401
402 unsigned calc_crc (unsigned) const;
403
404 public:
405 void unuse (unsigned count)
406 {
407 pos -= count;
408 }
409
410 public:
411 static allocator simple_memory;
412 };
413 } // anon namespace
414
415 /* The simple data allocator. */
416 data::allocator data::simple_memory;
417
418 /* Grow buffer to at least size NEEDED. */
419
420 void
421 data::allocator::grow (data &obj, unsigned needed, bool exact)
422 {
423 gcc_checking_assert (needed ? needed > obj.size : !obj.size);
424 if (!needed)
425 /* Pick a default size. */
426 needed = EXPERIMENT (100, 1000);
427
428 if (!exact)
429 needed *= 2;
430 obj.buffer = grow (obj.buffer, needed);
431 if (obj.buffer)
432 obj.size = needed;
433 else
434 obj.pos = obj.size = 0;
435 }
436
437 /* Free a buffer. */
438
439 void
440 data::allocator::shrink (data &obj)
441 {
442 shrink (obj.buffer);
443 obj.buffer = NULL;
444 obj.size = 0;
445 }
446
447 char *
448 data::allocator::grow (char *ptr, unsigned needed)
449 {
450 return XRESIZEVAR (char, ptr, needed);
451 }
452
453 void
454 data::allocator::shrink (char *ptr)
455 {
456 XDELETEVEC (ptr);
457 }
458
459 /* Calculate the crc32 of the buffer. Note the CRC is stored in the
460 first 4 bytes, so don't include them. */
461
462 unsigned
463 data::calc_crc (unsigned l) const
464 {
465 return crc32 (0, (unsigned char *)buffer + 4, l - 4);
466 }
467
468 class elf_in;
469
470 /* Byte stream reader. */
471
472 namespace {
473 class bytes_in : public data {
474 typedef data parent;
475
476 protected:
477 bool overrun; /* Sticky read-too-much flag. */
478
479 public:
480 bytes_in ()
481 : parent (), overrun (false)
482 {
483 }
484 ~bytes_in ()
485 {
486 }
487
488 public:
489 /* Begin reading a named section. */
490 bool begin (location_t loc, elf_in *src, const char *name);
491 /* Begin reading a numbered section with optional name. */
492 bool begin (location_t loc, elf_in *src, unsigned, const char * = NULL);
493 /* Complete reading a buffer. Propagate errors and return true on
494 success. */
495 bool end (elf_in *src);
496 /* Return true if there is unread data. */
497 bool more_p () const
498 {
499 return pos != size;
500 }
501
502 public:
503 /* Start reading at OFFSET. */
504 void random_access (unsigned offset)
505 {
506 if (offset > size)
507 set_overrun ();
508 pos = offset;
509 }
510
511 public:
512 void align (unsigned boundary)
513 {
514 if (unsigned pad = pos & (boundary - 1))
515 read (boundary - pad);
516 }
517
518 public:
519 const char *read (unsigned count)
520 {
521 char *ptr = use (count);
522 if (!ptr)
523 set_overrun ();
524 return ptr;
525 }
526
527 public:
528 bool check_crc () const;
529 /* We store the CRC in the first 4 bytes, using host endianness. */
530 unsigned get_crc () const
531 {
532 return *(const unsigned *)&buffer[0];
533 }
534
535 public:
536 /* Manipulate the overrun flag. */
537 bool get_overrun () const
538 {
539 return overrun;
540 }
541 void set_overrun ()
542 {
543 overrun = true;
544 }
545
546 public:
547 unsigned u32 (); /* Read uncompressed integer. */
548
549 public:
550 int c () ATTRIBUTE_UNUSED; /* Read a char. */
551 int i (); /* Read a signed int. */
552 unsigned u (); /* Read an unsigned int. */
553 size_t z (); /* Read a size_t. */
554 location_t loc (); /* Read a location_t. */
555 HOST_WIDE_INT wi (); /* Read a HOST_WIDE_INT. */
556 unsigned HOST_WIDE_INT wu (); /* Read an unsigned HOST_WIDE_INT. */
557 const char *str (size_t * = NULL); /* Read a string. */
558 const void *buf (size_t); /* Read a fixed-length buffer. */
559 cpp_hashnode *cpp_node (); /* Read a cpp node. */
560
561 struct bits_in;
562 bits_in stream_bits ();
563 };
564 } // anon namespace
565
566 /* Verify the buffer's CRC is correct. */
567
568 bool
569 bytes_in::check_crc () const
570 {
571 if (size < 4)
572 return false;
573
574 unsigned c_crc = calc_crc (size);
575 if (c_crc != get_crc ())
576 return false;
577
578 return true;
579 }
580
581 class elf_out;
582
583 /* Byte stream writer. */
584
585 namespace {
586 class bytes_out : public data {
587 typedef data parent;
588
589 public:
590 allocator *memory; /* Obtainer of memory. */
591
592 public:
593 bytes_out (allocator *memory)
594 : parent (), memory (memory)
595 {
596 }
597 ~bytes_out ()
598 {
599 }
600
601 public:
602 bool streaming_p () const
603 {
604 return memory != NULL;
605 }
606
607 public:
608 void set_crc (unsigned *crc_ptr);
609
610 public:
611 /* Begin writing, maybe reserve space for CRC. */
612 void begin (bool need_crc = true);
613 /* Finish writing. Spill to section by number. */
614 unsigned end (elf_out *, unsigned, unsigned *crc_ptr = NULL);
615
616 public:
617 void align (unsigned boundary)
618 {
619 if (unsigned pad = pos & (boundary - 1))
620 write (boundary - pad);
621 }
622
623 public:
624 char *write (unsigned count, bool exact = false)
625 {
626 if (size < pos + count)
627 memory->grow (*this, pos + count, exact);
628 return use (count);
629 }
630
631 public:
632 void u32 (unsigned); /* Write uncompressed integer. */
633
634 public:
635 void c (unsigned char) ATTRIBUTE_UNUSED; /* Write unsigned char. */
636 void i (int); /* Write signed int. */
637 void u (unsigned); /* Write unsigned int. */
638 void z (size_t s); /* Write size_t. */
639 void loc (location_t); /* Write location_t. */
640 void wi (HOST_WIDE_INT); /* Write HOST_WIDE_INT. */
641 void wu (unsigned HOST_WIDE_INT); /* Write unsigned HOST_WIDE_INT. */
642 void str (const char *ptr)
643 {
644 str (ptr, strlen (ptr));
645 }
646 void cpp_node (const cpp_hashnode *node)
647 {
648 str ((const char *)NODE_NAME (node), NODE_LEN (node));
649 }
650 void str (const char *, size_t); /* Write string of known length. */
651 void buf (const void *, size_t); /* Write fixed length buffer. */
652 void *buf (size_t); /* Create a writable buffer */
653
654 struct bits_out;
655 bits_out stream_bits ();
656
657 public:
658 /* Format a NUL-terminated raw string. */
659 void printf (const char *, ...) ATTRIBUTE_PRINTF_2;
660 void print_time (const char *, const tm *, const char *);
661
662 public:
663 /* Dump instrumentation. */
664 static void instrument ();
665
666 protected:
667 /* Instrumentation. */
668 static unsigned spans[4];
669 static unsigned lengths[4];
670 };
671 } // anon namespace
672
673 /* Finish bit packet. Rewind the bytes not used. */
674
675 static unsigned
676 bit_flush (data& bits, uint32_t& bit_val, unsigned& bit_pos)
677 {
678 gcc_assert (bit_pos);
679 unsigned bytes = (bit_pos + 7) / 8;
680 bits.unuse (4 - bytes);
681 bit_pos = 0;
682 bit_val = 0;
683 return bytes;
684 }
685
686 /* Bit stream reader (RAII-enabled). Bools are packed into bytes. You
687 cannot mix bools and non-bools. Use bflush to flush the current stream
688 of bools on demand. Upon destruction bflush is called.
689
690 When reading, we don't know how many bools we'll read in. So read
691 4 bytes-worth, and then rewind when flushing if we didn't need them
692 all. You can't have a block of bools closer than 4 bytes to the
693 end of the buffer.
694
695 Both bits_in and bits_out maintain the necessary state for bit packing,
696 and since these objects are locally constructed the compiler can more
697 easily track their state across consecutive reads/writes and optimize
698 away redundant buffering checks. */
699
700 struct bytes_in::bits_in {
701 bytes_in& in;
702 uint32_t bit_val = 0;
703 unsigned bit_pos = 0;
704
705 bits_in (bytes_in& in)
706 : in (in)
707 { }
708
709 ~bits_in ()
710 {
711 bflush ();
712 }
713
714 bits_in(bits_in&&) = default;
715 bits_in(const bits_in&) = delete;
716 bits_in& operator=(const bits_in&) = delete;
717
718 /* Completed a block of bools. */
719 void bflush ()
720 {
721 if (bit_pos)
722 bit_flush (in, bit_val, bit_pos);
723 }
724
725 /* Read one bit. */
726 bool b ()
727 {
728 if (!bit_pos)
729 bit_val = in.u32 ();
730 bool x = (bit_val >> bit_pos) & 1;
731 bit_pos = (bit_pos + 1) % 32;
732 return x;
733 }
734 };
735
736 /* Factory function for bits_in. */
737
738 bytes_in::bits_in
739 bytes_in::stream_bits ()
740 {
741 return bits_in (*this);
742 }
743
744 /* Bit stream writer (RAII-enabled), counterpart to bits_in. */
745
746 struct bytes_out::bits_out {
747 bytes_out& out;
748 uint32_t bit_val = 0;
749 unsigned bit_pos = 0;
750 char is_set = -1;
751
752 bits_out (bytes_out& out)
753 : out (out)
754 { }
755
756 ~bits_out ()
757 {
758 bflush ();
759 }
760
761 bits_out(bits_out&&) = default;
762 bits_out(const bits_out&) = delete;
763 bits_out& operator=(const bits_out&) = delete;
764
765 /* Completed a block of bools. */
766 void bflush ()
767 {
768 if (bit_pos)
769 {
770 out.u32 (bit_val);
771 out.lengths[2] += bit_flush (out, bit_val, bit_pos);
772 }
773 out.spans[2]++;
774 is_set = -1;
775 }
776
777 /* Write one bit.
778
779 It may be worth optimizing for most bools being zero. Some kind of
780 run-length encoding? */
781 void b (bool x)
782 {
783 if (is_set != x)
784 {
785 is_set = x;
786 out.spans[x]++;
787 }
788 out.lengths[x]++;
789 bit_val |= unsigned (x) << bit_pos++;
790 if (bit_pos == 32)
791 {
792 out.u32 (bit_val);
793 out.lengths[2] += bit_flush (out, bit_val, bit_pos);
794 }
795 }
796 };
797
798 /* Factory function for bits_out. */
799
800 bytes_out::bits_out
801 bytes_out::stream_bits ()
802 {
803 return bits_out (*this);
804 }
805
806 /* Instrumentation. */
807 unsigned bytes_out::spans[4];
808 unsigned bytes_out::lengths[4];
809
810 /* If CRC_PTR non-null, set the CRC of the buffer. Mix the CRC into
811 that pointed to by CRC_PTR. */
812
813 void
814 bytes_out::set_crc (unsigned *crc_ptr)
815 {
816 if (crc_ptr)
817 {
818 gcc_checking_assert (pos >= 4);
819
820 unsigned crc = calc_crc (pos);
821 unsigned accum = *crc_ptr;
822 /* Only mix the existing *CRC_PTR if it is non-zero. */
823 accum = accum ? crc32_combine (accum, crc, pos - 4) : crc;
824 *crc_ptr = accum;
825
826 /* Buffer will be sufficiently aligned. */
827 *(unsigned *)buffer = crc;
828 }
829 }
830
831 /* Exactly 4 bytes. Used internally for bool packing and a few other
832 places. We can't simply use uint32_t because (a) alignment and
833 (b) we need little-endian for the bool streaming rewinding to make
834 sense. */
835
836 void
837 bytes_out::u32 (unsigned val)
838 {
839 if (char *ptr = write (4))
840 {
841 ptr[0] = val;
842 ptr[1] = val >> 8;
843 ptr[2] = val >> 16;
844 ptr[3] = val >> 24;
845 }
846 }
847
848 unsigned
849 bytes_in::u32 ()
850 {
851 unsigned val = 0;
852 if (const char *ptr = read (4))
853 {
854 val |= (unsigned char)ptr[0];
855 val |= (unsigned char)ptr[1] << 8;
856 val |= (unsigned char)ptr[2] << 16;
857 val |= (unsigned char)ptr[3] << 24;
858 }
859
860 return val;
861 }
862
863 /* Chars are unsigned and written as single bytes. */
864
865 void
866 bytes_out::c (unsigned char v)
867 {
868 if (char *ptr = write (1))
869 *ptr = v;
870 }
871
872 int
873 bytes_in::c ()
874 {
875 int v = 0;
876 if (const char *ptr = read (1))
877 v = (unsigned char)ptr[0];
878 return v;
879 }
880
881 /* Ints 7-bit as a byte. Otherwise a 3bit count of following bytes in
882 big-endian form. 4 bits are in the first byte. */
883
884 void
885 bytes_out::i (int v)
886 {
887 if (char *ptr = write (1))
888 {
889 if (v <= 0x3f && v >= -0x40)
890 *ptr = v & 0x7f;
891 else
892 {
893 unsigned bytes = 0;
894 int probe;
895 if (v >= 0)
896 for (probe = v >> 8; probe > 0x7; probe >>= 8)
897 bytes++;
898 else
899 for (probe = v >> 8; probe < -0x8; probe >>= 8)
900 bytes++;
901 *ptr = 0x80 | bytes << 4 | (probe & 0xf);
902 if ((ptr = write (++bytes)))
903 for (; bytes--; v >>= 8)
904 ptr[bytes] = v & 0xff;
905 }
906 }
907 }
908
909 int
910 bytes_in::i ()
911 {
912 int v = 0;
913 if (const char *ptr = read (1))
914 {
915 v = *ptr & 0xff;
916 if (v & 0x80)
917 {
918 unsigned bytes = (v >> 4) & 0x7;
919 v &= 0xf;
920 if (v & 0x8)
921 v |= -1 ^ 0x7;
922 /* unsigned necessary due to left shifts of -ve values. */
923 unsigned uv = unsigned (v);
924 if ((ptr = read (++bytes)))
925 while (bytes--)
926 uv = (uv << 8) | (*ptr++ & 0xff);
927 v = int (uv);
928 }
929 else if (v & 0x40)
930 v |= -1 ^ 0x3f;
931 }
932
933 return v;
934 }
935
936 void
937 bytes_out::u (unsigned v)
938 {
939 if (char *ptr = write (1))
940 {
941 if (v <= 0x7f)
942 *ptr = v;
943 else
944 {
945 unsigned bytes = 0;
946 unsigned probe;
947 for (probe = v >> 8; probe > 0xf; probe >>= 8)
948 bytes++;
949 *ptr = 0x80 | bytes << 4 | probe;
950 if ((ptr = write (++bytes)))
951 for (; bytes--; v >>= 8)
952 ptr[bytes] = v & 0xff;
953 }
954 }
955 }
956
957 unsigned
958 bytes_in::u ()
959 {
960 unsigned v = 0;
961
962 if (const char *ptr = read (1))
963 {
964 v = *ptr & 0xff;
965 if (v & 0x80)
966 {
967 unsigned bytes = (v >> 4) & 0x7;
968 v &= 0xf;
969 if ((ptr = read (++bytes)))
970 while (bytes--)
971 v = (v << 8) | (*ptr++ & 0xff);
972 }
973 }
974
975 return v;
976 }
977
978 void
979 bytes_out::wi (HOST_WIDE_INT v)
980 {
981 if (char *ptr = write (1))
982 {
983 if (v <= 0x3f && v >= -0x40)
984 *ptr = v & 0x7f;
985 else
986 {
987 unsigned bytes = 0;
988 HOST_WIDE_INT probe;
989 if (v >= 0)
990 for (probe = v >> 8; probe > 0x7; probe >>= 8)
991 bytes++;
992 else
993 for (probe = v >> 8; probe < -0x8; probe >>= 8)
994 bytes++;
995 *ptr = 0x80 | bytes << 4 | (probe & 0xf);
996 if ((ptr = write (++bytes)))
997 for (; bytes--; v >>= 8)
998 ptr[bytes] = v & 0xff;
999 }
1000 }
1001 }
1002
1003 HOST_WIDE_INT
1004 bytes_in::wi ()
1005 {
1006 HOST_WIDE_INT v = 0;
1007 if (const char *ptr = read (1))
1008 {
1009 v = *ptr & 0xff;
1010 if (v & 0x80)
1011 {
1012 unsigned bytes = (v >> 4) & 0x7;
1013 v &= 0xf;
1014 if (v & 0x8)
1015 v |= -1 ^ 0x7;
1016 /* unsigned necessary due to left shifts of -ve values. */
1017 unsigned HOST_WIDE_INT uv = (unsigned HOST_WIDE_INT) v;
1018 if ((ptr = read (++bytes)))
1019 while (bytes--)
1020 uv = (uv << 8) | (*ptr++ & 0xff);
1021 v = (HOST_WIDE_INT) uv;
1022 }
1023 else if (v & 0x40)
1024 v |= -1 ^ 0x3f;
1025 }
1026
1027 return v;
1028 }
1029
1030 /* unsigned wide ints are just written as signed wide ints. */
1031
1032 inline void
1033 bytes_out::wu (unsigned HOST_WIDE_INT v)
1034 {
1035 wi ((HOST_WIDE_INT) v);
1036 }
1037
1038 inline unsigned HOST_WIDE_INT
1039 bytes_in::wu ()
1040 {
1041 return (unsigned HOST_WIDE_INT) wi ();
1042 }
1043
1044 /* size_t written as unsigned or unsigned wide int. */
1045
1046 inline void
1047 bytes_out::z (size_t s)
1048 {
1049 if (sizeof (s) == sizeof (unsigned))
1050 u (s);
1051 else
1052 wu (s);
1053 }
1054
1055 inline size_t
1056 bytes_in::z ()
1057 {
1058 if (sizeof (size_t) == sizeof (unsigned))
1059 return u ();
1060 else
1061 return wu ();
1062 }
1063
1064 /* location_t written as 32- or 64-bit as needed. */
1065
1066 inline void bytes_out::loc (location_t l)
1067 {
1068 if (sizeof (location_t) > sizeof (unsigned))
1069 wu (l);
1070 else
1071 u (l);
1072 }
1073
1074 inline location_t bytes_in::loc ()
1075 {
1076 if (sizeof (location_t) > sizeof (unsigned))
1077 return wu ();
1078 else
1079 return u ();
1080 }
1081
1082 /* Buffer simply memcpied. */
1083 void *
1084 bytes_out::buf (size_t len)
1085 {
1086 align (sizeof (void *) * 2);
1087 return write (len);
1088 }
1089
1090 void
1091 bytes_out::buf (const void *src, size_t len)
1092 {
1093 if (void *ptr = buf (len))
1094 memcpy (ptr, src, len);
1095 }
1096
1097 const void *
1098 bytes_in::buf (size_t len)
1099 {
1100 align (sizeof (void *) * 2);
1101 const char *ptr = read (len);
1102
1103 return ptr;
1104 }
1105
1106 /* strings as an size_t length, followed by the buffer. Make sure
1107 there's a NUL terminator on read. */
1108
1109 void
1110 bytes_out::str (const char *string, size_t len)
1111 {
1112 z (len);
1113 if (len)
1114 {
1115 gcc_checking_assert (!string[len]);
1116 buf (string, len + 1);
1117 }
1118 }
1119
1120 const char *
1121 bytes_in::str (size_t *len_p)
1122 {
1123 size_t len = z ();
1124
1125 /* We're about to trust some user data. */
1126 if (overrun)
1127 len = 0;
1128 if (len_p)
1129 *len_p = len;
1130 const char *str = NULL;
1131 if (len)
1132 {
1133 str = reinterpret_cast<const char *> (buf (len + 1));
1134 if (!str || str[len])
1135 {
1136 set_overrun ();
1137 str = NULL;
1138 }
1139 }
1140 return str ? str : "";
1141 }
1142
1143 cpp_hashnode *
1144 bytes_in::cpp_node ()
1145 {
1146 size_t len;
1147 const char *s = str (&len);
1148 if (!len)
1149 return NULL;
1150 return ::cpp_node (get_identifier_with_length (s, len));
1151 }
1152
1153 /* Format a string directly to the buffer, including a terminating
1154 NUL. Intended for human consumption. */
1155
1156 void
1157 bytes_out::printf (const char *format, ...)
1158 {
1159 va_list args;
1160 /* Exercise buffer expansion. */
1161 size_t len = EXPERIMENT (10, 500);
1162
1163 while (char *ptr = write (len))
1164 {
1165 va_start (args, format);
1166 size_t actual = vsnprintf (ptr, len, format, args) + 1;
1167 va_end (args);
1168 if (actual <= len)
1169 {
1170 unuse (len - actual);
1171 break;
1172 }
1173 unuse (len);
1174 len = actual;
1175 }
1176 }
1177
1178 void
1179 bytes_out::print_time (const char *kind, const tm *time, const char *tz)
1180 {
1181 printf ("%stime: %4u/%02u/%02u %02u:%02u:%02u %s",
1182 kind, time->tm_year + 1900, time->tm_mon + 1, time->tm_mday,
1183 time->tm_hour, time->tm_min, time->tm_sec, tz);
1184 }
1185
1186 /* Encapsulated Lazy Records Of Named Declarations.
1187 Header: Stunningly Elf32_Ehdr-like
1188 Sections: Sectional data
1189 [1-N) : User data sections
1190 N .strtab : strings, stunningly ELF STRTAB-like
1191 Index: Section table, stunningly ELF32_Shdr-like. */
1192
1193 class elf {
1194 protected:
1195 /* Constants used within the format. */
1196 enum private_constants {
1197 /* File kind. */
1198 ET_NONE = 0,
1199 EM_NONE = 0,
1200 OSABI_NONE = 0,
1201
1202 /* File format. */
1203 EV_CURRENT = 1,
1204 CLASS32 = 1,
1205 DATA2LSB = 1,
1206 DATA2MSB = 2,
1207
1208 /* Section numbering. */
1209 SHN_UNDEF = 0,
1210 SHN_LORESERVE = 0xff00,
1211 SHN_XINDEX = 0xffff,
1212
1213 /* Section types. */
1214 SHT_NONE = 0, /* No contents. */
1215 SHT_PROGBITS = 1, /* Random bytes. */
1216 SHT_STRTAB = 3, /* A string table. */
1217
1218 /* Section flags. */
1219 SHF_NONE = 0x00, /* Nothing. */
1220 SHF_STRINGS = 0x20, /* NUL-Terminated strings. */
1221
1222 /* I really hope we do not get CMI files larger than 4GB. */
1223 MY_CLASS = CLASS32,
1224 /* It is host endianness that is relevant. */
1225 MY_ENDIAN = DATA2LSB
1226 #ifdef WORDS_BIGENDIAN
1227 ^ DATA2LSB ^ DATA2MSB
1228 #endif
1229 };
1230
1231 public:
1232 /* Constants visible to users. */
1233 enum public_constants {
1234 /* Special error codes. Breaking layering a bit. */
1235 E_BAD_DATA = -1, /* Random unexpected data errors. */
1236 E_BAD_LAZY = -2, /* Badly ordered laziness. */
1237 E_BAD_IMPORT = -3 /* A nested import failed. */
1238 };
1239
1240 protected:
1241 /* File identification. On-disk representation. */
1242 struct ident {
1243 uint8_t magic[4]; /* 0x7f, 'E', 'L', 'F' */
1244 uint8_t klass; /* 4:CLASS32 */
1245 uint8_t data; /* 5:DATA2[LM]SB */
1246 uint8_t version; /* 6:EV_CURRENT */
1247 uint8_t osabi; /* 7:OSABI_NONE */
1248 uint8_t abiver; /* 8: 0 */
1249 uint8_t pad[7]; /* 9-15 */
1250 };
1251 /* File header. On-disk representation. */
1252 struct header {
1253 struct ident ident;
1254 uint16_t type; /* ET_NONE */
1255 uint16_t machine; /* EM_NONE */
1256 uint32_t version; /* EV_CURRENT */
1257 uint32_t entry; /* 0 */
1258 uint32_t phoff; /* 0 */
1259 uint32_t shoff; /* Section Header Offset in file */
1260 uint32_t flags;
1261 uint16_t ehsize; /* ELROND Header SIZE -- sizeof (header) */
1262 uint16_t phentsize; /* 0 */
1263 uint16_t phnum; /* 0 */
1264 uint16_t shentsize; /* Section Header SIZE -- sizeof (section) */
1265 uint16_t shnum; /* Section Header NUM */
1266 uint16_t shstrndx; /* Section Header STRing iNDeX */
1267 };
1268 /* File section. On-disk representation. */
1269 struct section {
1270 uint32_t name; /* String table offset. */
1271 uint32_t type; /* SHT_* */
1272 uint32_t flags; /* SHF_* */
1273 uint32_t addr; /* 0 */
1274 uint32_t offset; /* OFFSET in file */
1275 uint32_t size; /* SIZE of section */
1276 uint32_t link; /* 0 */
1277 uint32_t info; /* 0 */
1278 uint32_t addralign; /* 0 */
1279 uint32_t entsize; /* ENTry SIZE, usually 0 */
1280 };
1281
1282 protected:
1283 data hdr; /* The header. */
1284 data sectab; /* The section table. */
1285 data strtab; /* String table. */
1286 int fd; /* File descriptor we're reading or writing. */
1287 int err; /* Sticky error code. */
1288
1289 public:
1290 /* Construct from STREAM. E is errno if STREAM NULL. */
1291 elf (int fd, int e)
1292 :hdr (), sectab (), strtab (), fd (fd), err (fd >= 0 ? 0 : e)
1293 {}
1294 ~elf ()
1295 {
1296 gcc_checking_assert (fd < 0 && !hdr.buffer
1297 && !sectab.buffer && !strtab.buffer);
1298 }
1299
1300 public:
1301 /* Return the error, if we have an error. */
1302 int get_error () const
1303 {
1304 return err;
1305 }
1306 /* Set the error, unless it's already been set. */
1307 void set_error (int e = E_BAD_DATA)
1308 {
1309 if (!err)
1310 err = e;
1311 }
1312 /* Get an error string. */
1313 const char *get_error (const char *) const;
1314
1315 public:
1316 /* Begin reading/writing file. Return false on error. */
1317 bool begin () const
1318 {
1319 return !get_error ();
1320 }
1321 /* Finish reading/writing file. Return false on error. */
1322 bool end ();
1323 };
1324
1325 /* Return error string. */
1326
1327 const char *
1328 elf::get_error (const char *name) const
1329 {
1330 if (!name)
1331 return "Unknown CMI mapping";
1332
1333 switch (err)
1334 {
1335 case 0:
1336 gcc_unreachable ();
1337 case E_BAD_DATA:
1338 return "Bad file data";
1339 case E_BAD_IMPORT:
1340 return "Bad import dependency";
1341 case E_BAD_LAZY:
1342 return "Bad lazy ordering";
1343 default:
1344 return xstrerror (err);
1345 }
1346 }
1347
1348 /* Finish file, return true if there's an error. */
1349
1350 bool
1351 elf::end ()
1352 {
1353 /* Close the stream and free the section table. */
1354 if (fd >= 0 && close (fd))
1355 set_error (errno);
1356 fd = -1;
1357
1358 return !get_error ();
1359 }
1360
1361 /* ELROND reader. */
1362
1363 class elf_in : public elf {
1364 typedef elf parent;
1365
1366 private:
1367 /* For freezing & defrosting. */
1368 #if !defined (HOST_LACKS_INODE_NUMBERS)
1369 dev_t device;
1370 ino_t inode;
1371 #endif
1372
1373 public:
1374 elf_in (int fd, int e)
1375 :parent (fd, e)
1376 {
1377 }
1378 ~elf_in ()
1379 {
1380 }
1381
1382 public:
1383 bool is_frozen () const
1384 {
1385 return fd < 0 && hdr.pos;
1386 }
1387 bool is_freezable () const
1388 {
1389 return fd >= 0 && hdr.pos;
1390 }
1391 void freeze ();
1392 bool defrost (const char *);
1393
1394 /* If BYTES is in the mmapped area, allocate a new buffer for it. */
1395 void preserve (bytes_in &bytes ATTRIBUTE_UNUSED)
1396 {
1397 #if MAPPED_READING
1398 if (hdr.buffer && bytes.buffer >= hdr.buffer
1399 && bytes.buffer < hdr.buffer + hdr.pos)
1400 {
1401 char *buf = bytes.buffer;
1402 bytes.buffer = data::simple_memory.grow (NULL, bytes.size);
1403 memcpy (bytes.buffer, buf, bytes.size);
1404 }
1405 #endif
1406 }
1407 /* If BYTES is not in SELF's mmapped area, free it. SELF might be
1408 NULL. */
1409 static void release (elf_in *self ATTRIBUTE_UNUSED, bytes_in &bytes)
1410 {
1411 #if MAPPED_READING
1412 if (!(self && self->hdr.buffer && bytes.buffer >= self->hdr.buffer
1413 && bytes.buffer < self->hdr.buffer + self->hdr.pos))
1414 #endif
1415 data::simple_memory.shrink (bytes.buffer);
1416 bytes.buffer = NULL;
1417 bytes.size = 0;
1418 }
1419
1420 public:
1421 static void grow (data &data, unsigned needed)
1422 {
1423 gcc_checking_assert (!data.buffer);
1424 #if !MAPPED_READING
1425 data.buffer = XNEWVEC (char, needed);
1426 #endif
1427 data.size = needed;
1428 }
1429 static void shrink (data &data)
1430 {
1431 #if !MAPPED_READING
1432 XDELETEVEC (data.buffer);
1433 #endif
1434 data.buffer = NULL;
1435 data.size = 0;
1436 }
1437
1438 public:
1439 const section *get_section (unsigned s) const
1440 {
1441 if (s * sizeof (section) < sectab.size)
1442 return reinterpret_cast<const section *>
1443 (&sectab.buffer[s * sizeof (section)]);
1444 else
1445 return NULL;
1446 }
1447 unsigned get_section_limit () const
1448 {
1449 return sectab.size / sizeof (section);
1450 }
1451
1452 protected:
1453 const char *read (data *, unsigned, unsigned);
1454
1455 public:
1456 /* Read section by number. */
1457 bool read (data *d, const section *s)
1458 {
1459 return s && read (d, s->offset, s->size);
1460 }
1461
1462 /* Find section by name. */
1463 unsigned find (const char *name);
1464 /* Find section by index. */
1465 const section *find (unsigned snum, unsigned type = SHT_PROGBITS);
1466
1467 public:
1468 /* Release the string table, when we're done with it. */
1469 void release ()
1470 {
1471 shrink (strtab);
1472 }
1473
1474 public:
1475 bool begin (location_t);
1476 bool end ()
1477 {
1478 release ();
1479 #if MAPPED_READING
1480 if (hdr.buffer)
1481 munmap (hdr.buffer, hdr.pos);
1482 hdr.buffer = NULL;
1483 #endif
1484 shrink (sectab);
1485
1486 return parent::end ();
1487 }
1488
1489 public:
1490 /* Return string name at OFFSET. Checks OFFSET range. Always
1491 returns non-NULL. We know offset 0 is an empty string. */
1492 const char *name (unsigned offset)
1493 {
1494 return &strtab.buffer[offset < strtab.size ? offset : 0];
1495 }
1496 };
1497
1498 /* ELROND writer. */
1499
1500 class elf_out : public elf, public data::allocator {
1501 typedef elf parent;
1502 /* Desired section alignment on disk. */
1503 static const int SECTION_ALIGN = 16;
1504
1505 private:
1506 ptr_int_hash_map identtab; /* Map of IDENTIFIERS to strtab offsets. */
1507 unsigned pos; /* Write position in file. */
1508 #if MAPPED_WRITING
1509 unsigned offset; /* Offset of the mapping. */
1510 unsigned extent; /* Length of mapping. */
1511 unsigned page_size; /* System page size. */
1512 #endif
1513
1514 public:
1515 elf_out (int fd, int e)
1516 :parent (fd, e), identtab (500), pos (0)
1517 {
1518 #if MAPPED_WRITING
1519 offset = extent = 0;
1520 page_size = sysconf (_SC_PAGE_SIZE);
1521 if (page_size < SECTION_ALIGN)
1522 /* Something really strange. */
1523 set_error (EINVAL);
1524 #endif
1525 }
1526 ~elf_out ()
1527 {
1528 data::simple_memory.shrink (hdr);
1529 data::simple_memory.shrink (sectab);
1530 data::simple_memory.shrink (strtab);
1531 }
1532
1533 #if MAPPED_WRITING
1534 private:
1535 void create_mapping (unsigned ext, bool extending = true);
1536 void remove_mapping ();
1537 #endif
1538
1539 protected:
1540 using allocator::grow;
1541 char *grow (char *, unsigned needed) final override;
1542 #if MAPPED_WRITING
1543 using allocator::shrink;
1544 void shrink (char *) final override;
1545 #endif
1546
1547 public:
1548 unsigned get_section_limit () const
1549 {
1550 return sectab.pos / sizeof (section);
1551 }
1552
1553 protected:
1554 unsigned add (unsigned type, unsigned name = 0,
1555 unsigned off = 0, unsigned size = 0, unsigned flags = SHF_NONE);
1556 unsigned write (const data &);
1557 #if MAPPED_WRITING
1558 unsigned write (const bytes_out &);
1559 #endif
1560
1561 public:
1562 /* IDENTIFIER to strtab offset. */
1563 unsigned name (tree ident);
1564 /* String literal to strtab offset. */
1565 unsigned name (const char *n);
1566 /* Qualified name of DECL to strtab offset. */
1567 unsigned qualified_name (tree decl, bool is_defn);
1568
1569 private:
1570 unsigned strtab_write (const char *s, unsigned l);
1571 void strtab_write (tree decl, int);
1572
1573 public:
1574 /* Add a section with contents or strings. */
1575 unsigned add (const bytes_out &, bool string_p, unsigned name);
1576
1577 public:
1578 /* Begin and end writing. */
1579 bool begin ();
1580 bool end ();
1581 };
1582
1583 /* Begin reading section NAME (of type PROGBITS) from SOURCE.
1584 Data always checked for CRC. */
1585
1586 bool
1587 bytes_in::begin (location_t loc, elf_in *source, const char *name)
1588 {
1589 unsigned snum = source->find (name);
1590
1591 return begin (loc, source, snum, name);
1592 }
1593
1594 /* Begin reading section numbered SNUM with NAME (may be NULL). */
1595
1596 bool
1597 bytes_in::begin (location_t loc, elf_in *source, unsigned snum, const char *name)
1598 {
1599 if (!source->read (this, source->find (snum))
1600 || !size || !check_crc ())
1601 {
1602 source->set_error (elf::E_BAD_DATA);
1603 source->shrink (*this);
1604 if (name)
1605 error_at (loc, "section %qs is missing or corrupted", name);
1606 else
1607 error_at (loc, "section #%u is missing or corrupted", snum);
1608 return false;
1609 }
1610 pos = 4;
1611 return true;
1612 }
1613
1614 /* Finish reading a section. */
1615
1616 bool
1617 bytes_in::end (elf_in *src)
1618 {
1619 if (more_p ())
1620 set_overrun ();
1621 if (overrun)
1622 src->set_error ();
1623
1624 src->shrink (*this);
1625
1626 return !overrun;
1627 }
1628
1629 /* Begin writing buffer. */
1630
1631 void
1632 bytes_out::begin (bool need_crc)
1633 {
1634 if (need_crc)
1635 pos = 4;
1636 memory->grow (*this, 0, false);
1637 }
1638
1639 /* Finish writing buffer. Stream out to SINK as named section NAME.
1640 Return section number or 0 on failure. If CRC_PTR is true, crc
1641 the data. Otherwise it is a string section. */
1642
1643 unsigned
1644 bytes_out::end (elf_out *sink, unsigned name, unsigned *crc_ptr)
1645 {
1646 lengths[3] += pos;
1647 spans[3]++;
1648
1649 set_crc (crc_ptr);
1650 unsigned sec_num = sink->add (*this, !crc_ptr, name);
1651 memory->shrink (*this);
1652
1653 return sec_num;
1654 }
1655
1656 /* Close and open the file, without destroying it. */
1657
1658 void
1659 elf_in::freeze ()
1660 {
1661 gcc_checking_assert (!is_frozen ());
1662 #if MAPPED_READING
1663 if (munmap (hdr.buffer, hdr.pos) < 0)
1664 set_error (errno);
1665 #endif
1666 if (close (fd) < 0)
1667 set_error (errno);
1668 fd = -1;
1669 }
1670
1671 bool
1672 elf_in::defrost (const char *name)
1673 {
1674 gcc_checking_assert (is_frozen ());
1675 struct stat stat;
1676
1677 fd = open (name, O_RDONLY | O_CLOEXEC | O_BINARY);
1678 if (fd < 0 || fstat (fd, &stat) < 0)
1679 set_error (errno);
1680 else
1681 {
1682 bool ok = hdr.pos == unsigned (stat.st_size);
1683 #ifndef HOST_LACKS_INODE_NUMBERS
1684 if (device != stat.st_dev
1685 || inode != stat.st_ino)
1686 ok = false;
1687 #endif
1688 if (!ok)
1689 set_error (EMFILE);
1690 #if MAPPED_READING
1691 if (ok)
1692 {
1693 char *mapping = reinterpret_cast<char *>
1694 (mmap (NULL, hdr.pos, PROT_READ, MAP_SHARED, fd, 0));
1695 if (mapping == MAP_FAILED)
1696 fail:
1697 set_error (errno);
1698 else
1699 {
1700 if (madvise (mapping, hdr.pos, MADV_RANDOM))
1701 goto fail;
1702
1703 /* These buffers are never NULL in this case. */
1704 strtab.buffer = mapping + strtab.pos;
1705 sectab.buffer = mapping + sectab.pos;
1706 hdr.buffer = mapping;
1707 }
1708 }
1709 #endif
1710 }
1711
1712 return !get_error ();
1713 }
1714
1715 /* Read at current position into BUFFER. Return true on success. */
1716
1717 const char *
1718 elf_in::read (data *data, unsigned pos, unsigned length)
1719 {
1720 #if MAPPED_READING
1721 if (pos + length > hdr.pos)
1722 {
1723 set_error (EINVAL);
1724 return NULL;
1725 }
1726 #else
1727 if (pos != ~0u && lseek (fd, pos, SEEK_SET) < 0)
1728 {
1729 set_error (errno);
1730 return NULL;
1731 }
1732 #endif
1733 grow (*data, length);
1734 #if MAPPED_READING
1735 data->buffer = hdr.buffer + pos;
1736 #else
1737 if (::read (fd, data->buffer, data->size) != ssize_t (length))
1738 {
1739 set_error (errno);
1740 shrink (*data);
1741 return NULL;
1742 }
1743 #endif
1744
1745 return data->buffer;
1746 }
1747
1748 /* Read section SNUM of TYPE. Return section pointer or NULL on error. */
1749
1750 const elf::section *
1751 elf_in::find (unsigned snum, unsigned type)
1752 {
1753 const section *sec = get_section (snum);
1754 if (!snum || !sec || sec->type != type)
1755 return NULL;
1756 return sec;
1757 }
1758
1759 /* Find a section NAME and TYPE. Return section number, or zero on
1760 failure. */
1761
1762 unsigned
1763 elf_in::find (const char *sname)
1764 {
1765 for (unsigned pos = sectab.size; pos -= sizeof (section); )
1766 {
1767 const section *sec
1768 = reinterpret_cast<const section *> (&sectab.buffer[pos]);
1769
1770 if (0 == strcmp (sname, name (sec->name)))
1771 return pos / sizeof (section);
1772 }
1773
1774 return 0;
1775 }
1776
1777 /* Begin reading file. Verify header. Pull in section and string
1778 tables. Return true on success. */
1779
1780 bool
1781 elf_in::begin (location_t loc)
1782 {
1783 if (!parent::begin ())
1784 return false;
1785
1786 struct stat stat;
1787 unsigned size = 0;
1788 if (!fstat (fd, &stat))
1789 {
1790 #if !defined (HOST_LACKS_INODE_NUMBERS)
1791 device = stat.st_dev;
1792 inode = stat.st_ino;
1793 #endif
1794 /* Never generate files > 4GB, check we've not been given one. */
1795 if (stat.st_size == unsigned (stat.st_size))
1796 size = unsigned (stat.st_size);
1797 }
1798
1799 #if MAPPED_READING
1800 /* MAP_SHARED so that the file is backing store. If someone else
1801 concurrently writes it, they're wrong. */
1802 void *mapping = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0);
1803 if (mapping == MAP_FAILED)
1804 {
1805 fail:
1806 set_error (errno);
1807 return false;
1808 }
1809 /* We'll be hopping over this randomly. Some systems declare the
1810 first parm as char *, and other declare it as void *. */
1811 if (madvise (reinterpret_cast <char *> (mapping), size, MADV_RANDOM))
1812 goto fail;
1813
1814 hdr.buffer = (char *)mapping;
1815 #else
1816 read (&hdr, 0, sizeof (header));
1817 #endif
1818 hdr.pos = size; /* Record size of the file. */
1819
1820 const header *h = reinterpret_cast<const header *> (hdr.buffer);
1821 if (!h)
1822 return false;
1823
1824 if (h->ident.magic[0] != 0x7f
1825 || h->ident.magic[1] != 'E'
1826 || h->ident.magic[2] != 'L'
1827 || h->ident.magic[3] != 'F')
1828 {
1829 error_at (loc, "not Encapsulated Lazy Records of Named Declarations");
1830 failed:
1831 shrink (hdr);
1832 return false;
1833 }
1834
1835 /* We expect a particular format -- the ELF is not intended to be
1836 distributable. */
1837 if (h->ident.klass != MY_CLASS
1838 || h->ident.data != MY_ENDIAN
1839 || h->ident.version != EV_CURRENT
1840 || h->type != ET_NONE
1841 || h->machine != EM_NONE
1842 || h->ident.osabi != OSABI_NONE)
1843 {
1844 error_at (loc, "unexpected encapsulation format or type");
1845 goto failed;
1846 }
1847
1848 int e = -1;
1849 if (!h->shoff || h->shentsize != sizeof (section))
1850 {
1851 malformed:
1852 set_error (e);
1853 error_at (loc, "encapsulation is malformed");
1854 goto failed;
1855 }
1856
1857 unsigned strndx = h->shstrndx;
1858 unsigned shnum = h->shnum;
1859 if (shnum == SHN_XINDEX)
1860 {
1861 if (!read (&sectab, h->shoff, sizeof (section)))
1862 {
1863 section_table_fail:
1864 e = errno;
1865 goto malformed;
1866 }
1867 shnum = get_section (0)->size;
1868 /* Freeing does mean we'll re-read it in the case we're not
1869 mapping, but this is going to be rare. */
1870 shrink (sectab);
1871 }
1872
1873 if (!shnum)
1874 goto malformed;
1875
1876 if (!read (&sectab, h->shoff, shnum * sizeof (section)))
1877 goto section_table_fail;
1878
1879 if (strndx == SHN_XINDEX)
1880 strndx = get_section (0)->link;
1881
1882 if (!read (&strtab, find (strndx, SHT_STRTAB)))
1883 goto malformed;
1884
1885 /* The string table should be at least one byte, with NUL chars
1886 at either end. */
1887 if (!(strtab.size && !strtab.buffer[0]
1888 && !strtab.buffer[strtab.size - 1]))
1889 goto malformed;
1890
1891 #if MAPPED_READING
1892 /* Record the offsets of the section and string tables. */
1893 sectab.pos = h->shoff;
1894 strtab.pos = shnum * sizeof (section);
1895 #else
1896 shrink (hdr);
1897 #endif
1898
1899 return true;
1900 }
1901
1902 /* Create a new mapping. */
1903
1904 #if MAPPED_WRITING
1905 void
1906 elf_out::create_mapping (unsigned ext, bool extending)
1907 {
1908 /* A wrapper around posix_fallocate, falling back to ftruncate
1909 if the underlying filesystem does not support the operation. */
1910 auto allocate = [](int fd, off_t offset, off_t length)
1911 {
1912 #ifdef HAVE_POSIX_FALLOCATE
1913 int result = posix_fallocate (fd, offset, length);
1914 if (result != EINVAL)
1915 return result == 0;
1916 /* Not supported by the underlying filesystem, fallback to ftruncate. */
1917 #endif
1918 return ftruncate (fd, offset + length) == 0;
1919 };
1920
1921 void *mapping = MAP_FAILED;
1922 if (extending && ext < 1024 * 1024)
1923 {
1924 if (allocate (fd, offset, ext * 2))
1925 mapping = mmap (NULL, ext * 2, PROT_READ | PROT_WRITE,
1926 MAP_SHARED, fd, offset);
1927 if (mapping != MAP_FAILED)
1928 ext *= 2;
1929 }
1930 if (mapping == MAP_FAILED)
1931 {
1932 if (!extending || allocate (fd, offset, ext))
1933 mapping = mmap (NULL, ext, PROT_READ | PROT_WRITE,
1934 MAP_SHARED, fd, offset);
1935 if (mapping == MAP_FAILED)
1936 {
1937 set_error (errno);
1938 mapping = NULL;
1939 ext = 0;
1940 }
1941 }
1942 hdr.buffer = (char *)mapping;
1943 extent = ext;
1944 }
1945 #endif
1946
1947 /* Flush out the current mapping. */
1948
1949 #if MAPPED_WRITING
1950 void
1951 elf_out::remove_mapping ()
1952 {
1953 if (hdr.buffer)
1954 {
1955 /* MS_ASYNC dtrt with the removed mapping, including a
1956 subsequent overlapping remap. */
1957 if (msync (hdr.buffer, extent, MS_ASYNC)
1958 || munmap (hdr.buffer, extent))
1959 /* We're somewhat screwed at this point. */
1960 set_error (errno);
1961 }
1962
1963 hdr.buffer = NULL;
1964 }
1965 #endif
1966
1967 /* Grow a mapping of PTR to be NEEDED bytes long. This gets
1968 interesting if the new size grows the EXTENT. */
1969
1970 char *
1971 elf_out::grow (char *data, unsigned needed)
1972 {
1973 if (!data)
1974 {
1975 /* First allocation, check we're aligned. */
1976 gcc_checking_assert (!(pos & (SECTION_ALIGN - 1)));
1977 #if MAPPED_WRITING
1978 data = hdr.buffer + (pos - offset);
1979 #endif
1980 }
1981
1982 #if MAPPED_WRITING
1983 unsigned off = data - hdr.buffer;
1984 if (off + needed > extent)
1985 {
1986 /* We need to grow the mapping. */
1987 unsigned lwm = off & ~(page_size - 1);
1988 unsigned hwm = (off + needed + page_size - 1) & ~(page_size - 1);
1989
1990 gcc_checking_assert (hwm > extent);
1991
1992 remove_mapping ();
1993
1994 offset += lwm;
1995 create_mapping (extent < hwm - lwm ? hwm - lwm : extent);
1996
1997 data = hdr.buffer + (off - lwm);
1998 }
1999 #else
2000 data = allocator::grow (data, needed);
2001 #endif
2002
2003 return data;
2004 }
2005
2006 #if MAPPED_WRITING
2007 /* Shrinking is a NOP. */
2008 void
2009 elf_out::shrink (char *)
2010 {
2011 }
2012 #endif
2013
2014 /* Write S of length L to the strtab buffer. L must include the ending
2015 NUL, if that's what you want. */
2016
2017 unsigned
2018 elf_out::strtab_write (const char *s, unsigned l)
2019 {
2020 if (strtab.pos + l > strtab.size)
2021 data::simple_memory.grow (strtab, strtab.pos + l, false);
2022 memcpy (strtab.buffer + strtab.pos, s, l);
2023 unsigned res = strtab.pos;
2024 strtab.pos += l;
2025 return res;
2026 }
2027
2028 /* Write qualified name of decl. INNER >0 if this is a definition, <0
2029 if this is a qualifier of an outer name. */
2030
2031 void
2032 elf_out::strtab_write (tree decl, int inner)
2033 {
2034 tree ctx = CP_DECL_CONTEXT (decl);
2035 if (TYPE_P (ctx))
2036 ctx = TYPE_NAME (ctx);
2037 if (ctx != global_namespace)
2038 strtab_write (ctx, -1);
2039
2040 tree name = DECL_NAME (decl);
2041 if (!name)
2042 name = DECL_ASSEMBLER_NAME_RAW (decl);
2043 strtab_write (IDENTIFIER_POINTER (name), IDENTIFIER_LENGTH (name));
2044
2045 if (inner)
2046 strtab_write (&"::{}"[inner+1], 2);
2047 }
2048
2049 /* Map IDENTIFIER IDENT to strtab offset. Inserts into strtab if not
2050 already there. */
2051
2052 unsigned
2053 elf_out::name (tree ident)
2054 {
2055 unsigned res = 0;
2056 if (ident)
2057 {
2058 bool existed;
2059 int *slot = &identtab.get_or_insert (ident, &existed);
2060 if (!existed)
2061 *slot = strtab_write (IDENTIFIER_POINTER (ident),
2062 IDENTIFIER_LENGTH (ident) + 1);
2063 res = *slot;
2064 }
2065 return res;
2066 }
2067
2068 /* Map LITERAL to strtab offset. Does not detect duplicates and
2069 expects LITERAL to remain live until strtab is written out. */
2070
2071 unsigned
2072 elf_out::name (const char *literal)
2073 {
2074 return strtab_write (literal, strlen (literal) + 1);
2075 }
2076
2077 /* Map a DECL's qualified name to strtab offset. Does not detect
2078 duplicates. */
2079
2080 unsigned
2081 elf_out::qualified_name (tree decl, bool is_defn)
2082 {
2083 gcc_checking_assert (DECL_P (decl) && decl != global_namespace);
2084 unsigned result = strtab.pos;
2085
2086 strtab_write (decl, is_defn);
2087 strtab_write ("", 1);
2088
2089 return result;
2090 }
2091
2092 /* Add section to file. Return section number. TYPE & NAME identify
2093 the section. OFF and SIZE identify the file location of its
2094 data. FLAGS contains additional info. */
2095
2096 unsigned
2097 elf_out::add (unsigned type, unsigned name, unsigned off, unsigned size,
2098 unsigned flags)
2099 {
2100 gcc_checking_assert (!(off & (SECTION_ALIGN - 1)));
2101 if (sectab.pos + sizeof (section) > sectab.size)
2102 data::simple_memory.grow (sectab, sectab.pos + sizeof (section), false);
2103 section *sec = reinterpret_cast<section *> (sectab.buffer + sectab.pos);
2104 memset (sec, 0, sizeof (section));
2105 sec->type = type;
2106 sec->flags = flags;
2107 sec->name = name;
2108 sec->offset = off;
2109 sec->size = size;
2110 if (flags & SHF_STRINGS)
2111 sec->entsize = 1;
2112
2113 unsigned res = sectab.pos;
2114 sectab.pos += sizeof (section);
2115 return res / sizeof (section);
2116 }
2117
2118 /* Pad to the next alignment boundary, then write BUFFER to disk.
2119 Return the position of the start of the write, or zero on failure. */
2120
2121 unsigned
2122 elf_out::write (const data &buffer)
2123 {
2124 #if MAPPED_WRITING
2125 /* HDR is always mapped. */
2126 if (&buffer != &hdr)
2127 {
2128 bytes_out out (this);
2129 grow (out, buffer.pos, true);
2130 if (out.buffer)
2131 memcpy (out.buffer, buffer.buffer, buffer.pos);
2132 shrink (out);
2133 }
2134 else
2135 /* We should have been aligned during the first allocation. */
2136 gcc_checking_assert (!(pos & (SECTION_ALIGN - 1)));
2137 #else
2138 if (::write (fd, buffer.buffer, buffer.pos) != ssize_t (buffer.pos))
2139 {
2140 set_error (errno);
2141 return 0;
2142 }
2143 #endif
2144 unsigned res = pos;
2145 pos += buffer.pos;
2146
2147 if (unsigned padding = -pos & (SECTION_ALIGN - 1))
2148 {
2149 #if !MAPPED_WRITING
2150 /* Align the section on disk, should help the necessary copies.
2151 fseeking to extend is non-portable. */
2152 static char zero[SECTION_ALIGN];
2153 if (::write (fd, &zero, padding) != ssize_t (padding))
2154 set_error (errno);
2155 #endif
2156 pos += padding;
2157 }
2158 return res;
2159 }
2160
2161 /* Write a streaming buffer. It must be using us as an allocator. */
2162
2163 #if MAPPED_WRITING
2164 unsigned
2165 elf_out::write (const bytes_out &buf)
2166 {
2167 gcc_checking_assert (buf.memory == this);
2168 /* A directly mapped buffer. */
2169 gcc_checking_assert (buf.buffer - hdr.buffer >= 0
2170 && buf.buffer - hdr.buffer + buf.size <= extent);
2171 unsigned res = pos;
2172 pos += buf.pos;
2173
2174 /* Align up. We're not going to advance into the next page. */
2175 pos += -pos & (SECTION_ALIGN - 1);
2176
2177 return res;
2178 }
2179 #endif
2180
2181 /* Write data and add section. STRING_P is true for a string
2182 section, false for PROGBITS. NAME identifies the section (0 is the
2183 empty name). DATA is the contents. Return section number or 0 on
2184 failure (0 is the undef section). */
2185
2186 unsigned
2187 elf_out::add (const bytes_out &data, bool string_p, unsigned name)
2188 {
2189 unsigned off = write (data);
2190
2191 return add (string_p ? SHT_STRTAB : SHT_PROGBITS, name,
2192 off, data.pos, string_p ? SHF_STRINGS : SHF_NONE);
2193 }
2194
2195 /* Begin writing the file. Initialize the section table and write an
2196 empty header. Return false on failure. */
2197
2198 bool
2199 elf_out::begin ()
2200 {
2201 if (!parent::begin ())
2202 return false;
2203
2204 /* Let the allocators pick a default. */
2205 data::simple_memory.grow (strtab, 0, false);
2206 data::simple_memory.grow (sectab, 0, false);
2207
2208 /* The string table starts with an empty string. */
2209 name ("");
2210
2211 /* Create the UNDEF section. */
2212 add (SHT_NONE);
2213
2214 #if MAPPED_WRITING
2215 /* Start a mapping. */
2216 create_mapping (EXPERIMENT (page_size,
2217 (32767 + page_size) & ~(page_size - 1)));
2218 if (!hdr.buffer)
2219 return false;
2220 #endif
2221
2222 /* Write an empty header. */
2223 grow (hdr, sizeof (header), true);
2224 header *h = reinterpret_cast<header *> (hdr.buffer);
2225 memset (h, 0, sizeof (header));
2226 hdr.pos = hdr.size;
2227 write (hdr);
2228 return !get_error ();
2229 }
2230
2231 /* Finish writing the file. Write out the string & section tables.
2232 Fill in the header. Return true on error. */
2233
2234 bool
2235 elf_out::end ()
2236 {
2237 if (fd >= 0)
2238 {
2239 /* Write the string table. */
2240 unsigned strnam = name (".strtab");
2241 unsigned stroff = write (strtab);
2242 unsigned strndx = add (SHT_STRTAB, strnam, stroff, strtab.pos,
2243 SHF_STRINGS);
2244
2245 /* Store escape values in section[0]. */
2246 if (strndx >= SHN_LORESERVE)
2247 {
2248 reinterpret_cast<section *> (sectab.buffer)->link = strndx;
2249 strndx = SHN_XINDEX;
2250 }
2251 unsigned shnum = sectab.pos / sizeof (section);
2252 if (shnum >= SHN_LORESERVE)
2253 {
2254 reinterpret_cast<section *> (sectab.buffer)->size = shnum;
2255 shnum = SHN_XINDEX;
2256 }
2257
2258 unsigned shoff = write (sectab);
2259
2260 #if MAPPED_WRITING
2261 if (offset)
2262 {
2263 remove_mapping ();
2264 offset = 0;
2265 create_mapping ((sizeof (header) + page_size - 1) & ~(page_size - 1),
2266 false);
2267 }
2268 unsigned length = pos;
2269 #else
2270 if (lseek (fd, 0, SEEK_SET) < 0)
2271 set_error (errno);
2272 #endif
2273 /* Write header. */
2274 if (!get_error ())
2275 {
2276 /* Write the correct header now. */
2277 header *h = reinterpret_cast<header *> (hdr.buffer);
2278 h->ident.magic[0] = 0x7f;
2279 h->ident.magic[1] = 'E'; /* Elrond */
2280 h->ident.magic[2] = 'L'; /* is an */
2281 h->ident.magic[3] = 'F'; /* elf. */
2282 h->ident.klass = MY_CLASS;
2283 h->ident.data = MY_ENDIAN;
2284 h->ident.version = EV_CURRENT;
2285 h->ident.osabi = OSABI_NONE;
2286 h->type = ET_NONE;
2287 h->machine = EM_NONE;
2288 h->version = EV_CURRENT;
2289 h->shoff = shoff;
2290 h->ehsize = sizeof (header);
2291 h->shentsize = sizeof (section);
2292 h->shnum = shnum;
2293 h->shstrndx = strndx;
2294
2295 pos = 0;
2296 write (hdr);
2297 }
2298
2299 #if MAPPED_WRITING
2300 remove_mapping ();
2301 if (ftruncate (fd, length))
2302 set_error (errno);
2303 #endif
2304 }
2305
2306 data::simple_memory.shrink (sectab);
2307 data::simple_memory.shrink (strtab);
2308
2309 return parent::end ();
2310 }
2311
2312 /********************************************************************/
2313
2314 /* A dependency set. This is used during stream out to determine the
2315 connectivity of the graph. Every namespace-scope declaration that
2316 needs writing has a depset. The depset is filled with the (depsets
2317 of) declarations within this module that it references. For a
2318 declaration that'll generally be named types. For definitions
2319 it'll also be declarations in the body.
2320
2321 From that we can convert the graph to a DAG, via determining the
2322 Strongly Connected Clusters. Each cluster is streamed
2323 independently, and thus we achieve lazy loading.
2324
2325 Other decls that get a depset are namespaces themselves and
2326 unnameable declarations. */
2327
2328 class depset {
2329 private:
2330 tree entity; /* Entity, or containing namespace. */
2331 uintptr_t discriminator; /* Flags or identifier. */
2332
2333 public:
2334 /* The kinds of entity the depset could describe. The ordering is
2335 significant, see entity_kind_name. */
2336 enum entity_kind
2337 {
2338 EK_DECL, /* A decl. */
2339 EK_SPECIALIZATION, /* A specialization. */
2340 EK_PARTIAL, /* A partial specialization. */
2341 EK_USING, /* A using declaration (at namespace scope). */
2342 EK_NAMESPACE, /* A namespace. */
2343 EK_REDIRECT, /* Redirect to a template_decl. */
2344 EK_EXPLICIT_HWM,
2345 EK_BINDING = EK_EXPLICIT_HWM, /* Implicitly encoded. */
2346 EK_FOR_BINDING, /* A decl being inserted for a binding. */
2347 EK_INNER_DECL, /* A decl defined outside of its imported
2348 context. */
2349 EK_DIRECT_HWM = EK_PARTIAL + 1,
2350
2351 EK_BITS = 3 /* Only need to encode below EK_EXPLICIT_HWM. */
2352 };
2353
2354 private:
2355 /* Placement of bit fields in discriminator. */
2356 enum disc_bits
2357 {
2358 DB_ZERO_BIT, /* Set to disambiguate identifier from flags */
2359 DB_SPECIAL_BIT, /* First dep slot is special. */
2360 DB_KIND_BIT, /* Kind of the entity. */
2361 DB_KIND_BITS = EK_BITS,
2362 DB_DEFN_BIT = DB_KIND_BIT + DB_KIND_BITS,
2363 DB_IS_PENDING_BIT, /* Is a maybe-pending entity. */
2364 DB_TU_LOCAL_BIT, /* It is a TU-local entity. */
2365 DB_REFS_TU_LOCAL_BIT, /* Refers to a TU-local entity (but is not
2366 necessarily an exposure.) */
2367 DB_EXPOSURE_BIT, /* Exposes a TU-local entity. */
2368 DB_IMPORTED_BIT, /* An imported entity. */
2369 DB_UNREACHED_BIT, /* A yet-to-be reached entity. */
2370 DB_MAYBE_RECURSIVE_BIT, /* An entity maybe in a recursive cluster. */
2371 DB_ENTRY_BIT, /* The first reached recursive dep. */
2372 DB_HIDDEN_BIT, /* A hidden binding. */
2373 /* The following bits are not independent, but enumerating them is
2374 awkward. */
2375 DB_TYPE_SPEC_BIT, /* Specialization in the type table. */
2376 DB_FRIEND_SPEC_BIT, /* An instantiated template friend. */
2377 };
2378
2379 public:
2380 /* The first slot is special for EK_SPECIALIZATIONS it is a
2381 spec_entry pointer. It is not relevant for the SCC
2382 determination. */
2383 vec<depset *> deps; /* Depsets we reference. */
2384
2385 public:
2386 unsigned cluster; /* Strongly connected cluster, later entity number */
2387 unsigned section; /* Section written to. */
2388 /* During SCC construction, section is lowlink, until the depset is
2389 removed from the stack. See Tarjan algorithm for details. */
2390
2391 private:
2392 /* Construction via factories. Destruction via hash traits. */
2393 depset (tree entity);
2394 ~depset ();
2395
2396 public:
2397 static depset *make_binding (tree, tree);
2398 static depset *make_entity (tree, entity_kind, bool = false);
2399 /* Late setting a binding name -- /then/ insert into hash! */
2400 inline void set_binding_name (tree name)
2401 {
2402 gcc_checking_assert (!get_name ());
2403 discriminator = reinterpret_cast<uintptr_t> (name);
2404 }
2405
2406 private:
2407 template<unsigned I> void set_flag_bit ()
2408 {
2409 gcc_checking_assert (I < 2 || !is_binding ());
2410 discriminator |= 1u << I;
2411 }
2412 template<unsigned I> void clear_flag_bit ()
2413 {
2414 gcc_checking_assert (I < 2 || !is_binding ());
2415 discriminator &= ~(1u << I);
2416 }
2417 template<unsigned I> bool get_flag_bit () const
2418 {
2419 gcc_checking_assert (I < 2 || !is_binding ());
2420 return bool ((discriminator >> I) & 1);
2421 }
2422
2423 public:
2424 bool is_binding () const
2425 {
2426 return !get_flag_bit<DB_ZERO_BIT> ();
2427 }
2428 entity_kind get_entity_kind () const
2429 {
2430 if (is_binding ())
2431 return EK_BINDING;
2432 return entity_kind ((discriminator >> DB_KIND_BIT) & ((1u << EK_BITS) - 1));
2433 }
2434 const char *entity_kind_name () const;
2435
2436 public:
2437 bool has_defn () const
2438 {
2439 /* Never consider TU-local entities as having definitions, since
2440 we will never be accessing them from importers anyway. */
2441 return get_flag_bit<DB_DEFN_BIT> () && !is_tu_local ();
2442 }
2443
2444 public:
2445 /* This entity might be found other than by namespace-scope lookup;
2446 see module_state::write_pendings for more details. */
2447 bool is_pending_entity () const
2448 {
2449 return (get_entity_kind () == EK_SPECIALIZATION
2450 || get_entity_kind () == EK_PARTIAL
2451 || (get_entity_kind () == EK_DECL
2452 && get_flag_bit<DB_IS_PENDING_BIT> ()));
2453 }
2454 public:
2455 bool is_tu_local () const
2456 {
2457 return get_flag_bit<DB_TU_LOCAL_BIT> ();
2458 }
2459 bool refs_tu_local () const
2460 {
2461 return get_flag_bit<DB_REFS_TU_LOCAL_BIT> ();
2462 }
2463 bool is_exposure () const
2464 {
2465 return get_flag_bit<DB_EXPOSURE_BIT> ();
2466 }
2467 bool is_import () const
2468 {
2469 return get_flag_bit<DB_IMPORTED_BIT> ();
2470 }
2471 bool is_unreached () const
2472 {
2473 return get_flag_bit<DB_UNREACHED_BIT> ();
2474 }
2475 bool is_hidden () const
2476 {
2477 return get_flag_bit<DB_HIDDEN_BIT> ();
2478 }
2479 bool is_maybe_recursive () const
2480 {
2481 return get_flag_bit<DB_MAYBE_RECURSIVE_BIT> ();
2482 }
2483 bool is_entry () const
2484 {
2485 return get_flag_bit<DB_ENTRY_BIT> ();
2486 }
2487 bool is_type_spec () const
2488 {
2489 return get_flag_bit<DB_TYPE_SPEC_BIT> ();
2490 }
2491 bool is_friend_spec () const
2492 {
2493 return get_flag_bit<DB_FRIEND_SPEC_BIT> ();
2494 }
2495
2496 public:
2497 /* We set these bit outside of depset. */
2498 void set_hidden_binding ()
2499 {
2500 set_flag_bit<DB_HIDDEN_BIT> ();
2501 }
2502 void clear_hidden_binding ()
2503 {
2504 clear_flag_bit<DB_HIDDEN_BIT> ();
2505 }
2506
2507 public:
2508 bool is_special () const
2509 {
2510 return get_flag_bit<DB_SPECIAL_BIT> ();
2511 }
2512 void set_special ()
2513 {
2514 set_flag_bit<DB_SPECIAL_BIT> ();
2515 }
2516
2517 public:
2518 tree get_entity () const
2519 {
2520 return entity;
2521 }
2522 tree get_name () const
2523 {
2524 gcc_checking_assert (is_binding ());
2525 return reinterpret_cast <tree> (discriminator);
2526 }
2527
2528 public:
2529 /* Traits for a hash table of pointers to bindings. */
2530 struct traits {
2531 /* Each entry is a pointer to a depset. */
2532 typedef depset *value_type;
2533 /* We lookup by container:maybe-identifier pair. */
2534 typedef std::pair<tree,tree> compare_type;
2535
2536 static const bool empty_zero_p = true;
2537
2538 /* hash and equality for compare_type. */
2539 inline static hashval_t hash (const compare_type &p)
2540 {
2541 hashval_t h = pointer_hash<tree_node>::hash (p.first);
2542 if (p.second)
2543 {
2544 hashval_t nh = IDENTIFIER_HASH_VALUE (p.second);
2545 h = iterative_hash_hashval_t (h, nh);
2546 }
2547 return h;
2548 }
2549 inline static bool equal (const value_type b, const compare_type &p)
2550 {
2551 if (b->entity != p.first)
2552 return false;
2553
2554 if (p.second)
2555 return b->discriminator == reinterpret_cast<uintptr_t> (p.second);
2556 else
2557 return !b->is_binding ();
2558 }
2559
2560 /* (re)hasher for a binding itself. */
2561 inline static hashval_t hash (const value_type b)
2562 {
2563 hashval_t h = pointer_hash<tree_node>::hash (b->entity);
2564 if (b->is_binding ())
2565 {
2566 hashval_t nh = IDENTIFIER_HASH_VALUE (b->get_name ());
2567 h = iterative_hash_hashval_t (h, nh);
2568 }
2569 return h;
2570 }
2571
2572 /* Empty via NULL. */
2573 static inline void mark_empty (value_type &p) {p = NULL;}
2574 static inline bool is_empty (value_type p) {return !p;}
2575
2576 /* Nothing is deletable. Everything is insertable. */
2577 static bool is_deleted (value_type) { return false; }
2578 static void mark_deleted (value_type) { gcc_unreachable (); }
2579
2580 /* We own the entities in the hash table. */
2581 static void remove (value_type p)
2582 {
2583 delete (p);
2584 }
2585 };
2586
2587 public:
2588 class hash : public hash_table<traits> {
2589 typedef traits::compare_type key_t;
2590 typedef hash_table<traits> parent;
2591
2592 public:
2593 vec<depset *> worklist; /* Worklist of decls to walk. */
2594 hash *chain; /* Original table. */
2595 depset *current; /* Current depset being depended. */
2596 unsigned section; /* When writing out, the section. */
2597 bool reached_unreached; /* We reached an unreached entity. */
2598 bool writing_merge_key; /* We're writing merge key information. */
2599 bool ignore_tu_local; /* In a context where referencing a TU-local
2600 entity is not an exposure. */
2601
2602 public:
2603 hash (size_t size, hash *c = NULL)
2604 : parent (size), chain (c), current (NULL), section (0),
2605 reached_unreached (false), writing_merge_key (false),
2606 ignore_tu_local (false)
2607 {
2608 worklist.create (size);
2609 }
2610 ~hash ()
2611 {
2612 worklist.release ();
2613 }
2614
2615 public:
2616 bool is_key_order () const
2617 {
2618 return chain != NULL;
2619 }
2620
2621 private:
2622 depset **entity_slot (tree entity, bool = true);
2623 depset **binding_slot (tree ctx, tree name, bool = true);
2624 depset *maybe_add_declaration (tree decl);
2625
2626 public:
2627 depset *find_dependency (tree entity);
2628 depset *find_binding (tree ctx, tree name);
2629 depset *make_dependency (tree decl, entity_kind);
2630 void add_dependency (depset *);
2631
2632 public:
2633 void add_mergeable (depset *);
2634 depset *add_dependency (tree decl, entity_kind);
2635 void add_namespace_context (depset *, tree ns);
2636
2637 private:
2638 bool has_tu_local_tmpl_arg (tree decl, tree args, bool explain);
2639 bool is_tu_local_entity (tree decl, bool explain = false);
2640 bool is_tu_local_value (tree decl, tree expr, bool explain = false);
2641
2642 private:
2643 static bool add_binding_entity (tree, WMB_Flags, void *);
2644
2645 public:
2646 bool add_namespace_entities (tree ns, bitmap partitions);
2647 void add_specializations (bool decl_p);
2648 void add_partial_entities (vec<tree, va_gc> *);
2649 void add_class_entities (vec<tree, va_gc> *);
2650
2651 private:
2652 void add_deduction_guides (tree decl);
2653
2654 public:
2655 void find_dependencies (module_state *);
2656 bool finalize_dependencies ();
2657 vec<depset *> connect ();
2658 };
2659
2660 public:
2661 struct tarjan {
2662 vec<depset *> result;
2663 vec<depset *> stack;
2664 unsigned index;
2665
2666 tarjan (unsigned size)
2667 : index (0)
2668 {
2669 result.create (size);
2670 stack.create (50);
2671 }
2672 ~tarjan ()
2673 {
2674 gcc_assert (!stack.length ());
2675 stack.release ();
2676 }
2677
2678 public:
2679 void connect (depset *);
2680 };
2681 };
2682
2683 inline
2684 depset::depset (tree entity)
2685 :entity (entity), discriminator (0), cluster (0), section (0)
2686 {
2687 deps.create (0);
2688 }
2689
2690 inline
2691 depset::~depset ()
2692 {
2693 deps.release ();
2694 }
2695
2696 const char *
2697 depset::entity_kind_name () const
2698 {
2699 /* Same order as entity_kind. */
2700 static const char *const names[] =
2701 {"decl", "specialization", "partial", "using",
2702 "namespace", "redirect", "binding"};
2703 entity_kind kind = get_entity_kind ();
2704 gcc_checking_assert (kind < ARRAY_SIZE (names));
2705 return names[kind];
2706 }
2707
2708 /* Create a depset for a namespace binding NS::NAME. */
2709
2710 depset *depset::make_binding (tree ns, tree name)
2711 {
2712 depset *binding = new depset (ns);
2713
2714 binding->discriminator = reinterpret_cast <uintptr_t> (name);
2715
2716 return binding;
2717 }
2718
2719 depset *depset::make_entity (tree entity, entity_kind ek, bool is_defn)
2720 {
2721 depset *r = new depset (entity);
2722
2723 r->discriminator = ((1 << DB_ZERO_BIT)
2724 | (ek << DB_KIND_BIT)
2725 | is_defn << DB_DEFN_BIT);
2726
2727 return r;
2728 }
2729
2730 class pending_key
2731 {
2732 public:
2733 tree ns;
2734 tree id;
2735 };
2736
2737 template<>
2738 struct default_hash_traits<pending_key>
2739 {
2740 using value_type = pending_key;
2741
2742 static const bool empty_zero_p = false;
2743 static hashval_t hash (const value_type &k)
2744 {
2745 hashval_t h = IDENTIFIER_HASH_VALUE (k.id);
2746 h = iterative_hash_hashval_t (DECL_UID (k.ns), h);
2747
2748 return h;
2749 }
2750 static bool equal (const value_type &k, const value_type &l)
2751 {
2752 return k.ns == l.ns && k.id == l.id;
2753 }
2754 static void mark_empty (value_type &k)
2755 {
2756 k.ns = k.id = NULL_TREE;
2757 }
2758 static void mark_deleted (value_type &k)
2759 {
2760 k.ns = NULL_TREE;
2761 gcc_checking_assert (k.id);
2762 }
2763 static bool is_empty (const value_type &k)
2764 {
2765 return k.ns == NULL_TREE && k.id == NULL_TREE;
2766 }
2767 static bool is_deleted (const value_type &k)
2768 {
2769 return k.ns == NULL_TREE && k.id != NULL_TREE;
2770 }
2771 static void remove (value_type &)
2772 {
2773 }
2774 };
2775
2776 typedef hash_map<pending_key, auto_vec<unsigned>> pending_map_t;
2777
2778 /* Not-loaded entities that are keyed to a namespace-scope
2779 identifier. See module_state::write_pendings for details. */
2780 pending_map_t *pending_table;
2781
2782 /* Decls that need some post processing once a batch of lazy loads has
2783 completed. */
2784 vec<tree, va_heap, vl_embed> *post_load_decls;
2785
2786 /* Some entities are keyed to another entitity for ODR purposes.
2787 For example, at namespace scope, 'inline auto var = []{};', that
2788 lambda is keyed to 'var', and follows its ODRness. */
2789 typedef hash_map<tree, auto_vec<tree>> keyed_map_t;
2790 static keyed_map_t *keyed_table;
2791
2792 static tree get_keyed_decl_scope (tree);
2793
2794 /* Instantiations of temploid friends imported from another module
2795 need to be attached to the same module as the temploid. This maps
2796 these decls to the temploid they are instantiated from, as there is
2797 no other easy way to get this information. */
2798 static GTY((cache)) decl_tree_cache_map *imported_temploid_friends;
2799
2800 /********************************************************************/
2801 /* Tree streaming. The tree streaming is very specific to the tree
2802 structures themselves. A tag indicates the kind of tree being
2803 streamed. -ve tags indicate backreferences to already-streamed
2804 trees. Backreferences are auto-numbered. */
2805
2806 /* Tree tags. */
2807 enum tree_tag {
2808 tt_null, /* NULL_TREE. */
2809 tt_tu_local, /* A TU-local entity. */
2810 tt_fixed, /* Fixed vector index. */
2811
2812 tt_node, /* By-value node. */
2813 tt_decl, /* By-value mergeable decl. */
2814 tt_tpl_parm, /* Template parm. */
2815
2816 /* The ordering of the following 4 is relied upon in
2817 trees_out::tree_node. */
2818 tt_id, /* Identifier node. */
2819 tt_conv_id, /* Conversion operator name. */
2820 tt_anon_id, /* Anonymous name. */
2821 tt_lambda_id, /* Lambda name. */
2822
2823 tt_typedef_type, /* A (possibly implicit) typedefed type. */
2824 tt_derived_type, /* A type derived from another type. */
2825 tt_variant_type, /* A variant of another type. */
2826
2827 tt_tinfo_var, /* Typeinfo object. */
2828 tt_tinfo_typedef, /* Typeinfo typedef. */
2829 tt_ptrmem_type, /* Pointer to member type. */
2830 tt_nttp_var, /* NTTP_OBJECT VAR_DECL. */
2831
2832 tt_parm, /* Function parameter or result. */
2833 tt_enum_value, /* An enum value. */
2834 tt_enum_decl, /* An enum decl. */
2835 tt_data_member, /* Data member/using-decl. */
2836
2837 tt_binfo, /* A BINFO. */
2838 tt_vtable, /* A vtable. */
2839 tt_thunk, /* A thunk. */
2840 tt_clone_ref,
2841
2842 tt_entity, /* A extra-cluster entity. */
2843
2844 tt_template, /* The TEMPLATE_RESULT of a template. */
2845 };
2846
2847 enum walk_kind {
2848 WK_none, /* No walk to do (a back- or fixed-ref happened). */
2849 WK_normal, /* Normal walk (by-name if possible). */
2850
2851 WK_value, /* By-value walk. */
2852 };
2853
2854 enum merge_kind
2855 {
2856 MK_unique, /* Known unique. */
2857 MK_named, /* Found by CTX, NAME + maybe_arg types etc. */
2858 MK_field, /* Found by CTX and index on TYPE_FIELDS */
2859 MK_vtable, /* Found by CTX and index on TYPE_VTABLES */
2860 MK_as_base, /* Found by CTX. */
2861
2862 MK_partial,
2863
2864 MK_enum, /* Found by CTX, & 1stMemberNAME. */
2865 MK_keyed, /* Found by key & index. */
2866 MK_local_type, /* Found by CTX, index. */
2867
2868 MK_friend_spec, /* Like named, but has a tmpl & args too. */
2869 MK_local_friend, /* Found by CTX, index. */
2870
2871 MK_indirect_lwm = MK_enum,
2872
2873 /* Template specialization kinds below. These are all found via
2874 primary template and specialization args. */
2875 MK_template_mask = 0x10, /* A template specialization. */
2876
2877 MK_tmpl_decl_mask = 0x4, /* In decl table. */
2878
2879 MK_tmpl_tmpl_mask = 0x1, /* We want TEMPLATE_DECL. */
2880
2881 MK_type_spec = MK_template_mask,
2882 MK_decl_spec = MK_template_mask | MK_tmpl_decl_mask,
2883
2884 MK_hwm = 0x20
2885 };
2886 /* This is more than a debugging array. NULLs are used to determine
2887 an invalid merge_kind number. */
2888 static char const *const merge_kind_name[MK_hwm] =
2889 {
2890 "unique", "named", "field", "vtable", /* 0...3 */
2891 "asbase", "partial", "enum", "attached", /* 4...7 */
2892
2893 "local type", "friend spec", "local friend", NULL, /* 8...11 */
2894 NULL, NULL, NULL, NULL,
2895
2896 "type spec", "type tmpl spec", /* 16,17 type (template). */
2897 NULL, NULL,
2898
2899 "decl spec", "decl tmpl spec", /* 20,21 decl (template). */
2900 NULL, NULL,
2901 NULL, NULL, NULL, NULL,
2902 NULL, NULL, NULL, NULL,
2903 };
2904
2905 /* Mergeable entity location data. */
2906 struct merge_key {
2907 cp_ref_qualifier ref_q : 2;
2908 unsigned index;
2909
2910 tree ret; /* Return type, if appropriate. */
2911 tree args; /* Arg types, if appropriate. */
2912
2913 tree constraints; /* Constraints. */
2914
2915 merge_key ()
2916 :ref_q (REF_QUAL_NONE), index (0),
2917 ret (NULL_TREE), args (NULL_TREE),
2918 constraints (NULL_TREE)
2919 {
2920 }
2921 };
2922
2923 /* Hashmap of merged duplicates. Usually decls, but can contain
2924 BINFOs. */
2925 typedef hash_map<tree,uintptr_t,
2926 simple_hashmap_traits<nodel_ptr_hash<tree_node>,uintptr_t> >
2927 duplicate_hash_map;
2928
2929 /* Data needed for post-processing. */
2930 struct post_process_data {
2931 tree decl;
2932 location_t start_locus;
2933 location_t end_locus;
2934 bool returns_value;
2935 bool returns_null;
2936 bool returns_abnormally;
2937 bool infinite_loop;
2938 };
2939
2940 /* Tree stream reader. Note that reading a stream doesn't mark the
2941 read trees with TREE_VISITED. Thus it's quite safe to have
2942 multiple concurrent readers. Which is good, because lazy
2943 loading.
2944
2945 It's important that trees_in/out have internal linkage so that the
2946 compiler knows core_bools, lang_type_bools and lang_decl_bools have
2947 only a single caller (tree_node_bools) and inlines them appropriately. */
2948 namespace {
2949 class trees_in : public bytes_in {
2950 typedef bytes_in parent;
2951
2952 private:
2953 module_state *state; /* Module being imported. */
2954 vec<tree> back_refs; /* Back references. */
2955 duplicate_hash_map *duplicates; /* Map from existings to duplicate. */
2956 vec<post_process_data> post_decls; /* Decls to post process. */
2957 vec<tree> post_types; /* Types to post process. */
2958 unsigned unused; /* Inhibit any interior TREE_USED
2959 marking. */
2960
2961 public:
2962 trees_in (module_state *);
2963 ~trees_in ();
2964
2965 public:
2966 int insert (tree);
2967 tree back_ref (int);
2968
2969 private:
2970 tree start (unsigned = 0);
2971
2972 public:
2973 /* Needed for binfo writing */
2974 bool core_bools (tree, bits_in&);
2975
2976 private:
2977 /* Stream tree_core, lang_decl_specific and lang_type_specific
2978 bits. */
2979 bool core_vals (tree);
2980 bool lang_type_bools (tree, bits_in&);
2981 bool lang_type_vals (tree);
2982 bool lang_decl_bools (tree, bits_in&);
2983 bool lang_decl_vals (tree);
2984 bool lang_vals (tree);
2985 bool tree_node_bools (tree);
2986 bool tree_node_vals (tree);
2987 tree tree_value ();
2988 tree decl_value ();
2989 tree tpl_parm_value ();
2990
2991 private:
2992 tree chained_decls (); /* Follow DECL_CHAIN. */
2993 vec<tree, va_heap> *vec_chained_decls ();
2994 vec<tree, va_gc> *tree_vec (); /* vec of tree. */
2995 vec<tree_pair_s, va_gc> *tree_pair_vec (); /* vec of tree_pair. */
2996 tree tree_list (bool has_purpose);
2997
2998 public:
2999 /* Read a tree node. */
3000 tree tree_node (bool is_use = false);
3001
3002 private:
3003 bool install_entity (tree decl);
3004 tree tpl_parms (unsigned &tpl_levels);
3005 bool tpl_parms_fini (tree decl, unsigned tpl_levels);
3006 bool tpl_header (tree decl, unsigned *tpl_levels);
3007 int fn_parms_init (tree);
3008 void fn_parms_fini (int tag, tree fn, tree existing, bool has_defn);
3009 unsigned add_indirect_tpl_parms (tree);
3010 public:
3011 bool add_indirects (tree);
3012
3013 public:
3014 /* Serialize various definitions. */
3015 bool read_definition (tree decl);
3016
3017 private:
3018 void check_abi_tags (tree existing, tree decl, tree &eattr, tree &dattr);
3019 bool is_matching_decl (tree existing, tree decl, bool is_typedef);
3020 static bool install_implicit_member (tree decl);
3021 bool read_function_def (tree decl, tree maybe_template);
3022 bool read_var_def (tree decl, tree maybe_template);
3023 bool read_class_def (tree decl, tree maybe_template);
3024 bool read_enum_def (tree decl, tree maybe_template);
3025
3026 public:
3027 tree decl_container ();
3028 tree key_mergeable (int tag, merge_kind, tree decl, tree inner, tree type,
3029 tree container, bool is_attached,
3030 bool is_imported_temploid_friend);
3031 unsigned binfo_mergeable (tree *);
3032
3033 private:
3034 tree key_local_type (const merge_key&, tree, tree);
3035 uintptr_t *find_duplicate (tree existing);
3036 void register_duplicate (tree decl, tree existing);
3037 /* Mark as an already diagnosed bad duplicate. */
3038 void unmatched_duplicate (tree existing)
3039 {
3040 *find_duplicate (existing) |= 1;
3041 }
3042
3043 public:
3044 bool is_duplicate (tree decl)
3045 {
3046 return find_duplicate (decl) != NULL;
3047 }
3048 tree maybe_duplicate (tree decl)
3049 {
3050 if (uintptr_t *dup = find_duplicate (decl))
3051 return reinterpret_cast<tree> (*dup & ~uintptr_t (1));
3052 return decl;
3053 }
3054 tree odr_duplicate (tree decl, bool has_defn);
3055
3056 public:
3057 /* Return the decls to postprocess. */
3058 const vec<post_process_data>& post_process ()
3059 {
3060 return post_decls;
3061 }
3062 /* Return the types to postprocess. */
3063 const vec<tree>& post_process_type ()
3064 {
3065 return post_types;
3066 }
3067 private:
3068 /* Register DATA for postprocessing. */
3069 void post_process (post_process_data data)
3070 {
3071 post_decls.safe_push (data);
3072 }
3073 /* Register TYPE for postprocessing. */
3074 void post_process_type (tree type)
3075 {
3076 gcc_checking_assert (TYPE_P (type));
3077 post_types.safe_push (type);
3078 }
3079
3080 private:
3081 void assert_definition (tree, bool installing);
3082 };
3083 } // anon namespace
3084
3085 trees_in::trees_in (module_state *state)
3086 :parent (), state (state), unused (0)
3087 {
3088 duplicates = NULL;
3089 back_refs.create (500);
3090 post_decls.create (0);
3091 post_types.create (0);
3092 }
3093
3094 trees_in::~trees_in ()
3095 {
3096 delete (duplicates);
3097 back_refs.release ();
3098 post_decls.release ();
3099 post_types.release ();
3100 }
3101
3102 /* Tree stream writer. */
3103 namespace {
3104 class trees_out : public bytes_out {
3105 typedef bytes_out parent;
3106
3107 private:
3108 module_state *state; /* The module we are writing. */
3109 ptr_int_hash_map tree_map; /* Trees to references */
3110 depset::hash *dep_hash; /* Dependency table. */
3111 int ref_num; /* Back reference number. */
3112 unsigned section;
3113 bool writing_local_entities; /* Whether we might walk into a TU-local
3114 entity we need to emit placeholders for. */
3115 #if CHECKING_P
3116 int importedness; /* Checker that imports not occurring
3117 inappropriately. +ve imports ok,
3118 -ve imports not ok. */
3119 #endif
3120
3121 public:
3122 trees_out (allocator *, module_state *, depset::hash &deps, unsigned sec = 0);
3123 ~trees_out ();
3124
3125 private:
3126 void mark_trees ();
3127 void unmark_trees ();
3128
3129 public:
3130 /* Hey, let's ignore the well known STL iterator idiom. */
3131 void begin ();
3132 unsigned end (elf_out *sink, unsigned name, unsigned *crc_ptr);
3133 void end ();
3134
3135 public:
3136 enum tags
3137 {
3138 tag_backref = -1, /* Upper bound on the backrefs. */
3139 tag_value = 0, /* Write by value. */
3140 tag_fixed /* Lower bound on the fixed trees. */
3141 };
3142
3143 public:
3144 /* The walk is used for three similar purposes:
3145
3146 1. The initial scan for dependencies.
3147 2. Once dependencies have been found, ordering them.
3148 3. Writing dependencies to file (streaming_p).
3149
3150 For cases where it matters, these accessers can be used to determine
3151 which state we're in. */
3152 bool is_initial_scan () const
3153 {
3154 return !streaming_p () && !is_key_order ();
3155 }
3156 bool is_key_order () const
3157 {
3158 return dep_hash->is_key_order ();
3159 }
3160
3161 public:
3162 int insert (tree, walk_kind = WK_normal);
3163
3164 private:
3165 void start (tree, bool = false);
3166
3167 private:
3168 walk_kind ref_node (tree);
3169 public:
3170 int get_tag (tree);
3171 void set_importing (int i ATTRIBUTE_UNUSED)
3172 {
3173 #if CHECKING_P
3174 importedness = i;
3175 #endif
3176 }
3177
3178 private:
3179 void core_bools (tree, bits_out&);
3180 void core_vals (tree);
3181 void lang_type_bools (tree, bits_out&);
3182 void lang_type_vals (tree);
3183 void lang_decl_bools (tree, bits_out&);
3184 void lang_decl_vals (tree);
3185 void lang_vals (tree);
3186 void tree_node_bools (tree);
3187 void tree_node_vals (tree);
3188
3189 private:
3190 void chained_decls (tree);
3191 void vec_chained_decls (tree);
3192 void tree_vec (vec<tree, va_gc> *);
3193 void tree_pair_vec (vec<tree_pair_s, va_gc> *);
3194 void tree_list (tree, bool has_purpose);
3195
3196 private:
3197 bool has_tu_local_dep (tree) const;
3198 tree find_tu_local_decl (tree);
3199
3200 public:
3201 /* Mark a node for by-value walking. */
3202 void mark_by_value (tree);
3203
3204 public:
3205 void tree_node (tree);
3206
3207 private:
3208 void install_entity (tree decl, depset *);
3209 void tpl_parms (tree parms, unsigned &tpl_levels);
3210 void tpl_parms_fini (tree decl, unsigned tpl_levels);
3211 void fn_parms_fini (tree) {}
3212 unsigned add_indirect_tpl_parms (tree);
3213 public:
3214 void add_indirects (tree);
3215 void fn_parms_init (tree);
3216 void tpl_header (tree decl, unsigned *tpl_levels);
3217
3218 public:
3219 merge_kind get_merge_kind (tree decl, depset *maybe_dep);
3220 tree decl_container (tree decl);
3221 void key_mergeable (int tag, merge_kind, tree decl, tree inner,
3222 tree container, depset *maybe_dep);
3223 void binfo_mergeable (tree binfo);
3224
3225 private:
3226 void key_local_type (merge_key&, tree, tree);
3227 bool decl_node (tree, walk_kind ref);
3228 void type_node (tree);
3229 void tree_value (tree);
3230 void tpl_parm_value (tree);
3231
3232 public:
3233 void decl_value (tree, depset *);
3234
3235 public:
3236 /* Serialize various definitions. */
3237 void write_definition (tree decl, bool refs_tu_local = false);
3238 void mark_declaration (tree decl, bool do_defn);
3239
3240 private:
3241 void mark_function_def (tree decl);
3242 void mark_var_def (tree decl);
3243 void mark_class_def (tree decl);
3244 void mark_enum_def (tree decl);
3245 void mark_class_member (tree decl, bool do_defn = true);
3246 void mark_binfos (tree type);
3247
3248 private:
3249 void write_var_def (tree decl);
3250 void write_function_def (tree decl);
3251 void write_class_def (tree decl);
3252 void write_enum_def (tree decl);
3253
3254 private:
3255 static void assert_definition (tree);
3256
3257 public:
3258 static void instrument ();
3259
3260 private:
3261 /* Tree instrumentation. */
3262 static unsigned tree_val_count;
3263 static unsigned decl_val_count;
3264 static unsigned back_ref_count;
3265 static unsigned tu_local_count;
3266 static unsigned null_count;
3267 };
3268 } // anon namespace
3269
3270 /* Instrumentation counters. */
3271 unsigned trees_out::tree_val_count;
3272 unsigned trees_out::decl_val_count;
3273 unsigned trees_out::back_ref_count;
3274 unsigned trees_out::tu_local_count;
3275 unsigned trees_out::null_count;
3276
3277 trees_out::trees_out (allocator *mem, module_state *state, depset::hash &deps,
3278 unsigned section)
3279 :parent (mem), state (state), tree_map (500),
3280 dep_hash (&deps), ref_num (0), section (section),
3281 writing_local_entities (false)
3282 {
3283 #if CHECKING_P
3284 importedness = 0;
3285 #endif
3286 }
3287
3288 trees_out::~trees_out ()
3289 {
3290 }
3291
3292 /********************************************************************/
3293 /* Location. We're aware of the line-map concept and reproduce it
3294 here. Each imported module allocates a contiguous span of ordinary
3295 maps, and of macro maps. adhoc maps are serialized by contents,
3296 not pre-allocated. The scattered linemaps of a module are
3297 coalesced when writing. */
3298
3299
3300 /* I use half-open [first,second) ranges. */
3301 typedef std::pair<line_map_uint_t,line_map_uint_t> range_t;
3302
3303 /* A range of locations. */
3304 typedef std::pair<location_t,location_t> loc_range_t;
3305
3306 /* Spans of the line maps that are occupied by this TU. I.e. not
3307 within imports. Only extended when in an interface unit.
3308 Interval zero corresponds to the forced header linemap(s). This
3309 is a singleton object. */
3310
3311 class loc_spans {
3312 public:
3313 /* An interval of line maps. The line maps here represent a contiguous
3314 non-imported range. */
3315 struct span {
3316 loc_range_t ordinary; /* Ordinary map location range. */
3317 loc_range_t macro; /* Macro map location range. */
3318 /* Add to locs to get serialized loc. */
3319 location_diff_t ordinary_delta;
3320 location_diff_t macro_delta;
3321 };
3322
3323 private:
3324 vec<span> *spans;
3325 bool locs_exhausted_p;
3326
3327 public:
3328 loc_spans ()
3329 /* Do not preallocate spans, as that causes
3330 --enable-detailed-mem-stats problems. */
3331 : spans (nullptr), locs_exhausted_p (false)
3332 {
3333 }
3334 ~loc_spans ()
3335 {
3336 delete spans;
3337 }
3338
3339 public:
3340 span &operator[] (unsigned ix)
3341 {
3342 return (*spans)[ix];
3343 }
3344 unsigned length () const
3345 {
3346 return spans->length ();
3347 }
3348
3349 public:
3350 bool init_p () const
3351 {
3352 return spans != nullptr;
3353 }
3354 /* Initializer. */
3355 void init (const line_maps *lmaps, const line_map_ordinary *map);
3356
3357 /* Slightly skewed preprocessed files can cause us to miss an
3358 initialization in some places. Fallback initializer. */
3359 void maybe_init ()
3360 {
3361 if (!init_p ())
3362 init (line_table, nullptr);
3363 }
3364
3365 public:
3366 enum {
3367 SPAN_RESERVED = 0, /* Reserved (fixed) locations. */
3368 SPAN_FIRST = 1, /* LWM of locations to stream */
3369 SPAN_MAIN = 2 /* Main file and onwards. */
3370 };
3371
3372 public:
3373 location_t main_start () const
3374 {
3375 return (*spans)[SPAN_MAIN].ordinary.first;
3376 }
3377
3378 public:
3379 void open (location_t);
3380 void close ();
3381
3382 public:
3383 /* Propagate imported linemaps to us, if needed. */
3384 bool maybe_propagate (module_state *import, location_t loc);
3385
3386 public:
3387 /* Whether we can no longer represent new imported locations. */
3388 bool locations_exhausted_p () const
3389 {
3390 return locs_exhausted_p;
3391 }
3392 void report_location_exhaustion (location_t loc)
3393 {
3394 if (!locs_exhausted_p)
3395 {
3396 /* Just give the notice once. */
3397 locs_exhausted_p = true;
3398 inform (loc, "unable to represent further imported source locations");
3399 }
3400 }
3401
3402 public:
3403 const span *ordinary (location_t);
3404 const span *macro (location_t);
3405 };
3406
3407 static loc_spans spans;
3408
3409 /* Information about ordinary locations we stream out. */
3410 struct ord_loc_info
3411 {
3412 const line_map_ordinary *src; // line map we're based on
3413 line_map_uint_t offset; // offset to this line
3414 line_map_uint_t span; // number of locs we span
3415 line_map_uint_t remap; // serialization
3416
3417 static int compare (const void *a_, const void *b_)
3418 {
3419 auto *a = static_cast<const ord_loc_info *> (a_);
3420 auto *b = static_cast<const ord_loc_info *> (b_);
3421
3422 if (a->src != b->src)
3423 return a->src < b->src ? -1 : +1;
3424
3425 // Ensure no overlap
3426 gcc_checking_assert (a->offset + a->span <= b->offset
3427 || b->offset + b->span <= a->offset);
3428
3429 gcc_checking_assert (a->offset != b->offset);
3430 return a->offset < b->offset ? -1 : +1;
3431 }
3432 };
3433 struct ord_loc_traits
3434 {
3435 typedef ord_loc_info value_type;
3436 typedef value_type compare_type;
3437
3438 static const bool empty_zero_p = false;
3439
3440 static hashval_t hash (const value_type &v)
3441 {
3442 auto h = pointer_hash<const line_map_ordinary>::hash (v.src);
3443 return iterative_hash_hashval_t (v.offset, h);
3444 }
3445 static bool equal (const value_type &v, const compare_type p)
3446 {
3447 return v.src == p.src && v.offset == p.offset;
3448 }
3449
3450 static void mark_empty (value_type &v)
3451 {
3452 v.src = nullptr;
3453 }
3454 static bool is_empty (value_type &v)
3455 {
3456 return !v.src;
3457 }
3458
3459 static bool is_deleted (value_type &) { return false; }
3460 static void mark_deleted (value_type &) { gcc_unreachable (); }
3461
3462 static void remove (value_type &) {}
3463 };
3464 /* Table keyed by ord_loc_info, used for noting. */
3465 static hash_table<ord_loc_traits> *ord_loc_table;
3466 /* Sorted vector, used for writing. */
3467 static vec<ord_loc_info> *ord_loc_remap;
3468
3469 /* Information about macro locations we stream out. */
3470 struct macro_loc_info
3471 {
3472 const line_map_macro *src; // original expansion
3473 line_map_uint_t remap; // serialization
3474
3475 static int compare (const void *a_, const void *b_)
3476 {
3477 auto *a = static_cast<const macro_loc_info *> (a_);
3478 auto *b = static_cast<const macro_loc_info *> (b_);
3479
3480 gcc_checking_assert (MAP_START_LOCATION (a->src)
3481 != MAP_START_LOCATION (b->src));
3482 if (MAP_START_LOCATION (a->src) < MAP_START_LOCATION (b->src))
3483 return -1;
3484 else
3485 return +1;
3486 }
3487 };
3488 struct macro_loc_traits
3489 {
3490 typedef macro_loc_info value_type;
3491 typedef const line_map_macro *compare_type;
3492
3493 static const bool empty_zero_p = false;
3494
3495 static hashval_t hash (compare_type p)
3496 {
3497 return pointer_hash<const line_map_macro>::hash (p);
3498 }
3499 static hashval_t hash (const value_type &v)
3500 {
3501 return hash (v.src);
3502 }
3503 static bool equal (const value_type &v, const compare_type p)
3504 {
3505 return v.src == p;
3506 }
3507
3508 static void mark_empty (value_type &v)
3509 {
3510 v.src = nullptr;
3511 }
3512 static bool is_empty (value_type &v)
3513 {
3514 return !v.src;
3515 }
3516
3517 static bool is_deleted (value_type &) { return false; }
3518 static void mark_deleted (value_type &) { gcc_unreachable (); }
3519
3520 static void remove (value_type &) {}
3521 };
3522 /* Table keyed by line_map_macro, used for noting. */
3523 static hash_table<macro_loc_traits> *macro_loc_table;
3524 /* Sorted vector, used for writing. */
3525 static vec<macro_loc_info> *macro_loc_remap;
3526
3527 /* Indirection to allow bsearching imports by ordinary location. */
3528 static vec<module_state *> *ool;
3529
3530 /********************************************************************/
3531 /* Data needed by a module during the process of loading. */
3532 struct GTY(()) slurping {
3533
3534 /* Remap import's module numbering to our numbering. Values are
3535 shifted by 1. Bit0 encodes if the import is direct. */
3536 vec<unsigned, va_heap, vl_embed> *
3537 GTY((skip)) remap; /* Module owner remapping. */
3538
3539 elf_in *GTY((skip)) from; /* The elf loader. */
3540
3541 /* This map is only for header imports themselves -- the global
3542 headers bitmap hold it for the current TU. */
3543 bitmap headers; /* Transitive set of direct imports, including
3544 self. Used for macro visibility and
3545 priority. */
3546
3547 /* These objects point into the mmapped area, unless we're not doing
3548 that, or we got frozen or closed. In those cases they point to
3549 buffers we own. */
3550 bytes_in macro_defs; /* Macro definitions. */
3551 bytes_in macro_tbl; /* Macro table. */
3552
3553 /* Location remapping. first->ordinary, second->macro. */
3554 range_t GTY((skip)) loc_deltas;
3555
3556 unsigned current; /* Section currently being loaded. */
3557 unsigned remaining; /* Number of lazy sections yet to read. */
3558 unsigned lru; /* An LRU counter. */
3559
3560 public:
3561 slurping (elf_in *);
3562 ~slurping ();
3563
3564 public:
3565 /* Close the ELF file, if it's open. */
3566 void close ()
3567 {
3568 if (from)
3569 {
3570 from->end ();
3571 delete from;
3572 from = NULL;
3573 }
3574 }
3575
3576 public:
3577 void release_macros ();
3578
3579 public:
3580 void alloc_remap (unsigned size)
3581 {
3582 gcc_assert (!remap);
3583 vec_safe_reserve (remap, size);
3584 for (unsigned ix = size; ix--;)
3585 remap->quick_push (0);
3586 }
3587 unsigned remap_module (unsigned owner)
3588 {
3589 if (owner < remap->length ())
3590 return (*remap)[owner] >> 1;
3591 return 0;
3592 }
3593
3594 public:
3595 /* GC allocation. But we must explicitly delete it. */
3596 static void *operator new (size_t x)
3597 {
3598 return ggc_alloc_atomic (x);
3599 }
3600 static void operator delete (void *p)
3601 {
3602 ggc_free (p);
3603 }
3604 };
3605
3606 slurping::slurping (elf_in *from)
3607 : remap (NULL), from (from),
3608 headers (BITMAP_GGC_ALLOC ()), macro_defs (), macro_tbl (),
3609 loc_deltas (0, 0),
3610 current (~0u), remaining (0), lru (0)
3611 {
3612 }
3613
3614 slurping::~slurping ()
3615 {
3616 vec_free (remap);
3617 remap = NULL;
3618 release_macros ();
3619 close ();
3620 }
3621
3622 void slurping::release_macros ()
3623 {
3624 if (macro_defs.size)
3625 elf_in::release (from, macro_defs);
3626 if (macro_tbl.size)
3627 elf_in::release (from, macro_tbl);
3628 }
3629
3630 /* Flags for extensions that end up being streamed. */
3631
3632 enum streamed_extensions {
3633 SE_OPENMP_SIMD = 1 << 0,
3634 SE_OPENMP = 1 << 1,
3635 SE_OPENACC = 1 << 2,
3636 SE_BITS = 3
3637 };
3638
3639 /* Counter indices. */
3640 enum module_state_counts
3641 {
3642 MSC_sec_lwm,
3643 MSC_sec_hwm,
3644 MSC_pendings,
3645 MSC_entities,
3646 MSC_namespaces,
3647 MSC_bindings,
3648 MSC_macros,
3649 MSC_inits,
3650 MSC_HWM
3651 };
3652
3653 /********************************************************************/
3654 struct module_state_config;
3655
3656 /* Increasing levels of loadedness. */
3657 enum module_loadedness {
3658 ML_NONE, /* Not loaded. */
3659 ML_CONFIG, /* Config loaed. */
3660 ML_PREPROCESSOR, /* Preprocessor loaded. */
3661 ML_LANGUAGE, /* Language loaded. */
3662 };
3663
3664 /* Increasing levels of directness (toplevel) of import. */
3665 enum module_directness {
3666 MD_NONE, /* Not direct. */
3667 MD_PARTITION_DIRECT, /* Direct import of a partition. */
3668 MD_DIRECT, /* Direct import. */
3669 MD_PURVIEW_DIRECT, /* Direct import in purview. */
3670 };
3671
3672 /* State of a particular module. */
3673
3674 class GTY((chain_next ("%h.parent"), for_user)) module_state {
3675 public:
3676 /* We always import & export ourselves. */
3677 bitmap imports; /* Transitive modules we're importing. */
3678 bitmap exports; /* Subset of that, that we're exporting. */
3679
3680 module_state *parent;
3681 tree name; /* Name of the module. */
3682
3683 slurping *slurp; /* Data for loading. */
3684
3685 const char *flatname; /* Flatname of module. */
3686 char *filename; /* CMI Filename */
3687
3688 /* Indices into the entity_ary. */
3689 unsigned entity_lwm;
3690 unsigned entity_num;
3691
3692 /* Location ranges for this module. adhoc-locs are decomposed, so
3693 don't have a range. */
3694 loc_range_t GTY((skip)) ordinary_locs;
3695 loc_range_t GTY((skip)) macro_locs; // [lwm,num)
3696
3697 /* LOC is first set too the importing location. When initially
3698 loaded it refers to a module loc whose parent is the importing
3699 location. */
3700 location_t loc; /* Location referring to module itself. */
3701 unsigned crc; /* CRC we saw reading it in. */
3702
3703 unsigned mod; /* Module owner number. */
3704 unsigned remap; /* Remapping during writing. */
3705
3706 unsigned short subst; /* Mangle subst if !0. */
3707
3708 /* How loaded this module is. */
3709 enum module_loadedness loadedness : 2;
3710
3711 bool module_p : 1; /* /The/ module of this TU. */
3712 bool header_p : 1; /* Is a header unit. */
3713 bool interface_p : 1; /* An interface. */
3714 bool partition_p : 1; /* A partition. */
3715
3716 /* How directly this module is imported. */
3717 enum module_directness directness : 2;
3718
3719 bool exported_p : 1; /* directness != MD_NONE && exported. */
3720 bool cmi_noted_p : 1; /* We've told the user about the CMI, don't
3721 do it again */
3722 bool active_init_p : 1; /* This module's global initializer needs
3723 calling. */
3724 bool inform_cmi_p : 1; /* Inform of a read/write. */
3725 bool visited_p : 1; /* A walk-once flag. */
3726 /* Record extensions emitted or permitted. */
3727 unsigned extensions : SE_BITS;
3728 /* 14 bits used, 2 bits remain */
3729
3730 public:
3731 module_state (tree name, module_state *, bool);
3732 ~module_state ();
3733
3734 public:
3735 void release ()
3736 {
3737 imports = exports = NULL;
3738 slurped ();
3739 }
3740 void slurped ()
3741 {
3742 delete slurp;
3743 slurp = NULL;
3744 }
3745 elf_in *from () const
3746 {
3747 return slurp->from;
3748 }
3749
3750 public:
3751 /* Kind of this module. */
3752 bool is_module () const
3753 {
3754 return module_p;
3755 }
3756 bool is_header () const
3757 {
3758 return header_p;
3759 }
3760 bool is_interface () const
3761 {
3762 return interface_p;
3763 }
3764 bool is_partition () const
3765 {
3766 return partition_p;
3767 }
3768
3769 /* How this module is used in the current TU. */
3770 bool is_exported () const
3771 {
3772 return exported_p;
3773 }
3774 bool is_direct () const
3775 {
3776 return directness >= MD_DIRECT;
3777 }
3778 bool is_purview_direct () const
3779 {
3780 return directness == MD_PURVIEW_DIRECT;
3781 }
3782 bool is_partition_direct () const
3783 {
3784 return directness == MD_PARTITION_DIRECT;
3785 }
3786
3787 public:
3788 /* Is this a real module? */
3789 bool has_location () const
3790 {
3791 return loc != UNKNOWN_LOCATION;
3792 }
3793
3794 public:
3795 bool check_not_purview (location_t loc);
3796
3797 public:
3798 void mangle (bool include_partition);
3799
3800 public:
3801 void set_import (module_state const *, bool is_export);
3802 void announce (const char *) const;
3803
3804 public:
3805 /* Read and write module. */
3806 bool write_begin (elf_out *to, cpp_reader *,
3807 module_state_config &, unsigned &crc);
3808 void write_end (elf_out *to, cpp_reader *,
3809 module_state_config &, unsigned &crc);
3810 bool read_initial (cpp_reader *);
3811 bool read_preprocessor (bool);
3812 bool read_language (bool);
3813
3814 public:
3815 /* Read a section. */
3816 bool load_section (unsigned snum, binding_slot *mslot);
3817 /* Lazily read a section. */
3818 bool lazy_load (unsigned index, binding_slot *mslot);
3819
3820 public:
3821 /* Juggle a limited number of file numbers. */
3822 static void freeze_an_elf ();
3823 bool maybe_defrost ();
3824
3825 public:
3826 void maybe_completed_reading ();
3827 bool check_read (bool outermost, bool ok);
3828
3829 private:
3830 /* The README, for human consumption. */
3831 void write_readme (elf_out *to, cpp_reader *, const char *dialect);
3832 void write_env (elf_out *to);
3833
3834 private:
3835 /* Import tables. */
3836 void write_imports (bytes_out &cfg, bool direct);
3837 unsigned read_imports (bytes_in &cfg, cpp_reader *, line_maps *maps);
3838
3839 private:
3840 void write_imports (elf_out *to, unsigned *crc_ptr);
3841 bool read_imports (cpp_reader *, line_maps *);
3842
3843 private:
3844 void write_partitions (elf_out *to, unsigned, unsigned *crc_ptr);
3845 bool read_partitions (unsigned);
3846
3847 private:
3848 void write_config (elf_out *to, struct module_state_config &, unsigned crc);
3849 bool read_config (struct module_state_config &);
3850 static void write_counts (elf_out *to, unsigned [MSC_HWM], unsigned *crc_ptr);
3851 bool read_counts (unsigned *);
3852
3853 public:
3854 void note_cmi_name ();
3855
3856 private:
3857 static unsigned write_bindings (elf_out *to, vec<depset *> depsets,
3858 unsigned *crc_ptr);
3859 bool read_bindings (unsigned count, unsigned lwm, unsigned hwm);
3860
3861 static void write_namespace (bytes_out &sec, depset *ns_dep);
3862 tree read_namespace (bytes_in &sec);
3863
3864 void write_namespaces (elf_out *to, vec<depset *> spaces,
3865 unsigned, unsigned *crc_ptr);
3866 bool read_namespaces (unsigned);
3867
3868 void intercluster_seed (trees_out &sec, unsigned index, depset *dep);
3869 unsigned write_cluster (elf_out *to, depset *depsets[], unsigned size,
3870 depset::hash &, unsigned *counts, unsigned *crc_ptr);
3871 bool read_cluster (unsigned snum);
3872
3873 private:
3874 unsigned write_inits (elf_out *to, depset::hash &, unsigned *crc_ptr);
3875 bool read_inits (unsigned count);
3876
3877 private:
3878 unsigned write_pendings (elf_out *to, vec<depset *> depsets,
3879 depset::hash &, unsigned *crc_ptr);
3880 bool read_pendings (unsigned count);
3881
3882 private:
3883 void write_entities (elf_out *to, vec<depset *> depsets,
3884 unsigned count, unsigned *crc_ptr);
3885 bool read_entities (unsigned count, unsigned lwm, unsigned hwm);
3886
3887 private:
3888 void write_init_maps ();
3889 range_t write_prepare_maps (module_state_config *, bool);
3890 bool read_prepare_maps (const module_state_config *);
3891
3892 void write_ordinary_maps (elf_out *to, range_t &,
3893 bool, unsigned *crc_ptr);
3894 bool read_ordinary_maps (line_map_uint_t, unsigned);
3895 void write_macro_maps (elf_out *to, range_t &, unsigned *crc_ptr);
3896 bool read_macro_maps (line_map_uint_t);
3897
3898 private:
3899 void write_define (bytes_out &, const cpp_macro *);
3900 cpp_macro *read_define (bytes_in &, cpp_reader *) const;
3901 vec<cpp_hashnode *> *prepare_macros (cpp_reader *);
3902 unsigned write_macros (elf_out *to, vec<cpp_hashnode *> *, unsigned *crc_ptr);
3903 bool read_macros ();
3904 void install_macros ();
3905
3906 public:
3907 void import_macros ();
3908
3909 public:
3910 static void undef_macro (cpp_reader *, location_t, cpp_hashnode *);
3911 static cpp_macro *deferred_macro (cpp_reader *, location_t, cpp_hashnode *);
3912
3913 public:
3914 static bool note_location (location_t);
3915 static void write_location (bytes_out &, location_t);
3916 location_t read_location (bytes_in &) const;
3917
3918 public:
3919 void set_flatname ();
3920 const char *get_flatname () const
3921 {
3922 return flatname;
3923 }
3924 location_t imported_from () const;
3925
3926 public:
3927 void set_filename (const Cody::Packet &);
3928 bool do_import (cpp_reader *, bool outermost);
3929 };
3930
3931 /* Hash module state by name. This cannot be a member of
3932 module_state, because of GTY restrictions. We never delete from
3933 the hash table, but ggc_ptr_hash doesn't support that
3934 simplification. */
3935
3936 struct module_state_hash : ggc_ptr_hash<module_state> {
3937 typedef std::pair<tree,uintptr_t> compare_type; /* {name,parent} */
3938
3939 static inline hashval_t hash (const value_type m);
3940 static inline hashval_t hash (const compare_type &n);
3941 static inline bool equal (const value_type existing,
3942 const compare_type &candidate);
3943 };
3944
3945 module_state::module_state (tree name, module_state *parent, bool partition)
3946 : imports (BITMAP_GGC_ALLOC ()), exports (BITMAP_GGC_ALLOC ()),
3947 parent (parent), name (name), slurp (NULL),
3948 flatname (NULL), filename (NULL),
3949 entity_lwm (~0u >> 1), entity_num (0),
3950 ordinary_locs (0, 0), macro_locs (0, 0),
3951 loc (UNKNOWN_LOCATION),
3952 crc (0), mod (MODULE_UNKNOWN), remap (0), subst (0)
3953 {
3954 loadedness = ML_NONE;
3955
3956 module_p = header_p = interface_p = partition_p = false;
3957
3958 directness = MD_NONE;
3959 exported_p = false;
3960
3961 cmi_noted_p = false;
3962 active_init_p = false;
3963
3964 partition_p = partition;
3965
3966 inform_cmi_p = false;
3967 visited_p = false;
3968
3969 extensions = 0;
3970 if (name && TREE_CODE (name) == STRING_CST)
3971 {
3972 header_p = true;
3973
3974 const char *string = TREE_STRING_POINTER (name);
3975 gcc_checking_assert (string[0] == '.'
3976 ? IS_DIR_SEPARATOR (string[1])
3977 : IS_ABSOLUTE_PATH (string));
3978 }
3979
3980 gcc_checking_assert (!(parent && header_p));
3981 }
3982
3983 module_state::~module_state ()
3984 {
3985 release ();
3986 }
3987
3988 /* Hash module state. */
3989 static hashval_t
3990 module_name_hash (const_tree name)
3991 {
3992 if (TREE_CODE (name) == STRING_CST)
3993 return htab_hash_string (TREE_STRING_POINTER (name));
3994 else
3995 return IDENTIFIER_HASH_VALUE (name);
3996 }
3997
3998 hashval_t
3999 module_state_hash::hash (const value_type m)
4000 {
4001 hashval_t ph = pointer_hash<void>::hash
4002 (reinterpret_cast<void *> (reinterpret_cast<uintptr_t> (m->parent)
4003 | m->is_partition ()));
4004 hashval_t nh = module_name_hash (m->name);
4005 return iterative_hash_hashval_t (ph, nh);
4006 }
4007
4008 /* Hash a name. */
4009 hashval_t
4010 module_state_hash::hash (const compare_type &c)
4011 {
4012 hashval_t ph = pointer_hash<void>::hash (reinterpret_cast<void *> (c.second));
4013 hashval_t nh = module_name_hash (c.first);
4014
4015 return iterative_hash_hashval_t (ph, nh);
4016 }
4017
4018 bool
4019 module_state_hash::equal (const value_type existing,
4020 const compare_type &candidate)
4021 {
4022 uintptr_t ep = (reinterpret_cast<uintptr_t> (existing->parent)
4023 | existing->is_partition ());
4024 if (ep != candidate.second)
4025 return false;
4026
4027 /* Identifier comparison is by pointer. If the string_csts happen
4028 to be the same object, then they're equal too. */
4029 if (existing->name == candidate.first)
4030 return true;
4031
4032 /* If neither are string csts, they can't be equal. */
4033 if (TREE_CODE (candidate.first) != STRING_CST
4034 || TREE_CODE (existing->name) != STRING_CST)
4035 return false;
4036
4037 /* String equality. */
4038 if (TREE_STRING_LENGTH (existing->name)
4039 == TREE_STRING_LENGTH (candidate.first)
4040 && !memcmp (TREE_STRING_POINTER (existing->name),
4041 TREE_STRING_POINTER (candidate.first),
4042 TREE_STRING_LENGTH (existing->name)))
4043 return true;
4044
4045 return false;
4046 }
4047
4048 /********************************************************************/
4049 /* Global state */
4050
4051 /* Mapper name. */
4052 static const char *module_mapper_name;
4053
4054 /* Deferred import queue (FIFO). */
4055 static vec<module_state *, va_heap, vl_embed> *pending_imports;
4056
4057 /* CMI repository path and workspace. */
4058 static char *cmi_repo;
4059 static size_t cmi_repo_length;
4060 static char *cmi_path;
4061 static size_t cmi_path_alloc;
4062
4063 /* Count of available and loaded clusters. */
4064 static unsigned available_clusters;
4065 static unsigned loaded_clusters;
4066
4067 /* What the current TU is. */
4068 unsigned module_kind;
4069
4070 /* Global trees. */
4071 static const std::pair<tree *, unsigned> global_tree_arys[] =
4072 {
4073 std::pair<tree *, unsigned> (sizetype_tab, stk_type_kind_last),
4074 std::pair<tree *, unsigned> (integer_types, itk_none),
4075 std::pair<tree *, unsigned> (global_trees, TI_MODULE_HWM),
4076 std::pair<tree *, unsigned> (c_global_trees, CTI_MODULE_HWM),
4077 std::pair<tree *, unsigned> (cp_global_trees, CPTI_MODULE_HWM),
4078 std::pair<tree *, unsigned> (NULL, 0)
4079 };
4080 static GTY(()) vec<tree, va_gc> *fixed_trees;
4081 static unsigned global_crc;
4082
4083 /* Lazy loading can open many files concurrently, there are
4084 per-process limits on that. We pay attention to the process limit,
4085 and attempt to increase it when we run out. Otherwise we use an
4086 LRU scheme to figure out who to flush. Note that if the import
4087 graph /depth/ exceeds lazy_limit, we'll exceed the limit. */
4088 static unsigned lazy_lru; /* LRU counter. */
4089 static unsigned lazy_open; /* Number of open modules */
4090 static unsigned lazy_limit; /* Current limit of open modules. */
4091 static unsigned lazy_hard_limit; /* Hard limit on open modules. */
4092 /* Account for source, assembler and dump files & directory searches.
4093 We don't keep the source file's open, so we don't have to account
4094 for #include depth. I think dump files are opened and closed per
4095 pass, but ICBW. */
4096 #define LAZY_HEADROOM 15 /* File descriptor headroom. */
4097
4098 /* Vector of module state. Indexed by OWNER. Index 0 is reserved for the
4099 current TU; imports start at 1. */
4100 static GTY(()) vec<module_state *, va_gc> *modules;
4101
4102 /* Hash of module state, findable by {name, parent}. */
4103 static GTY(()) hash_table<module_state_hash> *modules_hash;
4104
4105 /* Map of imported entities. We map DECL_UID to index of entity
4106 vector. */
4107 typedef hash_map<unsigned/*UID*/, unsigned/*index*/,
4108 simple_hashmap_traits<int_hash<unsigned,0>, unsigned>
4109 > entity_map_t;
4110 static entity_map_t *entity_map;
4111 /* Doesn't need GTYing, because any tree referenced here is also
4112 findable by, symbol table, specialization table, return type of
4113 reachable function. */
4114 static vec<binding_slot, va_heap, vl_embed> *entity_ary;
4115
4116 /* Members entities of imported classes that are defined in this TU.
4117 These are where the entity's context is not from the current TU.
4118 We need to emit the definition (but not the enclosing class).
4119
4120 We could find these by walking ALL the imported classes that we
4121 could provide a member definition. But that's expensive,
4122 especially when you consider lazy implicit member declarations,
4123 which could be ANY imported class. */
4124 static GTY(()) vec<tree, va_gc> *class_members;
4125
4126 /* The same problem exists for class template partial
4127 specializations. Now that we have constraints, the invariant of
4128 expecting them in the instantiation table no longer holds. One of
4129 the constrained partial specializations will be there, but the
4130 others not so much. It's not even an unconstrained partial
4131 spacialization in the table :( so any partial template declaration
4132 is added to this list too. */
4133 static GTY(()) vec<tree, va_gc> *partial_specializations;
4134
4135 /********************************************************************/
4136
4137 /* Our module mapper (created lazily). */
4138 module_client *mapper;
4139
4140 static module_client *make_mapper (location_t loc, class mkdeps *deps);
4141 inline module_client *get_mapper (location_t loc, class mkdeps *deps)
4142 {
4143 auto *res = mapper;
4144 if (!res)
4145 res = make_mapper (loc, deps);
4146 return res;
4147 }
4148
4149 /********************************************************************/
4150 static tree
4151 get_clone_target (tree decl)
4152 {
4153 tree target;
4154
4155 if (TREE_CODE (decl) == TEMPLATE_DECL)
4156 {
4157 tree res_orig = DECL_CLONED_FUNCTION (DECL_TEMPLATE_RESULT (decl));
4158
4159 target = DECL_TI_TEMPLATE (res_orig);
4160 }
4161 else
4162 target = DECL_CLONED_FUNCTION (decl);
4163
4164 gcc_checking_assert (DECL_MAYBE_IN_CHARGE_CDTOR_P (target));
4165
4166 return target;
4167 }
4168
4169 /* Like FOR_EACH_CLONE, but will walk cloned templates. */
4170 #define FOR_EVERY_CLONE(CLONE, FN) \
4171 if (!DECL_MAYBE_IN_CHARGE_CDTOR_P (FN)); \
4172 else \
4173 for (CLONE = DECL_CHAIN (FN); \
4174 CLONE && DECL_CLONED_FUNCTION_P (CLONE); \
4175 CLONE = DECL_CHAIN (CLONE))
4176
4177 /* It'd be nice if USE_TEMPLATE was a field of template_info
4178 (a) it'd solve the enum case dealt with below,
4179 (b) both class templates and decl templates would store this in the
4180 same place
4181 (c) this function wouldn't need the by-ref arg, which is annoying. */
4182
4183 static tree
4184 node_template_info (tree decl, int &use)
4185 {
4186 tree ti = NULL_TREE;
4187 int use_tpl = -1;
4188 if (DECL_IMPLICIT_TYPEDEF_P (decl))
4189 {
4190 tree type = TREE_TYPE (decl);
4191
4192 ti = TYPE_TEMPLATE_INFO (type);
4193 if (ti)
4194 {
4195 if (TYPE_LANG_SPECIFIC (type))
4196 use_tpl = CLASSTYPE_USE_TEMPLATE (type);
4197 else
4198 {
4199 /* An enum, where we don't explicitly encode use_tpl.
4200 If the containing context (a type or a function), is
4201 an ({im,ex}plicit) instantiation, then this is too.
4202 If it's a partial or explicit specialization, then
4203 this is not!. */
4204 tree ctx = CP_DECL_CONTEXT (decl);
4205 if (TYPE_P (ctx))
4206 ctx = TYPE_NAME (ctx);
4207 node_template_info (ctx, use);
4208 use_tpl = use != 2 ? use : 0;
4209 }
4210 }
4211 }
4212 else if (DECL_LANG_SPECIFIC (decl)
4213 && (VAR_P (decl)
4214 || TREE_CODE (decl) == TYPE_DECL
4215 || TREE_CODE (decl) == FUNCTION_DECL
4216 || TREE_CODE (decl) == FIELD_DECL
4217 || TREE_CODE (decl) == CONCEPT_DECL
4218 || TREE_CODE (decl) == TEMPLATE_DECL))
4219 {
4220 use_tpl = DECL_USE_TEMPLATE (decl);
4221 ti = DECL_TEMPLATE_INFO (decl);
4222 }
4223
4224 use = use_tpl;
4225 return ti;
4226 }
4227
4228 /* Find the index in entity_ary for an imported DECL. It should
4229 always be there, but bugs can cause it to be missing, and that can
4230 crash the crash reporting -- let's not do that! When streaming
4231 out we place entities from this module there too -- with negated
4232 indices. */
4233
4234 static unsigned
4235 import_entity_index (tree decl, bool null_ok = false)
4236 {
4237 if (unsigned *slot = entity_map->get (DECL_UID (decl)))
4238 return *slot;
4239
4240 gcc_checking_assert (null_ok);
4241 return ~(~0u >> 1);
4242 }
4243
4244 /* Find the module for an imported entity at INDEX in the entity ary.
4245 There must be one. */
4246
4247 static module_state *
4248 import_entity_module (unsigned index)
4249 {
4250 if (index > ~(~0u >> 1))
4251 /* This is an index for an exported entity. */
4252 return (*modules)[0];
4253
4254 /* Do not include the current TU (not an off-by-one error). */
4255 unsigned pos = 1;
4256 unsigned len = modules->length () - pos;
4257 while (len)
4258 {
4259 unsigned half = len / 2;
4260 module_state *probe = (*modules)[pos + half];
4261 if (index < probe->entity_lwm)
4262 len = half;
4263 else if (index < probe->entity_lwm + probe->entity_num)
4264 return probe;
4265 else
4266 {
4267 pos += half + 1;
4268 len = len - (half + 1);
4269 }
4270 }
4271 gcc_unreachable ();
4272 }
4273
4274
4275 /********************************************************************/
4276 /* A dumping machinery. */
4277
4278 class dumper {
4279 public:
4280 enum {
4281 LOCATION = TDF_LINENO, /* -lineno:Source location streaming. */
4282 DEPEND = TDF_GRAPH, /* -graph:Dependency graph construction. */
4283 CLUSTER = TDF_BLOCKS, /* -blocks:Clusters. */
4284 TREE = TDF_UID, /* -uid:Tree streaming. */
4285 MERGE = TDF_ALIAS, /* -alias:Mergeable Entities. */
4286 ELF = TDF_ASMNAME, /* -asmname:Elf data. */
4287 MACRO = TDF_VOPS /* -vops:Macros. */
4288 };
4289
4290 private:
4291 struct impl {
4292 typedef vec<module_state *, va_heap, vl_embed> stack_t;
4293
4294 FILE *stream; /* Dump stream. */
4295 unsigned indent; /* Local indentation. */
4296 bool bol; /* Beginning of line. */
4297 stack_t stack; /* Trailing array of module_state. */
4298
4299 bool nested_name (tree); /* Dump a name following DECL_CONTEXT. */
4300 };
4301
4302 public:
4303 /* The dumper. */
4304 impl *dumps;
4305 dump_flags_t flags;
4306
4307 public:
4308 /* Push/pop module state dumping. */
4309 unsigned push (module_state *);
4310 void pop (unsigned);
4311
4312 public:
4313 /* Change local indentation. */
4314 void indent ()
4315 {
4316 if (dumps)
4317 dumps->indent++;
4318 }
4319 void outdent ()
4320 {
4321 if (dumps)
4322 {
4323 gcc_checking_assert (dumps->indent);
4324 dumps->indent--;
4325 }
4326 }
4327
4328 public:
4329 /* Is dump enabled?. */
4330 bool operator () (int mask = 0)
4331 {
4332 if (!dumps || !dumps->stream)
4333 return false;
4334 if (mask && !(mask & flags))
4335 return false;
4336 return true;
4337 }
4338 /* Dump some information. */
4339 bool operator () (const char *, ...);
4340 };
4341
4342 /* The dumper. */
4343 static dumper dump = {0, dump_flags_t (0)};
4344
4345 /* Push to dumping M. Return previous indentation level. */
4346
4347 unsigned
4348 dumper::push (module_state *m)
4349 {
4350 FILE *stream = NULL;
4351 if (!dumps || !dumps->stack.length ())
4352 {
4353 stream = dump_begin (module_dump_id, &flags);
4354 if (!stream)
4355 return 0;
4356 }
4357
4358 if (!dumps || !dumps->stack.space (1))
4359 {
4360 /* Create or extend the dump implementor. */
4361 unsigned current = dumps ? dumps->stack.length () : 0;
4362 unsigned count = current ? current * 2 : EXPERIMENT (1, 20);
4363 size_t alloc = (offsetof (impl, stack)
4364 + impl::stack_t::embedded_size (count));
4365 dumps = XRESIZEVAR (impl, dumps, alloc);
4366 dumps->stack.embedded_init (count, current);
4367 }
4368 if (stream)
4369 dumps->stream = stream;
4370
4371 unsigned n = dumps->indent;
4372 dumps->indent = 0;
4373 dumps->bol = true;
4374 dumps->stack.quick_push (m);
4375 if (m)
4376 {
4377 module_state *from = NULL;
4378
4379 if (dumps->stack.length () > 1)
4380 from = dumps->stack[dumps->stack.length () - 2];
4381 else
4382 dump ("");
4383 dump (from ? "Starting module %M (from %M)"
4384 : "Starting module %M", m, from);
4385 }
4386
4387 return n;
4388 }
4389
4390 /* Pop from dumping. Restore indentation to N. */
4391
4392 void dumper::pop (unsigned n)
4393 {
4394 if (!dumps)
4395 return;
4396
4397 gcc_checking_assert (dump () && !dumps->indent);
4398 if (module_state *m = dumps->stack[dumps->stack.length () - 1])
4399 {
4400 module_state *from = (dumps->stack.length () > 1
4401 ? dumps->stack[dumps->stack.length () - 2] : NULL);
4402 dump (from ? "Finishing module %M (returning to %M)"
4403 : "Finishing module %M", m, from);
4404 }
4405 dumps->stack.pop ();
4406 dumps->indent = n;
4407 if (!dumps->stack.length ())
4408 {
4409 dump_end (module_dump_id, dumps->stream);
4410 dumps->stream = NULL;
4411 }
4412 }
4413
4414 /* Dump a nested name for arbitrary tree T. Sometimes it won't have a
4415 name. */
4416
4417 bool
4418 dumper::impl::nested_name (tree t)
4419 {
4420 tree ti = NULL_TREE;
4421 int origin = -1;
4422 tree name = NULL_TREE;
4423
4424 if (t && TREE_CODE (t) == TU_LOCAL_ENTITY)
4425 t = TU_LOCAL_ENTITY_NAME (t);
4426
4427 if (t && TREE_CODE (t) == TREE_BINFO)
4428 t = BINFO_TYPE (t);
4429
4430 if (t && TYPE_P (t))
4431 t = TYPE_NAME (t);
4432
4433 if (t && DECL_P (t))
4434 {
4435 if (t == global_namespace || DECL_TEMPLATE_PARM_P (t))
4436 ;
4437 else if (tree ctx = DECL_CONTEXT (t))
4438 if (TREE_CODE (ctx) == TRANSLATION_UNIT_DECL
4439 || nested_name (ctx))
4440 fputs ("::", stream);
4441
4442 int use_tpl;
4443 ti = node_template_info (t, use_tpl);
4444 if (ti && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL
4445 && (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == t))
4446 t = TI_TEMPLATE (ti);
4447 tree not_tmpl = t;
4448 if (TREE_CODE (t) == TEMPLATE_DECL)
4449 {
4450 fputs ("template ", stream);
4451 not_tmpl = DECL_TEMPLATE_RESULT (t);
4452 }
4453
4454 if (not_tmpl
4455 && DECL_P (not_tmpl)
4456 && DECL_LANG_SPECIFIC (not_tmpl)
4457 && DECL_MODULE_IMPORT_P (not_tmpl))
4458 {
4459 /* We need to be careful here, so as to not explode on
4460 inconsistent data -- we're probably debugging, because
4461 Something Is Wrong. */
4462 unsigned index = import_entity_index (t, true);
4463 if (!(index & ~(~0u >> 1)))
4464 origin = import_entity_module (index)->mod;
4465 else if (index > ~(~0u >> 1))
4466 /* An imported partition member that we're emitting. */
4467 origin = 0;
4468 else
4469 origin = -2;
4470 }
4471
4472 name = DECL_NAME (t) ? DECL_NAME (t)
4473 : HAS_DECL_ASSEMBLER_NAME_P (t) ? DECL_ASSEMBLER_NAME_RAW (t)
4474 : NULL_TREE;
4475 }
4476 else
4477 name = t;
4478
4479 if (name)
4480 switch (TREE_CODE (name))
4481 {
4482 default:
4483 fputs ("#unnamed#", stream);
4484 break;
4485
4486 case IDENTIFIER_NODE:
4487 fwrite (IDENTIFIER_POINTER (name), 1, IDENTIFIER_LENGTH (name), stream);
4488 break;
4489
4490 case INTEGER_CST:
4491 print_hex (wi::to_wide (name), stream);
4492 break;
4493
4494 case STRING_CST:
4495 /* If TREE_TYPE is NULL, this is a raw string. */
4496 fwrite (TREE_STRING_POINTER (name), 1,
4497 TREE_STRING_LENGTH (name) - (TREE_TYPE (name) != NULL_TREE),
4498 stream);
4499 break;
4500 }
4501 else
4502 fputs ("#null#", stream);
4503
4504 if (origin >= 0)
4505 {
4506 const module_state *module = (*modules)[origin];
4507 fprintf (stream, "@%s:%d", !module ? "" : !module->name ? "(unnamed)"
4508 : module->get_flatname (), origin);
4509 }
4510 else if (origin == -2)
4511 fprintf (stream, "@???");
4512
4513 if (ti)
4514 {
4515 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (ti));
4516 fputs ("<", stream);
4517 if (args)
4518 for (int ix = 0; ix != TREE_VEC_LENGTH (args); ix++)
4519 {
4520 if (ix)
4521 fputs (",", stream);
4522 nested_name (TREE_VEC_ELT (args, ix));
4523 }
4524 fputs (">", stream);
4525 }
4526
4527 return true;
4528 }
4529
4530 /* Formatted dumping. FORMAT begins with '+' do not emit a trailing
4531 new line. (Normally it is appended.)
4532 Escapes:
4533 %C - tree_code
4534 %I - identifier
4535 %K - location_t or line_map_uint_t
4536 %M - module_state
4537 %N - name -- DECL_NAME
4538 %P - context:name pair
4539 %R - unsigned:unsigned ratio
4540 %S - symbol -- DECL_ASSEMBLER_NAME
4541 %U - long unsigned
4542 %V - version
4543 --- the following are printf-like, but without its flexibility
4544 %d - decimal int
4545 %p - pointer
4546 %s - string
4547 %u - unsigned int
4548 %x - hex int
4549
4550 We do not implement the printf modifiers. */
4551
4552 bool
4553 dumper::operator () (const char *format, ...)
4554 {
4555 if (!(*this) ())
4556 return false;
4557
4558 bool no_nl = format[0] == '+';
4559 format += no_nl;
4560
4561 if (dumps->bol)
4562 {
4563 /* Module import indent. */
4564 if (unsigned depth = dumps->stack.length () - 1)
4565 {
4566 const char *prefix = ">>>>";
4567 fprintf (dumps->stream, (depth <= strlen (prefix)
4568 ? &prefix[strlen (prefix) - depth]
4569 : ">.%d.>"), depth);
4570 }
4571
4572 /* Local indent. */
4573 if (unsigned indent = dumps->indent)
4574 {
4575 const char *prefix = " ";
4576 fprintf (dumps->stream, (indent <= strlen (prefix)
4577 ? &prefix[strlen (prefix) - indent]
4578 : " .%d. "), indent);
4579 }
4580 dumps->bol = false;
4581 }
4582
4583 va_list args;
4584 va_start (args, format);
4585 while (const char *esc = strchr (format, '%'))
4586 {
4587 fwrite (format, 1, (size_t)(esc - format), dumps->stream);
4588 format = ++esc;
4589 switch (*format++)
4590 {
4591 default:
4592 gcc_unreachable ();
4593
4594 case '%':
4595 fputc ('%', dumps->stream);
4596 break;
4597
4598 case 'C': /* Code */
4599 {
4600 tree_code code = (tree_code)va_arg (args, unsigned);
4601 fputs (get_tree_code_name (code), dumps->stream);
4602 }
4603 break;
4604
4605 case 'I': /* Identifier. */
4606 {
4607 tree t = va_arg (args, tree);
4608 dumps->nested_name (t);
4609 }
4610 break;
4611
4612 case 'K': /* location_t, either 32- or 64-bit. */
4613 {
4614 unsigned long long u = va_arg (args, location_t);
4615 fprintf (dumps->stream, "%llu", u);
4616 }
4617 break;
4618
4619 case 'M': /* Module. */
4620 {
4621 const char *str = "(none)";
4622 if (module_state *m = va_arg (args, module_state *))
4623 {
4624 if (!m->has_location ())
4625 str = "(detached)";
4626 else
4627 str = m->get_flatname ();
4628 }
4629 fputs (str, dumps->stream);
4630 }
4631 break;
4632
4633 case 'N': /* Name. */
4634 {
4635 tree t = va_arg (args, tree);
4636 while (t && TREE_CODE (t) == OVERLOAD)
4637 t = OVL_FUNCTION (t);
4638 fputc ('\'', dumps->stream);
4639 dumps->nested_name (t);
4640 fputc ('\'', dumps->stream);
4641 }
4642 break;
4643
4644 case 'P': /* Pair. */
4645 {
4646 tree ctx = va_arg (args, tree);
4647 tree name = va_arg (args, tree);
4648 fputc ('\'', dumps->stream);
4649 dumps->nested_name (ctx);
4650 if (ctx && ctx != global_namespace)
4651 fputs ("::", dumps->stream);
4652 dumps->nested_name (name);
4653 fputc ('\'', dumps->stream);
4654 }
4655 break;
4656
4657 case 'R': /* Ratio */
4658 {
4659 unsigned a = va_arg (args, unsigned);
4660 unsigned b = va_arg (args, unsigned);
4661 fprintf (dumps->stream, "%.1f", (float) a / (b + !b));
4662 }
4663 break;
4664
4665 case 'S': /* Symbol name */
4666 {
4667 tree t = va_arg (args, tree);
4668 if (t && TYPE_P (t))
4669 t = TYPE_NAME (t);
4670 if (t && HAS_DECL_ASSEMBLER_NAME_P (t)
4671 && DECL_ASSEMBLER_NAME_SET_P (t))
4672 {
4673 fputc ('(', dumps->stream);
4674 fputs (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (t)),
4675 dumps->stream);
4676 fputc (')', dumps->stream);
4677 }
4678 }
4679 break;
4680
4681 case 'U': /* long unsigned. */
4682 {
4683 unsigned long u = va_arg (args, unsigned long);
4684 fprintf (dumps->stream, "%lu", u);
4685 }
4686 break;
4687
4688 case 'V': /* Version. */
4689 {
4690 unsigned v = va_arg (args, unsigned);
4691 verstr_t string;
4692
4693 version2string (v, string);
4694 fputs (string, dumps->stream);
4695 }
4696 break;
4697
4698 case 'c': /* Character. */
4699 {
4700 int c = va_arg (args, int);
4701 fputc (c, dumps->stream);
4702 }
4703 break;
4704
4705 case 'd': /* Decimal Int. */
4706 {
4707 int d = va_arg (args, int);
4708 fprintf (dumps->stream, "%d", d);
4709 }
4710 break;
4711
4712 case 'p': /* Pointer. */
4713 {
4714 void *p = va_arg (args, void *);
4715 fprintf (dumps->stream, "%p", p);
4716 }
4717 break;
4718
4719 case 's': /* String. */
4720 {
4721 const char *s = va_arg (args, char *);
4722 gcc_checking_assert (s);
4723 fputs (s, dumps->stream);
4724 }
4725 break;
4726
4727 case 'u': /* Unsigned. */
4728 {
4729 unsigned u = va_arg (args, unsigned);
4730 fprintf (dumps->stream, "%u", u);
4731 }
4732 break;
4733
4734 case 'x': /* Hex. */
4735 {
4736 unsigned x = va_arg (args, unsigned);
4737 fprintf (dumps->stream, "%x", x);
4738 }
4739 break;
4740 }
4741 }
4742 fputs (format, dumps->stream);
4743 va_end (args);
4744 if (!no_nl)
4745 {
4746 dumps->bol = true;
4747 fputc ('\n', dumps->stream);
4748 }
4749 return true;
4750 }
4751
4752 struct note_def_cache_hasher : ggc_cache_ptr_hash<tree_node>
4753 {
4754 static int keep_cache_entry (tree t)
4755 {
4756 if (!CHECKING_P)
4757 /* GTY is unfortunately not clever enough to conditionalize
4758 this. */
4759 gcc_unreachable ();
4760
4761 if (ggc_marked_p (t))
4762 return -1;
4763
4764 unsigned n = dump.push (NULL);
4765 /* This might or might not be an error. We should note its
4766 dropping whichever. */
4767 dump () && dump ("Dropping %N from note_defs table", t);
4768 dump.pop (n);
4769
4770 return 0;
4771 }
4772 };
4773
4774 /* We should stream each definition at most once.
4775 This needs to be a cache because there are cases where a definition
4776 ends up being not retained, and we need to drop those so we don't
4777 get confused if memory is reallocated. */
4778 typedef hash_table<note_def_cache_hasher> note_defs_table_t;
4779 static GTY((cache)) note_defs_table_t *note_defs;
4780
4781 void
4782 trees_in::assert_definition (tree decl ATTRIBUTE_UNUSED,
4783 bool installing ATTRIBUTE_UNUSED)
4784 {
4785 #if CHECKING_P
4786 tree *slot = note_defs->find_slot (decl, installing ? INSERT : NO_INSERT);
4787 tree not_tmpl = STRIP_TEMPLATE (decl);
4788 if (installing)
4789 {
4790 /* We must be inserting for the first time. */
4791 gcc_assert (!*slot);
4792 *slot = decl;
4793 }
4794 else
4795 /* If this is not the mergeable entity, it should not be in the
4796 table. If it is a non-global-module mergeable entity, it
4797 should be in the table. Global module entities could have been
4798 defined textually in the current TU and so might or might not
4799 be present. */
4800 gcc_assert (!is_duplicate (decl)
4801 ? !slot
4802 : (slot
4803 || !DECL_LANG_SPECIFIC (not_tmpl)
4804 || !DECL_MODULE_PURVIEW_P (not_tmpl)
4805 || (!DECL_MODULE_IMPORT_P (not_tmpl)
4806 && header_module_p ())));
4807
4808 if (not_tmpl != decl)
4809 gcc_assert (!note_defs->find_slot (not_tmpl, NO_INSERT));
4810 #endif
4811 }
4812
4813 void
4814 trees_out::assert_definition (tree decl ATTRIBUTE_UNUSED)
4815 {
4816 #if CHECKING_P
4817 tree *slot = note_defs->find_slot (decl, INSERT);
4818 gcc_assert (!*slot);
4819 *slot = decl;
4820 if (TREE_CODE (decl) == TEMPLATE_DECL)
4821 gcc_assert (!note_defs->find_slot (DECL_TEMPLATE_RESULT (decl), NO_INSERT));
4822 #endif
4823 }
4824
4825 /********************************************************************/
4826 static bool
4827 noisy_p ()
4828 {
4829 if (quiet_flag)
4830 return false;
4831
4832 pp_needs_newline (global_dc->get_reference_printer ()) = true;
4833 diagnostic_set_last_function (global_dc, (diagnostic_info *) NULL);
4834
4835 return true;
4836 }
4837
4838 /* Set the cmi repo. Strip trailing '/', '.' becomes NULL. */
4839
4840 static void
4841 set_cmi_repo (const char *r)
4842 {
4843 XDELETEVEC (cmi_repo);
4844 XDELETEVEC (cmi_path);
4845 cmi_path_alloc = 0;
4846
4847 cmi_repo = NULL;
4848 cmi_repo_length = 0;
4849
4850 if (!r || !r[0])
4851 return;
4852
4853 size_t len = strlen (r);
4854 cmi_repo = XNEWVEC (char, len + 1);
4855 memcpy (cmi_repo, r, len + 1);
4856
4857 if (len > 1 && IS_DIR_SEPARATOR (cmi_repo[len-1]))
4858 len--;
4859 if (len == 1 && cmi_repo[0] == '.')
4860 len--;
4861 cmi_repo[len] = 0;
4862 cmi_repo_length = len;
4863 }
4864
4865 /* TO is a repo-relative name. Provide one that we may use from where
4866 we are. */
4867
4868 static const char *
4869 maybe_add_cmi_prefix (const char *to, size_t *len_p = NULL)
4870 {
4871 size_t len = len_p || cmi_repo_length ? strlen (to) : 0;
4872
4873 if (cmi_repo_length && !IS_ABSOLUTE_PATH (to))
4874 {
4875 if (cmi_path_alloc < cmi_repo_length + len + 2)
4876 {
4877 XDELETEVEC (cmi_path);
4878 cmi_path_alloc = cmi_repo_length + len * 2 + 2;
4879 cmi_path = XNEWVEC (char, cmi_path_alloc);
4880
4881 memcpy (cmi_path, cmi_repo, cmi_repo_length);
4882 cmi_path[cmi_repo_length] = DIR_SEPARATOR;
4883 }
4884
4885 memcpy (&cmi_path[cmi_repo_length + 1], to, len + 1);
4886 len += cmi_repo_length + 1;
4887 to = cmi_path;
4888 }
4889
4890 if (len_p)
4891 *len_p = len;
4892
4893 return to;
4894 }
4895
4896 /* Try and create the directories of PATH. */
4897
4898 static void
4899 create_dirs (char *path)
4900 {
4901 char *base = path;
4902 /* Skip past initial slashes of absolute path. */
4903 while (IS_DIR_SEPARATOR (*base))
4904 base++;
4905
4906 /* Try and create the missing directories. */
4907 for (; *base; base++)
4908 if (IS_DIR_SEPARATOR (*base))
4909 {
4910 char sep = *base;
4911 *base = 0;
4912 int failed = mkdir (path, S_IRWXU | S_IRWXG | S_IRWXO);
4913 dump () && dump ("Mkdir ('%s') errno:=%u", path, failed ? errno : 0);
4914 *base = sep;
4915 if (failed
4916 /* Maybe racing with another creator (of a *different*
4917 module). */
4918 && errno != EEXIST)
4919 break;
4920 }
4921 }
4922
4923 /* Given a CLASSTYPE_DECL_LIST VALUE get the template friend decl,
4924 if that's what this is. */
4925
4926 static tree
4927 friend_from_decl_list (tree frnd)
4928 {
4929 tree res = frnd;
4930
4931 if (TREE_CODE (frnd) != TEMPLATE_DECL)
4932 {
4933 tree tmpl = NULL_TREE;
4934 if (TYPE_P (frnd))
4935 {
4936 res = TYPE_NAME (frnd);
4937 if (CLASS_TYPE_P (frnd)
4938 && CLASSTYPE_TEMPLATE_INFO (frnd))
4939 tmpl = CLASSTYPE_TI_TEMPLATE (frnd);
4940 }
4941 else if (DECL_TEMPLATE_INFO (frnd))
4942 {
4943 tmpl = DECL_TI_TEMPLATE (frnd);
4944 if (TREE_CODE (tmpl) != TEMPLATE_DECL)
4945 tmpl = NULL_TREE;
4946 }
4947
4948 if (tmpl && DECL_TEMPLATE_RESULT (tmpl) == res)
4949 res = tmpl;
4950 }
4951
4952 return res;
4953 }
4954
4955 static tree
4956 find_enum_member (tree ctx, tree name)
4957 {
4958 for (tree values = TYPE_VALUES (ctx);
4959 values; values = TREE_CHAIN (values))
4960 if (DECL_NAME (TREE_VALUE (values)) == name)
4961 return TREE_VALUE (values);
4962
4963 return NULL_TREE;
4964 }
4965
4966 /********************************************************************/
4967 /* Instrumentation gathered writing bytes. */
4968
4969 void
4970 bytes_out::instrument ()
4971 {
4972 dump ("Wrote %u bytes in %u blocks", lengths[3], spans[3]);
4973 dump ("Wrote %u bits in %u bytes", lengths[0] + lengths[1], lengths[2]);
4974 for (unsigned ix = 0; ix < 2; ix++)
4975 dump (" %u %s spans of %R bits", spans[ix],
4976 ix ? "one" : "zero", lengths[ix], spans[ix]);
4977 dump (" %u blocks with %R bits padding", spans[2],
4978 lengths[2] * 8 - (lengths[0] + lengths[1]), spans[2]);
4979 }
4980
4981 /* Instrumentation gathered writing trees. */
4982 void
4983 trees_out::instrument ()
4984 {
4985 if (dump (""))
4986 {
4987 bytes_out::instrument ();
4988 dump ("Wrote:");
4989 dump (" %u decl trees", decl_val_count);
4990 dump (" %u other trees", tree_val_count);
4991 dump (" %u back references", back_ref_count);
4992 dump (" %u TU-local entities", tu_local_count);
4993 dump (" %u null trees", null_count);
4994 }
4995 }
4996
4997 /* Setup and teardown for a tree walk. */
4998
4999 void
5000 trees_out::begin ()
5001 {
5002 gcc_assert (!streaming_p () || !tree_map.elements ());
5003
5004 mark_trees ();
5005 if (streaming_p ())
5006 parent::begin ();
5007 }
5008
5009 unsigned
5010 trees_out::end (elf_out *sink, unsigned name, unsigned *crc_ptr)
5011 {
5012 gcc_checking_assert (streaming_p ());
5013
5014 unmark_trees ();
5015 return parent::end (sink, name, crc_ptr);
5016 }
5017
5018 void
5019 trees_out::end ()
5020 {
5021 gcc_assert (!streaming_p ());
5022
5023 unmark_trees ();
5024 /* Do not parent::end -- we weren't streaming. */
5025 }
5026
5027 void
5028 trees_out::mark_trees ()
5029 {
5030 if (size_t size = tree_map.elements ())
5031 {
5032 /* This isn't our first rodeo, destroy and recreate the
5033 tree_map. I'm a bad bad man. Use the previous size as a
5034 guess for the next one (so not all bad). */
5035 tree_map.~ptr_int_hash_map ();
5036 new (&tree_map) ptr_int_hash_map (size);
5037 }
5038
5039 /* Install the fixed trees, with +ve references. */
5040 unsigned limit = fixed_trees->length ();
5041 for (unsigned ix = 0; ix != limit; ix++)
5042 {
5043 tree val = (*fixed_trees)[ix];
5044 bool existed = tree_map.put (val, ix + tag_fixed);
5045 gcc_checking_assert (!TREE_VISITED (val) && !existed);
5046 TREE_VISITED (val) = true;
5047 }
5048
5049 ref_num = 0;
5050 }
5051
5052 /* Unmark the trees we encountered */
5053
5054 void
5055 trees_out::unmark_trees ()
5056 {
5057 ptr_int_hash_map::iterator end (tree_map.end ());
5058 for (ptr_int_hash_map::iterator iter (tree_map.begin ()); iter != end; ++iter)
5059 {
5060 tree node = reinterpret_cast<tree> ((*iter).first);
5061 int ref = (*iter).second;
5062 /* We should have visited the node, and converted its mergeable
5063 reference to a regular reference. */
5064 gcc_checking_assert (TREE_VISITED (node)
5065 && (ref <= tag_backref || ref >= tag_fixed));
5066 TREE_VISITED (node) = false;
5067 }
5068 }
5069
5070 /* Mark DECL for by-value walking. We do this by inserting it into
5071 the tree map with a reference of zero. May be called multiple
5072 times on the same node. */
5073
5074 void
5075 trees_out::mark_by_value (tree decl)
5076 {
5077 gcc_checking_assert (DECL_P (decl)
5078 /* Enum consts are INTEGER_CSTS. */
5079 || TREE_CODE (decl) == INTEGER_CST
5080 || TREE_CODE (decl) == TREE_BINFO);
5081
5082 if (TREE_VISITED (decl))
5083 /* Must already be forced or fixed. */
5084 gcc_checking_assert (*tree_map.get (decl) >= tag_value);
5085 else
5086 {
5087 bool existed = tree_map.put (decl, tag_value);
5088 gcc_checking_assert (!existed);
5089 TREE_VISITED (decl) = true;
5090 }
5091 }
5092
5093 int
5094 trees_out::get_tag (tree t)
5095 {
5096 gcc_checking_assert (TREE_VISITED (t));
5097 return *tree_map.get (t);
5098 }
5099
5100 /* Insert T into the map, return its tag number. */
5101
5102 int
5103 trees_out::insert (tree t, walk_kind walk)
5104 {
5105 gcc_checking_assert (walk != WK_normal || !TREE_VISITED (t));
5106 int tag = --ref_num;
5107 bool existed;
5108 int &slot = tree_map.get_or_insert (t, &existed);
5109 gcc_checking_assert (TREE_VISITED (t) == existed
5110 && (!existed
5111 || (walk == WK_value && slot == tag_value)));
5112 TREE_VISITED (t) = true;
5113 slot = tag;
5114
5115 return tag;
5116 }
5117
5118 /* Insert T into the backreference array. Return its back reference
5119 number. */
5120
5121 int
5122 trees_in::insert (tree t)
5123 {
5124 gcc_checking_assert (t || get_overrun ());
5125 back_refs.safe_push (t);
5126 return -(int)back_refs.length ();
5127 }
5128
5129 /* A chained set of decls. */
5130
5131 void
5132 trees_out::chained_decls (tree decls)
5133 {
5134 for (; decls; decls = DECL_CHAIN (decls))
5135 tree_node (decls);
5136 tree_node (NULL_TREE);
5137 }
5138
5139 tree
5140 trees_in::chained_decls ()
5141 {
5142 tree decls = NULL_TREE;
5143 for (tree *chain = &decls;;)
5144 if (tree decl = tree_node ())
5145 {
5146 if (!DECL_P (decl) || DECL_CHAIN (decl))
5147 {
5148 set_overrun ();
5149 break;
5150 }
5151 *chain = decl;
5152 chain = &DECL_CHAIN (decl);
5153 }
5154 else
5155 break;
5156
5157 return decls;
5158 }
5159
5160 /* A vector of decls following DECL_CHAIN. */
5161
5162 void
5163 trees_out::vec_chained_decls (tree decls)
5164 {
5165 if (streaming_p ())
5166 {
5167 unsigned len = 0;
5168
5169 for (tree decl = decls; decl; decl = DECL_CHAIN (decl))
5170 len++;
5171 u (len);
5172 }
5173
5174 for (tree decl = decls; decl; decl = DECL_CHAIN (decl))
5175 {
5176 if (DECL_IMPLICIT_TYPEDEF_P (decl)
5177 && TYPE_NAME (TREE_TYPE (decl)) != decl)
5178 /* An anonynmous struct with a typedef name. An odd thing to
5179 write. */
5180 tree_node (NULL_TREE);
5181 else
5182 tree_node (decl);
5183 }
5184 }
5185
5186 vec<tree, va_heap> *
5187 trees_in::vec_chained_decls ()
5188 {
5189 vec<tree, va_heap> *v = NULL;
5190
5191 if (unsigned len = u ())
5192 {
5193 vec_alloc (v, len);
5194
5195 for (unsigned ix = 0; ix < len; ix++)
5196 {
5197 tree decl = tree_node ();
5198 if (decl && !DECL_P (decl))
5199 {
5200 set_overrun ();
5201 break;
5202 }
5203 v->quick_push (decl);
5204 }
5205
5206 if (get_overrun ())
5207 {
5208 vec_free (v);
5209 v = NULL;
5210 }
5211 }
5212
5213 return v;
5214 }
5215
5216 /* A vector of trees. */
5217
5218 void
5219 trees_out::tree_vec (vec<tree, va_gc> *v)
5220 {
5221 unsigned len = vec_safe_length (v);
5222 if (streaming_p ())
5223 u (len);
5224 for (unsigned ix = 0; ix != len; ix++)
5225 tree_node ((*v)[ix]);
5226 }
5227
5228 vec<tree, va_gc> *
5229 trees_in::tree_vec ()
5230 {
5231 vec<tree, va_gc> *v = NULL;
5232 if (unsigned len = u ())
5233 {
5234 vec_alloc (v, len);
5235 for (unsigned ix = 0; ix != len; ix++)
5236 v->quick_push (tree_node ());
5237 }
5238 return v;
5239 }
5240
5241 /* A vector of tree pairs. */
5242
5243 void
5244 trees_out::tree_pair_vec (vec<tree_pair_s, va_gc> *v)
5245 {
5246 unsigned len = vec_safe_length (v);
5247 if (streaming_p ())
5248 u (len);
5249 if (len)
5250 for (unsigned ix = 0; ix != len; ix++)
5251 {
5252 tree_pair_s const &s = (*v)[ix];
5253 tree_node (s.purpose);
5254 tree_node (s.value);
5255 }
5256 }
5257
5258 vec<tree_pair_s, va_gc> *
5259 trees_in::tree_pair_vec ()
5260 {
5261 vec<tree_pair_s, va_gc> *v = NULL;
5262 if (unsigned len = u ())
5263 {
5264 vec_alloc (v, len);
5265 for (unsigned ix = 0; ix != len; ix++)
5266 {
5267 tree_pair_s s;
5268 s.purpose = tree_node ();
5269 s.value = tree_node ();
5270 v->quick_push (s);
5271 }
5272 }
5273 return v;
5274 }
5275
5276 void
5277 trees_out::tree_list (tree list, bool has_purpose)
5278 {
5279 for (; list; list = TREE_CHAIN (list))
5280 {
5281 gcc_checking_assert (TREE_VALUE (list));
5282 tree_node (TREE_VALUE (list));
5283 if (has_purpose)
5284 tree_node (TREE_PURPOSE (list));
5285 }
5286 tree_node (NULL_TREE);
5287 }
5288
5289 tree
5290 trees_in::tree_list (bool has_purpose)
5291 {
5292 tree res = NULL_TREE;
5293
5294 for (tree *chain = &res; tree value = tree_node ();
5295 chain = &TREE_CHAIN (*chain))
5296 {
5297 tree purpose = has_purpose ? tree_node () : NULL_TREE;
5298 *chain = build_tree_list (purpose, value);
5299 }
5300
5301 return res;
5302 }
5303
5304 #define CASE_OMP_SIMD_CODE \
5305 case OMP_SIMD: \
5306 case OMP_STRUCTURED_BLOCK: \
5307 case OMP_LOOP: \
5308 case OMP_ORDERED: \
5309 case OMP_TILE: \
5310 case OMP_UNROLL
5311 #define CASE_OMP_CODE \
5312 case OMP_PARALLEL: \
5313 case OMP_TASK: \
5314 case OMP_FOR: \
5315 case OMP_DISTRIBUTE: \
5316 case OMP_TASKLOOP: \
5317 case OMP_TEAMS: \
5318 case OMP_TARGET_DATA: \
5319 case OMP_TARGET: \
5320 case OMP_SECTIONS: \
5321 case OMP_CRITICAL: \
5322 case OMP_SINGLE: \
5323 case OMP_SCOPE: \
5324 case OMP_TASKGROUP: \
5325 case OMP_MASKED: \
5326 case OMP_DISPATCH: \
5327 case OMP_INTEROP: \
5328 case OMP_MASTER: \
5329 case OMP_TARGET_UPDATE: \
5330 case OMP_TARGET_ENTER_DATA: \
5331 case OMP_TARGET_EXIT_DATA: \
5332 case OMP_METADIRECTIVE: \
5333 case OMP_ATOMIC: \
5334 case OMP_ATOMIC_READ: \
5335 case OMP_ATOMIC_CAPTURE_OLD: \
5336 case OMP_ATOMIC_CAPTURE_NEW
5337 #define CASE_OACC_CODE \
5338 case OACC_PARALLEL: \
5339 case OACC_KERNELS: \
5340 case OACC_SERIAL: \
5341 case OACC_DATA: \
5342 case OACC_HOST_DATA: \
5343 case OACC_LOOP: \
5344 case OACC_CACHE: \
5345 case OACC_DECLARE: \
5346 case OACC_ENTER_DATA: \
5347 case OACC_EXIT_DATA: \
5348 case OACC_UPDATE
5349
5350 /* Start tree write. Write information to allocate the receiving
5351 node. */
5352
5353 void
5354 trees_out::start (tree t, bool code_streamed)
5355 {
5356 if (TYPE_P (t))
5357 {
5358 enum tree_code code = TREE_CODE (t);
5359 gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
5360 /* All these types are TYPE_NON_COMMON. */
5361 gcc_checking_assert (code == RECORD_TYPE
5362 || code == UNION_TYPE
5363 || code == ENUMERAL_TYPE
5364 || code == TEMPLATE_TYPE_PARM
5365 || code == TEMPLATE_TEMPLATE_PARM
5366 || code == BOUND_TEMPLATE_TEMPLATE_PARM);
5367 }
5368
5369 if (!code_streamed)
5370 u (TREE_CODE (t));
5371
5372 switch (TREE_CODE (t))
5373 {
5374 default:
5375 if (VL_EXP_CLASS_P (t))
5376 u (VL_EXP_OPERAND_LENGTH (t));
5377 break;
5378
5379 case INTEGER_CST:
5380 u (TREE_INT_CST_NUNITS (t));
5381 u (TREE_INT_CST_EXT_NUNITS (t));
5382 break;
5383
5384 case OMP_CLAUSE:
5385 u (OMP_CLAUSE_CODE (t));
5386 break;
5387
5388 CASE_OMP_SIMD_CODE:
5389 state->extensions |= SE_OPENMP_SIMD;
5390 break;
5391
5392 CASE_OMP_CODE:
5393 state->extensions |= SE_OPENMP;
5394 break;
5395
5396 CASE_OACC_CODE:
5397 state->extensions |= SE_OPENACC;
5398 break;
5399
5400 case STRING_CST:
5401 str (TREE_STRING_POINTER (t), TREE_STRING_LENGTH (t));
5402 break;
5403
5404 case RAW_DATA_CST:
5405 if (RAW_DATA_OWNER (t) == NULL_TREE)
5406 {
5407 /* Stream RAW_DATA_CST with no owner (i.e. data pointing
5408 into libcpp buffers) as something we can stream in as
5409 STRING_CST which owns the data. */
5410 u (0);
5411 /* Can't use str (RAW_DATA_POINTER (t), RAW_DATA_LENGTH (t));
5412 here as there isn't a null termination after it. */
5413 z (RAW_DATA_LENGTH (t));
5414 if (RAW_DATA_LENGTH (t))
5415 if (void *ptr = buf (RAW_DATA_LENGTH (t) + 1))
5416 {
5417 memcpy (ptr, RAW_DATA_POINTER (t), RAW_DATA_LENGTH (t));
5418 ((char *) ptr)[RAW_DATA_LENGTH (t)] = '\0';
5419 }
5420 }
5421 else
5422 {
5423 gcc_assert (RAW_DATA_LENGTH (t));
5424 u (RAW_DATA_LENGTH (t));
5425 }
5426 break;
5427
5428 case VECTOR_CST:
5429 u (VECTOR_CST_LOG2_NPATTERNS (t));
5430 u (VECTOR_CST_NELTS_PER_PATTERN (t));
5431 break;
5432
5433 case TREE_BINFO:
5434 u (BINFO_N_BASE_BINFOS (t));
5435 break;
5436
5437 case TREE_VEC:
5438 u (TREE_VEC_LENGTH (t));
5439 break;
5440
5441 case FIXED_CST:
5442 gcc_unreachable (); /* Not supported in C++. */
5443 break;
5444
5445 case IDENTIFIER_NODE:
5446 case SSA_NAME:
5447 case TARGET_MEM_REF:
5448 case TRANSLATION_UNIT_DECL:
5449 /* We shouldn't meet these. */
5450 gcc_unreachable ();
5451 break;
5452 }
5453 }
5454
5455 /* Start tree read. Allocate the receiving node. */
5456
5457 tree
5458 trees_in::start (unsigned code)
5459 {
5460 tree t = NULL_TREE;
5461
5462 if (!code)
5463 code = u ();
5464
5465 switch (code)
5466 {
5467 default:
5468 if (code >= MAX_TREE_CODES)
5469 {
5470 fail:
5471 set_overrun ();
5472 return NULL_TREE;
5473 }
5474 else if (TREE_CODE_CLASS (code) == tcc_vl_exp)
5475 {
5476 unsigned ops = u ();
5477 t = build_vl_exp (tree_code (code), ops);
5478 }
5479 else
5480 t = make_node (tree_code (code));
5481 break;
5482
5483 case INTEGER_CST:
5484 {
5485 unsigned n = u ();
5486 unsigned e = u ();
5487 t = make_int_cst (n, e);
5488 }
5489 break;
5490
5491 case OMP_CLAUSE:
5492 t = build_omp_clause (UNKNOWN_LOCATION, omp_clause_code (u ()));
5493 break;
5494
5495 CASE_OMP_SIMD_CODE:
5496 if (!(state->extensions & SE_OPENMP_SIMD))
5497 goto fail;
5498 t = make_node (tree_code (code));
5499 break;
5500
5501 CASE_OMP_CODE:
5502 if (!(state->extensions & SE_OPENMP))
5503 goto fail;
5504 t = make_node (tree_code (code));
5505 break;
5506
5507 CASE_OACC_CODE:
5508 if (!(state->extensions & SE_OPENACC))
5509 goto fail;
5510 t = make_node (tree_code (code));
5511 break;
5512
5513 case STRING_CST:
5514 {
5515 size_t l;
5516 const char *chars = str (&l);
5517 t = build_string (l, chars);
5518 }
5519 break;
5520
5521 case RAW_DATA_CST:
5522 {
5523 size_t l = u ();
5524 if (l == 0)
5525 {
5526 /* Stream in RAW_DATA_CST with no owner as STRING_CST
5527 which owns the data. */
5528 const char *chars = str (&l);
5529 t = build_string (l, chars);
5530 }
5531 else
5532 {
5533 t = make_node (RAW_DATA_CST);
5534 RAW_DATA_LENGTH (t) = l;
5535 }
5536 }
5537 break;
5538
5539 case VECTOR_CST:
5540 {
5541 unsigned log2_npats = u ();
5542 unsigned elts_per = u ();
5543 t = make_vector (log2_npats, elts_per);
5544 }
5545 break;
5546
5547 case TREE_BINFO:
5548 t = make_tree_binfo (u ());
5549 break;
5550
5551 case TREE_VEC:
5552 t = make_tree_vec (u ());
5553 break;
5554
5555 case FIXED_CST:
5556 case IDENTIFIER_NODE:
5557 case SSA_NAME:
5558 case TARGET_MEM_REF:
5559 case TRANSLATION_UNIT_DECL:
5560 goto fail;
5561 }
5562
5563 return t;
5564 }
5565
5566 /* The kinds of interface an importer could have for a decl. */
5567
5568 enum class importer_interface {
5569 unknown, /* The definition may or may not need to be emitted. */
5570 always_import, /* The definition can always be found in another TU. */
5571 always_emit, /* The definition must be emitted in the importer's TU. */
5572 };
5573
5574 /* Returns what kind of interface an importer will have of DECL. */
5575
5576 static importer_interface
5577 get_importer_interface (tree decl)
5578 {
5579 /* Internal linkage entities must be emitted in each importer if
5580 there is a definition available. */
5581 if (!TREE_PUBLIC (decl))
5582 return importer_interface::always_emit;
5583
5584 /* Entities that aren't vague linkage are either not definitions or
5585 will be emitted in this TU, so importers can just refer to an
5586 external definition. */
5587 if (!vague_linkage_p (decl))
5588 return importer_interface::always_import;
5589
5590 /* For explicit instantiations, importers can always rely on there
5591 being a definition in another TU, unless this is a definition
5592 in a header module: in which case the importer will always need
5593 to emit it. */
5594 if (DECL_LANG_SPECIFIC (decl)
5595 && DECL_EXPLICIT_INSTANTIATION (decl))
5596 return (header_module_p () && !DECL_EXTERNAL (decl)
5597 ? importer_interface::always_emit
5598 : importer_interface::always_import);
5599
5600 /* A gnu_inline function is never emitted in any TU. */
5601 if (TREE_CODE (decl) == FUNCTION_DECL
5602 && DECL_DECLARED_INLINE_P (decl)
5603 && lookup_attribute ("gnu_inline", DECL_ATTRIBUTES (decl)))
5604 return importer_interface::always_import;
5605
5606 /* Everything else has vague linkage. */
5607 return importer_interface::unknown;
5608 }
5609
5610 /* The structure streamers access the raw fields, because the
5611 alternative, of using the accessor macros can require using
5612 different accessors for the same underlying field, depending on the
5613 tree code. That's both confusing and annoying. */
5614
5615 /* Read & write the core boolean flags. */
5616
5617 void
5618 trees_out::core_bools (tree t, bits_out& bits)
5619 {
5620 #define WB(X) (bits.b (X))
5621 /* Stream X if COND holds, and if !COND stream a dummy value so that the
5622 overall number of bits streamed is independent of the runtime value
5623 of COND, which allows the compiler to better optimize this function. */
5624 #define WB_IF(COND, X) WB ((COND) ? (X) : false)
5625 tree_code code = TREE_CODE (t);
5626
5627 WB (t->base.side_effects_flag);
5628 WB (t->base.constant_flag);
5629 WB (t->base.addressable_flag);
5630 WB (t->base.volatile_flag);
5631 WB (t->base.readonly_flag);
5632 /* base.asm_written_flag is a property of the current TU's use of
5633 this decl. */
5634 WB (t->base.nowarning_flag);
5635 /* base.visited read as zero (it's set for writer, because that's
5636 how we mark nodes). */
5637 /* base.used_flag is not streamed. Readers may set TREE_USED of
5638 decls they use. */
5639 WB (t->base.nothrow_flag);
5640 WB (t->base.static_flag);
5641 /* This is TYPE_CACHED_VALUES_P for types. */
5642 WB_IF (TREE_CODE_CLASS (code) != tcc_type, t->base.public_flag);
5643 WB (t->base.private_flag);
5644 WB (t->base.protected_flag);
5645 WB (t->base.deprecated_flag);
5646 WB (t->base.default_def_flag);
5647
5648 switch (code)
5649 {
5650 case CALL_EXPR:
5651 case INTEGER_CST:
5652 case SSA_NAME:
5653 case TARGET_MEM_REF:
5654 case TREE_VEC:
5655 /* These use different base.u fields. */
5656 return;
5657
5658 default:
5659 WB (t->base.u.bits.lang_flag_0);
5660 bool flag_1 = t->base.u.bits.lang_flag_1;
5661 if (!flag_1)
5662 ;
5663 else if (code == TEMPLATE_INFO)
5664 /* This is TI_PENDING_TEMPLATE_FLAG, not relevant to reader. */
5665 flag_1 = false;
5666 else if (code == VAR_DECL)
5667 {
5668 /* This is DECL_INITIALIZED_P. */
5669 if (TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
5670 /* We'll set this when reading the definition. */
5671 flag_1 = false;
5672 }
5673 WB (flag_1);
5674 WB (t->base.u.bits.lang_flag_2);
5675 WB (t->base.u.bits.lang_flag_3);
5676 WB (t->base.u.bits.lang_flag_4);
5677 WB (t->base.u.bits.lang_flag_5);
5678 WB (t->base.u.bits.lang_flag_6);
5679 WB (t->base.u.bits.saturating_flag);
5680 WB (t->base.u.bits.unsigned_flag);
5681 WB (t->base.u.bits.packed_flag);
5682 WB (t->base.u.bits.user_align);
5683 WB (t->base.u.bits.nameless_flag);
5684 WB (t->base.u.bits.atomic_flag);
5685 WB (t->base.u.bits.unavailable_flag);
5686 break;
5687 }
5688
5689 if (TREE_CODE_CLASS (code) == tcc_type)
5690 {
5691 WB (t->type_common.no_force_blk_flag);
5692 WB (t->type_common.needs_constructing_flag);
5693 WB (t->type_common.transparent_aggr_flag);
5694 WB (t->type_common.restrict_flag);
5695 WB (t->type_common.string_flag);
5696 WB (t->type_common.lang_flag_0);
5697 WB (t->type_common.lang_flag_1);
5698 WB (t->type_common.lang_flag_2);
5699 WB (t->type_common.lang_flag_3);
5700 WB (t->type_common.lang_flag_4);
5701 WB (t->type_common.lang_flag_5);
5702 WB (t->type_common.lang_flag_6);
5703 WB (t->type_common.typeless_storage);
5704 }
5705
5706 if (TREE_CODE_CLASS (code) != tcc_declaration)
5707 return;
5708
5709 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5710 {
5711 WB (t->decl_common.nonlocal_flag);
5712 WB (t->decl_common.virtual_flag);
5713 WB (t->decl_common.ignored_flag);
5714 WB (t->decl_common.abstract_flag);
5715 WB (t->decl_common.artificial_flag);
5716 WB (t->decl_common.preserve_flag);
5717 WB (t->decl_common.debug_expr_is_from);
5718 WB (t->decl_common.lang_flag_0);
5719 WB (t->decl_common.lang_flag_1);
5720 WB (t->decl_common.lang_flag_2);
5721 WB (t->decl_common.lang_flag_3);
5722 WB (t->decl_common.lang_flag_4);
5723
5724 {
5725 /* This is DECL_INTERFACE_KNOWN: We should redetermine whether
5726 we need to import or export any vague-linkage entities on
5727 stream-in. */
5728 bool interface_known = t->decl_common.lang_flag_5;
5729 if (interface_known
5730 && get_importer_interface (t) == importer_interface::unknown)
5731 interface_known = false;
5732 WB (interface_known);
5733 }
5734
5735 WB (t->decl_common.lang_flag_6);
5736 WB (t->decl_common.lang_flag_7);
5737 WB (t->decl_common.lang_flag_8);
5738 WB (t->decl_common.decl_flag_0);
5739
5740 {
5741 /* DECL_EXTERNAL -> decl_flag_1
5742 == it is defined elsewhere
5743 DECL_NOT_REALLY_EXTERN -> base.not_really_extern
5744 == that was a lie, it is here */
5745
5746 bool is_external = t->decl_common.decl_flag_1;
5747 if (!is_external)
5748 /* decl_flag_1 is DECL_EXTERNAL. Things we emit here, might
5749 well be external from the POV of an importer. */
5750 // FIXME: Do we need to know if this is a TEMPLATE_RESULT --
5751 // a flag from the caller?
5752 switch (code)
5753 {
5754 default:
5755 break;
5756
5757 case VAR_DECL:
5758 if (TREE_PUBLIC (t)
5759 && DECL_VTABLE_OR_VTT_P (t))
5760 /* We handle vtable linkage specially. */
5761 is_external = true;
5762 gcc_fallthrough ();
5763 case FUNCTION_DECL:
5764 if (get_importer_interface (t)
5765 == importer_interface::always_import)
5766 is_external = true;
5767 break;
5768 }
5769 WB (is_external);
5770 }
5771
5772 WB (t->decl_common.decl_flag_2);
5773 WB (t->decl_common.decl_flag_3);
5774 WB (t->decl_common.not_gimple_reg_flag);
5775 WB (t->decl_common.decl_by_reference_flag);
5776 WB (t->decl_common.decl_read_flag);
5777 WB (t->decl_common.decl_nonshareable_flag);
5778 WB (t->decl_common.decl_not_flexarray);
5779 }
5780 else
5781 return;
5782
5783 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5784 {
5785 WB (t->decl_with_vis.defer_output);
5786 WB (t->decl_with_vis.hard_register);
5787 WB (t->decl_with_vis.common_flag);
5788 WB (t->decl_with_vis.in_text_section);
5789 WB (t->decl_with_vis.in_constant_pool);
5790 WB (t->decl_with_vis.dllimport_flag);
5791 WB (t->decl_with_vis.weak_flag);
5792 WB (t->decl_with_vis.seen_in_bind_expr);
5793 WB (t->decl_with_vis.comdat_flag);
5794 WB (t->decl_with_vis.visibility_specified);
5795 WB (t->decl_with_vis.init_priority_p);
5796 WB (t->decl_with_vis.shadowed_for_var_p);
5797 WB (t->decl_with_vis.cxx_constructor);
5798 WB (t->decl_with_vis.cxx_destructor);
5799 WB (t->decl_with_vis.final);
5800 WB (t->decl_with_vis.regdecl_flag);
5801 }
5802 else
5803 return;
5804
5805 if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
5806 {
5807 WB (t->function_decl.static_ctor_flag);
5808 WB (t->function_decl.static_dtor_flag);
5809 WB (t->function_decl.uninlinable);
5810 WB (t->function_decl.possibly_inlined);
5811 WB (t->function_decl.novops_flag);
5812 WB (t->function_decl.returns_twice_flag);
5813 WB (t->function_decl.malloc_flag);
5814 WB (t->function_decl.declared_inline_flag);
5815 WB (t->function_decl.no_inline_warning_flag);
5816 WB (t->function_decl.no_instrument_function_entry_exit);
5817 WB (t->function_decl.no_limit_stack);
5818 WB (t->function_decl.disregard_inline_limits);
5819 WB (t->function_decl.pure_flag);
5820 WB (t->function_decl.looping_const_or_pure_flag);
5821
5822 WB (t->function_decl.has_debug_args_flag);
5823 WB (t->function_decl.versioned_function);
5824 WB (t->function_decl.replaceable_operator);
5825
5826 /* decl_type is a (misnamed) 2 bit discriminator. */
5827 unsigned kind = (unsigned)t->function_decl.decl_type;
5828 WB ((kind >> 0) & 1);
5829 WB ((kind >> 1) & 1);
5830 }
5831 #undef WB_IF
5832 #undef WB
5833 }
5834
5835 bool
5836 trees_in::core_bools (tree t, bits_in& bits)
5837 {
5838 #define RB(X) ((X) = bits.b ())
5839 /* See the comment for WB_IF in trees_out::core_bools. */
5840 #define RB_IF(COND, X) ((COND) ? RB (X) : bits.b ())
5841
5842 tree_code code = TREE_CODE (t);
5843
5844 RB (t->base.side_effects_flag);
5845 RB (t->base.constant_flag);
5846 RB (t->base.addressable_flag);
5847 RB (t->base.volatile_flag);
5848 RB (t->base.readonly_flag);
5849 /* base.asm_written_flag is not streamed. */
5850 RB (t->base.nowarning_flag);
5851 /* base.visited is not streamed. */
5852 /* base.used_flag is not streamed. */
5853 RB (t->base.nothrow_flag);
5854 RB (t->base.static_flag);
5855 RB_IF (TREE_CODE_CLASS (code) != tcc_type, t->base.public_flag);
5856 RB (t->base.private_flag);
5857 RB (t->base.protected_flag);
5858 RB (t->base.deprecated_flag);
5859 RB (t->base.default_def_flag);
5860
5861 switch (code)
5862 {
5863 case CALL_EXPR:
5864 case INTEGER_CST:
5865 case SSA_NAME:
5866 case TARGET_MEM_REF:
5867 case TREE_VEC:
5868 /* These use different base.u fields. */
5869 goto done;
5870
5871 default:
5872 RB (t->base.u.bits.lang_flag_0);
5873 RB (t->base.u.bits.lang_flag_1);
5874 RB (t->base.u.bits.lang_flag_2);
5875 RB (t->base.u.bits.lang_flag_3);
5876 RB (t->base.u.bits.lang_flag_4);
5877 RB (t->base.u.bits.lang_flag_5);
5878 RB (t->base.u.bits.lang_flag_6);
5879 RB (t->base.u.bits.saturating_flag);
5880 RB (t->base.u.bits.unsigned_flag);
5881 RB (t->base.u.bits.packed_flag);
5882 RB (t->base.u.bits.user_align);
5883 RB (t->base.u.bits.nameless_flag);
5884 RB (t->base.u.bits.atomic_flag);
5885 RB (t->base.u.bits.unavailable_flag);
5886 break;
5887 }
5888
5889 if (TREE_CODE_CLASS (code) == tcc_type)
5890 {
5891 RB (t->type_common.no_force_blk_flag);
5892 RB (t->type_common.needs_constructing_flag);
5893 RB (t->type_common.transparent_aggr_flag);
5894 RB (t->type_common.restrict_flag);
5895 RB (t->type_common.string_flag);
5896 RB (t->type_common.lang_flag_0);
5897 RB (t->type_common.lang_flag_1);
5898 RB (t->type_common.lang_flag_2);
5899 RB (t->type_common.lang_flag_3);
5900 RB (t->type_common.lang_flag_4);
5901 RB (t->type_common.lang_flag_5);
5902 RB (t->type_common.lang_flag_6);
5903 RB (t->type_common.typeless_storage);
5904 }
5905
5906 if (TREE_CODE_CLASS (code) != tcc_declaration)
5907 goto done;
5908
5909 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5910 {
5911 RB (t->decl_common.nonlocal_flag);
5912 RB (t->decl_common.virtual_flag);
5913 RB (t->decl_common.ignored_flag);
5914 RB (t->decl_common.abstract_flag);
5915 RB (t->decl_common.artificial_flag);
5916 RB (t->decl_common.preserve_flag);
5917 RB (t->decl_common.debug_expr_is_from);
5918 RB (t->decl_common.lang_flag_0);
5919 RB (t->decl_common.lang_flag_1);
5920 RB (t->decl_common.lang_flag_2);
5921 RB (t->decl_common.lang_flag_3);
5922 RB (t->decl_common.lang_flag_4);
5923 RB (t->decl_common.lang_flag_5);
5924 RB (t->decl_common.lang_flag_6);
5925 RB (t->decl_common.lang_flag_7);
5926 RB (t->decl_common.lang_flag_8);
5927 RB (t->decl_common.decl_flag_0);
5928 RB (t->decl_common.decl_flag_1);
5929 RB (t->decl_common.decl_flag_2);
5930 RB (t->decl_common.decl_flag_3);
5931 RB (t->decl_common.not_gimple_reg_flag);
5932 RB (t->decl_common.decl_by_reference_flag);
5933 RB (t->decl_common.decl_read_flag);
5934 RB (t->decl_common.decl_nonshareable_flag);
5935 RB (t->decl_common.decl_not_flexarray);
5936 }
5937 else
5938 goto done;
5939
5940 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5941 {
5942 RB (t->decl_with_vis.defer_output);
5943 RB (t->decl_with_vis.hard_register);
5944 RB (t->decl_with_vis.common_flag);
5945 RB (t->decl_with_vis.in_text_section);
5946 RB (t->decl_with_vis.in_constant_pool);
5947 RB (t->decl_with_vis.dllimport_flag);
5948 RB (t->decl_with_vis.weak_flag);
5949 RB (t->decl_with_vis.seen_in_bind_expr);
5950 RB (t->decl_with_vis.comdat_flag);
5951 RB (t->decl_with_vis.visibility_specified);
5952 RB (t->decl_with_vis.init_priority_p);
5953 RB (t->decl_with_vis.shadowed_for_var_p);
5954 RB (t->decl_with_vis.cxx_constructor);
5955 RB (t->decl_with_vis.cxx_destructor);
5956 RB (t->decl_with_vis.final);
5957 RB (t->decl_with_vis.regdecl_flag);
5958 }
5959 else
5960 goto done;
5961
5962 if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
5963 {
5964 RB (t->function_decl.static_ctor_flag);
5965 RB (t->function_decl.static_dtor_flag);
5966 RB (t->function_decl.uninlinable);
5967 RB (t->function_decl.possibly_inlined);
5968 RB (t->function_decl.novops_flag);
5969 RB (t->function_decl.returns_twice_flag);
5970 RB (t->function_decl.malloc_flag);
5971 RB (t->function_decl.declared_inline_flag);
5972 RB (t->function_decl.no_inline_warning_flag);
5973 RB (t->function_decl.no_instrument_function_entry_exit);
5974 RB (t->function_decl.no_limit_stack);
5975 RB (t->function_decl.disregard_inline_limits);
5976 RB (t->function_decl.pure_flag);
5977 RB (t->function_decl.looping_const_or_pure_flag);
5978
5979 RB (t->function_decl.has_debug_args_flag);
5980 RB (t->function_decl.versioned_function);
5981 RB (t->function_decl.replaceable_operator);
5982
5983 /* decl_type is a (misnamed) 2 bit discriminator. */
5984 unsigned kind = 0;
5985 kind |= unsigned (bits.b ()) << 0;
5986 kind |= unsigned (bits.b ()) << 1;
5987 t->function_decl.decl_type = function_decl_type (kind);
5988 }
5989 #undef RB_IF
5990 #undef RB
5991 done:
5992 return !get_overrun ();
5993 }
5994
5995 void
5996 trees_out::lang_decl_bools (tree t, bits_out& bits)
5997 {
5998 #define WB(X) (bits.b (X))
5999 const struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
6000
6001 bits.bflush ();
6002 WB (lang->u.base.language == lang_cplusplus);
6003 WB ((lang->u.base.use_template >> 0) & 1);
6004 WB ((lang->u.base.use_template >> 1) & 1);
6005 /* Do not write lang->u.base.not_really_extern, importer will set
6006 when reading the definition (if any). */
6007 WB (lang->u.base.initialized_in_class);
6008 WB (lang->u.base.threadprivate_or_deleted_p);
6009 /* Do not write lang->u.base.anticipated_p, it is a property of the
6010 current TU. */
6011 WB (lang->u.base.friend_or_tls);
6012 WB (lang->u.base.unknown_bound_p);
6013 /* Do not write lang->u.base.odr_used, importer will recalculate if
6014 they do ODR use this decl. */
6015 WB (lang->u.base.concept_p);
6016 WB (lang->u.base.var_declared_inline_p);
6017 WB (lang->u.base.dependent_init_p);
6018 /* When building a header unit, everthing is marked as purview, (so
6019 we know which decls to write). But when we import them we do not
6020 want to mark them as in module purview. */
6021 WB (lang->u.base.module_purview_p && !header_module_p ());
6022 WB (lang->u.base.module_attach_p);
6023 WB (lang->u.base.module_keyed_decls_p);
6024 switch (lang->u.base.selector)
6025 {
6026 default:
6027 gcc_unreachable ();
6028
6029 case lds_fn: /* lang_decl_fn. */
6030 WB (lang->u.fn.global_ctor_p);
6031 WB (lang->u.fn.global_dtor_p);
6032 WB (lang->u.fn.static_function);
6033 WB (lang->u.fn.pure_virtual);
6034 WB (lang->u.fn.defaulted_p);
6035 WB (lang->u.fn.has_in_charge_parm_p);
6036 WB (lang->u.fn.has_vtt_parm_p);
6037 /* There shouldn't be a pending inline at this point. */
6038 gcc_assert (!lang->u.fn.pending_inline_p);
6039 WB (lang->u.fn.nonconverting);
6040 WB (lang->u.fn.thunk_p);
6041 WB (lang->u.fn.this_thunk_p);
6042 /* Do not stream lang->u.hidden_friend_p, it is a property of
6043 the TU. */
6044 WB (lang->u.fn.omp_declare_reduction_p);
6045 WB (lang->u.fn.has_dependent_explicit_spec_p);
6046 WB (lang->u.fn.immediate_fn_p);
6047 WB (lang->u.fn.maybe_deleted);
6048 /* We do not stream lang->u.fn.implicit_constexpr. */
6049 WB (lang->u.fn.escalated_p);
6050 WB (lang->u.fn.xobj_func);
6051 goto lds_min;
6052
6053 case lds_decomp: /* lang_decl_decomp. */
6054 /* No bools. */
6055 goto lds_min;
6056
6057 case lds_min: /* lang_decl_min. */
6058 lds_min:
6059 /* No bools. */
6060 break;
6061
6062 case lds_ns: /* lang_decl_ns. */
6063 /* No bools. */
6064 break;
6065
6066 case lds_parm: /* lang_decl_parm. */
6067 /* No bools. */
6068 break;
6069 }
6070 #undef WB
6071 }
6072
6073 bool
6074 trees_in::lang_decl_bools (tree t, bits_in& bits)
6075 {
6076 #define RB(X) ((X) = bits.b ())
6077 struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
6078
6079 bits.bflush ();
6080 lang->u.base.language = bits.b () ? lang_cplusplus : lang_c;
6081 unsigned v;
6082 v = bits.b () << 0;
6083 v |= bits.b () << 1;
6084 lang->u.base.use_template = v;
6085 /* lang->u.base.not_really_extern is not streamed. */
6086 RB (lang->u.base.initialized_in_class);
6087 RB (lang->u.base.threadprivate_or_deleted_p);
6088 /* lang->u.base.anticipated_p is not streamed. */
6089 RB (lang->u.base.friend_or_tls);
6090 RB (lang->u.base.unknown_bound_p);
6091 /* lang->u.base.odr_used is not streamed. */
6092 RB (lang->u.base.concept_p);
6093 RB (lang->u.base.var_declared_inline_p);
6094 RB (lang->u.base.dependent_init_p);
6095 RB (lang->u.base.module_purview_p);
6096 RB (lang->u.base.module_attach_p);
6097 RB (lang->u.base.module_keyed_decls_p);
6098 switch (lang->u.base.selector)
6099 {
6100 default:
6101 gcc_unreachable ();
6102
6103 case lds_fn: /* lang_decl_fn. */
6104 RB (lang->u.fn.global_ctor_p);
6105 RB (lang->u.fn.global_dtor_p);
6106 RB (lang->u.fn.static_function);
6107 RB (lang->u.fn.pure_virtual);
6108 RB (lang->u.fn.defaulted_p);
6109 RB (lang->u.fn.has_in_charge_parm_p);
6110 RB (lang->u.fn.has_vtt_parm_p);
6111 RB (lang->u.fn.nonconverting);
6112 RB (lang->u.fn.thunk_p);
6113 RB (lang->u.fn.this_thunk_p);
6114 /* lang->u.fn.hidden_friend_p is not streamed. */
6115 RB (lang->u.fn.omp_declare_reduction_p);
6116 RB (lang->u.fn.has_dependent_explicit_spec_p);
6117 RB (lang->u.fn.immediate_fn_p);
6118 RB (lang->u.fn.maybe_deleted);
6119 /* We do not stream lang->u.fn.implicit_constexpr. */
6120 RB (lang->u.fn.escalated_p);
6121 RB (lang->u.fn.xobj_func);
6122 goto lds_min;
6123
6124 case lds_decomp: /* lang_decl_decomp. */
6125 /* No bools. */
6126 goto lds_min;
6127
6128 case lds_min: /* lang_decl_min. */
6129 lds_min:
6130 /* No bools. */
6131 break;
6132
6133 case lds_ns: /* lang_decl_ns. */
6134 /* No bools. */
6135 break;
6136
6137 case lds_parm: /* lang_decl_parm. */
6138 /* No bools. */
6139 break;
6140 }
6141 #undef RB
6142 return !get_overrun ();
6143 }
6144
6145 void
6146 trees_out::lang_type_bools (tree t, bits_out& bits)
6147 {
6148 #define WB(X) (bits.b (X))
6149 const struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
6150
6151 bits.bflush ();
6152 WB (lang->has_type_conversion);
6153 WB (lang->has_copy_ctor);
6154 WB (lang->has_default_ctor);
6155 WB (lang->const_needs_init);
6156 WB (lang->ref_needs_init);
6157 WB (lang->has_const_copy_assign);
6158 WB ((lang->use_template >> 0) & 1);
6159 WB ((lang->use_template >> 1) & 1);
6160
6161 WB (lang->has_mutable);
6162 WB (lang->com_interface);
6163 WB (lang->non_pod_class);
6164 WB (lang->nearly_empty_p);
6165 WB (lang->user_align);
6166 WB (lang->has_copy_assign);
6167 WB (lang->has_new);
6168 WB (lang->has_array_new);
6169
6170 WB ((lang->gets_delete >> 0) & 1);
6171 WB ((lang->gets_delete >> 1) & 1);
6172 WB (lang->interface_only);
6173 WB (lang->interface_unknown);
6174 WB (lang->contains_empty_class_p);
6175 WB (lang->anon_aggr);
6176 WB (lang->non_zero_init);
6177 WB (lang->empty_p);
6178
6179 WB (lang->vec_new_uses_cookie);
6180 WB (lang->declared_class);
6181 WB (lang->diamond_shaped);
6182 WB (lang->repeated_base);
6183 gcc_assert (!lang->being_defined);
6184 // lang->debug_requested
6185 WB (lang->fields_readonly);
6186 WB (lang->ptrmemfunc_flag);
6187
6188 WB (lang->lazy_default_ctor);
6189 WB (lang->lazy_copy_ctor);
6190 WB (lang->lazy_copy_assign);
6191 WB (lang->lazy_destructor);
6192 WB (lang->has_const_copy_ctor);
6193 WB (lang->has_complex_copy_ctor);
6194 WB (lang->has_complex_copy_assign);
6195 WB (lang->non_aggregate);
6196
6197 WB (lang->has_complex_dflt);
6198 WB (lang->has_list_ctor);
6199 WB (lang->non_std_layout);
6200 WB (lang->is_literal);
6201 WB (lang->lazy_move_ctor);
6202 WB (lang->lazy_move_assign);
6203 WB (lang->has_complex_move_ctor);
6204 WB (lang->has_complex_move_assign);
6205
6206 WB (lang->has_constexpr_ctor);
6207 WB (lang->unique_obj_representations);
6208 WB (lang->unique_obj_representations_set);
6209 #undef WB
6210 }
6211
6212 bool
6213 trees_in::lang_type_bools (tree t, bits_in& bits)
6214 {
6215 #define RB(X) ((X) = bits.b ())
6216 struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
6217
6218 bits.bflush ();
6219 RB (lang->has_type_conversion);
6220 RB (lang->has_copy_ctor);
6221 RB (lang->has_default_ctor);
6222 RB (lang->const_needs_init);
6223 RB (lang->ref_needs_init);
6224 RB (lang->has_const_copy_assign);
6225 unsigned v;
6226 v = bits.b () << 0;
6227 v |= bits.b () << 1;
6228 lang->use_template = v;
6229
6230 RB (lang->has_mutable);
6231 RB (lang->com_interface);
6232 RB (lang->non_pod_class);
6233 RB (lang->nearly_empty_p);
6234 RB (lang->user_align);
6235 RB (lang->has_copy_assign);
6236 RB (lang->has_new);
6237 RB (lang->has_array_new);
6238
6239 v = bits.b () << 0;
6240 v |= bits.b () << 1;
6241 lang->gets_delete = v;
6242 RB (lang->interface_only);
6243 RB (lang->interface_unknown);
6244 RB (lang->contains_empty_class_p);
6245 RB (lang->anon_aggr);
6246 RB (lang->non_zero_init);
6247 RB (lang->empty_p);
6248
6249 RB (lang->vec_new_uses_cookie);
6250 RB (lang->declared_class);
6251 RB (lang->diamond_shaped);
6252 RB (lang->repeated_base);
6253 gcc_assert (!lang->being_defined);
6254 gcc_assert (!lang->debug_requested);
6255 RB (lang->fields_readonly);
6256 RB (lang->ptrmemfunc_flag);
6257
6258 RB (lang->lazy_default_ctor);
6259 RB (lang->lazy_copy_ctor);
6260 RB (lang->lazy_copy_assign);
6261 RB (lang->lazy_destructor);
6262 RB (lang->has_const_copy_ctor);
6263 RB (lang->has_complex_copy_ctor);
6264 RB (lang->has_complex_copy_assign);
6265 RB (lang->non_aggregate);
6266
6267 RB (lang->has_complex_dflt);
6268 RB (lang->has_list_ctor);
6269 RB (lang->non_std_layout);
6270 RB (lang->is_literal);
6271 RB (lang->lazy_move_ctor);
6272 RB (lang->lazy_move_assign);
6273 RB (lang->has_complex_move_ctor);
6274 RB (lang->has_complex_move_assign);
6275
6276 RB (lang->has_constexpr_ctor);
6277 RB (lang->unique_obj_representations);
6278 RB (lang->unique_obj_representations_set);
6279 #undef RB
6280 return !get_overrun ();
6281 }
6282
6283 /* Read & write the core values and pointers. */
6284
6285 void
6286 trees_out::core_vals (tree t)
6287 {
6288 #define WU(X) (u (X))
6289 #define WT(X) (tree_node (X))
6290 tree_code code = TREE_CODE (t);
6291
6292 /* First by shape of the tree. */
6293
6294 if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
6295 {
6296 /* Write this early, for better log information. */
6297 WT (t->decl_minimal.name);
6298 if (!DECL_TEMPLATE_PARM_P (t))
6299 WT (t->decl_minimal.context);
6300
6301 if (state)
6302 state->write_location (*this, t->decl_minimal.locus);
6303
6304 if (streaming_p ())
6305 if (has_warning_spec (t))
6306 u (get_warning_spec (t));
6307 }
6308
6309 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
6310 {
6311 /* The only types we write also have TYPE_NON_COMMON. */
6312 gcc_checking_assert (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON));
6313
6314 /* We only stream the main variant. */
6315 gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
6316
6317 /* Stream the name & context first, for better log information */
6318 WT (t->type_common.name);
6319 WT (t->type_common.context);
6320
6321 /* By construction we want to make sure we have the canonical
6322 and main variants already in the type table, so emit them
6323 now. */
6324 WT (t->type_common.main_variant);
6325
6326 tree canonical = t->type_common.canonical;
6327 if (canonical && DECL_TEMPLATE_PARM_P (TYPE_NAME (t)))
6328 /* We do not want to wander into different templates.
6329 Reconstructed on stream in. */
6330 canonical = t;
6331 WT (canonical);
6332
6333 /* type_common.next_variant is internally manipulated. */
6334 /* type_common.pointer_to, type_common.reference_to. */
6335
6336 if (streaming_p ())
6337 {
6338 WU (t->type_common.precision);
6339 WU (t->type_common.contains_placeholder_bits);
6340 WU (t->type_common.mode);
6341 WU (t->type_common.align);
6342 }
6343
6344 if (!RECORD_OR_UNION_CODE_P (code))
6345 {
6346 WT (t->type_common.size);
6347 WT (t->type_common.size_unit);
6348 }
6349 WT (t->type_common.attributes);
6350
6351 WT (t->type_common.common.chain); /* TYPE_STUB_DECL. */
6352 }
6353
6354 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
6355 {
6356 if (streaming_p ())
6357 {
6358 WU (t->decl_common.mode);
6359 WU (t->decl_common.off_align);
6360 WU (t->decl_common.align);
6361 }
6362
6363 /* For templates these hold instantiation (partial and/or
6364 specialization) information. */
6365 if (code != TEMPLATE_DECL)
6366 {
6367 WT (t->decl_common.size);
6368 WT (t->decl_common.size_unit);
6369 }
6370
6371 WT (t->decl_common.attributes);
6372 // FIXME: Does this introduce cross-decl links? For instance
6373 // from instantiation to the template. If so, we'll need more
6374 // deduplication logic. I think we'll need to walk the blocks
6375 // of the owning function_decl's abstract origin in tandem, to
6376 // generate the locating data needed?
6377 WT (t->decl_common.abstract_origin);
6378 }
6379
6380 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
6381 {
6382 WT (t->decl_with_vis.assembler_name);
6383 if (streaming_p ())
6384 WU (t->decl_with_vis.visibility);
6385 }
6386
6387 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
6388 {
6389 if (code == ENUMERAL_TYPE)
6390 {
6391 /* These fields get set even for opaque enums that lack a
6392 definition, so we stream them directly for each ENUMERAL_TYPE.
6393 We stream TYPE_VALUES as part of the definition. */
6394 WT (t->type_non_common.maxval);
6395 WT (t->type_non_common.minval);
6396 }
6397 /* Records and unions hold FIELDS, VFIELD & BINFO on these
6398 things. */
6399 else if (!RECORD_OR_UNION_CODE_P (code))
6400 {
6401 // FIXME: These are from tpl_parm_value's 'type' writing.
6402 // Perhaps it should just be doing them directly?
6403 gcc_checking_assert (code == TEMPLATE_TYPE_PARM
6404 || code == TEMPLATE_TEMPLATE_PARM
6405 || code == BOUND_TEMPLATE_TEMPLATE_PARM);
6406 gcc_checking_assert (!TYPE_CACHED_VALUES_P (t));
6407 WT (t->type_non_common.values);
6408 WT (t->type_non_common.maxval);
6409 WT (t->type_non_common.minval);
6410 }
6411
6412 WT (t->type_non_common.lang_1);
6413 }
6414
6415 if (CODE_CONTAINS_STRUCT (code, TS_EXP))
6416 {
6417 if (state)
6418 state->write_location (*this, t->exp.locus);
6419
6420 if (streaming_p ())
6421 if (has_warning_spec (t))
6422 u (get_warning_spec (t));
6423
6424 bool vl = TREE_CODE_CLASS (code) == tcc_vl_exp;
6425 unsigned limit = (vl ? VL_EXP_OPERAND_LENGTH (t)
6426 : TREE_OPERAND_LENGTH (t));
6427 unsigned ix = unsigned (vl);
6428 if (code == REQUIRES_EXPR)
6429 {
6430 /* The first operand of a REQUIRES_EXPR is a tree chain
6431 of PARM_DECLs. We need to stream this separately as
6432 otherwise we would only stream the first one. */
6433 chained_decls (REQUIRES_EXPR_PARMS (t));
6434 ++ix;
6435 }
6436 for (; ix != limit; ix++)
6437 WT (TREE_OPERAND (t, ix));
6438 }
6439 else
6440 /* The CODE_CONTAINS tables were inaccurate when I started. */
6441 gcc_checking_assert (TREE_CODE_CLASS (code) != tcc_expression
6442 && TREE_CODE_CLASS (code) != tcc_binary
6443 && TREE_CODE_CLASS (code) != tcc_unary
6444 && TREE_CODE_CLASS (code) != tcc_reference
6445 && TREE_CODE_CLASS (code) != tcc_comparison
6446 && TREE_CODE_CLASS (code) != tcc_statement
6447 && TREE_CODE_CLASS (code) != tcc_vl_exp);
6448
6449 /* Then by CODE. Special cases and/or 1:1 tree shape
6450 correspondance. */
6451 switch (code)
6452 {
6453 default:
6454 break;
6455
6456 case ARGUMENT_PACK_SELECT: /* Transient during instantiation. */
6457 case DEFERRED_PARSE: /* Expanded upon completion of
6458 outermost class. */
6459 case IDENTIFIER_NODE: /* Streamed specially. */
6460 case BINDING_VECTOR: /* Only in namespace-scope symbol
6461 table. */
6462 case SSA_NAME:
6463 case TRANSLATION_UNIT_DECL: /* There is only one, it is a
6464 global_tree. */
6465 case USERDEF_LITERAL: /* Expanded during parsing. */
6466 gcc_unreachable (); /* Should never meet. */
6467
6468 /* Constants. */
6469 case COMPLEX_CST:
6470 WT (TREE_REALPART (t));
6471 WT (TREE_IMAGPART (t));
6472 break;
6473
6474 case FIXED_CST:
6475 gcc_unreachable (); /* Not supported in C++. */
6476
6477 case INTEGER_CST:
6478 if (streaming_p ())
6479 {
6480 unsigned num = TREE_INT_CST_EXT_NUNITS (t);
6481 for (unsigned ix = 0; ix != num; ix++)
6482 wu (TREE_INT_CST_ELT (t, ix));
6483 }
6484 break;
6485
6486 case POLY_INT_CST:
6487 if (streaming_p ())
6488 for (unsigned ix = 0; ix != NUM_POLY_INT_COEFFS; ix++)
6489 WT (POLY_INT_CST_COEFF (t, ix));
6490 break;
6491
6492 case REAL_CST:
6493 if (streaming_p ())
6494 buf (TREE_REAL_CST_PTR (t), sizeof (real_value));
6495 break;
6496
6497 case STRING_CST:
6498 /* Streamed during start. */
6499 break;
6500
6501 case RAW_DATA_CST:
6502 if (RAW_DATA_OWNER (t) == NULL_TREE)
6503 break; /* Streamed as STRING_CST during start. */
6504 WT (RAW_DATA_OWNER (t));
6505 if (streaming_p ())
6506 {
6507 if (TREE_CODE (RAW_DATA_OWNER (t)) == RAW_DATA_CST)
6508 z (RAW_DATA_POINTER (t) - RAW_DATA_POINTER (RAW_DATA_OWNER (t)));
6509 else if (TREE_CODE (RAW_DATA_OWNER (t)) == STRING_CST)
6510 z (RAW_DATA_POINTER (t)
6511 - TREE_STRING_POINTER (RAW_DATA_OWNER (t)));
6512 else
6513 gcc_unreachable ();
6514 }
6515 break;
6516
6517 case VECTOR_CST:
6518 for (unsigned ix = vector_cst_encoded_nelts (t); ix--;)
6519 WT (VECTOR_CST_ENCODED_ELT (t, ix));
6520 break;
6521
6522 /* Decls. */
6523 case VAR_DECL:
6524 if (DECL_CONTEXT (t)
6525 && TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
6526 {
6527 if (DECL_HAS_VALUE_EXPR_P (t))
6528 WT (DECL_VALUE_EXPR (t));
6529 break;
6530 }
6531 /* FALLTHROUGH */
6532
6533 case RESULT_DECL:
6534 case PARM_DECL:
6535 if (DECL_HAS_VALUE_EXPR_P (t))
6536 WT (DECL_VALUE_EXPR (t));
6537 /* FALLTHROUGH */
6538
6539 case CONST_DECL:
6540 case IMPORTED_DECL:
6541 WT (t->decl_common.initial);
6542 break;
6543
6544 case FIELD_DECL:
6545 WT (t->field_decl.offset);
6546 WT (t->field_decl.bit_field_type);
6547 WT (t->field_decl.qualifier); /* bitfield unit. */
6548 WT (t->field_decl.bit_offset);
6549 WT (t->field_decl.fcontext);
6550 WT (t->decl_common.initial);
6551 break;
6552
6553 case LABEL_DECL:
6554 if (streaming_p ())
6555 {
6556 WU (t->label_decl.label_decl_uid);
6557 WU (t->label_decl.eh_landing_pad_nr);
6558 }
6559 break;
6560
6561 case FUNCTION_DECL:
6562 if (streaming_p ())
6563 {
6564 /* Builtins can be streamed by value when a header declares
6565 them. */
6566 WU (DECL_BUILT_IN_CLASS (t));
6567 if (DECL_BUILT_IN_CLASS (t) != NOT_BUILT_IN)
6568 WU (DECL_UNCHECKED_FUNCTION_CODE (t));
6569 }
6570
6571 WT (t->function_decl.personality);
6572 /* Rather than streaming target/optimize nodes, we should reconstruct
6573 them on stream-in from any attributes applied to the function. */
6574 if (streaming_p () && t->function_decl.function_specific_target)
6575 warning_at (DECL_SOURCE_LOCATION (t), 0,
6576 "%<target%> attribute currently unsupported in modules");
6577 if (streaming_p () && t->function_decl.function_specific_optimization)
6578 warning_at (DECL_SOURCE_LOCATION (t), 0,
6579 "%<optimize%> attribute currently unsupported in modules");
6580 WT (t->function_decl.vindex);
6581
6582 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
6583 WT (lookup_explicit_specifier (t));
6584 break;
6585
6586 case USING_DECL:
6587 /* USING_DECL_DECLS */
6588 WT (t->decl_common.initial);
6589 /* FALLTHROUGH */
6590
6591 case TYPE_DECL:
6592 /* USING_DECL: USING_DECL_SCOPE */
6593 /* TYPE_DECL: DECL_ORIGINAL_TYPE */
6594 WT (t->decl_non_common.result);
6595 break;
6596
6597 /* Miscellaneous common nodes. */
6598 case BLOCK:
6599 if (state)
6600 {
6601 state->write_location (*this, t->block.locus);
6602 state->write_location (*this, t->block.end_locus);
6603 }
6604
6605 /* DECL_LOCAL_DECL_P decls are first encountered here and
6606 streamed by value. */
6607 for (tree decls = t->block.vars; decls; decls = DECL_CHAIN (decls))
6608 {
6609 if (VAR_OR_FUNCTION_DECL_P (decls)
6610 && DECL_LOCAL_DECL_P (decls))
6611 {
6612 /* Make sure this is the first encounter, and mark for
6613 walk-by-value. */
6614 gcc_checking_assert (!TREE_VISITED (decls)
6615 && !DECL_TEMPLATE_INFO (decls));
6616 mark_by_value (decls);
6617 }
6618 tree_node (decls);
6619 }
6620 tree_node (NULL_TREE);
6621
6622 /* nonlocalized_vars is a middle-end thing. */
6623 WT (t->block.subblocks);
6624 WT (t->block.supercontext);
6625 // FIXME: As for decl's abstract_origin, does this introduce crosslinks?
6626 WT (t->block.abstract_origin);
6627 /* fragment_origin, fragment_chain are middle-end things. */
6628 WT (t->block.chain);
6629 /* nonlocalized_vars, block_num & die are middle endy/debug
6630 things. */
6631 break;
6632
6633 case CALL_EXPR:
6634 if (streaming_p ())
6635 WU (t->base.u.ifn);
6636 break;
6637
6638 case CONSTRUCTOR:
6639 // This must be streamed /after/ we've streamed the type,
6640 // because it can directly refer to elements of the type. Eg,
6641 // FIELD_DECLs of a RECORD_TYPE.
6642 break;
6643
6644 case OMP_CLAUSE:
6645 {
6646 /* The ompcode is serialized in start. */
6647 if (streaming_p ())
6648 WU (t->omp_clause.subcode.map_kind);
6649 if (state)
6650 state->write_location (*this, t->omp_clause.locus);
6651
6652 unsigned len = omp_clause_num_ops[OMP_CLAUSE_CODE (t)];
6653 for (unsigned ix = 0; ix != len; ix++)
6654 WT (t->omp_clause.ops[ix]);
6655 }
6656 break;
6657
6658 case STATEMENT_LIST:
6659 for (tree stmt : tsi_range (t))
6660 if (stmt)
6661 WT (stmt);
6662 WT (NULL_TREE);
6663 break;
6664
6665 case OPTIMIZATION_NODE:
6666 case TARGET_OPTION_NODE:
6667 // FIXME: Our representation for these two nodes is a cache of
6668 // the resulting set of options. Not a record of the options
6669 // that got changed by a particular attribute or pragma. Instead
6670 // of recording that, we probably should just rebuild the options
6671 // on stream-in from the function attributes. This could introduce
6672 // strangeness if the importer has some incompatible set of flags
6673 // but we currently assume users "know what they're doing" in such
6674 // a case anyway.
6675 gcc_unreachable ();
6676 break;
6677
6678 case TREE_BINFO:
6679 {
6680 WT (t->binfo.common.chain);
6681 WT (t->binfo.offset);
6682 WT (t->binfo.inheritance);
6683 WT (t->binfo.vptr_field);
6684
6685 WT (t->binfo.vtable);
6686 WT (t->binfo.virtuals);
6687 WT (t->binfo.vtt_subvtt);
6688 WT (t->binfo.vtt_vptr);
6689
6690 tree_vec (BINFO_BASE_ACCESSES (t));
6691 unsigned num = vec_safe_length (BINFO_BASE_ACCESSES (t));
6692 for (unsigned ix = 0; ix != num; ix++)
6693 WT (BINFO_BASE_BINFO (t, ix));
6694 }
6695 break;
6696
6697 case TREE_LIST:
6698 WT (t->list.purpose);
6699 WT (t->list.value);
6700 WT (t->list.common.chain);
6701 break;
6702
6703 case TREE_VEC:
6704 for (unsigned ix = TREE_VEC_LENGTH (t); ix--;)
6705 WT (TREE_VEC_ELT (t, ix));
6706 /* We stash NON_DEFAULT_TEMPLATE_ARGS_COUNT on TREE_CHAIN! */
6707 gcc_checking_assert (!t->type_common.common.chain
6708 || (TREE_CODE (t->type_common.common.chain)
6709 == INTEGER_CST));
6710 WT (t->type_common.common.chain);
6711 break;
6712
6713 /* C++-specific nodes ... */
6714 case BASELINK:
6715 WT (((lang_tree_node *)t)->baselink.binfo);
6716 WT (((lang_tree_node *)t)->baselink.functions);
6717 WT (((lang_tree_node *)t)->baselink.access_binfo);
6718 WT (((lang_tree_node *)t)->baselink.common.chain);
6719 break;
6720
6721 case CONSTRAINT_INFO:
6722 WT (((lang_tree_node *)t)->constraint_info.template_reqs);
6723 WT (((lang_tree_node *)t)->constraint_info.declarator_reqs);
6724 WT (((lang_tree_node *)t)->constraint_info.associated_constr);
6725 break;
6726
6727 case DEFERRED_NOEXCEPT:
6728 WT (((lang_tree_node *)t)->deferred_noexcept.pattern);
6729 WT (((lang_tree_node *)t)->deferred_noexcept.args);
6730 break;
6731
6732 case LAMBDA_EXPR:
6733 WT (((lang_tree_node *)t)->lambda_expression.capture_list);
6734 WT (((lang_tree_node *)t)->lambda_expression.this_capture);
6735 WT (((lang_tree_node *)t)->lambda_expression.extra_scope);
6736 WT (((lang_tree_node *)t)->lambda_expression.regen_info);
6737 WT (((lang_tree_node *)t)->lambda_expression.extra_args);
6738 /* pending_proxies is a parse-time thing. */
6739 gcc_assert (!((lang_tree_node *)t)->lambda_expression.pending_proxies);
6740 if (state)
6741 state->write_location
6742 (*this, ((lang_tree_node *)t)->lambda_expression.locus);
6743 if (streaming_p ())
6744 {
6745 WU (((lang_tree_node *)t)->lambda_expression.default_capture_mode);
6746 WU (((lang_tree_node *)t)->lambda_expression.discriminator_scope);
6747 WU (((lang_tree_node *)t)->lambda_expression.discriminator_sig);
6748 }
6749 break;
6750
6751 case OVERLOAD:
6752 WT (((lang_tree_node *)t)->overload.function);
6753 WT (t->common.chain);
6754 break;
6755
6756 case PTRMEM_CST:
6757 WT (((lang_tree_node *)t)->ptrmem.member);
6758 break;
6759
6760 case STATIC_ASSERT:
6761 WT (((lang_tree_node *)t)->static_assertion.condition);
6762 WT (((lang_tree_node *)t)->static_assertion.message);
6763 if (state)
6764 state->write_location
6765 (*this, ((lang_tree_node *)t)->static_assertion.location);
6766 break;
6767
6768 case TEMPLATE_DECL:
6769 /* Streamed with the template_decl node itself. */
6770 gcc_checking_assert
6771 (TREE_VISITED (((lang_tree_node *)t)->template_decl.arguments));
6772 gcc_checking_assert
6773 (TREE_VISITED (((lang_tree_node *)t)->template_decl.result));
6774 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (t))
6775 WT (DECL_CHAIN (t));
6776 break;
6777
6778 case TEMPLATE_INFO:
6779 {
6780 WT (((lang_tree_node *)t)->template_info.tmpl);
6781 WT (((lang_tree_node *)t)->template_info.args);
6782 WT (((lang_tree_node *)t)->template_info.partial);
6783
6784 const auto *ac = (((lang_tree_node *)t)
6785 ->template_info.deferred_access_checks);
6786 unsigned len = vec_safe_length (ac);
6787 if (streaming_p ())
6788 u (len);
6789 if (len)
6790 {
6791 for (unsigned ix = 0; ix != len; ix++)
6792 {
6793 const auto &m = (*ac)[ix];
6794 WT (m.binfo);
6795 WT (m.decl);
6796 WT (m.diag_decl);
6797 if (state)
6798 state->write_location (*this, m.loc);
6799 }
6800 }
6801 }
6802 break;
6803
6804 case TEMPLATE_PARM_INDEX:
6805 if (streaming_p ())
6806 {
6807 WU (((lang_tree_node *)t)->tpi.index);
6808 WU (((lang_tree_node *)t)->tpi.level);
6809 WU (((lang_tree_node *)t)->tpi.orig_level);
6810 }
6811 WT (((lang_tree_node *)t)->tpi.decl);
6812 /* TEMPLATE_PARM_DESCENDANTS (AKA TREE_CHAIN) is an internal
6813 cache, do not stream. */
6814 break;
6815
6816 case TRAIT_EXPR:
6817 WT (((lang_tree_node *)t)->trait_expression.type1);
6818 WT (((lang_tree_node *)t)->trait_expression.type2);
6819 if (streaming_p ())
6820 WU (((lang_tree_node *)t)->trait_expression.kind);
6821 break;
6822
6823 case TU_LOCAL_ENTITY:
6824 WT (((lang_tree_node *)t)->tu_local_entity.name);
6825 if (state)
6826 state->write_location
6827 (*this, ((lang_tree_node *)t)->tu_local_entity.loc);
6828 break;
6829 }
6830
6831 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
6832 {
6833 /* We want to stream the type of a expression-like nodes /after/
6834 we've streamed the operands. The type often contains (bits
6835 of the) types of the operands, and with things like decltype
6836 and noexcept in play, we really want to stream the decls
6837 defining the type before we try and stream the type on its
6838 own. Otherwise we can find ourselves trying to read in a
6839 decl, when we're already partially reading in a component of
6840 its type. And that's bad. */
6841 tree type = t->typed.type;
6842 unsigned prec = 0;
6843
6844 switch (code)
6845 {
6846 default:
6847 break;
6848
6849 case TEMPLATE_DECL:
6850 /* We fill in the template's type separately. */
6851 type = NULL_TREE;
6852 break;
6853
6854 case TYPE_DECL:
6855 if (DECL_ORIGINAL_TYPE (t) && t == TYPE_NAME (type))
6856 /* This is a typedef. We set its type separately. */
6857 type = NULL_TREE;
6858 break;
6859
6860 case ENUMERAL_TYPE:
6861 if (type && !ENUM_FIXED_UNDERLYING_TYPE_P (t))
6862 {
6863 /* Type is a restricted range integer type derived from the
6864 integer_types. Find the right one. */
6865 prec = TYPE_PRECISION (type);
6866 tree name = DECL_NAME (TYPE_NAME (type));
6867
6868 for (unsigned itk = itk_none; itk--;)
6869 if (integer_types[itk]
6870 && DECL_NAME (TYPE_NAME (integer_types[itk])) == name)
6871 {
6872 type = integer_types[itk];
6873 break;
6874 }
6875 gcc_assert (type != t->typed.type);
6876 }
6877 break;
6878 }
6879
6880 WT (type);
6881 if (prec && streaming_p ())
6882 WU (prec);
6883 }
6884
6885 if (TREE_CODE (t) == CONSTRUCTOR)
6886 {
6887 unsigned len = vec_safe_length (t->constructor.elts);
6888 if (streaming_p ())
6889 WU (len);
6890 if (len)
6891 for (unsigned ix = 0; ix != len; ix++)
6892 {
6893 const constructor_elt &elt = (*t->constructor.elts)[ix];
6894
6895 WT (elt.index);
6896 WT (elt.value);
6897 }
6898 }
6899
6900 #undef WT
6901 #undef WU
6902 }
6903
6904 // Streaming in a reference to a decl can cause that decl to be
6905 // TREE_USED, which is the mark_used behaviour we need most of the
6906 // time. The trees_in::unused can be incremented to inhibit this,
6907 // which is at least needed for vtables.
6908
6909 bool
6910 trees_in::core_vals (tree t)
6911 {
6912 #define RU(X) ((X) = u ())
6913 #define RUC(T,X) ((X) = T (u ()))
6914 #define RT(X) ((X) = tree_node ())
6915 #define RTU(X) ((X) = tree_node (true))
6916 tree_code code = TREE_CODE (t);
6917
6918 /* First by tree shape. */
6919 if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
6920 {
6921 RT (t->decl_minimal.name);
6922 if (!DECL_TEMPLATE_PARM_P (t))
6923 RT (t->decl_minimal.context);
6924
6925 /* Don't zap the locus just yet, we don't record it correctly
6926 and thus lose all location information. */
6927 t->decl_minimal.locus = state->read_location (*this);
6928 if (has_warning_spec (t))
6929 put_warning_spec (t, u ());
6930 }
6931
6932 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
6933 {
6934 RT (t->type_common.name);
6935 RT (t->type_common.context);
6936
6937 RT (t->type_common.main_variant);
6938 RT (t->type_common.canonical);
6939
6940 /* type_common.next_variant is internally manipulated. */
6941 /* type_common.pointer_to, type_common.reference_to. */
6942
6943 RU (t->type_common.precision);
6944 RU (t->type_common.contains_placeholder_bits);
6945 RUC (machine_mode, t->type_common.mode);
6946 RU (t->type_common.align);
6947
6948 if (!RECORD_OR_UNION_CODE_P (code))
6949 {
6950 RT (t->type_common.size);
6951 RT (t->type_common.size_unit);
6952 }
6953 RT (t->type_common.attributes);
6954
6955 RT (t->type_common.common.chain); /* TYPE_STUB_DECL. */
6956 }
6957
6958 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
6959 {
6960 RUC (machine_mode, t->decl_common.mode);
6961 RU (t->decl_common.off_align);
6962 RU (t->decl_common.align);
6963
6964 if (code != TEMPLATE_DECL)
6965 {
6966 RT (t->decl_common.size);
6967 RT (t->decl_common.size_unit);
6968 }
6969
6970 RT (t->decl_common.attributes);
6971 RT (t->decl_common.abstract_origin);
6972 }
6973
6974 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
6975 {
6976 RT (t->decl_with_vis.assembler_name);
6977 RUC (symbol_visibility, t->decl_with_vis.visibility);
6978 }
6979
6980 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
6981 {
6982 if (code == ENUMERAL_TYPE)
6983 {
6984 /* These fields get set even for opaque enums that lack a
6985 definition, so we stream them directly for each ENUMERAL_TYPE.
6986 We stream TYPE_VALUES as part of the definition. */
6987 RT (t->type_non_common.maxval);
6988 RT (t->type_non_common.minval);
6989 }
6990 /* Records and unions hold FIELDS, VFIELD & BINFO on these
6991 things. */
6992 else if (!RECORD_OR_UNION_CODE_P (code))
6993 {
6994 /* This is not clobbering TYPE_CACHED_VALUES, because this
6995 is a type that doesn't have any. */
6996 gcc_checking_assert (!TYPE_CACHED_VALUES_P (t));
6997 RT (t->type_non_common.values);
6998 RT (t->type_non_common.maxval);
6999 RT (t->type_non_common.minval);
7000 }
7001
7002 RT (t->type_non_common.lang_1);
7003 }
7004
7005 if (CODE_CONTAINS_STRUCT (code, TS_EXP))
7006 {
7007 t->exp.locus = state->read_location (*this);
7008 if (has_warning_spec (t))
7009 put_warning_spec (t, u ());
7010
7011 bool vl = TREE_CODE_CLASS (code) == tcc_vl_exp;
7012 unsigned limit = (vl ? VL_EXP_OPERAND_LENGTH (t)
7013 : TREE_OPERAND_LENGTH (t));
7014 unsigned ix = unsigned (vl);
7015 if (code == REQUIRES_EXPR)
7016 {
7017 REQUIRES_EXPR_PARMS (t) = chained_decls ();
7018 ++ix;
7019 }
7020 for (; ix != limit; ix++)
7021 RTU (TREE_OPERAND (t, ix));
7022 }
7023
7024 /* Then by CODE. Special cases and/or 1:1 tree shape
7025 correspondance. */
7026 switch (code)
7027 {
7028 default:
7029 break;
7030
7031 case ARGUMENT_PACK_SELECT:
7032 case DEFERRED_PARSE:
7033 case IDENTIFIER_NODE:
7034 case BINDING_VECTOR:
7035 case SSA_NAME:
7036 case TRANSLATION_UNIT_DECL:
7037 case USERDEF_LITERAL:
7038 return false; /* Should never meet. */
7039
7040 /* Constants. */
7041 case COMPLEX_CST:
7042 RT (TREE_REALPART (t));
7043 RT (TREE_IMAGPART (t));
7044 break;
7045
7046 case FIXED_CST:
7047 /* Not suported in C++. */
7048 return false;
7049
7050 case INTEGER_CST:
7051 {
7052 unsigned num = TREE_INT_CST_EXT_NUNITS (t);
7053 for (unsigned ix = 0; ix != num; ix++)
7054 TREE_INT_CST_ELT (t, ix) = wu ();
7055 }
7056 break;
7057
7058 case POLY_INT_CST:
7059 for (unsigned ix = 0; ix != NUM_POLY_INT_COEFFS; ix++)
7060 RT (POLY_INT_CST_COEFF (t, ix));
7061 break;
7062
7063 case REAL_CST:
7064 if (const void *bytes = buf (sizeof (real_value)))
7065 memcpy (TREE_REAL_CST_PTR (t), bytes, sizeof (real_value));
7066 break;
7067
7068 case STRING_CST:
7069 /* Streamed during start. */
7070 break;
7071
7072 case RAW_DATA_CST:
7073 RT (RAW_DATA_OWNER (t));
7074 gcc_assert (TREE_CODE (RAW_DATA_OWNER (t)) == STRING_CST
7075 && TREE_STRING_LENGTH (RAW_DATA_OWNER (t)));
7076 RAW_DATA_POINTER (t) = TREE_STRING_POINTER (RAW_DATA_OWNER (t)) + z ();
7077 break;
7078
7079 case VECTOR_CST:
7080 for (unsigned ix = vector_cst_encoded_nelts (t); ix--;)
7081 RT (VECTOR_CST_ENCODED_ELT (t, ix));
7082 break;
7083
7084 /* Decls. */
7085 case VAR_DECL:
7086 if (DECL_CONTEXT (t)
7087 && TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
7088 {
7089 if (DECL_HAS_VALUE_EXPR_P (t))
7090 {
7091 tree val = tree_node ();
7092 SET_DECL_VALUE_EXPR (t, val);
7093 }
7094 break;
7095 }
7096 /* FALLTHROUGH */
7097
7098 case RESULT_DECL:
7099 case PARM_DECL:
7100 if (DECL_HAS_VALUE_EXPR_P (t))
7101 {
7102 /* The DECL_VALUE hash table is a cache, thus if we're
7103 reading a duplicate (which we end up discarding), the
7104 value expr will also be cleaned up at the next gc. */
7105 tree val = tree_node ();
7106 SET_DECL_VALUE_EXPR (t, val);
7107 }
7108 /* FALLTHROUGH */
7109
7110 case CONST_DECL:
7111 case IMPORTED_DECL:
7112 RT (t->decl_common.initial);
7113 break;
7114
7115 case FIELD_DECL:
7116 RT (t->field_decl.offset);
7117 RT (t->field_decl.bit_field_type);
7118 RT (t->field_decl.qualifier);
7119 RT (t->field_decl.bit_offset);
7120 RT (t->field_decl.fcontext);
7121 RT (t->decl_common.initial);
7122 break;
7123
7124 case LABEL_DECL:
7125 RU (t->label_decl.label_decl_uid);
7126 RU (t->label_decl.eh_landing_pad_nr);
7127 break;
7128
7129 case FUNCTION_DECL:
7130 {
7131 unsigned bltin = u ();
7132 t->function_decl.built_in_class = built_in_class (bltin);
7133 if (bltin != NOT_BUILT_IN)
7134 {
7135 bltin = u ();
7136 DECL_UNCHECKED_FUNCTION_CODE (t) = built_in_function (bltin);
7137 }
7138
7139 RT (t->function_decl.personality);
7140 /* These properties are not streamed, and should be reconstructed
7141 from any function attributes. */
7142 // t->function_decl.function_specific_target);
7143 // t->function_decl.function_specific_optimization);
7144 RT (t->function_decl.vindex);
7145
7146 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
7147 {
7148 tree spec;
7149 RT (spec);
7150 store_explicit_specifier (t, spec);
7151 }
7152 }
7153 break;
7154
7155 case USING_DECL:
7156 /* USING_DECL_DECLS */
7157 RT (t->decl_common.initial);
7158 /* FALLTHROUGH */
7159
7160 case TYPE_DECL:
7161 /* USING_DECL: USING_DECL_SCOPE */
7162 /* TYPE_DECL: DECL_ORIGINAL_TYPE */
7163 RT (t->decl_non_common.result);
7164 break;
7165
7166 /* Miscellaneous common nodes. */
7167 case BLOCK:
7168 t->block.locus = state->read_location (*this);
7169 t->block.end_locus = state->read_location (*this);
7170
7171 for (tree *chain = &t->block.vars;;)
7172 if (tree decl = tree_node ())
7173 {
7174 /* For a deduplicated local type or enumerator, chain the
7175 duplicate decl instead of the canonical in-TU decl. Seeing
7176 a duplicate here means the containing function whose body
7177 we're streaming in is a duplicate too, so we'll end up
7178 discarding this BLOCK (and the rest of the duplicate function
7179 body) anyway. */
7180 decl = maybe_duplicate (decl);
7181
7182 if (!DECL_P (decl))
7183 {
7184 set_overrun ();
7185 break;
7186 }
7187
7188 /* If DECL_CHAIN is already set then this was a backreference to a
7189 local type or enumerator from a previous read (PR c++/114630).
7190 Let's copy the node so we can keep building the chain for ODR
7191 checking later. */
7192 if (DECL_CHAIN (decl))
7193 {
7194 gcc_checking_assert (TREE_CODE (decl) == TYPE_DECL
7195 && find_duplicate (DECL_CONTEXT (decl)));
7196 decl = copy_decl (decl);
7197 }
7198
7199 *chain = decl;
7200 chain = &DECL_CHAIN (decl);
7201 }
7202 else
7203 break;
7204
7205 /* nonlocalized_vars is middle-end. */
7206 RT (t->block.subblocks);
7207 RT (t->block.supercontext);
7208 RT (t->block.abstract_origin);
7209 /* fragment_origin, fragment_chain are middle-end. */
7210 RT (t->block.chain);
7211 /* nonlocalized_vars, block_num, die are middle endy/debug
7212 things. */
7213 break;
7214
7215 case CALL_EXPR:
7216 RUC (internal_fn, t->base.u.ifn);
7217 break;
7218
7219 case CONSTRUCTOR:
7220 // Streamed after the node's type.
7221 break;
7222
7223 case OMP_CLAUSE:
7224 {
7225 RU (t->omp_clause.subcode.map_kind);
7226 t->omp_clause.locus = state->read_location (*this);
7227
7228 unsigned len = omp_clause_num_ops[OMP_CLAUSE_CODE (t)];
7229 for (unsigned ix = 0; ix != len; ix++)
7230 RT (t->omp_clause.ops[ix]);
7231 }
7232 break;
7233
7234 case STATEMENT_LIST:
7235 {
7236 tree_stmt_iterator iter = tsi_start (t);
7237 for (tree stmt; RT (stmt);)
7238 {
7239 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT
7240 && !MAY_HAVE_DEBUG_MARKER_STMTS)
7241 continue;
7242 tsi_link_after (&iter, stmt, TSI_CONTINUE_LINKING);
7243 }
7244 }
7245 break;
7246
7247 case OPTIMIZATION_NODE:
7248 case TARGET_OPTION_NODE:
7249 /* Not implemented, see trees_out::core_vals. */
7250 gcc_unreachable ();
7251 break;
7252
7253 case TREE_BINFO:
7254 RT (t->binfo.common.chain);
7255 RT (t->binfo.offset);
7256 RT (t->binfo.inheritance);
7257 RT (t->binfo.vptr_field);
7258
7259 /* Do not mark the vtables as USED in the address expressions
7260 here. */
7261 unused++;
7262 RT (t->binfo.vtable);
7263 RT (t->binfo.virtuals);
7264 RT (t->binfo.vtt_subvtt);
7265 RT (t->binfo.vtt_vptr);
7266 unused--;
7267
7268 BINFO_BASE_ACCESSES (t) = tree_vec ();
7269 if (!get_overrun ())
7270 {
7271 unsigned num = vec_safe_length (BINFO_BASE_ACCESSES (t));
7272 for (unsigned ix = 0; ix != num; ix++)
7273 BINFO_BASE_APPEND (t, tree_node ());
7274 }
7275 break;
7276
7277 case TREE_LIST:
7278 RT (t->list.purpose);
7279 RT (t->list.value);
7280 RT (t->list.common.chain);
7281 break;
7282
7283 case TREE_VEC:
7284 for (unsigned ix = TREE_VEC_LENGTH (t); ix--;)
7285 RT (TREE_VEC_ELT (t, ix));
7286 RT (t->type_common.common.chain);
7287 break;
7288
7289 /* C++-specific nodes ... */
7290 case BASELINK:
7291 RT (((lang_tree_node *)t)->baselink.binfo);
7292 RTU (((lang_tree_node *)t)->baselink.functions);
7293 RT (((lang_tree_node *)t)->baselink.access_binfo);
7294 RT (((lang_tree_node *)t)->baselink.common.chain);
7295 break;
7296
7297 case CONSTRAINT_INFO:
7298 RT (((lang_tree_node *)t)->constraint_info.template_reqs);
7299 RT (((lang_tree_node *)t)->constraint_info.declarator_reqs);
7300 RT (((lang_tree_node *)t)->constraint_info.associated_constr);
7301 break;
7302
7303 case DEFERRED_NOEXCEPT:
7304 RT (((lang_tree_node *)t)->deferred_noexcept.pattern);
7305 RT (((lang_tree_node *)t)->deferred_noexcept.args);
7306 break;
7307
7308 case LAMBDA_EXPR:
7309 RT (((lang_tree_node *)t)->lambda_expression.capture_list);
7310 RT (((lang_tree_node *)t)->lambda_expression.this_capture);
7311 RT (((lang_tree_node *)t)->lambda_expression.extra_scope);
7312 RT (((lang_tree_node *)t)->lambda_expression.regen_info);
7313 RT (((lang_tree_node *)t)->lambda_expression.extra_args);
7314 /* lambda_expression.pending_proxies is NULL */
7315 ((lang_tree_node *)t)->lambda_expression.locus
7316 = state->read_location (*this);
7317 RUC (cp_lambda_default_capture_mode_type,
7318 ((lang_tree_node *)t)->lambda_expression.default_capture_mode);
7319 RU (((lang_tree_node *)t)->lambda_expression.discriminator_scope);
7320 RU (((lang_tree_node *)t)->lambda_expression.discriminator_sig);
7321 break;
7322
7323 case OVERLOAD:
7324 RT (((lang_tree_node *)t)->overload.function);
7325 RT (t->common.chain);
7326 break;
7327
7328 case PTRMEM_CST:
7329 RT (((lang_tree_node *)t)->ptrmem.member);
7330 break;
7331
7332 case STATIC_ASSERT:
7333 RT (((lang_tree_node *)t)->static_assertion.condition);
7334 RT (((lang_tree_node *)t)->static_assertion.message);
7335 ((lang_tree_node *)t)->static_assertion.location
7336 = state->read_location (*this);
7337 break;
7338
7339 case TEMPLATE_DECL:
7340 /* Streamed when reading the raw template decl itself. */
7341 gcc_assert (((lang_tree_node *)t)->template_decl.arguments);
7342 gcc_assert (((lang_tree_node *)t)->template_decl.result);
7343 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (t))
7344 RT (DECL_CHAIN (t));
7345 break;
7346
7347 case TEMPLATE_INFO:
7348 RT (((lang_tree_node *)t)->template_info.tmpl);
7349 RT (((lang_tree_node *)t)->template_info.args);
7350 RT (((lang_tree_node *)t)->template_info.partial);
7351 if (unsigned len = u ())
7352 {
7353 auto &ac = (((lang_tree_node *)t)
7354 ->template_info.deferred_access_checks);
7355 vec_alloc (ac, len);
7356 for (unsigned ix = 0; ix != len; ix++)
7357 {
7358 deferred_access_check m;
7359
7360 RT (m.binfo);
7361 RT (m.decl);
7362 RT (m.diag_decl);
7363 m.loc = state->read_location (*this);
7364 ac->quick_push (m);
7365 }
7366 }
7367 break;
7368
7369 case TEMPLATE_PARM_INDEX:
7370 RU (((lang_tree_node *)t)->tpi.index);
7371 RU (((lang_tree_node *)t)->tpi.level);
7372 RU (((lang_tree_node *)t)->tpi.orig_level);
7373 RT (((lang_tree_node *)t)->tpi.decl);
7374 break;
7375
7376 case TRAIT_EXPR:
7377 RT (((lang_tree_node *)t)->trait_expression.type1);
7378 RT (((lang_tree_node *)t)->trait_expression.type2);
7379 RUC (cp_trait_kind, ((lang_tree_node *)t)->trait_expression.kind);
7380 break;
7381
7382 case TU_LOCAL_ENTITY:
7383 RT (((lang_tree_node *)t)->tu_local_entity.name);
7384 ((lang_tree_node *)t)->tu_local_entity.loc
7385 = state->read_location (*this);
7386 }
7387
7388 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
7389 {
7390 tree type = tree_node ();
7391
7392 if (type && code == ENUMERAL_TYPE && !ENUM_FIXED_UNDERLYING_TYPE_P (t))
7393 {
7394 unsigned precision = u ();
7395
7396 type = build_distinct_type_copy (type);
7397 TYPE_PRECISION (type) = precision;
7398 set_min_and_max_values_for_integral_type (type, precision,
7399 TYPE_SIGN (type));
7400 }
7401
7402 if (code != TEMPLATE_DECL)
7403 t->typed.type = type;
7404 }
7405
7406 if (TREE_CODE (t) == CONSTRUCTOR)
7407 if (unsigned len = u ())
7408 {
7409 vec_alloc (t->constructor.elts, len);
7410 for (unsigned ix = 0; ix != len; ix++)
7411 {
7412 constructor_elt elt;
7413
7414 RT (elt.index);
7415 RTU (elt.value);
7416 t->constructor.elts->quick_push (elt);
7417 }
7418 }
7419
7420 #undef RT
7421 #undef RM
7422 #undef RU
7423 return !get_overrun ();
7424 }
7425
7426 void
7427 trees_out::lang_decl_vals (tree t)
7428 {
7429 const struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
7430 #define WU(X) (u (X))
7431 #define WT(X) (tree_node (X))
7432 /* Module index already written. */
7433 switch (lang->u.base.selector)
7434 {
7435 default:
7436 gcc_unreachable ();
7437
7438 case lds_fn: /* lang_decl_fn. */
7439 if (streaming_p ())
7440 {
7441 if (DECL_NAME (t) && IDENTIFIER_OVL_OP_P (DECL_NAME (t)))
7442 WU (lang->u.fn.ovl_op_code);
7443 }
7444
7445 if (DECL_CLASS_SCOPE_P (t) || DECL_UNIQUE_FRIEND_P (t))
7446 WT (lang->u.fn.context);
7447
7448 if (lang->u.fn.thunk_p)
7449 {
7450 /* The thunked-to function. */
7451 WT (lang->u.fn.befriending_classes);
7452 if (streaming_p ())
7453 wi (lang->u.fn.u5.fixed_offset);
7454 }
7455 else if (decl_tls_wrapper_p (t))
7456 /* The wrapped variable. */
7457 WT (lang->u.fn.befriending_classes);
7458 else
7459 WT (lang->u.fn.u5.cloned_function);
7460
7461 if (FNDECL_USED_AUTO (t))
7462 WT (lang->u.fn.u.saved_auto_return_type);
7463
7464 goto lds_min;
7465
7466 case lds_decomp: /* lang_decl_decomp. */
7467 WT (lang->u.decomp.base);
7468 goto lds_min;
7469
7470 case lds_min: /* lang_decl_min. */
7471 lds_min:
7472 WT (lang->u.min.template_info);
7473 {
7474 tree access = lang->u.min.access;
7475
7476 /* DECL_ACCESS needs to be maintained by the definition of the
7477 (derived) class that changes the access. The other users
7478 of DECL_ACCESS need to write it here. */
7479 if (!DECL_THUNK_P (t)
7480 && (DECL_CONTEXT (t) && TYPE_P (DECL_CONTEXT (t))))
7481 access = NULL_TREE;
7482
7483 WT (access);
7484 }
7485 break;
7486
7487 case lds_ns: /* lang_decl_ns. */
7488 break;
7489
7490 case lds_parm: /* lang_decl_parm. */
7491 if (streaming_p ())
7492 {
7493 WU (lang->u.parm.level);
7494 WU (lang->u.parm.index);
7495 }
7496 break;
7497 }
7498 #undef WU
7499 #undef WT
7500 }
7501
7502 bool
7503 trees_in::lang_decl_vals (tree t)
7504 {
7505 struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
7506 #define RU(X) ((X) = u ())
7507 #define RT(X) ((X) = tree_node ())
7508
7509 /* Module index already read. */
7510 switch (lang->u.base.selector)
7511 {
7512 default:
7513 gcc_unreachable ();
7514
7515 case lds_fn: /* lang_decl_fn. */
7516 if (DECL_NAME (t) && IDENTIFIER_OVL_OP_P (DECL_NAME (t)))
7517 {
7518 unsigned code = u ();
7519
7520 /* Check consistency. */
7521 if (code >= OVL_OP_MAX
7522 || (ovl_op_info[IDENTIFIER_ASSIGN_OP_P (DECL_NAME (t))][code]
7523 .ovl_op_code) == OVL_OP_ERROR_MARK)
7524 set_overrun ();
7525 else
7526 lang->u.fn.ovl_op_code = code;
7527 }
7528
7529 if (DECL_CLASS_SCOPE_P (t) || DECL_UNIQUE_FRIEND_P (t))
7530 RT (lang->u.fn.context);
7531
7532 if (lang->u.fn.thunk_p)
7533 {
7534 RT (lang->u.fn.befriending_classes);
7535 lang->u.fn.u5.fixed_offset = wi ();
7536 }
7537 else if (decl_tls_wrapper_p (t))
7538 RT (lang->u.fn.befriending_classes);
7539 else
7540 RT (lang->u.fn.u5.cloned_function);
7541
7542 if (FNDECL_USED_AUTO (t))
7543 RT (lang->u.fn.u.saved_auto_return_type);
7544 goto lds_min;
7545
7546 case lds_decomp: /* lang_decl_decomp. */
7547 RT (lang->u.decomp.base);
7548 goto lds_min;
7549
7550 case lds_min: /* lang_decl_min. */
7551 lds_min:
7552 RT (lang->u.min.template_info);
7553 RT (lang->u.min.access);
7554 break;
7555
7556 case lds_ns: /* lang_decl_ns. */
7557 break;
7558
7559 case lds_parm: /* lang_decl_parm. */
7560 RU (lang->u.parm.level);
7561 RU (lang->u.parm.index);
7562 break;
7563 }
7564 #undef RU
7565 #undef RT
7566 return !get_overrun ();
7567 }
7568
7569 /* Most of the value contents of lang_type is streamed in
7570 define_class. */
7571
7572 void
7573 trees_out::lang_type_vals (tree t)
7574 {
7575 const struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
7576 #define WU(X) (u (X))
7577 #define WT(X) (tree_node (X))
7578 if (streaming_p ())
7579 WU (lang->align);
7580 #undef WU
7581 #undef WT
7582 }
7583
7584 bool
7585 trees_in::lang_type_vals (tree t)
7586 {
7587 struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
7588 #define RU(X) ((X) = u ())
7589 #define RT(X) ((X) = tree_node ())
7590 RU (lang->align);
7591 #undef RU
7592 #undef RT
7593 return !get_overrun ();
7594 }
7595
7596 /* Write out the bools of T, including information about any
7597 LANG_SPECIFIC information. Including allocation of any lang
7598 specific object. */
7599
7600 void
7601 trees_out::tree_node_bools (tree t)
7602 {
7603 gcc_checking_assert (streaming_p ());
7604
7605 /* We should never stream a namespace. */
7606 gcc_checking_assert (TREE_CODE (t) != NAMESPACE_DECL
7607 || DECL_NAMESPACE_ALIAS (t));
7608
7609 bits_out bits = stream_bits ();
7610 core_bools (t, bits);
7611
7612 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7613 {
7614 case tcc_declaration:
7615 {
7616 bool specific = DECL_LANG_SPECIFIC (t) != NULL;
7617 bits.b (specific);
7618 if (specific && VAR_P (t))
7619 bits.b (DECL_DECOMPOSITION_P (t));
7620 if (specific)
7621 lang_decl_bools (t, bits);
7622 }
7623 break;
7624
7625 case tcc_type:
7626 {
7627 bool specific = (TYPE_MAIN_VARIANT (t) == t
7628 && TYPE_LANG_SPECIFIC (t) != NULL);
7629 gcc_assert (TYPE_LANG_SPECIFIC (t)
7630 == TYPE_LANG_SPECIFIC (TYPE_MAIN_VARIANT (t)));
7631
7632 bits.b (specific);
7633 if (specific)
7634 lang_type_bools (t, bits);
7635 }
7636 break;
7637
7638 default:
7639 break;
7640 }
7641
7642 bits.bflush ();
7643 }
7644
7645 bool
7646 trees_in::tree_node_bools (tree t)
7647 {
7648 bits_in bits = stream_bits ();
7649 bool ok = core_bools (t, bits);
7650
7651 if (ok)
7652 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7653 {
7654 case tcc_declaration:
7655 if (bits.b ())
7656 {
7657 bool decomp = VAR_P (t) && bits.b ();
7658
7659 ok = maybe_add_lang_decl_raw (t, decomp);
7660 if (ok)
7661 ok = lang_decl_bools (t, bits);
7662 }
7663 break;
7664
7665 case tcc_type:
7666 if (bits.b ())
7667 {
7668 ok = maybe_add_lang_type_raw (t);
7669 if (ok)
7670 ok = lang_type_bools (t, bits);
7671 }
7672 break;
7673
7674 default:
7675 break;
7676 }
7677
7678 bits.bflush ();
7679 if (!ok || get_overrun ())
7680 return false;
7681
7682 return true;
7683 }
7684
7685
7686 /* Write out the lang-specifc vals of node T. */
7687
7688 void
7689 trees_out::lang_vals (tree t)
7690 {
7691 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7692 {
7693 case tcc_declaration:
7694 if (DECL_LANG_SPECIFIC (t))
7695 lang_decl_vals (t);
7696 break;
7697
7698 case tcc_type:
7699 if (TYPE_MAIN_VARIANT (t) == t && TYPE_LANG_SPECIFIC (t))
7700 lang_type_vals (t);
7701 break;
7702
7703 default:
7704 break;
7705 }
7706 }
7707
7708 bool
7709 trees_in::lang_vals (tree t)
7710 {
7711 bool ok = true;
7712
7713 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7714 {
7715 case tcc_declaration:
7716 if (DECL_LANG_SPECIFIC (t))
7717 ok = lang_decl_vals (t);
7718 break;
7719
7720 case tcc_type:
7721 if (TYPE_LANG_SPECIFIC (t))
7722 ok = lang_type_vals (t);
7723 else
7724 TYPE_LANG_SPECIFIC (t) = TYPE_LANG_SPECIFIC (TYPE_MAIN_VARIANT (t));
7725 break;
7726
7727 default:
7728 break;
7729 }
7730
7731 return ok;
7732 }
7733
7734 /* Write out the value fields of node T. */
7735
7736 void
7737 trees_out::tree_node_vals (tree t)
7738 {
7739 core_vals (t);
7740 lang_vals (t);
7741 }
7742
7743 bool
7744 trees_in::tree_node_vals (tree t)
7745 {
7746 bool ok = core_vals (t);
7747 if (ok)
7748 ok = lang_vals (t);
7749
7750 return ok;
7751 }
7752
7753
7754 /* If T is a back reference, fixed reference or NULL, write out its
7755 code and return WK_none. Otherwise return WK_value if we must write
7756 by value, or WK_normal otherwise. */
7757
7758 walk_kind
7759 trees_out::ref_node (tree t)
7760 {
7761 if (!t)
7762 {
7763 if (streaming_p ())
7764 {
7765 /* NULL_TREE -> tt_null. */
7766 null_count++;
7767 i (tt_null);
7768 }
7769 return WK_none;
7770 }
7771
7772 if (!TREE_VISITED (t))
7773 return WK_normal;
7774
7775 /* An already-visited tree. It must be in the map. */
7776 int val = get_tag (t);
7777
7778 if (val == tag_value)
7779 /* An entry we should walk into. */
7780 return WK_value;
7781
7782 const char *kind;
7783
7784 if (val <= tag_backref)
7785 {
7786 /* Back reference -> -ve number */
7787 if (streaming_p ())
7788 i (val);
7789 kind = "backref";
7790 }
7791 else if (val >= tag_fixed)
7792 {
7793 /* Fixed reference -> tt_fixed */
7794 val -= tag_fixed;
7795 if (streaming_p ())
7796 i (tt_fixed), u (val);
7797 kind = "fixed";
7798 }
7799
7800 if (streaming_p ())
7801 {
7802 back_ref_count++;
7803 dump (dumper::TREE)
7804 && dump ("Wrote %s:%d %C:%N%S", kind, val, TREE_CODE (t), t, t);
7805 }
7806 return WK_none;
7807 }
7808
7809 tree
7810 trees_in::back_ref (int tag)
7811 {
7812 tree res = NULL_TREE;
7813
7814 if (tag < 0 && unsigned (~tag) < back_refs.length ())
7815 res = back_refs[~tag];
7816
7817 if (!res
7818 /* Checking TREE_CODE is a dereference, so we know this is not a
7819 wild pointer. Checking the code provides evidence we've not
7820 corrupted something. */
7821 || TREE_CODE (res) >= MAX_TREE_CODES)
7822 set_overrun ();
7823 else
7824 dump (dumper::TREE) && dump ("Read backref:%d found %C:%N%S", tag,
7825 TREE_CODE (res), res, res);
7826 return res;
7827 }
7828
7829 unsigned
7830 trees_out::add_indirect_tpl_parms (tree parms)
7831 {
7832 unsigned len = 0;
7833 for (; parms; parms = TREE_CHAIN (parms), len++)
7834 {
7835 if (TREE_VISITED (parms))
7836 break;
7837
7838 int tag = insert (parms);
7839 if (streaming_p ())
7840 dump (dumper::TREE)
7841 && dump ("Indirect:%d template's parameter %u %C:%N",
7842 tag, len, TREE_CODE (parms), parms);
7843 }
7844
7845 if (streaming_p ())
7846 u (len);
7847
7848 return len;
7849 }
7850
7851 unsigned
7852 trees_in::add_indirect_tpl_parms (tree parms)
7853 {
7854 unsigned len = u ();
7855 for (unsigned ix = 0; ix != len; parms = TREE_CHAIN (parms), ix++)
7856 {
7857 int tag = insert (parms);
7858 dump (dumper::TREE)
7859 && dump ("Indirect:%d template's parameter %u %C:%N",
7860 tag, ix, TREE_CODE (parms), parms);
7861 }
7862
7863 return len;
7864 }
7865
7866 /* We've just found DECL by name. Insert nodes that come with it, but
7867 cannot be found by name, so we'll not accidentally walk into them. */
7868
7869 void
7870 trees_out::add_indirects (tree decl)
7871 {
7872 unsigned count = 0;
7873
7874 // FIXME:OPTIMIZATION We'll eventually want default fn parms of
7875 // templates and perhaps default template parms too. The former can
7876 // be referenced from instantiations (as they are lazily
7877 // instantiated). Also (deferred?) exception specifications of
7878 // templates. See the note about PARM_DECLs in trees_out::decl_node.
7879 tree inner = decl;
7880 if (TREE_CODE (decl) == TEMPLATE_DECL)
7881 {
7882 count += add_indirect_tpl_parms (DECL_TEMPLATE_PARMS (decl));
7883
7884 inner = DECL_TEMPLATE_RESULT (decl);
7885 int tag = insert (inner);
7886 if (streaming_p ())
7887 dump (dumper::TREE)
7888 && dump ("Indirect:%d template's result %C:%N",
7889 tag, TREE_CODE (inner), inner);
7890 count++;
7891 }
7892
7893 if (TREE_CODE (inner) == TYPE_DECL)
7894 {
7895 /* Make sure the type is in the map too. Otherwise we get
7896 different RECORD_TYPEs for the same type, and things go
7897 south. */
7898 tree type = TREE_TYPE (inner);
7899 gcc_checking_assert (DECL_ORIGINAL_TYPE (inner)
7900 || TYPE_NAME (type) == inner);
7901 int tag = insert (type);
7902 if (streaming_p ())
7903 dump (dumper::TREE) && dump ("Indirect:%d decl's type %C:%N", tag,
7904 TREE_CODE (type), type);
7905 count++;
7906 }
7907
7908 if (streaming_p ())
7909 {
7910 u (count);
7911 dump (dumper::TREE) && dump ("Inserted %u indirects", count);
7912 }
7913 }
7914
7915 bool
7916 trees_in::add_indirects (tree decl)
7917 {
7918 unsigned count = 0;
7919
7920 tree inner = decl;
7921 if (TREE_CODE (inner) == TEMPLATE_DECL)
7922 {
7923 count += add_indirect_tpl_parms (DECL_TEMPLATE_PARMS (decl));
7924
7925 inner = DECL_TEMPLATE_RESULT (decl);
7926 int tag = insert (inner);
7927 dump (dumper::TREE)
7928 && dump ("Indirect:%d templates's result %C:%N", tag,
7929 TREE_CODE (inner), inner);
7930 count++;
7931 }
7932
7933 if (TREE_CODE (inner) == TYPE_DECL)
7934 {
7935 tree type = TREE_TYPE (inner);
7936 gcc_checking_assert (DECL_ORIGINAL_TYPE (inner)
7937 || TYPE_NAME (type) == inner);
7938 int tag = insert (type);
7939 dump (dumper::TREE)
7940 && dump ("Indirect:%d decl's type %C:%N", tag, TREE_CODE (type), type);
7941 count++;
7942 }
7943
7944 dump (dumper::TREE) && dump ("Inserted %u indirects", count);
7945 return count == u ();
7946 }
7947
7948 /* Stream a template parameter. There are 4.5 kinds of parameter:
7949 a) Template - TEMPLATE_DECL->TYPE_DECL->TEMPLATE_TEMPLATE_PARM
7950 TEMPLATE_TYPE_PARM_INDEX TPI
7951 b) Type - TYPE_DECL->TEMPLATE_TYPE_PARM TEMPLATE_TYPE_PARM_INDEX TPI
7952 c.1) NonTYPE - PARM_DECL DECL_INITIAL TPI We meet this first
7953 c.2) NonTYPE - CONST_DECL DECL_INITIAL Same TPI
7954 d) BoundTemplate - TYPE_DECL->BOUND_TEMPLATE_TEMPLATE_PARM
7955 TEMPLATE_TYPE_PARM_INDEX->TPI
7956 TEMPLATE_TEMPLATE_PARM_INFO->TEMPLATE_INFO
7957
7958 All of these point to a TEMPLATE_PARM_INDEX, and #B also has a TEMPLATE_INFO
7959 */
7960
7961 void
7962 trees_out::tpl_parm_value (tree parm)
7963 {
7964 gcc_checking_assert (DECL_P (parm) && DECL_TEMPLATE_PARM_P (parm));
7965
7966 int parm_tag = insert (parm);
7967 if (streaming_p ())
7968 {
7969 i (tt_tpl_parm);
7970 dump (dumper::TREE) && dump ("Writing template parm:%d %C:%N",
7971 parm_tag, TREE_CODE (parm), parm);
7972 start (parm);
7973 tree_node_bools (parm);
7974 }
7975
7976 tree inner = parm;
7977 if (TREE_CODE (inner) == TEMPLATE_DECL)
7978 {
7979 inner = DECL_TEMPLATE_RESULT (inner);
7980 int inner_tag = insert (inner);
7981 if (streaming_p ())
7982 {
7983 dump (dumper::TREE) && dump ("Writing inner template parm:%d %C:%N",
7984 inner_tag, TREE_CODE (inner), inner);
7985 start (inner);
7986 tree_node_bools (inner);
7987 }
7988 }
7989
7990 tree type = NULL_TREE;
7991 if (TREE_CODE (inner) == TYPE_DECL)
7992 {
7993 type = TREE_TYPE (inner);
7994 int type_tag = insert (type);
7995 if (streaming_p ())
7996 {
7997 dump (dumper::TREE) && dump ("Writing template parm type:%d %C:%N",
7998 type_tag, TREE_CODE (type), type);
7999 start (type);
8000 tree_node_bools (type);
8001 }
8002 }
8003
8004 if (inner != parm)
8005 {
8006 /* This is a template-template parameter. */
8007 unsigned tpl_levels = 0;
8008 tpl_header (parm, &tpl_levels);
8009 tpl_parms_fini (parm, tpl_levels);
8010 }
8011
8012 tree_node_vals (parm);
8013 if (inner != parm)
8014 tree_node_vals (inner);
8015 if (type)
8016 {
8017 tree_node_vals (type);
8018 if (DECL_NAME (inner) == auto_identifier
8019 || DECL_NAME (inner) == decltype_auto_identifier)
8020 {
8021 /* Placeholder auto. */
8022 tree_node (DECL_INITIAL (inner));
8023 tree_node (DECL_SIZE_UNIT (inner));
8024 }
8025 }
8026
8027 if (streaming_p ())
8028 dump (dumper::TREE) && dump ("Wrote template parm:%d %C:%N",
8029 parm_tag, TREE_CODE (parm), parm);
8030 }
8031
8032 tree
8033 trees_in::tpl_parm_value ()
8034 {
8035 tree parm = start ();
8036 if (!parm || !tree_node_bools (parm))
8037 return NULL_TREE;
8038
8039 int parm_tag = insert (parm);
8040 dump (dumper::TREE) && dump ("Reading template parm:%d %C:%N",
8041 parm_tag, TREE_CODE (parm), parm);
8042
8043 tree inner = parm;
8044 if (TREE_CODE (inner) == TEMPLATE_DECL)
8045 {
8046 inner = start ();
8047 if (!inner || !tree_node_bools (inner))
8048 return NULL_TREE;
8049 int inner_tag = insert (inner);
8050 dump (dumper::TREE) && dump ("Reading inner template parm:%d %C:%N",
8051 inner_tag, TREE_CODE (inner), inner);
8052 DECL_TEMPLATE_RESULT (parm) = inner;
8053 }
8054
8055 tree type = NULL_TREE;
8056 if (TREE_CODE (inner) == TYPE_DECL)
8057 {
8058 type = start ();
8059 if (!type || !tree_node_bools (type))
8060 return NULL_TREE;
8061 int type_tag = insert (type);
8062 dump (dumper::TREE) && dump ("Reading template parm type:%d %C:%N",
8063 type_tag, TREE_CODE (type), type);
8064
8065 TREE_TYPE (inner) = TREE_TYPE (parm) = type;
8066 TYPE_NAME (type) = parm;
8067 }
8068
8069 if (inner != parm)
8070 {
8071 /* A template template parameter. */
8072 unsigned tpl_levels = 0;
8073 tpl_header (parm, &tpl_levels);
8074 tpl_parms_fini (parm, tpl_levels);
8075 }
8076
8077 tree_node_vals (parm);
8078 if (inner != parm)
8079 tree_node_vals (inner);
8080 if (type)
8081 {
8082 tree_node_vals (type);
8083 if (DECL_NAME (inner) == auto_identifier
8084 || DECL_NAME (inner) == decltype_auto_identifier)
8085 {
8086 /* Placeholder auto. */
8087 DECL_INITIAL (inner) = tree_node ();
8088 DECL_SIZE_UNIT (inner) = tree_node ();
8089 }
8090 if (TYPE_CANONICAL (type))
8091 {
8092 gcc_checking_assert (TYPE_CANONICAL (type) == type);
8093 TYPE_CANONICAL (type) = canonical_type_parameter (type);
8094 }
8095 }
8096
8097 dump (dumper::TREE) && dump ("Read template parm:%d %C:%N",
8098 parm_tag, TREE_CODE (parm), parm);
8099
8100 return parm;
8101 }
8102
8103 void
8104 trees_out::install_entity (tree decl, depset *dep)
8105 {
8106 gcc_checking_assert (streaming_p ());
8107
8108 /* Write the entity index, so we can insert it as soon as we
8109 know this is new. */
8110 u (dep ? dep->cluster + 1 : 0);
8111 if (CHECKING_P && dep)
8112 {
8113 /* Add it to the entity map, such that we can tell it is
8114 part of us. */
8115 bool existed;
8116 unsigned *slot = &entity_map->get_or_insert
8117 (DECL_UID (decl), &existed);
8118 if (existed)
8119 /* If it existed, it should match. */
8120 gcc_checking_assert (decl == (*entity_ary)[*slot]);
8121 *slot = ~dep->cluster;
8122 }
8123 }
8124
8125 bool
8126 trees_in::install_entity (tree decl)
8127 {
8128 unsigned entity_index = u ();
8129 if (!entity_index)
8130 return false;
8131
8132 if (entity_index > state->entity_num)
8133 {
8134 set_overrun ();
8135 return false;
8136 }
8137
8138 /* Insert the real decl into the entity ary. */
8139 unsigned ident = state->entity_lwm + entity_index - 1;
8140 (*entity_ary)[ident] = decl;
8141
8142 /* And into the entity map, if it's not already there. */
8143 tree not_tmpl = STRIP_TEMPLATE (decl);
8144 if (!DECL_LANG_SPECIFIC (not_tmpl)
8145 || !DECL_MODULE_ENTITY_P (not_tmpl))
8146 {
8147 /* We don't want to use retrofit_lang_decl directly so that we aren't
8148 affected by the language state when we load in. */
8149 if (!DECL_LANG_SPECIFIC (not_tmpl))
8150 {
8151 maybe_add_lang_decl_raw (not_tmpl, false);
8152 SET_DECL_LANGUAGE (not_tmpl, lang_cplusplus);
8153 }
8154 DECL_MODULE_ENTITY_P (not_tmpl) = true;
8155
8156 /* Insert into the entity hash (it cannot already be there). */
8157 bool existed;
8158 unsigned &slot = entity_map->get_or_insert (DECL_UID (decl), &existed);
8159 gcc_checking_assert (!existed);
8160 slot = ident;
8161 }
8162 else
8163 {
8164 unsigned *slot = entity_map->get (DECL_UID (decl));
8165
8166 /* The entity must be in the entity map already. However, DECL may
8167 be the DECL_TEMPLATE_RESULT of an existing partial specialisation
8168 if we matched it while streaming another instantiation; in this
8169 case we already registered that TEMPLATE_DECL. */
8170 if (!slot)
8171 {
8172 tree type = TREE_TYPE (decl);
8173 gcc_checking_assert (TREE_CODE (decl) == TYPE_DECL
8174 && CLASS_TYPE_P (type)
8175 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type));
8176 slot = entity_map->get (DECL_UID (CLASSTYPE_TI_TEMPLATE (type)));
8177 }
8178 gcc_checking_assert (slot);
8179
8180 if (state->is_partition ())
8181 {
8182 /* The decl is already in the entity map, but we see it again now
8183 from a partition: we want to overwrite if the original decl
8184 wasn't also from a (possibly different) partition. Otherwise,
8185 for things like template instantiations, make_dependency might
8186 not realise that this is also provided from a partition and
8187 should be considered part of this module (and thus always
8188 emitted into the primary interface's CMI). */
8189 module_state *imp = import_entity_module (*slot);
8190 if (!imp->is_partition ())
8191 *slot = ident;
8192 }
8193 }
8194
8195 return true;
8196 }
8197
8198 static bool has_definition (tree decl);
8199
8200 /* DECL is a decl node that must be written by value. DEP is the
8201 decl's depset. */
8202
8203 void
8204 trees_out::decl_value (tree decl, depset *dep)
8205 {
8206 /* We should not be writing clones or template parms. */
8207 gcc_checking_assert (DECL_P (decl)
8208 && !DECL_CLONED_FUNCTION_P (decl)
8209 && !DECL_TEMPLATE_PARM_P (decl));
8210
8211 /* We should never be writing non-typedef ptrmemfuncs by value. */
8212 gcc_checking_assert (TREE_CODE (decl) != TYPE_DECL
8213 || DECL_ORIGINAL_TYPE (decl)
8214 || !TYPE_PTRMEMFUNC_P (TREE_TYPE (decl)));
8215
8216 /* There's no need to walk any of the contents of a known TU-local entity,
8217 since importers should never see any of it regardless. But make sure we
8218 at least note its location so importers can use it for diagnostics. */
8219 if (dep && dep->is_tu_local ())
8220 {
8221 gcc_checking_assert (is_initial_scan ());
8222 insert (decl, WK_value);
8223 state->note_location (DECL_SOURCE_LOCATION (decl));
8224 return;
8225 }
8226
8227 merge_kind mk = get_merge_kind (decl, dep);
8228
8229 if (CHECKING_P)
8230 {
8231 /* Never start in the middle of a template. */
8232 int use_tpl = -1;
8233 if (tree ti = node_template_info (decl, use_tpl))
8234 gcc_checking_assert (TREE_CODE (TI_TEMPLATE (ti)) == OVERLOAD
8235 || TREE_CODE (TI_TEMPLATE (ti)) == FIELD_DECL
8236 || (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti))
8237 != decl));
8238 }
8239
8240 if (streaming_p ())
8241 {
8242 /* A new node -> tt_decl. */
8243 decl_val_count++;
8244 i (tt_decl);
8245 u (mk);
8246 start (decl);
8247
8248 if (mk != MK_unique)
8249 {
8250 bits_out bits = stream_bits ();
8251 if (!(mk & MK_template_mask) && !state->is_header ())
8252 {
8253 /* Tell the importer whether this is a global module entity,
8254 or a module entity. */
8255 tree o = get_originating_module_decl (decl);
8256 bool is_attached = false;
8257
8258 tree not_tmpl = STRIP_TEMPLATE (o);
8259 if (DECL_LANG_SPECIFIC (not_tmpl)
8260 && DECL_MODULE_ATTACH_P (not_tmpl))
8261 is_attached = true;
8262
8263 bits.b (is_attached);
8264 }
8265 bits.b (dep && dep->has_defn ());
8266 }
8267 tree_node_bools (decl);
8268 }
8269
8270 int tag = insert (decl, WK_value);
8271 if (streaming_p ())
8272 dump (dumper::TREE)
8273 && dump ("Writing %s:%d %C:%N%S", merge_kind_name[mk], tag,
8274 TREE_CODE (decl), decl, decl);
8275
8276 tree inner = decl;
8277 int inner_tag = 0;
8278 if (TREE_CODE (decl) == TEMPLATE_DECL)
8279 {
8280 inner = DECL_TEMPLATE_RESULT (decl);
8281 inner_tag = insert (inner, WK_value);
8282
8283 if (streaming_p ())
8284 {
8285 int code = TREE_CODE (inner);
8286 u (code);
8287 start (inner, true);
8288 tree_node_bools (inner);
8289 dump (dumper::TREE)
8290 && dump ("Writing %s:%d %C:%N%S", merge_kind_name[mk], inner_tag,
8291 TREE_CODE (inner), inner, inner);
8292 }
8293 }
8294
8295 tree type = NULL_TREE;
8296 int type_tag = 0;
8297 tree stub_decl = NULL_TREE;
8298 int stub_tag = 0;
8299 if (TREE_CODE (inner) == TYPE_DECL)
8300 {
8301 type = TREE_TYPE (inner);
8302 bool has_type = (type == TYPE_MAIN_VARIANT (type)
8303 && TYPE_NAME (type) == inner);
8304
8305 if (streaming_p ())
8306 u (has_type ? TREE_CODE (type) : 0);
8307
8308 if (has_type)
8309 {
8310 type_tag = insert (type, WK_value);
8311 if (streaming_p ())
8312 {
8313 start (type, true);
8314 tree_node_bools (type);
8315 dump (dumper::TREE)
8316 && dump ("Writing type:%d %C:%N", type_tag,
8317 TREE_CODE (type), type);
8318 }
8319
8320 stub_decl = TYPE_STUB_DECL (type);
8321 bool has_stub = inner != stub_decl;
8322 if (streaming_p ())
8323 u (has_stub ? TREE_CODE (stub_decl) : 0);
8324 if (has_stub)
8325 {
8326 stub_tag = insert (stub_decl);
8327 if (streaming_p ())
8328 {
8329 start (stub_decl, true);
8330 tree_node_bools (stub_decl);
8331 dump (dumper::TREE)
8332 && dump ("Writing stub_decl:%d %C:%N", stub_tag,
8333 TREE_CODE (stub_decl), stub_decl);
8334 }
8335 }
8336 else
8337 stub_decl = NULL_TREE;
8338 }
8339 else
8340 /* Regular typedef. */
8341 type = NULL_TREE;
8342 }
8343
8344 /* Stream the container, we want it correctly canonicalized before
8345 we start emitting keys for this decl. */
8346 tree container = decl_container (decl);
8347 unsigned tpl_levels = 0;
8348
8349 /* Also tell the importer whether this is a temploid friend attached
8350 to a different module (which has implications for merging), so that
8351 importers can reconstruct this information on stream-in. */
8352 if (TREE_CODE (inner) == FUNCTION_DECL || TREE_CODE (inner) == TYPE_DECL)
8353 {
8354 tree* temploid_friend_slot = imported_temploid_friends->get (decl);
8355 gcc_checking_assert (!temploid_friend_slot || *temploid_friend_slot);
8356 tree_node (temploid_friend_slot ? *temploid_friend_slot : NULL_TREE);
8357 }
8358
8359 {
8360 auto wmk = make_temp_override (dep_hash->writing_merge_key, true);
8361 if (decl != inner)
8362 tpl_header (decl, &tpl_levels);
8363 if (TREE_CODE (inner) == FUNCTION_DECL)
8364 fn_parms_init (inner);
8365
8366 /* Now write out the merging information, and then really
8367 install the tag values. */
8368 key_mergeable (tag, mk, decl, inner, container, dep);
8369
8370 if (streaming_p ())
8371 dump (dumper::MERGE)
8372 && dump ("Wrote:%d's %s merge key %C:%N", tag,
8373 merge_kind_name[mk], TREE_CODE (decl), decl);
8374 }
8375
8376 if (TREE_CODE (inner) == FUNCTION_DECL)
8377 fn_parms_fini (inner);
8378
8379 if (!is_key_order ())
8380 tree_node_vals (decl);
8381
8382 if (inner_tag)
8383 {
8384 if (!is_key_order ())
8385 tree_node_vals (inner);
8386 tpl_parms_fini (decl, tpl_levels);
8387 }
8388
8389 if (type && !is_key_order ())
8390 {
8391 tree_node_vals (type);
8392 if (stub_decl)
8393 tree_node_vals (stub_decl);
8394 }
8395
8396 if (!is_key_order ())
8397 {
8398 if (mk & MK_template_mask
8399 || mk == MK_partial
8400 || mk == MK_friend_spec)
8401 {
8402 if (mk != MK_partial)
8403 {
8404 // FIXME: We should make use of the merge-key by
8405 // exposing it outside of key_mergeable. But this gets
8406 // the job done.
8407 auto *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
8408
8409 if (streaming_p ())
8410 u (get_mergeable_specialization_flags (mk & MK_tmpl_decl_mask,
8411 entry->tmpl, decl));
8412 tree_node (entry->tmpl);
8413 tree_node (entry->args);
8414 }
8415 else
8416 {
8417 tree ti = get_template_info (inner);
8418 tree_node (TI_TEMPLATE (ti));
8419 tree_node (TI_ARGS (ti));
8420 }
8421 }
8422 tree_node (get_constraints (decl));
8423 }
8424
8425 if (streaming_p ())
8426 {
8427 /* Do not stray outside this section. */
8428 gcc_checking_assert (!dep || dep->section == dep_hash->section);
8429
8430 /* Write the entity index, so we can insert it as soon as we
8431 know this is new. */
8432 install_entity (decl, dep);
8433 }
8434
8435 if (DECL_LANG_SPECIFIC (inner)
8436 && DECL_MODULE_KEYED_DECLS_P (inner)
8437 && !is_key_order ())
8438 {
8439 /* Stream the keyed entities. */
8440 auto *attach_vec = keyed_table->get (inner);
8441 unsigned num = attach_vec->length ();
8442 if (streaming_p ())
8443 u (num);
8444 for (unsigned ix = 0; ix != num; ix++)
8445 {
8446 tree attached = (*attach_vec)[ix];
8447 tree_node (attached);
8448 if (streaming_p ())
8449 dump (dumper::MERGE)
8450 && dump ("Written %d[%u] attached decl %N", tag, ix, attached);
8451 }
8452 }
8453
8454 bool is_typedef = false;
8455 if (!type && TREE_CODE (inner) == TYPE_DECL)
8456 {
8457 tree t = TREE_TYPE (inner);
8458 unsigned tdef_flags = 0;
8459 if (DECL_ORIGINAL_TYPE (inner)
8460 && TYPE_NAME (TREE_TYPE (inner)) == inner)
8461 {
8462 tdef_flags |= 1;
8463 if (TYPE_STRUCTURAL_EQUALITY_P (t)
8464 && TYPE_DEPENDENT_P_VALID (t)
8465 && TYPE_DEPENDENT_P (t))
8466 tdef_flags |= 2;
8467 }
8468 if (streaming_p ())
8469 u (tdef_flags);
8470
8471 if (tdef_flags & 1)
8472 {
8473 /* A typedef type. */
8474 int type_tag = insert (t);
8475 if (streaming_p ())
8476 dump (dumper::TREE)
8477 && dump ("Cloned:%d %s %C:%N", type_tag,
8478 tdef_flags & 2 ? "depalias" : "typedef",
8479 TREE_CODE (t), t);
8480
8481 is_typedef = true;
8482 }
8483 }
8484
8485 if (streaming_p () && DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
8486 {
8487 bool cloned_p
8488 = (DECL_CHAIN (decl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
8489 bool needs_vtt_parm_p
8490 = (cloned_p && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (decl)));
8491 bool omit_inherited_parms_p
8492 = (cloned_p && DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)
8493 && base_ctor_omit_inherited_parms (decl));
8494 unsigned flags = (int (cloned_p) << 0
8495 | int (needs_vtt_parm_p) << 1
8496 | int (omit_inherited_parms_p) << 2);
8497 u (flags);
8498 dump (dumper::TREE) && dump ("CDTOR %N is %scloned",
8499 decl, cloned_p ? "" : "not ");
8500 }
8501
8502 if (streaming_p () && VAR_P (decl) && CP_DECL_THREAD_LOCAL_P (decl))
8503 u (decl_tls_model (decl));
8504
8505 if (streaming_p ())
8506 dump (dumper::TREE) && dump ("Written decl:%d %C:%N", tag,
8507 TREE_CODE (decl), decl);
8508
8509 if (NAMESPACE_SCOPE_P (inner))
8510 gcc_checking_assert (!dep == (VAR_OR_FUNCTION_DECL_P (inner)
8511 && DECL_LOCAL_DECL_P (inner)));
8512 else if ((TREE_CODE (inner) == TYPE_DECL
8513 && !is_typedef
8514 && TYPE_NAME (TREE_TYPE (inner)) == inner)
8515 || TREE_CODE (inner) == FUNCTION_DECL)
8516 {
8517 bool write_defn = !dep && has_definition (decl);
8518 if (streaming_p ())
8519 u (write_defn);
8520 if (write_defn)
8521 write_definition (decl);
8522 }
8523 }
8524
8525 tree
8526 trees_in::decl_value ()
8527 {
8528 int tag = 0;
8529 bool is_attached = false;
8530 bool has_defn = false;
8531 unsigned mk_u = u ();
8532 if (mk_u >= MK_hwm || !merge_kind_name[mk_u])
8533 {
8534 set_overrun ();
8535 return NULL_TREE;
8536 }
8537
8538 unsigned saved_unused = unused;
8539 unused = 0;
8540
8541 merge_kind mk = merge_kind (mk_u);
8542
8543 tree decl = start ();
8544 if (decl)
8545 {
8546 if (mk != MK_unique)
8547 {
8548 bits_in bits = stream_bits ();
8549 if (!(mk & MK_template_mask) && !state->is_header ())
8550 is_attached = bits.b ();
8551
8552 has_defn = bits.b ();
8553 }
8554
8555 if (!tree_node_bools (decl))
8556 decl = NULL_TREE;
8557 }
8558
8559 /* Insert into map. */
8560 tag = insert (decl);
8561 if (decl)
8562 dump (dumper::TREE)
8563 && dump ("Reading:%d %C", tag, TREE_CODE (decl));
8564
8565 tree inner = decl;
8566 int inner_tag = 0;
8567 if (decl && TREE_CODE (decl) == TEMPLATE_DECL)
8568 {
8569 int code = u ();
8570 inner = start (code);
8571 if (inner && tree_node_bools (inner))
8572 DECL_TEMPLATE_RESULT (decl) = inner;
8573 else
8574 decl = NULL_TREE;
8575
8576 inner_tag = insert (inner);
8577 if (decl)
8578 dump (dumper::TREE)
8579 && dump ("Reading:%d %C", inner_tag, TREE_CODE (inner));
8580 }
8581
8582 tree type = NULL_TREE;
8583 int type_tag = 0;
8584 tree stub_decl = NULL_TREE;
8585 int stub_tag = 0;
8586 if (decl && TREE_CODE (inner) == TYPE_DECL)
8587 {
8588 if (unsigned type_code = u ())
8589 {
8590 type = start (type_code);
8591 if (type && tree_node_bools (type))
8592 {
8593 TREE_TYPE (inner) = type;
8594 TYPE_NAME (type) = inner;
8595 }
8596 else
8597 decl = NULL_TREE;
8598
8599 type_tag = insert (type);
8600 if (decl)
8601 dump (dumper::TREE)
8602 && dump ("Reading type:%d %C", type_tag, TREE_CODE (type));
8603
8604 if (unsigned stub_code = u ())
8605 {
8606 stub_decl = start (stub_code);
8607 if (stub_decl && tree_node_bools (stub_decl))
8608 {
8609 TREE_TYPE (stub_decl) = type;
8610 TYPE_STUB_DECL (type) = stub_decl;
8611 }
8612 else
8613 decl = NULL_TREE;
8614
8615 stub_tag = insert (stub_decl);
8616 if (decl)
8617 dump (dumper::TREE)
8618 && dump ("Reading stub_decl:%d %C", stub_tag,
8619 TREE_CODE (stub_decl));
8620 }
8621 }
8622 }
8623
8624 if (!decl)
8625 {
8626 bail:
8627 if (inner_tag != 0)
8628 back_refs[~inner_tag] = NULL_TREE;
8629 if (type_tag != 0)
8630 back_refs[~type_tag] = NULL_TREE;
8631 if (stub_tag != 0)
8632 back_refs[~stub_tag] = NULL_TREE;
8633 if (tag != 0)
8634 back_refs[~tag] = NULL_TREE;
8635 set_overrun ();
8636 /* Bail. */
8637 unused = saved_unused;
8638 return NULL_TREE;
8639 }
8640
8641 /* Read the container, to ensure it's already been streamed in. */
8642 tree container = decl_container ();
8643 unsigned tpl_levels = 0;
8644
8645 /* If this is an imported temploid friend, get the owning decl its
8646 attachment is determined by (or NULL_TREE otherwise). */
8647 tree temploid_friend = NULL_TREE;
8648 if (TREE_CODE (inner) == FUNCTION_DECL || TREE_CODE (inner) == TYPE_DECL)
8649 temploid_friend = tree_node ();
8650
8651 /* Figure out if this decl is already known about. */
8652 int parm_tag = 0;
8653
8654 if (decl != inner)
8655 if (!tpl_header (decl, &tpl_levels))
8656 goto bail;
8657 if (TREE_CODE (inner) == FUNCTION_DECL)
8658 parm_tag = fn_parms_init (inner);
8659
8660 tree existing = key_mergeable (tag, mk, decl, inner, type, container,
8661 is_attached, temploid_friend);
8662 tree existing_inner = existing;
8663 if (existing)
8664 {
8665 if (existing == error_mark_node)
8666 goto bail;
8667
8668 if (TREE_CODE (STRIP_TEMPLATE (existing)) == TYPE_DECL)
8669 {
8670 tree etype = TREE_TYPE (existing);
8671 if (TYPE_LANG_SPECIFIC (etype)
8672 && COMPLETE_TYPE_P (etype)
8673 && !CLASSTYPE_MEMBER_VEC (etype))
8674 /* Give it a member vec, we're likely gonna be looking
8675 inside it. */
8676 set_class_bindings (etype, -1);
8677 }
8678
8679 /* Install the existing decl into the back ref array. */
8680 register_duplicate (decl, existing);
8681 back_refs[~tag] = existing;
8682 if (inner_tag != 0)
8683 {
8684 existing_inner = DECL_TEMPLATE_RESULT (existing);
8685 back_refs[~inner_tag] = existing_inner;
8686 }
8687
8688 if (type_tag != 0)
8689 {
8690 tree existing_type = TREE_TYPE (existing);
8691 back_refs[~type_tag] = existing_type;
8692 if (stub_tag != 0)
8693 back_refs[~stub_tag] = TYPE_STUB_DECL (existing_type);
8694 }
8695 }
8696
8697 if (parm_tag)
8698 fn_parms_fini (parm_tag, inner, existing_inner, has_defn);
8699
8700 if (!tree_node_vals (decl))
8701 goto bail;
8702
8703 if (inner_tag)
8704 {
8705 gcc_checking_assert (DECL_TEMPLATE_RESULT (decl) == inner);
8706
8707 if (!tree_node_vals (inner))
8708 goto bail;
8709
8710 if (!tpl_parms_fini (decl, tpl_levels))
8711 goto bail;
8712 }
8713
8714 if (type && (!tree_node_vals (type)
8715 || (stub_decl && !tree_node_vals (stub_decl))))
8716 goto bail;
8717
8718 spec_entry spec;
8719 unsigned spec_flags = 0;
8720 if (mk & MK_template_mask
8721 || mk == MK_partial
8722 || mk == MK_friend_spec)
8723 {
8724 if (mk == MK_partial)
8725 spec_flags = 2;
8726 else
8727 spec_flags = u ();
8728
8729 spec.tmpl = tree_node ();
8730 spec.args = tree_node ();
8731 }
8732 /* Hold constraints on the spec field, for a short while. */
8733 spec.spec = tree_node ();
8734
8735 dump (dumper::TREE) && dump ("Read:%d %C:%N", tag, TREE_CODE (decl), decl);
8736
8737 existing = back_refs[~tag];
8738 bool installed = install_entity (existing);
8739 bool is_new = existing == decl;
8740
8741 if (DECL_LANG_SPECIFIC (inner)
8742 && DECL_MODULE_KEYED_DECLS_P (inner))
8743 {
8744 /* Read and maybe install the attached entities. */
8745 bool existed;
8746 auto &set = keyed_table->get_or_insert (STRIP_TEMPLATE (existing),
8747 &existed);
8748 unsigned num = u ();
8749 if (is_new == existed)
8750 set_overrun ();
8751 if (is_new)
8752 set.reserve (num);
8753 for (unsigned ix = 0; !get_overrun () && ix != num; ix++)
8754 {
8755 tree attached = tree_node ();
8756 dump (dumper::MERGE)
8757 && dump ("Read %d[%u] %s attached decl %N", tag, ix,
8758 is_new ? "new" : "matched", attached);
8759 if (is_new)
8760 set.quick_push (attached);
8761 else if (set[ix] != attached)
8762 set_overrun ();
8763 }
8764 }
8765
8766 /* Regular typedefs will have a NULL TREE_TYPE at this point. */
8767 unsigned tdef_flags = 0;
8768 bool is_typedef = false;
8769 if (!type && TREE_CODE (inner) == TYPE_DECL)
8770 {
8771 tdef_flags = u ();
8772 if (tdef_flags & 1)
8773 is_typedef = true;
8774 }
8775
8776 if (is_new)
8777 {
8778 /* A newly discovered node. */
8779 if (TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))
8780 /* Mark this identifier as naming a virtual function --
8781 lookup_overrides relies on this optimization. */
8782 IDENTIFIER_VIRTUAL_P (DECL_NAME (decl)) = true;
8783
8784 if (installed)
8785 {
8786 /* Mark the entity as imported. */
8787 retrofit_lang_decl (inner);
8788 DECL_MODULE_IMPORT_P (inner) = true;
8789 }
8790
8791 if (temploid_friend)
8792 imported_temploid_friends->put (decl, temploid_friend);
8793
8794 if (spec.spec)
8795 set_constraints (decl, spec.spec);
8796
8797 if (TREE_CODE (decl) == INTEGER_CST && !TREE_OVERFLOW (decl))
8798 {
8799 decl = cache_integer_cst (decl, true);
8800 back_refs[~tag] = decl;
8801 }
8802
8803 if (is_typedef)
8804 {
8805 /* Frob it to be ready for cloning. */
8806 TREE_TYPE (inner) = DECL_ORIGINAL_TYPE (inner);
8807 DECL_ORIGINAL_TYPE (inner) = NULL_TREE;
8808 if (TREE_CODE (TREE_TYPE (inner)) != TU_LOCAL_ENTITY)
8809 {
8810 set_underlying_type (inner);
8811 if (tdef_flags & 2)
8812 {
8813 /* Match instantiate_alias_template's handling. */
8814 tree type = TREE_TYPE (inner);
8815 TYPE_DEPENDENT_P (type) = true;
8816 TYPE_DEPENDENT_P_VALID (type) = true;
8817 SET_TYPE_STRUCTURAL_EQUALITY (type);
8818 }
8819 }
8820 }
8821
8822 if (inner_tag)
8823 /* Set the TEMPLATE_DECL's type. */
8824 TREE_TYPE (decl) = TREE_TYPE (inner);
8825
8826 /* Redetermine whether we need to import or export this declaration
8827 for this TU. But for extern templates we know we must import:
8828 they'll be defined in a different TU.
8829 FIXME: How do dllexport and dllimport interact across a module?
8830 See also https://github.com/itanium-cxx-abi/cxx-abi/issues/170.
8831 May have to revisit? */
8832 if (type
8833 && CLASS_TYPE_P (type)
8834 && TYPE_LANG_SPECIFIC (type)
8835 && !(CLASSTYPE_EXPLICIT_INSTANTIATION (type)
8836 && CLASSTYPE_INTERFACE_KNOWN (type)
8837 && CLASSTYPE_INTERFACE_ONLY (type)))
8838 {
8839 CLASSTYPE_INTERFACE_ONLY (type) = false;
8840 CLASSTYPE_INTERFACE_UNKNOWN (type) = true;
8841 }
8842
8843 /* Add to specialization tables now that constraints etc are
8844 added. */
8845 if (mk == MK_partial)
8846 {
8847 bool is_type = TREE_CODE (inner) == TYPE_DECL;
8848 spec.spec = is_type ? type : inner;
8849 add_mergeable_specialization (!is_type, &spec, decl, spec_flags);
8850 }
8851 else if (mk & MK_template_mask)
8852 {
8853 bool is_type = !(mk & MK_tmpl_decl_mask);
8854 spec.spec = is_type ? type : mk & MK_tmpl_tmpl_mask ? inner : decl;
8855 add_mergeable_specialization (!is_type, &spec, decl, spec_flags);
8856 }
8857
8858 if (NAMESPACE_SCOPE_P (decl)
8859 && (mk == MK_named || mk == MK_unique
8860 || mk == MK_enum || mk == MK_friend_spec)
8861 && !(VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl)))
8862 add_module_namespace_decl (CP_DECL_CONTEXT (decl), decl);
8863
8864 if (DECL_ARTIFICIAL (decl)
8865 && TREE_CODE (decl) == FUNCTION_DECL
8866 && !DECL_TEMPLATE_INFO (decl)
8867 && DECL_CONTEXT (decl) && TYPE_P (DECL_CONTEXT (decl))
8868 && TYPE_SIZE (DECL_CONTEXT (decl))
8869 && !DECL_THUNK_P (decl))
8870 /* A new implicit member function, when the class is
8871 complete. This means the importee declared it, and
8872 we must now add it to the class. Note that implicit
8873 member fns of template instantiations do not themselves
8874 look like templates. */
8875 if (!install_implicit_member (inner))
8876 set_overrun ();
8877
8878 /* When importing a TLS wrapper from a header unit, we haven't
8879 actually emitted its definition yet. Remember it so we can
8880 do this later. */
8881 if (state->is_header ()
8882 && decl_tls_wrapper_p (decl))
8883 note_vague_linkage_fn (decl);
8884
8885 /* Setup aliases for the declaration. */
8886 if (tree alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)))
8887 {
8888 alias = TREE_VALUE (TREE_VALUE (alias));
8889 alias = get_identifier (TREE_STRING_POINTER (alias));
8890 assemble_alias (decl, alias);
8891 }
8892 }
8893 else
8894 {
8895 /* DECL is the to-be-discarded decl. Its internal pointers will
8896 be to the EXISTING's structure. Frob it to point to its
8897 own other structures, so loading its definition will alter
8898 it, and not the existing decl. */
8899 dump (dumper::MERGE) && dump ("Deduping %N", existing);
8900
8901 if (inner_tag)
8902 DECL_TEMPLATE_RESULT (decl) = inner;
8903
8904 if (type)
8905 {
8906 /* Point at the to-be-discarded type & decl. */
8907 TYPE_NAME (type) = inner;
8908 TREE_TYPE (inner) = type;
8909
8910 TYPE_STUB_DECL (type) = stub_decl ? stub_decl : inner;
8911 if (stub_decl)
8912 TREE_TYPE (stub_decl) = type;
8913
8914 tree etype = TREE_TYPE (existing);
8915
8916 /* Handle separate declarations with different attributes. */
8917 tree &dattr = TYPE_ATTRIBUTES (type);
8918 tree &eattr = TYPE_ATTRIBUTES (etype);
8919 check_abi_tags (existing, decl, eattr, dattr);
8920 // TODO: handle other conflicting type attributes
8921 eattr = merge_attributes (eattr, dattr);
8922
8923 /* When merging a partial specialisation, the existing decl may have
8924 had its TYPE_CANONICAL adjusted. If so we should use structural
8925 equality to ensure is_matching_decl doesn't get confused. */
8926 if ((spec_flags & 2)
8927 && TYPE_CANONICAL (type) != TYPE_CANONICAL (etype))
8928 SET_TYPE_STRUCTURAL_EQUALITY (type);
8929 }
8930
8931 if (inner_tag)
8932 /* Set the TEMPLATE_DECL's type. */
8933 TREE_TYPE (decl) = TREE_TYPE (inner);
8934
8935 if (!is_matching_decl (existing, decl, is_typedef))
8936 unmatched_duplicate (existing);
8937
8938 if (TREE_CODE (inner) == FUNCTION_DECL)
8939 {
8940 tree e_inner = STRIP_TEMPLATE (existing);
8941 for (auto parm = DECL_ARGUMENTS (inner);
8942 parm; parm = DECL_CHAIN (parm))
8943 DECL_CONTEXT (parm) = e_inner;
8944 }
8945
8946 /* And our result is the existing node. */
8947 decl = existing;
8948 }
8949
8950 if (mk == MK_friend_spec)
8951 {
8952 tree e = match_mergeable_specialization (true, &spec);
8953 if (!e)
8954 {
8955 spec.spec = inner;
8956 add_mergeable_specialization (true, &spec, decl, spec_flags);
8957 }
8958 else if (e != existing)
8959 set_overrun ();
8960 }
8961
8962 if (is_typedef)
8963 {
8964 /* Insert the type into the array now. */
8965 tag = insert (TREE_TYPE (decl));
8966 dump (dumper::TREE)
8967 && dump ("Cloned:%d typedef %C:%N",
8968 tag, TREE_CODE (TREE_TYPE (decl)), TREE_TYPE (decl));
8969 }
8970
8971 unused = saved_unused;
8972
8973 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
8974 {
8975 unsigned flags = u ();
8976
8977 if (is_new)
8978 {
8979 bool cloned_p = flags & 1;
8980 dump (dumper::TREE) && dump ("CDTOR %N is %scloned",
8981 decl, cloned_p ? "" : "not ");
8982 if (cloned_p)
8983 build_cdtor_clones (decl, flags & 2, flags & 4,
8984 /* Update the member vec, if there is
8985 one (we're in a different cluster
8986 to the class defn). */
8987 CLASSTYPE_MEMBER_VEC (DECL_CONTEXT (decl)));
8988 }
8989 }
8990
8991 if (VAR_P (decl) && CP_DECL_THREAD_LOCAL_P (decl))
8992 {
8993 enum tls_model model = tls_model (u ());
8994 if (is_new)
8995 set_decl_tls_model (decl, model);
8996 }
8997
8998 if (!NAMESPACE_SCOPE_P (inner)
8999 && ((TREE_CODE (inner) == TYPE_DECL
9000 && !is_typedef
9001 && TYPE_NAME (TREE_TYPE (inner)) == inner)
9002 || TREE_CODE (inner) == FUNCTION_DECL)
9003 && u ())
9004 read_definition (decl);
9005
9006 return decl;
9007 }
9008
9009 /* DECL is an unnameable member of CTX. Return a suitable identifying
9010 index. */
9011
9012 static unsigned
9013 get_field_ident (tree ctx, tree decl)
9014 {
9015 gcc_checking_assert (TREE_CODE (decl) == USING_DECL
9016 || !DECL_NAME (decl)
9017 || IDENTIFIER_ANON_P (DECL_NAME (decl)));
9018
9019 unsigned ix = 0;
9020 for (tree fields = TYPE_FIELDS (ctx);
9021 fields; fields = DECL_CHAIN (fields))
9022 {
9023 if (fields == decl)
9024 return ix;
9025
9026 if (DECL_CONTEXT (fields) == ctx
9027 && (TREE_CODE (fields) == USING_DECL
9028 || (TREE_CODE (fields) == FIELD_DECL
9029 && (!DECL_NAME (fields)
9030 || IDENTIFIER_ANON_P (DECL_NAME (fields))))))
9031 /* Count this field. */
9032 ix++;
9033 }
9034 gcc_unreachable ();
9035 }
9036
9037 static tree
9038 lookup_field_ident (tree ctx, unsigned ix)
9039 {
9040 for (tree fields = TYPE_FIELDS (ctx);
9041 fields; fields = DECL_CHAIN (fields))
9042 if (DECL_CONTEXT (fields) == ctx
9043 && (TREE_CODE (fields) == USING_DECL
9044 || (TREE_CODE (fields) == FIELD_DECL
9045 && (!DECL_NAME (fields)
9046 || IDENTIFIER_ANON_P (DECL_NAME (fields))))))
9047 if (!ix--)
9048 return fields;
9049
9050 return NULL_TREE;
9051 }
9052
9053 /* Reference DECL. REF indicates the walk kind we are performing.
9054 Return true if we should write this decl by value. */
9055
9056 bool
9057 trees_out::decl_node (tree decl, walk_kind ref)
9058 {
9059 gcc_checking_assert (DECL_P (decl) && !DECL_TEMPLATE_PARM_P (decl)
9060 && DECL_CONTEXT (decl));
9061
9062 if (ref == WK_value)
9063 {
9064 depset *dep = dep_hash->find_dependency (decl);
9065 decl_value (decl, dep);
9066 return false;
9067 }
9068
9069 switch (TREE_CODE (decl))
9070 {
9071 default:
9072 break;
9073
9074 case FUNCTION_DECL:
9075 gcc_checking_assert (!DECL_LOCAL_DECL_P (decl));
9076 break;
9077
9078 case RESULT_DECL:
9079 /* Unlike PARM_DECLs, RESULT_DECLs are only generated and
9080 referenced when we're inside the function itself. */
9081 return true;
9082
9083 case PARM_DECL:
9084 {
9085 if (streaming_p ())
9086 i (tt_parm);
9087 tree_node (DECL_CONTEXT (decl));
9088
9089 /* That must have put this in the map. */
9090 walk_kind ref = ref_node (decl);
9091 if (ref != WK_none)
9092 // FIXME:OPTIMIZATION We can wander into bits of the
9093 // template this was instantiated from, for instance
9094 // deferred noexcept and default parms, or references
9095 // to parms from earlier forward-decls (PR c++/119608).
9096 //
9097 // Currently we'll end up cloning those bits of tree.
9098 // It would be nice to reference those specific nodes.
9099 // I think putting those things in the map when we
9100 // reference their template by name.
9101 //
9102 // See the note in add_indirects.
9103 return true;
9104
9105 if (streaming_p ())
9106 dump (dumper::TREE)
9107 && dump ("Wrote %s reference %N",
9108 TREE_CODE (decl) == PARM_DECL ? "parameter" : "result",
9109 decl);
9110 }
9111 return false;
9112
9113 case IMPORTED_DECL:
9114 /* This describes a USING_DECL to the ME's debug machinery. It
9115 originates from the fortran FE, and has nothing to do with
9116 C++ modules. */
9117 return true;
9118
9119 case LABEL_DECL:
9120 return true;
9121
9122 case CONST_DECL:
9123 {
9124 /* If I end up cloning enum decls, implementing C++20 using
9125 E::v, this will need tweaking. */
9126 if (streaming_p ())
9127 i (tt_enum_decl);
9128 tree ctx = DECL_CONTEXT (decl);
9129 gcc_checking_assert (TREE_CODE (ctx) == ENUMERAL_TYPE);
9130 tree_node (ctx);
9131 tree_node (DECL_NAME (decl));
9132
9133 int tag = insert (decl);
9134 if (streaming_p ())
9135 dump (dumper::TREE)
9136 && dump ("Wrote enum decl:%d %C:%N", tag, TREE_CODE (decl), decl);
9137 return false;
9138 }
9139 break;
9140
9141 case USING_DECL:
9142 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
9143 break;
9144 /* FALLTHROUGH */
9145
9146 case FIELD_DECL:
9147 {
9148 if (streaming_p ())
9149 i (tt_data_member);
9150
9151 tree ctx = DECL_CONTEXT (decl);
9152 tree_node (ctx);
9153
9154 tree name = NULL_TREE;
9155
9156 if (TREE_CODE (decl) == USING_DECL)
9157 ;
9158 else
9159 {
9160 name = DECL_NAME (decl);
9161 if (name && IDENTIFIER_ANON_P (name))
9162 name = NULL_TREE;
9163 }
9164
9165 tree_node (name);
9166 if (!name && streaming_p ())
9167 {
9168 unsigned ix = get_field_ident (ctx, decl);
9169 u (ix);
9170 }
9171
9172 int tag = insert (decl);
9173 if (streaming_p ())
9174 dump (dumper::TREE)
9175 && dump ("Wrote member:%d %C:%N", tag, TREE_CODE (decl), decl);
9176 return false;
9177 }
9178 break;
9179
9180 case VAR_DECL:
9181 gcc_checking_assert (!DECL_LOCAL_DECL_P (decl));
9182 if (DECL_VTABLE_OR_VTT_P (decl))
9183 {
9184 /* VTT or VTABLE, they are all on the vtables list. */
9185 tree ctx = CP_DECL_CONTEXT (decl);
9186 tree vtable = CLASSTYPE_VTABLES (ctx);
9187 for (unsigned ix = 0; ; vtable = DECL_CHAIN (vtable), ix++)
9188 if (vtable == decl)
9189 {
9190 gcc_checking_assert (DECL_VIRTUAL_P (decl));
9191 if (streaming_p ())
9192 {
9193 u (tt_vtable);
9194 u (ix);
9195 dump (dumper::TREE)
9196 && dump ("Writing vtable %N[%u]", ctx, ix);
9197 }
9198 tree_node (ctx);
9199 return false;
9200 }
9201 gcc_unreachable ();
9202 }
9203
9204 if (DECL_TINFO_P (decl))
9205 {
9206 tinfo:
9207 /* A typeinfo, tt_tinfo_typedef or tt_tinfo_var. */
9208 bool is_var = VAR_P (decl);
9209 tree type = TREE_TYPE (decl);
9210 unsigned ix = get_pseudo_tinfo_index (type);
9211 if (streaming_p ())
9212 {
9213 i (is_var ? tt_tinfo_var : tt_tinfo_typedef);
9214 u (ix);
9215 }
9216
9217 if (is_var)
9218 {
9219 /* We also need the type it is for and mangled name, so
9220 the reader doesn't need to complete the type (which
9221 would break section ordering). The type it is for is
9222 stashed on the name's TREE_TYPE. */
9223 tree name = DECL_NAME (decl);
9224 tree_node (name);
9225 type = TREE_TYPE (name);
9226 tree_node (type);
9227 }
9228
9229 int tag = insert (decl);
9230 if (streaming_p ())
9231 dump (dumper::TREE)
9232 && dump ("Wrote tinfo_%s:%d %u %N", is_var ? "var" : "type",
9233 tag, ix, type);
9234
9235 if (!is_var)
9236 {
9237 tag = insert (type);
9238 if (streaming_p ())
9239 dump (dumper::TREE)
9240 && dump ("Wrote tinfo_type:%d %u %N", tag, ix, type);
9241 }
9242 return false;
9243 }
9244
9245 if (DECL_NTTP_OBJECT_P (decl))
9246 {
9247 /* A NTTP parm object. */
9248 if (streaming_p ())
9249 i (tt_nttp_var);
9250 tree_node (tparm_object_argument (decl));
9251 tree_node (DECL_NAME (decl));
9252 int tag = insert (decl);
9253 if (streaming_p ())
9254 dump (dumper::TREE)
9255 && dump ("Wrote nttp object:%d %N", tag, DECL_NAME (decl));
9256 return false;
9257 }
9258
9259 break;
9260
9261 case TYPE_DECL:
9262 if (DECL_TINFO_P (decl))
9263 goto tinfo;
9264 break;
9265 }
9266
9267 if (DECL_THUNK_P (decl))
9268 {
9269 /* Thunks are similar to binfos -- write the thunked-to decl and
9270 then thunk-specific key info. */
9271 if (streaming_p ())
9272 {
9273 i (tt_thunk);
9274 i (THUNK_FIXED_OFFSET (decl));
9275 }
9276
9277 tree target = decl;
9278 while (DECL_THUNK_P (target))
9279 target = THUNK_TARGET (target);
9280 tree_node (target);
9281 tree_node (THUNK_VIRTUAL_OFFSET (decl));
9282 int tag = insert (decl);
9283 if (streaming_p ())
9284 dump (dumper::TREE)
9285 && dump ("Wrote:%d thunk %N to %N", tag, DECL_NAME (decl), target);
9286 return false;
9287 }
9288
9289 if (DECL_CLONED_FUNCTION_P (decl))
9290 {
9291 tree target = get_clone_target (decl);
9292 if (streaming_p ())
9293 i (tt_clone_ref);
9294
9295 tree_node (target);
9296 tree_node (DECL_NAME (decl));
9297 if (DECL_VIRTUAL_P (decl))
9298 tree_node (DECL_VINDEX (decl));
9299 int tag = insert (decl);
9300 if (streaming_p ())
9301 dump (dumper::TREE)
9302 && dump ("Wrote:%d clone %N of %N", tag, DECL_NAME (decl), target);
9303 return false;
9304 }
9305
9306 /* Everything left should be a thing that is in the entity table.
9307 Mostly things that can be defined outside of their (original
9308 declaration) context. */
9309 gcc_checking_assert (TREE_CODE (decl) == TEMPLATE_DECL
9310 || VAR_P (decl)
9311 || TREE_CODE (decl) == FUNCTION_DECL
9312 || TREE_CODE (decl) == TYPE_DECL
9313 || TREE_CODE (decl) == USING_DECL
9314 || TREE_CODE (decl) == CONCEPT_DECL
9315 || TREE_CODE (decl) == NAMESPACE_DECL);
9316
9317 int use_tpl = -1;
9318 tree ti = node_template_info (decl, use_tpl);
9319 tree tpl = NULL_TREE;
9320
9321 /* If this is the TEMPLATE_DECL_RESULT of a TEMPLATE_DECL, get the
9322 TEMPLATE_DECL. Note TI_TEMPLATE is not a TEMPLATE_DECL for
9323 (some) friends, so we need to check that. */
9324 // FIXME: Should local friend template specializations be by value?
9325 // They don't get idents so we'll never know they're imported, but I
9326 // think we can only reach them from the TU that defines the
9327 // befriending class?
9328 if (ti && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL
9329 && DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == decl)
9330 {
9331 tpl = TI_TEMPLATE (ti);
9332 partial_template:
9333 if (streaming_p ())
9334 {
9335 i (tt_template);
9336 dump (dumper::TREE)
9337 && dump ("Writing implicit template %C:%N%S",
9338 TREE_CODE (tpl), tpl, tpl);
9339 }
9340 tree_node (tpl);
9341
9342 /* Streaming TPL caused us to visit DECL and maybe its type,
9343 if it wasn't TU-local. */
9344 if (CHECKING_P && !has_tu_local_dep (tpl))
9345 {
9346 gcc_checking_assert (TREE_VISITED (decl));
9347 if (DECL_IMPLICIT_TYPEDEF_P (decl))
9348 gcc_checking_assert (TREE_VISITED (TREE_TYPE (decl)));
9349 }
9350 return false;
9351 }
9352
9353 tree ctx = CP_DECL_CONTEXT (decl);
9354 depset *dep = NULL;
9355 if (streaming_p ())
9356 dep = dep_hash->find_dependency (decl);
9357 else if (TREE_CODE (ctx) != FUNCTION_DECL
9358 || TREE_CODE (decl) == TEMPLATE_DECL
9359 || DECL_IMPLICIT_TYPEDEF_P (decl)
9360 || (DECL_LANG_SPECIFIC (decl)
9361 && DECL_MODULE_IMPORT_P (decl)))
9362 {
9363 auto kind = (TREE_CODE (decl) == NAMESPACE_DECL
9364 && !DECL_NAMESPACE_ALIAS (decl)
9365 ? depset::EK_NAMESPACE : depset::EK_DECL);
9366 dep = dep_hash->add_dependency (decl, kind);
9367 }
9368
9369 if (!dep || dep->is_tu_local ())
9370 {
9371 /* Some internal entity of context. Do by value. */
9372 decl_value (decl, dep);
9373 return false;
9374 }
9375
9376 if (dep->get_entity_kind () == depset::EK_REDIRECT)
9377 {
9378 /* The DECL_TEMPLATE_RESULT of a partial specialization.
9379 Write the partial specialization's template. */
9380 depset *redirect = dep->deps[0];
9381 gcc_checking_assert (redirect->get_entity_kind () == depset::EK_PARTIAL);
9382 tpl = redirect->get_entity ();
9383 goto partial_template;
9384 }
9385
9386 if (streaming_p ())
9387 {
9388 /* Locate the entity. */
9389 unsigned index = dep->cluster;
9390 unsigned import = 0;
9391
9392 if (dep->is_import ())
9393 import = dep->section;
9394 else if (CHECKING_P)
9395 /* It should be what we put there. */
9396 gcc_checking_assert (index == ~import_entity_index (decl));
9397
9398 #if CHECKING_P
9399 gcc_assert (!import || importedness >= 0);
9400 #endif
9401 i (tt_entity);
9402 u (import);
9403 u (index);
9404 }
9405
9406 int tag = insert (decl);
9407 if (streaming_p () && dump (dumper::TREE))
9408 {
9409 char const *kind = "import";
9410 module_state *from = (*modules)[0];
9411 if (dep->is_import ())
9412 /* Rediscover the unremapped index. */
9413 from = import_entity_module (import_entity_index (decl));
9414 else
9415 {
9416 tree o = get_originating_module_decl (decl);
9417 o = STRIP_TEMPLATE (o);
9418 kind = (DECL_LANG_SPECIFIC (o) && DECL_MODULE_PURVIEW_P (o)
9419 ? "purview" : "GMF");
9420 }
9421 dump ("Wrote %s:%d %C:%N@%M", kind,
9422 tag, TREE_CODE (decl), decl, from);
9423 }
9424
9425 add_indirects (decl);
9426
9427 return false;
9428 }
9429
9430 void
9431 trees_out::type_node (tree type)
9432 {
9433 gcc_assert (TYPE_P (type));
9434
9435 tree root = (TYPE_NAME (type)
9436 ? TREE_TYPE (TYPE_NAME (type)) : TYPE_MAIN_VARIANT (type));
9437
9438 if (type != root)
9439 {
9440 if (streaming_p ())
9441 i (tt_variant_type);
9442 tree_node (root);
9443
9444 int flags = -1;
9445
9446 if (TREE_CODE (type) == FUNCTION_TYPE
9447 || TREE_CODE (type) == METHOD_TYPE)
9448 {
9449 int quals = type_memfn_quals (type);
9450 int rquals = type_memfn_rqual (type);
9451 tree raises = TYPE_RAISES_EXCEPTIONS (type);
9452 bool late = TYPE_HAS_LATE_RETURN_TYPE (type);
9453
9454 if (raises != TYPE_RAISES_EXCEPTIONS (root)
9455 || rquals != type_memfn_rqual (root)
9456 || quals != type_memfn_quals (root)
9457 || late != TYPE_HAS_LATE_RETURN_TYPE (root))
9458 flags = rquals | (int (late) << 2) | (quals << 3);
9459 }
9460 else
9461 {
9462 if (TYPE_USER_ALIGN (type))
9463 flags = TYPE_ALIGN_RAW (type);
9464 }
9465
9466 if (streaming_p ())
9467 i (flags);
9468
9469 if (flags < 0)
9470 ;
9471 else if (TREE_CODE (type) == FUNCTION_TYPE
9472 || TREE_CODE (type) == METHOD_TYPE)
9473 {
9474 tree raises = TYPE_RAISES_EXCEPTIONS (type);
9475 if (raises == TYPE_RAISES_EXCEPTIONS (root))
9476 raises = error_mark_node;
9477 tree_node (raises);
9478 }
9479
9480 /* build_type_attribute_variant creates a new TYPE_MAIN_VARIANT, so
9481 variants should all have the same set of attributes. */
9482 gcc_checking_assert (TYPE_ATTRIBUTES (type)
9483 == TYPE_ATTRIBUTES (TYPE_MAIN_VARIANT (type)));
9484
9485 if (streaming_p ())
9486 {
9487 /* Qualifiers. */
9488 int rquals = cp_type_quals (root);
9489 int quals = cp_type_quals (type);
9490 if (quals == rquals)
9491 quals = -1;
9492 i (quals);
9493 }
9494
9495 if (ref_node (type) != WK_none)
9496 {
9497 int tag = insert (type);
9498 if (streaming_p ())
9499 {
9500 i (0);
9501 dump (dumper::TREE)
9502 && dump ("Wrote:%d variant type %C", tag, TREE_CODE (type));
9503 }
9504 }
9505 return;
9506 }
9507
9508 if (tree name = TYPE_NAME (type))
9509 if ((TREE_CODE (name) == TYPE_DECL && DECL_ORIGINAL_TYPE (name))
9510 || DECL_TEMPLATE_PARM_P (name)
9511 || TREE_CODE (type) == RECORD_TYPE
9512 || TREE_CODE (type) == UNION_TYPE
9513 || TREE_CODE (type) == ENUMERAL_TYPE)
9514 {
9515 /* We can meet template parms that we didn't meet in the
9516 tpl_parms walk, because we're referring to a derived type
9517 that was previously constructed from equivalent template
9518 parms. */
9519 if (streaming_p ())
9520 {
9521 i (tt_typedef_type);
9522 dump (dumper::TREE)
9523 && dump ("Writing %stypedef %C:%N",
9524 DECL_IMPLICIT_TYPEDEF_P (name) ? "implicit " : "",
9525 TREE_CODE (name), name);
9526 }
9527 tree_node (name);
9528 if (streaming_p ())
9529 dump (dumper::TREE) && dump ("Wrote typedef %C:%N%S",
9530 TREE_CODE (name), name, name);
9531
9532 /* We'll have either visited this type or have newly discovered
9533 that it's TU-local; either way we won't need to visit it again. */
9534 gcc_checking_assert (TREE_VISITED (type) || has_tu_local_dep (name));
9535 return;
9536 }
9537
9538 if (TYPE_PTRMEMFUNC_P (type))
9539 {
9540 /* This is a distinct type node, masquerading as a structure. */
9541 tree fn_type = TYPE_PTRMEMFUNC_FN_TYPE (type);
9542 if (streaming_p ())
9543 i (tt_ptrmem_type);
9544 tree_node (fn_type);
9545 int tag = insert (type);
9546 if (streaming_p ())
9547 dump (dumper::TREE) && dump ("Written:%d ptrmem type", tag);
9548 return;
9549 }
9550
9551 if (streaming_p ())
9552 {
9553 u (tt_derived_type);
9554 u (TREE_CODE (type));
9555 }
9556
9557 tree_node (TREE_TYPE (type));
9558 switch (TREE_CODE (type))
9559 {
9560 default:
9561 /* We should never meet a type here that is indescribable in
9562 terms of other types. */
9563 gcc_unreachable ();
9564
9565 case ARRAY_TYPE:
9566 tree_node (TYPE_DOMAIN (type));
9567 if (streaming_p ())
9568 /* Dependent arrays are constructed with TYPE_DEPENENT_P
9569 already set. */
9570 u (TYPE_DEPENDENT_P (type));
9571 break;
9572
9573 case COMPLEX_TYPE:
9574 /* No additional data. */
9575 break;
9576
9577 case BOOLEAN_TYPE:
9578 /* A non-standard boolean type. */
9579 if (streaming_p ())
9580 u (TYPE_PRECISION (type));
9581 break;
9582
9583 case INTEGER_TYPE:
9584 if (TREE_TYPE (type))
9585 {
9586 /* A range type (representing an array domain). */
9587 tree_node (TYPE_MIN_VALUE (type));
9588 tree_node (TYPE_MAX_VALUE (type));
9589 }
9590 else
9591 {
9592 /* A new integral type (representing a bitfield). */
9593 if (streaming_p ())
9594 {
9595 unsigned prec = TYPE_PRECISION (type);
9596 bool unsigned_p = TYPE_UNSIGNED (type);
9597
9598 u ((prec << 1) | unsigned_p);
9599 }
9600 }
9601 break;
9602
9603 case METHOD_TYPE:
9604 case FUNCTION_TYPE:
9605 {
9606 gcc_checking_assert (type_memfn_rqual (type) == REF_QUAL_NONE);
9607
9608 tree arg_types = TYPE_ARG_TYPES (type);
9609 if (TREE_CODE (type) == METHOD_TYPE)
9610 {
9611 tree_node (TREE_TYPE (TREE_VALUE (arg_types)));
9612 arg_types = TREE_CHAIN (arg_types);
9613 }
9614 tree_node (arg_types);
9615 }
9616 break;
9617
9618 case OFFSET_TYPE:
9619 tree_node (TYPE_OFFSET_BASETYPE (type));
9620 break;
9621
9622 case POINTER_TYPE:
9623 /* No additional data. */
9624 break;
9625
9626 case REFERENCE_TYPE:
9627 if (streaming_p ())
9628 u (TYPE_REF_IS_RVALUE (type));
9629 break;
9630
9631 case DECLTYPE_TYPE:
9632 case TYPEOF_TYPE:
9633 case DEPENDENT_OPERATOR_TYPE:
9634 tree_node (TYPE_VALUES_RAW (type));
9635 if (TREE_CODE (type) == DECLTYPE_TYPE)
9636 /* We stash a whole bunch of things into decltype's
9637 flags. */
9638 if (streaming_p ())
9639 tree_node_bools (type);
9640 break;
9641
9642 case TRAIT_TYPE:
9643 tree_node (TRAIT_TYPE_KIND_RAW (type));
9644 tree_node (TRAIT_TYPE_TYPE1 (type));
9645 tree_node (TRAIT_TYPE_TYPE2 (type));
9646 break;
9647
9648 case TYPE_ARGUMENT_PACK:
9649 /* No additional data. */
9650 break;
9651
9652 case TYPE_PACK_EXPANSION:
9653 if (streaming_p ())
9654 u (PACK_EXPANSION_LOCAL_P (type));
9655 tree_node (PACK_EXPANSION_PARAMETER_PACKS (type));
9656 tree_node (PACK_EXPANSION_EXTRA_ARGS (type));
9657 break;
9658
9659 case PACK_INDEX_TYPE:
9660 tree_node (PACK_INDEX_PACK (type));
9661 tree_node (PACK_INDEX_INDEX (type));
9662 break;
9663
9664 case TYPENAME_TYPE:
9665 {
9666 tree_node (TYPE_CONTEXT (type));
9667 tree_node (DECL_NAME (TYPE_NAME (type)));
9668 tree_node (TYPENAME_TYPE_FULLNAME (type));
9669 if (streaming_p ())
9670 {
9671 enum tag_types tag_type = none_type;
9672 if (TYPENAME_IS_ENUM_P (type))
9673 tag_type = enum_type;
9674 else if (TYPENAME_IS_CLASS_P (type))
9675 tag_type = class_type;
9676 u (int (tag_type));
9677 }
9678 }
9679 break;
9680
9681 case UNBOUND_CLASS_TEMPLATE:
9682 {
9683 tree decl = TYPE_NAME (type);
9684 tree_node (DECL_CONTEXT (decl));
9685 tree_node (DECL_NAME (decl));
9686 tree_node (DECL_TEMPLATE_PARMS (decl));
9687 }
9688 break;
9689
9690 case VECTOR_TYPE:
9691 if (streaming_p ())
9692 {
9693 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (type);
9694 for (unsigned ix = 0; ix != NUM_POLY_INT_COEFFS; ix++)
9695 wu (nunits.coeffs[ix]);
9696 }
9697 break;
9698 }
9699
9700 tree_node (TYPE_ATTRIBUTES (type));
9701
9702 /* We may have met the type during emitting the above. */
9703 if (ref_node (type) != WK_none)
9704 {
9705 int tag = insert (type);
9706 if (streaming_p ())
9707 {
9708 i (0);
9709 dump (dumper::TREE)
9710 && dump ("Wrote:%d derived type %C", tag, TREE_CODE (type));
9711 }
9712 }
9713
9714 return;
9715 }
9716
9717 /* T is (mostly*) a non-mergeable node that must be written by value.
9718 The mergeable case is a BINFO, which are as-if DECLSs. */
9719
9720 void
9721 trees_out::tree_value (tree t)
9722 {
9723 /* We should never be writing a type by value. tree_type should
9724 have streamed it, or we're going via its TYPE_DECL. */
9725 gcc_checking_assert (!TYPE_P (t));
9726
9727 if (DECL_P (t))
9728 /* No template, type, var or function, except anonymous
9729 non-context vars. */
9730 gcc_checking_assert ((TREE_CODE (t) != TEMPLATE_DECL
9731 && TREE_CODE (t) != TYPE_DECL
9732 && (TREE_CODE (t) != VAR_DECL
9733 || (!DECL_NAME (t) && !DECL_CONTEXT (t)))
9734 && TREE_CODE (t) != FUNCTION_DECL));
9735
9736 if (streaming_p ())
9737 {
9738 /* A new node -> tt_node. */
9739 tree_val_count++;
9740 i (tt_node);
9741 start (t);
9742 tree_node_bools (t);
9743 }
9744
9745 if (TREE_CODE (t) == TREE_BINFO)
9746 /* Binfos are decl-like and need merging information. */
9747 binfo_mergeable (t);
9748
9749 int tag = insert (t, WK_value);
9750 if (streaming_p ())
9751 dump (dumper::TREE)
9752 && dump ("Writing tree:%d %C:%N", tag, TREE_CODE (t), t);
9753
9754 tree_node_vals (t);
9755
9756 if (streaming_p ())
9757 dump (dumper::TREE) && dump ("Written tree:%d %C:%N", tag, TREE_CODE (t), t);
9758 }
9759
9760 tree
9761 trees_in::tree_value ()
9762 {
9763 tree t = start ();
9764 if (!t || !tree_node_bools (t))
9765 return NULL_TREE;
9766
9767 tree existing = t;
9768 if (TREE_CODE (t) == TREE_BINFO)
9769 {
9770 tree type;
9771 unsigned ix = binfo_mergeable (&type);
9772 if (TYPE_BINFO (type))
9773 {
9774 /* We already have a definition, this must be a duplicate. */
9775 dump (dumper::MERGE)
9776 && dump ("Deduping binfo %N[%u]", type, ix);
9777 existing = TYPE_BINFO (type);
9778 while (existing && ix--)
9779 existing = TREE_CHAIN (existing);
9780 if (existing)
9781 register_duplicate (t, existing);
9782 else
9783 /* Error, mismatch -- diagnose in read_class_def's
9784 checking. */
9785 existing = t;
9786 }
9787 }
9788
9789 /* Insert into map. */
9790 int tag = insert (existing);
9791 dump (dumper::TREE)
9792 && dump ("Reading tree:%d %C", tag, TREE_CODE (t));
9793
9794 if (!tree_node_vals (t))
9795 {
9796 back_refs[~tag] = NULL_TREE;
9797 set_overrun ();
9798 /* Bail. */
9799 return NULL_TREE;
9800 }
9801
9802 if (TREE_CODE (t) == LAMBDA_EXPR
9803 && CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (t)))
9804 {
9805 existing = CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (t));
9806 back_refs[~tag] = existing;
9807 }
9808
9809 dump (dumper::TREE) && dump ("Read tree:%d %C:%N", tag, TREE_CODE (t), t);
9810
9811 if (TREE_CODE (existing) == INTEGER_CST && !TREE_OVERFLOW (existing))
9812 {
9813 existing = cache_integer_cst (t, true);
9814 back_refs[~tag] = existing;
9815 }
9816
9817 return existing;
9818 }
9819
9820 /* Whether DECL has a TU-local dependency in the hash. */
9821
9822 bool
9823 trees_out::has_tu_local_dep (tree decl) const
9824 {
9825 /* Only the contexts of fields or enums remember that they're
9826 TU-local. */
9827 if (DECL_CONTEXT (decl)
9828 && (TREE_CODE (decl) == FIELD_DECL
9829 || TREE_CODE (decl) == CONST_DECL))
9830 decl = TYPE_NAME (DECL_CONTEXT (decl));
9831
9832 depset *dep = dep_hash->find_dependency (decl);
9833 if (!dep)
9834 {
9835 /* This might be the DECL_TEMPLATE_RESULT of a TEMPLATE_DECL
9836 which we found was TU-local and gave up early. */
9837 int use_tpl = -1;
9838 if (tree ti = node_template_info (decl, use_tpl))
9839 dep = dep_hash->find_dependency (TI_TEMPLATE (ti));
9840 }
9841
9842 return dep && dep->is_tu_local ();
9843 }
9844
9845 /* If T depends on a TU-local entity, return that decl. */
9846
9847 tree
9848 trees_out::find_tu_local_decl (tree t)
9849 {
9850 /* We need to have walked all deps first before we can check. */
9851 gcc_checking_assert (!is_initial_scan ());
9852
9853 auto walker = [](tree *tp, int *walk_subtrees, void *data) -> tree
9854 {
9855 auto self = (trees_out *)data;
9856
9857 tree decl = NULL_TREE;
9858 if (TYPE_P (*tp))
9859 {
9860 /* A PMF type is a record type, which we otherwise wouldn't walk;
9861 return whether the function type is TU-local. */
9862 if (TYPE_PTRMEMFUNC_P (*tp))
9863 {
9864 *walk_subtrees = 0;
9865 return self->find_tu_local_decl (TYPE_PTRMEMFUNC_FN_TYPE (*tp));
9866 }
9867 else
9868 decl = TYPE_MAIN_DECL (*tp);
9869 }
9870 else if (DECL_P (*tp))
9871 decl = *tp;
9872
9873 if (decl)
9874 {
9875 /* We found a DECL, this will tell us whether we're TU-local. */
9876 *walk_subtrees = 0;
9877 return self->has_tu_local_dep (decl) ? decl : NULL_TREE;
9878 }
9879 return NULL_TREE;
9880 };
9881
9882 /* We need to walk without duplicates so that we step into the pointed-to
9883 types of array types. */
9884 return cp_walk_tree_without_duplicates (&t, walker, this);
9885 }
9886
9887 /* Stream out tree node T. We automatically create local back
9888 references, which is essentially a single pass lisp
9889 self-referential structure pretty-printer. */
9890
9891 void
9892 trees_out::tree_node (tree t)
9893 {
9894 dump.indent ();
9895 walk_kind ref = ref_node (t);
9896 if (ref == WK_none)
9897 goto done;
9898
9899 /* Find TU-local entities and intercept streaming to instead write a
9900 placeholder value; this way we don't need to emit such decls.
9901 We only need to do this when writing a definition of an entity
9902 that we know names a TU-local entity. */
9903 if (!is_initial_scan () && writing_local_entities)
9904 {
9905 tree local_decl = NULL_TREE;
9906 if (DECL_P (t) && has_tu_local_dep (t))
9907 local_decl = t;
9908 /* Consider a type to be TU-local if it refers to any TU-local decl,
9909 no matter how deep.
9910
9911 This worsens diagnostics slightly, as we often no longer point
9912 directly to the at-fault entity when instantiating. However, this
9913 reduces the module size slightly and means that much less of pt.cc
9914 needs to know about us. */
9915 else if (TYPE_P (t))
9916 local_decl = find_tu_local_decl (t);
9917 else if (EXPR_P (t))
9918 local_decl = find_tu_local_decl (TREE_TYPE (t));
9919
9920 if (local_decl)
9921 {
9922 int tag = insert (t, WK_value);
9923 if (streaming_p ())
9924 {
9925 tu_local_count++;
9926 i (tt_tu_local);
9927 dump (dumper::TREE)
9928 && dump ("Writing TU-local entity:%d %C:%N",
9929 tag, TREE_CODE (t), t);
9930 }
9931 /* TODO: Get a more descriptive name? */
9932 tree_node (DECL_NAME (local_decl));
9933 if (state)
9934 state->write_location (*this, DECL_SOURCE_LOCATION (local_decl));
9935 goto done;
9936 }
9937 }
9938
9939 if (ref != WK_normal)
9940 goto skip_normal;
9941
9942 if (TREE_CODE (t) == IDENTIFIER_NODE)
9943 {
9944 /* An identifier node -> tt_id, tt_conv_id, tt_anon_id, tt_lambda_id. */
9945 int code = tt_id;
9946 if (IDENTIFIER_ANON_P (t))
9947 code = IDENTIFIER_LAMBDA_P (t) ? tt_lambda_id : tt_anon_id;
9948 else if (IDENTIFIER_CONV_OP_P (t))
9949 code = tt_conv_id;
9950
9951 if (streaming_p ())
9952 i (code);
9953
9954 if (code == tt_conv_id)
9955 {
9956 tree type = TREE_TYPE (t);
9957 gcc_checking_assert (type || t == conv_op_identifier);
9958 tree_node (type);
9959 }
9960 else if (code == tt_id && streaming_p ())
9961 str (IDENTIFIER_POINTER (t), IDENTIFIER_LENGTH (t));
9962
9963 int tag = insert (t);
9964 if (streaming_p ())
9965 {
9966 /* We know the ordering of the 4 id tags. */
9967 static const char *const kinds[] =
9968 {"", "conv_op ", "anon ", "lambda "};
9969 dump (dumper::TREE)
9970 && dump ("Written:%d %sidentifier:%N", tag,
9971 kinds[code - tt_id],
9972 code == tt_conv_id ? TREE_TYPE (t) : t);
9973 }
9974 goto done;
9975 }
9976
9977 if (TREE_CODE (t) == TREE_BINFO)
9978 {
9979 /* A BINFO -> tt_binfo.
9980 We must do this by reference. We stream the binfo tree
9981 itself when streaming its owning RECORD_TYPE. That we got
9982 here means the dominating type is not in this SCC. */
9983 if (streaming_p ())
9984 i (tt_binfo);
9985 binfo_mergeable (t);
9986 gcc_checking_assert (!TREE_VISITED (t));
9987 int tag = insert (t);
9988 if (streaming_p ())
9989 dump (dumper::TREE) && dump ("Inserting binfo:%d %N", tag, t);
9990 goto done;
9991 }
9992
9993 if (TREE_CODE (t) == INTEGER_CST
9994 && !TREE_OVERFLOW (t)
9995 && TREE_CODE (TREE_TYPE (t)) == ENUMERAL_TYPE)
9996 {
9997 /* An integral constant of enumeral type. See if it matches one
9998 of the enumeration values. */
9999 for (tree values = TYPE_VALUES (TREE_TYPE (t));
10000 values; values = TREE_CHAIN (values))
10001 {
10002 tree decl = TREE_VALUE (values);
10003 if (tree_int_cst_equal (DECL_INITIAL (decl), t))
10004 {
10005 if (streaming_p ())
10006 u (tt_enum_value);
10007 tree_node (decl);
10008 dump (dumper::TREE) && dump ("Written enum value %N", decl);
10009 goto done;
10010 }
10011 }
10012 /* It didn't match. We'll write it a an explicit INTEGER_CST
10013 node. */
10014 }
10015
10016 if (TYPE_P (t))
10017 {
10018 type_node (t);
10019 goto done;
10020 }
10021
10022 if (DECL_P (t))
10023 {
10024 if (DECL_TEMPLATE_PARM_P (t))
10025 {
10026 tpl_parm_value (t);
10027 goto done;
10028 }
10029
10030 if (!DECL_CONTEXT (t))
10031 {
10032 /* There are a few cases of decls with no context. We'll write
10033 these by value, but first assert they are cases we expect. */
10034 gcc_checking_assert (ref == WK_normal);
10035 switch (TREE_CODE (t))
10036 {
10037 default: gcc_unreachable ();
10038
10039 case LABEL_DECL:
10040 /* CASE_LABEL_EXPRs contain uncontexted LABEL_DECLs. */
10041 gcc_checking_assert (!DECL_NAME (t));
10042 break;
10043
10044 case VAR_DECL:
10045 /* AGGR_INIT_EXPRs cons up anonymous uncontexted VAR_DECLs. */
10046 gcc_checking_assert (!DECL_NAME (t)
10047 && DECL_ARTIFICIAL (t));
10048 break;
10049
10050 case PARM_DECL:
10051 /* REQUIRES_EXPRs have a chain of uncontexted PARM_DECLS,
10052 and an implicit this parm in an NSDMI has no context. */
10053 gcc_checking_assert (CONSTRAINT_VAR_P (t)
10054 || DECL_NAME (t) == this_identifier);
10055 break;
10056 }
10057 goto by_value;
10058 }
10059 }
10060
10061 skip_normal:
10062 if (DECL_P (t) && !decl_node (t, ref))
10063 goto done;
10064
10065 /* Otherwise by value */
10066 by_value:
10067 tree_value (t);
10068
10069 done:
10070 /* And, breath out. */
10071 dump.outdent ();
10072 }
10073
10074 /* Stream in a tree node. */
10075
10076 tree
10077 trees_in::tree_node (bool is_use)
10078 {
10079 if (get_overrun ())
10080 return NULL_TREE;
10081
10082 dump.indent ();
10083 int tag = i ();
10084 tree res = NULL_TREE;
10085 switch (tag)
10086 {
10087 default:
10088 /* backref, pull it out of the map. */
10089 res = back_ref (tag);
10090 break;
10091
10092 case tt_null:
10093 /* NULL_TREE. */
10094 break;
10095
10096 case tt_tu_local:
10097 {
10098 /* A translation-unit-local entity. */
10099 res = make_node (TU_LOCAL_ENTITY);
10100 int tag = insert (res);
10101
10102 TU_LOCAL_ENTITY_NAME (res) = tree_node ();
10103 TU_LOCAL_ENTITY_LOCATION (res) = state->read_location (*this);
10104 dump (dumper::TREE) && dump ("Read TU-local entity:%d %N", tag, res);
10105 }
10106 break;
10107
10108 case tt_fixed:
10109 /* A fixed ref, find it in the fixed_ref array. */
10110 {
10111 unsigned fix = u ();
10112 if (fix < (*fixed_trees).length ())
10113 {
10114 res = (*fixed_trees)[fix];
10115 dump (dumper::TREE) && dump ("Read fixed:%u %C:%N%S", fix,
10116 TREE_CODE (res), res, res);
10117 }
10118
10119 if (!res)
10120 set_overrun ();
10121 }
10122 break;
10123
10124 case tt_parm:
10125 {
10126 tree fn = tree_node ();
10127 if (fn && TREE_CODE (fn) == FUNCTION_DECL)
10128 res = tree_node ();
10129 if (res)
10130 dump (dumper::TREE)
10131 && dump ("Read %s reference %N",
10132 TREE_CODE (res) == PARM_DECL ? "parameter" : "result",
10133 res);
10134 }
10135 break;
10136
10137 case tt_node:
10138 /* A new node. Stream it in. */
10139 res = tree_value ();
10140 break;
10141
10142 case tt_decl:
10143 /* A new decl. Stream it in. */
10144 res = decl_value ();
10145 break;
10146
10147 case tt_tpl_parm:
10148 /* A template parameter. Stream it in. */
10149 res = tpl_parm_value ();
10150 break;
10151
10152 case tt_id:
10153 /* An identifier node. */
10154 {
10155 size_t l;
10156 const char *chars = str (&l);
10157 res = get_identifier_with_length (chars, l);
10158 int tag = insert (res);
10159 dump (dumper::TREE)
10160 && dump ("Read identifier:%d %N", tag, res);
10161 }
10162 break;
10163
10164 case tt_conv_id:
10165 /* A conversion operator. Get the type and recreate the
10166 identifier. */
10167 {
10168 tree type = tree_node ();
10169 if (!get_overrun ())
10170 {
10171 res = type ? make_conv_op_name (type) : conv_op_identifier;
10172 int tag = insert (res);
10173 dump (dumper::TREE)
10174 && dump ("Created conv_op:%d %S for %N", tag, res, type);
10175 }
10176 }
10177 break;
10178
10179 case tt_anon_id:
10180 case tt_lambda_id:
10181 /* An anonymous or lambda id. */
10182 {
10183 res = make_anon_name ();
10184 if (tag == tt_lambda_id)
10185 IDENTIFIER_LAMBDA_P (res) = true;
10186 int tag = insert (res);
10187 dump (dumper::TREE)
10188 && dump ("Read %s identifier:%d %N",
10189 IDENTIFIER_LAMBDA_P (res) ? "lambda" : "anon", tag, res);
10190 }
10191 break;
10192
10193 case tt_typedef_type:
10194 res = tree_node ();
10195 if (res)
10196 {
10197 dump (dumper::TREE)
10198 && dump ("Read %stypedef %C:%N",
10199 DECL_IMPLICIT_TYPEDEF_P (res) ? "implicit " : "",
10200 TREE_CODE (res), res);
10201 if (TREE_CODE (res) != TU_LOCAL_ENTITY)
10202 res = TREE_TYPE (res);
10203 }
10204 break;
10205
10206 case tt_derived_type:
10207 /* A type derived from some other type. */
10208 {
10209 enum tree_code code = tree_code (u ());
10210 res = tree_node ();
10211
10212 switch (code)
10213 {
10214 default:
10215 set_overrun ();
10216 break;
10217
10218 case ARRAY_TYPE:
10219 {
10220 tree elt_type = res;
10221 tree domain = tree_node ();
10222 int dep = u ();
10223 if (!get_overrun ())
10224 {
10225 res = build_cplus_array_type (elt_type, domain, dep);
10226 /* If we're an array of an incomplete imported type,
10227 save it for post-processing so that we can attempt
10228 to complete the type later if it will get a
10229 definition later in the cluster. */
10230 if (!dep
10231 && !COMPLETE_TYPE_P (elt_type)
10232 && CLASS_TYPE_P (elt_type)
10233 && DECL_LANG_SPECIFIC (TYPE_NAME (elt_type))
10234 && DECL_MODULE_IMPORT_P (TYPE_NAME (elt_type)))
10235 post_process_type (res);
10236 }
10237 }
10238 break;
10239
10240 case COMPLEX_TYPE:
10241 if (!get_overrun ())
10242 res = build_complex_type (res);
10243 break;
10244
10245 case BOOLEAN_TYPE:
10246 {
10247 unsigned precision = u ();
10248 if (!get_overrun ())
10249 res = build_nonstandard_boolean_type (precision);
10250 }
10251 break;
10252
10253 case INTEGER_TYPE:
10254 if (res)
10255 {
10256 /* A range type (representing an array domain). */
10257 tree min = tree_node ();
10258 tree max = tree_node ();
10259
10260 if (!get_overrun ())
10261 res = build_range_type (res, min, max);
10262 }
10263 else
10264 {
10265 /* A new integral type (representing a bitfield). */
10266 unsigned enc = u ();
10267 if (!get_overrun ())
10268 res = build_nonstandard_integer_type (enc >> 1, enc & 1);
10269 }
10270 break;
10271
10272 case FUNCTION_TYPE:
10273 case METHOD_TYPE:
10274 {
10275 tree klass = code == METHOD_TYPE ? tree_node () : NULL_TREE;
10276 tree args = tree_node ();
10277 if (!get_overrun ())
10278 {
10279 if (klass)
10280 res = build_method_type_directly (klass, res, args);
10281 else
10282 res = build_function_type (res, args);
10283 }
10284 }
10285 break;
10286
10287 case OFFSET_TYPE:
10288 {
10289 tree base = tree_node ();
10290 if (!get_overrun ())
10291 res = build_offset_type (base, res);
10292 }
10293 break;
10294
10295 case POINTER_TYPE:
10296 if (!get_overrun ())
10297 res = build_pointer_type (res);
10298 break;
10299
10300 case REFERENCE_TYPE:
10301 {
10302 bool rval = bool (u ());
10303 if (!get_overrun ())
10304 res = cp_build_reference_type (res, rval);
10305 }
10306 break;
10307
10308 case DECLTYPE_TYPE:
10309 case TYPEOF_TYPE:
10310 case DEPENDENT_OPERATOR_TYPE:
10311 {
10312 tree expr = tree_node ();
10313 if (!get_overrun ())
10314 {
10315 res = cxx_make_type (code);
10316 TYPE_VALUES_RAW (res) = expr;
10317 if (code == DECLTYPE_TYPE)
10318 tree_node_bools (res);
10319 SET_TYPE_STRUCTURAL_EQUALITY (res);
10320 }
10321 }
10322 break;
10323
10324 case TRAIT_TYPE:
10325 {
10326 tree kind = tree_node ();
10327 tree type1 = tree_node ();
10328 tree type2 = tree_node ();
10329 if (!get_overrun ())
10330 {
10331 res = cxx_make_type (TRAIT_TYPE);
10332 TRAIT_TYPE_KIND_RAW (res) = kind;
10333 TRAIT_TYPE_TYPE1 (res) = type1;
10334 TRAIT_TYPE_TYPE2 (res) = type2;
10335 SET_TYPE_STRUCTURAL_EQUALITY (res);
10336 }
10337 }
10338 break;
10339
10340 case TYPE_ARGUMENT_PACK:
10341 if (!get_overrun ())
10342 {
10343 tree pack = cxx_make_type (TYPE_ARGUMENT_PACK);
10344 ARGUMENT_PACK_ARGS (pack) = res;
10345 res = pack;
10346 }
10347 break;
10348
10349 case TYPE_PACK_EXPANSION:
10350 {
10351 bool local = u ();
10352 tree param_packs = tree_node ();
10353 tree extra_args = tree_node ();
10354 if (!get_overrun ())
10355 {
10356 tree expn = cxx_make_type (TYPE_PACK_EXPANSION);
10357 SET_TYPE_STRUCTURAL_EQUALITY (expn);
10358 PACK_EXPANSION_PATTERN (expn) = res;
10359 PACK_EXPANSION_PARAMETER_PACKS (expn) = param_packs;
10360 PACK_EXPANSION_EXTRA_ARGS (expn) = extra_args;
10361 PACK_EXPANSION_LOCAL_P (expn) = local;
10362 res = expn;
10363 }
10364 }
10365 break;
10366
10367 case PACK_INDEX_TYPE:
10368 {
10369 tree pack = tree_node ();
10370 tree index = tree_node ();
10371 if (!get_overrun ())
10372 res = make_pack_index (pack, index);
10373 }
10374 break;
10375
10376 case TYPENAME_TYPE:
10377 {
10378 tree ctx = tree_node ();
10379 tree name = tree_node ();
10380 tree fullname = tree_node ();
10381 enum tag_types tag_type = tag_types (u ());
10382
10383 if (!get_overrun ())
10384 res = build_typename_type (ctx, name, fullname, tag_type);
10385 }
10386 break;
10387
10388 case UNBOUND_CLASS_TEMPLATE:
10389 {
10390 tree ctx = tree_node ();
10391 tree name = tree_node ();
10392 tree parms = tree_node ();
10393
10394 if (!get_overrun ())
10395 res = make_unbound_class_template_raw (ctx, name, parms);
10396 }
10397 break;
10398
10399 case VECTOR_TYPE:
10400 {
10401 poly_uint64 nunits;
10402 for (unsigned ix = 0; ix != NUM_POLY_INT_COEFFS; ix++)
10403 nunits.coeffs[ix] = wu ();
10404 if (!get_overrun ())
10405 res = build_vector_type (res, nunits);
10406 }
10407 break;
10408 }
10409
10410 /* In the exporting TU, a derived type with attributes was built by
10411 build_type_attribute_variant as a distinct copy, with itself as
10412 TYPE_MAIN_VARIANT. We repeat that on import to get the version
10413 without attributes as TYPE_CANONICAL. */
10414 if (tree attribs = tree_node ())
10415 res = cp_build_type_attribute_variant (res, attribs);
10416
10417 int tag = i ();
10418 if (!tag)
10419 {
10420 tag = insert (res);
10421 if (res)
10422 dump (dumper::TREE)
10423 && dump ("Created:%d derived type %C", tag, code);
10424 }
10425 else
10426 res = back_ref (tag);
10427 }
10428 break;
10429
10430 case tt_variant_type:
10431 /* Variant of some type. */
10432 {
10433 res = tree_node ();
10434 int flags = i ();
10435 if (get_overrun ())
10436 ;
10437 else if (flags < 0)
10438 /* No change. */;
10439 else if (TREE_CODE (res) == FUNCTION_TYPE
10440 || TREE_CODE (res) == METHOD_TYPE)
10441 {
10442 cp_ref_qualifier rqual = cp_ref_qualifier (flags & 3);
10443 bool late = (flags >> 2) & 1;
10444 cp_cv_quals quals = cp_cv_quals (flags >> 3);
10445
10446 tree raises = tree_node ();
10447 if (raises == error_mark_node)
10448 raises = TYPE_RAISES_EXCEPTIONS (res);
10449
10450 res = build_cp_fntype_variant (res, rqual, raises, late);
10451 if (TREE_CODE (res) == FUNCTION_TYPE)
10452 res = apply_memfn_quals (res, quals, rqual);
10453 }
10454 else
10455 {
10456 res = build_aligned_type (res, (1u << flags) >> 1);
10457 TYPE_USER_ALIGN (res) = true;
10458 }
10459
10460 int quals = i ();
10461 if (quals >= 0 && !get_overrun ())
10462 res = cp_build_qualified_type (res, quals);
10463
10464 int tag = i ();
10465 if (!tag)
10466 {
10467 tag = insert (res);
10468 if (res)
10469 dump (dumper::TREE)
10470 && dump ("Created:%d variant type %C", tag, TREE_CODE (res));
10471 }
10472 else
10473 res = back_ref (tag);
10474 }
10475 break;
10476
10477 case tt_tinfo_var:
10478 case tt_tinfo_typedef:
10479 /* A tinfo var or typedef. */
10480 {
10481 bool is_var = tag == tt_tinfo_var;
10482 unsigned ix = u ();
10483 tree type = NULL_TREE;
10484
10485 if (is_var)
10486 {
10487 tree name = tree_node ();
10488 type = tree_node ();
10489
10490 if (!get_overrun ())
10491 res = get_tinfo_decl_direct (type, name, int (ix));
10492 }
10493 else
10494 {
10495 if (!get_overrun ())
10496 {
10497 type = get_pseudo_tinfo_type (ix);
10498 res = TYPE_NAME (type);
10499 }
10500 }
10501 if (res)
10502 {
10503 int tag = insert (res);
10504 dump (dumper::TREE)
10505 && dump ("Created tinfo_%s:%d %S:%u for %N",
10506 is_var ? "var" : "decl", tag, res, ix, type);
10507 if (!is_var)
10508 {
10509 tag = insert (type);
10510 dump (dumper::TREE)
10511 && dump ("Created tinfo_type:%d %u %N", tag, ix, type);
10512 }
10513 }
10514 }
10515 break;
10516
10517 case tt_ptrmem_type:
10518 /* A pointer to member function. */
10519 {
10520 tree type = tree_node ();
10521 if (type && TREE_CODE (type) == POINTER_TYPE
10522 && TREE_CODE (TREE_TYPE (type)) == METHOD_TYPE)
10523 {
10524 res = build_ptrmemfunc_type (type);
10525 int tag = insert (res);
10526 dump (dumper::TREE) && dump ("Created:%d ptrmem type", tag);
10527 }
10528 else
10529 set_overrun ();
10530 }
10531 break;
10532
10533 case tt_nttp_var:
10534 /* An NTTP object. */
10535 {
10536 tree init = tree_node ();
10537 tree name = tree_node ();
10538 if (!get_overrun ())
10539 {
10540 /* We don't want to check the initializer as that may require
10541 name lookup, which could recursively start lazy loading.
10542 Instead we know that INIT is already valid so we can just
10543 apply that directly. */
10544 res = get_template_parm_object (init, name, /*check_init=*/false);
10545 int tag = insert (res);
10546 dump (dumper::TREE)
10547 && dump ("Created nttp object:%d %N", tag, name);
10548 }
10549 }
10550 break;
10551
10552 case tt_enum_value:
10553 /* An enum const value. */
10554 {
10555 if (tree decl = tree_node ())
10556 {
10557 dump (dumper::TREE) && dump ("Read enum value %N", decl);
10558 res = DECL_INITIAL (decl);
10559 }
10560
10561 if (!res)
10562 set_overrun ();
10563 }
10564 break;
10565
10566 case tt_enum_decl:
10567 /* An enum decl. */
10568 {
10569 tree ctx = tree_node ();
10570 tree name = tree_node ();
10571
10572 if (!get_overrun ()
10573 && TREE_CODE (ctx) == ENUMERAL_TYPE)
10574 res = find_enum_member (ctx, name);
10575
10576 if (!res)
10577 set_overrun ();
10578 else
10579 {
10580 int tag = insert (res);
10581 dump (dumper::TREE)
10582 && dump ("Read enum decl:%d %C:%N", tag, TREE_CODE (res), res);
10583 }
10584 }
10585 break;
10586
10587 case tt_data_member:
10588 /* A data member. */
10589 {
10590 tree ctx = tree_node ();
10591 tree name = tree_node ();
10592
10593 if (!get_overrun ()
10594 && RECORD_OR_UNION_TYPE_P (ctx))
10595 {
10596 if (name)
10597 res = lookup_class_binding (ctx, name);
10598 else
10599 res = lookup_field_ident (ctx, u ());
10600
10601 if (!res
10602 || (TREE_CODE (res) != FIELD_DECL
10603 && TREE_CODE (res) != USING_DECL)
10604 || DECL_CONTEXT (res) != ctx)
10605 res = NULL_TREE;
10606 }
10607
10608 if (!res)
10609 set_overrun ();
10610 else
10611 {
10612 int tag = insert (res);
10613 dump (dumper::TREE)
10614 && dump ("Read member:%d %C:%N", tag, TREE_CODE (res), res);
10615 }
10616 }
10617 break;
10618
10619 case tt_binfo:
10620 /* A BINFO. Walk the tree of the dominating type. */
10621 {
10622 tree type;
10623 unsigned ix = binfo_mergeable (&type);
10624 if (type)
10625 {
10626 res = TYPE_BINFO (type);
10627 for (; ix && res; res = TREE_CHAIN (res))
10628 ix--;
10629 if (!res)
10630 set_overrun ();
10631 }
10632
10633 if (get_overrun ())
10634 break;
10635
10636 /* Insert binfo into backreferences. */
10637 tag = insert (res);
10638 dump (dumper::TREE) && dump ("Read binfo:%d %N", tag, res);
10639 }
10640 break;
10641
10642 case tt_vtable:
10643 {
10644 unsigned ix = u ();
10645 tree ctx = tree_node ();
10646 dump (dumper::TREE) && dump ("Reading vtable %N[%u]", ctx, ix);
10647 if (TREE_CODE (ctx) == RECORD_TYPE && TYPE_LANG_SPECIFIC (ctx))
10648 for (res = CLASSTYPE_VTABLES (ctx); res; res = DECL_CHAIN (res))
10649 if (!ix--)
10650 break;
10651 if (!res)
10652 set_overrun ();
10653 }
10654 break;
10655
10656 case tt_thunk:
10657 {
10658 int fixed = i ();
10659 tree target = tree_node ();
10660 tree virt = tree_node ();
10661
10662 for (tree thunk = DECL_THUNKS (target);
10663 thunk; thunk = DECL_CHAIN (thunk))
10664 if (THUNK_FIXED_OFFSET (thunk) == fixed
10665 && !THUNK_VIRTUAL_OFFSET (thunk) == !virt
10666 && (!virt
10667 || tree_int_cst_equal (virt, THUNK_VIRTUAL_OFFSET (thunk))))
10668 {
10669 res = thunk;
10670 break;
10671 }
10672
10673 int tag = insert (res);
10674 if (res)
10675 dump (dumper::TREE)
10676 && dump ("Read:%d thunk %N to %N", tag, DECL_NAME (res), target);
10677 else
10678 set_overrun ();
10679 }
10680 break;
10681
10682 case tt_clone_ref:
10683 {
10684 tree target = tree_node ();
10685 tree name = tree_node ();
10686
10687 if (DECL_P (target) && DECL_MAYBE_IN_CHARGE_CDTOR_P (target))
10688 {
10689 tree clone;
10690 FOR_EVERY_CLONE (clone, target)
10691 if (DECL_NAME (clone) == name)
10692 {
10693 res = clone;
10694 break;
10695 }
10696 }
10697
10698 /* A clone might have a different vtable entry. */
10699 if (res && DECL_VIRTUAL_P (res))
10700 DECL_VINDEX (res) = tree_node ();
10701
10702 if (!res)
10703 set_overrun ();
10704 int tag = insert (res);
10705 if (res)
10706 dump (dumper::TREE)
10707 && dump ("Read:%d clone %N of %N", tag, DECL_NAME (res), target);
10708 else
10709 set_overrun ();
10710 }
10711 break;
10712
10713 case tt_entity:
10714 /* Index into the entity table. Perhaps not loaded yet! */
10715 {
10716 unsigned origin = state->slurp->remap_module (u ());
10717 unsigned ident = u ();
10718 module_state *from = (*modules)[origin];
10719
10720 if (!origin || ident >= from->entity_num)
10721 set_overrun ();
10722 if (!get_overrun ())
10723 {
10724 binding_slot *slot = &(*entity_ary)[from->entity_lwm + ident];
10725 if (slot->is_lazy ())
10726 if (!from->lazy_load (ident, slot))
10727 set_overrun ();
10728 res = *slot;
10729 }
10730
10731 if (res)
10732 {
10733 const char *kind = (origin != state->mod ? "Imported" : "Named");
10734 int tag = insert (res);
10735 dump (dumper::TREE)
10736 && dump ("%s:%d %C:%N@%M", kind, tag, TREE_CODE (res),
10737 res, (*modules)[origin]);
10738
10739 if (!add_indirects (res))
10740 {
10741 set_overrun ();
10742 res = NULL_TREE;
10743 }
10744 }
10745 }
10746 break;
10747
10748 case tt_template:
10749 /* A template. */
10750 if (tree tpl = tree_node ())
10751 {
10752 res = (TREE_CODE (tpl) == TU_LOCAL_ENTITY ?
10753 tpl : DECL_TEMPLATE_RESULT (tpl));
10754 dump (dumper::TREE)
10755 && dump ("Read template %C:%N", TREE_CODE (res), res);
10756 }
10757 break;
10758 }
10759
10760 if (is_use && !unused && res && DECL_P (res) && !TREE_USED (res))
10761 {
10762 /* Mark decl used as mark_used does -- we cannot call
10763 mark_used in the middle of streaming, we only need a subset
10764 of its functionality. */
10765 TREE_USED (res) = true;
10766
10767 /* And for structured bindings also the underlying decl. */
10768 if (DECL_DECOMPOSITION_P (res) && !DECL_DECOMP_IS_BASE (res))
10769 TREE_USED (DECL_DECOMP_BASE (res)) = true;
10770
10771 if (DECL_CLONED_FUNCTION_P (res))
10772 TREE_USED (DECL_CLONED_FUNCTION (res)) = true;
10773 }
10774
10775 dump.outdent ();
10776 return res;
10777 }
10778
10779 void
10780 trees_out::tpl_parms (tree parms, unsigned &tpl_levels)
10781 {
10782 if (!parms)
10783 return;
10784
10785 if (TREE_VISITED (parms))
10786 {
10787 ref_node (parms);
10788 return;
10789 }
10790
10791 tpl_parms (TREE_CHAIN (parms), tpl_levels);
10792
10793 tree vec = TREE_VALUE (parms);
10794 unsigned len = TREE_VEC_LENGTH (vec);
10795 /* Depth. */
10796 int tag = insert (parms);
10797 if (streaming_p ())
10798 {
10799 i (len + 1);
10800 dump (dumper::TREE)
10801 && dump ("Writing template parms:%d level:%N length:%d",
10802 tag, TREE_PURPOSE (parms), len);
10803 }
10804 tree_node (TREE_PURPOSE (parms));
10805
10806 for (unsigned ix = 0; ix != len; ix++)
10807 {
10808 tree parm = TREE_VEC_ELT (vec, ix);
10809 tree decl = TREE_VALUE (parm);
10810
10811 gcc_checking_assert (DECL_TEMPLATE_PARM_P (decl));
10812 if (CHECKING_P)
10813 switch (TREE_CODE (decl))
10814 {
10815 default: gcc_unreachable ();
10816
10817 case TEMPLATE_DECL:
10818 gcc_assert ((TREE_CODE (TREE_TYPE (decl)) == TEMPLATE_TEMPLATE_PARM)
10819 && (TREE_CODE (DECL_TEMPLATE_RESULT (decl)) == TYPE_DECL)
10820 && (TYPE_NAME (TREE_TYPE (decl)) == decl));
10821 break;
10822
10823 case TYPE_DECL:
10824 gcc_assert ((TREE_CODE (TREE_TYPE (decl)) == TEMPLATE_TYPE_PARM)
10825 && (TYPE_NAME (TREE_TYPE (decl)) == decl));
10826 break;
10827
10828 case PARM_DECL:
10829 gcc_assert ((TREE_CODE (DECL_INITIAL (decl)) == TEMPLATE_PARM_INDEX)
10830 && (TREE_CODE (TEMPLATE_PARM_DECL (DECL_INITIAL (decl)))
10831 == CONST_DECL)
10832 && (DECL_TEMPLATE_PARM_P
10833 (TEMPLATE_PARM_DECL (DECL_INITIAL (decl)))));
10834 break;
10835 }
10836
10837 tree_node (decl);
10838 tree_node (TEMPLATE_PARM_CONSTRAINTS (parm));
10839 }
10840
10841 tpl_levels++;
10842 }
10843
10844 tree
10845 trees_in::tpl_parms (unsigned &tpl_levels)
10846 {
10847 tree parms = NULL_TREE;
10848
10849 while (int len = i ())
10850 {
10851 if (len < 0)
10852 {
10853 parms = back_ref (len);
10854 continue;
10855 }
10856
10857 len -= 1;
10858 parms = tree_cons (NULL_TREE, NULL_TREE, parms);
10859 int tag = insert (parms);
10860 TREE_PURPOSE (parms) = tree_node ();
10861
10862 dump (dumper::TREE)
10863 && dump ("Reading template parms:%d level:%N length:%d",
10864 tag, TREE_PURPOSE (parms), len);
10865
10866 tree vec = make_tree_vec (len);
10867 for (int ix = 0; ix != len; ix++)
10868 {
10869 tree decl = tree_node ();
10870 if (!decl)
10871 return NULL_TREE;
10872
10873 tree parm = build_tree_list (NULL, decl);
10874 TEMPLATE_PARM_CONSTRAINTS (parm) = tree_node ();
10875
10876 TREE_VEC_ELT (vec, ix) = parm;
10877 }
10878
10879 TREE_VALUE (parms) = vec;
10880 tpl_levels++;
10881 }
10882
10883 return parms;
10884 }
10885
10886 void
10887 trees_out::tpl_parms_fini (tree tmpl, unsigned tpl_levels)
10888 {
10889 for (tree parms = DECL_TEMPLATE_PARMS (tmpl);
10890 tpl_levels--; parms = TREE_CHAIN (parms))
10891 {
10892 tree vec = TREE_VALUE (parms);
10893
10894 tree_node (TREE_TYPE (vec));
10895 for (unsigned ix = TREE_VEC_LENGTH (vec); ix--;)
10896 {
10897 tree parm = TREE_VEC_ELT (vec, ix);
10898 tree dflt = TREE_PURPOSE (parm);
10899 tree_node (dflt);
10900
10901 /* Template template parameters need a context of their owning
10902 template. This is quite tricky to infer correctly on stream-in
10903 (see PR c++/98881) so we'll just provide it directly. */
10904 tree decl = TREE_VALUE (parm);
10905 if (TREE_CODE (decl) == TEMPLATE_DECL)
10906 tree_node (DECL_CONTEXT (decl));
10907 }
10908 }
10909 }
10910
10911 bool
10912 trees_in::tpl_parms_fini (tree tmpl, unsigned tpl_levels)
10913 {
10914 for (tree parms = DECL_TEMPLATE_PARMS (tmpl);
10915 tpl_levels--; parms = TREE_CHAIN (parms))
10916 {
10917 tree vec = TREE_VALUE (parms);
10918
10919 TREE_TYPE (vec) = tree_node ();
10920 for (unsigned ix = TREE_VEC_LENGTH (vec); ix--;)
10921 {
10922 tree parm = TREE_VEC_ELT (vec, ix);
10923 tree dflt = tree_node ();
10924 TREE_PURPOSE (parm) = dflt;
10925
10926 tree decl = TREE_VALUE (parm);
10927 if (TREE_CODE (decl) == TEMPLATE_DECL)
10928 DECL_CONTEXT (decl) = tree_node ();
10929
10930 if (get_overrun ())
10931 return false;
10932 }
10933 }
10934 return true;
10935 }
10936
10937 /* PARMS is a LIST, one node per level.
10938 TREE_VALUE is a TREE_VEC of parm info for that level.
10939 each ELT is a TREE_LIST
10940 TREE_VALUE is PARM_DECL, TYPE_DECL or TEMPLATE_DECL
10941 TREE_PURPOSE is the default value. */
10942
10943 void
10944 trees_out::tpl_header (tree tpl, unsigned *tpl_levels)
10945 {
10946 tree parms = DECL_TEMPLATE_PARMS (tpl);
10947 tpl_parms (parms, *tpl_levels);
10948
10949 /* Mark end. */
10950 if (streaming_p ())
10951 u (0);
10952
10953 if (*tpl_levels)
10954 tree_node (TEMPLATE_PARMS_CONSTRAINTS (parms));
10955 }
10956
10957 bool
10958 trees_in::tpl_header (tree tpl, unsigned *tpl_levels)
10959 {
10960 tree parms = tpl_parms (*tpl_levels);
10961 if (!parms)
10962 return false;
10963
10964 DECL_TEMPLATE_PARMS (tpl) = parms;
10965
10966 if (*tpl_levels)
10967 TEMPLATE_PARMS_CONSTRAINTS (parms) = tree_node ();
10968
10969 return true;
10970 }
10971
10972 /* Stream skeleton parm nodes, with their flags, type & parm indices.
10973 All the parms will have consecutive tags. */
10974
10975 void
10976 trees_out::fn_parms_init (tree fn)
10977 {
10978 /* First init them. */
10979 int base_tag = ref_num - 1;
10980 int ix = 0;
10981 for (tree parm = DECL_ARGUMENTS (fn);
10982 parm; parm = DECL_CHAIN (parm), ix++)
10983 {
10984 if (streaming_p ())
10985 {
10986 start (parm);
10987 tree_node_bools (parm);
10988 }
10989 int tag = insert (parm);
10990 gcc_checking_assert (base_tag - ix == tag);
10991 }
10992 /* Mark the end. */
10993 if (streaming_p ())
10994 u (0);
10995
10996 /* Now stream their contents. */
10997 ix = 0;
10998 for (tree parm = DECL_ARGUMENTS (fn);
10999 parm; parm = DECL_CHAIN (parm), ix++)
11000 {
11001 if (streaming_p ())
11002 dump (dumper::TREE)
11003 && dump ("Writing parm:%d %u (%N) of %N",
11004 base_tag - ix, ix, parm, fn);
11005 tree_node_vals (parm);
11006 }
11007
11008 if (!streaming_p ())
11009 {
11010 /* We must walk contract attrs so the dependency graph is complete. */
11011 for (tree contract = DECL_CONTRACTS (fn);
11012 contract;
11013 contract = CONTRACT_CHAIN (contract))
11014 tree_node (contract);
11015 }
11016
11017 /* Write a reference to contracts pre/post functions, if any, to avoid
11018 regenerating them in importers. */
11019 tree_node (DECL_PRE_FN (fn));
11020 tree_node (DECL_POST_FN (fn));
11021 }
11022
11023 /* Build skeleton parm nodes, read their flags, type & parm indices. */
11024
11025 int
11026 trees_in::fn_parms_init (tree fn)
11027 {
11028 int base_tag = ~(int)back_refs.length ();
11029
11030 tree *parm_ptr = &DECL_ARGUMENTS (fn);
11031 int ix = 0;
11032 for (; int code = u (); ix++)
11033 {
11034 tree parm = start (code);
11035 if (!tree_node_bools (parm))
11036 return 0;
11037
11038 int tag = insert (parm);
11039 gcc_checking_assert (base_tag - ix == tag);
11040 *parm_ptr = parm;
11041 parm_ptr = &DECL_CHAIN (parm);
11042 }
11043
11044 ix = 0;
11045 for (tree parm = DECL_ARGUMENTS (fn);
11046 parm; parm = DECL_CHAIN (parm), ix++)
11047 {
11048 dump (dumper::TREE)
11049 && dump ("Reading parm:%d %u (%N) of %N",
11050 base_tag - ix, ix, parm, fn);
11051 if (!tree_node_vals (parm))
11052 return 0;
11053 }
11054
11055 /* Reload references to contract functions, if any. */
11056 tree pre_fn = tree_node ();
11057 tree post_fn = tree_node ();
11058 set_contract_functions (fn, pre_fn, post_fn);
11059
11060 return base_tag;
11061 }
11062
11063 /* Read the remaining parm node data. Replace with existing (if
11064 non-null) in the map. */
11065
11066 void
11067 trees_in::fn_parms_fini (int tag, tree fn, tree existing, bool is_defn)
11068 {
11069 tree existing_parm = existing ? DECL_ARGUMENTS (existing) : NULL_TREE;
11070 tree parms = DECL_ARGUMENTS (fn);
11071 unsigned ix = 0;
11072 for (tree parm = parms; parm; parm = DECL_CHAIN (parm), ix++)
11073 {
11074 if (existing_parm)
11075 {
11076 if (is_defn && !DECL_SAVED_TREE (existing))
11077 {
11078 /* If we're about to become the definition, set the
11079 names of the parms from us. */
11080 DECL_NAME (existing_parm) = DECL_NAME (parm);
11081 DECL_SOURCE_LOCATION (existing_parm) = DECL_SOURCE_LOCATION (parm);
11082
11083 /* And some other flags important for codegen are only set
11084 by the definition. */
11085 TREE_ADDRESSABLE (existing_parm) = TREE_ADDRESSABLE (parm);
11086 DECL_BY_REFERENCE (existing_parm) = DECL_BY_REFERENCE (parm);
11087 DECL_NONLOCAL (existing_parm) = DECL_NONLOCAL (parm);
11088 DECL_ARG_TYPE (existing_parm) = DECL_ARG_TYPE (parm);
11089
11090 /* Invisiref parms had their types adjusted by cp_genericize. */
11091 if (DECL_BY_REFERENCE (parm))
11092 {
11093 TREE_TYPE (existing_parm) = TREE_TYPE (parm);
11094 relayout_decl (existing_parm);
11095 }
11096 }
11097
11098 back_refs[~tag] = existing_parm;
11099 existing_parm = DECL_CHAIN (existing_parm);
11100 }
11101 tag--;
11102 }
11103 }
11104
11105 /* Encode into KEY the position of the local type (class or enum)
11106 declaration DECL within FN. The position is encoded as the
11107 index of the innermost BLOCK (numbered in BFS order) along with
11108 the index within its BLOCK_VARS list. */
11109
11110 void
11111 trees_out::key_local_type (merge_key& key, tree decl, tree fn)
11112 {
11113 auto_vec<tree, 4> blocks;
11114 blocks.quick_push (DECL_INITIAL (fn));
11115 unsigned block_ix = 0;
11116 while (block_ix != blocks.length ())
11117 {
11118 tree block = blocks[block_ix];
11119 unsigned decl_ix = 0;
11120 for (tree var = BLOCK_VARS (block); var; var = DECL_CHAIN (var))
11121 {
11122 if (TREE_CODE (var) != TYPE_DECL)
11123 continue;
11124 if (var == decl)
11125 {
11126 key.index = (block_ix << 10) | decl_ix;
11127 return;
11128 }
11129 ++decl_ix;
11130 }
11131 for (tree sub = BLOCK_SUBBLOCKS (block); sub; sub = BLOCK_CHAIN (sub))
11132 blocks.safe_push (sub);
11133 ++block_ix;
11134 }
11135
11136 /* Not-found value. */
11137 key.index = 1023;
11138 }
11139
11140 /* Look up the local type corresponding at the position encoded by
11141 KEY within FN and named NAME. */
11142
11143 tree
11144 trees_in::key_local_type (const merge_key& key, tree fn, tree name)
11145 {
11146 if (!DECL_INITIAL (fn))
11147 return NULL_TREE;
11148
11149 const unsigned block_pos = key.index >> 10;
11150 const unsigned decl_pos = key.index & 1023;
11151
11152 if (decl_pos == 1023)
11153 return NULL_TREE;
11154
11155 auto_vec<tree, 4> blocks;
11156 blocks.quick_push (DECL_INITIAL (fn));
11157 unsigned block_ix = 0;
11158 while (block_ix != blocks.length ())
11159 {
11160 tree block = blocks[block_ix];
11161 if (block_ix == block_pos)
11162 {
11163 unsigned decl_ix = 0;
11164 for (tree var = BLOCK_VARS (block); var; var = DECL_CHAIN (var))
11165 {
11166 if (TREE_CODE (var) != TYPE_DECL)
11167 continue;
11168 /* Prefer using the identifier as the key for more robustness
11169 to ODR violations, except for anonymous types since their
11170 compiler-generated identifiers aren't stable. */
11171 if (IDENTIFIER_ANON_P (name)
11172 ? decl_ix == decl_pos
11173 : DECL_NAME (var) == name)
11174 return var;
11175 ++decl_ix;
11176 }
11177 return NULL_TREE;
11178 }
11179 for (tree sub = BLOCK_SUBBLOCKS (block); sub; sub = BLOCK_CHAIN (sub))
11180 blocks.safe_push (sub);
11181 ++block_ix;
11182 }
11183
11184 return NULL_TREE;
11185 }
11186
11187 /* DEP is the depset of some decl we're streaming by value. Determine
11188 the merging behaviour. */
11189
11190 merge_kind
11191 trees_out::get_merge_kind (tree decl, depset *dep)
11192 {
11193 if (!dep)
11194 {
11195 if (VAR_OR_FUNCTION_DECL_P (decl))
11196 {
11197 /* Any var or function with template info should have DEP. */
11198 gcc_checking_assert (!DECL_LANG_SPECIFIC (decl)
11199 || !DECL_TEMPLATE_INFO (decl));
11200 if (DECL_LOCAL_DECL_P (decl))
11201 return MK_unique;
11202 }
11203
11204 /* Either unique, or some member of a class that cannot have an
11205 out-of-class definition. For instance a FIELD_DECL. */
11206 tree ctx = CP_DECL_CONTEXT (decl);
11207 if (TREE_CODE (ctx) == FUNCTION_DECL)
11208 {
11209 /* USING_DECLs and NAMESPACE_DECLs cannot have DECL_TEMPLATE_INFO --
11210 this isn't permitting them to have one. */
11211 gcc_checking_assert (TREE_CODE (decl) == USING_DECL
11212 || TREE_CODE (decl) == NAMESPACE_DECL
11213 || !DECL_LANG_SPECIFIC (decl)
11214 || !DECL_TEMPLATE_INFO (decl));
11215
11216 return MK_unique;
11217 }
11218
11219 if (TREE_CODE (decl) == TEMPLATE_DECL
11220 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
11221 return MK_local_friend;
11222
11223 gcc_checking_assert (TYPE_P (ctx));
11224 if (TREE_CODE (decl) == USING_DECL)
11225 return MK_field;
11226
11227 if (TREE_CODE (decl) == FIELD_DECL)
11228 {
11229 if (DECL_NAME (decl))
11230 {
11231 /* Anonymous FIELD_DECLs have a NULL name. */
11232 gcc_checking_assert (!IDENTIFIER_ANON_P (DECL_NAME (decl)));
11233 return MK_named;
11234 }
11235
11236 if (!DECL_NAME (decl)
11237 && !RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl))
11238 && !DECL_BIT_FIELD_REPRESENTATIVE (decl))
11239 {
11240 /* The underlying storage unit for a bitfield. We do not
11241 need to dedup it, because it's only reachable through
11242 the bitfields it represents. And those are deduped. */
11243 // FIXME: Is that assertion correct -- do we ever fish it
11244 // out and put it in an expr?
11245 gcc_checking_assert ((TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
11246 ? TREE_CODE (TREE_TYPE (TREE_TYPE (decl)))
11247 : TREE_CODE (TREE_TYPE (decl)))
11248 == INTEGER_TYPE);
11249 return MK_unique;
11250 }
11251
11252 return MK_field;
11253 }
11254
11255 if (TREE_CODE (decl) == CONST_DECL)
11256 return MK_named;
11257
11258 if (TREE_CODE (decl) == VAR_DECL
11259 && DECL_VTABLE_OR_VTT_P (decl))
11260 return MK_vtable;
11261
11262 if (DECL_THUNK_P (decl))
11263 /* Thunks are unique-enough, because they're only referenced
11264 from the vtable. And that's either new (so we want the
11265 thunks), or it's a duplicate (so it will be dropped). */
11266 return MK_unique;
11267
11268 /* There should be no other cases. */
11269 gcc_unreachable ();
11270 }
11271
11272 gcc_checking_assert (TREE_CODE (decl) != FIELD_DECL
11273 && TREE_CODE (decl) != USING_DECL
11274 && TREE_CODE (decl) != CONST_DECL);
11275
11276 if (is_key_order ())
11277 {
11278 /* When doing the mergeablilty graph, there's an indirection to
11279 the actual depset. */
11280 gcc_assert (dep->is_special ());
11281 dep = dep->deps[0];
11282 }
11283
11284 gcc_checking_assert (decl == dep->get_entity ());
11285
11286 merge_kind mk = MK_named;
11287 switch (dep->get_entity_kind ())
11288 {
11289 default:
11290 gcc_unreachable ();
11291
11292 case depset::EK_PARTIAL:
11293 mk = MK_partial;
11294 break;
11295
11296 case depset::EK_DECL:
11297 {
11298 tree ctx = CP_DECL_CONTEXT (decl);
11299
11300 switch (TREE_CODE (ctx))
11301 {
11302 default:
11303 gcc_unreachable ();
11304
11305 case FUNCTION_DECL:
11306 gcc_checking_assert
11307 (DECL_IMPLICIT_TYPEDEF_P (STRIP_TEMPLATE (decl)));
11308
11309 mk = MK_local_type;
11310 break;
11311
11312 case RECORD_TYPE:
11313 case UNION_TYPE:
11314 case NAMESPACE_DECL:
11315 if (DECL_NAME (decl) == as_base_identifier)
11316 {
11317 mk = MK_as_base;
11318 break;
11319 }
11320
11321 /* A lambda may have a class as its context, even though it
11322 isn't a member in the traditional sense; see the test
11323 g++.dg/modules/lambda-6_a.C. */
11324 if (DECL_IMPLICIT_TYPEDEF_P (STRIP_TEMPLATE (decl))
11325 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
11326 {
11327 if (get_keyed_decl_scope (decl))
11328 mk = MK_keyed;
11329 else
11330 /* Lambdas not attached to any mangling scope are TU-local
11331 and so cannot be deduplicated. */
11332 mk = MK_unique;
11333 break;
11334 }
11335
11336 if (TREE_CODE (decl) == TEMPLATE_DECL
11337 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
11338 {
11339 mk = MK_local_friend;
11340 break;
11341 }
11342
11343 if (DECL_DECOMPOSITION_P (decl))
11344 {
11345 mk = MK_unique;
11346 break;
11347 }
11348
11349 if (IDENTIFIER_ANON_P (DECL_NAME (decl)))
11350 {
11351 if (RECORD_OR_UNION_TYPE_P (ctx))
11352 mk = MK_field;
11353 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
11354 && UNSCOPED_ENUM_P (TREE_TYPE (decl))
11355 && TYPE_VALUES (TREE_TYPE (decl)))
11356 /* Keyed by first enum value, and underlying type. */
11357 mk = MK_enum;
11358 else
11359 /* No way to merge it, it is an ODR land-mine. */
11360 mk = MK_unique;
11361 }
11362 }
11363 }
11364 break;
11365
11366 case depset::EK_SPECIALIZATION:
11367 {
11368 gcc_checking_assert (dep->is_special ());
11369
11370 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
11371 /* An block-scope classes of templates are themselves
11372 templates. */
11373 gcc_checking_assert (DECL_IMPLICIT_TYPEDEF_P (decl));
11374
11375 if (dep->is_friend_spec ())
11376 mk = MK_friend_spec;
11377 else if (dep->is_type_spec ())
11378 mk = MK_type_spec;
11379 else
11380 mk = MK_decl_spec;
11381
11382 if (TREE_CODE (decl) == TEMPLATE_DECL)
11383 {
11384 spec_entry *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
11385 if (TREE_CODE (entry->spec) != TEMPLATE_DECL)
11386 mk = merge_kind (mk | MK_tmpl_tmpl_mask);
11387 }
11388 }
11389 break;
11390 }
11391
11392 return mk;
11393 }
11394
11395
11396 /* The container of DECL -- not necessarily its context! */
11397
11398 tree
11399 trees_out::decl_container (tree decl)
11400 {
11401 int use_tpl;
11402 tree tpl = NULL_TREE;
11403 if (tree template_info = node_template_info (decl, use_tpl))
11404 tpl = TI_TEMPLATE (template_info);
11405 if (tpl == decl)
11406 tpl = nullptr;
11407
11408 /* Stream the template we're instantiated from. */
11409 tree_node (tpl);
11410
11411 tree container = NULL_TREE;
11412 if (TREE_CODE (decl) == TEMPLATE_DECL
11413 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
11414 container = DECL_CHAIN (decl);
11415 else
11416 container = CP_DECL_CONTEXT (decl);
11417
11418 if (TYPE_P (container))
11419 container = TYPE_NAME (container);
11420
11421 tree_node (container);
11422
11423 return container;
11424 }
11425
11426 tree
11427 trees_in::decl_container ()
11428 {
11429 /* The maybe-template. */
11430 (void)tree_node ();
11431
11432 tree container = tree_node ();
11433
11434 return container;
11435 }
11436
11437 /* Write out key information about a mergeable DEP. Does not write
11438 the contents of DEP itself. The context has already been
11439 written. The container has already been streamed. */
11440
11441 void
11442 trees_out::key_mergeable (int tag, merge_kind mk, tree decl, tree inner,
11443 tree container, depset *dep)
11444 {
11445 if (dep && is_key_order ())
11446 {
11447 gcc_checking_assert (dep->is_special ());
11448 dep = dep->deps[0];
11449 }
11450
11451 if (streaming_p ())
11452 dump (dumper::MERGE)
11453 && dump ("Writing:%d's %s merge key (%s) %C:%N", tag, merge_kind_name[mk],
11454 dep ? dep->entity_kind_name () : "contained",
11455 TREE_CODE (decl), decl);
11456
11457 /* Now write the locating information. */
11458 if (mk & MK_template_mask)
11459 {
11460 /* Specializations are located via their originating template,
11461 and the set of template args they specialize. */
11462 gcc_checking_assert (dep && dep->is_special ());
11463 spec_entry *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
11464
11465 tree_node (entry->tmpl);
11466 tree_node (entry->args);
11467 if (mk & MK_tmpl_decl_mask)
11468 if (flag_concepts && TREE_CODE (inner) == VAR_DECL)
11469 {
11470 /* Variable template partial specializations might need
11471 constraints (see spec_hasher::equal). It's simpler to
11472 write NULL when we don't need them. */
11473 tree constraints = NULL_TREE;
11474
11475 if (uses_template_parms (entry->args))
11476 constraints = get_constraints (inner);
11477 tree_node (constraints);
11478 }
11479
11480 if (CHECKING_P)
11481 {
11482 /* Make sure we can locate the decl. */
11483 tree existing = match_mergeable_specialization
11484 (bool (mk & MK_tmpl_decl_mask), entry);
11485
11486 gcc_assert (existing);
11487 if (mk & MK_tmpl_decl_mask)
11488 {
11489 if (mk & MK_tmpl_tmpl_mask)
11490 existing = DECL_TI_TEMPLATE (existing);
11491 }
11492 else
11493 {
11494 if (mk & MK_tmpl_tmpl_mask)
11495 existing = CLASSTYPE_TI_TEMPLATE (existing);
11496 else
11497 existing = TYPE_NAME (existing);
11498 }
11499
11500 /* The walkabout should have found ourselves. */
11501 gcc_checking_assert (TREE_CODE (decl) == TYPE_DECL
11502 ? same_type_p (TREE_TYPE (decl),
11503 TREE_TYPE (existing))
11504 : existing == decl);
11505 }
11506 }
11507 else if (mk != MK_unique)
11508 {
11509 merge_key key;
11510 tree name = DECL_NAME (decl);
11511
11512 switch (mk)
11513 {
11514 default:
11515 gcc_unreachable ();
11516
11517 case MK_named:
11518 case MK_friend_spec:
11519 if (IDENTIFIER_CONV_OP_P (name))
11520 name = conv_op_identifier;
11521
11522 if (TREE_CODE (inner) == FUNCTION_DECL)
11523 {
11524 /* Functions are distinguished by parameter types. */
11525 tree fn_type = TREE_TYPE (inner);
11526
11527 key.ref_q = type_memfn_rqual (fn_type);
11528 key.args = TYPE_ARG_TYPES (fn_type);
11529
11530 if (tree reqs = get_constraints (inner))
11531 {
11532 if (cxx_dialect < cxx20)
11533 reqs = CI_ASSOCIATED_CONSTRAINTS (reqs);
11534 else
11535 reqs = CI_DECLARATOR_REQS (reqs);
11536 key.constraints = reqs;
11537 }
11538
11539 if (IDENTIFIER_CONV_OP_P (name)
11540 || (decl != inner
11541 && !(name == fun_identifier
11542 /* In case the user names something _FUN */
11543 && LAMBDA_TYPE_P (DECL_CONTEXT (inner)))))
11544 /* And a function template, or conversion operator needs
11545 the return type. Except for the _FUN thunk of a
11546 generic lambda, which has a recursive decl_type'd
11547 return type. */
11548 // FIXME: What if the return type is a voldemort?
11549 key.ret = fndecl_declared_return_type (inner);
11550 }
11551 break;
11552
11553 case MK_field:
11554 {
11555 unsigned ix = 0;
11556 if (TREE_CODE (inner) != FIELD_DECL)
11557 name = NULL_TREE;
11558 else
11559 gcc_checking_assert (!name || !IDENTIFIER_ANON_P (name));
11560
11561 for (tree field = TYPE_FIELDS (TREE_TYPE (container));
11562 ; field = DECL_CHAIN (field))
11563 {
11564 tree finner = STRIP_TEMPLATE (field);
11565 if (TREE_CODE (finner) == TREE_CODE (inner))
11566 {
11567 if (finner == inner)
11568 break;
11569 ix++;
11570 }
11571 }
11572 key.index = ix;
11573 }
11574 break;
11575
11576 case MK_vtable:
11577 {
11578 tree vtable = CLASSTYPE_VTABLES (TREE_TYPE (container));
11579 for (unsigned ix = 0; ; vtable = DECL_CHAIN (vtable), ix++)
11580 if (vtable == decl)
11581 {
11582 key.index = ix;
11583 break;
11584 }
11585 name = NULL_TREE;
11586 }
11587 break;
11588
11589 case MK_as_base:
11590 gcc_checking_assert
11591 (decl == TYPE_NAME (CLASSTYPE_AS_BASE (TREE_TYPE (container))));
11592 break;
11593
11594 case MK_local_friend:
11595 {
11596 /* Find by index on the class's DECL_LIST */
11597 unsigned ix = 0;
11598 for (tree decls = CLASSTYPE_DECL_LIST (TREE_CHAIN (decl));
11599 decls; decls = TREE_CHAIN (decls))
11600 if (!TREE_PURPOSE (decls))
11601 {
11602 tree frnd = friend_from_decl_list (TREE_VALUE (decls));
11603 if (frnd == decl)
11604 break;
11605 ix++;
11606 }
11607 key.index = ix;
11608 name = NULL_TREE;
11609 }
11610 break;
11611
11612 case MK_local_type:
11613 key_local_type (key, STRIP_TEMPLATE (decl), container);
11614 break;
11615
11616 case MK_enum:
11617 {
11618 /* Anonymous enums are located by their first identifier,
11619 and underlying type. */
11620 tree type = TREE_TYPE (decl);
11621
11622 gcc_checking_assert (UNSCOPED_ENUM_P (type));
11623 /* Using the type name drops the bit precision we might
11624 have been using on the enum. */
11625 key.ret = TYPE_NAME (ENUM_UNDERLYING_TYPE (type));
11626 if (tree values = TYPE_VALUES (type))
11627 name = DECL_NAME (TREE_VALUE (values));
11628 }
11629 break;
11630
11631 case MK_keyed:
11632 {
11633 tree scope = get_keyed_decl_scope (inner);
11634 gcc_checking_assert (scope);
11635
11636 auto *root = keyed_table->get (scope);
11637 unsigned ix = root->length ();
11638 /* If we don't find it, we'll write a really big number
11639 that the reader will ignore. */
11640 while (ix--)
11641 if ((*root)[ix] == inner)
11642 break;
11643
11644 /* Use the keyed-to decl as the 'name'. */
11645 name = scope;
11646 key.index = ix;
11647 }
11648 break;
11649
11650 case MK_partial:
11651 {
11652 tree ti = get_template_info (inner);
11653 key.constraints = get_constraints (inner);
11654 key.ret = TI_TEMPLATE (ti);
11655 key.args = TI_ARGS (ti);
11656 }
11657 break;
11658 }
11659
11660 tree_node (name);
11661 if (streaming_p ())
11662 {
11663 unsigned code = (key.ref_q << 0) | (key.index << 2);
11664 u (code);
11665 }
11666
11667 if (mk == MK_enum)
11668 tree_node (key.ret);
11669 else if (mk == MK_partial
11670 || (mk == MK_named && inner
11671 && TREE_CODE (inner) == FUNCTION_DECL))
11672 {
11673 tree_node (key.ret);
11674 tree arg = key.args;
11675 if (mk == MK_named)
11676 while (arg && arg != void_list_node)
11677 {
11678 tree_node (TREE_VALUE (arg));
11679 arg = TREE_CHAIN (arg);
11680 }
11681 tree_node (arg);
11682 tree_node (key.constraints);
11683 }
11684 }
11685 }
11686
11687 /* DECL is a new declaration that may be duplicated in OVL. Use RET &
11688 ARGS to find its clone, or NULL. If DECL's DECL_NAME is NULL, this
11689 has been found by a proxy. It will be an enum type located by its
11690 first member.
11691
11692 We're conservative with matches, so ambiguous decls will be
11693 registered as different, then lead to a lookup error if the two
11694 modules are both visible. Perhaps we want to do something similar
11695 to duplicate decls to get ODR errors on loading? We already have
11696 some special casing for namespaces. */
11697
11698 static tree
11699 check_mergeable_decl (merge_kind mk, tree decl, tree ovl, merge_key const &key)
11700 {
11701 tree found = NULL_TREE;
11702 for (ovl_iterator iter (ovl); !found && iter; ++iter)
11703 {
11704 tree match = *iter;
11705
11706 tree d_inner = decl;
11707 tree m_inner = match;
11708
11709 again:
11710 if (TREE_CODE (d_inner) != TREE_CODE (m_inner))
11711 {
11712 if (TREE_CODE (match) == NAMESPACE_DECL
11713 && !DECL_NAMESPACE_ALIAS (match))
11714 /* Namespaces are never overloaded. */
11715 found = match;
11716
11717 continue;
11718 }
11719
11720 switch (TREE_CODE (d_inner))
11721 {
11722 case TEMPLATE_DECL:
11723 if (template_heads_equivalent_p (d_inner, m_inner))
11724 {
11725 d_inner = DECL_TEMPLATE_RESULT (d_inner);
11726 m_inner = DECL_TEMPLATE_RESULT (m_inner);
11727 if (d_inner == error_mark_node
11728 && TYPE_DECL_ALIAS_P (m_inner))
11729 {
11730 found = match;
11731 break;
11732 }
11733 goto again;
11734 }
11735 break;
11736
11737 case FUNCTION_DECL:
11738 if (tree m_type = TREE_TYPE (m_inner))
11739 if ((!key.ret
11740 || same_type_p (key.ret, fndecl_declared_return_type (m_inner)))
11741 && type_memfn_rqual (m_type) == key.ref_q
11742 && compparms (key.args, TYPE_ARG_TYPES (m_type))
11743 /* Reject if old is a "C" builtin and new is not "C".
11744 Matches decls_match behaviour. */
11745 && (!DECL_IS_UNDECLARED_BUILTIN (m_inner)
11746 || !DECL_EXTERN_C_P (m_inner)
11747 || DECL_EXTERN_C_P (d_inner))
11748 /* Reject if one is a different member of a
11749 guarded/pre/post fn set. */
11750 && (!flag_contracts
11751 || (DECL_IS_PRE_FN_P (d_inner)
11752 == DECL_IS_PRE_FN_P (m_inner)))
11753 && (!flag_contracts
11754 || (DECL_IS_POST_FN_P (d_inner)
11755 == DECL_IS_POST_FN_P (m_inner))))
11756 {
11757 tree m_reqs = get_constraints (m_inner);
11758 if (m_reqs)
11759 {
11760 if (cxx_dialect < cxx20)
11761 m_reqs = CI_ASSOCIATED_CONSTRAINTS (m_reqs);
11762 else
11763 m_reqs = CI_DECLARATOR_REQS (m_reqs);
11764 }
11765
11766 if (cp_tree_equal (key.constraints, m_reqs))
11767 found = match;
11768 }
11769 break;
11770
11771 case TYPE_DECL:
11772 if (DECL_IMPLICIT_TYPEDEF_P (d_inner)
11773 == DECL_IMPLICIT_TYPEDEF_P (m_inner))
11774 {
11775 if (!IDENTIFIER_ANON_P (DECL_NAME (m_inner)))
11776 return match;
11777 else if (mk == MK_enum
11778 && (TYPE_NAME (ENUM_UNDERLYING_TYPE (TREE_TYPE (m_inner)))
11779 == key.ret))
11780 found = match;
11781 }
11782 break;
11783
11784 default:
11785 found = match;
11786 break;
11787 }
11788 }
11789
11790 return found;
11791 }
11792
11793 /* DECL, INNER & TYPE are a skeleton set of nodes for a decl. Only
11794 the bools have been filled in. Read its merging key and merge it.
11795 Returns the existing decl if there is one. */
11796
11797 tree
11798 trees_in::key_mergeable (int tag, merge_kind mk, tree decl, tree inner,
11799 tree type, tree container, bool is_attached,
11800 bool is_imported_temploid_friend)
11801 {
11802 const char *kind = "new";
11803 tree existing = NULL_TREE;
11804
11805 if (mk & MK_template_mask)
11806 {
11807 // FIXME: We could stream the specialization hash?
11808 spec_entry spec;
11809 spec.tmpl = tree_node ();
11810 spec.args = tree_node ();
11811
11812 if (get_overrun ())
11813 return error_mark_node;
11814
11815 DECL_NAME (decl) = DECL_NAME (spec.tmpl);
11816 DECL_CONTEXT (decl) = DECL_CONTEXT (spec.tmpl);
11817 DECL_NAME (inner) = DECL_NAME (decl);
11818 DECL_CONTEXT (inner) = DECL_CONTEXT (decl);
11819
11820 tree constr = NULL_TREE;
11821 bool is_decl = mk & MK_tmpl_decl_mask;
11822 if (is_decl)
11823 {
11824 if (flag_concepts && TREE_CODE (inner) == VAR_DECL)
11825 {
11826 constr = tree_node ();
11827 if (constr)
11828 set_constraints (inner, constr);
11829 }
11830 spec.spec = (mk & MK_tmpl_tmpl_mask) ? inner : decl;
11831 }
11832 else
11833 spec.spec = type;
11834 existing = match_mergeable_specialization (is_decl, &spec);
11835 if (constr)
11836 /* We'll add these back later, if this is the new decl. */
11837 remove_constraints (inner);
11838
11839 if (!existing)
11840 ; /* We'll add to the table once read. */
11841 else if (mk & MK_tmpl_decl_mask)
11842 {
11843 /* A declaration specialization. */
11844 if (mk & MK_tmpl_tmpl_mask)
11845 existing = DECL_TI_TEMPLATE (existing);
11846 }
11847 else
11848 {
11849 /* A type specialization. */
11850 if (mk & MK_tmpl_tmpl_mask)
11851 existing = CLASSTYPE_TI_TEMPLATE (existing);
11852 else
11853 existing = TYPE_NAME (existing);
11854 }
11855 }
11856 else if (mk == MK_unique)
11857 kind = "unique";
11858 else
11859 {
11860 tree name = tree_node ();
11861
11862 merge_key key;
11863 unsigned code = u ();
11864 key.ref_q = cp_ref_qualifier ((code >> 0) & 3);
11865 key.index = code >> 2;
11866
11867 if (mk == MK_enum)
11868 key.ret = tree_node ();
11869 else if (mk == MK_partial
11870 || ((mk == MK_named || mk == MK_friend_spec)
11871 && TREE_CODE (inner) == FUNCTION_DECL))
11872 {
11873 key.ret = tree_node ();
11874 tree arg, *arg_ptr = &key.args;
11875 while ((arg = tree_node ())
11876 && arg != void_list_node
11877 && mk != MK_partial)
11878 {
11879 *arg_ptr = tree_cons (NULL_TREE, arg, NULL_TREE);
11880 arg_ptr = &TREE_CHAIN (*arg_ptr);
11881 }
11882 *arg_ptr = arg;
11883 key.constraints = tree_node ();
11884 }
11885
11886 if (get_overrun ())
11887 return error_mark_node;
11888
11889 if (mk < MK_indirect_lwm)
11890 {
11891 DECL_NAME (decl) = name;
11892 DECL_CONTEXT (decl) = FROB_CONTEXT (container);
11893 }
11894 DECL_NAME (inner) = DECL_NAME (decl);
11895 DECL_CONTEXT (inner) = DECL_CONTEXT (decl);
11896
11897 if (mk == MK_partial)
11898 {
11899 for (tree spec = DECL_TEMPLATE_SPECIALIZATIONS (key.ret);
11900 spec; spec = TREE_CHAIN (spec))
11901 {
11902 tree tmpl = TREE_VALUE (spec);
11903 tree ti = get_template_info (tmpl);
11904 if (template_args_equal (key.args, TI_ARGS (ti))
11905 && cp_tree_equal (key.constraints,
11906 get_constraints
11907 (DECL_TEMPLATE_RESULT (tmpl))))
11908 {
11909 existing = tmpl;
11910 break;
11911 }
11912 }
11913 }
11914 else if (mk == MK_keyed
11915 && DECL_LANG_SPECIFIC (name)
11916 && DECL_MODULE_KEYED_DECLS_P (name))
11917 {
11918 gcc_checking_assert (TREE_CODE (container) == NAMESPACE_DECL
11919 || TREE_CODE (container) == TYPE_DECL);
11920 if (auto *set = keyed_table->get (name))
11921 if (key.index < set->length ())
11922 {
11923 existing = (*set)[key.index];
11924 if (existing)
11925 {
11926 gcc_checking_assert
11927 (DECL_IMPLICIT_TYPEDEF_P (existing));
11928 if (inner != decl)
11929 existing
11930 = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (existing));
11931 }
11932 }
11933 }
11934 else
11935 switch (TREE_CODE (container))
11936 {
11937 default:
11938 gcc_unreachable ();
11939
11940 case NAMESPACE_DECL:
11941 if (is_attached
11942 && !is_imported_temploid_friend
11943 && !(state->is_module () || state->is_partition ()))
11944 kind = "unique";
11945 else
11946 {
11947 gcc_checking_assert (mk == MK_named || mk == MK_enum);
11948 tree mvec;
11949 tree *vslot = mergeable_namespace_slots (container, name,
11950 is_attached, &mvec);
11951 existing = check_mergeable_decl (mk, decl, *vslot, key);
11952 if (!existing)
11953 add_mergeable_namespace_entity (vslot, decl);
11954 else
11955 {
11956 /* Note that we now have duplicates to deal with in
11957 name lookup. */
11958 if (is_attached)
11959 BINDING_VECTOR_PARTITION_DUPS_P (mvec) = true;
11960 else
11961 BINDING_VECTOR_GLOBAL_DUPS_P (mvec) = true;
11962 }
11963 }
11964 break;
11965
11966 case FUNCTION_DECL:
11967 gcc_checking_assert (mk == MK_local_type);
11968 existing = key_local_type (key, container, name);
11969 if (existing && inner != decl)
11970 existing = TYPE_TI_TEMPLATE (TREE_TYPE (existing));
11971 break;
11972
11973 case TYPE_DECL:
11974 gcc_checking_assert (!is_imported_temploid_friend);
11975 int use_tmpl = 0;
11976 if (is_attached && !(state->is_module () || state->is_partition ())
11977 /* Implicit or in-class defaulted member functions
11978 can come from anywhere. */
11979 && !(TREE_CODE (decl) == FUNCTION_DECL
11980 && !DECL_THUNK_P (decl)
11981 && DECL_DEFAULTED_FN (decl)
11982 && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl))
11983 /* As can members of template specialisations. */
11984 && !(node_template_info (container, use_tmpl)
11985 && use_tmpl != 0))
11986 kind = "unique";
11987 else
11988 {
11989 tree ctx = TREE_TYPE (container);
11990
11991 /* For some reason templated enumeral types are not marked
11992 as COMPLETE_TYPE_P, even though they have members.
11993 This may well be a bug elsewhere. */
11994 if (TREE_CODE (ctx) == ENUMERAL_TYPE)
11995 existing = find_enum_member (ctx, name);
11996 else if (COMPLETE_TYPE_P (ctx))
11997 {
11998 switch (mk)
11999 {
12000 default:
12001 gcc_unreachable ();
12002
12003 case MK_named:
12004 existing = lookup_class_binding (ctx, name);
12005 if (existing)
12006 {
12007 tree inner = decl;
12008 if (TREE_CODE (inner) == TEMPLATE_DECL
12009 && !DECL_MEMBER_TEMPLATE_P (inner))
12010 inner = DECL_TEMPLATE_RESULT (inner);
12011
12012 existing = check_mergeable_decl
12013 (mk, inner, existing, key);
12014
12015 if (!existing && DECL_ALIAS_TEMPLATE_P (decl))
12016 {} // FIXME: Insert into specialization
12017 // tables, we'll need the arguments for that!
12018 }
12019 break;
12020
12021 case MK_field:
12022 {
12023 unsigned ix = key.index;
12024 for (tree field = TYPE_FIELDS (ctx);
12025 field; field = DECL_CHAIN (field))
12026 {
12027 tree finner = STRIP_TEMPLATE (field);
12028 if (TREE_CODE (finner) == TREE_CODE (inner))
12029 if (!ix--)
12030 {
12031 existing = field;
12032 break;
12033 }
12034 }
12035 }
12036 break;
12037
12038 case MK_vtable:
12039 {
12040 unsigned ix = key.index;
12041 for (tree vtable = CLASSTYPE_VTABLES (ctx);
12042 vtable; vtable = DECL_CHAIN (vtable))
12043 if (!ix--)
12044 {
12045 existing = vtable;
12046 break;
12047 }
12048 }
12049 break;
12050
12051 case MK_as_base:
12052 {
12053 tree as_base = CLASSTYPE_AS_BASE (ctx);
12054 if (as_base && as_base != ctx)
12055 existing = TYPE_NAME (as_base);
12056 }
12057 break;
12058
12059 case MK_local_friend:
12060 {
12061 unsigned ix = key.index;
12062 for (tree decls = CLASSTYPE_DECL_LIST (ctx);
12063 decls; decls = TREE_CHAIN (decls))
12064 if (!TREE_PURPOSE (decls) && !ix--)
12065 {
12066 existing
12067 = friend_from_decl_list (TREE_VALUE (decls));
12068 break;
12069 }
12070 }
12071 break;
12072 }
12073
12074 if (existing && mk < MK_indirect_lwm && mk != MK_partial
12075 && TREE_CODE (decl) == TEMPLATE_DECL
12076 && !DECL_MEMBER_TEMPLATE_P (decl))
12077 {
12078 tree ti;
12079 if (DECL_IMPLICIT_TYPEDEF_P (existing))
12080 ti = TYPE_TEMPLATE_INFO (TREE_TYPE (existing));
12081 else
12082 ti = DECL_TEMPLATE_INFO (existing);
12083 existing = TI_TEMPLATE (ti);
12084 }
12085 }
12086 }
12087 }
12088 }
12089
12090 dump (dumper::MERGE)
12091 && dump ("Read:%d's %s merge key (%s) %C:%N", tag, merge_kind_name[mk],
12092 existing ? "matched" : kind, TREE_CODE (decl), decl);
12093
12094 return existing;
12095 }
12096
12097 void
12098 trees_out::binfo_mergeable (tree binfo)
12099 {
12100 tree dom = binfo;
12101 while (tree parent = BINFO_INHERITANCE_CHAIN (dom))
12102 dom = parent;
12103 tree type = BINFO_TYPE (dom);
12104 gcc_checking_assert (TYPE_BINFO (type) == dom);
12105 tree_node (type);
12106 if (streaming_p ())
12107 {
12108 unsigned ix = 0;
12109 for (; dom != binfo; dom = TREE_CHAIN (dom))
12110 ix++;
12111 u (ix);
12112 }
12113 }
12114
12115 unsigned
12116 trees_in::binfo_mergeable (tree *type)
12117 {
12118 *type = tree_node ();
12119 return u ();
12120 }
12121
12122 /* DECL is a just streamed declaration with attributes DATTR that should
12123 have matching ABI tags as EXISTING's attributes EATTR. Check that the
12124 ABI tags match, and report an error if not. */
12125
12126 void
12127 trees_in::check_abi_tags (tree existing, tree decl, tree &eattr, tree &dattr)
12128 {
12129 tree etags = lookup_attribute ("abi_tag", eattr);
12130 tree dtags = lookup_attribute ("abi_tag", dattr);
12131 if ((etags == nullptr) != (dtags == nullptr)
12132 || (etags && !attribute_value_equal (etags, dtags)))
12133 {
12134 if (etags)
12135 etags = TREE_VALUE (etags);
12136 if (dtags)
12137 dtags = TREE_VALUE (dtags);
12138
12139 /* We only error if mangling wouldn't consider the tags equivalent. */
12140 if (!equal_abi_tags (etags, dtags))
12141 {
12142 auto_diagnostic_group d;
12143 if (dtags)
12144 error_at (DECL_SOURCE_LOCATION (decl),
12145 "mismatching abi tags for %qD with tags %qE",
12146 decl, dtags);
12147 else
12148 error_at (DECL_SOURCE_LOCATION (decl),
12149 "mismatching abi tags for %qD with no tags", decl);
12150 if (etags)
12151 inform (DECL_SOURCE_LOCATION (existing),
12152 "existing declaration here with tags %qE", etags);
12153 else
12154 inform (DECL_SOURCE_LOCATION (existing),
12155 "existing declaration here with no tags");
12156 }
12157
12158 /* Always use the existing abi_tags as the canonical set so that
12159 later processing doesn't get confused. */
12160 if (dtags)
12161 dattr = remove_attribute ("abi_tag", dattr);
12162 if (etags)
12163 duplicate_one_attribute (&dattr, eattr, "abi_tag");
12164 }
12165 }
12166
12167 /* DECL is a just streamed mergeable decl that should match EXISTING. Check
12168 it does and issue an appropriate diagnostic if not. Merge any
12169 bits from DECL to EXISTING. This is stricter matching than
12170 decls_match, because we can rely on ODR-sameness, and we cannot use
12171 decls_match because it can cause instantiations of constraints. */
12172
12173 bool
12174 trees_in::is_matching_decl (tree existing, tree decl, bool is_typedef)
12175 {
12176 // FIXME: We should probably do some duplicate decl-like stuff here
12177 // (beware, default parms should be the same?) Can we just call
12178 // duplicate_decls and teach it how to handle the module-specific
12179 // permitted/required duplications?
12180
12181 // We know at this point that the decls have matched by key, so we
12182 // can elide some of the checking
12183 gcc_checking_assert (TREE_CODE (existing) == TREE_CODE (decl));
12184
12185 tree d_inner = decl;
12186 tree e_inner = existing;
12187 if (TREE_CODE (decl) == TEMPLATE_DECL)
12188 {
12189 d_inner = DECL_TEMPLATE_RESULT (d_inner);
12190 e_inner = DECL_TEMPLATE_RESULT (e_inner);
12191 gcc_checking_assert (TREE_CODE (e_inner) == TREE_CODE (d_inner));
12192 }
12193
12194 // FIXME: do more precise errors at point of mismatch
12195 const char *mismatch_msg = nullptr;
12196
12197 if (VAR_OR_FUNCTION_DECL_P (d_inner)
12198 && DECL_EXTERN_C_P (d_inner) != DECL_EXTERN_C_P (e_inner))
12199 {
12200 mismatch_msg = G_("conflicting language linkage for imported "
12201 "declaration %#qD");
12202 goto mismatch;
12203 }
12204 else if (TREE_CODE (d_inner) == FUNCTION_DECL)
12205 {
12206 tree e_ret = fndecl_declared_return_type (existing);
12207 tree d_ret = fndecl_declared_return_type (decl);
12208
12209 if (decl != d_inner && DECL_NAME (d_inner) == fun_identifier
12210 && LAMBDA_TYPE_P (DECL_CONTEXT (d_inner)))
12211 /* This has a recursive type that will compare different. */;
12212 else if (!same_type_p (d_ret, e_ret))
12213 {
12214 mismatch_msg = G_("conflicting type for imported declaration %#qD");
12215 goto mismatch;
12216 }
12217
12218 tree e_type = TREE_TYPE (e_inner);
12219 tree d_type = TREE_TYPE (d_inner);
12220
12221 for (tree e_args = TYPE_ARG_TYPES (e_type),
12222 d_args = TYPE_ARG_TYPES (d_type);
12223 e_args != d_args && (e_args || d_args);
12224 e_args = TREE_CHAIN (e_args), d_args = TREE_CHAIN (d_args))
12225 {
12226 if (!(e_args && d_args))
12227 {
12228 mismatch_msg = G_("conflicting argument list for imported "
12229 "declaration %#qD");
12230 goto mismatch;
12231 }
12232
12233 if (!same_type_p (TREE_VALUE (d_args), TREE_VALUE (e_args)))
12234 {
12235 mismatch_msg = G_("conflicting argument types for imported "
12236 "declaration %#qD");
12237 goto mismatch;
12238 }
12239 }
12240
12241 /* If EXISTING has an undeduced or uninstantiated exception
12242 specification, but DECL does not, propagate the exception
12243 specification. Otherwise we end up asserting or trying to
12244 instantiate it in the middle of loading. */
12245 tree e_spec = TYPE_RAISES_EXCEPTIONS (e_type);
12246 tree d_spec = TYPE_RAISES_EXCEPTIONS (d_type);
12247 if (DECL_MAYBE_DELETED (e_inner) || DEFERRED_NOEXCEPT_SPEC_P (e_spec))
12248 {
12249 if (!(DECL_MAYBE_DELETED (d_inner)
12250 || DEFERRED_NOEXCEPT_SPEC_P (d_spec))
12251 || (UNEVALUATED_NOEXCEPT_SPEC_P (e_spec)
12252 && !UNEVALUATED_NOEXCEPT_SPEC_P (d_spec)))
12253 {
12254 dump (dumper::MERGE)
12255 && dump ("Propagating instantiated noexcept to %N", existing);
12256 gcc_checking_assert (existing == e_inner);
12257 TREE_TYPE (existing) = d_type;
12258
12259 /* Propagate to existing clones. */
12260 tree clone;
12261 FOR_EACH_CLONE (clone, existing)
12262 {
12263 if (TREE_TYPE (clone) == e_type)
12264 TREE_TYPE (clone) = d_type;
12265 else
12266 TREE_TYPE (clone)
12267 = build_exception_variant (TREE_TYPE (clone), d_spec);
12268 }
12269 }
12270 }
12271 else if (!DECL_MAYBE_DELETED (d_inner)
12272 && !DEFERRED_NOEXCEPT_SPEC_P (d_spec)
12273 && !comp_except_specs (d_spec, e_spec, ce_type))
12274 {
12275 mismatch_msg = G_("conflicting %<noexcept%> specifier for "
12276 "imported declaration %#qD");
12277 goto mismatch;
12278 }
12279
12280 /* Similarly if EXISTING has an undeduced return type, but DECL's
12281 is already deduced. */
12282 bool e_undeduced = undeduced_auto_decl (existing);
12283 bool d_undeduced = undeduced_auto_decl (decl);
12284 if (e_undeduced && !d_undeduced)
12285 {
12286 dump (dumper::MERGE)
12287 && dump ("Propagating deduced return type to %N", existing);
12288 FNDECL_USED_AUTO (e_inner) = true;
12289 DECL_SAVED_AUTO_RETURN_TYPE (existing) = TREE_TYPE (e_type);
12290 TREE_TYPE (existing) = change_return_type (TREE_TYPE (d_type), e_type);
12291 }
12292 else if (d_undeduced && !e_undeduced)
12293 /* EXISTING was deduced, leave it alone. */;
12294 else if (type_uses_auto (d_ret)
12295 && !same_type_p (TREE_TYPE (d_type), TREE_TYPE (e_type)))
12296 {
12297 mismatch_msg = G_("conflicting deduced return type for "
12298 "imported declaration %#qD");
12299 goto mismatch;
12300 }
12301
12302 /* Similarly if EXISTING has undeduced constexpr, but DECL's
12303 is already deduced. */
12304 if (DECL_MAYBE_DELETED (e_inner) && !DECL_MAYBE_DELETED (d_inner)
12305 && DECL_DECLARED_CONSTEXPR_P (d_inner))
12306 DECL_DECLARED_CONSTEXPR_P (e_inner) = true;
12307 else if (!DECL_MAYBE_DELETED (e_inner) && DECL_MAYBE_DELETED (d_inner))
12308 /* Nothing to do. */;
12309 else if (DECL_DECLARED_CONSTEXPR_P (e_inner)
12310 != DECL_DECLARED_CONSTEXPR_P (d_inner))
12311 {
12312 mismatch_msg = G_("conflicting %<constexpr%> for imported "
12313 "declaration %#qD");
12314 goto mismatch;
12315 }
12316
12317 /* Don't synthesize a defaulted function if we're importing one
12318 we've already determined. */
12319 if (!DECL_MAYBE_DELETED (d_inner))
12320 DECL_MAYBE_DELETED (e_inner) = false;
12321 }
12322 else if (is_typedef)
12323 {
12324 if (!DECL_ORIGINAL_TYPE (e_inner)
12325 || !same_type_p (DECL_ORIGINAL_TYPE (d_inner),
12326 DECL_ORIGINAL_TYPE (e_inner)))
12327 {
12328 mismatch_msg = G_("conflicting imported declaration %q#D");
12329 goto mismatch;
12330 }
12331 }
12332 /* Using cp_tree_equal because we can meet TYPE_ARGUMENT_PACKs
12333 here. I suspect the entities that directly do that are things
12334 that shouldn't go to duplicate_decls (FIELD_DECLs etc). */
12335 else if (!cp_tree_equal (TREE_TYPE (decl), TREE_TYPE (existing)))
12336 {
12337 mismatch_msg = G_("conflicting type for imported declaration %#qD");
12338 mismatch:
12339 if (DECL_IS_UNDECLARED_BUILTIN (existing))
12340 /* Just like duplicate_decls, presum the user knows what
12341 they're doing in overriding a builtin. */
12342 TREE_TYPE (existing) = TREE_TYPE (decl);
12343 else if (decl_function_context (decl))
12344 /* The type of a mergeable local entity (such as a function scope
12345 capturing lambda's closure type fields) can depend on an
12346 unmergeable local entity (such as a local variable), so type
12347 equality isn't feasible in general for local entities. */;
12348 else
12349 {
12350 gcc_checking_assert (mismatch_msg);
12351 auto_diagnostic_group d;
12352 error_at (DECL_SOURCE_LOCATION (decl), mismatch_msg, decl);
12353 inform (DECL_SOURCE_LOCATION (existing),
12354 "existing declaration %#qD", existing);
12355 return false;
12356 }
12357 }
12358
12359 if (DECL_IS_UNDECLARED_BUILTIN (existing)
12360 && !DECL_IS_UNDECLARED_BUILTIN (decl))
12361 {
12362 /* We're matching a builtin that the user has yet to declare.
12363 We are the one! This is very much duplicate-decl
12364 shenanigans. */
12365 DECL_SOURCE_LOCATION (existing) = DECL_SOURCE_LOCATION (decl);
12366 if (TREE_CODE (decl) != TYPE_DECL)
12367 {
12368 /* Propagate exceptions etc. */
12369 TREE_TYPE (existing) = TREE_TYPE (decl);
12370 TREE_NOTHROW (existing) = TREE_NOTHROW (decl);
12371 }
12372 /* This is actually an import! */
12373 DECL_MODULE_IMPORT_P (existing) = true;
12374
12375 /* Yay, sliced! */
12376 existing->base = decl->base;
12377
12378 if (TREE_CODE (decl) == FUNCTION_DECL)
12379 {
12380 /* Ew :( */
12381 memcpy (&existing->decl_common.size,
12382 &decl->decl_common.size,
12383 (offsetof (tree_decl_common, pt_uid)
12384 - offsetof (tree_decl_common, size)));
12385 auto bltin_class = DECL_BUILT_IN_CLASS (decl);
12386 existing->function_decl.built_in_class = bltin_class;
12387 auto fncode = DECL_UNCHECKED_FUNCTION_CODE (decl);
12388 DECL_UNCHECKED_FUNCTION_CODE (existing) = fncode;
12389 if (existing->function_decl.built_in_class == BUILT_IN_NORMAL)
12390 {
12391 if (builtin_decl_explicit_p (built_in_function (fncode)))
12392 switch (fncode)
12393 {
12394 case BUILT_IN_STPCPY:
12395 set_builtin_decl_implicit_p
12396 (built_in_function (fncode), true);
12397 break;
12398 default:
12399 set_builtin_decl_declared_p
12400 (built_in_function (fncode), true);
12401 break;
12402 }
12403 copy_attributes_to_builtin (decl);
12404 }
12405 }
12406 }
12407
12408 if (VAR_OR_FUNCTION_DECL_P (decl)
12409 && DECL_TEMPLATE_INSTANTIATED (decl))
12410 /* Don't instantiate again! */
12411 DECL_TEMPLATE_INSTANTIATED (existing) = true;
12412
12413 if (TREE_CODE (d_inner) == FUNCTION_DECL
12414 && DECL_DECLARED_INLINE_P (d_inner))
12415 {
12416 DECL_DECLARED_INLINE_P (e_inner) = true;
12417 if (!DECL_SAVED_TREE (e_inner)
12418 && lookup_attribute ("gnu_inline", DECL_ATTRIBUTES (d_inner))
12419 && !lookup_attribute ("gnu_inline", DECL_ATTRIBUTES (e_inner)))
12420 {
12421 DECL_INTERFACE_KNOWN (e_inner)
12422 |= DECL_INTERFACE_KNOWN (d_inner);
12423 DECL_DISREGARD_INLINE_LIMITS (e_inner)
12424 |= DECL_DISREGARD_INLINE_LIMITS (d_inner);
12425 // TODO: we will eventually want to merge all decl attributes
12426 duplicate_one_attribute (&DECL_ATTRIBUTES (e_inner),
12427 DECL_ATTRIBUTES (d_inner), "gnu_inline");
12428 }
12429 }
12430 if (!DECL_EXTERNAL (d_inner))
12431 DECL_EXTERNAL (e_inner) = false;
12432
12433 if (VAR_OR_FUNCTION_DECL_P (d_inner))
12434 check_abi_tags (existing, decl,
12435 DECL_ATTRIBUTES (e_inner), DECL_ATTRIBUTES (d_inner));
12436
12437 if (TREE_CODE (decl) == TEMPLATE_DECL)
12438 {
12439 /* Merge default template arguments. */
12440 tree d_parms = DECL_INNERMOST_TEMPLATE_PARMS (decl);
12441 tree e_parms = DECL_INNERMOST_TEMPLATE_PARMS (existing);
12442 gcc_checking_assert (TREE_VEC_LENGTH (d_parms)
12443 == TREE_VEC_LENGTH (e_parms));
12444 for (int i = 0; i < TREE_VEC_LENGTH (d_parms); ++i)
12445 {
12446 tree d_default = TREE_PURPOSE (TREE_VEC_ELT (d_parms, i));
12447 tree& e_default = TREE_PURPOSE (TREE_VEC_ELT (e_parms, i));
12448 if (e_default == NULL_TREE)
12449 e_default = d_default;
12450 else if (d_default != NULL_TREE
12451 && !cp_tree_equal (d_default, e_default))
12452 {
12453 auto_diagnostic_group d;
12454 tree d_parm = TREE_VALUE (TREE_VEC_ELT (d_parms, i));
12455 tree e_parm = TREE_VALUE (TREE_VEC_ELT (e_parms, i));
12456 error_at (DECL_SOURCE_LOCATION (d_parm),
12457 "conflicting default argument for %#qD", d_parm);
12458 inform (DECL_SOURCE_LOCATION (e_parm),
12459 "existing default declared here");
12460 return false;
12461 }
12462 }
12463 }
12464
12465 if (TREE_CODE (d_inner) == FUNCTION_DECL)
12466 {
12467 /* Merge default function arguments. */
12468 tree d_parm = FUNCTION_FIRST_USER_PARMTYPE (d_inner);
12469 tree e_parm = FUNCTION_FIRST_USER_PARMTYPE (e_inner);
12470 int i = 0;
12471 for (; d_parm && d_parm != void_list_node;
12472 d_parm = TREE_CHAIN (d_parm), e_parm = TREE_CHAIN (e_parm), ++i)
12473 {
12474 tree d_default = TREE_PURPOSE (d_parm);
12475 tree& e_default = TREE_PURPOSE (e_parm);
12476 if (e_default == NULL_TREE)
12477 e_default = d_default;
12478 else if (d_default != NULL_TREE
12479 && !cp_tree_equal (d_default, e_default))
12480 {
12481 auto_diagnostic_group d;
12482 error_at (get_fndecl_argument_location (d_inner, i),
12483 "conflicting default argument for parameter %P of %#qD",
12484 i, decl);
12485 inform (get_fndecl_argument_location (e_inner, i),
12486 "existing default declared here");
12487 return false;
12488 }
12489 }
12490 }
12491
12492 return true;
12493 }
12494
12495 /* FN is an implicit member function that we've discovered is new to
12496 the class. Add it to the TYPE_FIELDS chain and the method vector.
12497 Reset the appropriate classtype lazy flag. */
12498
12499 bool
12500 trees_in::install_implicit_member (tree fn)
12501 {
12502 tree ctx = DECL_CONTEXT (fn);
12503 tree name = DECL_NAME (fn);
12504 /* We know these are synthesized, so the set of expected prototypes
12505 is quite restricted. We're not validating correctness, just
12506 distinguishing beteeen the small set of possibilities. */
12507 tree parm_type = TREE_VALUE (FUNCTION_FIRST_USER_PARMTYPE (fn));
12508 if (IDENTIFIER_CTOR_P (name))
12509 {
12510 if (CLASSTYPE_LAZY_DEFAULT_CTOR (ctx)
12511 && VOID_TYPE_P (parm_type))
12512 CLASSTYPE_LAZY_DEFAULT_CTOR (ctx) = false;
12513 else if (!TYPE_REF_P (parm_type))
12514 return false;
12515 else if (CLASSTYPE_LAZY_COPY_CTOR (ctx)
12516 && !TYPE_REF_IS_RVALUE (parm_type))
12517 CLASSTYPE_LAZY_COPY_CTOR (ctx) = false;
12518 else if (CLASSTYPE_LAZY_MOVE_CTOR (ctx))
12519 CLASSTYPE_LAZY_MOVE_CTOR (ctx) = false;
12520 else
12521 return false;
12522 }
12523 else if (IDENTIFIER_DTOR_P (name))
12524 {
12525 if (CLASSTYPE_LAZY_DESTRUCTOR (ctx))
12526 CLASSTYPE_LAZY_DESTRUCTOR (ctx) = false;
12527 else
12528 return false;
12529 if (DECL_VIRTUAL_P (fn))
12530 /* A virtual dtor should have been created when the class
12531 became complete. */
12532 return false;
12533 }
12534 else if (name == assign_op_identifier)
12535 {
12536 if (!TYPE_REF_P (parm_type))
12537 return false;
12538 else if (CLASSTYPE_LAZY_COPY_ASSIGN (ctx)
12539 && !TYPE_REF_IS_RVALUE (parm_type))
12540 CLASSTYPE_LAZY_COPY_ASSIGN (ctx) = false;
12541 else if (CLASSTYPE_LAZY_MOVE_ASSIGN (ctx))
12542 CLASSTYPE_LAZY_MOVE_ASSIGN (ctx) = false;
12543 else
12544 return false;
12545 }
12546 else
12547 return false;
12548
12549 dump (dumper::MERGE) && dump ("Adding implicit member %N", fn);
12550
12551 DECL_CHAIN (fn) = TYPE_FIELDS (ctx);
12552 TYPE_FIELDS (ctx) = fn;
12553
12554 add_method (ctx, fn, false);
12555
12556 /* Propagate TYPE_FIELDS. */
12557 fixup_type_variants (ctx);
12558
12559 return true;
12560 }
12561
12562 /* Return non-zero if DECL has a definition that would be interesting to
12563 write out. */
12564
12565 static bool
12566 has_definition (tree decl)
12567 {
12568 bool is_tmpl = TREE_CODE (decl) == TEMPLATE_DECL;
12569 if (is_tmpl)
12570 decl = DECL_TEMPLATE_RESULT (decl);
12571
12572 switch (TREE_CODE (decl))
12573 {
12574 default:
12575 break;
12576
12577 case FUNCTION_DECL:
12578 if (!DECL_SAVED_TREE (decl))
12579 /* Not defined. */
12580 break;
12581
12582 if (DECL_DECLARED_INLINE_P (decl))
12583 return true;
12584
12585 if (header_module_p ())
12586 /* We always need to write definitions in header modules,
12587 since there's no TU to emit them in otherwise. */
12588 return true;
12589
12590 if (DECL_TEMPLATE_INFO (decl))
12591 {
12592 int use_tpl = DECL_USE_TEMPLATE (decl);
12593
12594 // FIXME: Partial specializations have definitions too.
12595 if (use_tpl < 2)
12596 return true;
12597 }
12598 break;
12599
12600 case TYPE_DECL:
12601 {
12602 tree type = TREE_TYPE (decl);
12603 if (type == TYPE_MAIN_VARIANT (type)
12604 && decl == TYPE_NAME (type)
12605 && (TREE_CODE (type) == ENUMERAL_TYPE
12606 ? TYPE_VALUES (type) : TYPE_FIELDS (type)))
12607 return true;
12608 }
12609 break;
12610
12611 case VAR_DECL:
12612 /* DECL_INITIALIZED_P might not be set on a dependent VAR_DECL. */
12613 if (DECL_LANG_SPECIFIC (decl)
12614 && DECL_TEMPLATE_INFO (decl)
12615 && DECL_INITIAL (decl))
12616 return true;
12617 else
12618 {
12619 if (!DECL_INITIALIZED_P (decl))
12620 /* Not defined. */
12621 return false;
12622
12623 if (header_module_p ())
12624 /* We always need to write definitions in header modules,
12625 since there's no TU to emit them in otherwise. */
12626 return true;
12627
12628 if (decl_maybe_constant_var_p (decl))
12629 /* We might need its constant value. */
12630 return true;
12631
12632 if (vague_linkage_p (decl))
12633 /* These are emitted as needed. */
12634 return true;
12635
12636 return false;
12637 }
12638 break;
12639
12640 case CONCEPT_DECL:
12641 if (DECL_INITIAL (decl))
12642 return true;
12643
12644 break;
12645 }
12646
12647 return false;
12648 }
12649
12650 uintptr_t *
12651 trees_in::find_duplicate (tree existing)
12652 {
12653 if (!duplicates)
12654 return NULL;
12655
12656 return duplicates->get (existing);
12657 }
12658
12659 /* We're starting to read a duplicate DECL. EXISTING is the already
12660 known node. */
12661
12662 void
12663 trees_in::register_duplicate (tree decl, tree existing)
12664 {
12665 if (!duplicates)
12666 duplicates = new duplicate_hash_map (40);
12667
12668 bool existed;
12669 uintptr_t &slot = duplicates->get_or_insert (existing, &existed);
12670 gcc_checking_assert (!existed);
12671 slot = reinterpret_cast<uintptr_t> (decl);
12672
12673 if (TREE_CODE (decl) == TEMPLATE_DECL)
12674 /* Also register the DECL_TEMPLATE_RESULT as a duplicate so
12675 that passing decl's _RESULT to maybe_duplicate naturally
12676 gives us existing's _RESULT back. */
12677 register_duplicate (DECL_TEMPLATE_RESULT (decl),
12678 DECL_TEMPLATE_RESULT (existing));
12679 }
12680
12681 /* We've read a definition of MAYBE_EXISTING. If not a duplicate,
12682 return MAYBE_EXISTING (into which the definition should be
12683 installed). Otherwise return NULL if already known bad, or the
12684 duplicate we read (for ODR checking, or extracting additional merge
12685 information). */
12686
12687 tree
12688 trees_in::odr_duplicate (tree maybe_existing, bool has_defn)
12689 {
12690 tree res = NULL_TREE;
12691
12692 if (uintptr_t *dup = find_duplicate (maybe_existing))
12693 {
12694 if (!(*dup & 1))
12695 res = reinterpret_cast<tree> (*dup);
12696 }
12697 else
12698 res = maybe_existing;
12699
12700 assert_definition (maybe_existing, res && !has_defn);
12701
12702 // FIXME: We probably need to return the template, so that the
12703 // template header can be checked?
12704 return res ? STRIP_TEMPLATE (res) : NULL_TREE;
12705 }
12706
12707 /* The following writer functions rely on the current behaviour of
12708 depset::hash::add_dependency making the decl and defn depset nodes
12709 depend on eachother. That way we don't have to worry about seeding
12710 the tree map with named decls that cannot be looked up by name (I.e
12711 template and function parms). We know the decl and definition will
12712 be in the same cluster, which is what we want. */
12713
12714 void
12715 trees_out::write_function_def (tree decl)
12716 {
12717 tree_node (DECL_RESULT (decl));
12718
12719 {
12720 /* The function body for a non-inline function or function template
12721 is ignored for determining exposures. This should only matter
12722 for templates (we don't emit the bodies of non-inline functions
12723 to begin with). */
12724 auto ovr = make_temp_override (dep_hash->ignore_tu_local,
12725 !DECL_DECLARED_INLINE_P (decl));
12726 tree_node (DECL_INITIAL (decl));
12727 tree_node (DECL_SAVED_TREE (decl));
12728 }
12729
12730 tree_node (DECL_FRIEND_CONTEXT (decl));
12731
12732 constexpr_fundef *cexpr = retrieve_constexpr_fundef (decl);
12733
12734 if (streaming_p ())
12735 u (cexpr != nullptr);
12736 if (cexpr)
12737 {
12738 chained_decls (cexpr->parms);
12739 tree_node (cexpr->result);
12740 tree_node (cexpr->body);
12741 }
12742
12743 function* f = DECL_STRUCT_FUNCTION (decl);
12744
12745 if (streaming_p ())
12746 {
12747 unsigned flags = 0;
12748
12749 /* Whether the importer should emit this definition, if used. */
12750 flags |= 1 * (DECL_NOT_REALLY_EXTERN (decl)
12751 && (get_importer_interface (decl)
12752 != importer_interface::always_import));
12753
12754 if (f)
12755 {
12756 flags |= 2;
12757 /* These flags are needed in tsubst_lambda_expr. */
12758 flags |= 4 * f->language->returns_value;
12759 flags |= 8 * f->language->returns_null;
12760 flags |= 16 * f->language->returns_abnormally;
12761 flags |= 32 * f->language->infinite_loop;
12762 }
12763
12764 u (flags);
12765 }
12766
12767 if (state && f)
12768 {
12769 state->write_location (*this, f->function_start_locus);
12770 state->write_location (*this, f->function_end_locus);
12771 }
12772 }
12773
12774 void
12775 trees_out::mark_function_def (tree)
12776 {
12777 }
12778
12779 bool
12780 trees_in::read_function_def (tree decl, tree maybe_template)
12781 {
12782 dump () && dump ("Reading function definition %N", decl);
12783 tree result = tree_node ();
12784 tree initial = tree_node ();
12785 tree saved = tree_node ();
12786 tree context = tree_node ();
12787 constexpr_fundef cexpr;
12788 post_process_data pdata {};
12789 pdata.decl = maybe_template;
12790
12791 tree maybe_dup = odr_duplicate (maybe_template, DECL_SAVED_TREE (decl));
12792 bool installing = maybe_dup && !DECL_SAVED_TREE (decl);
12793
12794 if (u ())
12795 {
12796 cexpr.parms = chained_decls ();
12797 cexpr.result = tree_node ();
12798 cexpr.body = tree_node ();
12799 cexpr.decl = decl;
12800 }
12801 else
12802 cexpr.decl = NULL_TREE;
12803
12804 unsigned flags = u ();
12805
12806 if (flags & 2)
12807 {
12808 pdata.start_locus = state->read_location (*this);
12809 pdata.end_locus = state->read_location (*this);
12810 pdata.returns_value = flags & 4;
12811 pdata.returns_null = flags & 8;
12812 pdata.returns_abnormally = flags & 16;
12813 pdata.infinite_loop = flags & 32;
12814 }
12815
12816 if (get_overrun ())
12817 return NULL_TREE;
12818
12819 if (installing)
12820 {
12821 DECL_NOT_REALLY_EXTERN (decl) = flags & 1;
12822 DECL_RESULT (decl) = result;
12823 DECL_INITIAL (decl) = initial;
12824 DECL_SAVED_TREE (decl) = saved;
12825
12826 /* Some entities (like anticipated builtins) were declared without
12827 DECL_ARGUMENTS, so update them now. But don't do it if there's
12828 already an argument list, because we've already built the
12829 definition referencing those merged PARM_DECLs. */
12830 if (!DECL_ARGUMENTS (decl))
12831 DECL_ARGUMENTS (decl) = DECL_ARGUMENTS (maybe_dup);
12832
12833 if (context)
12834 SET_DECL_FRIEND_CONTEXT (decl, context);
12835 if (cexpr.decl)
12836 register_constexpr_fundef (cexpr);
12837 post_process (pdata);
12838 }
12839 else if (maybe_dup)
12840 {
12841 // FIXME:QOI Check matching defn
12842 }
12843
12844 return true;
12845 }
12846
12847 /* Also for CONCEPT_DECLs. */
12848
12849 void
12850 trees_out::write_var_def (tree decl)
12851 {
12852 /* The initializer of a non-inline variable or variable template is
12853 ignored for determining exposures. */
12854 auto ovr = make_temp_override (dep_hash->ignore_tu_local,
12855 VAR_P (decl) && !DECL_INLINE_VAR_P (decl));
12856
12857 tree init = DECL_INITIAL (decl);
12858 tree_node (init);
12859 if (!init)
12860 {
12861 tree dyn_init = NULL_TREE;
12862
12863 /* We only need to write initializers in header modules. */
12864 if (header_module_p () && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
12865 {
12866 dyn_init = value_member (decl,
12867 CP_DECL_THREAD_LOCAL_P (decl)
12868 ? tls_aggregates : static_aggregates);
12869 gcc_checking_assert (dyn_init);
12870 /* Mark it so write_inits knows this is needed. */
12871 TREE_LANG_FLAG_0 (dyn_init) = true;
12872 dyn_init = TREE_PURPOSE (dyn_init);
12873 }
12874 tree_node (dyn_init);
12875 }
12876 }
12877
12878 void
12879 trees_out::mark_var_def (tree)
12880 {
12881 }
12882
12883 bool
12884 trees_in::read_var_def (tree decl, tree maybe_template)
12885 {
12886 /* Do not mark the virtual table entries as used. */
12887 bool vtable = VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl);
12888 unused += vtable;
12889 tree init = tree_node ();
12890 tree dyn_init = init ? NULL_TREE : tree_node ();
12891 unused -= vtable;
12892
12893 if (get_overrun ())
12894 return false;
12895
12896 bool initialized = (VAR_P (decl) ? bool (DECL_INITIALIZED_P (decl))
12897 : bool (DECL_INITIAL (decl)));
12898 tree maybe_dup = odr_duplicate (maybe_template, initialized);
12899 bool installing = maybe_dup && !initialized;
12900 if (installing)
12901 {
12902 DECL_INITIAL (decl) = init;
12903 if (DECL_EXTERNAL (decl))
12904 DECL_NOT_REALLY_EXTERN (decl) = true;
12905 if (VAR_P (decl))
12906 {
12907 DECL_INITIALIZED_P (decl) = true;
12908 if (maybe_dup && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (maybe_dup))
12909 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
12910 tentative_decl_linkage (decl);
12911 if (DECL_EXPLICIT_INSTANTIATION (decl)
12912 && !DECL_EXTERNAL (decl))
12913 setup_explicit_instantiation_definition_linkage (decl);
12914 /* Class non-template static members are handled in read_class_def.
12915 But still handle specialisations of member templates. */
12916 if ((!DECL_CLASS_SCOPE_P (decl)
12917 || primary_template_specialization_p (decl))
12918 && (DECL_IMPLICIT_INSTANTIATION (decl)
12919 || (DECL_EXPLICIT_INSTANTIATION (decl)
12920 && !DECL_EXTERNAL (decl))))
12921 note_vague_linkage_variable (decl);
12922 }
12923 if (!dyn_init)
12924 ;
12925 else if (CP_DECL_THREAD_LOCAL_P (decl))
12926 tls_aggregates = tree_cons (dyn_init, decl, tls_aggregates);
12927 else
12928 static_aggregates = tree_cons (dyn_init, decl, static_aggregates);
12929 }
12930 else if (maybe_dup)
12931 {
12932 // FIXME:QOI Check matching defn
12933 }
12934
12935 return true;
12936 }
12937
12938 /* If MEMBER doesn't have an independent life outside the class,
12939 return it (or its TEMPLATE_DECL). Otherwise NULL. */
12940
12941 static tree
12942 member_owned_by_class (tree member)
12943 {
12944 gcc_assert (DECL_P (member));
12945
12946 /* Clones are owned by their origin. */
12947 if (DECL_CLONED_FUNCTION_P (member))
12948 return NULL;
12949
12950 if (TREE_CODE (member) == FIELD_DECL)
12951 /* FIELD_DECLS can have template info in some cases. We always
12952 want the FIELD_DECL though, as there's never a TEMPLATE_DECL
12953 wrapping them. */
12954 return member;
12955
12956 int use_tpl = -1;
12957 if (tree ti = node_template_info (member, use_tpl))
12958 {
12959 // FIXME: Don't bail on things that CANNOT have their own
12960 // template header. No, make sure they're in the same cluster.
12961 if (use_tpl > 0)
12962 return NULL_TREE;
12963
12964 if (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == member)
12965 member = TI_TEMPLATE (ti);
12966 }
12967 return member;
12968 }
12969
12970 void
12971 trees_out::write_class_def (tree defn)
12972 {
12973 gcc_assert (DECL_P (defn));
12974 if (streaming_p ())
12975 dump () && dump ("Writing class definition %N", defn);
12976
12977 tree type = TREE_TYPE (defn);
12978 tree_node (TYPE_SIZE (type));
12979 tree_node (TYPE_SIZE_UNIT (type));
12980 tree_node (TYPE_VFIELD (type));
12981 tree_node (TYPE_BINFO (type));
12982
12983 vec_chained_decls (TYPE_FIELDS (type));
12984
12985 /* Every class but __as_base has a type-specific. */
12986 gcc_checking_assert (!TYPE_LANG_SPECIFIC (type) == IS_FAKE_BASE_TYPE (type));
12987
12988 if (TYPE_LANG_SPECIFIC (type))
12989 {
12990 {
12991 vec<tree, va_gc> *v = CLASSTYPE_MEMBER_VEC (type);
12992 if (!v)
12993 {
12994 gcc_checking_assert (!streaming_p ());
12995 /* Force a class vector. */
12996 v = set_class_bindings (type, -1);
12997 gcc_checking_assert (v);
12998 }
12999
13000 unsigned len = v->length ();
13001 if (streaming_p ())
13002 u (len);
13003 for (unsigned ix = 0; ix != len; ix++)
13004 {
13005 tree m = (*v)[ix];
13006 if (TREE_CODE (m) == TYPE_DECL
13007 && DECL_ARTIFICIAL (m)
13008 && TYPE_STUB_DECL (TREE_TYPE (m)) == m)
13009 /* This is a using-decl for a type, or an anonymous
13010 struct (maybe with a typedef name). Write the type. */
13011 m = TREE_TYPE (m);
13012 tree_node (m);
13013 }
13014 }
13015 tree_node (CLASSTYPE_LAMBDA_EXPR (type));
13016
13017 /* TYPE_CONTAINS_VPTR_P looks at the vbase vector, which the
13018 reader won't know at this point. */
13019 int has_vptr = TYPE_CONTAINS_VPTR_P (type);
13020
13021 if (streaming_p ())
13022 {
13023 unsigned nvbases = vec_safe_length (CLASSTYPE_VBASECLASSES (type));
13024 u (nvbases);
13025 i (has_vptr);
13026 }
13027
13028 if (has_vptr)
13029 {
13030 tree_vec (CLASSTYPE_PURE_VIRTUALS (type));
13031 tree_pair_vec (CLASSTYPE_VCALL_INDICES (type));
13032 tree_node (CLASSTYPE_KEY_METHOD (type));
13033 }
13034 }
13035
13036 if (TYPE_LANG_SPECIFIC (type))
13037 {
13038 tree_node (CLASSTYPE_PRIMARY_BINFO (type));
13039
13040 tree as_base = CLASSTYPE_AS_BASE (type);
13041 if (as_base)
13042 as_base = TYPE_NAME (as_base);
13043 tree_node (as_base);
13044
13045 /* Write the vtables. */
13046 tree vtables = CLASSTYPE_VTABLES (type);
13047 vec_chained_decls (vtables);
13048 for (; vtables; vtables = TREE_CHAIN (vtables))
13049 write_definition (vtables);
13050
13051 {
13052 /* Friend declarations in class definitions are ignored when
13053 determining exposures. */
13054 auto ovr = make_temp_override (dep_hash->ignore_tu_local, true);
13055
13056 /* Write the friend classes. */
13057 tree_list (CLASSTYPE_FRIEND_CLASSES (type), false);
13058
13059 /* Write the friend functions. */
13060 for (tree friends = DECL_FRIENDLIST (defn);
13061 friends; friends = TREE_CHAIN (friends))
13062 {
13063 tree_node (FRIEND_NAME (friends));
13064 tree_list (FRIEND_DECLS (friends), false);
13065 }
13066 /* End of friend fns. */
13067 tree_node (NULL_TREE);
13068 }
13069
13070 /* Write the decl list. We don't need to ignore exposures of friend
13071 decls here as any such decls should already have been added and
13072 ignored above. */
13073 tree_list (CLASSTYPE_DECL_LIST (type), true);
13074
13075 if (TYPE_CONTAINS_VPTR_P (type))
13076 {
13077 /* Write the thunks. */
13078 for (tree decls = TYPE_FIELDS (type);
13079 decls; decls = DECL_CHAIN (decls))
13080 if (TREE_CODE (decls) == FUNCTION_DECL
13081 && DECL_VIRTUAL_P (decls)
13082 && DECL_THUNKS (decls))
13083 {
13084 tree_node (decls);
13085 /* Thunks are always unique, so chaining is ok. */
13086 chained_decls (DECL_THUNKS (decls));
13087 }
13088 tree_node (NULL_TREE);
13089 }
13090 }
13091 }
13092
13093 void
13094 trees_out::mark_class_member (tree member, bool do_defn)
13095 {
13096 gcc_assert (DECL_P (member));
13097
13098 member = member_owned_by_class (member);
13099 if (member)
13100 mark_declaration (member, do_defn && has_definition (member));
13101 }
13102
13103 void
13104 trees_out::mark_class_def (tree defn)
13105 {
13106 gcc_assert (DECL_P (defn));
13107 tree type = TREE_TYPE (defn);
13108 /* Mark the class members that are not type-decls and cannot have
13109 independent definitions. */
13110 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
13111 if (TREE_CODE (member) == FIELD_DECL
13112 || TREE_CODE (member) == USING_DECL
13113 /* A cloned enum-decl from 'using enum unrelated;' */
13114 || (TREE_CODE (member) == CONST_DECL
13115 && DECL_CONTEXT (member) == type))
13116 {
13117 mark_class_member (member);
13118 if (TREE_CODE (member) == FIELD_DECL)
13119 if (tree repr = DECL_BIT_FIELD_REPRESENTATIVE (member))
13120 /* If we're marking a class template definition, then
13121 this'll contain the width (as set by grokbitfield)
13122 instead of a decl. */
13123 if (DECL_P (repr))
13124 mark_declaration (repr, false);
13125 }
13126
13127 /* Mark the binfo hierarchy. */
13128 for (tree child = TYPE_BINFO (type); child; child = TREE_CHAIN (child))
13129 mark_by_value (child);
13130
13131 if (TYPE_LANG_SPECIFIC (type))
13132 {
13133 for (tree vtable = CLASSTYPE_VTABLES (type);
13134 vtable; vtable = TREE_CHAIN (vtable))
13135 mark_declaration (vtable, true);
13136
13137 if (TYPE_CONTAINS_VPTR_P (type))
13138 /* Mark the thunks, they belong to the class definition,
13139 /not/ the thunked-to function. */
13140 for (tree decls = TYPE_FIELDS (type);
13141 decls; decls = DECL_CHAIN (decls))
13142 if (TREE_CODE (decls) == FUNCTION_DECL)
13143 for (tree thunks = DECL_THUNKS (decls);
13144 thunks; thunks = DECL_CHAIN (thunks))
13145 mark_declaration (thunks, false);
13146 }
13147 }
13148
13149 /* Nop sorting, needed for resorting the member vec. */
13150
13151 static void
13152 nop (void *, void *, void *)
13153 {
13154 }
13155
13156 bool
13157 trees_in::read_class_def (tree defn, tree maybe_template)
13158 {
13159 gcc_assert (DECL_P (defn));
13160 dump () && dump ("Reading class definition %N", defn);
13161 tree type = TREE_TYPE (defn);
13162 tree size = tree_node ();
13163 tree size_unit = tree_node ();
13164 tree vfield = tree_node ();
13165 tree binfo = tree_node ();
13166 vec<tree, va_gc> *vbase_vec = NULL;
13167 vec<tree, va_gc> *member_vec = NULL;
13168 vec<tree, va_gc> *pure_virts = NULL;
13169 vec<tree_pair_s, va_gc> *vcall_indices = NULL;
13170 tree key_method = NULL_TREE;
13171 tree lambda = NULL_TREE;
13172
13173 /* Read the fields. */
13174 vec<tree, va_heap> *fields = vec_chained_decls ();
13175
13176 if (TYPE_LANG_SPECIFIC (type))
13177 {
13178 if (unsigned len = u ())
13179 {
13180 vec_alloc (member_vec, len);
13181 for (unsigned ix = 0; ix != len; ix++)
13182 {
13183 tree m = tree_node ();
13184 if (get_overrun ())
13185 break;
13186 if (TYPE_P (m))
13187 m = TYPE_STUB_DECL (m);
13188 member_vec->quick_push (m);
13189 }
13190 }
13191 lambda = tree_node ();
13192
13193 if (!get_overrun ())
13194 {
13195 unsigned nvbases = u ();
13196 if (nvbases)
13197 {
13198 vec_alloc (vbase_vec, nvbases);
13199 for (tree child = binfo; child; child = TREE_CHAIN (child))
13200 if (BINFO_VIRTUAL_P (child))
13201 vbase_vec->quick_push (child);
13202 }
13203 }
13204
13205 if (!get_overrun ())
13206 {
13207 int has_vptr = i ();
13208 if (has_vptr)
13209 {
13210 pure_virts = tree_vec ();
13211 vcall_indices = tree_pair_vec ();
13212 key_method = tree_node ();
13213 }
13214 }
13215 }
13216
13217 tree maybe_dup = odr_duplicate (maybe_template, TYPE_SIZE (type));
13218 bool installing = maybe_dup && !TYPE_SIZE (type);
13219 if (installing)
13220 {
13221 if (maybe_dup != defn)
13222 {
13223 // FIXME: This is needed on other defns too, almost
13224 // duplicate-decl like? See is_matching_decl too.
13225 /* Copy flags from the duplicate. */
13226 tree type_dup = TREE_TYPE (maybe_dup);
13227
13228 /* Core pieces. */
13229 TYPE_MODE_RAW (type) = TYPE_MODE_RAW (type_dup);
13230 TYPE_ALIGN_RAW (type) = TYPE_ALIGN_RAW (type_dup);
13231 TYPE_WARN_IF_NOT_ALIGN_RAW (type)
13232 = TYPE_WARN_IF_NOT_ALIGN_RAW (type_dup);
13233 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (type_dup);
13234
13235 SET_DECL_MODE (defn, DECL_MODE (maybe_dup));
13236 DECL_SIZE (defn) = DECL_SIZE (maybe_dup);
13237 DECL_SIZE_UNIT (defn) = DECL_SIZE_UNIT (maybe_dup);
13238 DECL_ALIGN_RAW (defn) = DECL_ALIGN_RAW (maybe_dup);
13239 DECL_WARN_IF_NOT_ALIGN_RAW (defn)
13240 = DECL_WARN_IF_NOT_ALIGN_RAW (maybe_dup);
13241 DECL_USER_ALIGN (defn) = DECL_USER_ALIGN (maybe_dup);
13242
13243 TYPE_TYPELESS_STORAGE (type) = TYPE_TYPELESS_STORAGE (type_dup);
13244 TYPE_CXX_ODR_P (type) = TYPE_CXX_ODR_P (type_dup);
13245 TYPE_NO_FORCE_BLK (type) = TYPE_NO_FORCE_BLK (type_dup);
13246 TYPE_TRANSPARENT_AGGR (type) = TYPE_TRANSPARENT_AGGR (type_dup);
13247 TYPE_CONTAINS_PLACEHOLDER_INTERNAL (type)
13248 = TYPE_CONTAINS_PLACEHOLDER_INTERNAL (type_dup);
13249
13250 TYPE_EMPTY_P (type) = TYPE_EMPTY_P (type_dup);
13251 TREE_ADDRESSABLE (type) = TREE_ADDRESSABLE (type_dup);
13252
13253 /* C++ pieces. */
13254 TYPE_POLYMORPHIC_P (type) = TYPE_POLYMORPHIC_P (type_dup);
13255 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (type_dup);
13256
13257 TYPE_HAS_USER_CONSTRUCTOR (type)
13258 = TYPE_HAS_USER_CONSTRUCTOR (type_dup);
13259 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13260 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type_dup);
13261 TYPE_NEEDS_CONSTRUCTING (type)
13262 = TYPE_NEEDS_CONSTRUCTING (type_dup);
13263
13264 if (auto ls = TYPE_LANG_SPECIFIC (type_dup))
13265 {
13266 if (TYPE_LANG_SPECIFIC (type))
13267 {
13268 CLASSTYPE_BEFRIENDING_CLASSES (type_dup)
13269 = CLASSTYPE_BEFRIENDING_CLASSES (type);
13270 if (!ANON_AGGR_TYPE_P (type))
13271 CLASSTYPE_TYPEINFO_VAR (type_dup)
13272 = CLASSTYPE_TYPEINFO_VAR (type);
13273 }
13274 for (tree v = type; v; v = TYPE_NEXT_VARIANT (v))
13275 TYPE_LANG_SPECIFIC (v) = ls;
13276 }
13277 }
13278
13279 TYPE_SIZE (type) = size;
13280 TYPE_SIZE_UNIT (type) = size_unit;
13281
13282 if (fields)
13283 {
13284 tree *chain = &TYPE_FIELDS (type);
13285 unsigned len = fields->length ();
13286 for (unsigned ix = 0; ix != len; ix++)
13287 {
13288 tree decl = (*fields)[ix];
13289
13290 if (!decl)
13291 {
13292 /* An anonymous struct with typedef name. */
13293 tree tdef = (*fields)[ix+1];
13294 decl = TYPE_STUB_DECL (TREE_TYPE (tdef));
13295 gcc_checking_assert (IDENTIFIER_ANON_P (DECL_NAME (decl))
13296 && decl != tdef);
13297 }
13298
13299 gcc_checking_assert (!*chain == !DECL_CLONED_FUNCTION_P (decl));
13300 *chain = decl;
13301 chain = &DECL_CHAIN (decl);
13302
13303 if (TREE_CODE (decl) == FIELD_DECL
13304 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
13305 {
13306 tree anon_type = TYPE_MAIN_VARIANT (TREE_TYPE (decl));
13307 if (DECL_NAME (defn) == as_base_identifier)
13308 /* ANON_AGGR_TYPE_FIELD should already point to the
13309 original FIELD_DECL; don't overwrite it to point
13310 to the as-base FIELD_DECL copy. */
13311 gcc_checking_assert (ANON_AGGR_TYPE_FIELD (anon_type));
13312 else
13313 ANON_AGGR_TYPE_FIELD (anon_type) = decl;
13314 }
13315
13316 if (TREE_CODE (decl) == USING_DECL
13317 && TREE_CODE (USING_DECL_SCOPE (decl)) == RECORD_TYPE)
13318 {
13319 /* Reconstruct DECL_ACCESS. */
13320 tree decls = USING_DECL_DECLS (decl);
13321 tree access = declared_access (decl);
13322
13323 for (ovl_iterator iter (decls); iter; ++iter)
13324 {
13325 tree d = *iter;
13326
13327 retrofit_lang_decl (d);
13328 tree list = DECL_ACCESS (d);
13329
13330 if (!purpose_member (type, list))
13331 DECL_ACCESS (d) = tree_cons (type, access, list);
13332 }
13333 }
13334
13335 if (TREE_CODE (decl) == VAR_DECL
13336 && TREE_CODE (maybe_template) != TEMPLATE_DECL)
13337 note_vague_linkage_variable (decl);
13338 }
13339 }
13340
13341 TYPE_VFIELD (type) = vfield;
13342 TYPE_BINFO (type) = binfo;
13343
13344 if (TYPE_LANG_SPECIFIC (type))
13345 {
13346 CLASSTYPE_LAMBDA_EXPR (type) = lambda;
13347
13348 CLASSTYPE_MEMBER_VEC (type) = member_vec;
13349 CLASSTYPE_PURE_VIRTUALS (type) = pure_virts;
13350 CLASSTYPE_VCALL_INDICES (type) = vcall_indices;
13351
13352 CLASSTYPE_KEY_METHOD (type) = key_method;
13353
13354 CLASSTYPE_VBASECLASSES (type) = vbase_vec;
13355
13356 /* Resort the member vector. */
13357 resort_type_member_vec (member_vec, NULL, nop, NULL);
13358 }
13359 }
13360 else if (maybe_dup)
13361 {
13362 // FIXME:QOI Check matching defn
13363 }
13364
13365 if (TYPE_LANG_SPECIFIC (type))
13366 {
13367 tree primary = tree_node ();
13368 tree as_base = tree_node ();
13369
13370 if (as_base)
13371 as_base = TREE_TYPE (as_base);
13372
13373 /* Read the vtables. */
13374 vec<tree, va_heap> *vtables = vec_chained_decls ();
13375 if (vtables)
13376 {
13377 unsigned len = vtables->length ();
13378 for (unsigned ix = 0; ix != len; ix++)
13379 {
13380 tree vtable = (*vtables)[ix];
13381 read_var_def (vtable, vtable);
13382 }
13383 }
13384
13385 tree friend_classes = tree_list (false);
13386 tree friend_functions = NULL_TREE;
13387 for (tree *chain = &friend_functions;
13388 tree name = tree_node (); chain = &TREE_CHAIN (*chain))
13389 {
13390 tree val = tree_list (false);
13391 *chain = build_tree_list (name, val);
13392 }
13393 tree decl_list = tree_list (true);
13394
13395 if (installing)
13396 {
13397 CLASSTYPE_PRIMARY_BINFO (type) = primary;
13398 CLASSTYPE_AS_BASE (type) = as_base;
13399
13400 if (vtables)
13401 {
13402 if ((!CLASSTYPE_KEY_METHOD (type)
13403 /* Sneaky user may have defined it inline
13404 out-of-class. */
13405 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type)))
13406 /* An imported non-template class attached to a module
13407 doesn't need to have its vtables emitted here. */
13408 && (CLASSTYPE_USE_TEMPLATE (type)
13409 || !DECL_MODULE_ATTACH_P (defn)))
13410 vec_safe_push (keyed_classes, type);
13411 unsigned len = vtables->length ();
13412 tree *chain = &CLASSTYPE_VTABLES (type);
13413 for (unsigned ix = 0; ix != len; ix++)
13414 {
13415 tree vtable = (*vtables)[ix];
13416 gcc_checking_assert (!*chain);
13417 *chain = vtable;
13418 chain = &DECL_CHAIN (vtable);
13419 }
13420 }
13421 CLASSTYPE_FRIEND_CLASSES (type) = friend_classes;
13422 DECL_FRIENDLIST (defn) = friend_functions;
13423 CLASSTYPE_DECL_LIST (type) = decl_list;
13424
13425 for (; friend_classes; friend_classes = TREE_CHAIN (friend_classes))
13426 {
13427 tree f = TREE_VALUE (friend_classes);
13428 if (TREE_CODE (f) == TEMPLATE_DECL)
13429 f = TREE_TYPE (f);
13430
13431 if (CLASS_TYPE_P (f))
13432 {
13433 CLASSTYPE_BEFRIENDING_CLASSES (f)
13434 = tree_cons (NULL_TREE, type,
13435 CLASSTYPE_BEFRIENDING_CLASSES (f));
13436 dump () && dump ("Class %N befriending %C:%N",
13437 type, TREE_CODE (f), f);
13438 }
13439 }
13440
13441 for (; friend_functions;
13442 friend_functions = TREE_CHAIN (friend_functions))
13443 for (tree friend_decls = TREE_VALUE (friend_functions);
13444 friend_decls; friend_decls = TREE_CHAIN (friend_decls))
13445 {
13446 tree f = TREE_VALUE (friend_decls);
13447 if (TREE_CODE (f) == TU_LOCAL_ENTITY)
13448 continue;
13449
13450 DECL_BEFRIENDING_CLASSES (f)
13451 = tree_cons (NULL_TREE, type, DECL_BEFRIENDING_CLASSES (f));
13452 dump () && dump ("Class %N befriending %C:%N",
13453 type, TREE_CODE (f), f);
13454 }
13455 }
13456
13457 if (TYPE_CONTAINS_VPTR_P (type))
13458 /* Read and install the thunks. */
13459 while (tree vfunc = tree_node ())
13460 {
13461 tree thunks = chained_decls ();
13462 if (installing)
13463 SET_DECL_THUNKS (vfunc, thunks);
13464 }
13465
13466 vec_free (vtables);
13467 }
13468
13469 /* Propagate to all variants. */
13470 if (installing)
13471 fixup_type_variants (type);
13472
13473 /* IS_FAKE_BASE_TYPE is inaccurate at this point, because if this is
13474 the fake base, we've not hooked it into the containing class's
13475 data structure yet. Fortunately it has a unique name. */
13476 if (installing
13477 && DECL_NAME (defn) != as_base_identifier
13478 && (!CLASSTYPE_TEMPLATE_INFO (type)
13479 || !uses_template_parms (TI_ARGS (CLASSTYPE_TEMPLATE_INFO (type)))))
13480 /* Emit debug info. It'd be nice to know if the interface TU
13481 already emitted this. */
13482 rest_of_type_compilation (type, !LOCAL_CLASS_P (type));
13483
13484 vec_free (fields);
13485
13486 return !get_overrun ();
13487 }
13488
13489 void
13490 trees_out::write_enum_def (tree decl)
13491 {
13492 tree type = TREE_TYPE (decl);
13493
13494 tree_node (TYPE_VALUES (type));
13495 /* Note that we stream TYPE_MIN/MAX_VALUE directly as part of the
13496 ENUMERAL_TYPE. */
13497 }
13498
13499 void
13500 trees_out::mark_enum_def (tree decl)
13501 {
13502 tree type = TREE_TYPE (decl);
13503
13504 for (tree values = TYPE_VALUES (type); values; values = TREE_CHAIN (values))
13505 {
13506 tree cst = TREE_VALUE (values);
13507 mark_by_value (cst);
13508 /* We must mark the init to avoid circularity in tt_enum_int. */
13509 if (tree init = DECL_INITIAL (cst))
13510 if (TREE_CODE (init) == INTEGER_CST)
13511 mark_by_value (init);
13512 }
13513 }
13514
13515 bool
13516 trees_in::read_enum_def (tree defn, tree maybe_template)
13517 {
13518 tree type = TREE_TYPE (defn);
13519 tree values = tree_node ();
13520
13521 if (get_overrun ())
13522 return false;
13523
13524 tree maybe_dup = odr_duplicate (maybe_template, TYPE_VALUES (type));
13525 bool installing = maybe_dup && !TYPE_VALUES (type);
13526
13527 if (installing)
13528 {
13529 TYPE_VALUES (type) = values;
13530 /* Note that we stream TYPE_MIN/MAX_VALUE directly as part of the
13531 ENUMERAL_TYPE. */
13532
13533 rest_of_type_compilation (type, DECL_NAMESPACE_SCOPE_P (defn));
13534 }
13535 else if (maybe_dup)
13536 {
13537 tree known = TYPE_VALUES (type);
13538 for (; known && values;
13539 known = TREE_CHAIN (known), values = TREE_CHAIN (values))
13540 {
13541 tree known_decl = TREE_VALUE (known);
13542 tree new_decl = TREE_VALUE (values);
13543
13544 if (DECL_NAME (known_decl) != DECL_NAME (new_decl))
13545 break;
13546
13547 new_decl = maybe_duplicate (new_decl);
13548
13549 if (!cp_tree_equal (DECL_INITIAL (known_decl),
13550 DECL_INITIAL (new_decl)))
13551 break;
13552 }
13553
13554 if (known || values)
13555 {
13556 auto_diagnostic_group d;
13557 error_at (DECL_SOURCE_LOCATION (maybe_dup),
13558 "definition of %qD does not match", maybe_dup);
13559 inform (DECL_SOURCE_LOCATION (defn),
13560 "existing definition %qD", defn);
13561
13562 tree known_decl = NULL_TREE, new_decl = NULL_TREE;
13563
13564 if (known)
13565 known_decl = TREE_VALUE (known);
13566 if (values)
13567 new_decl = maybe_duplicate (TREE_VALUE (values));
13568
13569 if (known_decl && new_decl)
13570 {
13571 inform (DECL_SOURCE_LOCATION (new_decl),
13572 "enumerator %qD does not match ...", new_decl);
13573 inform (DECL_SOURCE_LOCATION (known_decl),
13574 "... this enumerator %qD", known_decl);
13575 }
13576 else if (known_decl || new_decl)
13577 {
13578 tree extra = known_decl ? known_decl : new_decl;
13579 inform (DECL_SOURCE_LOCATION (extra),
13580 "additional enumerators beginning with %qD", extra);
13581 }
13582 else
13583 inform (DECL_SOURCE_LOCATION (maybe_dup),
13584 "enumeration range differs");
13585
13586 /* Mark it bad. */
13587 unmatched_duplicate (maybe_template);
13588 }
13589 }
13590
13591 return true;
13592 }
13593
13594 /* Write out the body of DECL. See above circularity note. */
13595
13596 void
13597 trees_out::write_definition (tree decl, bool refs_tu_local)
13598 {
13599 auto ovr = make_temp_override (writing_local_entities,
13600 writing_local_entities || refs_tu_local);
13601
13602 if (streaming_p ())
13603 {
13604 assert_definition (decl);
13605 dump ()
13606 && dump ("Writing definition %C:%N", TREE_CODE (decl), decl);
13607 }
13608 else
13609 dump (dumper::DEPEND)
13610 && dump ("Depending definition %C:%N", TREE_CODE (decl), decl);
13611
13612 again:
13613 switch (TREE_CODE (decl))
13614 {
13615 default:
13616 gcc_unreachable ();
13617
13618 case TEMPLATE_DECL:
13619 decl = DECL_TEMPLATE_RESULT (decl);
13620 goto again;
13621
13622 case FUNCTION_DECL:
13623 write_function_def (decl);
13624 break;
13625
13626 case TYPE_DECL:
13627 {
13628 tree type = TREE_TYPE (decl);
13629 gcc_assert (TYPE_MAIN_VARIANT (type) == type
13630 && TYPE_NAME (type) == decl);
13631 if (TREE_CODE (type) == ENUMERAL_TYPE)
13632 write_enum_def (decl);
13633 else
13634 write_class_def (decl);
13635 }
13636 break;
13637
13638 case VAR_DECL:
13639 case CONCEPT_DECL:
13640 write_var_def (decl);
13641 break;
13642 }
13643 }
13644
13645 /* Mark a declaration for by-value walking. If DO_DEFN is true, mark
13646 its body too. */
13647
13648 void
13649 trees_out::mark_declaration (tree decl, bool do_defn)
13650 {
13651 mark_by_value (decl);
13652
13653 if (TREE_CODE (decl) == TEMPLATE_DECL)
13654 decl = DECL_TEMPLATE_RESULT (decl);
13655
13656 if (!do_defn)
13657 return;
13658
13659 switch (TREE_CODE (decl))
13660 {
13661 default:
13662 gcc_unreachable ();
13663
13664 case FUNCTION_DECL:
13665 mark_function_def (decl);
13666 break;
13667
13668 case TYPE_DECL:
13669 {
13670 tree type = TREE_TYPE (decl);
13671 gcc_assert (TYPE_MAIN_VARIANT (type) == type
13672 && TYPE_NAME (type) == decl);
13673 if (TREE_CODE (type) == ENUMERAL_TYPE)
13674 mark_enum_def (decl);
13675 else
13676 mark_class_def (decl);
13677 }
13678 break;
13679
13680 case VAR_DECL:
13681 case CONCEPT_DECL:
13682 mark_var_def (decl);
13683 break;
13684 }
13685 }
13686
13687 /* Read in the body of DECL. See above circularity note. */
13688
13689 bool
13690 trees_in::read_definition (tree decl)
13691 {
13692 dump () && dump ("Reading definition %C %N", TREE_CODE (decl), decl);
13693
13694 tree maybe_template = decl;
13695
13696 again:
13697 switch (TREE_CODE (decl))
13698 {
13699 default:
13700 break;
13701
13702 case TEMPLATE_DECL:
13703 decl = DECL_TEMPLATE_RESULT (decl);
13704 goto again;
13705
13706 case FUNCTION_DECL:
13707 return read_function_def (decl, maybe_template);
13708
13709 case TYPE_DECL:
13710 {
13711 tree type = TREE_TYPE (decl);
13712 gcc_assert (TYPE_MAIN_VARIANT (type) == type
13713 && TYPE_NAME (type) == decl);
13714 if (TREE_CODE (type) == ENUMERAL_TYPE)
13715 return read_enum_def (decl, maybe_template);
13716 else
13717 return read_class_def (decl, maybe_template);
13718 }
13719 break;
13720
13721 case VAR_DECL:
13722 case CONCEPT_DECL:
13723 return read_var_def (decl, maybe_template);
13724 }
13725
13726 return false;
13727 }
13728
13729 /* Lookup an maybe insert a slot for depset for KEY. */
13730
13731 depset **
13732 depset::hash::entity_slot (tree entity, bool insert)
13733 {
13734 traits::compare_type key (entity, NULL);
13735 depset **slot = find_slot_with_hash (key, traits::hash (key),
13736 insert ? INSERT : NO_INSERT);
13737
13738 return slot;
13739 }
13740
13741 depset **
13742 depset::hash::binding_slot (tree ctx, tree name, bool insert)
13743 {
13744 traits::compare_type key (ctx, name);
13745 depset **slot = find_slot_with_hash (key, traits::hash (key),
13746 insert ? INSERT : NO_INSERT);
13747
13748 return slot;
13749 }
13750
13751 depset *
13752 depset::hash::find_dependency (tree decl)
13753 {
13754 depset **slot = entity_slot (decl, false);
13755
13756 return slot ? *slot : NULL;
13757 }
13758
13759 depset *
13760 depset::hash::find_binding (tree ctx, tree name)
13761 {
13762 depset **slot = binding_slot (ctx, name, false);
13763
13764 return slot ? *slot : NULL;
13765 }
13766
13767 /* Returns true if DECL is a TU-local entity, as defined by [basic.link].
13768 If EXPLAIN is true, emit an informative note about why DECL is TU-local. */
13769
13770 bool
13771 depset::hash::is_tu_local_entity (tree decl, bool explain/*=false*/)
13772 {
13773 gcc_checking_assert (DECL_P (decl));
13774 location_t loc = DECL_SOURCE_LOCATION (decl);
13775 tree type = TREE_TYPE (decl);
13776
13777 /* Only types, functions, variables, and template (specialisations)
13778 can be TU-local. */
13779 if (TREE_CODE (decl) != TYPE_DECL
13780 && TREE_CODE (decl) != FUNCTION_DECL
13781 && TREE_CODE (decl) != VAR_DECL
13782 && TREE_CODE (decl) != TEMPLATE_DECL)
13783 return false;
13784
13785 /* An explicit type alias is not an entity; we don't want to stream
13786 such aliases if they refer to TU-local entities, so propagate this
13787 from the original type. The built-in declarations of 'int' and such
13788 are never TU-local. */
13789 if (TREE_CODE (decl) == TYPE_DECL
13790 && !DECL_SELF_REFERENCE_P (decl)
13791 && !DECL_IMPLICIT_TYPEDEF_P (decl))
13792 {
13793 tree orig = DECL_ORIGINAL_TYPE (decl);
13794 if (orig && TYPE_NAME (orig))
13795 {
13796 if (explain)
13797 inform (loc, "%qD is an alias of TU-local type %qT", decl, orig);
13798 return is_tu_local_entity (TYPE_NAME (orig), explain);
13799 }
13800 else
13801 return false;
13802 }
13803
13804 /* Check specializations first for slightly better explanations. */
13805 int use_tpl = -1;
13806 tree ti = node_template_info (decl, use_tpl);
13807 if (use_tpl > 0 && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL)
13808 {
13809 /* A specialization of a TU-local template. */
13810 tree tmpl = TI_TEMPLATE (ti);
13811 if (is_tu_local_entity (tmpl))
13812 {
13813 if (explain)
13814 {
13815 inform (loc, "%qD is a specialization of TU-local template %qD",
13816 decl, tmpl);
13817 is_tu_local_entity (tmpl, /*explain=*/true);
13818 }
13819 return true;
13820 }
13821
13822 /* A specialization of a template with any TU-local template argument. */
13823 if (has_tu_local_tmpl_arg (decl, TI_ARGS (ti), explain))
13824 return true;
13825
13826 /* FIXME A specialization of a template whose (possibly instantiated)
13827 declaration is an exposure. This should always be covered by the
13828 above cases?? */
13829 }
13830
13831 /* A type, function, variable, or template with internal linkage. */
13832 linkage_kind kind = decl_linkage (decl);
13833 if (kind == lk_internal
13834 /* But although weakrefs are marked static, don't consider them
13835 to be TU-local. */
13836 && !lookup_attribute ("weakref", DECL_ATTRIBUTES (decl)))
13837 {
13838 if (explain)
13839 inform (loc, "%qD declared with internal linkage", decl);
13840 return true;
13841 }
13842
13843 /* Does not have a name with linkage and is declared, or introduced by a
13844 lambda-expression, within the definition of a TU-local entity. */
13845 if (kind == lk_none)
13846 {
13847 tree ctx = CP_DECL_CONTEXT (decl);
13848 if (LAMBDA_TYPE_P (type))
13849 if (tree extra = LAMBDA_TYPE_EXTRA_SCOPE (type))
13850 ctx = extra;
13851
13852 if (TREE_CODE (ctx) == NAMESPACE_DECL)
13853 {
13854 if (!TREE_PUBLIC (ctx))
13855 {
13856 if (explain)
13857 inform (loc, "%qD has no linkage and is declared in an "
13858 "anonymous namespace", decl);
13859 return true;
13860 }
13861 }
13862 else if (TYPE_P (ctx))
13863 {
13864 tree ctx_decl = TYPE_MAIN_DECL (ctx);
13865 if (is_tu_local_entity (ctx_decl))
13866 {
13867 if (explain)
13868 {
13869 inform (loc, "%qD has no linkage and is declared within "
13870 "TU-local entity %qT", decl, ctx);
13871 is_tu_local_entity (ctx_decl, /*explain=*/true);
13872 }
13873 return true;
13874 }
13875 }
13876 else if (is_tu_local_entity (ctx))
13877 {
13878 if (explain)
13879 {
13880 inform (loc, "%qD has no linkage and is declared within "
13881 "TU-local entity %qD", decl, ctx);
13882 is_tu_local_entity (ctx, /*explain=*/true);
13883 }
13884 return true;
13885 }
13886 }
13887
13888 /* A type with no name that is defined outside a class-specifier, function
13889 body, or initializer; or is introduced by a defining-type-specifier that
13890 is used to declare only TU-local entities.
13891
13892 We consider types with names for linkage purposes as having names, since
13893 these aren't really TU-local. */
13894 tree inner = STRIP_TEMPLATE (decl);
13895 if (inner
13896 && TREE_CODE (inner) == TYPE_DECL
13897 && TYPE_ANON_P (type)
13898 && !DECL_SELF_REFERENCE_P (inner)
13899 /* An enum with an enumerator name for linkage. */
13900 && !(UNSCOPED_ENUM_P (type) && TYPE_VALUES (type)))
13901 {
13902 tree main_decl = TYPE_MAIN_DECL (type);
13903 if (LAMBDA_TYPE_P (type))
13904 {
13905 /* A lambda expression is, in practice, TU-local iff it has no
13906 mangling scope. This currently doesn't line up exactly with
13907 the standard's definition due to some ABI issues, but it's
13908 pretty close, and avoids other issues down the line. */
13909 if (!LAMBDA_TYPE_EXTRA_SCOPE (type))
13910 {
13911 if (explain)
13912 inform (loc, "%qT has no name and cannot be differentiated "
13913 "from similar lambdas in other TUs", type);
13914 return true;
13915 }
13916 }
13917 else if (!DECL_CLASS_SCOPE_P (main_decl)
13918 && !decl_function_context (main_decl))
13919 {
13920 if (explain)
13921 inform (loc, "%qT has no name and is not defined within a class, "
13922 "function, or initializer", type);
13923 return true;
13924 }
13925
13926 // FIXME introduced by a defining-type-specifier only declaring TU-local
13927 // entities; does this refer to e.g. 'static struct {} a;"? I can't
13928 // think of any cases where this isn't covered by earlier cases. */
13929 }
13930
13931 return false;
13932 }
13933
13934 /* Helper for is_tu_local_entity. Returns true if one of the ARGS of
13935 DECL is TU-local. Emits an explanation if EXPLAIN is true. */
13936
13937 bool
13938 depset::hash::has_tu_local_tmpl_arg (tree decl, tree args, bool explain)
13939 {
13940 if (!args || TREE_CODE (args) != TREE_VEC)
13941 return false;
13942
13943 for (tree a : tree_vec_range (args))
13944 {
13945 if (TREE_CODE (a) == TREE_VEC)
13946 {
13947 if (has_tu_local_tmpl_arg (decl, a, explain))
13948 return true;
13949 }
13950 else if (!WILDCARD_TYPE_P (a))
13951 {
13952 if (DECL_P (a) && is_tu_local_entity (a))
13953 {
13954 if (explain)
13955 {
13956 inform (DECL_SOURCE_LOCATION (decl),
13957 "%qD has TU-local template argument %qD",
13958 decl, a);
13959 is_tu_local_entity (a, /*explain=*/true);
13960 }
13961 return true;
13962 }
13963
13964 if (TYPE_P (a) && TYPE_NAME (a) && is_tu_local_entity (TYPE_NAME (a)))
13965 {
13966 if (explain)
13967 {
13968 inform (DECL_SOURCE_LOCATION (decl),
13969 "%qD has TU-local template argument %qT",
13970 decl, a);
13971 is_tu_local_entity (TYPE_NAME (a), /*explain=*/true);
13972 }
13973 return true;
13974 }
13975
13976 if (EXPR_P (a) && is_tu_local_value (decl, a, explain))
13977 return true;
13978 }
13979 }
13980
13981 return false;
13982 }
13983
13984 /* Returns true if EXPR (part of the initializer for DECL) is a TU-local value
13985 or object. Emits an explanation if EXPLAIN is true. */
13986
13987 bool
13988 depset::hash::is_tu_local_value (tree decl, tree expr, bool explain)
13989 {
13990 if (!expr)
13991 return false;
13992
13993 tree e = expr;
13994 STRIP_ANY_LOCATION_WRAPPER (e);
13995 STRIP_NOPS (e);
13996 if (TREE_CODE (e) == TARGET_EXPR)
13997 e = TARGET_EXPR_INITIAL (e);
13998 if (!e)
13999 return false;
14000
14001 /* It is, or is a pointer to, a TU-local function or the object associated
14002 with a TU-local variable. */
14003 tree object = NULL_TREE;
14004 if (TREE_CODE (e) == ADDR_EXPR)
14005 object = TREE_OPERAND (e, 0);
14006 else if (TREE_CODE (e) == PTRMEM_CST)
14007 object = PTRMEM_CST_MEMBER (e);
14008 else if (VAR_OR_FUNCTION_DECL_P (e))
14009 object = e;
14010
14011 if (object
14012 && VAR_OR_FUNCTION_DECL_P (object)
14013 && is_tu_local_entity (object))
14014 {
14015 if (explain)
14016 {
14017 /* We've lost a lot of location information by the time we get here,
14018 so let's just do our best effort. */
14019 auto loc = cp_expr_loc_or_loc (expr, DECL_SOURCE_LOCATION (decl));
14020 if (VAR_P (object))
14021 inform (loc, "%qD refers to TU-local object %qD", decl, object);
14022 else
14023 inform (loc, "%qD refers to TU-local function %qD", decl, object);
14024 is_tu_local_entity (object, true);
14025 }
14026 return true;
14027 }
14028
14029 /* It is an object of class or array type and any of its subobjects or
14030 any of the objects or functions to which its non-static data members
14031 of reference type refer is TU-local and is usable in constant
14032 expressions. */
14033 if (TREE_CODE (e) == CONSTRUCTOR && AGGREGATE_TYPE_P (TREE_TYPE (e)))
14034 for (auto &f : CONSTRUCTOR_ELTS (e))
14035 if (is_tu_local_value (decl, f.value, explain))
14036 return true;
14037
14038 return false;
14039 }
14040
14041 /* DECL is a newly discovered dependency. Create the depset, if it
14042 doesn't already exist. Add it to the worklist if so.
14043
14044 DECL will be an OVL_USING_P OVERLOAD, if it's from a binding that's
14045 a using decl.
14046
14047 We do not have to worry about adding the same dependency more than
14048 once. First it's harmless, but secondly the TREE_VISITED marking
14049 prevents us wanting to do it anyway. */
14050
14051 depset *
14052 depset::hash::make_dependency (tree decl, entity_kind ek)
14053 {
14054 /* Make sure we're being told consistent information. */
14055 gcc_checking_assert ((ek == EK_NAMESPACE)
14056 == (TREE_CODE (decl) == NAMESPACE_DECL
14057 && !DECL_NAMESPACE_ALIAS (decl)));
14058 gcc_checking_assert (ek != EK_BINDING && ek != EK_REDIRECT);
14059 gcc_checking_assert (TREE_CODE (decl) != FIELD_DECL
14060 && (TREE_CODE (decl) != USING_DECL
14061 || TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL));
14062 gcc_checking_assert (!is_key_order ());
14063 if (ek == EK_USING)
14064 gcc_checking_assert (TREE_CODE (decl) == OVERLOAD);
14065
14066 if (TREE_CODE (decl) == TEMPLATE_DECL)
14067 /* The template should have copied these from its result decl. */
14068 gcc_checking_assert (DECL_MODULE_EXPORT_P (decl)
14069 == DECL_MODULE_EXPORT_P (DECL_TEMPLATE_RESULT (decl)));
14070
14071 depset **slot = entity_slot (decl, true);
14072 depset *dep = *slot;
14073 bool for_binding = ek == EK_FOR_BINDING;
14074
14075 if (!dep)
14076 {
14077 if ((DECL_IMPLICIT_TYPEDEF_P (decl)
14078 /* ... not an enum, for instance. */
14079 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl))
14080 && TYPE_LANG_SPECIFIC (TREE_TYPE (decl))
14081 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
14082 || (VAR_P (decl)
14083 && DECL_LANG_SPECIFIC (decl)
14084 && DECL_USE_TEMPLATE (decl) == 2))
14085 {
14086 /* A partial or explicit specialization. Partial
14087 specializations might not be in the hash table, because
14088 there can be multiple differently-constrained variants.
14089
14090 template<typename T> class silly;
14091 template<typename T> requires true class silly {};
14092
14093 We need to find them, insert their TEMPLATE_DECL in the
14094 dep_hash, and then convert the dep we just found into a
14095 redirect. */
14096
14097 tree ti = get_template_info (decl);
14098 tree tmpl = TI_TEMPLATE (ti);
14099 tree partial = NULL_TREE;
14100 for (tree spec = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
14101 spec; spec = TREE_CHAIN (spec))
14102 if (DECL_TEMPLATE_RESULT (TREE_VALUE (spec)) == decl)
14103 {
14104 partial = TREE_VALUE (spec);
14105 break;
14106 }
14107
14108 if (partial)
14109 {
14110 /* Eagerly create an empty redirect. The following
14111 make_dependency call could cause hash reallocation,
14112 and invalidate slot's value. */
14113 depset *redirect = make_entity (decl, EK_REDIRECT);
14114
14115 /* Redirects are never reached -- always snap to their target. */
14116 redirect->set_flag_bit<DB_UNREACHED_BIT> ();
14117
14118 *slot = redirect;
14119
14120 depset *tmpl_dep = make_dependency (partial, EK_PARTIAL);
14121 gcc_checking_assert (tmpl_dep->get_entity_kind () == EK_PARTIAL);
14122
14123 redirect->deps.safe_push (tmpl_dep);
14124
14125 return redirect;
14126 }
14127 }
14128
14129 bool has_def = ek != EK_USING && has_definition (decl);
14130 if (ek > EK_BINDING)
14131 ek = EK_DECL;
14132
14133 /* The only OVERLOADS we should see are USING decls from
14134 bindings. */
14135 *slot = dep = make_entity (decl, ek, has_def);
14136
14137 if (CHECKING_P && TREE_CODE (decl) == TEMPLATE_DECL)
14138 /* The template_result should otherwise not be in the
14139 table, or be an empty redirect (created above). */
14140 if (auto *eslot = entity_slot (DECL_TEMPLATE_RESULT (decl), false))
14141 gcc_checking_assert ((*eslot)->get_entity_kind () == EK_REDIRECT
14142 && !(*eslot)->deps.length ());
14143
14144 if (ek != EK_USING)
14145 {
14146 tree not_tmpl = STRIP_TEMPLATE (decl);
14147 bool imported_from_module_p = false;
14148
14149 if (DECL_LANG_SPECIFIC (not_tmpl)
14150 && DECL_MODULE_IMPORT_P (not_tmpl))
14151 {
14152 /* Store the module number and index in cluster/section,
14153 so we don't have to look them up again. */
14154 unsigned index = import_entity_index (decl);
14155 module_state *from = import_entity_module (index);
14156 /* Remap will be zero for imports from partitions, which
14157 we want to treat as-if declared in this TU. */
14158 if (from->remap)
14159 {
14160 dep->cluster = index - from->entity_lwm;
14161 dep->section = from->remap;
14162 dep->set_flag_bit<DB_IMPORTED_BIT> ();
14163
14164 if (!from->is_header ())
14165 imported_from_module_p = true;
14166 }
14167 }
14168
14169 /* Check for TU-local entities. This is unnecessary in header
14170 units because we can export internal-linkage decls, and
14171 no declarations are exposures. Similarly, if the decl was
14172 imported from a non-header module we know it cannot have
14173 been TU-local. */
14174 if (!header_module_p () && !imported_from_module_p)
14175 {
14176 if (is_tu_local_entity (decl))
14177 dep->set_flag_bit<DB_TU_LOCAL_BIT> ();
14178
14179 if (VAR_P (decl)
14180 && decl_maybe_constant_var_p (decl)
14181 && is_tu_local_value (decl, DECL_INITIAL (decl)))
14182 {
14183 /* A potentially-constant variable initialized to a TU-local
14184 value is not usable in constant expressions within other
14185 translation units. We can achieve this by simply not
14186 streaming the definition in such cases. */
14187 dep->clear_flag_bit<DB_DEFN_BIT> ();
14188
14189 if (DECL_DECLARED_CONSTEXPR_P (decl)
14190 || DECL_INLINE_VAR_P (decl))
14191 /* A constexpr variable initialized to a TU-local value,
14192 or an inline value (PR c++/119996), is an exposure. */
14193 dep->set_flag_bit<DB_EXPOSURE_BIT> ();
14194 }
14195 }
14196
14197 /* A namespace-scope type may be declared in one module unit
14198 and defined in another; make sure that we're found when
14199 completing the class. */
14200 if (ek == EK_DECL
14201 && !dep->is_import ()
14202 && dep->has_defn ()
14203 && DECL_NAMESPACE_SCOPE_P (not_tmpl)
14204 && DECL_IMPLICIT_TYPEDEF_P (not_tmpl)
14205 /* Anonymous types can't be forward-declared. */
14206 && !IDENTIFIER_ANON_P (DECL_NAME (not_tmpl)))
14207 dep->set_flag_bit<DB_IS_PENDING_BIT> ();
14208 }
14209
14210 if (!dep->is_import ())
14211 worklist.safe_push (dep);
14212 }
14213
14214 dump (dumper::DEPEND)
14215 && dump ("%s on %s %C:%N found",
14216 ek == EK_REDIRECT ? "Redirect"
14217 : for_binding ? "Binding" : "Dependency",
14218 dep->entity_kind_name (), TREE_CODE (decl), decl);
14219
14220 return dep;
14221 }
14222
14223 /* Whether REF is an exposure of a member type of SOURCE.
14224
14225 This comes up with exposures of class-scope lambdas, that we currently
14226 treat as TU-local due to ABI reasons. In such a case the type of the
14227 lambda will be exposed in two places, first by the class type it is in
14228 the TYPE_FIELDS list of, and second by the actual member declaring that
14229 lambda. We only want the second case to warn. */
14230
14231 static bool
14232 is_exposure_of_member_type (depset *source, depset *ref)
14233 {
14234 gcc_checking_assert (source->refs_tu_local () && ref->is_tu_local ());
14235 tree source_entity = STRIP_TEMPLATE (source->get_entity ());
14236 tree ref_entity = STRIP_TEMPLATE (ref->get_entity ());
14237
14238 if (source_entity
14239 && ref_entity
14240 && DECL_IMPLICIT_TYPEDEF_P (source_entity)
14241 && DECL_IMPLICIT_TYPEDEF_P (ref_entity)
14242 && DECL_CLASS_SCOPE_P (ref_entity)
14243 && DECL_CONTEXT (ref_entity) == TREE_TYPE (source_entity))
14244 {
14245 gcc_checking_assert (LAMBDA_TYPE_P (TREE_TYPE (ref_entity)));
14246 return true;
14247 }
14248 else
14249 return false;
14250 }
14251
14252 /* DEP is a newly discovered dependency. Append it to current's
14253 depset. */
14254
14255 void
14256 depset::hash::add_dependency (depset *dep)
14257 {
14258 gcc_checking_assert (current && !is_key_order ());
14259 current->deps.safe_push (dep);
14260
14261 if (dep->is_tu_local ())
14262 {
14263 current->set_flag_bit<DB_REFS_TU_LOCAL_BIT> ();
14264 if (!ignore_tu_local && !is_exposure_of_member_type (current, dep))
14265 current->set_flag_bit<DB_EXPOSURE_BIT> ();
14266 }
14267
14268 if (current->get_entity_kind () == EK_USING
14269 && DECL_IMPLICIT_TYPEDEF_P (dep->get_entity ())
14270 && TREE_CODE (TREE_TYPE (dep->get_entity ())) == ENUMERAL_TYPE)
14271 {
14272 /* CURRENT is an unwrapped using-decl and DECL is an enum's
14273 implicit typedef. Is CURRENT a member of the enum? */
14274 tree c_decl = OVL_FUNCTION (current->get_entity ());
14275
14276 if (TREE_CODE (c_decl) == CONST_DECL
14277 && (current->deps[0]->get_entity ()
14278 == CP_DECL_CONTEXT (dep->get_entity ())))
14279 /* Make DECL depend on CURRENT. */
14280 dep->deps.safe_push (current);
14281 }
14282
14283 /* If two dependencies recursively depend on each other existing within
14284 their own merge keys, we must ensure that the first dep we saw while
14285 walking is written first in this cluster. See sort_cluster for more
14286 details. */
14287 if (writing_merge_key)
14288 {
14289 if (!dep->is_maybe_recursive () && !current->is_maybe_recursive ())
14290 current->set_flag_bit<DB_ENTRY_BIT> ();
14291 dep->set_flag_bit<DB_MAYBE_RECURSIVE_BIT> ();
14292 current->set_flag_bit<DB_MAYBE_RECURSIVE_BIT> ();
14293 }
14294
14295 if (dep->is_unreached ())
14296 {
14297 /* The dependency is reachable now. */
14298 reached_unreached = true;
14299 dep->clear_flag_bit<DB_UNREACHED_BIT> ();
14300 dump (dumper::DEPEND)
14301 && dump ("Reaching unreached %s %C:%N", dep->entity_kind_name (),
14302 TREE_CODE (dep->get_entity ()), dep->get_entity ());
14303 }
14304 }
14305
14306 depset *
14307 depset::hash::add_dependency (tree decl, entity_kind ek)
14308 {
14309 depset *dep;
14310
14311 if (is_key_order ())
14312 {
14313 dep = find_dependency (decl);
14314 if (dep)
14315 {
14316 current->deps.safe_push (dep);
14317 dump (dumper::MERGE)
14318 && dump ("Key dependency on %s %C:%N found",
14319 dep->entity_kind_name (), TREE_CODE (decl), decl);
14320 }
14321 else
14322 {
14323 /* It's not a mergeable decl, look for it in the original
14324 table. */
14325 dep = chain->find_dependency (decl);
14326 gcc_checking_assert (dep);
14327 }
14328 }
14329 else
14330 {
14331 dep = make_dependency (decl, ek);
14332 if (dep->get_entity_kind () != EK_REDIRECT)
14333 add_dependency (dep);
14334 }
14335
14336 return dep;
14337 }
14338
14339 void
14340 depset::hash::add_namespace_context (depset *dep, tree ns)
14341 {
14342 depset *ns_dep = make_dependency (ns, depset::EK_NAMESPACE);
14343 dep->deps.safe_push (ns_dep);
14344
14345 /* Mark it as special if imported so we don't walk connect when
14346 SCCing. */
14347 if (!dep->is_binding () && ns_dep->is_import ())
14348 dep->set_special ();
14349 }
14350
14351 struct add_binding_data
14352 {
14353 tree ns;
14354 bitmap partitions;
14355 depset *binding;
14356 depset::hash *hash;
14357 bool met_namespace;
14358 };
14359
14360 /* Return true if we are, or contain something that is exported. */
14361
14362 bool
14363 depset::hash::add_binding_entity (tree decl, WMB_Flags flags, void *data_)
14364 {
14365 auto data = static_cast <add_binding_data *> (data_);
14366 decl = strip_using_decl (decl);
14367
14368 if (!(TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl)))
14369 {
14370 tree inner = decl;
14371
14372 if (TREE_CODE (inner) == CONST_DECL
14373 && TREE_CODE (DECL_CONTEXT (inner)) == ENUMERAL_TYPE
14374 /* A using-decl could make a CONST_DECL purview for a non-purview
14375 enumeration. */
14376 && (!DECL_LANG_SPECIFIC (inner) || !DECL_MODULE_PURVIEW_P (inner)))
14377 inner = TYPE_NAME (DECL_CONTEXT (inner));
14378 else if (TREE_CODE (inner) == TEMPLATE_DECL)
14379 inner = DECL_TEMPLATE_RESULT (inner);
14380
14381 if ((!DECL_LANG_SPECIFIC (inner) || !DECL_MODULE_PURVIEW_P (inner))
14382 && !((flags & WMB_Using) && (flags & WMB_Purview)))
14383 /* Ignore entities not within the module purview. */
14384 return false;
14385
14386 if (!header_module_p () && data->hash->is_tu_local_entity (decl))
14387 /* Ignore TU-local entitites. */
14388 return false;
14389
14390 if ((TREE_CODE (decl) == VAR_DECL
14391 || TREE_CODE (decl) == TYPE_DECL)
14392 && DECL_TINFO_P (decl))
14393 /* Ignore TINFO things. */
14394 return false;
14395
14396 if (TREE_CODE (decl) == VAR_DECL && DECL_NTTP_OBJECT_P (decl))
14397 /* Ignore NTTP objects. */
14398 return false;
14399
14400 if (deduction_guide_p (decl))
14401 {
14402 /* Ignore deduction guides, bindings for them will be created within
14403 find_dependencies for their class template. But still build a dep
14404 for them so that we don't discard them. */
14405 data->hash->make_dependency (decl, EK_FOR_BINDING);
14406 return false;
14407 }
14408
14409 if (!(flags & WMB_Using) && CP_DECL_CONTEXT (decl) != data->ns)
14410 {
14411 /* An unscoped enum constant implicitly brought into the containing
14412 namespace. We treat this like a using-decl. */
14413 gcc_checking_assert (TREE_CODE (decl) == CONST_DECL);
14414
14415 flags = WMB_Flags (flags | WMB_Using);
14416 if (DECL_MODULE_EXPORT_P (TYPE_NAME (TREE_TYPE (decl)))
14417 /* A using-decl can make an enum constant exported for a
14418 non-exported enumeration. */
14419 || (DECL_LANG_SPECIFIC (decl) && DECL_MODULE_EXPORT_P (decl)))
14420 flags = WMB_Flags (flags | WMB_Export);
14421 }
14422
14423 if (!data->binding)
14424 /* No binding to check. */;
14425 else if (flags & WMB_Using)
14426 {
14427 /* Look in the binding to see if we already have this
14428 using. */
14429 for (unsigned ix = data->binding->deps.length (); --ix;)
14430 {
14431 depset *d = data->binding->deps[ix];
14432 if (d->get_entity_kind () == EK_USING
14433 && OVL_FUNCTION (d->get_entity ()) == decl)
14434 {
14435 if (!(flags & WMB_Hidden))
14436 d->clear_hidden_binding ();
14437 OVL_PURVIEW_P (d->get_entity ()) = true;
14438 if (flags & WMB_Export)
14439 OVL_EXPORT_P (d->get_entity ()) = true;
14440 return bool (flags & WMB_Export);
14441 }
14442 }
14443 }
14444 else if (flags & WMB_Dups)
14445 {
14446 /* Look in the binding to see if we already have this decl. */
14447 for (unsigned ix = data->binding->deps.length (); --ix;)
14448 {
14449 depset *d = data->binding->deps[ix];
14450 if (d->get_entity () == decl)
14451 {
14452 if (!(flags & WMB_Hidden))
14453 d->clear_hidden_binding ();
14454 return false;
14455 }
14456 }
14457 }
14458
14459 /* We're adding something. */
14460 if (!data->binding)
14461 {
14462 data->binding = make_binding (data->ns, DECL_NAME (decl));
14463 data->hash->add_namespace_context (data->binding, data->ns);
14464
14465 depset **slot = data->hash->binding_slot (data->ns,
14466 DECL_NAME (decl), true);
14467 gcc_checking_assert (!*slot);
14468 *slot = data->binding;
14469 }
14470
14471 /* Make sure nobody left a tree visited lying about. */
14472 gcc_checking_assert (!TREE_VISITED (decl));
14473
14474 if (flags & WMB_Using)
14475 {
14476 decl = ovl_make (decl, NULL_TREE);
14477 OVL_USING_P (decl) = true;
14478 OVL_PURVIEW_P (decl) = true;
14479 if (flags & WMB_Export)
14480 OVL_EXPORT_P (decl) = true;
14481 }
14482
14483 depset *dep = data->hash->make_dependency
14484 (decl, flags & WMB_Using ? EK_USING : EK_FOR_BINDING);
14485 if (flags & WMB_Hidden)
14486 dep->set_hidden_binding ();
14487 data->binding->deps.safe_push (dep);
14488 /* Binding and contents are mutually dependent. */
14489 dep->deps.safe_push (data->binding);
14490
14491 return (flags & WMB_Using
14492 ? flags & WMB_Export : DECL_MODULE_EXPORT_P (decl));
14493 }
14494 else if (!data->met_namespace)
14495 {
14496 /* Namespace, walk exactly once. */
14497 data->met_namespace = true;
14498 if (data->hash->add_namespace_entities (decl, data->partitions))
14499 {
14500 /* It contains an exported thing, so it is exported. */
14501 gcc_checking_assert (DECL_MODULE_PURVIEW_P (decl));
14502 gcc_checking_assert (TREE_PUBLIC (decl) || header_module_p ());
14503 DECL_MODULE_EXPORT_P (decl) = true;
14504 }
14505
14506 if (DECL_MODULE_PURVIEW_P (decl))
14507 {
14508 data->hash->make_dependency (decl, depset::EK_NAMESPACE);
14509
14510 return DECL_MODULE_EXPORT_P (decl);
14511 }
14512 }
14513
14514 return false;
14515 }
14516
14517 /* Recursively find all the namespace bindings of NS. Add a depset
14518 for every binding that contains an export or module-linkage entity.
14519 Add a defining depset for every such decl that we need to write a
14520 definition. Such defining depsets depend on the binding depset.
14521 Returns true if we contain something exported. */
14522
14523 bool
14524 depset::hash::add_namespace_entities (tree ns, bitmap partitions)
14525 {
14526 dump () && dump ("Looking for writables in %N", ns);
14527 dump.indent ();
14528
14529 unsigned count = 0;
14530 add_binding_data data;
14531 data.ns = ns;
14532 data.partitions = partitions;
14533 data.hash = this;
14534
14535 hash_table<named_decl_hash>::iterator end
14536 (DECL_NAMESPACE_BINDINGS (ns)->end ());
14537 for (hash_table<named_decl_hash>::iterator iter
14538 (DECL_NAMESPACE_BINDINGS (ns)->begin ()); iter != end; ++iter)
14539 {
14540 data.binding = nullptr;
14541 data.met_namespace = false;
14542 if (walk_module_binding (*iter, partitions, add_binding_entity, &data))
14543 count++;
14544 }
14545
14546 if (count)
14547 dump () && dump ("Found %u entries", count);
14548 dump.outdent ();
14549
14550 return count != 0;
14551 }
14552
14553 void
14554 depset::hash::add_partial_entities (vec<tree, va_gc> *partial_classes)
14555 {
14556 for (unsigned ix = 0; ix != partial_classes->length (); ix++)
14557 {
14558 tree inner = (*partial_classes)[ix];
14559
14560 depset *dep = make_dependency (inner, depset::EK_DECL);
14561
14562 if (dep->get_entity_kind () == depset::EK_REDIRECT)
14563 {
14564 dep = dep->deps[0];
14565 /* We should have recorded the template as a partial
14566 specialization. */
14567 gcc_checking_assert (dep->get_entity_kind ()
14568 == depset::EK_PARTIAL);
14569
14570 /* Only emit GM entities if reached. */
14571 if (!DECL_LANG_SPECIFIC (inner)
14572 || !DECL_MODULE_PURVIEW_P (inner))
14573 dep->set_flag_bit<DB_UNREACHED_BIT> ();
14574 }
14575 else
14576 {
14577 /* It was an explicit specialization, not a partial one.
14578 We should have already added this. */
14579 gcc_checking_assert (dep->get_entity_kind ()
14580 == depset::EK_SPECIALIZATION);
14581 gcc_checking_assert (dep->is_special ());
14582 }
14583 }
14584 }
14585
14586 /* Add the members of imported classes that we defined in this TU.
14587 This will also include lazily created implicit member function
14588 declarations. (All others will be definitions.) */
14589
14590 void
14591 depset::hash::add_class_entities (vec<tree, va_gc> *class_members)
14592 {
14593 for (unsigned ix = 0; ix != class_members->length (); ix++)
14594 {
14595 tree defn = (*class_members)[ix];
14596 depset *dep = make_dependency (defn, EK_INNER_DECL);
14597
14598 if (dep->get_entity_kind () == EK_REDIRECT)
14599 dep = dep->deps[0];
14600
14601 /* Only non-instantiations need marking as pendings. */
14602 if (dep->get_entity_kind () == EK_DECL)
14603 dep->set_flag_bit <DB_IS_PENDING_BIT> ();
14604 }
14605 }
14606
14607 /* We add the partial & explicit specializations, and the explicit
14608 instantiations. */
14609
14610 static void
14611 specialization_add (bool decl_p, spec_entry *entry, void *data_)
14612 {
14613 vec<spec_entry *> *data = reinterpret_cast <vec<spec_entry *> *> (data_);
14614
14615 if (!decl_p)
14616 {
14617 /* We exclusively use decls to locate things. Make sure there's
14618 no mismatch between the two specialization tables we keep.
14619 pt.cc optimizes instantiation lookup using a complicated
14620 heuristic. We don't attempt to replicate that algorithm, but
14621 observe its behaviour and reproduce it upon read back. */
14622
14623 gcc_checking_assert (TREE_CODE (entry->spec) == ENUMERAL_TYPE
14624 || DECL_CLASS_TEMPLATE_P (entry->tmpl));
14625
14626 gcc_checking_assert (!match_mergeable_specialization (true, entry));
14627 }
14628 else if (VAR_OR_FUNCTION_DECL_P (entry->spec))
14629 gcc_checking_assert (!DECL_LOCAL_DECL_P (entry->spec));
14630
14631 data->safe_push (entry);
14632 }
14633
14634 /* Arbitrary stable comparison. */
14635
14636 static int
14637 specialization_cmp (const void *a_, const void *b_)
14638 {
14639 const spec_entry *ea = *reinterpret_cast<const spec_entry *const *> (a_);
14640 const spec_entry *eb = *reinterpret_cast<const spec_entry *const *> (b_);
14641
14642 if (ea == eb)
14643 return 0;
14644
14645 tree a = ea->spec;
14646 tree b = eb->spec;
14647 if (TYPE_P (a))
14648 {
14649 a = TYPE_NAME (a);
14650 b = TYPE_NAME (b);
14651 }
14652
14653 if (a == b)
14654 /* This can happen with friend specializations. Just order by
14655 entry address. See note in depset_cmp. */
14656 return ea < eb ? -1 : +1;
14657
14658 return DECL_UID (a) < DECL_UID (b) ? -1 : +1;
14659 }
14660
14661 /* We add all kinds of specialializations. Implicit specializations
14662 should only streamed and walked if they are reachable from
14663 elsewhere. Hence the UNREACHED flag. This is making the
14664 assumption that it is cheaper to reinstantiate them on demand
14665 elsewhere, rather than stream them in when we instantiate their
14666 general template. Also, if we do stream them, we can only do that
14667 if they are not internal (which they can become if they themselves
14668 touch an internal entity?). */
14669
14670 void
14671 depset::hash::add_specializations (bool decl_p)
14672 {
14673 vec<spec_entry *> data;
14674 data.create (100);
14675 walk_specializations (decl_p, specialization_add, &data);
14676 data.qsort (specialization_cmp);
14677 while (data.length ())
14678 {
14679 spec_entry *entry = data.pop ();
14680 tree spec = entry->spec;
14681 int use_tpl = 0;
14682 bool is_friend = false;
14683
14684 if (decl_p && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (entry->tmpl))
14685 /* A friend of a template. This is keyed to the
14686 instantiation. */
14687 is_friend = true;
14688
14689 if (decl_p)
14690 {
14691 if (tree ti = DECL_TEMPLATE_INFO (spec))
14692 {
14693 tree tmpl = TI_TEMPLATE (ti);
14694
14695 use_tpl = DECL_USE_TEMPLATE (spec);
14696 if (spec == DECL_TEMPLATE_RESULT (tmpl))
14697 {
14698 spec = tmpl;
14699 gcc_checking_assert (DECL_USE_TEMPLATE (spec) == use_tpl);
14700 }
14701 else if (is_friend)
14702 {
14703 if (TI_TEMPLATE (ti) != entry->tmpl
14704 || !template_args_equal (TI_ARGS (ti), entry->tmpl))
14705 goto template_friend;
14706 }
14707 }
14708 else
14709 {
14710 template_friend:;
14711 gcc_checking_assert (is_friend);
14712 /* This is a friend of a template class, but not the one
14713 that generated entry->spec itself (i.e. it's an
14714 equivalent clone). We do not need to record
14715 this. */
14716 continue;
14717 }
14718 }
14719 else
14720 {
14721 if (TREE_CODE (spec) == ENUMERAL_TYPE)
14722 {
14723 tree ctx = DECL_CONTEXT (TYPE_NAME (spec));
14724
14725 if (TYPE_P (ctx))
14726 use_tpl = CLASSTYPE_USE_TEMPLATE (ctx);
14727 else
14728 use_tpl = DECL_USE_TEMPLATE (ctx);
14729 }
14730 else
14731 use_tpl = CLASSTYPE_USE_TEMPLATE (spec);
14732
14733 tree ti = TYPE_TEMPLATE_INFO (spec);
14734 tree tmpl = TI_TEMPLATE (ti);
14735
14736 spec = TYPE_NAME (spec);
14737 if (spec == DECL_TEMPLATE_RESULT (tmpl))
14738 {
14739 spec = tmpl;
14740 use_tpl = DECL_USE_TEMPLATE (spec);
14741 }
14742 }
14743
14744 bool needs_reaching = false;
14745 if (use_tpl == 1)
14746 /* Implicit instantiations only walked if we reach them. */
14747 needs_reaching = true;
14748 else if (!DECL_LANG_SPECIFIC (STRIP_TEMPLATE (spec))
14749 || !DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (spec)))
14750 /* Likewise, GMF explicit or partial specializations. */
14751 needs_reaching = true;
14752
14753 #if false && CHECKING_P
14754 /* The instantiation isn't always on
14755 DECL_TEMPLATE_INSTANTIATIONS, */
14756 // FIXME: we probably need to remember this information?
14757 /* Verify the specialization is on the
14758 DECL_TEMPLATE_INSTANTIATIONS of the template. */
14759 for (tree cons = DECL_TEMPLATE_INSTANTIATIONS (entry->tmpl);
14760 cons; cons = TREE_CHAIN (cons))
14761 if (TREE_VALUE (cons) == entry->spec)
14762 {
14763 gcc_assert (entry->args == TREE_PURPOSE (cons));
14764 goto have_spec;
14765 }
14766 gcc_unreachable ();
14767 have_spec:;
14768 #endif
14769
14770 /* Make sure nobody left a tree visited lying about. */
14771 gcc_checking_assert (!TREE_VISITED (spec));
14772 depset *dep = make_dependency (spec, depset::EK_SPECIALIZATION);
14773 if (dep->is_special ())
14774 gcc_unreachable ();
14775 else
14776 {
14777 if (dep->get_entity_kind () == depset::EK_REDIRECT)
14778 dep = dep->deps[0];
14779 else if (dep->get_entity_kind () == depset::EK_SPECIALIZATION)
14780 {
14781 dep->set_special ();
14782 dep->deps.safe_push (reinterpret_cast<depset *> (entry));
14783 if (!decl_p)
14784 dep->set_flag_bit<DB_TYPE_SPEC_BIT> ();
14785 }
14786
14787 if (needs_reaching)
14788 dep->set_flag_bit<DB_UNREACHED_BIT> ();
14789 if (is_friend)
14790 dep->set_flag_bit<DB_FRIEND_SPEC_BIT> ();
14791 }
14792 }
14793 data.release ();
14794 }
14795
14796 /* Add a depset into the mergeable hash. */
14797
14798 void
14799 depset::hash::add_mergeable (depset *mergeable)
14800 {
14801 gcc_checking_assert (is_key_order ());
14802 entity_kind ek = mergeable->get_entity_kind ();
14803 tree decl = mergeable->get_entity ();
14804 gcc_checking_assert (ek < EK_DIRECT_HWM);
14805
14806 depset **slot = entity_slot (decl, true);
14807 gcc_checking_assert (!*slot);
14808 depset *dep = make_entity (decl, ek);
14809 *slot = dep;
14810
14811 worklist.safe_push (dep);
14812
14813 /* So we can locate the mergeable depset this depset refers to,
14814 mark the first dep. */
14815 dep->set_special ();
14816 dep->deps.safe_push (mergeable);
14817 }
14818
14819 /* Find the innermost-namespace scope of DECL, and that
14820 namespace-scope decl. */
14821
14822 tree
14823 find_pending_key (tree decl, tree *decl_p = nullptr)
14824 {
14825 tree ns = decl;
14826 do
14827 {
14828 decl = ns;
14829 ns = CP_DECL_CONTEXT (ns);
14830 if (TYPE_P (ns))
14831 ns = TYPE_NAME (ns);
14832 }
14833 while (TREE_CODE (ns) != NAMESPACE_DECL);
14834
14835 if (decl_p)
14836 *decl_p = decl;
14837
14838 return ns;
14839 }
14840
14841 /* Creates bindings and dependencies for all deduction guides of
14842 the given class template DECL as needed. */
14843
14844 void
14845 depset::hash::add_deduction_guides (tree decl)
14846 {
14847 /* Alias templates never have deduction guides. */
14848 if (DECL_ALIAS_TEMPLATE_P (decl))
14849 return;
14850
14851 /* We don't need to do anything for class-scope deduction guides,
14852 as they will be added as members anyway. */
14853 if (!DECL_NAMESPACE_SCOPE_P (decl))
14854 return;
14855
14856 tree ns = CP_DECL_CONTEXT (decl);
14857 tree name = dguide_name (decl);
14858
14859 /* We always add all deduction guides with a given name at once,
14860 so if there's already a binding there's nothing to do. */
14861 if (find_binding (ns, name))
14862 return;
14863
14864 tree guides = lookup_qualified_name (ns, name, LOOK_want::NORMAL,
14865 /*complain=*/false);
14866 if (guides == error_mark_node)
14867 return;
14868
14869 depset *binding = nullptr;
14870 for (tree t : lkp_range (guides))
14871 {
14872 gcc_checking_assert (!TREE_VISITED (t));
14873 depset *dep = make_dependency (t, EK_FOR_BINDING);
14874
14875 /* We don't want to create bindings for imported deduction guides, as
14876 this would potentially cause name lookup to return duplicates. */
14877 if (dep->is_import ())
14878 continue;
14879
14880 if (!binding)
14881 {
14882 /* We have bindings to add. */
14883 binding = make_binding (ns, name);
14884 add_namespace_context (binding, ns);
14885
14886 depset **slot = binding_slot (ns, name, /*insert=*/true);
14887 *slot = binding;
14888 }
14889
14890 binding->deps.safe_push (dep);
14891 dep->deps.safe_push (binding);
14892 }
14893 }
14894
14895 /* Iteratively find dependencies. During the walk we may find more
14896 entries on the same binding that need walking. */
14897
14898 void
14899 depset::hash::find_dependencies (module_state *module)
14900 {
14901 trees_out walker (NULL, module, *this);
14902 vec<depset *> unreached;
14903 unreached.create (worklist.length ());
14904
14905 for (;;)
14906 {
14907 reached_unreached = false;
14908 while (worklist.length ())
14909 {
14910 depset *item = worklist.pop ();
14911
14912 gcc_checking_assert (!item->is_binding ());
14913 if (item->is_unreached ())
14914 unreached.quick_push (item);
14915 else
14916 {
14917 current = item;
14918 tree decl = current->get_entity ();
14919 dump (is_key_order () ? dumper::MERGE : dumper::DEPEND)
14920 && dump ("Dependencies of %s %C:%N",
14921 is_key_order () ? "key-order"
14922 : current->entity_kind_name (), TREE_CODE (decl), decl);
14923 dump.indent ();
14924 walker.begin ();
14925 if (current->get_entity_kind () == EK_USING)
14926 walker.tree_node (OVL_FUNCTION (decl));
14927 else if (TREE_VISITED (decl))
14928 /* A global tree. */;
14929 else if (item->get_entity_kind () == EK_NAMESPACE)
14930 {
14931 module->note_location (DECL_SOURCE_LOCATION (decl));
14932 add_namespace_context (current, CP_DECL_CONTEXT (decl));
14933 }
14934 else
14935 {
14936 walker.mark_declaration (decl, current->has_defn ());
14937
14938 if (!is_key_order ()
14939 && item->is_pending_entity ())
14940 {
14941 tree ns = find_pending_key (decl, nullptr);
14942 add_namespace_context (item, ns);
14943 }
14944
14945 walker.decl_value (decl, current);
14946 if (current->has_defn ())
14947 walker.write_definition (decl, current->refs_tu_local ());
14948 }
14949 walker.end ();
14950
14951 /* If we see either a class template or a deduction guide, make
14952 sure to add all visible deduction guides. We need to check
14953 both in case they have been added in separate modules, or
14954 one is in the GMF and would have otherwise been discarded. */
14955 if (!is_key_order ()
14956 && DECL_CLASS_TEMPLATE_P (decl))
14957 add_deduction_guides (decl);
14958 if (!is_key_order ()
14959 && deduction_guide_p (decl))
14960 add_deduction_guides (TYPE_NAME (TREE_TYPE (TREE_TYPE (decl))));
14961
14962 if (!is_key_order ()
14963 && TREE_CODE (decl) == TEMPLATE_DECL
14964 && !DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
14965 {
14966 /* Mark all the explicit & partial specializations as
14967 reachable. We search both specialization lists as some
14968 constrained partial specializations for class types are
14969 only found in DECL_TEMPLATE_SPECIALIZATIONS. */
14970 auto mark_reached = [this](tree spec)
14971 {
14972 if (TYPE_P (spec))
14973 spec = TYPE_NAME (spec);
14974 int use_tpl;
14975 node_template_info (spec, use_tpl);
14976 if (use_tpl & 2)
14977 {
14978 depset *spec_dep = find_dependency (spec);
14979 if (spec_dep->get_entity_kind () == EK_REDIRECT)
14980 spec_dep = spec_dep->deps[0];
14981 if (spec_dep->is_unreached ())
14982 {
14983 reached_unreached = true;
14984 spec_dep->clear_flag_bit<DB_UNREACHED_BIT> ();
14985 dump (dumper::DEPEND)
14986 && dump ("Reaching unreached specialization"
14987 " %C:%N", TREE_CODE (spec), spec);
14988 }
14989 }
14990 };
14991
14992 for (tree cons = DECL_TEMPLATE_INSTANTIATIONS (decl);
14993 cons; cons = TREE_CHAIN (cons))
14994 mark_reached (TREE_VALUE (cons));
14995 for (tree cons = DECL_TEMPLATE_SPECIALIZATIONS (decl);
14996 cons; cons = TREE_CHAIN (cons))
14997 mark_reached (TREE_VALUE (cons));
14998 }
14999
15000 dump.outdent ();
15001 current = NULL;
15002 }
15003 }
15004
15005 if (!reached_unreached)
15006 break;
15007
15008 /* It's possible the we reached the unreached before we
15009 processed it in the above loop, so we'll be doing this an
15010 extra time. However, to avoid that we have to do some
15011 bit shuffling that also involves a scan of the list.
15012 Swings & roundabouts I guess. */
15013 std::swap (worklist, unreached);
15014 }
15015
15016 unreached.release ();
15017 }
15018
15019 /* Compare two entries of a single binding. TYPE_DECL before
15020 non-exported before exported. */
15021
15022 static int
15023 binding_cmp (const void *a_, const void *b_)
15024 {
15025 depset *a = *(depset *const *)a_;
15026 depset *b = *(depset *const *)b_;
15027
15028 tree a_ent = a->get_entity ();
15029 tree b_ent = b->get_entity ();
15030 gcc_checking_assert (a_ent != b_ent
15031 && !a->is_binding ()
15032 && !b->is_binding ());
15033
15034 /* Implicit typedefs come first. */
15035 bool a_implicit = DECL_IMPLICIT_TYPEDEF_P (a_ent);
15036 bool b_implicit = DECL_IMPLICIT_TYPEDEF_P (b_ent);
15037 if (a_implicit || b_implicit)
15038 {
15039 /* A binding with two implicit type decls? That's unpossible! */
15040 gcc_checking_assert (!(a_implicit && b_implicit));
15041 return a_implicit ? -1 : +1; /* Implicit first. */
15042 }
15043
15044 /* Hidden before non-hidden. */
15045 bool a_hidden = a->is_hidden ();
15046 bool b_hidden = b->is_hidden ();
15047 if (a_hidden != b_hidden)
15048 return a_hidden ? -1 : +1;
15049
15050 bool a_using = a->get_entity_kind () == depset::EK_USING;
15051 bool a_export;
15052 if (a_using)
15053 {
15054 a_export = OVL_EXPORT_P (a_ent);
15055 a_ent = OVL_FUNCTION (a_ent);
15056 }
15057 else if (TREE_CODE (a_ent) == CONST_DECL
15058 && DECL_LANG_SPECIFIC (a_ent)
15059 && DECL_MODULE_EXPORT_P (a_ent))
15060 a_export = true;
15061 else
15062 a_export = DECL_MODULE_EXPORT_P (TREE_CODE (a_ent) == CONST_DECL
15063 ? TYPE_NAME (TREE_TYPE (a_ent))
15064 : STRIP_TEMPLATE (a_ent));
15065
15066 bool b_using = b->get_entity_kind () == depset::EK_USING;
15067 bool b_export;
15068 if (b_using)
15069 {
15070 b_export = OVL_EXPORT_P (b_ent);
15071 b_ent = OVL_FUNCTION (b_ent);
15072 }
15073 else if (TREE_CODE (b_ent) == CONST_DECL
15074 && DECL_LANG_SPECIFIC (b_ent)
15075 && DECL_MODULE_EXPORT_P (b_ent))
15076 b_export = true;
15077 else
15078 b_export = DECL_MODULE_EXPORT_P (TREE_CODE (b_ent) == CONST_DECL
15079 ? TYPE_NAME (TREE_TYPE (b_ent))
15080 : STRIP_TEMPLATE (b_ent));
15081
15082 /* Non-exports before exports. */
15083 if (a_export != b_export)
15084 return a_export ? +1 : -1;
15085
15086 /* At this point we don't care, but want a stable sort. */
15087
15088 if (a_using != b_using)
15089 /* using first. */
15090 return a_using? -1 : +1;
15091
15092 return DECL_UID (a_ent) < DECL_UID (b_ent) ? -1 : +1;
15093 }
15094
15095 /* True iff TMPL has an explicit instantiation definition.
15096
15097 This is local to module.cc because register_specialization skips adding most
15098 instantiations unless module_maybe_has_cmi_p. */
15099
15100 static bool
15101 template_has_explicit_inst (tree tmpl)
15102 {
15103 for (tree t = DECL_TEMPLATE_INSTANTIATIONS (tmpl); t; t = TREE_CHAIN (t))
15104 {
15105 tree spec = TREE_VALUE (t);
15106 if (DECL_EXPLICIT_INSTANTIATION (spec)
15107 && !DECL_REALLY_EXTERN (spec))
15108 return true;
15109 }
15110 return false;
15111 }
15112
15113 /* Sort the bindings, issue errors about bad internal refs. */
15114
15115 bool
15116 depset::hash::finalize_dependencies ()
15117 {
15118 bool ok = true;
15119 for (depset *dep : *this)
15120 {
15121 if (dep->is_binding ())
15122 {
15123 /* Keep the containing namespace dep first. */
15124 gcc_checking_assert (dep->deps.length () > 1
15125 && (dep->deps[0]->get_entity_kind ()
15126 == EK_NAMESPACE)
15127 && (dep->deps[0]->get_entity ()
15128 == dep->get_entity ()));
15129 if (dep->deps.length () > 2)
15130 gcc_qsort (&dep->deps[1], dep->deps.length () - 1,
15131 sizeof (dep->deps[1]), binding_cmp);
15132
15133 /* Bindings shouldn't refer to imported entities. */
15134 if (CHECKING_P)
15135 for (depset *entity : dep->deps)
15136 gcc_checking_assert (!entity->is_import ());
15137 }
15138 else if (dep->is_exposure () && !dep->is_tu_local ())
15139 {
15140 ok = false;
15141 bool explained = false;
15142 tree decl = dep->get_entity ();
15143
15144 for (depset *rdep : dep->deps)
15145 if (!rdep->is_binding ()
15146 && rdep->is_tu_local ()
15147 && !is_exposure_of_member_type (dep, rdep))
15148 {
15149 // FIXME:QOI Better location information? We're
15150 // losing, so it doesn't matter about efficiency
15151 tree exposed = rdep->get_entity ();
15152 auto_diagnostic_group d;
15153 error_at (DECL_SOURCE_LOCATION (decl),
15154 "%qD exposes TU-local entity %qD", decl, exposed);
15155 bool informed = is_tu_local_entity (exposed, /*explain=*/true);
15156 gcc_checking_assert (informed);
15157 explained = true;
15158 break;
15159 }
15160
15161 if (!explained
15162 && VAR_P (decl)
15163 && (DECL_DECLARED_CONSTEXPR_P (decl)
15164 || DECL_INLINE_VAR_P (decl)))
15165 {
15166 auto_diagnostic_group d;
15167 if (DECL_DECLARED_CONSTEXPR_P (decl))
15168 error_at (DECL_SOURCE_LOCATION (decl),
15169 "%qD is declared %<constexpr%> and is initialized to "
15170 "a TU-local value", decl);
15171 else
15172 {
15173 /* This can only occur with references. */
15174 gcc_checking_assert (TYPE_REF_P (TREE_TYPE (decl)));
15175 error_at (DECL_SOURCE_LOCATION (decl),
15176 "%qD is a reference declared %<inline%> and is "
15177 "constant-initialized to a TU-local value", decl);
15178 }
15179 bool informed = is_tu_local_value (decl, DECL_INITIAL (decl),
15180 /*explain=*/true);
15181 gcc_checking_assert (informed);
15182 explained = true;
15183 }
15184
15185 /* We should have emitted an error above. */
15186 gcc_checking_assert (explained);
15187 }
15188 else if (warn_template_names_tu_local
15189 && dep->refs_tu_local () && !dep->is_tu_local ())
15190 {
15191 tree decl = dep->get_entity ();
15192
15193 /* Friend decls in a class body are ignored, but this is harmless:
15194 it should not impact any consumers. */
15195 if (RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl)))
15196 continue;
15197
15198 /* We should now only be warning about templates. */
15199 gcc_checking_assert
15200 (TREE_CODE (decl) == TEMPLATE_DECL
15201 && VAR_OR_FUNCTION_DECL_P (DECL_TEMPLATE_RESULT (decl)));
15202
15203 /* Don't warn if we've seen any explicit instantiation definitions,
15204 the intent might be for importers to only use those. */
15205 if (template_has_explicit_inst (decl))
15206 continue;
15207
15208 for (depset *rdep : dep->deps)
15209 if (!rdep->is_binding () && rdep->is_tu_local ())
15210 {
15211 tree ref = rdep->get_entity ();
15212 auto_diagnostic_group d;
15213 if (warning_at (DECL_SOURCE_LOCATION (decl),
15214 OPT_Wtemplate_names_tu_local,
15215 "%qD refers to TU-local entity %qD and cannot "
15216 "be instantiated in other TUs", decl, ref))
15217 is_tu_local_entity (ref, /*explain=*/true);
15218 break;
15219 }
15220 }
15221 }
15222
15223 return ok;
15224 }
15225
15226 /* Core of TARJAN's algorithm to find Strongly Connected Components
15227 within a graph. See https://en.wikipedia.org/wiki/
15228 Tarjan%27s_strongly_connected_components_algorithm for details.
15229
15230 We use depset::section as lowlink. Completed nodes have
15231 depset::cluster containing the cluster number, with the top
15232 bit set.
15233
15234 A useful property is that the output vector is a reverse
15235 topological sort of the resulting DAG. In our case that means
15236 dependent SCCs are found before their dependers. We make use of
15237 that property. */
15238
15239 void
15240 depset::tarjan::connect (depset *v)
15241 {
15242 gcc_checking_assert (v->is_binding ()
15243 || !(v->is_tu_local ()
15244 || v->is_unreached ()
15245 || v->is_import ()));
15246
15247 v->cluster = v->section = ++index;
15248 stack.safe_push (v);
15249
15250 /* Walk all our dependencies, ignore a first marked slot */
15251 for (unsigned ix = v->is_special (); ix != v->deps.length (); ix++)
15252 {
15253 depset *dep = v->deps[ix];
15254
15255 if (dep->is_binding ()
15256 || !(dep->is_import () || dep->is_tu_local ()))
15257 {
15258 unsigned lwm = dep->cluster;
15259
15260 if (!dep->cluster)
15261 {
15262 /* A new node. Connect it. */
15263 connect (dep);
15264 lwm = dep->section;
15265 }
15266
15267 if (dep->section && v->section > lwm)
15268 v->section = lwm;
15269 }
15270 }
15271
15272 if (v->section == v->cluster)
15273 {
15274 /* Root of a new SCC. Push all the members onto the result list. */
15275 unsigned num = v->cluster;
15276 depset *p;
15277 do
15278 {
15279 p = stack.pop ();
15280 p->cluster = num;
15281 p->section = 0;
15282 result.quick_push (p);
15283 }
15284 while (p != v);
15285 }
15286 }
15287
15288 /* Compare two depsets. The specific ordering is unimportant, we're
15289 just trying to get consistency. */
15290
15291 static int
15292 depset_cmp (const void *a_, const void *b_)
15293 {
15294 depset *a = *(depset *const *)a_;
15295 depset *b = *(depset *const *)b_;
15296
15297 depset::entity_kind a_kind = a->get_entity_kind ();
15298 depset::entity_kind b_kind = b->get_entity_kind ();
15299
15300 if (a_kind != b_kind)
15301 /* Different entity kinds, order by that. */
15302 return a_kind < b_kind ? -1 : +1;
15303
15304 tree a_decl = a->get_entity ();
15305 tree b_decl = b->get_entity ();
15306 if (a_kind == depset::EK_USING)
15307 {
15308 /* If one is a using, the other must be too. */
15309 a_decl = OVL_FUNCTION (a_decl);
15310 b_decl = OVL_FUNCTION (b_decl);
15311 }
15312
15313 if (a_decl != b_decl)
15314 /* Different entities, order by their UID. */
15315 return DECL_UID (a_decl) < DECL_UID (b_decl) ? -1 : +1;
15316
15317 if (a_kind == depset::EK_BINDING)
15318 {
15319 /* Both are bindings. Order by identifier hash. */
15320 gcc_checking_assert (a->get_name () != b->get_name ());
15321 hashval_t ah = IDENTIFIER_HASH_VALUE (a->get_name ());
15322 hashval_t bh = IDENTIFIER_HASH_VALUE (b->get_name ());
15323 return (ah == bh ? 0 : ah < bh ? -1 : +1);
15324 }
15325
15326 /* They are the same decl. This can happen with two using decls
15327 pointing to the same target. The best we can aim for is
15328 consistently telling qsort how to order them. Hopefully we'll
15329 never have to debug a case that depends on this. Oh, who am I
15330 kidding? Good luck. */
15331 gcc_checking_assert (a_kind == depset::EK_USING);
15332
15333 /* Order by depset address. Not the best, but it is something. */
15334 return a < b ? -1 : +1;
15335 }
15336
15337 /* Sort the clusters in SCC such that those that depend on one another
15338 are placed later. */
15339
15340 // FIXME: I am not convinced this is needed and, if needed,
15341 // sufficient. We emit the decls in this order but that emission
15342 // could walk into later decls (from the body of the decl, or default
15343 // arg-like things). Why doesn't that walk do the right thing? And
15344 // if it DTRT why do we need to sort here -- won't things naturally
15345 // work? I think part of the issue is that when we're going to refer
15346 // to an entity by name, and that entity is in the same cluster as us,
15347 // we need to actually walk that entity, if we've not already walked
15348 // it.
15349 static void
15350 sort_cluster (depset::hash *original, depset *scc[], unsigned size)
15351 {
15352 depset::hash table (size, original);
15353
15354 dump.indent ();
15355
15356 /* Place bindings last, usings before that. It's not strictly
15357 necessary, but it does make things neater. Says Mr OCD. */
15358 unsigned bind_lwm = size;
15359 unsigned use_lwm = size;
15360 for (unsigned ix = 0; ix != use_lwm;)
15361 {
15362 depset *dep = scc[ix];
15363 switch (dep->get_entity_kind ())
15364 {
15365 case depset::EK_BINDING:
15366 /* Move to end. No increment. Notice this could be moving
15367 a using decl, which we'll then move again. */
15368 if (--bind_lwm != ix)
15369 {
15370 scc[ix] = scc[bind_lwm];
15371 scc[bind_lwm] = dep;
15372 }
15373 if (use_lwm > bind_lwm)
15374 {
15375 use_lwm--;
15376 break;
15377 }
15378 /* We must have copied a using, so move it too. */
15379 dep = scc[ix];
15380 gcc_checking_assert (dep->get_entity_kind () == depset::EK_USING);
15381 /* FALLTHROUGH */
15382
15383 case depset::EK_USING:
15384 if (--use_lwm != ix)
15385 {
15386 scc[ix] = scc[use_lwm];
15387 scc[use_lwm] = dep;
15388 }
15389 break;
15390
15391 case depset::EK_DECL:
15392 case depset::EK_SPECIALIZATION:
15393 case depset::EK_PARTIAL:
15394 table.add_mergeable (dep);
15395 ix++;
15396 break;
15397
15398 default:
15399 gcc_unreachable ();
15400 }
15401 }
15402
15403 gcc_checking_assert (use_lwm <= bind_lwm);
15404 dump (dumper::MERGE) && dump ("Ordering %u/%u depsets", use_lwm, size);
15405
15406 table.find_dependencies (nullptr);
15407
15408 auto_vec<depset *> order = table.connect ();
15409 gcc_checking_assert (order.length () == use_lwm);
15410
15411 /* Now rewrite entries [0,lwm), in the dependency order we
15412 discovered. Usually each entity is in its own cluster. Rarely,
15413 we can get multi-entity clusters, in which case all but one must
15414 only be reached from within the cluster. This happens for
15415 something like:
15416
15417 template<typename T>
15418 auto Foo (const T &arg) -> TPL<decltype (arg)>;
15419
15420 The instantiation of TPL will be in the specialization table, and
15421 refer to Foo via arg. But we can only get to that specialization
15422 from Foo's declaration, so we only need to treat Foo as mergable
15423 (We'll do structural comparison of TPL<decltype (arg)>).
15424
15425 We approximate finding the single cluster entry dep by checking for
15426 entities recursively depending on a dep first seen when streaming
15427 its own merge key; the first dep we see in such a cluster should be
15428 the first one streamed. */
15429 unsigned entry_pos = ~0u;
15430 unsigned cluster = ~0u;
15431 for (unsigned ix = 0; ix != order.length (); ix++)
15432 {
15433 gcc_checking_assert (order[ix]->is_special ());
15434 bool tight = order[ix]->cluster == cluster;
15435 depset *dep = order[ix]->deps[0];
15436 dump (dumper::MERGE)
15437 && dump ("Mergeable %u is %N%s%s", ix, dep->get_entity (),
15438 tight ? " (tight)" : "", dep->is_entry () ? " (entry)" : "");
15439 scc[ix] = dep;
15440 if (tight)
15441 {
15442 gcc_checking_assert (dep->is_maybe_recursive ());
15443 if (dep->is_entry ())
15444 {
15445 /* There should only be one entry dep in a cluster. */
15446 gcc_checking_assert (!scc[entry_pos]->is_entry ());
15447 gcc_checking_assert (scc[entry_pos]->is_maybe_recursive ());
15448 scc[ix] = scc[entry_pos];
15449 scc[entry_pos] = dep;
15450 }
15451 }
15452 else
15453 entry_pos = ix;
15454 cluster = order[ix]->cluster;
15455 }
15456
15457 dump (dumper::MERGE) && dump ("Ordered %u keys", order.length ());
15458 dump.outdent ();
15459 }
15460
15461 /* Reduce graph to SCCS clusters. SCCS will be populated with the
15462 depsets in dependency order. Each depset's CLUSTER field contains
15463 its cluster number. Each SCC has a unique cluster number, and are
15464 contiguous in SCCS. Cluster numbers are otherwise arbitrary. */
15465
15466 vec<depset *>
15467 depset::hash::connect ()
15468 {
15469 tarjan connector (size ());
15470 vec<depset *> deps;
15471 deps.create (size ());
15472 for (depset *item : *this)
15473 {
15474 entity_kind kind = item->get_entity_kind ();
15475 if (kind == EK_BINDING
15476 || !(kind == EK_REDIRECT
15477 || item->is_tu_local ()
15478 || item->is_unreached ()
15479 || item->is_import ()))
15480 deps.quick_push (item);
15481 }
15482
15483 /* Iteration over the hash table is an unspecified ordering. While
15484 that has advantages, it causes 2 problems. Firstly repeatable
15485 builds are tricky. Secondly creating testcases that check
15486 dependencies are correct by making sure a bad ordering would
15487 happen if that was wrong. */
15488 deps.qsort (depset_cmp);
15489
15490 while (deps.length ())
15491 {
15492 depset *v = deps.pop ();
15493 dump (dumper::CLUSTER) &&
15494 (v->is_binding ()
15495 ? dump ("Connecting binding %P", v->get_entity (), v->get_name ())
15496 : dump ("Connecting %s %s %C:%N",
15497 is_key_order () ? "key-order"
15498 : !v->has_defn () ? "declaration" : "definition",
15499 v->entity_kind_name (), TREE_CODE (v->get_entity ()),
15500 v->get_entity ()));
15501 if (!v->cluster)
15502 connector.connect (v);
15503 }
15504
15505 deps.release ();
15506 return connector.result;
15507 }
15508
15509 /* Initialize location spans. */
15510
15511 void
15512 loc_spans::init (const line_maps *lmaps, const line_map_ordinary *map)
15513 {
15514 gcc_checking_assert (!init_p ());
15515 spans = new vec<span> ();
15516 spans->reserve (20);
15517
15518 span interval;
15519 interval.ordinary.first = 0;
15520 interval.macro.second = MAX_LOCATION_T + 1;
15521 interval.ordinary_delta = interval.macro_delta = 0;
15522
15523 /* A span for reserved fixed locs. */
15524 interval.ordinary.second
15525 = MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0));
15526 interval.macro.first = interval.macro.second;
15527 dump (dumper::LOCATION)
15528 && dump ("Fixed span %u ordinary:[%K,%K) macro:[%K,%K)", spans->length (),
15529 interval.ordinary.first, interval.ordinary.second,
15530 interval.macro.first, interval.macro.second);
15531 spans->quick_push (interval);
15532
15533 /* A span for command line & forced headers. */
15534 interval.ordinary.first = interval.ordinary.second;
15535 interval.macro.second = interval.macro.first;
15536 if (map)
15537 {
15538 interval.ordinary.second = map->start_location;
15539 interval.macro.first = LINEMAPS_MACRO_LOWEST_LOCATION (lmaps);
15540 }
15541 dump (dumper::LOCATION)
15542 && dump ("Pre span %u ordinary:[%K,%K) macro:[%K,%K)", spans->length (),
15543 interval.ordinary.first, interval.ordinary.second,
15544 interval.macro.first, interval.macro.second);
15545 spans->quick_push (interval);
15546
15547 /* Start an interval for the main file. */
15548 interval.ordinary.first = interval.ordinary.second;
15549 interval.macro.second = interval.macro.first;
15550 dump (dumper::LOCATION)
15551 && dump ("Main span %u ordinary:[%K,*) macro:[*,%K)", spans->length (),
15552 interval.ordinary.first, interval.macro.second);
15553 spans->quick_push (interval);
15554 }
15555
15556 /* Reopen the span, if we want the about-to-be-inserted set of maps to
15557 be propagated in our own location table. I.e. we are the primary
15558 interface and we're importing a partition. */
15559
15560 bool
15561 loc_spans::maybe_propagate (module_state *import, location_t hwm)
15562 {
15563 bool opened = (module_interface_p () && !module_partition_p ()
15564 && import->is_partition ());
15565 if (opened)
15566 open (hwm);
15567 return opened;
15568 }
15569
15570 /* Open a new linemap interval. The just-created ordinary map is the
15571 first map of the interval. */
15572
15573 void
15574 loc_spans::open (location_t hwm)
15575 {
15576 span interval;
15577 interval.ordinary.first = interval.ordinary.second = hwm;
15578 interval.macro.first = interval.macro.second
15579 = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
15580 interval.ordinary_delta = interval.macro_delta = 0;
15581 dump (dumper::LOCATION)
15582 && dump ("Opening span %u ordinary:[%K,... macro:...,%K)",
15583 spans->length (), interval.ordinary.first,
15584 interval.macro.second);
15585 if (spans->length ())
15586 {
15587 /* No overlapping! */
15588 auto &last = spans->last ();
15589 gcc_checking_assert (interval.ordinary.first >= last.ordinary.second);
15590 gcc_checking_assert (interval.macro.second <= last.macro.first);
15591 }
15592 spans->safe_push (interval);
15593 }
15594
15595 /* Close out the current linemap interval. The last maps are within
15596 the interval. */
15597
15598 void
15599 loc_spans::close ()
15600 {
15601 span &interval = spans->last ();
15602
15603 interval.ordinary.second
15604 = ((line_table->highest_location
15605 + (loc_one << line_table->default_range_bits))
15606 & ~((loc_one << line_table->default_range_bits) - 1));
15607 interval.macro.first = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
15608 dump (dumper::LOCATION)
15609 && dump ("Closing span %u ordinary:[%K,%K) macro:[%K,%K)",
15610 spans->length () - 1,
15611 interval.ordinary.first,interval.ordinary.second,
15612 interval.macro.first, interval.macro.second);
15613 }
15614
15615 /* Given an ordinary location LOC, return the lmap_interval it resides
15616 in. NULL if it is not in an interval. */
15617
15618 const loc_spans::span *
15619 loc_spans::ordinary (location_t loc)
15620 {
15621 unsigned len = spans->length ();
15622 unsigned pos = 0;
15623 while (len)
15624 {
15625 unsigned half = len / 2;
15626 const span &probe = (*spans)[pos + half];
15627 if (loc < probe.ordinary.first)
15628 len = half;
15629 else if (loc < probe.ordinary.second)
15630 return &probe;
15631 else
15632 {
15633 pos += half + 1;
15634 len = len - (half + 1);
15635 }
15636 }
15637 return NULL;
15638 }
15639
15640 /* Likewise, given a macro location LOC, return the lmap interval it
15641 resides in. */
15642
15643 const loc_spans::span *
15644 loc_spans::macro (location_t loc)
15645 {
15646 unsigned len = spans->length ();
15647 unsigned pos = 0;
15648 while (len)
15649 {
15650 unsigned half = len / 2;
15651 const span &probe = (*spans)[pos + half];
15652 if (loc >= probe.macro.second)
15653 len = half;
15654 else if (loc >= probe.macro.first)
15655 return &probe;
15656 else
15657 {
15658 pos += half + 1;
15659 len = len - (half + 1);
15660 }
15661 }
15662 return NULL;
15663 }
15664
15665 /* Return the ordinary location closest to FROM. */
15666
15667 static location_t
15668 ordinary_loc_of (line_maps *lmaps, location_t from)
15669 {
15670 while (!IS_ORDINARY_LOC (from))
15671 {
15672 if (IS_ADHOC_LOC (from))
15673 from = get_location_from_adhoc_loc (lmaps, from);
15674 if (from >= LINEMAPS_MACRO_LOWEST_LOCATION (lmaps))
15675 {
15676 /* Find the ordinary location nearest FROM. */
15677 const line_map *map = linemap_lookup (lmaps, from);
15678 const line_map_macro *mac_map = linemap_check_macro (map);
15679 from = mac_map->get_expansion_point_location ();
15680 }
15681 }
15682 return from;
15683 }
15684
15685 static module_state **
15686 get_module_slot (tree name, module_state *parent, bool partition, bool insert)
15687 {
15688 module_state_hash::compare_type ct (name, uintptr_t (parent) | partition);
15689 hashval_t hv = module_state_hash::hash (ct);
15690
15691 return modules_hash->find_slot_with_hash (ct, hv, insert ? INSERT : NO_INSERT);
15692 }
15693
15694 static module_state *
15695 get_primary (module_state *parent)
15696 {
15697 while (parent->is_partition ())
15698 parent = parent->parent;
15699
15700 if (!parent->name)
15701 // Implementation unit has null name
15702 parent = parent->parent;
15703
15704 return parent;
15705 }
15706
15707 /* Find or create module NAME & PARENT in the hash table. */
15708
15709 module_state *
15710 get_module (tree name, module_state *parent, bool partition)
15711 {
15712 /* We might be given an empty NAME if preprocessing fails to handle
15713 a header-name token. */
15714 if (name && TREE_CODE (name) == STRING_CST
15715 && TREE_STRING_LENGTH (name) == 0)
15716 return nullptr;
15717
15718 if (partition)
15719 {
15720 if (!parent)
15721 parent = get_primary ((*modules)[0]);
15722
15723 if (!parent->is_partition () && !parent->flatname)
15724 parent->set_flatname ();
15725 }
15726
15727 module_state **slot = get_module_slot (name, parent, partition, true);
15728 module_state *state = *slot;
15729 if (!state)
15730 {
15731 state = (new (ggc_alloc<module_state> ())
15732 module_state (name, parent, partition));
15733 *slot = state;
15734 }
15735 return state;
15736 }
15737
15738 /* Process string name PTR into a module_state. */
15739
15740 static module_state *
15741 get_module (const char *ptr)
15742 {
15743 /* On DOS based file systems, there is an ambiguity with A:B which can be
15744 interpreted as a module Module:Partition or Drive:PATH. Interpret strings
15745 which clearly starts as pathnames as header-names and everything else is
15746 treated as a (possibly malformed) named moduled. */
15747 if (IS_DIR_SEPARATOR (ptr[ptr[0] == '.']) // ./FOO or /FOO
15748 #if HAVE_DOS_BASED_FILE_SYSTEM
15749 || (HAS_DRIVE_SPEC (ptr) && IS_DIR_SEPARATOR (ptr[2])) // A:/FOO
15750 #endif
15751 || false)
15752 /* A header name. */
15753 return get_module (build_string (strlen (ptr), ptr));
15754
15755 bool partition = false;
15756 module_state *mod = NULL;
15757
15758 for (const char *probe = ptr;; probe++)
15759 if (!*probe || *probe == '.' || *probe == ':')
15760 {
15761 if (probe == ptr)
15762 return NULL;
15763
15764 mod = get_module (get_identifier_with_length (ptr, probe - ptr),
15765 mod, partition);
15766 ptr = probe;
15767 if (*ptr == ':')
15768 {
15769 if (partition)
15770 return NULL;
15771 partition = true;
15772 }
15773
15774 if (!*ptr++)
15775 break;
15776 }
15777 else if (!(ISALPHA (*probe) || *probe == '_'
15778 || (probe != ptr && ISDIGIT (*probe))))
15779 return NULL;
15780
15781 return mod;
15782 }
15783
15784 /* Create a new mapper connecting to OPTION. */
15785
15786 module_client *
15787 make_mapper (location_t loc, class mkdeps *deps)
15788 {
15789 timevar_start (TV_MODULE_MAPPER);
15790 const char *option = module_mapper_name;
15791 if (!option)
15792 option = getenv ("CXX_MODULE_MAPPER");
15793
15794 mapper = module_client::open_module_client
15795 (loc, option, deps, &set_cmi_repo,
15796 (save_decoded_options[0].opt_index == OPT_SPECIAL_program_name)
15797 && save_decoded_options[0].arg != progname
15798 ? save_decoded_options[0].arg : nullptr);
15799
15800 timevar_stop (TV_MODULE_MAPPER);
15801
15802 return mapper;
15803 }
15804
15805 static unsigned lazy_snum;
15806
15807 static bool
15808 recursive_lazy (unsigned snum = ~0u)
15809 {
15810 if (lazy_snum)
15811 {
15812 error_at (input_location, "recursive lazy load");
15813 return true;
15814 }
15815
15816 lazy_snum = snum;
15817 return false;
15818 }
15819
15820 /* If THIS is the current purview, issue an import error and return false. */
15821
15822 bool
15823 module_state::check_not_purview (location_t from)
15824 {
15825 module_state *imp = (*modules)[0];
15826 if (imp && !imp->name)
15827 imp = imp->parent;
15828 if (imp == this)
15829 {
15830 /* Cannot import the current module. */
15831 auto_diagnostic_group d;
15832 error_at (from, "cannot import module in its own purview");
15833 inform (loc, "module %qs declared here", get_flatname ());
15834 return false;
15835 }
15836 return true;
15837 }
15838
15839 /* Module name substitutions. */
15840 static vec<module_state *,va_heap> substs;
15841
15842 void
15843 module_state::mangle (bool include_partition)
15844 {
15845 if (subst)
15846 mangle_module_substitution (subst);
15847 else
15848 {
15849 if (parent)
15850 parent->mangle (include_partition);
15851 if (include_partition || !is_partition ())
15852 {
15853 // Partitions are significant for global initializer
15854 // functions
15855 bool partition = is_partition () && !parent->is_partition ();
15856 subst = mangle_module_component (name, partition);
15857 substs.safe_push (this);
15858 }
15859 }
15860 }
15861
15862 void
15863 mangle_module (int mod, bool include_partition)
15864 {
15865 module_state *imp = (*modules)[mod];
15866
15867 gcc_checking_assert (!imp->is_header ());
15868
15869 if (!imp->name)
15870 /* Set when importing the primary module interface. */
15871 imp = imp->parent;
15872
15873 imp->mangle (include_partition);
15874 }
15875
15876 /* Clean up substitutions. */
15877 void
15878 mangle_module_fini ()
15879 {
15880 while (substs.length ())
15881 substs.pop ()->subst = 0;
15882 }
15883
15884 /* Announce WHAT about the module. */
15885
15886 void
15887 module_state::announce (const char *what) const
15888 {
15889 if (noisy_p ())
15890 {
15891 fprintf (stderr, " %s:%s", what, get_flatname ());
15892 fflush (stderr);
15893 }
15894 }
15895
15896 /* A human-readable README section. The contents of this section to
15897 not contribute to the CRC, so the contents can change per
15898 compilation. That allows us to embed CWD, hostname, build time and
15899 what not. It is a STRTAB that may be extracted with:
15900 readelf -pgnu.c++.README $(module).gcm */
15901
15902 void
15903 module_state::write_readme (elf_out *to, cpp_reader *reader, const char *dialect)
15904 {
15905 bytes_out readme (to);
15906
15907 readme.begin (false);
15908
15909 readme.printf ("GNU C++ %s",
15910 is_header () ? "header unit"
15911 : !is_partition () ? "primary interface"
15912 : is_interface () ? "interface partition"
15913 : "internal partition");
15914
15915 /* Compiler's version. */
15916 readme.printf ("compiler: %s", version_string);
15917
15918 /* Module format version. */
15919 verstr_t string;
15920 version2string (MODULE_VERSION, string);
15921 readme.printf ("version: %s", string);
15922
15923 /* Module information. */
15924 readme.printf ("module: %s", get_flatname ());
15925 readme.printf ("source: %s", main_input_filename);
15926 readme.printf ("dialect: %s", dialect);
15927 if (extensions)
15928 readme.printf ("extensions: %s%s%s",
15929 extensions & SE_OPENMP ? "-fopenmp"
15930 : extensions & SE_OPENMP_SIMD ? "-fopenmp-simd" : "",
15931 (extensions & SE_OPENACC)
15932 && (extensions & (SE_OPENMP | SE_OPENMP_SIMD))
15933 ? " " : "",
15934 extensions & SE_OPENACC ? "-fopenacc" : "");
15935
15936 /* The following fields could be expected to change between
15937 otherwise identical compilations. Consider a distributed build
15938 system. We should have a way of overriding that. */
15939 if (char *cwd = getcwd (NULL, 0))
15940 {
15941 readme.printf ("cwd: %s", cwd);
15942 free (cwd);
15943 }
15944 readme.printf ("repository: %s", cmi_repo ? cmi_repo : ".");
15945 #if NETWORKING
15946 {
15947 char hostname[64];
15948 if (!gethostname (hostname, sizeof (hostname)))
15949 readme.printf ("host: %s", hostname);
15950 }
15951 #endif
15952 {
15953 /* This of course will change! */
15954 time_t stampy;
15955 auto kind = cpp_get_date (reader, &stampy);
15956 if (kind != CPP_time_kind::UNKNOWN)
15957 {
15958 struct tm *time;
15959
15960 time = gmtime (&stampy);
15961 readme.print_time ("build", time, "UTC");
15962
15963 if (kind == CPP_time_kind::DYNAMIC)
15964 {
15965 time = localtime (&stampy);
15966 readme.print_time ("local", time,
15967 #if defined (__USE_MISC) || defined (__USE_BSD) /* Is there a better way? */
15968 time->tm_zone
15969 #else
15970 ""
15971 #endif
15972 );
15973 }
15974 }
15975 }
15976
15977 /* Its direct imports. */
15978 for (unsigned ix = 1; ix < modules->length (); ix++)
15979 {
15980 module_state *state = (*modules)[ix];
15981
15982 if (state->is_direct ())
15983 readme.printf ("%s: %s %s", state->exported_p ? "export" : "import",
15984 state->get_flatname (), state->filename);
15985 }
15986
15987 readme.end (to, to->name (MOD_SNAME_PFX ".README"), NULL);
15988 }
15989
15990 /* Sort environment var names in reverse order. */
15991
15992 static int
15993 env_var_cmp (const void *a_, const void *b_)
15994 {
15995 const unsigned char *a = *(const unsigned char *const *)a_;
15996 const unsigned char *b = *(const unsigned char *const *)b_;
15997
15998 for (unsigned ix = 0; ; ix++)
15999 {
16000 bool a_end = !a[ix] || a[ix] == '=';
16001 if (a[ix] == b[ix])
16002 {
16003 if (a_end)
16004 break;
16005 }
16006 else
16007 {
16008 bool b_end = !b[ix] || b[ix] == '=';
16009
16010 if (!a_end && !b_end)
16011 return a[ix] < b[ix] ? +1 : -1;
16012 if (a_end && b_end)
16013 break;
16014 return a_end ? +1 : -1;
16015 }
16016 }
16017
16018 return 0;
16019 }
16020
16021 /* Write the environment. It is a STRTAB that may be extracted with:
16022 readelf -pgnu.c++.ENV $(module).gcm */
16023
16024 void
16025 module_state::write_env (elf_out *to)
16026 {
16027 vec<const char *> vars;
16028 vars.create (20);
16029
16030 extern char **environ;
16031 while (const char *var = environ[vars.length ()])
16032 vars.safe_push (var);
16033 vars.qsort (env_var_cmp);
16034
16035 bytes_out env (to);
16036 env.begin (false);
16037 while (vars.length ())
16038 env.printf ("%s", vars.pop ());
16039 env.end (to, to->name (MOD_SNAME_PFX ".ENV"), NULL);
16040
16041 vars.release ();
16042 }
16043
16044 /* Write the direct or indirect imports.
16045 u:N
16046 {
16047 u:index
16048 s:name
16049 u32:crc
16050 s:filename (direct)
16051 u:exported (direct)
16052 } imports[N]
16053 */
16054
16055 void
16056 module_state::write_imports (bytes_out &sec, bool direct)
16057 {
16058 unsigned count = 0;
16059
16060 for (unsigned ix = 1; ix < modules->length (); ix++)
16061 {
16062 module_state *imp = (*modules)[ix];
16063
16064 if (imp->remap && imp->is_direct () == direct)
16065 count++;
16066 }
16067
16068 gcc_assert (!direct || count);
16069
16070 sec.u (count);
16071 for (unsigned ix = 1; ix < modules->length (); ix++)
16072 {
16073 module_state *imp = (*modules)[ix];
16074
16075 if (imp->remap && imp->is_direct () == direct)
16076 {
16077 dump () && dump ("Writing %simport:%u->%u %M (crc=%x)",
16078 !direct ? "indirect "
16079 : imp->exported_p ? "exported " : "",
16080 ix, imp->remap, imp, imp->crc);
16081 sec.u (imp->remap);
16082 sec.str (imp->get_flatname ());
16083 sec.u32 (imp->crc);
16084 if (direct)
16085 {
16086 write_location (sec, imp->imported_from ());
16087 sec.str (imp->filename);
16088 int exportedness = 0;
16089 if (imp->exported_p)
16090 exportedness = +1;
16091 else if (!imp->is_purview_direct ())
16092 exportedness = -1;
16093 sec.i (exportedness);
16094 }
16095 }
16096 }
16097 }
16098
16099 /* READER, LMAPS != NULL == direct imports,
16100 == NUL == indirect imports. */
16101
16102 unsigned
16103 module_state::read_imports (bytes_in &sec, cpp_reader *reader, line_maps *lmaps)
16104 {
16105 unsigned count = sec.u ();
16106 unsigned loaded = 0;
16107
16108 while (count--)
16109 {
16110 unsigned ix = sec.u ();
16111 if (ix >= slurp->remap->length () || !ix || (*slurp->remap)[ix])
16112 {
16113 sec.set_overrun ();
16114 break;
16115 }
16116
16117 const char *name = sec.str (NULL);
16118 module_state *imp = get_module (name);
16119 unsigned crc = sec.u32 ();
16120 int exportedness = 0;
16121
16122 /* If the import is a partition, it must be the same primary
16123 module as this TU. */
16124 if (imp && imp->is_partition () &&
16125 (!named_module_p ()
16126 || (get_primary ((*modules)[0]) != get_primary (imp))))
16127 imp = NULL;
16128
16129 if (!imp)
16130 sec.set_overrun ();
16131 if (sec.get_overrun ())
16132 break;
16133
16134 if (lmaps)
16135 {
16136 /* A direct import, maybe load it. */
16137 location_t floc = read_location (sec);
16138 const char *fname = sec.str (NULL);
16139 exportedness = sec.i ();
16140
16141 if (sec.get_overrun ())
16142 break;
16143
16144 if (!imp->check_not_purview (loc))
16145 continue;
16146
16147 if (imp->loadedness == ML_NONE)
16148 {
16149 imp->loc = floc;
16150 imp->crc = crc;
16151 if (!imp->get_flatname ())
16152 imp->set_flatname ();
16153
16154 unsigned n = dump.push (imp);
16155
16156 if (!imp->filename && fname)
16157 imp->filename = xstrdup (fname);
16158
16159 if (imp->is_partition ())
16160 dump () && dump ("Importing elided partition %M", imp);
16161
16162 if (!imp->do_import (reader, false))
16163 imp = NULL;
16164 dump.pop (n);
16165 if (!imp)
16166 continue;
16167 }
16168
16169 if (is_partition ())
16170 {
16171 if (!imp->is_direct () && !imp->is_partition_direct ())
16172 {
16173 imp->directness = MD_PARTITION_DIRECT;
16174 linemap_module_reparent (line_table, imp->loc, floc);
16175 }
16176 if (exportedness > 0)
16177 imp->exported_p = true;
16178 }
16179 }
16180 else
16181 {
16182 /* An indirect import, find it, it should already be here. */
16183 if (imp->loadedness == ML_NONE)
16184 {
16185 error_at (loc, "indirect import %qs is not already loaded", name);
16186 continue;
16187 }
16188 }
16189
16190 if (imp->crc != crc)
16191 error_at (loc, "import %qs has CRC mismatch", imp->get_flatname ());
16192
16193 (*slurp->remap)[ix] = (imp->mod << 1) | (lmaps != NULL);
16194
16195 if (lmaps && exportedness >= 0)
16196 set_import (imp, bool (exportedness));
16197 dump () && dump ("Found %simport:%u %M->%u", !lmaps ? "indirect "
16198 : exportedness > 0 ? "exported "
16199 : exportedness < 0 ? "gmf" : "", ix, imp,
16200 imp->mod);
16201 loaded++;
16202 }
16203
16204 return loaded;
16205 }
16206
16207 /* Write the import table to MOD_SNAME_PFX.imp. */
16208
16209 void
16210 module_state::write_imports (elf_out *to, unsigned *crc_ptr)
16211 {
16212 dump () && dump ("Writing imports");
16213 dump.indent ();
16214
16215 bytes_out sec (to);
16216 sec.begin ();
16217
16218 write_imports (sec, true);
16219 write_imports (sec, false);
16220
16221 sec.end (to, to->name (MOD_SNAME_PFX ".imp"), crc_ptr);
16222 dump.outdent ();
16223 }
16224
16225 bool
16226 module_state::read_imports (cpp_reader *reader, line_maps *lmaps)
16227 {
16228 bytes_in sec;
16229
16230 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".imp"))
16231 return false;
16232
16233 dump () && dump ("Reading %u imports", slurp->remap->length () - 1);
16234 dump.indent ();
16235
16236 /* Read the imports. */
16237 unsigned direct = read_imports (sec, reader, lmaps);
16238 unsigned indirect = read_imports (sec, NULL, NULL);
16239 if (direct + indirect + 1 != slurp->remap->length ())
16240 from ()->set_error (elf::E_BAD_IMPORT);
16241
16242 dump.outdent ();
16243 if (!sec.end (from ()))
16244 return false;
16245 return true;
16246 }
16247
16248 /* We're the primary module interface, but have partitions. Document
16249 them so that non-partition module implementation units know which
16250 have already been loaded. */
16251
16252 void
16253 module_state::write_partitions (elf_out *to, unsigned count, unsigned *crc_ptr)
16254 {
16255 dump () && dump ("Writing %u elided partitions", count);
16256 dump.indent ();
16257
16258 bytes_out sec (to);
16259 sec.begin ();
16260
16261 for (unsigned ix = 1; ix != modules->length (); ix++)
16262 {
16263 module_state *imp = (*modules)[ix];
16264 if (imp->is_partition ())
16265 {
16266 dump () && dump ("Writing elided partition %M (crc=%x)",
16267 imp, imp->crc);
16268 sec.str (imp->get_flatname ());
16269 sec.u32 (imp->crc);
16270 write_location (sec, imp->is_direct ()
16271 ? imp->imported_from () : UNKNOWN_LOCATION);
16272 sec.str (imp->filename);
16273 }
16274 }
16275
16276 sec.end (to, to->name (MOD_SNAME_PFX ".prt"), crc_ptr);
16277 dump.outdent ();
16278 }
16279
16280 bool
16281 module_state::read_partitions (unsigned count)
16282 {
16283 bytes_in sec;
16284 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".prt"))
16285 return false;
16286
16287 dump () && dump ("Reading %u elided partitions", count);
16288 dump.indent ();
16289
16290 while (count--)
16291 {
16292 const char *name = sec.str (NULL);
16293 unsigned crc = sec.u32 ();
16294 location_t floc = read_location (sec);
16295 const char *fname = sec.str (NULL);
16296
16297 if (sec.get_overrun ())
16298 break;
16299
16300 dump () && dump ("Reading elided partition %s (crc=%x)", name, crc);
16301
16302 module_state *imp = get_module (name);
16303 if (!imp /* Partition should be ... */
16304 || !imp->is_partition () /* a partition ... */
16305 || imp->loadedness != ML_NONE /* that is not yet loaded ... */
16306 || get_primary (imp) != this) /* whose primary is this. */
16307 {
16308 sec.set_overrun ();
16309 break;
16310 }
16311
16312 if (!imp->has_location ())
16313 imp->loc = floc;
16314 imp->crc = crc;
16315 if (!imp->filename && fname[0])
16316 imp->filename = xstrdup (fname);
16317 }
16318
16319 dump.outdent ();
16320 if (!sec.end (from ()))
16321 return false;
16322 return true;
16323 }
16324
16325 /* Data for config reading and writing. */
16326 struct module_state_config {
16327 const char *dialect_str = get_dialect ();
16328 line_map_uint_t ordinary_locs = 0;
16329 line_map_uint_t macro_locs = 0;
16330 unsigned num_imports = 0;
16331 unsigned num_partitions = 0;
16332 unsigned num_entities = 0;
16333 unsigned loc_range_bits = 0;
16334 unsigned active_init = 0;
16335
16336 static void release ()
16337 {
16338 XDELETEVEC (dialect);
16339 dialect = NULL;
16340 }
16341
16342 private:
16343 static const char *get_dialect ();
16344 static char *dialect;
16345 };
16346
16347 char *module_state_config::dialect;
16348
16349 /* Generate a string of the significant compilation options.
16350 Generally assume the user knows what they're doing, in the same way
16351 that object files can be mixed. */
16352
16353 const char *
16354 module_state_config::get_dialect ()
16355 {
16356 if (!dialect)
16357 dialect = concat (get_cxx_dialect_name (cxx_dialect),
16358 /* C++ implies these, only show if disabled. */
16359 flag_exceptions ? "" : "/no-exceptions",
16360 flag_rtti ? "" : "/no-rtti",
16361 flag_new_inheriting_ctors ? "" : "/old-inheriting-ctors",
16362 /* C++ 20 implies concepts and coroutines. */
16363 cxx_dialect < cxx20 && flag_concepts ? "/concepts" : "",
16364 (cxx_dialect < cxx20 && flag_coroutines
16365 ? "/coroutines" : ""),
16366 flag_module_implicit_inline ? "/implicit-inline" : "",
16367 flag_contracts ? "/contracts" : "",
16368 NULL);
16369
16370 return dialect;
16371 }
16372
16373 /* Contents of a cluster. */
16374 enum cluster_tag {
16375 ct_decl, /* A decl. */
16376 ct_defn, /* A definition. */
16377 ct_bind, /* A binding. */
16378 ct_hwm
16379 };
16380
16381 /* Binding modifiers. */
16382 enum ct_bind_flags
16383 {
16384 cbf_export = 0x1, /* An exported decl. */
16385 cbf_hidden = 0x2, /* A hidden (friend) decl. */
16386 cbf_using = 0x4, /* A using decl. */
16387 };
16388
16389 /* DEP belongs to a different cluster, seed it to prevent
16390 unfortunately timed duplicate import. */
16391 // FIXME: QOI For inter-cluster references we could just only pick
16392 // one entity from an earlier cluster. Even better track
16393 // dependencies between earlier clusters
16394
16395 void
16396 module_state::intercluster_seed (trees_out &sec, unsigned index_hwm, depset *dep)
16397 {
16398 if (dep->is_tu_local ())
16399 /* We only stream placeholders for TU-local entities anyway. */;
16400 else if (dep->is_import () || dep->cluster < index_hwm)
16401 {
16402 tree ent = dep->get_entity ();
16403 if (!TREE_VISITED (ent))
16404 {
16405 sec.tree_node (ent);
16406 dump (dumper::CLUSTER)
16407 && dump ("Seeded %s %N",
16408 dep->is_import () ? "import" : "intercluster", ent);
16409 }
16410 }
16411 }
16412
16413 /* Write the cluster of depsets in SCC[0-SIZE).
16414 dep->section -> section number
16415 dep->cluster -> entity number
16416 */
16417
16418 unsigned
16419 module_state::write_cluster (elf_out *to, depset *scc[], unsigned size,
16420 depset::hash &table, unsigned *counts,
16421 unsigned *crc_ptr)
16422 {
16423 dump () && dump ("Writing section:%u %u depsets", table.section, size);
16424 dump.indent ();
16425
16426 trees_out sec (to, this, table, table.section);
16427 sec.begin ();
16428 unsigned index_lwm = counts[MSC_entities];
16429
16430 /* Determine entity numbers, mark for writing. */
16431 dump (dumper::CLUSTER) && dump ("Cluster members:") && (dump.indent (), true);
16432 for (unsigned ix = 0; ix != size; ix++)
16433 {
16434 depset *b = scc[ix];
16435
16436 switch (b->get_entity_kind ())
16437 {
16438 default:
16439 gcc_unreachable ();
16440
16441 case depset::EK_BINDING:
16442 {
16443 dump (dumper::CLUSTER)
16444 && dump ("[%u]=%s %P", ix, b->entity_kind_name (),
16445 b->get_entity (), b->get_name ());
16446 depset *ns_dep = b->deps[0];
16447 gcc_checking_assert (ns_dep->get_entity_kind ()
16448 == depset::EK_NAMESPACE
16449 && ns_dep->get_entity () == b->get_entity ());
16450 for (unsigned jx = b->deps.length (); --jx;)
16451 {
16452 depset *dep = b->deps[jx];
16453 // We could be declaring something that is also a
16454 // (merged) import
16455 gcc_checking_assert (dep->is_import ()
16456 || TREE_VISITED (dep->get_entity ())
16457 || (dep->get_entity_kind ()
16458 == depset::EK_USING));
16459 }
16460 }
16461 break;
16462
16463 case depset::EK_DECL:
16464 case depset::EK_SPECIALIZATION:
16465 case depset::EK_PARTIAL:
16466 b->cluster = counts[MSC_entities]++;
16467 sec.mark_declaration (b->get_entity (), b->has_defn ());
16468 /* FALLTHROUGH */
16469
16470 case depset::EK_USING:
16471 gcc_checking_assert (!b->is_import ()
16472 && !b->is_unreached ());
16473 dump (dumper::CLUSTER)
16474 && dump ("[%u]=%s %s %N", ix, b->entity_kind_name (),
16475 b->has_defn () ? "definition" : "declaration",
16476 b->get_entity ());
16477 break;
16478 }
16479 }
16480 dump (dumper::CLUSTER) && (dump.outdent (), true);
16481
16482 /* Ensure every out-of-cluster decl is referenced before we start
16483 streaming. We must do both imports *and* earlier clusters,
16484 because the latter could reach into the former and cause a
16485 duplicate loop. */
16486 sec.set_importing (+1);
16487 for (unsigned ix = 0; ix != size; ix++)
16488 {
16489 depset *b = scc[ix];
16490 for (unsigned jx = b->is_special (); jx != b->deps.length (); jx++)
16491 {
16492 depset *dep = b->deps[jx];
16493
16494 if (dep->is_binding ())
16495 {
16496 for (unsigned ix = dep->deps.length (); --ix;)
16497 {
16498 depset *bind = dep->deps[ix];
16499 if (bind->get_entity_kind () == depset::EK_USING)
16500 bind = bind->deps[1];
16501
16502 intercluster_seed (sec, index_lwm, bind);
16503 }
16504 /* Also check the namespace itself. */
16505 dep = dep->deps[0];
16506 }
16507
16508 intercluster_seed (sec, index_lwm, dep);
16509 }
16510 }
16511 sec.tree_node (NULL_TREE);
16512 /* We're done importing now. */
16513 sec.set_importing (-1);
16514
16515 /* Write non-definitions. */
16516 for (unsigned ix = 0; ix != size; ix++)
16517 {
16518 depset *b = scc[ix];
16519 tree decl = b->get_entity ();
16520 switch (b->get_entity_kind ())
16521 {
16522 default:
16523 gcc_unreachable ();
16524 break;
16525
16526 case depset::EK_BINDING:
16527 {
16528 gcc_assert (TREE_CODE (decl) == NAMESPACE_DECL);
16529 dump () && dump ("Depset:%u binding %C:%P", ix, TREE_CODE (decl),
16530 decl, b->get_name ());
16531 sec.u (ct_bind);
16532 sec.tree_node (decl);
16533 sec.tree_node (b->get_name ());
16534
16535 /* Write in reverse order, so reading will see the exports
16536 first, thus building the overload chain will be
16537 optimized. */
16538 for (unsigned jx = b->deps.length (); --jx;)
16539 {
16540 depset *dep = b->deps[jx];
16541 tree bound = dep->get_entity ();
16542 unsigned flags = 0;
16543 if (dep->get_entity_kind () == depset::EK_USING)
16544 {
16545 tree ovl = bound;
16546 bound = OVL_FUNCTION (bound);
16547 if (!(TREE_CODE (bound) == CONST_DECL
16548 && UNSCOPED_ENUM_P (TREE_TYPE (bound))
16549 && decl == TYPE_NAME (TREE_TYPE (bound))))
16550 /* An unscoped enumerator in its enumeration's
16551 scope is not a using. */
16552 flags |= cbf_using;
16553 if (OVL_EXPORT_P (ovl))
16554 flags |= cbf_export;
16555 }
16556 else
16557 {
16558 /* An implicit typedef must be at one. */
16559 gcc_assert (!DECL_IMPLICIT_TYPEDEF_P (bound) || jx == 1);
16560 if (dep->is_hidden ())
16561 flags |= cbf_hidden;
16562 else if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (bound)))
16563 flags |= cbf_export;
16564 }
16565
16566 gcc_checking_assert (DECL_P (bound));
16567
16568 sec.i (flags);
16569 sec.tree_node (bound);
16570 }
16571
16572 /* Terminate the list. */
16573 sec.i (-1);
16574 }
16575 break;
16576
16577 case depset::EK_USING:
16578 dump () && dump ("Depset:%u %s %C:%N", ix, b->entity_kind_name (),
16579 TREE_CODE (decl), decl);
16580 break;
16581
16582 case depset::EK_SPECIALIZATION:
16583 case depset::EK_PARTIAL:
16584 case depset::EK_DECL:
16585 dump () && dump ("Depset:%u %s entity:%u %C:%N", ix,
16586 b->entity_kind_name (), b->cluster,
16587 TREE_CODE (decl), decl);
16588
16589 sec.u (ct_decl);
16590 sec.tree_node (decl);
16591
16592 dump () && dump ("Wrote declaration entity:%u %C:%N",
16593 b->cluster, TREE_CODE (decl), decl);
16594 break;
16595 }
16596 }
16597
16598 depset *namer = NULL;
16599
16600 /* Write out definitions */
16601 for (unsigned ix = 0; ix != size; ix++)
16602 {
16603 depset *b = scc[ix];
16604 tree decl = b->get_entity ();
16605 switch (b->get_entity_kind ())
16606 {
16607 default:
16608 break;
16609
16610 case depset::EK_SPECIALIZATION:
16611 case depset::EK_PARTIAL:
16612 case depset::EK_DECL:
16613 if (!namer)
16614 namer = b;
16615
16616 if (b->has_defn ())
16617 {
16618 sec.u (ct_defn);
16619 sec.tree_node (decl);
16620 dump () && dump ("Writing definition %N", decl);
16621 sec.write_definition (decl, b->refs_tu_local ());
16622
16623 if (!namer->has_defn ())
16624 namer = b;
16625 }
16626 break;
16627 }
16628 }
16629
16630 /* We don't find the section by name. Use depset's decl's name for
16631 human friendliness. */
16632 unsigned name = 0;
16633 tree naming_decl = NULL_TREE;
16634 if (namer)
16635 {
16636 naming_decl = namer->get_entity ();
16637 if (namer->get_entity_kind () == depset::EK_USING)
16638 /* This unfortunately names the section from the target of the
16639 using decl. But the name is only a guide, so Do Not Care. */
16640 naming_decl = OVL_FUNCTION (naming_decl);
16641 if (DECL_IMPLICIT_TYPEDEF_P (naming_decl))
16642 /* Lose any anonymousness. */
16643 naming_decl = TYPE_NAME (TREE_TYPE (naming_decl));
16644 name = to->qualified_name (naming_decl, namer->has_defn ());
16645 }
16646
16647 unsigned bytes = sec.pos;
16648 unsigned snum = sec.end (to, name, crc_ptr);
16649
16650 for (unsigned ix = size; ix--;)
16651 gcc_checking_assert (scc[ix]->section == snum);
16652
16653 dump.outdent ();
16654 dump () && dump ("Wrote section:%u named-by:%N", table.section, naming_decl);
16655
16656 return bytes;
16657 }
16658
16659 /* Read a cluster from section SNUM. */
16660
16661 bool
16662 module_state::read_cluster (unsigned snum)
16663 {
16664 trees_in sec (this);
16665
16666 if (!sec.begin (loc, from (), snum))
16667 return false;
16668
16669 dump () && dump ("Reading section:%u", snum);
16670 dump.indent ();
16671
16672 /* We care about structural equality. */
16673 comparing_dependent_aliases++;
16674
16675 /* First seed the imports. */
16676 while (tree import = sec.tree_node ())
16677 dump (dumper::CLUSTER) && dump ("Seeded import %N", import);
16678
16679 while (!sec.get_overrun () && sec.more_p ())
16680 {
16681 unsigned ct = sec.u ();
16682 switch (ct)
16683 {
16684 default:
16685 sec.set_overrun ();
16686 break;
16687
16688 case ct_bind:
16689 /* A set of namespace bindings. */
16690 {
16691 tree ns = sec.tree_node ();
16692 tree name = sec.tree_node ();
16693 tree decls = NULL_TREE;
16694 tree visible = NULL_TREE;
16695 tree type = NULL_TREE;
16696 bool dedup = false;
16697 bool global_p = is_header ();
16698
16699 /* We rely on the bindings being in the reverse order of
16700 the resulting overload set. */
16701 for (;;)
16702 {
16703 int flags = sec.i ();
16704 if (flags < 0)
16705 break;
16706
16707 if ((flags & cbf_hidden)
16708 && (flags & (cbf_using | cbf_export)))
16709 sec.set_overrun ();
16710
16711 tree decl = sec.tree_node ();
16712 if (sec.get_overrun ())
16713 break;
16714
16715 if (!global_p)
16716 {
16717 /* Check if the decl could require GM merging. */
16718 tree orig = get_originating_module_decl (decl);
16719 tree inner = STRIP_TEMPLATE (orig);
16720 if (!DECL_LANG_SPECIFIC (inner)
16721 || !DECL_MODULE_ATTACH_P (inner))
16722 global_p = true;
16723 }
16724
16725 if (decls && TREE_CODE (decl) == TYPE_DECL)
16726 {
16727 /* Stat hack. */
16728 if (type || !DECL_IMPLICIT_TYPEDEF_P (decl))
16729 sec.set_overrun ();
16730
16731 if (flags & cbf_using)
16732 {
16733 type = build_lang_decl_loc (UNKNOWN_LOCATION,
16734 USING_DECL,
16735 DECL_NAME (decl),
16736 NULL_TREE);
16737 USING_DECL_DECLS (type) = decl;
16738 USING_DECL_SCOPE (type) = CP_DECL_CONTEXT (decl);
16739 DECL_CONTEXT (type) = ns;
16740
16741 DECL_MODULE_PURVIEW_P (type) = true;
16742 if (flags & cbf_export)
16743 DECL_MODULE_EXPORT_P (type) = true;
16744 }
16745 else
16746 type = decl;
16747 }
16748 else
16749 {
16750 if ((flags & cbf_using) &&
16751 !DECL_DECLARES_FUNCTION_P (decl))
16752 {
16753 /* We should only see a single non-function using-decl
16754 for a binding; more than that would clash. */
16755 if (decls)
16756 sec.set_overrun ();
16757
16758 /* FIXME: Propagate the location of the using-decl
16759 for use in diagnostics. */
16760 decls = build_lang_decl_loc (UNKNOWN_LOCATION,
16761 USING_DECL,
16762 DECL_NAME (decl),
16763 NULL_TREE);
16764 USING_DECL_DECLS (decls) = decl;
16765 /* We don't currently record the actual scope of the
16766 using-declaration, but this approximation should
16767 generally be good enough. */
16768 USING_DECL_SCOPE (decls) = CP_DECL_CONTEXT (decl);
16769 DECL_CONTEXT (decls) = ns;
16770
16771 DECL_MODULE_PURVIEW_P (decls) = true;
16772 if (flags & cbf_export)
16773 DECL_MODULE_EXPORT_P (decls) = true;
16774 }
16775 else if (decls
16776 || (flags & (cbf_hidden | cbf_using))
16777 || DECL_FUNCTION_TEMPLATE_P (decl))
16778 {
16779 decls = ovl_make (decl, decls);
16780 if (flags & cbf_using)
16781 {
16782 dedup = true;
16783 OVL_USING_P (decls) = true;
16784 OVL_PURVIEW_P (decls) = true;
16785 if (flags & cbf_export)
16786 OVL_EXPORT_P (decls) = true;
16787 }
16788
16789 if (flags & cbf_hidden)
16790 OVL_HIDDEN_P (decls) = true;
16791 else if (dedup)
16792 OVL_DEDUP_P (decls) = true;
16793 }
16794 else
16795 decls = decl;
16796
16797 if (flags & cbf_export
16798 || (!(flags & cbf_hidden)
16799 && (is_module () || is_partition ())))
16800 visible = decls;
16801 }
16802 }
16803
16804 if (!decls)
16805 sec.set_overrun ();
16806
16807 if (sec.get_overrun ())
16808 break; /* Bail. */
16809
16810 dump () && dump ("Binding of %P", ns, name);
16811 if (!set_module_binding (ns, name, mod, global_p,
16812 is_module () || is_partition (),
16813 decls, type, visible))
16814 sec.set_overrun ();
16815 }
16816 break;
16817
16818 case ct_decl:
16819 /* A decl. */
16820 {
16821 tree decl = sec.tree_node ();
16822 dump () && dump ("Read declaration of %N", decl);
16823 }
16824 break;
16825
16826 case ct_defn:
16827 {
16828 tree decl = sec.tree_node ();
16829 dump () && dump ("Reading definition of %N", decl);
16830 sec.read_definition (decl);
16831 }
16832 break;
16833 }
16834 }
16835
16836 /* When lazy loading is in effect, we can be in the middle of
16837 parsing or instantiating a function. Save it away.
16838 push_function_context does too much work. */
16839 tree old_cfd = current_function_decl;
16840 struct function *old_cfun = cfun;
16841 for (const post_process_data& pdata : sec.post_process ())
16842 {
16843 tree decl = pdata.decl;
16844
16845 bool abstract = false;
16846 if (TREE_CODE (decl) == TEMPLATE_DECL)
16847 {
16848 abstract = true;
16849 decl = DECL_TEMPLATE_RESULT (decl);
16850 }
16851
16852 current_function_decl = decl;
16853 allocate_struct_function (decl, abstract);
16854 cfun->language = ggc_cleared_alloc<language_function> ();
16855 cfun->language->base.x_stmt_tree.stmts_are_full_exprs_p = 1;
16856 cfun->function_start_locus = pdata.start_locus;
16857 cfun->function_end_locus = pdata.end_locus;
16858 cfun->language->returns_value = pdata.returns_value;
16859 cfun->language->returns_null = pdata.returns_null;
16860 cfun->language->returns_abnormally = pdata.returns_abnormally;
16861 cfun->language->infinite_loop = pdata.infinite_loop;
16862
16863 /* Make sure we emit explicit instantiations.
16864 FIXME do we want to do this in expand_or_defer_fn instead? */
16865 if (DECL_EXPLICIT_INSTANTIATION (decl)
16866 && !DECL_EXTERNAL (decl))
16867 setup_explicit_instantiation_definition_linkage (decl);
16868
16869 if (abstract)
16870 ;
16871 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
16872 vec_safe_push (post_load_decls, decl);
16873 else
16874 {
16875 bool aggr = aggregate_value_p (DECL_RESULT (decl), decl);
16876 #ifdef PCC_STATIC_STRUCT_RETURN
16877 cfun->returns_pcc_struct = aggr;
16878 #endif
16879 cfun->returns_struct = aggr;
16880 expand_or_defer_fn (decl);
16881
16882 /* If we first see this function after at_eof, it doesn't get
16883 note_vague_linkage_fn from tentative_decl_linkage, so the loop in
16884 c_parse_final_cleanups won't consider it. But with DECL_COMDAT we
16885 can just clear DECL_EXTERNAL and let cgraph decide.
16886 FIXME handle this outside module.cc after GCC 15. */
16887 if (at_eof && DECL_COMDAT (decl) && DECL_EXTERNAL (decl)
16888 && DECL_NOT_REALLY_EXTERN (decl))
16889 DECL_EXTERNAL (decl) = false;
16890 }
16891 }
16892 for (const tree& type : sec.post_process_type ())
16893 {
16894 /* Attempt to complete an array type now in case its element type
16895 had a definition streamed later in the cluster. */
16896 gcc_checking_assert (TREE_CODE (type) == ARRAY_TYPE);
16897 complete_type (type);
16898 }
16899 /* Look, function.cc's interface to cfun does too much for us, we
16900 just need to restore the old value. I do not want to go
16901 redesigning that API right now. */
16902 #undef cfun
16903 cfun = old_cfun;
16904 current_function_decl = old_cfd;
16905 comparing_dependent_aliases--;
16906
16907 dump.outdent ();
16908 dump () && dump ("Read section:%u", snum);
16909
16910 loaded_clusters++;
16911
16912 if (!sec.end (from ()))
16913 return false;
16914
16915 return true;
16916 }
16917
16918 void
16919 module_state::write_namespace (bytes_out &sec, depset *dep)
16920 {
16921 unsigned ns_num = dep->cluster;
16922 unsigned ns_import = 0;
16923
16924 if (dep->is_import ())
16925 ns_import = dep->section;
16926 else if (dep->get_entity () != global_namespace)
16927 ns_num++;
16928
16929 sec.u (ns_import);
16930 sec.u (ns_num);
16931 }
16932
16933 tree
16934 module_state::read_namespace (bytes_in &sec)
16935 {
16936 unsigned ns_import = sec.u ();
16937 unsigned ns_num = sec.u ();
16938 tree ns = NULL_TREE;
16939
16940 if (ns_import || ns_num)
16941 {
16942 if (!ns_import)
16943 ns_num--;
16944
16945 if (unsigned origin = slurp->remap_module (ns_import))
16946 {
16947 module_state *from = (*modules)[origin];
16948 if (ns_num < from->entity_num)
16949 {
16950 binding_slot &slot = (*entity_ary)[from->entity_lwm + ns_num];
16951
16952 if (!slot.is_lazy ())
16953 ns = slot;
16954 }
16955 }
16956 else
16957 sec.set_overrun ();
16958 }
16959 else
16960 ns = global_namespace;
16961
16962 return ns;
16963 }
16964
16965 /* SPACES is a sorted vector of namespaces. Write out the namespaces
16966 to MOD_SNAME_PFX.nms section. */
16967
16968 void
16969 module_state::write_namespaces (elf_out *to, vec<depset *> spaces,
16970 unsigned num, unsigned *crc_p)
16971 {
16972 dump () && dump ("Writing namespaces");
16973 dump.indent ();
16974
16975 bytes_out sec (to);
16976 sec.begin ();
16977
16978 for (unsigned ix = 0; ix != num; ix++)
16979 {
16980 depset *b = spaces[ix];
16981 tree ns = b->get_entity ();
16982
16983 /* This could be an anonymous namespace even for a named module,
16984 since we can still emit no-linkage decls. */
16985 gcc_checking_assert (TREE_CODE (ns) == NAMESPACE_DECL);
16986
16987 unsigned flags = 0;
16988 if (TREE_PUBLIC (ns))
16989 flags |= 1;
16990 if (DECL_NAMESPACE_INLINE_P (ns))
16991 flags |= 2;
16992 if (DECL_MODULE_PURVIEW_P (ns))
16993 flags |= 4;
16994 if (DECL_MODULE_EXPORT_P (ns))
16995 flags |= 8;
16996
16997 dump () && dump ("Writing namespace:%u %N%s%s%s%s",
16998 b->cluster, ns,
16999 flags & 1 ? ", public" : "",
17000 flags & 2 ? ", inline" : "",
17001 flags & 4 ? ", purview" : "",
17002 flags & 8 ? ", export" : "");
17003 sec.u (b->cluster);
17004 sec.u (to->name (DECL_NAME (ns)));
17005 write_namespace (sec, b->deps[0]);
17006
17007 sec.u (flags);
17008 write_location (sec, DECL_SOURCE_LOCATION (ns));
17009
17010 if (DECL_NAMESPACE_INLINE_P (ns))
17011 {
17012 if (tree attr = lookup_attribute ("abi_tag", DECL_ATTRIBUTES (ns)))
17013 {
17014 tree tags = TREE_VALUE (attr);
17015 sec.u (list_length (tags));
17016 for (tree tag = tags; tag; tag = TREE_CHAIN (tag))
17017 sec.str (TREE_STRING_POINTER (TREE_VALUE (tag)));
17018 }
17019 else
17020 sec.u (0);
17021 }
17022 }
17023
17024 sec.end (to, to->name (MOD_SNAME_PFX ".nms"), crc_p);
17025 dump.outdent ();
17026 }
17027
17028 /* Read the namespace hierarchy from MOD_SNAME_PFX.namespace. Fill in
17029 SPACES from that data. */
17030
17031 bool
17032 module_state::read_namespaces (unsigned num)
17033 {
17034 bytes_in sec;
17035
17036 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".nms"))
17037 return false;
17038
17039 dump () && dump ("Reading namespaces");
17040 dump.indent ();
17041
17042 for (unsigned ix = 0; ix != num; ix++)
17043 {
17044 unsigned entity_index = sec.u ();
17045 unsigned name = sec.u ();
17046
17047 tree parent = read_namespace (sec);
17048
17049 /* See comment in write_namespace about why not bits. */
17050 unsigned flags = sec.u ();
17051 location_t src_loc = read_location (sec);
17052 unsigned tags_count = (flags & 2) ? sec.u () : 0;
17053
17054 if (entity_index >= entity_num
17055 || !parent
17056 || (flags & 0xc) == 0x8)
17057 sec.set_overrun ();
17058
17059 tree tags = NULL_TREE;
17060 while (tags_count--)
17061 {
17062 size_t len;
17063 const char *str = sec.str (&len);
17064 tags = tree_cons (NULL_TREE, build_string (len + 1, str), tags);
17065 tags = nreverse (tags);
17066 }
17067
17068 if (sec.get_overrun ())
17069 break;
17070
17071 tree id = name ? get_identifier (from ()->name (name)) : NULL_TREE;
17072
17073 dump () && dump ("Read namespace:%u %P%s%s%s%s",
17074 entity_index, parent, id,
17075 flags & 1 ? ", public" : "",
17076 flags & 2 ? ", inline" : "",
17077 flags & 4 ? ", purview" : "",
17078 flags & 8 ? ", export" : "");
17079 bool visible_p = ((flags & 8)
17080 || ((flags & 1)
17081 && (flags & 4)
17082 && (is_partition () || is_module ())));
17083 tree inner = add_imported_namespace (parent, id, src_loc, mod,
17084 bool (flags & 2), visible_p);
17085 if (!inner)
17086 {
17087 sec.set_overrun ();
17088 break;
17089 }
17090
17091 if (is_partition ())
17092 {
17093 if (flags & 4)
17094 DECL_MODULE_PURVIEW_P (inner) = true;
17095 if (flags & 8)
17096 DECL_MODULE_EXPORT_P (inner) = true;
17097 }
17098
17099 if (tags)
17100 DECL_ATTRIBUTES (inner)
17101 = tree_cons (get_identifier ("abi_tag"), tags, DECL_ATTRIBUTES (inner));
17102
17103 /* Install the namespace. */
17104 (*entity_ary)[entity_lwm + entity_index] = inner;
17105 if (DECL_MODULE_IMPORT_P (inner))
17106 {
17107 bool existed;
17108 unsigned *slot = &entity_map->get_or_insert
17109 (DECL_UID (inner), &existed);
17110 if (existed)
17111 /* If it existed, it should match. */
17112 gcc_checking_assert (inner == (*entity_ary)[*slot]);
17113 else
17114 *slot = entity_lwm + entity_index;
17115 }
17116 }
17117 dump.outdent ();
17118 if (!sec.end (from ()))
17119 return false;
17120 return true;
17121 }
17122
17123 /* Write the binding TABLE to MOD_SNAME_PFX.bnd */
17124
17125 unsigned
17126 module_state::write_bindings (elf_out *to, vec<depset *> sccs, unsigned *crc_p)
17127 {
17128 dump () && dump ("Writing binding table");
17129 dump.indent ();
17130
17131 unsigned num = 0;
17132 bytes_out sec (to);
17133 sec.begin ();
17134
17135 for (unsigned ix = 0; ix != sccs.length (); ix++)
17136 {
17137 depset *b = sccs[ix];
17138 if (b->is_binding ())
17139 {
17140 tree ns = b->get_entity ();
17141 dump () && dump ("Bindings %P section:%u", ns, b->get_name (),
17142 b->section);
17143 sec.u (to->name (b->get_name ()));
17144 write_namespace (sec, b->deps[0]);
17145 sec.u (b->section);
17146 num++;
17147 }
17148 }
17149
17150 sec.end (to, to->name (MOD_SNAME_PFX ".bnd"), crc_p);
17151 dump.outdent ();
17152
17153 return num;
17154 }
17155
17156 /* Read the binding table from MOD_SNAME_PFX.bind. */
17157
17158 bool
17159 module_state::read_bindings (unsigned num, unsigned lwm, unsigned hwm)
17160 {
17161 bytes_in sec;
17162
17163 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".bnd"))
17164 return false;
17165
17166 dump () && dump ("Reading binding table");
17167 dump.indent ();
17168 for (; !sec.get_overrun () && num--;)
17169 {
17170 const char *name = from ()->name (sec.u ());
17171 tree ns = read_namespace (sec);
17172 unsigned snum = sec.u ();
17173
17174 if (!ns || !name || (snum - lwm) >= (hwm - lwm))
17175 sec.set_overrun ();
17176 if (!sec.get_overrun ())
17177 {
17178 tree id = get_identifier (name);
17179 dump () && dump ("Bindings %P section:%u", ns, id, snum);
17180 if (mod && !import_module_binding (ns, id, mod, snum))
17181 break;
17182 }
17183 }
17184
17185 dump.outdent ();
17186 if (!sec.end (from ()))
17187 return false;
17188 return true;
17189 }
17190
17191 /* Write the entity table to MOD_SNAME_PFX.ent
17192
17193 Each entry is a section number. */
17194
17195 void
17196 module_state::write_entities (elf_out *to, vec<depset *> depsets,
17197 unsigned count, unsigned *crc_p)
17198 {
17199 dump () && dump ("Writing entities");
17200 dump.indent ();
17201
17202 bytes_out sec (to);
17203 sec.begin ();
17204
17205 unsigned current = 0;
17206 for (unsigned ix = 0; ix < depsets.length (); ix++)
17207 {
17208 depset *d = depsets[ix];
17209
17210 switch (d->get_entity_kind ())
17211 {
17212 default:
17213 break;
17214
17215 case depset::EK_NAMESPACE:
17216 if (!d->is_import () && d->get_entity () != global_namespace)
17217 {
17218 gcc_checking_assert (d->cluster == current);
17219 current++;
17220 sec.u (0);
17221 }
17222 break;
17223
17224 case depset::EK_DECL:
17225 case depset::EK_SPECIALIZATION:
17226 case depset::EK_PARTIAL:
17227 gcc_checking_assert (!d->is_unreached ()
17228 && !d->is_import ()
17229 && d->cluster == current
17230 && d->section);
17231 current++;
17232 sec.u (d->section);
17233 break;
17234 }
17235 }
17236 gcc_assert (count == current);
17237 sec.end (to, to->name (MOD_SNAME_PFX ".ent"), crc_p);
17238 dump.outdent ();
17239 }
17240
17241 bool
17242 module_state::read_entities (unsigned count, unsigned lwm, unsigned hwm)
17243 {
17244 trees_in sec (this);
17245
17246 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".ent"))
17247 return false;
17248
17249 dump () && dump ("Reading entities");
17250 dump.indent ();
17251
17252 for (binding_slot *slot = entity_ary->begin () + entity_lwm; count--; slot++)
17253 {
17254 unsigned snum = sec.u ();
17255 if (snum && (snum - lwm) >= (hwm - lwm))
17256 sec.set_overrun ();
17257 if (sec.get_overrun ())
17258 break;
17259
17260 if (snum)
17261 slot->set_lazy (snum << 2);
17262 }
17263
17264 dump.outdent ();
17265 if (!sec.end (from ()))
17266 return false;
17267 return true;
17268 }
17269
17270 /* Write the pending table to MOD_SNAME_PFX.pnd
17271
17272 The pending table holds information about clusters that need to be
17273 loaded because they contain information about something that is not
17274 found by namespace-scope lookup.
17275
17276 The three cases are:
17277
17278 (a) Template (maybe-partial) specializations that we have
17279 instantiated or defined. When an importer needs to instantiate
17280 that template, they /must have/ the partial, explicit & extern
17281 specializations available. If they have the other specializations
17282 available, they'll have less work to do. Thus, when we're about to
17283 instantiate FOO, we have to be able to ask 'are there any
17284 specialization of FOO in our imports?'.
17285
17286 (b) (Maybe-implicit) member functions definitions. A class could
17287 be defined in one header, and an inline member defined in a
17288 different header (this occurs in the STL). Similarly, like the
17289 specialization case, an implicit member function could have been
17290 'instantiated' in one module, and it'd be nice to not have to
17291 reinstantiate it in another.
17292
17293 (c) Classes completed elsewhere. A class could be declared in one
17294 header and defined in another. We need to know to load the class
17295 definition before looking in it. It does highlight an issue --
17296 there could be an intermediate import between the outermost containing
17297 namespace-scope class and the innermost being-defined class. This is
17298 actually possible with all of these cases, so be aware -- we're not
17299 just talking of one level of import to get to the innermost namespace.
17300
17301 This gets complicated fast, it took me multiple attempts to even
17302 get something remotely working. Partially because I focussed on
17303 optimizing what I think turns out to be a smaller problem, given
17304 the known need to do the more general case *anyway*. I document
17305 the smaller problem, because it does appear to be the natural way
17306 to do it. It's trap!
17307
17308 **** THE TRAP
17309
17310 Let's refer to the primary template or the containing class as the
17311 KEY. And the specialization or member as the PENDING-ENTITY. (To
17312 avoid having to say those mouthfuls all the time.)
17313
17314 In either case, we have an entity and we need some way of mapping
17315 that to a set of entities that need to be loaded before we can
17316 proceed with whatever processing of the entity we were going to do.
17317
17318 We need to link the key to the pending-entity in some way. Given a
17319 key, tell me the pending-entities I need to have loaded. However
17320 we tie the key to the pending-entity must not rely on the key being
17321 loaded -- that'd defeat the lazy loading scheme.
17322
17323 As the key will be an import in we know its entity number (either
17324 because we imported it, or we're writing it out too). Thus we can
17325 generate a map of key-indices to pending-entities. The
17326 pending-entity indices will be into our span of the entity table,
17327 and thus allow them to be lazily loaded. The key index will be
17328 into another slot of the entity table. Notice that this checking
17329 could be expensive, we don't want to iterate over a bunch of
17330 pending-entity indices (across multiple imports), every time we're
17331 about do to the thing with the key. We need to quickly determine
17332 'definitely nothing needed'.
17333
17334 That's almost good enough, except that key indices are not unique
17335 in a couple of cases :( Specifically the Global Module or a module
17336 partition can result in multiple modules assigning an entity index
17337 for the key. The decl-merging on loading will detect that so we
17338 only have one Key loaded, and in the entity hash it'll indicate the
17339 entity index of first load. Which might be different to how we
17340 know it. Notice this is restricted to GM entities or this-module
17341 entities. Foreign imports cannot have this.
17342
17343 We can simply resolve this in the direction of how this module
17344 referred to the key to how the importer knows it. Look in the
17345 entity table slot that we nominate, maybe lazy load it, and then
17346 lookup the resultant entity in the entity hash to learn how the
17347 importer knows it.
17348
17349 But we need to go in the other direction :( Given the key, find all
17350 the index-aliases of that key. We can partially solve that by
17351 adding an alias hash table. Whenever we load a merged decl, add or
17352 augment a mapping from the entity (or its entity-index) to the
17353 newly-discovered index. Then when we look for pending entities of
17354 a key, we also iterate over this aliases this mapping provides.
17355
17356 But that requires the alias to be loaded. And that's not
17357 necessarily true.
17358
17359 *** THE SIMPLER WAY
17360
17361 The remaining fixed thing we have is the innermost namespace
17362 containing the ultimate namespace-scope container of the key and
17363 the name of that container (which might be the key itself). I.e. a
17364 namespace-decl/identifier/module tuple. Let's call this the
17365 top-key. We'll discover that the module is not important here,
17366 because of cross-module possibilities mentioned in case #c above.
17367 We can't markup namespace-binding slots. The best we can do is
17368 mark the binding vector with 'there's something here', and have
17369 another map from namespace/identifier pairs to a vector of pending
17370 entity indices.
17371
17372 Maintain a pending-entity map. This is keyed by top-key, and
17373 maps to a vector of pending-entity indices. On the binding vector
17374 have flags saying whether the pending-name-entity map has contents.
17375 (We might want to further extend the key to be GM-vs-Partition and
17376 specialization-vs-member, but let's not get ahead of ourselves.)
17377
17378 For every key-like entity, find the outermost namespace-scope
17379 name. Use that to lookup in the pending-entity map and then make
17380 sure the specified entities are loaded.
17381
17382 An optimization might be to have a flag in each key-entity saying
17383 that its top key might be in the entity table. It's not clear to
17384 me how to set that flag cheaply -- cheaper than just looking.
17385
17386 FIXME: It'd be nice to have a bit in decls to tell us whether to
17387 even try this. We can have a 'already done' flag, that we set when
17388 we've done KLASS's lazy pendings. When we import a module that
17389 registers pendings on the same top-key as KLASS we need to clear
17390 the flag. A recursive walk of the top-key clearing the bit will
17391 suffice. Plus we only need to recurse on classes that have the bit
17392 set. (That means we need to set the bit on parents of KLASS here,
17393 don't forget.) However, first: correctness, second: efficiency. */
17394
17395 unsigned
17396 module_state::write_pendings (elf_out *to, vec<depset *> depsets,
17397 depset::hash &table, unsigned *crc_p)
17398 {
17399 dump () && dump ("Writing pending-entities");
17400 dump.indent ();
17401
17402 trees_out sec (to, this, table);
17403 sec.begin ();
17404
17405 unsigned count = 0;
17406 tree cache_ns = NULL_TREE;
17407 tree cache_id = NULL_TREE;
17408 unsigned cache_section = ~0;
17409 for (unsigned ix = 0; ix < depsets.length (); ix++)
17410 {
17411 depset *d = depsets[ix];
17412
17413 if (d->is_binding ())
17414 continue;
17415
17416 if (d->is_import ())
17417 continue;
17418
17419 if (!d->is_pending_entity ())
17420 continue;
17421
17422 tree key_decl = nullptr;
17423 tree key_ns = find_pending_key (d->get_entity (), &key_decl);
17424 tree key_name = DECL_NAME (key_decl);
17425
17426 if (IDENTIFIER_ANON_P (key_name))
17427 {
17428 gcc_checking_assert (IDENTIFIER_LAMBDA_P (key_name));
17429 if (tree attached = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (key_decl)))
17430 key_name = DECL_NAME (attached);
17431 else
17432 {
17433 /* There's nothing to attach it to. Must
17434 always reinstantiate. */
17435 dump ()
17436 && dump ("Unattached lambda %N[%u] section:%u",
17437 d->get_entity_kind () == depset::EK_DECL
17438 ? "Member" : "Specialization", d->get_entity (),
17439 d->cluster, d->section);
17440 continue;
17441 }
17442 }
17443
17444 char const *also = "";
17445 if (d->section == cache_section
17446 && key_ns == cache_ns
17447 && key_name == cache_id)
17448 /* Same section & key as previous, no need to repeat ourselves. */
17449 also = "also ";
17450 else
17451 {
17452 cache_ns = key_ns;
17453 cache_id = key_name;
17454 cache_section = d->section;
17455 gcc_checking_assert (table.find_dependency (cache_ns));
17456 sec.tree_node (cache_ns);
17457 sec.tree_node (cache_id);
17458 sec.u (d->cluster);
17459 count++;
17460 }
17461 dump () && dump ("Pending %s %N entity:%u section:%u %skeyed to %P",
17462 d->get_entity_kind () == depset::EK_DECL
17463 ? "member" : "specialization", d->get_entity (),
17464 d->cluster, cache_section, also, cache_ns, cache_id);
17465 }
17466 sec.end (to, to->name (MOD_SNAME_PFX ".pnd"), crc_p);
17467 dump.outdent ();
17468
17469 return count;
17470 }
17471
17472 bool
17473 module_state::read_pendings (unsigned count)
17474 {
17475 trees_in sec (this);
17476
17477 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".pnd"))
17478 return false;
17479
17480 dump () && dump ("Reading %u pendings", count);
17481 dump.indent ();
17482
17483 for (unsigned ix = 0; ix != count; ix++)
17484 {
17485 pending_key key;
17486 unsigned index;
17487
17488 key.ns = sec.tree_node ();
17489 key.id = sec.tree_node ();
17490 index = sec.u ();
17491
17492 if (!key.ns || !key.id
17493 || !(TREE_CODE (key.ns) == NAMESPACE_DECL
17494 && !DECL_NAMESPACE_ALIAS (key.ns))
17495 || !identifier_p (key.id)
17496 || index >= entity_num)
17497 sec.set_overrun ();
17498
17499 if (sec.get_overrun ())
17500 break;
17501
17502 dump () && dump ("Pending:%u keyed to %P", index, key.ns, key.id);
17503
17504 index += entity_lwm;
17505 auto &vec = pending_table->get_or_insert (key);
17506 vec.safe_push (index);
17507 }
17508
17509 dump.outdent ();
17510 if (!sec.end (from ()))
17511 return false;
17512 return true;
17513 }
17514
17515 /* Read & write locations. */
17516 enum loc_kind {
17517 LK_ORDINARY,
17518 LK_MACRO,
17519 LK_IMPORT_ORDINARY,
17520 LK_IMPORT_MACRO,
17521 LK_ADHOC,
17522 LK_RESERVED,
17523 };
17524
17525 static const module_state *
17526 module_for_ordinary_loc (location_t loc)
17527 {
17528 unsigned pos = 0;
17529 unsigned len = ool->length () - pos;
17530
17531 while (len)
17532 {
17533 unsigned half = len / 2;
17534 module_state *probe = (*ool)[pos + half];
17535 if (loc < probe->ordinary_locs.first)
17536 len = half;
17537 else if (loc < probe->ordinary_locs.first + probe->ordinary_locs.second)
17538 return probe;
17539 else
17540 {
17541 pos += half + 1;
17542 len = len - (half + 1);
17543 }
17544 }
17545
17546 return nullptr;
17547 }
17548
17549 static const module_state *
17550 module_for_macro_loc (location_t loc)
17551 {
17552 unsigned pos = 1;
17553 unsigned len = modules->length () - pos;
17554
17555 while (len)
17556 {
17557 unsigned half = len / 2;
17558 module_state *probe = (*modules)[pos + half];
17559 if (loc < probe->macro_locs.first)
17560 {
17561 pos += half + 1;
17562 len = len - (half + 1);
17563 }
17564 else if (loc >= probe->macro_locs.first + probe->macro_locs.second)
17565 len = half;
17566 else
17567 return probe;
17568 }
17569
17570 return NULL;
17571 }
17572
17573 location_t
17574 module_state::imported_from () const
17575 {
17576 location_t from = loc;
17577 line_map_ordinary const *fmap
17578 = linemap_check_ordinary (linemap_lookup (line_table, from));
17579
17580 if (MAP_MODULE_P (fmap))
17581 from = linemap_included_from (fmap);
17582
17583 return from;
17584 }
17585
17586 /* Note that LOC will need writing. This allows us to prune locations
17587 that are not needed. */
17588
17589 bool
17590 module_state::note_location (location_t loc)
17591 {
17592 bool added = false;
17593 if (!macro_loc_table && !ord_loc_table)
17594 ;
17595 else if (loc < RESERVED_LOCATION_COUNT)
17596 ;
17597 else if (IS_ADHOC_LOC (loc))
17598 {
17599 location_t locus = get_location_from_adhoc_loc (line_table, loc);
17600 note_location (locus);
17601 source_range range = get_range_from_loc (line_table, loc);
17602 if (range.m_start != locus)
17603 note_location (range.m_start);
17604 note_location (range.m_finish);
17605 }
17606 else if (loc >= LINEMAPS_MACRO_LOWEST_LOCATION (line_table))
17607 {
17608 if (spans.macro (loc))
17609 {
17610 const line_map *map = linemap_lookup (line_table, loc);
17611 const line_map_macro *mac_map = linemap_check_macro (map);
17612 hashval_t hv = macro_loc_traits::hash (mac_map);
17613 macro_loc_info *slot
17614 = macro_loc_table->find_slot_with_hash (mac_map, hv, INSERT);
17615 if (!slot->src)
17616 {
17617 slot->src = mac_map;
17618 slot->remap = 0;
17619 // Expansion locations could themselves be from a
17620 // macro, we need to note them all.
17621 note_location (mac_map->m_expansion);
17622 gcc_checking_assert (mac_map->n_tokens);
17623 location_t tloc = UNKNOWN_LOCATION;
17624 for (unsigned ix = mac_map->n_tokens * 2; ix--;)
17625 if (mac_map->macro_locations[ix] != tloc)
17626 {
17627 tloc = mac_map->macro_locations[ix];
17628 note_location (tloc);
17629 }
17630 added = true;
17631 }
17632 }
17633 }
17634 else if (IS_ORDINARY_LOC (loc))
17635 {
17636 if (spans.ordinary (loc))
17637 {
17638 const line_map *map = linemap_lookup (line_table, loc);
17639 const line_map_ordinary *ord_map = linemap_check_ordinary (map);
17640 ord_loc_info lkup;
17641 lkup.src = ord_map;
17642 lkup.span = loc_one << ord_map->m_column_and_range_bits;
17643 lkup.offset = (loc - MAP_START_LOCATION (ord_map)) & ~(lkup.span - 1);
17644 lkup.remap = 0;
17645 ord_loc_info *slot = (ord_loc_table->find_slot_with_hash
17646 (lkup, ord_loc_traits::hash (lkup), INSERT));
17647 if (!slot->src)
17648 {
17649 *slot = lkup;
17650 added = true;
17651 }
17652 }
17653 }
17654 else
17655 gcc_unreachable ();
17656 return added;
17657 }
17658
17659 /* If we're not streaming, record that we need location LOC.
17660 Otherwise stream it. */
17661
17662 void
17663 module_state::write_location (bytes_out &sec, location_t loc)
17664 {
17665 if (!sec.streaming_p ())
17666 {
17667 note_location (loc);
17668 return;
17669 }
17670
17671 if (loc < RESERVED_LOCATION_COUNT)
17672 {
17673 dump (dumper::LOCATION) && dump ("Reserved location %K", loc);
17674 sec.loc (LK_RESERVED + loc);
17675 }
17676 else if (IS_ADHOC_LOC (loc))
17677 {
17678 dump (dumper::LOCATION) && dump ("Adhoc location");
17679 sec.u (LK_ADHOC);
17680 location_t locus = get_location_from_adhoc_loc (line_table, loc);
17681 write_location (sec, locus);
17682 source_range range = get_range_from_loc (line_table, loc);
17683 if (range.m_start == locus)
17684 /* Compress. */
17685 range.m_start = UNKNOWN_LOCATION;
17686 write_location (sec, range.m_start);
17687 write_location (sec, range.m_finish);
17688 unsigned discriminator = get_discriminator_from_adhoc_loc (line_table, loc);
17689 sec.u (discriminator);
17690 }
17691 else if (loc >= LINEMAPS_MACRO_LOWEST_LOCATION (line_table))
17692 {
17693 const macro_loc_info *info = nullptr;
17694 line_map_uint_t offset = 0;
17695 if (unsigned hwm = macro_loc_remap->length ())
17696 {
17697 info = macro_loc_remap->begin ();
17698 while (hwm != 1)
17699 {
17700 unsigned mid = hwm / 2;
17701 if (MAP_START_LOCATION (info[mid].src) <= loc)
17702 {
17703 info += mid;
17704 hwm -= mid;
17705 }
17706 else
17707 hwm = mid;
17708 }
17709 offset = loc - MAP_START_LOCATION (info->src);
17710 if (offset > info->src->n_tokens)
17711 info = nullptr;
17712 }
17713
17714 gcc_checking_assert (bool (info) == bool (spans.macro (loc)));
17715
17716 if (info)
17717 {
17718 offset += info->remap;
17719 sec.u (LK_MACRO);
17720 sec.loc (offset);
17721 dump (dumper::LOCATION)
17722 && dump ("Macro location %K output %K", loc, offset);
17723 }
17724 else if (const module_state *import = module_for_macro_loc (loc))
17725 {
17726 auto off = loc - import->macro_locs.first;
17727 sec.u (LK_IMPORT_MACRO);
17728 sec.u (import->remap);
17729 sec.loc (off);
17730 dump (dumper::LOCATION)
17731 && dump ("Imported macro location %K output %u:%K",
17732 loc, import->remap, off);
17733 }
17734 else
17735 gcc_unreachable ();
17736 }
17737 else if (IS_ORDINARY_LOC (loc))
17738 {
17739 /* If we ran out of locations for imported decls, this location could
17740 be a module unit's location. In that case, remap the location
17741 to be where we imported the module from. */
17742 if (spans.locations_exhausted_p () || CHECKING_P)
17743 {
17744 const line_map_ordinary *map
17745 = linemap_check_ordinary (linemap_lookup (line_table, loc));
17746 if (MAP_MODULE_P (map) && loc == MAP_START_LOCATION (map))
17747 {
17748 gcc_checking_assert (spans.locations_exhausted_p ());
17749 write_location (sec, linemap_included_from (map));
17750 return;
17751 }
17752 }
17753
17754 const ord_loc_info *info = nullptr;
17755 line_map_uint_t offset = 0;
17756 if (line_map_uint_t hwm = ord_loc_remap->length ())
17757 {
17758 info = ord_loc_remap->begin ();
17759 while (hwm != 1)
17760 {
17761 auto mid = hwm / 2;
17762 if (MAP_START_LOCATION (info[mid].src) + info[mid].offset <= loc)
17763 {
17764 info += mid;
17765 hwm -= mid;
17766 }
17767 else
17768 hwm = mid;
17769 }
17770 offset = loc - MAP_START_LOCATION (info->src) - info->offset;
17771 if (offset > info->span)
17772 info = nullptr;
17773 }
17774
17775 gcc_checking_assert (bool (info) == bool (spans.ordinary (loc)));
17776
17777 if (info)
17778 {
17779 offset += info->remap;
17780 sec.u (LK_ORDINARY);
17781 sec.loc (offset);
17782
17783 dump (dumper::LOCATION)
17784 && dump ("Ordinary location %K output %K", loc, offset);
17785 }
17786 else if (const module_state *import = module_for_ordinary_loc (loc))
17787 {
17788 auto off = loc - import->ordinary_locs.first;
17789 sec.u (LK_IMPORT_ORDINARY);
17790 sec.u (import->remap);
17791 sec.loc (off);
17792 dump (dumper::LOCATION)
17793 && dump ("Imported ordinary location %K output %u:%K",
17794 loc, import->remap, off);
17795 }
17796 else
17797 gcc_unreachable ();
17798 }
17799 else
17800 gcc_unreachable ();
17801 }
17802
17803 location_t
17804 module_state::read_location (bytes_in &sec) const
17805 {
17806 location_t locus = UNKNOWN_LOCATION;
17807 unsigned kind = sec.u ();
17808 switch (kind)
17809 {
17810 default:
17811 {
17812 if (kind < LK_RESERVED + RESERVED_LOCATION_COUNT)
17813 locus = location_t (kind - LK_RESERVED);
17814 else
17815 sec.set_overrun ();
17816 dump (dumper::LOCATION)
17817 && dump ("Reserved location %K", locus);
17818 }
17819 break;
17820
17821 case LK_ADHOC:
17822 {
17823 dump (dumper::LOCATION) && dump ("Adhoc location");
17824 locus = read_location (sec);
17825 source_range range;
17826 range.m_start = read_location (sec);
17827 if (range.m_start == UNKNOWN_LOCATION)
17828 range.m_start = locus;
17829 range.m_finish = read_location (sec);
17830 unsigned discriminator = sec.u ();
17831 if (locus != loc && range.m_start != loc && range.m_finish != loc)
17832 locus = line_table->get_or_create_combined_loc (locus, range,
17833 nullptr, discriminator);
17834 }
17835 break;
17836
17837 case LK_MACRO:
17838 {
17839 auto off = sec.loc ();
17840
17841 if (macro_locs.second)
17842 {
17843 if (off < macro_locs.second)
17844 locus = off + macro_locs.first;
17845 else
17846 sec.set_overrun ();
17847 }
17848 else
17849 locus = loc;
17850 dump (dumper::LOCATION)
17851 && dump ("Macro %K becoming %K", off, locus);
17852 }
17853 break;
17854
17855 case LK_ORDINARY:
17856 {
17857 auto off = sec.loc ();
17858 if (ordinary_locs.second)
17859 {
17860 if (off < ordinary_locs.second)
17861 locus = off + ordinary_locs.first;
17862 else
17863 sec.set_overrun ();
17864 }
17865 else
17866 locus = loc;
17867
17868 dump (dumper::LOCATION)
17869 && dump ("Ordinary location %K becoming %K", off, locus);
17870 }
17871 break;
17872
17873 case LK_IMPORT_MACRO:
17874 case LK_IMPORT_ORDINARY:
17875 {
17876 unsigned mod = sec.u ();
17877 location_t off = sec.loc ();
17878 const module_state *import = NULL;
17879
17880 if (!mod && !slurp->remap)
17881 /* This is an early read of a partition location during the
17882 read of our ordinary location map. */
17883 import = this;
17884 else
17885 {
17886 mod = slurp->remap_module (mod);
17887 if (!mod)
17888 sec.set_overrun ();
17889 else
17890 import = (*modules)[mod];
17891 }
17892
17893 if (import)
17894 {
17895 if (kind == LK_IMPORT_MACRO)
17896 {
17897 if (!import->macro_locs.second)
17898 locus = import->loc;
17899 else if (off < import->macro_locs.second)
17900 locus = off + import->macro_locs.first;
17901 else
17902 sec.set_overrun ();
17903 }
17904 else
17905 {
17906 if (!import->ordinary_locs.second)
17907 locus = import->loc;
17908 else if (off < import->ordinary_locs.second)
17909 locus = import->ordinary_locs.first + off;
17910 else
17911 sec.set_overrun ();
17912 }
17913 }
17914 }
17915 break;
17916 }
17917
17918 return locus;
17919 }
17920
17921 /* Allocate hash tables to record needed locations. */
17922
17923 void
17924 module_state::write_init_maps ()
17925 {
17926 macro_loc_table = new hash_table<macro_loc_traits> (EXPERIMENT (1, 400));
17927 ord_loc_table = new hash_table<ord_loc_traits> (EXPERIMENT (1, 400));
17928 }
17929
17930 /* Prepare the span adjustments. We prune unneeded locations -- at
17931 this point every needed location must have been seen by
17932 note_location. */
17933
17934 range_t
17935 module_state::write_prepare_maps (module_state_config *cfg, bool has_partitions)
17936 {
17937 dump () && dump ("Preparing locations");
17938 dump.indent ();
17939
17940 dump () && dump ("Reserved locations [%K,%K) macro [%K,%K)",
17941 spans[loc_spans::SPAN_RESERVED].ordinary.first,
17942 spans[loc_spans::SPAN_RESERVED].ordinary.second,
17943 spans[loc_spans::SPAN_RESERVED].macro.first,
17944 spans[loc_spans::SPAN_RESERVED].macro.second);
17945
17946 range_t info {0, 0};
17947
17948 // Sort the noted lines.
17949 vec_alloc (ord_loc_remap, ord_loc_table->size ());
17950 for (auto iter = ord_loc_table->begin (), end = ord_loc_table->end ();
17951 iter != end; ++iter)
17952 ord_loc_remap->quick_push (*iter);
17953 ord_loc_remap->qsort (&ord_loc_info::compare);
17954
17955 // Note included-from maps.
17956 bool added = false;
17957 const line_map_ordinary *current = nullptr;
17958 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
17959 iter != end; ++iter)
17960 if (iter->src != current)
17961 {
17962 current = iter->src;
17963 for (auto probe = current;
17964 auto from = linemap_included_from (probe);
17965 probe = linemap_check_ordinary (linemap_lookup (line_table, from)))
17966 {
17967 if (has_partitions)
17968 {
17969 // Partition locations need to elide their module map
17970 // entry.
17971 probe
17972 = linemap_check_ordinary (linemap_lookup (line_table, from));
17973 if (MAP_MODULE_P (probe))
17974 from = linemap_included_from (probe);
17975 }
17976
17977 if (!note_location (from))
17978 break;
17979 added = true;
17980 }
17981 }
17982 if (added)
17983 {
17984 // Reconstruct the line array as we added items to the hash table.
17985 vec_free (ord_loc_remap);
17986 vec_alloc (ord_loc_remap, ord_loc_table->size ());
17987 for (auto iter = ord_loc_table->begin (), end = ord_loc_table->end ();
17988 iter != end; ++iter)
17989 ord_loc_remap->quick_push (*iter);
17990 ord_loc_remap->qsort (&ord_loc_info::compare);
17991 }
17992 delete ord_loc_table;
17993 ord_loc_table = nullptr;
17994
17995 // Merge (sufficiently) adjacent spans, and calculate remapping.
17996 constexpr line_map_uint_t adjacency = 2; // Allow 2 missing lines.
17997 auto begin = ord_loc_remap->begin (), end = ord_loc_remap->end ();
17998 auto dst = begin;
17999 line_map_uint_t offset = 0;
18000 unsigned range_bits = 0;
18001 ord_loc_info *base = nullptr;
18002 for (auto iter = begin; iter != end; ++iter)
18003 {
18004 if (base && iter->src == base->src)
18005 {
18006 if (base->offset + base->span +
18007 ((adjacency << base->src->m_column_and_range_bits)
18008 // If there are few c&r bits, allow further separation.
18009 | (adjacency << 4))
18010 >= iter->offset)
18011 {
18012 // Merge.
18013 offset -= base->span;
18014 base->span = iter->offset + iter->span - base->offset;
18015 offset += base->span;
18016 continue;
18017 }
18018 }
18019 else if (range_bits < iter->src->m_range_bits)
18020 range_bits = iter->src->m_range_bits;
18021
18022 offset += ((loc_one << iter->src->m_range_bits) - 1);
18023 offset &= ~((loc_one << iter->src->m_range_bits) - 1);
18024 iter->remap = offset;
18025 offset += iter->span;
18026 base = dst;
18027 *dst++ = *iter;
18028 }
18029 ord_loc_remap->truncate (dst - begin);
18030
18031 info.first = ord_loc_remap->length ();
18032 cfg->ordinary_locs = offset;
18033 cfg->loc_range_bits = range_bits;
18034 dump () && dump ("Ordinary maps:%K locs:%K range_bits:%u",
18035 info.first,
18036 cfg->ordinary_locs,
18037 cfg->loc_range_bits);
18038
18039 // Remap the macro locations.
18040 vec_alloc (macro_loc_remap, macro_loc_table->size ());
18041 for (auto iter = macro_loc_table->begin (), end = macro_loc_table->end ();
18042 iter != end; ++iter)
18043 macro_loc_remap->quick_push (*iter);
18044 delete macro_loc_table;
18045 macro_loc_table = nullptr;
18046
18047 macro_loc_remap->qsort (&macro_loc_info::compare);
18048 offset = 0;
18049 for (auto iter = macro_loc_remap->begin (), end = macro_loc_remap->end ();
18050 iter != end; ++iter)
18051 {
18052 auto mac = iter->src;
18053 iter->remap = offset;
18054 offset += mac->n_tokens;
18055 }
18056 info.second = macro_loc_remap->length ();
18057 cfg->macro_locs = offset;
18058
18059 dump () && dump ("Macro maps:%K locs:%K", info.second, cfg->macro_locs);
18060
18061 dump.outdent ();
18062
18063 // If we have no ordinary locs, we must also have no macro locs.
18064 gcc_checking_assert (cfg->ordinary_locs || !cfg->macro_locs);
18065
18066 return info;
18067 }
18068
18069 bool
18070 module_state::read_prepare_maps (const module_state_config *cfg)
18071 {
18072 location_t ordinary = line_table->highest_location + 1;
18073 ordinary += cfg->ordinary_locs;
18074
18075 location_t macro = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
18076 macro -= cfg->macro_locs;
18077
18078 if (ordinary < LINE_MAP_MAX_LOCATION_WITH_COLS
18079 && macro >= LINE_MAP_MAX_LOCATION)
18080 /* OK, we have enough locations. */
18081 return true;
18082
18083 ordinary_locs.first = ordinary_locs.second = 0;
18084 macro_locs.first = macro_locs.second = 0;
18085
18086 spans.report_location_exhaustion (loc);
18087
18088 return false;
18089 }
18090
18091 /* Write & read the location maps. Not called if there are no
18092 locations. */
18093
18094 void
18095 module_state::write_ordinary_maps (elf_out *to, range_t &info,
18096 bool has_partitions, unsigned *crc_p)
18097 {
18098 dump () && dump ("Writing ordinary location maps");
18099 dump.indent ();
18100
18101 vec<const char *> filenames;
18102 filenames.create (20);
18103
18104 /* Determine the unique filenames. */
18105 const line_map_ordinary *current = nullptr;
18106 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
18107 iter != end; ++iter)
18108 if (iter->src != current)
18109 {
18110 current = iter->src;
18111 const char *fname = ORDINARY_MAP_FILE_NAME (iter->src);
18112
18113 /* We should never find a module linemap in an interval. */
18114 gcc_checking_assert (!MAP_MODULE_P (iter->src));
18115
18116 /* We expect very few filenames, so just an array.
18117 (Not true when headers are still in play :() */
18118 for (unsigned jx = filenames.length (); jx--;)
18119 {
18120 const char *name = filenames[jx];
18121 if (0 == strcmp (name, fname))
18122 {
18123 /* Reset the linemap's name, because for things like
18124 preprocessed input we could have multiple instances
18125 of the same name, and we'd rather not percolate
18126 that. */
18127 const_cast<line_map_ordinary *> (iter->src)->to_file = name;
18128 fname = NULL;
18129 break;
18130 }
18131 }
18132 if (fname)
18133 filenames.safe_push (fname);
18134 }
18135
18136 bytes_out sec (to);
18137 sec.begin ();
18138
18139 /* Write the filenames. */
18140 unsigned len = filenames.length ();
18141 sec.u (len);
18142 dump () && dump ("%u source file names", len);
18143 for (unsigned ix = 0; ix != len; ix++)
18144 {
18145 const char *fname = filenames[ix];
18146 dump (dumper::LOCATION) && dump ("Source file[%u]=%s", ix, fname);
18147 sec.str (fname);
18148 }
18149
18150 sec.loc (info.first); /* Num maps. */
18151 const ord_loc_info *base = nullptr;
18152 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
18153 iter != end; ++iter)
18154 {
18155 dump (dumper::LOCATION)
18156 && dump ("Span:%K ordinary [%K+%K,+%K)->[%K,+%K)",
18157 (location_t) (iter - ord_loc_remap->begin ()),
18158 MAP_START_LOCATION (iter->src),
18159 iter->offset, iter->span, iter->remap,
18160 iter->span);
18161
18162 if (!base || iter->src != base->src)
18163 base = iter;
18164 sec.loc (iter->offset - base->offset);
18165 if (base == iter)
18166 {
18167 sec.u (iter->src->sysp);
18168 sec.u (iter->src->m_range_bits);
18169 sec.u (iter->src->m_column_and_range_bits - iter->src->m_range_bits);
18170
18171 const char *fname = ORDINARY_MAP_FILE_NAME (iter->src);
18172 for (unsigned ix = 0; ix != filenames.length (); ix++)
18173 if (filenames[ix] == fname)
18174 {
18175 sec.u (ix);
18176 break;
18177 }
18178 unsigned line = ORDINARY_MAP_STARTING_LINE_NUMBER (iter->src);
18179 line += iter->offset >> iter->src->m_column_and_range_bits;
18180 sec.u (line);
18181 }
18182 sec.loc (iter->remap);
18183 if (base == iter)
18184 {
18185 /* Write the included from location, which means reading it
18186 while reading in the ordinary maps. So we'd better not
18187 be getting ahead of ourselves. */
18188 location_t from = linemap_included_from (iter->src);
18189 gcc_checking_assert (from < MAP_START_LOCATION (iter->src));
18190 if (from != UNKNOWN_LOCATION && has_partitions)
18191 {
18192 /* A partition's span will have a from pointing at a
18193 MODULE_INC. Find that map's from. */
18194 line_map_ordinary const *fmap
18195 = linemap_check_ordinary (linemap_lookup (line_table, from));
18196 if (MAP_MODULE_P (fmap))
18197 from = linemap_included_from (fmap);
18198 }
18199 write_location (sec, from);
18200 }
18201 }
18202
18203 filenames.release ();
18204
18205 sec.end (to, to->name (MOD_SNAME_PFX ".olm"), crc_p);
18206 dump.outdent ();
18207 }
18208
18209 void
18210 module_state::write_macro_maps (elf_out *to, range_t &info, unsigned *crc_p)
18211 {
18212 dump () && dump ("Writing macro location maps");
18213 dump.indent ();
18214
18215 bytes_out sec (to);
18216 sec.begin ();
18217
18218 dump () && dump ("Macro maps:%K", info.second);
18219 sec.loc (info.second);
18220
18221 line_map_uint_t macro_num = 0;
18222 for (auto iter = macro_loc_remap->end (), begin = macro_loc_remap->begin ();
18223 iter-- != begin;)
18224 {
18225 auto mac = iter->src;
18226 sec.loc (iter->remap);
18227 sec.u (mac->n_tokens);
18228 sec.cpp_node (mac->macro);
18229 write_location (sec, mac->m_expansion);
18230 const location_t *locs = mac->macro_locations;
18231 /* There are lots of identical runs. */
18232 location_t prev = UNKNOWN_LOCATION;
18233 unsigned count = 0;
18234 unsigned runs = 0;
18235 for (unsigned jx = mac->n_tokens * 2; jx--;)
18236 {
18237 location_t tok_loc = locs[jx];
18238 if (tok_loc == prev)
18239 {
18240 count++;
18241 continue;
18242 }
18243 runs++;
18244 sec.u (count);
18245 count = 1;
18246 prev = tok_loc;
18247 write_location (sec, tok_loc);
18248 }
18249 sec.u (count);
18250 dump (dumper::LOCATION)
18251 && dump ("Macro:%K %I %u/%u*2 locations [%K,%K)->%K",
18252 macro_num, identifier (mac->macro),
18253 runs, mac->n_tokens,
18254 MAP_START_LOCATION (mac),
18255 MAP_START_LOCATION (mac) + mac->n_tokens,
18256 iter->remap);
18257 macro_num++;
18258 }
18259 gcc_assert (macro_num == info.second);
18260
18261 sec.end (to, to->name (MOD_SNAME_PFX ".mlm"), crc_p);
18262 dump.outdent ();
18263 }
18264
18265 bool
18266 module_state::read_ordinary_maps (line_map_uint_t num_ord_locs,
18267 unsigned range_bits)
18268 {
18269 bytes_in sec;
18270
18271 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".olm"))
18272 return false;
18273 dump () && dump ("Reading ordinary location maps");
18274 dump.indent ();
18275
18276 /* Read the filename table. */
18277 unsigned len = sec.u ();
18278 dump () && dump ("%u source file names", len);
18279 vec<const char *> filenames;
18280 filenames.create (len);
18281 for (unsigned ix = 0; ix != len; ix++)
18282 {
18283 size_t l;
18284 const char *buf = sec.str (&l);
18285 char *fname = XNEWVEC (char, l + 1);
18286 memcpy (fname, buf, l + 1);
18287 dump (dumper::LOCATION) && dump ("Source file[%u]=%s", ix, fname);
18288 /* We leak these names into the line-map table. But it
18289 doesn't own them. */
18290 filenames.quick_push (fname);
18291 }
18292
18293 line_map_uint_t num_ordinary = sec.loc ();
18294 dump () && dump ("Ordinary maps:%K, range_bits:%u",
18295 num_ordinary, range_bits);
18296
18297 location_t offset = line_table->highest_location + 1;
18298 offset += ((loc_one << range_bits) - 1);
18299 offset &= ~((loc_one << range_bits) - 1);
18300 ordinary_locs.first = offset;
18301
18302 bool propagated = spans.maybe_propagate (this, offset);
18303 line_map_ordinary *maps = static_cast<line_map_ordinary *>
18304 (line_map_new_raw (line_table, false, num_ordinary));
18305
18306 const line_map_ordinary *base = nullptr;
18307 for (line_map_uint_t ix = 0; ix != num_ordinary && !sec.get_overrun (); ix++)
18308 {
18309 line_map_ordinary *map = &maps[ix];
18310
18311 location_t offset = sec.loc ();
18312 if (!offset)
18313 {
18314 map->reason = LC_RENAME;
18315 map->sysp = sec.u ();
18316 map->m_range_bits = sec.u ();
18317 map->m_column_and_range_bits = sec.u () + map->m_range_bits;
18318 unsigned fnum = sec.u ();
18319 map->to_file = (fnum < filenames.length () ? filenames[fnum] : "");
18320 map->to_line = sec.u ();
18321 base = map;
18322 }
18323 else
18324 {
18325 *map = *base;
18326 map->to_line += offset >> map->m_column_and_range_bits;
18327 }
18328 location_t remap = sec.loc ();
18329 map->start_location = remap + ordinary_locs.first;
18330 if (base == map)
18331 {
18332 /* Root the outermost map at our location. */
18333 ordinary_locs.second = remap;
18334 location_t from = read_location (sec);
18335 map->included_from = from != UNKNOWN_LOCATION ? from : loc;
18336 }
18337 }
18338
18339 ordinary_locs.second = num_ord_locs;
18340 /* highest_location is the one handed out, not the next one to
18341 hand out. */
18342 line_table->highest_location = ordinary_locs.first + ordinary_locs.second - 1;
18343
18344 if (line_table->highest_location >= LINE_MAP_MAX_LOCATION_WITH_COLS)
18345 /* We shouldn't run out of locations, as we checked before
18346 starting. */
18347 sec.set_overrun ();
18348 dump () && dump ("Ordinary location [%K,+%K)",
18349 ordinary_locs.first, ordinary_locs.second);
18350
18351 if (propagated)
18352 spans.close ();
18353
18354 filenames.release ();
18355
18356 dump.outdent ();
18357 if (!sec.end (from ()))
18358 return false;
18359
18360 return true;
18361 }
18362
18363 bool
18364 module_state::read_macro_maps (line_map_uint_t num_macro_locs)
18365 {
18366 bytes_in sec;
18367
18368 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".mlm"))
18369 return false;
18370 dump () && dump ("Reading macro location maps");
18371 dump.indent ();
18372
18373 line_map_uint_t num_macros = sec.loc ();
18374 dump () && dump ("Macro maps:%K locs:%K",
18375 num_macros, num_macro_locs);
18376
18377 bool propagated = spans.maybe_propagate (this,
18378 line_table->highest_location + 1);
18379
18380 location_t offset = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
18381 macro_locs.second = num_macro_locs;
18382 macro_locs.first = offset - num_macro_locs;
18383
18384 dump () && dump ("Macro loc delta %K", offset);
18385 dump () && dump ("Macro locations [%K,%K)",
18386 macro_locs.first, macro_locs.second);
18387
18388 for (line_map_uint_t ix = 0; ix != num_macros && !sec.get_overrun (); ix++)
18389 {
18390 location_t offset = sec.loc ();
18391 unsigned n_tokens = sec.u ();
18392 cpp_hashnode *node = sec.cpp_node ();
18393 location_t exp_loc = read_location (sec);
18394
18395 const line_map_macro *macro
18396 = linemap_enter_macro (line_table, node, exp_loc, n_tokens);
18397 if (!macro)
18398 /* We shouldn't run out of locations, as we checked that we
18399 had enough before starting. */
18400 break;
18401 gcc_checking_assert (MAP_START_LOCATION (macro)
18402 == offset + macro_locs.first);
18403
18404 location_t *locs = macro->macro_locations;
18405 location_t tok_loc = UNKNOWN_LOCATION;
18406 unsigned count = sec.u ();
18407 unsigned runs = 0;
18408 for (unsigned jx = macro->n_tokens * 2; jx-- && !sec.get_overrun ();)
18409 {
18410 while (!count-- && !sec.get_overrun ())
18411 {
18412 runs++;
18413 tok_loc = read_location (sec);
18414 count = sec.u ();
18415 }
18416 locs[jx] = tok_loc;
18417 }
18418 if (count)
18419 sec.set_overrun ();
18420 dump (dumper::LOCATION)
18421 && dump ("Macro:%K %I %u/%u*2 locations [%K,%K)",
18422 ix, identifier (node), runs, n_tokens,
18423 MAP_START_LOCATION (macro),
18424 MAP_START_LOCATION (macro) + n_tokens);
18425 }
18426
18427 dump () && dump ("Macro location lwm:%K", macro_locs.first);
18428 if (propagated)
18429 spans.close ();
18430
18431 dump.outdent ();
18432 if (!sec.end (from ()))
18433 return false;
18434
18435 return true;
18436 }
18437
18438 /* Serialize the definition of MACRO. */
18439
18440 void
18441 module_state::write_define (bytes_out &sec, const cpp_macro *macro)
18442 {
18443 sec.u (macro->count);
18444
18445 bytes_out::bits_out bits = sec.stream_bits ();
18446 bits.b (macro->fun_like);
18447 bits.b (macro->variadic);
18448 bits.b (macro->syshdr);
18449 bits.bflush ();
18450
18451 write_location (sec, macro->line);
18452 if (macro->fun_like)
18453 {
18454 sec.u (macro->paramc);
18455 const cpp_hashnode *const *parms = macro->parm.params;
18456 for (unsigned ix = 0; ix != macro->paramc; ix++)
18457 sec.cpp_node (parms[ix]);
18458 }
18459
18460 unsigned len = 0;
18461 for (unsigned ix = 0; ix != macro->count; ix++)
18462 {
18463 const cpp_token *token = &macro->exp.tokens[ix];
18464 write_location (sec, token->src_loc);
18465 sec.u (token->type);
18466 sec.u (token->flags);
18467 switch (cpp_token_val_index (token))
18468 {
18469 default:
18470 gcc_unreachable ();
18471
18472 case CPP_TOKEN_FLD_ARG_NO:
18473 /* An argument reference. */
18474 sec.u (token->val.macro_arg.arg_no);
18475 sec.cpp_node (token->val.macro_arg.spelling);
18476 break;
18477
18478 case CPP_TOKEN_FLD_NODE:
18479 /* An identifier. */
18480 sec.cpp_node (token->val.node.node);
18481 if (token->val.node.spelling == token->val.node.node)
18482 /* The spelling will usually be the same. so optimize
18483 that. */
18484 sec.str (NULL, 0);
18485 else
18486 sec.cpp_node (token->val.node.spelling);
18487 break;
18488
18489 case CPP_TOKEN_FLD_NONE:
18490 break;
18491
18492 case CPP_TOKEN_FLD_STR:
18493 /* A string, number or comment. Not always NUL terminated,
18494 we stream out in a single contatenation with embedded
18495 NULs as that's a safe default. */
18496 len += token->val.str.len + 1;
18497 sec.u (token->val.str.len);
18498 break;
18499
18500 case CPP_TOKEN_FLD_SOURCE:
18501 case CPP_TOKEN_FLD_TOKEN_NO:
18502 case CPP_TOKEN_FLD_PRAGMA:
18503 /* These do not occur inside a macro itself. */
18504 gcc_unreachable ();
18505 }
18506 }
18507
18508 if (len)
18509 {
18510 char *ptr = reinterpret_cast<char *> (sec.buf (len));
18511 len = 0;
18512 for (unsigned ix = 0; ix != macro->count; ix++)
18513 {
18514 const cpp_token *token = &macro->exp.tokens[ix];
18515 if (cpp_token_val_index (token) == CPP_TOKEN_FLD_STR)
18516 {
18517 memcpy (ptr + len, token->val.str.text,
18518 token->val.str.len);
18519 len += token->val.str.len;
18520 ptr[len++] = 0;
18521 }
18522 }
18523 }
18524 }
18525
18526 /* Read a macro definition. */
18527
18528 cpp_macro *
18529 module_state::read_define (bytes_in &sec, cpp_reader *reader) const
18530 {
18531 unsigned count = sec.u ();
18532 /* We rely on knowing cpp_reader's hash table is ident_hash, and
18533 its subobject allocator is stringpool_ggc_alloc and that is just
18534 a wrapper for ggc_alloc_atomic. */
18535 cpp_macro *macro
18536 = (cpp_macro *)ggc_alloc_atomic (sizeof (cpp_macro)
18537 + sizeof (cpp_token) * (count - !!count));
18538 memset (macro, 0, sizeof (cpp_macro) + sizeof (cpp_token) * (count - !!count));
18539
18540 macro->count = count;
18541 macro->kind = cmk_macro;
18542 macro->imported_p = true;
18543
18544 bytes_in::bits_in bits = sec.stream_bits ();
18545 macro->fun_like = bits.b ();
18546 macro->variadic = bits.b ();
18547 macro->syshdr = bits.b ();
18548 bits.bflush ();
18549
18550 macro->line = read_location (sec);
18551
18552 if (macro->fun_like)
18553 {
18554 unsigned paramc = sec.u ();
18555 cpp_hashnode **params
18556 = (cpp_hashnode **)ggc_alloc_atomic (sizeof (cpp_hashnode *) * paramc);
18557 macro->paramc = paramc;
18558 macro->parm.params = params;
18559 for (unsigned ix = 0; ix != paramc; ix++)
18560 params[ix] = sec.cpp_node ();
18561 }
18562
18563 unsigned len = 0;
18564 for (unsigned ix = 0; ix != count && !sec.get_overrun (); ix++)
18565 {
18566 cpp_token *token = &macro->exp.tokens[ix];
18567 token->src_loc = read_location (sec);
18568 token->type = cpp_ttype (sec.u ());
18569 token->flags = sec.u ();
18570 switch (cpp_token_val_index (token))
18571 {
18572 default:
18573 sec.set_overrun ();
18574 break;
18575
18576 case CPP_TOKEN_FLD_ARG_NO:
18577 /* An argument reference. */
18578 {
18579 unsigned arg_no = sec.u ();
18580 if (arg_no - 1 >= macro->paramc)
18581 sec.set_overrun ();
18582 token->val.macro_arg.arg_no = arg_no;
18583 token->val.macro_arg.spelling = sec.cpp_node ();
18584 }
18585 break;
18586
18587 case CPP_TOKEN_FLD_NODE:
18588 /* An identifier. */
18589 token->val.node.node = sec.cpp_node ();
18590 token->val.node.spelling = sec.cpp_node ();
18591 if (!token->val.node.spelling)
18592 token->val.node.spelling = token->val.node.node;
18593 break;
18594
18595 case CPP_TOKEN_FLD_NONE:
18596 break;
18597
18598 case CPP_TOKEN_FLD_STR:
18599 /* A string, number or comment. */
18600 token->val.str.len = sec.u ();
18601 len += token->val.str.len + 1;
18602 break;
18603 }
18604 }
18605
18606 if (len)
18607 if (const char *ptr = reinterpret_cast<const char *> (sec.buf (len)))
18608 {
18609 /* There should be a final NUL. */
18610 if (ptr[len-1])
18611 sec.set_overrun ();
18612 /* cpp_alloc_token_string will add a final NUL. */
18613 const unsigned char *buf
18614 = cpp_alloc_token_string (reader, (const unsigned char *)ptr, len - 1);
18615 len = 0;
18616 for (unsigned ix = 0; ix != count && !sec.get_overrun (); ix++)
18617 {
18618 cpp_token *token = &macro->exp.tokens[ix];
18619 if (cpp_token_val_index (token) == CPP_TOKEN_FLD_STR)
18620 {
18621 token->val.str.text = buf + len;
18622 len += token->val.str.len;
18623 if (buf[len++])
18624 sec.set_overrun ();
18625 }
18626 }
18627 }
18628
18629 if (sec.get_overrun ())
18630 return NULL;
18631 return macro;
18632 }
18633
18634 /* Exported macro data. */
18635 struct GTY(()) macro_export {
18636 cpp_macro *def;
18637 location_t undef_loc;
18638
18639 macro_export ()
18640 :def (NULL), undef_loc (UNKNOWN_LOCATION)
18641 {
18642 }
18643 };
18644
18645 /* Imported macro data. */
18646 class macro_import {
18647 public:
18648 struct slot {
18649 #if defined (WORDS_BIGENDIAN) && SIZEOF_VOID_P == 8
18650 int offset;
18651 #endif
18652 /* We need to ensure we don't use the LSB for representation, as
18653 that's the union discriminator below. */
18654 unsigned bits;
18655
18656 #if !(defined (WORDS_BIGENDIAN) && SIZEOF_VOID_P == 8)
18657 int offset;
18658 #endif
18659
18660 public:
18661 enum Layout {
18662 L_DEF = 1,
18663 L_UNDEF = 2,
18664 L_BOTH = 3,
18665 L_MODULE_SHIFT = 2
18666 };
18667
18668 public:
18669 /* Not a regular ctor, because we put it in a union, and that's
18670 not allowed in C++ 98. */
18671 static slot ctor (unsigned module, unsigned defness)
18672 {
18673 gcc_checking_assert (defness);
18674 slot s;
18675 s.bits = defness | (module << L_MODULE_SHIFT);
18676 s.offset = -1;
18677 return s;
18678 }
18679
18680 public:
18681 unsigned get_defness () const
18682 {
18683 return bits & L_BOTH;
18684 }
18685 unsigned get_module () const
18686 {
18687 return bits >> L_MODULE_SHIFT;
18688 }
18689 void become_undef ()
18690 {
18691 bits &= ~unsigned (L_DEF);
18692 bits |= unsigned (L_UNDEF);
18693 }
18694 };
18695
18696 private:
18697 typedef vec<slot, va_heap, vl_embed> ary_t;
18698 union either {
18699 /* Discriminated by bits 0|1 != 0. The expected case is that
18700 there will be exactly one slot per macro, hence the effort of
18701 packing that. */
18702 ary_t *ary;
18703 slot single;
18704 } u;
18705
18706 public:
18707 macro_import ()
18708 {
18709 u.ary = NULL;
18710 }
18711
18712 private:
18713 bool single_p () const
18714 {
18715 return u.single.bits & slot::L_BOTH;
18716 }
18717 bool occupied_p () const
18718 {
18719 return u.ary != NULL;
18720 }
18721
18722 public:
18723 unsigned length () const
18724 {
18725 gcc_checking_assert (occupied_p ());
18726 return single_p () ? 1 : u.ary->length ();
18727 }
18728 slot &operator[] (unsigned ix)
18729 {
18730 gcc_checking_assert (occupied_p ());
18731 if (single_p ())
18732 {
18733 gcc_checking_assert (!ix);
18734 return u.single;
18735 }
18736 else
18737 return (*u.ary)[ix];
18738 }
18739
18740 public:
18741 slot &exported ();
18742 slot &append (unsigned module, unsigned defness);
18743 };
18744
18745 /* O is a new import to append to the list for. If we're an empty
18746 set, initialize us. */
18747
18748 macro_import::slot &
18749 macro_import::append (unsigned module, unsigned defness)
18750 {
18751 if (!occupied_p ())
18752 {
18753 u.single = slot::ctor (module, defness);
18754 return u.single;
18755 }
18756 else
18757 {
18758 bool single = single_p ();
18759 ary_t *m = single ? NULL : u.ary;
18760 vec_safe_reserve (m, 1 + single);
18761 if (single)
18762 m->quick_push (u.single);
18763 u.ary = m;
18764 return *u.ary->quick_push (slot::ctor (module, defness));
18765 }
18766 }
18767
18768 /* We're going to export something. Make sure the first import slot
18769 is us. */
18770
18771 macro_import::slot &
18772 macro_import::exported ()
18773 {
18774 if (occupied_p () && !(*this)[0].get_module ())
18775 {
18776 slot &res = (*this)[0];
18777 res.bits |= slot::L_DEF;
18778 return res;
18779 }
18780
18781 slot *a = &append (0, slot::L_DEF);
18782 if (!single_p ())
18783 {
18784 slot &f = (*this)[0];
18785 std::swap (f, *a);
18786 a = &f;
18787 }
18788 return *a;
18789 }
18790
18791 /* The import (&exported) macros. cpp_hasnode's deferred field
18792 indexes this array (offset by 1, so zero means 'not present'. */
18793
18794 static vec<macro_import, va_heap, vl_embed> *macro_imports;
18795
18796 /* The exported macros. A macro_import slot's zeroth element's offset
18797 indexes this array. If the zeroth slot is not for module zero,
18798 there is no export. */
18799
18800 static GTY(()) vec<macro_export, va_gc> *macro_exports;
18801
18802 /* The reachable set of header imports from this TU. */
18803
18804 static GTY(()) bitmap headers;
18805
18806 /* Get the (possibly empty) macro imports for NODE. */
18807
18808 static macro_import &
18809 get_macro_imports (cpp_hashnode *node)
18810 {
18811 if (node->deferred)
18812 return (*macro_imports)[node->deferred - 1];
18813
18814 vec_safe_reserve (macro_imports, 1);
18815 node->deferred = macro_imports->length () + 1;
18816 return *vec_safe_push (macro_imports, macro_import ());
18817 }
18818
18819 /* Get the macro export for export EXP of NODE. */
18820
18821 static macro_export &
18822 get_macro_export (macro_import::slot &slot)
18823 {
18824 if (slot.offset >= 0)
18825 return (*macro_exports)[slot.offset];
18826
18827 vec_safe_reserve (macro_exports, 1);
18828 slot.offset = macro_exports->length ();
18829 return *macro_exports->quick_push (macro_export ());
18830 }
18831
18832 /* If NODE is an exportable macro, add it to the export set. */
18833
18834 static int
18835 maybe_add_macro (cpp_reader *, cpp_hashnode *node, void *data_)
18836 {
18837 bool exporting = false;
18838
18839 if (cpp_user_macro_p (node))
18840 if (cpp_macro *macro = node->value.macro)
18841 /* Ignore imported, builtins, command line and forced header macros. */
18842 if (!macro->imported_p
18843 && !macro->lazy && macro->line >= spans.main_start ())
18844 {
18845 gcc_checking_assert (macro->kind == cmk_macro);
18846 /* I don't want to deal with this corner case, that I suspect is
18847 a devil's advocate reading of the standard. */
18848 gcc_checking_assert (!macro->extra_tokens);
18849
18850 macro_import::slot &slot = get_macro_imports (node).exported ();
18851 macro_export &exp = get_macro_export (slot);
18852 exp.def = macro;
18853 exporting = true;
18854 }
18855
18856 if (!exporting && node->deferred)
18857 {
18858 macro_import &imports = (*macro_imports)[node->deferred - 1];
18859 macro_import::slot &slot = imports[0];
18860 if (!slot.get_module ())
18861 {
18862 gcc_checking_assert (slot.get_defness ());
18863 exporting = true;
18864 }
18865 }
18866
18867 if (exporting)
18868 static_cast<vec<cpp_hashnode *> *> (data_)->safe_push (node);
18869
18870 return 1; /* Don't stop. */
18871 }
18872
18873 /* Order cpp_hashnodes A_ and B_ by their exported macro locations. */
18874
18875 static int
18876 macro_loc_cmp (const void *a_, const void *b_)
18877 {
18878 const cpp_hashnode *node_a = *(const cpp_hashnode *const *)a_;
18879 macro_import &import_a = (*macro_imports)[node_a->deferred - 1];
18880 const macro_export &export_a = (*macro_exports)[import_a[0].offset];
18881 location_t loc_a = export_a.def ? export_a.def->line : export_a.undef_loc;
18882
18883 const cpp_hashnode *node_b = *(const cpp_hashnode *const *)b_;
18884 macro_import &import_b = (*macro_imports)[node_b->deferred - 1];
18885 const macro_export &export_b = (*macro_exports)[import_b[0].offset];
18886 location_t loc_b = export_b.def ? export_b.def->line : export_b.undef_loc;
18887
18888 if (loc_a < loc_b)
18889 return +1;
18890 else if (loc_a > loc_b)
18891 return -1;
18892 else
18893 return 0;
18894 }
18895
18896 /* Gather the macro definitions and undefinitions that we will need to
18897 write out. */
18898
18899 vec<cpp_hashnode *> *
18900 module_state::prepare_macros (cpp_reader *reader)
18901 {
18902 vec<cpp_hashnode *> *macros;
18903 vec_alloc (macros, 100);
18904
18905 cpp_forall_identifiers (reader, maybe_add_macro, macros);
18906
18907 dump (dumper::MACRO) && dump ("No more than %u macros", macros->length ());
18908
18909 macros->qsort (macro_loc_cmp);
18910
18911 // Note the locations.
18912 for (unsigned ix = macros->length (); ix--;)
18913 {
18914 cpp_hashnode *node = (*macros)[ix];
18915 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
18916 macro_export &mac = (*macro_exports)[slot.offset];
18917
18918 if (IDENTIFIER_KEYWORD_P (identifier (node)))
18919 continue;
18920
18921 if (mac.undef_loc != UNKNOWN_LOCATION)
18922 note_location (mac.undef_loc);
18923 if (mac.def)
18924 {
18925 note_location (mac.def->line);
18926 for (unsigned ix = 0; ix != mac.def->count; ix++)
18927 note_location (mac.def->exp.tokens[ix].src_loc);
18928 }
18929 }
18930
18931 return macros;
18932 }
18933
18934 /* Write out the exported defines. This is two sections, one
18935 containing the definitions, the other a table of node names. */
18936
18937 unsigned
18938 module_state::write_macros (elf_out *to, vec<cpp_hashnode *> *macros,
18939 unsigned *crc_p)
18940 {
18941 dump () && dump ("Writing macros");
18942 dump.indent ();
18943
18944 /* Write the defs */
18945 bytes_out sec (to);
18946 sec.begin ();
18947
18948 unsigned count = 0;
18949 for (unsigned ix = macros->length (); ix--;)
18950 {
18951 cpp_hashnode *node = (*macros)[ix];
18952 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
18953 gcc_assert (!slot.get_module () && slot.get_defness ());
18954
18955 macro_export &mac = (*macro_exports)[slot.offset];
18956 gcc_assert (!!(slot.get_defness () & macro_import::slot::L_UNDEF)
18957 == (mac.undef_loc != UNKNOWN_LOCATION)
18958 && !!(slot.get_defness () & macro_import::slot::L_DEF)
18959 == (mac.def != NULL));
18960
18961 if (IDENTIFIER_KEYWORD_P (identifier (node)))
18962 {
18963 warning_at (mac.def->line, 0,
18964 "not exporting %<#define %E%> as it is a keyword",
18965 identifier (node));
18966 slot.offset = 0;
18967 continue;
18968 }
18969
18970 count++;
18971 slot.offset = sec.pos;
18972 dump (dumper::MACRO)
18973 && dump ("Writing macro %s%s%s %I at %u",
18974 slot.get_defness () & macro_import::slot::L_UNDEF
18975 ? "#undef" : "",
18976 slot.get_defness () == macro_import::slot::L_BOTH
18977 ? " & " : "",
18978 slot.get_defness () & macro_import::slot::L_DEF
18979 ? "#define" : "",
18980 identifier (node), slot.offset);
18981 if (mac.undef_loc != UNKNOWN_LOCATION)
18982 write_location (sec, mac.undef_loc);
18983 if (mac.def)
18984 write_define (sec, mac.def);
18985 }
18986 if (count)
18987 // We may have ended on a tokenless macro with a very short
18988 // location, that will cause problems reading its bit flags.
18989 sec.u (0);
18990 sec.end (to, to->name (MOD_SNAME_PFX ".def"), crc_p);
18991
18992 if (count)
18993 {
18994 /* Write the table. */
18995 bytes_out sec (to);
18996 sec.begin ();
18997 sec.u (count);
18998
18999 for (unsigned ix = macros->length (); ix--;)
19000 {
19001 const cpp_hashnode *node = (*macros)[ix];
19002 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
19003
19004 if (slot.offset)
19005 {
19006 sec.cpp_node (node);
19007 sec.u (slot.get_defness ());
19008 sec.u (slot.offset);
19009 }
19010 }
19011 sec.end (to, to->name (MOD_SNAME_PFX ".mac"), crc_p);
19012 }
19013
19014 dump.outdent ();
19015 return count;
19016 }
19017
19018 bool
19019 module_state::read_macros ()
19020 {
19021 /* Get the def section. */
19022 if (!slurp->macro_defs.begin (loc, from (), MOD_SNAME_PFX ".def"))
19023 return false;
19024
19025 /* Get the tbl section, if there are defs. */
19026 if (slurp->macro_defs.more_p ()
19027 && !slurp->macro_tbl.begin (loc, from (), MOD_SNAME_PFX ".mac"))
19028 return false;
19029
19030 return true;
19031 }
19032
19033 /* Install the macro name table. */
19034
19035 void
19036 module_state::install_macros ()
19037 {
19038 bytes_in &sec = slurp->macro_tbl;
19039 if (!sec.size)
19040 return;
19041
19042 dump () && dump ("Reading macro table %M", this);
19043 dump.indent ();
19044
19045 unsigned count = sec.u ();
19046 dump () && dump ("%u macros", count);
19047 while (count--)
19048 {
19049 cpp_hashnode *node = sec.cpp_node ();
19050 macro_import &imp = get_macro_imports (node);
19051 unsigned flags = sec.u () & macro_import::slot::L_BOTH;
19052 if (!flags)
19053 sec.set_overrun ();
19054
19055 if (sec.get_overrun ())
19056 break;
19057
19058 macro_import::slot &slot = imp.append (mod, flags);
19059 slot.offset = sec.u ();
19060
19061 dump (dumper::MACRO)
19062 && dump ("Read %s macro %s%s%s %I at %u",
19063 imp.length () > 1 ? "add" : "new",
19064 flags & macro_import::slot::L_UNDEF ? "#undef" : "",
19065 flags == macro_import::slot::L_BOTH ? " & " : "",
19066 flags & macro_import::slot::L_DEF ? "#define" : "",
19067 identifier (node), slot.offset);
19068
19069 /* We'll leak an imported definition's TOKEN_FLD_STR's data
19070 here. But that only happens when we've had to resolve the
19071 deferred macro before this import -- why are you doing
19072 that? */
19073 if (cpp_macro *cur = cpp_set_deferred_macro (node))
19074 if (!cur->imported_p)
19075 {
19076 macro_import::slot &slot = imp.exported ();
19077 macro_export &exp = get_macro_export (slot);
19078 exp.def = cur;
19079 dump (dumper::MACRO)
19080 && dump ("Saving current #define %I", identifier (node));
19081 }
19082 }
19083
19084 /* We're now done with the table. */
19085 elf_in::release (slurp->from, sec);
19086
19087 dump.outdent ();
19088 }
19089
19090 /* Import the transitive macros. */
19091
19092 void
19093 module_state::import_macros ()
19094 {
19095 bitmap_ior_into (headers, slurp->headers);
19096
19097 bitmap_iterator bititer;
19098 unsigned bitnum;
19099 EXECUTE_IF_SET_IN_BITMAP (slurp->headers, 0, bitnum, bititer)
19100 (*modules)[bitnum]->install_macros ();
19101 }
19102
19103 /* NODE is being undefined at LOC. Record it in the export table, if
19104 necessary. */
19105
19106 void
19107 module_state::undef_macro (cpp_reader *, location_t loc, cpp_hashnode *node)
19108 {
19109 if (!node->deferred)
19110 /* The macro is not imported, so our undef is irrelevant. */
19111 return;
19112
19113 unsigned n = dump.push (NULL);
19114
19115 macro_import::slot &slot = (*macro_imports)[node->deferred - 1].exported ();
19116 macro_export &exp = get_macro_export (slot);
19117
19118 exp.undef_loc = loc;
19119 slot.become_undef ();
19120 exp.def = NULL;
19121
19122 dump (dumper::MACRO) && dump ("Recording macro #undef %I", identifier (node));
19123
19124 dump.pop (n);
19125 }
19126
19127 /* NODE is a deferred macro node. Determine the definition and return
19128 it, with NULL if undefined. May issue diagnostics.
19129
19130 This can leak memory, when merging declarations -- the string
19131 contents (TOKEN_FLD_STR) of each definition are allocated in
19132 unreclaimable cpp objstack. Only one will win. However, I do not
19133 expect this to be common -- mostly macros have a single point of
19134 definition. Perhaps we could restore the objstack to its position
19135 after the first imported definition (if that wins)? The macros
19136 themselves are GC'd. */
19137
19138 cpp_macro *
19139 module_state::deferred_macro (cpp_reader *reader, location_t loc,
19140 cpp_hashnode *node)
19141 {
19142 macro_import &imports = (*macro_imports)[node->deferred - 1];
19143
19144 unsigned n = dump.push (NULL);
19145 dump (dumper::MACRO) && dump ("Deferred macro %I", identifier (node));
19146
19147 bitmap visible (BITMAP_GGC_ALLOC ());
19148
19149 if (!((imports[0].get_defness () & macro_import::slot::L_UNDEF)
19150 && !imports[0].get_module ()))
19151 {
19152 /* Calculate the set of visible header imports. */
19153 bitmap_copy (visible, headers);
19154 for (unsigned ix = imports.length (); ix--;)
19155 {
19156 const macro_import::slot &slot = imports[ix];
19157 unsigned mod = slot.get_module ();
19158 if ((slot.get_defness () & macro_import::slot::L_UNDEF)
19159 && bitmap_bit_p (visible, mod))
19160 {
19161 bitmap arg = mod ? (*modules)[mod]->slurp->headers : headers;
19162 bitmap_and_compl_into (visible, arg);
19163 bitmap_set_bit (visible, mod);
19164 }
19165 }
19166 }
19167 bitmap_set_bit (visible, 0);
19168
19169 /* Now find the macros that are still visible. */
19170 bool failed = false;
19171 cpp_macro *def = NULL;
19172 vec<macro_export> defs;
19173 defs.create (imports.length ());
19174 for (unsigned ix = imports.length (); ix--;)
19175 {
19176 const macro_import::slot &slot = imports[ix];
19177 unsigned mod = slot.get_module ();
19178 if (bitmap_bit_p (visible, mod))
19179 {
19180 macro_export *pushed = NULL;
19181 if (mod)
19182 {
19183 const module_state *imp = (*modules)[mod];
19184 bytes_in &sec = imp->slurp->macro_defs;
19185 if (!sec.get_overrun ())
19186 {
19187 dump (dumper::MACRO)
19188 && dump ("Reading macro %s%s%s %I module %M at %u",
19189 slot.get_defness () & macro_import::slot::L_UNDEF
19190 ? "#undef" : "",
19191 slot.get_defness () == macro_import::slot::L_BOTH
19192 ? " & " : "",
19193 slot.get_defness () & macro_import::slot::L_DEF
19194 ? "#define" : "",
19195 identifier (node), imp, slot.offset);
19196 sec.random_access (slot.offset);
19197
19198 macro_export exp;
19199 if (slot.get_defness () & macro_import::slot::L_UNDEF)
19200 exp.undef_loc = imp->read_location (sec);
19201 if (slot.get_defness () & macro_import::slot::L_DEF)
19202 exp.def = imp->read_define (sec, reader);
19203 if (sec.get_overrun ())
19204 error_at (loc, "macro definitions of %qE corrupted",
19205 imp->name);
19206 else
19207 pushed = defs.quick_push (exp);
19208 }
19209 }
19210 else
19211 pushed = defs.quick_push ((*macro_exports)[slot.offset]);
19212 if (pushed && pushed->def)
19213 {
19214 if (!def)
19215 def = pushed->def;
19216 else if (cpp_compare_macros (def, pushed->def))
19217 failed = true;
19218 }
19219 }
19220 }
19221
19222 if (failed)
19223 {
19224 /* If LOC is the first loc, this is the end of file check, which
19225 is a warning. */
19226 auto_diagnostic_group d;
19227 if (loc == MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0)))
19228 warning_at (loc, OPT_Winvalid_imported_macros,
19229 "inconsistent imported macro definition %qE",
19230 identifier (node));
19231 else
19232 error_at (loc, "inconsistent imported macro definition %qE",
19233 identifier (node));
19234 for (unsigned ix = defs.length (); ix--;)
19235 {
19236 macro_export &exp = defs[ix];
19237 if (exp.undef_loc)
19238 inform (exp.undef_loc, "%<#undef %E%>", identifier (node));
19239 if (exp.def)
19240 inform (exp.def->line, "%<#define %s%>",
19241 cpp_macro_definition (reader, node, exp.def));
19242 }
19243 def = NULL;
19244 }
19245
19246 defs.release ();
19247
19248 dump.pop (n);
19249
19250 return def;
19251 }
19252
19253 /* Stream the static aggregates. Sadly some headers (ahem:
19254 iostream) contain static vars, and rely on them to run global
19255 ctors. */
19256 unsigned
19257 module_state::write_inits (elf_out *to, depset::hash &table, unsigned *crc_ptr)
19258 {
19259 if (!static_aggregates && !tls_aggregates)
19260 return 0;
19261
19262 dump () && dump ("Writing initializers");
19263 dump.indent ();
19264
19265 static_aggregates = nreverse (static_aggregates);
19266 tls_aggregates = nreverse (tls_aggregates);
19267
19268 unsigned count = 0;
19269 trees_out sec (to, this, table, ~0u);
19270 sec.begin ();
19271
19272 tree list = static_aggregates;
19273 for (int passes = 0; passes != 2; passes++)
19274 {
19275 for (tree init = list; init; init = TREE_CHAIN (init))
19276 if (TREE_LANG_FLAG_0 (init))
19277 {
19278 if (STATIC_INIT_DECOMP_BASE_P (init))
19279 {
19280 /* Ensure that in the returned result chain if the
19281 STATIC_INIT_DECOMP_*BASE_P flags are set, there is
19282 always one or more STATIC_INIT_DECOMP_BASE_P TREE_LIST
19283 followed by one or more STATIC_INIT_DECOMP_NONBASE_P. */
19284 int phase = 0;
19285 tree last = NULL_TREE;
19286 for (tree init2 = TREE_CHAIN (init);
19287 init2; init2 = TREE_CHAIN (init2))
19288 {
19289 if (phase == 0 && STATIC_INIT_DECOMP_BASE_P (init2))
19290 ;
19291 else if (phase == 0
19292 && STATIC_INIT_DECOMP_NONBASE_P (init2))
19293 {
19294 phase = TREE_LANG_FLAG_0 (init2) ? 2 : 1;
19295 last = init2;
19296 }
19297 else if (IN_RANGE (phase, 1, 2)
19298 && STATIC_INIT_DECOMP_NONBASE_P (init2))
19299 {
19300 if (TREE_LANG_FLAG_0 (init2))
19301 phase = 2;
19302 last = init2;
19303 }
19304 else
19305 break;
19306 }
19307 if (phase == 2)
19308 {
19309 /* In that case, add markers about it so that the
19310 STATIC_INIT_DECOMP_BASE_P and
19311 STATIC_INIT_DECOMP_NONBASE_P flags can be restored. */
19312 sec.tree_node (build_int_cst (integer_type_node,
19313 2 * passes + 1));
19314 phase = 1;
19315 for (tree init2 = init; init2 != TREE_CHAIN (last);
19316 init2 = TREE_CHAIN (init2))
19317 if (TREE_LANG_FLAG_0 (init2))
19318 {
19319 tree decl = TREE_VALUE (init2);
19320 if (phase == 1
19321 && STATIC_INIT_DECOMP_NONBASE_P (init2))
19322 {
19323 sec.tree_node (build_int_cst (integer_type_node,
19324 2 * passes + 2));
19325 phase = 2;
19326 }
19327 dump ("Initializer:%u for %N", count, decl);
19328 sec.tree_node (decl);
19329 ++count;
19330 }
19331 sec.tree_node (integer_zero_node);
19332 init = last;
19333 continue;
19334 }
19335 }
19336
19337 tree decl = TREE_VALUE (init);
19338
19339 dump ("Initializer:%u for %N", count, decl);
19340 sec.tree_node (decl);
19341 ++count;
19342 }
19343
19344 list = tls_aggregates;
19345 }
19346
19347 sec.end (to, to->name (MOD_SNAME_PFX ".ini"), crc_ptr);
19348 dump.outdent ();
19349
19350 return count;
19351 }
19352
19353 /* We have to defer some post-load processing until we've completed
19354 reading, because they can cause more reading. */
19355
19356 static void
19357 post_load_processing ()
19358 {
19359 /* We mustn't cause a GC, our caller should have arranged for that
19360 not to happen. */
19361 gcc_checking_assert (function_depth);
19362
19363 if (!post_load_decls)
19364 return;
19365
19366 tree old_cfd = current_function_decl;
19367 struct function *old_cfun = cfun;
19368 while (post_load_decls->length ())
19369 {
19370 tree decl = post_load_decls->pop ();
19371
19372 dump () && dump ("Post-load processing of %N", decl);
19373
19374 gcc_checking_assert (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl));
19375 expand_or_defer_fn (decl);
19376 /* As in module_state::read_cluster. */
19377 if (at_eof && DECL_COMDAT (decl) && DECL_EXTERNAL (decl)
19378 && DECL_NOT_REALLY_EXTERN (decl))
19379 DECL_EXTERNAL (decl) = false;
19380 }
19381
19382 cfun = old_cfun;
19383 current_function_decl = old_cfd;
19384 }
19385
19386 bool
19387 module_state::read_inits (unsigned count)
19388 {
19389 trees_in sec (this);
19390 if (!sec.begin (loc, from (), from ()->find (MOD_SNAME_PFX ".ini")))
19391 return false;
19392 dump () && dump ("Reading %u initializers", count);
19393 dump.indent ();
19394
19395 lazy_snum = ~0u;
19396 int decomp_phase = 0;
19397 tree *aggrp = NULL;
19398 for (unsigned ix = 0; ix != count; ix++)
19399 {
19400 tree last = NULL_TREE;
19401 if (decomp_phase)
19402 last = *aggrp;
19403 /* Merely referencing the decl causes its initializer to be read
19404 and added to the correct list. */
19405 tree decl = sec.tree_node ();
19406 /* module_state::write_inits can add special INTEGER_CST markers in
19407 between the decls. 1 means STATIC_INIT_DECOMP_BASE_P entries
19408 follow in static_aggregates, 2 means STATIC_INIT_DECOMP_NONBASE_P
19409 entries follow in static_aggregates, 3 means
19410 STATIC_INIT_DECOMP_BASE_P entries follow in tls_aggregates,
19411 4 means STATIC_INIT_DECOMP_NONBASE_P follow in tls_aggregates,
19412 0 means end of STATIC_INIT_DECOMP_{,NON}BASE_P sequence. */
19413 if (tree_fits_shwi_p (decl))
19414 {
19415 if (sec.get_overrun ())
19416 break;
19417 decomp_phase = tree_to_shwi (decl);
19418 if (decomp_phase)
19419 {
19420 aggrp = decomp_phase > 2 ? &tls_aggregates : &static_aggregates;
19421 last = *aggrp;
19422 }
19423 decl = sec.tree_node ();
19424 }
19425
19426 if (sec.get_overrun ())
19427 break;
19428 if (decl)
19429 dump ("Initializer:%u for %N", ix, decl);
19430 if (decomp_phase)
19431 {
19432 tree init = *aggrp;
19433 gcc_assert (TREE_VALUE (init) == decl && TREE_CHAIN (init) == last);
19434 if ((decomp_phase & 1) != 0)
19435 STATIC_INIT_DECOMP_BASE_P (init) = 1;
19436 else
19437 STATIC_INIT_DECOMP_NONBASE_P (init) = 1;
19438 }
19439 }
19440 if (decomp_phase && !sec.get_overrun ())
19441 {
19442 tree decl = sec.tree_node ();
19443 gcc_assert (integer_zerop (decl));
19444 }
19445 lazy_snum = 0;
19446 post_load_processing ();
19447 dump.outdent ();
19448 if (!sec.end (from ()))
19449 return false;
19450 return true;
19451 }
19452
19453 void
19454 module_state::write_counts (elf_out *to, unsigned counts[MSC_HWM],
19455 unsigned *crc_ptr)
19456 {
19457 bytes_out cfg (to);
19458
19459 cfg.begin ();
19460
19461 for (unsigned ix = MSC_HWM; ix--;)
19462 cfg.u (counts[ix]);
19463
19464 if (dump ())
19465 {
19466 dump ("Cluster sections are [%u,%u)",
19467 counts[MSC_sec_lwm], counts[MSC_sec_hwm]);
19468 dump ("Bindings %u", counts[MSC_bindings]);
19469 dump ("Pendings %u", counts[MSC_pendings]);
19470 dump ("Entities %u", counts[MSC_entities]);
19471 dump ("Namespaces %u", counts[MSC_namespaces]);
19472 dump ("Macros %u", counts[MSC_macros]);
19473 dump ("Initializers %u", counts[MSC_inits]);
19474 }
19475
19476 cfg.end (to, to->name (MOD_SNAME_PFX ".cnt"), crc_ptr);
19477 }
19478
19479 bool
19480 module_state::read_counts (unsigned counts[MSC_HWM])
19481 {
19482 bytes_in cfg;
19483
19484 if (!cfg.begin (loc, from (), MOD_SNAME_PFX ".cnt"))
19485 return false;
19486
19487 for (unsigned ix = MSC_HWM; ix--;)
19488 counts[ix] = cfg.u ();
19489
19490 if (dump ())
19491 {
19492 dump ("Declaration sections are [%u,%u)",
19493 counts[MSC_sec_lwm], counts[MSC_sec_hwm]);
19494 dump ("Bindings %u", counts[MSC_bindings]);
19495 dump ("Pendings %u", counts[MSC_pendings]);
19496 dump ("Entities %u", counts[MSC_entities]);
19497 dump ("Namespaces %u", counts[MSC_namespaces]);
19498 dump ("Macros %u", counts[MSC_macros]);
19499 dump ("Initializers %u", counts[MSC_inits]);
19500 }
19501
19502 return cfg.end (from ());
19503 }
19504
19505 /* Tool configuration: MOD_SNAME_PFX .config
19506
19507 This is data that confirms current state (or fails). */
19508
19509 void
19510 module_state::write_config (elf_out *to, module_state_config &config,
19511 unsigned inner_crc)
19512 {
19513 bytes_out cfg (to);
19514
19515 cfg.begin ();
19516
19517 /* Write version and inner crc as u32 values, for easier
19518 debug inspection. */
19519 dump () && dump ("Writing version=%V, inner_crc=%x",
19520 MODULE_VERSION, inner_crc);
19521 cfg.u32 (unsigned (MODULE_VERSION));
19522 cfg.u32 (inner_crc);
19523
19524 cfg.u (to->name (is_header () ? "" : get_flatname ()));
19525
19526 /* Configuration. */
19527 dump () && dump ("Writing target='%s', host='%s'",
19528 TARGET_MACHINE, HOST_MACHINE);
19529 unsigned target = to->name (TARGET_MACHINE);
19530 unsigned host = (!strcmp (TARGET_MACHINE, HOST_MACHINE)
19531 ? target : to->name (HOST_MACHINE));
19532 cfg.u (target);
19533 cfg.u (host);
19534
19535 cfg.str (config.dialect_str);
19536 cfg.u (extensions);
19537
19538 /* Global tree information. We write the globals crc separately,
19539 rather than mix it directly into the overall crc, as it is used
19540 to ensure data match between instances of the compiler, not
19541 integrity of the file. */
19542 dump () && dump ("Writing globals=%u, crc=%x",
19543 fixed_trees->length (), global_crc);
19544 cfg.u (fixed_trees->length ());
19545 cfg.u32 (global_crc);
19546
19547 if (is_partition ())
19548 cfg.u (is_interface ());
19549
19550 cfg.u (config.num_imports);
19551 cfg.u (config.num_partitions);
19552 cfg.u (config.num_entities);
19553
19554 cfg.loc (config.ordinary_locs);
19555 cfg.loc (config.macro_locs);
19556 cfg.u (config.loc_range_bits);
19557
19558 cfg.u (config.active_init);
19559
19560 /* Now generate CRC, we'll have incorporated the inner CRC because
19561 of its serialization above. */
19562 cfg.end (to, to->name (MOD_SNAME_PFX ".cfg"), &crc);
19563 dump () && dump ("Writing CRC=%x", crc);
19564 }
19565
19566 void
19567 module_state::note_cmi_name ()
19568 {
19569 if (!cmi_noted_p && filename)
19570 {
19571 cmi_noted_p = true;
19572 inform (loc, "compiled module file is %qs",
19573 maybe_add_cmi_prefix (filename));
19574 }
19575 }
19576
19577 bool
19578 module_state::read_config (module_state_config &config)
19579 {
19580 bytes_in cfg;
19581
19582 if (!cfg.begin (loc, from (), MOD_SNAME_PFX ".cfg"))
19583 return false;
19584
19585 /* Check version. */
19586 unsigned my_ver = MODULE_VERSION;
19587 unsigned their_ver = cfg.u32 ();
19588 dump () && dump (my_ver == their_ver ? "Version %V"
19589 : "Expecting %V found %V", my_ver, their_ver);
19590 if (their_ver != my_ver)
19591 {
19592 /* The compiler versions differ. Close enough? */
19593 verstr_t my_string, their_string;
19594
19595 version2string (my_ver, my_string);
19596 version2string (their_ver, their_string);
19597
19598 /* Reject when either is non-experimental or when experimental
19599 major versions differ. */
19600 auto_diagnostic_group d;
19601 bool reject_p = ((!IS_EXPERIMENTAL (my_ver)
19602 || !IS_EXPERIMENTAL (their_ver)
19603 || MODULE_MAJOR (my_ver) != MODULE_MAJOR (their_ver))
19604 /* The 'I know what I'm doing' switch. */
19605 && !flag_module_version_ignore);
19606 bool inform_p = true;
19607 if (reject_p)
19608 {
19609 cfg.set_overrun ();
19610 error_at (loc, "compiled module is %sversion %s",
19611 IS_EXPERIMENTAL (their_ver) ? "experimental " : "",
19612 their_string);
19613 }
19614 else
19615 inform_p = warning_at (loc, 0, "compiled module is %sversion %s",
19616 IS_EXPERIMENTAL (their_ver) ? "experimental " : "",
19617 their_string);
19618
19619 if (inform_p)
19620 {
19621 inform (loc, "compiler is %sversion %s%s%s",
19622 IS_EXPERIMENTAL (my_ver) ? "experimental " : "",
19623 my_string,
19624 reject_p ? "" : flag_module_version_ignore
19625 ? ", be it on your own head!" : ", close enough?",
19626 reject_p ? "" : " \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf");
19627 note_cmi_name ();
19628 }
19629
19630 if (reject_p)
19631 goto done;
19632 }
19633
19634 /* We wrote the inner crc merely to merge it, so simply read it
19635 back and forget it. */
19636 cfg.u32 ();
19637
19638 /* Check module name. */
19639 {
19640 const char *their_name = from ()->name (cfg.u ());
19641 const char *our_name = "";
19642
19643 if (!is_header ())
19644 our_name = get_flatname ();
19645
19646 /* Header units can be aliased, so name checking is
19647 inappropriate. */
19648 if (0 != strcmp (their_name, our_name))
19649 {
19650 error_at (loc,
19651 their_name[0] && our_name[0] ? G_("module %qs found")
19652 : their_name[0]
19653 ? G_("header module expected, module %qs found")
19654 : G_("module %qs expected, header module found"),
19655 their_name[0] ? their_name : our_name);
19656 cfg.set_overrun ();
19657 goto done;
19658 }
19659 }
19660
19661 /* Check the CRC after the above sanity checks, so that the user is
19662 clued in. */
19663 {
19664 unsigned e_crc = crc;
19665 crc = cfg.get_crc ();
19666 dump () && dump ("Reading CRC=%x", crc);
19667 if (!is_direct () && crc != e_crc)
19668 {
19669 error_at (loc, "module %qs CRC mismatch", get_flatname ());
19670 cfg.set_overrun ();
19671 goto done;
19672 }
19673 }
19674
19675 /* Check target & host. */
19676 {
19677 const char *their_target = from ()->name (cfg.u ());
19678 const char *their_host = from ()->name (cfg.u ());
19679 dump () && dump ("Read target='%s', host='%s'", their_target, their_host);
19680 if (strcmp (their_target, TARGET_MACHINE)
19681 || strcmp (their_host, HOST_MACHINE))
19682 {
19683 error_at (loc, "target & host is %qs:%qs, expected %qs:%qs",
19684 their_target, TARGET_MACHINE, their_host, HOST_MACHINE);
19685 cfg.set_overrun ();
19686 goto done;
19687 }
19688 }
19689
19690 /* Check compilation dialect. This must match. */
19691 {
19692 const char *their_dialect = cfg.str ();
19693 if (strcmp (their_dialect, config.dialect_str))
19694 {
19695 error_at (loc, "language dialect differs %qs, expected %qs",
19696 their_dialect, config.dialect_str);
19697 cfg.set_overrun ();
19698 goto done;
19699 }
19700 }
19701
19702 /* Check for extensions. If they set any, we must have them set
19703 too. */
19704 {
19705 unsigned ext = cfg.u ();
19706 unsigned allowed = (flag_openmp ? SE_OPENMP | SE_OPENMP_SIMD : 0);
19707 if (flag_openmp_simd)
19708 allowed |= SE_OPENMP_SIMD;
19709 if (flag_openacc)
19710 allowed |= SE_OPENACC;
19711
19712 if (unsigned bad = ext & ~allowed)
19713 {
19714 if (bad & SE_OPENMP)
19715 error_at (loc, "module contains OpenMP, use %<-fopenmp%> to enable");
19716 else if (bad & SE_OPENMP_SIMD)
19717 error_at (loc, "module contains OpenMP, use %<-fopenmp%> or "
19718 "%<-fopenmp-simd%> to enable");
19719 if (bad & SE_OPENACC)
19720 error_at (loc, "module contains OpenACC, use %<-fopenacc%> to "
19721 "enable");
19722 cfg.set_overrun ();
19723 goto done;
19724 }
19725 extensions = ext;
19726 }
19727
19728 /* Check global trees. */
19729 {
19730 unsigned their_fixed_length = cfg.u ();
19731 unsigned their_fixed_crc = cfg.u32 ();
19732 dump () && dump ("Read globals=%u, crc=%x",
19733 their_fixed_length, their_fixed_crc);
19734 if (!flag_preprocess_only
19735 && (their_fixed_length != fixed_trees->length ()
19736 || their_fixed_crc != global_crc))
19737 {
19738 error_at (loc, "fixed tree mismatch");
19739 cfg.set_overrun ();
19740 goto done;
19741 }
19742 }
19743
19744 /* All non-partitions are interfaces. */
19745 interface_p = !is_partition () || cfg.u ();
19746
19747 config.num_imports = cfg.u ();
19748 config.num_partitions = cfg.u ();
19749 config.num_entities = cfg.u ();
19750
19751 config.ordinary_locs = cfg.loc ();
19752 config.macro_locs = cfg.loc ();
19753 config.loc_range_bits = cfg.u ();
19754
19755 config.active_init = cfg.u ();
19756
19757 done:
19758 return cfg.end (from ());
19759 }
19760
19761 /* Comparator for ordering the Ordered Ordinary Location array. */
19762
19763 static int
19764 ool_cmp (const void *a_, const void *b_)
19765 {
19766 auto *a = *static_cast<const module_state *const *> (a_);
19767 auto *b = *static_cast<const module_state *const *> (b_);
19768 if (a == b)
19769 return 0;
19770 else if (a->ordinary_locs.first < b->ordinary_locs.first)
19771 return -1;
19772 else
19773 return +1;
19774 }
19775
19776 /* Use ELROND format to record the following sections:
19777 qualified-names : binding value(s)
19778 MOD_SNAME_PFX.README : human readable, strings
19779 MOD_SNAME_PFX.ENV : environment strings, strings
19780 MOD_SNAME_PFX.nms : namespace hierarchy
19781 MOD_SNAME_PFX.bnd : binding table
19782 MOD_SNAME_PFX.spc : specialization table
19783 MOD_SNAME_PFX.imp : import table
19784 MOD_SNAME_PFX.ent : entity table
19785 MOD_SNAME_PFX.prt : partitions table
19786 MOD_SNAME_PFX.olm : ordinary line maps
19787 MOD_SNAME_PFX.mlm : macro line maps
19788 MOD_SNAME_PFX.def : macro definitions
19789 MOD_SNAME_PFX.mac : macro index
19790 MOD_SNAME_PFX.ini : inits
19791 MOD_SNAME_PFX.cnt : counts
19792 MOD_SNAME_PFX.cfg : config data
19793 */
19794
19795 bool
19796 module_state::write_begin (elf_out *to, cpp_reader *reader,
19797 module_state_config &config, unsigned &crc)
19798 {
19799 /* Figure out remapped module numbers, which might elide
19800 partitions. */
19801 bitmap partitions = NULL;
19802 if (!is_header () && !is_partition ())
19803 partitions = BITMAP_GGC_ALLOC ();
19804 write_init_maps ();
19805
19806 unsigned mod_hwm = 1;
19807 for (unsigned ix = 1; ix != modules->length (); ix++)
19808 {
19809 module_state *imp = (*modules)[ix];
19810
19811 /* Promote any non-partition direct import from a partition, unless
19812 we're a partition. */
19813 if (!is_partition () && !imp->is_partition ()
19814 && imp->is_partition_direct ())
19815 imp->directness = MD_PURVIEW_DIRECT;
19816
19817 /* Write any import that is not a partition, unless we're a
19818 partition. */
19819 if (!partitions || !imp->is_partition ())
19820 imp->remap = mod_hwm++;
19821 else
19822 {
19823 dump () && dump ("Partition %M %u", imp, ix);
19824 bitmap_set_bit (partitions, ix);
19825 imp->remap = 0;
19826 /* All interface partitions must be exported. */
19827 if (imp->is_interface () && !bitmap_bit_p (exports, imp->mod))
19828 {
19829 error_at (imp->loc, "interface partition is not exported");
19830 bitmap_set_bit (exports, imp->mod);
19831 }
19832
19833 /* All the partition entities should have been loaded when
19834 loading the partition. */
19835 if (CHECKING_P)
19836 for (unsigned jx = 0; jx != imp->entity_num; jx++)
19837 {
19838 binding_slot *slot = &(*entity_ary)[imp->entity_lwm + jx];
19839 gcc_checking_assert (!slot->is_lazy ());
19840 }
19841 }
19842
19843 if (imp->is_direct () && (imp->remap || imp->is_partition ()))
19844 note_location (imp->imported_from ());
19845 }
19846
19847 if (partitions && bitmap_empty_p (partitions))
19848 /* No partitions present. */
19849 partitions = nullptr;
19850
19851 /* Find the set of decls we must write out. */
19852 depset::hash table (DECL_NAMESPACE_BINDINGS (global_namespace)->size () * 8);
19853 /* Add the specializations before the writables, so that we can
19854 detect injected friend specializations. */
19855 table.add_specializations (true);
19856 table.add_specializations (false);
19857 if (partial_specializations)
19858 {
19859 table.add_partial_entities (partial_specializations);
19860 partial_specializations = NULL;
19861 }
19862 table.add_namespace_entities (global_namespace, partitions);
19863 if (class_members)
19864 {
19865 table.add_class_entities (class_members);
19866 class_members = NULL;
19867 }
19868
19869 /* Now join everything up. */
19870 table.find_dependencies (this);
19871
19872 if (!table.finalize_dependencies ())
19873 return false;
19874
19875 #if CHECKING_P
19876 /* We're done verifying at-most once reading, reset to verify
19877 at-most once writing. */
19878 note_defs = note_defs_table_t::create_ggc (1000);
19879 #endif
19880
19881 /* Determine Strongly Connected Components. This will also strip any
19882 unnecessary dependencies on imported or TU-local entities. */
19883 vec<depset *> sccs = table.connect ();
19884
19885 vec_alloc (ool, modules->length ());
19886 for (unsigned ix = modules->length (); --ix;)
19887 {
19888 auto *import = (*modules)[ix];
19889 if (import->loadedness > ML_NONE
19890 && !(partitions && bitmap_bit_p (partitions, import->mod)))
19891 ool->quick_push (import);
19892 }
19893 ool->qsort (ool_cmp);
19894
19895 vec<cpp_hashnode *> *macros = nullptr;
19896 if (is_header ())
19897 macros = prepare_macros (reader);
19898
19899 config.num_imports = mod_hwm;
19900 config.num_partitions = modules->length () - mod_hwm;
19901 auto map_info = write_prepare_maps (&config, bool (config.num_partitions));
19902 unsigned counts[MSC_HWM];
19903 memset (counts, 0, sizeof (counts));
19904
19905 /* depset::cluster is the cluster number,
19906 depset::section is unspecified scratch value.
19907
19908 The following loops make use of the tarjan property that
19909 dependencies will be earlier in the SCCS array. */
19910
19911 /* This first loop determines the number of depsets in each SCC, and
19912 also the number of namespaces we're dealing with. During the
19913 loop, the meaning of a couple of depset fields now change:
19914
19915 depset::cluster -> size_of cluster, if first of cluster & !namespace
19916 depset::section -> section number of cluster (if !namespace). */
19917
19918 unsigned n_spaces = 0;
19919 counts[MSC_sec_lwm] = counts[MSC_sec_hwm] = to->get_section_limit ();
19920 for (unsigned size, ix = 0; ix < sccs.length (); ix += size)
19921 {
19922 depset **base = &sccs[ix];
19923
19924 if (base[0]->get_entity_kind () == depset::EK_NAMESPACE)
19925 {
19926 n_spaces++;
19927 size = 1;
19928 }
19929 else
19930 {
19931 /* Count the members in this cluster. */
19932 for (size = 1; ix + size < sccs.length (); size++)
19933 if (base[size]->cluster != base[0]->cluster)
19934 break;
19935
19936 for (unsigned jx = 0; jx != size; jx++)
19937 {
19938 /* Set the section number. */
19939 base[jx]->cluster = ~(~0u >> 1); /* A bad value. */
19940 base[jx]->section = counts[MSC_sec_hwm];
19941 }
19942
19943 /* Save the size in the first member's cluster slot. */
19944 base[0]->cluster = size;
19945
19946 counts[MSC_sec_hwm]++;
19947 }
19948 }
19949
19950 /* Write the clusters. Namespace decls are put in the spaces array.
19951 The meaning of depset::cluster changes to provide the
19952 unnamed-decl count of the depset's decl (and remains zero for
19953 non-decls and non-unnamed). */
19954 unsigned bytes = 0;
19955 vec<depset *> spaces;
19956 spaces.create (n_spaces);
19957
19958 for (unsigned size, ix = 0; ix < sccs.length (); ix += size)
19959 {
19960 depset **base = &sccs[ix];
19961
19962 if (base[0]->get_entity_kind () == depset::EK_NAMESPACE)
19963 {
19964 tree decl = base[0]->get_entity ();
19965 if (decl == global_namespace)
19966 base[0]->cluster = 0;
19967 else if (!base[0]->is_import ())
19968 {
19969 base[0]->cluster = counts[MSC_entities]++;
19970 spaces.quick_push (base[0]);
19971 counts[MSC_namespaces]++;
19972 if (CHECKING_P)
19973 {
19974 /* Add it to the entity map, such that we can tell it is
19975 part of us. */
19976 bool existed;
19977 unsigned *slot = &entity_map->get_or_insert
19978 (DECL_UID (decl), &existed);
19979 if (existed)
19980 /* It must have come from a partition. */
19981 gcc_checking_assert
19982 (import_entity_module (*slot)->is_partition ());
19983 *slot = ~base[0]->cluster;
19984 }
19985 dump (dumper::CLUSTER) && dump ("Cluster namespace %N", decl);
19986 }
19987 size = 1;
19988 }
19989 else
19990 {
19991 size = base[0]->cluster;
19992
19993 /* Cluster is now used to number entities. */
19994 base[0]->cluster = ~(~0u >> 1); /* A bad value. */
19995
19996 sort_cluster (&table, base, size);
19997
19998 /* Record the section for consistency checking during stream
19999 out -- we don't want to start writing decls in different
20000 sections. */
20001 table.section = base[0]->section;
20002 bytes += write_cluster (to, base, size, table, counts, &crc);
20003 table.section = 0;
20004 }
20005 }
20006
20007 /* depset::cluster - entity number (on entities)
20008 depset::section - cluster number */
20009 /* We'd better have written as many sections and found as many
20010 namespaces as we predicted. */
20011 gcc_assert (counts[MSC_sec_hwm] == to->get_section_limit ()
20012 && spaces.length () == counts[MSC_namespaces]);
20013
20014 /* Write the entitites. None happens if we contain namespaces or
20015 nothing. */
20016 config.num_entities = counts[MSC_entities];
20017 if (counts[MSC_entities])
20018 write_entities (to, sccs, counts[MSC_entities], &crc);
20019
20020 /* Write the namespaces. */
20021 if (counts[MSC_namespaces])
20022 write_namespaces (to, spaces, counts[MSC_namespaces], &crc);
20023
20024 /* Write the bindings themselves. */
20025 counts[MSC_bindings] = write_bindings (to, sccs, &crc);
20026
20027 /* Write the unnamed. */
20028 counts[MSC_pendings] = write_pendings (to, sccs, table, &crc);
20029
20030 /* Write the import table. */
20031 if (config.num_imports > 1)
20032 write_imports (to, &crc);
20033
20034 /* Write elided partition table. */
20035 if (config.num_partitions)
20036 write_partitions (to, config.num_partitions, &crc);
20037
20038 /* Write the line maps. */
20039 if (config.ordinary_locs)
20040 write_ordinary_maps (to, map_info, bool (config.num_partitions), &crc);
20041 if (config.macro_locs)
20042 write_macro_maps (to, map_info, &crc);
20043
20044 if (is_header ())
20045 {
20046 counts[MSC_macros] = write_macros (to, macros, &crc);
20047 counts[MSC_inits] = write_inits (to, table, &crc);
20048 vec_free (macros);
20049 }
20050
20051 unsigned clusters = counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
20052 dump () && dump ("Wrote %u clusters, average %u bytes/cluster",
20053 clusters, (bytes + clusters / 2) / (clusters + !clusters));
20054 trees_out::instrument ();
20055
20056 write_counts (to, counts, &crc);
20057
20058 spaces.release ();
20059 sccs.release ();
20060
20061 vec_free (macro_loc_remap);
20062 vec_free (ord_loc_remap);
20063 vec_free (ool);
20064
20065 // FIXME:QOI: Have a command line switch to control more detailed
20066 // information (which might leak data you do not want to leak).
20067 // Perhaps (some of) the write_readme contents should also be
20068 // so-controlled.
20069 if (false)
20070 write_env (to);
20071
20072 return true;
20073 }
20074
20075 // Finish module writing after we've emitted all dynamic initializers.
20076
20077 void
20078 module_state::write_end (elf_out *to, cpp_reader *reader,
20079 module_state_config &config, unsigned &crc)
20080 {
20081 /* And finish up. */
20082 write_config (to, config, crc);
20083
20084 /* Human-readable info. */
20085 write_readme (to, reader, config.dialect_str);
20086
20087 dump () && dump ("Wrote %u sections", to->get_section_limit ());
20088 }
20089
20090 /* Initial read of a CMI. Checks config, loads up imports and line
20091 maps. */
20092
20093 bool
20094 module_state::read_initial (cpp_reader *reader)
20095 {
20096 module_state_config config;
20097 bool ok = true;
20098
20099 if (ok && !from ()->begin (loc))
20100 ok = false;
20101
20102 if (ok && !read_config (config))
20103 ok = false;
20104
20105 bool have_locs = ok && read_prepare_maps (&config);
20106
20107 /* Ordinary maps before the imports. */
20108 if (!(have_locs && config.ordinary_locs))
20109 ordinary_locs.first = line_table->highest_location + 1;
20110 else if (!read_ordinary_maps (config.ordinary_locs, config.loc_range_bits))
20111 ok = false;
20112
20113 /* Allocate the REMAP vector. */
20114 slurp->alloc_remap (config.num_imports);
20115
20116 if (ok)
20117 {
20118 /* Read the import table. Decrement current to stop this CMI
20119 from being evicted during the import. */
20120 slurp->current--;
20121 if (config.num_imports > 1 && !read_imports (reader, line_table))
20122 ok = false;
20123 slurp->current++;
20124 }
20125
20126 /* Read the elided partition table, if we're the primary partition. */
20127 if (ok && config.num_partitions && is_module ()
20128 && !read_partitions (config.num_partitions))
20129 ok = false;
20130
20131 /* Determine the module's number. */
20132 gcc_checking_assert (mod == MODULE_UNKNOWN);
20133 gcc_checking_assert (this != (*modules)[0]);
20134
20135 {
20136 /* Allocate space in the entities array now -- that array must be
20137 monotonically in step with the modules array. */
20138 entity_lwm = vec_safe_length (entity_ary);
20139 entity_num = config.num_entities;
20140 gcc_checking_assert (modules->length () == 1
20141 || modules->last ()->entity_lwm <= entity_lwm);
20142 vec_safe_reserve (entity_ary, config.num_entities);
20143
20144 binding_slot slot;
20145 slot.u.binding = NULL_TREE;
20146 for (unsigned count = config.num_entities; count--;)
20147 entity_ary->quick_push (slot);
20148 }
20149
20150 /* We'll run out of other resources before we run out of module
20151 indices. */
20152 mod = modules->length ();
20153 vec_safe_push (modules, this);
20154
20155 /* We always import and export ourselves. */
20156 bitmap_set_bit (imports, mod);
20157 bitmap_set_bit (exports, mod);
20158
20159 if (ok)
20160 (*slurp->remap)[0] = mod << 1;
20161 dump () && dump ("Assigning %M module number %u", this, mod);
20162
20163 /* We should not have been frozen during the importing done by
20164 read_config. */
20165 gcc_assert (!from ()->is_frozen ());
20166
20167 /* Macro maps after the imports. */
20168 if (!(ok && have_locs && config.macro_locs))
20169 macro_locs.first = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
20170 else if (!read_macro_maps (config.macro_locs))
20171 ok = false;
20172
20173 /* Note whether there's an active initializer. */
20174 active_init_p = !is_header () && bool (config.active_init);
20175
20176 gcc_assert (slurp->current == ~0u);
20177 return ok;
20178 }
20179
20180 /* Read a preprocessor state. */
20181
20182 bool
20183 module_state::read_preprocessor (bool outermost)
20184 {
20185 gcc_checking_assert (is_header () && slurp
20186 && slurp->remap_module (0) == mod);
20187
20188 if (loadedness == ML_PREPROCESSOR)
20189 return !(from () && from ()->get_error ());
20190
20191 bool ok = true;
20192
20193 /* Read direct header imports. */
20194 unsigned len = slurp->remap->length ();
20195 for (unsigned ix = 1; ok && ix != len; ix++)
20196 {
20197 unsigned map = (*slurp->remap)[ix];
20198 if (map & 1)
20199 {
20200 module_state *import = (*modules)[map >> 1];
20201 if (import->is_header ())
20202 {
20203 ok = import->read_preprocessor (false);
20204 bitmap_ior_into (slurp->headers, import->slurp->headers);
20205 }
20206 }
20207 }
20208
20209 /* Record as a direct header. */
20210 if (ok)
20211 bitmap_set_bit (slurp->headers, mod);
20212
20213 if (ok && !read_macros ())
20214 ok = false;
20215
20216 loadedness = ML_PREPROCESSOR;
20217 announce ("macros");
20218
20219 if (flag_preprocess_only)
20220 /* We're done with the string table. */
20221 from ()->release ();
20222
20223 return check_read (outermost, ok);
20224 }
20225
20226 /* Read language state. */
20227
20228 bool
20229 module_state::read_language (bool outermost)
20230 {
20231 gcc_checking_assert (!lazy_snum);
20232
20233 if (loadedness == ML_LANGUAGE)
20234 return !(slurp && from () && from ()->get_error ());
20235
20236 gcc_checking_assert (slurp && slurp->current == ~0u
20237 && slurp->remap_module (0) == mod);
20238
20239 bool ok = true;
20240
20241 /* Read direct imports. */
20242 unsigned len = slurp->remap->length ();
20243 for (unsigned ix = 1; ok && ix != len; ix++)
20244 {
20245 unsigned map = (*slurp->remap)[ix];
20246 if (map & 1)
20247 {
20248 module_state *import = (*modules)[map >> 1];
20249 if (!import->read_language (false))
20250 ok = false;
20251 }
20252 }
20253
20254 unsigned counts[MSC_HWM];
20255
20256 if (ok && !read_counts (counts))
20257 ok = false;
20258
20259 function_depth++; /* Prevent unexpected GCs. */
20260
20261 if (ok && counts[MSC_entities] != entity_num)
20262 ok = false;
20263 if (ok && counts[MSC_entities]
20264 && !read_entities (counts[MSC_entities],
20265 counts[MSC_sec_lwm], counts[MSC_sec_hwm]))
20266 ok = false;
20267
20268 /* Read the namespace hierarchy. */
20269 if (ok && counts[MSC_namespaces]
20270 && !read_namespaces (counts[MSC_namespaces]))
20271 ok = false;
20272
20273 if (ok && !read_bindings (counts[MSC_bindings],
20274 counts[MSC_sec_lwm], counts[MSC_sec_hwm]))
20275 ok = false;
20276
20277 /* And unnamed. */
20278 if (ok && counts[MSC_pendings] && !read_pendings (counts[MSC_pendings]))
20279 ok = false;
20280
20281 if (ok)
20282 {
20283 slurp->remaining = counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
20284 available_clusters += counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
20285 }
20286
20287 if (!flag_module_lazy
20288 || (is_partition ()
20289 && module_interface_p ()
20290 && !module_partition_p ()))
20291 {
20292 /* Read the sections in forward order, so that dependencies are read
20293 first. See note about tarjan_connect. */
20294 ggc_collect ();
20295
20296 lazy_snum = ~0u;
20297
20298 unsigned hwm = counts[MSC_sec_hwm];
20299 for (unsigned ix = counts[MSC_sec_lwm]; ok && ix != hwm; ix++)
20300 if (!load_section (ix, NULL))
20301 {
20302 ok = false;
20303 break;
20304 }
20305 lazy_snum = 0;
20306 post_load_processing ();
20307
20308 ggc_collect ();
20309
20310 if (ok && CHECKING_P)
20311 for (unsigned ix = 0; ix != entity_num; ix++)
20312 gcc_assert (!(*entity_ary)[ix + entity_lwm].is_lazy ());
20313 }
20314
20315 // If the import is a header-unit, we need to register initializers
20316 // of any static objects it contains (looking at you _Ioinit).
20317 // Notice, the ordering of these initializers will be that of a
20318 // dynamic initializer at this point in the current TU. (Other
20319 // instances of these objects in other TUs will be initialized as
20320 // part of that TU's global initializers.)
20321 if (ok && counts[MSC_inits] && !read_inits (counts[MSC_inits]))
20322 ok = false;
20323
20324 function_depth--;
20325
20326 announce (flag_module_lazy ? "lazy" : "imported");
20327 loadedness = ML_LANGUAGE;
20328
20329 gcc_assert (slurp->current == ~0u);
20330
20331 /* We're done with the string table. */
20332 from ()->release ();
20333
20334 return check_read (outermost, ok);
20335 }
20336
20337 bool
20338 module_state::maybe_defrost ()
20339 {
20340 bool ok = true;
20341 if (from ()->is_frozen ())
20342 {
20343 if (lazy_open >= lazy_limit)
20344 freeze_an_elf ();
20345 dump () && dump ("Defrosting '%s'", filename);
20346 ok = from ()->defrost (maybe_add_cmi_prefix (filename));
20347 lazy_open++;
20348 }
20349
20350 return ok;
20351 }
20352
20353 /* Load section SNUM, dealing with laziness. It doesn't matter if we
20354 have multiple concurrent loads, because we do not use TREE_VISITED
20355 when reading back in. */
20356
20357 bool
20358 module_state::load_section (unsigned snum, binding_slot *mslot)
20359 {
20360 if (from ()->get_error ())
20361 return false;
20362
20363 if (snum >= slurp->current)
20364 from ()->set_error (elf::E_BAD_LAZY);
20365 else if (maybe_defrost ())
20366 {
20367 unsigned old_current = slurp->current;
20368 slurp->current = snum;
20369 slurp->lru = 0; /* Do not swap out. */
20370 slurp->remaining--;
20371 read_cluster (snum);
20372 slurp->lru = ++lazy_lru;
20373 slurp->current = old_current;
20374 }
20375
20376 if (mslot && mslot->is_lazy ())
20377 {
20378 /* Oops, the section didn't set this slot. */
20379 from ()->set_error (elf::E_BAD_DATA);
20380 *mslot = NULL_TREE;
20381 }
20382
20383 bool ok = !from ()->get_error ();
20384 if (!ok)
20385 {
20386 error_at (loc, "failed to read compiled module cluster %u: %s",
20387 snum, from ()->get_error (filename));
20388 note_cmi_name ();
20389 }
20390
20391 maybe_completed_reading ();
20392
20393 return ok;
20394 }
20395
20396 void
20397 module_state::maybe_completed_reading ()
20398 {
20399 if (loadedness == ML_LANGUAGE && slurp->current == ~0u && !slurp->remaining)
20400 {
20401 lazy_open--;
20402 /* We no longer need the macros, all tokenizing has been done. */
20403 slurp->release_macros ();
20404
20405 from ()->end ();
20406 slurp->close ();
20407 slurped ();
20408 }
20409 }
20410
20411 /* After a reading operation, make sure things are still ok. If not,
20412 emit an error and clean up. */
20413
20414 bool
20415 module_state::check_read (bool outermost, bool ok)
20416 {
20417 gcc_checking_assert (!outermost || slurp->current == ~0u);
20418
20419 if (!ok)
20420 from ()->set_error ();
20421
20422 if (int e = from ()->get_error ())
20423 {
20424 auto_diagnostic_group d;
20425 error_at (loc, "failed to read compiled module: %s",
20426 from ()->get_error (filename));
20427 note_cmi_name ();
20428
20429 if (e == EMFILE
20430 || e == ENFILE
20431 #if MAPPED_READING
20432 || e == ENOMEM
20433 #endif
20434 || false)
20435 inform (loc, "consider using %<-fno-module-lazy%>,"
20436 " increasing %<-param-lazy-modules=%u%> value,"
20437 " or increasing the per-process file descriptor limit",
20438 param_lazy_modules);
20439 else if (e == ENOENT)
20440 inform (loc, "imports must be built before being imported");
20441
20442 if (outermost)
20443 fatal_error (loc, "returning to the gate for a mechanical issue");
20444
20445 ok = false;
20446 }
20447
20448 maybe_completed_reading ();
20449
20450 return ok;
20451 }
20452
20453 /* Return the IDENTIFIER_NODE naming module IX. This is the name
20454 including dots. */
20455
20456 char const *
20457 module_name (unsigned ix, bool header_ok)
20458 {
20459 if (modules)
20460 {
20461 module_state *imp = (*modules)[ix];
20462
20463 if (ix && !imp->name)
20464 imp = imp->parent;
20465
20466 if (header_ok || !imp->is_header ())
20467 return imp->get_flatname ();
20468 }
20469
20470 return NULL;
20471 }
20472
20473 /* Return the bitmap describing what modules are imported. Remember,
20474 we always import ourselves. */
20475
20476 bitmap
20477 get_import_bitmap ()
20478 {
20479 return (*modules)[0]->imports;
20480 }
20481
20482 /* Return the visible imports and path of instantiation for an
20483 instantiation at TINST. If TINST is nullptr, we're not in an
20484 instantiation, and thus will return the visible imports of the
20485 current TU (and NULL *PATH_MAP_P). We cache the information on
20486 the tinst level itself. */
20487
20488 static bitmap
20489 path_of_instantiation (tinst_level *tinst, bitmap *path_map_p)
20490 {
20491 gcc_checking_assert (modules_p ());
20492
20493 if (!tinst)
20494 {
20495 /* Not inside an instantiation, just the regular case. */
20496 *path_map_p = nullptr;
20497 return get_import_bitmap ();
20498 }
20499
20500 if (!tinst->path)
20501 {
20502 /* Calculate. */
20503 bitmap visible = path_of_instantiation (tinst->next, path_map_p);
20504 bitmap path_map = *path_map_p;
20505
20506 if (!path_map)
20507 {
20508 path_map = BITMAP_GGC_ALLOC ();
20509 bitmap_set_bit (path_map, 0);
20510 }
20511
20512 tree decl = tinst->tldcl;
20513 if (TREE_CODE (decl) == TREE_LIST)
20514 decl = TREE_PURPOSE (decl);
20515 if (TYPE_P (decl))
20516 decl = TYPE_NAME (decl);
20517
20518 if (unsigned mod = get_originating_module (decl))
20519 if (!bitmap_bit_p (path_map, mod))
20520 {
20521 /* This is brand new information! */
20522 bitmap new_path = BITMAP_GGC_ALLOC ();
20523 bitmap_copy (new_path, path_map);
20524 bitmap_set_bit (new_path, mod);
20525 path_map = new_path;
20526
20527 bitmap imports = (*modules)[mod]->imports;
20528 if (bitmap_intersect_compl_p (imports, visible))
20529 {
20530 /* IMPORTS contains additional modules to VISIBLE. */
20531 bitmap new_visible = BITMAP_GGC_ALLOC ();
20532
20533 bitmap_ior (new_visible, visible, imports);
20534 visible = new_visible;
20535 }
20536 }
20537
20538 tinst->path = path_map;
20539 tinst->visible = visible;
20540 }
20541
20542 *path_map_p = tinst->path;
20543 return tinst->visible;
20544 }
20545
20546 /* Return the bitmap describing what modules are visible along the
20547 path of instantiation. If we're not an instantiation, this will be
20548 the visible imports of the TU. *PATH_MAP_P is filled in with the
20549 modules owning the instantiation path -- we see the module-linkage
20550 entities of those modules. */
20551
20552 bitmap
20553 visible_instantiation_path (bitmap *path_map_p)
20554 {
20555 if (!modules_p ())
20556 return NULL;
20557
20558 return path_of_instantiation (current_instantiation (), path_map_p);
20559 }
20560
20561 /* We've just directly imported IMPORT. Update our import/export
20562 bitmaps. IS_EXPORT is true if we're reexporting the OTHER. */
20563
20564 void
20565 module_state::set_import (module_state const *import, bool is_export)
20566 {
20567 gcc_checking_assert (this != import);
20568
20569 /* We see IMPORT's exports (which includes IMPORT). If IMPORT is
20570 the primary interface or a partition we'll see its imports. */
20571 bitmap_ior_into (imports, import->is_module () || import->is_partition ()
20572 ? import->imports : import->exports);
20573
20574 if (is_export)
20575 /* We'll export OTHER's exports. */
20576 bitmap_ior_into (exports, import->exports);
20577 }
20578
20579 /* Return the declaring entity of DECL. That is the decl determining
20580 how to decorate DECL with module information. Returns NULL_TREE if
20581 it's the global module. */
20582
20583 tree
20584 get_originating_module_decl (tree decl)
20585 {
20586 /* An enumeration constant. */
20587 if (TREE_CODE (decl) == CONST_DECL
20588 && DECL_CONTEXT (decl)
20589 && (TREE_CODE (DECL_CONTEXT (decl)) == ENUMERAL_TYPE))
20590 decl = TYPE_NAME (DECL_CONTEXT (decl));
20591 else if (TREE_CODE (decl) == FIELD_DECL
20592 || TREE_CODE (decl) == USING_DECL
20593 || CONST_DECL_USING_P (decl))
20594 {
20595 decl = DECL_CONTEXT (decl);
20596 if (TREE_CODE (decl) != FUNCTION_DECL)
20597 decl = TYPE_NAME (decl);
20598 }
20599
20600 gcc_checking_assert (TREE_CODE (decl) == TEMPLATE_DECL
20601 || TREE_CODE (decl) == FUNCTION_DECL
20602 || TREE_CODE (decl) == TYPE_DECL
20603 || TREE_CODE (decl) == VAR_DECL
20604 || TREE_CODE (decl) == CONCEPT_DECL
20605 || TREE_CODE (decl) == NAMESPACE_DECL);
20606
20607 for (;;)
20608 {
20609 /* Uninstantiated template friends are owned by the befriending
20610 class -- not their context. */
20611 if (TREE_CODE (decl) == TEMPLATE_DECL
20612 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
20613 decl = TYPE_NAME (DECL_CHAIN (decl));
20614
20615 /* An imported temploid friend is attached to the same module the
20616 befriending class was. */
20617 if (imported_temploid_friends)
20618 if (tree *slot = imported_temploid_friends->get (decl))
20619 decl = *slot;
20620
20621 int use;
20622 if (tree ti = node_template_info (decl, use))
20623 {
20624 decl = TI_TEMPLATE (ti);
20625 if (TREE_CODE (decl) != TEMPLATE_DECL)
20626 {
20627 /* A friend template specialization. */
20628 gcc_checking_assert (OVL_P (decl));
20629 return global_namespace;
20630 }
20631 }
20632 else
20633 {
20634 tree ctx = CP_DECL_CONTEXT (decl);
20635 if (TREE_CODE (ctx) == NAMESPACE_DECL)
20636 break;
20637
20638 if (TYPE_P (ctx))
20639 {
20640 ctx = TYPE_NAME (ctx);
20641 if (!ctx)
20642 {
20643 /* Some kind of internal type. */
20644 gcc_checking_assert (DECL_ARTIFICIAL (decl));
20645 return global_namespace;
20646 }
20647 }
20648 decl = ctx;
20649 }
20650 }
20651
20652 return decl;
20653 }
20654
20655 /* If DECL is imported, return which module imported it, or 0 for the current
20656 module. Except that if GLOBAL_M1, return -1 for decls attached to the
20657 global module. */
20658
20659 int
20660 get_originating_module (tree decl, bool global_m1)
20661 {
20662 tree owner = get_originating_module_decl (decl);
20663 tree not_tmpl = STRIP_TEMPLATE (owner);
20664
20665 if (!DECL_LANG_SPECIFIC (not_tmpl))
20666 return global_m1 ? -1 : 0;
20667
20668 if (global_m1 && !DECL_MODULE_ATTACH_P (not_tmpl))
20669 return -1;
20670
20671 int mod = !DECL_MODULE_IMPORT_P (not_tmpl) ? 0 : get_importing_module (owner);
20672 gcc_checking_assert (!global_m1 || !(*modules)[mod]->is_header ());
20673 return mod;
20674 }
20675
20676 /* DECL is imported, return which module imported it.
20677 If FLEXIBLE, return -1 if not found, otherwise checking ICE. */
20678
20679 unsigned
20680 get_importing_module (tree decl, bool flexible)
20681 {
20682 unsigned index = import_entity_index (decl, flexible);
20683 if (index == ~(~0u >> 1))
20684 return -1;
20685 module_state *module = import_entity_module (index);
20686
20687 return module->mod;
20688 }
20689
20690 /* Is it permissible to redeclare OLDDECL with NEWDECL.
20691
20692 If NEWDECL is NULL, assumes that OLDDECL will be redeclared using
20693 the current scope's module and attachment. */
20694
20695 bool
20696 module_may_redeclare (tree olddecl, tree newdecl)
20697 {
20698 tree decl = olddecl;
20699 for (;;)
20700 {
20701 tree ctx = CP_DECL_CONTEXT (decl);
20702 if (TREE_CODE (ctx) == NAMESPACE_DECL)
20703 // Found the namespace-scope decl.
20704 break;
20705 if (!CLASS_TYPE_P (ctx))
20706 // We've met a non-class scope. Such a thing is not
20707 // reopenable, so we must be ok.
20708 return true;
20709 decl = TYPE_NAME (ctx);
20710 }
20711
20712 int use_tpl = 0;
20713 if (node_template_info (STRIP_TEMPLATE (decl), use_tpl) && use_tpl)
20714 // Specializations of any kind can be redeclared anywhere.
20715 // FIXME: Should we be checking this in more places on the scope chain?
20716 return true;
20717
20718 module_state *old_mod = get_primary ((*modules)[0]);
20719 module_state *new_mod = old_mod;
20720
20721 tree old_origin = get_originating_module_decl (decl);
20722 tree old_inner = STRIP_TEMPLATE (old_origin);
20723 bool olddecl_attached_p = (DECL_LANG_SPECIFIC (old_inner)
20724 && DECL_MODULE_ATTACH_P (old_inner));
20725 if (DECL_LANG_SPECIFIC (old_inner) && DECL_MODULE_IMPORT_P (old_inner))
20726 {
20727 unsigned index = import_entity_index (old_origin);
20728 old_mod = get_primary (import_entity_module (index));
20729 }
20730
20731 bool newdecl_attached_p = module_attach_p ();
20732 if (newdecl)
20733 {
20734 tree new_origin = get_originating_module_decl (newdecl);
20735 tree new_inner = STRIP_TEMPLATE (new_origin);
20736 newdecl_attached_p = (DECL_LANG_SPECIFIC (new_inner)
20737 && DECL_MODULE_ATTACH_P (new_inner));
20738 if (DECL_LANG_SPECIFIC (new_inner) && DECL_MODULE_IMPORT_P (new_inner))
20739 {
20740 unsigned index = import_entity_index (new_origin);
20741 new_mod = get_primary (import_entity_module (index));
20742 }
20743 }
20744
20745 /* Module attachment needs to match. */
20746 if (olddecl_attached_p == newdecl_attached_p)
20747 {
20748 if (!olddecl_attached_p)
20749 /* Both are GM entities, OK. */
20750 return true;
20751
20752 if (new_mod == old_mod)
20753 /* Both attached to same named module, OK. */
20754 return true;
20755 }
20756
20757 /* Attached to different modules, error. */
20758 decl = newdecl ? newdecl : olddecl;
20759 location_t loc = newdecl ? DECL_SOURCE_LOCATION (newdecl) : input_location;
20760 if (DECL_IS_UNDECLARED_BUILTIN (olddecl))
20761 {
20762 if (newdecl_attached_p)
20763 error_at (loc, "declaring %qD in module %qs conflicts with builtin "
20764 "in global module", decl, new_mod->get_flatname ());
20765 else
20766 error_at (loc, "declaration %qD conflicts with builtin", decl);
20767 }
20768 else if (DECL_LANG_SPECIFIC (old_inner) && DECL_MODULE_IMPORT_P (old_inner))
20769 {
20770 auto_diagnostic_group d;
20771 if (newdecl_attached_p)
20772 error_at (loc, "redeclaring %qD in module %qs conflicts with import",
20773 decl, new_mod->get_flatname ());
20774 else
20775 error_at (loc, "redeclaring %qD in global module conflicts with import",
20776 decl);
20777
20778 if (olddecl_attached_p)
20779 inform (DECL_SOURCE_LOCATION (olddecl),
20780 "import declared attached to module %qs",
20781 old_mod->get_flatname ());
20782 else
20783 inform (DECL_SOURCE_LOCATION (olddecl),
20784 "import declared in global module");
20785 }
20786 else
20787 {
20788 auto_diagnostic_group d;
20789 if (newdecl_attached_p)
20790 error_at (loc, "conflicting declaration of %qD in module %qs",
20791 decl, new_mod->get_flatname ());
20792 else
20793 error_at (loc, "conflicting declaration of %qD in global module",
20794 decl);
20795
20796 if (olddecl_attached_p)
20797 inform (DECL_SOURCE_LOCATION (olddecl),
20798 "previously declared in module %qs",
20799 old_mod->get_flatname ());
20800 else
20801 inform (DECL_SOURCE_LOCATION (olddecl),
20802 "previously declared in global module");
20803 }
20804 return false;
20805 }
20806
20807 /* DECL is being created by this TU. Record it came from here. We
20808 record module purview, so we can see if partial or explicit
20809 specialization needs to be written out, even though its purviewness
20810 comes from the most general template. */
20811
20812 void
20813 set_instantiating_module (tree decl)
20814 {
20815 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
20816 || VAR_P (decl)
20817 || TREE_CODE (decl) == TYPE_DECL
20818 || TREE_CODE (decl) == CONCEPT_DECL
20819 || TREE_CODE (decl) == TEMPLATE_DECL
20820 || TREE_CODE (decl) == CONST_DECL
20821 || (TREE_CODE (decl) == NAMESPACE_DECL
20822 && DECL_NAMESPACE_ALIAS (decl)));
20823
20824 if (!modules_p ())
20825 return;
20826
20827 decl = STRIP_TEMPLATE (decl);
20828
20829 if (!DECL_LANG_SPECIFIC (decl) && module_purview_p ())
20830 retrofit_lang_decl (decl);
20831
20832 if (DECL_LANG_SPECIFIC (decl))
20833 {
20834 DECL_MODULE_PURVIEW_P (decl) = module_purview_p ();
20835 /* If this was imported, we'll still be in the entity_hash. */
20836 DECL_MODULE_IMPORT_P (decl) = false;
20837 }
20838 }
20839
20840 /* If DECL is a class member, whose class is not defined in this TU
20841 (it was imported), remember this decl. */
20842
20843 void
20844 set_defining_module (tree decl)
20845 {
20846 gcc_checking_assert (!DECL_LANG_SPECIFIC (decl)
20847 || !DECL_MODULE_IMPORT_P (decl));
20848
20849 if (module_maybe_has_cmi_p ())
20850 {
20851 /* We need to track all declarations within a module, not just those
20852 in the module purview, because we don't necessarily know yet if
20853 this module will require a CMI while in the global fragment. */
20854 tree ctx = DECL_CONTEXT (decl);
20855 if (ctx
20856 && (TREE_CODE (ctx) == RECORD_TYPE || TREE_CODE (ctx) == UNION_TYPE)
20857 && DECL_LANG_SPECIFIC (TYPE_NAME (ctx))
20858 && DECL_MODULE_IMPORT_P (TYPE_NAME (ctx)))
20859 {
20860 /* This entity's context is from an import. We may need to
20861 record this entity to make sure we emit it in the CMI.
20862 Template specializations are in the template hash tables,
20863 so we don't need to record them here as well. */
20864 int use_tpl = -1;
20865 tree ti = node_template_info (decl, use_tpl);
20866 if (use_tpl <= 0)
20867 {
20868 if (ti)
20869 {
20870 gcc_checking_assert (!use_tpl);
20871 /* Get to the TEMPLATE_DECL. */
20872 decl = TI_TEMPLATE (ti);
20873 }
20874
20875 /* Record it on the class_members list. */
20876 vec_safe_push (class_members, decl);
20877 }
20878 }
20879 }
20880 }
20881
20882 /* Also remember DECL if it's a newly declared class template partial
20883 specialization, because these are not necessarily added to the
20884 instantiation tables. */
20885
20886 void
20887 set_defining_module_for_partial_spec (tree decl)
20888 {
20889 if (module_maybe_has_cmi_p ()
20890 && DECL_IMPLICIT_TYPEDEF_P (decl)
20891 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
20892 vec_safe_push (partial_specializations, decl);
20893 }
20894
20895 /* Record that DECL is declared in this TU, and note attachment and
20896 exporting for namespace-scope entities. FRIEND_P is true if
20897 this is a friend declaration. */
20898
20899 void
20900 set_originating_module (tree decl, bool friend_p ATTRIBUTE_UNUSED)
20901 {
20902 set_instantiating_module (decl);
20903
20904 /* DECL_CONTEXT may not be set yet when we're called for
20905 non-namespace-scope entities. */
20906 if (!DECL_CONTEXT (decl) || !DECL_NAMESPACE_SCOPE_P (decl))
20907 return;
20908
20909 gcc_checking_assert (friend_p || decl == get_originating_module_decl (decl));
20910
20911 if (module_attach_p ())
20912 {
20913 retrofit_lang_decl (decl);
20914 DECL_MODULE_ATTACH_P (decl) = true;
20915 }
20916
20917 /* It is ill-formed to export a declaration with internal linkage. However,
20918 at the point this function is called we don't yet always know whether this
20919 declaration has internal linkage; instead we defer this check for callers
20920 to do once visibility has been determined. */
20921 if (module_exporting_p ())
20922 DECL_MODULE_EXPORT_P (decl) = true;
20923 }
20924
20925 /* Checks whether DECL within a module unit has valid linkage for its kind.
20926 Must be called after visibility for DECL has been finalised. */
20927
20928 void
20929 check_module_decl_linkage (tree decl)
20930 {
20931 if (!module_has_cmi_p ())
20932 return;
20933
20934 /* A header unit shall not contain a definition of a non-inline function
20935 or variable (not template) whose name has external linkage. */
20936 if (header_module_p ()
20937 && !processing_template_decl
20938 && ((TREE_CODE (decl) == FUNCTION_DECL
20939 && !DECL_DECLARED_INLINE_P (decl))
20940 || (TREE_CODE (decl) == VAR_DECL
20941 && !DECL_INLINE_VAR_P (decl)))
20942 && decl_defined_p (decl)
20943 && !(DECL_LANG_SPECIFIC (decl)
20944 && DECL_TEMPLATE_INSTANTIATION (decl))
20945 && decl_linkage (decl) == lk_external)
20946 error_at (DECL_SOURCE_LOCATION (decl),
20947 "external linkage definition of %qD in header module must "
20948 "be declared %<inline%>", decl);
20949
20950 /* An internal-linkage declaration cannot be generally be exported.
20951 But it's OK to export any declaration from a header unit, including
20952 internal linkage declarations. */
20953 if (!header_module_p () && DECL_MODULE_EXPORT_P (decl))
20954 {
20955 /* Let's additionally treat any exported declaration within an
20956 internal namespace as exporting a declaration with internal
20957 linkage, as this would also implicitly export the internal
20958 linkage namespace. */
20959 if (decl_anon_ns_mem_p (decl))
20960 {
20961 error_at (DECL_SOURCE_LOCATION (decl),
20962 "exporting declaration %qD declared in unnamed namespace",
20963 decl);
20964 DECL_MODULE_EXPORT_P (decl) = false;
20965 }
20966 else if (decl_linkage (decl) == lk_internal)
20967 {
20968 error_at (DECL_SOURCE_LOCATION (decl),
20969 "exporting declaration %qD with internal linkage", decl);
20970 DECL_MODULE_EXPORT_P (decl) = false;
20971 }
20972 }
20973 }
20974
20975 /* DECL is keyed to CTX for odr purposes. */
20976
20977 void
20978 maybe_key_decl (tree ctx, tree decl)
20979 {
20980 if (!modules_p ())
20981 return;
20982
20983 /* We only need to deal with lambdas attached to var, field,
20984 parm, type, or concept decls. */
20985 if (TREE_CODE (ctx) != VAR_DECL
20986 && TREE_CODE (ctx) != FIELD_DECL
20987 && TREE_CODE (ctx) != PARM_DECL
20988 && TREE_CODE (ctx) != TYPE_DECL
20989 && TREE_CODE (ctx) != CONCEPT_DECL)
20990 return;
20991
20992 /* For members, key it to the containing type to handle deduplication
20993 correctly. For fields, this is necessary as FIELD_DECLs have no
20994 dep and so would only be streamed after the lambda type, defeating
20995 our ability to merge them.
20996
20997 Other class-scope key decls might depend on the type of the lambda
20998 but be within the same cluster; we need to ensure that we never
20999 first see the key decl while streaming the lambda type as merging
21000 would then fail when comparing the partially-streamed lambda type
21001 of the key decl with the existing (PR c++/122310).
21002
21003 Perhaps sort_cluster can be adjusted to handle this better, but
21004 this is a simple workaround (and might down on the number of
21005 entries in keyed_table as a bonus). */
21006 while (DECL_CLASS_SCOPE_P (ctx))
21007 ctx = TYPE_NAME (DECL_CONTEXT (ctx));
21008
21009 if (!keyed_table)
21010 keyed_table = new keyed_map_t (EXPERIMENT (1, 400));
21011
21012 auto &vec = keyed_table->get_or_insert (ctx);
21013 if (!vec.length ())
21014 {
21015 retrofit_lang_decl (ctx);
21016 DECL_MODULE_KEYED_DECLS_P (ctx) = true;
21017 }
21018 vec.safe_push (decl);
21019 }
21020
21021 /* Find the scope that the lambda DECL is keyed to, if any. */
21022
21023 static tree
21024 get_keyed_decl_scope (tree decl)
21025 {
21026 gcc_checking_assert (LAMBDA_TYPE_P (TREE_TYPE (decl)));
21027 tree scope = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (decl));
21028 if (!scope)
21029 return NULL_TREE;
21030
21031 gcc_checking_assert (TREE_CODE (scope) == VAR_DECL
21032 || TREE_CODE (scope) == FIELD_DECL
21033 || TREE_CODE (scope) == PARM_DECL
21034 || TREE_CODE (scope) == TYPE_DECL
21035 || TREE_CODE (scope) == CONCEPT_DECL);
21036
21037 while (DECL_CLASS_SCOPE_P (scope))
21038 scope = TYPE_NAME (DECL_CONTEXT (scope));
21039
21040 gcc_checking_assert (DECL_LANG_SPECIFIC (scope)
21041 && DECL_MODULE_KEYED_DECLS_P (scope));
21042 return scope;
21043 }
21044
21045 /* DECL is an instantiated friend that should be attached to the same
21046 module that ORIG is. */
21047
21048 void
21049 propagate_defining_module (tree decl, tree orig)
21050 {
21051 if (!modules_p ())
21052 return;
21053
21054 tree not_tmpl = STRIP_TEMPLATE (orig);
21055 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_ATTACH_P (not_tmpl))
21056 {
21057 tree inner = STRIP_TEMPLATE (decl);
21058 retrofit_lang_decl (inner);
21059 DECL_MODULE_ATTACH_P (inner) = true;
21060 }
21061
21062 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_IMPORT_P (not_tmpl))
21063 {
21064 bool exists = imported_temploid_friends->put (decl, orig);
21065
21066 /* We should only be called if lookup for an existing decl
21067 failed, in which case there shouldn't already be an entry
21068 in the map. */
21069 gcc_assert (!exists);
21070 }
21071 }
21072
21073 /* DECL is being freed, clear data we don't need anymore. */
21074
21075 void
21076 remove_defining_module (tree decl)
21077 {
21078 if (!modules_p ())
21079 return;
21080
21081 if (imported_temploid_friends)
21082 imported_temploid_friends->remove (decl);
21083 }
21084
21085 /* Create the flat name string. It is simplest to have it handy. */
21086
21087 void
21088 module_state::set_flatname ()
21089 {
21090 gcc_checking_assert (!flatname);
21091 if (parent)
21092 {
21093 auto_vec<tree,5> ids;
21094 size_t len = 0;
21095 char const *primary = NULL;
21096 size_t pfx_len = 0;
21097
21098 for (module_state *probe = this;
21099 probe;
21100 probe = probe->parent)
21101 if (is_partition () && !probe->is_partition ())
21102 {
21103 primary = probe->get_flatname ();
21104 pfx_len = strlen (primary);
21105 break;
21106 }
21107 else
21108 {
21109 ids.safe_push (probe->name);
21110 len += IDENTIFIER_LENGTH (probe->name) + 1;
21111 }
21112
21113 char *flat = XNEWVEC (char, pfx_len + len + is_partition ());
21114 flatname = flat;
21115
21116 if (primary)
21117 {
21118 memcpy (flat, primary, pfx_len);
21119 flat += pfx_len;
21120 *flat++ = ':';
21121 }
21122
21123 for (unsigned len = 0; ids.length ();)
21124 {
21125 if (len)
21126 flat[len++] = '.';
21127 tree elt = ids.pop ();
21128 unsigned l = IDENTIFIER_LENGTH (elt);
21129 memcpy (flat + len, IDENTIFIER_POINTER (elt), l + 1);
21130 len += l;
21131 }
21132 }
21133 else if (is_header ())
21134 flatname = TREE_STRING_POINTER (name);
21135 else
21136 flatname = IDENTIFIER_POINTER (name);
21137 }
21138
21139 /* Read the CMI file for a module. */
21140
21141 bool
21142 module_state::do_import (cpp_reader *reader, bool outermost)
21143 {
21144 gcc_assert (global_namespace == current_scope () && loadedness == ML_NONE);
21145
21146 loc = linemap_module_loc (line_table, loc, get_flatname ());
21147
21148 if (lazy_open >= lazy_limit)
21149 freeze_an_elf ();
21150
21151 int fd = -1;
21152 int e = ENOENT;
21153 if (filename)
21154 {
21155 const char *file = maybe_add_cmi_prefix (filename);
21156 dump () && dump ("CMI is %s", file);
21157 if (note_module_cmi_yes || inform_cmi_p)
21158 inform (loc, "reading CMI %qs", file);
21159 /* Add the CMI file to the dependency tracking. */
21160 if (cpp_get_deps (reader))
21161 deps_add_dep (cpp_get_deps (reader), file);
21162 fd = open (file, O_RDONLY | O_CLOEXEC | O_BINARY);
21163 e = errno;
21164 }
21165
21166 gcc_checking_assert (!slurp);
21167 slurp = new slurping (new elf_in (fd, e));
21168
21169 bool ok = true;
21170 if (!from ()->get_error ())
21171 {
21172 announce ("importing");
21173 loadedness = ML_CONFIG;
21174 lazy_open++;
21175 ok = read_initial (reader);
21176 slurp->lru = ++lazy_lru;
21177 }
21178
21179 gcc_assert (slurp->current == ~0u);
21180
21181 return check_read (outermost, ok);
21182 }
21183
21184 /* Attempt to increase the file descriptor limit. */
21185
21186 static bool
21187 try_increase_lazy (unsigned want)
21188 {
21189 gcc_checking_assert (lazy_open >= lazy_limit);
21190
21191 /* If we're increasing, saturate at hard limit. */
21192 if (want > lazy_hard_limit && lazy_limit < lazy_hard_limit)
21193 want = lazy_hard_limit;
21194
21195 #if HAVE_SETRLIMIT
21196 if ((!lazy_limit || !param_lazy_modules)
21197 && lazy_hard_limit
21198 && want <= lazy_hard_limit)
21199 {
21200 struct rlimit rlimit;
21201 rlimit.rlim_cur = want + LAZY_HEADROOM;
21202 rlimit.rlim_max = lazy_hard_limit + LAZY_HEADROOM;
21203 if (!setrlimit (RLIMIT_NOFILE, &rlimit))
21204 lazy_limit = want;
21205 }
21206 #endif
21207
21208 return lazy_open < lazy_limit;
21209 }
21210
21211 /* Pick a victim module to freeze its reader. */
21212
21213 void
21214 module_state::freeze_an_elf ()
21215 {
21216 if (try_increase_lazy (lazy_open * 2))
21217 return;
21218
21219 module_state *victim = NULL;
21220 for (unsigned ix = modules->length (); ix--;)
21221 {
21222 module_state *candidate = (*modules)[ix];
21223 if (candidate && candidate->slurp && candidate->slurp->lru
21224 && candidate->from ()->is_freezable ()
21225 && (!victim || victim->slurp->lru > candidate->slurp->lru))
21226 victim = candidate;
21227 }
21228
21229 if (victim)
21230 {
21231 dump () && dump ("Freezing '%s'", victim->filename);
21232 if (victim->slurp->macro_defs.size)
21233 /* Save the macro definitions to a buffer. */
21234 victim->from ()->preserve (victim->slurp->macro_defs);
21235 if (victim->slurp->macro_tbl.size)
21236 /* Save the macro definitions to a buffer. */
21237 victim->from ()->preserve (victim->slurp->macro_tbl);
21238 victim->from ()->freeze ();
21239 lazy_open--;
21240 }
21241 else
21242 dump () && dump ("No module available for freezing");
21243 }
21244
21245 /* Load the lazy slot *MSLOT, INDEX'th slot of the module. */
21246
21247 bool
21248 module_state::lazy_load (unsigned index, binding_slot *mslot)
21249 {
21250 unsigned n = dump.push (this);
21251
21252 gcc_checking_assert (function_depth);
21253
21254 unsigned cookie = mslot->get_lazy ();
21255 unsigned snum = cookie >> 2;
21256 dump () && dump ("Loading entity %M[%u] section:%u", this, index, snum);
21257
21258 bool ok = load_section (snum, mslot);
21259
21260 dump.pop (n);
21261
21262 return ok;
21263 }
21264
21265 /* Load MOD's binding for NS::ID into *MSLOT. *MSLOT contains the
21266 lazy cookie. OUTER is true if this is the outermost lazy, (used
21267 for diagnostics). */
21268
21269 void
21270 lazy_load_binding (unsigned mod, tree ns, tree id, binding_slot *mslot)
21271 {
21272 int count = errorcount + warningcount;
21273
21274 bool timer_running = timevar_cond_start (TV_MODULE_IMPORT);
21275
21276 /* Make sure lazy loading from a template context behaves as if
21277 from a non-template context. */
21278 processing_template_decl_sentinel ptds;
21279
21280 /* Stop GC happening, even in outermost loads (because our caller
21281 could well be building up a lookup set). */
21282 function_depth++;
21283
21284 gcc_checking_assert (mod);
21285 module_state *module = (*modules)[mod];
21286 unsigned n = dump.push (module);
21287
21288 unsigned snum = mslot->get_lazy ();
21289 dump () && dump ("Lazily binding %P@%N section:%u", ns, id,
21290 module->name, snum);
21291
21292 bool ok = !recursive_lazy (snum);
21293 if (ok)
21294 {
21295 ok = module->load_section (snum, mslot);
21296 lazy_snum = 0;
21297 post_load_processing ();
21298 }
21299
21300 dump.pop (n);
21301
21302 function_depth--;
21303
21304 timevar_cond_stop (TV_MODULE_IMPORT, timer_running);
21305
21306 if (!ok)
21307 fatal_error (input_location,
21308 module->is_header ()
21309 ? G_("failed to load binding %<%E%s%E%>")
21310 : G_("failed to load binding %<%E%s%E@%s%>"),
21311 ns, &"::"[ns == global_namespace ? 2 : 0], id,
21312 module->get_flatname ());
21313
21314 if (count != errorcount + warningcount)
21315 inform (input_location,
21316 module->is_header ()
21317 ? G_("during load of binding %<%E%s%E%>")
21318 : G_("during load of binding %<%E%s%E@%s%>"),
21319 ns, &"::"[ns == global_namespace ? 2 : 0], id,
21320 module->get_flatname ());
21321 }
21322
21323 /* Load any pending entities keyed to the top-key of DECL. */
21324
21325 void
21326 lazy_load_pendings (tree decl)
21327 {
21328 /* Make sure lazy loading from a template context behaves as if
21329 from a non-template context. */
21330 processing_template_decl_sentinel ptds;
21331
21332 tree key_decl;
21333 pending_key key;
21334 key.ns = find_pending_key (decl, &key_decl);
21335 key.id = DECL_NAME (key_decl);
21336
21337 auto *pending_vec = pending_table ? pending_table->get (key) : nullptr;
21338 if (!pending_vec)
21339 return;
21340
21341 int count = errorcount + warningcount;
21342
21343 bool timer_running = timevar_cond_start (TV_MODULE_IMPORT);
21344 bool ok = !recursive_lazy ();
21345 if (ok)
21346 {
21347 function_depth++; /* Prevent GC */
21348 unsigned n = dump.push (NULL);
21349 dump () && dump ("Reading %u pending entities keyed to %P",
21350 pending_vec->length (), key.ns, key.id);
21351 for (unsigned ix = pending_vec->length (); ix--;)
21352 {
21353 unsigned index = (*pending_vec)[ix];
21354 binding_slot *slot = &(*entity_ary)[index];
21355
21356 if (slot->is_lazy ())
21357 {
21358 module_state *import = import_entity_module (index);
21359 if (!import->lazy_load (index - import->entity_lwm, slot))
21360 ok = false;
21361 }
21362 else if (dump ())
21363 {
21364 module_state *import = import_entity_module (index);
21365 dump () && dump ("Entity %M[%u] already loaded",
21366 import, index - import->entity_lwm);
21367 }
21368 }
21369
21370 pending_table->remove (key);
21371 dump.pop (n);
21372 lazy_snum = 0;
21373 post_load_processing ();
21374 function_depth--;
21375 }
21376
21377 timevar_cond_stop (TV_MODULE_IMPORT, timer_running);
21378
21379 if (!ok)
21380 fatal_error (input_location, "failed to load pendings for %<%E%s%E%>",
21381 key.ns, &"::"[key.ns == global_namespace ? 2 : 0], key.id);
21382
21383 if (count != errorcount + warningcount)
21384 inform (input_location, "during load of pendings for %<%E%s%E%>",
21385 key.ns, &"::"[key.ns == global_namespace ? 2 : 0], key.id);
21386 }
21387
21388 static void
21389 direct_import (module_state *import, cpp_reader *reader)
21390 {
21391 timevar_start (TV_MODULE_IMPORT);
21392 unsigned n = dump.push (import);
21393
21394 gcc_checking_assert (import->is_direct () && import->has_location ());
21395 if (import->loadedness == ML_NONE)
21396 if (!import->do_import (reader, true))
21397 gcc_unreachable ();
21398
21399 if (import->loadedness < ML_LANGUAGE)
21400 {
21401 if (!keyed_table)
21402 keyed_table = new keyed_map_t (EXPERIMENT (1, 400));
21403 import->read_language (true);
21404 }
21405
21406 (*modules)[0]->set_import (import, import->exported_p);
21407
21408 dump.pop (n);
21409 timevar_stop (TV_MODULE_IMPORT);
21410 }
21411
21412 /* Import module IMPORT. */
21413
21414 void
21415 import_module (module_state *import, location_t from_loc, bool exporting_p,
21416 tree, cpp_reader *reader)
21417 {
21418 if (!import->check_not_purview (from_loc))
21419 return;
21420
21421 if (!import->is_header () && current_lang_depth ())
21422 /* Only header units should appear inside language
21423 specifications. The std doesn't specify this, but I think
21424 that's an error in resolving US 033, because language linkage
21425 is also our escape clause to getting things into the global
21426 module, so we don't want to confuse things by having to think
21427 about whether 'extern "C++" { import foo; }' puts foo's
21428 contents into the global module all of a sudden. */
21429 warning (0, "import of named module %qs inside language-linkage block",
21430 import->get_flatname ());
21431
21432 if (exporting_p || module_exporting_p ())
21433 import->exported_p = true;
21434
21435 if (import->loadedness != ML_NONE)
21436 {
21437 from_loc = ordinary_loc_of (line_table, from_loc);
21438 linemap_module_reparent (line_table, import->loc, from_loc);
21439 }
21440 gcc_checking_assert (!import->module_p);
21441 gcc_checking_assert (import->is_direct () && import->has_location ());
21442
21443 direct_import (import, reader);
21444 }
21445
21446 /* Declare the name of the current module to be NAME. EXPORTING_p is
21447 true if this TU is the exporting module unit. */
21448
21449 void
21450 declare_module (module_state *module, location_t from_loc, bool exporting_p,
21451 tree, cpp_reader *reader)
21452 {
21453 gcc_assert (global_namespace == current_scope ());
21454
21455 module_state *current = (*modules)[0];
21456 if (module_purview_p () || module->loadedness > ML_CONFIG)
21457 {
21458 auto_diagnostic_group d;
21459 error_at (from_loc, module_purview_p ()
21460 ? G_("module already declared")
21461 : G_("module already imported"));
21462 if (module_purview_p ())
21463 module = current;
21464 inform (module->loc, module_purview_p ()
21465 ? G_("module %qs declared here")
21466 : G_("module %qs imported here"),
21467 module->get_flatname ());
21468 return;
21469 }
21470
21471 gcc_checking_assert (module->module_p);
21472 gcc_checking_assert (module->is_direct () && module->has_location ());
21473
21474 /* Yer a module, 'arry. */
21475 module_kind = module->is_header () ? MK_HEADER : MK_NAMED | MK_ATTACH;
21476
21477 // Even in header units, we consider the decls to be purview
21478 module_kind |= MK_PURVIEW;
21479
21480 if (module->is_partition ())
21481 module_kind |= MK_PARTITION;
21482 if (exporting_p)
21483 {
21484 module->interface_p = true;
21485 module_kind |= MK_INTERFACE;
21486 }
21487
21488 if (module_has_cmi_p ())
21489 {
21490 /* Copy the importing information we may have already done. We
21491 do not need to separate out the imports that only happen in
21492 the GMF, inspite of what the literal wording of the std
21493 might imply. See p2191, the core list had a discussion
21494 where the module implementors agreed that the GMF of a named
21495 module is invisible to importers. */
21496 module->imports = current->imports;
21497
21498 module->mod = 0;
21499 (*modules)[0] = module;
21500 }
21501 else
21502 {
21503 module->interface_p = true;
21504 current->parent = module; /* So mangler knows module identity. */
21505 direct_import (module, reader);
21506 }
21507 }
21508
21509 /* Return true IFF we must emit a module global initializer function
21510 (which will be called by importers' init code). */
21511
21512 bool
21513 module_global_init_needed ()
21514 {
21515 return module_has_cmi_p () && !header_module_p ();
21516 }
21517
21518 /* Calculate which, if any, import initializers need calling. */
21519
21520 bool
21521 module_determine_import_inits ()
21522 {
21523 if (!modules || header_module_p ())
21524 return false;
21525
21526 /* Prune active_init_p. We need the same bitmap allocation
21527 scheme as for the imports member. */
21528 function_depth++; /* Disable GC. */
21529 bitmap covered_imports (BITMAP_GGC_ALLOC ());
21530
21531 bool any = false;
21532
21533 /* Because indirect imports are before their direct import, and
21534 we're scanning the array backwards, we only need one pass! */
21535 for (unsigned ix = modules->length (); --ix;)
21536 {
21537 module_state *import = (*modules)[ix];
21538
21539 if (!import->active_init_p)
21540 ;
21541 else if (bitmap_bit_p (covered_imports, ix))
21542 import->active_init_p = false;
21543 else
21544 {
21545 /* Everything this imports is therefore handled by its
21546 initializer, so doesn't need initializing by us. */
21547 bitmap_ior_into (covered_imports, import->imports);
21548 any = true;
21549 }
21550 }
21551 function_depth--;
21552
21553 return any;
21554 }
21555
21556 /* Emit calls to each direct import's global initializer. Including
21557 direct imports of directly imported header units. The initializers
21558 of (static) entities in header units will be called by their
21559 importing modules (for the instance contained within that), or by
21560 the current TU (for the instances we've brought in). Of course
21561 such header unit behaviour is evil, but iostream went through that
21562 door some time ago. */
21563
21564 void
21565 module_add_import_initializers ()
21566 {
21567 if (!modules || header_module_p ())
21568 return;
21569
21570 tree fntype = build_function_type (void_type_node, void_list_node);
21571 releasing_vec args; // There are no args
21572
21573 for (unsigned ix = modules->length (); --ix;)
21574 {
21575 module_state *import = (*modules)[ix];
21576 if (import->active_init_p)
21577 {
21578 tree name = mangle_module_global_init (ix);
21579 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
21580
21581 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
21582 SET_DECL_ASSEMBLER_NAME (fndecl, name);
21583 TREE_PUBLIC (fndecl) = true;
21584 determine_visibility (fndecl);
21585
21586 tree call = cp_build_function_call_vec (fndecl, &args,
21587 tf_warning_or_error);
21588 finish_expr_stmt (call);
21589 }
21590 }
21591 }
21592
21593 /* NAME & LEN are a preprocessed header name, possibly including the
21594 surrounding "" or <> characters. Return the raw string name of the
21595 module to which it refers. This will be an absolute path, or begin
21596 with ./, so it is immediately distinguishable from a (non-header
21597 unit) module name. If READER is non-null, ask the preprocessor to
21598 locate the header to which it refers using the appropriate include
21599 path. Note that we do never do \ processing of the string, as that
21600 matches the preprocessor's behaviour. */
21601
21602 static const char *
21603 canonicalize_header_name (cpp_reader *reader, location_t loc, bool unquoted,
21604 const char *str, size_t &len_r)
21605 {
21606 size_t len = len_r;
21607 static char *buf = 0;
21608 static size_t alloc = 0;
21609
21610 if (!unquoted)
21611 {
21612 gcc_checking_assert (len >= 2
21613 && ((reader && str[0] == '<' && str[len-1] == '>')
21614 || (str[0] == '"' && str[len-1] == '"')));
21615 str += 1;
21616 len -= 2;
21617 }
21618
21619 if (reader)
21620 {
21621 gcc_assert (!unquoted);
21622
21623 if (len >= alloc)
21624 {
21625 alloc = len + 1;
21626 buf = XRESIZEVEC (char, buf, alloc);
21627 }
21628 memcpy (buf, str, len);
21629 buf[len] = 0;
21630
21631 if (const char *hdr
21632 = cpp_probe_header_unit (reader, buf, str[-1] == '<', loc))
21633 {
21634 len = strlen (hdr);
21635 str = hdr;
21636 }
21637 else
21638 str = buf;
21639 }
21640
21641 if (!(str[0] == '.' ? IS_DIR_SEPARATOR (str[1]) : IS_ABSOLUTE_PATH (str)))
21642 {
21643 /* Prepend './' */
21644 if (len + 3 > alloc)
21645 {
21646 alloc = len + 3;
21647 buf = XRESIZEVEC (char, buf, alloc);
21648 }
21649
21650 buf[0] = '.';
21651 buf[1] = DIR_SEPARATOR;
21652 memmove (buf + 2, str, len);
21653 len += 2;
21654 buf[len] = 0;
21655 str = buf;
21656 }
21657
21658 len_r = len;
21659 return str;
21660 }
21661
21662 /* Set the CMI name from a cody packet. Issue an error if
21663 ill-formed. */
21664
21665 void module_state::set_filename (const Cody::Packet &packet)
21666 {
21667 if (packet.GetCode () == Cody::Client::PC_PATHNAME)
21668 {
21669 /* If we've seen this import before we better have the same CMI. */
21670 const std::string &path = packet.GetString ();
21671 if (!filename)
21672 filename = xstrdup (packet.GetString ().c_str ());
21673 else if (filename != path)
21674 error_at (loc, "mismatching compiled module interface: "
21675 "had %qs, got %qs", filename, path.c_str ());
21676 }
21677 else
21678 {
21679 gcc_checking_assert (packet.GetCode () == Cody::Client::PC_ERROR);
21680 fatal_error (loc, "unknown compiled module interface: %s",
21681 packet.GetString ().c_str ());
21682 }
21683 }
21684
21685 /* Figure out whether to treat HEADER as an include or an import. */
21686
21687 static char *
21688 maybe_translate_include (cpp_reader *reader, line_maps *lmaps, location_t loc,
21689 const char *path)
21690 {
21691 if (!modules_p ())
21692 {
21693 /* Turn off. */
21694 cpp_get_callbacks (reader)->translate_include = NULL;
21695 return nullptr;
21696 }
21697
21698 dump.push (NULL);
21699
21700 dump () && dump ("Checking include translation '%s'", path);
21701 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
21702
21703 size_t len = strlen (path);
21704 path = canonicalize_header_name (NULL, loc, true, path, len);
21705 auto packet = mapper->IncludeTranslate (path, Cody::Flags::None, len);
21706
21707 enum class xlate_kind {
21708 unknown, text, import,
21709 } translate = xlate_kind::unknown;
21710
21711 if (packet.GetCode () == Cody::Client::PC_BOOL)
21712 translate = packet.GetInteger () ? xlate_kind::text : xlate_kind::unknown;
21713 else if (packet.GetCode () == Cody::Client::PC_PATHNAME)
21714 {
21715 /* Record the CMI name for when we do the import.
21716 We may already know about this import, but libcpp doesn't yet. */
21717 module_state *import = get_module (build_string (len, path));
21718 import->set_filename (packet);
21719 translate = xlate_kind::import;
21720 }
21721 else
21722 {
21723 gcc_checking_assert (packet.GetCode () == Cody::Client::PC_ERROR);
21724 error_at (loc, "cannot determine %<#include%> translation of %s: %s",
21725 path, packet.GetString ().c_str ());
21726 }
21727
21728 bool note = false;
21729 if (note_include_translate_yes && translate == xlate_kind::import)
21730 note = true;
21731 else if (note_include_translate_no && translate == xlate_kind::unknown)
21732 note = true;
21733 else if (note_includes)
21734 /* We do not expect the note_includes vector to be large, so O(N)
21735 iteration. */
21736 for (unsigned ix = note_includes->length (); !note && ix--;)
21737 if (!strcmp ((*note_includes)[ix], path))
21738 note = true;
21739
21740 if (note)
21741 inform (loc, translate == xlate_kind::import
21742 ? G_("include %qs translated to import")
21743 : G_("include %qs processed textually"), path);
21744
21745 dump () && dump (translate == xlate_kind::import
21746 ? "Translating include to import"
21747 : "Keeping include as include");
21748 dump.pop (0);
21749
21750 if (translate != xlate_kind::import)
21751 return nullptr;
21752
21753 /* Create the translation text. */
21754 loc = ordinary_loc_of (lmaps, loc);
21755 const line_map_ordinary *map
21756 = linemap_check_ordinary (linemap_lookup (lmaps, loc));
21757 unsigned col = SOURCE_COLUMN (map, loc);
21758 col -= (col != 0); /* Columns are 1-based. */
21759
21760 unsigned alloc = len + col + 60;
21761 char *res = XNEWVEC (char, alloc);
21762
21763 strcpy (res, "__import");
21764 unsigned actual = 8;
21765 if (col > actual)
21766 {
21767 /* Pad out so the filename appears at the same position. */
21768 memset (res + actual, ' ', col - actual);
21769 actual = col;
21770 }
21771 /* No need to encode characters, that's not how header names are
21772 handled. */
21773 actual += snprintf (res + actual, alloc - actual,
21774 "\"%s\" [[__translated]];\n", path);
21775 gcc_checking_assert (actual < alloc);
21776
21777 /* cpplib will delete the buffer. */
21778 return res;
21779 }
21780
21781 static void
21782 begin_header_unit (cpp_reader *reader)
21783 {
21784 /* Set the module header name from the main_input_filename. */
21785 const char *main = main_input_filename;
21786 size_t len = strlen (main);
21787 main = canonicalize_header_name (NULL, 0, true, main, len);
21788 module_state *module = get_module (build_string (len, main));
21789
21790 preprocess_module (module, cpp_main_loc (reader), false, false, true, reader);
21791 }
21792
21793 /* We've just properly entered the main source file. I.e. after the
21794 command line, builtins and forced headers. Record the line map and
21795 location of this map. Note we may be called more than once. The
21796 first call sticks. */
21797
21798 void
21799 module_begin_main_file (cpp_reader *reader, line_maps *lmaps,
21800 const line_map_ordinary *map)
21801 {
21802 gcc_checking_assert (lmaps == line_table);
21803 if (modules_p () && !spans.init_p ())
21804 {
21805 unsigned n = dump.push (NULL);
21806 spans.init (lmaps, map);
21807 dump.pop (n);
21808 if (flag_header_unit && !cpp_get_options (reader)->preprocessed)
21809 {
21810 /* Tell the preprocessor this is an include file. */
21811 cpp_retrofit_as_include (reader);
21812 begin_header_unit (reader);
21813 }
21814 }
21815 }
21816
21817 /* Process the pending_import queue, making sure we know the
21818 filenames. */
21819
21820 static void
21821 name_pending_imports (cpp_reader *reader)
21822 {
21823 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
21824
21825 if (!vec_safe_length (pending_imports))
21826 /* Not doing anything. */
21827 return;
21828
21829 timevar_start (TV_MODULE_MAPPER);
21830
21831 auto n = dump.push (NULL);
21832 dump () && dump ("Resolving direct import names");
21833 bool want_deps = (bool (mapper->get_flags () & Cody::Flags::NameOnly)
21834 || cpp_get_deps (reader));
21835 bool any = false;
21836
21837 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
21838 {
21839 module_state *module = (*pending_imports)[ix];
21840 gcc_checking_assert (module->is_direct ());
21841 if (!module->filename && !module->visited_p)
21842 {
21843 bool export_p = (module->module_p
21844 && (module->is_partition () || module->exported_p));
21845
21846 Cody::Flags flags = Cody::Flags::None;
21847 if (flag_preprocess_only
21848 && !(module->is_header () && !export_p))
21849 {
21850 if (!want_deps)
21851 continue;
21852 flags = Cody::Flags::NameOnly;
21853 }
21854
21855 if (!any)
21856 {
21857 any = true;
21858 mapper->Cork ();
21859 }
21860 if (export_p)
21861 mapper->ModuleExport (module->get_flatname (), flags);
21862 else
21863 mapper->ModuleImport (module->get_flatname (), flags);
21864 module->visited_p = true;
21865 }
21866 }
21867
21868 if (any)
21869 {
21870 auto response = mapper->Uncork ();
21871 auto r_iter = response.begin ();
21872 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
21873 {
21874 module_state *module = (*pending_imports)[ix];
21875 if (module->visited_p)
21876 {
21877 module->visited_p = false;
21878 gcc_checking_assert (!module->filename);
21879
21880 module->set_filename (*r_iter);
21881 ++r_iter;
21882 }
21883 }
21884 }
21885
21886 dump.pop (n);
21887
21888 timevar_stop (TV_MODULE_MAPPER);
21889 }
21890
21891 /* We've just lexed a module-specific control line for MODULE. Mark
21892 the module as a direct import, and possibly load up its macro
21893 state. Returns the primary module, if this is a module
21894 declaration. */
21895 /* Perhaps we should offer a preprocessing mode where we read the
21896 directives from the header unit, rather than require the header's
21897 CMI. */
21898
21899 module_state *
21900 preprocess_module (module_state *module, location_t from_loc,
21901 bool in_purview, bool is_import, bool is_export,
21902 cpp_reader *reader)
21903 {
21904 if (!is_import)
21905 {
21906 if (module->loc)
21907 /* It's already been mentioned, so ignore its module-ness. */
21908 is_import = true;
21909 else
21910 {
21911 /* Record it is the module. */
21912 module->module_p = true;
21913 if (is_export)
21914 {
21915 module->exported_p = true;
21916 module->interface_p = true;
21917 }
21918 }
21919 }
21920
21921 if (module->directness < MD_DIRECT + in_purview)
21922 {
21923 /* Mark as a direct import. */
21924 module->directness = module_directness (MD_DIRECT + in_purview);
21925
21926 /* Set the location to be most informative for users. */
21927 from_loc = ordinary_loc_of (line_table, from_loc);
21928 if (module->loadedness != ML_NONE)
21929 linemap_module_reparent (line_table, module->loc, from_loc);
21930 else
21931 {
21932 module->loc = from_loc;
21933 if (!module->flatname)
21934 module->set_flatname ();
21935 }
21936 }
21937
21938 auto desired = ML_CONFIG;
21939 if (is_import
21940 && module->is_header ()
21941 && (!cpp_get_options (reader)->preprocessed
21942 || cpp_get_options (reader)->directives_only))
21943 /* We need preprocessor state now. */
21944 desired = ML_PREPROCESSOR;
21945
21946 if (!is_import || module->loadedness < desired)
21947 {
21948 vec_safe_push (pending_imports, module);
21949
21950 if (desired == ML_PREPROCESSOR)
21951 {
21952 unsigned n = dump.push (NULL);
21953
21954 dump () && dump ("Reading %M preprocessor state", module);
21955 name_pending_imports (reader);
21956
21957 /* Preserve the state of the line-map. */
21958 auto pre_hwm = LINEMAPS_ORDINARY_USED (line_table);
21959
21960 /* We only need to close the span, if we're going to emit a
21961 CMI. But that's a little tricky -- our token scanner
21962 needs to be smarter -- and this isn't much state.
21963 Remember, we've not parsed anything at this point, so
21964 our module state flags are inadequate. */
21965 spans.maybe_init ();
21966 spans.close ();
21967
21968 timevar_start (TV_MODULE_IMPORT);
21969
21970 /* Load the config of each pending import -- we must assign
21971 module numbers monotonically. */
21972 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
21973 {
21974 auto *import = (*pending_imports)[ix];
21975 if (!(import->module_p
21976 && (import->is_partition () || import->exported_p))
21977 && import->loadedness == ML_NONE
21978 && (import->is_header () || !flag_preprocess_only))
21979 {
21980 unsigned n = dump.push (import);
21981 import->do_import (reader, true);
21982 dump.pop (n);
21983 }
21984 }
21985 vec_free (pending_imports);
21986
21987 /* Restore the line-map state. */
21988 spans.open (linemap_module_restore (line_table, pre_hwm));
21989
21990 /* Now read the preprocessor state of this particular
21991 import. */
21992 if (module->loadedness == ML_CONFIG
21993 && module->read_preprocessor (true))
21994 module->import_macros ();
21995
21996 timevar_stop (TV_MODULE_IMPORT);
21997
21998 dump.pop (n);
21999 }
22000 }
22001
22002 return is_import ? NULL : get_primary (module);
22003 }
22004
22005 /* We've completed phase-4 translation. Emit any dependency
22006 information for the not-yet-loaded direct imports, and fill in
22007 their file names. We'll have already loaded up the direct header
22008 unit wavefront. */
22009
22010 void
22011 preprocessed_module (cpp_reader *reader)
22012 {
22013 unsigned n = dump.push (NULL);
22014
22015 dump () && dump ("Completed phase-4 (tokenization) processing");
22016
22017 name_pending_imports (reader);
22018 vec_free (pending_imports);
22019
22020 spans.maybe_init ();
22021 spans.close ();
22022
22023 using iterator = hash_table<module_state_hash>::iterator;
22024 if (mkdeps *deps = cpp_get_deps (reader))
22025 {
22026 /* Walk the module hash, informing the dependency machinery. */
22027 iterator end = modules_hash->end ();
22028 for (iterator iter = modules_hash->begin (); iter != end; ++iter)
22029 {
22030 module_state *module = *iter;
22031
22032 if (module->is_direct ())
22033 {
22034 if (module->is_module ()
22035 && (module->is_interface () || module->is_partition ()))
22036 deps_add_module_target (deps, module->get_flatname (),
22037 maybe_add_cmi_prefix (module->filename),
22038 module->is_header (),
22039 module->is_exported ());
22040 else
22041 deps_add_module_dep (deps, module->get_flatname ());
22042 }
22043 }
22044 }
22045
22046 if (flag_header_unit && !flag_preprocess_only)
22047 {
22048 /* Find the main module -- remember, it's not yet in the module
22049 array. */
22050 iterator end = modules_hash->end ();
22051 for (iterator iter = modules_hash->begin (); iter != end; ++iter)
22052 {
22053 module_state *module = *iter;
22054 if (module->is_module ())
22055 {
22056 declare_module (module, cpp_main_loc (reader), true, NULL, reader);
22057 module_kind |= MK_EXPORTING;
22058 break;
22059 }
22060 }
22061 }
22062
22063 dump.pop (n);
22064 }
22065
22066 /* VAL is a global tree, add it to the global vec if it is
22067 interesting. Add some of its targets, if they too are
22068 interesting. We do not add identifiers, as they can be re-found
22069 via the identifier hash table. There is a cost to the number of
22070 global trees. */
22071
22072 static int
22073 maybe_add_global (tree val, unsigned &crc)
22074 {
22075 int v = 0;
22076
22077 if (val && !(identifier_p (val) || TREE_VISITED (val)))
22078 {
22079 TREE_VISITED (val) = true;
22080 crc = crc32_unsigned (crc, fixed_trees->length ());
22081 vec_safe_push (fixed_trees, val);
22082 v++;
22083
22084 if (CODE_CONTAINS_STRUCT (TREE_CODE (val), TS_TYPED))
22085 v += maybe_add_global (TREE_TYPE (val), crc);
22086 if (CODE_CONTAINS_STRUCT (TREE_CODE (val), TS_TYPE_COMMON))
22087 v += maybe_add_global (TYPE_NAME (val), crc);
22088 }
22089
22090 return v;
22091 }
22092
22093 /* Initialize module state. Create the hash table, determine the
22094 global trees. Create the module for current TU. */
22095
22096 void
22097 init_modules (cpp_reader *reader)
22098 {
22099 /* PCH should not be reachable because of lang-specs, but the
22100 user could have overriden that. */
22101 if (pch_file)
22102 fatal_error (input_location,
22103 "C++ modules are incompatible with precompiled headers");
22104
22105 if (cpp_get_options (reader)->traditional)
22106 fatal_error (input_location,
22107 "C++ modules are incompatible with traditional preprocessing");
22108
22109 /* :: is always exported. */
22110 DECL_MODULE_EXPORT_P (global_namespace) = true;
22111
22112 modules_hash = hash_table<module_state_hash>::create_ggc (31);
22113 vec_safe_reserve (modules, 20);
22114
22115 /* Create module for current TU. */
22116 module_state *current
22117 = new (ggc_alloc<module_state> ()) module_state (NULL_TREE, NULL, false);
22118 current->mod = 0;
22119 bitmap_set_bit (current->imports, 0);
22120 modules->quick_push (current);
22121
22122 gcc_checking_assert (!fixed_trees);
22123
22124 headers = BITMAP_GGC_ALLOC ();
22125
22126 if (note_includes)
22127 /* Canonicalize header names. */
22128 for (unsigned ix = 0; ix != note_includes->length (); ix++)
22129 {
22130 const char *hdr = (*note_includes)[ix];
22131 size_t len = strlen (hdr);
22132
22133 bool system = hdr[0] == '<';
22134 bool user = hdr[0] == '"';
22135 bool delimed = system || user;
22136
22137 if (len <= (delimed ? 2 : 0)
22138 || (delimed && hdr[len-1] != (system ? '>' : '"')))
22139 error ("invalid header name %qs", hdr);
22140
22141 hdr = canonicalize_header_name (delimed ? reader : NULL,
22142 0, !delimed, hdr, len);
22143 char *path = XNEWVEC (char, len + 1);
22144 memcpy (path, hdr, len);
22145 path[len] = 0;
22146
22147 (*note_includes)[ix] = path;
22148 }
22149
22150 if (note_cmis)
22151 /* Canonicalize & mark module names. */
22152 for (unsigned ix = 0; ix != note_cmis->length (); ix++)
22153 {
22154 const char *name = (*note_cmis)[ix];
22155 size_t len = strlen (name);
22156
22157 bool is_system = name[0] == '<';
22158 bool is_user = name[0] == '"';
22159 bool is_pathname = false;
22160 if (!(is_system || is_user))
22161 for (unsigned ix = len; !is_pathname && ix--;)
22162 is_pathname = IS_DIR_SEPARATOR (name[ix]);
22163 if (is_system || is_user || is_pathname)
22164 {
22165 if (len <= (is_pathname ? 0 : 2)
22166 || (!is_pathname && name[len-1] != (is_system ? '>' : '"')))
22167 {
22168 error ("invalid header name %qs", name);
22169 continue;
22170 }
22171 else
22172 name = canonicalize_header_name (is_pathname ? nullptr : reader,
22173 0, is_pathname, name, len);
22174 }
22175 if (auto module = get_module (name))
22176 module->inform_cmi_p = 1;
22177 else
22178 error ("invalid module name %qs", name);
22179 }
22180
22181 dump.push (NULL);
22182
22183 /* Determine lazy handle bound. */
22184 {
22185 unsigned limit = 1000;
22186 #if HAVE_GETRLIMIT
22187 struct rlimit rlimit;
22188 if (!getrlimit (RLIMIT_NOFILE, &rlimit))
22189 {
22190 lazy_hard_limit = (rlimit.rlim_max < 1000000
22191 ? unsigned (rlimit.rlim_max) : 1000000);
22192 lazy_hard_limit = (lazy_hard_limit > LAZY_HEADROOM
22193 ? lazy_hard_limit - LAZY_HEADROOM : 0);
22194 if (rlimit.rlim_cur < limit)
22195 limit = unsigned (rlimit.rlim_cur);
22196 }
22197 #endif
22198 limit = limit > LAZY_HEADROOM ? limit - LAZY_HEADROOM : 1;
22199
22200 if (unsigned parm = param_lazy_modules)
22201 {
22202 if (parm <= limit || !lazy_hard_limit || !try_increase_lazy (parm))
22203 lazy_limit = parm;
22204 }
22205 else
22206 lazy_limit = limit;
22207 }
22208
22209 if (dump ())
22210 {
22211 verstr_t ver;
22212 version2string (MODULE_VERSION, ver);
22213 dump ("Source: %s", main_input_filename);
22214 dump ("Compiler: %s", version_string);
22215 dump ("Modules: %s", ver);
22216 dump ("Checking: %s",
22217 #if CHECKING_P
22218 "checking"
22219 #elif ENABLE_ASSERT_CHECKING
22220 "asserting"
22221 #else
22222 "release"
22223 #endif
22224 );
22225 dump ("Compiled by: "
22226 #ifdef __GNUC__
22227 "GCC %d.%d, %s", __GNUC__, __GNUC_MINOR__,
22228 #ifdef __OPTIMIZE__
22229 "optimizing"
22230 #else
22231 "not optimizing"
22232 #endif
22233 #else
22234 "not GCC"
22235 #endif
22236 );
22237 dump ("Reading: %s", MAPPED_READING ? "mmap" : "fileio");
22238 dump ("Writing: %s", MAPPED_WRITING ? "mmap" : "fileio");
22239 dump ("Lazy limit: %u", lazy_limit);
22240 dump ("Lazy hard limit: %u", lazy_hard_limit);
22241 dump ("");
22242 }
22243
22244 /* Construct the global tree array. This is an array of unique
22245 global trees (& types). Do this now, rather than lazily, as
22246 some global trees are lazily created and we don't want that to
22247 mess with our syndrome of fixed trees. */
22248 unsigned crc = 0;
22249 vec_alloc (fixed_trees, 250);
22250
22251 dump () && dump ("+Creating globals");
22252 /* Insert the TRANSLATION_UNIT_DECL. */
22253 TREE_VISITED (DECL_CONTEXT (global_namespace)) = true;
22254 fixed_trees->quick_push (DECL_CONTEXT (global_namespace));
22255 for (unsigned jx = 0; global_tree_arys[jx].first; jx++)
22256 {
22257 const tree *ptr = global_tree_arys[jx].first;
22258 unsigned limit = global_tree_arys[jx].second;
22259
22260 for (unsigned ix = 0; ix != limit; ix++, ptr++)
22261 {
22262 !(ix & 31) && dump ("") && dump ("+\t%u:%u:", jx, ix);
22263 unsigned v = maybe_add_global (*ptr, crc);
22264 dump () && dump ("+%u", v);
22265 }
22266 }
22267 /* OS- and machine-specific types are dynamically registered at
22268 runtime, so cannot be part of global_tree_arys. */
22269 registered_builtin_types && dump ("") && dump ("+\tB:");
22270 for (tree t = registered_builtin_types; t; t = TREE_CHAIN (t))
22271 {
22272 unsigned v = maybe_add_global (TREE_VALUE (t), crc);
22273 dump () && dump ("+%u", v);
22274 }
22275 global_crc = crc32_unsigned (crc, fixed_trees->length ());
22276 dump ("") && dump ("Created %u unique globals, crc=%x",
22277 fixed_trees->length (), global_crc);
22278 for (unsigned ix = fixed_trees->length (); ix--;)
22279 TREE_VISITED ((*fixed_trees)[ix]) = false;
22280
22281 dump.pop (0);
22282
22283 if (!flag_module_lazy)
22284 /* Get the mapper now, if we're not being lazy. */
22285 get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
22286
22287 if (!flag_preprocess_only)
22288 {
22289 pending_table = new pending_map_t (EXPERIMENT (1, 400));
22290 entity_map = new entity_map_t (EXPERIMENT (1, 400));
22291 vec_safe_reserve (entity_ary, EXPERIMENT (1, 400));
22292 imported_temploid_friends
22293 = decl_tree_cache_map::create_ggc (EXPERIMENT (1, 400));
22294 }
22295
22296 #if CHECKING_P
22297 note_defs = note_defs_table_t::create_ggc (1000);
22298 #endif
22299
22300 if (flag_header_unit && cpp_get_options (reader)->preprocessed)
22301 begin_header_unit (reader);
22302
22303 /* Collect here to make sure things are tagged correctly (when
22304 aggressively GC'd). */
22305 ggc_collect ();
22306 }
22307
22308 /* If NODE is a deferred macro, load it. */
22309
22310 static int
22311 load_macros (cpp_reader *reader, cpp_hashnode *node, void *)
22312 {
22313 location_t main_loc
22314 = MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0));
22315
22316 if (cpp_user_macro_p (node)
22317 && !node->value.macro)
22318 {
22319 cpp_macro *macro = cpp_get_deferred_macro (reader, node, main_loc);
22320 dump () && dump ("Loaded macro #%s %I",
22321 macro ? "define" : "undef", identifier (node));
22322 }
22323
22324 return 1;
22325 }
22326
22327 /* At the end of tokenizing, we no longer need the macro tables of
22328 imports. But the user might have requested some checking. */
22329
22330 void
22331 maybe_check_all_macros (cpp_reader *reader)
22332 {
22333 if (!warn_imported_macros)
22334 return;
22335
22336 /* Force loading of any remaining deferred macros. This will
22337 produce diagnostics if they are ill-formed. */
22338 unsigned n = dump.push (NULL);
22339 cpp_forall_identifiers (reader, load_macros, NULL);
22340 dump.pop (n);
22341 }
22342
22343 // State propagated from finish_module_processing to fini_modules
22344
22345 struct module_processing_cookie
22346 {
22347 elf_out out;
22348 module_state_config config;
22349 char *cmi_name;
22350 char *tmp_name;
22351 unsigned crc;
22352 bool began;
22353
22354 module_processing_cookie (char *cmi, char *tmp, int fd, int e)
22355 : out (fd, e), cmi_name (cmi), tmp_name (tmp), crc (0), began (false)
22356 {
22357 }
22358 ~module_processing_cookie ()
22359 {
22360 XDELETEVEC (tmp_name);
22361 XDELETEVEC (cmi_name);
22362 }
22363 };
22364
22365 /* Write the CMI, if we're a module interface. */
22366
22367 void *
22368 finish_module_processing (cpp_reader *reader)
22369 {
22370 module_processing_cookie *cookie = nullptr;
22371
22372 if (header_module_p ())
22373 module_kind &= ~MK_EXPORTING;
22374
22375 if (!modules || !(*modules)[0]->name)
22376 {
22377 if (flag_module_only)
22378 warning (0, "%<-fmodule-only%> used for non-interface");
22379 }
22380 else if (!flag_syntax_only)
22381 {
22382 int fd = -1;
22383 int e = -1;
22384
22385 timevar_start (TV_MODULE_EXPORT);
22386
22387 /* Force a valid but empty line map at the end. This simplifies
22388 the line table preparation and writing logic. */
22389 linemap_add (line_table, LC_ENTER, false, "", 0);
22390
22391 /* We write to a tmpname, and then atomically rename. */
22392 char *cmi_name = NULL;
22393 char *tmp_name = NULL;
22394 module_state *state = (*modules)[0];
22395
22396 unsigned n = dump.push (state);
22397 state->announce ("creating");
22398 if (state->filename)
22399 {
22400 size_t len = 0;
22401 cmi_name = xstrdup (maybe_add_cmi_prefix (state->filename, &len));
22402 tmp_name = XNEWVEC (char, len + 3);
22403 memcpy (tmp_name, cmi_name, len);
22404 strcpy (&tmp_name[len], "~");
22405
22406 if (!errorcount)
22407 for (unsigned again = 2; ; again--)
22408 {
22409 fd = open (tmp_name,
22410 O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY,
22411 S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
22412 e = errno;
22413 if (fd >= 0 || !again || e != ENOENT)
22414 break;
22415 create_dirs (tmp_name);
22416 }
22417 if (note_module_cmi_yes || state->inform_cmi_p)
22418 inform (state->loc, "writing CMI %qs", cmi_name);
22419 dump () && dump ("CMI is %s", cmi_name);
22420 }
22421
22422 cookie = new module_processing_cookie (cmi_name, tmp_name, fd, e);
22423
22424 if (errorcount)
22425 /* Don't write the module if we have reported errors. */;
22426 else if (erroneous_templates
22427 && !erroneous_templates->is_empty ())
22428 {
22429 /* Don't write the module if it contains an erroneous template.
22430 Also emit notes about where errors occurred in case
22431 -Wno-template-body was passed. */
22432 auto_diagnostic_group d;
22433 error_at (state->loc, "not writing module %qs due to errors "
22434 "in template bodies", state->get_flatname ());
22435 if (!warn_template_body)
22436 inform (state->loc, "enable %<-Wtemplate-body%> for more details");
22437 for (auto e : *erroneous_templates)
22438 inform (e.second, "first error in %qD appeared here", e.first);
22439 }
22440 else if (cookie->out.begin ())
22441 {
22442 /* So crashes finger-point the module decl. */
22443 iloc_sentinel ils = state->loc;
22444 if (state->write_begin (&cookie->out, reader, cookie->config,
22445 cookie->crc))
22446 cookie->began = true;
22447 }
22448
22449 dump.pop (n);
22450 timevar_stop (TV_MODULE_EXPORT);
22451
22452 ggc_collect ();
22453 }
22454
22455 if (modules)
22456 {
22457 unsigned n = dump.push (NULL);
22458 dump () && dump ("Imported %u modules", modules->length () - 1);
22459 dump () && dump ("Containing %u clusters", available_clusters);
22460 dump () && dump ("Loaded %u clusters (%u%%)", loaded_clusters,
22461 (loaded_clusters * 100 + available_clusters / 2) /
22462 (available_clusters + !available_clusters));
22463 dump.pop (n);
22464 }
22465
22466 return cookie;
22467 }
22468
22469 // Do the final emission of a module. At this point we know whether
22470 // the module static initializer is a NOP or not.
22471
22472 static void
22473 late_finish_module (cpp_reader *reader, module_processing_cookie *cookie,
22474 bool init_fn_non_empty)
22475 {
22476 timevar_start (TV_MODULE_EXPORT);
22477
22478 module_state *state = (*modules)[0];
22479 unsigned n = dump.push (state);
22480 state->announce ("finishing");
22481
22482 cookie->config.active_init = init_fn_non_empty;
22483 if (cookie->began)
22484 state->write_end (&cookie->out, reader, cookie->config, cookie->crc);
22485
22486 if (cookie->out.end () && cookie->cmi_name)
22487 {
22488 /* Some OS's do not replace NEWNAME if it already exists.
22489 This'll have a race condition in erroneous concurrent
22490 builds. */
22491 unlink (cookie->cmi_name);
22492 if (rename (cookie->tmp_name, cookie->cmi_name))
22493 {
22494 dump () && dump ("Rename ('%s','%s') errno=%u",
22495 cookie->tmp_name, cookie->cmi_name, errno);
22496 cookie->out.set_error (errno);
22497 }
22498 }
22499
22500 if (cookie->out.get_error () && cookie->began)
22501 {
22502 error_at (state->loc, "failed to write compiled module: %s",
22503 cookie->out.get_error (state->filename));
22504 state->note_cmi_name ();
22505 }
22506
22507 if (!errorcount)
22508 {
22509 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
22510 mapper->ModuleCompiled (state->get_flatname ());
22511 }
22512 else if (cookie->cmi_name)
22513 {
22514 /* We failed, attempt to erase all evidence we even tried. */
22515 unlink (cookie->tmp_name);
22516 unlink (cookie->cmi_name);
22517 }
22518
22519 delete cookie;
22520 dump.pop (n);
22521 timevar_stop (TV_MODULE_EXPORT);
22522 }
22523
22524 void
22525 fini_modules (cpp_reader *reader, void *cookie, bool has_inits)
22526 {
22527 if (cookie)
22528 late_finish_module (reader,
22529 static_cast<module_processing_cookie *> (cookie),
22530 has_inits);
22531
22532 /* We're done with the macro tables now. */
22533 vec_free (macro_exports);
22534 vec_free (macro_imports);
22535 headers = NULL;
22536
22537 /* We're now done with everything but the module names. */
22538 set_cmi_repo (NULL);
22539 if (mapper)
22540 {
22541 timevar_start (TV_MODULE_MAPPER);
22542 module_client::close_module_client (0, mapper);
22543 mapper = nullptr;
22544 timevar_stop (TV_MODULE_MAPPER);
22545 }
22546 module_state_config::release ();
22547
22548 #if CHECKING_P
22549 note_defs = NULL;
22550 #endif
22551
22552 if (modules)
22553 for (unsigned ix = modules->length (); --ix;)
22554 if (module_state *state = (*modules)[ix])
22555 state->release ();
22556
22557 /* No need to lookup modules anymore. */
22558 modules_hash = NULL;
22559
22560 /* Or entity array. We still need the entity map to find import numbers. */
22561 vec_free (entity_ary);
22562 entity_ary = NULL;
22563
22564 /* Or remember any pending entities. */
22565 delete pending_table;
22566 pending_table = NULL;
22567
22568 /* Or any keys -- Let it go! */
22569 delete keyed_table;
22570 keyed_table = NULL;
22571
22572 /* Allow a GC, we've possibly made much data unreachable. */
22573 ggc_collect ();
22574 }
22575
22576 /* If CODE is a module option, handle it & return true. Otherwise
22577 return false. For unknown reasons I cannot get the option
22578 generation machinery to set fmodule-mapper or -fmodule-header to
22579 make a string type option variable. */
22580
22581 bool
22582 handle_module_option (unsigned code, const char *str, int)
22583 {
22584 auto hdr = CMS_header;
22585
22586 switch (opt_code (code))
22587 {
22588 case OPT_fmodule_mapper_:
22589 module_mapper_name = str;
22590 return true;
22591
22592 case OPT_fmodule_header_:
22593 {
22594 if (!strcmp (str, "user"))
22595 hdr = CMS_user;
22596 else if (!strcmp (str, "system"))
22597 hdr = CMS_system;
22598 else
22599 error ("unknown header kind %qs", str);
22600 }
22601 /* Fallthrough. */
22602
22603 case OPT_fmodule_header:
22604 flag_header_unit = hdr;
22605 flag_modules = 1;
22606 return true;
22607
22608 case OPT_flang_info_include_translate_:
22609 vec_safe_push (note_includes, str);
22610 return true;
22611
22612 case OPT_flang_info_module_cmi_:
22613 vec_safe_push (note_cmis, str);
22614 return true;
22615
22616 default:
22617 return false;
22618 }
22619 }
22620
22621 /* Set preprocessor callbacks and options for modules. */
22622
22623 void
22624 module_preprocess_options (cpp_reader *reader)
22625 {
22626 gcc_checking_assert (!lang_hooks.preprocess_undef);
22627 if (modules_p ())
22628 {
22629 auto *cb = cpp_get_callbacks (reader);
22630
22631 cb->translate_include = maybe_translate_include;
22632 cb->user_deferred_macro = module_state::deferred_macro;
22633 if (flag_header_unit)
22634 {
22635 /* If the preprocessor hook is already in use, that
22636 implementation will call the undef langhook. */
22637 if (cb->undef)
22638 lang_hooks.preprocess_undef = module_state::undef_macro;
22639 else
22640 cb->undef = module_state::undef_macro;
22641 }
22642 auto *opt = cpp_get_options (reader);
22643 opt->module_directives = true;
22644 if (flag_no_output)
22645 opt->directives_only = true;
22646 if (opt->main_search == CMS_none)
22647 opt->main_search = cpp_main_search (flag_header_unit);
22648 }
22649 }
22650
22651 #include "gt-cp-module.h"