c++/modules: Fix dangling pointer with imported_temploid_friends
[official-gcc.git] / gcc / cp / module.cc
blob520dd710549ed735923b678b15f22428257ca85f
1 /* C++ modules. Experimental!
2 Copyright (C) 2017-2024 Free Software Foundation, Inc.
3 Written by Nathan Sidwell <nathan@acm.org> while at FaceBook
5 This file is part of GCC.
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.
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.
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/>. */
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. */
27 /* (Incomplete) Design Notes
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).
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.
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.
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.
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.
68 Header units are module-like.
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.
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.
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.
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.
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.
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.
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.
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).
150 Classes used:
152 dumper - logger
154 data - buffer
156 bytes_in : data - scalar reader
157 bytes_out : data - scalar writer
159 bytes_in::bits_in - bit stream reader
160 bytes_out::bits_out - bit stream writer
162 elf - ELROND format
163 elf_in : elf - ELROND reader
164 elf_out : elf - ELROND writer
166 trees_in : bytes_in - tree reader
167 trees_out : bytes_out - tree writer
169 depset - dependency set
170 depset::hash - hash table of depsets
171 depset::tarjan - SCC determinator
173 uidset<T> - set T's related to a UID
174 uidset<T>::hash hash table of uidset<T>
176 loc_spans - location map data
178 module_state - module object
180 slurping - data needed during loading
182 macro_import - imported macro data
183 macro_export - exported macro data
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.
188 The mapper object uses fileno IO to communicate with the server or
189 program. */
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
209 #define _DEFAULT_SOURCE 1 /* To get TZ field of struct tm, if available. */
210 #include "config.h"
211 #define INCLUDE_MEMORY
212 #define INCLUDE_STRING
213 #define INCLUDE_VECTOR
214 #include "system.h"
215 #include "coretypes.h"
216 #include "cp-tree.h"
217 #include "timevar.h"
218 #include "stringpool.h"
219 #include "dumpfile.h"
220 #include "bitmap.h"
221 #include "cgraph.h"
222 #include "varasm.h"
223 #include "tree-iterator.h"
224 #include "cpplib.h"
225 #include "mkdeps.h"
226 #include "incpath.h"
227 #include "libiberty.h"
228 #include "stor-layout.h"
229 #include "version.h"
230 #include "tree-diagnostic.h"
231 #include "toplev.h"
232 #include "opts.h"
233 #include "attribs.h"
234 #include "intl.h"
235 #include "langhooks.h"
236 /* This TU doesn't need or want to see the networking. */
237 #define CODY_NETWORKING 0
238 #include "mapper-client.h"
239 #include <zlib.h> // for crc32, crc32_combine
241 #if 0 // 1 for testing no mmap
242 #define MAPPED_READING 0
243 #define MAPPED_WRITING 0
244 #else
245 #if HAVE_MMAP_FILE && _POSIX_MAPPED_FILES > 0
246 /* mmap, munmap. */
247 #define MAPPED_READING 1
248 #if HAVE_SYSCONF && defined (_SC_PAGE_SIZE)
249 /* msync, sysconf (_SC_PAGE_SIZE), ftruncate */
250 /* posix_fallocate used if available. */
251 #define MAPPED_WRITING 1
252 #else
253 #define MAPPED_WRITING 0
254 #endif
255 #else
256 #define MAPPED_READING 0
257 #define MAPPED_WRITING 0
258 #endif
259 #endif
261 /* Some open(2) flag differences, what a colourful world it is! */
262 #if defined (O_CLOEXEC)
263 // OK
264 #elif defined (_O_NOINHERIT)
265 /* Windows' _O_NOINHERIT matches O_CLOEXEC flag */
266 #define O_CLOEXEC _O_NOINHERIT
267 #else
268 #define O_CLOEXEC 0
269 #endif
270 #if defined (O_BINARY)
271 // Ok?
272 #elif defined (_O_BINARY)
273 /* Windows' open(2) call defaults to text! */
274 #define O_BINARY _O_BINARY
275 #else
276 #define O_BINARY 0
277 #endif
279 static inline cpp_hashnode *cpp_node (tree id)
281 return CPP_HASHNODE (GCC_IDENT_TO_HT_IDENT (id));
284 static inline tree identifier (const cpp_hashnode *node)
286 /* HT_NODE() expands to node->ident that HT_IDENT_TO_GCC_IDENT()
287 then subtracts a nonzero constant, deriving a pointer to
288 a different member than ident. That's strictly undefined
289 and detected by -Warray-bounds. Suppress it. See PR 101372. */
290 #pragma GCC diagnostic push
291 #pragma GCC diagnostic ignored "-Warray-bounds"
292 return HT_IDENT_TO_GCC_IDENT (HT_NODE (const_cast<cpp_hashnode *> (node)));
293 #pragma GCC diagnostic pop
296 /* Id for dumping module information. */
297 int module_dump_id;
299 /* We have a special module owner. */
300 #define MODULE_UNKNOWN (~0U) /* Not yet known. */
302 /* Prefix for section names. */
303 #define MOD_SNAME_PFX ".gnu.c++"
305 /* Format a version for user consumption. */
307 typedef char verstr_t[32];
308 static void
309 version2string (unsigned version, verstr_t &out)
311 unsigned major = MODULE_MAJOR (version);
312 unsigned minor = MODULE_MINOR (version);
314 if (IS_EXPERIMENTAL (version))
315 sprintf (out, "%04u/%02u/%02u-%02u:%02u%s",
316 2000 + major / 10000, (major / 100) % 100, (major % 100),
317 minor / 100, minor % 100,
318 EXPERIMENT ("", " (experimental)"));
319 else
320 sprintf (out, "%u.%u", major, minor);
323 /* Include files to note translation for. */
324 static vec<const char *, va_heap, vl_embed> *note_includes;
326 /* Modules to note CMI pathames. */
327 static vec<const char *, va_heap, vl_embed> *note_cmis;
329 /* Traits to hash an arbitrary pointer. Entries are not deletable,
330 and removal is a noop (removal needed upon destruction). */
331 template <typename T>
332 struct nodel_ptr_hash : pointer_hash<T>, typed_noop_remove <T *> {
333 /* Nothing is deletable. Everything is insertable. */
334 static bool is_deleted (T *) { return false; }
335 static void mark_deleted (T *) { gcc_unreachable (); }
338 /* Map from pointer to signed integer. */
339 typedef simple_hashmap_traits<nodel_ptr_hash<void>, int> ptr_int_traits;
340 typedef hash_map<void *,signed,ptr_int_traits> ptr_int_hash_map;
342 /********************************************************************/
343 /* Basic streaming & ELF. Serialization is usually via mmap. For
344 writing we slide a buffer over the output file, syncing it
345 approproiately. For reading we simply map the whole file (as a
346 file-backed read-only map -- it's just address space, leaving the
347 OS pager to deal with getting the data to us). Some buffers need
348 to be more conventional malloc'd contents. */
350 /* Variable length buffer. */
352 namespace {
353 class data {
354 public:
355 class allocator {
356 public:
357 /* Tools tend to moan if the dtor's not virtual. */
358 virtual ~allocator () {}
360 public:
361 void grow (data &obj, unsigned needed, bool exact);
362 void shrink (data &obj);
364 public:
365 virtual char *grow (char *ptr, unsigned needed);
366 virtual void shrink (char *ptr);
369 public:
370 char *buffer; /* Buffer being transferred. */
371 /* Although size_t would be the usual size, we know we never get
372 more than 4GB of buffer -- because that's the limit of the
373 encapsulation format. And if you need bigger imports, you're
374 doing it wrong. */
375 unsigned size; /* Allocated size of buffer. */
376 unsigned pos; /* Position in buffer. */
378 public:
379 data ()
380 :buffer (NULL), size (0), pos (0)
383 ~data ()
385 /* Make sure the derived and/or using class know what they're
386 doing. */
387 gcc_checking_assert (!buffer);
390 protected:
391 char *use (unsigned count)
393 if (size < pos + count)
394 return NULL;
395 char *res = &buffer[pos];
396 pos += count;
397 return res;
400 unsigned calc_crc (unsigned) const;
402 public:
403 void unuse (unsigned count)
405 pos -= count;
408 public:
409 static allocator simple_memory;
411 } // anon namespace
413 /* The simple data allocator. */
414 data::allocator data::simple_memory;
416 /* Grow buffer to at least size NEEDED. */
418 void
419 data::allocator::grow (data &obj, unsigned needed, bool exact)
421 gcc_checking_assert (needed ? needed > obj.size : !obj.size);
422 if (!needed)
423 /* Pick a default size. */
424 needed = EXPERIMENT (100, 1000);
426 if (!exact)
427 needed *= 2;
428 obj.buffer = grow (obj.buffer, needed);
429 if (obj.buffer)
430 obj.size = needed;
431 else
432 obj.pos = obj.size = 0;
435 /* Free a buffer. */
437 void
438 data::allocator::shrink (data &obj)
440 shrink (obj.buffer);
441 obj.buffer = NULL;
442 obj.size = 0;
445 char *
446 data::allocator::grow (char *ptr, unsigned needed)
448 return XRESIZEVAR (char, ptr, needed);
451 void
452 data::allocator::shrink (char *ptr)
454 XDELETEVEC (ptr);
457 /* Calculate the crc32 of the buffer. Note the CRC is stored in the
458 first 4 bytes, so don't include them. */
460 unsigned
461 data::calc_crc (unsigned l) const
463 return crc32 (0, (unsigned char *)buffer + 4, l - 4);
466 class elf_in;
468 /* Byte stream reader. */
470 namespace {
471 class bytes_in : public data {
472 typedef data parent;
474 protected:
475 bool overrun; /* Sticky read-too-much flag. */
477 public:
478 bytes_in ()
479 : parent (), overrun (false)
482 ~bytes_in ()
486 public:
487 /* Begin reading a named section. */
488 bool begin (location_t loc, elf_in *src, const char *name);
489 /* Begin reading a numbered section with optional name. */
490 bool begin (location_t loc, elf_in *src, unsigned, const char * = NULL);
491 /* Complete reading a buffer. Propagate errors and return true on
492 success. */
493 bool end (elf_in *src);
494 /* Return true if there is unread data. */
495 bool more_p () const
497 return pos != size;
500 public:
501 /* Start reading at OFFSET. */
502 void random_access (unsigned offset)
504 if (offset > size)
505 set_overrun ();
506 pos = offset;
509 public:
510 void align (unsigned boundary)
512 if (unsigned pad = pos & (boundary - 1))
513 read (boundary - pad);
516 public:
517 const char *read (unsigned count)
519 char *ptr = use (count);
520 if (!ptr)
521 set_overrun ();
522 return ptr;
525 public:
526 bool check_crc () const;
527 /* We store the CRC in the first 4 bytes, using host endianness. */
528 unsigned get_crc () const
530 return *(const unsigned *)&buffer[0];
533 public:
534 /* Manipulate the overrun flag. */
535 bool get_overrun () const
537 return overrun;
539 void set_overrun ()
541 overrun = true;
544 public:
545 unsigned u32 (); /* Read uncompressed integer. */
547 public:
548 int c () ATTRIBUTE_UNUSED; /* Read a char. */
549 int i (); /* Read a signed int. */
550 unsigned u (); /* Read an unsigned int. */
551 size_t z (); /* Read a size_t. */
552 HOST_WIDE_INT wi (); /* Read a HOST_WIDE_INT. */
553 unsigned HOST_WIDE_INT wu (); /* Read an unsigned HOST_WIDE_INT. */
554 const char *str (size_t * = NULL); /* Read a string. */
555 const void *buf (size_t); /* Read a fixed-length buffer. */
556 cpp_hashnode *cpp_node (); /* Read a cpp node. */
558 struct bits_in;
559 bits_in stream_bits ();
561 } // anon namespace
563 /* Verify the buffer's CRC is correct. */
565 bool
566 bytes_in::check_crc () const
568 if (size < 4)
569 return false;
571 unsigned c_crc = calc_crc (size);
572 if (c_crc != get_crc ())
573 return false;
575 return true;
578 class elf_out;
580 /* Byte stream writer. */
582 namespace {
583 class bytes_out : public data {
584 typedef data parent;
586 public:
587 allocator *memory; /* Obtainer of memory. */
589 public:
590 bytes_out (allocator *memory)
591 : parent (), memory (memory)
594 ~bytes_out ()
598 public:
599 bool streaming_p () const
601 return memory != NULL;
604 public:
605 void set_crc (unsigned *crc_ptr);
607 public:
608 /* Begin writing, maybe reserve space for CRC. */
609 void begin (bool need_crc = true);
610 /* Finish writing. Spill to section by number. */
611 unsigned end (elf_out *, unsigned, unsigned *crc_ptr = NULL);
613 public:
614 void align (unsigned boundary)
616 if (unsigned pad = pos & (boundary - 1))
617 write (boundary - pad);
620 public:
621 char *write (unsigned count, bool exact = false)
623 if (size < pos + count)
624 memory->grow (*this, pos + count, exact);
625 return use (count);
628 public:
629 void u32 (unsigned); /* Write uncompressed integer. */
631 public:
632 void c (unsigned char) ATTRIBUTE_UNUSED; /* Write unsigned char. */
633 void i (int); /* Write signed int. */
634 void u (unsigned); /* Write unsigned int. */
635 void z (size_t s); /* Write size_t. */
636 void wi (HOST_WIDE_INT); /* Write HOST_WIDE_INT. */
637 void wu (unsigned HOST_WIDE_INT); /* Write unsigned HOST_WIDE_INT. */
638 void str (const char *ptr)
640 str (ptr, strlen (ptr));
642 void cpp_node (const cpp_hashnode *node)
644 str ((const char *)NODE_NAME (node), NODE_LEN (node));
646 void str (const char *, size_t); /* Write string of known length. */
647 void buf (const void *, size_t); /* Write fixed length buffer. */
648 void *buf (size_t); /* Create a writable buffer */
650 struct bits_out;
651 bits_out stream_bits ();
653 public:
654 /* Format a NUL-terminated raw string. */
655 void printf (const char *, ...) ATTRIBUTE_PRINTF_2;
656 void print_time (const char *, const tm *, const char *);
658 public:
659 /* Dump instrumentation. */
660 static void instrument ();
662 protected:
663 /* Instrumentation. */
664 static unsigned spans[4];
665 static unsigned lengths[4];
667 } // anon namespace
669 /* Finish bit packet. Rewind the bytes not used. */
671 static unsigned
672 bit_flush (data& bits, uint32_t& bit_val, unsigned& bit_pos)
674 gcc_assert (bit_pos);
675 unsigned bytes = (bit_pos + 7) / 8;
676 bits.unuse (4 - bytes);
677 bit_pos = 0;
678 bit_val = 0;
679 return bytes;
682 /* Bit stream reader (RAII-enabled). Bools are packed into bytes. You
683 cannot mix bools and non-bools. Use bflush to flush the current stream
684 of bools on demand. Upon destruction bflush is called.
686 When reading, we don't know how many bools we'll read in. So read
687 4 bytes-worth, and then rewind when flushing if we didn't need them
688 all. You can't have a block of bools closer than 4 bytes to the
689 end of the buffer.
691 Both bits_in and bits_out maintain the necessary state for bit packing,
692 and since these objects are locally constructed the compiler can more
693 easily track their state across consecutive reads/writes and optimize
694 away redundant buffering checks. */
696 struct bytes_in::bits_in {
697 bytes_in& in;
698 uint32_t bit_val = 0;
699 unsigned bit_pos = 0;
701 bits_in (bytes_in& in)
702 : in (in)
705 ~bits_in ()
707 bflush ();
710 bits_in(bits_in&&) = default;
711 bits_in(const bits_in&) = delete;
712 bits_in& operator=(const bits_in&) = delete;
714 /* Completed a block of bools. */
715 void bflush ()
717 if (bit_pos)
718 bit_flush (in, bit_val, bit_pos);
721 /* Read one bit. */
722 bool b ()
724 if (!bit_pos)
725 bit_val = in.u32 ();
726 bool x = (bit_val >> bit_pos) & 1;
727 bit_pos = (bit_pos + 1) % 32;
728 return x;
732 /* Factory function for bits_in. */
734 bytes_in::bits_in
735 bytes_in::stream_bits ()
737 return bits_in (*this);
740 /* Bit stream writer (RAII-enabled), counterpart to bits_in. */
742 struct bytes_out::bits_out {
743 bytes_out& out;
744 uint32_t bit_val = 0;
745 unsigned bit_pos = 0;
746 char is_set = -1;
748 bits_out (bytes_out& out)
749 : out (out)
752 ~bits_out ()
754 bflush ();
757 bits_out(bits_out&&) = default;
758 bits_out(const bits_out&) = delete;
759 bits_out& operator=(const bits_out&) = delete;
761 /* Completed a block of bools. */
762 void bflush ()
764 if (bit_pos)
766 out.u32 (bit_val);
767 out.lengths[2] += bit_flush (out, bit_val, bit_pos);
769 out.spans[2]++;
770 is_set = -1;
773 /* Write one bit.
775 It may be worth optimizing for most bools being zero. Some kind of
776 run-length encoding? */
777 void b (bool x)
779 if (is_set != x)
781 is_set = x;
782 out.spans[x]++;
784 out.lengths[x]++;
785 bit_val |= unsigned (x) << bit_pos++;
786 if (bit_pos == 32)
788 out.u32 (bit_val);
789 out.lengths[2] += bit_flush (out, bit_val, bit_pos);
794 /* Factory function for bits_out. */
796 bytes_out::bits_out
797 bytes_out::stream_bits ()
799 return bits_out (*this);
802 /* Instrumentation. */
803 unsigned bytes_out::spans[4];
804 unsigned bytes_out::lengths[4];
806 /* If CRC_PTR non-null, set the CRC of the buffer. Mix the CRC into
807 that pointed to by CRC_PTR. */
809 void
810 bytes_out::set_crc (unsigned *crc_ptr)
812 if (crc_ptr)
814 gcc_checking_assert (pos >= 4);
816 unsigned crc = calc_crc (pos);
817 unsigned accum = *crc_ptr;
818 /* Only mix the existing *CRC_PTR if it is non-zero. */
819 accum = accum ? crc32_combine (accum, crc, pos - 4) : crc;
820 *crc_ptr = accum;
822 /* Buffer will be sufficiently aligned. */
823 *(unsigned *)buffer = crc;
827 /* Exactly 4 bytes. Used internally for bool packing and a few other
828 places. We can't simply use uint32_t because (a) alignment and
829 (b) we need little-endian for the bool streaming rewinding to make
830 sense. */
832 void
833 bytes_out::u32 (unsigned val)
835 if (char *ptr = write (4))
837 ptr[0] = val;
838 ptr[1] = val >> 8;
839 ptr[2] = val >> 16;
840 ptr[3] = val >> 24;
844 unsigned
845 bytes_in::u32 ()
847 unsigned val = 0;
848 if (const char *ptr = read (4))
850 val |= (unsigned char)ptr[0];
851 val |= (unsigned char)ptr[1] << 8;
852 val |= (unsigned char)ptr[2] << 16;
853 val |= (unsigned char)ptr[3] << 24;
856 return val;
859 /* Chars are unsigned and written as single bytes. */
861 void
862 bytes_out::c (unsigned char v)
864 if (char *ptr = write (1))
865 *ptr = v;
869 bytes_in::c ()
871 int v = 0;
872 if (const char *ptr = read (1))
873 v = (unsigned char)ptr[0];
874 return v;
877 /* Ints 7-bit as a byte. Otherwise a 3bit count of following bytes in
878 big-endian form. 4 bits are in the first byte. */
880 void
881 bytes_out::i (int v)
883 if (char *ptr = write (1))
885 if (v <= 0x3f && v >= -0x40)
886 *ptr = v & 0x7f;
887 else
889 unsigned bytes = 0;
890 int probe;
891 if (v >= 0)
892 for (probe = v >> 8; probe > 0x7; probe >>= 8)
893 bytes++;
894 else
895 for (probe = v >> 8; probe < -0x8; probe >>= 8)
896 bytes++;
897 *ptr = 0x80 | bytes << 4 | (probe & 0xf);
898 if ((ptr = write (++bytes)))
899 for (; bytes--; v >>= 8)
900 ptr[bytes] = v & 0xff;
906 bytes_in::i ()
908 int v = 0;
909 if (const char *ptr = read (1))
911 v = *ptr & 0xff;
912 if (v & 0x80)
914 unsigned bytes = (v >> 4) & 0x7;
915 v &= 0xf;
916 if (v & 0x8)
917 v |= -1 ^ 0x7;
918 /* unsigned necessary due to left shifts of -ve values. */
919 unsigned uv = unsigned (v);
920 if ((ptr = read (++bytes)))
921 while (bytes--)
922 uv = (uv << 8) | (*ptr++ & 0xff);
923 v = int (uv);
925 else if (v & 0x40)
926 v |= -1 ^ 0x3f;
929 return v;
932 void
933 bytes_out::u (unsigned v)
935 if (char *ptr = write (1))
937 if (v <= 0x7f)
938 *ptr = v;
939 else
941 unsigned bytes = 0;
942 unsigned probe;
943 for (probe = v >> 8; probe > 0xf; probe >>= 8)
944 bytes++;
945 *ptr = 0x80 | bytes << 4 | probe;
946 if ((ptr = write (++bytes)))
947 for (; bytes--; v >>= 8)
948 ptr[bytes] = v & 0xff;
953 unsigned
954 bytes_in::u ()
956 unsigned v = 0;
958 if (const char *ptr = read (1))
960 v = *ptr & 0xff;
961 if (v & 0x80)
963 unsigned bytes = (v >> 4) & 0x7;
964 v &= 0xf;
965 if ((ptr = read (++bytes)))
966 while (bytes--)
967 v = (v << 8) | (*ptr++ & 0xff);
971 return v;
974 void
975 bytes_out::wi (HOST_WIDE_INT v)
977 if (char *ptr = write (1))
979 if (v <= 0x3f && v >= -0x40)
980 *ptr = v & 0x7f;
981 else
983 unsigned bytes = 0;
984 HOST_WIDE_INT probe;
985 if (v >= 0)
986 for (probe = v >> 8; probe > 0x7; probe >>= 8)
987 bytes++;
988 else
989 for (probe = v >> 8; probe < -0x8; probe >>= 8)
990 bytes++;
991 *ptr = 0x80 | bytes << 4 | (probe & 0xf);
992 if ((ptr = write (++bytes)))
993 for (; bytes--; v >>= 8)
994 ptr[bytes] = v & 0xff;
999 HOST_WIDE_INT
1000 bytes_in::wi ()
1002 HOST_WIDE_INT v = 0;
1003 if (const char *ptr = read (1))
1005 v = *ptr & 0xff;
1006 if (v & 0x80)
1008 unsigned bytes = (v >> 4) & 0x7;
1009 v &= 0xf;
1010 if (v & 0x8)
1011 v |= -1 ^ 0x7;
1012 /* unsigned necessary due to left shifts of -ve values. */
1013 unsigned HOST_WIDE_INT uv = (unsigned HOST_WIDE_INT) v;
1014 if ((ptr = read (++bytes)))
1015 while (bytes--)
1016 uv = (uv << 8) | (*ptr++ & 0xff);
1017 v = (HOST_WIDE_INT) uv;
1019 else if (v & 0x40)
1020 v |= -1 ^ 0x3f;
1023 return v;
1026 /* unsigned wide ints are just written as signed wide ints. */
1028 inline void
1029 bytes_out::wu (unsigned HOST_WIDE_INT v)
1031 wi ((HOST_WIDE_INT) v);
1034 inline unsigned HOST_WIDE_INT
1035 bytes_in::wu ()
1037 return (unsigned HOST_WIDE_INT) wi ();
1040 /* size_t written as unsigned or unsigned wide int. */
1042 inline void
1043 bytes_out::z (size_t s)
1045 if (sizeof (s) == sizeof (unsigned))
1046 u (s);
1047 else
1048 wu (s);
1051 inline size_t
1052 bytes_in::z ()
1054 if (sizeof (size_t) == sizeof (unsigned))
1055 return u ();
1056 else
1057 return wu ();
1060 /* Buffer simply memcpied. */
1061 void *
1062 bytes_out::buf (size_t len)
1064 align (sizeof (void *) * 2);
1065 return write (len);
1068 void
1069 bytes_out::buf (const void *src, size_t len)
1071 if (void *ptr = buf (len))
1072 memcpy (ptr, src, len);
1075 const void *
1076 bytes_in::buf (size_t len)
1078 align (sizeof (void *) * 2);
1079 const char *ptr = read (len);
1081 return ptr;
1084 /* strings as an size_t length, followed by the buffer. Make sure
1085 there's a NUL terminator on read. */
1087 void
1088 bytes_out::str (const char *string, size_t len)
1090 z (len);
1091 if (len)
1093 gcc_checking_assert (!string[len]);
1094 buf (string, len + 1);
1098 const char *
1099 bytes_in::str (size_t *len_p)
1101 size_t len = z ();
1103 /* We're about to trust some user data. */
1104 if (overrun)
1105 len = 0;
1106 if (len_p)
1107 *len_p = len;
1108 const char *str = NULL;
1109 if (len)
1111 str = reinterpret_cast<const char *> (buf (len + 1));
1112 if (!str || str[len])
1114 set_overrun ();
1115 str = NULL;
1118 return str ? str : "";
1121 cpp_hashnode *
1122 bytes_in::cpp_node ()
1124 size_t len;
1125 const char *s = str (&len);
1126 if (!len)
1127 return NULL;
1128 return ::cpp_node (get_identifier_with_length (s, len));
1131 /* Format a string directly to the buffer, including a terminating
1132 NUL. Intended for human consumption. */
1134 void
1135 bytes_out::printf (const char *format, ...)
1137 va_list args;
1138 /* Exercise buffer expansion. */
1139 size_t len = EXPERIMENT (10, 500);
1141 while (char *ptr = write (len))
1143 va_start (args, format);
1144 size_t actual = vsnprintf (ptr, len, format, args) + 1;
1145 va_end (args);
1146 if (actual <= len)
1148 unuse (len - actual);
1149 break;
1151 unuse (len);
1152 len = actual;
1156 void
1157 bytes_out::print_time (const char *kind, const tm *time, const char *tz)
1159 printf ("%stime: %4u/%02u/%02u %02u:%02u:%02u %s",
1160 kind, time->tm_year + 1900, time->tm_mon + 1, time->tm_mday,
1161 time->tm_hour, time->tm_min, time->tm_sec, tz);
1164 /* Encapsulated Lazy Records Of Named Declarations.
1165 Header: Stunningly Elf32_Ehdr-like
1166 Sections: Sectional data
1167 [1-N) : User data sections
1168 N .strtab : strings, stunningly ELF STRTAB-like
1169 Index: Section table, stunningly ELF32_Shdr-like. */
1171 class elf {
1172 protected:
1173 /* Constants used within the format. */
1174 enum private_constants {
1175 /* File kind. */
1176 ET_NONE = 0,
1177 EM_NONE = 0,
1178 OSABI_NONE = 0,
1180 /* File format. */
1181 EV_CURRENT = 1,
1182 CLASS32 = 1,
1183 DATA2LSB = 1,
1184 DATA2MSB = 2,
1186 /* Section numbering. */
1187 SHN_UNDEF = 0,
1188 SHN_LORESERVE = 0xff00,
1189 SHN_XINDEX = 0xffff,
1191 /* Section types. */
1192 SHT_NONE = 0, /* No contents. */
1193 SHT_PROGBITS = 1, /* Random bytes. */
1194 SHT_STRTAB = 3, /* A string table. */
1196 /* Section flags. */
1197 SHF_NONE = 0x00, /* Nothing. */
1198 SHF_STRINGS = 0x20, /* NUL-Terminated strings. */
1200 /* I really hope we do not get CMI files larger than 4GB. */
1201 MY_CLASS = CLASS32,
1202 /* It is host endianness that is relevant. */
1203 MY_ENDIAN = DATA2LSB
1204 #ifdef WORDS_BIGENDIAN
1205 ^ DATA2LSB ^ DATA2MSB
1206 #endif
1209 public:
1210 /* Constants visible to users. */
1211 enum public_constants {
1212 /* Special error codes. Breaking layering a bit. */
1213 E_BAD_DATA = -1, /* Random unexpected data errors. */
1214 E_BAD_LAZY = -2, /* Badly ordered laziness. */
1215 E_BAD_IMPORT = -3 /* A nested import failed. */
1218 protected:
1219 /* File identification. On-disk representation. */
1220 struct ident {
1221 uint8_t magic[4]; /* 0x7f, 'E', 'L', 'F' */
1222 uint8_t klass; /* 4:CLASS32 */
1223 uint8_t data; /* 5:DATA2[LM]SB */
1224 uint8_t version; /* 6:EV_CURRENT */
1225 uint8_t osabi; /* 7:OSABI_NONE */
1226 uint8_t abiver; /* 8: 0 */
1227 uint8_t pad[7]; /* 9-15 */
1229 /* File header. On-disk representation. */
1230 struct header {
1231 struct ident ident;
1232 uint16_t type; /* ET_NONE */
1233 uint16_t machine; /* EM_NONE */
1234 uint32_t version; /* EV_CURRENT */
1235 uint32_t entry; /* 0 */
1236 uint32_t phoff; /* 0 */
1237 uint32_t shoff; /* Section Header Offset in file */
1238 uint32_t flags;
1239 uint16_t ehsize; /* ELROND Header SIZE -- sizeof (header) */
1240 uint16_t phentsize; /* 0 */
1241 uint16_t phnum; /* 0 */
1242 uint16_t shentsize; /* Section Header SIZE -- sizeof (section) */
1243 uint16_t shnum; /* Section Header NUM */
1244 uint16_t shstrndx; /* Section Header STRing iNDeX */
1246 /* File section. On-disk representation. */
1247 struct section {
1248 uint32_t name; /* String table offset. */
1249 uint32_t type; /* SHT_* */
1250 uint32_t flags; /* SHF_* */
1251 uint32_t addr; /* 0 */
1252 uint32_t offset; /* OFFSET in file */
1253 uint32_t size; /* SIZE of section */
1254 uint32_t link; /* 0 */
1255 uint32_t info; /* 0 */
1256 uint32_t addralign; /* 0 */
1257 uint32_t entsize; /* ENTry SIZE, usually 0 */
1260 protected:
1261 data hdr; /* The header. */
1262 data sectab; /* The section table. */
1263 data strtab; /* String table. */
1264 int fd; /* File descriptor we're reading or writing. */
1265 int err; /* Sticky error code. */
1267 public:
1268 /* Construct from STREAM. E is errno if STREAM NULL. */
1269 elf (int fd, int e)
1270 :hdr (), sectab (), strtab (), fd (fd), err (fd >= 0 ? 0 : e)
1272 ~elf ()
1274 gcc_checking_assert (fd < 0 && !hdr.buffer
1275 && !sectab.buffer && !strtab.buffer);
1278 public:
1279 /* Return the error, if we have an error. */
1280 int get_error () const
1282 return err;
1284 /* Set the error, unless it's already been set. */
1285 void set_error (int e = E_BAD_DATA)
1287 if (!err)
1288 err = e;
1290 /* Get an error string. */
1291 const char *get_error (const char *) const;
1293 public:
1294 /* Begin reading/writing file. Return false on error. */
1295 bool begin () const
1297 return !get_error ();
1299 /* Finish reading/writing file. Return false on error. */
1300 bool end ();
1303 /* Return error string. */
1305 const char *
1306 elf::get_error (const char *name) const
1308 if (!name)
1309 return "Unknown CMI mapping";
1311 switch (err)
1313 case 0:
1314 gcc_unreachable ();
1315 case E_BAD_DATA:
1316 return "Bad file data";
1317 case E_BAD_IMPORT:
1318 return "Bad import dependency";
1319 case E_BAD_LAZY:
1320 return "Bad lazy ordering";
1321 default:
1322 return xstrerror (err);
1326 /* Finish file, return true if there's an error. */
1328 bool
1329 elf::end ()
1331 /* Close the stream and free the section table. */
1332 if (fd >= 0 && close (fd))
1333 set_error (errno);
1334 fd = -1;
1336 return !get_error ();
1339 /* ELROND reader. */
1341 class elf_in : public elf {
1342 typedef elf parent;
1344 private:
1345 /* For freezing & defrosting. */
1346 #if !defined (HOST_LACKS_INODE_NUMBERS)
1347 dev_t device;
1348 ino_t inode;
1349 #endif
1351 public:
1352 elf_in (int fd, int e)
1353 :parent (fd, e)
1356 ~elf_in ()
1360 public:
1361 bool is_frozen () const
1363 return fd < 0 && hdr.pos;
1365 bool is_freezable () const
1367 return fd >= 0 && hdr.pos;
1369 void freeze ();
1370 bool defrost (const char *);
1372 /* If BYTES is in the mmapped area, allocate a new buffer for it. */
1373 void preserve (bytes_in &bytes ATTRIBUTE_UNUSED)
1375 #if MAPPED_READING
1376 if (hdr.buffer && bytes.buffer >= hdr.buffer
1377 && bytes.buffer < hdr.buffer + hdr.pos)
1379 char *buf = bytes.buffer;
1380 bytes.buffer = data::simple_memory.grow (NULL, bytes.size);
1381 memcpy (bytes.buffer, buf, bytes.size);
1383 #endif
1385 /* If BYTES is not in SELF's mmapped area, free it. SELF might be
1386 NULL. */
1387 static void release (elf_in *self ATTRIBUTE_UNUSED, bytes_in &bytes)
1389 #if MAPPED_READING
1390 if (!(self && self->hdr.buffer && bytes.buffer >= self->hdr.buffer
1391 && bytes.buffer < self->hdr.buffer + self->hdr.pos))
1392 #endif
1393 data::simple_memory.shrink (bytes.buffer);
1394 bytes.buffer = NULL;
1395 bytes.size = 0;
1398 public:
1399 static void grow (data &data, unsigned needed)
1401 gcc_checking_assert (!data.buffer);
1402 #if !MAPPED_READING
1403 data.buffer = XNEWVEC (char, needed);
1404 #endif
1405 data.size = needed;
1407 static void shrink (data &data)
1409 #if !MAPPED_READING
1410 XDELETEVEC (data.buffer);
1411 #endif
1412 data.buffer = NULL;
1413 data.size = 0;
1416 public:
1417 const section *get_section (unsigned s) const
1419 if (s * sizeof (section) < sectab.size)
1420 return reinterpret_cast<const section *>
1421 (&sectab.buffer[s * sizeof (section)]);
1422 else
1423 return NULL;
1425 unsigned get_section_limit () const
1427 return sectab.size / sizeof (section);
1430 protected:
1431 const char *read (data *, unsigned, unsigned);
1433 public:
1434 /* Read section by number. */
1435 bool read (data *d, const section *s)
1437 return s && read (d, s->offset, s->size);
1440 /* Find section by name. */
1441 unsigned find (const char *name);
1442 /* Find section by index. */
1443 const section *find (unsigned snum, unsigned type = SHT_PROGBITS);
1445 public:
1446 /* Release the string table, when we're done with it. */
1447 void release ()
1449 shrink (strtab);
1452 public:
1453 bool begin (location_t);
1454 bool end ()
1456 release ();
1457 #if MAPPED_READING
1458 if (hdr.buffer)
1459 munmap (hdr.buffer, hdr.pos);
1460 hdr.buffer = NULL;
1461 #endif
1462 shrink (sectab);
1464 return parent::end ();
1467 public:
1468 /* Return string name at OFFSET. Checks OFFSET range. Always
1469 returns non-NULL. We know offset 0 is an empty string. */
1470 const char *name (unsigned offset)
1472 return &strtab.buffer[offset < strtab.size ? offset : 0];
1476 /* ELROND writer. */
1478 class elf_out : public elf, public data::allocator {
1479 typedef elf parent;
1480 /* Desired section alignment on disk. */
1481 static const int SECTION_ALIGN = 16;
1483 private:
1484 ptr_int_hash_map identtab; /* Map of IDENTIFIERS to strtab offsets. */
1485 unsigned pos; /* Write position in file. */
1486 #if MAPPED_WRITING
1487 unsigned offset; /* Offset of the mapping. */
1488 unsigned extent; /* Length of mapping. */
1489 unsigned page_size; /* System page size. */
1490 #endif
1492 public:
1493 elf_out (int fd, int e)
1494 :parent (fd, e), identtab (500), pos (0)
1496 #if MAPPED_WRITING
1497 offset = extent = 0;
1498 page_size = sysconf (_SC_PAGE_SIZE);
1499 if (page_size < SECTION_ALIGN)
1500 /* Something really strange. */
1501 set_error (EINVAL);
1502 #endif
1504 ~elf_out ()
1506 data::simple_memory.shrink (hdr);
1507 data::simple_memory.shrink (sectab);
1508 data::simple_memory.shrink (strtab);
1511 #if MAPPED_WRITING
1512 private:
1513 void create_mapping (unsigned ext, bool extending = true);
1514 void remove_mapping ();
1515 #endif
1517 protected:
1518 using allocator::grow;
1519 char *grow (char *, unsigned needed) final override;
1520 #if MAPPED_WRITING
1521 using allocator::shrink;
1522 void shrink (char *) final override;
1523 #endif
1525 public:
1526 unsigned get_section_limit () const
1528 return sectab.pos / sizeof (section);
1531 protected:
1532 unsigned add (unsigned type, unsigned name = 0,
1533 unsigned off = 0, unsigned size = 0, unsigned flags = SHF_NONE);
1534 unsigned write (const data &);
1535 #if MAPPED_WRITING
1536 unsigned write (const bytes_out &);
1537 #endif
1539 public:
1540 /* IDENTIFIER to strtab offset. */
1541 unsigned name (tree ident);
1542 /* String literal to strtab offset. */
1543 unsigned name (const char *n);
1544 /* Qualified name of DECL to strtab offset. */
1545 unsigned qualified_name (tree decl, bool is_defn);
1547 private:
1548 unsigned strtab_write (const char *s, unsigned l);
1549 void strtab_write (tree decl, int);
1551 public:
1552 /* Add a section with contents or strings. */
1553 unsigned add (const bytes_out &, bool string_p, unsigned name);
1555 public:
1556 /* Begin and end writing. */
1557 bool begin ();
1558 bool end ();
1561 /* Begin reading section NAME (of type PROGBITS) from SOURCE.
1562 Data always checked for CRC. */
1564 bool
1565 bytes_in::begin (location_t loc, elf_in *source, const char *name)
1567 unsigned snum = source->find (name);
1569 return begin (loc, source, snum, name);
1572 /* Begin reading section numbered SNUM with NAME (may be NULL). */
1574 bool
1575 bytes_in::begin (location_t loc, elf_in *source, unsigned snum, const char *name)
1577 if (!source->read (this, source->find (snum))
1578 || !size || !check_crc ())
1580 source->set_error (elf::E_BAD_DATA);
1581 source->shrink (*this);
1582 if (name)
1583 error_at (loc, "section %qs is missing or corrupted", name);
1584 else
1585 error_at (loc, "section #%u is missing or corrupted", snum);
1586 return false;
1588 pos = 4;
1589 return true;
1592 /* Finish reading a section. */
1594 bool
1595 bytes_in::end (elf_in *src)
1597 if (more_p ())
1598 set_overrun ();
1599 if (overrun)
1600 src->set_error ();
1602 src->shrink (*this);
1604 return !overrun;
1607 /* Begin writing buffer. */
1609 void
1610 bytes_out::begin (bool need_crc)
1612 if (need_crc)
1613 pos = 4;
1614 memory->grow (*this, 0, false);
1617 /* Finish writing buffer. Stream out to SINK as named section NAME.
1618 Return section number or 0 on failure. If CRC_PTR is true, crc
1619 the data. Otherwise it is a string section. */
1621 unsigned
1622 bytes_out::end (elf_out *sink, unsigned name, unsigned *crc_ptr)
1624 lengths[3] += pos;
1625 spans[3]++;
1627 set_crc (crc_ptr);
1628 unsigned sec_num = sink->add (*this, !crc_ptr, name);
1629 memory->shrink (*this);
1631 return sec_num;
1634 /* Close and open the file, without destroying it. */
1636 void
1637 elf_in::freeze ()
1639 gcc_checking_assert (!is_frozen ());
1640 #if MAPPED_READING
1641 if (munmap (hdr.buffer, hdr.pos) < 0)
1642 set_error (errno);
1643 #endif
1644 if (close (fd) < 0)
1645 set_error (errno);
1646 fd = -1;
1649 bool
1650 elf_in::defrost (const char *name)
1652 gcc_checking_assert (is_frozen ());
1653 struct stat stat;
1655 fd = open (name, O_RDONLY | O_CLOEXEC | O_BINARY);
1656 if (fd < 0 || fstat (fd, &stat) < 0)
1657 set_error (errno);
1658 else
1660 bool ok = hdr.pos == unsigned (stat.st_size);
1661 #ifndef HOST_LACKS_INODE_NUMBERS
1662 if (device != stat.st_dev
1663 || inode != stat.st_ino)
1664 ok = false;
1665 #endif
1666 if (!ok)
1667 set_error (EMFILE);
1668 #if MAPPED_READING
1669 if (ok)
1671 char *mapping = reinterpret_cast<char *>
1672 (mmap (NULL, hdr.pos, PROT_READ, MAP_SHARED, fd, 0));
1673 if (mapping == MAP_FAILED)
1674 fail:
1675 set_error (errno);
1676 else
1678 if (madvise (mapping, hdr.pos, MADV_RANDOM))
1679 goto fail;
1681 /* These buffers are never NULL in this case. */
1682 strtab.buffer = mapping + strtab.pos;
1683 sectab.buffer = mapping + sectab.pos;
1684 hdr.buffer = mapping;
1687 #endif
1690 return !get_error ();
1693 /* Read at current position into BUFFER. Return true on success. */
1695 const char *
1696 elf_in::read (data *data, unsigned pos, unsigned length)
1698 #if MAPPED_READING
1699 if (pos + length > hdr.pos)
1701 set_error (EINVAL);
1702 return NULL;
1704 #else
1705 if (pos != ~0u && lseek (fd, pos, SEEK_SET) < 0)
1707 set_error (errno);
1708 return NULL;
1710 #endif
1711 grow (*data, length);
1712 #if MAPPED_READING
1713 data->buffer = hdr.buffer + pos;
1714 #else
1715 if (::read (fd, data->buffer, data->size) != ssize_t (length))
1717 set_error (errno);
1718 shrink (*data);
1719 return NULL;
1721 #endif
1723 return data->buffer;
1726 /* Read section SNUM of TYPE. Return section pointer or NULL on error. */
1728 const elf::section *
1729 elf_in::find (unsigned snum, unsigned type)
1731 const section *sec = get_section (snum);
1732 if (!snum || !sec || sec->type != type)
1733 return NULL;
1734 return sec;
1737 /* Find a section NAME and TYPE. Return section number, or zero on
1738 failure. */
1740 unsigned
1741 elf_in::find (const char *sname)
1743 for (unsigned pos = sectab.size; pos -= sizeof (section); )
1745 const section *sec
1746 = reinterpret_cast<const section *> (&sectab.buffer[pos]);
1748 if (0 == strcmp (sname, name (sec->name)))
1749 return pos / sizeof (section);
1752 return 0;
1755 /* Begin reading file. Verify header. Pull in section and string
1756 tables. Return true on success. */
1758 bool
1759 elf_in::begin (location_t loc)
1761 if (!parent::begin ())
1762 return false;
1764 struct stat stat;
1765 unsigned size = 0;
1766 if (!fstat (fd, &stat))
1768 #if !defined (HOST_LACKS_INODE_NUMBERS)
1769 device = stat.st_dev;
1770 inode = stat.st_ino;
1771 #endif
1772 /* Never generate files > 4GB, check we've not been given one. */
1773 if (stat.st_size == unsigned (stat.st_size))
1774 size = unsigned (stat.st_size);
1777 #if MAPPED_READING
1778 /* MAP_SHARED so that the file is backing store. If someone else
1779 concurrently writes it, they're wrong. */
1780 void *mapping = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0);
1781 if (mapping == MAP_FAILED)
1783 fail:
1784 set_error (errno);
1785 return false;
1787 /* We'll be hopping over this randomly. Some systems declare the
1788 first parm as char *, and other declare it as void *. */
1789 if (madvise (reinterpret_cast <char *> (mapping), size, MADV_RANDOM))
1790 goto fail;
1792 hdr.buffer = (char *)mapping;
1793 #else
1794 read (&hdr, 0, sizeof (header));
1795 #endif
1796 hdr.pos = size; /* Record size of the file. */
1798 const header *h = reinterpret_cast<const header *> (hdr.buffer);
1799 if (!h)
1800 return false;
1802 if (h->ident.magic[0] != 0x7f
1803 || h->ident.magic[1] != 'E'
1804 || h->ident.magic[2] != 'L'
1805 || h->ident.magic[3] != 'F')
1807 error_at (loc, "not Encapsulated Lazy Records of Named Declarations");
1808 failed:
1809 shrink (hdr);
1810 return false;
1813 /* We expect a particular format -- the ELF is not intended to be
1814 distributable. */
1815 if (h->ident.klass != MY_CLASS
1816 || h->ident.data != MY_ENDIAN
1817 || h->ident.version != EV_CURRENT
1818 || h->type != ET_NONE
1819 || h->machine != EM_NONE
1820 || h->ident.osabi != OSABI_NONE)
1822 error_at (loc, "unexpected encapsulation format or type");
1823 goto failed;
1826 int e = -1;
1827 if (!h->shoff || h->shentsize != sizeof (section))
1829 malformed:
1830 set_error (e);
1831 error_at (loc, "encapsulation is malformed");
1832 goto failed;
1835 unsigned strndx = h->shstrndx;
1836 unsigned shnum = h->shnum;
1837 if (shnum == SHN_XINDEX)
1839 if (!read (&sectab, h->shoff, sizeof (section)))
1841 section_table_fail:
1842 e = errno;
1843 goto malformed;
1845 shnum = get_section (0)->size;
1846 /* Freeing does mean we'll re-read it in the case we're not
1847 mapping, but this is going to be rare. */
1848 shrink (sectab);
1851 if (!shnum)
1852 goto malformed;
1854 if (!read (&sectab, h->shoff, shnum * sizeof (section)))
1855 goto section_table_fail;
1857 if (strndx == SHN_XINDEX)
1858 strndx = get_section (0)->link;
1860 if (!read (&strtab, find (strndx, SHT_STRTAB)))
1861 goto malformed;
1863 /* The string table should be at least one byte, with NUL chars
1864 at either end. */
1865 if (!(strtab.size && !strtab.buffer[0]
1866 && !strtab.buffer[strtab.size - 1]))
1867 goto malformed;
1869 #if MAPPED_READING
1870 /* Record the offsets of the section and string tables. */
1871 sectab.pos = h->shoff;
1872 strtab.pos = shnum * sizeof (section);
1873 #else
1874 shrink (hdr);
1875 #endif
1877 return true;
1880 /* Create a new mapping. */
1882 #if MAPPED_WRITING
1883 void
1884 elf_out::create_mapping (unsigned ext, bool extending)
1886 #ifndef HAVE_POSIX_FALLOCATE
1887 #define posix_fallocate(fd,off,len) ftruncate (fd, off + len)
1888 #endif
1889 void *mapping = MAP_FAILED;
1890 if (extending && ext < 1024 * 1024)
1892 if (!posix_fallocate (fd, offset, ext * 2))
1893 mapping = mmap (NULL, ext * 2, PROT_READ | PROT_WRITE,
1894 MAP_SHARED, fd, offset);
1895 if (mapping != MAP_FAILED)
1896 ext *= 2;
1898 if (mapping == MAP_FAILED)
1900 if (!extending || !posix_fallocate (fd, offset, ext))
1901 mapping = mmap (NULL, ext, PROT_READ | PROT_WRITE,
1902 MAP_SHARED, fd, offset);
1903 if (mapping == MAP_FAILED)
1905 set_error (errno);
1906 mapping = NULL;
1907 ext = 0;
1910 #undef posix_fallocate
1911 hdr.buffer = (char *)mapping;
1912 extent = ext;
1914 #endif
1916 /* Flush out the current mapping. */
1918 #if MAPPED_WRITING
1919 void
1920 elf_out::remove_mapping ()
1922 if (hdr.buffer)
1924 /* MS_ASYNC dtrt with the removed mapping, including a
1925 subsequent overlapping remap. */
1926 if (msync (hdr.buffer, extent, MS_ASYNC)
1927 || munmap (hdr.buffer, extent))
1928 /* We're somewhat screwed at this point. */
1929 set_error (errno);
1932 hdr.buffer = NULL;
1934 #endif
1936 /* Grow a mapping of PTR to be NEEDED bytes long. This gets
1937 interesting if the new size grows the EXTENT. */
1939 char *
1940 elf_out::grow (char *data, unsigned needed)
1942 if (!data)
1944 /* First allocation, check we're aligned. */
1945 gcc_checking_assert (!(pos & (SECTION_ALIGN - 1)));
1946 #if MAPPED_WRITING
1947 data = hdr.buffer + (pos - offset);
1948 #endif
1951 #if MAPPED_WRITING
1952 unsigned off = data - hdr.buffer;
1953 if (off + needed > extent)
1955 /* We need to grow the mapping. */
1956 unsigned lwm = off & ~(page_size - 1);
1957 unsigned hwm = (off + needed + page_size - 1) & ~(page_size - 1);
1959 gcc_checking_assert (hwm > extent);
1961 remove_mapping ();
1963 offset += lwm;
1964 create_mapping (extent < hwm - lwm ? hwm - lwm : extent);
1966 data = hdr.buffer + (off - lwm);
1968 #else
1969 data = allocator::grow (data, needed);
1970 #endif
1972 return data;
1975 #if MAPPED_WRITING
1976 /* Shrinking is a NOP. */
1977 void
1978 elf_out::shrink (char *)
1981 #endif
1983 /* Write S of length L to the strtab buffer. L must include the ending
1984 NUL, if that's what you want. */
1986 unsigned
1987 elf_out::strtab_write (const char *s, unsigned l)
1989 if (strtab.pos + l > strtab.size)
1990 data::simple_memory.grow (strtab, strtab.pos + l, false);
1991 memcpy (strtab.buffer + strtab.pos, s, l);
1992 unsigned res = strtab.pos;
1993 strtab.pos += l;
1994 return res;
1997 /* Write qualified name of decl. INNER >0 if this is a definition, <0
1998 if this is a qualifier of an outer name. */
2000 void
2001 elf_out::strtab_write (tree decl, int inner)
2003 tree ctx = CP_DECL_CONTEXT (decl);
2004 if (TYPE_P (ctx))
2005 ctx = TYPE_NAME (ctx);
2006 if (ctx != global_namespace)
2007 strtab_write (ctx, -1);
2009 tree name = DECL_NAME (decl);
2010 if (!name)
2011 name = DECL_ASSEMBLER_NAME_RAW (decl);
2012 strtab_write (IDENTIFIER_POINTER (name), IDENTIFIER_LENGTH (name));
2014 if (inner)
2015 strtab_write (&"::{}"[inner+1], 2);
2018 /* Map IDENTIFIER IDENT to strtab offset. Inserts into strtab if not
2019 already there. */
2021 unsigned
2022 elf_out::name (tree ident)
2024 unsigned res = 0;
2025 if (ident)
2027 bool existed;
2028 int *slot = &identtab.get_or_insert (ident, &existed);
2029 if (!existed)
2030 *slot = strtab_write (IDENTIFIER_POINTER (ident),
2031 IDENTIFIER_LENGTH (ident) + 1);
2032 res = *slot;
2034 return res;
2037 /* Map LITERAL to strtab offset. Does not detect duplicates and
2038 expects LITERAL to remain live until strtab is written out. */
2040 unsigned
2041 elf_out::name (const char *literal)
2043 return strtab_write (literal, strlen (literal) + 1);
2046 /* Map a DECL's qualified name to strtab offset. Does not detect
2047 duplicates. */
2049 unsigned
2050 elf_out::qualified_name (tree decl, bool is_defn)
2052 gcc_checking_assert (DECL_P (decl) && decl != global_namespace);
2053 unsigned result = strtab.pos;
2055 strtab_write (decl, is_defn);
2056 strtab_write ("", 1);
2058 return result;
2061 /* Add section to file. Return section number. TYPE & NAME identify
2062 the section. OFF and SIZE identify the file location of its
2063 data. FLAGS contains additional info. */
2065 unsigned
2066 elf_out::add (unsigned type, unsigned name, unsigned off, unsigned size,
2067 unsigned flags)
2069 gcc_checking_assert (!(off & (SECTION_ALIGN - 1)));
2070 if (sectab.pos + sizeof (section) > sectab.size)
2071 data::simple_memory.grow (sectab, sectab.pos + sizeof (section), false);
2072 section *sec = reinterpret_cast<section *> (sectab.buffer + sectab.pos);
2073 memset (sec, 0, sizeof (section));
2074 sec->type = type;
2075 sec->flags = flags;
2076 sec->name = name;
2077 sec->offset = off;
2078 sec->size = size;
2079 if (flags & SHF_STRINGS)
2080 sec->entsize = 1;
2082 unsigned res = sectab.pos;
2083 sectab.pos += sizeof (section);
2084 return res / sizeof (section);
2087 /* Pad to the next alignment boundary, then write BUFFER to disk.
2088 Return the position of the start of the write, or zero on failure. */
2090 unsigned
2091 elf_out::write (const data &buffer)
2093 #if MAPPED_WRITING
2094 /* HDR is always mapped. */
2095 if (&buffer != &hdr)
2097 bytes_out out (this);
2098 grow (out, buffer.pos, true);
2099 if (out.buffer)
2100 memcpy (out.buffer, buffer.buffer, buffer.pos);
2101 shrink (out);
2103 else
2104 /* We should have been aligned during the first allocation. */
2105 gcc_checking_assert (!(pos & (SECTION_ALIGN - 1)));
2106 #else
2107 if (::write (fd, buffer.buffer, buffer.pos) != ssize_t (buffer.pos))
2109 set_error (errno);
2110 return 0;
2112 #endif
2113 unsigned res = pos;
2114 pos += buffer.pos;
2116 if (unsigned padding = -pos & (SECTION_ALIGN - 1))
2118 #if !MAPPED_WRITING
2119 /* Align the section on disk, should help the necessary copies.
2120 fseeking to extend is non-portable. */
2121 static char zero[SECTION_ALIGN];
2122 if (::write (fd, &zero, padding) != ssize_t (padding))
2123 set_error (errno);
2124 #endif
2125 pos += padding;
2127 return res;
2130 /* Write a streaming buffer. It must be using us as an allocator. */
2132 #if MAPPED_WRITING
2133 unsigned
2134 elf_out::write (const bytes_out &buf)
2136 gcc_checking_assert (buf.memory == this);
2137 /* A directly mapped buffer. */
2138 gcc_checking_assert (buf.buffer - hdr.buffer >= 0
2139 && buf.buffer - hdr.buffer + buf.size <= extent);
2140 unsigned res = pos;
2141 pos += buf.pos;
2143 /* Align up. We're not going to advance into the next page. */
2144 pos += -pos & (SECTION_ALIGN - 1);
2146 return res;
2148 #endif
2150 /* Write data and add section. STRING_P is true for a string
2151 section, false for PROGBITS. NAME identifies the section (0 is the
2152 empty name). DATA is the contents. Return section number or 0 on
2153 failure (0 is the undef section). */
2155 unsigned
2156 elf_out::add (const bytes_out &data, bool string_p, unsigned name)
2158 unsigned off = write (data);
2160 return add (string_p ? SHT_STRTAB : SHT_PROGBITS, name,
2161 off, data.pos, string_p ? SHF_STRINGS : SHF_NONE);
2164 /* Begin writing the file. Initialize the section table and write an
2165 empty header. Return false on failure. */
2167 bool
2168 elf_out::begin ()
2170 if (!parent::begin ())
2171 return false;
2173 /* Let the allocators pick a default. */
2174 data::simple_memory.grow (strtab, 0, false);
2175 data::simple_memory.grow (sectab, 0, false);
2177 /* The string table starts with an empty string. */
2178 name ("");
2180 /* Create the UNDEF section. */
2181 add (SHT_NONE);
2183 #if MAPPED_WRITING
2184 /* Start a mapping. */
2185 create_mapping (EXPERIMENT (page_size,
2186 (32767 + page_size) & ~(page_size - 1)));
2187 if (!hdr.buffer)
2188 return false;
2189 #endif
2191 /* Write an empty header. */
2192 grow (hdr, sizeof (header), true);
2193 header *h = reinterpret_cast<header *> (hdr.buffer);
2194 memset (h, 0, sizeof (header));
2195 hdr.pos = hdr.size;
2196 write (hdr);
2197 return !get_error ();
2200 /* Finish writing the file. Write out the string & section tables.
2201 Fill in the header. Return true on error. */
2203 bool
2204 elf_out::end ()
2206 if (fd >= 0)
2208 /* Write the string table. */
2209 unsigned strnam = name (".strtab");
2210 unsigned stroff = write (strtab);
2211 unsigned strndx = add (SHT_STRTAB, strnam, stroff, strtab.pos,
2212 SHF_STRINGS);
2214 /* Store escape values in section[0]. */
2215 if (strndx >= SHN_LORESERVE)
2217 reinterpret_cast<section *> (sectab.buffer)->link = strndx;
2218 strndx = SHN_XINDEX;
2220 unsigned shnum = sectab.pos / sizeof (section);
2221 if (shnum >= SHN_LORESERVE)
2223 reinterpret_cast<section *> (sectab.buffer)->size = shnum;
2224 shnum = SHN_XINDEX;
2227 unsigned shoff = write (sectab);
2229 #if MAPPED_WRITING
2230 if (offset)
2232 remove_mapping ();
2233 offset = 0;
2234 create_mapping ((sizeof (header) + page_size - 1) & ~(page_size - 1),
2235 false);
2237 unsigned length = pos;
2238 #else
2239 if (lseek (fd, 0, SEEK_SET) < 0)
2240 set_error (errno);
2241 #endif
2242 /* Write header. */
2243 if (!get_error ())
2245 /* Write the correct header now. */
2246 header *h = reinterpret_cast<header *> (hdr.buffer);
2247 h->ident.magic[0] = 0x7f;
2248 h->ident.magic[1] = 'E'; /* Elrond */
2249 h->ident.magic[2] = 'L'; /* is an */
2250 h->ident.magic[3] = 'F'; /* elf. */
2251 h->ident.klass = MY_CLASS;
2252 h->ident.data = MY_ENDIAN;
2253 h->ident.version = EV_CURRENT;
2254 h->ident.osabi = OSABI_NONE;
2255 h->type = ET_NONE;
2256 h->machine = EM_NONE;
2257 h->version = EV_CURRENT;
2258 h->shoff = shoff;
2259 h->ehsize = sizeof (header);
2260 h->shentsize = sizeof (section);
2261 h->shnum = shnum;
2262 h->shstrndx = strndx;
2264 pos = 0;
2265 write (hdr);
2268 #if MAPPED_WRITING
2269 remove_mapping ();
2270 if (ftruncate (fd, length))
2271 set_error (errno);
2272 #endif
2275 data::simple_memory.shrink (sectab);
2276 data::simple_memory.shrink (strtab);
2278 return parent::end ();
2281 /********************************************************************/
2283 /* A dependency set. This is used during stream out to determine the
2284 connectivity of the graph. Every namespace-scope declaration that
2285 needs writing has a depset. The depset is filled with the (depsets
2286 of) declarations within this module that it references. For a
2287 declaration that'll generally be named types. For definitions
2288 it'll also be declarations in the body.
2290 From that we can convert the graph to a DAG, via determining the
2291 Strongly Connected Clusters. Each cluster is streamed
2292 independently, and thus we achieve lazy loading.
2294 Other decls that get a depset are namespaces themselves and
2295 unnameable declarations. */
2297 class depset {
2298 private:
2299 tree entity; /* Entity, or containing namespace. */
2300 uintptr_t discriminator; /* Flags or identifier. */
2302 public:
2303 /* The kinds of entity the depset could describe. The ordering is
2304 significant, see entity_kind_name. */
2305 enum entity_kind
2307 EK_DECL, /* A decl. */
2308 EK_SPECIALIZATION, /* A specialization. */
2309 EK_PARTIAL, /* A partial specialization. */
2310 EK_USING, /* A using declaration (at namespace scope). */
2311 EK_NAMESPACE, /* A namespace. */
2312 EK_REDIRECT, /* Redirect to a template_decl. */
2313 EK_EXPLICIT_HWM,
2314 EK_BINDING = EK_EXPLICIT_HWM, /* Implicitly encoded. */
2315 EK_FOR_BINDING, /* A decl being inserted for a binding. */
2316 EK_INNER_DECL, /* A decl defined outside of its imported
2317 context. */
2318 EK_DIRECT_HWM = EK_PARTIAL + 1,
2320 EK_BITS = 3 /* Only need to encode below EK_EXPLICIT_HWM. */
2323 private:
2324 /* Placement of bit fields in discriminator. */
2325 enum disc_bits
2327 DB_ZERO_BIT, /* Set to disambiguate identifier from flags */
2328 DB_SPECIAL_BIT, /* First dep slot is special. */
2329 DB_KIND_BIT, /* Kind of the entity. */
2330 DB_KIND_BITS = EK_BITS,
2331 DB_DEFN_BIT = DB_KIND_BIT + DB_KIND_BITS,
2332 DB_IS_MEMBER_BIT, /* Is an out-of-class member. */
2333 DB_IS_INTERNAL_BIT, /* It is an (erroneous)
2334 internal-linkage entity. */
2335 DB_REFS_INTERNAL_BIT, /* Refers to an internal-linkage
2336 entity. */
2337 DB_IMPORTED_BIT, /* An imported entity. */
2338 DB_UNREACHED_BIT, /* A yet-to-be reached entity. */
2339 DB_HIDDEN_BIT, /* A hidden binding. */
2340 /* The following bits are not independent, but enumerating them is
2341 awkward. */
2342 DB_TYPE_SPEC_BIT, /* Specialization in the type table. */
2343 DB_FRIEND_SPEC_BIT, /* An instantiated template friend. */
2346 public:
2347 /* The first slot is special for EK_SPECIALIZATIONS it is a
2348 spec_entry pointer. It is not relevant for the SCC
2349 determination. */
2350 vec<depset *> deps; /* Depsets we reference. */
2352 public:
2353 unsigned cluster; /* Strongly connected cluster, later entity number */
2354 unsigned section; /* Section written to. */
2355 /* During SCC construction, section is lowlink, until the depset is
2356 removed from the stack. See Tarjan algorithm for details. */
2358 private:
2359 /* Construction via factories. Destruction via hash traits. */
2360 depset (tree entity);
2361 ~depset ();
2363 public:
2364 static depset *make_binding (tree, tree);
2365 static depset *make_entity (tree, entity_kind, bool = false);
2366 /* Late setting a binding name -- /then/ insert into hash! */
2367 inline void set_binding_name (tree name)
2369 gcc_checking_assert (!get_name ());
2370 discriminator = reinterpret_cast<uintptr_t> (name);
2373 private:
2374 template<unsigned I> void set_flag_bit ()
2376 gcc_checking_assert (I < 2 || !is_binding ());
2377 discriminator |= 1u << I;
2379 template<unsigned I> void clear_flag_bit ()
2381 gcc_checking_assert (I < 2 || !is_binding ());
2382 discriminator &= ~(1u << I);
2384 template<unsigned I> bool get_flag_bit () const
2386 gcc_checking_assert (I < 2 || !is_binding ());
2387 return bool ((discriminator >> I) & 1);
2390 public:
2391 bool is_binding () const
2393 return !get_flag_bit<DB_ZERO_BIT> ();
2395 entity_kind get_entity_kind () const
2397 if (is_binding ())
2398 return EK_BINDING;
2399 return entity_kind ((discriminator >> DB_KIND_BIT) & ((1u << EK_BITS) - 1));
2401 const char *entity_kind_name () const;
2403 public:
2404 bool has_defn () const
2406 return get_flag_bit<DB_DEFN_BIT> ();
2409 public:
2410 /* This class-member is defined here, but the class was imported. */
2411 bool is_member () const
2413 gcc_checking_assert (get_entity_kind () == EK_DECL);
2414 return get_flag_bit<DB_IS_MEMBER_BIT> ();
2416 public:
2417 bool is_internal () const
2419 return get_flag_bit<DB_IS_INTERNAL_BIT> ();
2421 bool refs_internal () const
2423 return get_flag_bit<DB_REFS_INTERNAL_BIT> ();
2425 bool is_import () const
2427 return get_flag_bit<DB_IMPORTED_BIT> ();
2429 bool is_unreached () const
2431 return get_flag_bit<DB_UNREACHED_BIT> ();
2433 bool is_hidden () const
2435 return get_flag_bit<DB_HIDDEN_BIT> ();
2437 bool is_type_spec () const
2439 return get_flag_bit<DB_TYPE_SPEC_BIT> ();
2441 bool is_friend_spec () const
2443 return get_flag_bit<DB_FRIEND_SPEC_BIT> ();
2446 public:
2447 /* We set these bit outside of depset. */
2448 void set_hidden_binding ()
2450 set_flag_bit<DB_HIDDEN_BIT> ();
2452 void clear_hidden_binding ()
2454 clear_flag_bit<DB_HIDDEN_BIT> ();
2457 public:
2458 bool is_special () const
2460 return get_flag_bit<DB_SPECIAL_BIT> ();
2462 void set_special ()
2464 set_flag_bit<DB_SPECIAL_BIT> ();
2467 public:
2468 tree get_entity () const
2470 return entity;
2472 tree get_name () const
2474 gcc_checking_assert (is_binding ());
2475 return reinterpret_cast <tree> (discriminator);
2478 public:
2479 /* Traits for a hash table of pointers to bindings. */
2480 struct traits {
2481 /* Each entry is a pointer to a depset. */
2482 typedef depset *value_type;
2483 /* We lookup by container:maybe-identifier pair. */
2484 typedef std::pair<tree,tree> compare_type;
2486 static const bool empty_zero_p = true;
2488 /* hash and equality for compare_type. */
2489 inline static hashval_t hash (const compare_type &p)
2491 hashval_t h = pointer_hash<tree_node>::hash (p.first);
2492 if (p.second)
2494 hashval_t nh = IDENTIFIER_HASH_VALUE (p.second);
2495 h = iterative_hash_hashval_t (h, nh);
2497 return h;
2499 inline static bool equal (const value_type b, const compare_type &p)
2501 if (b->entity != p.first)
2502 return false;
2504 if (p.second)
2505 return b->discriminator == reinterpret_cast<uintptr_t> (p.second);
2506 else
2507 return !b->is_binding ();
2510 /* (re)hasher for a binding itself. */
2511 inline static hashval_t hash (const value_type b)
2513 hashval_t h = pointer_hash<tree_node>::hash (b->entity);
2514 if (b->is_binding ())
2516 hashval_t nh = IDENTIFIER_HASH_VALUE (b->get_name ());
2517 h = iterative_hash_hashval_t (h, nh);
2519 return h;
2522 /* Empty via NULL. */
2523 static inline void mark_empty (value_type &p) {p = NULL;}
2524 static inline bool is_empty (value_type p) {return !p;}
2526 /* Nothing is deletable. Everything is insertable. */
2527 static bool is_deleted (value_type) { return false; }
2528 static void mark_deleted (value_type) { gcc_unreachable (); }
2530 /* We own the entities in the hash table. */
2531 static void remove (value_type p)
2533 delete (p);
2537 public:
2538 class hash : public hash_table<traits> {
2539 typedef traits::compare_type key_t;
2540 typedef hash_table<traits> parent;
2542 public:
2543 vec<depset *> worklist; /* Worklist of decls to walk. */
2544 hash *chain; /* Original table. */
2545 depset *current; /* Current depset being depended. */
2546 unsigned section; /* When writing out, the section. */
2547 bool reached_unreached; /* We reached an unreached entity. */
2549 public:
2550 hash (size_t size, hash *c = NULL)
2551 : parent (size), chain (c), current (NULL), section (0),
2552 reached_unreached (false)
2554 worklist.create (size);
2556 ~hash ()
2558 worklist.release ();
2561 public:
2562 bool is_key_order () const
2564 return chain != NULL;
2567 private:
2568 depset **entity_slot (tree entity, bool = true);
2569 depset **binding_slot (tree ctx, tree name, bool = true);
2570 depset *maybe_add_declaration (tree decl);
2572 public:
2573 depset *find_dependency (tree entity);
2574 depset *find_binding (tree ctx, tree name);
2575 depset *make_dependency (tree decl, entity_kind);
2576 void add_dependency (depset *);
2578 public:
2579 void add_mergeable (depset *);
2580 depset *add_dependency (tree decl, entity_kind);
2581 void add_namespace_context (depset *, tree ns);
2583 private:
2584 static bool add_binding_entity (tree, WMB_Flags, void *);
2586 public:
2587 bool add_namespace_entities (tree ns, bitmap partitions);
2588 void add_specializations (bool decl_p);
2589 void add_partial_entities (vec<tree, va_gc> *);
2590 void add_class_entities (vec<tree, va_gc> *);
2592 public:
2593 void find_dependencies (module_state *);
2594 bool finalize_dependencies ();
2595 vec<depset *> connect ();
2598 public:
2599 struct tarjan {
2600 vec<depset *> result;
2601 vec<depset *> stack;
2602 unsigned index;
2604 tarjan (unsigned size)
2605 : index (0)
2607 result.create (size);
2608 stack.create (50);
2610 ~tarjan ()
2612 gcc_assert (!stack.length ());
2613 stack.release ();
2616 public:
2617 void connect (depset *);
2621 inline
2622 depset::depset (tree entity)
2623 :entity (entity), discriminator (0), cluster (0), section (0)
2625 deps.create (0);
2628 inline
2629 depset::~depset ()
2631 deps.release ();
2634 const char *
2635 depset::entity_kind_name () const
2637 /* Same order as entity_kind. */
2638 static const char *const names[] =
2639 {"decl", "specialization", "partial", "using",
2640 "namespace", "redirect", "binding"};
2641 entity_kind kind = get_entity_kind ();
2642 gcc_checking_assert (kind < ARRAY_SIZE (names));
2643 return names[kind];
2646 /* Create a depset for a namespace binding NS::NAME. */
2648 depset *depset::make_binding (tree ns, tree name)
2650 depset *binding = new depset (ns);
2652 binding->discriminator = reinterpret_cast <uintptr_t> (name);
2654 return binding;
2657 depset *depset::make_entity (tree entity, entity_kind ek, bool is_defn)
2659 depset *r = new depset (entity);
2661 r->discriminator = ((1 << DB_ZERO_BIT)
2662 | (ek << DB_KIND_BIT)
2663 | is_defn << DB_DEFN_BIT);
2665 return r;
2668 class pending_key
2670 public:
2671 tree ns;
2672 tree id;
2675 template<>
2676 struct default_hash_traits<pending_key>
2678 using value_type = pending_key;
2680 static const bool empty_zero_p = false;
2681 static hashval_t hash (const value_type &k)
2683 hashval_t h = IDENTIFIER_HASH_VALUE (k.id);
2684 h = iterative_hash_hashval_t (DECL_UID (k.ns), h);
2686 return h;
2688 static bool equal (const value_type &k, const value_type &l)
2690 return k.ns == l.ns && k.id == l.id;
2692 static void mark_empty (value_type &k)
2694 k.ns = k.id = NULL_TREE;
2696 static void mark_deleted (value_type &k)
2698 k.ns = NULL_TREE;
2699 gcc_checking_assert (k.id);
2701 static bool is_empty (const value_type &k)
2703 return k.ns == NULL_TREE && k.id == NULL_TREE;
2705 static bool is_deleted (const value_type &k)
2707 return k.ns == NULL_TREE && k.id != NULL_TREE;
2709 static void remove (value_type &)
2714 typedef hash_map<pending_key, auto_vec<unsigned>> pending_map_t;
2716 /* Not-loaded entities that are keyed to a namespace-scope
2717 identifier. See module_state::write_pendings for details. */
2718 pending_map_t *pending_table;
2720 /* Decls that need some post processing once a batch of lazy loads has
2721 completed. */
2722 vec<tree, va_heap, vl_embed> *post_load_decls;
2724 /* Some entities are keyed to another entitity for ODR purposes.
2725 For example, at namespace scope, 'inline auto var = []{};', that
2726 lambda is keyed to 'var', and follows its ODRness. */
2727 typedef hash_map<tree, auto_vec<tree>> keyed_map_t;
2728 static keyed_map_t *keyed_table;
2730 /* Instantiations of temploid friends imported from another module
2731 need to be attached to the same module as the temploid. This maps
2732 these decls to the temploid they are instantiated them, as there is
2733 no other easy way to get this information. */
2734 static GTY((cache)) decl_tree_cache_map *imported_temploid_friends;
2736 /********************************************************************/
2737 /* Tree streaming. The tree streaming is very specific to the tree
2738 structures themselves. A tag indicates the kind of tree being
2739 streamed. -ve tags indicate backreferences to already-streamed
2740 trees. Backreferences are auto-numbered. */
2742 /* Tree tags. */
2743 enum tree_tag {
2744 tt_null, /* NULL_TREE. */
2745 tt_fixed, /* Fixed vector index. */
2747 tt_node, /* By-value node. */
2748 tt_decl, /* By-value mergeable decl. */
2749 tt_tpl_parm, /* Template parm. */
2751 /* The ordering of the following 4 is relied upon in
2752 trees_out::tree_node. */
2753 tt_id, /* Identifier node. */
2754 tt_conv_id, /* Conversion operator name. */
2755 tt_anon_id, /* Anonymous name. */
2756 tt_lambda_id, /* Lambda name. */
2758 tt_typedef_type, /* A (possibly implicit) typedefed type. */
2759 tt_derived_type, /* A type derived from another type. */
2760 tt_variant_type, /* A variant of another type. */
2762 tt_tinfo_var, /* Typeinfo object. */
2763 tt_tinfo_typedef, /* Typeinfo typedef. */
2764 tt_ptrmem_type, /* Pointer to member type. */
2765 tt_nttp_var, /* NTTP_OBJECT VAR_DECL. */
2767 tt_parm, /* Function parameter or result. */
2768 tt_enum_value, /* An enum value. */
2769 tt_enum_decl, /* An enum decl. */
2770 tt_data_member, /* Data member/using-decl. */
2772 tt_binfo, /* A BINFO. */
2773 tt_vtable, /* A vtable. */
2774 tt_thunk, /* A thunk. */
2775 tt_clone_ref,
2777 tt_entity, /* A extra-cluster entity. */
2779 tt_template, /* The TEMPLATE_RESULT of a template. */
2782 enum walk_kind {
2783 WK_none, /* No walk to do (a back- or fixed-ref happened). */
2784 WK_normal, /* Normal walk (by-name if possible). */
2786 WK_value, /* By-value walk. */
2789 enum merge_kind
2791 MK_unique, /* Known unique. */
2792 MK_named, /* Found by CTX, NAME + maybe_arg types etc. */
2793 MK_field, /* Found by CTX and index on TYPE_FIELDS */
2794 MK_vtable, /* Found by CTX and index on TYPE_VTABLES */
2795 MK_as_base, /* Found by CTX. */
2797 MK_partial,
2799 MK_enum, /* Found by CTX, & 1stMemberNAME. */
2800 MK_keyed, /* Found by key & index. */
2801 MK_local_type, /* Found by CTX, index. */
2803 MK_friend_spec, /* Like named, but has a tmpl & args too. */
2804 MK_local_friend, /* Found by CTX, index. */
2806 MK_indirect_lwm = MK_enum,
2808 /* Template specialization kinds below. These are all found via
2809 primary template and specialization args. */
2810 MK_template_mask = 0x10, /* A template specialization. */
2812 MK_tmpl_decl_mask = 0x4, /* In decl table. */
2814 MK_tmpl_tmpl_mask = 0x1, /* We want TEMPLATE_DECL. */
2816 MK_type_spec = MK_template_mask,
2817 MK_decl_spec = MK_template_mask | MK_tmpl_decl_mask,
2819 MK_hwm = 0x20
2821 /* This is more than a debugging array. NULLs are used to determine
2822 an invalid merge_kind number. */
2823 static char const *const merge_kind_name[MK_hwm] =
2825 "unique", "named", "field", "vtable", /* 0...3 */
2826 "asbase", "partial", "enum", "attached", /* 4...7 */
2828 "local type", "friend spec", "local friend", NULL, /* 8...11 */
2829 NULL, NULL, NULL, NULL,
2831 "type spec", "type tmpl spec", /* 16,17 type (template). */
2832 NULL, NULL,
2834 "decl spec", "decl tmpl spec", /* 20,21 decl (template). */
2835 NULL, NULL,
2836 NULL, NULL, NULL, NULL,
2837 NULL, NULL, NULL, NULL,
2840 /* Mergeable entity location data. */
2841 struct merge_key {
2842 cp_ref_qualifier ref_q : 2;
2843 unsigned index;
2845 tree ret; /* Return type, if appropriate. */
2846 tree args; /* Arg types, if appropriate. */
2848 tree constraints; /* Constraints. */
2850 merge_key ()
2851 :ref_q (REF_QUAL_NONE), index (0),
2852 ret (NULL_TREE), args (NULL_TREE),
2853 constraints (NULL_TREE)
2858 /* Hashmap of merged duplicates. Usually decls, but can contain
2859 BINFOs. */
2860 typedef hash_map<tree,uintptr_t,
2861 simple_hashmap_traits<nodel_ptr_hash<tree_node>,uintptr_t> >
2862 duplicate_hash_map;
2864 /* Data needed for post-processing. */
2865 struct post_process_data {
2866 tree decl;
2867 location_t start_locus;
2868 location_t end_locus;
2871 /* Tree stream reader. Note that reading a stream doesn't mark the
2872 read trees with TREE_VISITED. Thus it's quite safe to have
2873 multiple concurrent readers. Which is good, because lazy
2874 loading.
2876 It's important that trees_in/out have internal linkage so that the
2877 compiler knows core_bools, lang_type_bools and lang_decl_bools have
2878 only a single caller (tree_node_bools) and inlines them appropriately. */
2879 namespace {
2880 class trees_in : public bytes_in {
2881 typedef bytes_in parent;
2883 private:
2884 module_state *state; /* Module being imported. */
2885 vec<tree> back_refs; /* Back references. */
2886 duplicate_hash_map *duplicates; /* Map from existings to duplicate. */
2887 vec<post_process_data> post_decls; /* Decls to post process. */
2888 unsigned unused; /* Inhibit any interior TREE_USED
2889 marking. */
2891 public:
2892 trees_in (module_state *);
2893 ~trees_in ();
2895 public:
2896 int insert (tree);
2897 tree back_ref (int);
2899 private:
2900 tree start (unsigned = 0);
2902 public:
2903 /* Needed for binfo writing */
2904 bool core_bools (tree, bits_in&);
2906 private:
2907 /* Stream tree_core, lang_decl_specific and lang_type_specific
2908 bits. */
2909 bool core_vals (tree);
2910 bool lang_type_bools (tree, bits_in&);
2911 bool lang_type_vals (tree);
2912 bool lang_decl_bools (tree, bits_in&);
2913 bool lang_decl_vals (tree);
2914 bool lang_vals (tree);
2915 bool tree_node_bools (tree);
2916 bool tree_node_vals (tree);
2917 tree tree_value ();
2918 tree decl_value ();
2919 tree tpl_parm_value ();
2921 private:
2922 tree chained_decls (); /* Follow DECL_CHAIN. */
2923 vec<tree, va_heap> *vec_chained_decls ();
2924 vec<tree, va_gc> *tree_vec (); /* vec of tree. */
2925 vec<tree_pair_s, va_gc> *tree_pair_vec (); /* vec of tree_pair. */
2926 tree tree_list (bool has_purpose);
2928 public:
2929 /* Read a tree node. */
2930 tree tree_node (bool is_use = false);
2932 private:
2933 bool install_entity (tree decl);
2934 tree tpl_parms (unsigned &tpl_levels);
2935 bool tpl_parms_fini (tree decl, unsigned tpl_levels);
2936 bool tpl_header (tree decl, unsigned *tpl_levels);
2937 int fn_parms_init (tree);
2938 void fn_parms_fini (int tag, tree fn, tree existing, bool has_defn);
2939 unsigned add_indirect_tpl_parms (tree);
2940 public:
2941 bool add_indirects (tree);
2943 public:
2944 /* Serialize various definitions. */
2945 bool read_definition (tree decl);
2947 private:
2948 bool is_matching_decl (tree existing, tree decl, bool is_typedef);
2949 static bool install_implicit_member (tree decl);
2950 bool read_function_def (tree decl, tree maybe_template);
2951 bool read_var_def (tree decl, tree maybe_template);
2952 bool read_class_def (tree decl, tree maybe_template);
2953 bool read_enum_def (tree decl, tree maybe_template);
2955 public:
2956 tree decl_container ();
2957 tree key_mergeable (int tag, merge_kind, tree decl, tree inner, tree type,
2958 tree container, bool is_attached);
2959 unsigned binfo_mergeable (tree *);
2961 private:
2962 tree key_local_type (const merge_key&, tree, tree);
2963 uintptr_t *find_duplicate (tree existing);
2964 void register_duplicate (tree decl, tree existing);
2965 /* Mark as an already diagnosed bad duplicate. */
2966 void unmatched_duplicate (tree existing)
2968 *find_duplicate (existing) |= 1;
2971 public:
2972 bool is_duplicate (tree decl)
2974 return find_duplicate (decl) != NULL;
2976 tree maybe_duplicate (tree decl)
2978 if (uintptr_t *dup = find_duplicate (decl))
2979 return reinterpret_cast<tree> (*dup & ~uintptr_t (1));
2980 return decl;
2982 tree odr_duplicate (tree decl, bool has_defn);
2984 public:
2985 /* Return the decls to postprocess. */
2986 const vec<post_process_data>& post_process ()
2988 return post_decls;
2990 private:
2991 /* Register DATA for postprocessing. */
2992 void post_process (post_process_data data)
2994 post_decls.safe_push (data);
2997 private:
2998 void assert_definition (tree, bool installing);
3000 } // anon namespace
3002 trees_in::trees_in (module_state *state)
3003 :parent (), state (state), unused (0)
3005 duplicates = NULL;
3006 back_refs.create (500);
3007 post_decls.create (0);
3010 trees_in::~trees_in ()
3012 delete (duplicates);
3013 back_refs.release ();
3014 post_decls.release ();
3017 /* Tree stream writer. */
3018 namespace {
3019 class trees_out : public bytes_out {
3020 typedef bytes_out parent;
3022 private:
3023 module_state *state; /* The module we are writing. */
3024 ptr_int_hash_map tree_map; /* Trees to references */
3025 depset::hash *dep_hash; /* Dependency table. */
3026 int ref_num; /* Back reference number. */
3027 unsigned section;
3028 #if CHECKING_P
3029 int importedness; /* Checker that imports not occurring
3030 inappropriately. +ve imports ok,
3031 -ve imports not ok. */
3032 #endif
3034 public:
3035 trees_out (allocator *, module_state *, depset::hash &deps, unsigned sec = 0);
3036 ~trees_out ();
3038 private:
3039 void mark_trees ();
3040 void unmark_trees ();
3042 public:
3043 /* Hey, let's ignore the well known STL iterator idiom. */
3044 void begin ();
3045 unsigned end (elf_out *sink, unsigned name, unsigned *crc_ptr);
3046 void end ();
3048 public:
3049 enum tags
3051 tag_backref = -1, /* Upper bound on the backrefs. */
3052 tag_value = 0, /* Write by value. */
3053 tag_fixed /* Lower bound on the fixed trees. */
3056 public:
3057 bool is_key_order () const
3059 return dep_hash->is_key_order ();
3062 public:
3063 int insert (tree, walk_kind = WK_normal);
3065 private:
3066 void start (tree, bool = false);
3068 private:
3069 walk_kind ref_node (tree);
3070 public:
3071 int get_tag (tree);
3072 void set_importing (int i ATTRIBUTE_UNUSED)
3074 #if CHECKING_P
3075 importedness = i;
3076 #endif
3079 private:
3080 void core_bools (tree, bits_out&);
3081 void core_vals (tree);
3082 void lang_type_bools (tree, bits_out&);
3083 void lang_type_vals (tree);
3084 void lang_decl_bools (tree, bits_out&);
3085 void lang_decl_vals (tree);
3086 void lang_vals (tree);
3087 void tree_node_bools (tree);
3088 void tree_node_vals (tree);
3090 private:
3091 void chained_decls (tree);
3092 void vec_chained_decls (tree);
3093 void tree_vec (vec<tree, va_gc> *);
3094 void tree_pair_vec (vec<tree_pair_s, va_gc> *);
3095 void tree_list (tree, bool has_purpose);
3097 public:
3098 /* Mark a node for by-value walking. */
3099 void mark_by_value (tree);
3101 public:
3102 void tree_node (tree);
3104 private:
3105 void install_entity (tree decl, depset *);
3106 void tpl_parms (tree parms, unsigned &tpl_levels);
3107 void tpl_parms_fini (tree decl, unsigned tpl_levels);
3108 void fn_parms_fini (tree) {}
3109 unsigned add_indirect_tpl_parms (tree);
3110 public:
3111 void add_indirects (tree);
3112 void fn_parms_init (tree);
3113 void tpl_header (tree decl, unsigned *tpl_levels);
3115 public:
3116 merge_kind get_merge_kind (tree decl, depset *maybe_dep);
3117 tree decl_container (tree decl);
3118 void key_mergeable (int tag, merge_kind, tree decl, tree inner,
3119 tree container, depset *maybe_dep);
3120 void binfo_mergeable (tree binfo);
3122 private:
3123 void key_local_type (merge_key&, tree, tree);
3124 bool decl_node (tree, walk_kind ref);
3125 void type_node (tree);
3126 void tree_value (tree);
3127 void tpl_parm_value (tree);
3129 public:
3130 void decl_value (tree, depset *);
3132 public:
3133 /* Serialize various definitions. */
3134 void write_definition (tree decl);
3135 void mark_declaration (tree decl, bool do_defn);
3137 private:
3138 void mark_function_def (tree decl);
3139 void mark_var_def (tree decl);
3140 void mark_class_def (tree decl);
3141 void mark_enum_def (tree decl);
3142 void mark_class_member (tree decl, bool do_defn = true);
3143 void mark_binfos (tree type);
3145 private:
3146 void write_var_def (tree decl);
3147 void write_function_def (tree decl);
3148 void write_class_def (tree decl);
3149 void write_enum_def (tree decl);
3151 private:
3152 static void assert_definition (tree);
3154 public:
3155 static void instrument ();
3157 private:
3158 /* Tree instrumentation. */
3159 static unsigned tree_val_count;
3160 static unsigned decl_val_count;
3161 static unsigned back_ref_count;
3162 static unsigned null_count;
3164 } // anon namespace
3166 /* Instrumentation counters. */
3167 unsigned trees_out::tree_val_count;
3168 unsigned trees_out::decl_val_count;
3169 unsigned trees_out::back_ref_count;
3170 unsigned trees_out::null_count;
3172 trees_out::trees_out (allocator *mem, module_state *state, depset::hash &deps,
3173 unsigned section)
3174 :parent (mem), state (state), tree_map (500),
3175 dep_hash (&deps), ref_num (0), section (section)
3177 #if CHECKING_P
3178 importedness = 0;
3179 #endif
3182 trees_out::~trees_out ()
3186 /********************************************************************/
3187 /* Location. We're aware of the line-map concept and reproduce it
3188 here. Each imported module allocates a contiguous span of ordinary
3189 maps, and of macro maps. adhoc maps are serialized by contents,
3190 not pre-allocated. The scattered linemaps of a module are
3191 coalesced when writing. */
3194 /* I use half-open [first,second) ranges. */
3195 typedef std::pair<unsigned,unsigned> range_t;
3197 /* A range of locations. */
3198 typedef std::pair<location_t,location_t> loc_range_t;
3200 /* Spans of the line maps that are occupied by this TU. I.e. not
3201 within imports. Only extended when in an interface unit.
3202 Interval zero corresponds to the forced header linemap(s). This
3203 is a singleton object. */
3205 class loc_spans {
3206 public:
3207 /* An interval of line maps. The line maps here represent a contiguous
3208 non-imported range. */
3209 struct span {
3210 loc_range_t ordinary; /* Ordinary map location range. */
3211 loc_range_t macro; /* Macro map location range. */
3212 int ordinary_delta; /* Add to ordinary loc to get serialized loc. */
3213 int macro_delta; /* Likewise for macro loc. */
3216 private:
3217 vec<span> *spans;
3219 public:
3220 loc_spans ()
3221 /* Do not preallocate spans, as that causes
3222 --enable-detailed-mem-stats problems. */
3223 : spans (nullptr)
3226 ~loc_spans ()
3228 delete spans;
3231 public:
3232 span &operator[] (unsigned ix)
3234 return (*spans)[ix];
3236 unsigned length () const
3238 return spans->length ();
3241 public:
3242 bool init_p () const
3244 return spans != nullptr;
3246 /* Initializer. */
3247 void init (const line_maps *lmaps, const line_map_ordinary *map);
3249 /* Slightly skewed preprocessed files can cause us to miss an
3250 initialization in some places. Fallback initializer. */
3251 void maybe_init ()
3253 if (!init_p ())
3254 init (line_table, nullptr);
3257 public:
3258 enum {
3259 SPAN_RESERVED = 0, /* Reserved (fixed) locations. */
3260 SPAN_FIRST = 1, /* LWM of locations to stream */
3261 SPAN_MAIN = 2 /* Main file and onwards. */
3264 public:
3265 location_t main_start () const
3267 return (*spans)[SPAN_MAIN].ordinary.first;
3270 public:
3271 void open (location_t);
3272 void close ();
3274 public:
3275 /* Propagate imported linemaps to us, if needed. */
3276 bool maybe_propagate (module_state *import, location_t loc);
3278 public:
3279 const span *ordinary (location_t);
3280 const span *macro (location_t);
3283 static loc_spans spans;
3285 /* Information about ordinary locations we stream out. */
3286 struct ord_loc_info
3288 const line_map_ordinary *src; // line map we're based on
3289 unsigned offset; // offset to this line
3290 unsigned span; // number of locs we span
3291 unsigned remap; // serialization
3293 static int compare (const void *a_, const void *b_)
3295 auto *a = static_cast<const ord_loc_info *> (a_);
3296 auto *b = static_cast<const ord_loc_info *> (b_);
3298 if (a->src != b->src)
3299 return a->src < b->src ? -1 : +1;
3301 // Ensure no overlap
3302 gcc_checking_assert (a->offset + a->span <= b->offset
3303 || b->offset + b->span <= a->offset);
3305 gcc_checking_assert (a->offset != b->offset);
3306 return a->offset < b->offset ? -1 : +1;
3309 struct ord_loc_traits
3311 typedef ord_loc_info value_type;
3312 typedef value_type compare_type;
3314 static const bool empty_zero_p = false;
3316 static hashval_t hash (const value_type &v)
3318 auto h = pointer_hash<const line_map_ordinary>::hash (v.src);
3319 return iterative_hash_hashval_t (v.offset, h);
3321 static bool equal (const value_type &v, const compare_type p)
3323 return v.src == p.src && v.offset == p.offset;
3326 static void mark_empty (value_type &v)
3328 v.src = nullptr;
3330 static bool is_empty (value_type &v)
3332 return !v.src;
3335 static bool is_deleted (value_type &) { return false; }
3336 static void mark_deleted (value_type &) { gcc_unreachable (); }
3338 static void remove (value_type &) {}
3340 /* Table keyed by ord_loc_info, used for noting. */
3341 static hash_table<ord_loc_traits> *ord_loc_table;
3342 /* Sorted vector, used for writing. */
3343 static vec<ord_loc_info> *ord_loc_remap;
3345 /* Information about macro locations we stream out. */
3346 struct macro_loc_info
3348 const line_map_macro *src; // original expansion
3349 unsigned remap; // serialization
3351 static int compare (const void *a_, const void *b_)
3353 auto *a = static_cast<const macro_loc_info *> (a_);
3354 auto *b = static_cast<const macro_loc_info *> (b_);
3356 gcc_checking_assert (MAP_START_LOCATION (a->src)
3357 != MAP_START_LOCATION (b->src));
3358 if (MAP_START_LOCATION (a->src) < MAP_START_LOCATION (b->src))
3359 return -1;
3360 else
3361 return +1;
3364 struct macro_loc_traits
3366 typedef macro_loc_info value_type;
3367 typedef const line_map_macro *compare_type;
3369 static const bool empty_zero_p = false;
3371 static hashval_t hash (compare_type p)
3373 return pointer_hash<const line_map_macro>::hash (p);
3375 static hashval_t hash (const value_type &v)
3377 return hash (v.src);
3379 static bool equal (const value_type &v, const compare_type p)
3381 return v.src == p;
3384 static void mark_empty (value_type &v)
3386 v.src = nullptr;
3388 static bool is_empty (value_type &v)
3390 return !v.src;
3393 static bool is_deleted (value_type &) { return false; }
3394 static void mark_deleted (value_type &) { gcc_unreachable (); }
3396 static void remove (value_type &) {}
3398 /* Table keyed by line_map_macro, used for noting. */
3399 static hash_table<macro_loc_traits> *macro_loc_table;
3400 /* Sorted vector, used for writing. */
3401 static vec<macro_loc_info> *macro_loc_remap;
3403 /* Indirection to allow bsearching imports by ordinary location. */
3404 static vec<module_state *> *ool;
3406 /********************************************************************/
3407 /* Data needed by a module during the process of loading. */
3408 struct GTY(()) slurping {
3410 /* Remap import's module numbering to our numbering. Values are
3411 shifted by 1. Bit0 encodes if the import is direct. */
3412 vec<unsigned, va_heap, vl_embed> *
3413 GTY((skip)) remap; /* Module owner remapping. */
3415 elf_in *GTY((skip)) from; /* The elf loader. */
3417 /* This map is only for header imports themselves -- the global
3418 headers bitmap hold it for the current TU. */
3419 bitmap headers; /* Transitive set of direct imports, including
3420 self. Used for macro visibility and
3421 priority. */
3423 /* These objects point into the mmapped area, unless we're not doing
3424 that, or we got frozen or closed. In those cases they point to
3425 buffers we own. */
3426 bytes_in macro_defs; /* Macro definitions. */
3427 bytes_in macro_tbl; /* Macro table. */
3429 /* Location remapping. first->ordinary, second->macro. */
3430 range_t GTY((skip)) loc_deltas;
3432 unsigned current; /* Section currently being loaded. */
3433 unsigned remaining; /* Number of lazy sections yet to read. */
3434 unsigned lru; /* An LRU counter. */
3436 public:
3437 slurping (elf_in *);
3438 ~slurping ();
3440 public:
3441 /* Close the ELF file, if it's open. */
3442 void close ()
3444 if (from)
3446 from->end ();
3447 delete from;
3448 from = NULL;
3452 public:
3453 void release_macros ();
3455 public:
3456 void alloc_remap (unsigned size)
3458 gcc_assert (!remap);
3459 vec_safe_reserve (remap, size);
3460 for (unsigned ix = size; ix--;)
3461 remap->quick_push (0);
3463 unsigned remap_module (unsigned owner)
3465 if (owner < remap->length ())
3466 return (*remap)[owner] >> 1;
3467 return 0;
3470 public:
3471 /* GC allocation. But we must explicitly delete it. */
3472 static void *operator new (size_t x)
3474 return ggc_alloc_atomic (x);
3476 static void operator delete (void *p)
3478 ggc_free (p);
3482 slurping::slurping (elf_in *from)
3483 : remap (NULL), from (from),
3484 headers (BITMAP_GGC_ALLOC ()), macro_defs (), macro_tbl (),
3485 loc_deltas (0, 0),
3486 current (~0u), remaining (0), lru (0)
3490 slurping::~slurping ()
3492 vec_free (remap);
3493 remap = NULL;
3494 release_macros ();
3495 close ();
3498 void slurping::release_macros ()
3500 if (macro_defs.size)
3501 elf_in::release (from, macro_defs);
3502 if (macro_tbl.size)
3503 elf_in::release (from, macro_tbl);
3506 /* Flags for extensions that end up being streamed. */
3508 enum streamed_extensions {
3509 SE_OPENMP = 1 << 0,
3510 SE_BITS = 1
3513 /* Counter indices. */
3514 enum module_state_counts
3516 MSC_sec_lwm,
3517 MSC_sec_hwm,
3518 MSC_pendings,
3519 MSC_entities,
3520 MSC_namespaces,
3521 MSC_bindings,
3522 MSC_macros,
3523 MSC_inits,
3524 MSC_HWM
3527 /********************************************************************/
3528 struct module_state_config;
3530 /* Increasing levels of loadedness. */
3531 enum module_loadedness {
3532 ML_NONE, /* Not loaded. */
3533 ML_CONFIG, /* Config loaed. */
3534 ML_PREPROCESSOR, /* Preprocessor loaded. */
3535 ML_LANGUAGE, /* Language loaded. */
3538 /* Increasing levels of directness (toplevel) of import. */
3539 enum module_directness {
3540 MD_NONE, /* Not direct. */
3541 MD_PARTITION_DIRECT, /* Direct import of a partition. */
3542 MD_DIRECT, /* Direct import. */
3543 MD_PURVIEW_DIRECT, /* direct import in purview. */
3546 /* State of a particular module. */
3548 class GTY((chain_next ("%h.parent"), for_user)) module_state {
3549 public:
3550 /* We always import & export ourselves. */
3551 bitmap imports; /* Transitive modules we're importing. */
3552 bitmap exports; /* Subset of that, that we're exporting. */
3554 module_state *parent;
3555 tree name; /* Name of the module. */
3557 slurping *slurp; /* Data for loading. */
3559 const char *flatname; /* Flatname of module. */
3560 char *filename; /* CMI Filename */
3562 /* Indices into the entity_ary. */
3563 unsigned entity_lwm;
3564 unsigned entity_num;
3566 /* Location ranges for this module. adhoc-locs are decomposed, so
3567 don't have a range. */
3568 loc_range_t GTY((skip)) ordinary_locs;
3569 loc_range_t GTY((skip)) macro_locs; // [lwm,num)
3571 /* LOC is first set too the importing location. When initially
3572 loaded it refers to a module loc whose parent is the importing
3573 location. */
3574 location_t loc; /* Location referring to module itself. */
3575 unsigned crc; /* CRC we saw reading it in. */
3577 unsigned mod; /* Module owner number. */
3578 unsigned remap; /* Remapping during writing. */
3580 unsigned short subst; /* Mangle subst if !0. */
3582 /* How loaded this module is. */
3583 enum module_loadedness loadedness : 2;
3585 bool module_p : 1; /* /The/ module of this TU. */
3586 bool header_p : 1; /* Is a header unit. */
3587 bool interface_p : 1; /* An interface. */
3588 bool partition_p : 1; /* A partition. */
3590 /* How directly this module is imported. */
3591 enum module_directness directness : 2;
3593 bool exported_p : 1; /* directness != MD_NONE && exported. */
3594 bool cmi_noted_p : 1; /* We've told the user about the CMI, don't
3595 do it again */
3596 bool active_init_p : 1; /* This module's global initializer needs
3597 calling. */
3598 bool inform_cmi_p : 1; /* Inform of a read/write. */
3599 bool visited_p : 1; /* A walk-once flag. */
3600 /* Record extensions emitted or permitted. */
3601 unsigned extensions : SE_BITS;
3602 /* 14 bits used, 2 bits remain */
3604 public:
3605 module_state (tree name, module_state *, bool);
3606 ~module_state ();
3608 public:
3609 void release ()
3611 imports = exports = NULL;
3612 slurped ();
3614 void slurped ()
3616 delete slurp;
3617 slurp = NULL;
3619 elf_in *from () const
3621 return slurp->from;
3624 public:
3625 /* Kind of this module. */
3626 bool is_module () const
3628 return module_p;
3630 bool is_header () const
3632 return header_p;
3634 bool is_interface () const
3636 return interface_p;
3638 bool is_partition () const
3640 return partition_p;
3643 /* How this module is used in the current TU. */
3644 bool is_exported () const
3646 return exported_p;
3648 bool is_direct () const
3650 return directness >= MD_DIRECT;
3652 bool is_purview_direct () const
3654 return directness == MD_PURVIEW_DIRECT;
3656 bool is_partition_direct () const
3658 return directness == MD_PARTITION_DIRECT;
3661 public:
3662 /* Is this a real module? */
3663 bool has_location () const
3665 return loc != UNKNOWN_LOCATION;
3668 public:
3669 bool check_not_purview (location_t loc);
3671 public:
3672 void mangle (bool include_partition);
3674 public:
3675 void set_import (module_state const *, bool is_export);
3676 void announce (const char *) const;
3678 public:
3679 /* Read and write module. */
3680 void write_begin (elf_out *to, cpp_reader *,
3681 module_state_config &, unsigned &crc);
3682 void write_end (elf_out *to, cpp_reader *,
3683 module_state_config &, unsigned &crc);
3684 bool read_initial (cpp_reader *);
3685 bool read_preprocessor (bool);
3686 bool read_language (bool);
3688 public:
3689 /* Read a section. */
3690 bool load_section (unsigned snum, binding_slot *mslot);
3691 /* Lazily read a section. */
3692 bool lazy_load (unsigned index, binding_slot *mslot);
3694 public:
3695 /* Juggle a limited number of file numbers. */
3696 static void freeze_an_elf ();
3697 bool maybe_defrost ();
3699 public:
3700 void maybe_completed_reading ();
3701 bool check_read (bool outermost, bool ok);
3703 private:
3704 /* The README, for human consumption. */
3705 void write_readme (elf_out *to, cpp_reader *, const char *dialect);
3706 void write_env (elf_out *to);
3708 private:
3709 /* Import tables. */
3710 void write_imports (bytes_out &cfg, bool direct);
3711 unsigned read_imports (bytes_in &cfg, cpp_reader *, line_maps *maps);
3713 private:
3714 void write_imports (elf_out *to, unsigned *crc_ptr);
3715 bool read_imports (cpp_reader *, line_maps *);
3717 private:
3718 void write_partitions (elf_out *to, unsigned, unsigned *crc_ptr);
3719 bool read_partitions (unsigned);
3721 private:
3722 void write_config (elf_out *to, struct module_state_config &, unsigned crc);
3723 bool read_config (struct module_state_config &);
3724 static void write_counts (elf_out *to, unsigned [MSC_HWM], unsigned *crc_ptr);
3725 bool read_counts (unsigned *);
3727 public:
3728 void note_cmi_name ();
3730 private:
3731 static unsigned write_bindings (elf_out *to, vec<depset *> depsets,
3732 unsigned *crc_ptr);
3733 bool read_bindings (unsigned count, unsigned lwm, unsigned hwm);
3735 static void write_namespace (bytes_out &sec, depset *ns_dep);
3736 tree read_namespace (bytes_in &sec);
3738 void write_namespaces (elf_out *to, vec<depset *> spaces,
3739 unsigned, unsigned *crc_ptr);
3740 bool read_namespaces (unsigned);
3742 void intercluster_seed (trees_out &sec, unsigned index, depset *dep);
3743 unsigned write_cluster (elf_out *to, depset *depsets[], unsigned size,
3744 depset::hash &, unsigned *counts, unsigned *crc_ptr);
3745 bool read_cluster (unsigned snum);
3747 private:
3748 unsigned write_inits (elf_out *to, depset::hash &, unsigned *crc_ptr);
3749 bool read_inits (unsigned count);
3751 private:
3752 unsigned write_pendings (elf_out *to, vec<depset *> depsets,
3753 depset::hash &, unsigned *crc_ptr);
3754 bool read_pendings (unsigned count);
3756 private:
3757 void write_entities (elf_out *to, vec<depset *> depsets,
3758 unsigned count, unsigned *crc_ptr);
3759 bool read_entities (unsigned count, unsigned lwm, unsigned hwm);
3761 private:
3762 void write_init_maps ();
3763 range_t write_prepare_maps (module_state_config *, bool);
3764 bool read_prepare_maps (const module_state_config *);
3766 void write_ordinary_maps (elf_out *to, range_t &,
3767 bool, unsigned *crc_ptr);
3768 bool read_ordinary_maps (unsigned, unsigned);
3769 void write_macro_maps (elf_out *to, range_t &, unsigned *crc_ptr);
3770 bool read_macro_maps (unsigned);
3772 private:
3773 void write_define (bytes_out &, const cpp_macro *);
3774 cpp_macro *read_define (bytes_in &, cpp_reader *) const;
3775 vec<cpp_hashnode *> *prepare_macros (cpp_reader *);
3776 unsigned write_macros (elf_out *to, vec<cpp_hashnode *> *, unsigned *crc_ptr);
3777 bool read_macros ();
3778 void install_macros ();
3780 public:
3781 void import_macros ();
3783 public:
3784 static void undef_macro (cpp_reader *, location_t, cpp_hashnode *);
3785 static cpp_macro *deferred_macro (cpp_reader *, location_t, cpp_hashnode *);
3787 public:
3788 static bool note_location (location_t);
3789 static void write_location (bytes_out &, location_t);
3790 location_t read_location (bytes_in &) const;
3792 public:
3793 void set_flatname ();
3794 const char *get_flatname () const
3796 return flatname;
3798 location_t imported_from () const;
3800 public:
3801 void set_filename (const Cody::Packet &);
3802 bool do_import (cpp_reader *, bool outermost);
3805 /* Hash module state by name. This cannot be a member of
3806 module_state, because of GTY restrictions. We never delete from
3807 the hash table, but ggc_ptr_hash doesn't support that
3808 simplification. */
3810 struct module_state_hash : ggc_ptr_hash<module_state> {
3811 typedef std::pair<tree,uintptr_t> compare_type; /* {name,parent} */
3813 static inline hashval_t hash (const value_type m);
3814 static inline hashval_t hash (const compare_type &n);
3815 static inline bool equal (const value_type existing,
3816 const compare_type &candidate);
3819 module_state::module_state (tree name, module_state *parent, bool partition)
3820 : imports (BITMAP_GGC_ALLOC ()), exports (BITMAP_GGC_ALLOC ()),
3821 parent (parent), name (name), slurp (NULL),
3822 flatname (NULL), filename (NULL),
3823 entity_lwm (~0u >> 1), entity_num (0),
3824 ordinary_locs (0, 0), macro_locs (0, 0),
3825 loc (UNKNOWN_LOCATION),
3826 crc (0), mod (MODULE_UNKNOWN), remap (0), subst (0)
3828 loadedness = ML_NONE;
3830 module_p = header_p = interface_p = partition_p = false;
3832 directness = MD_NONE;
3833 exported_p = false;
3835 cmi_noted_p = false;
3836 active_init_p = false;
3838 partition_p = partition;
3840 inform_cmi_p = false;
3841 visited_p = false;
3843 extensions = 0;
3844 if (name && TREE_CODE (name) == STRING_CST)
3846 header_p = true;
3848 const char *string = TREE_STRING_POINTER (name);
3849 gcc_checking_assert (string[0] == '.'
3850 ? IS_DIR_SEPARATOR (string[1])
3851 : IS_ABSOLUTE_PATH (string));
3854 gcc_checking_assert (!(parent && header_p));
3857 module_state::~module_state ()
3859 release ();
3862 /* Hash module state. */
3863 static hashval_t
3864 module_name_hash (const_tree name)
3866 if (TREE_CODE (name) == STRING_CST)
3867 return htab_hash_string (TREE_STRING_POINTER (name));
3868 else
3869 return IDENTIFIER_HASH_VALUE (name);
3872 hashval_t
3873 module_state_hash::hash (const value_type m)
3875 hashval_t ph = pointer_hash<void>::hash
3876 (reinterpret_cast<void *> (reinterpret_cast<uintptr_t> (m->parent)
3877 | m->is_partition ()));
3878 hashval_t nh = module_name_hash (m->name);
3879 return iterative_hash_hashval_t (ph, nh);
3882 /* Hash a name. */
3883 hashval_t
3884 module_state_hash::hash (const compare_type &c)
3886 hashval_t ph = pointer_hash<void>::hash (reinterpret_cast<void *> (c.second));
3887 hashval_t nh = module_name_hash (c.first);
3889 return iterative_hash_hashval_t (ph, nh);
3892 bool
3893 module_state_hash::equal (const value_type existing,
3894 const compare_type &candidate)
3896 uintptr_t ep = (reinterpret_cast<uintptr_t> (existing->parent)
3897 | existing->is_partition ());
3898 if (ep != candidate.second)
3899 return false;
3901 /* Identifier comparison is by pointer. If the string_csts happen
3902 to be the same object, then they're equal too. */
3903 if (existing->name == candidate.first)
3904 return true;
3906 /* If neither are string csts, they can't be equal. */
3907 if (TREE_CODE (candidate.first) != STRING_CST
3908 || TREE_CODE (existing->name) != STRING_CST)
3909 return false;
3911 /* String equality. */
3912 if (TREE_STRING_LENGTH (existing->name)
3913 == TREE_STRING_LENGTH (candidate.first)
3914 && !memcmp (TREE_STRING_POINTER (existing->name),
3915 TREE_STRING_POINTER (candidate.first),
3916 TREE_STRING_LENGTH (existing->name)))
3917 return true;
3919 return false;
3922 /********************************************************************/
3923 /* Global state */
3925 /* Mapper name. */
3926 static const char *module_mapper_name;
3928 /* Deferred import queue (FIFO). */
3929 static vec<module_state *, va_heap, vl_embed> *pending_imports;
3931 /* CMI repository path and workspace. */
3932 static char *cmi_repo;
3933 static size_t cmi_repo_length;
3934 static char *cmi_path;
3935 static size_t cmi_path_alloc;
3937 /* Count of available and loaded clusters. */
3938 static unsigned available_clusters;
3939 static unsigned loaded_clusters;
3941 /* What the current TU is. */
3942 unsigned module_kind;
3944 /* Global trees. */
3945 static const std::pair<tree *, unsigned> global_tree_arys[] =
3947 std::pair<tree *, unsigned> (sizetype_tab, stk_type_kind_last),
3948 std::pair<tree *, unsigned> (integer_types, itk_none),
3949 std::pair<tree *, unsigned> (global_trees, TI_MODULE_HWM),
3950 std::pair<tree *, unsigned> (c_global_trees, CTI_MODULE_HWM),
3951 std::pair<tree *, unsigned> (cp_global_trees, CPTI_MODULE_HWM),
3952 std::pair<tree *, unsigned> (NULL, 0)
3954 static GTY(()) vec<tree, va_gc> *fixed_trees;
3955 static unsigned global_crc;
3957 /* Lazy loading can open many files concurrently, there are
3958 per-process limits on that. We pay attention to the process limit,
3959 and attempt to increase it when we run out. Otherwise we use an
3960 LRU scheme to figure out who to flush. Note that if the import
3961 graph /depth/ exceeds lazy_limit, we'll exceed the limit. */
3962 static unsigned lazy_lru; /* LRU counter. */
3963 static unsigned lazy_open; /* Number of open modules */
3964 static unsigned lazy_limit; /* Current limit of open modules. */
3965 static unsigned lazy_hard_limit; /* Hard limit on open modules. */
3966 /* Account for source, assembler and dump files & directory searches.
3967 We don't keep the source file's open, so we don't have to account
3968 for #include depth. I think dump files are opened and closed per
3969 pass, but ICBW. */
3970 #define LAZY_HEADROOM 15 /* File descriptor headroom. */
3972 /* Vector of module state. Indexed by OWNER. Has at least 2 slots. */
3973 static GTY(()) vec<module_state *, va_gc> *modules;
3975 /* Hash of module state, findable by {name, parent}. */
3976 static GTY(()) hash_table<module_state_hash> *modules_hash;
3978 /* Map of imported entities. We map DECL_UID to index of entity
3979 vector. */
3980 typedef hash_map<unsigned/*UID*/, unsigned/*index*/,
3981 simple_hashmap_traits<int_hash<unsigned,0>, unsigned>
3982 > entity_map_t;
3983 static entity_map_t *entity_map;
3984 /* Doesn't need GTYing, because any tree referenced here is also
3985 findable by, symbol table, specialization table, return type of
3986 reachable function. */
3987 static vec<binding_slot, va_heap, vl_embed> *entity_ary;
3989 /* Members entities of imported classes that are defined in this TU.
3990 These are where the entity's context is not from the current TU.
3991 We need to emit the definition (but not the enclosing class).
3993 We could find these by walking ALL the imported classes that we
3994 could provide a member definition. But that's expensive,
3995 especially when you consider lazy implicit member declarations,
3996 which could be ANY imported class. */
3997 static GTY(()) vec<tree, va_gc> *class_members;
3999 /* The same problem exists for class template partial
4000 specializations. Now that we have constraints, the invariant of
4001 expecting them in the instantiation table no longer holds. One of
4002 the constrained partial specializations will be there, but the
4003 others not so much. It's not even an unconstrained partial
4004 spacialization in the table :( so any partial template declaration
4005 is added to this list too. */
4006 static GTY(()) vec<tree, va_gc> *partial_specializations;
4008 /********************************************************************/
4010 /* Our module mapper (created lazily). */
4011 module_client *mapper;
4013 static module_client *make_mapper (location_t loc, class mkdeps *deps);
4014 inline module_client *get_mapper (location_t loc, class mkdeps *deps)
4016 auto *res = mapper;
4017 if (!res)
4018 res = make_mapper (loc, deps);
4019 return res;
4022 /********************************************************************/
4023 static tree
4024 get_clone_target (tree decl)
4026 tree target;
4028 if (TREE_CODE (decl) == TEMPLATE_DECL)
4030 tree res_orig = DECL_CLONED_FUNCTION (DECL_TEMPLATE_RESULT (decl));
4032 target = DECL_TI_TEMPLATE (res_orig);
4034 else
4035 target = DECL_CLONED_FUNCTION (decl);
4037 gcc_checking_assert (DECL_MAYBE_IN_CHARGE_CDTOR_P (target));
4039 return target;
4042 /* Like FOR_EACH_CLONE, but will walk cloned templates. */
4043 #define FOR_EVERY_CLONE(CLONE, FN) \
4044 if (!DECL_MAYBE_IN_CHARGE_CDTOR_P (FN)); \
4045 else \
4046 for (CLONE = DECL_CHAIN (FN); \
4047 CLONE && DECL_CLONED_FUNCTION_P (CLONE); \
4048 CLONE = DECL_CHAIN (CLONE))
4050 /* It'd be nice if USE_TEMPLATE was a field of template_info
4051 (a) it'd solve the enum case dealt with below,
4052 (b) both class templates and decl templates would store this in the
4053 same place
4054 (c) this function wouldn't need the by-ref arg, which is annoying. */
4056 static tree
4057 node_template_info (tree decl, int &use)
4059 tree ti = NULL_TREE;
4060 int use_tpl = -1;
4061 if (DECL_IMPLICIT_TYPEDEF_P (decl))
4063 tree type = TREE_TYPE (decl);
4065 ti = TYPE_TEMPLATE_INFO (type);
4066 if (ti)
4068 if (TYPE_LANG_SPECIFIC (type))
4069 use_tpl = CLASSTYPE_USE_TEMPLATE (type);
4070 else
4072 /* An enum, where we don't explicitly encode use_tpl.
4073 If the containing context (a type or a function), is
4074 an ({im,ex}plicit) instantiation, then this is too.
4075 If it's a partial or explicit specialization, then
4076 this is not!. */
4077 tree ctx = CP_DECL_CONTEXT (decl);
4078 if (TYPE_P (ctx))
4079 ctx = TYPE_NAME (ctx);
4080 node_template_info (ctx, use);
4081 use_tpl = use != 2 ? use : 0;
4085 else if (DECL_LANG_SPECIFIC (decl)
4086 && (VAR_P (decl)
4087 || TREE_CODE (decl) == TYPE_DECL
4088 || TREE_CODE (decl) == FUNCTION_DECL
4089 || TREE_CODE (decl) == FIELD_DECL
4090 || TREE_CODE (decl) == CONCEPT_DECL
4091 || TREE_CODE (decl) == TEMPLATE_DECL))
4093 use_tpl = DECL_USE_TEMPLATE (decl);
4094 ti = DECL_TEMPLATE_INFO (decl);
4097 use = use_tpl;
4098 return ti;
4101 /* Find the index in entity_ary for an imported DECL. It should
4102 always be there, but bugs can cause it to be missing, and that can
4103 crash the crash reporting -- let's not do that! When streaming
4104 out we place entities from this module there too -- with negated
4105 indices. */
4107 static unsigned
4108 import_entity_index (tree decl, bool null_ok = false)
4110 if (unsigned *slot = entity_map->get (DECL_UID (decl)))
4111 return *slot;
4113 gcc_checking_assert (null_ok);
4114 return ~(~0u >> 1);
4117 /* Find the module for an imported entity at INDEX in the entity ary.
4118 There must be one. */
4120 static module_state *
4121 import_entity_module (unsigned index)
4123 if (index > ~(~0u >> 1))
4124 /* This is an index for an exported entity. */
4125 return (*modules)[0];
4127 /* Do not include the current TU (not an off-by-one error). */
4128 unsigned pos = 1;
4129 unsigned len = modules->length () - pos;
4130 while (len)
4132 unsigned half = len / 2;
4133 module_state *probe = (*modules)[pos + half];
4134 if (index < probe->entity_lwm)
4135 len = half;
4136 else if (index < probe->entity_lwm + probe->entity_num)
4137 return probe;
4138 else
4140 pos += half + 1;
4141 len = len - (half + 1);
4144 gcc_unreachable ();
4148 /********************************************************************/
4149 /* A dumping machinery. */
4151 class dumper {
4152 public:
4153 enum {
4154 LOCATION = TDF_LINENO, /* -lineno:Source location streaming. */
4155 DEPEND = TDF_GRAPH, /* -graph:Dependency graph construction. */
4156 CLUSTER = TDF_BLOCKS, /* -blocks:Clusters. */
4157 TREE = TDF_UID, /* -uid:Tree streaming. */
4158 MERGE = TDF_ALIAS, /* -alias:Mergeable Entities. */
4159 ELF = TDF_ASMNAME, /* -asmname:Elf data. */
4160 MACRO = TDF_VOPS /* -vops:Macros. */
4163 private:
4164 struct impl {
4165 typedef vec<module_state *, va_heap, vl_embed> stack_t;
4167 FILE *stream; /* Dump stream. */
4168 unsigned indent; /* Local indentation. */
4169 bool bol; /* Beginning of line. */
4170 stack_t stack; /* Trailing array of module_state. */
4172 bool nested_name (tree); /* Dump a name following DECL_CONTEXT. */
4175 public:
4176 /* The dumper. */
4177 impl *dumps;
4178 dump_flags_t flags;
4180 public:
4181 /* Push/pop module state dumping. */
4182 unsigned push (module_state *);
4183 void pop (unsigned);
4185 public:
4186 /* Change local indentation. */
4187 void indent ()
4189 if (dumps)
4190 dumps->indent++;
4192 void outdent ()
4194 if (dumps)
4196 gcc_checking_assert (dumps->indent);
4197 dumps->indent--;
4201 public:
4202 /* Is dump enabled?. */
4203 bool operator () (int mask = 0)
4205 if (!dumps || !dumps->stream)
4206 return false;
4207 if (mask && !(mask & flags))
4208 return false;
4209 return true;
4211 /* Dump some information. */
4212 bool operator () (const char *, ...);
4215 /* The dumper. */
4216 static dumper dump = {0, dump_flags_t (0)};
4218 /* Push to dumping M. Return previous indentation level. */
4220 unsigned
4221 dumper::push (module_state *m)
4223 FILE *stream = NULL;
4224 if (!dumps || !dumps->stack.length ())
4226 stream = dump_begin (module_dump_id, &flags);
4227 if (!stream)
4228 return 0;
4231 if (!dumps || !dumps->stack.space (1))
4233 /* Create or extend the dump implementor. */
4234 unsigned current = dumps ? dumps->stack.length () : 0;
4235 unsigned count = current ? current * 2 : EXPERIMENT (1, 20);
4236 size_t alloc = (offsetof (impl, stack)
4237 + impl::stack_t::embedded_size (count));
4238 dumps = XRESIZEVAR (impl, dumps, alloc);
4239 dumps->stack.embedded_init (count, current);
4241 if (stream)
4242 dumps->stream = stream;
4244 unsigned n = dumps->indent;
4245 dumps->indent = 0;
4246 dumps->bol = true;
4247 dumps->stack.quick_push (m);
4248 if (m)
4250 module_state *from = NULL;
4252 if (dumps->stack.length () > 1)
4253 from = dumps->stack[dumps->stack.length () - 2];
4254 else
4255 dump ("");
4256 dump (from ? "Starting module %M (from %M)"
4257 : "Starting module %M", m, from);
4260 return n;
4263 /* Pop from dumping. Restore indentation to N. */
4265 void dumper::pop (unsigned n)
4267 if (!dumps)
4268 return;
4270 gcc_checking_assert (dump () && !dumps->indent);
4271 if (module_state *m = dumps->stack[dumps->stack.length () - 1])
4273 module_state *from = (dumps->stack.length () > 1
4274 ? dumps->stack[dumps->stack.length () - 2] : NULL);
4275 dump (from ? "Finishing module %M (returning to %M)"
4276 : "Finishing module %M", m, from);
4278 dumps->stack.pop ();
4279 dumps->indent = n;
4280 if (!dumps->stack.length ())
4282 dump_end (module_dump_id, dumps->stream);
4283 dumps->stream = NULL;
4287 /* Dump a nested name for arbitrary tree T. Sometimes it won't have a
4288 name. */
4290 bool
4291 dumper::impl::nested_name (tree t)
4293 tree ti = NULL_TREE;
4294 int origin = -1;
4295 tree name = NULL_TREE;
4297 if (t && TREE_CODE (t) == TREE_BINFO)
4298 t = BINFO_TYPE (t);
4300 if (t && TYPE_P (t))
4301 t = TYPE_NAME (t);
4303 if (t && DECL_P (t))
4305 if (t == global_namespace || DECL_TEMPLATE_PARM_P (t))
4307 else if (tree ctx = DECL_CONTEXT (t))
4308 if (TREE_CODE (ctx) == TRANSLATION_UNIT_DECL
4309 || nested_name (ctx))
4310 fputs ("::", stream);
4312 int use_tpl;
4313 ti = node_template_info (t, use_tpl);
4314 if (ti && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL
4315 && (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == t))
4316 t = TI_TEMPLATE (ti);
4317 tree not_tmpl = t;
4318 if (TREE_CODE (t) == TEMPLATE_DECL)
4320 fputs ("template ", stream);
4321 not_tmpl = DECL_TEMPLATE_RESULT (t);
4324 if (not_tmpl
4325 && DECL_P (not_tmpl)
4326 && DECL_LANG_SPECIFIC (not_tmpl)
4327 && DECL_MODULE_IMPORT_P (not_tmpl))
4329 /* We need to be careful here, so as to not explode on
4330 inconsistent data -- we're probably debugging, because
4331 Something Is Wrong. */
4332 unsigned index = import_entity_index (t, true);
4333 if (!(index & ~(~0u >> 1)))
4334 origin = import_entity_module (index)->mod;
4335 else if (index > ~(~0u >> 1))
4336 /* An imported partition member that we're emitting. */
4337 origin = 0;
4338 else
4339 origin = -2;
4342 name = DECL_NAME (t) ? DECL_NAME (t)
4343 : HAS_DECL_ASSEMBLER_NAME_P (t) ? DECL_ASSEMBLER_NAME_RAW (t)
4344 : NULL_TREE;
4346 else
4347 name = t;
4349 if (name)
4350 switch (TREE_CODE (name))
4352 default:
4353 fputs ("#unnamed#", stream);
4354 break;
4356 case IDENTIFIER_NODE:
4357 fwrite (IDENTIFIER_POINTER (name), 1, IDENTIFIER_LENGTH (name), stream);
4358 break;
4360 case INTEGER_CST:
4361 print_hex (wi::to_wide (name), stream);
4362 break;
4364 case STRING_CST:
4365 /* If TREE_TYPE is NULL, this is a raw string. */
4366 fwrite (TREE_STRING_POINTER (name), 1,
4367 TREE_STRING_LENGTH (name) - (TREE_TYPE (name) != NULL_TREE),
4368 stream);
4369 break;
4371 else
4372 fputs ("#null#", stream);
4374 if (origin >= 0)
4376 const module_state *module = (*modules)[origin];
4377 fprintf (stream, "@%s:%d", !module ? "" : !module->name ? "(unnamed)"
4378 : module->get_flatname (), origin);
4380 else if (origin == -2)
4381 fprintf (stream, "@???");
4383 if (ti)
4385 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (ti));
4386 fputs ("<", stream);
4387 if (args)
4388 for (int ix = 0; ix != TREE_VEC_LENGTH (args); ix++)
4390 if (ix)
4391 fputs (",", stream);
4392 nested_name (TREE_VEC_ELT (args, ix));
4394 fputs (">", stream);
4397 return true;
4400 /* Formatted dumping. FORMAT begins with '+' do not emit a trailing
4401 new line. (Normally it is appended.)
4402 Escapes:
4403 %C - tree_code
4404 %I - identifier
4405 %M - module_state
4406 %N - name -- DECL_NAME
4407 %P - context:name pair
4408 %R - unsigned:unsigned ratio
4409 %S - symbol -- DECL_ASSEMBLER_NAME
4410 %U - long unsigned
4411 %V - version
4412 --- the following are printf-like, but without its flexibility
4413 %d - decimal int
4414 %p - pointer
4415 %s - string
4416 %u - unsigned int
4417 %x - hex int
4419 We do not implement the printf modifiers. */
4421 bool
4422 dumper::operator () (const char *format, ...)
4424 if (!(*this) ())
4425 return false;
4427 bool no_nl = format[0] == '+';
4428 format += no_nl;
4430 if (dumps->bol)
4432 /* Module import indent. */
4433 if (unsigned depth = dumps->stack.length () - 1)
4435 const char *prefix = ">>>>";
4436 fprintf (dumps->stream, (depth <= strlen (prefix)
4437 ? &prefix[strlen (prefix) - depth]
4438 : ">.%d.>"), depth);
4441 /* Local indent. */
4442 if (unsigned indent = dumps->indent)
4444 const char *prefix = " ";
4445 fprintf (dumps->stream, (indent <= strlen (prefix)
4446 ? &prefix[strlen (prefix) - indent]
4447 : " .%d. "), indent);
4449 dumps->bol = false;
4452 va_list args;
4453 va_start (args, format);
4454 while (const char *esc = strchr (format, '%'))
4456 fwrite (format, 1, (size_t)(esc - format), dumps->stream);
4457 format = ++esc;
4458 switch (*format++)
4460 default:
4461 gcc_unreachable ();
4463 case '%':
4464 fputc ('%', dumps->stream);
4465 break;
4467 case 'C': /* Code */
4469 tree_code code = (tree_code)va_arg (args, unsigned);
4470 fputs (get_tree_code_name (code), dumps->stream);
4472 break;
4474 case 'I': /* Identifier. */
4476 tree t = va_arg (args, tree);
4477 dumps->nested_name (t);
4479 break;
4481 case 'M': /* Module. */
4483 const char *str = "(none)";
4484 if (module_state *m = va_arg (args, module_state *))
4486 if (!m->has_location ())
4487 str = "(detached)";
4488 else
4489 str = m->get_flatname ();
4491 fputs (str, dumps->stream);
4493 break;
4495 case 'N': /* Name. */
4497 tree t = va_arg (args, tree);
4498 while (t && TREE_CODE (t) == OVERLOAD)
4499 t = OVL_FUNCTION (t);
4500 fputc ('\'', dumps->stream);
4501 dumps->nested_name (t);
4502 fputc ('\'', dumps->stream);
4504 break;
4506 case 'P': /* Pair. */
4508 tree ctx = va_arg (args, tree);
4509 tree name = va_arg (args, tree);
4510 fputc ('\'', dumps->stream);
4511 dumps->nested_name (ctx);
4512 if (ctx && ctx != global_namespace)
4513 fputs ("::", dumps->stream);
4514 dumps->nested_name (name);
4515 fputc ('\'', dumps->stream);
4517 break;
4519 case 'R': /* Ratio */
4521 unsigned a = va_arg (args, unsigned);
4522 unsigned b = va_arg (args, unsigned);
4523 fprintf (dumps->stream, "%.1f", (float) a / (b + !b));
4525 break;
4527 case 'S': /* Symbol name */
4529 tree t = va_arg (args, tree);
4530 if (t && TYPE_P (t))
4531 t = TYPE_NAME (t);
4532 if (t && HAS_DECL_ASSEMBLER_NAME_P (t)
4533 && DECL_ASSEMBLER_NAME_SET_P (t))
4535 fputc ('(', dumps->stream);
4536 fputs (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (t)),
4537 dumps->stream);
4538 fputc (')', dumps->stream);
4541 break;
4543 case 'U': /* long unsigned. */
4545 unsigned long u = va_arg (args, unsigned long);
4546 fprintf (dumps->stream, "%lu", u);
4548 break;
4550 case 'V': /* Verson. */
4552 unsigned v = va_arg (args, unsigned);
4553 verstr_t string;
4555 version2string (v, string);
4556 fputs (string, dumps->stream);
4558 break;
4560 case 'c': /* Character. */
4562 int c = va_arg (args, int);
4563 fputc (c, dumps->stream);
4565 break;
4567 case 'd': /* Decimal Int. */
4569 int d = va_arg (args, int);
4570 fprintf (dumps->stream, "%d", d);
4572 break;
4574 case 'p': /* Pointer. */
4576 void *p = va_arg (args, void *);
4577 fprintf (dumps->stream, "%p", p);
4579 break;
4581 case 's': /* String. */
4583 const char *s = va_arg (args, char *);
4584 gcc_checking_assert (s);
4585 fputs (s, dumps->stream);
4587 break;
4589 case 'u': /* Unsigned. */
4591 unsigned u = va_arg (args, unsigned);
4592 fprintf (dumps->stream, "%u", u);
4594 break;
4596 case 'x': /* Hex. */
4598 unsigned x = va_arg (args, unsigned);
4599 fprintf (dumps->stream, "%x", x);
4601 break;
4604 fputs (format, dumps->stream);
4605 va_end (args);
4606 if (!no_nl)
4608 dumps->bol = true;
4609 fputc ('\n', dumps->stream);
4611 return true;
4614 struct note_def_cache_hasher : ggc_cache_ptr_hash<tree_node>
4616 static int keep_cache_entry (tree t)
4618 if (!CHECKING_P)
4619 /* GTY is unfortunately not clever enough to conditionalize
4620 this. */
4621 gcc_unreachable ();
4623 if (ggc_marked_p (t))
4624 return -1;
4626 unsigned n = dump.push (NULL);
4627 /* This might or might not be an error. We should note its
4628 dropping whichever. */
4629 dump () && dump ("Dropping %N from note_defs table", t);
4630 dump.pop (n);
4632 return 0;
4636 /* We should stream each definition at most once.
4637 This needs to be a cache because there are cases where a definition
4638 ends up being not retained, and we need to drop those so we don't
4639 get confused if memory is reallocated. */
4640 typedef hash_table<note_def_cache_hasher> note_defs_table_t;
4641 static GTY((cache)) note_defs_table_t *note_defs;
4643 void
4644 trees_in::assert_definition (tree decl ATTRIBUTE_UNUSED,
4645 bool installing ATTRIBUTE_UNUSED)
4647 #if CHECKING_P
4648 tree *slot = note_defs->find_slot (decl, installing ? INSERT : NO_INSERT);
4649 tree not_tmpl = STRIP_TEMPLATE (decl);
4650 if (installing)
4652 /* We must be inserting for the first time. */
4653 gcc_assert (!*slot);
4654 *slot = decl;
4656 else
4657 /* If this is not the mergeable entity, it should not be in the
4658 table. If it is a non-global-module mergeable entity, it
4659 should be in the table. Global module entities could have been
4660 defined textually in the current TU and so might or might not
4661 be present. */
4662 gcc_assert (!is_duplicate (decl)
4663 ? !slot
4664 : (slot
4665 || !DECL_LANG_SPECIFIC (not_tmpl)
4666 || !DECL_MODULE_PURVIEW_P (not_tmpl)
4667 || (!DECL_MODULE_IMPORT_P (not_tmpl)
4668 && header_module_p ())));
4670 if (not_tmpl != decl)
4671 gcc_assert (!note_defs->find_slot (not_tmpl, NO_INSERT));
4672 #endif
4675 void
4676 trees_out::assert_definition (tree decl ATTRIBUTE_UNUSED)
4678 #if CHECKING_P
4679 tree *slot = note_defs->find_slot (decl, INSERT);
4680 gcc_assert (!*slot);
4681 *slot = decl;
4682 if (TREE_CODE (decl) == TEMPLATE_DECL)
4683 gcc_assert (!note_defs->find_slot (DECL_TEMPLATE_RESULT (decl), NO_INSERT));
4684 #endif
4687 /********************************************************************/
4688 static bool
4689 noisy_p ()
4691 if (quiet_flag)
4692 return false;
4694 pp_needs_newline (global_dc->printer) = true;
4695 diagnostic_set_last_function (global_dc, (diagnostic_info *) NULL);
4697 return true;
4700 /* Set the cmi repo. Strip trailing '/', '.' becomes NULL. */
4702 static void
4703 set_cmi_repo (const char *r)
4705 XDELETEVEC (cmi_repo);
4706 XDELETEVEC (cmi_path);
4707 cmi_path_alloc = 0;
4709 cmi_repo = NULL;
4710 cmi_repo_length = 0;
4712 if (!r || !r[0])
4713 return;
4715 size_t len = strlen (r);
4716 cmi_repo = XNEWVEC (char, len + 1);
4717 memcpy (cmi_repo, r, len + 1);
4719 if (len > 1 && IS_DIR_SEPARATOR (cmi_repo[len-1]))
4720 len--;
4721 if (len == 1 && cmi_repo[0] == '.')
4722 len--;
4723 cmi_repo[len] = 0;
4724 cmi_repo_length = len;
4727 /* TO is a repo-relative name. Provide one that we may use from where
4728 we are. */
4730 static const char *
4731 maybe_add_cmi_prefix (const char *to, size_t *len_p = NULL)
4733 size_t len = len_p || cmi_repo_length ? strlen (to) : 0;
4735 if (cmi_repo_length && !IS_ABSOLUTE_PATH (to))
4737 if (cmi_path_alloc < cmi_repo_length + len + 2)
4739 XDELETEVEC (cmi_path);
4740 cmi_path_alloc = cmi_repo_length + len * 2 + 2;
4741 cmi_path = XNEWVEC (char, cmi_path_alloc);
4743 memcpy (cmi_path, cmi_repo, cmi_repo_length);
4744 cmi_path[cmi_repo_length] = DIR_SEPARATOR;
4747 memcpy (&cmi_path[cmi_repo_length + 1], to, len + 1);
4748 len += cmi_repo_length + 1;
4749 to = cmi_path;
4752 if (len_p)
4753 *len_p = len;
4755 return to;
4758 /* Try and create the directories of PATH. */
4760 static void
4761 create_dirs (char *path)
4763 /* Try and create the missing directories. */
4764 for (char *base = path; *base; base++)
4765 if (IS_DIR_SEPARATOR (*base))
4767 char sep = *base;
4768 *base = 0;
4769 int failed = mkdir (path, S_IRWXU | S_IRWXG | S_IRWXO);
4770 dump () && dump ("Mkdir ('%s') errno:=%u", path, failed ? errno : 0);
4771 *base = sep;
4772 if (failed
4773 /* Maybe racing with another creator (of a *different*
4774 module). */
4775 && errno != EEXIST)
4776 break;
4780 /* Given a CLASSTYPE_DECL_LIST VALUE get the template friend decl,
4781 if that's what this is. */
4783 static tree
4784 friend_from_decl_list (tree frnd)
4786 tree res = frnd;
4788 if (TREE_CODE (frnd) != TEMPLATE_DECL)
4790 tree tmpl = NULL_TREE;
4791 if (TYPE_P (frnd))
4793 res = TYPE_NAME (frnd);
4794 if (CLASS_TYPE_P (frnd)
4795 && CLASSTYPE_TEMPLATE_INFO (frnd))
4796 tmpl = CLASSTYPE_TI_TEMPLATE (frnd);
4798 else if (DECL_TEMPLATE_INFO (frnd))
4800 tmpl = DECL_TI_TEMPLATE (frnd);
4801 if (TREE_CODE (tmpl) != TEMPLATE_DECL)
4802 tmpl = NULL_TREE;
4805 if (tmpl && DECL_TEMPLATE_RESULT (tmpl) == res)
4806 res = tmpl;
4809 return res;
4812 static tree
4813 find_enum_member (tree ctx, tree name)
4815 for (tree values = TYPE_VALUES (ctx);
4816 values; values = TREE_CHAIN (values))
4817 if (DECL_NAME (TREE_VALUE (values)) == name)
4818 return TREE_VALUE (values);
4820 return NULL_TREE;
4823 /********************************************************************/
4824 /* Instrumentation gathered writing bytes. */
4826 void
4827 bytes_out::instrument ()
4829 dump ("Wrote %u bytes in %u blocks", lengths[3], spans[3]);
4830 dump ("Wrote %u bits in %u bytes", lengths[0] + lengths[1], lengths[2]);
4831 for (unsigned ix = 0; ix < 2; ix++)
4832 dump (" %u %s spans of %R bits", spans[ix],
4833 ix ? "one" : "zero", lengths[ix], spans[ix]);
4834 dump (" %u blocks with %R bits padding", spans[2],
4835 lengths[2] * 8 - (lengths[0] + lengths[1]), spans[2]);
4838 /* Instrumentation gathered writing trees. */
4839 void
4840 trees_out::instrument ()
4842 if (dump (""))
4844 bytes_out::instrument ();
4845 dump ("Wrote:");
4846 dump (" %u decl trees", decl_val_count);
4847 dump (" %u other trees", tree_val_count);
4848 dump (" %u back references", back_ref_count);
4849 dump (" %u null trees", null_count);
4853 /* Setup and teardown for a tree walk. */
4855 void
4856 trees_out::begin ()
4858 gcc_assert (!streaming_p () || !tree_map.elements ());
4860 mark_trees ();
4861 if (streaming_p ())
4862 parent::begin ();
4865 unsigned
4866 trees_out::end (elf_out *sink, unsigned name, unsigned *crc_ptr)
4868 gcc_checking_assert (streaming_p ());
4870 unmark_trees ();
4871 return parent::end (sink, name, crc_ptr);
4874 void
4875 trees_out::end ()
4877 gcc_assert (!streaming_p ());
4879 unmark_trees ();
4880 /* Do not parent::end -- we weren't streaming. */
4883 void
4884 trees_out::mark_trees ()
4886 if (size_t size = tree_map.elements ())
4888 /* This isn't our first rodeo, destroy and recreate the
4889 tree_map. I'm a bad bad man. Use the previous size as a
4890 guess for the next one (so not all bad). */
4891 tree_map.~ptr_int_hash_map ();
4892 new (&tree_map) ptr_int_hash_map (size);
4895 /* Install the fixed trees, with +ve references. */
4896 unsigned limit = fixed_trees->length ();
4897 for (unsigned ix = 0; ix != limit; ix++)
4899 tree val = (*fixed_trees)[ix];
4900 bool existed = tree_map.put (val, ix + tag_fixed);
4901 gcc_checking_assert (!TREE_VISITED (val) && !existed);
4902 TREE_VISITED (val) = true;
4905 ref_num = 0;
4908 /* Unmark the trees we encountered */
4910 void
4911 trees_out::unmark_trees ()
4913 ptr_int_hash_map::iterator end (tree_map.end ());
4914 for (ptr_int_hash_map::iterator iter (tree_map.begin ()); iter != end; ++iter)
4916 tree node = reinterpret_cast<tree> ((*iter).first);
4917 int ref = (*iter).second;
4918 /* We should have visited the node, and converted its mergeable
4919 reference to a regular reference. */
4920 gcc_checking_assert (TREE_VISITED (node)
4921 && (ref <= tag_backref || ref >= tag_fixed));
4922 TREE_VISITED (node) = false;
4926 /* Mark DECL for by-value walking. We do this by inserting it into
4927 the tree map with a reference of zero. May be called multiple
4928 times on the same node. */
4930 void
4931 trees_out::mark_by_value (tree decl)
4933 gcc_checking_assert (DECL_P (decl)
4934 /* Enum consts are INTEGER_CSTS. */
4935 || TREE_CODE (decl) == INTEGER_CST
4936 || TREE_CODE (decl) == TREE_BINFO);
4938 if (TREE_VISITED (decl))
4939 /* Must already be forced or fixed. */
4940 gcc_checking_assert (*tree_map.get (decl) >= tag_value);
4941 else
4943 bool existed = tree_map.put (decl, tag_value);
4944 gcc_checking_assert (!existed);
4945 TREE_VISITED (decl) = true;
4950 trees_out::get_tag (tree t)
4952 gcc_checking_assert (TREE_VISITED (t));
4953 return *tree_map.get (t);
4956 /* Insert T into the map, return its tag number. */
4959 trees_out::insert (tree t, walk_kind walk)
4961 gcc_checking_assert (walk != WK_normal || !TREE_VISITED (t));
4962 int tag = --ref_num;
4963 bool existed;
4964 int &slot = tree_map.get_or_insert (t, &existed);
4965 gcc_checking_assert (TREE_VISITED (t) == existed
4966 && (!existed
4967 || (walk == WK_value && slot == tag_value)));
4968 TREE_VISITED (t) = true;
4969 slot = tag;
4971 return tag;
4974 /* Insert T into the backreference array. Return its back reference
4975 number. */
4978 trees_in::insert (tree t)
4980 gcc_checking_assert (t || get_overrun ());
4981 back_refs.safe_push (t);
4982 return -(int)back_refs.length ();
4985 /* A chained set of decls. */
4987 void
4988 trees_out::chained_decls (tree decls)
4990 for (; decls; decls = DECL_CHAIN (decls))
4991 tree_node (decls);
4992 tree_node (NULL_TREE);
4995 tree
4996 trees_in::chained_decls ()
4998 tree decls = NULL_TREE;
4999 for (tree *chain = &decls;;)
5000 if (tree decl = tree_node ())
5002 if (!DECL_P (decl) || DECL_CHAIN (decl))
5004 set_overrun ();
5005 break;
5007 *chain = decl;
5008 chain = &DECL_CHAIN (decl);
5010 else
5011 break;
5013 return decls;
5016 /* A vector of decls following DECL_CHAIN. */
5018 void
5019 trees_out::vec_chained_decls (tree decls)
5021 if (streaming_p ())
5023 unsigned len = 0;
5025 for (tree decl = decls; decl; decl = DECL_CHAIN (decl))
5026 len++;
5027 u (len);
5030 for (tree decl = decls; decl; decl = DECL_CHAIN (decl))
5032 if (DECL_IMPLICIT_TYPEDEF_P (decl)
5033 && TYPE_NAME (TREE_TYPE (decl)) != decl)
5034 /* An anonynmous struct with a typedef name. An odd thing to
5035 write. */
5036 tree_node (NULL_TREE);
5037 else
5038 tree_node (decl);
5042 vec<tree, va_heap> *
5043 trees_in::vec_chained_decls ()
5045 vec<tree, va_heap> *v = NULL;
5047 if (unsigned len = u ())
5049 vec_alloc (v, len);
5051 for (unsigned ix = 0; ix < len; ix++)
5053 tree decl = tree_node ();
5054 if (decl && !DECL_P (decl))
5056 set_overrun ();
5057 break;
5059 v->quick_push (decl);
5062 if (get_overrun ())
5064 vec_free (v);
5065 v = NULL;
5069 return v;
5072 /* A vector of trees. */
5074 void
5075 trees_out::tree_vec (vec<tree, va_gc> *v)
5077 unsigned len = vec_safe_length (v);
5078 if (streaming_p ())
5079 u (len);
5080 for (unsigned ix = 0; ix != len; ix++)
5081 tree_node ((*v)[ix]);
5084 vec<tree, va_gc> *
5085 trees_in::tree_vec ()
5087 vec<tree, va_gc> *v = NULL;
5088 if (unsigned len = u ())
5090 vec_alloc (v, len);
5091 for (unsigned ix = 0; ix != len; ix++)
5092 v->quick_push (tree_node ());
5094 return v;
5097 /* A vector of tree pairs. */
5099 void
5100 trees_out::tree_pair_vec (vec<tree_pair_s, va_gc> *v)
5102 unsigned len = vec_safe_length (v);
5103 if (streaming_p ())
5104 u (len);
5105 if (len)
5106 for (unsigned ix = 0; ix != len; ix++)
5108 tree_pair_s const &s = (*v)[ix];
5109 tree_node (s.purpose);
5110 tree_node (s.value);
5114 vec<tree_pair_s, va_gc> *
5115 trees_in::tree_pair_vec ()
5117 vec<tree_pair_s, va_gc> *v = NULL;
5118 if (unsigned len = u ())
5120 vec_alloc (v, len);
5121 for (unsigned ix = 0; ix != len; ix++)
5123 tree_pair_s s;
5124 s.purpose = tree_node ();
5125 s.value = tree_node ();
5126 v->quick_push (s);
5129 return v;
5132 void
5133 trees_out::tree_list (tree list, bool has_purpose)
5135 for (; list; list = TREE_CHAIN (list))
5137 gcc_checking_assert (TREE_VALUE (list));
5138 tree_node (TREE_VALUE (list));
5139 if (has_purpose)
5140 tree_node (TREE_PURPOSE (list));
5142 tree_node (NULL_TREE);
5145 tree
5146 trees_in::tree_list (bool has_purpose)
5148 tree res = NULL_TREE;
5150 for (tree *chain = &res; tree value = tree_node ();
5151 chain = &TREE_CHAIN (*chain))
5153 tree purpose = has_purpose ? tree_node () : NULL_TREE;
5154 *chain = build_tree_list (purpose, value);
5157 return res;
5159 /* Start tree write. Write information to allocate the receiving
5160 node. */
5162 void
5163 trees_out::start (tree t, bool code_streamed)
5165 if (TYPE_P (t))
5167 enum tree_code code = TREE_CODE (t);
5168 gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
5169 /* All these types are TYPE_NON_COMMON. */
5170 gcc_checking_assert (code == RECORD_TYPE
5171 || code == UNION_TYPE
5172 || code == ENUMERAL_TYPE
5173 || code == TEMPLATE_TYPE_PARM
5174 || code == TEMPLATE_TEMPLATE_PARM
5175 || code == BOUND_TEMPLATE_TEMPLATE_PARM);
5178 if (!code_streamed)
5179 u (TREE_CODE (t));
5181 switch (TREE_CODE (t))
5183 default:
5184 if (VL_EXP_CLASS_P (t))
5185 u (VL_EXP_OPERAND_LENGTH (t));
5186 break;
5188 case INTEGER_CST:
5189 u (TREE_INT_CST_NUNITS (t));
5190 u (TREE_INT_CST_EXT_NUNITS (t));
5191 break;
5193 case OMP_CLAUSE:
5194 state->extensions |= SE_OPENMP;
5195 u (OMP_CLAUSE_CODE (t));
5196 break;
5198 case STRING_CST:
5199 str (TREE_STRING_POINTER (t), TREE_STRING_LENGTH (t));
5200 break;
5202 case VECTOR_CST:
5203 u (VECTOR_CST_LOG2_NPATTERNS (t));
5204 u (VECTOR_CST_NELTS_PER_PATTERN (t));
5205 break;
5207 case TREE_BINFO:
5208 u (BINFO_N_BASE_BINFOS (t));
5209 break;
5211 case TREE_VEC:
5212 u (TREE_VEC_LENGTH (t));
5213 break;
5215 case FIXED_CST:
5216 gcc_unreachable (); /* Not supported in C++. */
5217 break;
5219 case IDENTIFIER_NODE:
5220 case SSA_NAME:
5221 case TARGET_MEM_REF:
5222 case TRANSLATION_UNIT_DECL:
5223 /* We shouldn't meet these. */
5224 gcc_unreachable ();
5225 break;
5229 /* Start tree read. Allocate the receiving node. */
5231 tree
5232 trees_in::start (unsigned code)
5234 tree t = NULL_TREE;
5236 if (!code)
5237 code = u ();
5239 switch (code)
5241 default:
5242 if (code >= MAX_TREE_CODES)
5244 fail:
5245 set_overrun ();
5246 return NULL_TREE;
5248 else if (TREE_CODE_CLASS (code) == tcc_vl_exp)
5250 unsigned ops = u ();
5251 t = build_vl_exp (tree_code (code), ops);
5253 else
5254 t = make_node (tree_code (code));
5255 break;
5257 case INTEGER_CST:
5259 unsigned n = u ();
5260 unsigned e = u ();
5261 t = make_int_cst (n, e);
5263 break;
5265 case OMP_CLAUSE:
5267 if (!(state->extensions & SE_OPENMP))
5268 goto fail;
5270 unsigned omp_code = u ();
5271 t = build_omp_clause (UNKNOWN_LOCATION, omp_clause_code (omp_code));
5273 break;
5275 case STRING_CST:
5277 size_t l;
5278 const char *chars = str (&l);
5279 t = build_string (l, chars);
5281 break;
5283 case VECTOR_CST:
5285 unsigned log2_npats = u ();
5286 unsigned elts_per = u ();
5287 t = make_vector (log2_npats, elts_per);
5289 break;
5291 case TREE_BINFO:
5292 t = make_tree_binfo (u ());
5293 break;
5295 case TREE_VEC:
5296 t = make_tree_vec (u ());
5297 break;
5299 case FIXED_CST:
5300 case IDENTIFIER_NODE:
5301 case SSA_NAME:
5302 case TARGET_MEM_REF:
5303 case TRANSLATION_UNIT_DECL:
5304 goto fail;
5307 return t;
5310 /* The structure streamers access the raw fields, because the
5311 alternative, of using the accessor macros can require using
5312 different accessors for the same underlying field, depending on the
5313 tree code. That's both confusing and annoying. */
5315 /* Read & write the core boolean flags. */
5317 void
5318 trees_out::core_bools (tree t, bits_out& bits)
5320 #define WB(X) (bits.b (X))
5321 /* Stream X if COND holds, and if !COND stream a dummy value so that the
5322 overall number of bits streamed is independent of the runtime value
5323 of COND, which allows the compiler to better optimize this function. */
5324 #define WB_IF(COND, X) WB ((COND) ? (X) : false)
5325 tree_code code = TREE_CODE (t);
5327 WB (t->base.side_effects_flag);
5328 WB (t->base.constant_flag);
5329 WB (t->base.addressable_flag);
5330 WB (t->base.volatile_flag);
5331 WB (t->base.readonly_flag);
5332 /* base.asm_written_flag is a property of the current TU's use of
5333 this decl. */
5334 WB (t->base.nowarning_flag);
5335 /* base.visited read as zero (it's set for writer, because that's
5336 how we mark nodes). */
5337 /* base.used_flag is not streamed. Readers may set TREE_USED of
5338 decls they use. */
5339 WB (t->base.nothrow_flag);
5340 WB (t->base.static_flag);
5341 /* This is TYPE_CACHED_VALUES_P for types. */
5342 WB_IF (TREE_CODE_CLASS (code) != tcc_type, t->base.public_flag);
5343 WB (t->base.private_flag);
5344 WB (t->base.protected_flag);
5345 WB (t->base.deprecated_flag);
5346 WB (t->base.default_def_flag);
5348 switch (code)
5350 case CALL_EXPR:
5351 case INTEGER_CST:
5352 case SSA_NAME:
5353 case TARGET_MEM_REF:
5354 case TREE_VEC:
5355 /* These use different base.u fields. */
5356 return;
5358 default:
5359 WB (t->base.u.bits.lang_flag_0);
5360 bool flag_1 = t->base.u.bits.lang_flag_1;
5361 if (!flag_1)
5363 else if (code == TEMPLATE_INFO)
5364 /* This is TI_PENDING_TEMPLATE_FLAG, not relevant to reader. */
5365 flag_1 = false;
5366 else if (code == VAR_DECL)
5368 /* This is DECL_INITIALIZED_P. */
5369 if (TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
5370 /* We'll set this when reading the definition. */
5371 flag_1 = false;
5373 WB (flag_1);
5374 WB (t->base.u.bits.lang_flag_2);
5375 WB (t->base.u.bits.lang_flag_3);
5376 WB (t->base.u.bits.lang_flag_4);
5377 WB (t->base.u.bits.lang_flag_5);
5378 WB (t->base.u.bits.lang_flag_6);
5379 WB (t->base.u.bits.saturating_flag);
5380 WB (t->base.u.bits.unsigned_flag);
5381 WB (t->base.u.bits.packed_flag);
5382 WB (t->base.u.bits.user_align);
5383 WB (t->base.u.bits.nameless_flag);
5384 WB (t->base.u.bits.atomic_flag);
5385 WB (t->base.u.bits.unavailable_flag);
5386 break;
5389 if (TREE_CODE_CLASS (code) == tcc_type)
5391 WB (t->type_common.no_force_blk_flag);
5392 WB (t->type_common.needs_constructing_flag);
5393 WB (t->type_common.transparent_aggr_flag);
5394 WB (t->type_common.restrict_flag);
5395 WB (t->type_common.string_flag);
5396 WB (t->type_common.lang_flag_0);
5397 WB (t->type_common.lang_flag_1);
5398 WB (t->type_common.lang_flag_2);
5399 WB (t->type_common.lang_flag_3);
5400 WB (t->type_common.lang_flag_4);
5401 WB (t->type_common.lang_flag_5);
5402 WB (t->type_common.lang_flag_6);
5403 WB (t->type_common.typeless_storage);
5406 if (TREE_CODE_CLASS (code) != tcc_declaration)
5407 return;
5409 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5411 WB (t->decl_common.nonlocal_flag);
5412 WB (t->decl_common.virtual_flag);
5413 WB (t->decl_common.ignored_flag);
5414 WB (t->decl_common.abstract_flag);
5415 WB (t->decl_common.artificial_flag);
5416 WB (t->decl_common.preserve_flag);
5417 WB (t->decl_common.debug_expr_is_from);
5418 WB (t->decl_common.lang_flag_0);
5419 WB (t->decl_common.lang_flag_1);
5420 WB (t->decl_common.lang_flag_2);
5421 WB (t->decl_common.lang_flag_3);
5422 WB (t->decl_common.lang_flag_4);
5425 /* This is DECL_INTERFACE_KNOWN: We should redetermine whether
5426 we need to import or export any vtables or typeinfo objects
5427 on stream-in. */
5428 bool interface_known = t->decl_common.lang_flag_5;
5429 if (VAR_P (t) && (DECL_VTABLE_OR_VTT_P (t) || DECL_TINFO_P (t)))
5430 interface_known = false;
5431 WB (interface_known);
5434 WB (t->decl_common.lang_flag_6);
5435 WB (t->decl_common.lang_flag_7);
5436 WB (t->decl_common.lang_flag_8);
5437 WB (t->decl_common.decl_flag_0);
5440 /* DECL_EXTERNAL -> decl_flag_1
5441 == it is defined elsewhere
5442 DECL_NOT_REALLY_EXTERN -> base.not_really_extern
5443 == that was a lie, it is here */
5445 bool is_external = t->decl_common.decl_flag_1;
5446 if (!is_external)
5447 /* decl_flag_1 is DECL_EXTERNAL. Things we emit here, might
5448 well be external from the POV of an importer. */
5449 // FIXME: Do we need to know if this is a TEMPLATE_RESULT --
5450 // a flag from the caller?
5451 switch (code)
5453 default:
5454 break;
5456 case VAR_DECL:
5457 if (TREE_PUBLIC (t)
5458 && !(TREE_STATIC (t)
5459 && DECL_FUNCTION_SCOPE_P (t)
5460 && DECL_DECLARED_INLINE_P (DECL_CONTEXT (t)))
5461 && !DECL_VAR_DECLARED_INLINE_P (t))
5462 is_external = true;
5463 break;
5465 case FUNCTION_DECL:
5466 if (TREE_PUBLIC (t)
5467 && !DECL_DECLARED_INLINE_P (t))
5468 is_external = true;
5469 break;
5471 WB (is_external);
5474 WB (t->decl_common.decl_flag_2);
5475 WB (t->decl_common.decl_flag_3);
5476 WB (t->decl_common.not_gimple_reg_flag);
5477 WB (t->decl_common.decl_by_reference_flag);
5478 WB (t->decl_common.decl_read_flag);
5479 WB (t->decl_common.decl_nonshareable_flag);
5480 WB (t->decl_common.decl_not_flexarray);
5482 else
5483 return;
5485 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5487 WB (t->decl_with_vis.defer_output);
5488 WB (t->decl_with_vis.hard_register);
5489 WB (t->decl_with_vis.common_flag);
5490 WB (t->decl_with_vis.in_text_section);
5491 WB (t->decl_with_vis.in_constant_pool);
5492 WB (t->decl_with_vis.dllimport_flag);
5493 WB (t->decl_with_vis.weak_flag);
5494 WB (t->decl_with_vis.seen_in_bind_expr);
5495 WB (t->decl_with_vis.comdat_flag);
5496 WB (t->decl_with_vis.visibility_specified);
5497 WB (t->decl_with_vis.init_priority_p);
5498 WB (t->decl_with_vis.shadowed_for_var_p);
5499 WB (t->decl_with_vis.cxx_constructor);
5500 WB (t->decl_with_vis.cxx_destructor);
5501 WB (t->decl_with_vis.final);
5502 WB (t->decl_with_vis.regdecl_flag);
5504 else
5505 return;
5507 if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
5509 WB (t->function_decl.static_ctor_flag);
5510 WB (t->function_decl.static_dtor_flag);
5511 WB (t->function_decl.uninlinable);
5512 WB (t->function_decl.possibly_inlined);
5513 WB (t->function_decl.novops_flag);
5514 WB (t->function_decl.returns_twice_flag);
5515 WB (t->function_decl.malloc_flag);
5516 WB (t->function_decl.declared_inline_flag);
5517 WB (t->function_decl.no_inline_warning_flag);
5518 WB (t->function_decl.no_instrument_function_entry_exit);
5519 WB (t->function_decl.no_limit_stack);
5520 WB (t->function_decl.disregard_inline_limits);
5521 WB (t->function_decl.pure_flag);
5522 WB (t->function_decl.looping_const_or_pure_flag);
5524 WB (t->function_decl.has_debug_args_flag);
5525 WB (t->function_decl.versioned_function);
5527 /* decl_type is a (misnamed) 2 bit discriminator. */
5528 unsigned kind = t->function_decl.decl_type;
5529 WB ((kind >> 0) & 1);
5530 WB ((kind >> 1) & 1);
5532 #undef WB_IF
5533 #undef WB
5536 bool
5537 trees_in::core_bools (tree t, bits_in& bits)
5539 #define RB(X) ((X) = bits.b ())
5540 /* See the comment for WB_IF in trees_out::core_bools. */
5541 #define RB_IF(COND, X) ((COND) ? RB (X) : bits.b ())
5543 tree_code code = TREE_CODE (t);
5545 RB (t->base.side_effects_flag);
5546 RB (t->base.constant_flag);
5547 RB (t->base.addressable_flag);
5548 RB (t->base.volatile_flag);
5549 RB (t->base.readonly_flag);
5550 /* base.asm_written_flag is not streamed. */
5551 RB (t->base.nowarning_flag);
5552 /* base.visited is not streamed. */
5553 /* base.used_flag is not streamed. */
5554 RB (t->base.nothrow_flag);
5555 RB (t->base.static_flag);
5556 RB_IF (TREE_CODE_CLASS (code) != tcc_type, t->base.public_flag);
5557 RB (t->base.private_flag);
5558 RB (t->base.protected_flag);
5559 RB (t->base.deprecated_flag);
5560 RB (t->base.default_def_flag);
5562 switch (code)
5564 case CALL_EXPR:
5565 case INTEGER_CST:
5566 case SSA_NAME:
5567 case TARGET_MEM_REF:
5568 case TREE_VEC:
5569 /* These use different base.u fields. */
5570 goto done;
5572 default:
5573 RB (t->base.u.bits.lang_flag_0);
5574 RB (t->base.u.bits.lang_flag_1);
5575 RB (t->base.u.bits.lang_flag_2);
5576 RB (t->base.u.bits.lang_flag_3);
5577 RB (t->base.u.bits.lang_flag_4);
5578 RB (t->base.u.bits.lang_flag_5);
5579 RB (t->base.u.bits.lang_flag_6);
5580 RB (t->base.u.bits.saturating_flag);
5581 RB (t->base.u.bits.unsigned_flag);
5582 RB (t->base.u.bits.packed_flag);
5583 RB (t->base.u.bits.user_align);
5584 RB (t->base.u.bits.nameless_flag);
5585 RB (t->base.u.bits.atomic_flag);
5586 RB (t->base.u.bits.unavailable_flag);
5587 break;
5590 if (TREE_CODE_CLASS (code) == tcc_type)
5592 RB (t->type_common.no_force_blk_flag);
5593 RB (t->type_common.needs_constructing_flag);
5594 RB (t->type_common.transparent_aggr_flag);
5595 RB (t->type_common.restrict_flag);
5596 RB (t->type_common.string_flag);
5597 RB (t->type_common.lang_flag_0);
5598 RB (t->type_common.lang_flag_1);
5599 RB (t->type_common.lang_flag_2);
5600 RB (t->type_common.lang_flag_3);
5601 RB (t->type_common.lang_flag_4);
5602 RB (t->type_common.lang_flag_5);
5603 RB (t->type_common.lang_flag_6);
5604 RB (t->type_common.typeless_storage);
5607 if (TREE_CODE_CLASS (code) != tcc_declaration)
5608 goto done;
5610 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5612 RB (t->decl_common.nonlocal_flag);
5613 RB (t->decl_common.virtual_flag);
5614 RB (t->decl_common.ignored_flag);
5615 RB (t->decl_common.abstract_flag);
5616 RB (t->decl_common.artificial_flag);
5617 RB (t->decl_common.preserve_flag);
5618 RB (t->decl_common.debug_expr_is_from);
5619 RB (t->decl_common.lang_flag_0);
5620 RB (t->decl_common.lang_flag_1);
5621 RB (t->decl_common.lang_flag_2);
5622 RB (t->decl_common.lang_flag_3);
5623 RB (t->decl_common.lang_flag_4);
5624 RB (t->decl_common.lang_flag_5);
5625 RB (t->decl_common.lang_flag_6);
5626 RB (t->decl_common.lang_flag_7);
5627 RB (t->decl_common.lang_flag_8);
5628 RB (t->decl_common.decl_flag_0);
5629 RB (t->decl_common.decl_flag_1);
5630 RB (t->decl_common.decl_flag_2);
5631 RB (t->decl_common.decl_flag_3);
5632 RB (t->decl_common.not_gimple_reg_flag);
5633 RB (t->decl_common.decl_by_reference_flag);
5634 RB (t->decl_common.decl_read_flag);
5635 RB (t->decl_common.decl_nonshareable_flag);
5636 RB (t->decl_common.decl_not_flexarray);
5638 else
5639 goto done;
5641 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5643 RB (t->decl_with_vis.defer_output);
5644 RB (t->decl_with_vis.hard_register);
5645 RB (t->decl_with_vis.common_flag);
5646 RB (t->decl_with_vis.in_text_section);
5647 RB (t->decl_with_vis.in_constant_pool);
5648 RB (t->decl_with_vis.dllimport_flag);
5649 RB (t->decl_with_vis.weak_flag);
5650 RB (t->decl_with_vis.seen_in_bind_expr);
5651 RB (t->decl_with_vis.comdat_flag);
5652 RB (t->decl_with_vis.visibility_specified);
5653 RB (t->decl_with_vis.init_priority_p);
5654 RB (t->decl_with_vis.shadowed_for_var_p);
5655 RB (t->decl_with_vis.cxx_constructor);
5656 RB (t->decl_with_vis.cxx_destructor);
5657 RB (t->decl_with_vis.final);
5658 RB (t->decl_with_vis.regdecl_flag);
5660 else
5661 goto done;
5663 if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
5665 RB (t->function_decl.static_ctor_flag);
5666 RB (t->function_decl.static_dtor_flag);
5667 RB (t->function_decl.uninlinable);
5668 RB (t->function_decl.possibly_inlined);
5669 RB (t->function_decl.novops_flag);
5670 RB (t->function_decl.returns_twice_flag);
5671 RB (t->function_decl.malloc_flag);
5672 RB (t->function_decl.declared_inline_flag);
5673 RB (t->function_decl.no_inline_warning_flag);
5674 RB (t->function_decl.no_instrument_function_entry_exit);
5675 RB (t->function_decl.no_limit_stack);
5676 RB (t->function_decl.disregard_inline_limits);
5677 RB (t->function_decl.pure_flag);
5678 RB (t->function_decl.looping_const_or_pure_flag);
5680 RB (t->function_decl.has_debug_args_flag);
5681 RB (t->function_decl.versioned_function);
5683 /* decl_type is a (misnamed) 2 bit discriminator. */
5684 unsigned kind = 0;
5685 kind |= unsigned (bits.b ()) << 0;
5686 kind |= unsigned (bits.b ()) << 1;
5687 t->function_decl.decl_type = function_decl_type (kind);
5689 #undef RB_IF
5690 #undef RB
5691 done:
5692 return !get_overrun ();
5695 void
5696 trees_out::lang_decl_bools (tree t, bits_out& bits)
5698 #define WB(X) (bits.b (X))
5699 const struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
5701 bits.bflush ();
5702 WB (lang->u.base.language == lang_cplusplus);
5703 WB ((lang->u.base.use_template >> 0) & 1);
5704 WB ((lang->u.base.use_template >> 1) & 1);
5705 /* Do not write lang->u.base.not_really_extern, importer will set
5706 when reading the definition (if any). */
5707 WB (lang->u.base.initialized_in_class);
5708 WB (lang->u.base.threadprivate_or_deleted_p);
5709 /* Do not write lang->u.base.anticipated_p, it is a property of the
5710 current TU. */
5711 WB (lang->u.base.friend_or_tls);
5712 WB (lang->u.base.unknown_bound_p);
5713 /* Do not write lang->u.base.odr_used, importer will recalculate if
5714 they do ODR use this decl. */
5715 WB (lang->u.base.concept_p);
5716 WB (lang->u.base.var_declared_inline_p);
5717 WB (lang->u.base.dependent_init_p);
5718 /* When building a header unit, everthing is marked as purview, (so
5719 we know which decls to write). But when we import them we do not
5720 want to mark them as in module purview. */
5721 WB (lang->u.base.module_purview_p && !header_module_p ());
5722 WB (lang->u.base.module_attach_p);
5723 WB (lang->u.base.module_keyed_decls_p);
5724 switch (lang->u.base.selector)
5726 default:
5727 gcc_unreachable ();
5729 case lds_fn: /* lang_decl_fn. */
5730 WB (lang->u.fn.global_ctor_p);
5731 WB (lang->u.fn.global_dtor_p);
5732 WB (lang->u.fn.static_function);
5733 WB (lang->u.fn.pure_virtual);
5734 WB (lang->u.fn.defaulted_p);
5735 WB (lang->u.fn.has_in_charge_parm_p);
5736 WB (lang->u.fn.has_vtt_parm_p);
5737 /* There shouldn't be a pending inline at this point. */
5738 gcc_assert (!lang->u.fn.pending_inline_p);
5739 WB (lang->u.fn.nonconverting);
5740 WB (lang->u.fn.thunk_p);
5741 WB (lang->u.fn.this_thunk_p);
5742 /* Do not stream lang->u.hidden_friend_p, it is a property of
5743 the TU. */
5744 WB (lang->u.fn.omp_declare_reduction_p);
5745 WB (lang->u.fn.has_dependent_explicit_spec_p);
5746 WB (lang->u.fn.immediate_fn_p);
5747 WB (lang->u.fn.maybe_deleted);
5748 /* We do not stream lang->u.fn.implicit_constexpr. */
5749 WB (lang->u.fn.escalated_p);
5750 WB (lang->u.fn.xobj_func);
5751 goto lds_min;
5753 case lds_decomp: /* lang_decl_decomp. */
5754 /* No bools. */
5755 goto lds_min;
5757 case lds_min: /* lang_decl_min. */
5758 lds_min:
5759 /* No bools. */
5760 break;
5762 case lds_ns: /* lang_decl_ns. */
5763 /* No bools. */
5764 break;
5766 case lds_parm: /* lang_decl_parm. */
5767 /* No bools. */
5768 break;
5770 #undef WB
5773 bool
5774 trees_in::lang_decl_bools (tree t, bits_in& bits)
5776 #define RB(X) ((X) = bits.b ())
5777 struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
5779 bits.bflush ();
5780 lang->u.base.language = bits.b () ? lang_cplusplus : lang_c;
5781 unsigned v;
5782 v = bits.b () << 0;
5783 v |= bits.b () << 1;
5784 lang->u.base.use_template = v;
5785 /* lang->u.base.not_really_extern is not streamed. */
5786 RB (lang->u.base.initialized_in_class);
5787 RB (lang->u.base.threadprivate_or_deleted_p);
5788 /* lang->u.base.anticipated_p is not streamed. */
5789 RB (lang->u.base.friend_or_tls);
5790 RB (lang->u.base.unknown_bound_p);
5791 /* lang->u.base.odr_used is not streamed. */
5792 RB (lang->u.base.concept_p);
5793 RB (lang->u.base.var_declared_inline_p);
5794 RB (lang->u.base.dependent_init_p);
5795 RB (lang->u.base.module_purview_p);
5796 RB (lang->u.base.module_attach_p);
5797 RB (lang->u.base.module_keyed_decls_p);
5798 switch (lang->u.base.selector)
5800 default:
5801 gcc_unreachable ();
5803 case lds_fn: /* lang_decl_fn. */
5804 RB (lang->u.fn.global_ctor_p);
5805 RB (lang->u.fn.global_dtor_p);
5806 RB (lang->u.fn.static_function);
5807 RB (lang->u.fn.pure_virtual);
5808 RB (lang->u.fn.defaulted_p);
5809 RB (lang->u.fn.has_in_charge_parm_p);
5810 RB (lang->u.fn.has_vtt_parm_p);
5811 RB (lang->u.fn.nonconverting);
5812 RB (lang->u.fn.thunk_p);
5813 RB (lang->u.fn.this_thunk_p);
5814 /* lang->u.fn.hidden_friend_p is not streamed. */
5815 RB (lang->u.fn.omp_declare_reduction_p);
5816 RB (lang->u.fn.has_dependent_explicit_spec_p);
5817 RB (lang->u.fn.immediate_fn_p);
5818 RB (lang->u.fn.maybe_deleted);
5819 /* We do not stream lang->u.fn.implicit_constexpr. */
5820 RB (lang->u.fn.escalated_p);
5821 RB (lang->u.fn.xobj_func);
5822 goto lds_min;
5824 case lds_decomp: /* lang_decl_decomp. */
5825 /* No bools. */
5826 goto lds_min;
5828 case lds_min: /* lang_decl_min. */
5829 lds_min:
5830 /* No bools. */
5831 break;
5833 case lds_ns: /* lang_decl_ns. */
5834 /* No bools. */
5835 break;
5837 case lds_parm: /* lang_decl_parm. */
5838 /* No bools. */
5839 break;
5841 #undef RB
5842 return !get_overrun ();
5845 void
5846 trees_out::lang_type_bools (tree t, bits_out& bits)
5848 #define WB(X) (bits.b (X))
5849 const struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
5851 bits.bflush ();
5852 WB (lang->has_type_conversion);
5853 WB (lang->has_copy_ctor);
5854 WB (lang->has_default_ctor);
5855 WB (lang->const_needs_init);
5856 WB (lang->ref_needs_init);
5857 WB (lang->has_const_copy_assign);
5858 WB ((lang->use_template >> 0) & 1);
5859 WB ((lang->use_template >> 1) & 1);
5861 WB (lang->has_mutable);
5862 WB (lang->com_interface);
5863 WB (lang->non_pod_class);
5864 WB (lang->nearly_empty_p);
5865 WB (lang->user_align);
5866 WB (lang->has_copy_assign);
5867 WB (lang->has_new);
5868 WB (lang->has_array_new);
5870 WB ((lang->gets_delete >> 0) & 1);
5871 WB ((lang->gets_delete >> 1) & 1);
5872 WB (lang->interface_only);
5873 WB (lang->interface_unknown);
5874 WB (lang->contains_empty_class_p);
5875 WB (lang->anon_aggr);
5876 WB (lang->non_zero_init);
5877 WB (lang->empty_p);
5879 WB (lang->vec_new_uses_cookie);
5880 WB (lang->declared_class);
5881 WB (lang->diamond_shaped);
5882 WB (lang->repeated_base);
5883 gcc_assert (!lang->being_defined);
5884 // lang->debug_requested
5885 WB (lang->fields_readonly);
5886 WB (lang->ptrmemfunc_flag);
5888 WB (lang->lazy_default_ctor);
5889 WB (lang->lazy_copy_ctor);
5890 WB (lang->lazy_copy_assign);
5891 WB (lang->lazy_destructor);
5892 WB (lang->has_const_copy_ctor);
5893 WB (lang->has_complex_copy_ctor);
5894 WB (lang->has_complex_copy_assign);
5895 WB (lang->non_aggregate);
5897 WB (lang->has_complex_dflt);
5898 WB (lang->has_list_ctor);
5899 WB (lang->non_std_layout);
5900 WB (lang->is_literal);
5901 WB (lang->lazy_move_ctor);
5902 WB (lang->lazy_move_assign);
5903 WB (lang->has_complex_move_ctor);
5904 WB (lang->has_complex_move_assign);
5906 WB (lang->has_constexpr_ctor);
5907 WB (lang->unique_obj_representations);
5908 WB (lang->unique_obj_representations_set);
5909 #undef WB
5912 bool
5913 trees_in::lang_type_bools (tree t, bits_in& bits)
5915 #define RB(X) ((X) = bits.b ())
5916 struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
5918 bits.bflush ();
5919 RB (lang->has_type_conversion);
5920 RB (lang->has_copy_ctor);
5921 RB (lang->has_default_ctor);
5922 RB (lang->const_needs_init);
5923 RB (lang->ref_needs_init);
5924 RB (lang->has_const_copy_assign);
5925 unsigned v;
5926 v = bits.b () << 0;
5927 v |= bits.b () << 1;
5928 lang->use_template = v;
5930 RB (lang->has_mutable);
5931 RB (lang->com_interface);
5932 RB (lang->non_pod_class);
5933 RB (lang->nearly_empty_p);
5934 RB (lang->user_align);
5935 RB (lang->has_copy_assign);
5936 RB (lang->has_new);
5937 RB (lang->has_array_new);
5939 v = bits.b () << 0;
5940 v |= bits.b () << 1;
5941 lang->gets_delete = v;
5942 RB (lang->interface_only);
5943 RB (lang->interface_unknown);
5944 RB (lang->contains_empty_class_p);
5945 RB (lang->anon_aggr);
5946 RB (lang->non_zero_init);
5947 RB (lang->empty_p);
5949 RB (lang->vec_new_uses_cookie);
5950 RB (lang->declared_class);
5951 RB (lang->diamond_shaped);
5952 RB (lang->repeated_base);
5953 gcc_assert (!lang->being_defined);
5954 gcc_assert (!lang->debug_requested);
5955 RB (lang->fields_readonly);
5956 RB (lang->ptrmemfunc_flag);
5958 RB (lang->lazy_default_ctor);
5959 RB (lang->lazy_copy_ctor);
5960 RB (lang->lazy_copy_assign);
5961 RB (lang->lazy_destructor);
5962 RB (lang->has_const_copy_ctor);
5963 RB (lang->has_complex_copy_ctor);
5964 RB (lang->has_complex_copy_assign);
5965 RB (lang->non_aggregate);
5967 RB (lang->has_complex_dflt);
5968 RB (lang->has_list_ctor);
5969 RB (lang->non_std_layout);
5970 RB (lang->is_literal);
5971 RB (lang->lazy_move_ctor);
5972 RB (lang->lazy_move_assign);
5973 RB (lang->has_complex_move_ctor);
5974 RB (lang->has_complex_move_assign);
5976 RB (lang->has_constexpr_ctor);
5977 RB (lang->unique_obj_representations);
5978 RB (lang->unique_obj_representations_set);
5979 #undef RB
5980 return !get_overrun ();
5983 /* Read & write the core values and pointers. */
5985 void
5986 trees_out::core_vals (tree t)
5988 #define WU(X) (u (X))
5989 #define WT(X) (tree_node (X))
5990 tree_code code = TREE_CODE (t);
5992 /* First by shape of the tree. */
5994 if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
5996 /* Write this early, for better log information. */
5997 WT (t->decl_minimal.name);
5998 if (!DECL_TEMPLATE_PARM_P (t))
5999 WT (t->decl_minimal.context);
6001 if (state)
6002 state->write_location (*this, t->decl_minimal.locus);
6005 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
6007 /* The only types we write also have TYPE_NON_COMMON. */
6008 gcc_checking_assert (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON));
6010 /* We only stream the main variant. */
6011 gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
6013 /* Stream the name & context first, for better log information */
6014 WT (t->type_common.name);
6015 WT (t->type_common.context);
6017 /* By construction we want to make sure we have the canonical
6018 and main variants already in the type table, so emit them
6019 now. */
6020 WT (t->type_common.main_variant);
6022 tree canonical = t->type_common.canonical;
6023 if (canonical && DECL_TEMPLATE_PARM_P (TYPE_NAME (t)))
6024 /* We do not want to wander into different templates.
6025 Reconstructed on stream in. */
6026 canonical = t;
6027 WT (canonical);
6029 /* type_common.next_variant is internally manipulated. */
6030 /* type_common.pointer_to, type_common.reference_to. */
6032 if (streaming_p ())
6034 WU (t->type_common.precision);
6035 WU (t->type_common.contains_placeholder_bits);
6036 WU (t->type_common.mode);
6037 WU (t->type_common.align);
6040 if (!RECORD_OR_UNION_CODE_P (code))
6042 WT (t->type_common.size);
6043 WT (t->type_common.size_unit);
6045 WT (t->type_common.attributes);
6047 WT (t->type_common.common.chain); /* TYPE_STUB_DECL. */
6050 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
6052 if (streaming_p ())
6054 WU (t->decl_common.mode);
6055 WU (t->decl_common.off_align);
6056 WU (t->decl_common.align);
6059 /* For templates these hold instantiation (partial and/or
6060 specialization) information. */
6061 if (code != TEMPLATE_DECL)
6063 WT (t->decl_common.size);
6064 WT (t->decl_common.size_unit);
6067 WT (t->decl_common.attributes);
6068 // FIXME: Does this introduce cross-decl links? For instance
6069 // from instantiation to the template. If so, we'll need more
6070 // deduplication logic. I think we'll need to walk the blocks
6071 // of the owning function_decl's abstract origin in tandem, to
6072 // generate the locating data needed?
6073 WT (t->decl_common.abstract_origin);
6076 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
6078 WT (t->decl_with_vis.assembler_name);
6079 if (streaming_p ())
6080 WU (t->decl_with_vis.visibility);
6083 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
6085 if (code == ENUMERAL_TYPE)
6087 /* These fields get set even for opaque enums that lack a
6088 definition, so we stream them directly for each ENUMERAL_TYPE.
6089 We stream TYPE_VALUES as part of the definition. */
6090 WT (t->type_non_common.maxval);
6091 WT (t->type_non_common.minval);
6093 /* Records and unions hold FIELDS, VFIELD & BINFO on these
6094 things. */
6095 else if (!RECORD_OR_UNION_CODE_P (code))
6097 // FIXME: These are from tpl_parm_value's 'type' writing.
6098 // Perhaps it should just be doing them directly?
6099 gcc_checking_assert (code == TEMPLATE_TYPE_PARM
6100 || code == TEMPLATE_TEMPLATE_PARM
6101 || code == BOUND_TEMPLATE_TEMPLATE_PARM);
6102 gcc_checking_assert (!TYPE_CACHED_VALUES_P (t));
6103 WT (t->type_non_common.values);
6104 WT (t->type_non_common.maxval);
6105 WT (t->type_non_common.minval);
6108 WT (t->type_non_common.lang_1);
6111 if (CODE_CONTAINS_STRUCT (code, TS_EXP))
6113 if (state)
6114 state->write_location (*this, t->exp.locus);
6116 /* Walk in forward order, as (for instance) REQUIRES_EXPR has a
6117 bunch of unscoped parms on its first operand. It's safer to
6118 create those in order. */
6119 bool vl = TREE_CODE_CLASS (code) == tcc_vl_exp;
6120 for (unsigned limit = (vl ? VL_EXP_OPERAND_LENGTH (t)
6121 : TREE_OPERAND_LENGTH (t)),
6122 ix = unsigned (vl); ix != limit; ix++)
6123 WT (TREE_OPERAND (t, ix));
6125 else
6126 /* The CODE_CONTAINS tables were inaccurate when I started. */
6127 gcc_checking_assert (TREE_CODE_CLASS (code) != tcc_expression
6128 && TREE_CODE_CLASS (code) != tcc_binary
6129 && TREE_CODE_CLASS (code) != tcc_unary
6130 && TREE_CODE_CLASS (code) != tcc_reference
6131 && TREE_CODE_CLASS (code) != tcc_comparison
6132 && TREE_CODE_CLASS (code) != tcc_statement
6133 && TREE_CODE_CLASS (code) != tcc_vl_exp);
6135 /* Then by CODE. Special cases and/or 1:1 tree shape
6136 correspondance. */
6137 switch (code)
6139 default:
6140 break;
6142 case ARGUMENT_PACK_SELECT: /* Transient during instantiation. */
6143 case DEFERRED_PARSE: /* Expanded upon completion of
6144 outermost class. */
6145 case IDENTIFIER_NODE: /* Streamed specially. */
6146 case BINDING_VECTOR: /* Only in namespace-scope symbol
6147 table. */
6148 case SSA_NAME:
6149 case TRANSLATION_UNIT_DECL: /* There is only one, it is a
6150 global_tree. */
6151 case USERDEF_LITERAL: /* Expanded during parsing. */
6152 gcc_unreachable (); /* Should never meet. */
6154 /* Constants. */
6155 case COMPLEX_CST:
6156 WT (TREE_REALPART (t));
6157 WT (TREE_IMAGPART (t));
6158 break;
6160 case FIXED_CST:
6161 gcc_unreachable (); /* Not supported in C++. */
6163 case INTEGER_CST:
6164 if (streaming_p ())
6166 unsigned num = TREE_INT_CST_EXT_NUNITS (t);
6167 for (unsigned ix = 0; ix != num; ix++)
6168 wu (TREE_INT_CST_ELT (t, ix));
6170 break;
6172 case POLY_INT_CST:
6173 if (streaming_p ())
6174 for (unsigned ix = 0; ix != NUM_POLY_INT_COEFFS; ix++)
6175 WT (POLY_INT_CST_COEFF (t, ix));
6176 break;
6178 case REAL_CST:
6179 if (streaming_p ())
6180 buf (TREE_REAL_CST_PTR (t), sizeof (real_value));
6181 break;
6183 case STRING_CST:
6184 /* Streamed during start. */
6185 break;
6187 case VECTOR_CST:
6188 for (unsigned ix = vector_cst_encoded_nelts (t); ix--;)
6189 WT (VECTOR_CST_ENCODED_ELT (t, ix));
6190 break;
6192 /* Decls. */
6193 case VAR_DECL:
6194 if (DECL_CONTEXT (t)
6195 && TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
6196 break;
6197 /* FALLTHROUGH */
6199 case RESULT_DECL:
6200 case PARM_DECL:
6201 if (DECL_HAS_VALUE_EXPR_P (t))
6202 WT (DECL_VALUE_EXPR (t));
6203 /* FALLTHROUGH */
6205 case CONST_DECL:
6206 case IMPORTED_DECL:
6207 WT (t->decl_common.initial);
6208 break;
6210 case FIELD_DECL:
6211 WT (t->field_decl.offset);
6212 WT (t->field_decl.bit_field_type);
6213 WT (t->field_decl.qualifier); /* bitfield unit. */
6214 WT (t->field_decl.bit_offset);
6215 WT (t->field_decl.fcontext);
6216 WT (t->decl_common.initial);
6217 break;
6219 case LABEL_DECL:
6220 if (streaming_p ())
6222 WU (t->label_decl.label_decl_uid);
6223 WU (t->label_decl.eh_landing_pad_nr);
6225 break;
6227 case FUNCTION_DECL:
6228 if (streaming_p ())
6230 /* Builtins can be streamed by value when a header declares
6231 them. */
6232 WU (DECL_BUILT_IN_CLASS (t));
6233 if (DECL_BUILT_IN_CLASS (t) != NOT_BUILT_IN)
6234 WU (DECL_UNCHECKED_FUNCTION_CODE (t));
6237 WT (t->function_decl.personality);
6238 WT (t->function_decl.function_specific_target);
6239 WT (t->function_decl.function_specific_optimization);
6240 WT (t->function_decl.vindex);
6242 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
6243 WT (lookup_explicit_specifier (t));
6244 break;
6246 case USING_DECL:
6247 /* USING_DECL_DECLS */
6248 WT (t->decl_common.initial);
6249 /* FALLTHROUGH */
6251 case TYPE_DECL:
6252 /* USING_DECL: USING_DECL_SCOPE */
6253 /* TYPE_DECL: DECL_ORIGINAL_TYPE */
6254 WT (t->decl_non_common.result);
6255 break;
6257 /* Miscellaneous common nodes. */
6258 case BLOCK:
6259 if (state)
6261 state->write_location (*this, t->block.locus);
6262 state->write_location (*this, t->block.end_locus);
6265 /* DECL_LOCAL_DECL_P decls are first encountered here and
6266 streamed by value. */
6267 for (tree decls = t->block.vars; decls; decls = DECL_CHAIN (decls))
6269 if (VAR_OR_FUNCTION_DECL_P (decls)
6270 && DECL_LOCAL_DECL_P (decls))
6272 /* Make sure this is the first encounter, and mark for
6273 walk-by-value. */
6274 gcc_checking_assert (!TREE_VISITED (decls)
6275 && !DECL_TEMPLATE_INFO (decls));
6276 mark_by_value (decls);
6278 tree_node (decls);
6280 tree_node (NULL_TREE);
6282 /* nonlocalized_vars is a middle-end thing. */
6283 WT (t->block.subblocks);
6284 WT (t->block.supercontext);
6285 // FIXME: As for decl's abstract_origin, does this introduce crosslinks?
6286 WT (t->block.abstract_origin);
6287 /* fragment_origin, fragment_chain are middle-end things. */
6288 WT (t->block.chain);
6289 /* nonlocalized_vars, block_num & die are middle endy/debug
6290 things. */
6291 break;
6293 case CALL_EXPR:
6294 if (streaming_p ())
6295 WU (t->base.u.ifn);
6296 break;
6298 case CONSTRUCTOR:
6299 // This must be streamed /after/ we've streamed the type,
6300 // because it can directly refer to elements of the type. Eg,
6301 // FIELD_DECLs of a RECORD_TYPE.
6302 break;
6304 case OMP_CLAUSE:
6306 /* The ompcode is serialized in start. */
6307 if (streaming_p ())
6308 WU (t->omp_clause.subcode.map_kind);
6309 if (state)
6310 state->write_location (*this, t->omp_clause.locus);
6312 unsigned len = omp_clause_num_ops[OMP_CLAUSE_CODE (t)];
6313 for (unsigned ix = 0; ix != len; ix++)
6314 WT (t->omp_clause.ops[ix]);
6316 break;
6318 case STATEMENT_LIST:
6319 for (tree stmt : tsi_range (t))
6320 if (stmt)
6321 WT (stmt);
6322 WT (NULL_TREE);
6323 break;
6325 case OPTIMIZATION_NODE:
6326 case TARGET_OPTION_NODE:
6327 // FIXME: Our representation for these two nodes is a cache of
6328 // the resulting set of options. Not a record of the options
6329 // that got changed by a particular attribute or pragma. Should
6330 // we record that, or should we record the diff from the command
6331 // line options? The latter seems the right behaviour, but is
6332 // (a) harder, and I guess could introduce strangeness if the
6333 // importer has set some incompatible set of optimization flags?
6334 gcc_unreachable ();
6335 break;
6337 case TREE_BINFO:
6339 WT (t->binfo.common.chain);
6340 WT (t->binfo.offset);
6341 WT (t->binfo.inheritance);
6342 WT (t->binfo.vptr_field);
6344 WT (t->binfo.vtable);
6345 WT (t->binfo.virtuals);
6346 WT (t->binfo.vtt_subvtt);
6347 WT (t->binfo.vtt_vptr);
6349 tree_vec (BINFO_BASE_ACCESSES (t));
6350 unsigned num = vec_safe_length (BINFO_BASE_ACCESSES (t));
6351 for (unsigned ix = 0; ix != num; ix++)
6352 WT (BINFO_BASE_BINFO (t, ix));
6354 break;
6356 case TREE_LIST:
6357 WT (t->list.purpose);
6358 WT (t->list.value);
6359 WT (t->list.common.chain);
6360 break;
6362 case TREE_VEC:
6363 for (unsigned ix = TREE_VEC_LENGTH (t); ix--;)
6364 WT (TREE_VEC_ELT (t, ix));
6365 /* We stash NON_DEFAULT_TEMPLATE_ARGS_COUNT on TREE_CHAIN! */
6366 gcc_checking_assert (!t->type_common.common.chain
6367 || (TREE_CODE (t->type_common.common.chain)
6368 == INTEGER_CST));
6369 WT (t->type_common.common.chain);
6370 break;
6372 /* C++-specific nodes ... */
6373 case BASELINK:
6374 WT (((lang_tree_node *)t)->baselink.binfo);
6375 WT (((lang_tree_node *)t)->baselink.functions);
6376 WT (((lang_tree_node *)t)->baselink.access_binfo);
6377 break;
6379 case CONSTRAINT_INFO:
6380 WT (((lang_tree_node *)t)->constraint_info.template_reqs);
6381 WT (((lang_tree_node *)t)->constraint_info.declarator_reqs);
6382 WT (((lang_tree_node *)t)->constraint_info.associated_constr);
6383 break;
6385 case DEFERRED_NOEXCEPT:
6386 WT (((lang_tree_node *)t)->deferred_noexcept.pattern);
6387 WT (((lang_tree_node *)t)->deferred_noexcept.args);
6388 break;
6390 case LAMBDA_EXPR:
6391 WT (((lang_tree_node *)t)->lambda_expression.capture_list);
6392 WT (((lang_tree_node *)t)->lambda_expression.this_capture);
6393 WT (((lang_tree_node *)t)->lambda_expression.extra_scope);
6394 WT (((lang_tree_node *)t)->lambda_expression.regen_info);
6395 WT (((lang_tree_node *)t)->lambda_expression.extra_args);
6396 /* pending_proxies is a parse-time thing. */
6397 gcc_assert (!((lang_tree_node *)t)->lambda_expression.pending_proxies);
6398 if (state)
6399 state->write_location
6400 (*this, ((lang_tree_node *)t)->lambda_expression.locus);
6401 if (streaming_p ())
6403 WU (((lang_tree_node *)t)->lambda_expression.default_capture_mode);
6404 WU (((lang_tree_node *)t)->lambda_expression.discriminator_scope);
6405 WU (((lang_tree_node *)t)->lambda_expression.discriminator_sig);
6407 break;
6409 case OVERLOAD:
6410 WT (((lang_tree_node *)t)->overload.function);
6411 WT (t->common.chain);
6412 break;
6414 case PTRMEM_CST:
6415 WT (((lang_tree_node *)t)->ptrmem.member);
6416 break;
6418 case STATIC_ASSERT:
6419 WT (((lang_tree_node *)t)->static_assertion.condition);
6420 WT (((lang_tree_node *)t)->static_assertion.message);
6421 if (state)
6422 state->write_location
6423 (*this, ((lang_tree_node *)t)->static_assertion.location);
6424 break;
6426 case TEMPLATE_DECL:
6427 /* Streamed with the template_decl node itself. */
6428 gcc_checking_assert
6429 (TREE_VISITED (((lang_tree_node *)t)->template_decl.arguments));
6430 gcc_checking_assert
6431 (TREE_VISITED (((lang_tree_node *)t)->template_decl.result));
6432 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (t))
6433 WT (DECL_CHAIN (t));
6434 break;
6436 case TEMPLATE_INFO:
6438 WT (((lang_tree_node *)t)->template_info.tmpl);
6439 WT (((lang_tree_node *)t)->template_info.args);
6440 WT (((lang_tree_node *)t)->template_info.partial);
6442 const auto *ac = (((lang_tree_node *)t)
6443 ->template_info.deferred_access_checks);
6444 unsigned len = vec_safe_length (ac);
6445 if (streaming_p ())
6446 u (len);
6447 if (len)
6449 for (unsigned ix = 0; ix != len; ix++)
6451 const auto &m = (*ac)[ix];
6452 WT (m.binfo);
6453 WT (m.decl);
6454 WT (m.diag_decl);
6455 if (state)
6456 state->write_location (*this, m.loc);
6460 break;
6462 case TEMPLATE_PARM_INDEX:
6463 if (streaming_p ())
6465 WU (((lang_tree_node *)t)->tpi.index);
6466 WU (((lang_tree_node *)t)->tpi.level);
6467 WU (((lang_tree_node *)t)->tpi.orig_level);
6469 WT (((lang_tree_node *)t)->tpi.decl);
6470 /* TEMPLATE_PARM_DESCENDANTS (AKA TREE_CHAIN) is an internal
6471 cache, do not stream. */
6472 break;
6474 case TRAIT_EXPR:
6475 WT (((lang_tree_node *)t)->trait_expression.type1);
6476 WT (((lang_tree_node *)t)->trait_expression.type2);
6477 if (streaming_p ())
6478 WU (((lang_tree_node *)t)->trait_expression.kind);
6479 break;
6482 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
6484 /* We want to stream the type of a expression-like nodes /after/
6485 we've streamed the operands. The type often contains (bits
6486 of the) types of the operands, and with things like decltype
6487 and noexcept in play, we really want to stream the decls
6488 defining the type before we try and stream the type on its
6489 own. Otherwise we can find ourselves trying to read in a
6490 decl, when we're already partially reading in a component of
6491 its type. And that's bad. */
6492 tree type = t->typed.type;
6493 unsigned prec = 0;
6495 switch (code)
6497 default:
6498 break;
6500 case TEMPLATE_DECL:
6501 /* We fill in the template's type separately. */
6502 type = NULL_TREE;
6503 break;
6505 case TYPE_DECL:
6506 if (DECL_ORIGINAL_TYPE (t) && t == TYPE_NAME (type))
6507 /* This is a typedef. We set its type separately. */
6508 type = NULL_TREE;
6509 break;
6511 case ENUMERAL_TYPE:
6512 if (type && !ENUM_FIXED_UNDERLYING_TYPE_P (t))
6514 /* Type is a restricted range integer type derived from the
6515 integer_types. Find the right one. */
6516 prec = TYPE_PRECISION (type);
6517 tree name = DECL_NAME (TYPE_NAME (type));
6519 for (unsigned itk = itk_none; itk--;)
6520 if (integer_types[itk]
6521 && DECL_NAME (TYPE_NAME (integer_types[itk])) == name)
6523 type = integer_types[itk];
6524 break;
6526 gcc_assert (type != t->typed.type);
6528 break;
6531 WT (type);
6532 if (prec && streaming_p ())
6533 WU (prec);
6536 if (TREE_CODE (t) == CONSTRUCTOR)
6538 unsigned len = vec_safe_length (t->constructor.elts);
6539 if (streaming_p ())
6540 WU (len);
6541 if (len)
6542 for (unsigned ix = 0; ix != len; ix++)
6544 const constructor_elt &elt = (*t->constructor.elts)[ix];
6546 WT (elt.index);
6547 WT (elt.value);
6551 #undef WT
6552 #undef WU
6555 // Streaming in a reference to a decl can cause that decl to be
6556 // TREE_USED, which is the mark_used behaviour we need most of the
6557 // time. The trees_in::unused can be incremented to inhibit this,
6558 // which is at least needed for vtables.
6560 bool
6561 trees_in::core_vals (tree t)
6563 #define RU(X) ((X) = u ())
6564 #define RUC(T,X) ((X) = T (u ()))
6565 #define RT(X) ((X) = tree_node ())
6566 #define RTU(X) ((X) = tree_node (true))
6567 tree_code code = TREE_CODE (t);
6569 /* First by tree shape. */
6570 if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
6572 RT (t->decl_minimal.name);
6573 if (!DECL_TEMPLATE_PARM_P (t))
6574 RT (t->decl_minimal.context);
6576 /* Don't zap the locus just yet, we don't record it correctly
6577 and thus lose all location information. */
6578 t->decl_minimal.locus = state->read_location (*this);
6581 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
6583 RT (t->type_common.name);
6584 RT (t->type_common.context);
6586 RT (t->type_common.main_variant);
6587 RT (t->type_common.canonical);
6589 /* type_common.next_variant is internally manipulated. */
6590 /* type_common.pointer_to, type_common.reference_to. */
6592 RU (t->type_common.precision);
6593 RU (t->type_common.contains_placeholder_bits);
6594 RUC (machine_mode, t->type_common.mode);
6595 RU (t->type_common.align);
6597 if (!RECORD_OR_UNION_CODE_P (code))
6599 RT (t->type_common.size);
6600 RT (t->type_common.size_unit);
6602 RT (t->type_common.attributes);
6604 RT (t->type_common.common.chain); /* TYPE_STUB_DECL. */
6607 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
6609 RUC (machine_mode, t->decl_common.mode);
6610 RU (t->decl_common.off_align);
6611 RU (t->decl_common.align);
6613 if (code != TEMPLATE_DECL)
6615 RT (t->decl_common.size);
6616 RT (t->decl_common.size_unit);
6619 RT (t->decl_common.attributes);
6620 RT (t->decl_common.abstract_origin);
6623 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
6625 RT (t->decl_with_vis.assembler_name);
6626 RUC (symbol_visibility, t->decl_with_vis.visibility);
6629 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
6631 if (code == ENUMERAL_TYPE)
6633 /* These fields get set even for opaque enums that lack a
6634 definition, so we stream them directly for each ENUMERAL_TYPE.
6635 We stream TYPE_VALUES as part of the definition. */
6636 RT (t->type_non_common.maxval);
6637 RT (t->type_non_common.minval);
6639 /* Records and unions hold FIELDS, VFIELD & BINFO on these
6640 things. */
6641 else if (!RECORD_OR_UNION_CODE_P (code))
6643 /* This is not clobbering TYPE_CACHED_VALUES, because this
6644 is a type that doesn't have any. */
6645 gcc_checking_assert (!TYPE_CACHED_VALUES_P (t));
6646 RT (t->type_non_common.values);
6647 RT (t->type_non_common.maxval);
6648 RT (t->type_non_common.minval);
6651 RT (t->type_non_common.lang_1);
6654 if (CODE_CONTAINS_STRUCT (code, TS_EXP))
6656 t->exp.locus = state->read_location (*this);
6658 bool vl = TREE_CODE_CLASS (code) == tcc_vl_exp;
6659 for (unsigned limit = (vl ? VL_EXP_OPERAND_LENGTH (t)
6660 : TREE_OPERAND_LENGTH (t)),
6661 ix = unsigned (vl); ix != limit; ix++)
6662 RTU (TREE_OPERAND (t, ix));
6665 /* Then by CODE. Special cases and/or 1:1 tree shape
6666 correspondance. */
6667 switch (code)
6669 default:
6670 break;
6672 case ARGUMENT_PACK_SELECT:
6673 case DEFERRED_PARSE:
6674 case IDENTIFIER_NODE:
6675 case BINDING_VECTOR:
6676 case SSA_NAME:
6677 case TRANSLATION_UNIT_DECL:
6678 case USERDEF_LITERAL:
6679 return false; /* Should never meet. */
6681 /* Constants. */
6682 case COMPLEX_CST:
6683 RT (TREE_REALPART (t));
6684 RT (TREE_IMAGPART (t));
6685 break;
6687 case FIXED_CST:
6688 /* Not suported in C++. */
6689 return false;
6691 case INTEGER_CST:
6693 unsigned num = TREE_INT_CST_EXT_NUNITS (t);
6694 for (unsigned ix = 0; ix != num; ix++)
6695 TREE_INT_CST_ELT (t, ix) = wu ();
6697 break;
6699 case POLY_INT_CST:
6700 for (unsigned ix = 0; ix != NUM_POLY_INT_COEFFS; ix++)
6701 RT (POLY_INT_CST_COEFF (t, ix));
6702 break;
6704 case REAL_CST:
6705 if (const void *bytes = buf (sizeof (real_value)))
6706 memcpy (TREE_REAL_CST_PTR (t), bytes, sizeof (real_value));
6707 break;
6709 case STRING_CST:
6710 /* Streamed during start. */
6711 break;
6713 case VECTOR_CST:
6714 for (unsigned ix = vector_cst_encoded_nelts (t); ix--;)
6715 RT (VECTOR_CST_ENCODED_ELT (t, ix));
6716 break;
6718 /* Decls. */
6719 case VAR_DECL:
6720 if (DECL_CONTEXT (t)
6721 && TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
6722 break;
6723 /* FALLTHROUGH */
6725 case RESULT_DECL:
6726 case PARM_DECL:
6727 if (DECL_HAS_VALUE_EXPR_P (t))
6729 /* The DECL_VALUE hash table is a cache, thus if we're
6730 reading a duplicate (which we end up discarding), the
6731 value expr will also be cleaned up at the next gc. */
6732 tree val = tree_node ();
6733 SET_DECL_VALUE_EXPR (t, val);
6735 /* FALLTHROUGH */
6737 case CONST_DECL:
6738 case IMPORTED_DECL:
6739 RT (t->decl_common.initial);
6740 break;
6742 case FIELD_DECL:
6743 RT (t->field_decl.offset);
6744 RT (t->field_decl.bit_field_type);
6745 RT (t->field_decl.qualifier);
6746 RT (t->field_decl.bit_offset);
6747 RT (t->field_decl.fcontext);
6748 RT (t->decl_common.initial);
6749 break;
6751 case LABEL_DECL:
6752 RU (t->label_decl.label_decl_uid);
6753 RU (t->label_decl.eh_landing_pad_nr);
6754 break;
6756 case FUNCTION_DECL:
6758 unsigned bltin = u ();
6759 t->function_decl.built_in_class = built_in_class (bltin);
6760 if (bltin != NOT_BUILT_IN)
6762 bltin = u ();
6763 DECL_UNCHECKED_FUNCTION_CODE (t) = built_in_function (bltin);
6766 RT (t->function_decl.personality);
6767 RT (t->function_decl.function_specific_target);
6768 RT (t->function_decl.function_specific_optimization);
6769 RT (t->function_decl.vindex);
6771 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
6773 tree spec;
6774 RT (spec);
6775 store_explicit_specifier (t, spec);
6778 break;
6780 case USING_DECL:
6781 /* USING_DECL_DECLS */
6782 RT (t->decl_common.initial);
6783 /* FALLTHROUGH */
6785 case TYPE_DECL:
6786 /* USING_DECL: USING_DECL_SCOPE */
6787 /* TYPE_DECL: DECL_ORIGINAL_TYPE */
6788 RT (t->decl_non_common.result);
6789 break;
6791 /* Miscellaneous common nodes. */
6792 case BLOCK:
6793 t->block.locus = state->read_location (*this);
6794 t->block.end_locus = state->read_location (*this);
6796 for (tree *chain = &t->block.vars;;)
6797 if (tree decl = tree_node ())
6799 /* For a deduplicated local type or enumerator, chain the
6800 duplicate decl instead of the canonical in-TU decl. Seeing
6801 a duplicate here means the containing function whose body
6802 we're streaming in is a duplicate too, so we'll end up
6803 discarding this BLOCK (and the rest of the duplicate function
6804 body) anyway. */
6805 decl = maybe_duplicate (decl);
6807 if (!DECL_P (decl) || DECL_CHAIN (decl))
6809 set_overrun ();
6810 break;
6812 *chain = decl;
6813 chain = &DECL_CHAIN (decl);
6815 else
6816 break;
6818 /* nonlocalized_vars is middle-end. */
6819 RT (t->block.subblocks);
6820 RT (t->block.supercontext);
6821 RT (t->block.abstract_origin);
6822 /* fragment_origin, fragment_chain are middle-end. */
6823 RT (t->block.chain);
6824 /* nonlocalized_vars, block_num, die are middle endy/debug
6825 things. */
6826 break;
6828 case CALL_EXPR:
6829 RUC (internal_fn, t->base.u.ifn);
6830 break;
6832 case CONSTRUCTOR:
6833 // Streamed after the node's type.
6834 break;
6836 case OMP_CLAUSE:
6838 RU (t->omp_clause.subcode.map_kind);
6839 t->omp_clause.locus = state->read_location (*this);
6841 unsigned len = omp_clause_num_ops[OMP_CLAUSE_CODE (t)];
6842 for (unsigned ix = 0; ix != len; ix++)
6843 RT (t->omp_clause.ops[ix]);
6845 break;
6847 case STATEMENT_LIST:
6849 tree_stmt_iterator iter = tsi_start (t);
6850 for (tree stmt; RT (stmt);)
6851 tsi_link_after (&iter, stmt, TSI_CONTINUE_LINKING);
6853 break;
6855 case OPTIMIZATION_NODE:
6856 case TARGET_OPTION_NODE:
6857 /* Not yet implemented, see trees_out::core_vals. */
6858 gcc_unreachable ();
6859 break;
6861 case TREE_BINFO:
6862 RT (t->binfo.common.chain);
6863 RT (t->binfo.offset);
6864 RT (t->binfo.inheritance);
6865 RT (t->binfo.vptr_field);
6867 /* Do not mark the vtables as USED in the address expressions
6868 here. */
6869 unused++;
6870 RT (t->binfo.vtable);
6871 RT (t->binfo.virtuals);
6872 RT (t->binfo.vtt_subvtt);
6873 RT (t->binfo.vtt_vptr);
6874 unused--;
6876 BINFO_BASE_ACCESSES (t) = tree_vec ();
6877 if (!get_overrun ())
6879 unsigned num = vec_safe_length (BINFO_BASE_ACCESSES (t));
6880 for (unsigned ix = 0; ix != num; ix++)
6881 BINFO_BASE_APPEND (t, tree_node ());
6883 break;
6885 case TREE_LIST:
6886 RT (t->list.purpose);
6887 RT (t->list.value);
6888 RT (t->list.common.chain);
6889 break;
6891 case TREE_VEC:
6892 for (unsigned ix = TREE_VEC_LENGTH (t); ix--;)
6893 RT (TREE_VEC_ELT (t, ix));
6894 RT (t->type_common.common.chain);
6895 break;
6897 /* C++-specific nodes ... */
6898 case BASELINK:
6899 RT (((lang_tree_node *)t)->baselink.binfo);
6900 RTU (((lang_tree_node *)t)->baselink.functions);
6901 RT (((lang_tree_node *)t)->baselink.access_binfo);
6902 break;
6904 case CONSTRAINT_INFO:
6905 RT (((lang_tree_node *)t)->constraint_info.template_reqs);
6906 RT (((lang_tree_node *)t)->constraint_info.declarator_reqs);
6907 RT (((lang_tree_node *)t)->constraint_info.associated_constr);
6908 break;
6910 case DEFERRED_NOEXCEPT:
6911 RT (((lang_tree_node *)t)->deferred_noexcept.pattern);
6912 RT (((lang_tree_node *)t)->deferred_noexcept.args);
6913 break;
6915 case LAMBDA_EXPR:
6916 RT (((lang_tree_node *)t)->lambda_expression.capture_list);
6917 RT (((lang_tree_node *)t)->lambda_expression.this_capture);
6918 RT (((lang_tree_node *)t)->lambda_expression.extra_scope);
6919 RT (((lang_tree_node *)t)->lambda_expression.regen_info);
6920 RT (((lang_tree_node *)t)->lambda_expression.extra_args);
6921 /* lambda_expression.pending_proxies is NULL */
6922 ((lang_tree_node *)t)->lambda_expression.locus
6923 = state->read_location (*this);
6924 RUC (cp_lambda_default_capture_mode_type,
6925 ((lang_tree_node *)t)->lambda_expression.default_capture_mode);
6926 RU (((lang_tree_node *)t)->lambda_expression.discriminator_scope);
6927 RU (((lang_tree_node *)t)->lambda_expression.discriminator_sig);
6928 break;
6930 case OVERLOAD:
6931 RT (((lang_tree_node *)t)->overload.function);
6932 RT (t->common.chain);
6933 break;
6935 case PTRMEM_CST:
6936 RT (((lang_tree_node *)t)->ptrmem.member);
6937 break;
6939 case STATIC_ASSERT:
6940 RT (((lang_tree_node *)t)->static_assertion.condition);
6941 RT (((lang_tree_node *)t)->static_assertion.message);
6942 ((lang_tree_node *)t)->static_assertion.location
6943 = state->read_location (*this);
6944 break;
6946 case TEMPLATE_DECL:
6947 /* Streamed when reading the raw template decl itself. */
6948 gcc_assert (((lang_tree_node *)t)->template_decl.arguments);
6949 gcc_assert (((lang_tree_node *)t)->template_decl.result);
6950 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (t))
6951 RT (DECL_CHAIN (t));
6952 break;
6954 case TEMPLATE_INFO:
6955 RT (((lang_tree_node *)t)->template_info.tmpl);
6956 RT (((lang_tree_node *)t)->template_info.args);
6957 RT (((lang_tree_node *)t)->template_info.partial);
6958 if (unsigned len = u ())
6960 auto &ac = (((lang_tree_node *)t)
6961 ->template_info.deferred_access_checks);
6962 vec_alloc (ac, len);
6963 for (unsigned ix = 0; ix != len; ix++)
6965 deferred_access_check m;
6967 RT (m.binfo);
6968 RT (m.decl);
6969 RT (m.diag_decl);
6970 m.loc = state->read_location (*this);
6971 ac->quick_push (m);
6974 break;
6976 case TEMPLATE_PARM_INDEX:
6977 RU (((lang_tree_node *)t)->tpi.index);
6978 RU (((lang_tree_node *)t)->tpi.level);
6979 RU (((lang_tree_node *)t)->tpi.orig_level);
6980 RT (((lang_tree_node *)t)->tpi.decl);
6981 break;
6983 case TRAIT_EXPR:
6984 RT (((lang_tree_node *)t)->trait_expression.type1);
6985 RT (((lang_tree_node *)t)->trait_expression.type2);
6986 RUC (cp_trait_kind, ((lang_tree_node *)t)->trait_expression.kind);
6987 break;
6990 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
6992 tree type = tree_node ();
6994 if (type && code == ENUMERAL_TYPE && !ENUM_FIXED_UNDERLYING_TYPE_P (t))
6996 unsigned precision = u ();
6998 type = build_distinct_type_copy (type);
6999 TYPE_PRECISION (type) = precision;
7000 set_min_and_max_values_for_integral_type (type, precision,
7001 TYPE_SIGN (type));
7004 if (code != TEMPLATE_DECL)
7005 t->typed.type = type;
7008 if (TREE_CODE (t) == CONSTRUCTOR)
7009 if (unsigned len = u ())
7011 vec_alloc (t->constructor.elts, len);
7012 for (unsigned ix = 0; ix != len; ix++)
7014 constructor_elt elt;
7016 RT (elt.index);
7017 RTU (elt.value);
7018 t->constructor.elts->quick_push (elt);
7022 #undef RT
7023 #undef RM
7024 #undef RU
7025 return !get_overrun ();
7028 void
7029 trees_out::lang_decl_vals (tree t)
7031 const struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
7032 #define WU(X) (u (X))
7033 #define WT(X) (tree_node (X))
7034 /* Module index already written. */
7035 switch (lang->u.base.selector)
7037 default:
7038 gcc_unreachable ();
7040 case lds_fn: /* lang_decl_fn. */
7041 if (streaming_p ())
7043 if (DECL_NAME (t) && IDENTIFIER_OVL_OP_P (DECL_NAME (t)))
7044 WU (lang->u.fn.ovl_op_code);
7047 if (DECL_CLASS_SCOPE_P (t))
7048 WT (lang->u.fn.context);
7050 if (lang->u.fn.thunk_p)
7052 /* The thunked-to function. */
7053 WT (lang->u.fn.befriending_classes);
7054 if (streaming_p ())
7055 wi (lang->u.fn.u5.fixed_offset);
7057 else if (decl_tls_wrapper_p (t))
7058 /* The wrapped variable. */
7059 WT (lang->u.fn.befriending_classes);
7060 else
7061 WT (lang->u.fn.u5.cloned_function);
7063 if (FNDECL_USED_AUTO (t))
7064 WT (lang->u.fn.u.saved_auto_return_type);
7066 goto lds_min;
7068 case lds_decomp: /* lang_decl_decomp. */
7069 WT (lang->u.decomp.base);
7070 goto lds_min;
7072 case lds_min: /* lang_decl_min. */
7073 lds_min:
7074 WT (lang->u.min.template_info);
7076 tree access = lang->u.min.access;
7078 /* DECL_ACCESS needs to be maintained by the definition of the
7079 (derived) class that changes the access. The other users
7080 of DECL_ACCESS need to write it here. */
7081 if (!DECL_THUNK_P (t)
7082 && (DECL_CONTEXT (t) && TYPE_P (DECL_CONTEXT (t))))
7083 access = NULL_TREE;
7085 WT (access);
7087 break;
7089 case lds_ns: /* lang_decl_ns. */
7090 break;
7092 case lds_parm: /* lang_decl_parm. */
7093 if (streaming_p ())
7095 WU (lang->u.parm.level);
7096 WU (lang->u.parm.index);
7098 break;
7100 #undef WU
7101 #undef WT
7104 bool
7105 trees_in::lang_decl_vals (tree t)
7107 struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
7108 #define RU(X) ((X) = u ())
7109 #define RT(X) ((X) = tree_node ())
7111 /* Module index already read. */
7112 switch (lang->u.base.selector)
7114 default:
7115 gcc_unreachable ();
7117 case lds_fn: /* lang_decl_fn. */
7118 if (DECL_NAME (t) && IDENTIFIER_OVL_OP_P (DECL_NAME (t)))
7120 unsigned code = u ();
7122 /* Check consistency. */
7123 if (code >= OVL_OP_MAX
7124 || (ovl_op_info[IDENTIFIER_ASSIGN_OP_P (DECL_NAME (t))][code]
7125 .ovl_op_code) == OVL_OP_ERROR_MARK)
7126 set_overrun ();
7127 else
7128 lang->u.fn.ovl_op_code = code;
7131 if (DECL_CLASS_SCOPE_P (t))
7132 RT (lang->u.fn.context);
7134 if (lang->u.fn.thunk_p)
7136 RT (lang->u.fn.befriending_classes);
7137 lang->u.fn.u5.fixed_offset = wi ();
7139 else if (decl_tls_wrapper_p (t))
7140 RT (lang->u.fn.befriending_classes);
7141 else
7142 RT (lang->u.fn.u5.cloned_function);
7144 if (FNDECL_USED_AUTO (t))
7145 RT (lang->u.fn.u.saved_auto_return_type);
7146 goto lds_min;
7148 case lds_decomp: /* lang_decl_decomp. */
7149 RT (lang->u.decomp.base);
7150 goto lds_min;
7152 case lds_min: /* lang_decl_min. */
7153 lds_min:
7154 RT (lang->u.min.template_info);
7155 RT (lang->u.min.access);
7156 break;
7158 case lds_ns: /* lang_decl_ns. */
7159 break;
7161 case lds_parm: /* lang_decl_parm. */
7162 RU (lang->u.parm.level);
7163 RU (lang->u.parm.index);
7164 break;
7166 #undef RU
7167 #undef RT
7168 return !get_overrun ();
7171 /* Most of the value contents of lang_type is streamed in
7172 define_class. */
7174 void
7175 trees_out::lang_type_vals (tree t)
7177 const struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
7178 #define WU(X) (u (X))
7179 #define WT(X) (tree_node (X))
7180 if (streaming_p ())
7181 WU (lang->align);
7182 #undef WU
7183 #undef WT
7186 bool
7187 trees_in::lang_type_vals (tree t)
7189 struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
7190 #define RU(X) ((X) = u ())
7191 #define RT(X) ((X) = tree_node ())
7192 RU (lang->align);
7193 #undef RU
7194 #undef RT
7195 return !get_overrun ();
7198 /* Write out the bools of T, including information about any
7199 LANG_SPECIFIC information. Including allocation of any lang
7200 specific object. */
7202 void
7203 trees_out::tree_node_bools (tree t)
7205 gcc_checking_assert (streaming_p ());
7207 /* We should never stream a namespace. */
7208 gcc_checking_assert (TREE_CODE (t) != NAMESPACE_DECL
7209 || DECL_NAMESPACE_ALIAS (t));
7211 bits_out bits = stream_bits ();
7212 core_bools (t, bits);
7214 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7216 case tcc_declaration:
7218 bool specific = DECL_LANG_SPECIFIC (t) != NULL;
7219 bits.b (specific);
7220 if (specific && VAR_P (t))
7221 bits.b (DECL_DECOMPOSITION_P (t));
7222 if (specific)
7223 lang_decl_bools (t, bits);
7225 break;
7227 case tcc_type:
7229 bool specific = (TYPE_MAIN_VARIANT (t) == t
7230 && TYPE_LANG_SPECIFIC (t) != NULL);
7231 gcc_assert (TYPE_LANG_SPECIFIC (t)
7232 == TYPE_LANG_SPECIFIC (TYPE_MAIN_VARIANT (t)));
7234 bits.b (specific);
7235 if (specific)
7236 lang_type_bools (t, bits);
7238 break;
7240 default:
7241 break;
7244 bits.bflush ();
7247 bool
7248 trees_in::tree_node_bools (tree t)
7250 bits_in bits = stream_bits ();
7251 bool ok = core_bools (t, bits);
7253 if (ok)
7254 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7256 case tcc_declaration:
7257 if (bits.b ())
7259 bool decomp = VAR_P (t) && bits.b ();
7261 ok = maybe_add_lang_decl_raw (t, decomp);
7262 if (ok)
7263 ok = lang_decl_bools (t, bits);
7265 break;
7267 case tcc_type:
7268 if (bits.b ())
7270 ok = maybe_add_lang_type_raw (t);
7271 if (ok)
7272 ok = lang_type_bools (t, bits);
7274 break;
7276 default:
7277 break;
7280 bits.bflush ();
7281 if (!ok || get_overrun ())
7282 return false;
7284 return true;
7288 /* Write out the lang-specifc vals of node T. */
7290 void
7291 trees_out::lang_vals (tree t)
7293 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7295 case tcc_declaration:
7296 if (DECL_LANG_SPECIFIC (t))
7297 lang_decl_vals (t);
7298 break;
7300 case tcc_type:
7301 if (TYPE_MAIN_VARIANT (t) == t && TYPE_LANG_SPECIFIC (t))
7302 lang_type_vals (t);
7303 break;
7305 default:
7306 break;
7310 bool
7311 trees_in::lang_vals (tree t)
7313 bool ok = true;
7315 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7317 case tcc_declaration:
7318 if (DECL_LANG_SPECIFIC (t))
7319 ok = lang_decl_vals (t);
7320 break;
7322 case tcc_type:
7323 if (TYPE_LANG_SPECIFIC (t))
7324 ok = lang_type_vals (t);
7325 else
7326 TYPE_LANG_SPECIFIC (t) = TYPE_LANG_SPECIFIC (TYPE_MAIN_VARIANT (t));
7327 break;
7329 default:
7330 break;
7333 return ok;
7336 /* Write out the value fields of node T. */
7338 void
7339 trees_out::tree_node_vals (tree t)
7341 core_vals (t);
7342 lang_vals (t);
7345 bool
7346 trees_in::tree_node_vals (tree t)
7348 bool ok = core_vals (t);
7349 if (ok)
7350 ok = lang_vals (t);
7352 return ok;
7356 /* If T is a back reference, fixed reference or NULL, write out its
7357 code and return WK_none. Otherwise return WK_value if we must write
7358 by value, or WK_normal otherwise. */
7360 walk_kind
7361 trees_out::ref_node (tree t)
7363 if (!t)
7365 if (streaming_p ())
7367 /* NULL_TREE -> tt_null. */
7368 null_count++;
7369 i (tt_null);
7371 return WK_none;
7374 if (!TREE_VISITED (t))
7375 return WK_normal;
7377 /* An already-visited tree. It must be in the map. */
7378 int val = get_tag (t);
7380 if (val == tag_value)
7381 /* An entry we should walk into. */
7382 return WK_value;
7384 const char *kind;
7386 if (val <= tag_backref)
7388 /* Back reference -> -ve number */
7389 if (streaming_p ())
7390 i (val);
7391 kind = "backref";
7393 else if (val >= tag_fixed)
7395 /* Fixed reference -> tt_fixed */
7396 val -= tag_fixed;
7397 if (streaming_p ())
7398 i (tt_fixed), u (val);
7399 kind = "fixed";
7402 if (streaming_p ())
7404 back_ref_count++;
7405 dump (dumper::TREE)
7406 && dump ("Wrote %s:%d %C:%N%S", kind, val, TREE_CODE (t), t, t);
7408 return WK_none;
7411 tree
7412 trees_in::back_ref (int tag)
7414 tree res = NULL_TREE;
7416 if (tag < 0 && unsigned (~tag) < back_refs.length ())
7417 res = back_refs[~tag];
7419 if (!res
7420 /* Checking TREE_CODE is a dereference, so we know this is not a
7421 wild pointer. Checking the code provides evidence we've not
7422 corrupted something. */
7423 || TREE_CODE (res) >= MAX_TREE_CODES)
7424 set_overrun ();
7425 else
7426 dump (dumper::TREE) && dump ("Read backref:%d found %C:%N%S", tag,
7427 TREE_CODE (res), res, res);
7428 return res;
7431 unsigned
7432 trees_out::add_indirect_tpl_parms (tree parms)
7434 unsigned len = 0;
7435 for (; parms; parms = TREE_CHAIN (parms), len++)
7437 if (TREE_VISITED (parms))
7438 break;
7440 int tag = insert (parms);
7441 if (streaming_p ())
7442 dump (dumper::TREE)
7443 && dump ("Indirect:%d template's parameter %u %C:%N",
7444 tag, len, TREE_CODE (parms), parms);
7447 if (streaming_p ())
7448 u (len);
7450 return len;
7453 unsigned
7454 trees_in::add_indirect_tpl_parms (tree parms)
7456 unsigned len = u ();
7457 for (unsigned ix = 0; ix != len; parms = TREE_CHAIN (parms), ix++)
7459 int tag = insert (parms);
7460 dump (dumper::TREE)
7461 && dump ("Indirect:%d template's parameter %u %C:%N",
7462 tag, ix, TREE_CODE (parms), parms);
7465 return len;
7468 /* We've just found DECL by name. Insert nodes that come with it, but
7469 cannot be found by name, so we'll not accidentally walk into them. */
7471 void
7472 trees_out::add_indirects (tree decl)
7474 unsigned count = 0;
7476 // FIXME:OPTIMIZATION We'll eventually want default fn parms of
7477 // templates and perhaps default template parms too. The former can
7478 // be referenced from instantiations (as they are lazily
7479 // instantiated). Also (deferred?) exception specifications of
7480 // templates. See the note about PARM_DECLs in trees_out::decl_node.
7481 tree inner = decl;
7482 if (TREE_CODE (decl) == TEMPLATE_DECL)
7484 count += add_indirect_tpl_parms (DECL_TEMPLATE_PARMS (decl));
7486 inner = DECL_TEMPLATE_RESULT (decl);
7487 int tag = insert (inner);
7488 if (streaming_p ())
7489 dump (dumper::TREE)
7490 && dump ("Indirect:%d template's result %C:%N",
7491 tag, TREE_CODE (inner), inner);
7492 count++;
7495 if (TREE_CODE (inner) == TYPE_DECL)
7497 /* Make sure the type is in the map too. Otherwise we get
7498 different RECORD_TYPEs for the same type, and things go
7499 south. */
7500 tree type = TREE_TYPE (inner);
7501 gcc_checking_assert (DECL_ORIGINAL_TYPE (inner)
7502 || TYPE_NAME (type) == inner);
7503 int tag = insert (type);
7504 if (streaming_p ())
7505 dump (dumper::TREE) && dump ("Indirect:%d decl's type %C:%N", tag,
7506 TREE_CODE (type), type);
7507 count++;
7510 if (streaming_p ())
7512 u (count);
7513 dump (dumper::TREE) && dump ("Inserted %u indirects", count);
7517 bool
7518 trees_in::add_indirects (tree decl)
7520 unsigned count = 0;
7522 tree inner = decl;
7523 if (TREE_CODE (inner) == TEMPLATE_DECL)
7525 count += add_indirect_tpl_parms (DECL_TEMPLATE_PARMS (decl));
7527 inner = DECL_TEMPLATE_RESULT (decl);
7528 int tag = insert (inner);
7529 dump (dumper::TREE)
7530 && dump ("Indirect:%d templates's result %C:%N", tag,
7531 TREE_CODE (inner), inner);
7532 count++;
7535 if (TREE_CODE (inner) == TYPE_DECL)
7537 tree type = TREE_TYPE (inner);
7538 gcc_checking_assert (DECL_ORIGINAL_TYPE (inner)
7539 || TYPE_NAME (type) == inner);
7540 int tag = insert (type);
7541 dump (dumper::TREE)
7542 && dump ("Indirect:%d decl's type %C:%N", tag, TREE_CODE (type), type);
7543 count++;
7546 dump (dumper::TREE) && dump ("Inserted %u indirects", count);
7547 return count == u ();
7550 /* Stream a template parameter. There are 4.5 kinds of parameter:
7551 a) Template - TEMPLATE_DECL->TYPE_DECL->TEMPLATE_TEMPLATE_PARM
7552 TEMPLATE_TYPE_PARM_INDEX TPI
7553 b) Type - TYPE_DECL->TEMPLATE_TYPE_PARM TEMPLATE_TYPE_PARM_INDEX TPI
7554 c.1) NonTYPE - PARM_DECL DECL_INITIAL TPI We meet this first
7555 c.2) NonTYPE - CONST_DECL DECL_INITIAL Same TPI
7556 d) BoundTemplate - TYPE_DECL->BOUND_TEMPLATE_TEMPLATE_PARM
7557 TEMPLATE_TYPE_PARM_INDEX->TPI
7558 TEMPLATE_TEMPLATE_PARM_INFO->TEMPLATE_INFO
7560 All of these point to a TEMPLATE_PARM_INDEX, and #B also has a TEMPLATE_INFO
7563 void
7564 trees_out::tpl_parm_value (tree parm)
7566 gcc_checking_assert (DECL_P (parm) && DECL_TEMPLATE_PARM_P (parm));
7568 int parm_tag = insert (parm);
7569 if (streaming_p ())
7571 i (tt_tpl_parm);
7572 dump (dumper::TREE) && dump ("Writing template parm:%d %C:%N",
7573 parm_tag, TREE_CODE (parm), parm);
7574 start (parm);
7575 tree_node_bools (parm);
7578 tree inner = parm;
7579 if (TREE_CODE (inner) == TEMPLATE_DECL)
7581 inner = DECL_TEMPLATE_RESULT (inner);
7582 int inner_tag = insert (inner);
7583 if (streaming_p ())
7585 dump (dumper::TREE) && dump ("Writing inner template parm:%d %C:%N",
7586 inner_tag, TREE_CODE (inner), inner);
7587 start (inner);
7588 tree_node_bools (inner);
7592 tree type = NULL_TREE;
7593 if (TREE_CODE (inner) == TYPE_DECL)
7595 type = TREE_TYPE (inner);
7596 int type_tag = insert (type);
7597 if (streaming_p ())
7599 dump (dumper::TREE) && dump ("Writing template parm type:%d %C:%N",
7600 type_tag, TREE_CODE (type), type);
7601 start (type);
7602 tree_node_bools (type);
7606 if (inner != parm)
7608 /* This is a template-template parameter. */
7609 unsigned tpl_levels = 0;
7610 tpl_header (parm, &tpl_levels);
7611 tpl_parms_fini (parm, tpl_levels);
7614 tree_node_vals (parm);
7615 if (inner != parm)
7616 tree_node_vals (inner);
7617 if (type)
7619 tree_node_vals (type);
7620 if (DECL_NAME (inner) == auto_identifier
7621 || DECL_NAME (inner) == decltype_auto_identifier)
7623 /* Placeholder auto. */
7624 tree_node (DECL_INITIAL (inner));
7625 tree_node (DECL_SIZE_UNIT (inner));
7629 if (streaming_p ())
7630 dump (dumper::TREE) && dump ("Wrote template parm:%d %C:%N",
7631 parm_tag, TREE_CODE (parm), parm);
7634 tree
7635 trees_in::tpl_parm_value ()
7637 tree parm = start ();
7638 if (!parm || !tree_node_bools (parm))
7639 return NULL_TREE;
7641 int parm_tag = insert (parm);
7642 dump (dumper::TREE) && dump ("Reading template parm:%d %C:%N",
7643 parm_tag, TREE_CODE (parm), parm);
7645 tree inner = parm;
7646 if (TREE_CODE (inner) == TEMPLATE_DECL)
7648 inner = start ();
7649 if (!inner || !tree_node_bools (inner))
7650 return NULL_TREE;
7651 int inner_tag = insert (inner);
7652 dump (dumper::TREE) && dump ("Reading inner template parm:%d %C:%N",
7653 inner_tag, TREE_CODE (inner), inner);
7654 DECL_TEMPLATE_RESULT (parm) = inner;
7657 tree type = NULL_TREE;
7658 if (TREE_CODE (inner) == TYPE_DECL)
7660 type = start ();
7661 if (!type || !tree_node_bools (type))
7662 return NULL_TREE;
7663 int type_tag = insert (type);
7664 dump (dumper::TREE) && dump ("Reading template parm type:%d %C:%N",
7665 type_tag, TREE_CODE (type), type);
7667 TREE_TYPE (inner) = TREE_TYPE (parm) = type;
7668 TYPE_NAME (type) = parm;
7671 if (inner != parm)
7673 /* A template template parameter. */
7674 unsigned tpl_levels = 0;
7675 tpl_header (parm, &tpl_levels);
7676 tpl_parms_fini (parm, tpl_levels);
7679 tree_node_vals (parm);
7680 if (inner != parm)
7681 tree_node_vals (inner);
7682 if (type)
7684 tree_node_vals (type);
7685 if (DECL_NAME (inner) == auto_identifier
7686 || DECL_NAME (inner) == decltype_auto_identifier)
7688 /* Placeholder auto. */
7689 DECL_INITIAL (inner) = tree_node ();
7690 DECL_SIZE_UNIT (inner) = tree_node ();
7692 if (TYPE_CANONICAL (type))
7694 gcc_checking_assert (TYPE_CANONICAL (type) == type);
7695 TYPE_CANONICAL (type) = canonical_type_parameter (type);
7699 dump (dumper::TREE) && dump ("Read template parm:%d %C:%N",
7700 parm_tag, TREE_CODE (parm), parm);
7702 return parm;
7705 void
7706 trees_out::install_entity (tree decl, depset *dep)
7708 gcc_checking_assert (streaming_p ());
7710 /* Write the entity index, so we can insert it as soon as we
7711 know this is new. */
7712 u (dep ? dep->cluster + 1 : 0);
7713 if (CHECKING_P && dep)
7715 /* Add it to the entity map, such that we can tell it is
7716 part of us. */
7717 bool existed;
7718 unsigned *slot = &entity_map->get_or_insert
7719 (DECL_UID (decl), &existed);
7720 if (existed)
7721 /* If it existed, it should match. */
7722 gcc_checking_assert (decl == (*entity_ary)[*slot]);
7723 *slot = ~dep->cluster;
7727 bool
7728 trees_in::install_entity (tree decl)
7730 unsigned entity_index = u ();
7731 if (!entity_index)
7732 return false;
7734 if (entity_index > state->entity_num)
7736 set_overrun ();
7737 return false;
7740 /* Insert the real decl into the entity ary. */
7741 unsigned ident = state->entity_lwm + entity_index - 1;
7742 (*entity_ary)[ident] = decl;
7744 /* And into the entity map, if it's not already there. */
7745 tree not_tmpl = STRIP_TEMPLATE (decl);
7746 if (!DECL_LANG_SPECIFIC (not_tmpl)
7747 || !DECL_MODULE_ENTITY_P (not_tmpl))
7749 retrofit_lang_decl (not_tmpl);
7750 DECL_MODULE_ENTITY_P (not_tmpl) = true;
7752 /* Insert into the entity hash (it cannot already be there). */
7753 bool existed;
7754 unsigned &slot = entity_map->get_or_insert (DECL_UID (decl), &existed);
7755 gcc_checking_assert (!existed);
7756 slot = ident;
7758 else if (state->is_partition ())
7760 /* The decl is already in the entity map, but we see it again now from a
7761 partition: we want to overwrite if the original decl wasn't also from
7762 a (possibly different) partition. Otherwise, for things like template
7763 instantiations, make_dependency might not realise that this is also
7764 provided from a partition and should be considered part of this module
7765 (and thus always emitted into the primary interface's CMI). */
7766 unsigned *slot = entity_map->get (DECL_UID (decl));
7767 module_state *imp = import_entity_module (*slot);
7768 if (!imp->is_partition ())
7769 *slot = ident;
7772 return true;
7775 static bool has_definition (tree decl);
7777 /* DECL is a decl node that must be written by value. DEP is the
7778 decl's depset. */
7780 void
7781 trees_out::decl_value (tree decl, depset *dep)
7783 /* We should not be writing clones or template parms. */
7784 gcc_checking_assert (DECL_P (decl)
7785 && !DECL_CLONED_FUNCTION_P (decl)
7786 && !DECL_TEMPLATE_PARM_P (decl));
7788 /* We should never be writing non-typedef ptrmemfuncs by value. */
7789 gcc_checking_assert (TREE_CODE (decl) != TYPE_DECL
7790 || DECL_ORIGINAL_TYPE (decl)
7791 || !TYPE_PTRMEMFUNC_P (TREE_TYPE (decl)));
7793 merge_kind mk = get_merge_kind (decl, dep);
7795 if (CHECKING_P)
7797 /* Never start in the middle of a template. */
7798 int use_tpl = -1;
7799 if (tree ti = node_template_info (decl, use_tpl))
7800 gcc_checking_assert (TREE_CODE (TI_TEMPLATE (ti)) == OVERLOAD
7801 || TREE_CODE (TI_TEMPLATE (ti)) == FIELD_DECL
7802 || (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti))
7803 != decl));
7806 if (streaming_p ())
7808 /* A new node -> tt_decl. */
7809 decl_val_count++;
7810 i (tt_decl);
7811 u (mk);
7812 start (decl);
7814 if (mk != MK_unique)
7816 bits_out bits = stream_bits ();
7817 if (!(mk & MK_template_mask) && !state->is_header ())
7819 /* Tell the importer whether this is a global module entity,
7820 or a module entity. */
7821 tree o = get_originating_module_decl (decl);
7822 bool is_attached = false;
7824 tree not_tmpl = STRIP_TEMPLATE (o);
7825 if (DECL_LANG_SPECIFIC (not_tmpl)
7826 && DECL_MODULE_ATTACH_P (not_tmpl))
7827 is_attached = true;
7829 /* But don't consider imported temploid friends as attached,
7830 since importers will need to merge this decl even if it was
7831 attached to a different module. */
7832 if (imported_temploid_friends->get (decl))
7833 is_attached = false;
7835 bits.b (is_attached);
7837 bits.b (dep && dep->has_defn ());
7839 tree_node_bools (decl);
7842 int tag = insert (decl, WK_value);
7843 if (streaming_p ())
7844 dump (dumper::TREE)
7845 && dump ("Writing %s:%d %C:%N%S", merge_kind_name[mk], tag,
7846 TREE_CODE (decl), decl, decl);
7848 tree inner = decl;
7849 int inner_tag = 0;
7850 if (TREE_CODE (decl) == TEMPLATE_DECL)
7852 inner = DECL_TEMPLATE_RESULT (decl);
7853 inner_tag = insert (inner, WK_value);
7855 if (streaming_p ())
7857 int code = TREE_CODE (inner);
7858 u (code);
7859 start (inner, true);
7860 tree_node_bools (inner);
7861 dump (dumper::TREE)
7862 && dump ("Writing %s:%d %C:%N%S", merge_kind_name[mk], inner_tag,
7863 TREE_CODE (inner), inner, inner);
7867 tree type = NULL_TREE;
7868 int type_tag = 0;
7869 tree stub_decl = NULL_TREE;
7870 int stub_tag = 0;
7871 if (TREE_CODE (inner) == TYPE_DECL)
7873 type = TREE_TYPE (inner);
7874 bool has_type = (type == TYPE_MAIN_VARIANT (type)
7875 && TYPE_NAME (type) == inner);
7877 if (streaming_p ())
7878 u (has_type ? TREE_CODE (type) : 0);
7880 if (has_type)
7882 type_tag = insert (type, WK_value);
7883 if (streaming_p ())
7885 start (type, true);
7886 tree_node_bools (type);
7887 dump (dumper::TREE)
7888 && dump ("Writing type:%d %C:%N", type_tag,
7889 TREE_CODE (type), type);
7892 stub_decl = TYPE_STUB_DECL (type);
7893 bool has_stub = inner != stub_decl;
7894 if (streaming_p ())
7895 u (has_stub ? TREE_CODE (stub_decl) : 0);
7896 if (has_stub)
7898 stub_tag = insert (stub_decl);
7899 if (streaming_p ())
7901 start (stub_decl, true);
7902 tree_node_bools (stub_decl);
7903 dump (dumper::TREE)
7904 && dump ("Writing stub_decl:%d %C:%N", stub_tag,
7905 TREE_CODE (stub_decl), stub_decl);
7908 else
7909 stub_decl = NULL_TREE;
7911 else
7912 /* Regular typedef. */
7913 type = NULL_TREE;
7916 /* Stream the container, we want it correctly canonicalized before
7917 we start emitting keys for this decl. */
7918 tree container = decl_container (decl);
7920 unsigned tpl_levels = 0;
7921 if (decl != inner)
7922 tpl_header (decl, &tpl_levels);
7923 if (TREE_CODE (inner) == FUNCTION_DECL)
7924 fn_parms_init (inner);
7926 /* Now write out the merging information, and then really
7927 install the tag values. */
7928 key_mergeable (tag, mk, decl, inner, container, dep);
7930 if (streaming_p ())
7931 dump (dumper::MERGE)
7932 && dump ("Wrote:%d's %s merge key %C:%N", tag,
7933 merge_kind_name[mk], TREE_CODE (decl), decl);
7935 if (TREE_CODE (inner) == FUNCTION_DECL)
7936 fn_parms_fini (inner);
7938 if (!is_key_order ())
7939 tree_node_vals (decl);
7941 if (inner_tag)
7943 if (!is_key_order ())
7944 tree_node_vals (inner);
7945 tpl_parms_fini (decl, tpl_levels);
7948 if (type && !is_key_order ())
7950 tree_node_vals (type);
7951 if (stub_decl)
7952 tree_node_vals (stub_decl);
7955 if (!is_key_order ())
7957 if (mk & MK_template_mask
7958 || mk == MK_partial
7959 || mk == MK_friend_spec)
7961 if (mk != MK_partial)
7963 // FIXME: We should make use of the merge-key by
7964 // exposing it outside of key_mergeable. But this gets
7965 // the job done.
7966 auto *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
7968 if (streaming_p ())
7969 u (get_mergeable_specialization_flags (entry->tmpl, decl));
7970 tree_node (entry->tmpl);
7971 tree_node (entry->args);
7973 else
7975 tree ti = get_template_info (inner);
7976 tree_node (TI_TEMPLATE (ti));
7977 tree_node (TI_ARGS (ti));
7980 tree_node (get_constraints (decl));
7983 if (streaming_p ())
7985 /* Do not stray outside this section. */
7986 gcc_checking_assert (!dep || dep->section == dep_hash->section);
7988 /* Write the entity index, so we can insert it as soon as we
7989 know this is new. */
7990 install_entity (decl, dep);
7993 if (DECL_LANG_SPECIFIC (inner)
7994 && DECL_MODULE_KEYED_DECLS_P (inner)
7995 && !is_key_order ())
7997 /* Stream the keyed entities. */
7998 auto *attach_vec = keyed_table->get (inner);
7999 unsigned num = attach_vec->length ();
8000 if (streaming_p ())
8001 u (num);
8002 for (unsigned ix = 0; ix != num; ix++)
8004 tree attached = (*attach_vec)[ix];
8005 tree_node (attached);
8006 if (streaming_p ())
8007 dump (dumper::MERGE)
8008 && dump ("Written %d[%u] attached decl %N", tag, ix, attached);
8012 if (TREE_CODE (inner) == FUNCTION_DECL
8013 || TREE_CODE (inner) == TYPE_DECL)
8015 /* Write imported temploid friends so that importers can reconstruct
8016 this information on stream-in. */
8017 tree* slot = imported_temploid_friends->get (decl);
8018 tree_node (slot ? *slot : NULL_TREE);
8021 bool is_typedef = false;
8022 if (!type && TREE_CODE (inner) == TYPE_DECL)
8024 tree t = TREE_TYPE (inner);
8025 unsigned tdef_flags = 0;
8026 if (DECL_ORIGINAL_TYPE (inner)
8027 && TYPE_NAME (TREE_TYPE (inner)) == inner)
8029 tdef_flags |= 1;
8030 if (TYPE_STRUCTURAL_EQUALITY_P (t)
8031 && TYPE_DEPENDENT_P_VALID (t)
8032 && TYPE_DEPENDENT_P (t))
8033 tdef_flags |= 2;
8035 if (streaming_p ())
8036 u (tdef_flags);
8038 if (tdef_flags & 1)
8040 /* A typedef type. */
8041 int type_tag = insert (t);
8042 if (streaming_p ())
8043 dump (dumper::TREE)
8044 && dump ("Cloned:%d %s %C:%N", type_tag,
8045 tdef_flags & 2 ? "depalias" : "typedef",
8046 TREE_CODE (t), t);
8048 is_typedef = true;
8052 if (streaming_p () && DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
8054 bool cloned_p
8055 = (DECL_CHAIN (decl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
8056 bool needs_vtt_parm_p
8057 = (cloned_p && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (decl)));
8058 bool omit_inherited_parms_p
8059 = (cloned_p && DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)
8060 && base_ctor_omit_inherited_parms (decl));
8061 unsigned flags = (int (cloned_p) << 0
8062 | int (needs_vtt_parm_p) << 1
8063 | int (omit_inherited_parms_p) << 2);
8064 u (flags);
8065 dump (dumper::TREE) && dump ("CDTOR %N is %scloned",
8066 decl, cloned_p ? "" : "not ");
8069 if (streaming_p () && VAR_P (decl) && CP_DECL_THREAD_LOCAL_P (decl))
8070 u (decl_tls_model (decl));
8072 if (streaming_p ())
8073 dump (dumper::TREE) && dump ("Written decl:%d %C:%N", tag,
8074 TREE_CODE (decl), decl);
8076 if (NAMESPACE_SCOPE_P (inner))
8077 gcc_checking_assert (!dep == (VAR_OR_FUNCTION_DECL_P (inner)
8078 && DECL_LOCAL_DECL_P (inner)));
8079 else if ((TREE_CODE (inner) == TYPE_DECL
8080 && !is_typedef
8081 && TYPE_NAME (TREE_TYPE (inner)) == inner)
8082 || TREE_CODE (inner) == FUNCTION_DECL)
8084 bool write_defn = !dep && has_definition (decl);
8085 if (streaming_p ())
8086 u (write_defn);
8087 if (write_defn)
8088 write_definition (decl);
8092 tree
8093 trees_in::decl_value ()
8095 int tag = 0;
8096 bool is_attached = false;
8097 bool has_defn = false;
8098 unsigned mk_u = u ();
8099 if (mk_u >= MK_hwm || !merge_kind_name[mk_u])
8101 set_overrun ();
8102 return NULL_TREE;
8105 unsigned saved_unused = unused;
8106 unused = 0;
8108 merge_kind mk = merge_kind (mk_u);
8110 tree decl = start ();
8111 if (decl)
8113 if (mk != MK_unique)
8115 bits_in bits = stream_bits ();
8116 if (!(mk & MK_template_mask) && !state->is_header ())
8117 is_attached = bits.b ();
8119 has_defn = bits.b ();
8122 if (!tree_node_bools (decl))
8123 decl = NULL_TREE;
8126 /* Insert into map. */
8127 tag = insert (decl);
8128 if (decl)
8129 dump (dumper::TREE)
8130 && dump ("Reading:%d %C", tag, TREE_CODE (decl));
8132 tree inner = decl;
8133 int inner_tag = 0;
8134 if (decl && TREE_CODE (decl) == TEMPLATE_DECL)
8136 int code = u ();
8137 inner = start (code);
8138 if (inner && tree_node_bools (inner))
8139 DECL_TEMPLATE_RESULT (decl) = inner;
8140 else
8141 decl = NULL_TREE;
8143 inner_tag = insert (inner);
8144 if (decl)
8145 dump (dumper::TREE)
8146 && dump ("Reading:%d %C", inner_tag, TREE_CODE (inner));
8149 tree type = NULL_TREE;
8150 int type_tag = 0;
8151 tree stub_decl = NULL_TREE;
8152 int stub_tag = 0;
8153 if (decl && TREE_CODE (inner) == TYPE_DECL)
8155 if (unsigned type_code = u ())
8157 type = start (type_code);
8158 if (type && tree_node_bools (type))
8160 TREE_TYPE (inner) = type;
8161 TYPE_NAME (type) = inner;
8163 else
8164 decl = NULL_TREE;
8166 type_tag = insert (type);
8167 if (decl)
8168 dump (dumper::TREE)
8169 && dump ("Reading type:%d %C", type_tag, TREE_CODE (type));
8171 if (unsigned stub_code = u ())
8173 stub_decl = start (stub_code);
8174 if (stub_decl && tree_node_bools (stub_decl))
8176 TREE_TYPE (stub_decl) = type;
8177 TYPE_STUB_DECL (type) = stub_decl;
8179 else
8180 decl = NULL_TREE;
8182 stub_tag = insert (stub_decl);
8183 if (decl)
8184 dump (dumper::TREE)
8185 && dump ("Reading stub_decl:%d %C", stub_tag,
8186 TREE_CODE (stub_decl));
8191 if (!decl)
8193 bail:
8194 if (inner_tag != 0)
8195 back_refs[~inner_tag] = NULL_TREE;
8196 if (type_tag != 0)
8197 back_refs[~type_tag] = NULL_TREE;
8198 if (stub_tag != 0)
8199 back_refs[~stub_tag] = NULL_TREE;
8200 if (tag != 0)
8201 back_refs[~tag] = NULL_TREE;
8202 set_overrun ();
8203 /* Bail. */
8204 unused = saved_unused;
8205 return NULL_TREE;
8208 /* Read the container, to ensure it's already been streamed in. */
8209 tree container = decl_container ();
8210 unsigned tpl_levels = 0;
8212 /* Figure out if this decl is already known about. */
8213 int parm_tag = 0;
8215 if (decl != inner)
8216 if (!tpl_header (decl, &tpl_levels))
8217 goto bail;
8218 if (TREE_CODE (inner) == FUNCTION_DECL)
8219 parm_tag = fn_parms_init (inner);
8221 tree existing = key_mergeable (tag, mk, decl, inner, type, container,
8222 is_attached);
8223 tree existing_inner = existing;
8224 if (existing)
8226 if (existing == error_mark_node)
8227 goto bail;
8229 if (TREE_CODE (STRIP_TEMPLATE (existing)) == TYPE_DECL)
8231 tree etype = TREE_TYPE (existing);
8232 if (TYPE_LANG_SPECIFIC (etype)
8233 && COMPLETE_TYPE_P (etype)
8234 && !CLASSTYPE_MEMBER_VEC (etype))
8235 /* Give it a member vec, we're likely gonna be looking
8236 inside it. */
8237 set_class_bindings (etype, -1);
8240 /* Install the existing decl into the back ref array. */
8241 register_duplicate (decl, existing);
8242 back_refs[~tag] = existing;
8243 if (inner_tag != 0)
8245 existing_inner = DECL_TEMPLATE_RESULT (existing);
8246 back_refs[~inner_tag] = existing_inner;
8249 if (type_tag != 0)
8251 tree existing_type = TREE_TYPE (existing);
8252 back_refs[~type_tag] = existing_type;
8253 if (stub_tag != 0)
8254 back_refs[~stub_tag] = TYPE_STUB_DECL (existing_type);
8258 if (parm_tag)
8259 fn_parms_fini (parm_tag, inner, existing_inner, has_defn);
8261 if (!tree_node_vals (decl))
8262 goto bail;
8264 if (inner_tag)
8266 gcc_checking_assert (DECL_TEMPLATE_RESULT (decl) == inner);
8268 if (!tree_node_vals (inner))
8269 goto bail;
8271 if (!tpl_parms_fini (decl, tpl_levels))
8272 goto bail;
8275 if (type && (!tree_node_vals (type)
8276 || (stub_decl && !tree_node_vals (stub_decl))))
8277 goto bail;
8279 spec_entry spec;
8280 unsigned spec_flags = 0;
8281 if (mk & MK_template_mask
8282 || mk == MK_partial
8283 || mk == MK_friend_spec)
8285 if (mk == MK_partial)
8286 spec_flags = 2;
8287 else
8288 spec_flags = u ();
8290 spec.tmpl = tree_node ();
8291 spec.args = tree_node ();
8293 /* Hold constraints on the spec field, for a short while. */
8294 spec.spec = tree_node ();
8296 dump (dumper::TREE) && dump ("Read:%d %C:%N", tag, TREE_CODE (decl), decl);
8298 existing = back_refs[~tag];
8299 bool installed = install_entity (existing);
8300 bool is_new = existing == decl;
8302 if (DECL_LANG_SPECIFIC (inner)
8303 && DECL_MODULE_KEYED_DECLS_P (inner))
8305 /* Read and maybe install the attached entities. */
8306 bool existed;
8307 auto &set = keyed_table->get_or_insert (STRIP_TEMPLATE (existing),
8308 &existed);
8309 unsigned num = u ();
8310 if (is_new == existed)
8311 set_overrun ();
8312 if (is_new)
8313 set.reserve (num);
8314 for (unsigned ix = 0; !get_overrun () && ix != num; ix++)
8316 tree attached = tree_node ();
8317 dump (dumper::MERGE)
8318 && dump ("Read %d[%u] %s attached decl %N", tag, ix,
8319 is_new ? "new" : "matched", attached);
8320 if (is_new)
8321 set.quick_push (attached);
8322 else if (set[ix] != attached)
8323 set_overrun ();
8327 if (TREE_CODE (inner) == FUNCTION_DECL
8328 || TREE_CODE (inner) == TYPE_DECL)
8329 if (tree owner = tree_node ())
8330 if (is_new)
8331 imported_temploid_friends->put (decl, owner);
8333 /* Regular typedefs will have a NULL TREE_TYPE at this point. */
8334 unsigned tdef_flags = 0;
8335 bool is_typedef = false;
8336 if (!type && TREE_CODE (inner) == TYPE_DECL)
8338 tdef_flags = u ();
8339 if (tdef_flags & 1)
8340 is_typedef = true;
8343 if (is_new)
8345 /* A newly discovered node. */
8346 if (TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))
8347 /* Mark this identifier as naming a virtual function --
8348 lookup_overrides relies on this optimization. */
8349 IDENTIFIER_VIRTUAL_P (DECL_NAME (decl)) = true;
8351 if (installed)
8353 /* Mark the entity as imported. */
8354 retrofit_lang_decl (inner);
8355 DECL_MODULE_IMPORT_P (inner) = true;
8358 if (spec.spec)
8359 set_constraints (decl, spec.spec);
8361 if (TREE_CODE (decl) == INTEGER_CST && !TREE_OVERFLOW (decl))
8363 decl = cache_integer_cst (decl, true);
8364 back_refs[~tag] = decl;
8367 if (is_typedef)
8369 /* Frob it to be ready for cloning. */
8370 TREE_TYPE (inner) = DECL_ORIGINAL_TYPE (inner);
8371 DECL_ORIGINAL_TYPE (inner) = NULL_TREE;
8372 set_underlying_type (inner);
8373 if (tdef_flags & 2)
8375 /* Match instantiate_alias_template's handling. */
8376 tree type = TREE_TYPE (inner);
8377 TYPE_DEPENDENT_P (type) = true;
8378 TYPE_DEPENDENT_P_VALID (type) = true;
8379 SET_TYPE_STRUCTURAL_EQUALITY (type);
8383 if (inner_tag)
8384 /* Set the TEMPLATE_DECL's type. */
8385 TREE_TYPE (decl) = TREE_TYPE (inner);
8387 /* Redetermine whether we need to import or export this declaration
8388 for this TU. But for extern templates we know we must import:
8389 they'll be defined in a different TU.
8390 FIXME: How do dllexport and dllimport interact across a module?
8391 See also https://github.com/itanium-cxx-abi/cxx-abi/issues/170.
8392 May have to revisit? */
8393 if (type
8394 && CLASS_TYPE_P (type)
8395 && TYPE_LANG_SPECIFIC (type)
8396 && !(CLASSTYPE_EXPLICIT_INSTANTIATION (type)
8397 && CLASSTYPE_INTERFACE_KNOWN (type)
8398 && CLASSTYPE_INTERFACE_ONLY (type)))
8400 CLASSTYPE_INTERFACE_ONLY (type) = false;
8401 CLASSTYPE_INTERFACE_UNKNOWN (type) = true;
8404 /* Add to specialization tables now that constraints etc are
8405 added. */
8406 if (mk == MK_partial)
8408 bool is_type = TREE_CODE (inner) == TYPE_DECL;
8409 spec.spec = is_type ? type : inner;
8410 add_mergeable_specialization (!is_type, &spec, decl, spec_flags);
8412 else if (mk & MK_template_mask)
8414 bool is_type = !(mk & MK_tmpl_decl_mask);
8415 spec.spec = is_type ? type : mk & MK_tmpl_tmpl_mask ? inner : decl;
8416 add_mergeable_specialization (!is_type, &spec, decl, spec_flags);
8419 if (NAMESPACE_SCOPE_P (decl)
8420 && (mk == MK_named || mk == MK_unique
8421 || mk == MK_enum || mk == MK_friend_spec)
8422 && !(VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl)))
8423 add_module_namespace_decl (CP_DECL_CONTEXT (decl), decl);
8425 if (DECL_ARTIFICIAL (decl)
8426 && TREE_CODE (decl) == FUNCTION_DECL
8427 && !DECL_TEMPLATE_INFO (decl)
8428 && DECL_CONTEXT (decl) && TYPE_P (DECL_CONTEXT (decl))
8429 && TYPE_SIZE (DECL_CONTEXT (decl))
8430 && !DECL_THUNK_P (decl))
8431 /* A new implicit member function, when the class is
8432 complete. This means the importee declared it, and
8433 we must now add it to the class. Note that implicit
8434 member fns of template instantiations do not themselves
8435 look like templates. */
8436 if (!install_implicit_member (inner))
8437 set_overrun ();
8439 /* When importing a TLS wrapper from a header unit, we haven't
8440 actually emitted its definition yet. Remember it so we can
8441 do this later. */
8442 if (state->is_header ()
8443 && decl_tls_wrapper_p (decl))
8444 note_vague_linkage_fn (decl);
8446 /* Setup aliases for the declaration. */
8447 if (tree alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)))
8449 alias = TREE_VALUE (TREE_VALUE (alias));
8450 alias = get_identifier (TREE_STRING_POINTER (alias));
8451 assemble_alias (decl, alias);
8454 else
8456 /* DECL is the to-be-discarded decl. Its internal pointers will
8457 be to the EXISTING's structure. Frob it to point to its
8458 own other structures, so loading its definition will alter
8459 it, and not the existing decl. */
8460 dump (dumper::MERGE) && dump ("Deduping %N", existing);
8462 if (inner_tag)
8463 DECL_TEMPLATE_RESULT (decl) = inner;
8465 if (type)
8467 /* Point at the to-be-discarded type & decl. */
8468 TYPE_NAME (type) = inner;
8469 TREE_TYPE (inner) = type;
8471 TYPE_STUB_DECL (type) = stub_decl ? stub_decl : inner;
8472 if (stub_decl)
8473 TREE_TYPE (stub_decl) = type;
8476 if (inner_tag)
8477 /* Set the TEMPLATE_DECL's type. */
8478 TREE_TYPE (decl) = TREE_TYPE (inner);
8480 if (!is_matching_decl (existing, decl, is_typedef))
8481 unmatched_duplicate (existing);
8483 if (TREE_CODE (inner) == FUNCTION_DECL)
8485 tree e_inner = STRIP_TEMPLATE (existing);
8486 for (auto parm = DECL_ARGUMENTS (inner);
8487 parm; parm = DECL_CHAIN (parm))
8488 DECL_CONTEXT (parm) = e_inner;
8491 /* And our result is the existing node. */
8492 decl = existing;
8495 if (mk == MK_friend_spec)
8497 tree e = match_mergeable_specialization (true, &spec);
8498 if (!e)
8500 spec.spec = inner;
8501 add_mergeable_specialization (true, &spec, decl, spec_flags);
8503 else if (e != existing)
8504 set_overrun ();
8507 if (is_typedef)
8509 /* Insert the type into the array now. */
8510 tag = insert (TREE_TYPE (decl));
8511 dump (dumper::TREE)
8512 && dump ("Cloned:%d typedef %C:%N",
8513 tag, TREE_CODE (TREE_TYPE (decl)), TREE_TYPE (decl));
8516 unused = saved_unused;
8518 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
8520 unsigned flags = u ();
8522 if (is_new)
8524 bool cloned_p = flags & 1;
8525 dump (dumper::TREE) && dump ("CDTOR %N is %scloned",
8526 decl, cloned_p ? "" : "not ");
8527 if (cloned_p)
8528 build_cdtor_clones (decl, flags & 2, flags & 4,
8529 /* Update the member vec, if there is
8530 one (we're in a different cluster
8531 to the class defn). */
8532 CLASSTYPE_MEMBER_VEC (DECL_CONTEXT (decl)));
8536 if (VAR_P (decl) && CP_DECL_THREAD_LOCAL_P (decl))
8538 enum tls_model model = tls_model (u ());
8539 if (is_new)
8540 set_decl_tls_model (decl, model);
8543 if (!NAMESPACE_SCOPE_P (inner)
8544 && ((TREE_CODE (inner) == TYPE_DECL
8545 && !is_typedef
8546 && TYPE_NAME (TREE_TYPE (inner)) == inner)
8547 || TREE_CODE (inner) == FUNCTION_DECL)
8548 && u ())
8549 read_definition (decl);
8551 return decl;
8554 /* DECL is an unnameable member of CTX. Return a suitable identifying
8555 index. */
8557 static unsigned
8558 get_field_ident (tree ctx, tree decl)
8560 gcc_checking_assert (TREE_CODE (decl) == USING_DECL
8561 || !DECL_NAME (decl)
8562 || IDENTIFIER_ANON_P (DECL_NAME (decl)));
8564 unsigned ix = 0;
8565 for (tree fields = TYPE_FIELDS (ctx);
8566 fields; fields = DECL_CHAIN (fields))
8568 if (fields == decl)
8569 return ix;
8571 if (DECL_CONTEXT (fields) == ctx
8572 && (TREE_CODE (fields) == USING_DECL
8573 || (TREE_CODE (fields) == FIELD_DECL
8574 && (!DECL_NAME (fields)
8575 || IDENTIFIER_ANON_P (DECL_NAME (fields))))))
8576 /* Count this field. */
8577 ix++;
8579 gcc_unreachable ();
8582 static tree
8583 lookup_field_ident (tree ctx, unsigned ix)
8585 for (tree fields = TYPE_FIELDS (ctx);
8586 fields; fields = DECL_CHAIN (fields))
8587 if (DECL_CONTEXT (fields) == ctx
8588 && (TREE_CODE (fields) == USING_DECL
8589 || (TREE_CODE (fields) == FIELD_DECL
8590 && (!DECL_NAME (fields)
8591 || IDENTIFIER_ANON_P (DECL_NAME (fields))))))
8592 if (!ix--)
8593 return fields;
8595 return NULL_TREE;
8598 /* Reference DECL. REF indicates the walk kind we are performing.
8599 Return true if we should write this decl by value. */
8601 bool
8602 trees_out::decl_node (tree decl, walk_kind ref)
8604 gcc_checking_assert (DECL_P (decl) && !DECL_TEMPLATE_PARM_P (decl)
8605 && DECL_CONTEXT (decl));
8607 if (ref == WK_value)
8609 depset *dep = dep_hash->find_dependency (decl);
8610 decl_value (decl, dep);
8611 return false;
8614 switch (TREE_CODE (decl))
8616 default:
8617 break;
8619 case FUNCTION_DECL:
8620 gcc_checking_assert (!DECL_LOCAL_DECL_P (decl));
8621 break;
8623 case RESULT_DECL:
8624 /* Unlike PARM_DECLs, RESULT_DECLs are only generated and
8625 referenced when we're inside the function itself. */
8626 return true;
8628 case PARM_DECL:
8630 if (streaming_p ())
8631 i (tt_parm);
8632 tree_node (DECL_CONTEXT (decl));
8633 if (streaming_p ())
8635 /* That must have put this in the map. */
8636 walk_kind ref = ref_node (decl);
8637 if (ref != WK_none)
8638 // FIXME:OPTIMIZATION We can wander into bits of the
8639 // template this was instantiated from. For instance
8640 // deferred noexcept and default parms. Currently we'll
8641 // end up cloning those bits of tree. It would be nice
8642 // to reference those specific nodes. I think putting
8643 // those things in the map when we reference their
8644 // template by name. See the note in add_indirects.
8645 return true;
8647 dump (dumper::TREE)
8648 && dump ("Wrote %s reference %N",
8649 TREE_CODE (decl) == PARM_DECL ? "parameter" : "result",
8650 decl);
8653 return false;
8655 case IMPORTED_DECL:
8656 /* This describes a USING_DECL to the ME's debug machinery. It
8657 originates from the fortran FE, and has nothing to do with
8658 C++ modules. */
8659 return true;
8661 case LABEL_DECL:
8662 return true;
8664 case CONST_DECL:
8666 /* If I end up cloning enum decls, implementing C++20 using
8667 E::v, this will need tweaking. */
8668 if (streaming_p ())
8669 i (tt_enum_decl);
8670 tree ctx = DECL_CONTEXT (decl);
8671 gcc_checking_assert (TREE_CODE (ctx) == ENUMERAL_TYPE);
8672 tree_node (ctx);
8673 tree_node (DECL_NAME (decl));
8675 int tag = insert (decl);
8676 if (streaming_p ())
8677 dump (dumper::TREE)
8678 && dump ("Wrote enum decl:%d %C:%N", tag, TREE_CODE (decl), decl);
8679 return false;
8681 break;
8683 case USING_DECL:
8684 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
8685 break;
8686 /* FALLTHROUGH */
8688 case FIELD_DECL:
8690 if (streaming_p ())
8691 i (tt_data_member);
8693 tree ctx = DECL_CONTEXT (decl);
8694 tree_node (ctx);
8696 tree name = NULL_TREE;
8698 if (TREE_CODE (decl) == USING_DECL)
8700 else
8702 name = DECL_NAME (decl);
8703 if (name && IDENTIFIER_ANON_P (name))
8704 name = NULL_TREE;
8707 tree_node (name);
8708 if (!name && streaming_p ())
8710 unsigned ix = get_field_ident (ctx, decl);
8711 u (ix);
8714 int tag = insert (decl);
8715 if (streaming_p ())
8716 dump (dumper::TREE)
8717 && dump ("Wrote member:%d %C:%N", tag, TREE_CODE (decl), decl);
8718 return false;
8720 break;
8722 case VAR_DECL:
8723 gcc_checking_assert (!DECL_LOCAL_DECL_P (decl));
8724 if (DECL_VTABLE_OR_VTT_P (decl))
8726 /* VTT or VTABLE, they are all on the vtables list. */
8727 tree ctx = CP_DECL_CONTEXT (decl);
8728 tree vtable = CLASSTYPE_VTABLES (ctx);
8729 for (unsigned ix = 0; ; vtable = DECL_CHAIN (vtable), ix++)
8730 if (vtable == decl)
8732 gcc_checking_assert (DECL_VIRTUAL_P (decl));
8733 if (streaming_p ())
8735 u (tt_vtable);
8736 u (ix);
8737 dump (dumper::TREE)
8738 && dump ("Writing vtable %N[%u]", ctx, ix);
8740 tree_node (ctx);
8741 return false;
8743 gcc_unreachable ();
8746 if (DECL_TINFO_P (decl))
8748 tinfo:
8749 /* A typeinfo, tt_tinfo_typedef or tt_tinfo_var. */
8750 bool is_var = VAR_P (decl);
8751 tree type = TREE_TYPE (decl);
8752 unsigned ix = get_pseudo_tinfo_index (type);
8753 if (streaming_p ())
8755 i (is_var ? tt_tinfo_var : tt_tinfo_typedef);
8756 u (ix);
8759 if (is_var)
8761 /* We also need the type it is for and mangled name, so
8762 the reader doesn't need to complete the type (which
8763 would break section ordering). The type it is for is
8764 stashed on the name's TREE_TYPE. */
8765 tree name = DECL_NAME (decl);
8766 tree_node (name);
8767 type = TREE_TYPE (name);
8768 tree_node (type);
8771 int tag = insert (decl);
8772 if (streaming_p ())
8773 dump (dumper::TREE)
8774 && dump ("Wrote tinfo_%s:%d %u %N", is_var ? "var" : "type",
8775 tag, ix, type);
8777 if (!is_var)
8779 tag = insert (type);
8780 if (streaming_p ())
8781 dump (dumper::TREE)
8782 && dump ("Wrote tinfo_type:%d %u %N", tag, ix, type);
8784 return false;
8787 if (DECL_NTTP_OBJECT_P (decl))
8789 /* A NTTP parm object. */
8790 if (streaming_p ())
8791 i (tt_nttp_var);
8792 tree_node (tparm_object_argument (decl));
8793 tree_node (DECL_NAME (decl));
8794 int tag = insert (decl);
8795 if (streaming_p ())
8796 dump (dumper::TREE)
8797 && dump ("Wrote nttp object:%d %N", tag, DECL_NAME (decl));
8798 return false;
8801 break;
8803 case TYPE_DECL:
8804 if (DECL_TINFO_P (decl))
8805 goto tinfo;
8806 break;
8809 if (DECL_THUNK_P (decl))
8811 /* Thunks are similar to binfos -- write the thunked-to decl and
8812 then thunk-specific key info. */
8813 if (streaming_p ())
8815 i (tt_thunk);
8816 i (THUNK_FIXED_OFFSET (decl));
8819 tree target = decl;
8820 while (DECL_THUNK_P (target))
8821 target = THUNK_TARGET (target);
8822 tree_node (target);
8823 tree_node (THUNK_VIRTUAL_OFFSET (decl));
8824 int tag = insert (decl);
8825 if (streaming_p ())
8826 dump (dumper::TREE)
8827 && dump ("Wrote:%d thunk %N to %N", tag, DECL_NAME (decl), target);
8828 return false;
8831 if (DECL_CLONED_FUNCTION_P (decl))
8833 tree target = get_clone_target (decl);
8834 if (streaming_p ())
8835 i (tt_clone_ref);
8837 tree_node (target);
8838 tree_node (DECL_NAME (decl));
8839 if (DECL_VIRTUAL_P (decl))
8840 tree_node (DECL_VINDEX (decl));
8841 int tag = insert (decl);
8842 if (streaming_p ())
8843 dump (dumper::TREE)
8844 && dump ("Wrote:%d clone %N of %N", tag, DECL_NAME (decl), target);
8845 return false;
8848 /* Everything left should be a thing that is in the entity table.
8849 Mostly things that can be defined outside of their (original
8850 declaration) context. */
8851 gcc_checking_assert (TREE_CODE (decl) == TEMPLATE_DECL
8852 || VAR_P (decl)
8853 || TREE_CODE (decl) == FUNCTION_DECL
8854 || TREE_CODE (decl) == TYPE_DECL
8855 || TREE_CODE (decl) == USING_DECL
8856 || TREE_CODE (decl) == CONCEPT_DECL
8857 || TREE_CODE (decl) == NAMESPACE_DECL);
8859 int use_tpl = -1;
8860 tree ti = node_template_info (decl, use_tpl);
8861 tree tpl = NULL_TREE;
8863 /* If this is the TEMPLATE_DECL_RESULT of a TEMPLATE_DECL, get the
8864 TEMPLATE_DECL. Note TI_TEMPLATE is not a TEMPLATE_DECL for
8865 (some) friends, so we need to check that. */
8866 // FIXME: Should local friend template specializations be by value?
8867 // They don't get idents so we'll never know they're imported, but I
8868 // think we can only reach them from the TU that defines the
8869 // befriending class?
8870 if (ti && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL
8871 && DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == decl)
8873 tpl = TI_TEMPLATE (ti);
8874 partial_template:
8875 if (streaming_p ())
8877 i (tt_template);
8878 dump (dumper::TREE)
8879 && dump ("Writing implicit template %C:%N%S",
8880 TREE_CODE (tpl), tpl, tpl);
8882 tree_node (tpl);
8884 /* Streaming TPL caused us to visit DECL and maybe its type. */
8885 gcc_checking_assert (TREE_VISITED (decl));
8886 if (DECL_IMPLICIT_TYPEDEF_P (decl))
8887 gcc_checking_assert (TREE_VISITED (TREE_TYPE (decl)));
8888 return false;
8891 tree ctx = CP_DECL_CONTEXT (decl);
8892 depset *dep = NULL;
8893 if (streaming_p ())
8894 dep = dep_hash->find_dependency (decl);
8895 else if (TREE_CODE (ctx) != FUNCTION_DECL
8896 || TREE_CODE (decl) == TEMPLATE_DECL
8897 || DECL_IMPLICIT_TYPEDEF_P (decl)
8898 || (DECL_LANG_SPECIFIC (decl)
8899 && DECL_MODULE_IMPORT_P (decl)))
8901 auto kind = (TREE_CODE (decl) == NAMESPACE_DECL
8902 && !DECL_NAMESPACE_ALIAS (decl)
8903 ? depset::EK_NAMESPACE : depset::EK_DECL);
8904 dep = dep_hash->add_dependency (decl, kind);
8907 if (!dep)
8909 /* Some internal entity of context. Do by value. */
8910 decl_value (decl, NULL);
8911 return false;
8914 if (dep->get_entity_kind () == depset::EK_REDIRECT)
8916 /* The DECL_TEMPLATE_RESULT of a partial specialization.
8917 Write the partial specialization's template. */
8918 depset *redirect = dep->deps[0];
8919 gcc_checking_assert (redirect->get_entity_kind () == depset::EK_PARTIAL);
8920 tpl = redirect->get_entity ();
8921 goto partial_template;
8924 if (streaming_p ())
8926 /* Locate the entity. */
8927 unsigned index = dep->cluster;
8928 unsigned import = 0;
8930 if (dep->is_import ())
8931 import = dep->section;
8932 else if (CHECKING_P)
8933 /* It should be what we put there. */
8934 gcc_checking_assert (index == ~import_entity_index (decl));
8936 #if CHECKING_P
8937 gcc_assert (!import || importedness >= 0);
8938 #endif
8939 i (tt_entity);
8940 u (import);
8941 u (index);
8944 int tag = insert (decl);
8945 if (streaming_p () && dump (dumper::TREE))
8947 char const *kind = "import";
8948 module_state *from = (*modules)[0];
8949 if (dep->is_import ())
8950 /* Rediscover the unremapped index. */
8951 from = import_entity_module (import_entity_index (decl));
8952 else
8954 tree o = get_originating_module_decl (decl);
8955 o = STRIP_TEMPLATE (o);
8956 kind = (DECL_LANG_SPECIFIC (o) && DECL_MODULE_PURVIEW_P (o)
8957 ? "purview" : "GMF");
8959 dump ("Wrote %s:%d %C:%N@%M", kind,
8960 tag, TREE_CODE (decl), decl, from);
8963 add_indirects (decl);
8965 return false;
8968 void
8969 trees_out::type_node (tree type)
8971 gcc_assert (TYPE_P (type));
8973 tree root = (TYPE_NAME (type)
8974 ? TREE_TYPE (TYPE_NAME (type)) : TYPE_MAIN_VARIANT (type));
8976 if (type != root)
8978 if (streaming_p ())
8979 i (tt_variant_type);
8980 tree_node (root);
8982 int flags = -1;
8984 if (TREE_CODE (type) == FUNCTION_TYPE
8985 || TREE_CODE (type) == METHOD_TYPE)
8987 int quals = type_memfn_quals (type);
8988 int rquals = type_memfn_rqual (type);
8989 tree raises = TYPE_RAISES_EXCEPTIONS (type);
8990 bool late = TYPE_HAS_LATE_RETURN_TYPE (type);
8992 if (raises != TYPE_RAISES_EXCEPTIONS (root)
8993 || rquals != type_memfn_rqual (root)
8994 || quals != type_memfn_quals (root)
8995 || late != TYPE_HAS_LATE_RETURN_TYPE (root))
8996 flags = rquals | (int (late) << 2) | (quals << 3);
8998 else
9000 if (TYPE_USER_ALIGN (type))
9001 flags = TYPE_ALIGN_RAW (type);
9004 if (streaming_p ())
9005 i (flags);
9007 if (flags < 0)
9009 else if (TREE_CODE (type) == FUNCTION_TYPE
9010 || TREE_CODE (type) == METHOD_TYPE)
9012 tree raises = TYPE_RAISES_EXCEPTIONS (type);
9013 if (raises == TYPE_RAISES_EXCEPTIONS (root))
9014 raises = error_mark_node;
9015 tree_node (raises);
9018 tree_node (TYPE_ATTRIBUTES (type));
9020 if (streaming_p ())
9022 /* Qualifiers. */
9023 int rquals = cp_type_quals (root);
9024 int quals = cp_type_quals (type);
9025 if (quals == rquals)
9026 quals = -1;
9027 i (quals);
9030 if (ref_node (type) != WK_none)
9032 int tag = insert (type);
9033 if (streaming_p ())
9035 i (0);
9036 dump (dumper::TREE)
9037 && dump ("Wrote:%d variant type %C", tag, TREE_CODE (type));
9040 return;
9043 if (tree name = TYPE_NAME (type))
9044 if ((TREE_CODE (name) == TYPE_DECL && DECL_ORIGINAL_TYPE (name))
9045 || DECL_TEMPLATE_PARM_P (name)
9046 || TREE_CODE (type) == RECORD_TYPE
9047 || TREE_CODE (type) == UNION_TYPE
9048 || TREE_CODE (type) == ENUMERAL_TYPE)
9050 /* We can meet template parms that we didn't meet in the
9051 tpl_parms walk, because we're referring to a derived type
9052 that was previously constructed from equivalent template
9053 parms. */
9054 if (streaming_p ())
9056 i (tt_typedef_type);
9057 dump (dumper::TREE)
9058 && dump ("Writing %stypedef %C:%N",
9059 DECL_IMPLICIT_TYPEDEF_P (name) ? "implicit " : "",
9060 TREE_CODE (name), name);
9062 tree_node (name);
9063 if (streaming_p ())
9064 dump (dumper::TREE) && dump ("Wrote typedef %C:%N%S",
9065 TREE_CODE (name), name, name);
9066 gcc_checking_assert (TREE_VISITED (type));
9067 return;
9070 if (TYPE_PTRMEMFUNC_P (type))
9072 /* This is a distinct type node, masquerading as a structure. */
9073 tree fn_type = TYPE_PTRMEMFUNC_FN_TYPE (type);
9074 if (streaming_p ())
9075 i (tt_ptrmem_type);
9076 tree_node (fn_type);
9077 int tag = insert (type);
9078 if (streaming_p ())
9079 dump (dumper::TREE) && dump ("Written:%d ptrmem type", tag);
9080 return;
9083 if (streaming_p ())
9085 u (tt_derived_type);
9086 u (TREE_CODE (type));
9089 tree_node (TREE_TYPE (type));
9090 switch (TREE_CODE (type))
9092 default:
9093 /* We should never meet a type here that is indescribable in
9094 terms of other types. */
9095 gcc_unreachable ();
9097 case ARRAY_TYPE:
9098 tree_node (TYPE_DOMAIN (type));
9099 if (streaming_p ())
9100 /* Dependent arrays are constructed with TYPE_DEPENENT_P
9101 already set. */
9102 u (TYPE_DEPENDENT_P (type));
9103 break;
9105 case COMPLEX_TYPE:
9106 /* No additional data. */
9107 break;
9109 case BOOLEAN_TYPE:
9110 /* A non-standard boolean type. */
9111 if (streaming_p ())
9112 u (TYPE_PRECISION (type));
9113 break;
9115 case INTEGER_TYPE:
9116 if (TREE_TYPE (type))
9118 /* A range type (representing an array domain). */
9119 tree_node (TYPE_MIN_VALUE (type));
9120 tree_node (TYPE_MAX_VALUE (type));
9122 else
9124 /* A new integral type (representing a bitfield). */
9125 if (streaming_p ())
9127 unsigned prec = TYPE_PRECISION (type);
9128 bool unsigned_p = TYPE_UNSIGNED (type);
9130 u ((prec << 1) | unsigned_p);
9133 break;
9135 case METHOD_TYPE:
9136 case FUNCTION_TYPE:
9138 gcc_checking_assert (type_memfn_rqual (type) == REF_QUAL_NONE);
9140 tree arg_types = TYPE_ARG_TYPES (type);
9141 if (TREE_CODE (type) == METHOD_TYPE)
9143 tree_node (TREE_TYPE (TREE_VALUE (arg_types)));
9144 arg_types = TREE_CHAIN (arg_types);
9146 tree_node (arg_types);
9148 break;
9150 case OFFSET_TYPE:
9151 tree_node (TYPE_OFFSET_BASETYPE (type));
9152 break;
9154 case POINTER_TYPE:
9155 /* No additional data. */
9156 break;
9158 case REFERENCE_TYPE:
9159 if (streaming_p ())
9160 u (TYPE_REF_IS_RVALUE (type));
9161 break;
9163 case DECLTYPE_TYPE:
9164 case TYPEOF_TYPE:
9165 case DEPENDENT_OPERATOR_TYPE:
9166 tree_node (TYPE_VALUES_RAW (type));
9167 if (TREE_CODE (type) == DECLTYPE_TYPE)
9168 /* We stash a whole bunch of things into decltype's
9169 flags. */
9170 if (streaming_p ())
9171 tree_node_bools (type);
9172 break;
9174 case TRAIT_TYPE:
9175 tree_node (TRAIT_TYPE_KIND_RAW (type));
9176 tree_node (TRAIT_TYPE_TYPE1 (type));
9177 tree_node (TRAIT_TYPE_TYPE2 (type));
9178 break;
9180 case TYPE_ARGUMENT_PACK:
9181 /* No additional data. */
9182 break;
9184 case TYPE_PACK_EXPANSION:
9185 if (streaming_p ())
9186 u (PACK_EXPANSION_LOCAL_P (type));
9187 tree_node (PACK_EXPANSION_PARAMETER_PACKS (type));
9188 tree_node (PACK_EXPANSION_EXTRA_ARGS (type));
9189 break;
9191 case TYPENAME_TYPE:
9193 tree_node (TYPE_CONTEXT (type));
9194 tree_node (DECL_NAME (TYPE_NAME (type)));
9195 tree_node (TYPENAME_TYPE_FULLNAME (type));
9196 if (streaming_p ())
9198 enum tag_types tag_type = none_type;
9199 if (TYPENAME_IS_ENUM_P (type))
9200 tag_type = enum_type;
9201 else if (TYPENAME_IS_CLASS_P (type))
9202 tag_type = class_type;
9203 u (int (tag_type));
9206 break;
9208 case UNBOUND_CLASS_TEMPLATE:
9210 tree decl = TYPE_NAME (type);
9211 tree_node (DECL_CONTEXT (decl));
9212 tree_node (DECL_NAME (decl));
9213 tree_node (DECL_TEMPLATE_PARMS (decl));
9215 break;
9217 case VECTOR_TYPE:
9218 if (streaming_p ())
9220 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (type);
9221 for (unsigned ix = 0; ix != NUM_POLY_INT_COEFFS; ix++)
9222 wu (nunits.coeffs[ix]);
9224 break;
9227 /* We may have met the type during emitting the above. */
9228 if (ref_node (type) != WK_none)
9230 int tag = insert (type);
9231 if (streaming_p ())
9233 i (0);
9234 dump (dumper::TREE)
9235 && dump ("Wrote:%d derived type %C", tag, TREE_CODE (type));
9239 return;
9242 /* T is (mostly*) a non-mergeable node that must be written by value.
9243 The mergeable case is a BINFO, which are as-if DECLSs. */
9245 void
9246 trees_out::tree_value (tree t)
9248 /* We should never be writing a type by value. tree_type should
9249 have streamed it, or we're going via its TYPE_DECL. */
9250 gcc_checking_assert (!TYPE_P (t));
9252 if (DECL_P (t))
9253 /* No template, type, var or function, except anonymous
9254 non-context vars. */
9255 gcc_checking_assert ((TREE_CODE (t) != TEMPLATE_DECL
9256 && TREE_CODE (t) != TYPE_DECL
9257 && (TREE_CODE (t) != VAR_DECL
9258 || (!DECL_NAME (t) && !DECL_CONTEXT (t)))
9259 && TREE_CODE (t) != FUNCTION_DECL));
9261 if (streaming_p ())
9263 /* A new node -> tt_node. */
9264 tree_val_count++;
9265 i (tt_node);
9266 start (t);
9267 tree_node_bools (t);
9270 if (TREE_CODE (t) == TREE_BINFO)
9271 /* Binfos are decl-like and need merging information. */
9272 binfo_mergeable (t);
9274 int tag = insert (t, WK_value);
9275 if (streaming_p ())
9276 dump (dumper::TREE)
9277 && dump ("Writing tree:%d %C:%N", tag, TREE_CODE (t), t);
9279 tree_node_vals (t);
9281 if (streaming_p ())
9282 dump (dumper::TREE) && dump ("Written tree:%d %C:%N", tag, TREE_CODE (t), t);
9285 tree
9286 trees_in::tree_value ()
9288 tree t = start ();
9289 if (!t || !tree_node_bools (t))
9290 return NULL_TREE;
9292 tree existing = t;
9293 if (TREE_CODE (t) == TREE_BINFO)
9295 tree type;
9296 unsigned ix = binfo_mergeable (&type);
9297 if (TYPE_BINFO (type))
9299 /* We already have a definition, this must be a duplicate. */
9300 dump (dumper::MERGE)
9301 && dump ("Deduping binfo %N[%u]", type, ix);
9302 existing = TYPE_BINFO (type);
9303 while (existing && ix--)
9304 existing = TREE_CHAIN (existing);
9305 if (existing)
9306 register_duplicate (t, existing);
9307 else
9308 /* Error, mismatch -- diagnose in read_class_def's
9309 checking. */
9310 existing = t;
9314 /* Insert into map. */
9315 int tag = insert (existing);
9316 dump (dumper::TREE)
9317 && dump ("Reading tree:%d %C", tag, TREE_CODE (t));
9319 if (!tree_node_vals (t))
9321 back_refs[~tag] = NULL_TREE;
9322 set_overrun ();
9323 /* Bail. */
9324 return NULL_TREE;
9327 if (TREE_CODE (t) == LAMBDA_EXPR
9328 && CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (t)))
9330 existing = CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (t));
9331 back_refs[~tag] = existing;
9334 dump (dumper::TREE) && dump ("Read tree:%d %C:%N", tag, TREE_CODE (t), t);
9336 if (TREE_CODE (existing) == INTEGER_CST && !TREE_OVERFLOW (existing))
9338 existing = cache_integer_cst (t, true);
9339 back_refs[~tag] = existing;
9342 return existing;
9345 /* Stream out tree node T. We automatically create local back
9346 references, which is essentially a single pass lisp
9347 self-referential structure pretty-printer. */
9349 void
9350 trees_out::tree_node (tree t)
9352 dump.indent ();
9353 walk_kind ref = ref_node (t);
9354 if (ref == WK_none)
9355 goto done;
9357 if (ref != WK_normal)
9358 goto skip_normal;
9360 if (TREE_CODE (t) == IDENTIFIER_NODE)
9362 /* An identifier node -> tt_id, tt_conv_id, tt_anon_id, tt_lambda_id. */
9363 int code = tt_id;
9364 if (IDENTIFIER_ANON_P (t))
9365 code = IDENTIFIER_LAMBDA_P (t) ? tt_lambda_id : tt_anon_id;
9366 else if (IDENTIFIER_CONV_OP_P (t))
9367 code = tt_conv_id;
9369 if (streaming_p ())
9370 i (code);
9372 if (code == tt_conv_id)
9374 tree type = TREE_TYPE (t);
9375 gcc_checking_assert (type || t == conv_op_identifier);
9376 tree_node (type);
9378 else if (code == tt_id && streaming_p ())
9379 str (IDENTIFIER_POINTER (t), IDENTIFIER_LENGTH (t));
9381 int tag = insert (t);
9382 if (streaming_p ())
9384 /* We know the ordering of the 4 id tags. */
9385 static const char *const kinds[] =
9386 {"", "conv_op ", "anon ", "lambda "};
9387 dump (dumper::TREE)
9388 && dump ("Written:%d %sidentifier:%N", tag,
9389 kinds[code - tt_id],
9390 code == tt_conv_id ? TREE_TYPE (t) : t);
9392 goto done;
9395 if (TREE_CODE (t) == TREE_BINFO)
9397 /* A BINFO -> tt_binfo.
9398 We must do this by reference. We stream the binfo tree
9399 itself when streaming its owning RECORD_TYPE. That we got
9400 here means the dominating type is not in this SCC. */
9401 if (streaming_p ())
9402 i (tt_binfo);
9403 binfo_mergeable (t);
9404 gcc_checking_assert (!TREE_VISITED (t));
9405 int tag = insert (t);
9406 if (streaming_p ())
9407 dump (dumper::TREE) && dump ("Inserting binfo:%d %N", tag, t);
9408 goto done;
9411 if (TREE_CODE (t) == INTEGER_CST
9412 && !TREE_OVERFLOW (t)
9413 && TREE_CODE (TREE_TYPE (t)) == ENUMERAL_TYPE)
9415 /* An integral constant of enumeral type. See if it matches one
9416 of the enumeration values. */
9417 for (tree values = TYPE_VALUES (TREE_TYPE (t));
9418 values; values = TREE_CHAIN (values))
9420 tree decl = TREE_VALUE (values);
9421 if (tree_int_cst_equal (DECL_INITIAL (decl), t))
9423 if (streaming_p ())
9424 u (tt_enum_value);
9425 tree_node (decl);
9426 dump (dumper::TREE) && dump ("Written enum value %N", decl);
9427 goto done;
9430 /* It didn't match. We'll write it a an explicit INTEGER_CST
9431 node. */
9434 if (TYPE_P (t))
9436 type_node (t);
9437 goto done;
9440 if (DECL_P (t))
9442 if (DECL_TEMPLATE_PARM_P (t))
9444 tpl_parm_value (t);
9445 goto done;
9448 if (!DECL_CONTEXT (t))
9450 /* There are a few cases of decls with no context. We'll write
9451 these by value, but first assert they are cases we expect. */
9452 gcc_checking_assert (ref == WK_normal);
9453 switch (TREE_CODE (t))
9455 default: gcc_unreachable ();
9457 case LABEL_DECL:
9458 /* CASE_LABEL_EXPRs contain uncontexted LABEL_DECLs. */
9459 gcc_checking_assert (!DECL_NAME (t));
9460 break;
9462 case VAR_DECL:
9463 /* AGGR_INIT_EXPRs cons up anonymous uncontexted VAR_DECLs. */
9464 gcc_checking_assert (!DECL_NAME (t)
9465 && DECL_ARTIFICIAL (t));
9466 break;
9468 case PARM_DECL:
9469 /* REQUIRES_EXPRs have a tree list of uncontexted
9470 PARM_DECLS. It'd be nice if they had a
9471 distinguishing flag to double check. */
9472 break;
9474 goto by_value;
9478 skip_normal:
9479 if (DECL_P (t) && !decl_node (t, ref))
9480 goto done;
9482 /* Otherwise by value */
9483 by_value:
9484 tree_value (t);
9486 done:
9487 /* And, breath out. */
9488 dump.outdent ();
9491 /* Stream in a tree node. */
9493 tree
9494 trees_in::tree_node (bool is_use)
9496 if (get_overrun ())
9497 return NULL_TREE;
9499 dump.indent ();
9500 int tag = i ();
9501 tree res = NULL_TREE;
9502 switch (tag)
9504 default:
9505 /* backref, pull it out of the map. */
9506 res = back_ref (tag);
9507 break;
9509 case tt_null:
9510 /* NULL_TREE. */
9511 break;
9513 case tt_fixed:
9514 /* A fixed ref, find it in the fixed_ref array. */
9516 unsigned fix = u ();
9517 if (fix < (*fixed_trees).length ())
9519 res = (*fixed_trees)[fix];
9520 dump (dumper::TREE) && dump ("Read fixed:%u %C:%N%S", fix,
9521 TREE_CODE (res), res, res);
9524 if (!res)
9525 set_overrun ();
9527 break;
9529 case tt_parm:
9531 tree fn = tree_node ();
9532 if (fn && TREE_CODE (fn) == FUNCTION_DECL)
9533 res = tree_node ();
9534 if (res)
9535 dump (dumper::TREE)
9536 && dump ("Read %s reference %N",
9537 TREE_CODE (res) == PARM_DECL ? "parameter" : "result",
9538 res);
9540 break;
9542 case tt_node:
9543 /* A new node. Stream it in. */
9544 res = tree_value ();
9545 break;
9547 case tt_decl:
9548 /* A new decl. Stream it in. */
9549 res = decl_value ();
9550 break;
9552 case tt_tpl_parm:
9553 /* A template parameter. Stream it in. */
9554 res = tpl_parm_value ();
9555 break;
9557 case tt_id:
9558 /* An identifier node. */
9560 size_t l;
9561 const char *chars = str (&l);
9562 res = get_identifier_with_length (chars, l);
9563 int tag = insert (res);
9564 dump (dumper::TREE)
9565 && dump ("Read identifier:%d %N", tag, res);
9567 break;
9569 case tt_conv_id:
9570 /* A conversion operator. Get the type and recreate the
9571 identifier. */
9573 tree type = tree_node ();
9574 if (!get_overrun ())
9576 res = type ? make_conv_op_name (type) : conv_op_identifier;
9577 int tag = insert (res);
9578 dump (dumper::TREE)
9579 && dump ("Created conv_op:%d %S for %N", tag, res, type);
9582 break;
9584 case tt_anon_id:
9585 case tt_lambda_id:
9586 /* An anonymous or lambda id. */
9588 res = make_anon_name ();
9589 if (tag == tt_lambda_id)
9590 IDENTIFIER_LAMBDA_P (res) = true;
9591 int tag = insert (res);
9592 dump (dumper::TREE)
9593 && dump ("Read %s identifier:%d %N",
9594 IDENTIFIER_LAMBDA_P (res) ? "lambda" : "anon", tag, res);
9596 break;
9598 case tt_typedef_type:
9599 res = tree_node ();
9600 if (res)
9602 dump (dumper::TREE)
9603 && dump ("Read %stypedef %C:%N",
9604 DECL_IMPLICIT_TYPEDEF_P (res) ? "implicit " : "",
9605 TREE_CODE (res), res);
9606 res = TREE_TYPE (res);
9608 break;
9610 case tt_derived_type:
9611 /* A type derived from some other type. */
9613 enum tree_code code = tree_code (u ());
9614 res = tree_node ();
9616 switch (code)
9618 default:
9619 set_overrun ();
9620 break;
9622 case ARRAY_TYPE:
9624 tree domain = tree_node ();
9625 int dep = u ();
9626 if (!get_overrun ())
9627 res = build_cplus_array_type (res, domain, dep);
9629 break;
9631 case COMPLEX_TYPE:
9632 if (!get_overrun ())
9633 res = build_complex_type (res);
9634 break;
9636 case BOOLEAN_TYPE:
9638 unsigned precision = u ();
9639 if (!get_overrun ())
9640 res = build_nonstandard_boolean_type (precision);
9642 break;
9644 case INTEGER_TYPE:
9645 if (res)
9647 /* A range type (representing an array domain). */
9648 tree min = tree_node ();
9649 tree max = tree_node ();
9651 if (!get_overrun ())
9652 res = build_range_type (res, min, max);
9654 else
9656 /* A new integral type (representing a bitfield). */
9657 unsigned enc = u ();
9658 if (!get_overrun ())
9659 res = build_nonstandard_integer_type (enc >> 1, enc & 1);
9661 break;
9663 case FUNCTION_TYPE:
9664 case METHOD_TYPE:
9666 tree klass = code == METHOD_TYPE ? tree_node () : NULL_TREE;
9667 tree args = tree_node ();
9668 if (!get_overrun ())
9670 if (klass)
9671 res = build_method_type_directly (klass, res, args);
9672 else
9673 res = build_function_type (res, args);
9676 break;
9678 case OFFSET_TYPE:
9680 tree base = tree_node ();
9681 if (!get_overrun ())
9682 res = build_offset_type (base, res);
9684 break;
9686 case POINTER_TYPE:
9687 if (!get_overrun ())
9688 res = build_pointer_type (res);
9689 break;
9691 case REFERENCE_TYPE:
9693 bool rval = bool (u ());
9694 if (!get_overrun ())
9695 res = cp_build_reference_type (res, rval);
9697 break;
9699 case DECLTYPE_TYPE:
9700 case TYPEOF_TYPE:
9701 case DEPENDENT_OPERATOR_TYPE:
9703 tree expr = tree_node ();
9704 if (!get_overrun ())
9706 res = cxx_make_type (code);
9707 TYPE_VALUES_RAW (res) = expr;
9708 if (code == DECLTYPE_TYPE)
9709 tree_node_bools (res);
9710 SET_TYPE_STRUCTURAL_EQUALITY (res);
9713 break;
9715 case TRAIT_TYPE:
9717 tree kind = tree_node ();
9718 tree type1 = tree_node ();
9719 tree type2 = tree_node ();
9720 if (!get_overrun ())
9722 res = cxx_make_type (TRAIT_TYPE);
9723 TRAIT_TYPE_KIND_RAW (res) = kind;
9724 TRAIT_TYPE_TYPE1 (res) = type1;
9725 TRAIT_TYPE_TYPE2 (res) = type2;
9726 SET_TYPE_STRUCTURAL_EQUALITY (res);
9729 break;
9731 case TYPE_ARGUMENT_PACK:
9732 if (!get_overrun ())
9734 tree pack = cxx_make_type (TYPE_ARGUMENT_PACK);
9735 ARGUMENT_PACK_ARGS (pack) = res;
9736 res = pack;
9738 break;
9740 case TYPE_PACK_EXPANSION:
9742 bool local = u ();
9743 tree param_packs = tree_node ();
9744 tree extra_args = tree_node ();
9745 if (!get_overrun ())
9747 tree expn = cxx_make_type (TYPE_PACK_EXPANSION);
9748 SET_TYPE_STRUCTURAL_EQUALITY (expn);
9749 PACK_EXPANSION_PATTERN (expn) = res;
9750 PACK_EXPANSION_PARAMETER_PACKS (expn) = param_packs;
9751 PACK_EXPANSION_EXTRA_ARGS (expn) = extra_args;
9752 PACK_EXPANSION_LOCAL_P (expn) = local;
9753 res = expn;
9756 break;
9758 case TYPENAME_TYPE:
9760 tree ctx = tree_node ();
9761 tree name = tree_node ();
9762 tree fullname = tree_node ();
9763 enum tag_types tag_type = tag_types (u ());
9765 if (!get_overrun ())
9766 res = build_typename_type (ctx, name, fullname, tag_type);
9768 break;
9770 case UNBOUND_CLASS_TEMPLATE:
9772 tree ctx = tree_node ();
9773 tree name = tree_node ();
9774 tree parms = tree_node ();
9776 if (!get_overrun ())
9777 res = make_unbound_class_template_raw (ctx, name, parms);
9779 break;
9781 case VECTOR_TYPE:
9783 poly_uint64 nunits;
9784 for (unsigned ix = 0; ix != NUM_POLY_INT_COEFFS; ix++)
9785 nunits.coeffs[ix] = wu ();
9786 if (!get_overrun ())
9787 res = build_vector_type (res, nunits);
9789 break;
9792 int tag = i ();
9793 if (!tag)
9795 tag = insert (res);
9796 if (res)
9797 dump (dumper::TREE)
9798 && dump ("Created:%d derived type %C", tag, code);
9800 else
9801 res = back_ref (tag);
9803 break;
9805 case tt_variant_type:
9806 /* Variant of some type. */
9808 res = tree_node ();
9809 int flags = i ();
9810 if (get_overrun ())
9812 else if (flags < 0)
9813 /* No change. */;
9814 else if (TREE_CODE (res) == FUNCTION_TYPE
9815 || TREE_CODE (res) == METHOD_TYPE)
9817 cp_ref_qualifier rqual = cp_ref_qualifier (flags & 3);
9818 bool late = (flags >> 2) & 1;
9819 cp_cv_quals quals = cp_cv_quals (flags >> 3);
9821 tree raises = tree_node ();
9822 if (raises == error_mark_node)
9823 raises = TYPE_RAISES_EXCEPTIONS (res);
9825 res = build_cp_fntype_variant (res, rqual, raises, late);
9826 if (TREE_CODE (res) == FUNCTION_TYPE)
9827 res = apply_memfn_quals (res, quals, rqual);
9829 else
9831 res = build_aligned_type (res, (1u << flags) >> 1);
9832 TYPE_USER_ALIGN (res) = true;
9835 if (tree attribs = tree_node ())
9836 res = cp_build_type_attribute_variant (res, attribs);
9838 int quals = i ();
9839 if (quals >= 0 && !get_overrun ())
9840 res = cp_build_qualified_type (res, quals);
9842 int tag = i ();
9843 if (!tag)
9845 tag = insert (res);
9846 if (res)
9847 dump (dumper::TREE)
9848 && dump ("Created:%d variant type %C", tag, TREE_CODE (res));
9850 else
9851 res = back_ref (tag);
9853 break;
9855 case tt_tinfo_var:
9856 case tt_tinfo_typedef:
9857 /* A tinfo var or typedef. */
9859 bool is_var = tag == tt_tinfo_var;
9860 unsigned ix = u ();
9861 tree type = NULL_TREE;
9863 if (is_var)
9865 tree name = tree_node ();
9866 type = tree_node ();
9868 if (!get_overrun ())
9869 res = get_tinfo_decl_direct (type, name, int (ix));
9871 else
9873 if (!get_overrun ())
9875 type = get_pseudo_tinfo_type (ix);
9876 res = TYPE_NAME (type);
9879 if (res)
9881 int tag = insert (res);
9882 dump (dumper::TREE)
9883 && dump ("Created tinfo_%s:%d %S:%u for %N",
9884 is_var ? "var" : "decl", tag, res, ix, type);
9885 if (!is_var)
9887 tag = insert (type);
9888 dump (dumper::TREE)
9889 && dump ("Created tinfo_type:%d %u %N", tag, ix, type);
9893 break;
9895 case tt_ptrmem_type:
9896 /* A pointer to member function. */
9898 tree type = tree_node ();
9899 if (type && TREE_CODE (type) == POINTER_TYPE
9900 && TREE_CODE (TREE_TYPE (type)) == METHOD_TYPE)
9902 res = build_ptrmemfunc_type (type);
9903 int tag = insert (res);
9904 dump (dumper::TREE) && dump ("Created:%d ptrmem type", tag);
9906 else
9907 set_overrun ();
9909 break;
9911 case tt_nttp_var:
9912 /* An NTTP object. */
9914 tree init = tree_node ();
9915 tree name = tree_node ();
9916 if (!get_overrun ())
9918 res = get_template_parm_object (init, name);
9919 int tag = insert (res);
9920 dump (dumper::TREE)
9921 && dump ("Created nttp object:%d %N", tag, name);
9924 break;
9926 case tt_enum_value:
9927 /* An enum const value. */
9929 if (tree decl = tree_node ())
9931 dump (dumper::TREE) && dump ("Read enum value %N", decl);
9932 res = DECL_INITIAL (decl);
9935 if (!res)
9936 set_overrun ();
9938 break;
9940 case tt_enum_decl:
9941 /* An enum decl. */
9943 tree ctx = tree_node ();
9944 tree name = tree_node ();
9946 if (!get_overrun ()
9947 && TREE_CODE (ctx) == ENUMERAL_TYPE)
9948 res = find_enum_member (ctx, name);
9950 if (!res)
9951 set_overrun ();
9952 else
9954 int tag = insert (res);
9955 dump (dumper::TREE)
9956 && dump ("Read enum decl:%d %C:%N", tag, TREE_CODE (res), res);
9959 break;
9961 case tt_data_member:
9962 /* A data member. */
9964 tree ctx = tree_node ();
9965 tree name = tree_node ();
9967 if (!get_overrun ()
9968 && RECORD_OR_UNION_TYPE_P (ctx))
9970 if (name)
9971 res = lookup_class_binding (ctx, name);
9972 else
9973 res = lookup_field_ident (ctx, u ());
9975 if (!res
9976 || TREE_CODE (res) != FIELD_DECL
9977 || DECL_CONTEXT (res) != ctx)
9978 res = NULL_TREE;
9981 if (!res)
9982 set_overrun ();
9983 else
9985 int tag = insert (res);
9986 dump (dumper::TREE)
9987 && dump ("Read member:%d %C:%N", tag, TREE_CODE (res), res);
9990 break;
9992 case tt_binfo:
9993 /* A BINFO. Walk the tree of the dominating type. */
9995 tree type;
9996 unsigned ix = binfo_mergeable (&type);
9997 if (type)
9999 res = TYPE_BINFO (type);
10000 for (; ix && res; res = TREE_CHAIN (res))
10001 ix--;
10002 if (!res)
10003 set_overrun ();
10006 if (get_overrun ())
10007 break;
10009 /* Insert binfo into backreferences. */
10010 tag = insert (res);
10011 dump (dumper::TREE) && dump ("Read binfo:%d %N", tag, res);
10013 break;
10015 case tt_vtable:
10017 unsigned ix = u ();
10018 tree ctx = tree_node ();
10019 dump (dumper::TREE) && dump ("Reading vtable %N[%u]", ctx, ix);
10020 if (TREE_CODE (ctx) == RECORD_TYPE && TYPE_LANG_SPECIFIC (ctx))
10021 for (res = CLASSTYPE_VTABLES (ctx); res; res = DECL_CHAIN (res))
10022 if (!ix--)
10023 break;
10024 if (!res)
10025 set_overrun ();
10027 break;
10029 case tt_thunk:
10031 int fixed = i ();
10032 tree target = tree_node ();
10033 tree virt = tree_node ();
10035 for (tree thunk = DECL_THUNKS (target);
10036 thunk; thunk = DECL_CHAIN (thunk))
10037 if (THUNK_FIXED_OFFSET (thunk) == fixed
10038 && !THUNK_VIRTUAL_OFFSET (thunk) == !virt
10039 && (!virt
10040 || tree_int_cst_equal (virt, THUNK_VIRTUAL_OFFSET (thunk))))
10042 res = thunk;
10043 break;
10046 int tag = insert (res);
10047 if (res)
10048 dump (dumper::TREE)
10049 && dump ("Read:%d thunk %N to %N", tag, DECL_NAME (res), target);
10050 else
10051 set_overrun ();
10053 break;
10055 case tt_clone_ref:
10057 tree target = tree_node ();
10058 tree name = tree_node ();
10060 if (DECL_P (target) && DECL_MAYBE_IN_CHARGE_CDTOR_P (target))
10062 tree clone;
10063 FOR_EVERY_CLONE (clone, target)
10064 if (DECL_NAME (clone) == name)
10066 res = clone;
10067 break;
10071 /* A clone might have a different vtable entry. */
10072 if (res && DECL_VIRTUAL_P (res))
10073 DECL_VINDEX (res) = tree_node ();
10075 if (!res)
10076 set_overrun ();
10077 int tag = insert (res);
10078 if (res)
10079 dump (dumper::TREE)
10080 && dump ("Read:%d clone %N of %N", tag, DECL_NAME (res), target);
10081 else
10082 set_overrun ();
10084 break;
10086 case tt_entity:
10087 /* Index into the entity table. Perhaps not loaded yet! */
10089 unsigned origin = state->slurp->remap_module (u ());
10090 unsigned ident = u ();
10091 module_state *from = (*modules)[origin];
10093 if (!origin || ident >= from->entity_num)
10094 set_overrun ();
10095 if (!get_overrun ())
10097 binding_slot *slot = &(*entity_ary)[from->entity_lwm + ident];
10098 if (slot->is_lazy ())
10099 if (!from->lazy_load (ident, slot))
10100 set_overrun ();
10101 res = *slot;
10104 if (res)
10106 const char *kind = (origin != state->mod ? "Imported" : "Named");
10107 int tag = insert (res);
10108 dump (dumper::TREE)
10109 && dump ("%s:%d %C:%N@%M", kind, tag, TREE_CODE (res),
10110 res, (*modules)[origin]);
10112 if (!add_indirects (res))
10114 set_overrun ();
10115 res = NULL_TREE;
10119 break;
10121 case tt_template:
10122 /* A template. */
10123 if (tree tpl = tree_node ())
10125 res = DECL_TEMPLATE_RESULT (tpl);
10126 dump (dumper::TREE)
10127 && dump ("Read template %C:%N", TREE_CODE (res), res);
10129 break;
10132 if (is_use && !unused && res && DECL_P (res) && !TREE_USED (res))
10134 /* Mark decl used as mark_used does -- we cannot call
10135 mark_used in the middle of streaming, we only need a subset
10136 of its functionality. */
10137 TREE_USED (res) = true;
10139 /* And for structured bindings also the underlying decl. */
10140 if (DECL_DECOMPOSITION_P (res) && DECL_DECOMP_BASE (res))
10141 TREE_USED (DECL_DECOMP_BASE (res)) = true;
10143 if (DECL_CLONED_FUNCTION_P (res))
10144 TREE_USED (DECL_CLONED_FUNCTION (res)) = true;
10147 dump.outdent ();
10148 return res;
10151 void
10152 trees_out::tpl_parms (tree parms, unsigned &tpl_levels)
10154 if (!parms)
10155 return;
10157 if (TREE_VISITED (parms))
10159 ref_node (parms);
10160 return;
10163 tpl_parms (TREE_CHAIN (parms), tpl_levels);
10165 tree vec = TREE_VALUE (parms);
10166 unsigned len = TREE_VEC_LENGTH (vec);
10167 /* Depth. */
10168 int tag = insert (parms);
10169 if (streaming_p ())
10171 i (len + 1);
10172 dump (dumper::TREE)
10173 && dump ("Writing template parms:%d level:%N length:%d",
10174 tag, TREE_PURPOSE (parms), len);
10176 tree_node (TREE_PURPOSE (parms));
10178 for (unsigned ix = 0; ix != len; ix++)
10180 tree parm = TREE_VEC_ELT (vec, ix);
10181 tree decl = TREE_VALUE (parm);
10183 gcc_checking_assert (DECL_TEMPLATE_PARM_P (decl));
10184 if (CHECKING_P)
10185 switch (TREE_CODE (decl))
10187 default: gcc_unreachable ();
10189 case TEMPLATE_DECL:
10190 gcc_assert ((TREE_CODE (TREE_TYPE (decl)) == TEMPLATE_TEMPLATE_PARM)
10191 && (TREE_CODE (DECL_TEMPLATE_RESULT (decl)) == TYPE_DECL)
10192 && (TYPE_NAME (TREE_TYPE (decl)) == decl));
10193 break;
10195 case TYPE_DECL:
10196 gcc_assert ((TREE_CODE (TREE_TYPE (decl)) == TEMPLATE_TYPE_PARM)
10197 && (TYPE_NAME (TREE_TYPE (decl)) == decl));
10198 break;
10200 case PARM_DECL:
10201 gcc_assert ((TREE_CODE (DECL_INITIAL (decl)) == TEMPLATE_PARM_INDEX)
10202 && (TREE_CODE (TEMPLATE_PARM_DECL (DECL_INITIAL (decl)))
10203 == CONST_DECL)
10204 && (DECL_TEMPLATE_PARM_P
10205 (TEMPLATE_PARM_DECL (DECL_INITIAL (decl)))));
10206 break;
10209 tree_node (decl);
10210 tree_node (TEMPLATE_PARM_CONSTRAINTS (parm));
10213 tpl_levels++;
10216 tree
10217 trees_in::tpl_parms (unsigned &tpl_levels)
10219 tree parms = NULL_TREE;
10221 while (int len = i ())
10223 if (len < 0)
10225 parms = back_ref (len);
10226 continue;
10229 len -= 1;
10230 parms = tree_cons (NULL_TREE, NULL_TREE, parms);
10231 int tag = insert (parms);
10232 TREE_PURPOSE (parms) = tree_node ();
10234 dump (dumper::TREE)
10235 && dump ("Reading template parms:%d level:%N length:%d",
10236 tag, TREE_PURPOSE (parms), len);
10238 tree vec = make_tree_vec (len);
10239 for (int ix = 0; ix != len; ix++)
10241 tree decl = tree_node ();
10242 if (!decl)
10243 return NULL_TREE;
10245 tree parm = build_tree_list (NULL, decl);
10246 TEMPLATE_PARM_CONSTRAINTS (parm) = tree_node ();
10248 TREE_VEC_ELT (vec, ix) = parm;
10251 TREE_VALUE (parms) = vec;
10252 tpl_levels++;
10255 return parms;
10258 void
10259 trees_out::tpl_parms_fini (tree tmpl, unsigned tpl_levels)
10261 for (tree parms = DECL_TEMPLATE_PARMS (tmpl);
10262 tpl_levels--; parms = TREE_CHAIN (parms))
10264 tree vec = TREE_VALUE (parms);
10266 tree_node (TREE_TYPE (vec));
10267 for (unsigned ix = TREE_VEC_LENGTH (vec); ix--;)
10269 tree parm = TREE_VEC_ELT (vec, ix);
10270 tree dflt = TREE_PURPOSE (parm);
10271 tree_node (dflt);
10273 /* Template template parameters need a context of their owning
10274 template. This is quite tricky to infer correctly on stream-in
10275 (see PR c++/98881) so we'll just provide it directly. */
10276 tree decl = TREE_VALUE (parm);
10277 if (TREE_CODE (decl) == TEMPLATE_DECL)
10278 tree_node (DECL_CONTEXT (decl));
10283 bool
10284 trees_in::tpl_parms_fini (tree tmpl, unsigned tpl_levels)
10286 for (tree parms = DECL_TEMPLATE_PARMS (tmpl);
10287 tpl_levels--; parms = TREE_CHAIN (parms))
10289 tree vec = TREE_VALUE (parms);
10291 TREE_TYPE (vec) = tree_node ();
10292 for (unsigned ix = TREE_VEC_LENGTH (vec); ix--;)
10294 tree parm = TREE_VEC_ELT (vec, ix);
10295 tree dflt = tree_node ();
10296 TREE_PURPOSE (parm) = dflt;
10298 tree decl = TREE_VALUE (parm);
10299 if (TREE_CODE (decl) == TEMPLATE_DECL)
10300 DECL_CONTEXT (decl) = tree_node ();
10302 if (get_overrun ())
10303 return false;
10306 return true;
10309 /* PARMS is a LIST, one node per level.
10310 TREE_VALUE is a TREE_VEC of parm info for that level.
10311 each ELT is a TREE_LIST
10312 TREE_VALUE is PARM_DECL, TYPE_DECL or TEMPLATE_DECL
10313 TREE_PURPOSE is the default value. */
10315 void
10316 trees_out::tpl_header (tree tpl, unsigned *tpl_levels)
10318 tree parms = DECL_TEMPLATE_PARMS (tpl);
10319 tpl_parms (parms, *tpl_levels);
10321 /* Mark end. */
10322 if (streaming_p ())
10323 u (0);
10325 if (*tpl_levels)
10326 tree_node (TEMPLATE_PARMS_CONSTRAINTS (parms));
10329 bool
10330 trees_in::tpl_header (tree tpl, unsigned *tpl_levels)
10332 tree parms = tpl_parms (*tpl_levels);
10333 if (!parms)
10334 return false;
10336 DECL_TEMPLATE_PARMS (tpl) = parms;
10338 if (*tpl_levels)
10339 TEMPLATE_PARMS_CONSTRAINTS (parms) = tree_node ();
10341 return true;
10344 /* Stream skeleton parm nodes, with their flags, type & parm indices.
10345 All the parms will have consecutive tags. */
10347 void
10348 trees_out::fn_parms_init (tree fn)
10350 /* First init them. */
10351 int base_tag = ref_num - 1;
10352 int ix = 0;
10353 for (tree parm = DECL_ARGUMENTS (fn);
10354 parm; parm = DECL_CHAIN (parm), ix++)
10356 if (streaming_p ())
10358 start (parm);
10359 tree_node_bools (parm);
10361 int tag = insert (parm);
10362 gcc_checking_assert (base_tag - ix == tag);
10364 /* Mark the end. */
10365 if (streaming_p ())
10366 u (0);
10368 /* Now stream their contents. */
10369 ix = 0;
10370 for (tree parm = DECL_ARGUMENTS (fn);
10371 parm; parm = DECL_CHAIN (parm), ix++)
10373 if (streaming_p ())
10374 dump (dumper::TREE)
10375 && dump ("Writing parm:%d %u (%N) of %N",
10376 base_tag - ix, ix, parm, fn);
10377 tree_node_vals (parm);
10380 if (!streaming_p ())
10382 /* We must walk contract attrs so the dependency graph is complete. */
10383 for (tree contract = DECL_CONTRACTS (fn);
10384 contract;
10385 contract = CONTRACT_CHAIN (contract))
10386 tree_node (contract);
10389 /* Write a reference to contracts pre/post functions, if any, to avoid
10390 regenerating them in importers. */
10391 tree_node (DECL_PRE_FN (fn));
10392 tree_node (DECL_POST_FN (fn));
10395 /* Build skeleton parm nodes, read their flags, type & parm indices. */
10398 trees_in::fn_parms_init (tree fn)
10400 int base_tag = ~(int)back_refs.length ();
10402 tree *parm_ptr = &DECL_ARGUMENTS (fn);
10403 int ix = 0;
10404 for (; int code = u (); ix++)
10406 tree parm = start (code);
10407 if (!tree_node_bools (parm))
10408 return 0;
10410 int tag = insert (parm);
10411 gcc_checking_assert (base_tag - ix == tag);
10412 *parm_ptr = parm;
10413 parm_ptr = &DECL_CHAIN (parm);
10416 ix = 0;
10417 for (tree parm = DECL_ARGUMENTS (fn);
10418 parm; parm = DECL_CHAIN (parm), ix++)
10420 dump (dumper::TREE)
10421 && dump ("Reading parm:%d %u (%N) of %N",
10422 base_tag - ix, ix, parm, fn);
10423 if (!tree_node_vals (parm))
10424 return 0;
10427 /* Reload references to contract functions, if any. */
10428 tree pre_fn = tree_node ();
10429 tree post_fn = tree_node ();
10430 set_contract_functions (fn, pre_fn, post_fn);
10432 return base_tag;
10435 /* Read the remaining parm node data. Replace with existing (if
10436 non-null) in the map. */
10438 void
10439 trees_in::fn_parms_fini (int tag, tree fn, tree existing, bool is_defn)
10441 tree existing_parm = existing ? DECL_ARGUMENTS (existing) : NULL_TREE;
10442 tree parms = DECL_ARGUMENTS (fn);
10443 unsigned ix = 0;
10444 for (tree parm = parms; parm; parm = DECL_CHAIN (parm), ix++)
10446 if (existing_parm)
10448 if (is_defn && !DECL_SAVED_TREE (existing))
10450 /* If we're about to become the definition, set the
10451 names of the parms from us. */
10452 DECL_NAME (existing_parm) = DECL_NAME (parm);
10453 DECL_SOURCE_LOCATION (existing_parm) = DECL_SOURCE_LOCATION (parm);
10456 back_refs[~tag] = existing_parm;
10457 existing_parm = DECL_CHAIN (existing_parm);
10459 tag--;
10463 /* Encode into KEY the position of the local type (class or enum)
10464 declaration DECL within FN. The position is encoded as the
10465 index of the innermost BLOCK (numbered in BFS order) along with
10466 the index within its BLOCK_VARS list. */
10468 void
10469 trees_out::key_local_type (merge_key& key, tree decl, tree fn)
10471 auto_vec<tree, 4> blocks;
10472 blocks.quick_push (DECL_INITIAL (fn));
10473 unsigned block_ix = 0;
10474 while (block_ix != blocks.length ())
10476 tree block = blocks[block_ix];
10477 unsigned decl_ix = 0;
10478 for (tree var = BLOCK_VARS (block); var; var = DECL_CHAIN (var))
10480 if (TREE_CODE (var) != TYPE_DECL)
10481 continue;
10482 if (var == decl)
10484 key.index = (block_ix << 10) | decl_ix;
10485 return;
10487 ++decl_ix;
10489 for (tree sub = BLOCK_SUBBLOCKS (block); sub; sub = BLOCK_CHAIN (sub))
10490 blocks.safe_push (sub);
10491 ++block_ix;
10494 /* Not-found value. */
10495 key.index = 1023;
10498 /* Look up the local type corresponding at the position encoded by
10499 KEY within FN and named NAME. */
10501 tree
10502 trees_in::key_local_type (const merge_key& key, tree fn, tree name)
10504 if (!DECL_INITIAL (fn))
10505 return NULL_TREE;
10507 const unsigned block_pos = key.index >> 10;
10508 const unsigned decl_pos = key.index & 1023;
10510 if (decl_pos == 1023)
10511 return NULL_TREE;
10513 auto_vec<tree, 4> blocks;
10514 blocks.quick_push (DECL_INITIAL (fn));
10515 unsigned block_ix = 0;
10516 while (block_ix != blocks.length ())
10518 tree block = blocks[block_ix];
10519 if (block_ix == block_pos)
10521 unsigned decl_ix = 0;
10522 for (tree var = BLOCK_VARS (block); var; var = DECL_CHAIN (var))
10524 if (TREE_CODE (var) != TYPE_DECL)
10525 continue;
10526 /* Prefer using the identifier as the key for more robustness
10527 to ODR violations, except for anonymous types since their
10528 compiler-generated identifiers aren't stable. */
10529 if (IDENTIFIER_ANON_P (name)
10530 ? decl_ix == decl_pos
10531 : DECL_NAME (var) == name)
10532 return var;
10533 ++decl_ix;
10535 return NULL_TREE;
10537 for (tree sub = BLOCK_SUBBLOCKS (block); sub; sub = BLOCK_CHAIN (sub))
10538 blocks.safe_push (sub);
10539 ++block_ix;
10542 return NULL_TREE;
10545 /* DEP is the depset of some decl we're streaming by value. Determine
10546 the merging behaviour. */
10548 merge_kind
10549 trees_out::get_merge_kind (tree decl, depset *dep)
10551 if (!dep)
10553 if (VAR_OR_FUNCTION_DECL_P (decl))
10555 /* Any var or function with template info should have DEP. */
10556 gcc_checking_assert (!DECL_LANG_SPECIFIC (decl)
10557 || !DECL_TEMPLATE_INFO (decl));
10558 if (DECL_LOCAL_DECL_P (decl))
10559 return MK_unique;
10562 /* Either unique, or some member of a class that cannot have an
10563 out-of-class definition. For instance a FIELD_DECL. */
10564 tree ctx = CP_DECL_CONTEXT (decl);
10565 if (TREE_CODE (ctx) == FUNCTION_DECL)
10567 /* USING_DECLs and NAMESPACE_DECLs cannot have DECL_TEMPLATE_INFO --
10568 this isn't permitting them to have one. */
10569 gcc_checking_assert (TREE_CODE (decl) == USING_DECL
10570 || TREE_CODE (decl) == NAMESPACE_DECL
10571 || !DECL_LANG_SPECIFIC (decl)
10572 || !DECL_TEMPLATE_INFO (decl));
10574 return MK_unique;
10577 if (TREE_CODE (decl) == TEMPLATE_DECL
10578 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10579 return MK_local_friend;
10581 gcc_checking_assert (TYPE_P (ctx));
10582 if (TREE_CODE (decl) == USING_DECL)
10583 return MK_field;
10585 if (TREE_CODE (decl) == FIELD_DECL)
10587 if (DECL_NAME (decl))
10589 /* Anonymous FIELD_DECLs have a NULL name. */
10590 gcc_checking_assert (!IDENTIFIER_ANON_P (DECL_NAME (decl)));
10591 return MK_named;
10594 if (!DECL_NAME (decl)
10595 && !RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl))
10596 && !DECL_BIT_FIELD_REPRESENTATIVE (decl))
10598 /* The underlying storage unit for a bitfield. We do not
10599 need to dedup it, because it's only reachable through
10600 the bitfields it represents. And those are deduped. */
10601 // FIXME: Is that assertion correct -- do we ever fish it
10602 // out and put it in an expr?
10603 gcc_checking_assert ((TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
10604 ? TREE_CODE (TREE_TYPE (TREE_TYPE (decl)))
10605 : TREE_CODE (TREE_TYPE (decl)))
10606 == INTEGER_TYPE);
10607 return MK_unique;
10610 return MK_field;
10613 if (TREE_CODE (decl) == CONST_DECL)
10614 return MK_named;
10616 if (TREE_CODE (decl) == VAR_DECL
10617 && DECL_VTABLE_OR_VTT_P (decl))
10618 return MK_vtable;
10620 if (DECL_THUNK_P (decl))
10621 /* Thunks are unique-enough, because they're only referenced
10622 from the vtable. And that's either new (so we want the
10623 thunks), or it's a duplicate (so it will be dropped). */
10624 return MK_unique;
10626 /* There should be no other cases. */
10627 gcc_unreachable ();
10630 gcc_checking_assert (TREE_CODE (decl) != FIELD_DECL
10631 && TREE_CODE (decl) != USING_DECL
10632 && TREE_CODE (decl) != CONST_DECL);
10634 if (is_key_order ())
10636 /* When doing the mergeablilty graph, there's an indirection to
10637 the actual depset. */
10638 gcc_assert (dep->is_special ());
10639 dep = dep->deps[0];
10642 gcc_checking_assert (decl == dep->get_entity ());
10644 merge_kind mk = MK_named;
10645 switch (dep->get_entity_kind ())
10647 default:
10648 gcc_unreachable ();
10650 case depset::EK_PARTIAL:
10651 mk = MK_partial;
10652 break;
10654 case depset::EK_DECL:
10656 tree ctx = CP_DECL_CONTEXT (decl);
10658 switch (TREE_CODE (ctx))
10660 default:
10661 gcc_unreachable ();
10663 case FUNCTION_DECL:
10664 gcc_checking_assert
10665 (DECL_IMPLICIT_TYPEDEF_P (STRIP_TEMPLATE (decl)));
10667 mk = MK_local_type;
10668 break;
10670 case RECORD_TYPE:
10671 case UNION_TYPE:
10672 case NAMESPACE_DECL:
10673 if (DECL_NAME (decl) == as_base_identifier)
10675 mk = MK_as_base;
10676 break;
10679 /* A lambda may have a class as its context, even though it
10680 isn't a member in the traditional sense; see the test
10681 g++.dg/modules/lambda-6_a.C. */
10682 if (DECL_IMPLICIT_TYPEDEF_P (STRIP_TEMPLATE (decl))
10683 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
10684 if (tree scope
10685 = LAMBDA_EXPR_EXTRA_SCOPE (CLASSTYPE_LAMBDA_EXPR
10686 (TREE_TYPE (decl))))
10688 /* Lambdas attached to fields are keyed to its class. */
10689 if (TREE_CODE (scope) == FIELD_DECL)
10690 scope = TYPE_NAME (DECL_CONTEXT (scope));
10691 if (DECL_LANG_SPECIFIC (scope)
10692 && DECL_MODULE_KEYED_DECLS_P (scope))
10694 mk = MK_keyed;
10695 break;
10699 if (TREE_CODE (decl) == TEMPLATE_DECL
10700 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10702 mk = MK_local_friend;
10703 break;
10706 if (IDENTIFIER_ANON_P (DECL_NAME (decl)))
10708 if (RECORD_OR_UNION_TYPE_P (ctx))
10709 mk = MK_field;
10710 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
10711 && UNSCOPED_ENUM_P (TREE_TYPE (decl))
10712 && TYPE_VALUES (TREE_TYPE (decl)))
10713 /* Keyed by first enum value, and underlying type. */
10714 mk = MK_enum;
10715 else
10716 /* No way to merge it, it is an ODR land-mine. */
10717 mk = MK_unique;
10721 break;
10723 case depset::EK_SPECIALIZATION:
10725 gcc_checking_assert (dep->is_special ());
10727 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
10728 /* An block-scope classes of templates are themselves
10729 templates. */
10730 gcc_checking_assert (DECL_IMPLICIT_TYPEDEF_P (decl));
10732 if (dep->is_friend_spec ())
10733 mk = MK_friend_spec;
10734 else if (dep->is_type_spec ())
10735 mk = MK_type_spec;
10736 else
10737 mk = MK_decl_spec;
10739 if (TREE_CODE (decl) == TEMPLATE_DECL)
10741 spec_entry *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
10742 if (TREE_CODE (entry->spec) != TEMPLATE_DECL)
10743 mk = merge_kind (mk | MK_tmpl_tmpl_mask);
10746 break;
10749 return mk;
10753 /* The container of DECL -- not necessarily its context! */
10755 tree
10756 trees_out::decl_container (tree decl)
10758 int use_tpl;
10759 tree tpl = NULL_TREE;
10760 if (tree template_info = node_template_info (decl, use_tpl))
10761 tpl = TI_TEMPLATE (template_info);
10762 if (tpl == decl)
10763 tpl = nullptr;
10765 /* Stream the template we're instantiated from. */
10766 tree_node (tpl);
10768 tree container = NULL_TREE;
10769 if (TREE_CODE (decl) == TEMPLATE_DECL
10770 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10771 container = DECL_CHAIN (decl);
10772 else
10773 container = CP_DECL_CONTEXT (decl);
10775 if (TYPE_P (container))
10776 container = TYPE_NAME (container);
10778 tree_node (container);
10780 return container;
10783 tree
10784 trees_in::decl_container ()
10786 /* The maybe-template. */
10787 (void)tree_node ();
10789 tree container = tree_node ();
10791 return container;
10794 /* Write out key information about a mergeable DEP. Does not write
10795 the contents of DEP itself. The context has already been
10796 written. The container has already been streamed. */
10798 void
10799 trees_out::key_mergeable (int tag, merge_kind mk, tree decl, tree inner,
10800 tree container, depset *dep)
10802 if (dep && is_key_order ())
10804 gcc_checking_assert (dep->is_special ());
10805 dep = dep->deps[0];
10808 if (streaming_p ())
10809 dump (dumper::MERGE)
10810 && dump ("Writing:%d's %s merge key (%s) %C:%N", tag, merge_kind_name[mk],
10811 dep ? dep->entity_kind_name () : "contained",
10812 TREE_CODE (decl), decl);
10814 /* Now write the locating information. */
10815 if (mk & MK_template_mask)
10817 /* Specializations are located via their originating template,
10818 and the set of template args they specialize. */
10819 gcc_checking_assert (dep && dep->is_special ());
10820 spec_entry *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
10822 tree_node (entry->tmpl);
10823 tree_node (entry->args);
10824 if (mk & MK_tmpl_decl_mask)
10825 if (flag_concepts && TREE_CODE (inner) == VAR_DECL)
10827 /* Variable template partial specializations might need
10828 constraints (see spec_hasher::equal). It's simpler to
10829 write NULL when we don't need them. */
10830 tree constraints = NULL_TREE;
10832 if (uses_template_parms (entry->args))
10833 constraints = get_constraints (inner);
10834 tree_node (constraints);
10837 if (CHECKING_P)
10839 /* Make sure we can locate the decl. */
10840 tree existing = match_mergeable_specialization
10841 (bool (mk & MK_tmpl_decl_mask), entry);
10843 gcc_assert (existing);
10844 if (mk & MK_tmpl_decl_mask)
10846 if (mk & MK_tmpl_tmpl_mask)
10847 existing = DECL_TI_TEMPLATE (existing);
10849 else
10851 if (mk & MK_tmpl_tmpl_mask)
10852 existing = CLASSTYPE_TI_TEMPLATE (existing);
10853 else
10854 existing = TYPE_NAME (existing);
10857 /* The walkabout should have found ourselves. */
10858 gcc_checking_assert (TREE_CODE (decl) == TYPE_DECL
10859 ? same_type_p (TREE_TYPE (decl),
10860 TREE_TYPE (existing))
10861 : existing == decl);
10864 else if (mk != MK_unique)
10866 merge_key key;
10867 tree name = DECL_NAME (decl);
10869 switch (mk)
10871 default:
10872 gcc_unreachable ();
10874 case MK_named:
10875 case MK_friend_spec:
10876 if (IDENTIFIER_CONV_OP_P (name))
10877 name = conv_op_identifier;
10879 if (TREE_CODE (inner) == FUNCTION_DECL)
10881 /* Functions are distinguished by parameter types. */
10882 tree fn_type = TREE_TYPE (inner);
10884 key.ref_q = type_memfn_rqual (fn_type);
10885 key.args = TYPE_ARG_TYPES (fn_type);
10887 if (tree reqs = get_constraints (inner))
10889 if (cxx_dialect < cxx20)
10890 reqs = CI_ASSOCIATED_CONSTRAINTS (reqs);
10891 else
10892 reqs = CI_DECLARATOR_REQS (reqs);
10893 key.constraints = reqs;
10896 if (IDENTIFIER_CONV_OP_P (name)
10897 || (decl != inner
10898 && !(name == fun_identifier
10899 /* In case the user names something _FUN */
10900 && LAMBDA_TYPE_P (DECL_CONTEXT (inner)))))
10901 /* And a function template, or conversion operator needs
10902 the return type. Except for the _FUN thunk of a
10903 generic lambda, which has a recursive decl_type'd
10904 return type. */
10905 // FIXME: What if the return type is a voldemort?
10906 key.ret = fndecl_declared_return_type (inner);
10908 break;
10910 case MK_field:
10912 unsigned ix = 0;
10913 if (TREE_CODE (inner) != FIELD_DECL)
10914 name = NULL_TREE;
10915 else
10916 gcc_checking_assert (!name || !IDENTIFIER_ANON_P (name));
10918 for (tree field = TYPE_FIELDS (TREE_TYPE (container));
10919 ; field = DECL_CHAIN (field))
10921 tree finner = STRIP_TEMPLATE (field);
10922 if (TREE_CODE (finner) == TREE_CODE (inner))
10924 if (finner == inner)
10925 break;
10926 ix++;
10929 key.index = ix;
10931 break;
10933 case MK_vtable:
10935 tree vtable = CLASSTYPE_VTABLES (TREE_TYPE (container));
10936 for (unsigned ix = 0; ; vtable = DECL_CHAIN (vtable), ix++)
10937 if (vtable == decl)
10939 key.index = ix;
10940 break;
10942 name = NULL_TREE;
10944 break;
10946 case MK_as_base:
10947 gcc_checking_assert
10948 (decl == TYPE_NAME (CLASSTYPE_AS_BASE (TREE_TYPE (container))));
10949 break;
10951 case MK_local_friend:
10953 /* Find by index on the class's DECL_LIST */
10954 unsigned ix = 0;
10955 for (tree decls = CLASSTYPE_DECL_LIST (TREE_CHAIN (decl));
10956 decls; decls = TREE_CHAIN (decls))
10957 if (!TREE_PURPOSE (decls))
10959 tree frnd = friend_from_decl_list (TREE_VALUE (decls));
10960 if (frnd == decl)
10961 break;
10962 ix++;
10964 key.index = ix;
10965 name = NULL_TREE;
10967 break;
10969 case MK_local_type:
10970 key_local_type (key, STRIP_TEMPLATE (decl), container);
10971 break;
10973 case MK_enum:
10975 /* Anonymous enums are located by their first identifier,
10976 and underlying type. */
10977 tree type = TREE_TYPE (decl);
10979 gcc_checking_assert (UNSCOPED_ENUM_P (type));
10980 /* Using the type name drops the bit precision we might
10981 have been using on the enum. */
10982 key.ret = TYPE_NAME (ENUM_UNDERLYING_TYPE (type));
10983 if (tree values = TYPE_VALUES (type))
10984 name = DECL_NAME (TREE_VALUE (values));
10986 break;
10988 case MK_keyed:
10990 gcc_checking_assert (LAMBDA_TYPE_P (TREE_TYPE (inner)));
10991 tree scope = LAMBDA_EXPR_EXTRA_SCOPE (CLASSTYPE_LAMBDA_EXPR
10992 (TREE_TYPE (inner)));
10993 gcc_checking_assert (TREE_CODE (scope) == VAR_DECL
10994 || TREE_CODE (scope) == FIELD_DECL
10995 || TREE_CODE (scope) == PARM_DECL
10996 || TREE_CODE (scope) == TYPE_DECL);
10997 /* Lambdas attached to fields are keyed to the class. */
10998 if (TREE_CODE (scope) == FIELD_DECL)
10999 scope = TYPE_NAME (DECL_CONTEXT (scope));
11000 auto *root = keyed_table->get (scope);
11001 unsigned ix = root->length ();
11002 /* If we don't find it, we'll write a really big number
11003 that the reader will ignore. */
11004 while (ix--)
11005 if ((*root)[ix] == inner)
11006 break;
11008 /* Use the keyed-to decl as the 'name'. */
11009 name = scope;
11010 key.index = ix;
11012 break;
11014 case MK_partial:
11016 tree ti = get_template_info (inner);
11017 key.constraints = get_constraints (inner);
11018 key.ret = TI_TEMPLATE (ti);
11019 key.args = TI_ARGS (ti);
11021 break;
11024 tree_node (name);
11025 if (streaming_p ())
11027 unsigned code = (key.ref_q << 0) | (key.index << 2);
11028 u (code);
11031 if (mk == MK_enum)
11032 tree_node (key.ret);
11033 else if (mk == MK_partial
11034 || (mk == MK_named && inner
11035 && TREE_CODE (inner) == FUNCTION_DECL))
11037 tree_node (key.ret);
11038 tree arg = key.args;
11039 if (mk == MK_named)
11040 while (arg && arg != void_list_node)
11042 tree_node (TREE_VALUE (arg));
11043 arg = TREE_CHAIN (arg);
11045 tree_node (arg);
11046 tree_node (key.constraints);
11051 /* DECL is a new declaration that may be duplicated in OVL. Use RET &
11052 ARGS to find its clone, or NULL. If DECL's DECL_NAME is NULL, this
11053 has been found by a proxy. It will be an enum type located by its
11054 first member.
11056 We're conservative with matches, so ambiguous decls will be
11057 registered as different, then lead to a lookup error if the two
11058 modules are both visible. Perhaps we want to do something similar
11059 to duplicate decls to get ODR errors on loading? We already have
11060 some special casing for namespaces. */
11062 static tree
11063 check_mergeable_decl (merge_kind mk, tree decl, tree ovl, merge_key const &key)
11065 tree found = NULL_TREE;
11066 for (ovl_iterator iter (ovl); !found && iter; ++iter)
11068 tree match = *iter;
11070 tree d_inner = decl;
11071 tree m_inner = match;
11073 again:
11074 if (TREE_CODE (d_inner) != TREE_CODE (m_inner))
11076 if (TREE_CODE (match) == NAMESPACE_DECL
11077 && !DECL_NAMESPACE_ALIAS (match))
11078 /* Namespaces are never overloaded. */
11079 found = match;
11081 continue;
11084 switch (TREE_CODE (d_inner))
11086 case TEMPLATE_DECL:
11087 if (template_heads_equivalent_p (d_inner, m_inner))
11089 d_inner = DECL_TEMPLATE_RESULT (d_inner);
11090 m_inner = DECL_TEMPLATE_RESULT (m_inner);
11091 if (d_inner == error_mark_node
11092 && TYPE_DECL_ALIAS_P (m_inner))
11094 found = match;
11095 break;
11097 goto again;
11099 break;
11101 case FUNCTION_DECL:
11102 if (tree m_type = TREE_TYPE (m_inner))
11103 if ((!key.ret
11104 || same_type_p (key.ret, fndecl_declared_return_type (m_inner)))
11105 && type_memfn_rqual (m_type) == key.ref_q
11106 && compparms (key.args, TYPE_ARG_TYPES (m_type))
11107 /* Reject if old is a "C" builtin and new is not "C".
11108 Matches decls_match behaviour. */
11109 && (!DECL_IS_UNDECLARED_BUILTIN (m_inner)
11110 || !DECL_EXTERN_C_P (m_inner)
11111 || DECL_EXTERN_C_P (d_inner))
11112 /* Reject if one is a different member of a
11113 guarded/pre/post fn set. */
11114 && (!flag_contracts
11115 || (DECL_IS_PRE_FN_P (d_inner)
11116 == DECL_IS_PRE_FN_P (m_inner)))
11117 && (!flag_contracts
11118 || (DECL_IS_POST_FN_P (d_inner)
11119 == DECL_IS_POST_FN_P (m_inner))))
11121 tree m_reqs = get_constraints (m_inner);
11122 if (m_reqs)
11124 if (cxx_dialect < cxx20)
11125 m_reqs = CI_ASSOCIATED_CONSTRAINTS (m_reqs);
11126 else
11127 m_reqs = CI_DECLARATOR_REQS (m_reqs);
11130 if (cp_tree_equal (key.constraints, m_reqs))
11131 found = match;
11133 break;
11135 case TYPE_DECL:
11136 if (DECL_IMPLICIT_TYPEDEF_P (d_inner)
11137 == DECL_IMPLICIT_TYPEDEF_P (m_inner))
11139 if (!IDENTIFIER_ANON_P (DECL_NAME (m_inner)))
11140 return match;
11141 else if (mk == MK_enum
11142 && (TYPE_NAME (ENUM_UNDERLYING_TYPE (TREE_TYPE (m_inner)))
11143 == key.ret))
11144 found = match;
11146 break;
11148 default:
11149 found = match;
11150 break;
11154 return found;
11157 /* DECL, INNER & TYPE are a skeleton set of nodes for a decl. Only
11158 the bools have been filled in. Read its merging key and merge it.
11159 Returns the existing decl if there is one. */
11161 tree
11162 trees_in::key_mergeable (int tag, merge_kind mk, tree decl, tree inner,
11163 tree type, tree container, bool is_attached)
11165 const char *kind = "new";
11166 tree existing = NULL_TREE;
11168 if (mk & MK_template_mask)
11170 // FIXME: We could stream the specialization hash?
11171 spec_entry spec;
11172 spec.tmpl = tree_node ();
11173 spec.args = tree_node ();
11175 if (get_overrun ())
11176 return error_mark_node;
11178 DECL_NAME (decl) = DECL_NAME (spec.tmpl);
11179 DECL_CONTEXT (decl) = DECL_CONTEXT (spec.tmpl);
11180 DECL_NAME (inner) = DECL_NAME (decl);
11181 DECL_CONTEXT (inner) = DECL_CONTEXT (decl);
11183 tree constr = NULL_TREE;
11184 bool is_decl = mk & MK_tmpl_decl_mask;
11185 if (is_decl)
11187 if (flag_concepts && TREE_CODE (inner) == VAR_DECL)
11189 constr = tree_node ();
11190 if (constr)
11191 set_constraints (inner, constr);
11193 spec.spec = (mk & MK_tmpl_tmpl_mask) ? inner : decl;
11195 else
11196 spec.spec = type;
11197 existing = match_mergeable_specialization (is_decl, &spec);
11198 if (constr)
11199 /* We'll add these back later, if this is the new decl. */
11200 remove_constraints (inner);
11202 if (!existing)
11203 ; /* We'll add to the table once read. */
11204 else if (mk & MK_tmpl_decl_mask)
11206 /* A declaration specialization. */
11207 if (mk & MK_tmpl_tmpl_mask)
11208 existing = DECL_TI_TEMPLATE (existing);
11210 else
11212 /* A type specialization. */
11213 if (mk & MK_tmpl_tmpl_mask)
11214 existing = CLASSTYPE_TI_TEMPLATE (existing);
11215 else
11216 existing = TYPE_NAME (existing);
11219 else if (mk == MK_unique)
11220 kind = "unique";
11221 else
11223 tree name = tree_node ();
11225 merge_key key;
11226 unsigned code = u ();
11227 key.ref_q = cp_ref_qualifier ((code >> 0) & 3);
11228 key.index = code >> 2;
11230 if (mk == MK_enum)
11231 key.ret = tree_node ();
11232 else if (mk == MK_partial
11233 || ((mk == MK_named || mk == MK_friend_spec)
11234 && TREE_CODE (inner) == FUNCTION_DECL))
11236 key.ret = tree_node ();
11237 tree arg, *arg_ptr = &key.args;
11238 while ((arg = tree_node ())
11239 && arg != void_list_node
11240 && mk != MK_partial)
11242 *arg_ptr = tree_cons (NULL_TREE, arg, NULL_TREE);
11243 arg_ptr = &TREE_CHAIN (*arg_ptr);
11245 *arg_ptr = arg;
11246 key.constraints = tree_node ();
11249 if (get_overrun ())
11250 return error_mark_node;
11252 if (mk < MK_indirect_lwm)
11254 DECL_NAME (decl) = name;
11255 DECL_CONTEXT (decl) = FROB_CONTEXT (container);
11257 DECL_NAME (inner) = DECL_NAME (decl);
11258 DECL_CONTEXT (inner) = DECL_CONTEXT (decl);
11260 if (mk == MK_partial)
11262 for (tree spec = DECL_TEMPLATE_SPECIALIZATIONS (key.ret);
11263 spec; spec = TREE_CHAIN (spec))
11265 tree tmpl = TREE_VALUE (spec);
11266 tree ti = get_template_info (tmpl);
11267 if (template_args_equal (key.args, TI_ARGS (ti))
11268 && cp_tree_equal (key.constraints,
11269 get_constraints
11270 (DECL_TEMPLATE_RESULT (tmpl))))
11272 existing = tmpl;
11273 break;
11277 else if (mk == MK_keyed
11278 && DECL_LANG_SPECIFIC (name)
11279 && DECL_MODULE_KEYED_DECLS_P (name))
11281 gcc_checking_assert (TREE_CODE (container) == NAMESPACE_DECL
11282 || TREE_CODE (container) == TYPE_DECL);
11283 if (auto *set = keyed_table->get (name))
11284 if (key.index < set->length ())
11286 existing = (*set)[key.index];
11287 if (existing)
11289 gcc_checking_assert
11290 (DECL_IMPLICIT_TYPEDEF_P (existing));
11291 if (inner != decl)
11292 existing
11293 = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (existing));
11297 else
11298 switch (TREE_CODE (container))
11300 default:
11301 gcc_unreachable ();
11303 case NAMESPACE_DECL:
11304 if (is_attached
11305 && !(state->is_module () || state->is_partition ()))
11306 kind = "unique";
11307 else
11309 gcc_checking_assert (mk == MK_named || mk == MK_enum);
11310 tree mvec;
11311 tree *vslot = mergeable_namespace_slots (container, name,
11312 is_attached, &mvec);
11313 existing = check_mergeable_decl (mk, decl, *vslot, key);
11314 if (!existing)
11315 add_mergeable_namespace_entity (vslot, decl);
11316 else
11318 /* Note that we now have duplicates to deal with in
11319 name lookup. */
11320 if (is_attached)
11321 BINDING_VECTOR_PARTITION_DUPS_P (mvec) = true;
11322 else
11323 BINDING_VECTOR_GLOBAL_DUPS_P (mvec) = true;
11326 break;
11328 case FUNCTION_DECL:
11329 gcc_checking_assert (mk == MK_local_type);
11330 existing = key_local_type (key, container, name);
11331 if (existing && inner != decl)
11332 existing = TYPE_TI_TEMPLATE (TREE_TYPE (existing));
11333 break;
11335 case TYPE_DECL:
11336 if (is_attached && !(state->is_module () || state->is_partition ())
11337 /* Implicit member functions can come from
11338 anywhere. */
11339 && !(DECL_ARTIFICIAL (decl)
11340 && TREE_CODE (decl) == FUNCTION_DECL
11341 && !DECL_THUNK_P (decl)))
11342 kind = "unique";
11343 else
11345 tree ctx = TREE_TYPE (container);
11347 /* For some reason templated enumeral types are not marked
11348 as COMPLETE_TYPE_P, even though they have members.
11349 This may well be a bug elsewhere. */
11350 if (TREE_CODE (ctx) == ENUMERAL_TYPE)
11351 existing = find_enum_member (ctx, name);
11352 else if (COMPLETE_TYPE_P (ctx))
11354 switch (mk)
11356 default:
11357 gcc_unreachable ();
11359 case MK_named:
11360 existing = lookup_class_binding (ctx, name);
11361 if (existing)
11363 tree inner = decl;
11364 if (TREE_CODE (inner) == TEMPLATE_DECL
11365 && !DECL_MEMBER_TEMPLATE_P (inner))
11366 inner = DECL_TEMPLATE_RESULT (inner);
11368 existing = check_mergeable_decl
11369 (mk, inner, existing, key);
11371 if (!existing && DECL_ALIAS_TEMPLATE_P (decl))
11372 {} // FIXME: Insert into specialization
11373 // tables, we'll need the arguments for that!
11375 break;
11377 case MK_field:
11379 unsigned ix = key.index;
11380 for (tree field = TYPE_FIELDS (ctx);
11381 field; field = DECL_CHAIN (field))
11383 tree finner = STRIP_TEMPLATE (field);
11384 if (TREE_CODE (finner) == TREE_CODE (inner))
11385 if (!ix--)
11387 existing = field;
11388 break;
11392 break;
11394 case MK_vtable:
11396 unsigned ix = key.index;
11397 for (tree vtable = CLASSTYPE_VTABLES (ctx);
11398 vtable; vtable = DECL_CHAIN (vtable))
11399 if (!ix--)
11401 existing = vtable;
11402 break;
11405 break;
11407 case MK_as_base:
11409 tree as_base = CLASSTYPE_AS_BASE (ctx);
11410 if (as_base && as_base != ctx)
11411 existing = TYPE_NAME (as_base);
11413 break;
11415 case MK_local_friend:
11417 unsigned ix = key.index;
11418 for (tree decls = CLASSTYPE_DECL_LIST (ctx);
11419 decls; decls = TREE_CHAIN (decls))
11420 if (!TREE_PURPOSE (decls) && !ix--)
11422 existing
11423 = friend_from_decl_list (TREE_VALUE (decls));
11424 break;
11427 break;
11430 if (existing && mk < MK_indirect_lwm && mk != MK_partial
11431 && TREE_CODE (decl) == TEMPLATE_DECL
11432 && !DECL_MEMBER_TEMPLATE_P (decl))
11434 tree ti;
11435 if (DECL_IMPLICIT_TYPEDEF_P (existing))
11436 ti = TYPE_TEMPLATE_INFO (TREE_TYPE (existing));
11437 else
11438 ti = DECL_TEMPLATE_INFO (existing);
11439 existing = TI_TEMPLATE (ti);
11446 dump (dumper::MERGE)
11447 && dump ("Read:%d's %s merge key (%s) %C:%N", tag, merge_kind_name[mk],
11448 existing ? "matched" : kind, TREE_CODE (decl), decl);
11450 return existing;
11453 void
11454 trees_out::binfo_mergeable (tree binfo)
11456 tree dom = binfo;
11457 while (tree parent = BINFO_INHERITANCE_CHAIN (dom))
11458 dom = parent;
11459 tree type = BINFO_TYPE (dom);
11460 gcc_checking_assert (TYPE_BINFO (type) == dom);
11461 tree_node (type);
11462 if (streaming_p ())
11464 unsigned ix = 0;
11465 for (; dom != binfo; dom = TREE_CHAIN (dom))
11466 ix++;
11467 u (ix);
11471 unsigned
11472 trees_in::binfo_mergeable (tree *type)
11474 *type = tree_node ();
11475 return u ();
11478 /* DECL is a just streamed mergeable decl that should match EXISTING. Check
11479 it does and issue an appropriate diagnostic if not. Merge any
11480 bits from DECL to EXISTING. This is stricter matching than
11481 decls_match, because we can rely on ODR-sameness, and we cannot use
11482 decls_match because it can cause instantiations of constraints. */
11484 bool
11485 trees_in::is_matching_decl (tree existing, tree decl, bool is_typedef)
11487 // FIXME: We should probably do some duplicate decl-like stuff here
11488 // (beware, default parms should be the same?) Can we just call
11489 // duplicate_decls and teach it how to handle the module-specific
11490 // permitted/required duplications?
11492 // We know at this point that the decls have matched by key, so we
11493 // can elide some of the checking
11494 gcc_checking_assert (TREE_CODE (existing) == TREE_CODE (decl));
11496 tree d_inner = decl;
11497 tree e_inner = existing;
11498 if (TREE_CODE (decl) == TEMPLATE_DECL)
11500 d_inner = DECL_TEMPLATE_RESULT (d_inner);
11501 e_inner = DECL_TEMPLATE_RESULT (e_inner);
11502 gcc_checking_assert (TREE_CODE (e_inner) == TREE_CODE (d_inner));
11505 if (TREE_CODE (d_inner) == FUNCTION_DECL)
11507 tree e_ret = fndecl_declared_return_type (existing);
11508 tree d_ret = fndecl_declared_return_type (decl);
11510 if (decl != d_inner && DECL_NAME (d_inner) == fun_identifier
11511 && LAMBDA_TYPE_P (DECL_CONTEXT (d_inner)))
11512 /* This has a recursive type that will compare different. */;
11513 else if (!same_type_p (d_ret, e_ret))
11514 goto mismatch;
11516 tree e_type = TREE_TYPE (e_inner);
11517 tree d_type = TREE_TYPE (d_inner);
11519 if (DECL_EXTERN_C_P (d_inner) != DECL_EXTERN_C_P (e_inner))
11520 goto mismatch;
11522 for (tree e_args = TYPE_ARG_TYPES (e_type),
11523 d_args = TYPE_ARG_TYPES (d_type);
11524 e_args != d_args && (e_args || d_args);
11525 e_args = TREE_CHAIN (e_args), d_args = TREE_CHAIN (d_args))
11527 if (!(e_args && d_args))
11528 goto mismatch;
11530 if (!same_type_p (TREE_VALUE (d_args), TREE_VALUE (e_args)))
11531 goto mismatch;
11533 // FIXME: Check default values
11536 /* If EXISTING has an undeduced or uninstantiated exception
11537 specification, but DECL does not, propagate the exception
11538 specification. Otherwise we end up asserting or trying to
11539 instantiate it in the middle of loading. */
11540 tree e_spec = TYPE_RAISES_EXCEPTIONS (e_type);
11541 tree d_spec = TYPE_RAISES_EXCEPTIONS (d_type);
11542 if (DEFERRED_NOEXCEPT_SPEC_P (e_spec))
11544 if (!DEFERRED_NOEXCEPT_SPEC_P (d_spec)
11545 || (UNEVALUATED_NOEXCEPT_SPEC_P (e_spec)
11546 && !UNEVALUATED_NOEXCEPT_SPEC_P (d_spec)))
11548 dump (dumper::MERGE)
11549 && dump ("Propagating instantiated noexcept to %N", existing);
11550 TREE_TYPE (existing) = d_type;
11552 /* Propagate to existing clones. */
11553 tree clone;
11554 FOR_EACH_CLONE (clone, existing)
11556 if (TREE_TYPE (clone) == e_type)
11557 TREE_TYPE (clone) = d_type;
11558 else
11559 TREE_TYPE (clone)
11560 = build_exception_variant (TREE_TYPE (clone), d_spec);
11564 else if (!DEFERRED_NOEXCEPT_SPEC_P (d_spec)
11565 && !comp_except_specs (d_spec, e_spec, ce_type))
11566 goto mismatch;
11568 /* Similarly if EXISTING has an undeduced return type, but DECL's
11569 is already deduced. */
11570 if (undeduced_auto_decl (existing) && !undeduced_auto_decl (decl))
11572 dump (dumper::MERGE)
11573 && dump ("Propagating deduced return type to %N", existing);
11574 TREE_TYPE (existing) = change_return_type (TREE_TYPE (d_type), e_type);
11577 else if (is_typedef)
11579 if (!DECL_ORIGINAL_TYPE (e_inner)
11580 || !same_type_p (DECL_ORIGINAL_TYPE (d_inner),
11581 DECL_ORIGINAL_TYPE (e_inner)))
11582 goto mismatch;
11584 /* Using cp_tree_equal because we can meet TYPE_ARGUMENT_PACKs
11585 here. I suspect the entities that directly do that are things
11586 that shouldn't go to duplicate_decls (FIELD_DECLs etc). */
11587 else if (!cp_tree_equal (TREE_TYPE (decl), TREE_TYPE (existing)))
11589 mismatch:
11590 if (DECL_IS_UNDECLARED_BUILTIN (existing))
11591 /* Just like duplicate_decls, presum the user knows what
11592 they're doing in overriding a builtin. */
11593 TREE_TYPE (existing) = TREE_TYPE (decl);
11594 else if (decl_function_context (decl))
11595 /* The type of a mergeable local entity (such as a function scope
11596 capturing lambda's closure type fields) can depend on an
11597 unmergeable local entity (such as a local variable), so type
11598 equality isn't feasible in general for local entities. */;
11599 else
11601 // FIXME:QOI Might be template specialization from a module,
11602 // not necessarily global module
11603 error_at (DECL_SOURCE_LOCATION (decl),
11604 "conflicting global module declaration %#qD", decl);
11605 inform (DECL_SOURCE_LOCATION (existing),
11606 "existing declaration %#qD", existing);
11607 return false;
11611 if (DECL_IS_UNDECLARED_BUILTIN (existing)
11612 && !DECL_IS_UNDECLARED_BUILTIN (decl))
11614 /* We're matching a builtin that the user has yet to declare.
11615 We are the one! This is very much duplicate-decl
11616 shenanigans. */
11617 DECL_SOURCE_LOCATION (existing) = DECL_SOURCE_LOCATION (decl);
11618 if (TREE_CODE (decl) != TYPE_DECL)
11620 /* Propagate exceptions etc. */
11621 TREE_TYPE (existing) = TREE_TYPE (decl);
11622 TREE_NOTHROW (existing) = TREE_NOTHROW (decl);
11624 /* This is actually an import! */
11625 DECL_MODULE_IMPORT_P (existing) = true;
11627 /* Yay, sliced! */
11628 existing->base = decl->base;
11630 if (TREE_CODE (decl) == FUNCTION_DECL)
11632 /* Ew :( */
11633 memcpy (&existing->decl_common.size,
11634 &decl->decl_common.size,
11635 (offsetof (tree_decl_common, pt_uid)
11636 - offsetof (tree_decl_common, size)));
11637 auto bltin_class = DECL_BUILT_IN_CLASS (decl);
11638 existing->function_decl.built_in_class = bltin_class;
11639 auto fncode = DECL_UNCHECKED_FUNCTION_CODE (decl);
11640 DECL_UNCHECKED_FUNCTION_CODE (existing) = fncode;
11641 if (existing->function_decl.built_in_class == BUILT_IN_NORMAL)
11643 if (builtin_decl_explicit_p (built_in_function (fncode)))
11644 switch (fncode)
11646 case BUILT_IN_STPCPY:
11647 set_builtin_decl_implicit_p
11648 (built_in_function (fncode), true);
11649 break;
11650 default:
11651 set_builtin_decl_declared_p
11652 (built_in_function (fncode), true);
11653 break;
11655 copy_attributes_to_builtin (decl);
11660 if (VAR_OR_FUNCTION_DECL_P (decl)
11661 && DECL_TEMPLATE_INSTANTIATED (decl))
11662 /* Don't instantiate again! */
11663 DECL_TEMPLATE_INSTANTIATED (existing) = true;
11665 if (TREE_CODE (d_inner) == FUNCTION_DECL
11666 && DECL_DECLARED_INLINE_P (d_inner))
11667 DECL_DECLARED_INLINE_P (e_inner) = true;
11668 if (!DECL_EXTERNAL (d_inner))
11669 DECL_EXTERNAL (e_inner) = false;
11671 // FIXME: Check default tmpl and fn parms here
11673 return true;
11676 /* FN is an implicit member function that we've discovered is new to
11677 the class. Add it to the TYPE_FIELDS chain and the method vector.
11678 Reset the appropriate classtype lazy flag. */
11680 bool
11681 trees_in::install_implicit_member (tree fn)
11683 tree ctx = DECL_CONTEXT (fn);
11684 tree name = DECL_NAME (fn);
11685 /* We know these are synthesized, so the set of expected prototypes
11686 is quite restricted. We're not validating correctness, just
11687 distinguishing beteeen the small set of possibilities. */
11688 tree parm_type = TREE_VALUE (FUNCTION_FIRST_USER_PARMTYPE (fn));
11689 if (IDENTIFIER_CTOR_P (name))
11691 if (CLASSTYPE_LAZY_DEFAULT_CTOR (ctx)
11692 && VOID_TYPE_P (parm_type))
11693 CLASSTYPE_LAZY_DEFAULT_CTOR (ctx) = false;
11694 else if (!TYPE_REF_P (parm_type))
11695 return false;
11696 else if (CLASSTYPE_LAZY_COPY_CTOR (ctx)
11697 && !TYPE_REF_IS_RVALUE (parm_type))
11698 CLASSTYPE_LAZY_COPY_CTOR (ctx) = false;
11699 else if (CLASSTYPE_LAZY_MOVE_CTOR (ctx))
11700 CLASSTYPE_LAZY_MOVE_CTOR (ctx) = false;
11701 else
11702 return false;
11704 else if (IDENTIFIER_DTOR_P (name))
11706 if (CLASSTYPE_LAZY_DESTRUCTOR (ctx))
11707 CLASSTYPE_LAZY_DESTRUCTOR (ctx) = false;
11708 else
11709 return false;
11710 if (DECL_VIRTUAL_P (fn))
11711 /* A virtual dtor should have been created when the class
11712 became complete. */
11713 return false;
11715 else if (name == assign_op_identifier)
11717 if (!TYPE_REF_P (parm_type))
11718 return false;
11719 else if (CLASSTYPE_LAZY_COPY_ASSIGN (ctx)
11720 && !TYPE_REF_IS_RVALUE (parm_type))
11721 CLASSTYPE_LAZY_COPY_ASSIGN (ctx) = false;
11722 else if (CLASSTYPE_LAZY_MOVE_ASSIGN (ctx))
11723 CLASSTYPE_LAZY_MOVE_ASSIGN (ctx) = false;
11724 else
11725 return false;
11727 else
11728 return false;
11730 dump (dumper::MERGE) && dump ("Adding implicit member %N", fn);
11732 DECL_CHAIN (fn) = TYPE_FIELDS (ctx);
11733 TYPE_FIELDS (ctx) = fn;
11735 add_method (ctx, fn, false);
11737 /* Propagate TYPE_FIELDS. */
11738 fixup_type_variants (ctx);
11740 return true;
11743 /* Return non-zero if DECL has a definition that would be interesting to
11744 write out. */
11746 static bool
11747 has_definition (tree decl)
11749 bool is_tmpl = TREE_CODE (decl) == TEMPLATE_DECL;
11750 if (is_tmpl)
11751 decl = DECL_TEMPLATE_RESULT (decl);
11753 switch (TREE_CODE (decl))
11755 default:
11756 break;
11758 case FUNCTION_DECL:
11759 if (!DECL_SAVED_TREE (decl))
11760 /* Not defined. */
11761 break;
11763 if (DECL_DECLARED_INLINE_P (decl))
11764 return true;
11766 if (DECL_THIS_STATIC (decl)
11767 && (header_module_p ()
11768 || (!DECL_LANG_SPECIFIC (decl) || !DECL_MODULE_PURVIEW_P (decl))))
11769 /* GM static function. */
11770 return true;
11772 if (DECL_TEMPLATE_INFO (decl))
11774 int use_tpl = DECL_USE_TEMPLATE (decl);
11776 // FIXME: Partial specializations have definitions too.
11777 if (use_tpl < 2)
11778 return true;
11780 break;
11782 case TYPE_DECL:
11784 tree type = TREE_TYPE (decl);
11785 if (type == TYPE_MAIN_VARIANT (type)
11786 && decl == TYPE_NAME (type)
11787 && (TREE_CODE (type) == ENUMERAL_TYPE
11788 ? TYPE_VALUES (type) : TYPE_FIELDS (type)))
11789 return true;
11791 break;
11793 case VAR_DECL:
11794 /* DECL_INITIALIZED_P might not be set on a dependent VAR_DECL. */
11795 if (DECL_LANG_SPECIFIC (decl)
11796 && DECL_TEMPLATE_INFO (decl)
11797 && DECL_INITIAL (decl))
11798 return true;
11799 else
11801 if (!DECL_INITIALIZED_P (decl))
11802 return false;
11804 if (header_module_p ()
11805 || (!DECL_LANG_SPECIFIC (decl) || !DECL_MODULE_PURVIEW_P (decl)))
11806 /* GM static variable. */
11807 return true;
11809 if (!TREE_CONSTANT (decl))
11810 return false;
11812 return true;
11814 break;
11816 case CONCEPT_DECL:
11817 if (DECL_INITIAL (decl))
11818 return true;
11820 break;
11823 return false;
11826 uintptr_t *
11827 trees_in::find_duplicate (tree existing)
11829 if (!duplicates)
11830 return NULL;
11832 return duplicates->get (existing);
11835 /* We're starting to read a duplicate DECL. EXISTING is the already
11836 known node. */
11838 void
11839 trees_in::register_duplicate (tree decl, tree existing)
11841 if (!duplicates)
11842 duplicates = new duplicate_hash_map (40);
11844 bool existed;
11845 uintptr_t &slot = duplicates->get_or_insert (existing, &existed);
11846 gcc_checking_assert (!existed);
11847 slot = reinterpret_cast<uintptr_t> (decl);
11849 if (TREE_CODE (decl) == TEMPLATE_DECL)
11850 /* Also register the DECL_TEMPLATE_RESULT as a duplicate so
11851 that passing decl's _RESULT to maybe_duplicate naturally
11852 gives us existing's _RESULT back. */
11853 register_duplicate (DECL_TEMPLATE_RESULT (decl),
11854 DECL_TEMPLATE_RESULT (existing));
11857 /* We've read a definition of MAYBE_EXISTING. If not a duplicate,
11858 return MAYBE_EXISTING (into which the definition should be
11859 installed). Otherwise return NULL if already known bad, or the
11860 duplicate we read (for ODR checking, or extracting additional merge
11861 information). */
11863 tree
11864 trees_in::odr_duplicate (tree maybe_existing, bool has_defn)
11866 tree res = NULL_TREE;
11868 if (uintptr_t *dup = find_duplicate (maybe_existing))
11870 if (!(*dup & 1))
11871 res = reinterpret_cast<tree> (*dup);
11873 else
11874 res = maybe_existing;
11876 assert_definition (maybe_existing, res && !has_defn);
11878 // FIXME: We probably need to return the template, so that the
11879 // template header can be checked?
11880 return res ? STRIP_TEMPLATE (res) : NULL_TREE;
11883 /* The following writer functions rely on the current behaviour of
11884 depset::hash::add_dependency making the decl and defn depset nodes
11885 depend on eachother. That way we don't have to worry about seeding
11886 the tree map with named decls that cannot be looked up by name (I.e
11887 template and function parms). We know the decl and definition will
11888 be in the same cluster, which is what we want. */
11890 void
11891 trees_out::write_function_def (tree decl)
11893 tree_node (DECL_RESULT (decl));
11894 tree_node (DECL_INITIAL (decl));
11895 tree_node (DECL_SAVED_TREE (decl));
11896 tree_node (DECL_FRIEND_CONTEXT (decl));
11898 constexpr_fundef *cexpr = retrieve_constexpr_fundef (decl);
11900 if (streaming_p ())
11901 u (cexpr != nullptr);
11902 if (cexpr)
11904 chained_decls (cexpr->parms);
11905 tree_node (cexpr->result);
11906 tree_node (cexpr->body);
11909 function* f = DECL_STRUCT_FUNCTION (decl);
11911 if (streaming_p ())
11913 unsigned flags = 0;
11915 if (f)
11916 flags |= 2;
11917 if (DECL_NOT_REALLY_EXTERN (decl))
11918 flags |= 1;
11920 u (flags);
11923 if (state && f)
11925 state->write_location (*this, f->function_start_locus);
11926 state->write_location (*this, f->function_end_locus);
11930 void
11931 trees_out::mark_function_def (tree)
11935 bool
11936 trees_in::read_function_def (tree decl, tree maybe_template)
11938 dump () && dump ("Reading function definition %N", decl);
11939 tree result = tree_node ();
11940 tree initial = tree_node ();
11941 tree saved = tree_node ();
11942 tree context = tree_node ();
11943 constexpr_fundef cexpr;
11944 post_process_data pdata {};
11945 pdata.decl = maybe_template;
11947 tree maybe_dup = odr_duplicate (maybe_template, DECL_SAVED_TREE (decl));
11948 bool installing = maybe_dup && !DECL_SAVED_TREE (decl);
11950 if (u ())
11952 cexpr.parms = chained_decls ();
11953 cexpr.result = tree_node ();
11954 cexpr.body = tree_node ();
11955 cexpr.decl = decl;
11957 else
11958 cexpr.decl = NULL_TREE;
11960 unsigned flags = u ();
11962 if (flags & 2)
11964 pdata.start_locus = state->read_location (*this);
11965 pdata.end_locus = state->read_location (*this);
11968 if (get_overrun ())
11969 return NULL_TREE;
11971 if (installing)
11973 DECL_NOT_REALLY_EXTERN (decl) = flags & 1;
11974 DECL_RESULT (decl) = result;
11975 DECL_INITIAL (decl) = initial;
11976 DECL_SAVED_TREE (decl) = saved;
11978 if (context)
11979 SET_DECL_FRIEND_CONTEXT (decl, context);
11980 if (cexpr.decl)
11981 register_constexpr_fundef (cexpr);
11982 post_process (pdata);
11984 else if (maybe_dup)
11986 // FIXME:QOI Check matching defn
11989 return true;
11992 /* Also for CONCEPT_DECLs. */
11994 void
11995 trees_out::write_var_def (tree decl)
11997 tree init = DECL_INITIAL (decl);
11998 tree_node (init);
11999 if (!init)
12001 tree dyn_init = NULL_TREE;
12003 /* We only need to write initializers in header modules. */
12004 if (header_module_p () && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
12006 dyn_init = value_member (decl,
12007 CP_DECL_THREAD_LOCAL_P (decl)
12008 ? tls_aggregates : static_aggregates);
12009 gcc_checking_assert (dyn_init);
12010 /* Mark it so write_inits knows this is needed. */
12011 TREE_LANG_FLAG_0 (dyn_init) = true;
12012 dyn_init = TREE_PURPOSE (dyn_init);
12014 tree_node (dyn_init);
12018 void
12019 trees_out::mark_var_def (tree)
12023 bool
12024 trees_in::read_var_def (tree decl, tree maybe_template)
12026 /* Do not mark the virtual table entries as used. */
12027 bool vtable = VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl);
12028 unused += vtable;
12029 tree init = tree_node ();
12030 tree dyn_init = init ? NULL_TREE : tree_node ();
12031 unused -= vtable;
12033 if (get_overrun ())
12034 return false;
12036 bool initialized = (VAR_P (decl) ? bool (DECL_INITIALIZED_P (decl))
12037 : bool (DECL_INITIAL (decl)));
12038 tree maybe_dup = odr_duplicate (maybe_template, initialized);
12039 bool installing = maybe_dup && !initialized;
12040 if (installing)
12042 if (DECL_EXTERNAL (decl))
12043 DECL_NOT_REALLY_EXTERN (decl) = true;
12044 if (VAR_P (decl))
12046 DECL_INITIALIZED_P (decl) = true;
12047 if (maybe_dup && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (maybe_dup))
12048 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
12049 if (DECL_IMPLICIT_INSTANTIATION (decl)
12050 || (DECL_CLASS_SCOPE_P (decl)
12051 && !DECL_VTABLE_OR_VTT_P (decl)
12052 && !DECL_TEMPLATE_INFO (decl)))
12053 note_vague_linkage_variable (decl);
12055 DECL_INITIAL (decl) = init;
12056 if (!dyn_init)
12058 else if (CP_DECL_THREAD_LOCAL_P (decl))
12059 tls_aggregates = tree_cons (dyn_init, decl, tls_aggregates);
12060 else
12061 static_aggregates = tree_cons (dyn_init, decl, static_aggregates);
12063 else if (maybe_dup)
12065 // FIXME:QOI Check matching defn
12068 return true;
12071 /* If MEMBER doesn't have an independent life outside the class,
12072 return it (or its TEMPLATE_DECL). Otherwise NULL. */
12074 static tree
12075 member_owned_by_class (tree member)
12077 gcc_assert (DECL_P (member));
12079 /* Clones are owned by their origin. */
12080 if (DECL_CLONED_FUNCTION_P (member))
12081 return NULL;
12083 if (TREE_CODE (member) == FIELD_DECL)
12084 /* FIELD_DECLS can have template info in some cases. We always
12085 want the FIELD_DECL though, as there's never a TEMPLATE_DECL
12086 wrapping them. */
12087 return member;
12089 int use_tpl = -1;
12090 if (tree ti = node_template_info (member, use_tpl))
12092 // FIXME: Don't bail on things that CANNOT have their own
12093 // template header. No, make sure they're in the same cluster.
12094 if (use_tpl > 0)
12095 return NULL_TREE;
12097 if (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == member)
12098 member = TI_TEMPLATE (ti);
12100 return member;
12103 void
12104 trees_out::write_class_def (tree defn)
12106 gcc_assert (DECL_P (defn));
12107 if (streaming_p ())
12108 dump () && dump ("Writing class definition %N", defn);
12110 tree type = TREE_TYPE (defn);
12111 tree_node (TYPE_SIZE (type));
12112 tree_node (TYPE_SIZE_UNIT (type));
12113 tree_node (TYPE_VFIELD (type));
12114 tree_node (TYPE_BINFO (type));
12116 vec_chained_decls (TYPE_FIELDS (type));
12118 /* Every class but __as_base has a type-specific. */
12119 gcc_checking_assert (!TYPE_LANG_SPECIFIC (type) == IS_FAKE_BASE_TYPE (type));
12121 if (TYPE_LANG_SPECIFIC (type))
12124 vec<tree, va_gc> *v = CLASSTYPE_MEMBER_VEC (type);
12125 if (!v)
12127 gcc_checking_assert (!streaming_p ());
12128 /* Force a class vector. */
12129 v = set_class_bindings (type, -1);
12130 gcc_checking_assert (v);
12133 unsigned len = v->length ();
12134 if (streaming_p ())
12135 u (len);
12136 for (unsigned ix = 0; ix != len; ix++)
12138 tree m = (*v)[ix];
12139 if (TREE_CODE (m) == TYPE_DECL
12140 && DECL_ARTIFICIAL (m)
12141 && TYPE_STUB_DECL (TREE_TYPE (m)) == m)
12142 /* This is a using-decl for a type, or an anonymous
12143 struct (maybe with a typedef name). Write the type. */
12144 m = TREE_TYPE (m);
12145 tree_node (m);
12148 tree_node (CLASSTYPE_LAMBDA_EXPR (type));
12150 /* TYPE_CONTAINS_VPTR_P looks at the vbase vector, which the
12151 reader won't know at this point. */
12152 int has_vptr = TYPE_CONTAINS_VPTR_P (type);
12154 if (streaming_p ())
12156 unsigned nvbases = vec_safe_length (CLASSTYPE_VBASECLASSES (type));
12157 u (nvbases);
12158 i (has_vptr);
12161 if (has_vptr)
12163 tree_vec (CLASSTYPE_PURE_VIRTUALS (type));
12164 tree_pair_vec (CLASSTYPE_VCALL_INDICES (type));
12165 tree_node (CLASSTYPE_KEY_METHOD (type));
12169 if (TYPE_LANG_SPECIFIC (type))
12171 tree_node (CLASSTYPE_PRIMARY_BINFO (type));
12173 tree as_base = CLASSTYPE_AS_BASE (type);
12174 if (as_base)
12175 as_base = TYPE_NAME (as_base);
12176 tree_node (as_base);
12178 /* Write the vtables. */
12179 tree vtables = CLASSTYPE_VTABLES (type);
12180 vec_chained_decls (vtables);
12181 for (; vtables; vtables = TREE_CHAIN (vtables))
12182 write_definition (vtables);
12184 /* Write the friend classes. */
12185 tree_list (CLASSTYPE_FRIEND_CLASSES (type), false);
12187 /* Write the friend functions. */
12188 for (tree friends = DECL_FRIENDLIST (defn);
12189 friends; friends = TREE_CHAIN (friends))
12191 /* Name of these friends. */
12192 tree_node (TREE_PURPOSE (friends));
12193 tree_list (TREE_VALUE (friends), false);
12195 /* End of friend fns. */
12196 tree_node (NULL_TREE);
12198 /* Write the decl list. */
12199 tree_list (CLASSTYPE_DECL_LIST (type), true);
12201 if (TYPE_CONTAINS_VPTR_P (type))
12203 /* Write the thunks. */
12204 for (tree decls = TYPE_FIELDS (type);
12205 decls; decls = DECL_CHAIN (decls))
12206 if (TREE_CODE (decls) == FUNCTION_DECL
12207 && DECL_VIRTUAL_P (decls)
12208 && DECL_THUNKS (decls))
12210 tree_node (decls);
12211 /* Thunks are always unique, so chaining is ok. */
12212 chained_decls (DECL_THUNKS (decls));
12214 tree_node (NULL_TREE);
12219 void
12220 trees_out::mark_class_member (tree member, bool do_defn)
12222 gcc_assert (DECL_P (member));
12224 member = member_owned_by_class (member);
12225 if (member)
12226 mark_declaration (member, do_defn && has_definition (member));
12229 void
12230 trees_out::mark_class_def (tree defn)
12232 gcc_assert (DECL_P (defn));
12233 tree type = TREE_TYPE (defn);
12234 /* Mark the class members that are not type-decls and cannot have
12235 independent definitions. */
12236 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
12237 if (TREE_CODE (member) == FIELD_DECL
12238 || TREE_CODE (member) == USING_DECL
12239 /* A cloned enum-decl from 'using enum unrelated;' */
12240 || (TREE_CODE (member) == CONST_DECL
12241 && DECL_CONTEXT (member) == type))
12243 mark_class_member (member);
12244 if (TREE_CODE (member) == FIELD_DECL)
12245 if (tree repr = DECL_BIT_FIELD_REPRESENTATIVE (member))
12246 /* If we're marking a class template definition, then
12247 this'll contain the width (as set by grokbitfield)
12248 instead of a decl. */
12249 if (DECL_P (repr))
12250 mark_declaration (repr, false);
12253 /* Mark the binfo hierarchy. */
12254 for (tree child = TYPE_BINFO (type); child; child = TREE_CHAIN (child))
12255 mark_by_value (child);
12257 if (TYPE_LANG_SPECIFIC (type))
12259 for (tree vtable = CLASSTYPE_VTABLES (type);
12260 vtable; vtable = TREE_CHAIN (vtable))
12261 mark_declaration (vtable, true);
12263 if (TYPE_CONTAINS_VPTR_P (type))
12264 /* Mark the thunks, they belong to the class definition,
12265 /not/ the thunked-to function. */
12266 for (tree decls = TYPE_FIELDS (type);
12267 decls; decls = DECL_CHAIN (decls))
12268 if (TREE_CODE (decls) == FUNCTION_DECL)
12269 for (tree thunks = DECL_THUNKS (decls);
12270 thunks; thunks = DECL_CHAIN (thunks))
12271 mark_declaration (thunks, false);
12275 /* Nop sorting, needed for resorting the member vec. */
12277 static void
12278 nop (void *, void *, void *)
12282 bool
12283 trees_in::read_class_def (tree defn, tree maybe_template)
12285 gcc_assert (DECL_P (defn));
12286 dump () && dump ("Reading class definition %N", defn);
12287 tree type = TREE_TYPE (defn);
12288 tree size = tree_node ();
12289 tree size_unit = tree_node ();
12290 tree vfield = tree_node ();
12291 tree binfo = tree_node ();
12292 vec<tree, va_gc> *vbase_vec = NULL;
12293 vec<tree, va_gc> *member_vec = NULL;
12294 vec<tree, va_gc> *pure_virts = NULL;
12295 vec<tree_pair_s, va_gc> *vcall_indices = NULL;
12296 tree key_method = NULL_TREE;
12297 tree lambda = NULL_TREE;
12299 /* Read the fields. */
12300 vec<tree, va_heap> *fields = vec_chained_decls ();
12302 if (TYPE_LANG_SPECIFIC (type))
12304 if (unsigned len = u ())
12306 vec_alloc (member_vec, len);
12307 for (unsigned ix = 0; ix != len; ix++)
12309 tree m = tree_node ();
12310 if (get_overrun ())
12311 break;
12312 if (TYPE_P (m))
12313 m = TYPE_STUB_DECL (m);
12314 member_vec->quick_push (m);
12317 lambda = tree_node ();
12319 if (!get_overrun ())
12321 unsigned nvbases = u ();
12322 if (nvbases)
12324 vec_alloc (vbase_vec, nvbases);
12325 for (tree child = binfo; child; child = TREE_CHAIN (child))
12326 if (BINFO_VIRTUAL_P (child))
12327 vbase_vec->quick_push (child);
12331 if (!get_overrun ())
12333 int has_vptr = i ();
12334 if (has_vptr)
12336 pure_virts = tree_vec ();
12337 vcall_indices = tree_pair_vec ();
12338 key_method = tree_node ();
12343 tree maybe_dup = odr_duplicate (maybe_template, TYPE_SIZE (type));
12344 bool installing = maybe_dup && !TYPE_SIZE (type);
12345 if (installing)
12347 if (maybe_dup != defn)
12349 // FIXME: This is needed on other defns too, almost
12350 // duplicate-decl like? See is_matching_decl too.
12351 /* Copy flags from the duplicate. */
12352 tree type_dup = TREE_TYPE (maybe_dup);
12354 /* Core pieces. */
12355 TYPE_MODE_RAW (type) = TYPE_MODE_RAW (type_dup);
12356 SET_DECL_MODE (defn, DECL_MODE (maybe_dup));
12357 TREE_ADDRESSABLE (type) = TREE_ADDRESSABLE (type_dup);
12358 DECL_SIZE (defn) = DECL_SIZE (maybe_dup);
12359 DECL_SIZE_UNIT (defn) = DECL_SIZE_UNIT (maybe_dup);
12360 DECL_ALIGN_RAW (defn) = DECL_ALIGN_RAW (maybe_dup);
12361 DECL_WARN_IF_NOT_ALIGN_RAW (defn)
12362 = DECL_WARN_IF_NOT_ALIGN_RAW (maybe_dup);
12363 DECL_USER_ALIGN (defn) = DECL_USER_ALIGN (maybe_dup);
12365 /* C++ pieces. */
12366 TYPE_POLYMORPHIC_P (type) = TYPE_POLYMORPHIC_P (type_dup);
12367 TYPE_HAS_USER_CONSTRUCTOR (type)
12368 = TYPE_HAS_USER_CONSTRUCTOR (type_dup);
12369 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
12370 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type_dup);
12372 if (auto ls = TYPE_LANG_SPECIFIC (type_dup))
12374 if (TYPE_LANG_SPECIFIC (type))
12376 CLASSTYPE_BEFRIENDING_CLASSES (type_dup)
12377 = CLASSTYPE_BEFRIENDING_CLASSES (type);
12378 if (!ANON_AGGR_TYPE_P (type))
12379 CLASSTYPE_TYPEINFO_VAR (type_dup)
12380 = CLASSTYPE_TYPEINFO_VAR (type);
12382 for (tree v = type; v; v = TYPE_NEXT_VARIANT (v))
12383 TYPE_LANG_SPECIFIC (v) = ls;
12387 TYPE_SIZE (type) = size;
12388 TYPE_SIZE_UNIT (type) = size_unit;
12390 if (fields)
12392 tree *chain = &TYPE_FIELDS (type);
12393 unsigned len = fields->length ();
12394 for (unsigned ix = 0; ix != len; ix++)
12396 tree decl = (*fields)[ix];
12398 if (!decl)
12400 /* An anonymous struct with typedef name. */
12401 tree tdef = (*fields)[ix+1];
12402 decl = TYPE_STUB_DECL (TREE_TYPE (tdef));
12403 gcc_checking_assert (IDENTIFIER_ANON_P (DECL_NAME (decl))
12404 && decl != tdef);
12407 gcc_checking_assert (!*chain == !DECL_CLONED_FUNCTION_P (decl));
12408 *chain = decl;
12409 chain = &DECL_CHAIN (decl);
12411 if (TREE_CODE (decl) == FIELD_DECL
12412 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12414 tree anon_type = TYPE_MAIN_VARIANT (TREE_TYPE (decl));
12415 if (DECL_NAME (defn) == as_base_identifier)
12416 /* ANON_AGGR_TYPE_FIELD should already point to the
12417 original FIELD_DECL; don't overwrite it to point
12418 to the as-base FIELD_DECL copy. */
12419 gcc_checking_assert (ANON_AGGR_TYPE_FIELD (anon_type));
12420 else
12421 ANON_AGGR_TYPE_FIELD (anon_type) = decl;
12424 if (TREE_CODE (decl) == USING_DECL
12425 && TREE_CODE (USING_DECL_SCOPE (decl)) == RECORD_TYPE)
12427 /* Reconstruct DECL_ACCESS. */
12428 tree decls = USING_DECL_DECLS (decl);
12429 tree access = declared_access (decl);
12431 for (ovl_iterator iter (decls); iter; ++iter)
12433 tree d = *iter;
12435 retrofit_lang_decl (d);
12436 tree list = DECL_ACCESS (d);
12438 if (!purpose_member (type, list))
12439 DECL_ACCESS (d) = tree_cons (type, access, list);
12445 TYPE_VFIELD (type) = vfield;
12446 TYPE_BINFO (type) = binfo;
12448 if (TYPE_LANG_SPECIFIC (type))
12450 CLASSTYPE_LAMBDA_EXPR (type) = lambda;
12452 CLASSTYPE_MEMBER_VEC (type) = member_vec;
12453 CLASSTYPE_PURE_VIRTUALS (type) = pure_virts;
12454 CLASSTYPE_VCALL_INDICES (type) = vcall_indices;
12456 CLASSTYPE_KEY_METHOD (type) = key_method;
12458 CLASSTYPE_VBASECLASSES (type) = vbase_vec;
12460 /* Resort the member vector. */
12461 resort_type_member_vec (member_vec, NULL, nop, NULL);
12464 else if (maybe_dup)
12466 // FIXME:QOI Check matching defn
12469 if (TYPE_LANG_SPECIFIC (type))
12471 tree primary = tree_node ();
12472 tree as_base = tree_node ();
12474 if (as_base)
12475 as_base = TREE_TYPE (as_base);
12477 /* Read the vtables. */
12478 vec<tree, va_heap> *vtables = vec_chained_decls ();
12479 if (vtables)
12481 unsigned len = vtables->length ();
12482 for (unsigned ix = 0; ix != len; ix++)
12484 tree vtable = (*vtables)[ix];
12485 read_var_def (vtable, vtable);
12489 tree friend_classes = tree_list (false);
12490 tree friend_functions = NULL_TREE;
12491 for (tree *chain = &friend_functions;
12492 tree name = tree_node (); chain = &TREE_CHAIN (*chain))
12494 tree val = tree_list (false);
12495 *chain = build_tree_list (name, val);
12497 tree decl_list = tree_list (true);
12499 if (installing)
12501 CLASSTYPE_PRIMARY_BINFO (type) = primary;
12502 CLASSTYPE_AS_BASE (type) = as_base;
12504 if (vtables)
12506 if ((!CLASSTYPE_KEY_METHOD (type)
12507 /* Sneaky user may have defined it inline
12508 out-of-class. */
12509 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type)))
12510 /* An imported non-template class attached to a module
12511 doesn't need to have its vtables emitted here. */
12512 && (CLASSTYPE_USE_TEMPLATE (type)
12513 || !DECL_MODULE_ATTACH_P (defn)))
12514 vec_safe_push (keyed_classes, type);
12515 unsigned len = vtables->length ();
12516 tree *chain = &CLASSTYPE_VTABLES (type);
12517 for (unsigned ix = 0; ix != len; ix++)
12519 tree vtable = (*vtables)[ix];
12520 gcc_checking_assert (!*chain);
12521 *chain = vtable;
12522 chain = &DECL_CHAIN (vtable);
12525 CLASSTYPE_FRIEND_CLASSES (type) = friend_classes;
12526 DECL_FRIENDLIST (defn) = friend_functions;
12527 CLASSTYPE_DECL_LIST (type) = decl_list;
12529 for (; friend_classes; friend_classes = TREE_CHAIN (friend_classes))
12531 tree f = TREE_VALUE (friend_classes);
12532 if (TREE_CODE (f) == TEMPLATE_DECL)
12533 f = TREE_TYPE (f);
12535 if (CLASS_TYPE_P (f))
12537 CLASSTYPE_BEFRIENDING_CLASSES (f)
12538 = tree_cons (NULL_TREE, type,
12539 CLASSTYPE_BEFRIENDING_CLASSES (f));
12540 dump () && dump ("Class %N befriending %C:%N",
12541 type, TREE_CODE (f), f);
12545 for (; friend_functions;
12546 friend_functions = TREE_CHAIN (friend_functions))
12547 for (tree friend_decls = TREE_VALUE (friend_functions);
12548 friend_decls; friend_decls = TREE_CHAIN (friend_decls))
12550 tree f = TREE_VALUE (friend_decls);
12552 DECL_BEFRIENDING_CLASSES (f)
12553 = tree_cons (NULL_TREE, type, DECL_BEFRIENDING_CLASSES (f));
12554 dump () && dump ("Class %N befriending %C:%N",
12555 type, TREE_CODE (f), f);
12559 if (TYPE_CONTAINS_VPTR_P (type))
12560 /* Read and install the thunks. */
12561 while (tree vfunc = tree_node ())
12563 tree thunks = chained_decls ();
12564 if (installing)
12565 SET_DECL_THUNKS (vfunc, thunks);
12568 vec_free (vtables);
12571 /* Propagate to all variants. */
12572 if (installing)
12573 fixup_type_variants (type);
12575 /* IS_FAKE_BASE_TYPE is inaccurate at this point, because if this is
12576 the fake base, we've not hooked it into the containing class's
12577 data structure yet. Fortunately it has a unique name. */
12578 if (installing
12579 && DECL_NAME (defn) != as_base_identifier
12580 && (!CLASSTYPE_TEMPLATE_INFO (type)
12581 || !uses_template_parms (TI_ARGS (CLASSTYPE_TEMPLATE_INFO (type)))))
12582 /* Emit debug info. It'd be nice to know if the interface TU
12583 already emitted this. */
12584 rest_of_type_compilation (type, !LOCAL_CLASS_P (type));
12586 vec_free (fields);
12588 return !get_overrun ();
12591 void
12592 trees_out::write_enum_def (tree decl)
12594 tree type = TREE_TYPE (decl);
12596 tree_node (TYPE_VALUES (type));
12597 /* Note that we stream TYPE_MIN/MAX_VALUE directly as part of the
12598 ENUMERAL_TYPE. */
12601 void
12602 trees_out::mark_enum_def (tree decl)
12604 tree type = TREE_TYPE (decl);
12606 for (tree values = TYPE_VALUES (type); values; values = TREE_CHAIN (values))
12608 tree cst = TREE_VALUE (values);
12609 mark_by_value (cst);
12610 /* We must mark the init to avoid circularity in tt_enum_int. */
12611 if (tree init = DECL_INITIAL (cst))
12612 if (TREE_CODE (init) == INTEGER_CST)
12613 mark_by_value (init);
12617 bool
12618 trees_in::read_enum_def (tree defn, tree maybe_template)
12620 tree type = TREE_TYPE (defn);
12621 tree values = tree_node ();
12623 if (get_overrun ())
12624 return false;
12626 tree maybe_dup = odr_duplicate (maybe_template, TYPE_VALUES (type));
12627 bool installing = maybe_dup && !TYPE_VALUES (type);
12629 if (installing)
12631 TYPE_VALUES (type) = values;
12632 /* Note that we stream TYPE_MIN/MAX_VALUE directly as part of the
12633 ENUMERAL_TYPE. */
12635 rest_of_type_compilation (type, DECL_NAMESPACE_SCOPE_P (defn));
12637 else if (maybe_dup)
12639 tree known = TYPE_VALUES (type);
12640 for (; known && values;
12641 known = TREE_CHAIN (known), values = TREE_CHAIN (values))
12643 tree known_decl = TREE_VALUE (known);
12644 tree new_decl = TREE_VALUE (values);
12646 if (DECL_NAME (known_decl) != DECL_NAME (new_decl))
12647 break;
12649 new_decl = maybe_duplicate (new_decl);
12651 if (!cp_tree_equal (DECL_INITIAL (known_decl),
12652 DECL_INITIAL (new_decl)))
12653 break;
12656 if (known || values)
12658 error_at (DECL_SOURCE_LOCATION (maybe_dup),
12659 "definition of %qD does not match", maybe_dup);
12660 inform (DECL_SOURCE_LOCATION (defn),
12661 "existing definition %qD", defn);
12663 tree known_decl = NULL_TREE, new_decl = NULL_TREE;
12665 if (known)
12666 known_decl = TREE_VALUE (known);
12667 if (values)
12668 new_decl = maybe_duplicate (TREE_VALUE (values));
12670 if (known_decl && new_decl)
12672 inform (DECL_SOURCE_LOCATION (new_decl),
12673 "... this enumerator %qD", new_decl);
12674 inform (DECL_SOURCE_LOCATION (known_decl),
12675 "enumerator %qD does not match ...", known_decl);
12677 else if (known_decl || new_decl)
12679 tree extra = known_decl ? known_decl : new_decl;
12680 inform (DECL_SOURCE_LOCATION (extra),
12681 "additional enumerators beginning with %qD", extra);
12683 else
12684 inform (DECL_SOURCE_LOCATION (maybe_dup),
12685 "enumeration range differs");
12687 /* Mark it bad. */
12688 unmatched_duplicate (maybe_template);
12692 return true;
12695 /* Write out the body of DECL. See above circularity note. */
12697 void
12698 trees_out::write_definition (tree decl)
12700 if (streaming_p ())
12702 assert_definition (decl);
12703 dump ()
12704 && dump ("Writing definition %C:%N", TREE_CODE (decl), decl);
12706 else
12707 dump (dumper::DEPEND)
12708 && dump ("Depending definition %C:%N", TREE_CODE (decl), decl);
12710 again:
12711 switch (TREE_CODE (decl))
12713 default:
12714 gcc_unreachable ();
12716 case TEMPLATE_DECL:
12717 decl = DECL_TEMPLATE_RESULT (decl);
12718 goto again;
12720 case FUNCTION_DECL:
12721 write_function_def (decl);
12722 break;
12724 case TYPE_DECL:
12726 tree type = TREE_TYPE (decl);
12727 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12728 && TYPE_NAME (type) == decl);
12729 if (TREE_CODE (type) == ENUMERAL_TYPE)
12730 write_enum_def (decl);
12731 else
12732 write_class_def (decl);
12734 break;
12736 case VAR_DECL:
12737 case CONCEPT_DECL:
12738 write_var_def (decl);
12739 break;
12743 /* Mark a declaration for by-value walking. If DO_DEFN is true, mark
12744 its body too. */
12746 void
12747 trees_out::mark_declaration (tree decl, bool do_defn)
12749 mark_by_value (decl);
12751 if (TREE_CODE (decl) == TEMPLATE_DECL)
12752 decl = DECL_TEMPLATE_RESULT (decl);
12754 if (!do_defn)
12755 return;
12757 switch (TREE_CODE (decl))
12759 default:
12760 gcc_unreachable ();
12762 case FUNCTION_DECL:
12763 mark_function_def (decl);
12764 break;
12766 case TYPE_DECL:
12768 tree type = TREE_TYPE (decl);
12769 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12770 && TYPE_NAME (type) == decl);
12771 if (TREE_CODE (type) == ENUMERAL_TYPE)
12772 mark_enum_def (decl);
12773 else
12774 mark_class_def (decl);
12776 break;
12778 case VAR_DECL:
12779 case CONCEPT_DECL:
12780 mark_var_def (decl);
12781 break;
12785 /* Read in the body of DECL. See above circularity note. */
12787 bool
12788 trees_in::read_definition (tree decl)
12790 dump () && dump ("Reading definition %C %N", TREE_CODE (decl), decl);
12792 tree maybe_template = decl;
12794 again:
12795 switch (TREE_CODE (decl))
12797 default:
12798 break;
12800 case TEMPLATE_DECL:
12801 decl = DECL_TEMPLATE_RESULT (decl);
12802 goto again;
12804 case FUNCTION_DECL:
12805 return read_function_def (decl, maybe_template);
12807 case TYPE_DECL:
12809 tree type = TREE_TYPE (decl);
12810 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12811 && TYPE_NAME (type) == decl);
12812 if (TREE_CODE (type) == ENUMERAL_TYPE)
12813 return read_enum_def (decl, maybe_template);
12814 else
12815 return read_class_def (decl, maybe_template);
12817 break;
12819 case VAR_DECL:
12820 case CONCEPT_DECL:
12821 return read_var_def (decl, maybe_template);
12824 return false;
12827 /* Lookup an maybe insert a slot for depset for KEY. */
12829 depset **
12830 depset::hash::entity_slot (tree entity, bool insert)
12832 traits::compare_type key (entity, NULL);
12833 depset **slot = find_slot_with_hash (key, traits::hash (key),
12834 insert ? INSERT : NO_INSERT);
12836 return slot;
12839 depset **
12840 depset::hash::binding_slot (tree ctx, tree name, bool insert)
12842 traits::compare_type key (ctx, name);
12843 depset **slot = find_slot_with_hash (key, traits::hash (key),
12844 insert ? INSERT : NO_INSERT);
12846 return slot;
12849 depset *
12850 depset::hash::find_dependency (tree decl)
12852 depset **slot = entity_slot (decl, false);
12854 return slot ? *slot : NULL;
12857 depset *
12858 depset::hash::find_binding (tree ctx, tree name)
12860 depset **slot = binding_slot (ctx, name, false);
12862 return slot ? *slot : NULL;
12865 /* DECL is a newly discovered dependency. Create the depset, if it
12866 doesn't already exist. Add it to the worklist if so.
12868 DECL will be an OVL_USING_P OVERLOAD, if it's from a binding that's
12869 a using decl.
12871 We do not have to worry about adding the same dependency more than
12872 once. First it's harmless, but secondly the TREE_VISITED marking
12873 prevents us wanting to do it anyway. */
12875 depset *
12876 depset::hash::make_dependency (tree decl, entity_kind ek)
12878 /* Make sure we're being told consistent information. */
12879 gcc_checking_assert ((ek == EK_NAMESPACE)
12880 == (TREE_CODE (decl) == NAMESPACE_DECL
12881 && !DECL_NAMESPACE_ALIAS (decl)));
12882 gcc_checking_assert (ek != EK_BINDING && ek != EK_REDIRECT);
12883 gcc_checking_assert (TREE_CODE (decl) != FIELD_DECL
12884 && (TREE_CODE (decl) != USING_DECL
12885 || TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL));
12886 gcc_checking_assert (!is_key_order ());
12887 if (ek == EK_USING)
12888 gcc_checking_assert (TREE_CODE (decl) == OVERLOAD);
12890 if (TREE_CODE (decl) == TEMPLATE_DECL)
12891 /* The template should have copied these from its result decl. */
12892 gcc_checking_assert (DECL_MODULE_EXPORT_P (decl)
12893 == DECL_MODULE_EXPORT_P (DECL_TEMPLATE_RESULT (decl)));
12895 depset **slot = entity_slot (decl, true);
12896 depset *dep = *slot;
12897 bool for_binding = ek == EK_FOR_BINDING;
12899 if (!dep)
12901 if ((DECL_IMPLICIT_TYPEDEF_P (decl)
12902 /* ... not an enum, for instance. */
12903 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl))
12904 && TYPE_LANG_SPECIFIC (TREE_TYPE (decl))
12905 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
12906 || (VAR_P (decl)
12907 && DECL_LANG_SPECIFIC (decl)
12908 && DECL_USE_TEMPLATE (decl) == 2))
12910 /* A partial or explicit specialization. Partial
12911 specializations might not be in the hash table, because
12912 there can be multiple differently-constrained variants.
12914 template<typename T> class silly;
12915 template<typename T> requires true class silly {};
12917 We need to find them, insert their TEMPLATE_DECL in the
12918 dep_hash, and then convert the dep we just found into a
12919 redirect. */
12921 tree ti = get_template_info (decl);
12922 tree tmpl = TI_TEMPLATE (ti);
12923 tree partial = NULL_TREE;
12924 for (tree spec = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
12925 spec; spec = TREE_CHAIN (spec))
12926 if (DECL_TEMPLATE_RESULT (TREE_VALUE (spec)) == decl)
12928 partial = TREE_VALUE (spec);
12929 break;
12932 if (partial)
12934 /* Eagerly create an empty redirect. The following
12935 make_dependency call could cause hash reallocation,
12936 and invalidate slot's value. */
12937 depset *redirect = make_entity (decl, EK_REDIRECT);
12939 /* Redirects are never reached -- always snap to their target. */
12940 redirect->set_flag_bit<DB_UNREACHED_BIT> ();
12942 *slot = redirect;
12944 depset *tmpl_dep = make_dependency (partial, EK_PARTIAL);
12945 gcc_checking_assert (tmpl_dep->get_entity_kind () == EK_PARTIAL);
12947 redirect->deps.safe_push (tmpl_dep);
12949 return redirect;
12953 bool has_def = ek != EK_USING && has_definition (decl);
12954 if (ek > EK_BINDING)
12955 ek = EK_DECL;
12957 /* The only OVERLOADS we should see are USING decls from
12958 bindings. */
12959 *slot = dep = make_entity (decl, ek, has_def);
12961 if (CHECKING_P && TREE_CODE (decl) == TEMPLATE_DECL)
12962 /* The template_result should otherwise not be in the
12963 table, or be an empty redirect (created above). */
12964 if (auto *eslot = entity_slot (DECL_TEMPLATE_RESULT (decl), false))
12965 gcc_checking_assert ((*eslot)->get_entity_kind () == EK_REDIRECT
12966 && !(*eslot)->deps.length ());
12968 if (ek != EK_USING)
12970 tree not_tmpl = STRIP_TEMPLATE (decl);
12972 if (DECL_LANG_SPECIFIC (not_tmpl)
12973 && DECL_MODULE_IMPORT_P (not_tmpl))
12975 /* Store the module number and index in cluster/section,
12976 so we don't have to look them up again. */
12977 unsigned index = import_entity_index (decl);
12978 module_state *from = import_entity_module (index);
12979 /* Remap will be zero for imports from partitions, which
12980 we want to treat as-if declared in this TU. */
12981 if (from->remap)
12983 dep->cluster = index - from->entity_lwm;
12984 dep->section = from->remap;
12985 dep->set_flag_bit<DB_IMPORTED_BIT> ();
12989 if (ek == EK_DECL
12990 && !dep->is_import ()
12991 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL
12992 && !(TREE_CODE (decl) == TEMPLATE_DECL
12993 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl)))
12995 tree ctx = CP_DECL_CONTEXT (decl);
12997 if (!TREE_PUBLIC (ctx))
12998 /* Member of internal namespace. */
12999 dep->set_flag_bit<DB_IS_INTERNAL_BIT> ();
13000 else if (VAR_OR_FUNCTION_DECL_P (not_tmpl)
13001 && DECL_THIS_STATIC (not_tmpl))
13003 /* An internal decl. This is ok in a GM entity. */
13004 if (!(header_module_p ()
13005 || !DECL_LANG_SPECIFIC (not_tmpl)
13006 || !DECL_MODULE_PURVIEW_P (not_tmpl)))
13007 dep->set_flag_bit<DB_IS_INTERNAL_BIT> ();
13012 if (!dep->is_import ())
13013 worklist.safe_push (dep);
13016 dump (dumper::DEPEND)
13017 && dump ("%s on %s %C:%N found",
13018 ek == EK_REDIRECT ? "Redirect"
13019 : for_binding ? "Binding" : "Dependency",
13020 dep->entity_kind_name (), TREE_CODE (decl), decl);
13022 return dep;
13025 /* DEP is a newly discovered dependency. Append it to current's
13026 depset. */
13028 void
13029 depset::hash::add_dependency (depset *dep)
13031 gcc_checking_assert (current && !is_key_order ());
13032 current->deps.safe_push (dep);
13034 if (dep->is_internal () && !current->is_internal ())
13035 current->set_flag_bit<DB_REFS_INTERNAL_BIT> ();
13037 if (current->get_entity_kind () == EK_USING
13038 && DECL_IMPLICIT_TYPEDEF_P (dep->get_entity ())
13039 && TREE_CODE (TREE_TYPE (dep->get_entity ())) == ENUMERAL_TYPE)
13041 /* CURRENT is an unwrapped using-decl and DECL is an enum's
13042 implicit typedef. Is CURRENT a member of the enum? */
13043 tree c_decl = OVL_FUNCTION (current->get_entity ());
13045 if (TREE_CODE (c_decl) == CONST_DECL
13046 && (current->deps[0]->get_entity ()
13047 == CP_DECL_CONTEXT (dep->get_entity ())))
13048 /* Make DECL depend on CURRENT. */
13049 dep->deps.safe_push (current);
13052 if (dep->is_unreached ())
13054 /* The dependency is reachable now. */
13055 reached_unreached = true;
13056 dep->clear_flag_bit<DB_UNREACHED_BIT> ();
13057 dump (dumper::DEPEND)
13058 && dump ("Reaching unreached %s %C:%N", dep->entity_kind_name (),
13059 TREE_CODE (dep->get_entity ()), dep->get_entity ());
13063 depset *
13064 depset::hash::add_dependency (tree decl, entity_kind ek)
13066 depset *dep;
13068 if (is_key_order ())
13070 dep = find_dependency (decl);
13071 if (dep)
13073 current->deps.safe_push (dep);
13074 dump (dumper::MERGE)
13075 && dump ("Key dependency on %s %C:%N found",
13076 dep->entity_kind_name (), TREE_CODE (decl), decl);
13078 else
13080 /* It's not a mergeable decl, look for it in the original
13081 table. */
13082 dep = chain->find_dependency (decl);
13083 gcc_checking_assert (dep);
13086 else
13088 dep = make_dependency (decl, ek);
13089 if (dep->get_entity_kind () != EK_REDIRECT)
13090 add_dependency (dep);
13093 return dep;
13096 void
13097 depset::hash::add_namespace_context (depset *dep, tree ns)
13099 depset *ns_dep = make_dependency (ns, depset::EK_NAMESPACE);
13100 dep->deps.safe_push (ns_dep);
13102 /* Mark it as special if imported so we don't walk connect when
13103 SCCing. */
13104 if (!dep->is_binding () && ns_dep->is_import ())
13105 dep->set_special ();
13108 struct add_binding_data
13110 tree ns;
13111 bitmap partitions;
13112 depset *binding;
13113 depset::hash *hash;
13114 bool met_namespace;
13117 /* Return true if we are, or contain something that is exported. */
13119 bool
13120 depset::hash::add_binding_entity (tree decl, WMB_Flags flags, void *data_)
13122 auto data = static_cast <add_binding_data *> (data_);
13124 if (!(TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl)))
13126 tree inner = decl;
13128 if (TREE_CODE (inner) == CONST_DECL
13129 && TREE_CODE (DECL_CONTEXT (inner)) == ENUMERAL_TYPE)
13130 inner = TYPE_NAME (DECL_CONTEXT (inner));
13131 else if (TREE_CODE (inner) == TEMPLATE_DECL)
13132 inner = DECL_TEMPLATE_RESULT (inner);
13134 if ((!DECL_LANG_SPECIFIC (inner) || !DECL_MODULE_PURVIEW_P (inner))
13135 && !((flags & WMB_Using) && (flags & WMB_Export)))
13136 /* Ignore global module fragment entities unless explicitly
13137 exported with a using declaration. */
13138 return false;
13140 if (VAR_OR_FUNCTION_DECL_P (inner)
13141 && DECL_THIS_STATIC (inner))
13143 if (!header_module_p ())
13144 /* Ignore internal-linkage entitites. */
13145 return false;
13148 if ((TREE_CODE (decl) == VAR_DECL
13149 || TREE_CODE (decl) == TYPE_DECL)
13150 && DECL_TINFO_P (decl))
13151 /* Ignore TINFO things. */
13152 return false;
13154 if (TREE_CODE (decl) == VAR_DECL && DECL_NTTP_OBJECT_P (decl))
13155 /* Ignore NTTP objects. */
13156 return false;
13158 bool unscoped_enum_const_p = false;
13159 if (!(flags & WMB_Using) && CP_DECL_CONTEXT (decl) != data->ns)
13161 /* A using that lost its wrapper or an unscoped enum
13162 constant. */
13163 /* FIXME: Ensure that unscoped enums are differentiated from
13164 'using enum' declarations when PR c++/114683 is fixed. */
13165 unscoped_enum_const_p = (TREE_CODE (decl) == CONST_DECL);
13166 flags = WMB_Flags (flags | WMB_Using);
13167 if (DECL_MODULE_EXPORT_P (TREE_CODE (decl) == CONST_DECL
13168 ? TYPE_NAME (TREE_TYPE (decl))
13169 : STRIP_TEMPLATE (decl)))
13170 flags = WMB_Flags (flags | WMB_Export);
13173 if (!data->binding)
13174 /* No binding to check. */;
13175 else if (flags & WMB_Using)
13177 /* Look in the binding to see if we already have this
13178 using. */
13179 for (unsigned ix = data->binding->deps.length (); --ix;)
13181 depset *d = data->binding->deps[ix];
13182 if (d->get_entity_kind () == EK_USING
13183 && OVL_FUNCTION (d->get_entity ()) == decl)
13185 if (!(flags & WMB_Hidden))
13186 d->clear_hidden_binding ();
13187 if (flags & WMB_Export)
13188 OVL_EXPORT_P (d->get_entity ()) = true;
13189 return bool (flags & WMB_Export);
13193 else if (flags & WMB_Dups)
13195 /* Look in the binding to see if we already have this decl. */
13196 for (unsigned ix = data->binding->deps.length (); --ix;)
13198 depset *d = data->binding->deps[ix];
13199 if (d->get_entity () == decl)
13201 if (!(flags & WMB_Hidden))
13202 d->clear_hidden_binding ();
13203 return false;
13208 /* We're adding something. */
13209 if (!data->binding)
13211 data->binding = make_binding (data->ns, DECL_NAME (decl));
13212 data->hash->add_namespace_context (data->binding, data->ns);
13214 depset **slot = data->hash->binding_slot (data->ns,
13215 DECL_NAME (decl), true);
13216 gcc_checking_assert (!*slot);
13217 *slot = data->binding;
13220 /* Make sure nobody left a tree visited lying about. */
13221 gcc_checking_assert (!TREE_VISITED (decl));
13223 if (flags & WMB_Using)
13225 decl = ovl_make (decl, NULL_TREE);
13226 if (!unscoped_enum_const_p)
13227 OVL_USING_P (decl) = true;
13228 if (flags & WMB_Export)
13229 OVL_EXPORT_P (decl) = true;
13232 depset *dep = data->hash->make_dependency
13233 (decl, flags & WMB_Using ? EK_USING : EK_FOR_BINDING);
13234 if (flags & WMB_Hidden)
13235 dep->set_hidden_binding ();
13236 data->binding->deps.safe_push (dep);
13237 /* Binding and contents are mutually dependent. */
13238 dep->deps.safe_push (data->binding);
13240 return (flags & WMB_Using
13241 ? flags & WMB_Export : DECL_MODULE_EXPORT_P (decl));
13243 else if (DECL_NAME (decl) && !data->met_namespace)
13245 /* Namespace, walk exactly once. */
13246 gcc_checking_assert (TREE_PUBLIC (decl));
13247 data->met_namespace = true;
13248 if (data->hash->add_namespace_entities (decl, data->partitions))
13250 /* It contains an exported thing, so it is exported. */
13251 gcc_checking_assert (DECL_MODULE_PURVIEW_P (decl));
13252 DECL_MODULE_EXPORT_P (decl) = true;
13255 if (DECL_MODULE_PURVIEW_P (decl))
13257 data->hash->make_dependency (decl, depset::EK_NAMESPACE);
13259 return DECL_MODULE_EXPORT_P (decl);
13263 return false;
13266 /* Recursively find all the namespace bindings of NS. Add a depset
13267 for every binding that contains an export or module-linkage entity.
13268 Add a defining depset for every such decl that we need to write a
13269 definition. Such defining depsets depend on the binding depset.
13270 Returns true if we contain something exported. */
13272 bool
13273 depset::hash::add_namespace_entities (tree ns, bitmap partitions)
13275 dump () && dump ("Looking for writables in %N", ns);
13276 dump.indent ();
13278 unsigned count = 0;
13279 add_binding_data data;
13280 data.ns = ns;
13281 data.partitions = partitions;
13282 data.hash = this;
13284 hash_table<named_decl_hash>::iterator end
13285 (DECL_NAMESPACE_BINDINGS (ns)->end ());
13286 for (hash_table<named_decl_hash>::iterator iter
13287 (DECL_NAMESPACE_BINDINGS (ns)->begin ()); iter != end; ++iter)
13289 data.binding = nullptr;
13290 data.met_namespace = false;
13291 if (walk_module_binding (*iter, partitions, add_binding_entity, &data))
13292 count++;
13295 if (count)
13296 dump () && dump ("Found %u entries", count);
13297 dump.outdent ();
13299 return count != 0;
13302 void
13303 depset::hash::add_partial_entities (vec<tree, va_gc> *partial_classes)
13305 for (unsigned ix = 0; ix != partial_classes->length (); ix++)
13307 tree inner = (*partial_classes)[ix];
13309 depset *dep = make_dependency (inner, depset::EK_DECL);
13311 if (dep->get_entity_kind () == depset::EK_REDIRECT)
13313 dep = dep->deps[0];
13314 /* We should have recorded the template as a partial
13315 specialization. */
13316 gcc_checking_assert (dep->get_entity_kind ()
13317 == depset::EK_PARTIAL);
13319 else
13320 /* It was an explicit specialization, not a partial one. */
13321 gcc_checking_assert (dep->get_entity_kind ()
13322 == depset::EK_SPECIALIZATION);
13324 /* Only emit GM entities if reached. */
13325 if (!DECL_LANG_SPECIFIC (inner)
13326 || !DECL_MODULE_PURVIEW_P (inner))
13327 dep->set_flag_bit<DB_UNREACHED_BIT> ();
13331 /* Add the members of imported classes that we defined in this TU.
13332 This will also include lazily created implicit member function
13333 declarations. (All others will be definitions.) */
13335 void
13336 depset::hash::add_class_entities (vec<tree, va_gc> *class_members)
13338 for (unsigned ix = 0; ix != class_members->length (); ix++)
13340 tree defn = (*class_members)[ix];
13341 depset *dep = make_dependency (defn, EK_INNER_DECL);
13343 if (dep->get_entity_kind () == EK_REDIRECT)
13344 dep = dep->deps[0];
13346 /* Only non-instantiations need marking as members. */
13347 if (dep->get_entity_kind () == EK_DECL)
13348 dep->set_flag_bit <DB_IS_MEMBER_BIT> ();
13352 /* We add the partial & explicit specializations, and the explicit
13353 instantiations. */
13355 static void
13356 specialization_add (bool decl_p, spec_entry *entry, void *data_)
13358 vec<spec_entry *> *data = reinterpret_cast <vec<spec_entry *> *> (data_);
13360 if (!decl_p)
13362 /* We exclusively use decls to locate things. Make sure there's
13363 no mismatch between the two specialization tables we keep.
13364 pt.cc optimizes instantiation lookup using a complicated
13365 heuristic. We don't attempt to replicate that algorithm, but
13366 observe its behaviour and reproduce it upon read back. */
13368 gcc_checking_assert (TREE_CODE (entry->spec) == ENUMERAL_TYPE
13369 || DECL_CLASS_TEMPLATE_P (entry->tmpl));
13371 gcc_checking_assert (!match_mergeable_specialization (true, entry));
13373 else if (VAR_OR_FUNCTION_DECL_P (entry->spec))
13374 gcc_checking_assert (!DECL_LOCAL_DECL_P (entry->spec));
13376 data->safe_push (entry);
13379 /* Arbitrary stable comparison. */
13381 static int
13382 specialization_cmp (const void *a_, const void *b_)
13384 const spec_entry *ea = *reinterpret_cast<const spec_entry *const *> (a_);
13385 const spec_entry *eb = *reinterpret_cast<const spec_entry *const *> (b_);
13387 if (ea == eb)
13388 return 0;
13390 tree a = ea->spec;
13391 tree b = eb->spec;
13392 if (TYPE_P (a))
13394 a = TYPE_NAME (a);
13395 b = TYPE_NAME (b);
13398 if (a == b)
13399 /* This can happen with friend specializations. Just order by
13400 entry address. See note in depset_cmp. */
13401 return ea < eb ? -1 : +1;
13403 return DECL_UID (a) < DECL_UID (b) ? -1 : +1;
13406 /* We add all kinds of specialializations. Implicit specializations
13407 should only streamed and walked if they are reachable from
13408 elsewhere. Hence the UNREACHED flag. This is making the
13409 assumption that it is cheaper to reinstantiate them on demand
13410 elsewhere, rather than stream them in when we instantiate their
13411 general template. Also, if we do stream them, we can only do that
13412 if they are not internal (which they can become if they themselves
13413 touch an internal entity?). */
13415 void
13416 depset::hash::add_specializations (bool decl_p)
13418 vec<spec_entry *> data;
13419 data.create (100);
13420 walk_specializations (decl_p, specialization_add, &data);
13421 data.qsort (specialization_cmp);
13422 while (data.length ())
13424 spec_entry *entry = data.pop ();
13425 tree spec = entry->spec;
13426 int use_tpl = 0;
13427 bool is_friend = false;
13429 if (decl_p && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (entry->tmpl))
13430 /* A friend of a template. This is keyed to the
13431 instantiation. */
13432 is_friend = true;
13434 if (decl_p)
13436 if (tree ti = DECL_TEMPLATE_INFO (spec))
13438 tree tmpl = TI_TEMPLATE (ti);
13440 use_tpl = DECL_USE_TEMPLATE (spec);
13441 if (spec == DECL_TEMPLATE_RESULT (tmpl))
13443 spec = tmpl;
13444 gcc_checking_assert (DECL_USE_TEMPLATE (spec) == use_tpl);
13446 else if (is_friend)
13448 if (TI_TEMPLATE (ti) != entry->tmpl
13449 || !template_args_equal (TI_ARGS (ti), entry->tmpl))
13450 goto template_friend;
13453 else
13455 template_friend:;
13456 gcc_checking_assert (is_friend);
13457 /* This is a friend of a template class, but not the one
13458 that generated entry->spec itself (i.e. it's an
13459 equivalent clone). We do not need to record
13460 this. */
13461 continue;
13464 else
13466 if (TREE_CODE (spec) == ENUMERAL_TYPE)
13468 tree ctx = DECL_CONTEXT (TYPE_NAME (spec));
13470 if (TYPE_P (ctx))
13471 use_tpl = CLASSTYPE_USE_TEMPLATE (ctx);
13472 else
13473 use_tpl = DECL_USE_TEMPLATE (ctx);
13475 else
13476 use_tpl = CLASSTYPE_USE_TEMPLATE (spec);
13478 tree ti = TYPE_TEMPLATE_INFO (spec);
13479 tree tmpl = TI_TEMPLATE (ti);
13481 spec = TYPE_NAME (spec);
13482 if (spec == DECL_TEMPLATE_RESULT (tmpl))
13484 spec = tmpl;
13485 use_tpl = DECL_USE_TEMPLATE (spec);
13489 bool needs_reaching = false;
13490 if (use_tpl == 1)
13491 /* Implicit instantiations only walked if we reach them. */
13492 needs_reaching = true;
13493 else if (!DECL_LANG_SPECIFIC (STRIP_TEMPLATE (spec))
13494 || !DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (spec)))
13495 /* Likewise, GMF explicit or partial specializations. */
13496 needs_reaching = true;
13498 #if false && CHECKING_P
13499 /* The instantiation isn't always on
13500 DECL_TEMPLATE_INSTANTIATIONS, */
13501 // FIXME: we probably need to remember this information?
13502 /* Verify the specialization is on the
13503 DECL_TEMPLATE_INSTANTIATIONS of the template. */
13504 for (tree cons = DECL_TEMPLATE_INSTANTIATIONS (entry->tmpl);
13505 cons; cons = TREE_CHAIN (cons))
13506 if (TREE_VALUE (cons) == entry->spec)
13508 gcc_assert (entry->args == TREE_PURPOSE (cons));
13509 goto have_spec;
13511 gcc_unreachable ();
13512 have_spec:;
13513 #endif
13515 /* Make sure nobody left a tree visited lying about. */
13516 gcc_checking_assert (!TREE_VISITED (spec));
13517 depset *dep = make_dependency (spec, depset::EK_SPECIALIZATION);
13518 if (dep->is_special ())
13519 gcc_unreachable ();
13520 else
13522 if (dep->get_entity_kind () == depset::EK_REDIRECT)
13523 dep = dep->deps[0];
13524 else if (dep->get_entity_kind () == depset::EK_SPECIALIZATION)
13526 dep->set_special ();
13527 dep->deps.safe_push (reinterpret_cast<depset *> (entry));
13528 if (!decl_p)
13529 dep->set_flag_bit<DB_TYPE_SPEC_BIT> ();
13532 if (needs_reaching)
13533 dep->set_flag_bit<DB_UNREACHED_BIT> ();
13534 if (is_friend)
13535 dep->set_flag_bit<DB_FRIEND_SPEC_BIT> ();
13538 data.release ();
13541 /* Add a depset into the mergeable hash. */
13543 void
13544 depset::hash::add_mergeable (depset *mergeable)
13546 gcc_checking_assert (is_key_order ());
13547 entity_kind ek = mergeable->get_entity_kind ();
13548 tree decl = mergeable->get_entity ();
13549 gcc_checking_assert (ek < EK_DIRECT_HWM);
13551 depset **slot = entity_slot (decl, true);
13552 gcc_checking_assert (!*slot);
13553 depset *dep = make_entity (decl, ek);
13554 *slot = dep;
13556 worklist.safe_push (dep);
13558 /* So we can locate the mergeable depset this depset refers to,
13559 mark the first dep. */
13560 dep->set_special ();
13561 dep->deps.safe_push (mergeable);
13564 /* Find the innermost-namespace scope of DECL, and that
13565 namespace-scope decl. */
13567 tree
13568 find_pending_key (tree decl, tree *decl_p = nullptr)
13570 tree ns = decl;
13573 decl = ns;
13574 ns = CP_DECL_CONTEXT (ns);
13575 if (TYPE_P (ns))
13576 ns = TYPE_NAME (ns);
13578 while (TREE_CODE (ns) != NAMESPACE_DECL);
13580 if (decl_p)
13581 *decl_p = decl;
13583 return ns;
13586 /* Iteratively find dependencies. During the walk we may find more
13587 entries on the same binding that need walking. */
13589 void
13590 depset::hash::find_dependencies (module_state *module)
13592 trees_out walker (NULL, module, *this);
13593 vec<depset *> unreached;
13594 unreached.create (worklist.length ());
13596 for (;;)
13598 reached_unreached = false;
13599 while (worklist.length ())
13601 depset *item = worklist.pop ();
13603 gcc_checking_assert (!item->is_binding ());
13604 if (item->is_unreached ())
13605 unreached.quick_push (item);
13606 else
13608 current = item;
13609 tree decl = current->get_entity ();
13610 dump (is_key_order () ? dumper::MERGE : dumper::DEPEND)
13611 && dump ("Dependencies of %s %C:%N",
13612 is_key_order () ? "key-order"
13613 : current->entity_kind_name (), TREE_CODE (decl), decl);
13614 dump.indent ();
13615 walker.begin ();
13616 if (current->get_entity_kind () == EK_USING)
13617 walker.tree_node (OVL_FUNCTION (decl));
13618 else if (TREE_VISITED (decl))
13619 /* A global tree. */;
13620 else if (item->get_entity_kind () == EK_NAMESPACE)
13622 module->note_location (DECL_SOURCE_LOCATION (decl));
13623 add_namespace_context (current, CP_DECL_CONTEXT (decl));
13625 else
13627 walker.mark_declaration (decl, current->has_defn ());
13629 if (!walker.is_key_order ()
13630 && (item->get_entity_kind () == EK_SPECIALIZATION
13631 || item->get_entity_kind () == EK_PARTIAL
13632 || (item->get_entity_kind () == EK_DECL
13633 && item->is_member ())))
13635 tree ns = find_pending_key (decl, nullptr);
13636 add_namespace_context (item, ns);
13639 walker.decl_value (decl, current);
13640 if (current->has_defn ())
13641 walker.write_definition (decl);
13643 walker.end ();
13645 if (!walker.is_key_order ()
13646 && TREE_CODE (decl) == TEMPLATE_DECL
13647 && !DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
13649 /* Mark all the explicit & partial specializations as
13650 reachable. We search both specialization lists as some
13651 constrained partial specializations for class types are
13652 only found in DECL_TEMPLATE_SPECIALIZATIONS. */
13653 auto mark_reached = [this](tree spec)
13655 if (TYPE_P (spec))
13656 spec = TYPE_NAME (spec);
13657 int use_tpl;
13658 node_template_info (spec, use_tpl);
13659 if (use_tpl & 2)
13661 depset *spec_dep = find_dependency (spec);
13662 if (spec_dep->get_entity_kind () == EK_REDIRECT)
13663 spec_dep = spec_dep->deps[0];
13664 if (spec_dep->is_unreached ())
13666 reached_unreached = true;
13667 spec_dep->clear_flag_bit<DB_UNREACHED_BIT> ();
13668 dump (dumper::DEPEND)
13669 && dump ("Reaching unreached specialization"
13670 " %C:%N", TREE_CODE (spec), spec);
13675 for (tree cons = DECL_TEMPLATE_INSTANTIATIONS (decl);
13676 cons; cons = TREE_CHAIN (cons))
13677 mark_reached (TREE_VALUE (cons));
13678 for (tree cons = DECL_TEMPLATE_SPECIALIZATIONS (decl);
13679 cons; cons = TREE_CHAIN (cons))
13680 mark_reached (TREE_VALUE (cons));
13683 dump.outdent ();
13684 current = NULL;
13688 if (!reached_unreached)
13689 break;
13691 /* It's possible the we reached the unreached before we
13692 processed it in the above loop, so we'll be doing this an
13693 extra time. However, to avoid that we have to do some
13694 bit shuffling that also involves a scan of the list.
13695 Swings & roundabouts I guess. */
13696 std::swap (worklist, unreached);
13699 unreached.release ();
13702 /* Compare two entries of a single binding. TYPE_DECL before
13703 non-exported before exported. */
13705 static int
13706 binding_cmp (const void *a_, const void *b_)
13708 depset *a = *(depset *const *)a_;
13709 depset *b = *(depset *const *)b_;
13711 tree a_ent = a->get_entity ();
13712 tree b_ent = b->get_entity ();
13713 gcc_checking_assert (a_ent != b_ent
13714 && !a->is_binding ()
13715 && !b->is_binding ());
13717 /* Implicit typedefs come first. */
13718 bool a_implicit = DECL_IMPLICIT_TYPEDEF_P (a_ent);
13719 bool b_implicit = DECL_IMPLICIT_TYPEDEF_P (b_ent);
13720 if (a_implicit || b_implicit)
13722 /* A binding with two implicit type decls? That's unpossible! */
13723 gcc_checking_assert (!(a_implicit && b_implicit));
13724 return a_implicit ? -1 : +1; /* Implicit first. */
13727 /* Hidden before non-hidden. */
13728 bool a_hidden = a->is_hidden ();
13729 bool b_hidden = b->is_hidden ();
13730 if (a_hidden != b_hidden)
13731 return a_hidden ? -1 : +1;
13733 bool a_using = a->get_entity_kind () == depset::EK_USING;
13734 bool a_export;
13735 if (a_using)
13737 a_export = OVL_EXPORT_P (a_ent);
13738 a_ent = OVL_FUNCTION (a_ent);
13740 else
13741 a_export = DECL_MODULE_EXPORT_P (TREE_CODE (a_ent) == CONST_DECL
13742 ? TYPE_NAME (TREE_TYPE (a_ent))
13743 : STRIP_TEMPLATE (a_ent));
13745 bool b_using = b->get_entity_kind () == depset::EK_USING;
13746 bool b_export;
13747 if (b_using)
13749 b_export = OVL_EXPORT_P (b_ent);
13750 b_ent = OVL_FUNCTION (b_ent);
13752 else
13753 b_export = DECL_MODULE_EXPORT_P (TREE_CODE (b_ent) == CONST_DECL
13754 ? TYPE_NAME (TREE_TYPE (b_ent))
13755 : STRIP_TEMPLATE (b_ent));
13757 /* Non-exports before exports. */
13758 if (a_export != b_export)
13759 return a_export ? +1 : -1;
13761 /* At this point we don't care, but want a stable sort. */
13763 if (a_using != b_using)
13764 /* using first. */
13765 return a_using? -1 : +1;
13767 return DECL_UID (a_ent) < DECL_UID (b_ent) ? -1 : +1;
13770 /* Sort the bindings, issue errors about bad internal refs. */
13772 bool
13773 depset::hash::finalize_dependencies ()
13775 bool ok = true;
13776 depset::hash::iterator end (this->end ());
13777 for (depset::hash::iterator iter (begin ()); iter != end; ++iter)
13779 depset *dep = *iter;
13780 if (dep->is_binding ())
13782 /* Keep the containing namespace dep first. */
13783 gcc_checking_assert (dep->deps.length () > 1
13784 && (dep->deps[0]->get_entity_kind ()
13785 == EK_NAMESPACE)
13786 && (dep->deps[0]->get_entity ()
13787 == dep->get_entity ()));
13788 if (dep->deps.length () > 2)
13789 gcc_qsort (&dep->deps[1], dep->deps.length () - 1,
13790 sizeof (dep->deps[1]), binding_cmp);
13792 else if (dep->refs_internal ())
13794 for (unsigned ix = dep->deps.length (); ix--;)
13796 depset *rdep = dep->deps[ix];
13797 if (rdep->is_internal ())
13799 // FIXME:QOI Better location information? We're
13800 // losing, so it doesn't matter about efficiency
13801 tree decl = dep->get_entity ();
13802 error_at (DECL_SOURCE_LOCATION (decl),
13803 "%q#D references internal linkage entity %q#D",
13804 decl, rdep->get_entity ());
13805 break;
13808 ok = false;
13812 return ok;
13815 /* Core of TARJAN's algorithm to find Strongly Connected Components
13816 within a graph. See https://en.wikipedia.org/wiki/
13817 Tarjan%27s_strongly_connected_components_algorithm for details.
13819 We use depset::section as lowlink. Completed nodes have
13820 depset::cluster containing the cluster number, with the top
13821 bit set.
13823 A useful property is that the output vector is a reverse
13824 topological sort of the resulting DAG. In our case that means
13825 dependent SCCs are found before their dependers. We make use of
13826 that property. */
13828 void
13829 depset::tarjan::connect (depset *v)
13831 gcc_checking_assert (v->is_binding ()
13832 || !(v->is_unreached () || v->is_import ()));
13834 v->cluster = v->section = ++index;
13835 stack.safe_push (v);
13837 /* Walk all our dependencies, ignore a first marked slot */
13838 for (unsigned ix = v->is_special (); ix != v->deps.length (); ix++)
13840 depset *dep = v->deps[ix];
13842 if (dep->is_binding () || !dep->is_import ())
13844 unsigned lwm = dep->cluster;
13846 if (!dep->cluster)
13848 /* A new node. Connect it. */
13849 connect (dep);
13850 lwm = dep->section;
13853 if (dep->section && v->section > lwm)
13854 v->section = lwm;
13858 if (v->section == v->cluster)
13860 /* Root of a new SCC. Push all the members onto the result list. */
13861 unsigned num = v->cluster;
13862 depset *p;
13865 p = stack.pop ();
13866 p->cluster = num;
13867 p->section = 0;
13868 result.quick_push (p);
13870 while (p != v);
13874 /* Compare two depsets. The specific ordering is unimportant, we're
13875 just trying to get consistency. */
13877 static int
13878 depset_cmp (const void *a_, const void *b_)
13880 depset *a = *(depset *const *)a_;
13881 depset *b = *(depset *const *)b_;
13883 depset::entity_kind a_kind = a->get_entity_kind ();
13884 depset::entity_kind b_kind = b->get_entity_kind ();
13886 if (a_kind != b_kind)
13887 /* Different entity kinds, order by that. */
13888 return a_kind < b_kind ? -1 : +1;
13890 tree a_decl = a->get_entity ();
13891 tree b_decl = b->get_entity ();
13892 if (a_kind == depset::EK_USING)
13894 /* If one is a using, the other must be too. */
13895 a_decl = OVL_FUNCTION (a_decl);
13896 b_decl = OVL_FUNCTION (b_decl);
13899 if (a_decl != b_decl)
13900 /* Different entities, order by their UID. */
13901 return DECL_UID (a_decl) < DECL_UID (b_decl) ? -1 : +1;
13903 if (a_kind == depset::EK_BINDING)
13905 /* Both are bindings. Order by identifier hash. */
13906 gcc_checking_assert (a->get_name () != b->get_name ());
13907 hashval_t ah = IDENTIFIER_HASH_VALUE (a->get_name ());
13908 hashval_t bh = IDENTIFIER_HASH_VALUE (b->get_name ());
13909 return (ah == bh ? 0 : ah < bh ? -1 : +1);
13912 /* They are the same decl. This can happen with two using decls
13913 pointing to the same target. The best we can aim for is
13914 consistently telling qsort how to order them. Hopefully we'll
13915 never have to debug a case that depends on this. Oh, who am I
13916 kidding? Good luck. */
13917 gcc_checking_assert (a_kind == depset::EK_USING);
13919 /* Order by depset address. Not the best, but it is something. */
13920 return a < b ? -1 : +1;
13923 /* Sort the clusters in SCC such that those that depend on one another
13924 are placed later. */
13926 // FIXME: I am not convinced this is needed and, if needed,
13927 // sufficient. We emit the decls in this order but that emission
13928 // could walk into later decls (from the body of the decl, or default
13929 // arg-like things). Why doesn't that walk do the right thing? And
13930 // if it DTRT why do we need to sort here -- won't things naturally
13931 // work? I think part of the issue is that when we're going to refer
13932 // to an entity by name, and that entity is in the same cluster as us,
13933 // we need to actually walk that entity, if we've not already walked
13934 // it.
13935 static void
13936 sort_cluster (depset::hash *original, depset *scc[], unsigned size)
13938 depset::hash table (size, original);
13940 dump.indent ();
13942 /* Place bindings last, usings before that. It's not strictly
13943 necessary, but it does make things neater. Says Mr OCD. */
13944 unsigned bind_lwm = size;
13945 unsigned use_lwm = size;
13946 for (unsigned ix = 0; ix != use_lwm;)
13948 depset *dep = scc[ix];
13949 switch (dep->get_entity_kind ())
13951 case depset::EK_BINDING:
13952 /* Move to end. No increment. Notice this could be moving
13953 a using decl, which we'll then move again. */
13954 if (--bind_lwm != ix)
13956 scc[ix] = scc[bind_lwm];
13957 scc[bind_lwm] = dep;
13959 if (use_lwm > bind_lwm)
13961 use_lwm--;
13962 break;
13964 /* We must have copied a using, so move it too. */
13965 dep = scc[ix];
13966 gcc_checking_assert (dep->get_entity_kind () == depset::EK_USING);
13967 /* FALLTHROUGH */
13969 case depset::EK_USING:
13970 if (--use_lwm != ix)
13972 scc[ix] = scc[use_lwm];
13973 scc[use_lwm] = dep;
13975 break;
13977 case depset::EK_DECL:
13978 case depset::EK_SPECIALIZATION:
13979 case depset::EK_PARTIAL:
13980 table.add_mergeable (dep);
13981 ix++;
13982 break;
13984 default:
13985 gcc_unreachable ();
13989 gcc_checking_assert (use_lwm <= bind_lwm);
13990 dump (dumper::MERGE) && dump ("Ordering %u/%u depsets", use_lwm, size);
13992 table.find_dependencies (nullptr);
13994 vec<depset *> order = table.connect ();
13995 gcc_checking_assert (order.length () == use_lwm);
13997 /* Now rewrite entries [0,lwm), in the dependency order we
13998 discovered. Usually each entity is in its own cluster. Rarely,
13999 we can get multi-entity clusters, in which case all but one must
14000 only be reached from within the cluster. This happens for
14001 something like:
14003 template<typename T>
14004 auto Foo (const T &arg) -> TPL<decltype (arg)>;
14006 The instantiation of TPL will be in the specialization table, and
14007 refer to Foo via arg. But we can only get to that specialization
14008 from Foo's declaration, so we only need to treat Foo as mergable
14009 (We'll do structural comparison of TPL<decltype (arg)>).
14011 Finding the single cluster entry dep is very tricky and
14012 expensive. Let's just not do that. It's harmless in this case
14013 anyway. */
14014 unsigned pos = 0;
14015 unsigned cluster = ~0u;
14016 for (unsigned ix = 0; ix != order.length (); ix++)
14018 gcc_checking_assert (order[ix]->is_special ());
14019 depset *dep = order[ix]->deps[0];
14020 scc[pos++] = dep;
14021 dump (dumper::MERGE)
14022 && dump ("Mergeable %u is %N%s", ix, dep->get_entity (),
14023 order[ix]->cluster == cluster ? " (tight)" : "");
14024 cluster = order[ix]->cluster;
14027 gcc_checking_assert (pos == use_lwm);
14029 order.release ();
14030 dump (dumper::MERGE) && dump ("Ordered %u keys", pos);
14031 dump.outdent ();
14034 /* Reduce graph to SCCS clusters. SCCS will be populated with the
14035 depsets in dependency order. Each depset's CLUSTER field contains
14036 its cluster number. Each SCC has a unique cluster number, and are
14037 contiguous in SCCS. Cluster numbers are otherwise arbitrary. */
14039 vec<depset *>
14040 depset::hash::connect ()
14042 tarjan connector (size ());
14043 vec<depset *> deps;
14044 deps.create (size ());
14045 iterator end (this->end ());
14046 for (iterator iter (begin ()); iter != end; ++iter)
14048 depset *item = *iter;
14050 entity_kind kind = item->get_entity_kind ();
14051 if (kind == EK_BINDING
14052 || !(kind == EK_REDIRECT
14053 || item->is_unreached ()
14054 || item->is_import ()))
14055 deps.quick_push (item);
14058 /* Iteration over the hash table is an unspecified ordering. While
14059 that has advantages, it causes 2 problems. Firstly repeatable
14060 builds are tricky. Secondly creating testcases that check
14061 dependencies are correct by making sure a bad ordering would
14062 happen if that was wrong. */
14063 deps.qsort (depset_cmp);
14065 while (deps.length ())
14067 depset *v = deps.pop ();
14068 dump (dumper::CLUSTER) &&
14069 (v->is_binding ()
14070 ? dump ("Connecting binding %P", v->get_entity (), v->get_name ())
14071 : dump ("Connecting %s %s %C:%N",
14072 is_key_order () ? "key-order"
14073 : !v->has_defn () ? "declaration" : "definition",
14074 v->entity_kind_name (), TREE_CODE (v->get_entity ()),
14075 v->get_entity ()));
14076 if (!v->cluster)
14077 connector.connect (v);
14080 deps.release ();
14081 return connector.result;
14084 /* Initialize location spans. */
14086 void
14087 loc_spans::init (const line_maps *lmaps, const line_map_ordinary *map)
14089 gcc_checking_assert (!init_p ());
14090 spans = new vec<span> ();
14091 spans->reserve (20);
14093 span interval;
14094 interval.ordinary.first = 0;
14095 interval.macro.second = MAX_LOCATION_T + 1;
14096 interval.ordinary_delta = interval.macro_delta = 0;
14098 /* A span for reserved fixed locs. */
14099 interval.ordinary.second
14100 = MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0));
14101 interval.macro.first = interval.macro.second;
14102 dump (dumper::LOCATION)
14103 && dump ("Fixed span %u ordinary:[%u,%u) macro:[%u,%u)", spans->length (),
14104 interval.ordinary.first, interval.ordinary.second,
14105 interval.macro.first, interval.macro.second);
14106 spans->quick_push (interval);
14108 /* A span for command line & forced headers. */
14109 interval.ordinary.first = interval.ordinary.second;
14110 interval.macro.second = interval.macro.first;
14111 if (map)
14113 interval.ordinary.second = map->start_location;
14114 interval.macro.first = LINEMAPS_MACRO_LOWEST_LOCATION (lmaps);
14116 dump (dumper::LOCATION)
14117 && dump ("Pre span %u ordinary:[%u,%u) macro:[%u,%u)", spans->length (),
14118 interval.ordinary.first, interval.ordinary.second,
14119 interval.macro.first, interval.macro.second);
14120 spans->quick_push (interval);
14122 /* Start an interval for the main file. */
14123 interval.ordinary.first = interval.ordinary.second;
14124 interval.macro.second = interval.macro.first;
14125 dump (dumper::LOCATION)
14126 && dump ("Main span %u ordinary:[%u,*) macro:[*,%u)", spans->length (),
14127 interval.ordinary.first, interval.macro.second);
14128 spans->quick_push (interval);
14131 /* Reopen the span, if we want the about-to-be-inserted set of maps to
14132 be propagated in our own location table. I.e. we are the primary
14133 interface and we're importing a partition. */
14135 bool
14136 loc_spans::maybe_propagate (module_state *import, location_t hwm)
14138 bool opened = (module_interface_p () && !module_partition_p ()
14139 && import->is_partition ());
14140 if (opened)
14141 open (hwm);
14142 return opened;
14145 /* Open a new linemap interval. The just-created ordinary map is the
14146 first map of the interval. */
14148 void
14149 loc_spans::open (location_t hwm)
14151 span interval;
14152 interval.ordinary.first = interval.ordinary.second = hwm;
14153 interval.macro.first = interval.macro.second
14154 = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
14155 interval.ordinary_delta = interval.macro_delta = 0;
14156 dump (dumper::LOCATION)
14157 && dump ("Opening span %u ordinary:[%u,... macro:...,%u)",
14158 spans->length (), interval.ordinary.first,
14159 interval.macro.second);
14160 if (spans->length ())
14162 /* No overlapping! */
14163 auto &last = spans->last ();
14164 gcc_checking_assert (interval.ordinary.first >= last.ordinary.second);
14165 gcc_checking_assert (interval.macro.second <= last.macro.first);
14167 spans->safe_push (interval);
14170 /* Close out the current linemap interval. The last maps are within
14171 the interval. */
14173 void
14174 loc_spans::close ()
14176 span &interval = spans->last ();
14178 interval.ordinary.second
14179 = ((line_table->highest_location + (1 << line_table->default_range_bits))
14180 & ~((1u << line_table->default_range_bits) - 1));
14181 interval.macro.first = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
14182 dump (dumper::LOCATION)
14183 && dump ("Closing span %u ordinary:[%u,%u) macro:[%u,%u)",
14184 spans->length () - 1,
14185 interval.ordinary.first,interval.ordinary.second,
14186 interval.macro.first, interval.macro.second);
14189 /* Given an ordinary location LOC, return the lmap_interval it resides
14190 in. NULL if it is not in an interval. */
14192 const loc_spans::span *
14193 loc_spans::ordinary (location_t loc)
14195 unsigned len = spans->length ();
14196 unsigned pos = 0;
14197 while (len)
14199 unsigned half = len / 2;
14200 const span &probe = (*spans)[pos + half];
14201 if (loc < probe.ordinary.first)
14202 len = half;
14203 else if (loc < probe.ordinary.second)
14204 return &probe;
14205 else
14207 pos += half + 1;
14208 len = len - (half + 1);
14211 return NULL;
14214 /* Likewise, given a macro location LOC, return the lmap interval it
14215 resides in. */
14217 const loc_spans::span *
14218 loc_spans::macro (location_t loc)
14220 unsigned len = spans->length ();
14221 unsigned pos = 0;
14222 while (len)
14224 unsigned half = len / 2;
14225 const span &probe = (*spans)[pos + half];
14226 if (loc >= probe.macro.second)
14227 len = half;
14228 else if (loc >= probe.macro.first)
14229 return &probe;
14230 else
14232 pos += half + 1;
14233 len = len - (half + 1);
14236 return NULL;
14239 /* Return the ordinary location closest to FROM. */
14241 static location_t
14242 ordinary_loc_of (line_maps *lmaps, location_t from)
14244 while (!IS_ORDINARY_LOC (from))
14246 if (IS_ADHOC_LOC (from))
14247 from = get_location_from_adhoc_loc (lmaps, from);
14248 if (from >= LINEMAPS_MACRO_LOWEST_LOCATION (lmaps))
14250 /* Find the ordinary location nearest FROM. */
14251 const line_map *map = linemap_lookup (lmaps, from);
14252 const line_map_macro *mac_map = linemap_check_macro (map);
14253 from = mac_map->get_expansion_point_location ();
14256 return from;
14259 static module_state **
14260 get_module_slot (tree name, module_state *parent, bool partition, bool insert)
14262 module_state_hash::compare_type ct (name, uintptr_t (parent) | partition);
14263 hashval_t hv = module_state_hash::hash (ct);
14265 return modules_hash->find_slot_with_hash (ct, hv, insert ? INSERT : NO_INSERT);
14268 static module_state *
14269 get_primary (module_state *parent)
14271 while (parent->is_partition ())
14272 parent = parent->parent;
14274 if (!parent->name)
14275 // Implementation unit has null name
14276 parent = parent->parent;
14278 return parent;
14281 /* Find or create module NAME & PARENT in the hash table. */
14283 module_state *
14284 get_module (tree name, module_state *parent, bool partition)
14286 /* We might be given an empty NAME if preprocessing fails to handle
14287 a header-name token. */
14288 if (name && TREE_CODE (name) == STRING_CST
14289 && TREE_STRING_LENGTH (name) == 0)
14290 return nullptr;
14292 if (partition)
14294 if (!parent)
14295 parent = get_primary ((*modules)[0]);
14297 if (!parent->is_partition () && !parent->flatname)
14298 parent->set_flatname ();
14301 module_state **slot = get_module_slot (name, parent, partition, true);
14302 module_state *state = *slot;
14303 if (!state)
14305 state = (new (ggc_alloc<module_state> ())
14306 module_state (name, parent, partition));
14307 *slot = state;
14309 return state;
14312 /* Process string name PTR into a module_state. */
14314 static module_state *
14315 get_module (const char *ptr)
14317 /* On DOS based file systems, there is an ambiguity with A:B which can be
14318 interpreted as a module Module:Partition or Drive:PATH. Interpret strings
14319 which clearly starts as pathnames as header-names and everything else is
14320 treated as a (possibly malformed) named moduled. */
14321 if (IS_DIR_SEPARATOR (ptr[ptr[0] == '.']) // ./FOO or /FOO
14322 #if HAVE_DOS_BASED_FILE_SYSTEM
14323 || (HAS_DRIVE_SPEC (ptr) && IS_DIR_SEPARATOR (ptr[2])) // A:/FOO
14324 #endif
14325 || false)
14326 /* A header name. */
14327 return get_module (build_string (strlen (ptr), ptr));
14329 bool partition = false;
14330 module_state *mod = NULL;
14332 for (const char *probe = ptr;; probe++)
14333 if (!*probe || *probe == '.' || *probe == ':')
14335 if (probe == ptr)
14336 return NULL;
14338 mod = get_module (get_identifier_with_length (ptr, probe - ptr),
14339 mod, partition);
14340 ptr = probe;
14341 if (*ptr == ':')
14343 if (partition)
14344 return NULL;
14345 partition = true;
14348 if (!*ptr++)
14349 break;
14351 else if (!(ISALPHA (*probe) || *probe == '_'
14352 || (probe != ptr && ISDIGIT (*probe))))
14353 return NULL;
14355 return mod;
14358 /* Create a new mapper connecting to OPTION. */
14360 module_client *
14361 make_mapper (location_t loc, class mkdeps *deps)
14363 timevar_start (TV_MODULE_MAPPER);
14364 const char *option = module_mapper_name;
14365 if (!option)
14366 option = getenv ("CXX_MODULE_MAPPER");
14368 mapper = module_client::open_module_client
14369 (loc, option, deps, &set_cmi_repo,
14370 (save_decoded_options[0].opt_index == OPT_SPECIAL_program_name)
14371 && save_decoded_options[0].arg != progname
14372 ? save_decoded_options[0].arg : nullptr);
14374 timevar_stop (TV_MODULE_MAPPER);
14376 return mapper;
14379 static unsigned lazy_snum;
14381 static bool
14382 recursive_lazy (unsigned snum = ~0u)
14384 if (lazy_snum)
14386 error_at (input_location, "recursive lazy load");
14387 return true;
14390 lazy_snum = snum;
14391 return false;
14394 /* If THIS is the current purview, issue an import error and return false. */
14396 bool
14397 module_state::check_not_purview (location_t from)
14399 module_state *imp = (*modules)[0];
14400 if (imp && !imp->name)
14401 imp = imp->parent;
14402 if (imp == this)
14404 /* Cannot import the current module. */
14405 error_at (from, "cannot import module in its own purview");
14406 inform (loc, "module %qs declared here", get_flatname ());
14407 return false;
14409 return true;
14412 /* Module name substitutions. */
14413 static vec<module_state *,va_heap> substs;
14415 void
14416 module_state::mangle (bool include_partition)
14418 if (subst)
14419 mangle_module_substitution (subst);
14420 else
14422 if (parent)
14423 parent->mangle (include_partition);
14424 if (include_partition || !is_partition ())
14426 // Partitions are significant for global initializer
14427 // functions
14428 bool partition = is_partition () && !parent->is_partition ();
14429 subst = mangle_module_component (name, partition);
14430 substs.safe_push (this);
14435 void
14436 mangle_module (int mod, bool include_partition)
14438 module_state *imp = (*modules)[mod];
14440 gcc_checking_assert (!imp->is_header ());
14442 if (!imp->name)
14443 /* Set when importing the primary module interface. */
14444 imp = imp->parent;
14446 imp->mangle (include_partition);
14449 /* Clean up substitutions. */
14450 void
14451 mangle_module_fini ()
14453 while (substs.length ())
14454 substs.pop ()->subst = 0;
14457 /* Announce WHAT about the module. */
14459 void
14460 module_state::announce (const char *what) const
14462 if (noisy_p ())
14464 fprintf (stderr, " %s:%s", what, get_flatname ());
14465 fflush (stderr);
14469 /* A human-readable README section. The contents of this section to
14470 not contribute to the CRC, so the contents can change per
14471 compilation. That allows us to embed CWD, hostname, build time and
14472 what not. It is a STRTAB that may be extracted with:
14473 readelf -pgnu.c++.README $(module).gcm */
14475 void
14476 module_state::write_readme (elf_out *to, cpp_reader *reader, const char *dialect)
14478 bytes_out readme (to);
14480 readme.begin (false);
14482 readme.printf ("GNU C++ %s",
14483 is_header () ? "header unit"
14484 : !is_partition () ? "primary interface"
14485 : is_interface () ? "interface partition"
14486 : "internal partition");
14488 /* Compiler's version. */
14489 readme.printf ("compiler: %s", version_string);
14491 /* Module format version. */
14492 verstr_t string;
14493 version2string (MODULE_VERSION, string);
14494 readme.printf ("version: %s", string);
14496 /* Module information. */
14497 readme.printf ("module: %s", get_flatname ());
14498 readme.printf ("source: %s", main_input_filename);
14499 readme.printf ("dialect: %s", dialect);
14500 if (extensions)
14501 readme.printf ("extensions: %s",
14502 extensions & SE_OPENMP ? "-fopenmp" : "");
14504 /* The following fields could be expected to change between
14505 otherwise identical compilations. Consider a distributed build
14506 system. We should have a way of overriding that. */
14507 if (char *cwd = getcwd (NULL, 0))
14509 readme.printf ("cwd: %s", cwd);
14510 free (cwd);
14512 readme.printf ("repository: %s", cmi_repo ? cmi_repo : ".");
14513 #if NETWORKING
14515 char hostname[64];
14516 if (!gethostname (hostname, sizeof (hostname)))
14517 readme.printf ("host: %s", hostname);
14519 #endif
14521 /* This of course will change! */
14522 time_t stampy;
14523 auto kind = cpp_get_date (reader, &stampy);
14524 if (kind != CPP_time_kind::UNKNOWN)
14526 struct tm *time;
14528 time = gmtime (&stampy);
14529 readme.print_time ("build", time, "UTC");
14531 if (kind == CPP_time_kind::DYNAMIC)
14533 time = localtime (&stampy);
14534 readme.print_time ("local", time,
14535 #if defined (__USE_MISC) || defined (__USE_BSD) /* Is there a better way? */
14536 time->tm_zone
14537 #else
14539 #endif
14545 /* Its direct imports. */
14546 for (unsigned ix = 1; ix < modules->length (); ix++)
14548 module_state *state = (*modules)[ix];
14550 if (state->is_direct ())
14551 readme.printf ("%s: %s %s", state->exported_p ? "export" : "import",
14552 state->get_flatname (), state->filename);
14555 readme.end (to, to->name (MOD_SNAME_PFX ".README"), NULL);
14558 /* Sort environment var names in reverse order. */
14560 static int
14561 env_var_cmp (const void *a_, const void *b_)
14563 const unsigned char *a = *(const unsigned char *const *)a_;
14564 const unsigned char *b = *(const unsigned char *const *)b_;
14566 for (unsigned ix = 0; ; ix++)
14568 bool a_end = !a[ix] || a[ix] == '=';
14569 if (a[ix] == b[ix])
14571 if (a_end)
14572 break;
14574 else
14576 bool b_end = !b[ix] || b[ix] == '=';
14578 if (!a_end && !b_end)
14579 return a[ix] < b[ix] ? +1 : -1;
14580 if (a_end && b_end)
14581 break;
14582 return a_end ? +1 : -1;
14586 return 0;
14589 /* Write the environment. It is a STRTAB that may be extracted with:
14590 readelf -pgnu.c++.ENV $(module).gcm */
14592 void
14593 module_state::write_env (elf_out *to)
14595 vec<const char *> vars;
14596 vars.create (20);
14598 extern char **environ;
14599 while (const char *var = environ[vars.length ()])
14600 vars.safe_push (var);
14601 vars.qsort (env_var_cmp);
14603 bytes_out env (to);
14604 env.begin (false);
14605 while (vars.length ())
14606 env.printf ("%s", vars.pop ());
14607 env.end (to, to->name (MOD_SNAME_PFX ".ENV"), NULL);
14609 vars.release ();
14612 /* Write the direct or indirect imports.
14615 u:index
14616 s:name
14617 u32:crc
14618 s:filename (direct)
14619 u:exported (direct)
14620 } imports[N]
14623 void
14624 module_state::write_imports (bytes_out &sec, bool direct)
14626 unsigned count = 0;
14628 for (unsigned ix = 1; ix < modules->length (); ix++)
14630 module_state *imp = (*modules)[ix];
14632 if (imp->remap && imp->is_direct () == direct)
14633 count++;
14636 gcc_assert (!direct || count);
14638 sec.u (count);
14639 for (unsigned ix = 1; ix < modules->length (); ix++)
14641 module_state *imp = (*modules)[ix];
14643 if (imp->remap && imp->is_direct () == direct)
14645 dump () && dump ("Writing %simport:%u->%u %M (crc=%x)",
14646 !direct ? "indirect "
14647 : imp->exported_p ? "exported " : "",
14648 ix, imp->remap, imp, imp->crc);
14649 sec.u (imp->remap);
14650 sec.str (imp->get_flatname ());
14651 sec.u32 (imp->crc);
14652 if (direct)
14654 write_location (sec, imp->imported_from ());
14655 sec.str (imp->filename);
14656 int exportedness = 0;
14657 if (imp->exported_p)
14658 exportedness = +1;
14659 else if (!imp->is_purview_direct ())
14660 exportedness = -1;
14661 sec.i (exportedness);
14667 /* READER, LMAPS != NULL == direct imports,
14668 == NUL == indirect imports. */
14670 unsigned
14671 module_state::read_imports (bytes_in &sec, cpp_reader *reader, line_maps *lmaps)
14673 unsigned count = sec.u ();
14674 unsigned loaded = 0;
14676 while (count--)
14678 unsigned ix = sec.u ();
14679 if (ix >= slurp->remap->length () || !ix || (*slurp->remap)[ix])
14681 sec.set_overrun ();
14682 break;
14685 const char *name = sec.str (NULL);
14686 module_state *imp = get_module (name);
14687 unsigned crc = sec.u32 ();
14688 int exportedness = 0;
14690 /* If the import is a partition, it must be the same primary
14691 module as this TU. */
14692 if (imp && imp->is_partition () &&
14693 (!named_module_p ()
14694 || (get_primary ((*modules)[0]) != get_primary (imp))))
14695 imp = NULL;
14697 if (!imp)
14698 sec.set_overrun ();
14699 if (sec.get_overrun ())
14700 break;
14702 if (lmaps)
14704 /* A direct import, maybe load it. */
14705 location_t floc = read_location (sec);
14706 const char *fname = sec.str (NULL);
14707 exportedness = sec.i ();
14709 if (sec.get_overrun ())
14710 break;
14712 if (!imp->check_not_purview (loc))
14713 continue;
14715 if (imp->loadedness == ML_NONE)
14717 imp->loc = floc;
14718 imp->crc = crc;
14719 if (!imp->get_flatname ())
14720 imp->set_flatname ();
14722 unsigned n = dump.push (imp);
14724 if (!imp->filename && fname)
14725 imp->filename = xstrdup (fname);
14727 if (imp->is_partition ())
14728 dump () && dump ("Importing elided partition %M", imp);
14730 if (!imp->do_import (reader, false))
14731 imp = NULL;
14732 dump.pop (n);
14733 if (!imp)
14734 continue;
14737 if (is_partition ())
14739 if (!imp->is_direct ())
14740 imp->directness = MD_PARTITION_DIRECT;
14741 if (exportedness > 0)
14742 imp->exported_p = true;
14745 else
14747 /* An indirect import, find it, it should already be here. */
14748 if (imp->loadedness == ML_NONE)
14750 error_at (loc, "indirect import %qs is not already loaded", name);
14751 continue;
14755 if (imp->crc != crc)
14756 error_at (loc, "import %qs has CRC mismatch", imp->get_flatname ());
14758 (*slurp->remap)[ix] = (imp->mod << 1) | (lmaps != NULL);
14760 if (lmaps && exportedness >= 0)
14761 set_import (imp, bool (exportedness));
14762 dump () && dump ("Found %simport:%u %M->%u", !lmaps ? "indirect "
14763 : exportedness > 0 ? "exported "
14764 : exportedness < 0 ? "gmf" : "", ix, imp,
14765 imp->mod);
14766 loaded++;
14769 return loaded;
14772 /* Write the import table to MOD_SNAME_PFX.imp. */
14774 void
14775 module_state::write_imports (elf_out *to, unsigned *crc_ptr)
14777 dump () && dump ("Writing imports");
14778 dump.indent ();
14780 bytes_out sec (to);
14781 sec.begin ();
14783 write_imports (sec, true);
14784 write_imports (sec, false);
14786 sec.end (to, to->name (MOD_SNAME_PFX ".imp"), crc_ptr);
14787 dump.outdent ();
14790 bool
14791 module_state::read_imports (cpp_reader *reader, line_maps *lmaps)
14793 bytes_in sec;
14795 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".imp"))
14796 return false;
14798 dump () && dump ("Reading %u imports", slurp->remap->length () - 1);
14799 dump.indent ();
14801 /* Read the imports. */
14802 unsigned direct = read_imports (sec, reader, lmaps);
14803 unsigned indirect = read_imports (sec, NULL, NULL);
14804 if (direct + indirect + 1 != slurp->remap->length ())
14805 from ()->set_error (elf::E_BAD_IMPORT);
14807 dump.outdent ();
14808 if (!sec.end (from ()))
14809 return false;
14810 return true;
14813 /* We're the primary module interface, but have partitions. Document
14814 them so that non-partition module implementation units know which
14815 have already been loaded. */
14817 void
14818 module_state::write_partitions (elf_out *to, unsigned count, unsigned *crc_ptr)
14820 dump () && dump ("Writing %u elided partitions", count);
14821 dump.indent ();
14823 bytes_out sec (to);
14824 sec.begin ();
14826 for (unsigned ix = 1; ix != modules->length (); ix++)
14828 module_state *imp = (*modules)[ix];
14829 if (imp->is_partition ())
14831 dump () && dump ("Writing elided partition %M (crc=%x)",
14832 imp, imp->crc);
14833 sec.str (imp->get_flatname ());
14834 sec.u32 (imp->crc);
14835 write_location (sec, imp->is_direct ()
14836 ? imp->imported_from () : UNKNOWN_LOCATION);
14837 sec.str (imp->filename);
14841 sec.end (to, to->name (MOD_SNAME_PFX ".prt"), crc_ptr);
14842 dump.outdent ();
14845 bool
14846 module_state::read_partitions (unsigned count)
14848 bytes_in sec;
14849 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".prt"))
14850 return false;
14852 dump () && dump ("Reading %u elided partitions", count);
14853 dump.indent ();
14855 while (count--)
14857 const char *name = sec.str (NULL);
14858 unsigned crc = sec.u32 ();
14859 location_t floc = read_location (sec);
14860 const char *fname = sec.str (NULL);
14862 if (sec.get_overrun ())
14863 break;
14865 dump () && dump ("Reading elided partition %s (crc=%x)", name, crc);
14867 module_state *imp = get_module (name);
14868 if (!imp /* Partition should be ... */
14869 || !imp->is_partition () /* a partition ... */
14870 || imp->loadedness != ML_NONE /* that is not yet loaded ... */
14871 || get_primary (imp) != this) /* whose primary is this. */
14873 sec.set_overrun ();
14874 break;
14877 if (!imp->has_location ())
14878 imp->loc = floc;
14879 imp->crc = crc;
14880 if (!imp->filename && fname[0])
14881 imp->filename = xstrdup (fname);
14884 dump.outdent ();
14885 if (!sec.end (from ()))
14886 return false;
14887 return true;
14890 /* Data for config reading and writing. */
14891 struct module_state_config {
14892 const char *dialect_str;
14893 unsigned num_imports;
14894 unsigned num_partitions;
14895 unsigned num_entities;
14896 unsigned ordinary_locs;
14897 unsigned macro_locs;
14898 unsigned loc_range_bits;
14899 unsigned active_init;
14901 public:
14902 module_state_config ()
14903 :dialect_str (get_dialect ()),
14904 num_imports (0), num_partitions (0), num_entities (0),
14905 ordinary_locs (0), macro_locs (0), loc_range_bits (0),
14906 active_init (0)
14910 static void release ()
14912 XDELETEVEC (dialect);
14913 dialect = NULL;
14916 private:
14917 static const char *get_dialect ();
14918 static char *dialect;
14921 char *module_state_config::dialect;
14923 /* Generate a string of the significant compilation options.
14924 Generally assume the user knows what they're doing, in the same way
14925 that object files can be mixed. */
14927 const char *
14928 module_state_config::get_dialect ()
14930 if (!dialect)
14931 dialect = concat (get_cxx_dialect_name (cxx_dialect),
14932 /* C++ implies these, only show if disabled. */
14933 flag_exceptions ? "" : "/no-exceptions",
14934 flag_rtti ? "" : "/no-rtti",
14935 flag_new_inheriting_ctors ? "" : "/old-inheriting-ctors",
14936 /* C++ 20 implies concepts. */
14937 cxx_dialect < cxx20 && flag_concepts ? "/concepts" : "",
14938 flag_coroutines ? "/coroutines" : "",
14939 flag_module_implicit_inline ? "/implicit-inline" : "",
14940 flag_contracts ? "/contracts" : "",
14941 NULL);
14943 return dialect;
14946 /* Contents of a cluster. */
14947 enum cluster_tag {
14948 ct_decl, /* A decl. */
14949 ct_defn, /* A definition. */
14950 ct_bind, /* A binding. */
14951 ct_hwm
14954 /* Binding modifiers. */
14955 enum ct_bind_flags
14957 cbf_export = 0x1, /* An exported decl. */
14958 cbf_hidden = 0x2, /* A hidden (friend) decl. */
14959 cbf_using = 0x4, /* A using decl. */
14960 cbf_wrapped = 0x8, /* ... that is wrapped. */
14963 /* DEP belongs to a different cluster, seed it to prevent
14964 unfortunately timed duplicate import. */
14965 // FIXME: QOI For inter-cluster references we could just only pick
14966 // one entity from an earlier cluster. Even better track
14967 // dependencies between earlier clusters
14969 void
14970 module_state::intercluster_seed (trees_out &sec, unsigned index_hwm, depset *dep)
14972 if (dep->is_import ()
14973 || dep->cluster < index_hwm)
14975 tree ent = dep->get_entity ();
14976 if (!TREE_VISITED (ent))
14978 sec.tree_node (ent);
14979 dump (dumper::CLUSTER)
14980 && dump ("Seeded %s %N",
14981 dep->is_import () ? "import" : "intercluster", ent);
14986 /* Write the cluster of depsets in SCC[0-SIZE).
14987 dep->section -> section number
14988 dep->cluster -> entity number
14991 unsigned
14992 module_state::write_cluster (elf_out *to, depset *scc[], unsigned size,
14993 depset::hash &table, unsigned *counts,
14994 unsigned *crc_ptr)
14996 dump () && dump ("Writing section:%u %u depsets", table.section, size);
14997 dump.indent ();
14999 trees_out sec (to, this, table, table.section);
15000 sec.begin ();
15001 unsigned index_lwm = counts[MSC_entities];
15003 /* Determine entity numbers, mark for writing. */
15004 dump (dumper::CLUSTER) && dump ("Cluster members:") && (dump.indent (), true);
15005 for (unsigned ix = 0; ix != size; ix++)
15007 depset *b = scc[ix];
15009 switch (b->get_entity_kind ())
15011 default:
15012 gcc_unreachable ();
15014 case depset::EK_BINDING:
15016 dump (dumper::CLUSTER)
15017 && dump ("[%u]=%s %P", ix, b->entity_kind_name (),
15018 b->get_entity (), b->get_name ());
15019 depset *ns_dep = b->deps[0];
15020 gcc_checking_assert (ns_dep->get_entity_kind ()
15021 == depset::EK_NAMESPACE
15022 && ns_dep->get_entity () == b->get_entity ());
15023 for (unsigned jx = b->deps.length (); --jx;)
15025 depset *dep = b->deps[jx];
15026 // We could be declaring something that is also a
15027 // (merged) import
15028 gcc_checking_assert (dep->is_import ()
15029 || TREE_VISITED (dep->get_entity ())
15030 || (dep->get_entity_kind ()
15031 == depset::EK_USING));
15034 break;
15036 case depset::EK_DECL:
15037 case depset::EK_SPECIALIZATION:
15038 case depset::EK_PARTIAL:
15039 b->cluster = counts[MSC_entities]++;
15040 sec.mark_declaration (b->get_entity (), b->has_defn ());
15041 /* FALLTHROUGH */
15043 case depset::EK_USING:
15044 gcc_checking_assert (!b->is_import ()
15045 && !b->is_unreached ());
15046 dump (dumper::CLUSTER)
15047 && dump ("[%u]=%s %s %N", ix, b->entity_kind_name (),
15048 b->has_defn () ? "definition" : "declaration",
15049 b->get_entity ());
15050 break;
15053 dump (dumper::CLUSTER) && (dump.outdent (), true);
15055 /* Ensure every out-of-cluster decl is referenced before we start
15056 streaming. We must do both imports *and* earlier clusters,
15057 because the latter could reach into the former and cause a
15058 duplicate loop. */
15059 sec.set_importing (+1);
15060 for (unsigned ix = 0; ix != size; ix++)
15062 depset *b = scc[ix];
15063 for (unsigned jx = b->is_special (); jx != b->deps.length (); jx++)
15065 depset *dep = b->deps[jx];
15067 if (dep->is_binding ())
15069 for (unsigned ix = dep->deps.length (); --ix;)
15071 depset *bind = dep->deps[ix];
15072 if (bind->get_entity_kind () == depset::EK_USING)
15073 bind = bind->deps[1];
15075 intercluster_seed (sec, index_lwm, bind);
15077 /* Also check the namespace itself. */
15078 dep = dep->deps[0];
15081 intercluster_seed (sec, index_lwm, dep);
15084 sec.tree_node (NULL_TREE);
15085 /* We're done importing now. */
15086 sec.set_importing (-1);
15088 /* Write non-definitions. */
15089 for (unsigned ix = 0; ix != size; ix++)
15091 depset *b = scc[ix];
15092 tree decl = b->get_entity ();
15093 switch (b->get_entity_kind ())
15095 default:
15096 gcc_unreachable ();
15097 break;
15099 case depset::EK_BINDING:
15101 gcc_assert (TREE_CODE (decl) == NAMESPACE_DECL);
15102 dump () && dump ("Depset:%u binding %C:%P", ix, TREE_CODE (decl),
15103 decl, b->get_name ());
15104 sec.u (ct_bind);
15105 sec.tree_node (decl);
15106 sec.tree_node (b->get_name ());
15108 /* Write in reverse order, so reading will see the exports
15109 first, thus building the overload chain will be
15110 optimized. */
15111 for (unsigned jx = b->deps.length (); --jx;)
15113 depset *dep = b->deps[jx];
15114 tree bound = dep->get_entity ();
15115 unsigned flags = 0;
15116 if (dep->get_entity_kind () == depset::EK_USING)
15118 tree ovl = bound;
15119 bound = OVL_FUNCTION (bound);
15120 if (!(TREE_CODE (bound) == CONST_DECL
15121 && UNSCOPED_ENUM_P (TREE_TYPE (bound))
15122 && decl == TYPE_NAME (TREE_TYPE (bound))))
15124 /* An unscope enumerator in its enumeration's
15125 scope is not a using. */
15126 flags |= cbf_using;
15127 if (OVL_USING_P (ovl))
15128 flags |= cbf_wrapped;
15130 if (OVL_EXPORT_P (ovl))
15131 flags |= cbf_export;
15133 else
15135 /* An implicit typedef must be at one. */
15136 gcc_assert (!DECL_IMPLICIT_TYPEDEF_P (bound) || jx == 1);
15137 if (dep->is_hidden ())
15138 flags |= cbf_hidden;
15139 else if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (bound)))
15140 flags |= cbf_export;
15143 gcc_checking_assert (DECL_P (bound));
15145 sec.i (flags);
15146 sec.tree_node (bound);
15149 /* Terminate the list. */
15150 sec.i (-1);
15152 break;
15154 case depset::EK_USING:
15155 dump () && dump ("Depset:%u %s %C:%N", ix, b->entity_kind_name (),
15156 TREE_CODE (decl), decl);
15157 break;
15159 case depset::EK_SPECIALIZATION:
15160 case depset::EK_PARTIAL:
15161 case depset::EK_DECL:
15162 dump () && dump ("Depset:%u %s entity:%u %C:%N", ix,
15163 b->entity_kind_name (), b->cluster,
15164 TREE_CODE (decl), decl);
15166 sec.u (ct_decl);
15167 sec.tree_node (decl);
15169 dump () && dump ("Wrote declaration entity:%u %C:%N",
15170 b->cluster, TREE_CODE (decl), decl);
15171 break;
15175 depset *namer = NULL;
15177 /* Write out definitions */
15178 for (unsigned ix = 0; ix != size; ix++)
15180 depset *b = scc[ix];
15181 tree decl = b->get_entity ();
15182 switch (b->get_entity_kind ())
15184 default:
15185 break;
15187 case depset::EK_SPECIALIZATION:
15188 case depset::EK_PARTIAL:
15189 case depset::EK_DECL:
15190 if (!namer)
15191 namer = b;
15193 if (b->has_defn ())
15195 sec.u (ct_defn);
15196 sec.tree_node (decl);
15197 dump () && dump ("Writing definition %N", decl);
15198 sec.write_definition (decl);
15200 if (!namer->has_defn ())
15201 namer = b;
15203 break;
15207 /* We don't find the section by name. Use depset's decl's name for
15208 human friendliness. */
15209 unsigned name = 0;
15210 tree naming_decl = NULL_TREE;
15211 if (namer)
15213 naming_decl = namer->get_entity ();
15214 if (namer->get_entity_kind () == depset::EK_USING)
15215 /* This unfortunately names the section from the target of the
15216 using decl. But the name is only a guide, so Do Not Care. */
15217 naming_decl = OVL_FUNCTION (naming_decl);
15218 if (DECL_IMPLICIT_TYPEDEF_P (naming_decl))
15219 /* Lose any anonymousness. */
15220 naming_decl = TYPE_NAME (TREE_TYPE (naming_decl));
15221 name = to->qualified_name (naming_decl, namer->has_defn ());
15224 unsigned bytes = sec.pos;
15225 unsigned snum = sec.end (to, name, crc_ptr);
15227 for (unsigned ix = size; ix--;)
15228 gcc_checking_assert (scc[ix]->section == snum);
15230 dump.outdent ();
15231 dump () && dump ("Wrote section:%u named-by:%N", table.section, naming_decl);
15233 return bytes;
15236 /* Read a cluster from section SNUM. */
15238 bool
15239 module_state::read_cluster (unsigned snum)
15241 trees_in sec (this);
15243 if (!sec.begin (loc, from (), snum))
15244 return false;
15246 dump () && dump ("Reading section:%u", snum);
15247 dump.indent ();
15249 /* We care about structural equality. */
15250 comparing_dependent_aliases++;
15252 /* First seed the imports. */
15253 while (tree import = sec.tree_node ())
15254 dump (dumper::CLUSTER) && dump ("Seeded import %N", import);
15256 while (!sec.get_overrun () && sec.more_p ())
15258 unsigned ct = sec.u ();
15259 switch (ct)
15261 default:
15262 sec.set_overrun ();
15263 break;
15265 case ct_bind:
15266 /* A set of namespace bindings. */
15268 tree ns = sec.tree_node ();
15269 tree name = sec.tree_node ();
15270 tree decls = NULL_TREE;
15271 tree visible = NULL_TREE;
15272 tree type = NULL_TREE;
15273 bool dedup = false;
15275 /* We rely on the bindings being in the reverse order of
15276 the resulting overload set. */
15277 for (;;)
15279 int flags = sec.i ();
15280 if (flags < 0)
15281 break;
15283 if ((flags & cbf_hidden)
15284 && (flags & (cbf_using | cbf_export)))
15285 sec.set_overrun ();
15287 tree decl = sec.tree_node ();
15288 if (sec.get_overrun ())
15289 break;
15291 if (decls && TREE_CODE (decl) == TYPE_DECL)
15293 /* Stat hack. */
15294 if (type || !DECL_IMPLICIT_TYPEDEF_P (decl))
15295 sec.set_overrun ();
15296 type = decl;
15298 else
15300 if (decls
15301 || (flags & (cbf_hidden | cbf_wrapped))
15302 || DECL_FUNCTION_TEMPLATE_P (decl))
15304 decls = ovl_make (decl, decls);
15305 if (flags & cbf_using)
15307 dedup = true;
15308 OVL_USING_P (decls) = true;
15309 if (flags & cbf_export)
15310 OVL_EXPORT_P (decls) = true;
15313 if (flags & cbf_hidden)
15314 OVL_HIDDEN_P (decls) = true;
15315 else if (dedup)
15316 OVL_DEDUP_P (decls) = true;
15318 else
15319 decls = decl;
15321 if (flags & cbf_export
15322 || (!(flags & cbf_hidden)
15323 && (is_module () || is_partition ())))
15324 visible = decls;
15328 if (!decls)
15329 sec.set_overrun ();
15331 if (sec.get_overrun ())
15332 break; /* Bail. */
15334 dump () && dump ("Binding of %P", ns, name);
15335 if (!set_module_binding (ns, name, mod,
15336 is_header () ? -1
15337 : is_module () || is_partition () ? 1
15338 : 0,
15339 decls, type, visible))
15340 sec.set_overrun ();
15342 break;
15344 case ct_decl:
15345 /* A decl. */
15347 tree decl = sec.tree_node ();
15348 dump () && dump ("Read declaration of %N", decl);
15350 break;
15352 case ct_defn:
15354 tree decl = sec.tree_node ();
15355 dump () && dump ("Reading definition of %N", decl);
15356 sec.read_definition (decl);
15358 break;
15362 /* When lazy loading is in effect, we can be in the middle of
15363 parsing or instantiating a function. Save it away.
15364 push_function_context does too much work. */
15365 tree old_cfd = current_function_decl;
15366 struct function *old_cfun = cfun;
15367 for (const post_process_data& pdata : sec.post_process ())
15369 tree decl = pdata.decl;
15371 bool abstract = false;
15372 if (TREE_CODE (decl) == TEMPLATE_DECL)
15374 abstract = true;
15375 decl = DECL_TEMPLATE_RESULT (decl);
15378 current_function_decl = decl;
15379 allocate_struct_function (decl, abstract);
15380 cfun->language = ggc_cleared_alloc<language_function> ();
15381 cfun->language->base.x_stmt_tree.stmts_are_full_exprs_p = 1;
15382 cfun->function_start_locus = pdata.start_locus;
15383 cfun->function_end_locus = pdata.end_locus;
15385 if (abstract)
15387 else if (DECL_ABSTRACT_P (decl))
15388 vec_safe_push (post_load_decls, decl);
15389 else
15391 bool aggr = aggregate_value_p (DECL_RESULT (decl), decl);
15392 #ifdef PCC_STATIC_STRUCT_RETURN
15393 cfun->returns_pcc_struct = aggr;
15394 #endif
15395 cfun->returns_struct = aggr;
15397 if (DECL_COMDAT (decl))
15398 // FIXME: Comdat grouping?
15399 comdat_linkage (decl);
15400 note_vague_linkage_fn (decl);
15401 cgraph_node::finalize_function (decl, true);
15405 /* Look, function.cc's interface to cfun does too much for us, we
15406 just need to restore the old value. I do not want to go
15407 redesigning that API right now. */
15408 #undef cfun
15409 cfun = old_cfun;
15410 current_function_decl = old_cfd;
15411 comparing_dependent_aliases--;
15413 dump.outdent ();
15414 dump () && dump ("Read section:%u", snum);
15416 loaded_clusters++;
15418 if (!sec.end (from ()))
15419 return false;
15421 return true;
15424 void
15425 module_state::write_namespace (bytes_out &sec, depset *dep)
15427 unsigned ns_num = dep->cluster;
15428 unsigned ns_import = 0;
15430 if (dep->is_import ())
15431 ns_import = dep->section;
15432 else if (dep->get_entity () != global_namespace)
15433 ns_num++;
15435 sec.u (ns_import);
15436 sec.u (ns_num);
15439 tree
15440 module_state::read_namespace (bytes_in &sec)
15442 unsigned ns_import = sec.u ();
15443 unsigned ns_num = sec.u ();
15444 tree ns = NULL_TREE;
15446 if (ns_import || ns_num)
15448 if (!ns_import)
15449 ns_num--;
15451 if (unsigned origin = slurp->remap_module (ns_import))
15453 module_state *from = (*modules)[origin];
15454 if (ns_num < from->entity_num)
15456 binding_slot &slot = (*entity_ary)[from->entity_lwm + ns_num];
15458 if (!slot.is_lazy ())
15459 ns = slot;
15462 else
15463 sec.set_overrun ();
15465 else
15466 ns = global_namespace;
15468 return ns;
15471 /* SPACES is a sorted vector of namespaces. Write out the namespaces
15472 to MOD_SNAME_PFX.nms section. */
15474 void
15475 module_state::write_namespaces (elf_out *to, vec<depset *> spaces,
15476 unsigned num, unsigned *crc_p)
15478 dump () && dump ("Writing namespaces");
15479 dump.indent ();
15481 bytes_out sec (to);
15482 sec.begin ();
15484 for (unsigned ix = 0; ix != num; ix++)
15486 depset *b = spaces[ix];
15487 tree ns = b->get_entity ();
15489 gcc_checking_assert (TREE_CODE (ns) == NAMESPACE_DECL);
15490 /* P1815 may have something to say about this. */
15491 gcc_checking_assert (TREE_PUBLIC (ns));
15493 unsigned flags = 0;
15494 if (TREE_PUBLIC (ns))
15495 flags |= 1;
15496 if (DECL_NAMESPACE_INLINE_P (ns))
15497 flags |= 2;
15498 if (DECL_MODULE_PURVIEW_P (ns))
15499 flags |= 4;
15500 if (DECL_MODULE_EXPORT_P (ns))
15501 flags |= 8;
15503 dump () && dump ("Writing namespace:%u %N%s%s%s%s",
15504 b->cluster, ns,
15505 flags & 1 ? ", public" : "",
15506 flags & 2 ? ", inline" : "",
15507 flags & 4 ? ", purview" : "",
15508 flags & 8 ? ", export" : "");
15509 sec.u (b->cluster);
15510 sec.u (to->name (DECL_NAME (ns)));
15511 write_namespace (sec, b->deps[0]);
15513 sec.u (flags);
15514 write_location (sec, DECL_SOURCE_LOCATION (ns));
15516 if (DECL_NAMESPACE_INLINE_P (ns))
15518 if (tree attr = lookup_attribute ("abi_tag", DECL_ATTRIBUTES (ns)))
15520 tree tags = TREE_VALUE (attr);
15521 sec.u (list_length (tags));
15522 for (tree tag = tags; tag; tag = TREE_CHAIN (tag))
15523 sec.str (TREE_STRING_POINTER (TREE_VALUE (tag)));
15525 else
15526 sec.u (0);
15530 sec.end (to, to->name (MOD_SNAME_PFX ".nms"), crc_p);
15531 dump.outdent ();
15534 /* Read the namespace hierarchy from MOD_SNAME_PFX.namespace. Fill in
15535 SPACES from that data. */
15537 bool
15538 module_state::read_namespaces (unsigned num)
15540 bytes_in sec;
15542 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".nms"))
15543 return false;
15545 dump () && dump ("Reading namespaces");
15546 dump.indent ();
15548 for (unsigned ix = 0; ix != num; ix++)
15550 unsigned entity_index = sec.u ();
15551 unsigned name = sec.u ();
15553 tree parent = read_namespace (sec);
15555 /* See comment in write_namespace about why not bits. */
15556 unsigned flags = sec.u ();
15557 location_t src_loc = read_location (sec);
15558 unsigned tags_count = (flags & 2) ? sec.u () : 0;
15560 if (entity_index >= entity_num
15561 || !parent
15562 || (flags & 0xc) == 0x8)
15563 sec.set_overrun ();
15565 tree tags = NULL_TREE;
15566 while (tags_count--)
15568 size_t len;
15569 const char *str = sec.str (&len);
15570 tags = tree_cons (NULL_TREE, build_string (len + 1, str), tags);
15571 tags = nreverse (tags);
15574 if (sec.get_overrun ())
15575 break;
15577 tree id = name ? get_identifier (from ()->name (name)) : NULL_TREE;
15579 dump () && dump ("Read namespace:%u %P%s%s%s%s",
15580 entity_index, parent, id,
15581 flags & 1 ? ", public" : "",
15582 flags & 2 ? ", inline" : "",
15583 flags & 4 ? ", purview" : "",
15584 flags & 8 ? ", export" : "");
15585 bool visible_p = ((flags & 8)
15586 || ((flags & 1)
15587 && (flags & 4)
15588 && (is_partition () || is_module ())));
15589 tree inner = add_imported_namespace (parent, id, src_loc, mod,
15590 bool (flags & 2), visible_p);
15591 if (!inner)
15593 sec.set_overrun ();
15594 break;
15597 if (is_partition ())
15599 if (flags & 4)
15600 DECL_MODULE_PURVIEW_P (inner) = true;
15601 if (flags & 8)
15602 DECL_MODULE_EXPORT_P (inner) = true;
15605 if (tags)
15606 DECL_ATTRIBUTES (inner)
15607 = tree_cons (get_identifier ("abi_tag"), tags, DECL_ATTRIBUTES (inner));
15609 /* Install the namespace. */
15610 (*entity_ary)[entity_lwm + entity_index] = inner;
15611 if (DECL_MODULE_IMPORT_P (inner))
15613 bool existed;
15614 unsigned *slot = &entity_map->get_or_insert
15615 (DECL_UID (inner), &existed);
15616 if (existed)
15617 /* If it existed, it should match. */
15618 gcc_checking_assert (inner == (*entity_ary)[*slot]);
15619 else
15620 *slot = entity_lwm + entity_index;
15623 dump.outdent ();
15624 if (!sec.end (from ()))
15625 return false;
15626 return true;
15629 /* Write the binding TABLE to MOD_SNAME_PFX.bnd */
15631 unsigned
15632 module_state::write_bindings (elf_out *to, vec<depset *> sccs, unsigned *crc_p)
15634 dump () && dump ("Writing binding table");
15635 dump.indent ();
15637 unsigned num = 0;
15638 bytes_out sec (to);
15639 sec.begin ();
15641 for (unsigned ix = 0; ix != sccs.length (); ix++)
15643 depset *b = sccs[ix];
15644 if (b->is_binding ())
15646 tree ns = b->get_entity ();
15647 dump () && dump ("Bindings %P section:%u", ns, b->get_name (),
15648 b->section);
15649 sec.u (to->name (b->get_name ()));
15650 write_namespace (sec, b->deps[0]);
15651 sec.u (b->section);
15652 num++;
15656 sec.end (to, to->name (MOD_SNAME_PFX ".bnd"), crc_p);
15657 dump.outdent ();
15659 return num;
15662 /* Read the binding table from MOD_SNAME_PFX.bind. */
15664 bool
15665 module_state::read_bindings (unsigned num, unsigned lwm, unsigned hwm)
15667 bytes_in sec;
15669 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".bnd"))
15670 return false;
15672 dump () && dump ("Reading binding table");
15673 dump.indent ();
15674 for (; !sec.get_overrun () && num--;)
15676 const char *name = from ()->name (sec.u ());
15677 tree ns = read_namespace (sec);
15678 unsigned snum = sec.u ();
15680 if (!ns || !name || (snum - lwm) >= (hwm - lwm))
15681 sec.set_overrun ();
15682 if (!sec.get_overrun ())
15684 tree id = get_identifier (name);
15685 dump () && dump ("Bindings %P section:%u", ns, id, snum);
15686 if (mod && !import_module_binding (ns, id, mod, snum))
15687 break;
15691 dump.outdent ();
15692 if (!sec.end (from ()))
15693 return false;
15694 return true;
15697 /* Write the entity table to MOD_SNAME_PFX.ent
15699 Each entry is a section number. */
15701 void
15702 module_state::write_entities (elf_out *to, vec<depset *> depsets,
15703 unsigned count, unsigned *crc_p)
15705 dump () && dump ("Writing entities");
15706 dump.indent ();
15708 bytes_out sec (to);
15709 sec.begin ();
15711 unsigned current = 0;
15712 for (unsigned ix = 0; ix < depsets.length (); ix++)
15714 depset *d = depsets[ix];
15716 switch (d->get_entity_kind ())
15718 default:
15719 break;
15721 case depset::EK_NAMESPACE:
15722 if (!d->is_import () && d->get_entity () != global_namespace)
15724 gcc_checking_assert (d->cluster == current);
15725 current++;
15726 sec.u (0);
15728 break;
15730 case depset::EK_DECL:
15731 case depset::EK_SPECIALIZATION:
15732 case depset::EK_PARTIAL:
15733 gcc_checking_assert (!d->is_unreached ()
15734 && !d->is_import ()
15735 && d->cluster == current
15736 && d->section);
15737 current++;
15738 sec.u (d->section);
15739 break;
15742 gcc_assert (count == current);
15743 sec.end (to, to->name (MOD_SNAME_PFX ".ent"), crc_p);
15744 dump.outdent ();
15747 bool
15748 module_state::read_entities (unsigned count, unsigned lwm, unsigned hwm)
15750 trees_in sec (this);
15752 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".ent"))
15753 return false;
15755 dump () && dump ("Reading entities");
15756 dump.indent ();
15758 for (binding_slot *slot = entity_ary->begin () + entity_lwm; count--; slot++)
15760 unsigned snum = sec.u ();
15761 if (snum && (snum - lwm) >= (hwm - lwm))
15762 sec.set_overrun ();
15763 if (sec.get_overrun ())
15764 break;
15766 if (snum)
15767 slot->set_lazy (snum << 2);
15770 dump.outdent ();
15771 if (!sec.end (from ()))
15772 return false;
15773 return true;
15776 /* Write the pending table to MOD_SNAME_PFX.pnd
15778 The pending table holds information about clusters that need to be
15779 loaded because they contain information about something that is not
15780 found by namespace-scope lookup.
15782 The three cases are:
15784 (a) Template (maybe-partial) specializations that we have
15785 instantiated or defined. When an importer needs to instantiate
15786 that template, they /must have/ the partial, explicit & extern
15787 specializations available. If they have the other specializations
15788 available, they'll have less work to do. Thus, when we're about to
15789 instantiate FOO, we have to be able to ask 'are there any
15790 specialization of FOO in our imports?'.
15792 (b) (Maybe-implicit) member functions definitions. A class could
15793 be defined in one header, and an inline member defined in a
15794 different header (this occurs in the STL). Similarly, like the
15795 specialization case, an implicit member function could have been
15796 'instantiated' in one module, and it'd be nice to not have to
15797 reinstantiate it in another.
15799 (c) A member classes completed elsewhere. A member class could be
15800 declared in one header and defined in another. We need to know to
15801 load the class definition before looking in it. This turns out to
15802 be a specific case of #b, so we can treat these the same. But it
15803 does highlight an issue -- there could be an intermediate import
15804 between the outermost containing namespace-scope class and the
15805 innermost being-defined member class. This is actually possible
15806 with all of these cases, so be aware -- we're not just talking of
15807 one level of import to get to the innermost namespace.
15809 This gets complicated fast, it took me multiple attempts to even
15810 get something remotely working. Partially because I focussed on
15811 optimizing what I think turns out to be a smaller problem, given
15812 the known need to do the more general case *anyway*. I document
15813 the smaller problem, because it does appear to be the natural way
15814 to do it. It's trap!
15816 **** THE TRAP
15818 Let's refer to the primary template or the containing class as the
15819 KEY. And the specialization or member as the PENDING-ENTITY. (To
15820 avoid having to say those mouthfuls all the time.)
15822 In either case, we have an entity and we need some way of mapping
15823 that to a set of entities that need to be loaded before we can
15824 proceed with whatever processing of the entity we were going to do.
15826 We need to link the key to the pending-entity in some way. Given a
15827 key, tell me the pending-entities I need to have loaded. However
15828 we tie the key to the pending-entity must not rely on the key being
15829 loaded -- that'd defeat the lazy loading scheme.
15831 As the key will be an import in we know its entity number (either
15832 because we imported it, or we're writing it out too). Thus we can
15833 generate a map of key-indices to pending-entities. The
15834 pending-entity indices will be into our span of the entity table,
15835 and thus allow them to be lazily loaded. The key index will be
15836 into another slot of the entity table. Notice that this checking
15837 could be expensive, we don't want to iterate over a bunch of
15838 pending-entity indices (across multiple imports), every time we're
15839 about do to the thing with the key. We need to quickly determine
15840 'definitely nothing needed'.
15842 That's almost good enough, except that key indices are not unique
15843 in a couple of cases :( Specifically the Global Module or a module
15844 partition can result in multiple modules assigning an entity index
15845 for the key. The decl-merging on loading will detect that so we
15846 only have one Key loaded, and in the entity hash it'll indicate the
15847 entity index of first load. Which might be different to how we
15848 know it. Notice this is restricted to GM entities or this-module
15849 entities. Foreign imports cannot have this.
15851 We can simply resolve this in the direction of how this module
15852 referred to the key to how the importer knows it. Look in the
15853 entity table slot that we nominate, maybe lazy load it, and then
15854 lookup the resultant entity in the entity hash to learn how the
15855 importer knows it.
15857 But we need to go in the other direction :( Given the key, find all
15858 the index-aliases of that key. We can partially solve that by
15859 adding an alias hash table. Whenever we load a merged decl, add or
15860 augment a mapping from the entity (or its entity-index) to the
15861 newly-discovered index. Then when we look for pending entities of
15862 a key, we also iterate over this aliases this mapping provides.
15864 But that requires the alias to be loaded. And that's not
15865 necessarily true.
15867 *** THE SIMPLER WAY
15869 The remaining fixed thing we have is the innermost namespace
15870 containing the ultimate namespace-scope container of the key and
15871 the name of that container (which might be the key itself). I.e. a
15872 namespace-decl/identifier/module tuple. Let's call this the
15873 top-key. We'll discover that the module is not important here,
15874 because of cross-module possibilities mentioned in case #c above.
15875 We can't markup namespace-binding slots. The best we can do is
15876 mark the binding vector with 'there's something here', and have
15877 another map from namespace/identifier pairs to a vector of pending
15878 entity indices.
15880 Maintain a pending-entity map. This is keyed by top-key, and
15881 maps to a vector of pending-entity indices. On the binding vector
15882 have flags saying whether the pending-name-entity map has contents.
15883 (We might want to further extend the key to be GM-vs-Partition and
15884 specialization-vs-member, but let's not get ahead of ourselves.)
15886 For every key-like entity, find the outermost namespace-scope
15887 name. Use that to lookup in the pending-entity map and then make
15888 sure the specified entities are loaded.
15890 An optimization might be to have a flag in each key-entity saying
15891 that its top key might be in the entity table. It's not clear to
15892 me how to set that flag cheaply -- cheaper than just looking.
15894 FIXME: It'd be nice to have a bit in decls to tell us whether to
15895 even try this. We can have a 'already done' flag, that we set when
15896 we've done KLASS's lazy pendings. When we import a module that
15897 registers pendings on the same top-key as KLASS we need to clear
15898 the flag. A recursive walk of the top-key clearing the bit will
15899 suffice. Plus we only need to recurse on classes that have the bit
15900 set. (That means we need to set the bit on parents of KLASS here,
15901 don't forget.) However, first: correctness, second: efficiency. */
15903 unsigned
15904 module_state::write_pendings (elf_out *to, vec<depset *> depsets,
15905 depset::hash &table, unsigned *crc_p)
15907 dump () && dump ("Writing pending-entities");
15908 dump.indent ();
15910 trees_out sec (to, this, table);
15911 sec.begin ();
15913 unsigned count = 0;
15914 tree cache_ns = NULL_TREE;
15915 tree cache_id = NULL_TREE;
15916 unsigned cache_section = ~0;
15917 for (unsigned ix = 0; ix < depsets.length (); ix++)
15919 depset *d = depsets[ix];
15921 if (d->is_binding ())
15922 continue;
15924 if (d->is_import ())
15925 continue;
15927 if (!(d->get_entity_kind () == depset::EK_SPECIALIZATION
15928 || d->get_entity_kind () == depset::EK_PARTIAL
15929 || (d->get_entity_kind () == depset::EK_DECL && d->is_member ())))
15930 continue;
15932 tree key_decl = nullptr;
15933 tree key_ns = find_pending_key (d->get_entity (), &key_decl);
15934 tree key_name = DECL_NAME (key_decl);
15936 if (IDENTIFIER_ANON_P (key_name))
15938 gcc_checking_assert (IDENTIFIER_LAMBDA_P (key_name));
15939 if (tree attached = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (key_decl)))
15940 key_name = DECL_NAME (attached);
15941 else
15943 /* There's nothing to attach it to. Must
15944 always reinstantiate. */
15945 dump ()
15946 && dump ("Unattached lambda %N[%u] section:%u",
15947 d->get_entity_kind () == depset::EK_DECL
15948 ? "Member" : "Specialization", d->get_entity (),
15949 d->cluster, d->section);
15950 continue;
15954 char const *also = "";
15955 if (d->section == cache_section
15956 && key_ns == cache_ns
15957 && key_name == cache_id)
15958 /* Same section & key as previous, no need to repeat ourselves. */
15959 also = "also ";
15960 else
15962 cache_ns = key_ns;
15963 cache_id = key_name;
15964 cache_section = d->section;
15965 gcc_checking_assert (table.find_dependency (cache_ns));
15966 sec.tree_node (cache_ns);
15967 sec.tree_node (cache_id);
15968 sec.u (d->cluster);
15969 count++;
15971 dump () && dump ("Pending %s %N entity:%u section:%u %skeyed to %P",
15972 d->get_entity_kind () == depset::EK_DECL
15973 ? "member" : "specialization", d->get_entity (),
15974 d->cluster, cache_section, also, cache_ns, cache_id);
15976 sec.end (to, to->name (MOD_SNAME_PFX ".pnd"), crc_p);
15977 dump.outdent ();
15979 return count;
15982 bool
15983 module_state::read_pendings (unsigned count)
15985 trees_in sec (this);
15987 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".pnd"))
15988 return false;
15990 dump () && dump ("Reading %u pendings", count);
15991 dump.indent ();
15993 for (unsigned ix = 0; ix != count; ix++)
15995 pending_key key;
15996 unsigned index;
15998 key.ns = sec.tree_node ();
15999 key.id = sec.tree_node ();
16000 index = sec.u ();
16002 if (!key.ns || !key.id
16003 || !(TREE_CODE (key.ns) == NAMESPACE_DECL
16004 && !DECL_NAMESPACE_ALIAS (key.ns))
16005 || !identifier_p (key.id)
16006 || index >= entity_num)
16007 sec.set_overrun ();
16009 if (sec.get_overrun ())
16010 break;
16012 dump () && dump ("Pending:%u keyed to %P", index, key.ns, key.id);
16014 index += entity_lwm;
16015 auto &vec = pending_table->get_or_insert (key);
16016 vec.safe_push (index);
16019 dump.outdent ();
16020 if (!sec.end (from ()))
16021 return false;
16022 return true;
16025 /* Read & write locations. */
16026 enum loc_kind {
16027 LK_ORDINARY,
16028 LK_MACRO,
16029 LK_IMPORT_ORDINARY,
16030 LK_IMPORT_MACRO,
16031 LK_ADHOC,
16032 LK_RESERVED,
16035 static const module_state *
16036 module_for_ordinary_loc (location_t loc)
16038 unsigned pos = 0;
16039 unsigned len = ool->length () - pos;
16041 while (len)
16043 unsigned half = len / 2;
16044 module_state *probe = (*ool)[pos + half];
16045 if (loc < probe->ordinary_locs.first)
16046 len = half;
16047 else if (loc < probe->ordinary_locs.first + probe->ordinary_locs.second)
16048 return probe;
16049 else
16051 pos += half + 1;
16052 len = len - (half + 1);
16056 return nullptr;
16059 static const module_state *
16060 module_for_macro_loc (location_t loc)
16062 unsigned pos = 1;
16063 unsigned len = modules->length () - pos;
16065 while (len)
16067 unsigned half = len / 2;
16068 module_state *probe = (*modules)[pos + half];
16069 if (loc < probe->macro_locs.first)
16071 pos += half + 1;
16072 len = len - (half + 1);
16074 else if (loc >= probe->macro_locs.first + probe->macro_locs.second)
16075 len = half;
16076 else
16077 return probe;
16080 return NULL;
16083 location_t
16084 module_state::imported_from () const
16086 location_t from = loc;
16087 line_map_ordinary const *fmap
16088 = linemap_check_ordinary (linemap_lookup (line_table, from));
16090 if (MAP_MODULE_P (fmap))
16091 from = linemap_included_from (fmap);
16093 return from;
16096 /* Note that LOC will need writing. This allows us to prune locations
16097 that are not needed. */
16099 bool
16100 module_state::note_location (location_t loc)
16102 bool added = false;
16103 if (!macro_loc_table && !ord_loc_table)
16105 else if (loc < RESERVED_LOCATION_COUNT)
16107 else if (IS_ADHOC_LOC (loc))
16109 location_t locus = get_location_from_adhoc_loc (line_table, loc);
16110 note_location (locus);
16111 source_range range = get_range_from_loc (line_table, loc);
16112 if (range.m_start != locus)
16113 note_location (range.m_start);
16114 note_location (range.m_finish);
16116 else if (loc >= LINEMAPS_MACRO_LOWEST_LOCATION (line_table))
16118 if (spans.macro (loc))
16120 const line_map *map = linemap_lookup (line_table, loc);
16121 const line_map_macro *mac_map = linemap_check_macro (map);
16122 hashval_t hv = macro_loc_traits::hash (mac_map);
16123 macro_loc_info *slot
16124 = macro_loc_table->find_slot_with_hash (mac_map, hv, INSERT);
16125 if (!slot->src)
16127 slot->src = mac_map;
16128 slot->remap = 0;
16129 // Expansion locations could themselves be from a
16130 // macro, we need to note them all.
16131 note_location (mac_map->m_expansion);
16132 gcc_checking_assert (mac_map->n_tokens);
16133 location_t tloc = UNKNOWN_LOCATION;
16134 for (unsigned ix = mac_map->n_tokens * 2; ix--;)
16135 if (mac_map->macro_locations[ix] != tloc)
16137 tloc = mac_map->macro_locations[ix];
16138 note_location (tloc);
16140 added = true;
16144 else if (IS_ORDINARY_LOC (loc))
16146 if (spans.ordinary (loc))
16148 const line_map *map = linemap_lookup (line_table, loc);
16149 const line_map_ordinary *ord_map = linemap_check_ordinary (map);
16150 ord_loc_info lkup;
16151 lkup.src = ord_map;
16152 lkup.span = 1 << ord_map->m_column_and_range_bits;
16153 lkup.offset = (loc - MAP_START_LOCATION (ord_map)) & ~(lkup.span - 1);
16154 lkup.remap = 0;
16155 ord_loc_info *slot = (ord_loc_table->find_slot_with_hash
16156 (lkup, ord_loc_traits::hash (lkup), INSERT));
16157 if (!slot->src)
16159 *slot = lkup;
16160 added = true;
16164 else
16165 gcc_unreachable ();
16166 return added;
16169 /* If we're not streaming, record that we need location LOC.
16170 Otherwise stream it. */
16172 void
16173 module_state::write_location (bytes_out &sec, location_t loc)
16175 if (!sec.streaming_p ())
16177 note_location (loc);
16178 return;
16181 if (loc < RESERVED_LOCATION_COUNT)
16183 dump (dumper::LOCATION) && dump ("Reserved location %u", unsigned (loc));
16184 sec.u (LK_RESERVED + loc);
16186 else if (IS_ADHOC_LOC (loc))
16188 dump (dumper::LOCATION) && dump ("Adhoc location");
16189 sec.u (LK_ADHOC);
16190 location_t locus = get_location_from_adhoc_loc (line_table, loc);
16191 write_location (sec, locus);
16192 source_range range = get_range_from_loc (line_table, loc);
16193 if (range.m_start == locus)
16194 /* Compress. */
16195 range.m_start = UNKNOWN_LOCATION;
16196 write_location (sec, range.m_start);
16197 write_location (sec, range.m_finish);
16198 unsigned discriminator = get_discriminator_from_adhoc_loc (line_table, loc);
16199 sec.u (discriminator);
16201 else if (loc >= LINEMAPS_MACRO_LOWEST_LOCATION (line_table))
16203 const macro_loc_info *info = nullptr;
16204 unsigned offset = 0;
16205 if (unsigned hwm = macro_loc_remap->length ())
16207 info = macro_loc_remap->begin ();
16208 while (hwm != 1)
16210 unsigned mid = hwm / 2;
16211 if (MAP_START_LOCATION (info[mid].src) <= loc)
16213 info += mid;
16214 hwm -= mid;
16216 else
16217 hwm = mid;
16219 offset = loc - MAP_START_LOCATION (info->src);
16220 if (offset > info->src->n_tokens)
16221 info = nullptr;
16224 gcc_checking_assert (bool (info) == bool (spans.macro (loc)));
16226 if (info)
16228 offset += info->remap;
16229 sec.u (LK_MACRO);
16230 sec.u (offset);
16231 dump (dumper::LOCATION)
16232 && dump ("Macro location %u output %u", loc, offset);
16234 else if (const module_state *import = module_for_macro_loc (loc))
16236 unsigned off = loc - import->macro_locs.first;
16237 sec.u (LK_IMPORT_MACRO);
16238 sec.u (import->remap);
16239 sec.u (off);
16240 dump (dumper::LOCATION)
16241 && dump ("Imported macro location %u output %u:%u",
16242 loc, import->remap, off);
16244 else
16245 gcc_unreachable ();
16247 else if (IS_ORDINARY_LOC (loc))
16249 const ord_loc_info *info = nullptr;
16250 unsigned offset = 0;
16251 if (unsigned hwm = ord_loc_remap->length ())
16253 info = ord_loc_remap->begin ();
16254 while (hwm != 1)
16256 unsigned mid = hwm / 2;
16257 if (MAP_START_LOCATION (info[mid].src) + info[mid].offset <= loc)
16259 info += mid;
16260 hwm -= mid;
16262 else
16263 hwm = mid;
16265 offset = loc - MAP_START_LOCATION (info->src) - info->offset;
16266 if (offset > info->span)
16267 info = nullptr;
16270 gcc_checking_assert (bool (info) == bool (spans.ordinary (loc)));
16272 if (info)
16274 offset += info->remap;
16275 sec.u (LK_ORDINARY);
16276 sec.u (offset);
16278 dump (dumper::LOCATION)
16279 && dump ("Ordinary location %u output %u", loc, offset);
16281 else if (const module_state *import = module_for_ordinary_loc (loc))
16283 unsigned off = loc - import->ordinary_locs.first;
16284 sec.u (LK_IMPORT_ORDINARY);
16285 sec.u (import->remap);
16286 sec.u (off);
16287 dump (dumper::LOCATION)
16288 && dump ("Imported ordinary location %u output %u:%u",
16289 import->remap, import->remap, off);
16291 else
16292 gcc_unreachable ();
16294 else
16295 gcc_unreachable ();
16298 location_t
16299 module_state::read_location (bytes_in &sec) const
16301 location_t locus = UNKNOWN_LOCATION;
16302 unsigned kind = sec.u ();
16303 switch (kind)
16305 default:
16307 if (kind < LK_RESERVED + RESERVED_LOCATION_COUNT)
16308 locus = location_t (kind - LK_RESERVED);
16309 else
16310 sec.set_overrun ();
16311 dump (dumper::LOCATION)
16312 && dump ("Reserved location %u", unsigned (locus));
16314 break;
16316 case LK_ADHOC:
16318 dump (dumper::LOCATION) && dump ("Adhoc location");
16319 locus = read_location (sec);
16320 source_range range;
16321 range.m_start = read_location (sec);
16322 if (range.m_start == UNKNOWN_LOCATION)
16323 range.m_start = locus;
16324 range.m_finish = read_location (sec);
16325 unsigned discriminator = sec.u ();
16326 if (locus != loc && range.m_start != loc && range.m_finish != loc)
16327 locus = line_table->get_or_create_combined_loc (locus, range,
16328 nullptr, discriminator);
16330 break;
16332 case LK_MACRO:
16334 unsigned off = sec.u ();
16336 if (macro_locs.second)
16338 if (off < macro_locs.second)
16339 locus = off + macro_locs.first;
16340 else
16341 sec.set_overrun ();
16343 else
16344 locus = loc;
16345 dump (dumper::LOCATION)
16346 && dump ("Macro %u becoming %u", off, locus);
16348 break;
16350 case LK_ORDINARY:
16352 unsigned off = sec.u ();
16353 if (ordinary_locs.second)
16355 if (off < ordinary_locs.second)
16356 locus = off + ordinary_locs.first;
16357 else
16358 sec.set_overrun ();
16360 else
16361 locus = loc;
16363 dump (dumper::LOCATION)
16364 && dump ("Ordinary location %u becoming %u", off, locus);
16366 break;
16368 case LK_IMPORT_MACRO:
16369 case LK_IMPORT_ORDINARY:
16371 unsigned mod = sec.u ();
16372 unsigned off = sec.u ();
16373 const module_state *import = NULL;
16375 if (!mod && !slurp->remap)
16376 /* This is an early read of a partition location during the
16377 read of our ordinary location map. */
16378 import = this;
16379 else
16381 mod = slurp->remap_module (mod);
16382 if (!mod)
16383 sec.set_overrun ();
16384 else
16385 import = (*modules)[mod];
16388 if (import)
16390 if (kind == LK_IMPORT_MACRO)
16392 if (!import->macro_locs.second)
16393 locus = import->loc;
16394 else if (off < import->macro_locs.second)
16395 locus = off + import->macro_locs.first;
16396 else
16397 sec.set_overrun ();
16399 else
16401 if (!import->ordinary_locs.second)
16402 locus = import->loc;
16403 else if (off < import->ordinary_locs.second)
16404 locus = import->ordinary_locs.first + off;
16405 else
16406 sec.set_overrun ();
16410 break;
16413 return locus;
16416 /* Allocate hash tables to record needed locations. */
16418 void
16419 module_state::write_init_maps ()
16421 macro_loc_table = new hash_table<macro_loc_traits> (EXPERIMENT (1, 400));
16422 ord_loc_table = new hash_table<ord_loc_traits> (EXPERIMENT (1, 400));
16425 /* Prepare the span adjustments. We prune unneeded locations -- at
16426 this point every needed location must have been seen by
16427 note_location. */
16429 range_t
16430 module_state::write_prepare_maps (module_state_config *cfg, bool has_partitions)
16432 dump () && dump ("Preparing locations");
16433 dump.indent ();
16435 dump () && dump ("Reserved locations [%u,%u) macro [%u,%u)",
16436 spans[loc_spans::SPAN_RESERVED].ordinary.first,
16437 spans[loc_spans::SPAN_RESERVED].ordinary.second,
16438 spans[loc_spans::SPAN_RESERVED].macro.first,
16439 spans[loc_spans::SPAN_RESERVED].macro.second);
16441 range_t info {0, 0};
16443 // Sort the noted lines.
16444 vec_alloc (ord_loc_remap, ord_loc_table->size ());
16445 for (auto iter = ord_loc_table->begin (), end = ord_loc_table->end ();
16446 iter != end; ++iter)
16447 ord_loc_remap->quick_push (*iter);
16448 ord_loc_remap->qsort (&ord_loc_info::compare);
16450 // Note included-from maps.
16451 bool added = false;
16452 const line_map_ordinary *current = nullptr;
16453 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
16454 iter != end; ++iter)
16455 if (iter->src != current)
16457 current = iter->src;
16458 for (auto probe = current;
16459 auto from = linemap_included_from (probe);
16460 probe = linemap_check_ordinary (linemap_lookup (line_table, from)))
16462 if (has_partitions)
16464 // Partition locations need to elide their module map
16465 // entry.
16466 probe
16467 = linemap_check_ordinary (linemap_lookup (line_table, from));
16468 if (MAP_MODULE_P (probe))
16469 from = linemap_included_from (probe);
16472 if (!note_location (from))
16473 break;
16474 added = true;
16477 if (added)
16479 // Reconstruct the line array as we added items to the hash table.
16480 vec_free (ord_loc_remap);
16481 vec_alloc (ord_loc_remap, ord_loc_table->size ());
16482 for (auto iter = ord_loc_table->begin (), end = ord_loc_table->end ();
16483 iter != end; ++iter)
16484 ord_loc_remap->quick_push (*iter);
16485 ord_loc_remap->qsort (&ord_loc_info::compare);
16487 delete ord_loc_table;
16488 ord_loc_table = nullptr;
16490 // Merge (sufficiently) adjacent spans, and calculate remapping.
16491 constexpr unsigned adjacency = 2; // Allow 2 missing lines.
16492 auto begin = ord_loc_remap->begin (), end = ord_loc_remap->end ();
16493 auto dst = begin;
16494 unsigned offset = 0, range_bits = 0;
16495 ord_loc_info *base = nullptr;
16496 for (auto iter = begin; iter != end; ++iter)
16498 if (base && iter->src == base->src)
16500 if (base->offset + base->span +
16501 ((adjacency << base->src->m_column_and_range_bits)
16502 // If there are few c&r bits, allow further separation.
16503 | (adjacency << 4))
16504 >= iter->offset)
16506 // Merge.
16507 offset -= base->span;
16508 base->span = iter->offset + iter->span - base->offset;
16509 offset += base->span;
16510 continue;
16513 else if (range_bits < iter->src->m_range_bits)
16514 range_bits = iter->src->m_range_bits;
16516 offset += ((1u << iter->src->m_range_bits) - 1);
16517 offset &= ~((1u << iter->src->m_range_bits) - 1);
16518 iter->remap = offset;
16519 offset += iter->span;
16520 base = dst;
16521 *dst++ = *iter;
16523 ord_loc_remap->truncate (dst - begin);
16525 info.first = ord_loc_remap->length ();
16526 cfg->ordinary_locs = offset;
16527 cfg->loc_range_bits = range_bits;
16528 dump () && dump ("Ordinary maps:%u locs:%u range_bits:%u",
16529 info.first, cfg->ordinary_locs,
16530 cfg->loc_range_bits);
16532 // Remap the macro locations.
16533 vec_alloc (macro_loc_remap, macro_loc_table->size ());
16534 for (auto iter = macro_loc_table->begin (), end = macro_loc_table->end ();
16535 iter != end; ++iter)
16536 macro_loc_remap->quick_push (*iter);
16537 delete macro_loc_table;
16538 macro_loc_table = nullptr;
16540 macro_loc_remap->qsort (&macro_loc_info::compare);
16541 offset = 0;
16542 for (auto iter = macro_loc_remap->begin (), end = macro_loc_remap->end ();
16543 iter != end; ++iter)
16545 auto mac = iter->src;
16546 iter->remap = offset;
16547 offset += mac->n_tokens;
16549 info.second = macro_loc_remap->length ();
16550 cfg->macro_locs = offset;
16552 dump () && dump ("Macro maps:%u locs:%u", info.second, cfg->macro_locs);
16554 dump.outdent ();
16556 // If we have no ordinary locs, we must also have no macro locs.
16557 gcc_checking_assert (cfg->ordinary_locs || !cfg->macro_locs);
16559 return info;
16562 bool
16563 module_state::read_prepare_maps (const module_state_config *cfg)
16565 location_t ordinary = line_table->highest_location + 1;
16566 ordinary += cfg->ordinary_locs;
16568 location_t macro = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
16569 macro -= cfg->macro_locs;
16571 if (ordinary < LINE_MAP_MAX_LOCATION_WITH_COLS
16572 && macro >= LINE_MAP_MAX_LOCATION)
16573 /* OK, we have enough locations. */
16574 return true;
16576 ordinary_locs.first = ordinary_locs.second = 0;
16577 macro_locs.first = macro_locs.second = 0;
16579 static bool informed = false;
16580 if (!informed)
16582 /* Just give the notice once. */
16583 informed = true;
16584 inform (loc, "unable to represent further imported source locations");
16587 return false;
16590 /* Write & read the location maps. Not called if there are no
16591 locations. */
16593 void
16594 module_state::write_ordinary_maps (elf_out *to, range_t &info,
16595 bool has_partitions, unsigned *crc_p)
16597 dump () && dump ("Writing ordinary location maps");
16598 dump.indent ();
16600 vec<const char *> filenames;
16601 filenames.create (20);
16603 /* Determine the unique filenames. */
16604 const line_map_ordinary *current = nullptr;
16605 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
16606 iter != end; ++iter)
16607 if (iter->src != current)
16609 current = iter->src;
16610 const char *fname = ORDINARY_MAP_FILE_NAME (iter->src);
16612 /* We should never find a module linemap in an interval. */
16613 gcc_checking_assert (!MAP_MODULE_P (iter->src));
16615 /* We expect very few filenames, so just an array.
16616 (Not true when headers are still in play :() */
16617 for (unsigned jx = filenames.length (); jx--;)
16619 const char *name = filenames[jx];
16620 if (0 == strcmp (name, fname))
16622 /* Reset the linemap's name, because for things like
16623 preprocessed input we could have multiple instances
16624 of the same name, and we'd rather not percolate
16625 that. */
16626 const_cast<line_map_ordinary *> (iter->src)->to_file = name;
16627 fname = NULL;
16628 break;
16631 if (fname)
16632 filenames.safe_push (fname);
16635 bytes_out sec (to);
16636 sec.begin ();
16638 /* Write the filenames. */
16639 unsigned len = filenames.length ();
16640 sec.u (len);
16641 dump () && dump ("%u source file names", len);
16642 for (unsigned ix = 0; ix != len; ix++)
16644 const char *fname = filenames[ix];
16645 dump (dumper::LOCATION) && dump ("Source file[%u]=%s", ix, fname);
16646 sec.str (fname);
16649 sec.u (info.first); /* Num maps. */
16650 const ord_loc_info *base = nullptr;
16651 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
16652 iter != end; ++iter)
16654 dump (dumper::LOCATION)
16655 && dump ("Span:%u ordinary [%u+%u,+%u)->[%u,+%u)",
16656 iter - ord_loc_remap->begin (),
16657 MAP_START_LOCATION (iter->src), iter->offset, iter->span,
16658 iter->remap, iter->span);
16660 if (!base || iter->src != base->src)
16661 base = iter;
16662 sec.u (iter->offset - base->offset);
16663 if (base == iter)
16665 sec.u (iter->src->sysp);
16666 sec.u (iter->src->m_range_bits);
16667 sec.u (iter->src->m_column_and_range_bits - iter->src->m_range_bits);
16669 const char *fname = ORDINARY_MAP_FILE_NAME (iter->src);
16670 for (unsigned ix = 0; ix != filenames.length (); ix++)
16671 if (filenames[ix] == fname)
16673 sec.u (ix);
16674 break;
16676 unsigned line = ORDINARY_MAP_STARTING_LINE_NUMBER (iter->src);
16677 line += iter->offset >> iter->src->m_column_and_range_bits;
16678 sec.u (line);
16680 sec.u (iter->remap);
16681 if (base == iter)
16683 /* Write the included from location, which means reading it
16684 while reading in the ordinary maps. So we'd better not
16685 be getting ahead of ourselves. */
16686 location_t from = linemap_included_from (iter->src);
16687 gcc_checking_assert (from < MAP_START_LOCATION (iter->src));
16688 if (from != UNKNOWN_LOCATION && has_partitions)
16690 /* A partition's span will have a from pointing at a
16691 MODULE_INC. Find that map's from. */
16692 line_map_ordinary const *fmap
16693 = linemap_check_ordinary (linemap_lookup (line_table, from));
16694 if (MAP_MODULE_P (fmap))
16695 from = linemap_included_from (fmap);
16697 write_location (sec, from);
16701 filenames.release ();
16703 sec.end (to, to->name (MOD_SNAME_PFX ".olm"), crc_p);
16704 dump.outdent ();
16707 void
16708 module_state::write_macro_maps (elf_out *to, range_t &info, unsigned *crc_p)
16710 dump () && dump ("Writing macro location maps");
16711 dump.indent ();
16713 bytes_out sec (to);
16714 sec.begin ();
16716 dump () && dump ("Macro maps:%u", info.second);
16717 sec.u (info.second);
16719 unsigned macro_num = 0;
16720 for (auto iter = macro_loc_remap->end (), begin = macro_loc_remap->begin ();
16721 iter-- != begin;)
16723 auto mac = iter->src;
16724 sec.u (iter->remap);
16725 sec.u (mac->n_tokens);
16726 sec.cpp_node (mac->macro);
16727 write_location (sec, mac->m_expansion);
16728 const location_t *locs = mac->macro_locations;
16729 /* There are lots of identical runs. */
16730 location_t prev = UNKNOWN_LOCATION;
16731 unsigned count = 0;
16732 unsigned runs = 0;
16733 for (unsigned jx = mac->n_tokens * 2; jx--;)
16735 location_t tok_loc = locs[jx];
16736 if (tok_loc == prev)
16738 count++;
16739 continue;
16741 runs++;
16742 sec.u (count);
16743 count = 1;
16744 prev = tok_loc;
16745 write_location (sec, tok_loc);
16747 sec.u (count);
16748 dump (dumper::LOCATION)
16749 && dump ("Macro:%u %I %u/%u*2 locations [%u,%u)->%u",
16750 macro_num, identifier (mac->macro),
16751 runs, mac->n_tokens,
16752 MAP_START_LOCATION (mac),
16753 MAP_START_LOCATION (mac) + mac->n_tokens,
16754 iter->remap);
16755 macro_num++;
16757 gcc_assert (macro_num == info.second);
16759 sec.end (to, to->name (MOD_SNAME_PFX ".mlm"), crc_p);
16760 dump.outdent ();
16763 bool
16764 module_state::read_ordinary_maps (unsigned num_ord_locs, unsigned range_bits)
16766 bytes_in sec;
16768 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".olm"))
16769 return false;
16770 dump () && dump ("Reading ordinary location maps");
16771 dump.indent ();
16773 /* Read the filename table. */
16774 unsigned len = sec.u ();
16775 dump () && dump ("%u source file names", len);
16776 vec<const char *> filenames;
16777 filenames.create (len);
16778 for (unsigned ix = 0; ix != len; ix++)
16780 size_t l;
16781 const char *buf = sec.str (&l);
16782 char *fname = XNEWVEC (char, l + 1);
16783 memcpy (fname, buf, l + 1);
16784 dump (dumper::LOCATION) && dump ("Source file[%u]=%s", ix, fname);
16785 /* We leak these names into the line-map table. But it
16786 doesn't own them. */
16787 filenames.quick_push (fname);
16790 unsigned num_ordinary = sec.u ();
16791 dump () && dump ("Ordinary maps:%u, range_bits:%u", num_ordinary, range_bits);
16793 location_t offset = line_table->highest_location + 1;
16794 offset += ((1u << range_bits) - 1);
16795 offset &= ~((1u << range_bits) - 1);
16796 ordinary_locs.first = offset;
16798 bool propagated = spans.maybe_propagate (this, offset);
16799 line_map_ordinary *maps = static_cast<line_map_ordinary *>
16800 (line_map_new_raw (line_table, false, num_ordinary));
16802 const line_map_ordinary *base = nullptr;
16803 for (unsigned ix = 0; ix != num_ordinary && !sec.get_overrun (); ix++)
16805 line_map_ordinary *map = &maps[ix];
16807 unsigned offset = sec.u ();
16808 if (!offset)
16810 map->reason = LC_RENAME;
16811 map->sysp = sec.u ();
16812 map->m_range_bits = sec.u ();
16813 map->m_column_and_range_bits = sec.u () + map->m_range_bits;
16814 unsigned fnum = sec.u ();
16815 map->to_file = (fnum < filenames.length () ? filenames[fnum] : "");
16816 map->to_line = sec.u ();
16817 base = map;
16819 else
16821 *map = *base;
16822 map->to_line += offset >> map->m_column_and_range_bits;
16824 unsigned remap = sec.u ();
16825 map->start_location = remap + ordinary_locs.first;
16826 if (base == map)
16828 /* Root the outermost map at our location. */
16829 ordinary_locs.second = remap;
16830 location_t from = read_location (sec);
16831 map->included_from = from != UNKNOWN_LOCATION ? from : loc;
16835 ordinary_locs.second = num_ord_locs;
16836 /* highest_location is the one handed out, not the next one to
16837 hand out. */
16838 line_table->highest_location = ordinary_locs.first + ordinary_locs.second - 1;
16840 if (line_table->highest_location >= LINE_MAP_MAX_LOCATION_WITH_COLS)
16841 /* We shouldn't run out of locations, as we checked before
16842 starting. */
16843 sec.set_overrun ();
16844 dump () && dump ("Ordinary location [%u,+%u)",
16845 ordinary_locs.first, ordinary_locs.second);
16847 if (propagated)
16848 spans.close ();
16850 filenames.release ();
16852 dump.outdent ();
16853 if (!sec.end (from ()))
16854 return false;
16856 return true;
16859 bool
16860 module_state::read_macro_maps (unsigned num_macro_locs)
16862 bytes_in sec;
16864 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".mlm"))
16865 return false;
16866 dump () && dump ("Reading macro location maps");
16867 dump.indent ();
16869 unsigned num_macros = sec.u ();
16870 dump () && dump ("Macro maps:%u locs:%u", num_macros, num_macro_locs);
16872 bool propagated = spans.maybe_propagate (this,
16873 line_table->highest_location + 1);
16875 location_t offset = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
16876 macro_locs.second = num_macro_locs;
16877 macro_locs.first = offset - num_macro_locs;
16879 dump () && dump ("Macro loc delta %d", offset);
16880 dump () && dump ("Macro locations [%u,%u)",
16881 macro_locs.first, macro_locs.second);
16883 for (unsigned ix = 0; ix != num_macros && !sec.get_overrun (); ix++)
16885 unsigned offset = sec.u ();
16886 unsigned n_tokens = sec.u ();
16887 cpp_hashnode *node = sec.cpp_node ();
16888 location_t exp_loc = read_location (sec);
16890 const line_map_macro *macro
16891 = linemap_enter_macro (line_table, node, exp_loc, n_tokens);
16892 if (!macro)
16893 /* We shouldn't run out of locations, as we checked that we
16894 had enough before starting. */
16895 break;
16896 gcc_checking_assert (MAP_START_LOCATION (macro)
16897 == offset + macro_locs.first);
16899 location_t *locs = macro->macro_locations;
16900 location_t tok_loc = UNKNOWN_LOCATION;
16901 unsigned count = sec.u ();
16902 unsigned runs = 0;
16903 for (unsigned jx = macro->n_tokens * 2; jx-- && !sec.get_overrun ();)
16905 while (!count-- && !sec.get_overrun ())
16907 runs++;
16908 tok_loc = read_location (sec);
16909 count = sec.u ();
16911 locs[jx] = tok_loc;
16913 if (count)
16914 sec.set_overrun ();
16915 dump (dumper::LOCATION)
16916 && dump ("Macro:%u %I %u/%u*2 locations [%u,%u)",
16917 ix, identifier (node), runs, n_tokens,
16918 MAP_START_LOCATION (macro),
16919 MAP_START_LOCATION (macro) + n_tokens);
16922 dump () && dump ("Macro location lwm:%u", macro_locs.first);
16923 if (propagated)
16924 spans.close ();
16926 dump.outdent ();
16927 if (!sec.end (from ()))
16928 return false;
16930 return true;
16933 /* Serialize the definition of MACRO. */
16935 void
16936 module_state::write_define (bytes_out &sec, const cpp_macro *macro)
16938 sec.u (macro->count);
16940 bytes_out::bits_out bits = sec.stream_bits ();
16941 bits.b (macro->fun_like);
16942 bits.b (macro->variadic);
16943 bits.b (macro->syshdr);
16944 bits.bflush ();
16946 write_location (sec, macro->line);
16947 if (macro->fun_like)
16949 sec.u (macro->paramc);
16950 const cpp_hashnode *const *parms = macro->parm.params;
16951 for (unsigned ix = 0; ix != macro->paramc; ix++)
16952 sec.cpp_node (parms[ix]);
16955 unsigned len = 0;
16956 for (unsigned ix = 0; ix != macro->count; ix++)
16958 const cpp_token *token = &macro->exp.tokens[ix];
16959 write_location (sec, token->src_loc);
16960 sec.u (token->type);
16961 sec.u (token->flags);
16962 switch (cpp_token_val_index (token))
16964 default:
16965 gcc_unreachable ();
16967 case CPP_TOKEN_FLD_ARG_NO:
16968 /* An argument reference. */
16969 sec.u (token->val.macro_arg.arg_no);
16970 sec.cpp_node (token->val.macro_arg.spelling);
16971 break;
16973 case CPP_TOKEN_FLD_NODE:
16974 /* An identifier. */
16975 sec.cpp_node (token->val.node.node);
16976 if (token->val.node.spelling == token->val.node.node)
16977 /* The spelling will usually be the same. so optimize
16978 that. */
16979 sec.str (NULL, 0);
16980 else
16981 sec.cpp_node (token->val.node.spelling);
16982 break;
16984 case CPP_TOKEN_FLD_NONE:
16985 break;
16987 case CPP_TOKEN_FLD_STR:
16988 /* A string, number or comment. Not always NUL terminated,
16989 we stream out in a single contatenation with embedded
16990 NULs as that's a safe default. */
16991 len += token->val.str.len + 1;
16992 sec.u (token->val.str.len);
16993 break;
16995 case CPP_TOKEN_FLD_SOURCE:
16996 case CPP_TOKEN_FLD_TOKEN_NO:
16997 case CPP_TOKEN_FLD_PRAGMA:
16998 /* These do not occur inside a macro itself. */
16999 gcc_unreachable ();
17003 if (len)
17005 char *ptr = reinterpret_cast<char *> (sec.buf (len));
17006 len = 0;
17007 for (unsigned ix = 0; ix != macro->count; ix++)
17009 const cpp_token *token = &macro->exp.tokens[ix];
17010 if (cpp_token_val_index (token) == CPP_TOKEN_FLD_STR)
17012 memcpy (ptr + len, token->val.str.text,
17013 token->val.str.len);
17014 len += token->val.str.len;
17015 ptr[len++] = 0;
17021 /* Read a macro definition. */
17023 cpp_macro *
17024 module_state::read_define (bytes_in &sec, cpp_reader *reader) const
17026 unsigned count = sec.u ();
17027 /* We rely on knowing cpp_reader's hash table is ident_hash, and
17028 its subobject allocator is stringpool_ggc_alloc and that is just
17029 a wrapper for ggc_alloc_atomic. */
17030 cpp_macro *macro
17031 = (cpp_macro *)ggc_alloc_atomic (sizeof (cpp_macro)
17032 + sizeof (cpp_token) * (count - !!count));
17033 memset (macro, 0, sizeof (cpp_macro) + sizeof (cpp_token) * (count - !!count));
17035 macro->count = count;
17036 macro->kind = cmk_macro;
17037 macro->imported_p = true;
17039 bytes_in::bits_in bits = sec.stream_bits ();
17040 macro->fun_like = bits.b ();
17041 macro->variadic = bits.b ();
17042 macro->syshdr = bits.b ();
17043 bits.bflush ();
17045 macro->line = read_location (sec);
17047 if (macro->fun_like)
17049 unsigned paramc = sec.u ();
17050 cpp_hashnode **params
17051 = (cpp_hashnode **)ggc_alloc_atomic (sizeof (cpp_hashnode *) * paramc);
17052 macro->paramc = paramc;
17053 macro->parm.params = params;
17054 for (unsigned ix = 0; ix != paramc; ix++)
17055 params[ix] = sec.cpp_node ();
17058 unsigned len = 0;
17059 for (unsigned ix = 0; ix != count && !sec.get_overrun (); ix++)
17061 cpp_token *token = &macro->exp.tokens[ix];
17062 token->src_loc = read_location (sec);
17063 token->type = cpp_ttype (sec.u ());
17064 token->flags = sec.u ();
17065 switch (cpp_token_val_index (token))
17067 default:
17068 sec.set_overrun ();
17069 break;
17071 case CPP_TOKEN_FLD_ARG_NO:
17072 /* An argument reference. */
17074 unsigned arg_no = sec.u ();
17075 if (arg_no - 1 >= macro->paramc)
17076 sec.set_overrun ();
17077 token->val.macro_arg.arg_no = arg_no;
17078 token->val.macro_arg.spelling = sec.cpp_node ();
17080 break;
17082 case CPP_TOKEN_FLD_NODE:
17083 /* An identifier. */
17084 token->val.node.node = sec.cpp_node ();
17085 token->val.node.spelling = sec.cpp_node ();
17086 if (!token->val.node.spelling)
17087 token->val.node.spelling = token->val.node.node;
17088 break;
17090 case CPP_TOKEN_FLD_NONE:
17091 break;
17093 case CPP_TOKEN_FLD_STR:
17094 /* A string, number or comment. */
17095 token->val.str.len = sec.u ();
17096 len += token->val.str.len + 1;
17097 break;
17101 if (len)
17102 if (const char *ptr = reinterpret_cast<const char *> (sec.buf (len)))
17104 /* There should be a final NUL. */
17105 if (ptr[len-1])
17106 sec.set_overrun ();
17107 /* cpp_alloc_token_string will add a final NUL. */
17108 const unsigned char *buf
17109 = cpp_alloc_token_string (reader, (const unsigned char *)ptr, len - 1);
17110 len = 0;
17111 for (unsigned ix = 0; ix != count && !sec.get_overrun (); ix++)
17113 cpp_token *token = &macro->exp.tokens[ix];
17114 if (cpp_token_val_index (token) == CPP_TOKEN_FLD_STR)
17116 token->val.str.text = buf + len;
17117 len += token->val.str.len;
17118 if (buf[len++])
17119 sec.set_overrun ();
17124 if (sec.get_overrun ())
17125 return NULL;
17126 return macro;
17129 /* Exported macro data. */
17130 struct GTY(()) macro_export {
17131 cpp_macro *def;
17132 location_t undef_loc;
17134 macro_export ()
17135 :def (NULL), undef_loc (UNKNOWN_LOCATION)
17140 /* Imported macro data. */
17141 class macro_import {
17142 public:
17143 struct slot {
17144 #if defined (WORDS_BIGENDIAN) && SIZEOF_VOID_P == 8
17145 int offset;
17146 #endif
17147 /* We need to ensure we don't use the LSB for representation, as
17148 that's the union discriminator below. */
17149 unsigned bits;
17151 #if !(defined (WORDS_BIGENDIAN) && SIZEOF_VOID_P == 8)
17152 int offset;
17153 #endif
17155 public:
17156 enum Layout {
17157 L_DEF = 1,
17158 L_UNDEF = 2,
17159 L_BOTH = 3,
17160 L_MODULE_SHIFT = 2
17163 public:
17164 /* Not a regular ctor, because we put it in a union, and that's
17165 not allowed in C++ 98. */
17166 static slot ctor (unsigned module, unsigned defness)
17168 gcc_checking_assert (defness);
17169 slot s;
17170 s.bits = defness | (module << L_MODULE_SHIFT);
17171 s.offset = -1;
17172 return s;
17175 public:
17176 unsigned get_defness () const
17178 return bits & L_BOTH;
17180 unsigned get_module () const
17182 return bits >> L_MODULE_SHIFT;
17184 void become_undef ()
17186 bits &= ~unsigned (L_DEF);
17187 bits |= unsigned (L_UNDEF);
17191 private:
17192 typedef vec<slot, va_heap, vl_embed> ary_t;
17193 union either {
17194 /* Discriminated by bits 0|1 != 0. The expected case is that
17195 there will be exactly one slot per macro, hence the effort of
17196 packing that. */
17197 ary_t *ary;
17198 slot single;
17199 } u;
17201 public:
17202 macro_import ()
17204 u.ary = NULL;
17207 private:
17208 bool single_p () const
17210 return u.single.bits & slot::L_BOTH;
17212 bool occupied_p () const
17214 return u.ary != NULL;
17217 public:
17218 unsigned length () const
17220 gcc_checking_assert (occupied_p ());
17221 return single_p () ? 1 : u.ary->length ();
17223 slot &operator[] (unsigned ix)
17225 gcc_checking_assert (occupied_p ());
17226 if (single_p ())
17228 gcc_checking_assert (!ix);
17229 return u.single;
17231 else
17232 return (*u.ary)[ix];
17235 public:
17236 slot &exported ();
17237 slot &append (unsigned module, unsigned defness);
17240 /* O is a new import to append to the list for. If we're an empty
17241 set, initialize us. */
17243 macro_import::slot &
17244 macro_import::append (unsigned module, unsigned defness)
17246 if (!occupied_p ())
17248 u.single = slot::ctor (module, defness);
17249 return u.single;
17251 else
17253 bool single = single_p ();
17254 ary_t *m = single ? NULL : u.ary;
17255 vec_safe_reserve (m, 1 + single);
17256 if (single)
17257 m->quick_push (u.single);
17258 u.ary = m;
17259 return *u.ary->quick_push (slot::ctor (module, defness));
17263 /* We're going to export something. Make sure the first import slot
17264 is us. */
17266 macro_import::slot &
17267 macro_import::exported ()
17269 if (occupied_p () && !(*this)[0].get_module ())
17271 slot &res = (*this)[0];
17272 res.bits |= slot::L_DEF;
17273 return res;
17276 slot *a = &append (0, slot::L_DEF);
17277 if (!single_p ())
17279 slot &f = (*this)[0];
17280 std::swap (f, *a);
17281 a = &f;
17283 return *a;
17286 /* The import (&exported) macros. cpp_hasnode's deferred field
17287 indexes this array (offset by 1, so zero means 'not present'. */
17289 static vec<macro_import, va_heap, vl_embed> *macro_imports;
17291 /* The exported macros. A macro_import slot's zeroth element's offset
17292 indexes this array. If the zeroth slot is not for module zero,
17293 there is no export. */
17295 static GTY(()) vec<macro_export, va_gc> *macro_exports;
17297 /* The reachable set of header imports from this TU. */
17299 static GTY(()) bitmap headers;
17301 /* Get the (possibly empty) macro imports for NODE. */
17303 static macro_import &
17304 get_macro_imports (cpp_hashnode *node)
17306 if (node->deferred)
17307 return (*macro_imports)[node->deferred - 1];
17309 vec_safe_reserve (macro_imports, 1);
17310 node->deferred = macro_imports->length () + 1;
17311 return *vec_safe_push (macro_imports, macro_import ());
17314 /* Get the macro export for export EXP of NODE. */
17316 static macro_export &
17317 get_macro_export (macro_import::slot &slot)
17319 if (slot.offset >= 0)
17320 return (*macro_exports)[slot.offset];
17322 vec_safe_reserve (macro_exports, 1);
17323 slot.offset = macro_exports->length ();
17324 return *macro_exports->quick_push (macro_export ());
17327 /* If NODE is an exportable macro, add it to the export set. */
17329 static int
17330 maybe_add_macro (cpp_reader *, cpp_hashnode *node, void *data_)
17332 bool exporting = false;
17334 if (cpp_user_macro_p (node))
17335 if (cpp_macro *macro = node->value.macro)
17336 /* Ignore imported, builtins, command line and forced header macros. */
17337 if (!macro->imported_p
17338 && !macro->lazy && macro->line >= spans.main_start ())
17340 gcc_checking_assert (macro->kind == cmk_macro);
17341 /* I don't want to deal with this corner case, that I suspect is
17342 a devil's advocate reading of the standard. */
17343 gcc_checking_assert (!macro->extra_tokens);
17345 macro_import::slot &slot = get_macro_imports (node).exported ();
17346 macro_export &exp = get_macro_export (slot);
17347 exp.def = macro;
17348 exporting = true;
17351 if (!exporting && node->deferred)
17353 macro_import &imports = (*macro_imports)[node->deferred - 1];
17354 macro_import::slot &slot = imports[0];
17355 if (!slot.get_module ())
17357 gcc_checking_assert (slot.get_defness ());
17358 exporting = true;
17362 if (exporting)
17363 static_cast<vec<cpp_hashnode *> *> (data_)->safe_push (node);
17365 return 1; /* Don't stop. */
17368 /* Order cpp_hashnodes A_ and B_ by their exported macro locations. */
17370 static int
17371 macro_loc_cmp (const void *a_, const void *b_)
17373 const cpp_hashnode *node_a = *(const cpp_hashnode *const *)a_;
17374 macro_import &import_a = (*macro_imports)[node_a->deferred - 1];
17375 const macro_export &export_a = (*macro_exports)[import_a[0].offset];
17376 location_t loc_a = export_a.def ? export_a.def->line : export_a.undef_loc;
17378 const cpp_hashnode *node_b = *(const cpp_hashnode *const *)b_;
17379 macro_import &import_b = (*macro_imports)[node_b->deferred - 1];
17380 const macro_export &export_b = (*macro_exports)[import_b[0].offset];
17381 location_t loc_b = export_b.def ? export_b.def->line : export_b.undef_loc;
17383 if (loc_a < loc_b)
17384 return +1;
17385 else if (loc_a > loc_b)
17386 return -1;
17387 else
17388 return 0;
17391 /* Gather the macro definitions and undefinitions that we will need to
17392 write out. */
17394 vec<cpp_hashnode *> *
17395 module_state::prepare_macros (cpp_reader *reader)
17397 vec<cpp_hashnode *> *macros;
17398 vec_alloc (macros, 100);
17400 cpp_forall_identifiers (reader, maybe_add_macro, macros);
17402 dump (dumper::MACRO) && dump ("No more than %u macros", macros->length ());
17404 macros->qsort (macro_loc_cmp);
17406 // Note the locations.
17407 for (unsigned ix = macros->length (); ix--;)
17409 cpp_hashnode *node = (*macros)[ix];
17410 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
17411 macro_export &mac = (*macro_exports)[slot.offset];
17413 if (IDENTIFIER_KEYWORD_P (identifier (node)))
17414 continue;
17416 if (mac.undef_loc != UNKNOWN_LOCATION)
17417 note_location (mac.undef_loc);
17418 if (mac.def)
17420 note_location (mac.def->line);
17421 for (unsigned ix = 0; ix != mac.def->count; ix++)
17422 note_location (mac.def->exp.tokens[ix].src_loc);
17426 return macros;
17429 /* Write out the exported defines. This is two sections, one
17430 containing the definitions, the other a table of node names. */
17432 unsigned
17433 module_state::write_macros (elf_out *to, vec<cpp_hashnode *> *macros,
17434 unsigned *crc_p)
17436 dump () && dump ("Writing macros");
17437 dump.indent ();
17439 /* Write the defs */
17440 bytes_out sec (to);
17441 sec.begin ();
17443 unsigned count = 0;
17444 for (unsigned ix = macros->length (); ix--;)
17446 cpp_hashnode *node = (*macros)[ix];
17447 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
17448 gcc_assert (!slot.get_module () && slot.get_defness ());
17450 macro_export &mac = (*macro_exports)[slot.offset];
17451 gcc_assert (!!(slot.get_defness () & macro_import::slot::L_UNDEF)
17452 == (mac.undef_loc != UNKNOWN_LOCATION)
17453 && !!(slot.get_defness () & macro_import::slot::L_DEF)
17454 == (mac.def != NULL));
17456 if (IDENTIFIER_KEYWORD_P (identifier (node)))
17458 warning_at (mac.def->line, 0,
17459 "not exporting %<#define %E%> as it is a keyword",
17460 identifier (node));
17461 slot.offset = 0;
17462 continue;
17465 count++;
17466 slot.offset = sec.pos;
17467 dump (dumper::MACRO)
17468 && dump ("Writing macro %s%s%s %I at %u",
17469 slot.get_defness () & macro_import::slot::L_UNDEF
17470 ? "#undef" : "",
17471 slot.get_defness () == macro_import::slot::L_BOTH
17472 ? " & " : "",
17473 slot.get_defness () & macro_import::slot::L_DEF
17474 ? "#define" : "",
17475 identifier (node), slot.offset);
17476 if (mac.undef_loc != UNKNOWN_LOCATION)
17477 write_location (sec, mac.undef_loc);
17478 if (mac.def)
17479 write_define (sec, mac.def);
17481 if (count)
17482 // We may have ended on a tokenless macro with a very short
17483 // location, that will cause problems reading its bit flags.
17484 sec.u (0);
17485 sec.end (to, to->name (MOD_SNAME_PFX ".def"), crc_p);
17487 if (count)
17489 /* Write the table. */
17490 bytes_out sec (to);
17491 sec.begin ();
17492 sec.u (count);
17494 for (unsigned ix = macros->length (); ix--;)
17496 const cpp_hashnode *node = (*macros)[ix];
17497 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
17499 if (slot.offset)
17501 sec.cpp_node (node);
17502 sec.u (slot.get_defness ());
17503 sec.u (slot.offset);
17506 sec.end (to, to->name (MOD_SNAME_PFX ".mac"), crc_p);
17509 dump.outdent ();
17510 return count;
17513 bool
17514 module_state::read_macros ()
17516 /* Get the def section. */
17517 if (!slurp->macro_defs.begin (loc, from (), MOD_SNAME_PFX ".def"))
17518 return false;
17520 /* Get the tbl section, if there are defs. */
17521 if (slurp->macro_defs.more_p ()
17522 && !slurp->macro_tbl.begin (loc, from (), MOD_SNAME_PFX ".mac"))
17523 return false;
17525 return true;
17528 /* Install the macro name table. */
17530 void
17531 module_state::install_macros ()
17533 bytes_in &sec = slurp->macro_tbl;
17534 if (!sec.size)
17535 return;
17537 dump () && dump ("Reading macro table %M", this);
17538 dump.indent ();
17540 unsigned count = sec.u ();
17541 dump () && dump ("%u macros", count);
17542 while (count--)
17544 cpp_hashnode *node = sec.cpp_node ();
17545 macro_import &imp = get_macro_imports (node);
17546 unsigned flags = sec.u () & macro_import::slot::L_BOTH;
17547 if (!flags)
17548 sec.set_overrun ();
17550 if (sec.get_overrun ())
17551 break;
17553 macro_import::slot &slot = imp.append (mod, flags);
17554 slot.offset = sec.u ();
17556 dump (dumper::MACRO)
17557 && dump ("Read %s macro %s%s%s %I at %u",
17558 imp.length () > 1 ? "add" : "new",
17559 flags & macro_import::slot::L_UNDEF ? "#undef" : "",
17560 flags == macro_import::slot::L_BOTH ? " & " : "",
17561 flags & macro_import::slot::L_DEF ? "#define" : "",
17562 identifier (node), slot.offset);
17564 /* We'll leak an imported definition's TOKEN_FLD_STR's data
17565 here. But that only happens when we've had to resolve the
17566 deferred macro before this import -- why are you doing
17567 that? */
17568 if (cpp_macro *cur = cpp_set_deferred_macro (node))
17569 if (!cur->imported_p)
17571 macro_import::slot &slot = imp.exported ();
17572 macro_export &exp = get_macro_export (slot);
17573 exp.def = cur;
17574 dump (dumper::MACRO)
17575 && dump ("Saving current #define %I", identifier (node));
17579 /* We're now done with the table. */
17580 elf_in::release (slurp->from, sec);
17582 dump.outdent ();
17585 /* Import the transitive macros. */
17587 void
17588 module_state::import_macros ()
17590 bitmap_ior_into (headers, slurp->headers);
17592 bitmap_iterator bititer;
17593 unsigned bitnum;
17594 EXECUTE_IF_SET_IN_BITMAP (slurp->headers, 0, bitnum, bititer)
17595 (*modules)[bitnum]->install_macros ();
17598 /* NODE is being undefined at LOC. Record it in the export table, if
17599 necessary. */
17601 void
17602 module_state::undef_macro (cpp_reader *, location_t loc, cpp_hashnode *node)
17604 if (!node->deferred)
17605 /* The macro is not imported, so our undef is irrelevant. */
17606 return;
17608 unsigned n = dump.push (NULL);
17610 macro_import::slot &slot = (*macro_imports)[node->deferred - 1].exported ();
17611 macro_export &exp = get_macro_export (slot);
17613 exp.undef_loc = loc;
17614 slot.become_undef ();
17615 exp.def = NULL;
17617 dump (dumper::MACRO) && dump ("Recording macro #undef %I", identifier (node));
17619 dump.pop (n);
17622 /* NODE is a deferred macro node. Determine the definition and return
17623 it, with NULL if undefined. May issue diagnostics.
17625 This can leak memory, when merging declarations -- the string
17626 contents (TOKEN_FLD_STR) of each definition are allocated in
17627 unreclaimable cpp objstack. Only one will win. However, I do not
17628 expect this to be common -- mostly macros have a single point of
17629 definition. Perhaps we could restore the objstack to its position
17630 after the first imported definition (if that wins)? The macros
17631 themselves are GC'd. */
17633 cpp_macro *
17634 module_state::deferred_macro (cpp_reader *reader, location_t loc,
17635 cpp_hashnode *node)
17637 macro_import &imports = (*macro_imports)[node->deferred - 1];
17639 unsigned n = dump.push (NULL);
17640 dump (dumper::MACRO) && dump ("Deferred macro %I", identifier (node));
17642 bitmap visible (BITMAP_GGC_ALLOC ());
17644 if (!((imports[0].get_defness () & macro_import::slot::L_UNDEF)
17645 && !imports[0].get_module ()))
17647 /* Calculate the set of visible header imports. */
17648 bitmap_copy (visible, headers);
17649 for (unsigned ix = imports.length (); ix--;)
17651 const macro_import::slot &slot = imports[ix];
17652 unsigned mod = slot.get_module ();
17653 if ((slot.get_defness () & macro_import::slot::L_UNDEF)
17654 && bitmap_bit_p (visible, mod))
17656 bitmap arg = mod ? (*modules)[mod]->slurp->headers : headers;
17657 bitmap_and_compl_into (visible, arg);
17658 bitmap_set_bit (visible, mod);
17662 bitmap_set_bit (visible, 0);
17664 /* Now find the macros that are still visible. */
17665 bool failed = false;
17666 cpp_macro *def = NULL;
17667 vec<macro_export> defs;
17668 defs.create (imports.length ());
17669 for (unsigned ix = imports.length (); ix--;)
17671 const macro_import::slot &slot = imports[ix];
17672 unsigned mod = slot.get_module ();
17673 if (bitmap_bit_p (visible, mod))
17675 macro_export *pushed = NULL;
17676 if (mod)
17678 const module_state *imp = (*modules)[mod];
17679 bytes_in &sec = imp->slurp->macro_defs;
17680 if (!sec.get_overrun ())
17682 dump (dumper::MACRO)
17683 && dump ("Reading macro %s%s%s %I module %M at %u",
17684 slot.get_defness () & macro_import::slot::L_UNDEF
17685 ? "#undef" : "",
17686 slot.get_defness () == macro_import::slot::L_BOTH
17687 ? " & " : "",
17688 slot.get_defness () & macro_import::slot::L_DEF
17689 ? "#define" : "",
17690 identifier (node), imp, slot.offset);
17691 sec.random_access (slot.offset);
17693 macro_export exp;
17694 if (slot.get_defness () & macro_import::slot::L_UNDEF)
17695 exp.undef_loc = imp->read_location (sec);
17696 if (slot.get_defness () & macro_import::slot::L_DEF)
17697 exp.def = imp->read_define (sec, reader);
17698 if (sec.get_overrun ())
17699 error_at (loc, "macro definitions of %qE corrupted",
17700 imp->name);
17701 else
17702 pushed = defs.quick_push (exp);
17705 else
17706 pushed = defs.quick_push ((*macro_exports)[slot.offset]);
17707 if (pushed && pushed->def)
17709 if (!def)
17710 def = pushed->def;
17711 else if (cpp_compare_macros (def, pushed->def))
17712 failed = true;
17717 if (failed)
17719 /* If LOC is the first loc, this is the end of file check, which
17720 is a warning. */
17721 if (loc == MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0)))
17722 warning_at (loc, OPT_Winvalid_imported_macros,
17723 "inconsistent imported macro definition %qE",
17724 identifier (node));
17725 else
17726 error_at (loc, "inconsistent imported macro definition %qE",
17727 identifier (node));
17728 for (unsigned ix = defs.length (); ix--;)
17730 macro_export &exp = defs[ix];
17731 if (exp.undef_loc)
17732 inform (exp.undef_loc, "%<#undef %E%>", identifier (node));
17733 if (exp.def)
17734 inform (exp.def->line, "%<#define %s%>",
17735 cpp_macro_definition (reader, node, exp.def));
17737 def = NULL;
17740 defs.release ();
17742 dump.pop (n);
17744 return def;
17747 /* Stream the static aggregates. Sadly some headers (ahem:
17748 iostream) contain static vars, and rely on them to run global
17749 ctors. */
17750 unsigned
17751 module_state::write_inits (elf_out *to, depset::hash &table, unsigned *crc_ptr)
17753 if (!static_aggregates && !tls_aggregates)
17754 return 0;
17756 dump () && dump ("Writing initializers");
17757 dump.indent ();
17759 static_aggregates = nreverse (static_aggregates);
17760 tls_aggregates = nreverse (tls_aggregates);
17762 unsigned count = 0;
17763 trees_out sec (to, this, table, ~0u);
17764 sec.begin ();
17766 tree list = static_aggregates;
17767 for (int passes = 0; passes != 2; passes++)
17769 for (tree init = list; init; init = TREE_CHAIN (init))
17770 if (TREE_LANG_FLAG_0 (init))
17772 tree decl = TREE_VALUE (init);
17774 dump ("Initializer:%u for %N", count, decl);
17775 sec.tree_node (decl);
17776 ++count;
17779 list = tls_aggregates;
17782 sec.end (to, to->name (MOD_SNAME_PFX ".ini"), crc_ptr);
17783 dump.outdent ();
17785 return count;
17788 /* We have to defer some post-load processing until we've completed
17789 reading, because they can cause more reading. */
17791 static void
17792 post_load_processing ()
17794 /* We mustn't cause a GC, our caller should have arranged for that
17795 not to happen. */
17796 gcc_checking_assert (function_depth);
17798 if (!post_load_decls)
17799 return;
17801 tree old_cfd = current_function_decl;
17802 struct function *old_cfun = cfun;
17803 while (post_load_decls->length ())
17805 tree decl = post_load_decls->pop ();
17807 dump () && dump ("Post-load processing of %N", decl);
17809 gcc_checking_assert (DECL_ABSTRACT_P (decl));
17810 /* Cloning can cause loading -- specifically operator delete for
17811 the deleting dtor. */
17812 maybe_clone_body (decl);
17815 cfun = old_cfun;
17816 current_function_decl = old_cfd;
17819 bool
17820 module_state::read_inits (unsigned count)
17822 trees_in sec (this);
17823 if (!sec.begin (loc, from (), from ()->find (MOD_SNAME_PFX ".ini")))
17824 return false;
17825 dump () && dump ("Reading %u initializers", count);
17826 dump.indent ();
17828 lazy_snum = ~0u;
17829 for (unsigned ix = 0; ix != count; ix++)
17831 /* Merely referencing the decl causes its initializer to be read
17832 and added to the correct list. */
17833 tree decl = sec.tree_node ();
17835 if (sec.get_overrun ())
17836 break;
17837 if (decl)
17838 dump ("Initializer:%u for %N", count, decl);
17840 lazy_snum = 0;
17841 post_load_processing ();
17842 dump.outdent ();
17843 if (!sec.end (from ()))
17844 return false;
17845 return true;
17848 void
17849 module_state::write_counts (elf_out *to, unsigned counts[MSC_HWM],
17850 unsigned *crc_ptr)
17852 bytes_out cfg (to);
17854 cfg.begin ();
17856 for (unsigned ix = MSC_HWM; ix--;)
17857 cfg.u (counts[ix]);
17859 if (dump ())
17861 dump ("Cluster sections are [%u,%u)",
17862 counts[MSC_sec_lwm], counts[MSC_sec_hwm]);
17863 dump ("Bindings %u", counts[MSC_bindings]);
17864 dump ("Pendings %u", counts[MSC_pendings]);
17865 dump ("Entities %u", counts[MSC_entities]);
17866 dump ("Namespaces %u", counts[MSC_namespaces]);
17867 dump ("Macros %u", counts[MSC_macros]);
17868 dump ("Initializers %u", counts[MSC_inits]);
17871 cfg.end (to, to->name (MOD_SNAME_PFX ".cnt"), crc_ptr);
17874 bool
17875 module_state::read_counts (unsigned counts[MSC_HWM])
17877 bytes_in cfg;
17879 if (!cfg.begin (loc, from (), MOD_SNAME_PFX ".cnt"))
17880 return false;
17882 for (unsigned ix = MSC_HWM; ix--;)
17883 counts[ix] = cfg.u ();
17885 if (dump ())
17887 dump ("Declaration sections are [%u,%u)",
17888 counts[MSC_sec_lwm], counts[MSC_sec_hwm]);
17889 dump ("Bindings %u", counts[MSC_bindings]);
17890 dump ("Pendings %u", counts[MSC_pendings]);
17891 dump ("Entities %u", counts[MSC_entities]);
17892 dump ("Namespaces %u", counts[MSC_namespaces]);
17893 dump ("Macros %u", counts[MSC_macros]);
17894 dump ("Initializers %u", counts[MSC_inits]);
17897 return cfg.end (from ());
17900 /* Tool configuration: MOD_SNAME_PFX .config
17902 This is data that confirms current state (or fails). */
17904 void
17905 module_state::write_config (elf_out *to, module_state_config &config,
17906 unsigned inner_crc)
17908 bytes_out cfg (to);
17910 cfg.begin ();
17912 /* Write version and inner crc as u32 values, for easier
17913 debug inspection. */
17914 dump () && dump ("Writing version=%V, inner_crc=%x",
17915 MODULE_VERSION, inner_crc);
17916 cfg.u32 (unsigned (MODULE_VERSION));
17917 cfg.u32 (inner_crc);
17919 cfg.u (to->name (is_header () ? "" : get_flatname ()));
17921 /* Configuration. */
17922 dump () && dump ("Writing target='%s', host='%s'",
17923 TARGET_MACHINE, HOST_MACHINE);
17924 unsigned target = to->name (TARGET_MACHINE);
17925 unsigned host = (!strcmp (TARGET_MACHINE, HOST_MACHINE)
17926 ? target : to->name (HOST_MACHINE));
17927 cfg.u (target);
17928 cfg.u (host);
17930 cfg.str (config.dialect_str);
17931 cfg.u (extensions);
17933 /* Global tree information. We write the globals crc separately,
17934 rather than mix it directly into the overall crc, as it is used
17935 to ensure data match between instances of the compiler, not
17936 integrity of the file. */
17937 dump () && dump ("Writing globals=%u, crc=%x",
17938 fixed_trees->length (), global_crc);
17939 cfg.u (fixed_trees->length ());
17940 cfg.u32 (global_crc);
17942 if (is_partition ())
17943 cfg.u (is_interface ());
17945 cfg.u (config.num_imports);
17946 cfg.u (config.num_partitions);
17947 cfg.u (config.num_entities);
17949 cfg.u (config.ordinary_locs);
17950 cfg.u (config.macro_locs);
17951 cfg.u (config.loc_range_bits);
17953 cfg.u (config.active_init);
17955 /* Now generate CRC, we'll have incorporated the inner CRC because
17956 of its serialization above. */
17957 cfg.end (to, to->name (MOD_SNAME_PFX ".cfg"), &crc);
17958 dump () && dump ("Writing CRC=%x", crc);
17961 void
17962 module_state::note_cmi_name ()
17964 if (!cmi_noted_p && filename)
17966 cmi_noted_p = true;
17967 inform (loc, "compiled module file is %qs",
17968 maybe_add_cmi_prefix (filename));
17972 bool
17973 module_state::read_config (module_state_config &config)
17975 bytes_in cfg;
17977 if (!cfg.begin (loc, from (), MOD_SNAME_PFX ".cfg"))
17978 return false;
17980 /* Check version. */
17981 unsigned my_ver = MODULE_VERSION;
17982 unsigned their_ver = cfg.u32 ();
17983 dump () && dump (my_ver == their_ver ? "Version %V"
17984 : "Expecting %V found %V", my_ver, their_ver);
17985 if (their_ver != my_ver)
17987 /* The compiler versions differ. Close enough? */
17988 verstr_t my_string, their_string;
17990 version2string (my_ver, my_string);
17991 version2string (their_ver, their_string);
17993 /* Reject when either is non-experimental or when experimental
17994 major versions differ. */
17995 bool reject_p = ((!IS_EXPERIMENTAL (my_ver)
17996 || !IS_EXPERIMENTAL (their_ver)
17997 || MODULE_MAJOR (my_ver) != MODULE_MAJOR (their_ver))
17998 /* The 'I know what I'm doing' switch. */
17999 && !flag_module_version_ignore);
18000 bool inform_p = true;
18001 if (reject_p)
18003 cfg.set_overrun ();
18004 error_at (loc, "compiled module is %sversion %s",
18005 IS_EXPERIMENTAL (their_ver) ? "experimental " : "",
18006 their_string);
18008 else
18009 inform_p = warning_at (loc, 0, "compiled module is %sversion %s",
18010 IS_EXPERIMENTAL (their_ver) ? "experimental " : "",
18011 their_string);
18013 if (inform_p)
18015 inform (loc, "compiler is %sversion %s%s%s",
18016 IS_EXPERIMENTAL (my_ver) ? "experimental " : "",
18017 my_string,
18018 reject_p ? "" : flag_module_version_ignore
18019 ? ", be it on your own head!" : ", close enough?",
18020 reject_p ? "" : " \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf");
18021 note_cmi_name ();
18024 if (reject_p)
18025 goto done;
18028 /* We wrote the inner crc merely to merge it, so simply read it
18029 back and forget it. */
18030 cfg.u32 ();
18032 /* Check module name. */
18034 const char *their_name = from ()->name (cfg.u ());
18035 const char *our_name = "";
18037 if (!is_header ())
18038 our_name = get_flatname ();
18040 /* Header units can be aliased, so name checking is
18041 inappropriate. */
18042 if (0 != strcmp (their_name, our_name))
18044 error_at (loc,
18045 their_name[0] && our_name[0] ? G_("module %qs found")
18046 : their_name[0]
18047 ? G_("header module expected, module %qs found")
18048 : G_("module %qs expected, header module found"),
18049 their_name[0] ? their_name : our_name);
18050 cfg.set_overrun ();
18051 goto done;
18055 /* Check the CRC after the above sanity checks, so that the user is
18056 clued in. */
18058 unsigned e_crc = crc;
18059 crc = cfg.get_crc ();
18060 dump () && dump ("Reading CRC=%x", crc);
18061 if (!is_direct () && crc != e_crc)
18063 error_at (loc, "module %qs CRC mismatch", get_flatname ());
18064 cfg.set_overrun ();
18065 goto done;
18069 /* Check target & host. */
18071 const char *their_target = from ()->name (cfg.u ());
18072 const char *their_host = from ()->name (cfg.u ());
18073 dump () && dump ("Read target='%s', host='%s'", their_target, their_host);
18074 if (strcmp (their_target, TARGET_MACHINE)
18075 || strcmp (their_host, HOST_MACHINE))
18077 error_at (loc, "target & host is %qs:%qs, expected %qs:%qs",
18078 their_target, TARGET_MACHINE, their_host, HOST_MACHINE);
18079 cfg.set_overrun ();
18080 goto done;
18084 /* Check compilation dialect. This must match. */
18086 const char *their_dialect = cfg.str ();
18087 if (strcmp (their_dialect, config.dialect_str))
18089 error_at (loc, "language dialect differs %qs, expected %qs",
18090 their_dialect, config.dialect_str);
18091 cfg.set_overrun ();
18092 goto done;
18096 /* Check for extensions. If they set any, we must have them set
18097 too. */
18099 unsigned ext = cfg.u ();
18100 unsigned allowed = (flag_openmp ? SE_OPENMP : 0);
18102 if (unsigned bad = ext & ~allowed)
18104 if (bad & SE_OPENMP)
18105 error_at (loc, "module contains OpenMP, use %<-fopenmp%> to enable");
18106 cfg.set_overrun ();
18107 goto done;
18109 extensions = ext;
18112 /* Check global trees. */
18114 unsigned their_fixed_length = cfg.u ();
18115 unsigned their_fixed_crc = cfg.u32 ();
18116 dump () && dump ("Read globals=%u, crc=%x",
18117 their_fixed_length, their_fixed_crc);
18118 if (!flag_preprocess_only
18119 && (their_fixed_length != fixed_trees->length ()
18120 || their_fixed_crc != global_crc))
18122 error_at (loc, "fixed tree mismatch");
18123 cfg.set_overrun ();
18124 goto done;
18128 /* All non-partitions are interfaces. */
18129 interface_p = !is_partition () || cfg.u ();
18131 config.num_imports = cfg.u ();
18132 config.num_partitions = cfg.u ();
18133 config.num_entities = cfg.u ();
18135 config.ordinary_locs = cfg.u ();
18136 config.macro_locs = cfg.u ();
18137 config.loc_range_bits = cfg.u ();
18139 config.active_init = cfg.u ();
18141 done:
18142 return cfg.end (from ());
18145 /* Comparator for ordering the Ordered Ordinary Location array. */
18147 static int
18148 ool_cmp (const void *a_, const void *b_)
18150 auto *a = *static_cast<const module_state *const *> (a_);
18151 auto *b = *static_cast<const module_state *const *> (b_);
18152 if (a == b)
18153 return 0;
18154 else if (a->ordinary_locs.first < b->ordinary_locs.first)
18155 return -1;
18156 else
18157 return +1;
18160 /* Use ELROND format to record the following sections:
18161 qualified-names : binding value(s)
18162 MOD_SNAME_PFX.README : human readable, strings
18163 MOD_SNAME_PFX.ENV : environment strings, strings
18164 MOD_SNAME_PFX.nms : namespace hierarchy
18165 MOD_SNAME_PFX.bnd : binding table
18166 MOD_SNAME_PFX.spc : specialization table
18167 MOD_SNAME_PFX.imp : import table
18168 MOD_SNAME_PFX.ent : entity table
18169 MOD_SNAME_PFX.prt : partitions table
18170 MOD_SNAME_PFX.olm : ordinary line maps
18171 MOD_SNAME_PFX.mlm : macro line maps
18172 MOD_SNAME_PFX.def : macro definitions
18173 MOD_SNAME_PFX.mac : macro index
18174 MOD_SNAME_PFX.ini : inits
18175 MOD_SNAME_PFX.cnt : counts
18176 MOD_SNAME_PFX.cfg : config data
18179 void
18180 module_state::write_begin (elf_out *to, cpp_reader *reader,
18181 module_state_config &config, unsigned &crc)
18183 /* Figure out remapped module numbers, which might elide
18184 partitions. */
18185 bitmap partitions = NULL;
18186 if (!is_header () && !is_partition ())
18187 partitions = BITMAP_GGC_ALLOC ();
18188 write_init_maps ();
18190 unsigned mod_hwm = 1;
18191 for (unsigned ix = 1; ix != modules->length (); ix++)
18193 module_state *imp = (*modules)[ix];
18195 /* Promote any non-partition direct import from a partition, unless
18196 we're a partition. */
18197 if (!is_partition () && !imp->is_partition ()
18198 && imp->is_partition_direct ())
18199 imp->directness = MD_PURVIEW_DIRECT;
18201 /* Write any import that is not a partition, unless we're a
18202 partition. */
18203 if (!partitions || !imp->is_partition ())
18204 imp->remap = mod_hwm++;
18205 else
18207 dump () && dump ("Partition %M %u", imp, ix);
18208 bitmap_set_bit (partitions, ix);
18209 imp->remap = 0;
18210 /* All interface partitions must be exported. */
18211 if (imp->is_interface () && !bitmap_bit_p (exports, imp->mod))
18213 error_at (imp->loc, "interface partition is not exported");
18214 bitmap_set_bit (exports, imp->mod);
18217 /* All the partition entities should have been loaded when
18218 loading the partition. */
18219 if (CHECKING_P)
18220 for (unsigned jx = 0; jx != imp->entity_num; jx++)
18222 binding_slot *slot = &(*entity_ary)[imp->entity_lwm + jx];
18223 gcc_checking_assert (!slot->is_lazy ());
18227 if (imp->is_direct () && (imp->remap || imp->is_partition ()))
18228 note_location (imp->imported_from ());
18231 if (partitions && bitmap_empty_p (partitions))
18232 /* No partitions present. */
18233 partitions = nullptr;
18235 /* Find the set of decls we must write out. */
18236 depset::hash table (DECL_NAMESPACE_BINDINGS (global_namespace)->size () * 8);
18237 /* Add the specializations before the writables, so that we can
18238 detect injected friend specializations. */
18239 table.add_specializations (true);
18240 table.add_specializations (false);
18241 if (partial_specializations)
18243 table.add_partial_entities (partial_specializations);
18244 partial_specializations = NULL;
18246 table.add_namespace_entities (global_namespace, partitions);
18247 if (class_members)
18249 table.add_class_entities (class_members);
18250 class_members = NULL;
18253 /* Now join everything up. */
18254 table.find_dependencies (this);
18256 if (!table.finalize_dependencies ())
18258 to->set_error ();
18259 return;
18262 #if CHECKING_P
18263 /* We're done verifying at-most once reading, reset to verify
18264 at-most once writing. */
18265 note_defs = note_defs_table_t::create_ggc (1000);
18266 #endif
18268 /* Determine Strongy Connected Components. */
18269 vec<depset *> sccs = table.connect ();
18271 vec_alloc (ool, modules->length ());
18272 for (unsigned ix = modules->length (); --ix;)
18274 auto *import = (*modules)[ix];
18275 if (import->loadedness > ML_NONE
18276 && !(partitions && bitmap_bit_p (partitions, import->mod)))
18277 ool->quick_push (import);
18279 ool->qsort (ool_cmp);
18281 vec<cpp_hashnode *> *macros = nullptr;
18282 if (is_header ())
18283 macros = prepare_macros (reader);
18285 config.num_imports = mod_hwm;
18286 config.num_partitions = modules->length () - mod_hwm;
18287 auto map_info = write_prepare_maps (&config, bool (config.num_partitions));
18288 unsigned counts[MSC_HWM];
18289 memset (counts, 0, sizeof (counts));
18291 /* depset::cluster is the cluster number,
18292 depset::section is unspecified scratch value.
18294 The following loops make use of the tarjan property that
18295 dependencies will be earlier in the SCCS array. */
18297 /* This first loop determines the number of depsets in each SCC, and
18298 also the number of namespaces we're dealing with. During the
18299 loop, the meaning of a couple of depset fields now change:
18301 depset::cluster -> size_of cluster, if first of cluster & !namespace
18302 depset::section -> section number of cluster (if !namespace). */
18304 unsigned n_spaces = 0;
18305 counts[MSC_sec_lwm] = counts[MSC_sec_hwm] = to->get_section_limit ();
18306 for (unsigned size, ix = 0; ix < sccs.length (); ix += size)
18308 depset **base = &sccs[ix];
18310 if (base[0]->get_entity_kind () == depset::EK_NAMESPACE)
18312 n_spaces++;
18313 size = 1;
18315 else
18317 /* Count the members in this cluster. */
18318 for (size = 1; ix + size < sccs.length (); size++)
18319 if (base[size]->cluster != base[0]->cluster)
18320 break;
18322 for (unsigned jx = 0; jx != size; jx++)
18324 /* Set the section number. */
18325 base[jx]->cluster = ~(~0u >> 1); /* A bad value. */
18326 base[jx]->section = counts[MSC_sec_hwm];
18329 /* Save the size in the first member's cluster slot. */
18330 base[0]->cluster = size;
18332 counts[MSC_sec_hwm]++;
18336 /* Write the clusters. Namespace decls are put in the spaces array.
18337 The meaning of depset::cluster changes to provide the
18338 unnamed-decl count of the depset's decl (and remains zero for
18339 non-decls and non-unnamed). */
18340 unsigned bytes = 0;
18341 vec<depset *> spaces;
18342 spaces.create (n_spaces);
18344 for (unsigned size, ix = 0; ix < sccs.length (); ix += size)
18346 depset **base = &sccs[ix];
18348 if (base[0]->get_entity_kind () == depset::EK_NAMESPACE)
18350 tree decl = base[0]->get_entity ();
18351 if (decl == global_namespace)
18352 base[0]->cluster = 0;
18353 else if (!base[0]->is_import ())
18355 base[0]->cluster = counts[MSC_entities]++;
18356 spaces.quick_push (base[0]);
18357 counts[MSC_namespaces]++;
18358 if (CHECKING_P)
18360 /* Add it to the entity map, such that we can tell it is
18361 part of us. */
18362 bool existed;
18363 unsigned *slot = &entity_map->get_or_insert
18364 (DECL_UID (decl), &existed);
18365 if (existed)
18366 /* It must have come from a partition. */
18367 gcc_checking_assert
18368 (import_entity_module (*slot)->is_partition ());
18369 *slot = ~base[0]->cluster;
18371 dump (dumper::CLUSTER) && dump ("Cluster namespace %N", decl);
18373 size = 1;
18375 else
18377 size = base[0]->cluster;
18379 /* Cluster is now used to number entities. */
18380 base[0]->cluster = ~(~0u >> 1); /* A bad value. */
18382 sort_cluster (&table, base, size);
18384 /* Record the section for consistency checking during stream
18385 out -- we don't want to start writing decls in different
18386 sections. */
18387 table.section = base[0]->section;
18388 bytes += write_cluster (to, base, size, table, counts, &crc);
18389 table.section = 0;
18393 /* depset::cluster - entity number (on entities)
18394 depset::section - cluster number */
18395 /* We'd better have written as many sections and found as many
18396 namespaces as we predicted. */
18397 gcc_assert (counts[MSC_sec_hwm] == to->get_section_limit ()
18398 && spaces.length () == counts[MSC_namespaces]);
18400 /* Write the entitites. None happens if we contain namespaces or
18401 nothing. */
18402 config.num_entities = counts[MSC_entities];
18403 if (counts[MSC_entities])
18404 write_entities (to, sccs, counts[MSC_entities], &crc);
18406 /* Write the namespaces. */
18407 if (counts[MSC_namespaces])
18408 write_namespaces (to, spaces, counts[MSC_namespaces], &crc);
18410 /* Write the bindings themselves. */
18411 counts[MSC_bindings] = write_bindings (to, sccs, &crc);
18413 /* Write the unnamed. */
18414 counts[MSC_pendings] = write_pendings (to, sccs, table, &crc);
18416 /* Write the import table. */
18417 if (config.num_imports > 1)
18418 write_imports (to, &crc);
18420 /* Write elided partition table. */
18421 if (config.num_partitions)
18422 write_partitions (to, config.num_partitions, &crc);
18424 /* Write the line maps. */
18425 if (config.ordinary_locs)
18426 write_ordinary_maps (to, map_info, bool (config.num_partitions), &crc);
18427 if (config.macro_locs)
18428 write_macro_maps (to, map_info, &crc);
18430 if (is_header ())
18432 counts[MSC_macros] = write_macros (to, macros, &crc);
18433 counts[MSC_inits] = write_inits (to, table, &crc);
18434 vec_free (macros);
18437 unsigned clusters = counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
18438 dump () && dump ("Wrote %u clusters, average %u bytes/cluster",
18439 clusters, (bytes + clusters / 2) / (clusters + !clusters));
18440 trees_out::instrument ();
18442 write_counts (to, counts, &crc);
18444 spaces.release ();
18445 sccs.release ();
18447 vec_free (macro_loc_remap);
18448 vec_free (ord_loc_remap);
18449 vec_free (ool);
18451 // FIXME:QOI: Have a command line switch to control more detailed
18452 // information (which might leak data you do not want to leak).
18453 // Perhaps (some of) the write_readme contents should also be
18454 // so-controlled.
18455 if (false)
18456 write_env (to);
18459 // Finish module writing after we've emitted all dynamic initializers.
18461 void
18462 module_state::write_end (elf_out *to, cpp_reader *reader,
18463 module_state_config &config, unsigned &crc)
18465 /* And finish up. */
18466 write_config (to, config, crc);
18468 /* Human-readable info. */
18469 write_readme (to, reader, config.dialect_str);
18471 dump () && dump ("Wrote %u sections", to->get_section_limit ());
18474 /* Initial read of a CMI. Checks config, loads up imports and line
18475 maps. */
18477 bool
18478 module_state::read_initial (cpp_reader *reader)
18480 module_state_config config;
18481 bool ok = true;
18483 if (ok && !from ()->begin (loc))
18484 ok = false;
18486 if (ok && !read_config (config))
18487 ok = false;
18489 bool have_locs = ok && read_prepare_maps (&config);
18491 /* Ordinary maps before the imports. */
18492 if (!(have_locs && config.ordinary_locs))
18493 ordinary_locs.first = line_table->highest_location + 1;
18494 else if (!read_ordinary_maps (config.ordinary_locs, config.loc_range_bits))
18495 ok = false;
18497 /* Allocate the REMAP vector. */
18498 slurp->alloc_remap (config.num_imports);
18500 if (ok)
18502 /* Read the import table. Decrement current to stop this CMI
18503 from being evicted during the import. */
18504 slurp->current--;
18505 if (config.num_imports > 1 && !read_imports (reader, line_table))
18506 ok = false;
18507 slurp->current++;
18510 /* Read the elided partition table, if we're the primary partition. */
18511 if (ok && config.num_partitions && is_module ()
18512 && !read_partitions (config.num_partitions))
18513 ok = false;
18515 /* Determine the module's number. */
18516 gcc_checking_assert (mod == MODULE_UNKNOWN);
18517 gcc_checking_assert (this != (*modules)[0]);
18520 /* Allocate space in the entities array now -- that array must be
18521 monotonically in step with the modules array. */
18522 entity_lwm = vec_safe_length (entity_ary);
18523 entity_num = config.num_entities;
18524 gcc_checking_assert (modules->length () == 1
18525 || modules->last ()->entity_lwm <= entity_lwm);
18526 vec_safe_reserve (entity_ary, config.num_entities);
18528 binding_slot slot;
18529 slot.u.binding = NULL_TREE;
18530 for (unsigned count = config.num_entities; count--;)
18531 entity_ary->quick_push (slot);
18534 /* We'll run out of other resources before we run out of module
18535 indices. */
18536 mod = modules->length ();
18537 vec_safe_push (modules, this);
18539 /* We always import and export ourselves. */
18540 bitmap_set_bit (imports, mod);
18541 bitmap_set_bit (exports, mod);
18543 if (ok)
18544 (*slurp->remap)[0] = mod << 1;
18545 dump () && dump ("Assigning %M module number %u", this, mod);
18547 /* We should not have been frozen during the importing done by
18548 read_config. */
18549 gcc_assert (!from ()->is_frozen ());
18551 /* Macro maps after the imports. */
18552 if (!(ok && have_locs && config.macro_locs))
18553 macro_locs.first = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
18554 else if (!read_macro_maps (config.macro_locs))
18555 ok = false;
18557 /* Note whether there's an active initializer. */
18558 active_init_p = !is_header () && bool (config.active_init);
18560 gcc_assert (slurp->current == ~0u);
18561 return ok;
18564 /* Read a preprocessor state. */
18566 bool
18567 module_state::read_preprocessor (bool outermost)
18569 gcc_checking_assert (is_header () && slurp
18570 && slurp->remap_module (0) == mod);
18572 if (loadedness == ML_PREPROCESSOR)
18573 return !(from () && from ()->get_error ());
18575 bool ok = true;
18577 /* Read direct header imports. */
18578 unsigned len = slurp->remap->length ();
18579 for (unsigned ix = 1; ok && ix != len; ix++)
18581 unsigned map = (*slurp->remap)[ix];
18582 if (map & 1)
18584 module_state *import = (*modules)[map >> 1];
18585 if (import->is_header ())
18587 ok = import->read_preprocessor (false);
18588 bitmap_ior_into (slurp->headers, import->slurp->headers);
18593 /* Record as a direct header. */
18594 if (ok)
18595 bitmap_set_bit (slurp->headers, mod);
18597 if (ok && !read_macros ())
18598 ok = false;
18600 loadedness = ML_PREPROCESSOR;
18601 announce ("macros");
18603 if (flag_preprocess_only)
18604 /* We're done with the string table. */
18605 from ()->release ();
18607 return check_read (outermost, ok);
18610 /* Read language state. */
18612 bool
18613 module_state::read_language (bool outermost)
18615 gcc_checking_assert (!lazy_snum);
18617 if (loadedness == ML_LANGUAGE)
18618 return !(slurp && from () && from ()->get_error ());
18620 gcc_checking_assert (slurp && slurp->current == ~0u
18621 && slurp->remap_module (0) == mod);
18623 bool ok = true;
18625 /* Read direct imports. */
18626 unsigned len = slurp->remap->length ();
18627 for (unsigned ix = 1; ok && ix != len; ix++)
18629 unsigned map = (*slurp->remap)[ix];
18630 if (map & 1)
18632 module_state *import = (*modules)[map >> 1];
18633 if (!import->read_language (false))
18634 ok = false;
18638 unsigned counts[MSC_HWM];
18640 if (ok && !read_counts (counts))
18641 ok = false;
18643 function_depth++; /* Prevent unexpected GCs. */
18645 if (ok && counts[MSC_entities] != entity_num)
18646 ok = false;
18647 if (ok && counts[MSC_entities]
18648 && !read_entities (counts[MSC_entities],
18649 counts[MSC_sec_lwm], counts[MSC_sec_hwm]))
18650 ok = false;
18652 /* Read the namespace hierarchy. */
18653 if (ok && counts[MSC_namespaces]
18654 && !read_namespaces (counts[MSC_namespaces]))
18655 ok = false;
18657 if (ok && !read_bindings (counts[MSC_bindings],
18658 counts[MSC_sec_lwm], counts[MSC_sec_hwm]))
18659 ok = false;
18661 /* And unnamed. */
18662 if (ok && counts[MSC_pendings] && !read_pendings (counts[MSC_pendings]))
18663 ok = false;
18665 if (ok)
18667 slurp->remaining = counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
18668 available_clusters += counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
18671 if (!flag_module_lazy
18672 || (is_partition ()
18673 && module_interface_p ()
18674 && !module_partition_p ()))
18676 /* Read the sections in forward order, so that dependencies are read
18677 first. See note about tarjan_connect. */
18678 ggc_collect ();
18680 lazy_snum = ~0u;
18682 unsigned hwm = counts[MSC_sec_hwm];
18683 for (unsigned ix = counts[MSC_sec_lwm]; ok && ix != hwm; ix++)
18684 if (!load_section (ix, NULL))
18686 ok = false;
18687 break;
18689 lazy_snum = 0;
18690 post_load_processing ();
18692 ggc_collect ();
18694 if (ok && CHECKING_P)
18695 for (unsigned ix = 0; ix != entity_num; ix++)
18696 gcc_assert (!(*entity_ary)[ix + entity_lwm].is_lazy ());
18699 // If the import is a header-unit, we need to register initializers
18700 // of any static objects it contains (looking at you _Ioinit).
18701 // Notice, the ordering of these initializers will be that of a
18702 // dynamic initializer at this point in the current TU. (Other
18703 // instances of these objects in other TUs will be initialized as
18704 // part of that TU's global initializers.)
18705 if (ok && counts[MSC_inits] && !read_inits (counts[MSC_inits]))
18706 ok = false;
18708 function_depth--;
18710 announce (flag_module_lazy ? "lazy" : "imported");
18711 loadedness = ML_LANGUAGE;
18713 gcc_assert (slurp->current == ~0u);
18715 /* We're done with the string table. */
18716 from ()->release ();
18718 return check_read (outermost, ok);
18721 bool
18722 module_state::maybe_defrost ()
18724 bool ok = true;
18725 if (from ()->is_frozen ())
18727 if (lazy_open >= lazy_limit)
18728 freeze_an_elf ();
18729 dump () && dump ("Defrosting '%s'", filename);
18730 ok = from ()->defrost (maybe_add_cmi_prefix (filename));
18731 lazy_open++;
18734 return ok;
18737 /* Load section SNUM, dealing with laziness. It doesn't matter if we
18738 have multiple concurrent loads, because we do not use TREE_VISITED
18739 when reading back in. */
18741 bool
18742 module_state::load_section (unsigned snum, binding_slot *mslot)
18744 if (from ()->get_error ())
18745 return false;
18747 if (snum >= slurp->current)
18748 from ()->set_error (elf::E_BAD_LAZY);
18749 else if (maybe_defrost ())
18751 unsigned old_current = slurp->current;
18752 slurp->current = snum;
18753 slurp->lru = 0; /* Do not swap out. */
18754 slurp->remaining--;
18755 read_cluster (snum);
18756 slurp->lru = ++lazy_lru;
18757 slurp->current = old_current;
18760 if (mslot && mslot->is_lazy ())
18762 /* Oops, the section didn't set this slot. */
18763 from ()->set_error (elf::E_BAD_DATA);
18764 *mslot = NULL_TREE;
18767 bool ok = !from ()->get_error ();
18768 if (!ok)
18770 error_at (loc, "failed to read compiled module cluster %u: %s",
18771 snum, from ()->get_error (filename));
18772 note_cmi_name ();
18775 maybe_completed_reading ();
18777 return ok;
18780 void
18781 module_state::maybe_completed_reading ()
18783 if (loadedness == ML_LANGUAGE && slurp->current == ~0u && !slurp->remaining)
18785 lazy_open--;
18786 /* We no longer need the macros, all tokenizing has been done. */
18787 slurp->release_macros ();
18789 from ()->end ();
18790 slurp->close ();
18791 slurped ();
18795 /* After a reading operation, make sure things are still ok. If not,
18796 emit an error and clean up. */
18798 bool
18799 module_state::check_read (bool outermost, bool ok)
18801 gcc_checking_assert (!outermost || slurp->current == ~0u);
18803 if (!ok)
18804 from ()->set_error ();
18806 if (int e = from ()->get_error ())
18808 error_at (loc, "failed to read compiled module: %s",
18809 from ()->get_error (filename));
18810 note_cmi_name ();
18812 if (e == EMFILE
18813 || e == ENFILE
18814 #if MAPPED_READING
18815 || e == ENOMEM
18816 #endif
18817 || false)
18818 inform (loc, "consider using %<-fno-module-lazy%>,"
18819 " increasing %<-param-lazy-modules=%u%> value,"
18820 " or increasing the per-process file descriptor limit",
18821 param_lazy_modules);
18822 else if (e == ENOENT)
18823 inform (loc, "imports must be built before being imported");
18825 if (outermost)
18826 fatal_error (loc, "returning to the gate for a mechanical issue");
18828 ok = false;
18831 maybe_completed_reading ();
18833 return ok;
18836 /* Return the IDENTIFIER_NODE naming module IX. This is the name
18837 including dots. */
18839 char const *
18840 module_name (unsigned ix, bool header_ok)
18842 if (modules)
18844 module_state *imp = (*modules)[ix];
18846 if (ix && !imp->name)
18847 imp = imp->parent;
18849 if (header_ok || !imp->is_header ())
18850 return imp->get_flatname ();
18853 return NULL;
18856 /* Return the bitmap describing what modules are imported. Remember,
18857 we always import ourselves. */
18859 bitmap
18860 get_import_bitmap ()
18862 return (*modules)[0]->imports;
18865 /* Return the visible imports and path of instantiation for an
18866 instantiation at TINST. If TINST is nullptr, we're not in an
18867 instantiation, and thus will return the visible imports of the
18868 current TU (and NULL *PATH_MAP_P). We cache the information on
18869 the tinst level itself. */
18871 static bitmap
18872 path_of_instantiation (tinst_level *tinst, bitmap *path_map_p)
18874 gcc_checking_assert (modules_p ());
18876 if (!tinst)
18878 /* Not inside an instantiation, just the regular case. */
18879 *path_map_p = nullptr;
18880 return get_import_bitmap ();
18883 if (!tinst->path)
18885 /* Calculate. */
18886 bitmap visible = path_of_instantiation (tinst->next, path_map_p);
18887 bitmap path_map = *path_map_p;
18889 if (!path_map)
18891 path_map = BITMAP_GGC_ALLOC ();
18892 bitmap_set_bit (path_map, 0);
18895 tree decl = tinst->tldcl;
18896 if (TREE_CODE (decl) == TREE_LIST)
18897 decl = TREE_PURPOSE (decl);
18898 if (TYPE_P (decl))
18899 decl = TYPE_NAME (decl);
18901 if (unsigned mod = get_originating_module (decl))
18902 if (!bitmap_bit_p (path_map, mod))
18904 /* This is brand new information! */
18905 bitmap new_path = BITMAP_GGC_ALLOC ();
18906 bitmap_copy (new_path, path_map);
18907 bitmap_set_bit (new_path, mod);
18908 path_map = new_path;
18910 bitmap imports = (*modules)[mod]->imports;
18911 if (bitmap_intersect_compl_p (imports, visible))
18913 /* IMPORTS contains additional modules to VISIBLE. */
18914 bitmap new_visible = BITMAP_GGC_ALLOC ();
18916 bitmap_ior (new_visible, visible, imports);
18917 visible = new_visible;
18921 tinst->path = path_map;
18922 tinst->visible = visible;
18925 *path_map_p = tinst->path;
18926 return tinst->visible;
18929 /* Return the bitmap describing what modules are visible along the
18930 path of instantiation. If we're not an instantiation, this will be
18931 the visible imports of the TU. *PATH_MAP_P is filled in with the
18932 modules owning the instantiation path -- we see the module-linkage
18933 entities of those modules. */
18935 bitmap
18936 visible_instantiation_path (bitmap *path_map_p)
18938 if (!modules_p ())
18939 return NULL;
18941 return path_of_instantiation (current_instantiation (), path_map_p);
18944 /* We've just directly imported IMPORT. Update our import/export
18945 bitmaps. IS_EXPORT is true if we're reexporting the OTHER. */
18947 void
18948 module_state::set_import (module_state const *import, bool is_export)
18950 gcc_checking_assert (this != import);
18952 /* We see IMPORT's exports (which includes IMPORT). If IMPORT is
18953 the primary interface or a partition we'll see its imports. */
18954 bitmap_ior_into (imports, import->is_module () || import->is_partition ()
18955 ? import->imports : import->exports);
18957 if (is_export)
18958 /* We'll export OTHER's exports. */
18959 bitmap_ior_into (exports, import->exports);
18962 /* Return the declaring entity of DECL. That is the decl determining
18963 how to decorate DECL with module information. Returns NULL_TREE if
18964 it's the global module. */
18966 tree
18967 get_originating_module_decl (tree decl)
18969 /* An enumeration constant. */
18970 if (TREE_CODE (decl) == CONST_DECL
18971 && DECL_CONTEXT (decl)
18972 && (TREE_CODE (DECL_CONTEXT (decl)) == ENUMERAL_TYPE))
18973 decl = TYPE_NAME (DECL_CONTEXT (decl));
18974 else if (TREE_CODE (decl) == FIELD_DECL
18975 || TREE_CODE (decl) == USING_DECL
18976 || CONST_DECL_USING_P (decl))
18978 decl = DECL_CONTEXT (decl);
18979 if (TREE_CODE (decl) != FUNCTION_DECL)
18980 decl = TYPE_NAME (decl);
18983 gcc_checking_assert (TREE_CODE (decl) == TEMPLATE_DECL
18984 || TREE_CODE (decl) == FUNCTION_DECL
18985 || TREE_CODE (decl) == TYPE_DECL
18986 || TREE_CODE (decl) == VAR_DECL
18987 || TREE_CODE (decl) == CONCEPT_DECL
18988 || TREE_CODE (decl) == NAMESPACE_DECL);
18990 for (;;)
18992 /* Uninstantiated template friends are owned by the befriending
18993 class -- not their context. */
18994 if (TREE_CODE (decl) == TEMPLATE_DECL
18995 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
18996 decl = TYPE_NAME (DECL_CHAIN (decl));
18998 /* An imported temploid friend is attached to the same module the
18999 befriending class was. */
19000 if (imported_temploid_friends)
19001 if (tree *slot = imported_temploid_friends->get (decl))
19002 decl = *slot;
19004 int use;
19005 if (tree ti = node_template_info (decl, use))
19007 decl = TI_TEMPLATE (ti);
19008 if (TREE_CODE (decl) != TEMPLATE_DECL)
19010 /* A friend template specialization. */
19011 gcc_checking_assert (OVL_P (decl));
19012 return global_namespace;
19015 else
19017 tree ctx = CP_DECL_CONTEXT (decl);
19018 if (TREE_CODE (ctx) == NAMESPACE_DECL)
19019 break;
19021 if (TYPE_P (ctx))
19023 ctx = TYPE_NAME (ctx);
19024 if (!ctx)
19026 /* Some kind of internal type. */
19027 gcc_checking_assert (DECL_ARTIFICIAL (decl));
19028 return global_namespace;
19031 decl = ctx;
19035 return decl;
19039 get_originating_module (tree decl, bool for_mangle)
19041 tree owner = get_originating_module_decl (decl);
19042 tree not_tmpl = STRIP_TEMPLATE (owner);
19044 if (!DECL_LANG_SPECIFIC (not_tmpl))
19045 return for_mangle ? -1 : 0;
19047 if (for_mangle && !DECL_MODULE_ATTACH_P (not_tmpl))
19048 return -1;
19050 int mod = !DECL_MODULE_IMPORT_P (not_tmpl) ? 0 : get_importing_module (owner);
19051 gcc_checking_assert (!for_mangle || !(*modules)[mod]->is_header ());
19052 return mod;
19055 unsigned
19056 get_importing_module (tree decl, bool flexible)
19058 unsigned index = import_entity_index (decl, flexible);
19059 if (index == ~(~0u >> 1))
19060 return -1;
19061 module_state *module = import_entity_module (index);
19063 return module->mod;
19066 /* Is it permissible to redeclare OLDDECL with NEWDECL.
19068 If NEWDECL is NULL, assumes that OLDDECL will be redeclared using
19069 the current scope's module and attachment. */
19071 bool
19072 module_may_redeclare (tree olddecl, tree newdecl)
19074 tree decl = olddecl;
19075 for (;;)
19077 tree ctx = CP_DECL_CONTEXT (decl);
19078 if (TREE_CODE (ctx) == NAMESPACE_DECL)
19079 // Found the namespace-scope decl.
19080 break;
19081 if (!CLASS_TYPE_P (ctx))
19082 // We've met a non-class scope. Such a thing is not
19083 // reopenable, so we must be ok.
19084 return true;
19085 decl = TYPE_NAME (ctx);
19088 int use_tpl = 0;
19089 if (node_template_info (STRIP_TEMPLATE (decl), use_tpl) && use_tpl)
19090 // Specializations of any kind can be redeclared anywhere.
19091 // FIXME: Should we be checking this in more places on the scope chain?
19092 return true;
19094 module_state *old_mod = (*modules)[0];
19095 module_state *new_mod = old_mod;
19097 tree old_origin = get_originating_module_decl (decl);
19098 tree old_inner = STRIP_TEMPLATE (old_origin);
19099 bool olddecl_attached_p = (DECL_LANG_SPECIFIC (old_inner)
19100 && DECL_MODULE_ATTACH_P (old_inner));
19101 if (DECL_LANG_SPECIFIC (old_inner) && DECL_MODULE_IMPORT_P (old_inner))
19103 unsigned index = import_entity_index (old_origin);
19104 old_mod = import_entity_module (index);
19107 bool newdecl_attached_p = module_attach_p ();
19108 if (newdecl)
19110 tree new_origin = get_originating_module_decl (newdecl);
19111 tree new_inner = STRIP_TEMPLATE (new_origin);
19112 newdecl_attached_p = (DECL_LANG_SPECIFIC (new_inner)
19113 && DECL_MODULE_ATTACH_P (new_inner));
19114 if (DECL_LANG_SPECIFIC (new_inner) && DECL_MODULE_IMPORT_P (new_inner))
19116 unsigned index = import_entity_index (new_origin);
19117 new_mod = import_entity_module (index);
19121 /* Module attachment needs to match. */
19122 if (olddecl_attached_p == newdecl_attached_p)
19124 if (!olddecl_attached_p)
19125 /* Both are GM entities, OK. */
19126 return true;
19128 if (new_mod == old_mod
19129 || (new_mod && get_primary (new_mod) == get_primary (old_mod)))
19130 /* Both attached to same named module, OK. */
19131 return true;
19134 /* Attached to different modules, error. */
19135 decl = newdecl ? newdecl : olddecl;
19136 location_t loc = newdecl ? DECL_SOURCE_LOCATION (newdecl) : input_location;
19137 if (DECL_IS_UNDECLARED_BUILTIN (olddecl))
19138 error_at (loc, "declaration %qD conflicts with builtin", decl);
19139 else if (DECL_LANG_SPECIFIC (old_inner) && DECL_MODULE_IMPORT_P (old_inner))
19141 auto_diagnostic_group d;
19142 if (newdecl_attached_p)
19143 error_at (loc, "redeclaring %qD in module %qs conflicts with import",
19144 decl, new_mod->get_flatname ());
19145 else
19146 error_at (loc, "redeclaring %qD in global module conflicts with import",
19147 decl);
19149 if (olddecl_attached_p)
19150 inform (DECL_SOURCE_LOCATION (olddecl),
19151 "import declared attached to module %qs",
19152 old_mod->get_flatname ());
19153 else
19154 inform (DECL_SOURCE_LOCATION (olddecl),
19155 "import declared in global module");
19157 else
19159 auto_diagnostic_group d;
19160 if (newdecl_attached_p)
19161 error_at (loc, "conflicting declaration of %qD in module %qs",
19162 decl, new_mod->get_flatname ());
19163 else
19164 error_at (loc, "conflicting declaration of %qD in global module",
19165 decl);
19167 if (olddecl_attached_p)
19168 inform (DECL_SOURCE_LOCATION (olddecl),
19169 "previously declared in module %qs",
19170 old_mod->get_flatname ());
19171 else
19172 inform (DECL_SOURCE_LOCATION (olddecl),
19173 "previously declared in global module");
19175 return false;
19178 /* DECL is being created by this TU. Record it came from here. We
19179 record module purview, so we can see if partial or explicit
19180 specialization needs to be written out, even though its purviewness
19181 comes from the most general template. */
19183 void
19184 set_instantiating_module (tree decl)
19186 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
19187 || VAR_P (decl)
19188 || TREE_CODE (decl) == TYPE_DECL
19189 || TREE_CODE (decl) == CONCEPT_DECL
19190 || TREE_CODE (decl) == TEMPLATE_DECL
19191 || (TREE_CODE (decl) == NAMESPACE_DECL
19192 && DECL_NAMESPACE_ALIAS (decl)));
19194 if (!modules_p ())
19195 return;
19197 decl = STRIP_TEMPLATE (decl);
19199 if (!DECL_LANG_SPECIFIC (decl) && module_purview_p ())
19200 retrofit_lang_decl (decl);
19202 if (DECL_LANG_SPECIFIC (decl))
19204 DECL_MODULE_PURVIEW_P (decl) = module_purview_p ();
19205 /* If this was imported, we'll still be in the entity_hash. */
19206 DECL_MODULE_IMPORT_P (decl) = false;
19210 /* If DECL is a class member, whose class is not defined in this TU
19211 (it was imported), remember this decl. */
19213 void
19214 set_defining_module (tree decl)
19216 gcc_checking_assert (!DECL_LANG_SPECIFIC (decl)
19217 || !DECL_MODULE_IMPORT_P (decl));
19219 if (module_p ())
19221 /* We need to track all declarations within a module, not just those
19222 in the module purview, because we don't necessarily know yet if
19223 this module will require a CMI while in the global fragment. */
19224 tree ctx = DECL_CONTEXT (decl);
19225 if (ctx
19226 && (TREE_CODE (ctx) == RECORD_TYPE || TREE_CODE (ctx) == UNION_TYPE)
19227 && DECL_LANG_SPECIFIC (TYPE_NAME (ctx))
19228 && DECL_MODULE_IMPORT_P (TYPE_NAME (ctx)))
19230 /* This entity's context is from an import. We may need to
19231 record this entity to make sure we emit it in the CMI.
19232 Template specializations are in the template hash tables,
19233 so we don't need to record them here as well. */
19234 int use_tpl = -1;
19235 tree ti = node_template_info (decl, use_tpl);
19236 if (use_tpl <= 0)
19238 if (ti)
19240 gcc_checking_assert (!use_tpl);
19241 /* Get to the TEMPLATE_DECL. */
19242 decl = TI_TEMPLATE (ti);
19245 /* Record it on the class_members list. */
19246 vec_safe_push (class_members, decl);
19249 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
19250 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
19251 /* This is a partial or explicit specialization. */
19252 vec_safe_push (partial_specializations, decl);
19256 void
19257 set_originating_module (tree decl, bool friend_p ATTRIBUTE_UNUSED)
19259 set_instantiating_module (decl);
19261 if (!DECL_NAMESPACE_SCOPE_P (decl))
19262 return;
19264 gcc_checking_assert (friend_p || decl == get_originating_module_decl (decl));
19266 if (module_attach_p ())
19268 retrofit_lang_decl (decl);
19269 DECL_MODULE_ATTACH_P (decl) = true;
19272 if (!module_exporting_p ())
19273 return;
19275 // FIXME: Check ill-formed linkage
19276 DECL_MODULE_EXPORT_P (decl) = true;
19279 /* DECL is keyed to CTX for odr purposes. */
19281 void
19282 maybe_key_decl (tree ctx, tree decl)
19284 if (!modules_p ())
19285 return;
19287 /* We only need to deal with lambdas attached to var, field,
19288 parm, or type decls. */
19289 if (TREE_CODE (ctx) != VAR_DECL
19290 && TREE_CODE (ctx) != FIELD_DECL
19291 && TREE_CODE (ctx) != PARM_DECL
19292 && TREE_CODE (ctx) != TYPE_DECL)
19293 return;
19295 /* For fields, key it to the containing type to handle deduplication
19296 correctly. */
19297 if (TREE_CODE (ctx) == FIELD_DECL)
19298 ctx = TYPE_NAME (DECL_CONTEXT (ctx));
19300 if (!keyed_table)
19301 keyed_table = new keyed_map_t (EXPERIMENT (1, 400));
19303 auto &vec = keyed_table->get_or_insert (ctx);
19304 if (!vec.length ())
19306 retrofit_lang_decl (ctx);
19307 DECL_MODULE_KEYED_DECLS_P (ctx) = true;
19309 vec.safe_push (decl);
19312 /* DECL is an instantiated friend that should be attached to the same
19313 module that ORIG is. */
19315 void
19316 propagate_defining_module (tree decl, tree orig)
19318 if (!modules_p ())
19319 return;
19321 tree not_tmpl = STRIP_TEMPLATE (orig);
19322 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_ATTACH_P (not_tmpl))
19324 tree inner = STRIP_TEMPLATE (decl);
19325 retrofit_lang_decl (inner);
19326 DECL_MODULE_ATTACH_P (inner) = true;
19329 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_IMPORT_P (not_tmpl))
19331 bool exists = imported_temploid_friends->put (decl, orig);
19333 /* We should only be called if lookup for an existing decl
19334 failed, in which case there shouldn't already be an entry
19335 in the map. */
19336 gcc_assert (!exists);
19340 /* DECL is being freed, clear data we don't need anymore. */
19342 void
19343 remove_defining_module (tree decl)
19345 if (!modules_p ())
19346 return;
19348 if (imported_temploid_friends)
19349 imported_temploid_friends->remove (decl);
19352 /* Create the flat name string. It is simplest to have it handy. */
19354 void
19355 module_state::set_flatname ()
19357 gcc_checking_assert (!flatname);
19358 if (parent)
19360 auto_vec<tree,5> ids;
19361 size_t len = 0;
19362 char const *primary = NULL;
19363 size_t pfx_len = 0;
19365 for (module_state *probe = this;
19366 probe;
19367 probe = probe->parent)
19368 if (is_partition () && !probe->is_partition ())
19370 primary = probe->get_flatname ();
19371 pfx_len = strlen (primary);
19372 break;
19374 else
19376 ids.safe_push (probe->name);
19377 len += IDENTIFIER_LENGTH (probe->name) + 1;
19380 char *flat = XNEWVEC (char, pfx_len + len + is_partition ());
19381 flatname = flat;
19383 if (primary)
19385 memcpy (flat, primary, pfx_len);
19386 flat += pfx_len;
19387 *flat++ = ':';
19390 for (unsigned len = 0; ids.length ();)
19392 if (len)
19393 flat[len++] = '.';
19394 tree elt = ids.pop ();
19395 unsigned l = IDENTIFIER_LENGTH (elt);
19396 memcpy (flat + len, IDENTIFIER_POINTER (elt), l + 1);
19397 len += l;
19400 else if (is_header ())
19401 flatname = TREE_STRING_POINTER (name);
19402 else
19403 flatname = IDENTIFIER_POINTER (name);
19406 /* Read the CMI file for a module. */
19408 bool
19409 module_state::do_import (cpp_reader *reader, bool outermost)
19411 gcc_assert (global_namespace == current_scope () && loadedness == ML_NONE);
19413 loc = linemap_module_loc (line_table, loc, get_flatname ());
19415 if (lazy_open >= lazy_limit)
19416 freeze_an_elf ();
19418 int fd = -1;
19419 int e = ENOENT;
19420 if (filename)
19422 const char *file = maybe_add_cmi_prefix (filename);
19423 dump () && dump ("CMI is %s", file);
19424 if (note_module_cmi_yes || inform_cmi_p)
19425 inform (loc, "reading CMI %qs", file);
19426 /* Add the CMI file to the dependency tracking. */
19427 if (cpp_get_deps (reader))
19428 deps_add_dep (cpp_get_deps (reader), file);
19429 fd = open (file, O_RDONLY | O_CLOEXEC | O_BINARY);
19430 e = errno;
19433 gcc_checking_assert (!slurp);
19434 slurp = new slurping (new elf_in (fd, e));
19436 bool ok = true;
19437 if (!from ()->get_error ())
19439 announce ("importing");
19440 loadedness = ML_CONFIG;
19441 lazy_open++;
19442 ok = read_initial (reader);
19443 slurp->lru = ++lazy_lru;
19446 gcc_assert (slurp->current == ~0u);
19448 return check_read (outermost, ok);
19451 /* Attempt to increase the file descriptor limit. */
19453 static bool
19454 try_increase_lazy (unsigned want)
19456 gcc_checking_assert (lazy_open >= lazy_limit);
19458 /* If we're increasing, saturate at hard limit. */
19459 if (want > lazy_hard_limit && lazy_limit < lazy_hard_limit)
19460 want = lazy_hard_limit;
19462 #if HAVE_SETRLIMIT
19463 if ((!lazy_limit || !param_lazy_modules)
19464 && lazy_hard_limit
19465 && want <= lazy_hard_limit)
19467 struct rlimit rlimit;
19468 rlimit.rlim_cur = want + LAZY_HEADROOM;
19469 rlimit.rlim_max = lazy_hard_limit + LAZY_HEADROOM;
19470 if (!setrlimit (RLIMIT_NOFILE, &rlimit))
19471 lazy_limit = want;
19473 #endif
19475 return lazy_open < lazy_limit;
19478 /* Pick a victim module to freeze its reader. */
19480 void
19481 module_state::freeze_an_elf ()
19483 if (try_increase_lazy (lazy_open * 2))
19484 return;
19486 module_state *victim = NULL;
19487 for (unsigned ix = modules->length (); ix--;)
19489 module_state *candidate = (*modules)[ix];
19490 if (candidate && candidate->slurp && candidate->slurp->lru
19491 && candidate->from ()->is_freezable ()
19492 && (!victim || victim->slurp->lru > candidate->slurp->lru))
19493 victim = candidate;
19496 if (victim)
19498 dump () && dump ("Freezing '%s'", victim->filename);
19499 if (victim->slurp->macro_defs.size)
19500 /* Save the macro definitions to a buffer. */
19501 victim->from ()->preserve (victim->slurp->macro_defs);
19502 if (victim->slurp->macro_tbl.size)
19503 /* Save the macro definitions to a buffer. */
19504 victim->from ()->preserve (victim->slurp->macro_tbl);
19505 victim->from ()->freeze ();
19506 lazy_open--;
19508 else
19509 dump () && dump ("No module available for freezing");
19512 /* Load the lazy slot *MSLOT, INDEX'th slot of the module. */
19514 bool
19515 module_state::lazy_load (unsigned index, binding_slot *mslot)
19517 unsigned n = dump.push (this);
19519 gcc_checking_assert (function_depth);
19521 unsigned cookie = mslot->get_lazy ();
19522 unsigned snum = cookie >> 2;
19523 dump () && dump ("Loading entity %M[%u] section:%u", this, index, snum);
19525 bool ok = load_section (snum, mslot);
19527 dump.pop (n);
19529 return ok;
19532 /* Load MOD's binding for NS::ID into *MSLOT. *MSLOT contains the
19533 lazy cookie. OUTER is true if this is the outermost lazy, (used
19534 for diagnostics). */
19536 void
19537 lazy_load_binding (unsigned mod, tree ns, tree id, binding_slot *mslot)
19539 int count = errorcount + warningcount;
19541 timevar_start (TV_MODULE_IMPORT);
19543 /* Make sure lazy loading from a template context behaves as if
19544 from a non-template context. */
19545 processing_template_decl_sentinel ptds;
19547 /* Stop GC happening, even in outermost loads (because our caller
19548 could well be building up a lookup set). */
19549 function_depth++;
19551 gcc_checking_assert (mod);
19552 module_state *module = (*modules)[mod];
19553 unsigned n = dump.push (module);
19555 unsigned snum = mslot->get_lazy ();
19556 dump () && dump ("Lazily binding %P@%N section:%u", ns, id,
19557 module->name, snum);
19559 bool ok = !recursive_lazy (snum);
19560 if (ok)
19562 ok = module->load_section (snum, mslot);
19563 lazy_snum = 0;
19564 post_load_processing ();
19567 dump.pop (n);
19569 function_depth--;
19571 timevar_stop (TV_MODULE_IMPORT);
19573 if (!ok)
19574 fatal_error (input_location,
19575 module->is_header ()
19576 ? G_("failed to load binding %<%E%s%E%>")
19577 : G_("failed to load binding %<%E%s%E@%s%>"),
19578 ns, &"::"[ns == global_namespace ? 2 : 0], id,
19579 module->get_flatname ());
19581 if (count != errorcount + warningcount)
19582 inform (input_location,
19583 module->is_header ()
19584 ? G_("during load of binding %<%E%s%E%>")
19585 : G_("during load of binding %<%E%s%E@%s%>"),
19586 ns, &"::"[ns == global_namespace ? 2 : 0], id,
19587 module->get_flatname ());
19590 /* Load any pending entities keyed to the top-key of DECL. */
19592 void
19593 lazy_load_pendings (tree decl)
19595 /* Make sure lazy loading from a template context behaves as if
19596 from a non-template context. */
19597 processing_template_decl_sentinel ptds;
19599 tree key_decl;
19600 pending_key key;
19601 key.ns = find_pending_key (decl, &key_decl);
19602 key.id = DECL_NAME (key_decl);
19604 auto *pending_vec = pending_table ? pending_table->get (key) : nullptr;
19605 if (!pending_vec)
19606 return;
19608 int count = errorcount + warningcount;
19610 timevar_start (TV_MODULE_IMPORT);
19611 bool ok = !recursive_lazy ();
19612 if (ok)
19614 function_depth++; /* Prevent GC */
19615 unsigned n = dump.push (NULL);
19616 dump () && dump ("Reading %u pending entities keyed to %P",
19617 pending_vec->length (), key.ns, key.id);
19618 for (unsigned ix = pending_vec->length (); ix--;)
19620 unsigned index = (*pending_vec)[ix];
19621 binding_slot *slot = &(*entity_ary)[index];
19623 if (slot->is_lazy ())
19625 module_state *import = import_entity_module (index);
19626 if (!import->lazy_load (index - import->entity_lwm, slot))
19627 ok = false;
19629 else if (dump ())
19631 module_state *import = import_entity_module (index);
19632 dump () && dump ("Entity %M[%u] already loaded",
19633 import, index - import->entity_lwm);
19637 pending_table->remove (key);
19638 dump.pop (n);
19639 lazy_snum = 0;
19640 post_load_processing ();
19641 function_depth--;
19644 timevar_stop (TV_MODULE_IMPORT);
19646 if (!ok)
19647 fatal_error (input_location, "failed to load pendings for %<%E%s%E%>",
19648 key.ns, &"::"[key.ns == global_namespace ? 2 : 0], key.id);
19650 if (count != errorcount + warningcount)
19651 inform (input_location, "during load of pendings for %<%E%s%E%>",
19652 key.ns, &"::"[key.ns == global_namespace ? 2 : 0], key.id);
19655 static void
19656 direct_import (module_state *import, cpp_reader *reader)
19658 timevar_start (TV_MODULE_IMPORT);
19659 unsigned n = dump.push (import);
19661 gcc_checking_assert (import->is_direct () && import->has_location ());
19662 if (import->loadedness == ML_NONE)
19663 if (!import->do_import (reader, true))
19664 gcc_unreachable ();
19666 if (import->loadedness < ML_LANGUAGE)
19668 if (!keyed_table)
19669 keyed_table = new keyed_map_t (EXPERIMENT (1, 400));
19670 import->read_language (true);
19673 (*modules)[0]->set_import (import, import->exported_p);
19675 dump.pop (n);
19676 timevar_stop (TV_MODULE_IMPORT);
19679 /* Import module IMPORT. */
19681 void
19682 import_module (module_state *import, location_t from_loc, bool exporting_p,
19683 tree, cpp_reader *reader)
19685 if (!import->check_not_purview (from_loc))
19686 return;
19688 if (!import->is_header () && current_lang_depth ())
19689 /* Only header units should appear inside language
19690 specifications. The std doesn't specify this, but I think
19691 that's an error in resolving US 033, because language linkage
19692 is also our escape clause to getting things into the global
19693 module, so we don't want to confuse things by having to think
19694 about whether 'extern "C++" { import foo; }' puts foo's
19695 contents into the global module all of a sudden. */
19696 warning (0, "import of named module %qs inside language-linkage block",
19697 import->get_flatname ());
19699 if (exporting_p || module_exporting_p ())
19700 import->exported_p = true;
19702 if (import->loadedness != ML_NONE)
19704 from_loc = ordinary_loc_of (line_table, from_loc);
19705 linemap_module_reparent (line_table, import->loc, from_loc);
19707 gcc_checking_assert (!import->module_p);
19708 gcc_checking_assert (import->is_direct () && import->has_location ());
19710 direct_import (import, reader);
19713 /* Declare the name of the current module to be NAME. EXPORTING_p is
19714 true if this TU is the exporting module unit. */
19716 void
19717 declare_module (module_state *module, location_t from_loc, bool exporting_p,
19718 tree, cpp_reader *reader)
19720 gcc_assert (global_namespace == current_scope ());
19722 module_state *current = (*modules)[0];
19723 if (module_purview_p () || module->loadedness > ML_CONFIG)
19725 error_at (from_loc, module_purview_p ()
19726 ? G_("module already declared")
19727 : G_("module already imported"));
19728 if (module_purview_p ())
19729 module = current;
19730 inform (module->loc, module_purview_p ()
19731 ? G_("module %qs declared here")
19732 : G_("module %qs imported here"),
19733 module->get_flatname ());
19734 return;
19737 gcc_checking_assert (module->module_p);
19738 gcc_checking_assert (module->is_direct () && module->has_location ());
19740 /* Yer a module, 'arry. */
19741 module_kind = module->is_header () ? MK_HEADER : MK_NAMED | MK_ATTACH;
19743 // Even in header units, we consider the decls to be purview
19744 module_kind |= MK_PURVIEW;
19746 if (module->is_partition ())
19747 module_kind |= MK_PARTITION;
19748 if (exporting_p)
19750 module->interface_p = true;
19751 module_kind |= MK_INTERFACE;
19754 if (module_has_cmi_p ())
19756 /* Copy the importing information we may have already done. We
19757 do not need to separate out the imports that only happen in
19758 the GMF, inspite of what the literal wording of the std
19759 might imply. See p2191, the core list had a discussion
19760 where the module implementors agreed that the GMF of a named
19761 module is invisible to importers. */
19762 module->imports = current->imports;
19764 module->mod = 0;
19765 (*modules)[0] = module;
19767 else
19769 module->interface_p = true;
19770 current->parent = module; /* So mangler knows module identity. */
19771 direct_import (module, reader);
19775 /* Return true IFF we must emit a module global initializer function
19776 (which will be called by importers' init code). */
19778 bool
19779 module_global_init_needed ()
19781 return module_has_cmi_p () && !header_module_p ();
19784 /* Calculate which, if any, import initializers need calling. */
19786 bool
19787 module_determine_import_inits ()
19789 if (!modules || header_module_p ())
19790 return false;
19792 /* Prune active_init_p. We need the same bitmap allocation
19793 scheme as for the imports member. */
19794 function_depth++; /* Disable GC. */
19795 bitmap covered_imports (BITMAP_GGC_ALLOC ());
19797 bool any = false;
19799 /* Because indirect imports are before their direct import, and
19800 we're scanning the array backwards, we only need one pass! */
19801 for (unsigned ix = modules->length (); --ix;)
19803 module_state *import = (*modules)[ix];
19805 if (!import->active_init_p)
19807 else if (bitmap_bit_p (covered_imports, ix))
19808 import->active_init_p = false;
19809 else
19811 /* Everything this imports is therefore handled by its
19812 initializer, so doesn't need initializing by us. */
19813 bitmap_ior_into (covered_imports, import->imports);
19814 any = true;
19817 function_depth--;
19819 return any;
19822 /* Emit calls to each direct import's global initializer. Including
19823 direct imports of directly imported header units. The initializers
19824 of (static) entities in header units will be called by their
19825 importing modules (for the instance contained within that), or by
19826 the current TU (for the instances we've brought in). Of course
19827 such header unit behaviour is evil, but iostream went through that
19828 door some time ago. */
19830 void
19831 module_add_import_initializers ()
19833 if (!modules || header_module_p ())
19834 return;
19836 tree fntype = build_function_type (void_type_node, void_list_node);
19837 releasing_vec args; // There are no args
19839 for (unsigned ix = modules->length (); --ix;)
19841 module_state *import = (*modules)[ix];
19842 if (import->active_init_p)
19844 tree name = mangle_module_global_init (ix);
19845 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
19847 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
19848 SET_DECL_ASSEMBLER_NAME (fndecl, name);
19849 TREE_PUBLIC (fndecl) = true;
19850 determine_visibility (fndecl);
19852 tree call = cp_build_function_call_vec (fndecl, &args,
19853 tf_warning_or_error);
19854 finish_expr_stmt (call);
19859 /* NAME & LEN are a preprocessed header name, possibly including the
19860 surrounding "" or <> characters. Return the raw string name of the
19861 module to which it refers. This will be an absolute path, or begin
19862 with ./, so it is immediately distinguishable from a (non-header
19863 unit) module name. If READER is non-null, ask the preprocessor to
19864 locate the header to which it refers using the appropriate include
19865 path. Note that we do never do \ processing of the string, as that
19866 matches the preprocessor's behaviour. */
19868 static const char *
19869 canonicalize_header_name (cpp_reader *reader, location_t loc, bool unquoted,
19870 const char *str, size_t &len_r)
19872 size_t len = len_r;
19873 static char *buf = 0;
19874 static size_t alloc = 0;
19876 if (!unquoted)
19878 gcc_checking_assert (len >= 2
19879 && ((reader && str[0] == '<' && str[len-1] == '>')
19880 || (str[0] == '"' && str[len-1] == '"')));
19881 str += 1;
19882 len -= 2;
19885 if (reader)
19887 gcc_assert (!unquoted);
19889 if (len >= alloc)
19891 alloc = len + 1;
19892 buf = XRESIZEVEC (char, buf, alloc);
19894 memcpy (buf, str, len);
19895 buf[len] = 0;
19897 if (const char *hdr
19898 = cpp_probe_header_unit (reader, buf, str[-1] == '<', loc))
19900 len = strlen (hdr);
19901 str = hdr;
19903 else
19904 str = buf;
19907 if (!(str[0] == '.' ? IS_DIR_SEPARATOR (str[1]) : IS_ABSOLUTE_PATH (str)))
19909 /* Prepend './' */
19910 if (len + 3 > alloc)
19912 alloc = len + 3;
19913 buf = XRESIZEVEC (char, buf, alloc);
19916 buf[0] = '.';
19917 buf[1] = DIR_SEPARATOR;
19918 memmove (buf + 2, str, len);
19919 len += 2;
19920 buf[len] = 0;
19921 str = buf;
19924 len_r = len;
19925 return str;
19928 /* Set the CMI name from a cody packet. Issue an error if
19929 ill-formed. */
19931 void module_state::set_filename (const Cody::Packet &packet)
19933 gcc_checking_assert (!filename);
19934 if (packet.GetCode () == Cody::Client::PC_PATHNAME)
19935 filename = xstrdup (packet.GetString ().c_str ());
19936 else
19938 gcc_checking_assert (packet.GetCode () == Cody::Client::PC_ERROR);
19939 error_at (loc, "unknown Compiled Module Interface: %s",
19940 packet.GetString ().c_str ());
19944 /* Figure out whether to treat HEADER as an include or an import. */
19946 static char *
19947 maybe_translate_include (cpp_reader *reader, line_maps *lmaps, location_t loc,
19948 const char *path)
19950 if (!modules_p ())
19952 /* Turn off. */
19953 cpp_get_callbacks (reader)->translate_include = NULL;
19954 return nullptr;
19957 if (!spans.init_p ())
19958 /* Before the main file, don't divert. */
19959 return nullptr;
19961 dump.push (NULL);
19963 dump () && dump ("Checking include translation '%s'", path);
19964 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
19966 size_t len = strlen (path);
19967 path = canonicalize_header_name (NULL, loc, true, path, len);
19968 auto packet = mapper->IncludeTranslate (path, Cody::Flags::None, len);
19969 int xlate = false;
19970 if (packet.GetCode () == Cody::Client::PC_BOOL)
19971 xlate = -int (packet.GetInteger ());
19972 else if (packet.GetCode () == Cody::Client::PC_PATHNAME)
19974 /* Record the CMI name for when we do the import. */
19975 module_state *import = get_module (build_string (len, path));
19976 import->set_filename (packet);
19977 xlate = +1;
19979 else
19981 gcc_checking_assert (packet.GetCode () == Cody::Client::PC_ERROR);
19982 error_at (loc, "cannot determine %<#include%> translation of %s: %s",
19983 path, packet.GetString ().c_str ());
19986 bool note = false;
19987 if (note_include_translate_yes && xlate > 1)
19988 note = true;
19989 else if (note_include_translate_no && xlate == 0)
19990 note = true;
19991 else if (note_includes)
19992 /* We do not expect the note_includes vector to be large, so O(N)
19993 iteration. */
19994 for (unsigned ix = note_includes->length (); !note && ix--;)
19995 if (!strcmp ((*note_includes)[ix], path))
19996 note = true;
19998 if (note)
19999 inform (loc, xlate
20000 ? G_("include %qs translated to import")
20001 : G_("include %qs processed textually") , path);
20003 dump () && dump (xlate ? "Translating include to import"
20004 : "Keeping include as include");
20005 dump.pop (0);
20007 if (!(xlate > 0))
20008 return nullptr;
20010 /* Create the translation text. */
20011 loc = ordinary_loc_of (lmaps, loc);
20012 const line_map_ordinary *map
20013 = linemap_check_ordinary (linemap_lookup (lmaps, loc));
20014 unsigned col = SOURCE_COLUMN (map, loc);
20015 col -= (col != 0); /* Columns are 1-based. */
20017 unsigned alloc = len + col + 60;
20018 char *res = XNEWVEC (char, alloc);
20020 strcpy (res, "__import");
20021 unsigned actual = 8;
20022 if (col > actual)
20024 /* Pad out so the filename appears at the same position. */
20025 memset (res + actual, ' ', col - actual);
20026 actual = col;
20028 /* No need to encode characters, that's not how header names are
20029 handled. */
20030 actual += snprintf (res + actual, alloc - actual,
20031 "\"%s\" [[__translated]];\n", path);
20032 gcc_checking_assert (actual < alloc);
20034 /* cpplib will delete the buffer. */
20035 return res;
20038 static void
20039 begin_header_unit (cpp_reader *reader)
20041 /* Set the module header name from the main_input_filename. */
20042 const char *main = main_input_filename;
20043 size_t len = strlen (main);
20044 main = canonicalize_header_name (NULL, 0, true, main, len);
20045 module_state *module = get_module (build_string (len, main));
20047 preprocess_module (module, cpp_main_loc (reader), false, false, true, reader);
20050 /* We've just properly entered the main source file. I.e. after the
20051 command line, builtins and forced headers. Record the line map and
20052 location of this map. Note we may be called more than once. The
20053 first call sticks. */
20055 void
20056 module_begin_main_file (cpp_reader *reader, line_maps *lmaps,
20057 const line_map_ordinary *map)
20059 gcc_checking_assert (lmaps == line_table);
20060 if (modules_p () && !spans.init_p ())
20062 unsigned n = dump.push (NULL);
20063 spans.init (lmaps, map);
20064 dump.pop (n);
20065 if (flag_header_unit && !cpp_get_options (reader)->preprocessed)
20067 /* Tell the preprocessor this is an include file. */
20068 cpp_retrofit_as_include (reader);
20069 begin_header_unit (reader);
20074 /* Process the pending_import queue, making sure we know the
20075 filenames. */
20077 static void
20078 name_pending_imports (cpp_reader *reader)
20080 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
20082 if (!vec_safe_length (pending_imports))
20083 /* Not doing anything. */
20084 return;
20086 timevar_start (TV_MODULE_MAPPER);
20088 auto n = dump.push (NULL);
20089 dump () && dump ("Resolving direct import names");
20090 bool want_deps = (bool (mapper->get_flags () & Cody::Flags::NameOnly)
20091 || cpp_get_deps (reader));
20092 bool any = false;
20094 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
20096 module_state *module = (*pending_imports)[ix];
20097 gcc_checking_assert (module->is_direct ());
20098 if (!module->filename && !module->visited_p)
20100 bool export_p = (module->module_p
20101 && (module->is_partition () || module->exported_p));
20103 Cody::Flags flags = Cody::Flags::None;
20104 if (flag_preprocess_only
20105 && !(module->is_header () && !export_p))
20107 if (!want_deps)
20108 continue;
20109 flags = Cody::Flags::NameOnly;
20112 if (!any)
20114 any = true;
20115 mapper->Cork ();
20117 if (export_p)
20118 mapper->ModuleExport (module->get_flatname (), flags);
20119 else
20120 mapper->ModuleImport (module->get_flatname (), flags);
20121 module->visited_p = true;
20125 if (any)
20127 auto response = mapper->Uncork ();
20128 auto r_iter = response.begin ();
20129 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
20131 module_state *module = (*pending_imports)[ix];
20132 if (module->visited_p)
20134 module->visited_p = false;
20135 gcc_checking_assert (!module->filename);
20137 module->set_filename (*r_iter);
20138 ++r_iter;
20143 dump.pop (n);
20145 timevar_stop (TV_MODULE_MAPPER);
20148 /* We've just lexed a module-specific control line for MODULE. Mark
20149 the module as a direct import, and possibly load up its macro
20150 state. Returns the primary module, if this is a module
20151 declaration. */
20152 /* Perhaps we should offer a preprocessing mode where we read the
20153 directives from the header unit, rather than require the header's
20154 CMI. */
20156 module_state *
20157 preprocess_module (module_state *module, location_t from_loc,
20158 bool in_purview, bool is_import, bool is_export,
20159 cpp_reader *reader)
20161 if (!is_import)
20163 if (module->loc)
20164 /* It's already been mentioned, so ignore its module-ness. */
20165 is_import = true;
20166 else
20168 /* Record it is the module. */
20169 module->module_p = true;
20170 if (is_export)
20172 module->exported_p = true;
20173 module->interface_p = true;
20178 if (module->directness < MD_DIRECT + in_purview)
20180 /* Mark as a direct import. */
20181 module->directness = module_directness (MD_DIRECT + in_purview);
20183 /* Set the location to be most informative for users. */
20184 from_loc = ordinary_loc_of (line_table, from_loc);
20185 if (module->loadedness != ML_NONE)
20186 linemap_module_reparent (line_table, module->loc, from_loc);
20187 else
20189 module->loc = from_loc;
20190 if (!module->flatname)
20191 module->set_flatname ();
20195 auto desired = ML_CONFIG;
20196 if (is_import
20197 && module->is_header ()
20198 && (!cpp_get_options (reader)->preprocessed
20199 || cpp_get_options (reader)->directives_only))
20200 /* We need preprocessor state now. */
20201 desired = ML_PREPROCESSOR;
20203 if (!is_import || module->loadedness < desired)
20205 vec_safe_push (pending_imports, module);
20207 if (desired == ML_PREPROCESSOR)
20209 unsigned n = dump.push (NULL);
20211 dump () && dump ("Reading %M preprocessor state", module);
20212 name_pending_imports (reader);
20214 /* Preserve the state of the line-map. */
20215 unsigned pre_hwm = LINEMAPS_ORDINARY_USED (line_table);
20217 /* We only need to close the span, if we're going to emit a
20218 CMI. But that's a little tricky -- our token scanner
20219 needs to be smarter -- and this isn't much state.
20220 Remember, we've not parsed anything at this point, so
20221 our module state flags are inadequate. */
20222 spans.maybe_init ();
20223 spans.close ();
20225 timevar_start (TV_MODULE_IMPORT);
20227 /* Load the config of each pending import -- we must assign
20228 module numbers monotonically. */
20229 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
20231 auto *import = (*pending_imports)[ix];
20232 if (!(import->module_p
20233 && (import->is_partition () || import->exported_p))
20234 && import->loadedness == ML_NONE
20235 && (import->is_header () || !flag_preprocess_only))
20237 unsigned n = dump.push (import);
20238 import->do_import (reader, true);
20239 dump.pop (n);
20242 vec_free (pending_imports);
20244 /* Restore the line-map state. */
20245 spans.open (linemap_module_restore (line_table, pre_hwm));
20247 /* Now read the preprocessor state of this particular
20248 import. */
20249 if (module->loadedness == ML_CONFIG
20250 && module->read_preprocessor (true))
20251 module->import_macros ();
20253 timevar_stop (TV_MODULE_IMPORT);
20255 dump.pop (n);
20259 return is_import ? NULL : get_primary (module);
20262 /* We've completed phase-4 translation. Emit any dependency
20263 information for the not-yet-loaded direct imports, and fill in
20264 their file names. We'll have already loaded up the direct header
20265 unit wavefront. */
20267 void
20268 preprocessed_module (cpp_reader *reader)
20270 unsigned n = dump.push (NULL);
20272 dump () && dump ("Completed phase-4 (tokenization) processing");
20274 name_pending_imports (reader);
20275 vec_free (pending_imports);
20277 spans.maybe_init ();
20278 spans.close ();
20280 using iterator = hash_table<module_state_hash>::iterator;
20281 if (mkdeps *deps = cpp_get_deps (reader))
20283 /* Walk the module hash, informing the dependency machinery. */
20284 iterator end = modules_hash->end ();
20285 for (iterator iter = modules_hash->begin (); iter != end; ++iter)
20287 module_state *module = *iter;
20289 if (module->is_direct ())
20291 if (module->is_module ()
20292 && (module->is_interface () || module->is_partition ()))
20293 deps_add_module_target (deps, module->get_flatname (),
20294 maybe_add_cmi_prefix (module->filename),
20295 module->is_header (),
20296 module->is_exported ());
20297 else
20298 deps_add_module_dep (deps, module->get_flatname ());
20303 if (flag_header_unit && !flag_preprocess_only)
20305 /* Find the main module -- remember, it's not yet in the module
20306 array. */
20307 iterator end = modules_hash->end ();
20308 for (iterator iter = modules_hash->begin (); iter != end; ++iter)
20310 module_state *module = *iter;
20311 if (module->is_module ())
20313 declare_module (module, cpp_main_loc (reader), true, NULL, reader);
20314 module_kind |= MK_EXPORTING;
20315 break;
20320 dump.pop (n);
20323 /* VAL is a global tree, add it to the global vec if it is
20324 interesting. Add some of its targets, if they too are
20325 interesting. We do not add identifiers, as they can be re-found
20326 via the identifier hash table. There is a cost to the number of
20327 global trees. */
20329 static int
20330 maybe_add_global (tree val, unsigned &crc)
20332 int v = 0;
20334 if (val && !(identifier_p (val) || TREE_VISITED (val)))
20336 TREE_VISITED (val) = true;
20337 crc = crc32_unsigned (crc, fixed_trees->length ());
20338 vec_safe_push (fixed_trees, val);
20339 v++;
20341 if (CODE_CONTAINS_STRUCT (TREE_CODE (val), TS_TYPED))
20342 v += maybe_add_global (TREE_TYPE (val), crc);
20343 if (CODE_CONTAINS_STRUCT (TREE_CODE (val), TS_TYPE_COMMON))
20344 v += maybe_add_global (TYPE_NAME (val), crc);
20347 return v;
20350 /* Initialize module state. Create the hash table, determine the
20351 global trees. Create the module for current TU. */
20353 void
20354 init_modules (cpp_reader *reader)
20356 /* PCH should not be reachable because of lang-specs, but the
20357 user could have overriden that. */
20358 if (pch_file)
20359 fatal_error (input_location,
20360 "C++ modules are incompatible with precompiled headers");
20362 if (cpp_get_options (reader)->traditional)
20363 fatal_error (input_location,
20364 "C++ modules are incompatible with traditional preprocessing");
20366 if (flag_preprocess_only)
20368 cpp_options *cpp_opts = cpp_get_options (reader);
20369 if (flag_no_output
20370 || (cpp_opts->deps.style != DEPS_NONE
20371 && !cpp_opts->deps.need_preprocessor_output))
20373 warning (0, flag_dump_macros == 'M'
20374 ? G_("macro debug output may be incomplete with modules")
20375 : G_("module dependencies require preprocessing"));
20376 if (cpp_opts->deps.style != DEPS_NONE)
20377 inform (input_location, "you should use the %<-%s%> option",
20378 cpp_opts->deps.style == DEPS_SYSTEM ? "MD" : "MMD");
20382 /* :: is always exported. */
20383 DECL_MODULE_EXPORT_P (global_namespace) = true;
20385 modules_hash = hash_table<module_state_hash>::create_ggc (31);
20386 vec_safe_reserve (modules, 20);
20388 /* Create module for current TU. */
20389 module_state *current
20390 = new (ggc_alloc<module_state> ()) module_state (NULL_TREE, NULL, false);
20391 current->mod = 0;
20392 bitmap_set_bit (current->imports, 0);
20393 modules->quick_push (current);
20395 gcc_checking_assert (!fixed_trees);
20397 headers = BITMAP_GGC_ALLOC ();
20399 if (note_includes)
20400 /* Canonicalize header names. */
20401 for (unsigned ix = 0; ix != note_includes->length (); ix++)
20403 const char *hdr = (*note_includes)[ix];
20404 size_t len = strlen (hdr);
20406 bool system = hdr[0] == '<';
20407 bool user = hdr[0] == '"';
20408 bool delimed = system || user;
20410 if (len <= (delimed ? 2 : 0)
20411 || (delimed && hdr[len-1] != (system ? '>' : '"')))
20412 error ("invalid header name %qs", hdr);
20414 hdr = canonicalize_header_name (delimed ? reader : NULL,
20415 0, !delimed, hdr, len);
20416 char *path = XNEWVEC (char, len + 1);
20417 memcpy (path, hdr, len);
20418 path[len] = 0;
20420 (*note_includes)[ix] = path;
20423 if (note_cmis)
20424 /* Canonicalize & mark module names. */
20425 for (unsigned ix = 0; ix != note_cmis->length (); ix++)
20427 const char *name = (*note_cmis)[ix];
20428 size_t len = strlen (name);
20430 bool is_system = name[0] == '<';
20431 bool is_user = name[0] == '"';
20432 bool is_pathname = false;
20433 if (!(is_system || is_user))
20434 for (unsigned ix = len; !is_pathname && ix--;)
20435 is_pathname = IS_DIR_SEPARATOR (name[ix]);
20436 if (is_system || is_user || is_pathname)
20438 if (len <= (is_pathname ? 0 : 2)
20439 || (!is_pathname && name[len-1] != (is_system ? '>' : '"')))
20441 error ("invalid header name %qs", name);
20442 continue;
20444 else
20445 name = canonicalize_header_name (is_pathname ? nullptr : reader,
20446 0, is_pathname, name, len);
20448 if (auto module = get_module (name))
20449 module->inform_cmi_p = 1;
20450 else
20451 error ("invalid module name %qs", name);
20454 dump.push (NULL);
20456 /* Determine lazy handle bound. */
20458 unsigned limit = 1000;
20459 #if HAVE_GETRLIMIT
20460 struct rlimit rlimit;
20461 if (!getrlimit (RLIMIT_NOFILE, &rlimit))
20463 lazy_hard_limit = (rlimit.rlim_max < 1000000
20464 ? unsigned (rlimit.rlim_max) : 1000000);
20465 lazy_hard_limit = (lazy_hard_limit > LAZY_HEADROOM
20466 ? lazy_hard_limit - LAZY_HEADROOM : 0);
20467 if (rlimit.rlim_cur < limit)
20468 limit = unsigned (rlimit.rlim_cur);
20470 #endif
20471 limit = limit > LAZY_HEADROOM ? limit - LAZY_HEADROOM : 1;
20473 if (unsigned parm = param_lazy_modules)
20475 if (parm <= limit || !lazy_hard_limit || !try_increase_lazy (parm))
20476 lazy_limit = parm;
20478 else
20479 lazy_limit = limit;
20482 if (dump ())
20484 verstr_t ver;
20485 version2string (MODULE_VERSION, ver);
20486 dump ("Source: %s", main_input_filename);
20487 dump ("Compiler: %s", version_string);
20488 dump ("Modules: %s", ver);
20489 dump ("Checking: %s",
20490 #if CHECKING_P
20491 "checking"
20492 #elif ENABLE_ASSERT_CHECKING
20493 "asserting"
20494 #else
20495 "release"
20496 #endif
20498 dump ("Compiled by: "
20499 #ifdef __GNUC__
20500 "GCC %d.%d, %s", __GNUC__, __GNUC_MINOR__,
20501 #ifdef __OPTIMIZE__
20502 "optimizing"
20503 #else
20504 "not optimizing"
20505 #endif
20506 #else
20507 "not GCC"
20508 #endif
20510 dump ("Reading: %s", MAPPED_READING ? "mmap" : "fileio");
20511 dump ("Writing: %s", MAPPED_WRITING ? "mmap" : "fileio");
20512 dump ("Lazy limit: %u", lazy_limit);
20513 dump ("Lazy hard limit: %u", lazy_hard_limit);
20514 dump ("");
20517 /* Construct the global tree array. This is an array of unique
20518 global trees (& types). Do this now, rather than lazily, as
20519 some global trees are lazily created and we don't want that to
20520 mess with our syndrome of fixed trees. */
20521 unsigned crc = 0;
20522 vec_alloc (fixed_trees, 250);
20524 dump () && dump ("+Creating globals");
20525 /* Insert the TRANSLATION_UNIT_DECL. */
20526 TREE_VISITED (DECL_CONTEXT (global_namespace)) = true;
20527 fixed_trees->quick_push (DECL_CONTEXT (global_namespace));
20528 for (unsigned jx = 0; global_tree_arys[jx].first; jx++)
20530 const tree *ptr = global_tree_arys[jx].first;
20531 unsigned limit = global_tree_arys[jx].second;
20533 for (unsigned ix = 0; ix != limit; ix++, ptr++)
20535 !(ix & 31) && dump ("") && dump ("+\t%u:%u:", jx, ix);
20536 unsigned v = maybe_add_global (*ptr, crc);
20537 dump () && dump ("+%u", v);
20540 /* OS- and machine-specific types are dynamically registered at
20541 runtime, so cannot be part of global_tree_arys. */
20542 registered_builtin_types && dump ("") && dump ("+\tB:");
20543 for (tree t = registered_builtin_types; t; t = TREE_CHAIN (t))
20545 unsigned v = maybe_add_global (TREE_VALUE (t), crc);
20546 dump () && dump ("+%u", v);
20548 global_crc = crc32_unsigned (crc, fixed_trees->length ());
20549 dump ("") && dump ("Created %u unique globals, crc=%x",
20550 fixed_trees->length (), global_crc);
20551 for (unsigned ix = fixed_trees->length (); ix--;)
20552 TREE_VISITED ((*fixed_trees)[ix]) = false;
20554 dump.pop (0);
20556 if (!flag_module_lazy)
20557 /* Get the mapper now, if we're not being lazy. */
20558 get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
20560 if (!flag_preprocess_only)
20562 pending_table = new pending_map_t (EXPERIMENT (1, 400));
20563 entity_map = new entity_map_t (EXPERIMENT (1, 400));
20564 vec_safe_reserve (entity_ary, EXPERIMENT (1, 400));
20565 imported_temploid_friends
20566 = decl_tree_cache_map::create_ggc (EXPERIMENT (1, 400));
20569 #if CHECKING_P
20570 note_defs = note_defs_table_t::create_ggc (1000);
20571 #endif
20573 if (flag_header_unit && cpp_get_options (reader)->preprocessed)
20574 begin_header_unit (reader);
20576 /* Collect here to make sure things are tagged correctly (when
20577 aggressively GC'd). */
20578 ggc_collect ();
20581 /* If NODE is a deferred macro, load it. */
20583 static int
20584 load_macros (cpp_reader *reader, cpp_hashnode *node, void *)
20586 location_t main_loc
20587 = MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0));
20589 if (cpp_user_macro_p (node)
20590 && !node->value.macro)
20592 cpp_macro *macro = cpp_get_deferred_macro (reader, node, main_loc);
20593 dump () && dump ("Loaded macro #%s %I",
20594 macro ? "define" : "undef", identifier (node));
20597 return 1;
20600 /* At the end of tokenizing, we no longer need the macro tables of
20601 imports. But the user might have requested some checking. */
20603 void
20604 maybe_check_all_macros (cpp_reader *reader)
20606 if (!warn_imported_macros)
20607 return;
20609 /* Force loading of any remaining deferred macros. This will
20610 produce diagnostics if they are ill-formed. */
20611 unsigned n = dump.push (NULL);
20612 cpp_forall_identifiers (reader, load_macros, NULL);
20613 dump.pop (n);
20616 // State propagated from finish_module_processing to fini_modules
20618 struct module_processing_cookie
20620 elf_out out;
20621 module_state_config config;
20622 char *cmi_name;
20623 char *tmp_name;
20624 unsigned crc;
20625 bool began;
20627 module_processing_cookie (char *cmi, char *tmp, int fd, int e)
20628 : out (fd, e), cmi_name (cmi), tmp_name (tmp), crc (0), began (false)
20631 ~module_processing_cookie ()
20633 XDELETEVEC (tmp_name);
20634 XDELETEVEC (cmi_name);
20638 /* Write the CMI, if we're a module interface. */
20640 void *
20641 finish_module_processing (cpp_reader *reader)
20643 module_processing_cookie *cookie = nullptr;
20645 if (header_module_p ())
20646 module_kind &= ~MK_EXPORTING;
20648 if (!modules || !(*modules)[0]->name)
20650 if (flag_module_only)
20651 warning (0, "%<-fmodule-only%> used for non-interface");
20653 else if (!flag_syntax_only)
20655 int fd = -1;
20656 int e = -1;
20658 timevar_start (TV_MODULE_EXPORT);
20660 /* Force a valid but empty line map at the end. This simplifies
20661 the line table preparation and writing logic. */
20662 linemap_add (line_table, LC_ENTER, false, "", 0);
20664 /* We write to a tmpname, and then atomically rename. */
20665 char *cmi_name = NULL;
20666 char *tmp_name = NULL;
20667 module_state *state = (*modules)[0];
20669 unsigned n = dump.push (state);
20670 state->announce ("creating");
20671 if (state->filename)
20673 size_t len = 0;
20674 cmi_name = xstrdup (maybe_add_cmi_prefix (state->filename, &len));
20675 tmp_name = XNEWVEC (char, len + 3);
20676 memcpy (tmp_name, cmi_name, len);
20677 strcpy (&tmp_name[len], "~");
20679 if (!errorcount)
20680 for (unsigned again = 2; ; again--)
20682 fd = open (tmp_name,
20683 O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY,
20684 S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
20685 e = errno;
20686 if (fd >= 0 || !again || e != ENOENT)
20687 break;
20688 create_dirs (tmp_name);
20690 if (note_module_cmi_yes || state->inform_cmi_p)
20691 inform (state->loc, "writing CMI %qs", cmi_name);
20692 dump () && dump ("CMI is %s", cmi_name);
20695 cookie = new module_processing_cookie (cmi_name, tmp_name, fd, e);
20697 if (errorcount)
20698 warning_at (state->loc, 0, "not writing module %qs due to errors",
20699 state->get_flatname ());
20700 else if (cookie->out.begin ())
20702 cookie->began = true;
20703 auto loc = input_location;
20704 /* So crashes finger-point the module decl. */
20705 input_location = state->loc;
20706 state->write_begin (&cookie->out, reader, cookie->config, cookie->crc);
20707 input_location = loc;
20710 dump.pop (n);
20711 timevar_stop (TV_MODULE_EXPORT);
20713 ggc_collect ();
20716 if (modules)
20718 unsigned n = dump.push (NULL);
20719 dump () && dump ("Imported %u modules", modules->length () - 1);
20720 dump () && dump ("Containing %u clusters", available_clusters);
20721 dump () && dump ("Loaded %u clusters (%u%%)", loaded_clusters,
20722 (loaded_clusters * 100 + available_clusters / 2) /
20723 (available_clusters + !available_clusters));
20724 dump.pop (n);
20727 return cookie;
20730 // Do the final emission of a module. At this point we know whether
20731 // the module static initializer is a NOP or not.
20733 static void
20734 late_finish_module (cpp_reader *reader, module_processing_cookie *cookie,
20735 bool init_fn_non_empty)
20737 timevar_start (TV_MODULE_EXPORT);
20739 module_state *state = (*modules)[0];
20740 unsigned n = dump.push (state);
20741 state->announce ("finishing");
20743 cookie->config.active_init = init_fn_non_empty;
20744 if (cookie->began)
20745 state->write_end (&cookie->out, reader, cookie->config, cookie->crc);
20747 if (cookie->out.end () && cookie->cmi_name)
20749 /* Some OS's do not replace NEWNAME if it already exists.
20750 This'll have a race condition in erroneous concurrent
20751 builds. */
20752 unlink (cookie->cmi_name);
20753 if (rename (cookie->tmp_name, cookie->cmi_name))
20755 dump () && dump ("Rename ('%s','%s') errno=%u",
20756 cookie->tmp_name, cookie->cmi_name, errno);
20757 cookie->out.set_error (errno);
20761 if (cookie->out.get_error () && cookie->began)
20763 error_at (state->loc, "failed to write compiled module: %s",
20764 cookie->out.get_error (state->filename));
20765 state->note_cmi_name ();
20768 if (!errorcount)
20770 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
20771 mapper->ModuleCompiled (state->get_flatname ());
20773 else if (cookie->cmi_name)
20775 /* We failed, attempt to erase all evidence we even tried. */
20776 unlink (cookie->tmp_name);
20777 unlink (cookie->cmi_name);
20780 delete cookie;
20781 dump.pop (n);
20782 timevar_stop (TV_MODULE_EXPORT);
20785 void
20786 fini_modules (cpp_reader *reader, void *cookie, bool has_inits)
20788 if (cookie)
20789 late_finish_module (reader,
20790 static_cast<module_processing_cookie *> (cookie),
20791 has_inits);
20793 /* We're done with the macro tables now. */
20794 vec_free (macro_exports);
20795 vec_free (macro_imports);
20796 headers = NULL;
20798 /* We're now done with everything but the module names. */
20799 set_cmi_repo (NULL);
20800 if (mapper)
20802 timevar_start (TV_MODULE_MAPPER);
20803 module_client::close_module_client (0, mapper);
20804 mapper = nullptr;
20805 timevar_stop (TV_MODULE_MAPPER);
20807 module_state_config::release ();
20809 #if CHECKING_P
20810 note_defs = NULL;
20811 #endif
20813 if (modules)
20814 for (unsigned ix = modules->length (); --ix;)
20815 if (module_state *state = (*modules)[ix])
20816 state->release ();
20818 /* No need to lookup modules anymore. */
20819 modules_hash = NULL;
20821 /* Or entity array. We still need the entity map to find import numbers. */
20822 vec_free (entity_ary);
20823 entity_ary = NULL;
20825 /* Or remember any pending entities. */
20826 delete pending_table;
20827 pending_table = NULL;
20829 /* Or any keys -- Let it go! */
20830 delete keyed_table;
20831 keyed_table = NULL;
20833 /* Allow a GC, we've possibly made much data unreachable. */
20834 ggc_collect ();
20837 /* If CODE is a module option, handle it & return true. Otherwise
20838 return false. For unknown reasons I cannot get the option
20839 generation machinery to set fmodule-mapper or -fmodule-header to
20840 make a string type option variable. */
20842 bool
20843 handle_module_option (unsigned code, const char *str, int)
20845 auto hdr = CMS_header;
20847 switch (opt_code (code))
20849 case OPT_fmodule_mapper_:
20850 module_mapper_name = str;
20851 return true;
20853 case OPT_fmodule_header_:
20855 if (!strcmp (str, "user"))
20856 hdr = CMS_user;
20857 else if (!strcmp (str, "system"))
20858 hdr = CMS_system;
20859 else
20860 error ("unknown header kind %qs", str);
20862 /* Fallthrough. */
20864 case OPT_fmodule_header:
20865 flag_header_unit = hdr;
20866 flag_modules = 1;
20867 return true;
20869 case OPT_flang_info_include_translate_:
20870 vec_safe_push (note_includes, str);
20871 return true;
20873 case OPT_flang_info_module_cmi_:
20874 vec_safe_push (note_cmis, str);
20875 return true;
20877 default:
20878 return false;
20882 /* Set preprocessor callbacks and options for modules. */
20884 void
20885 module_preprocess_options (cpp_reader *reader)
20887 gcc_checking_assert (!lang_hooks.preprocess_undef);
20888 if (modules_p ())
20890 auto *cb = cpp_get_callbacks (reader);
20892 cb->translate_include = maybe_translate_include;
20893 cb->user_deferred_macro = module_state::deferred_macro;
20894 if (flag_header_unit)
20896 /* If the preprocessor hook is already in use, that
20897 implementation will call the undef langhook. */
20898 if (cb->undef)
20899 lang_hooks.preprocess_undef = module_state::undef_macro;
20900 else
20901 cb->undef = module_state::undef_macro;
20903 auto *opt = cpp_get_options (reader);
20904 opt->module_directives = true;
20905 opt->main_search = cpp_main_search (flag_header_unit);
20909 #include "gt-cp-module.h"