Daily bump.
[official-gcc.git] / gcc / cp / module.cc
blob71d0fab411f6fb3fc976f8e31b42fe6d0d055761
1 /* C++ modules. Experimental!
2 Copyright (C) 2017-2021 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_EXPORT_P, DECL_MODULE_PURVIEW_P and DECL_MODULE_IMPORT_P. The
51 first indicates whether it is exported, the second whether it is in
52 the module purview (as opposed to the global module fragment), and
53 the third indicates whether it was an import into this TU or not.
55 The more detailed flags are DECL_MODULE_PARTITION_P,
56 DECL_MODULE_ENTITY_P. The first is set in a primary interface unit
57 on decls that were read from module partitions (these will have
58 DECL_MODULE_IMPORT_P set too). Such decls will be streamed out to
59 the primary's CMI. DECL_MODULE_ENTITY_P is set when an entity is
60 imported, even if it matched a non-imported entity. Such a decl
61 will not have DECL_MODULE_IMPORT_P set, even though it has an entry
62 in the entity map and array.
64 Header units are module-like.
66 For namespace-scope lookup, the decls for a particular module are
67 held located in a sparse array hanging off the binding of the name.
68 This is partitioned into two: a few fixed slots at the start
69 followed by the sparse slots afterwards. By construction we only
70 need to append new slots to the end -- there is never a need to
71 insert in the middle. The fixed slots are MODULE_SLOT_CURRENT for
72 the current TU (regardless of whether it is a module or not),
73 MODULE_SLOT_GLOBAL and MODULE_SLOT_PARTITION. These latter two
74 slots are used for merging entities across the global module and
75 module partitions respectively. MODULE_SLOT_PARTITION is only
76 present in a module. Neither of those two slots is searched during
77 name lookup -- they are internal use only. This vector is created
78 lazily once we require it, if there is only a declaration from the
79 current TU, a regular binding is present. It is converted on
80 demand.
82 OPTIMIZATION: Outside of the current TU, we only need ADL to work.
83 We could optimize regular lookup for the current TU by glomming all
84 the visible decls on its slot. Perhaps wait until design is a
85 little more settled though.
87 There is only one instance of each extern-linkage namespace. It
88 appears in every module slot that makes it visible. It also
89 appears in MODULE_SLOT_GLOBAL. (It is an ODR violation if they
90 collide with some other global module entity.) We also have an
91 optimization that shares the slot for adjacent modules that declare
92 the same such namespace.
94 A module interface compilation produces a Compiled Module Interface
95 (CMI). The format used is Encapsulated Lazy Records Of Numbered
96 Declarations, which is essentially ELF's section encapsulation. (As
97 all good nerds are aware, Elrond is half Elf.) Some sections are
98 named, and contain information about the module as a whole (indices
99 etc), and other sections are referenced by number. Although I
100 don't defend against actively hostile CMIs, there is some
101 checksumming involved to verify data integrity. When dumping out
102 an interface, we generate a graph of all the
103 independently-redeclarable DECLS that are needed, and the decls
104 they reference. From that we determine the strongly connected
105 components (SCC) within this TU. Each SCC is dumped to a separate
106 numbered section of the CMI. We generate a binding table section,
107 mapping each namespace&name to a defining section. This allows
108 lazy loading.
110 Lazy loading employs mmap to map a read-only image of the CMI.
111 It thus only occupies address space and is paged in on demand,
112 backed by the CMI file itself. If mmap is unavailable, regular
113 FILEIO is used. Also, there's a bespoke ELF reader/writer here,
114 which implements just the section table and sections (including
115 string sections) of a 32-bit ELF in host byte-order. You can of
116 course inspect it with readelf. I figured 32-bit is sufficient,
117 for a single module. I detect running out of section numbers, but
118 do not implement the ELF overflow mechanism. At least you'll get
119 an error if that happens.
121 We do not separate declarations and definitions. My guess is that
122 if you refer to the declaration, you'll also need the definition
123 (template body, inline function, class definition etc). But this
124 does mean we can get larger SCCs than if we separated them. It is
125 unclear whether this is a win or not.
127 Notice that we embed section indices into the contents of other
128 sections. Thus random manipulation of the CMI file by ELF tools
129 may well break it. The kosher way would probably be to introduce
130 indirection via section symbols, but that would require defining a
131 relocation type.
133 Notice that lazy loading of one module's decls can cause lazy
134 loading of other decls in the same or another module. Clearly we
135 want to avoid loops. In a correct program there can be no loops in
136 the module dependency graph, and the above-mentioned SCC algorithm
137 places all intra-module circular dependencies in the same SCC. It
138 also orders the SCCs wrt each other, so dependent SCCs come first.
139 As we load dependent modules first, we know there can be no
140 reference to a higher-numbered module, and because we write out
141 dependent SCCs first, likewise for SCCs within the module. This
142 allows us to immediately detect broken references. When loading,
143 we must ensure the rest of the compiler doesn't cause some
144 unconnected load to occur (for instance, instantiate a template).
146 Classes used:
148 dumper - logger
150 data - buffer
152 bytes - data streamer
153 bytes_in : bytes - scalar reader
154 bytes_out : bytes - scalar writer
156 elf - ELROND format
157 elf_in : elf - ELROND reader
158 elf_out : elf - ELROND writer
160 trees_in : bytes_in - tree reader
161 trees_out : bytes_out - tree writer
163 depset - dependency set
164 depset::hash - hash table of depsets
165 depset::tarjan - SCC determinator
167 uidset<T> - set T's related to a UID
168 uidset<T>::hash hash table of uidset<T>
170 loc_spans - location map data
172 module_state - module object
174 slurping - data needed during loading
176 macro_import - imported macro data
177 macro_export - exported macro data
179 The ELROND objects use mmap, for both reading and writing. If mmap
180 is unavailable, fileno IO is used to read and write blocks of data.
182 The mapper object uses fileno IO to communicate with the server or
183 program. */
185 /* In expermental (trunk) sources, MODULE_VERSION is a #define passed
186 in from the Makefile. It records the modification date of the
187 source directory -- that's the only way to stay sane. In release
188 sources, we (plan to) use the compiler's major.minor versioning.
189 While the format might not change between at minor versions, it
190 seems simplest to tie the two together. There's no concept of
191 inter-version compatibility. */
192 #define IS_EXPERIMENTAL(V) ((V) >= (1U << 20))
193 #define MODULE_MAJOR(V) ((V) / 10000)
194 #define MODULE_MINOR(V) ((V) % 10000)
195 #define EXPERIMENT(A,B) (IS_EXPERIMENTAL (MODULE_VERSION) ? (A) : (B))
196 #ifndef MODULE_VERSION
197 #include "bversion.h"
198 #define MODULE_VERSION (BUILDING_GCC_MAJOR * 10000U + BUILDING_GCC_MINOR)
199 #elif !IS_EXPERIMENTAL (MODULE_VERSION)
200 #error "This is not the version I was looking for."
201 #endif
203 #define _DEFAULT_SOURCE 1 /* To get TZ field of struct tm, if available. */
204 #include "config.h"
205 #define INCLUDE_STRING
206 #define INCLUDE_VECTOR
207 #include "system.h"
208 #include "coretypes.h"
209 #include "cp-tree.h"
210 #include "timevar.h"
211 #include "stringpool.h"
212 #include "dumpfile.h"
213 #include "bitmap.h"
214 #include "cgraph.h"
215 #include "tree-iterator.h"
216 #include "cpplib.h"
217 #include "mkdeps.h"
218 #include "incpath.h"
219 #include "libiberty.h"
220 #include "stor-layout.h"
221 #include "version.h"
222 #include "tree-diagnostic.h"
223 #include "toplev.h"
224 #include "opts.h"
225 #include "attribs.h"
226 #include "intl.h"
227 #include "langhooks.h"
228 /* This TU doesn't need or want to see the networking. */
229 #define CODY_NETWORKING 0
230 #include "mapper-client.h"
232 #if 0 // 1 for testing no mmap
233 #define MAPPED_READING 0
234 #define MAPPED_WRITING 0
235 #else
236 #if HAVE_MMAP_FILE && _POSIX_MAPPED_FILES > 0
237 /* mmap, munmap. */
238 #define MAPPED_READING 1
239 #if HAVE_SYSCONF && defined (_SC_PAGE_SIZE)
240 /* msync, sysconf (_SC_PAGE_SIZE), ftruncate */
241 /* posix_fallocate used if available. */
242 #define MAPPED_WRITING 1
243 #else
244 #define MAPPED_WRITING 0
245 #endif
246 #else
247 #define MAPPED_READING 0
248 #define MAPPED_WRITING 0
249 #endif
250 #endif
252 /* Some open(2) flag differences, what a colourful world it is! */
253 #if defined (O_CLOEXEC)
254 // OK
255 #elif defined (_O_NOINHERIT)
256 /* Windows' _O_NOINHERIT matches O_CLOEXEC flag */
257 #define O_CLOEXEC _O_NOINHERIT
258 #else
259 #define O_CLOEXEC 0
260 #endif
261 #if defined (O_BINARY)
262 // Ok?
263 #elif defined (_O_BINARY)
264 /* Windows' open(2) call defaults to text! */
265 #define O_BINARY _O_BINARY
266 #else
267 #define O_BINARY 0
268 #endif
270 static inline cpp_hashnode *cpp_node (tree id)
272 return CPP_HASHNODE (GCC_IDENT_TO_HT_IDENT (id));
275 static inline tree identifier (const cpp_hashnode *node)
277 /* HT_NODE() expands to node->ident that HT_IDENT_TO_GCC_IDENT()
278 then subtracts a nonzero constant, deriving a pointer to
279 a different member than ident. That's strictly undefined
280 and detected by -Warray-bounds. Suppress it. See PR 101372. */
281 #pragma GCC diagnostic push
282 #pragma GCC diagnostic ignored "-Warray-bounds"
283 return HT_IDENT_TO_GCC_IDENT (HT_NODE (const_cast<cpp_hashnode *> (node)));
284 #pragma GCC diagnostic pop
287 /* Id for dumping module information. */
288 int module_dump_id;
290 /* We have a special module owner. */
291 #define MODULE_UNKNOWN (~0U) /* Not yet known. */
293 /* Prefix for section names. */
294 #define MOD_SNAME_PFX ".gnu.c++"
296 /* Format a version for user consumption. */
298 typedef char verstr_t[32];
299 static void
300 version2string (unsigned version, verstr_t &out)
302 unsigned major = MODULE_MAJOR (version);
303 unsigned minor = MODULE_MINOR (version);
305 if (IS_EXPERIMENTAL (version))
306 sprintf (out, "%04u/%02u/%02u-%02u:%02u%s",
307 2000 + major / 10000, (major / 100) % 100, (major % 100),
308 minor / 100, minor % 100,
309 EXPERIMENT ("", " (experimental)"));
310 else
311 sprintf (out, "%u.%u", major, minor);
314 /* Include files to note translation for. */
315 static vec<const char *, va_heap, vl_embed> *note_includes;
317 /* Modules to note CMI pathames. */
318 static vec<const char *, va_heap, vl_embed> *note_cmis;
320 /* Traits to hash an arbitrary pointer. Entries are not deletable,
321 and removal is a noop (removal needed upon destruction). */
322 template <typename T>
323 struct nodel_ptr_hash : pointer_hash<T>, typed_noop_remove <T *> {
324 /* Nothing is deletable. Everything is insertable. */
325 static bool is_deleted (T *) { return false; }
326 static void mark_deleted (T *) { gcc_unreachable (); }
329 /* Map from pointer to signed integer. */
330 typedef simple_hashmap_traits<nodel_ptr_hash<void>, int> ptr_int_traits;
331 typedef hash_map<void *,signed,ptr_int_traits> ptr_int_hash_map;
333 /********************************************************************/
334 /* Basic streaming & ELF. Serialization is usually via mmap. For
335 writing we slide a buffer over the output file, syncing it
336 approproiately. For reading we simply map the whole file (as a
337 file-backed read-only map -- it's just address space, leaving the
338 OS pager to deal with getting the data to us). Some buffers need
339 to be more conventional malloc'd contents. */
341 /* Variable length buffer. */
343 class data {
344 public:
345 class allocator {
346 public:
347 /* Tools tend to moan if the dtor's not virtual. */
348 virtual ~allocator () {}
350 public:
351 void grow (data &obj, unsigned needed, bool exact);
352 void shrink (data &obj);
354 public:
355 virtual char *grow (char *ptr, unsigned needed);
356 virtual void shrink (char *ptr);
359 public:
360 char *buffer; /* Buffer being transferred. */
361 /* Although size_t would be the usual size, we know we never get
362 more than 4GB of buffer -- because that's the limit of the
363 encapsulation format. And if you need bigger imports, you're
364 doing it wrong. */
365 unsigned size; /* Allocated size of buffer. */
366 unsigned pos; /* Position in buffer. */
368 public:
369 data ()
370 :buffer (NULL), size (0), pos (0)
373 ~data ()
375 /* Make sure the derived and/or using class know what they're
376 doing. */
377 gcc_checking_assert (!buffer);
380 protected:
381 char *use (unsigned count)
383 if (size < pos + count)
384 return NULL;
385 char *res = &buffer[pos];
386 pos += count;
387 return res;
390 public:
391 void unuse (unsigned count)
393 pos -= count;
396 public:
397 static allocator simple_memory;
400 /* The simple data allocator. */
401 data::allocator data::simple_memory;
403 /* Grow buffer to at least size NEEDED. */
405 void
406 data::allocator::grow (data &obj, unsigned needed, bool exact)
408 gcc_checking_assert (needed ? needed > obj.size : !obj.size);
409 if (!needed)
410 /* Pick a default size. */
411 needed = EXPERIMENT (100, 1000);
413 if (!exact)
414 needed *= 2;
415 obj.buffer = grow (obj.buffer, needed);
416 if (obj.buffer)
417 obj.size = needed;
418 else
419 obj.pos = obj.size = 0;
422 /* Free a buffer. */
424 void
425 data::allocator::shrink (data &obj)
427 shrink (obj.buffer);
428 obj.buffer = NULL;
429 obj.size = 0;
432 char *
433 data::allocator::grow (char *ptr, unsigned needed)
435 return XRESIZEVAR (char, ptr, needed);
438 void
439 data::allocator::shrink (char *ptr)
441 XDELETEVEC (ptr);
444 /* Byte streamer base. Buffer with read/write position and smarts
445 for single bits. */
447 class bytes : public data {
448 public:
449 typedef data parent;
451 protected:
452 uint32_t bit_val; /* Bit buffer. */
453 unsigned bit_pos; /* Next bit in bit buffer. */
455 public:
456 bytes ()
457 :parent (), bit_val (0), bit_pos (0)
459 ~bytes ()
463 protected:
464 unsigned calc_crc (unsigned) const;
466 protected:
467 /* Finish bit packet. Rewind the bytes not used. */
468 unsigned bit_flush ()
470 gcc_assert (bit_pos);
471 unsigned bytes = (bit_pos + 7) / 8;
472 unuse (4 - bytes);
473 bit_pos = 0;
474 bit_val = 0;
475 return bytes;
479 /* Calculate the crc32 of the buffer. Note the CRC is stored in the
480 first 4 bytes, so don't include them. */
482 unsigned
483 bytes::calc_crc (unsigned l) const
485 unsigned crc = 0;
486 for (size_t ix = 4; ix < l; ix++)
487 crc = crc32_byte (crc, buffer[ix]);
488 return crc;
491 class elf_in;
493 /* Byte stream reader. */
495 class bytes_in : public bytes {
496 typedef bytes parent;
498 protected:
499 bool overrun; /* Sticky read-too-much flag. */
501 public:
502 bytes_in ()
503 : parent (), overrun (false)
506 ~bytes_in ()
510 public:
511 /* Begin reading a named section. */
512 bool begin (location_t loc, elf_in *src, const char *name);
513 /* Begin reading a numbered section with optional name. */
514 bool begin (location_t loc, elf_in *src, unsigned, const char * = NULL);
515 /* Complete reading a buffer. Propagate errors and return true on
516 success. */
517 bool end (elf_in *src);
518 /* Return true if there is unread data. */
519 bool more_p () const
521 return pos != size;
524 public:
525 /* Start reading at OFFSET. */
526 void random_access (unsigned offset)
528 if (offset > size)
529 set_overrun ();
530 pos = offset;
531 bit_pos = bit_val = 0;
534 public:
535 void align (unsigned boundary)
537 if (unsigned pad = pos & (boundary - 1))
538 read (boundary - pad);
541 public:
542 const char *read (unsigned count)
544 char *ptr = use (count);
545 if (!ptr)
546 set_overrun ();
547 return ptr;
550 public:
551 bool check_crc () const;
552 /* We store the CRC in the first 4 bytes, using host endianness. */
553 unsigned get_crc () const
555 return *(const unsigned *)&buffer[0];
558 public:
559 /* Manipulate the overrun flag. */
560 bool get_overrun () const
562 return overrun;
564 void set_overrun ()
566 overrun = true;
569 public:
570 unsigned u32 (); /* Read uncompressed integer. */
572 public:
573 bool b (); /* Read a bool. */
574 void bflush (); /* Completed a block of bools. */
576 private:
577 void bfill (); /* Get the next block of bools. */
579 public:
580 int c (); /* Read a char. */
581 int i (); /* Read a signed int. */
582 unsigned u (); /* Read an unsigned int. */
583 size_t z (); /* Read a size_t. */
584 HOST_WIDE_INT wi (); /* Read a HOST_WIDE_INT. */
585 unsigned HOST_WIDE_INT wu (); /* Read an unsigned HOST_WIDE_INT. */
586 const char *str (size_t * = NULL); /* Read a string. */
587 const void *buf (size_t); /* Read a fixed-length buffer. */
588 cpp_hashnode *cpp_node (); /* Read a cpp node. */
591 /* Verify the buffer's CRC is correct. */
593 bool
594 bytes_in::check_crc () const
596 if (size < 4)
597 return false;
599 unsigned c_crc = calc_crc (size);
600 if (c_crc != get_crc ())
601 return false;
603 return true;
606 class elf_out;
608 /* Byte stream writer. */
610 class bytes_out : public bytes {
611 typedef bytes parent;
613 public:
614 allocator *memory; /* Obtainer of memory. */
616 public:
617 bytes_out (allocator *memory)
618 : parent (), memory (memory)
621 ~bytes_out ()
625 public:
626 bool streaming_p () const
628 return memory != NULL;
631 public:
632 void set_crc (unsigned *crc_ptr);
634 public:
635 /* Begin writing, maybe reserve space for CRC. */
636 void begin (bool need_crc = true);
637 /* Finish writing. Spill to section by number. */
638 unsigned end (elf_out *, unsigned, unsigned *crc_ptr = NULL);
640 public:
641 void align (unsigned boundary)
643 if (unsigned pad = pos & (boundary - 1))
644 write (boundary - pad);
647 public:
648 char *write (unsigned count, bool exact = false)
650 if (size < pos + count)
651 memory->grow (*this, pos + count, exact);
652 return use (count);
655 public:
656 void u32 (unsigned); /* Write uncompressed integer. */
658 public:
659 void b (bool); /* Write bool. */
660 void bflush (); /* Finish block of bools. */
662 public:
663 void c (unsigned char); /* Write unsigned char. */
664 void i (int); /* Write signed int. */
665 void u (unsigned); /* Write unsigned int. */
666 void z (size_t s); /* Write size_t. */
667 void wi (HOST_WIDE_INT); /* Write HOST_WIDE_INT. */
668 void wu (unsigned HOST_WIDE_INT); /* Write unsigned HOST_WIDE_INT. */
669 void str (const char *ptr)
671 str (ptr, strlen (ptr));
673 void cpp_node (const cpp_hashnode *node)
675 str ((const char *)NODE_NAME (node), NODE_LEN (node));
677 void str (const char *, size_t); /* Write string of known length. */
678 void buf (const void *, size_t); /* Write fixed length buffer. */
679 void *buf (size_t); /* Create a writable buffer */
681 public:
682 /* Format a NUL-terminated raw string. */
683 void printf (const char *, ...) ATTRIBUTE_PRINTF_2;
684 void print_time (const char *, const tm *, const char *);
686 public:
687 /* Dump instrumentation. */
688 static void instrument ();
690 protected:
691 /* Instrumentation. */
692 static unsigned spans[4];
693 static unsigned lengths[4];
694 static int is_set;
697 /* Instrumentation. */
698 unsigned bytes_out::spans[4];
699 unsigned bytes_out::lengths[4];
700 int bytes_out::is_set = -1;
702 /* If CRC_PTR non-null, set the CRC of the buffer. Mix the CRC into
703 that pointed to by CRC_PTR. */
705 void
706 bytes_out::set_crc (unsigned *crc_ptr)
708 if (crc_ptr)
710 gcc_checking_assert (pos >= 4);
712 unsigned crc = calc_crc (pos);
713 unsigned accum = *crc_ptr;
714 /* Only mix the existing *CRC_PTR if it is non-zero. */
715 accum = accum ? crc32_unsigned (accum, crc) : crc;
716 *crc_ptr = accum;
718 /* Buffer will be sufficiently aligned. */
719 *(unsigned *)buffer = crc;
723 /* Finish a set of bools. */
725 void
726 bytes_out::bflush ()
728 if (bit_pos)
730 u32 (bit_val);
731 lengths[2] += bit_flush ();
733 spans[2]++;
734 is_set = -1;
737 void
738 bytes_in::bflush ()
740 if (bit_pos)
741 bit_flush ();
744 /* When reading, we don't know how many bools we'll read in. So read
745 4 bytes-worth, and then rewind when flushing if we didn't need them
746 all. You can't have a block of bools closer than 4 bytes to the
747 end of the buffer. */
749 void
750 bytes_in::bfill ()
752 bit_val = u32 ();
755 /* Bools are packed into bytes. You cannot mix bools and non-bools.
756 You must call bflush before emitting another type. So batch your
757 bools.
759 It may be worth optimizing for most bools being zero. Some kind of
760 run-length encoding? */
762 void
763 bytes_out::b (bool x)
765 if (is_set != x)
767 is_set = x;
768 spans[x]++;
770 lengths[x]++;
771 bit_val |= unsigned (x) << bit_pos++;
772 if (bit_pos == 32)
774 u32 (bit_val);
775 lengths[2] += bit_flush ();
779 bool
780 bytes_in::b ()
782 if (!bit_pos)
783 bfill ();
784 bool v = (bit_val >> bit_pos++) & 1;
785 if (bit_pos == 32)
786 bit_flush ();
787 return v;
790 /* Exactly 4 bytes. Used internally for bool packing and a few other
791 places. We can't simply use uint32_t because (a) alignment and
792 (b) we need little-endian for the bool streaming rewinding to make
793 sense. */
795 void
796 bytes_out::u32 (unsigned val)
798 if (char *ptr = write (4))
800 ptr[0] = val;
801 ptr[1] = val >> 8;
802 ptr[2] = val >> 16;
803 ptr[3] = val >> 24;
807 unsigned
808 bytes_in::u32 ()
810 unsigned val = 0;
811 if (const char *ptr = read (4))
813 val |= (unsigned char)ptr[0];
814 val |= (unsigned char)ptr[1] << 8;
815 val |= (unsigned char)ptr[2] << 16;
816 val |= (unsigned char)ptr[3] << 24;
819 return val;
822 /* Chars are unsigned and written as single bytes. */
824 void
825 bytes_out::c (unsigned char v)
827 if (char *ptr = write (1))
828 *ptr = v;
832 bytes_in::c ()
834 int v = 0;
835 if (const char *ptr = read (1))
836 v = (unsigned char)ptr[0];
837 return v;
840 /* Ints 7-bit as a byte. Otherwise a 3bit count of following bytes in
841 big-endian form. 4 bits are in the first byte. */
843 void
844 bytes_out::i (int v)
846 if (char *ptr = write (1))
848 if (v <= 0x3f && v >= -0x40)
849 *ptr = v & 0x7f;
850 else
852 unsigned bytes = 0;
853 int probe;
854 if (v >= 0)
855 for (probe = v >> 8; probe > 0x7; probe >>= 8)
856 bytes++;
857 else
858 for (probe = v >> 8; probe < -0x8; probe >>= 8)
859 bytes++;
860 *ptr = 0x80 | bytes << 4 | (probe & 0xf);
861 if ((ptr = write (++bytes)))
862 for (; bytes--; v >>= 8)
863 ptr[bytes] = v & 0xff;
869 bytes_in::i ()
871 int v = 0;
872 if (const char *ptr = read (1))
874 v = *ptr & 0xff;
875 if (v & 0x80)
877 unsigned bytes = (v >> 4) & 0x7;
878 v &= 0xf;
879 if (v & 0x8)
880 v |= -1 ^ 0x7;
881 /* unsigned necessary due to left shifts of -ve values. */
882 unsigned uv = unsigned (v);
883 if ((ptr = read (++bytes)))
884 while (bytes--)
885 uv = (uv << 8) | (*ptr++ & 0xff);
886 v = int (uv);
888 else if (v & 0x40)
889 v |= -1 ^ 0x3f;
892 return v;
895 void
896 bytes_out::u (unsigned v)
898 if (char *ptr = write (1))
900 if (v <= 0x7f)
901 *ptr = v;
902 else
904 unsigned bytes = 0;
905 unsigned probe;
906 for (probe = v >> 8; probe > 0xf; probe >>= 8)
907 bytes++;
908 *ptr = 0x80 | bytes << 4 | probe;
909 if ((ptr = write (++bytes)))
910 for (; bytes--; v >>= 8)
911 ptr[bytes] = v & 0xff;
916 unsigned
917 bytes_in::u ()
919 unsigned v = 0;
921 if (const char *ptr = read (1))
923 v = *ptr & 0xff;
924 if (v & 0x80)
926 unsigned bytes = (v >> 4) & 0x7;
927 v &= 0xf;
928 if ((ptr = read (++bytes)))
929 while (bytes--)
930 v = (v << 8) | (*ptr++ & 0xff);
934 return v;
937 void
938 bytes_out::wi (HOST_WIDE_INT v)
940 if (char *ptr = write (1))
942 if (v <= 0x3f && v >= -0x40)
943 *ptr = v & 0x7f;
944 else
946 unsigned bytes = 0;
947 HOST_WIDE_INT probe;
948 if (v >= 0)
949 for (probe = v >> 8; probe > 0x7; probe >>= 8)
950 bytes++;
951 else
952 for (probe = v >> 8; probe < -0x8; probe >>= 8)
953 bytes++;
954 *ptr = 0x80 | bytes << 4 | (probe & 0xf);
955 if ((ptr = write (++bytes)))
956 for (; bytes--; v >>= 8)
957 ptr[bytes] = v & 0xff;
962 HOST_WIDE_INT
963 bytes_in::wi ()
965 HOST_WIDE_INT v = 0;
966 if (const char *ptr = read (1))
968 v = *ptr & 0xff;
969 if (v & 0x80)
971 unsigned bytes = (v >> 4) & 0x7;
972 v &= 0xf;
973 if (v & 0x8)
974 v |= -1 ^ 0x7;
975 /* unsigned necessary due to left shifts of -ve values. */
976 unsigned HOST_WIDE_INT uv = (unsigned HOST_WIDE_INT) v;
977 if ((ptr = read (++bytes)))
978 while (bytes--)
979 uv = (uv << 8) | (*ptr++ & 0xff);
980 v = (HOST_WIDE_INT) uv;
982 else if (v & 0x40)
983 v |= -1 ^ 0x3f;
986 return v;
989 /* unsigned wide ints are just written as signed wide ints. */
991 inline void
992 bytes_out::wu (unsigned HOST_WIDE_INT v)
994 wi ((HOST_WIDE_INT) v);
997 inline unsigned HOST_WIDE_INT
998 bytes_in::wu ()
1000 return (unsigned HOST_WIDE_INT) wi ();
1003 /* size_t written as unsigned or unsigned wide int. */
1005 inline void
1006 bytes_out::z (size_t s)
1008 if (sizeof (s) == sizeof (unsigned))
1009 u (s);
1010 else
1011 wu (s);
1014 inline size_t
1015 bytes_in::z ()
1017 if (sizeof (size_t) == sizeof (unsigned))
1018 return u ();
1019 else
1020 return wu ();
1023 /* Buffer simply memcpied. */
1024 void *
1025 bytes_out::buf (size_t len)
1027 align (sizeof (void *) * 2);
1028 return write (len);
1031 void
1032 bytes_out::buf (const void *src, size_t len)
1034 if (void *ptr = buf (len))
1035 memcpy (ptr, src, len);
1038 const void *
1039 bytes_in::buf (size_t len)
1041 align (sizeof (void *) * 2);
1042 const char *ptr = read (len);
1044 return ptr;
1047 /* strings as an size_t length, followed by the buffer. Make sure
1048 there's a NUL terminator on read. */
1050 void
1051 bytes_out::str (const char *string, size_t len)
1053 z (len);
1054 if (len)
1056 gcc_checking_assert (!string[len]);
1057 buf (string, len + 1);
1061 const char *
1062 bytes_in::str (size_t *len_p)
1064 size_t len = z ();
1066 /* We're about to trust some user data. */
1067 if (overrun)
1068 len = 0;
1069 if (len_p)
1070 *len_p = len;
1071 const char *str = NULL;
1072 if (len)
1074 str = reinterpret_cast<const char *> (buf (len + 1));
1075 if (!str || str[len])
1077 set_overrun ();
1078 str = NULL;
1081 return str ? str : "";
1084 cpp_hashnode *
1085 bytes_in::cpp_node ()
1087 size_t len;
1088 const char *s = str (&len);
1089 if (!len)
1090 return NULL;
1091 return ::cpp_node (get_identifier_with_length (s, len));
1094 /* Format a string directly to the buffer, including a terminating
1095 NUL. Intended for human consumption. */
1097 void
1098 bytes_out::printf (const char *format, ...)
1100 va_list args;
1101 /* Exercise buffer expansion. */
1102 size_t len = EXPERIMENT (10, 500);
1104 while (char *ptr = write (len))
1106 va_start (args, format);
1107 size_t actual = vsnprintf (ptr, len, format, args) + 1;
1108 va_end (args);
1109 if (actual <= len)
1111 unuse (len - actual);
1112 break;
1114 unuse (len);
1115 len = actual;
1119 void
1120 bytes_out::print_time (const char *kind, const tm *time, const char *tz)
1122 printf ("%stime: %4u/%02u/%02u %02u:%02u:%02u %s",
1123 kind, time->tm_year + 1900, time->tm_mon + 1, time->tm_mday,
1124 time->tm_hour, time->tm_min, time->tm_sec, tz);
1127 /* Encapsulated Lazy Records Of Named Declarations.
1128 Header: Stunningly Elf32_Ehdr-like
1129 Sections: Sectional data
1130 [1-N) : User data sections
1131 N .strtab : strings, stunningly ELF STRTAB-like
1132 Index: Section table, stunningly ELF32_Shdr-like. */
1134 class elf {
1135 protected:
1136 /* Constants used within the format. */
1137 enum private_constants {
1138 /* File kind. */
1139 ET_NONE = 0,
1140 EM_NONE = 0,
1141 OSABI_NONE = 0,
1143 /* File format. */
1144 EV_CURRENT = 1,
1145 CLASS32 = 1,
1146 DATA2LSB = 1,
1147 DATA2MSB = 2,
1149 /* Section numbering. */
1150 SHN_UNDEF = 0,
1151 SHN_LORESERVE = 0xff00,
1152 SHN_XINDEX = 0xffff,
1154 /* Section types. */
1155 SHT_NONE = 0, /* No contents. */
1156 SHT_PROGBITS = 1, /* Random bytes. */
1157 SHT_STRTAB = 3, /* A string table. */
1159 /* Section flags. */
1160 SHF_NONE = 0x00, /* Nothing. */
1161 SHF_STRINGS = 0x20, /* NUL-Terminated strings. */
1163 /* I really hope we do not get CMI files larger than 4GB. */
1164 MY_CLASS = CLASS32,
1165 /* It is host endianness that is relevant. */
1166 MY_ENDIAN = DATA2LSB
1167 #ifdef WORDS_BIGENDIAN
1168 ^ DATA2LSB ^ DATA2MSB
1169 #endif
1172 public:
1173 /* Constants visible to users. */
1174 enum public_constants {
1175 /* Special error codes. Breaking layering a bit. */
1176 E_BAD_DATA = -1, /* Random unexpected data errors. */
1177 E_BAD_LAZY = -2, /* Badly ordered laziness. */
1178 E_BAD_IMPORT = -3 /* A nested import failed. */
1181 protected:
1182 /* File identification. On-disk representation. */
1183 struct ident {
1184 uint8_t magic[4]; /* 0x7f, 'E', 'L', 'F' */
1185 uint8_t klass; /* 4:CLASS32 */
1186 uint8_t data; /* 5:DATA2[LM]SB */
1187 uint8_t version; /* 6:EV_CURRENT */
1188 uint8_t osabi; /* 7:OSABI_NONE */
1189 uint8_t abiver; /* 8: 0 */
1190 uint8_t pad[7]; /* 9-15 */
1192 /* File header. On-disk representation. */
1193 struct header {
1194 struct ident ident;
1195 uint16_t type; /* ET_NONE */
1196 uint16_t machine; /* EM_NONE */
1197 uint32_t version; /* EV_CURRENT */
1198 uint32_t entry; /* 0 */
1199 uint32_t phoff; /* 0 */
1200 uint32_t shoff; /* Section Header Offset in file */
1201 uint32_t flags;
1202 uint16_t ehsize; /* ELROND Header SIZE -- sizeof (header) */
1203 uint16_t phentsize; /* 0 */
1204 uint16_t phnum; /* 0 */
1205 uint16_t shentsize; /* Section Header SIZE -- sizeof (section) */
1206 uint16_t shnum; /* Section Header NUM */
1207 uint16_t shstrndx; /* Section Header STRing iNDeX */
1209 /* File section. On-disk representation. */
1210 struct section {
1211 uint32_t name; /* String table offset. */
1212 uint32_t type; /* SHT_* */
1213 uint32_t flags; /* SHF_* */
1214 uint32_t addr; /* 0 */
1215 uint32_t offset; /* OFFSET in file */
1216 uint32_t size; /* SIZE of section */
1217 uint32_t link; /* 0 */
1218 uint32_t info; /* 0 */
1219 uint32_t addralign; /* 0 */
1220 uint32_t entsize; /* ENTry SIZE, usually 0 */
1223 protected:
1224 data hdr; /* The header. */
1225 data sectab; /* The section table. */
1226 data strtab; /* String table. */
1227 int fd; /* File descriptor we're reading or writing. */
1228 int err; /* Sticky error code. */
1230 public:
1231 /* Construct from STREAM. E is errno if STREAM NULL. */
1232 elf (int fd, int e)
1233 :hdr (), sectab (), strtab (), fd (fd), err (fd >= 0 ? 0 : e)
1235 ~elf ()
1237 gcc_checking_assert (fd < 0 && !hdr.buffer
1238 && !sectab.buffer && !strtab.buffer);
1241 public:
1242 /* Return the error, if we have an error. */
1243 int get_error () const
1245 return err;
1247 /* Set the error, unless it's already been set. */
1248 void set_error (int e = E_BAD_DATA)
1250 if (!err)
1251 err = e;
1253 /* Get an error string. */
1254 const char *get_error (const char *) const;
1256 public:
1257 /* Begin reading/writing file. Return false on error. */
1258 bool begin () const
1260 return !get_error ();
1262 /* Finish reading/writing file. Return false on error. */
1263 bool end ();
1266 /* Return error string. */
1268 const char *
1269 elf::get_error (const char *name) const
1271 if (!name)
1272 return "Unknown CMI mapping";
1274 switch (err)
1276 case 0:
1277 gcc_unreachable ();
1278 case E_BAD_DATA:
1279 return "Bad file data";
1280 case E_BAD_IMPORT:
1281 return "Bad import dependency";
1282 case E_BAD_LAZY:
1283 return "Bad lazy ordering";
1284 default:
1285 return xstrerror (err);
1289 /* Finish file, return true if there's an error. */
1291 bool
1292 elf::end ()
1294 /* Close the stream and free the section table. */
1295 if (fd >= 0 && close (fd))
1296 set_error (errno);
1297 fd = -1;
1299 return !get_error ();
1302 /* ELROND reader. */
1304 class elf_in : public elf {
1305 typedef elf parent;
1307 private:
1308 /* For freezing & defrosting. */
1309 #if !defined (HOST_LACKS_INODE_NUMBERS)
1310 dev_t device;
1311 ino_t inode;
1312 #endif
1314 public:
1315 elf_in (int fd, int e)
1316 :parent (fd, e)
1319 ~elf_in ()
1323 public:
1324 bool is_frozen () const
1326 return fd < 0 && hdr.pos;
1328 bool is_freezable () const
1330 return fd >= 0 && hdr.pos;
1332 void freeze ();
1333 bool defrost (const char *);
1335 /* If BYTES is in the mmapped area, allocate a new buffer for it. */
1336 void preserve (bytes_in &bytes ATTRIBUTE_UNUSED)
1338 #if MAPPED_READING
1339 if (hdr.buffer && bytes.buffer >= hdr.buffer
1340 && bytes.buffer < hdr.buffer + hdr.pos)
1342 char *buf = bytes.buffer;
1343 bytes.buffer = data::simple_memory.grow (NULL, bytes.size);
1344 memcpy (bytes.buffer, buf, bytes.size);
1346 #endif
1348 /* If BYTES is not in SELF's mmapped area, free it. SELF might be
1349 NULL. */
1350 static void release (elf_in *self ATTRIBUTE_UNUSED, bytes_in &bytes)
1352 #if MAPPED_READING
1353 if (!(self && self->hdr.buffer && bytes.buffer >= self->hdr.buffer
1354 && bytes.buffer < self->hdr.buffer + self->hdr.pos))
1355 #endif
1356 data::simple_memory.shrink (bytes.buffer);
1357 bytes.buffer = NULL;
1358 bytes.size = 0;
1361 public:
1362 static void grow (data &data, unsigned needed)
1364 gcc_checking_assert (!data.buffer);
1365 #if !MAPPED_READING
1366 data.buffer = XNEWVEC (char, needed);
1367 #endif
1368 data.size = needed;
1370 static void shrink (data &data)
1372 #if !MAPPED_READING
1373 XDELETEVEC (data.buffer);
1374 #endif
1375 data.buffer = NULL;
1376 data.size = 0;
1379 public:
1380 const section *get_section (unsigned s) const
1382 if (s * sizeof (section) < sectab.size)
1383 return reinterpret_cast<const section *>
1384 (&sectab.buffer[s * sizeof (section)]);
1385 else
1386 return NULL;
1388 unsigned get_section_limit () const
1390 return sectab.size / sizeof (section);
1393 protected:
1394 const char *read (data *, unsigned, unsigned);
1396 public:
1397 /* Read section by number. */
1398 bool read (data *d, const section *s)
1400 return s && read (d, s->offset, s->size);
1403 /* Find section by name. */
1404 unsigned find (const char *name);
1405 /* Find section by index. */
1406 const section *find (unsigned snum, unsigned type = SHT_PROGBITS);
1408 public:
1409 /* Release the string table, when we're done with it. */
1410 void release ()
1412 shrink (strtab);
1415 public:
1416 bool begin (location_t);
1417 bool end ()
1419 release ();
1420 #if MAPPED_READING
1421 if (hdr.buffer)
1422 munmap (hdr.buffer, hdr.pos);
1423 hdr.buffer = NULL;
1424 #endif
1425 shrink (sectab);
1427 return parent::end ();
1430 public:
1431 /* Return string name at OFFSET. Checks OFFSET range. Always
1432 returns non-NULL. We know offset 0 is an empty string. */
1433 const char *name (unsigned offset)
1435 return &strtab.buffer[offset < strtab.size ? offset : 0];
1439 /* ELROND writer. */
1441 class elf_out : public elf, public data::allocator {
1442 typedef elf parent;
1443 /* Desired section alignment on disk. */
1444 static const int SECTION_ALIGN = 16;
1446 private:
1447 ptr_int_hash_map identtab; /* Map of IDENTIFIERS to strtab offsets. */
1448 unsigned pos; /* Write position in file. */
1449 #if MAPPED_WRITING
1450 unsigned offset; /* Offset of the mapping. */
1451 unsigned extent; /* Length of mapping. */
1452 unsigned page_size; /* System page size. */
1453 #endif
1455 public:
1456 elf_out (int fd, int e)
1457 :parent (fd, e), identtab (500), pos (0)
1459 #if MAPPED_WRITING
1460 offset = extent = 0;
1461 page_size = sysconf (_SC_PAGE_SIZE);
1462 if (page_size < SECTION_ALIGN)
1463 /* Something really strange. */
1464 set_error (EINVAL);
1465 #endif
1467 ~elf_out ()
1469 data::simple_memory.shrink (hdr);
1470 data::simple_memory.shrink (sectab);
1471 data::simple_memory.shrink (strtab);
1474 #if MAPPED_WRITING
1475 private:
1476 void create_mapping (unsigned ext, bool extending = true);
1477 void remove_mapping ();
1478 #endif
1480 protected:
1481 using allocator::grow;
1482 virtual char *grow (char *, unsigned needed);
1483 #if MAPPED_WRITING
1484 using allocator::shrink;
1485 virtual void shrink (char *);
1486 #endif
1488 public:
1489 unsigned get_section_limit () const
1491 return sectab.pos / sizeof (section);
1494 protected:
1495 unsigned add (unsigned type, unsigned name = 0,
1496 unsigned off = 0, unsigned size = 0, unsigned flags = SHF_NONE);
1497 unsigned write (const data &);
1498 #if MAPPED_WRITING
1499 unsigned write (const bytes_out &);
1500 #endif
1502 public:
1503 /* IDENTIFIER to strtab offset. */
1504 unsigned name (tree ident);
1505 /* String literal to strtab offset. */
1506 unsigned name (const char *n);
1507 /* Qualified name of DECL to strtab offset. */
1508 unsigned qualified_name (tree decl, bool is_defn);
1510 private:
1511 unsigned strtab_write (const char *s, unsigned l);
1512 void strtab_write (tree decl, int);
1514 public:
1515 /* Add a section with contents or strings. */
1516 unsigned add (const bytes_out &, bool string_p, unsigned name);
1518 public:
1519 /* Begin and end writing. */
1520 bool begin ();
1521 bool end ();
1524 /* Begin reading section NAME (of type PROGBITS) from SOURCE.
1525 Data always checked for CRC. */
1527 bool
1528 bytes_in::begin (location_t loc, elf_in *source, const char *name)
1530 unsigned snum = source->find (name);
1532 return begin (loc, source, snum, name);
1535 /* Begin reading section numbered SNUM with NAME (may be NULL). */
1537 bool
1538 bytes_in::begin (location_t loc, elf_in *source, unsigned snum, const char *name)
1540 if (!source->read (this, source->find (snum))
1541 || !size || !check_crc ())
1543 source->set_error (elf::E_BAD_DATA);
1544 source->shrink (*this);
1545 if (name)
1546 error_at (loc, "section %qs is missing or corrupted", name);
1547 else
1548 error_at (loc, "section #%u is missing or corrupted", snum);
1549 return false;
1551 pos = 4;
1552 return true;
1555 /* Finish reading a section. */
1557 bool
1558 bytes_in::end (elf_in *src)
1560 if (more_p ())
1561 set_overrun ();
1562 if (overrun)
1563 src->set_error ();
1565 src->shrink (*this);
1567 return !overrun;
1570 /* Begin writing buffer. */
1572 void
1573 bytes_out::begin (bool need_crc)
1575 if (need_crc)
1576 pos = 4;
1577 memory->grow (*this, 0, false);
1580 /* Finish writing buffer. Stream out to SINK as named section NAME.
1581 Return section number or 0 on failure. If CRC_PTR is true, crc
1582 the data. Otherwise it is a string section. */
1584 unsigned
1585 bytes_out::end (elf_out *sink, unsigned name, unsigned *crc_ptr)
1587 lengths[3] += pos;
1588 spans[3]++;
1590 set_crc (crc_ptr);
1591 unsigned sec_num = sink->add (*this, !crc_ptr, name);
1592 memory->shrink (*this);
1594 return sec_num;
1597 /* Close and open the file, without destroying it. */
1599 void
1600 elf_in::freeze ()
1602 gcc_checking_assert (!is_frozen ());
1603 #if MAPPED_READING
1604 if (munmap (hdr.buffer, hdr.pos) < 0)
1605 set_error (errno);
1606 #endif
1607 if (close (fd) < 0)
1608 set_error (errno);
1609 fd = -1;
1612 bool
1613 elf_in::defrost (const char *name)
1615 gcc_checking_assert (is_frozen ());
1616 struct stat stat;
1618 fd = open (name, O_RDONLY | O_CLOEXEC | O_BINARY);
1619 if (fd < 0 || fstat (fd, &stat) < 0)
1620 set_error (errno);
1621 else
1623 bool ok = hdr.pos == unsigned (stat.st_size);
1624 #ifndef HOST_LACKS_INODE_NUMBERS
1625 if (device != stat.st_dev
1626 || inode != stat.st_ino)
1627 ok = false;
1628 #endif
1629 if (!ok)
1630 set_error (EMFILE);
1631 #if MAPPED_READING
1632 if (ok)
1634 char *mapping = reinterpret_cast<char *>
1635 (mmap (NULL, hdr.pos, PROT_READ, MAP_SHARED, fd, 0));
1636 if (mapping == MAP_FAILED)
1637 fail:
1638 set_error (errno);
1639 else
1641 if (madvise (mapping, hdr.pos, MADV_RANDOM))
1642 goto fail;
1644 /* These buffers are never NULL in this case. */
1645 strtab.buffer = mapping + strtab.pos;
1646 sectab.buffer = mapping + sectab.pos;
1647 hdr.buffer = mapping;
1650 #endif
1653 return !get_error ();
1656 /* Read at current position into BUFFER. Return true on success. */
1658 const char *
1659 elf_in::read (data *data, unsigned pos, unsigned length)
1661 #if MAPPED_READING
1662 if (pos + length > hdr.pos)
1664 set_error (EINVAL);
1665 return NULL;
1667 #else
1668 if (pos != ~0u && lseek (fd, pos, SEEK_SET) < 0)
1670 set_error (errno);
1671 return NULL;
1673 #endif
1674 grow (*data, length);
1675 #if MAPPED_READING
1676 data->buffer = hdr.buffer + pos;
1677 #else
1678 if (::read (fd, data->buffer, data->size) != ssize_t (length))
1680 set_error (errno);
1681 shrink (*data);
1682 return NULL;
1684 #endif
1686 return data->buffer;
1689 /* Read section SNUM of TYPE. Return section pointer or NULL on error. */
1691 const elf::section *
1692 elf_in::find (unsigned snum, unsigned type)
1694 const section *sec = get_section (snum);
1695 if (!snum || !sec || sec->type != type)
1696 return NULL;
1697 return sec;
1700 /* Find a section NAME and TYPE. Return section number, or zero on
1701 failure. */
1703 unsigned
1704 elf_in::find (const char *sname)
1706 for (unsigned pos = sectab.size; pos -= sizeof (section); )
1708 const section *sec
1709 = reinterpret_cast<const section *> (&sectab.buffer[pos]);
1711 if (0 == strcmp (sname, name (sec->name)))
1712 return pos / sizeof (section);
1715 return 0;
1718 /* Begin reading file. Verify header. Pull in section and string
1719 tables. Return true on success. */
1721 bool
1722 elf_in::begin (location_t loc)
1724 if (!parent::begin ())
1725 return false;
1727 struct stat stat;
1728 unsigned size = 0;
1729 if (!fstat (fd, &stat))
1731 #if !defined (HOST_LACKS_INODE_NUMBERS)
1732 device = stat.st_dev;
1733 inode = stat.st_ino;
1734 #endif
1735 /* Never generate files > 4GB, check we've not been given one. */
1736 if (stat.st_size == unsigned (stat.st_size))
1737 size = unsigned (stat.st_size);
1740 #if MAPPED_READING
1741 /* MAP_SHARED so that the file is backing store. If someone else
1742 concurrently writes it, they're wrong. */
1743 void *mapping = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0);
1744 if (mapping == MAP_FAILED)
1746 fail:
1747 set_error (errno);
1748 return false;
1750 /* We'll be hopping over this randomly. Some systems declare the
1751 first parm as char *, and other declare it as void *. */
1752 if (madvise (reinterpret_cast <char *> (mapping), size, MADV_RANDOM))
1753 goto fail;
1755 hdr.buffer = (char *)mapping;
1756 #else
1757 read (&hdr, 0, sizeof (header));
1758 #endif
1759 hdr.pos = size; /* Record size of the file. */
1761 const header *h = reinterpret_cast<const header *> (hdr.buffer);
1762 if (!h)
1763 return false;
1765 if (h->ident.magic[0] != 0x7f
1766 || h->ident.magic[1] != 'E'
1767 || h->ident.magic[2] != 'L'
1768 || h->ident.magic[3] != 'F')
1770 error_at (loc, "not Encapsulated Lazy Records of Named Declarations");
1771 failed:
1772 shrink (hdr);
1773 return false;
1776 /* We expect a particular format -- the ELF is not intended to be
1777 distributable. */
1778 if (h->ident.klass != MY_CLASS
1779 || h->ident.data != MY_ENDIAN
1780 || h->ident.version != EV_CURRENT
1781 || h->type != ET_NONE
1782 || h->machine != EM_NONE
1783 || h->ident.osabi != OSABI_NONE)
1785 error_at (loc, "unexpected encapsulation format or type");
1786 goto failed;
1789 int e = -1;
1790 if (!h->shoff || h->shentsize != sizeof (section))
1792 malformed:
1793 set_error (e);
1794 error_at (loc, "encapsulation is malformed");
1795 goto failed;
1798 unsigned strndx = h->shstrndx;
1799 unsigned shnum = h->shnum;
1800 if (shnum == SHN_XINDEX)
1802 if (!read (&sectab, h->shoff, sizeof (section)))
1804 section_table_fail:
1805 e = errno;
1806 goto malformed;
1808 shnum = get_section (0)->size;
1809 /* Freeing does mean we'll re-read it in the case we're not
1810 mapping, but this is going to be rare. */
1811 shrink (sectab);
1814 if (!shnum)
1815 goto malformed;
1817 if (!read (&sectab, h->shoff, shnum * sizeof (section)))
1818 goto section_table_fail;
1820 if (strndx == SHN_XINDEX)
1821 strndx = get_section (0)->link;
1823 if (!read (&strtab, find (strndx, SHT_STRTAB)))
1824 goto malformed;
1826 /* The string table should be at least one byte, with NUL chars
1827 at either end. */
1828 if (!(strtab.size && !strtab.buffer[0]
1829 && !strtab.buffer[strtab.size - 1]))
1830 goto malformed;
1832 #if MAPPED_READING
1833 /* Record the offsets of the section and string tables. */
1834 sectab.pos = h->shoff;
1835 strtab.pos = shnum * sizeof (section);
1836 #else
1837 shrink (hdr);
1838 #endif
1840 return true;
1843 /* Create a new mapping. */
1845 #if MAPPED_WRITING
1846 void
1847 elf_out::create_mapping (unsigned ext, bool extending)
1849 #ifndef HAVE_POSIX_FALLOCATE
1850 #define posix_fallocate(fd,off,len) ftruncate (fd, off + len)
1851 #endif
1852 void *mapping = MAP_FAILED;
1853 if (extending && ext < 1024 * 1024)
1855 if (!posix_fallocate (fd, offset, ext * 2))
1856 mapping = mmap (NULL, ext * 2, PROT_READ | PROT_WRITE,
1857 MAP_SHARED, fd, offset);
1858 if (mapping != MAP_FAILED)
1859 ext *= 2;
1861 if (mapping == MAP_FAILED)
1863 if (!extending || !posix_fallocate (fd, offset, ext))
1864 mapping = mmap (NULL, ext, PROT_READ | PROT_WRITE,
1865 MAP_SHARED, fd, offset);
1866 if (mapping == MAP_FAILED)
1868 set_error (errno);
1869 mapping = NULL;
1870 ext = 0;
1873 #undef posix_fallocate
1874 hdr.buffer = (char *)mapping;
1875 extent = ext;
1877 #endif
1879 /* Flush out the current mapping. */
1881 #if MAPPED_WRITING
1882 void
1883 elf_out::remove_mapping ()
1885 if (hdr.buffer)
1887 /* MS_ASYNC dtrt with the removed mapping, including a
1888 subsequent overlapping remap. */
1889 if (msync (hdr.buffer, extent, MS_ASYNC)
1890 || munmap (hdr.buffer, extent))
1891 /* We're somewhat screwed at this point. */
1892 set_error (errno);
1895 hdr.buffer = NULL;
1897 #endif
1899 /* Grow a mapping of PTR to be NEEDED bytes long. This gets
1900 interesting if the new size grows the EXTENT. */
1902 char *
1903 elf_out::grow (char *data, unsigned needed)
1905 if (!data)
1907 /* First allocation, check we're aligned. */
1908 gcc_checking_assert (!(pos & (SECTION_ALIGN - 1)));
1909 #if MAPPED_WRITING
1910 data = hdr.buffer + (pos - offset);
1911 #endif
1914 #if MAPPED_WRITING
1915 unsigned off = data - hdr.buffer;
1916 if (off + needed > extent)
1918 /* We need to grow the mapping. */
1919 unsigned lwm = off & ~(page_size - 1);
1920 unsigned hwm = (off + needed + page_size - 1) & ~(page_size - 1);
1922 gcc_checking_assert (hwm > extent);
1924 remove_mapping ();
1926 offset += lwm;
1927 create_mapping (extent < hwm - lwm ? hwm - lwm : extent);
1929 data = hdr.buffer + (off - lwm);
1931 #else
1932 data = allocator::grow (data, needed);
1933 #endif
1935 return data;
1938 #if MAPPED_WRITING
1939 /* Shrinking is a NOP. */
1940 void
1941 elf_out::shrink (char *)
1944 #endif
1946 /* Write S of length L to the strtab buffer. L must include the ending
1947 NUL, if that's what you want. */
1949 unsigned
1950 elf_out::strtab_write (const char *s, unsigned l)
1952 if (strtab.pos + l > strtab.size)
1953 data::simple_memory.grow (strtab, strtab.pos + l, false);
1954 memcpy (strtab.buffer + strtab.pos, s, l);
1955 unsigned res = strtab.pos;
1956 strtab.pos += l;
1957 return res;
1960 /* Write qualified name of decl. INNER >0 if this is a definition, <0
1961 if this is a qualifier of an outer name. */
1963 void
1964 elf_out::strtab_write (tree decl, int inner)
1966 tree ctx = CP_DECL_CONTEXT (decl);
1967 if (TYPE_P (ctx))
1968 ctx = TYPE_NAME (ctx);
1969 if (ctx != global_namespace)
1970 strtab_write (ctx, -1);
1972 tree name = DECL_NAME (decl);
1973 if (!name)
1974 name = DECL_ASSEMBLER_NAME_RAW (decl);
1975 strtab_write (IDENTIFIER_POINTER (name), IDENTIFIER_LENGTH (name));
1977 if (inner)
1978 strtab_write (&"::{}"[inner+1], 2);
1981 /* Map IDENTIFIER IDENT to strtab offset. Inserts into strtab if not
1982 already there. */
1984 unsigned
1985 elf_out::name (tree ident)
1987 unsigned res = 0;
1988 if (ident)
1990 bool existed;
1991 int *slot = &identtab.get_or_insert (ident, &existed);
1992 if (!existed)
1993 *slot = strtab_write (IDENTIFIER_POINTER (ident),
1994 IDENTIFIER_LENGTH (ident) + 1);
1995 res = *slot;
1997 return res;
2000 /* Map LITERAL to strtab offset. Does not detect duplicates and
2001 expects LITERAL to remain live until strtab is written out. */
2003 unsigned
2004 elf_out::name (const char *literal)
2006 return strtab_write (literal, strlen (literal) + 1);
2009 /* Map a DECL's qualified name to strtab offset. Does not detect
2010 duplicates. */
2012 unsigned
2013 elf_out::qualified_name (tree decl, bool is_defn)
2015 gcc_checking_assert (DECL_P (decl) && decl != global_namespace);
2016 unsigned result = strtab.pos;
2018 strtab_write (decl, is_defn);
2019 strtab_write ("", 1);
2021 return result;
2024 /* Add section to file. Return section number. TYPE & NAME identify
2025 the section. OFF and SIZE identify the file location of its
2026 data. FLAGS contains additional info. */
2028 unsigned
2029 elf_out::add (unsigned type, unsigned name, unsigned off, unsigned size,
2030 unsigned flags)
2032 gcc_checking_assert (!(off & (SECTION_ALIGN - 1)));
2033 if (sectab.pos + sizeof (section) > sectab.size)
2034 data::simple_memory.grow (sectab, sectab.pos + sizeof (section), false);
2035 section *sec = reinterpret_cast<section *> (sectab.buffer + sectab.pos);
2036 memset (sec, 0, sizeof (section));
2037 sec->type = type;
2038 sec->flags = flags;
2039 sec->name = name;
2040 sec->offset = off;
2041 sec->size = size;
2042 if (flags & SHF_STRINGS)
2043 sec->entsize = 1;
2045 unsigned res = sectab.pos;
2046 sectab.pos += sizeof (section);
2047 return res / sizeof (section);
2050 /* Pad to the next alignment boundary, then write BUFFER to disk.
2051 Return the position of the start of the write, or zero on failure. */
2053 unsigned
2054 elf_out::write (const data &buffer)
2056 #if MAPPED_WRITING
2057 /* HDR is always mapped. */
2058 if (&buffer != &hdr)
2060 bytes_out out (this);
2061 grow (out, buffer.pos, true);
2062 if (out.buffer)
2063 memcpy (out.buffer, buffer.buffer, buffer.pos);
2064 shrink (out);
2066 else
2067 /* We should have been aligned during the first allocation. */
2068 gcc_checking_assert (!(pos & (SECTION_ALIGN - 1)));
2069 #else
2070 if (::write (fd, buffer.buffer, buffer.pos) != ssize_t (buffer.pos))
2072 set_error (errno);
2073 return 0;
2075 #endif
2076 unsigned res = pos;
2077 pos += buffer.pos;
2079 if (unsigned padding = -pos & (SECTION_ALIGN - 1))
2081 #if !MAPPED_WRITING
2082 /* Align the section on disk, should help the necessary copies.
2083 fseeking to extend is non-portable. */
2084 static char zero[SECTION_ALIGN];
2085 if (::write (fd, &zero, padding) != ssize_t (padding))
2086 set_error (errno);
2087 #endif
2088 pos += padding;
2090 return res;
2093 /* Write a streaming buffer. It must be using us as an allocator. */
2095 #if MAPPED_WRITING
2096 unsigned
2097 elf_out::write (const bytes_out &buf)
2099 gcc_checking_assert (buf.memory == this);
2100 /* A directly mapped buffer. */
2101 gcc_checking_assert (buf.buffer - hdr.buffer >= 0
2102 && buf.buffer - hdr.buffer + buf.size <= extent);
2103 unsigned res = pos;
2104 pos += buf.pos;
2106 /* Align up. We're not going to advance into the next page. */
2107 pos += -pos & (SECTION_ALIGN - 1);
2109 return res;
2111 #endif
2113 /* Write data and add section. STRING_P is true for a string
2114 section, false for PROGBITS. NAME identifies the section (0 is the
2115 empty name). DATA is the contents. Return section number or 0 on
2116 failure (0 is the undef section). */
2118 unsigned
2119 elf_out::add (const bytes_out &data, bool string_p, unsigned name)
2121 unsigned off = write (data);
2123 return add (string_p ? SHT_STRTAB : SHT_PROGBITS, name,
2124 off, data.pos, string_p ? SHF_STRINGS : SHF_NONE);
2127 /* Begin writing the file. Initialize the section table and write an
2128 empty header. Return false on failure. */
2130 bool
2131 elf_out::begin ()
2133 if (!parent::begin ())
2134 return false;
2136 /* Let the allocators pick a default. */
2137 data::simple_memory.grow (strtab, 0, false);
2138 data::simple_memory.grow (sectab, 0, false);
2140 /* The string table starts with an empty string. */
2141 name ("");
2143 /* Create the UNDEF section. */
2144 add (SHT_NONE);
2146 #if MAPPED_WRITING
2147 /* Start a mapping. */
2148 create_mapping (EXPERIMENT (page_size,
2149 (32767 + page_size) & ~(page_size - 1)));
2150 if (!hdr.buffer)
2151 return false;
2152 #endif
2154 /* Write an empty header. */
2155 grow (hdr, sizeof (header), true);
2156 header *h = reinterpret_cast<header *> (hdr.buffer);
2157 memset (h, 0, sizeof (header));
2158 hdr.pos = hdr.size;
2159 write (hdr);
2160 return !get_error ();
2163 /* Finish writing the file. Write out the string & section tables.
2164 Fill in the header. Return true on error. */
2166 bool
2167 elf_out::end ()
2169 if (fd >= 0)
2171 /* Write the string table. */
2172 unsigned strnam = name (".strtab");
2173 unsigned stroff = write (strtab);
2174 unsigned strndx = add (SHT_STRTAB, strnam, stroff, strtab.pos,
2175 SHF_STRINGS);
2177 /* Store escape values in section[0]. */
2178 if (strndx >= SHN_LORESERVE)
2180 reinterpret_cast<section *> (sectab.buffer)->link = strndx;
2181 strndx = SHN_XINDEX;
2183 unsigned shnum = sectab.pos / sizeof (section);
2184 if (shnum >= SHN_LORESERVE)
2186 reinterpret_cast<section *> (sectab.buffer)->size = shnum;
2187 shnum = SHN_XINDEX;
2190 unsigned shoff = write (sectab);
2192 #if MAPPED_WRITING
2193 if (offset)
2195 remove_mapping ();
2196 offset = 0;
2197 create_mapping ((sizeof (header) + page_size - 1) & ~(page_size - 1),
2198 false);
2200 unsigned length = pos;
2201 #else
2202 if (lseek (fd, 0, SEEK_SET) < 0)
2203 set_error (errno);
2204 #endif
2205 /* Write header. */
2206 if (!get_error ())
2208 /* Write the correct header now. */
2209 header *h = reinterpret_cast<header *> (hdr.buffer);
2210 h->ident.magic[0] = 0x7f;
2211 h->ident.magic[1] = 'E'; /* Elrond */
2212 h->ident.magic[2] = 'L'; /* is an */
2213 h->ident.magic[3] = 'F'; /* elf. */
2214 h->ident.klass = MY_CLASS;
2215 h->ident.data = MY_ENDIAN;
2216 h->ident.version = EV_CURRENT;
2217 h->ident.osabi = OSABI_NONE;
2218 h->type = ET_NONE;
2219 h->machine = EM_NONE;
2220 h->version = EV_CURRENT;
2221 h->shoff = shoff;
2222 h->ehsize = sizeof (header);
2223 h->shentsize = sizeof (section);
2224 h->shnum = shnum;
2225 h->shstrndx = strndx;
2227 pos = 0;
2228 write (hdr);
2231 #if MAPPED_WRITING
2232 remove_mapping ();
2233 if (ftruncate (fd, length))
2234 set_error (errno);
2235 #endif
2238 data::simple_memory.shrink (sectab);
2239 data::simple_memory.shrink (strtab);
2241 return parent::end ();
2244 /********************************************************************/
2246 /* A dependency set. This is used during stream out to determine the
2247 connectivity of the graph. Every namespace-scope declaration that
2248 needs writing has a depset. The depset is filled with the (depsets
2249 of) declarations within this module that it references. For a
2250 declaration that'll generally be named types. For definitions
2251 it'll also be declarations in the body.
2253 From that we can convert the graph to a DAG, via determining the
2254 Strongly Connected Clusters. Each cluster is streamed
2255 independently, and thus we achieve lazy loading.
2257 Other decls that get a depset are namespaces themselves and
2258 unnameable declarations. */
2260 class depset {
2261 private:
2262 tree entity; /* Entity, or containing namespace. */
2263 uintptr_t discriminator; /* Flags or identifier. */
2265 public:
2266 /* The kinds of entity the depset could describe. The ordering is
2267 significant, see entity_kind_name. */
2268 enum entity_kind
2270 EK_DECL, /* A decl. */
2271 EK_SPECIALIZATION, /* A specialization. */
2272 EK_PARTIAL, /* A partial specialization. */
2273 EK_USING, /* A using declaration (at namespace scope). */
2274 EK_NAMESPACE, /* A namespace. */
2275 EK_REDIRECT, /* Redirect to a template_decl. */
2276 EK_EXPLICIT_HWM,
2277 EK_BINDING = EK_EXPLICIT_HWM, /* Implicitly encoded. */
2278 EK_FOR_BINDING, /* A decl being inserted for a binding. */
2279 EK_INNER_DECL, /* A decl defined outside of it's imported
2280 context. */
2281 EK_DIRECT_HWM = EK_PARTIAL + 1,
2283 EK_BITS = 3 /* Only need to encode below EK_EXPLICIT_HWM. */
2286 private:
2287 /* Placement of bit fields in discriminator. */
2288 enum disc_bits
2290 DB_ZERO_BIT, /* Set to disambiguate identifier from flags */
2291 DB_SPECIAL_BIT, /* First dep slot is special. */
2292 DB_KIND_BIT, /* Kind of the entity. */
2293 DB_KIND_BITS = EK_BITS,
2294 DB_DEFN_BIT = DB_KIND_BIT + DB_KIND_BITS,
2295 DB_IS_MEMBER_BIT, /* Is an out-of-class member. */
2296 DB_IS_INTERNAL_BIT, /* It is an (erroneous)
2297 internal-linkage entity. */
2298 DB_REFS_INTERNAL_BIT, /* Refers to an internal-linkage
2299 entity. */
2300 DB_IMPORTED_BIT, /* An imported entity. */
2301 DB_UNREACHED_BIT, /* A yet-to-be reached entity. */
2302 DB_HIDDEN_BIT, /* A hidden binding. */
2303 /* The following bits are not independent, but enumerating them is
2304 awkward. */
2305 DB_ALIAS_TMPL_INST_BIT, /* An alias template instantiation. */
2306 DB_ALIAS_SPEC_BIT, /* Specialization of an alias template
2307 (in both spec tables). */
2308 DB_TYPE_SPEC_BIT, /* Specialization in the type table.
2310 DB_FRIEND_SPEC_BIT, /* An instantiated template friend. */
2313 public:
2314 /* The first slot is special for EK_SPECIALIZATIONS it is a
2315 spec_entry pointer. It is not relevant for the SCC
2316 determination. */
2317 vec<depset *> deps; /* Depsets we reference. */
2319 public:
2320 unsigned cluster; /* Strongly connected cluster, later entity number */
2321 unsigned section; /* Section written to. */
2322 /* During SCC construction, section is lowlink, until the depset is
2323 removed from the stack. See Tarjan algorithm for details. */
2325 private:
2326 /* Construction via factories. Destruction via hash traits. */
2327 depset (tree entity);
2328 ~depset ();
2330 public:
2331 static depset *make_binding (tree, tree);
2332 static depset *make_entity (tree, entity_kind, bool = false);
2333 /* Late setting a binding name -- /then/ insert into hash! */
2334 inline void set_binding_name (tree name)
2336 gcc_checking_assert (!get_name ());
2337 discriminator = reinterpret_cast<uintptr_t> (name);
2340 private:
2341 template<unsigned I> void set_flag_bit ()
2343 gcc_checking_assert (I < 2 || !is_binding ());
2344 discriminator |= 1u << I;
2346 template<unsigned I> void clear_flag_bit ()
2348 gcc_checking_assert (I < 2 || !is_binding ());
2349 discriminator &= ~(1u << I);
2351 template<unsigned I> bool get_flag_bit () const
2353 gcc_checking_assert (I < 2 || !is_binding ());
2354 return bool ((discriminator >> I) & 1);
2357 public:
2358 bool is_binding () const
2360 return !get_flag_bit<DB_ZERO_BIT> ();
2362 entity_kind get_entity_kind () const
2364 if (is_binding ())
2365 return EK_BINDING;
2366 return entity_kind ((discriminator >> DB_KIND_BIT) & ((1u << EK_BITS) - 1));
2368 const char *entity_kind_name () const;
2370 public:
2371 bool has_defn () const
2373 return get_flag_bit<DB_DEFN_BIT> ();
2376 public:
2377 /* This class-member is defined here, but the class was imported. */
2378 bool is_member () const
2380 gcc_checking_assert (get_entity_kind () == EK_DECL);
2381 return get_flag_bit<DB_IS_MEMBER_BIT> ();
2383 public:
2384 bool is_internal () const
2386 return get_flag_bit<DB_IS_INTERNAL_BIT> ();
2388 bool refs_internal () const
2390 return get_flag_bit<DB_REFS_INTERNAL_BIT> ();
2392 bool is_import () const
2394 return get_flag_bit<DB_IMPORTED_BIT> ();
2396 bool is_unreached () const
2398 return get_flag_bit<DB_UNREACHED_BIT> ();
2400 bool is_alias_tmpl_inst () const
2402 return get_flag_bit<DB_ALIAS_TMPL_INST_BIT> ();
2404 bool is_alias () const
2406 return get_flag_bit<DB_ALIAS_SPEC_BIT> ();
2408 bool is_hidden () const
2410 return get_flag_bit<DB_HIDDEN_BIT> ();
2412 bool is_type_spec () const
2414 return get_flag_bit<DB_TYPE_SPEC_BIT> ();
2416 bool is_friend_spec () const
2418 return get_flag_bit<DB_FRIEND_SPEC_BIT> ();
2421 public:
2422 /* We set these bit outside of depset. */
2423 void set_hidden_binding ()
2425 set_flag_bit<DB_HIDDEN_BIT> ();
2427 void clear_hidden_binding ()
2429 clear_flag_bit<DB_HIDDEN_BIT> ();
2432 public:
2433 bool is_special () const
2435 return get_flag_bit<DB_SPECIAL_BIT> ();
2437 void set_special ()
2439 set_flag_bit<DB_SPECIAL_BIT> ();
2442 public:
2443 tree get_entity () const
2445 return entity;
2447 tree get_name () const
2449 gcc_checking_assert (is_binding ());
2450 return reinterpret_cast <tree> (discriminator);
2453 public:
2454 /* Traits for a hash table of pointers to bindings. */
2455 struct traits {
2456 /* Each entry is a pointer to a depset. */
2457 typedef depset *value_type;
2458 /* We lookup by container:maybe-identifier pair. */
2459 typedef std::pair<tree,tree> compare_type;
2461 static const bool empty_zero_p = true;
2463 /* hash and equality for compare_type. */
2464 inline static hashval_t hash (const compare_type &p)
2466 hashval_t h = pointer_hash<tree_node>::hash (p.first);
2467 if (p.second)
2469 hashval_t nh = IDENTIFIER_HASH_VALUE (p.second);
2470 h = iterative_hash_hashval_t (h, nh);
2472 return h;
2474 inline static bool equal (const value_type b, const compare_type &p)
2476 if (b->entity != p.first)
2477 return false;
2479 if (p.second)
2480 return b->discriminator == reinterpret_cast<uintptr_t> (p.second);
2481 else
2482 return !b->is_binding ();
2485 /* (re)hasher for a binding itself. */
2486 inline static hashval_t hash (const value_type b)
2488 hashval_t h = pointer_hash<tree_node>::hash (b->entity);
2489 if (b->is_binding ())
2491 hashval_t nh = IDENTIFIER_HASH_VALUE (b->get_name ());
2492 h = iterative_hash_hashval_t (h, nh);
2494 return h;
2497 /* Empty via NULL. */
2498 static inline void mark_empty (value_type &p) {p = NULL;}
2499 static inline bool is_empty (value_type p) {return !p;}
2501 /* Nothing is deletable. Everything is insertable. */
2502 static bool is_deleted (value_type) { return false; }
2503 static void mark_deleted (value_type) { gcc_unreachable (); }
2505 /* We own the entities in the hash table. */
2506 static void remove (value_type p)
2508 delete (p);
2512 public:
2513 class hash : public hash_table<traits> {
2514 typedef traits::compare_type key_t;
2515 typedef hash_table<traits> parent;
2517 public:
2518 vec<depset *> worklist; /* Worklist of decls to walk. */
2519 hash *chain; /* Original table. */
2520 depset *current; /* Current depset being depended. */
2521 unsigned section; /* When writing out, the section. */
2522 bool sneakoscope; /* Detecting dark magic (of a voldemort). */
2523 bool reached_unreached; /* We reached an unreached entity. */
2525 public:
2526 hash (size_t size, hash *c = NULL)
2527 : parent (size), chain (c), current (NULL), section (0),
2528 sneakoscope (false), reached_unreached (false)
2530 worklist.create (size);
2532 ~hash ()
2534 worklist.release ();
2537 public:
2538 bool is_key_order () const
2540 return chain != NULL;
2543 private:
2544 depset **entity_slot (tree entity, bool = true);
2545 depset **binding_slot (tree ctx, tree name, bool = true);
2546 depset *maybe_add_declaration (tree decl);
2548 public:
2549 depset *find_dependency (tree entity);
2550 depset *find_binding (tree ctx, tree name);
2551 depset *make_dependency (tree decl, entity_kind);
2552 void add_dependency (depset *);
2554 public:
2555 void add_mergeable (depset *);
2556 depset *add_dependency (tree decl, entity_kind);
2557 void add_namespace_context (depset *, tree ns);
2559 private:
2560 static bool add_binding_entity (tree, WMB_Flags, void *);
2562 public:
2563 bool add_namespace_entities (tree ns, bitmap partitions);
2564 void add_specializations (bool decl_p);
2565 void add_partial_entities (vec<tree, va_gc> *);
2566 void add_class_entities (vec<tree, va_gc> *);
2568 public:
2569 void find_dependencies (module_state *);
2570 bool finalize_dependencies ();
2571 vec<depset *> connect ();
2574 public:
2575 struct tarjan {
2576 vec<depset *> result;
2577 vec<depset *> stack;
2578 unsigned index;
2580 tarjan (unsigned size)
2581 : index (0)
2583 result.create (size);
2584 stack.create (50);
2586 ~tarjan ()
2588 gcc_assert (!stack.length ());
2589 stack.release ();
2592 public:
2593 void connect (depset *);
2597 inline
2598 depset::depset (tree entity)
2599 :entity (entity), discriminator (0), cluster (0), section (0)
2601 deps.create (0);
2604 inline
2605 depset::~depset ()
2607 deps.release ();
2610 const char *
2611 depset::entity_kind_name () const
2613 /* Same order as entity_kind. */
2614 static const char *const names[] =
2615 {"decl", "specialization", "partial", "using",
2616 "namespace", "redirect", "binding"};
2617 entity_kind kind = get_entity_kind ();
2618 gcc_checking_assert (kind < sizeof (names) / sizeof(names[0]));
2619 return names[kind];
2622 /* Create a depset for a namespace binding NS::NAME. */
2624 depset *depset::make_binding (tree ns, tree name)
2626 depset *binding = new depset (ns);
2628 binding->discriminator = reinterpret_cast <uintptr_t> (name);
2630 return binding;
2633 depset *depset::make_entity (tree entity, entity_kind ek, bool is_defn)
2635 depset *r = new depset (entity);
2637 r->discriminator = ((1 << DB_ZERO_BIT)
2638 | (ek << DB_KIND_BIT)
2639 | is_defn << DB_DEFN_BIT);
2641 return r;
2644 class pending_key
2646 public:
2647 tree ns;
2648 tree id;
2651 template<>
2652 struct default_hash_traits<pending_key>
2654 using value_type = pending_key;
2656 static const bool empty_zero_p = false;
2657 static hashval_t hash (const value_type &k)
2659 hashval_t h = IDENTIFIER_HASH_VALUE (k.id);
2660 h = iterative_hash_hashval_t (DECL_UID (k.ns), h);
2662 return h;
2664 static bool equal (const value_type &k, const value_type &l)
2666 return k.ns == l.ns && k.id == l.id;
2668 static void mark_empty (value_type &k)
2670 k.ns = k.id = NULL_TREE;
2672 static void mark_deleted (value_type &k)
2674 k.ns = NULL_TREE;
2675 gcc_checking_assert (k.id);
2677 static bool is_empty (const value_type &k)
2679 return k.ns == NULL_TREE && k.id == NULL_TREE;
2681 static bool is_deleted (const value_type &k)
2683 return k.ns == NULL_TREE && k.id != NULL_TREE;
2685 static void remove (value_type &)
2690 typedef hash_map<pending_key, auto_vec<unsigned>> pending_map_t;
2692 /* Not-loaded entities that are keyed to a namespace-scope
2693 identifier. See module_state::write_pendings for details. */
2694 pending_map_t *pending_table;
2696 /* Decls that need some post processing once a batch of lazy loads has
2697 completed. */
2698 vec<tree, va_heap, vl_embed> *post_load_decls;
2700 /* Some entities are attached to another entitity for ODR purposes.
2701 For example, at namespace scope, 'inline auto var = []{};', that
2702 lambda is attached to 'var', and follows its ODRness. */
2703 typedef hash_map<tree, auto_vec<tree>> attached_map_t;
2704 static attached_map_t *attached_table;
2706 /********************************************************************/
2707 /* Tree streaming. The tree streaming is very specific to the tree
2708 structures themselves. A tag indicates the kind of tree being
2709 streamed. -ve tags indicate backreferences to already-streamed
2710 trees. Backreferences are auto-numbered. */
2712 /* Tree tags. */
2713 enum tree_tag {
2714 tt_null, /* NULL_TREE. */
2715 tt_fixed, /* Fixed vector index. */
2717 tt_node, /* By-value node. */
2718 tt_decl, /* By-value mergeable decl. */
2719 tt_tpl_parm, /* Template parm. */
2721 /* The ordering of the following 4 is relied upon in
2722 trees_out::tree_node. */
2723 tt_id, /* Identifier node. */
2724 tt_conv_id, /* Conversion operator name. */
2725 tt_anon_id, /* Anonymous name. */
2726 tt_lambda_id, /* Lambda name. */
2728 tt_typedef_type, /* A (possibly implicit) typedefed type. */
2729 tt_derived_type, /* A type derived from another type. */
2730 tt_variant_type, /* A variant of another type. */
2732 tt_tinfo_var, /* Typeinfo object. */
2733 tt_tinfo_typedef, /* Typeinfo typedef. */
2734 tt_ptrmem_type, /* Pointer to member type. */
2736 tt_parm, /* Function parameter or result. */
2737 tt_enum_value, /* An enum value. */
2738 tt_enum_decl, /* An enum decl. */
2739 tt_data_member, /* Data member/using-decl. */
2741 tt_binfo, /* A BINFO. */
2742 tt_vtable, /* A vtable. */
2743 tt_thunk, /* A thunk. */
2744 tt_clone_ref,
2746 tt_entity, /* A extra-cluster entity. */
2748 tt_template, /* The TEMPLATE_RESULT of a template. */
2751 enum walk_kind {
2752 WK_none, /* No walk to do (a back- or fixed-ref happened). */
2753 WK_normal, /* Normal walk (by-name if possible). */
2755 WK_value, /* By-value walk. */
2758 enum merge_kind
2760 MK_unique, /* Known unique. */
2761 MK_named, /* Found by CTX, NAME + maybe_arg types etc. */
2762 MK_field, /* Found by CTX and index on TYPE_FIELDS */
2763 MK_vtable, /* Found by CTX and index on TYPE_VTABLES */
2764 MK_as_base, /* Found by CTX. */
2766 MK_partial,
2768 MK_enum, /* Found by CTX, & 1stMemberNAME. */
2769 MK_attached, /* Found by attachee & index. */
2771 MK_friend_spec, /* Like named, but has a tmpl & args too. */
2772 MK_local_friend, /* Found by CTX, index. */
2774 MK_indirect_lwm = MK_enum,
2776 /* Template specialization kinds below. These are all found via
2777 primary template and specialization args. */
2778 MK_template_mask = 0x10, /* A template specialization. */
2780 MK_tmpl_decl_mask = 0x4, /* In decl table. */
2781 MK_tmpl_alias_mask = 0x2, /* Also in type table */
2783 MK_tmpl_tmpl_mask = 0x1, /* We want TEMPLATE_DECL. */
2785 MK_type_spec = MK_template_mask,
2786 MK_decl_spec = MK_template_mask | MK_tmpl_decl_mask,
2787 MK_alias_spec = MK_decl_spec | MK_tmpl_alias_mask,
2789 MK_hwm = 0x20
2791 /* This is more than a debugging array. NULLs are used to determine
2792 an invalid merge_kind number. */
2793 static char const *const merge_kind_name[MK_hwm] =
2795 "unique", "named", "field", "vtable", /* 0...3 */
2796 "asbase", "partial", "enum", "attached", /* 4...7 */
2798 "friend spec", "local friend", NULL, NULL, /* 8...11 */
2799 NULL, NULL, NULL, NULL,
2801 "type spec", "type tmpl spec", /* 16,17 type (template). */
2802 NULL, NULL,
2804 "decl spec", "decl tmpl spec", /* 20,21 decl (template). */
2805 "alias spec", "alias tmpl spec", /* 22,23 alias (template). */
2806 NULL, NULL, NULL, NULL,
2807 NULL, NULL, NULL, NULL,
2810 /* Mergeable entity location data. */
2811 struct merge_key {
2812 cp_ref_qualifier ref_q : 2;
2813 unsigned index;
2815 tree ret; /* Return type, if appropriate. */
2816 tree args; /* Arg types, if appropriate. */
2818 tree constraints; /* Constraints. */
2820 merge_key ()
2821 :ref_q (REF_QUAL_NONE), index (0),
2822 ret (NULL_TREE), args (NULL_TREE),
2823 constraints (NULL_TREE)
2828 struct duplicate_hash : nodel_ptr_hash<tree_node>
2830 #if 0
2831 /* This breaks variadic bases in the xtreme_header tests. Since ::equal is
2832 the default pointer_hash::equal, let's use the default hash as well. */
2833 inline static hashval_t hash (value_type decl)
2835 if (TREE_CODE (decl) == TREE_BINFO)
2836 decl = TYPE_NAME (BINFO_TYPE (decl));
2837 return hashval_t (DECL_UID (decl));
2839 #endif
2842 /* Hashmap of merged duplicates. Usually decls, but can contain
2843 BINFOs. */
2844 typedef hash_map<tree,uintptr_t,
2845 simple_hashmap_traits<duplicate_hash,uintptr_t> >
2846 duplicate_hash_map;
2848 /* Tree stream reader. Note that reading a stream doesn't mark the
2849 read trees with TREE_VISITED. Thus it's quite safe to have
2850 multiple concurrent readers. Which is good, because lazy
2851 loading. */
2852 class trees_in : public bytes_in {
2853 typedef bytes_in parent;
2855 private:
2856 module_state *state; /* Module being imported. */
2857 vec<tree> back_refs; /* Back references. */
2858 duplicate_hash_map *duplicates; /* Map from existings to duplicate. */
2859 vec<tree> post_decls; /* Decls to post process. */
2860 unsigned unused; /* Inhibit any interior TREE_USED
2861 marking. */
2863 public:
2864 trees_in (module_state *);
2865 ~trees_in ();
2867 public:
2868 int insert (tree);
2869 tree back_ref (int);
2871 private:
2872 tree start (unsigned = 0);
2874 public:
2875 /* Needed for binfo writing */
2876 bool core_bools (tree);
2878 private:
2879 /* Stream tree_core, lang_decl_specific and lang_type_specific
2880 bits. */
2881 bool core_vals (tree);
2882 bool lang_type_bools (tree);
2883 bool lang_type_vals (tree);
2884 bool lang_decl_bools (tree);
2885 bool lang_decl_vals (tree);
2886 bool lang_vals (tree);
2887 bool tree_node_bools (tree);
2888 bool tree_node_vals (tree);
2889 tree tree_value ();
2890 tree decl_value ();
2891 tree tpl_parm_value ();
2893 private:
2894 tree chained_decls (); /* Follow DECL_CHAIN. */
2895 vec<tree, va_heap> *vec_chained_decls ();
2896 vec<tree, va_gc> *tree_vec (); /* vec of tree. */
2897 vec<tree_pair_s, va_gc> *tree_pair_vec (); /* vec of tree_pair. */
2898 tree tree_list (bool has_purpose);
2900 public:
2901 /* Read a tree node. */
2902 tree tree_node (bool is_use = false);
2904 private:
2905 bool install_entity (tree decl);
2906 tree tpl_parms (unsigned &tpl_levels);
2907 bool tpl_parms_fini (tree decl, unsigned tpl_levels);
2908 bool tpl_header (tree decl, unsigned *tpl_levels);
2909 int fn_parms_init (tree);
2910 void fn_parms_fini (int tag, tree fn, tree existing, bool has_defn);
2911 unsigned add_indirect_tpl_parms (tree);
2912 public:
2913 bool add_indirects (tree);
2915 public:
2916 /* Serialize various definitions. */
2917 bool read_definition (tree decl);
2919 private:
2920 bool is_matching_decl (tree existing, tree decl, bool is_typedef);
2921 static bool install_implicit_member (tree decl);
2922 bool read_function_def (tree decl, tree maybe_template);
2923 bool read_var_def (tree decl, tree maybe_template);
2924 bool read_class_def (tree decl, tree maybe_template);
2925 bool read_enum_def (tree decl, tree maybe_template);
2927 public:
2928 tree decl_container ();
2929 tree key_mergeable (int tag, merge_kind, tree decl, tree inner, tree type,
2930 tree container, bool is_mod);
2931 unsigned binfo_mergeable (tree *);
2933 private:
2934 uintptr_t *find_duplicate (tree existing);
2935 void register_duplicate (tree decl, tree existing);
2936 /* Mark as an already diagnosed bad duplicate. */
2937 void unmatched_duplicate (tree existing)
2939 *find_duplicate (existing) |= 1;
2942 public:
2943 bool is_duplicate (tree decl)
2945 return find_duplicate (decl) != NULL;
2947 tree maybe_duplicate (tree decl)
2949 if (uintptr_t *dup = find_duplicate (decl))
2950 return reinterpret_cast<tree> (*dup & ~uintptr_t (1));
2951 return decl;
2953 tree odr_duplicate (tree decl, bool has_defn);
2955 public:
2956 /* Return the next decl to postprocess, or NULL. */
2957 tree post_process ()
2959 return post_decls.length () ? post_decls.pop () : NULL_TREE;
2961 private:
2962 /* Register DECL for postprocessing. */
2963 void post_process (tree decl)
2965 post_decls.safe_push (decl);
2968 private:
2969 void assert_definition (tree, bool installing);
2972 trees_in::trees_in (module_state *state)
2973 :parent (), state (state), unused (0)
2975 duplicates = NULL;
2976 back_refs.create (500);
2977 post_decls.create (0);
2980 trees_in::~trees_in ()
2982 delete (duplicates);
2983 back_refs.release ();
2984 post_decls.release ();
2987 /* Tree stream writer. */
2988 class trees_out : public bytes_out {
2989 typedef bytes_out parent;
2991 private:
2992 module_state *state; /* The module we are writing. */
2993 ptr_int_hash_map tree_map; /* Trees to references */
2994 depset::hash *dep_hash; /* Dependency table. */
2995 int ref_num; /* Back reference number. */
2996 unsigned section;
2997 #if CHECKING_P
2998 int importedness; /* Checker that imports not occurring
2999 inappropriately. +ve imports ok,
3000 -ve imports not ok. */
3001 #endif
3003 public:
3004 trees_out (allocator *, module_state *, depset::hash &deps, unsigned sec = 0);
3005 ~trees_out ();
3007 private:
3008 void mark_trees ();
3009 void unmark_trees ();
3011 public:
3012 /* Hey, let's ignore the well known STL iterator idiom. */
3013 void begin ();
3014 unsigned end (elf_out *sink, unsigned name, unsigned *crc_ptr);
3015 void end ();
3017 public:
3018 enum tags
3020 tag_backref = -1, /* Upper bound on the backrefs. */
3021 tag_value = 0, /* Write by value. */
3022 tag_fixed /* Lower bound on the fixed trees. */
3025 public:
3026 bool is_key_order () const
3028 return dep_hash->is_key_order ();
3031 public:
3032 int insert (tree, walk_kind = WK_normal);
3034 private:
3035 void start (tree, bool = false);
3037 private:
3038 walk_kind ref_node (tree);
3039 public:
3040 int get_tag (tree);
3041 void set_importing (int i ATTRIBUTE_UNUSED)
3043 #if CHECKING_P
3044 importedness = i;
3045 #endif
3048 private:
3049 void core_bools (tree);
3050 void core_vals (tree);
3051 void lang_type_bools (tree);
3052 void lang_type_vals (tree);
3053 void lang_decl_bools (tree);
3054 void lang_decl_vals (tree);
3055 void lang_vals (tree);
3056 void tree_node_bools (tree);
3057 void tree_node_vals (tree);
3059 private:
3060 void chained_decls (tree);
3061 void vec_chained_decls (tree);
3062 void tree_vec (vec<tree, va_gc> *);
3063 void tree_pair_vec (vec<tree_pair_s, va_gc> *);
3064 void tree_list (tree, bool has_purpose);
3066 public:
3067 /* Mark a node for by-value walking. */
3068 void mark_by_value (tree);
3070 public:
3071 void tree_node (tree);
3073 private:
3074 void install_entity (tree decl, depset *);
3075 void tpl_parms (tree parms, unsigned &tpl_levels);
3076 void tpl_parms_fini (tree decl, unsigned tpl_levels);
3077 void fn_parms_fini (tree) {}
3078 unsigned add_indirect_tpl_parms (tree);
3079 public:
3080 void add_indirects (tree);
3081 void fn_parms_init (tree);
3082 void tpl_header (tree decl, unsigned *tpl_levels);
3084 public:
3085 merge_kind get_merge_kind (tree decl, depset *maybe_dep);
3086 tree decl_container (tree decl);
3087 void key_mergeable (int tag, merge_kind, tree decl, tree inner,
3088 tree container, depset *maybe_dep);
3089 void binfo_mergeable (tree binfo);
3091 private:
3092 bool decl_node (tree, walk_kind ref);
3093 void type_node (tree);
3094 void tree_value (tree);
3095 void tpl_parm_value (tree);
3097 public:
3098 void decl_value (tree, depset *);
3100 public:
3101 /* Serialize various definitions. */
3102 void write_definition (tree decl);
3103 void mark_declaration (tree decl, bool do_defn);
3105 private:
3106 void mark_function_def (tree decl);
3107 void mark_var_def (tree decl);
3108 void mark_class_def (tree decl);
3109 void mark_enum_def (tree decl);
3110 void mark_class_member (tree decl, bool do_defn = true);
3111 void mark_binfos (tree type);
3113 private:
3114 void write_var_def (tree decl);
3115 void write_function_def (tree decl);
3116 void write_class_def (tree decl);
3117 void write_enum_def (tree decl);
3119 private:
3120 static void assert_definition (tree);
3122 public:
3123 static void instrument ();
3125 private:
3126 /* Tree instrumentation. */
3127 static unsigned tree_val_count;
3128 static unsigned decl_val_count;
3129 static unsigned back_ref_count;
3130 static unsigned null_count;
3133 /* Instrumentation counters. */
3134 unsigned trees_out::tree_val_count;
3135 unsigned trees_out::decl_val_count;
3136 unsigned trees_out::back_ref_count;
3137 unsigned trees_out::null_count;
3139 trees_out::trees_out (allocator *mem, module_state *state, depset::hash &deps,
3140 unsigned section)
3141 :parent (mem), state (state), tree_map (500),
3142 dep_hash (&deps), ref_num (0), section (section)
3144 #if CHECKING_P
3145 importedness = 0;
3146 #endif
3149 trees_out::~trees_out ()
3153 /********************************************************************/
3154 /* Location. We're aware of the line-map concept and reproduce it
3155 here. Each imported module allocates a contiguous span of ordinary
3156 maps, and of macro maps. adhoc maps are serialized by contents,
3157 not pre-allocated. The scattered linemaps of a module are
3158 coalesced when writing. */
3161 /* I use half-open [first,second) ranges. */
3162 typedef std::pair<unsigned,unsigned> range_t;
3164 /* A range of locations. */
3165 typedef std::pair<location_t,location_t> loc_range_t;
3167 /* Spans of the line maps that are occupied by this TU. I.e. not
3168 within imports. Only extended when in an interface unit.
3169 Interval zero corresponds to the forced header linemap(s). This
3170 is a singleton object. */
3172 class loc_spans {
3173 public:
3174 /* An interval of line maps. The line maps here represent a contiguous
3175 non-imported range. */
3176 struct span {
3177 loc_range_t ordinary; /* Ordinary map location range. */
3178 loc_range_t macro; /* Macro map location range. */
3179 int ordinary_delta; /* Add to ordinary loc to get serialized loc. */
3180 int macro_delta; /* Likewise for macro loc. */
3183 private:
3184 vec<span> *spans;
3186 public:
3187 loc_spans ()
3188 /* Do not preallocate spans, as that causes
3189 --enable-detailed-mem-stats problems. */
3190 : spans (nullptr)
3193 ~loc_spans ()
3195 delete spans;
3198 public:
3199 span &operator[] (unsigned ix)
3201 return (*spans)[ix];
3203 unsigned length () const
3205 return spans->length ();
3208 public:
3209 bool init_p () const
3211 return spans != nullptr;
3213 /* Initializer. */
3214 void init (const line_maps *lmaps, const line_map_ordinary *map);
3216 /* Slightly skewed preprocessed files can cause us to miss an
3217 initialization in some places. Fallback initializer. */
3218 void maybe_init ()
3220 if (!init_p ())
3221 init (line_table, nullptr);
3224 public:
3225 enum {
3226 SPAN_RESERVED = 0, /* Reserved (fixed) locations. */
3227 SPAN_FIRST = 1, /* LWM of locations to stream */
3228 SPAN_MAIN = 2 /* Main file and onwards. */
3231 public:
3232 location_t main_start () const
3234 return (*spans)[SPAN_MAIN].ordinary.first;
3237 public:
3238 void open (location_t);
3239 void close ();
3241 public:
3242 /* Propagate imported linemaps to us, if needed. */
3243 bool maybe_propagate (module_state *import, location_t loc);
3245 public:
3246 const span *ordinary (location_t);
3247 const span *macro (location_t);
3250 static loc_spans spans;
3251 /* Indirection to allow bsearching imports by ordinary location. */
3252 static vec<module_state *> *ool;
3254 /********************************************************************/
3255 /* Data needed by a module during the process of loading. */
3256 struct GTY(()) slurping {
3258 /* Remap import's module numbering to our numbering. Values are
3259 shifted by 1. Bit0 encodes if the import is direct. */
3260 vec<unsigned, va_heap, vl_embed> *
3261 GTY((skip)) remap; /* Module owner remapping. */
3263 elf_in *GTY((skip)) from; /* The elf loader. */
3265 /* This map is only for header imports themselves -- the global
3266 headers bitmap hold it for the current TU. */
3267 bitmap headers; /* Transitive set of direct imports, including
3268 self. Used for macro visibility and
3269 priority. */
3271 /* These objects point into the mmapped area, unless we're not doing
3272 that, or we got frozen or closed. In those cases they point to
3273 buffers we own. */
3274 bytes_in macro_defs; /* Macro definitions. */
3275 bytes_in macro_tbl; /* Macro table. */
3277 /* Location remapping. first->ordinary, second->macro. */
3278 range_t GTY((skip)) loc_deltas;
3280 unsigned current; /* Section currently being loaded. */
3281 unsigned remaining; /* Number of lazy sections yet to read. */
3282 unsigned lru; /* An LRU counter. */
3284 public:
3285 slurping (elf_in *);
3286 ~slurping ();
3288 public:
3289 /* Close the ELF file, if it's open. */
3290 void close ()
3292 if (from)
3294 from->end ();
3295 delete from;
3296 from = NULL;
3300 public:
3301 void release_macros ();
3303 public:
3304 void alloc_remap (unsigned size)
3306 gcc_assert (!remap);
3307 vec_safe_reserve (remap, size);
3308 for (unsigned ix = size; ix--;)
3309 remap->quick_push (0);
3311 unsigned remap_module (unsigned owner)
3313 if (owner < remap->length ())
3314 return (*remap)[owner] >> 1;
3315 return 0;
3318 public:
3319 /* GC allocation. But we must explicitly delete it. */
3320 static void *operator new (size_t x)
3322 return ggc_alloc_atomic (x);
3324 static void operator delete (void *p)
3326 ggc_free (p);
3330 slurping::slurping (elf_in *from)
3331 : remap (NULL), from (from),
3332 headers (BITMAP_GGC_ALLOC ()), macro_defs (), macro_tbl (),
3333 loc_deltas (0, 0),
3334 current (~0u), remaining (0), lru (0)
3338 slurping::~slurping ()
3340 vec_free (remap);
3341 remap = NULL;
3342 release_macros ();
3343 close ();
3346 void slurping::release_macros ()
3348 if (macro_defs.size)
3349 elf_in::release (from, macro_defs);
3350 if (macro_tbl.size)
3351 elf_in::release (from, macro_tbl);
3354 /* Information about location maps used during writing. */
3356 struct location_map_info {
3357 range_t num_maps;
3359 unsigned max_range;
3362 /* Flage for extensions that end up being streamed. */
3364 enum streamed_extensions {
3365 SE_OPENMP = 1 << 0,
3366 SE_BITS = 1
3369 /********************************************************************/
3370 struct module_state_config;
3372 /* Increasing levels of loadedness. */
3373 enum module_loadedness {
3374 ML_NONE, /* Not loaded. */
3375 ML_CONFIG, /* Config loaed. */
3376 ML_PREPROCESSOR, /* Preprocessor loaded. */
3377 ML_LANGUAGE, /* Language loaded. */
3380 /* Increasing levels of directness (toplevel) of import. */
3381 enum module_directness {
3382 MD_NONE, /* Not direct. */
3383 MD_PARTITION_DIRECT, /* Direct import of a partition. */
3384 MD_DIRECT, /* Direct import. */
3385 MD_PURVIEW_DIRECT, /* direct import in purview. */
3388 /* State of a particular module. */
3390 class GTY((chain_next ("%h.parent"), for_user)) module_state {
3391 public:
3392 /* We always import & export ourselves. */
3393 bitmap imports; /* Transitive modules we're importing. */
3394 bitmap exports; /* Subset of that, that we're exporting. */
3396 module_state *parent;
3397 tree name; /* Name of the module. */
3399 slurping *slurp; /* Data for loading. */
3401 const char *flatname; /* Flatname of module. */
3402 char *filename; /* CMI Filename */
3404 /* Indices into the entity_ary. */
3405 unsigned entity_lwm;
3406 unsigned entity_num;
3408 /* Location ranges for this module. adhoc-locs are decomposed, so
3409 don't have a range. */
3410 loc_range_t GTY((skip)) ordinary_locs;
3411 loc_range_t GTY((skip)) macro_locs;
3413 /* LOC is first set too the importing location. When initially
3414 loaded it refers to a module loc whose parent is the importing
3415 location. */
3416 location_t loc; /* Location referring to module itself. */
3417 unsigned crc; /* CRC we saw reading it in. */
3419 unsigned mod; /* Module owner number. */
3420 unsigned remap; /* Remapping during writing. */
3422 unsigned short subst; /* Mangle subst if !0. */
3424 /* How loaded this module is. */
3425 enum module_loadedness loadedness : 2;
3427 bool module_p : 1; /* /The/ module of this TU. */
3428 bool header_p : 1; /* Is a header unit. */
3429 bool interface_p : 1; /* An interface. */
3430 bool partition_p : 1; /* A partition. */
3432 /* How directly this module is imported. */
3433 enum module_directness directness : 2;
3435 bool exported_p : 1; /* directness != MD_NONE && exported. */
3436 bool cmi_noted_p : 1; /* We've told the user about the CMI, don't
3437 do it again */
3438 bool call_init_p : 1; /* This module's global initializer needs
3439 calling. */
3440 bool inform_cmi_p : 1; /* Inform of a read/write. */
3441 bool visited_p : 1; /* A walk-once flag. */
3442 /* Record extensions emitted or permitted. */
3443 unsigned extensions : SE_BITS;
3444 /* 14 bits used, 2 bits remain */
3446 public:
3447 module_state (tree name, module_state *, bool);
3448 ~module_state ();
3450 public:
3451 void release ()
3453 imports = exports = NULL;
3454 slurped ();
3456 void slurped ()
3458 delete slurp;
3459 slurp = NULL;
3461 elf_in *from () const
3463 return slurp->from;
3466 public:
3467 /* Kind of this module. */
3468 bool is_module () const
3470 return module_p;
3472 bool is_header () const
3474 return header_p;
3476 bool is_interface () const
3478 return interface_p;
3480 bool is_partition () const
3482 return partition_p;
3485 /* How this module is used in the current TU. */
3486 bool is_exported () const
3488 return exported_p;
3490 bool is_direct () const
3492 return directness >= MD_DIRECT;
3494 bool is_purview_direct () const
3496 return directness == MD_PURVIEW_DIRECT;
3498 bool is_partition_direct () const
3500 return directness == MD_PARTITION_DIRECT;
3503 public:
3504 /* Is this a real module? */
3505 bool has_location () const
3507 return loc != UNKNOWN_LOCATION;
3510 public:
3511 bool check_not_purview (location_t loc);
3513 public:
3514 void mangle (bool include_partition);
3516 public:
3517 void set_import (module_state const *, bool is_export);
3518 void announce (const char *) const;
3520 public:
3521 /* Read and write module. */
3522 void write (elf_out *to, cpp_reader *);
3523 bool read_initial (cpp_reader *);
3524 bool read_preprocessor (bool);
3525 bool read_language (bool);
3527 public:
3528 /* Read a section. */
3529 bool load_section (unsigned snum, binding_slot *mslot);
3530 /* Lazily read a section. */
3531 bool lazy_load (unsigned index, binding_slot *mslot);
3533 public:
3534 /* Juggle a limited number of file numbers. */
3535 static void freeze_an_elf ();
3536 bool maybe_defrost ();
3538 public:
3539 void maybe_completed_reading ();
3540 bool check_read (bool outermost, bool ok);
3542 private:
3543 /* The README, for human consumption. */
3544 void write_readme (elf_out *to, cpp_reader *,
3545 const char *dialect, unsigned extensions);
3546 void write_env (elf_out *to);
3548 private:
3549 /* Import tables. */
3550 void write_imports (bytes_out &cfg, bool direct);
3551 unsigned read_imports (bytes_in &cfg, cpp_reader *, line_maps *maps);
3553 private:
3554 void write_imports (elf_out *to, unsigned *crc_ptr);
3555 bool read_imports (cpp_reader *, line_maps *);
3557 private:
3558 void write_partitions (elf_out *to, unsigned, unsigned *crc_ptr);
3559 bool read_partitions (unsigned);
3561 private:
3562 void write_config (elf_out *to, struct module_state_config &, unsigned crc);
3563 bool read_config (struct module_state_config &);
3564 static void write_counts (elf_out *to, unsigned [], unsigned *crc_ptr);
3565 bool read_counts (unsigned []);
3567 public:
3568 void note_cmi_name ();
3570 private:
3571 static unsigned write_bindings (elf_out *to, vec<depset *> depsets,
3572 unsigned *crc_ptr);
3573 bool read_bindings (unsigned count, unsigned lwm, unsigned hwm);
3575 static void write_namespace (bytes_out &sec, depset *ns_dep);
3576 tree read_namespace (bytes_in &sec);
3578 void write_namespaces (elf_out *to, vec<depset *> spaces,
3579 unsigned, unsigned *crc_ptr);
3580 bool read_namespaces (unsigned);
3582 void intercluster_seed (trees_out &sec, unsigned index, depset *dep);
3583 unsigned write_cluster (elf_out *to, depset *depsets[], unsigned size,
3584 depset::hash &, unsigned *counts, unsigned *crc_ptr);
3585 bool read_cluster (unsigned snum);
3587 private:
3588 unsigned write_inits (elf_out *to, depset::hash &, unsigned *crc_ptr);
3589 bool read_inits (unsigned count);
3591 private:
3592 unsigned write_pendings (elf_out *to, vec<depset *> depsets,
3593 depset::hash &, unsigned *crc_ptr);
3594 bool read_pendings (unsigned count);
3596 private:
3597 void write_entities (elf_out *to, vec<depset *> depsets,
3598 unsigned count, unsigned *crc_ptr);
3599 bool read_entities (unsigned count, unsigned lwm, unsigned hwm);
3601 private:
3602 location_map_info write_prepare_maps (module_state_config *);
3603 bool read_prepare_maps (const module_state_config *);
3605 void write_ordinary_maps (elf_out *to, location_map_info &,
3606 module_state_config *, bool, unsigned *crc_ptr);
3607 bool read_ordinary_maps ();
3608 void write_macro_maps (elf_out *to, location_map_info &,
3609 module_state_config *, unsigned *crc_ptr);
3610 bool read_macro_maps ();
3612 private:
3613 void write_define (bytes_out &, const cpp_macro *, bool located = true);
3614 cpp_macro *read_define (bytes_in &, cpp_reader *, bool located = true) const;
3615 unsigned write_macros (elf_out *to, cpp_reader *, unsigned *crc_ptr);
3616 bool read_macros ();
3617 void install_macros ();
3619 public:
3620 void import_macros ();
3622 public:
3623 static void undef_macro (cpp_reader *, location_t, cpp_hashnode *);
3624 static cpp_macro *deferred_macro (cpp_reader *, location_t, cpp_hashnode *);
3626 public:
3627 static void write_location (bytes_out &, location_t);
3628 location_t read_location (bytes_in &) const;
3630 public:
3631 void set_flatname ();
3632 const char *get_flatname () const
3634 return flatname;
3636 location_t imported_from () const;
3638 public:
3639 void set_filename (const Cody::Packet &);
3640 bool do_import (cpp_reader *, bool outermost);
3643 /* Hash module state by name. This cannot be a member of
3644 module_state, because of GTY restrictions. We never delete from
3645 the hash table, but ggc_ptr_hash doesn't support that
3646 simplification. */
3648 struct module_state_hash : ggc_ptr_hash<module_state> {
3649 typedef std::pair<tree,uintptr_t> compare_type; /* {name,parent} */
3651 static inline hashval_t hash (const value_type m);
3652 static inline hashval_t hash (const compare_type &n);
3653 static inline bool equal (const value_type existing,
3654 const compare_type &candidate);
3657 module_state::module_state (tree name, module_state *parent, bool partition)
3658 : imports (BITMAP_GGC_ALLOC ()), exports (BITMAP_GGC_ALLOC ()),
3659 parent (parent), name (name), slurp (NULL),
3660 flatname (NULL), filename (NULL),
3661 entity_lwm (~0u >> 1), entity_num (0),
3662 ordinary_locs (0, 0), macro_locs (0, 0),
3663 loc (UNKNOWN_LOCATION),
3664 crc (0), mod (MODULE_UNKNOWN), remap (0), subst (0)
3666 loadedness = ML_NONE;
3668 module_p = header_p = interface_p = partition_p = false;
3670 directness = MD_NONE;
3671 exported_p = false;
3673 cmi_noted_p = false;
3674 call_init_p = false;
3676 partition_p = partition;
3678 inform_cmi_p = false;
3679 visited_p = false;
3681 extensions = 0;
3682 if (name && TREE_CODE (name) == STRING_CST)
3684 header_p = true;
3686 const char *string = TREE_STRING_POINTER (name);
3687 gcc_checking_assert (string[0] == '.'
3688 ? IS_DIR_SEPARATOR (string[1])
3689 : IS_ABSOLUTE_PATH (string));
3692 gcc_checking_assert (!(parent && header_p));
3695 module_state::~module_state ()
3697 release ();
3700 /* Hash module state. */
3701 static hashval_t
3702 module_name_hash (const_tree name)
3704 if (TREE_CODE (name) == STRING_CST)
3705 return htab_hash_string (TREE_STRING_POINTER (name));
3706 else
3707 return IDENTIFIER_HASH_VALUE (name);
3710 hashval_t
3711 module_state_hash::hash (const value_type m)
3713 hashval_t ph = pointer_hash<void>::hash
3714 (reinterpret_cast<void *> (reinterpret_cast<uintptr_t> (m->parent)
3715 | m->is_partition ()));
3716 hashval_t nh = module_name_hash (m->name);
3717 return iterative_hash_hashval_t (ph, nh);
3720 /* Hash a name. */
3721 hashval_t
3722 module_state_hash::hash (const compare_type &c)
3724 hashval_t ph = pointer_hash<void>::hash (reinterpret_cast<void *> (c.second));
3725 hashval_t nh = module_name_hash (c.first);
3727 return iterative_hash_hashval_t (ph, nh);
3730 bool
3731 module_state_hash::equal (const value_type existing,
3732 const compare_type &candidate)
3734 uintptr_t ep = (reinterpret_cast<uintptr_t> (existing->parent)
3735 | existing->is_partition ());
3736 if (ep != candidate.second)
3737 return false;
3739 /* Identifier comparison is by pointer. If the string_csts happen
3740 to be the same object, then they're equal too. */
3741 if (existing->name == candidate.first)
3742 return true;
3744 /* If neither are string csts, they can't be equal. */
3745 if (TREE_CODE (candidate.first) != STRING_CST
3746 || TREE_CODE (existing->name) != STRING_CST)
3747 return false;
3749 /* String equality. */
3750 if (TREE_STRING_LENGTH (existing->name)
3751 == TREE_STRING_LENGTH (candidate.first)
3752 && !memcmp (TREE_STRING_POINTER (existing->name),
3753 TREE_STRING_POINTER (candidate.first),
3754 TREE_STRING_LENGTH (existing->name)))
3755 return true;
3757 return false;
3760 /********************************************************************/
3761 /* Global state */
3763 /* Mapper name. */
3764 static const char *module_mapper_name;
3766 /* Deferred import queue (FIFO). */
3767 static vec<module_state *, va_heap, vl_embed> *pending_imports;
3769 /* CMI repository path and workspace. */
3770 static char *cmi_repo;
3771 static size_t cmi_repo_length;
3772 static char *cmi_path;
3773 static size_t cmi_path_alloc;
3775 /* Count of available and loaded clusters. */
3776 static unsigned available_clusters;
3777 static unsigned loaded_clusters;
3779 /* What the current TU is. */
3780 unsigned module_kind;
3782 /* Number of global init calls needed. */
3783 unsigned num_init_calls_needed = 0;
3785 /* Global trees. */
3786 static const std::pair<tree *, unsigned> global_tree_arys[] =
3788 std::pair<tree *, unsigned> (sizetype_tab, stk_type_kind_last),
3789 std::pair<tree *, unsigned> (integer_types, itk_none),
3790 std::pair<tree *, unsigned> (global_trees, TI_MODULE_HWM),
3791 std::pair<tree *, unsigned> (c_global_trees, CTI_MODULE_HWM),
3792 std::pair<tree *, unsigned> (cp_global_trees, CPTI_MODULE_HWM),
3793 std::pair<tree *, unsigned> (NULL, 0)
3795 static GTY(()) vec<tree, va_gc> *fixed_trees;
3796 static unsigned global_crc;
3798 /* Lazy loading can open many files concurrently, there are
3799 per-process limits on that. We pay attention to the process limit,
3800 and attempt to increase it when we run out. Otherwise we use an
3801 LRU scheme to figure out who to flush. Note that if the import
3802 graph /depth/ exceeds lazy_limit, we'll exceed the limit. */
3803 static unsigned lazy_lru; /* LRU counter. */
3804 static unsigned lazy_open; /* Number of open modules */
3805 static unsigned lazy_limit; /* Current limit of open modules. */
3806 static unsigned lazy_hard_limit; /* Hard limit on open modules. */
3807 /* Account for source, assembler and dump files & directory searches.
3808 We don't keep the source file's open, so we don't have to account
3809 for #include depth. I think dump files are opened and closed per
3810 pass, but ICBW. */
3811 #define LAZY_HEADROOM 15 /* File descriptor headroom. */
3813 /* Vector of module state. Indexed by OWNER. Has at least 2 slots. */
3814 static GTY(()) vec<module_state *, va_gc> *modules;
3816 /* Hash of module state, findable by {name, parent}. */
3817 static GTY(()) hash_table<module_state_hash> *modules_hash;
3819 /* Map of imported entities. We map DECL_UID to index of entity
3820 vector. */
3821 typedef hash_map<unsigned/*UID*/, unsigned/*index*/,
3822 simple_hashmap_traits<int_hash<unsigned,0>, unsigned>
3823 > entity_map_t;
3824 static entity_map_t *entity_map;
3825 /* Doesn't need GTYing, because any tree referenced here is also
3826 findable by, symbol table, specialization table, return type of
3827 reachable function. */
3828 static vec<binding_slot, va_heap, vl_embed> *entity_ary;
3830 /* Members entities of imported classes that are defined in this TU.
3831 These are where the entity's context is not from the current TU.
3832 We need to emit the definition (but not the enclosing class).
3834 We could find these by walking ALL the imported classes that we
3835 could provide a member definition. But that's expensive,
3836 especially when you consider lazy implicit member declarations,
3837 which could be ANY imported class. */
3838 static GTY(()) vec<tree, va_gc> *class_members;
3840 /* The same problem exists for class template partial
3841 specializations. Now that we have constraints, the invariant of
3842 expecting them in the instantiation table no longer holds. One of
3843 the constrained partial specializations will be there, but the
3844 others not so much. It's not even an unconstrained partial
3845 spacialization in the table :( so any partial template declaration
3846 is added to this list too. */
3847 static GTY(()) vec<tree, va_gc> *partial_specializations;
3849 /********************************************************************/
3851 /* Our module mapper (created lazily). */
3852 module_client *mapper;
3854 static module_client *make_mapper (location_t loc);
3855 inline module_client *get_mapper (location_t loc)
3857 auto *res = mapper;
3858 if (!res)
3859 res = make_mapper (loc);
3860 return res;
3863 /********************************************************************/
3864 static tree
3865 get_clone_target (tree decl)
3867 tree target;
3869 if (TREE_CODE (decl) == TEMPLATE_DECL)
3871 tree res_orig = DECL_CLONED_FUNCTION (DECL_TEMPLATE_RESULT (decl));
3873 target = DECL_TI_TEMPLATE (res_orig);
3875 else
3876 target = DECL_CLONED_FUNCTION (decl);
3878 gcc_checking_assert (DECL_MAYBE_IN_CHARGE_CDTOR_P (target));
3880 return target;
3883 /* Like FOR_EACH_CLONE, but will walk cloned templates. */
3884 #define FOR_EVERY_CLONE(CLONE, FN) \
3885 if (!DECL_MAYBE_IN_CHARGE_CDTOR_P (FN)); \
3886 else \
3887 for (CLONE = DECL_CHAIN (FN); \
3888 CLONE && DECL_CLONED_FUNCTION_P (CLONE); \
3889 CLONE = DECL_CHAIN (CLONE))
3891 /* It'd be nice if USE_TEMPLATE was a field of template_info
3892 (a) it'd solve the enum case dealt with below,
3893 (b) both class templates and decl templates would store this in the
3894 same place
3895 (c) this function wouldn't need the by-ref arg, which is annoying. */
3897 static tree
3898 node_template_info (tree decl, int &use)
3900 tree ti = NULL_TREE;
3901 int use_tpl = -1;
3902 if (DECL_IMPLICIT_TYPEDEF_P (decl))
3904 tree type = TREE_TYPE (decl);
3906 ti = TYPE_TEMPLATE_INFO (type);
3907 if (ti)
3909 if (TYPE_LANG_SPECIFIC (type))
3910 use_tpl = CLASSTYPE_USE_TEMPLATE (type);
3911 else
3913 /* An enum, where we don't explicitly encode use_tpl.
3914 If the containing context (a type or a function), is
3915 an ({im,ex}plicit) instantiation, then this is too.
3916 If it's a partial or explicit specialization, then
3917 this is not!. */
3918 tree ctx = CP_DECL_CONTEXT (decl);
3919 if (TYPE_P (ctx))
3920 ctx = TYPE_NAME (ctx);
3921 node_template_info (ctx, use);
3922 use_tpl = use != 2 ? use : 0;
3926 else if (DECL_LANG_SPECIFIC (decl)
3927 && (TREE_CODE (decl) == VAR_DECL
3928 || TREE_CODE (decl) == TYPE_DECL
3929 || TREE_CODE (decl) == FUNCTION_DECL
3930 || TREE_CODE (decl) == FIELD_DECL
3931 || TREE_CODE (decl) == TEMPLATE_DECL))
3933 use_tpl = DECL_USE_TEMPLATE (decl);
3934 ti = DECL_TEMPLATE_INFO (decl);
3937 use = use_tpl;
3938 return ti;
3941 /* Find the index in entity_ary for an imported DECL. It should
3942 always be there, but bugs can cause it to be missing, and that can
3943 crash the crash reporting -- let's not do that! When streaming
3944 out we place entities from this module there too -- with negated
3945 indices. */
3947 static unsigned
3948 import_entity_index (tree decl, bool null_ok = false)
3950 if (unsigned *slot = entity_map->get (DECL_UID (decl)))
3951 return *slot;
3953 gcc_checking_assert (null_ok);
3954 return ~(~0u >> 1);
3957 /* Find the module for an imported entity at INDEX in the entity ary.
3958 There must be one. */
3960 static module_state *
3961 import_entity_module (unsigned index)
3963 if (index > ~(~0u >> 1))
3964 /* This is an index for an exported entity. */
3965 return (*modules)[0];
3967 /* Do not include the current TU (not an off-by-one error). */
3968 unsigned pos = 1;
3969 unsigned len = modules->length () - pos;
3970 while (len)
3972 unsigned half = len / 2;
3973 module_state *probe = (*modules)[pos + half];
3974 if (index < probe->entity_lwm)
3975 len = half;
3976 else if (index < probe->entity_lwm + probe->entity_num)
3977 return probe;
3978 else
3980 pos += half + 1;
3981 len = len - (half + 1);
3984 gcc_unreachable ();
3988 /********************************************************************/
3989 /* A dumping machinery. */
3991 class dumper {
3992 public:
3993 enum {
3994 LOCATION = TDF_LINENO, /* -lineno:Source location streaming. */
3995 DEPEND = TDF_GRAPH, /* -graph:Dependency graph construction. */
3996 CLUSTER = TDF_BLOCKS, /* -blocks:Clusters. */
3997 TREE = TDF_UID, /* -uid:Tree streaming. */
3998 MERGE = TDF_ALIAS, /* -alias:Mergeable Entities. */
3999 ELF = TDF_ASMNAME, /* -asmname:Elf data. */
4000 MACRO = TDF_VOPS /* -vops:Macros. */
4003 private:
4004 struct impl {
4005 typedef vec<module_state *, va_heap, vl_embed> stack_t;
4007 FILE *stream; /* Dump stream. */
4008 unsigned indent; /* Local indentation. */
4009 bool bol; /* Beginning of line. */
4010 stack_t stack; /* Trailing array of module_state. */
4012 bool nested_name (tree); /* Dump a name following DECL_CONTEXT. */
4015 public:
4016 /* The dumper. */
4017 impl *dumps;
4018 dump_flags_t flags;
4020 public:
4021 /* Push/pop module state dumping. */
4022 unsigned push (module_state *);
4023 void pop (unsigned);
4025 public:
4026 /* Change local indentation. */
4027 void indent ()
4029 if (dumps)
4030 dumps->indent++;
4032 void outdent ()
4034 if (dumps)
4036 gcc_checking_assert (dumps->indent);
4037 dumps->indent--;
4041 public:
4042 /* Is dump enabled?. */
4043 bool operator () (int mask = 0)
4045 if (!dumps || !dumps->stream)
4046 return false;
4047 if (mask && !(mask & flags))
4048 return false;
4049 return true;
4051 /* Dump some information. */
4052 bool operator () (const char *, ...);
4055 /* The dumper. */
4056 static dumper dump = {0, dump_flags_t (0)};
4058 /* Push to dumping M. Return previous indentation level. */
4060 unsigned
4061 dumper::push (module_state *m)
4063 FILE *stream = NULL;
4064 if (!dumps || !dumps->stack.length ())
4066 stream = dump_begin (module_dump_id, &flags);
4067 if (!stream)
4068 return 0;
4071 if (!dumps || !dumps->stack.space (1))
4073 /* Create or extend the dump implementor. */
4074 unsigned current = dumps ? dumps->stack.length () : 0;
4075 unsigned count = current ? current * 2 : EXPERIMENT (1, 20);
4076 size_t alloc = (offsetof (impl, stack)
4077 + impl::stack_t::embedded_size (count));
4078 dumps = XRESIZEVAR (impl, dumps, alloc);
4079 dumps->stack.embedded_init (count, current);
4081 if (stream)
4082 dumps->stream = stream;
4084 unsigned n = dumps->indent;
4085 dumps->indent = 0;
4086 dumps->bol = true;
4087 dumps->stack.quick_push (m);
4088 if (m)
4090 module_state *from = NULL;
4092 if (dumps->stack.length () > 1)
4093 from = dumps->stack[dumps->stack.length () - 2];
4094 else
4095 dump ("");
4096 dump (from ? "Starting module %M (from %M)"
4097 : "Starting module %M", m, from);
4100 return n;
4103 /* Pop from dumping. Restore indentation to N. */
4105 void dumper::pop (unsigned n)
4107 if (!dumps)
4108 return;
4110 gcc_checking_assert (dump () && !dumps->indent);
4111 if (module_state *m = dumps->stack[dumps->stack.length () - 1])
4113 module_state *from = (dumps->stack.length () > 1
4114 ? dumps->stack[dumps->stack.length () - 2] : NULL);
4115 dump (from ? "Finishing module %M (returning to %M)"
4116 : "Finishing module %M", m, from);
4118 dumps->stack.pop ();
4119 dumps->indent = n;
4120 if (!dumps->stack.length ())
4122 dump_end (module_dump_id, dumps->stream);
4123 dumps->stream = NULL;
4127 /* Dump a nested name for arbitrary tree T. Sometimes it won't have a
4128 name. */
4130 bool
4131 dumper::impl::nested_name (tree t)
4133 tree ti = NULL_TREE;
4134 int origin = -1;
4135 tree name = NULL_TREE;
4137 if (t && TREE_CODE (t) == TREE_BINFO)
4138 t = BINFO_TYPE (t);
4140 if (t && TYPE_P (t))
4141 t = TYPE_NAME (t);
4143 if (t && DECL_P (t))
4145 if (t == global_namespace || DECL_TEMPLATE_PARM_P (t))
4147 else if (tree ctx = DECL_CONTEXT (t))
4148 if (TREE_CODE (ctx) == TRANSLATION_UNIT_DECL
4149 || nested_name (ctx))
4150 fputs ("::", stream);
4152 int use_tpl;
4153 ti = node_template_info (t, use_tpl);
4154 if (ti && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL
4155 && (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == t))
4156 t = TI_TEMPLATE (ti);
4157 tree not_tmpl = t;
4158 if (TREE_CODE (t) == TEMPLATE_DECL)
4160 fputs ("template ", stream);
4161 not_tmpl = DECL_TEMPLATE_RESULT (t);
4164 if (not_tmpl
4165 && DECL_P (not_tmpl)
4166 && DECL_LANG_SPECIFIC (not_tmpl)
4167 && DECL_MODULE_IMPORT_P (not_tmpl))
4169 /* We need to be careful here, so as to not explode on
4170 inconsistent data -- we're probably debugging, because
4171 Something Is Wrong. */
4172 unsigned index = import_entity_index (t, true);
4173 if (!(index & ~(~0u >> 1)))
4174 origin = import_entity_module (index)->mod;
4175 else if (index > ~(~0u >> 1))
4176 /* An imported partition member that we're emitting. */
4177 origin = 0;
4178 else
4179 origin = -2;
4182 name = DECL_NAME (t) ? DECL_NAME (t)
4183 : HAS_DECL_ASSEMBLER_NAME_P (t) ? DECL_ASSEMBLER_NAME_RAW (t)
4184 : NULL_TREE;
4186 else
4187 name = t;
4189 if (name)
4190 switch (TREE_CODE (name))
4192 default:
4193 fputs ("#unnamed#", stream);
4194 break;
4196 case IDENTIFIER_NODE:
4197 fwrite (IDENTIFIER_POINTER (name), 1, IDENTIFIER_LENGTH (name), stream);
4198 break;
4200 case INTEGER_CST:
4201 print_hex (wi::to_wide (name), stream);
4202 break;
4204 case STRING_CST:
4205 /* If TREE_TYPE is NULL, this is a raw string. */
4206 fwrite (TREE_STRING_POINTER (name), 1,
4207 TREE_STRING_LENGTH (name) - (TREE_TYPE (name) != NULL_TREE),
4208 stream);
4209 break;
4211 else
4212 fputs ("#null#", stream);
4214 if (origin >= 0)
4216 const module_state *module = (*modules)[origin];
4217 fprintf (stream, "@%s:%d", !module ? "" : !module->name ? "(unnamed)"
4218 : module->get_flatname (), origin);
4220 else if (origin == -2)
4221 fprintf (stream, "@???");
4223 if (ti)
4225 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (ti));
4226 fputs ("<", stream);
4227 if (args)
4228 for (int ix = 0; ix != TREE_VEC_LENGTH (args); ix++)
4230 if (ix)
4231 fputs (",", stream);
4232 nested_name (TREE_VEC_ELT (args, ix));
4234 fputs (">", stream);
4237 return true;
4240 /* Formatted dumping. FORMAT begins with '+' do not emit a trailing
4241 new line. (Normally it is appended.)
4242 Escapes:
4243 %C - tree_code
4244 %I - identifier
4245 %M - module_state
4246 %N - name -- DECL_NAME
4247 %P - context:name pair
4248 %R - unsigned:unsigned ratio
4249 %S - symbol -- DECL_ASSEMBLER_NAME
4250 %U - long unsigned
4251 %V - version
4252 --- the following are printf-like, but without its flexibility
4253 %d - decimal int
4254 %p - pointer
4255 %s - string
4256 %u - unsigned int
4257 %x - hex int
4259 We do not implement the printf modifiers. */
4261 bool
4262 dumper::operator () (const char *format, ...)
4264 if (!(*this) ())
4265 return false;
4267 bool no_nl = format[0] == '+';
4268 format += no_nl;
4270 if (dumps->bol)
4272 /* Module import indent. */
4273 if (unsigned depth = dumps->stack.length () - 1)
4275 const char *prefix = ">>>>";
4276 fprintf (dumps->stream, (depth <= strlen (prefix)
4277 ? &prefix[strlen (prefix) - depth]
4278 : ">.%d.>"), depth);
4281 /* Local indent. */
4282 if (unsigned indent = dumps->indent)
4284 const char *prefix = " ";
4285 fprintf (dumps->stream, (indent <= strlen (prefix)
4286 ? &prefix[strlen (prefix) - indent]
4287 : " .%d. "), indent);
4289 dumps->bol = false;
4292 va_list args;
4293 va_start (args, format);
4294 while (const char *esc = strchr (format, '%'))
4296 fwrite (format, 1, (size_t)(esc - format), dumps->stream);
4297 format = ++esc;
4298 switch (*format++)
4300 default:
4301 gcc_unreachable ();
4303 case '%':
4304 fputc ('%', dumps->stream);
4305 break;
4307 case 'C': /* Code */
4309 tree_code code = (tree_code)va_arg (args, unsigned);
4310 fputs (get_tree_code_name (code), dumps->stream);
4312 break;
4314 case 'I': /* Identifier. */
4316 tree t = va_arg (args, tree);
4317 dumps->nested_name (t);
4319 break;
4321 case 'M': /* Module. */
4323 const char *str = "(none)";
4324 if (module_state *m = va_arg (args, module_state *))
4326 if (!m->has_location ())
4327 str = "(detached)";
4328 else
4329 str = m->get_flatname ();
4331 fputs (str, dumps->stream);
4333 break;
4335 case 'N': /* Name. */
4337 tree t = va_arg (args, tree);
4338 while (t && TREE_CODE (t) == OVERLOAD)
4339 t = OVL_FUNCTION (t);
4340 fputc ('\'', dumps->stream);
4341 dumps->nested_name (t);
4342 fputc ('\'', dumps->stream);
4344 break;
4346 case 'P': /* Pair. */
4348 tree ctx = va_arg (args, tree);
4349 tree name = va_arg (args, tree);
4350 fputc ('\'', dumps->stream);
4351 dumps->nested_name (ctx);
4352 if (ctx && ctx != global_namespace)
4353 fputs ("::", dumps->stream);
4354 dumps->nested_name (name);
4355 fputc ('\'', dumps->stream);
4357 break;
4359 case 'R': /* Ratio */
4361 unsigned a = va_arg (args, unsigned);
4362 unsigned b = va_arg (args, unsigned);
4363 fprintf (dumps->stream, "%.1f", (float) a / (b + !b));
4365 break;
4367 case 'S': /* Symbol name */
4369 tree t = va_arg (args, tree);
4370 if (t && TYPE_P (t))
4371 t = TYPE_NAME (t);
4372 if (t && HAS_DECL_ASSEMBLER_NAME_P (t)
4373 && DECL_ASSEMBLER_NAME_SET_P (t))
4375 fputc ('(', dumps->stream);
4376 fputs (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (t)),
4377 dumps->stream);
4378 fputc (')', dumps->stream);
4381 break;
4383 case 'U': /* long unsigned. */
4385 unsigned long u = va_arg (args, unsigned long);
4386 fprintf (dumps->stream, "%lu", u);
4388 break;
4390 case 'V': /* Verson. */
4392 unsigned v = va_arg (args, unsigned);
4393 verstr_t string;
4395 version2string (v, string);
4396 fputs (string, dumps->stream);
4398 break;
4400 case 'c': /* Character. */
4402 int c = va_arg (args, int);
4403 fputc (c, dumps->stream);
4405 break;
4407 case 'd': /* Decimal Int. */
4409 int d = va_arg (args, int);
4410 fprintf (dumps->stream, "%d", d);
4412 break;
4414 case 'p': /* Pointer. */
4416 void *p = va_arg (args, void *);
4417 fprintf (dumps->stream, "%p", p);
4419 break;
4421 case 's': /* String. */
4423 const char *s = va_arg (args, char *);
4424 gcc_checking_assert (s);
4425 fputs (s, dumps->stream);
4427 break;
4429 case 'u': /* Unsigned. */
4431 unsigned u = va_arg (args, unsigned);
4432 fprintf (dumps->stream, "%u", u);
4434 break;
4436 case 'x': /* Hex. */
4438 unsigned x = va_arg (args, unsigned);
4439 fprintf (dumps->stream, "%x", x);
4441 break;
4444 fputs (format, dumps->stream);
4445 va_end (args);
4446 if (!no_nl)
4448 dumps->bol = true;
4449 fputc ('\n', dumps->stream);
4451 return true;
4454 struct note_def_cache_hasher : ggc_cache_ptr_hash<tree_node>
4456 static int keep_cache_entry (tree t)
4458 if (!CHECKING_P)
4459 /* GTY is unfortunately not clever enough to conditionalize
4460 this. */
4461 gcc_unreachable ();
4463 if (ggc_marked_p (t))
4464 return -1;
4466 unsigned n = dump.push (NULL);
4467 /* This might or might not be an error. We should note its
4468 dropping whichever. */
4469 dump () && dump ("Dropping %N from note_defs table", t);
4470 dump.pop (n);
4472 return 0;
4476 /* We should stream each definition at most once.
4477 This needs to be a cache because there are cases where a definition
4478 ends up being not retained, and we need to drop those so we don't
4479 get confused if memory is reallocated. */
4480 typedef hash_table<note_def_cache_hasher> note_defs_table_t;
4481 static GTY((cache)) note_defs_table_t *note_defs;
4483 void
4484 trees_in::assert_definition (tree decl ATTRIBUTE_UNUSED,
4485 bool installing ATTRIBUTE_UNUSED)
4487 #if CHECKING_P
4488 tree *slot = note_defs->find_slot (decl, installing ? INSERT : NO_INSERT);
4489 tree not_tmpl = STRIP_TEMPLATE (decl);
4490 if (installing)
4492 /* We must be inserting for the first time. */
4493 gcc_assert (!*slot);
4494 *slot = decl;
4496 else
4497 /* If this is not the mergeable entity, it should not be in the
4498 table. If it is a non-global-module mergeable entity, it
4499 should be in the table. Global module entities could have been
4500 defined textually in the current TU and so might or might not
4501 be present. */
4502 gcc_assert (!is_duplicate (decl)
4503 ? !slot
4504 : (slot
4505 || !DECL_LANG_SPECIFIC (not_tmpl)
4506 || !DECL_MODULE_PURVIEW_P (not_tmpl)
4507 || (!DECL_MODULE_IMPORT_P (not_tmpl)
4508 && header_module_p ())));
4510 if (not_tmpl != decl)
4511 gcc_assert (!note_defs->find_slot (not_tmpl, NO_INSERT));
4512 #endif
4515 void
4516 trees_out::assert_definition (tree decl ATTRIBUTE_UNUSED)
4518 #if CHECKING_P
4519 tree *slot = note_defs->find_slot (decl, INSERT);
4520 gcc_assert (!*slot);
4521 *slot = decl;
4522 if (TREE_CODE (decl) == TEMPLATE_DECL)
4523 gcc_assert (!note_defs->find_slot (DECL_TEMPLATE_RESULT (decl), NO_INSERT));
4524 #endif
4527 /********************************************************************/
4528 static bool
4529 noisy_p ()
4531 if (quiet_flag)
4532 return false;
4534 pp_needs_newline (global_dc->printer) = true;
4535 diagnostic_set_last_function (global_dc, (diagnostic_info *) NULL);
4537 return true;
4540 /* Set the cmi repo. Strip trailing '/', '.' becomes NULL. */
4542 static void
4543 set_cmi_repo (const char *r)
4545 XDELETEVEC (cmi_repo);
4546 XDELETEVEC (cmi_path);
4547 cmi_path_alloc = 0;
4549 cmi_repo = NULL;
4550 cmi_repo_length = 0;
4552 if (!r || !r[0])
4553 return;
4555 size_t len = strlen (r);
4556 cmi_repo = XNEWVEC (char, len + 1);
4557 memcpy (cmi_repo, r, len + 1);
4559 if (len > 1 && IS_DIR_SEPARATOR (cmi_repo[len-1]))
4560 len--;
4561 if (len == 1 && cmi_repo[0] == '.')
4562 len--;
4563 cmi_repo[len] = 0;
4564 cmi_repo_length = len;
4567 /* TO is a repo-relative name. Provide one that we may use from where
4568 we are. */
4570 static const char *
4571 maybe_add_cmi_prefix (const char *to, size_t *len_p = NULL)
4573 size_t len = len_p || cmi_repo_length ? strlen (to) : 0;
4575 if (cmi_repo_length && !IS_ABSOLUTE_PATH (to))
4577 if (cmi_path_alloc < cmi_repo_length + len + 2)
4579 XDELETEVEC (cmi_path);
4580 cmi_path_alloc = cmi_repo_length + len * 2 + 2;
4581 cmi_path = XNEWVEC (char, cmi_path_alloc);
4583 memcpy (cmi_path, cmi_repo, cmi_repo_length);
4584 cmi_path[cmi_repo_length] = DIR_SEPARATOR;
4587 memcpy (&cmi_path[cmi_repo_length + 1], to, len + 1);
4588 len += cmi_repo_length + 1;
4589 to = cmi_path;
4592 if (len_p)
4593 *len_p = len;
4595 return to;
4598 /* Try and create the directories of PATH. */
4600 static void
4601 create_dirs (char *path)
4603 /* Try and create the missing directories. */
4604 for (char *base = path; *base; base++)
4605 if (IS_DIR_SEPARATOR (*base))
4607 char sep = *base;
4608 *base = 0;
4609 int failed = mkdir (path, S_IRWXU | S_IRWXG | S_IRWXO);
4610 dump () && dump ("Mkdir ('%s') errno:=%u", path, failed ? errno : 0);
4611 *base = sep;
4612 if (failed
4613 /* Maybe racing with another creator (of a *different*
4614 module). */
4615 && errno != EEXIST)
4616 break;
4620 /* Given a CLASSTYPE_DECL_LIST VALUE get the the template friend decl,
4621 if that's what this is. */
4623 static tree
4624 friend_from_decl_list (tree frnd)
4626 tree res = frnd;
4628 if (TREE_CODE (frnd) != TEMPLATE_DECL)
4630 tree tmpl = NULL_TREE;
4631 if (TYPE_P (frnd))
4633 res = TYPE_NAME (frnd);
4634 if (CLASSTYPE_TEMPLATE_INFO (frnd))
4635 tmpl = CLASSTYPE_TI_TEMPLATE (frnd);
4637 else if (DECL_TEMPLATE_INFO (frnd))
4639 tmpl = DECL_TI_TEMPLATE (frnd);
4640 if (TREE_CODE (tmpl) != TEMPLATE_DECL)
4641 tmpl = NULL_TREE;
4644 if (tmpl && DECL_TEMPLATE_RESULT (tmpl) == res)
4645 res = tmpl;
4648 return res;
4651 static tree
4652 find_enum_member (tree ctx, tree name)
4654 for (tree values = TYPE_VALUES (ctx);
4655 values; values = TREE_CHAIN (values))
4656 if (DECL_NAME (TREE_VALUE (values)) == name)
4657 return TREE_VALUE (values);
4659 return NULL_TREE;
4662 /********************************************************************/
4663 /* Instrumentation gathered writing bytes. */
4665 void
4666 bytes_out::instrument ()
4668 dump ("Wrote %u bytes in %u blocks", lengths[3], spans[3]);
4669 dump ("Wrote %u bits in %u bytes", lengths[0] + lengths[1], lengths[2]);
4670 for (unsigned ix = 0; ix < 2; ix++)
4671 dump (" %u %s spans of %R bits", spans[ix],
4672 ix ? "one" : "zero", lengths[ix], spans[ix]);
4673 dump (" %u blocks with %R bits padding", spans[2],
4674 lengths[2] * 8 - (lengths[0] + lengths[1]), spans[2]);
4677 /* Instrumentation gathered writing trees. */
4678 void
4679 trees_out::instrument ()
4681 if (dump (""))
4683 bytes_out::instrument ();
4684 dump ("Wrote:");
4685 dump (" %u decl trees", decl_val_count);
4686 dump (" %u other trees", tree_val_count);
4687 dump (" %u back references", back_ref_count);
4688 dump (" %u null trees", null_count);
4692 /* Setup and teardown for a tree walk. */
4694 void
4695 trees_out::begin ()
4697 gcc_assert (!streaming_p () || !tree_map.elements ());
4699 mark_trees ();
4700 if (streaming_p ())
4701 parent::begin ();
4704 unsigned
4705 trees_out::end (elf_out *sink, unsigned name, unsigned *crc_ptr)
4707 gcc_checking_assert (streaming_p ());
4709 unmark_trees ();
4710 return parent::end (sink, name, crc_ptr);
4713 void
4714 trees_out::end ()
4716 gcc_assert (!streaming_p ());
4718 unmark_trees ();
4719 /* Do not parent::end -- we weren't streaming. */
4722 void
4723 trees_out::mark_trees ()
4725 if (size_t size = tree_map.elements ())
4727 /* This isn't our first rodeo, destroy and recreate the
4728 tree_map. I'm a bad bad man. Use the previous size as a
4729 guess for the next one (so not all bad). */
4730 tree_map.~ptr_int_hash_map ();
4731 new (&tree_map) ptr_int_hash_map (size);
4734 /* Install the fixed trees, with +ve references. */
4735 unsigned limit = fixed_trees->length ();
4736 for (unsigned ix = 0; ix != limit; ix++)
4738 tree val = (*fixed_trees)[ix];
4739 bool existed = tree_map.put (val, ix + tag_fixed);
4740 gcc_checking_assert (!TREE_VISITED (val) && !existed);
4741 TREE_VISITED (val) = true;
4744 ref_num = 0;
4747 /* Unmark the trees we encountered */
4749 void
4750 trees_out::unmark_trees ()
4752 ptr_int_hash_map::iterator end (tree_map.end ());
4753 for (ptr_int_hash_map::iterator iter (tree_map.begin ()); iter != end; ++iter)
4755 tree node = reinterpret_cast<tree> ((*iter).first);
4756 int ref = (*iter).second;
4757 /* We should have visited the node, and converted its mergeable
4758 reference to a regular reference. */
4759 gcc_checking_assert (TREE_VISITED (node)
4760 && (ref <= tag_backref || ref >= tag_fixed));
4761 TREE_VISITED (node) = false;
4765 /* Mark DECL for by-value walking. We do this by inserting it into
4766 the tree map with a reference of zero. May be called multiple
4767 times on the same node. */
4769 void
4770 trees_out::mark_by_value (tree decl)
4772 gcc_checking_assert (DECL_P (decl)
4773 /* Enum consts are INTEGER_CSTS. */
4774 || TREE_CODE (decl) == INTEGER_CST
4775 || TREE_CODE (decl) == TREE_BINFO);
4777 if (TREE_VISITED (decl))
4778 /* Must already be forced or fixed. */
4779 gcc_checking_assert (*tree_map.get (decl) >= tag_value);
4780 else
4782 bool existed = tree_map.put (decl, tag_value);
4783 gcc_checking_assert (!existed);
4784 TREE_VISITED (decl) = true;
4789 trees_out::get_tag (tree t)
4791 gcc_checking_assert (TREE_VISITED (t));
4792 return *tree_map.get (t);
4795 /* Insert T into the map, return its tag number. */
4798 trees_out::insert (tree t, walk_kind walk)
4800 gcc_checking_assert (walk != WK_normal || !TREE_VISITED (t));
4801 int tag = --ref_num;
4802 bool existed;
4803 int &slot = tree_map.get_or_insert (t, &existed);
4804 gcc_checking_assert (TREE_VISITED (t) == existed
4805 && (!existed
4806 || (walk == WK_value && slot == tag_value)));
4807 TREE_VISITED (t) = true;
4808 slot = tag;
4810 return tag;
4813 /* Insert T into the backreference array. Return its back reference
4814 number. */
4817 trees_in::insert (tree t)
4819 gcc_checking_assert (t || get_overrun ());
4820 back_refs.safe_push (t);
4821 return -(int)back_refs.length ();
4824 /* A chained set of decls. */
4826 void
4827 trees_out::chained_decls (tree decls)
4829 for (; decls; decls = DECL_CHAIN (decls))
4831 if (VAR_OR_FUNCTION_DECL_P (decls)
4832 && DECL_LOCAL_DECL_P (decls))
4834 /* Make sure this is the first encounter, and mark for
4835 walk-by-value. */
4836 gcc_checking_assert (!TREE_VISITED (decls)
4837 && !DECL_TEMPLATE_INFO (decls));
4838 mark_by_value (decls);
4840 tree_node (decls);
4842 tree_node (NULL_TREE);
4845 tree
4846 trees_in::chained_decls ()
4848 tree decls = NULL_TREE;
4849 for (tree *chain = &decls;;)
4850 if (tree decl = tree_node ())
4852 if (!DECL_P (decl) || DECL_CHAIN (decl))
4854 set_overrun ();
4855 break;
4857 *chain = decl;
4858 chain = &DECL_CHAIN (decl);
4860 else
4861 break;
4863 return decls;
4866 /* A vector of decls following DECL_CHAIN. */
4868 void
4869 trees_out::vec_chained_decls (tree decls)
4871 if (streaming_p ())
4873 unsigned len = 0;
4875 for (tree decl = decls; decl; decl = DECL_CHAIN (decl))
4876 len++;
4877 u (len);
4880 for (tree decl = decls; decl; decl = DECL_CHAIN (decl))
4882 if (DECL_IMPLICIT_TYPEDEF_P (decl)
4883 && TYPE_NAME (TREE_TYPE (decl)) != decl)
4884 /* An anonynmous struct with a typedef name. An odd thing to
4885 write. */
4886 tree_node (NULL_TREE);
4887 else
4888 tree_node (decl);
4892 vec<tree, va_heap> *
4893 trees_in::vec_chained_decls ()
4895 vec<tree, va_heap> *v = NULL;
4897 if (unsigned len = u ())
4899 vec_alloc (v, len);
4901 for (unsigned ix = 0; ix < len; ix++)
4903 tree decl = tree_node ();
4904 if (decl && !DECL_P (decl))
4906 set_overrun ();
4907 break;
4909 v->quick_push (decl);
4912 if (get_overrun ())
4914 vec_free (v);
4915 v = NULL;
4919 return v;
4922 /* A vector of trees. */
4924 void
4925 trees_out::tree_vec (vec<tree, va_gc> *v)
4927 unsigned len = vec_safe_length (v);
4928 if (streaming_p ())
4929 u (len);
4930 for (unsigned ix = 0; ix != len; ix++)
4931 tree_node ((*v)[ix]);
4934 vec<tree, va_gc> *
4935 trees_in::tree_vec ()
4937 vec<tree, va_gc> *v = NULL;
4938 if (unsigned len = u ())
4940 vec_alloc (v, len);
4941 for (unsigned ix = 0; ix != len; ix++)
4942 v->quick_push (tree_node ());
4944 return v;
4947 /* A vector of tree pairs. */
4949 void
4950 trees_out::tree_pair_vec (vec<tree_pair_s, va_gc> *v)
4952 unsigned len = vec_safe_length (v);
4953 if (streaming_p ())
4954 u (len);
4955 if (len)
4956 for (unsigned ix = 0; ix != len; ix++)
4958 tree_pair_s const &s = (*v)[ix];
4959 tree_node (s.purpose);
4960 tree_node (s.value);
4964 vec<tree_pair_s, va_gc> *
4965 trees_in::tree_pair_vec ()
4967 vec<tree_pair_s, va_gc> *v = NULL;
4968 if (unsigned len = u ())
4970 vec_alloc (v, len);
4971 for (unsigned ix = 0; ix != len; ix++)
4973 tree_pair_s s;
4974 s.purpose = tree_node ();
4975 s.value = tree_node ();
4976 v->quick_push (s);
4979 return v;
4982 void
4983 trees_out::tree_list (tree list, bool has_purpose)
4985 for (; list; list = TREE_CHAIN (list))
4987 gcc_checking_assert (TREE_VALUE (list));
4988 tree_node (TREE_VALUE (list));
4989 if (has_purpose)
4990 tree_node (TREE_PURPOSE (list));
4992 tree_node (NULL_TREE);
4995 tree
4996 trees_in::tree_list (bool has_purpose)
4998 tree res = NULL_TREE;
5000 for (tree *chain = &res; tree value = tree_node ();
5001 chain = &TREE_CHAIN (*chain))
5003 tree purpose = has_purpose ? tree_node () : NULL_TREE;
5004 *chain = build_tree_list (purpose, value);
5007 return res;
5009 /* Start tree write. Write information to allocate the receiving
5010 node. */
5012 void
5013 trees_out::start (tree t, bool code_streamed)
5015 if (TYPE_P (t))
5017 enum tree_code code = TREE_CODE (t);
5018 gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
5019 /* All these types are TYPE_NON_COMMON. */
5020 gcc_checking_assert (code == RECORD_TYPE
5021 || code == UNION_TYPE
5022 || code == ENUMERAL_TYPE
5023 || code == TEMPLATE_TYPE_PARM
5024 || code == TEMPLATE_TEMPLATE_PARM
5025 || code == BOUND_TEMPLATE_TEMPLATE_PARM);
5028 if (!code_streamed)
5029 u (TREE_CODE (t));
5031 switch (TREE_CODE (t))
5033 default:
5034 if (TREE_CODE_CLASS (TREE_CODE (t)) == tcc_vl_exp)
5035 u (VL_EXP_OPERAND_LENGTH (t));
5036 break;
5038 case INTEGER_CST:
5039 u (TREE_INT_CST_NUNITS (t));
5040 u (TREE_INT_CST_EXT_NUNITS (t));
5041 u (TREE_INT_CST_OFFSET_NUNITS (t));
5042 break;
5044 case OMP_CLAUSE:
5045 state->extensions |= SE_OPENMP;
5046 u (OMP_CLAUSE_CODE (t));
5047 break;
5049 case STRING_CST:
5050 str (TREE_STRING_POINTER (t), TREE_STRING_LENGTH (t));
5051 break;
5053 case VECTOR_CST:
5054 u (VECTOR_CST_LOG2_NPATTERNS (t));
5055 u (VECTOR_CST_NELTS_PER_PATTERN (t));
5056 break;
5058 case TREE_BINFO:
5059 u (BINFO_N_BASE_BINFOS (t));
5060 break;
5062 case TREE_VEC:
5063 u (TREE_VEC_LENGTH (t));
5064 break;
5066 case FIXED_CST:
5067 case POLY_INT_CST:
5068 gcc_unreachable (); /* Not supported in C++. */
5069 break;
5071 case IDENTIFIER_NODE:
5072 case SSA_NAME:
5073 case TARGET_MEM_REF:
5074 case TRANSLATION_UNIT_DECL:
5075 /* We shouldn't meet these. */
5076 gcc_unreachable ();
5077 break;
5081 /* Start tree read. Allocate the receiving node. */
5083 tree
5084 trees_in::start (unsigned code)
5086 tree t = NULL_TREE;
5088 if (!code)
5089 code = u ();
5091 switch (code)
5093 default:
5094 if (code >= MAX_TREE_CODES)
5096 fail:
5097 set_overrun ();
5098 return NULL_TREE;
5100 else if (TREE_CODE_CLASS (code) == tcc_vl_exp)
5102 unsigned ops = u ();
5103 t = build_vl_exp (tree_code (code), ops);
5105 else
5106 t = make_node (tree_code (code));
5107 break;
5109 case INTEGER_CST:
5111 unsigned n = u ();
5112 unsigned e = u ();
5113 t = make_int_cst (n, e);
5114 TREE_INT_CST_OFFSET_NUNITS(t) = u ();
5116 break;
5118 case OMP_CLAUSE:
5120 if (!(state->extensions & SE_OPENMP))
5121 goto fail;
5123 unsigned omp_code = u ();
5124 t = build_omp_clause (UNKNOWN_LOCATION, omp_clause_code (omp_code));
5126 break;
5128 case STRING_CST:
5130 size_t l;
5131 const char *chars = str (&l);
5132 t = build_string (l, chars);
5134 break;
5136 case VECTOR_CST:
5138 unsigned log2_npats = u ();
5139 unsigned elts_per = u ();
5140 t = make_vector (log2_npats, elts_per);
5142 break;
5144 case TREE_BINFO:
5145 t = make_tree_binfo (u ());
5146 break;
5148 case TREE_VEC:
5149 t = make_tree_vec (u ());
5150 break;
5152 case FIXED_CST:
5153 case IDENTIFIER_NODE:
5154 case POLY_INT_CST:
5155 case SSA_NAME:
5156 case TARGET_MEM_REF:
5157 case TRANSLATION_UNIT_DECL:
5158 goto fail;
5161 return t;
5164 /* The structure streamers access the raw fields, because the
5165 alternative, of using the accessor macros can require using
5166 different accessors for the same underlying field, depending on the
5167 tree code. That's both confusing and annoying. */
5169 /* Read & write the core boolean flags. */
5171 void
5172 trees_out::core_bools (tree t)
5174 #define WB(X) (b (X))
5175 tree_code code = TREE_CODE (t);
5177 WB (t->base.side_effects_flag);
5178 WB (t->base.constant_flag);
5179 WB (t->base.addressable_flag);
5180 WB (t->base.volatile_flag);
5181 WB (t->base.readonly_flag);
5182 /* base.asm_written_flag is a property of the current TU's use of
5183 this decl. */
5184 WB (t->base.nowarning_flag);
5185 /* base.visited read as zero (it's set for writer, because that's
5186 how we mark nodes). */
5187 /* base.used_flag is not streamed. Readers may set TREE_USED of
5188 decls they use. */
5189 WB (t->base.nothrow_flag);
5190 WB (t->base.static_flag);
5191 if (TREE_CODE_CLASS (code) != tcc_type)
5192 /* This is TYPE_CACHED_VALUES_P for types. */
5193 WB (t->base.public_flag);
5194 WB (t->base.private_flag);
5195 WB (t->base.protected_flag);
5196 WB (t->base.deprecated_flag);
5197 WB (t->base.default_def_flag);
5199 switch (code)
5201 case CALL_EXPR:
5202 case INTEGER_CST:
5203 case SSA_NAME:
5204 case TARGET_MEM_REF:
5205 case TREE_VEC:
5206 /* These use different base.u fields. */
5207 break;
5209 default:
5210 WB (t->base.u.bits.lang_flag_0);
5211 bool flag_1 = t->base.u.bits.lang_flag_1;
5212 if (!flag_1)
5214 else if (code == TEMPLATE_INFO)
5215 /* This is TI_PENDING_TEMPLATE_FLAG, not relevant to reader. */
5216 flag_1 = false;
5217 else if (code == VAR_DECL)
5219 /* This is DECL_INITIALIZED_P. */
5220 if (TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
5221 /* We'll set this when reading the definition. */
5222 flag_1 = false;
5224 WB (flag_1);
5225 WB (t->base.u.bits.lang_flag_2);
5226 WB (t->base.u.bits.lang_flag_3);
5227 WB (t->base.u.bits.lang_flag_4);
5228 WB (t->base.u.bits.lang_flag_5);
5229 WB (t->base.u.bits.lang_flag_6);
5230 WB (t->base.u.bits.saturating_flag);
5231 WB (t->base.u.bits.unsigned_flag);
5232 WB (t->base.u.bits.packed_flag);
5233 WB (t->base.u.bits.user_align);
5234 WB (t->base.u.bits.nameless_flag);
5235 WB (t->base.u.bits.atomic_flag);
5236 break;
5239 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
5241 WB (t->type_common.no_force_blk_flag);
5242 WB (t->type_common.needs_constructing_flag);
5243 WB (t->type_common.transparent_aggr_flag);
5244 WB (t->type_common.restrict_flag);
5245 WB (t->type_common.string_flag);
5246 WB (t->type_common.lang_flag_0);
5247 WB (t->type_common.lang_flag_1);
5248 WB (t->type_common.lang_flag_2);
5249 WB (t->type_common.lang_flag_3);
5250 WB (t->type_common.lang_flag_4);
5251 WB (t->type_common.lang_flag_5);
5252 WB (t->type_common.lang_flag_6);
5253 WB (t->type_common.typeless_storage);
5256 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5258 WB (t->decl_common.nonlocal_flag);
5259 WB (t->decl_common.virtual_flag);
5260 WB (t->decl_common.ignored_flag);
5261 WB (t->decl_common.abstract_flag);
5262 WB (t->decl_common.artificial_flag);
5263 WB (t->decl_common.preserve_flag);
5264 WB (t->decl_common.debug_expr_is_from);
5265 WB (t->decl_common.lang_flag_0);
5266 WB (t->decl_common.lang_flag_1);
5267 WB (t->decl_common.lang_flag_2);
5268 WB (t->decl_common.lang_flag_3);
5269 WB (t->decl_common.lang_flag_4);
5270 WB (t->decl_common.lang_flag_5);
5271 WB (t->decl_common.lang_flag_6);
5272 WB (t->decl_common.lang_flag_7);
5273 WB (t->decl_common.lang_flag_8);
5274 WB (t->decl_common.decl_flag_0);
5277 /* DECL_EXTERNAL -> decl_flag_1
5278 == it is defined elsewhere
5279 DECL_NOT_REALLY_EXTERN -> base.not_really_extern
5280 == that was a lie, it is here */
5282 bool is_external = t->decl_common.decl_flag_1;
5283 if (!is_external)
5284 /* decl_flag_1 is DECL_EXTERNAL. Things we emit here, might
5285 well be external from the POV of an importer. */
5286 // FIXME: Do we need to know if this is a TEMPLATE_RESULT --
5287 // a flag from the caller?
5288 switch (code)
5290 default:
5291 break;
5293 case VAR_DECL:
5294 if (TREE_PUBLIC (t)
5295 && !DECL_VAR_DECLARED_INLINE_P (t))
5296 is_external = true;
5297 break;
5299 case FUNCTION_DECL:
5300 if (TREE_PUBLIC (t)
5301 && !DECL_DECLARED_INLINE_P (t))
5302 is_external = true;
5303 break;
5305 WB (is_external);
5308 WB (t->decl_common.decl_flag_2);
5309 WB (t->decl_common.decl_flag_3);
5310 WB (t->decl_common.not_gimple_reg_flag);
5311 WB (t->decl_common.decl_by_reference_flag);
5312 WB (t->decl_common.decl_read_flag);
5313 WB (t->decl_common.decl_nonshareable_flag);
5316 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5318 WB (t->decl_with_vis.defer_output);
5319 WB (t->decl_with_vis.hard_register);
5320 WB (t->decl_with_vis.common_flag);
5321 WB (t->decl_with_vis.in_text_section);
5322 WB (t->decl_with_vis.in_constant_pool);
5323 WB (t->decl_with_vis.dllimport_flag);
5324 WB (t->decl_with_vis.weak_flag);
5325 WB (t->decl_with_vis.seen_in_bind_expr);
5326 WB (t->decl_with_vis.comdat_flag);
5327 WB (t->decl_with_vis.visibility_specified);
5328 WB (t->decl_with_vis.init_priority_p);
5329 WB (t->decl_with_vis.shadowed_for_var_p);
5330 WB (t->decl_with_vis.cxx_constructor);
5331 WB (t->decl_with_vis.cxx_destructor);
5332 WB (t->decl_with_vis.final);
5333 WB (t->decl_with_vis.regdecl_flag);
5336 if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
5338 WB (t->function_decl.static_ctor_flag);
5339 WB (t->function_decl.static_dtor_flag);
5340 WB (t->function_decl.uninlinable);
5341 WB (t->function_decl.possibly_inlined);
5342 WB (t->function_decl.novops_flag);
5343 WB (t->function_decl.returns_twice_flag);
5344 WB (t->function_decl.malloc_flag);
5345 WB (t->function_decl.declared_inline_flag);
5346 WB (t->function_decl.no_inline_warning_flag);
5347 WB (t->function_decl.no_instrument_function_entry_exit);
5348 WB (t->function_decl.no_limit_stack);
5349 WB (t->function_decl.disregard_inline_limits);
5350 WB (t->function_decl.pure_flag);
5351 WB (t->function_decl.looping_const_or_pure_flag);
5353 WB (t->function_decl.has_debug_args_flag);
5354 WB (t->function_decl.versioned_function);
5356 /* decl_type is a (misnamed) 2 bit discriminator. */
5357 unsigned kind = t->function_decl.decl_type;
5358 WB ((kind >> 0) & 1);
5359 WB ((kind >> 1) & 1);
5361 #undef WB
5364 bool
5365 trees_in::core_bools (tree t)
5367 #define RB(X) ((X) = b ())
5368 tree_code code = TREE_CODE (t);
5370 RB (t->base.side_effects_flag);
5371 RB (t->base.constant_flag);
5372 RB (t->base.addressable_flag);
5373 RB (t->base.volatile_flag);
5374 RB (t->base.readonly_flag);
5375 /* base.asm_written_flag is not streamed. */
5376 RB (t->base.nowarning_flag);
5377 /* base.visited is not streamed. */
5378 /* base.used_flag is not streamed. */
5379 RB (t->base.nothrow_flag);
5380 RB (t->base.static_flag);
5381 if (TREE_CODE_CLASS (code) != tcc_type)
5382 RB (t->base.public_flag);
5383 RB (t->base.private_flag);
5384 RB (t->base.protected_flag);
5385 RB (t->base.deprecated_flag);
5386 RB (t->base.default_def_flag);
5388 switch (code)
5390 case CALL_EXPR:
5391 case INTEGER_CST:
5392 case SSA_NAME:
5393 case TARGET_MEM_REF:
5394 case TREE_VEC:
5395 /* These use different base.u fields. */
5396 break;
5398 default:
5399 RB (t->base.u.bits.lang_flag_0);
5400 RB (t->base.u.bits.lang_flag_1);
5401 RB (t->base.u.bits.lang_flag_2);
5402 RB (t->base.u.bits.lang_flag_3);
5403 RB (t->base.u.bits.lang_flag_4);
5404 RB (t->base.u.bits.lang_flag_5);
5405 RB (t->base.u.bits.lang_flag_6);
5406 RB (t->base.u.bits.saturating_flag);
5407 RB (t->base.u.bits.unsigned_flag);
5408 RB (t->base.u.bits.packed_flag);
5409 RB (t->base.u.bits.user_align);
5410 RB (t->base.u.bits.nameless_flag);
5411 RB (t->base.u.bits.atomic_flag);
5412 break;
5415 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
5417 RB (t->type_common.no_force_blk_flag);
5418 RB (t->type_common.needs_constructing_flag);
5419 RB (t->type_common.transparent_aggr_flag);
5420 RB (t->type_common.restrict_flag);
5421 RB (t->type_common.string_flag);
5422 RB (t->type_common.lang_flag_0);
5423 RB (t->type_common.lang_flag_1);
5424 RB (t->type_common.lang_flag_2);
5425 RB (t->type_common.lang_flag_3);
5426 RB (t->type_common.lang_flag_4);
5427 RB (t->type_common.lang_flag_5);
5428 RB (t->type_common.lang_flag_6);
5429 RB (t->type_common.typeless_storage);
5432 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5434 RB (t->decl_common.nonlocal_flag);
5435 RB (t->decl_common.virtual_flag);
5436 RB (t->decl_common.ignored_flag);
5437 RB (t->decl_common.abstract_flag);
5438 RB (t->decl_common.artificial_flag);
5439 RB (t->decl_common.preserve_flag);
5440 RB (t->decl_common.debug_expr_is_from);
5441 RB (t->decl_common.lang_flag_0);
5442 RB (t->decl_common.lang_flag_1);
5443 RB (t->decl_common.lang_flag_2);
5444 RB (t->decl_common.lang_flag_3);
5445 RB (t->decl_common.lang_flag_4);
5446 RB (t->decl_common.lang_flag_5);
5447 RB (t->decl_common.lang_flag_6);
5448 RB (t->decl_common.lang_flag_7);
5449 RB (t->decl_common.lang_flag_8);
5450 RB (t->decl_common.decl_flag_0);
5451 RB (t->decl_common.decl_flag_1);
5452 RB (t->decl_common.decl_flag_2);
5453 RB (t->decl_common.decl_flag_3);
5454 RB (t->decl_common.not_gimple_reg_flag);
5455 RB (t->decl_common.decl_by_reference_flag);
5456 RB (t->decl_common.decl_read_flag);
5457 RB (t->decl_common.decl_nonshareable_flag);
5460 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5462 RB (t->decl_with_vis.defer_output);
5463 RB (t->decl_with_vis.hard_register);
5464 RB (t->decl_with_vis.common_flag);
5465 RB (t->decl_with_vis.in_text_section);
5466 RB (t->decl_with_vis.in_constant_pool);
5467 RB (t->decl_with_vis.dllimport_flag);
5468 RB (t->decl_with_vis.weak_flag);
5469 RB (t->decl_with_vis.seen_in_bind_expr);
5470 RB (t->decl_with_vis.comdat_flag);
5471 RB (t->decl_with_vis.visibility_specified);
5472 RB (t->decl_with_vis.init_priority_p);
5473 RB (t->decl_with_vis.shadowed_for_var_p);
5474 RB (t->decl_with_vis.cxx_constructor);
5475 RB (t->decl_with_vis.cxx_destructor);
5476 RB (t->decl_with_vis.final);
5477 RB (t->decl_with_vis.regdecl_flag);
5480 if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
5482 RB (t->function_decl.static_ctor_flag);
5483 RB (t->function_decl.static_dtor_flag);
5484 RB (t->function_decl.uninlinable);
5485 RB (t->function_decl.possibly_inlined);
5486 RB (t->function_decl.novops_flag);
5487 RB (t->function_decl.returns_twice_flag);
5488 RB (t->function_decl.malloc_flag);
5489 RB (t->function_decl.declared_inline_flag);
5490 RB (t->function_decl.no_inline_warning_flag);
5491 RB (t->function_decl.no_instrument_function_entry_exit);
5492 RB (t->function_decl.no_limit_stack);
5493 RB (t->function_decl.disregard_inline_limits);
5494 RB (t->function_decl.pure_flag);
5495 RB (t->function_decl.looping_const_or_pure_flag);
5497 RB (t->function_decl.has_debug_args_flag);
5498 RB (t->function_decl.versioned_function);
5500 /* decl_type is a (misnamed) 2 bit discriminator. */
5501 unsigned kind = 0;
5502 kind |= unsigned (b ()) << 0;
5503 kind |= unsigned (b ()) << 1;
5504 t->function_decl.decl_type = function_decl_type (kind);
5506 #undef RB
5507 return !get_overrun ();
5510 void
5511 trees_out::lang_decl_bools (tree t)
5513 #define WB(X) (b (X))
5514 const struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
5516 WB (lang->u.base.language == lang_cplusplus);
5517 WB ((lang->u.base.use_template >> 0) & 1);
5518 WB ((lang->u.base.use_template >> 1) & 1);
5519 /* Do not write lang->u.base.not_really_extern, importer will set
5520 when reading the definition (if any). */
5521 WB (lang->u.base.initialized_in_class);
5522 WB (lang->u.base.threadprivate_or_deleted_p);
5523 /* Do not write lang->u.base.anticipated_p, it is a property of the
5524 current TU. */
5525 WB (lang->u.base.friend_or_tls);
5526 WB (lang->u.base.unknown_bound_p);
5527 /* Do not write lang->u.base.odr_used, importer will recalculate if
5528 they do ODR use this decl. */
5529 WB (lang->u.base.concept_p);
5530 WB (lang->u.base.var_declared_inline_p);
5531 WB (lang->u.base.dependent_init_p);
5532 /* When building a header unit, everthing is marked as purview, but
5533 that's the GM purview, so not what the importer will mean */
5534 WB (lang->u.base.module_purview_p && !header_module_p ());
5535 if (VAR_OR_FUNCTION_DECL_P (t))
5536 WB (lang->u.base.module_attached_p);
5537 switch (lang->u.base.selector)
5539 default:
5540 gcc_unreachable ();
5542 case lds_fn: /* lang_decl_fn. */
5543 WB (lang->u.fn.global_ctor_p);
5544 WB (lang->u.fn.global_dtor_p);
5545 WB (lang->u.fn.static_function);
5546 WB (lang->u.fn.pure_virtual);
5547 WB (lang->u.fn.defaulted_p);
5548 WB (lang->u.fn.has_in_charge_parm_p);
5549 WB (lang->u.fn.has_vtt_parm_p);
5550 /* There shouldn't be a pending inline at this point. */
5551 gcc_assert (!lang->u.fn.pending_inline_p);
5552 WB (lang->u.fn.nonconverting);
5553 WB (lang->u.fn.thunk_p);
5554 WB (lang->u.fn.this_thunk_p);
5555 /* Do not stream lang->u.hidden_friend_p, it is a property of
5556 the TU. */
5557 WB (lang->u.fn.omp_declare_reduction_p);
5558 WB (lang->u.fn.has_dependent_explicit_spec_p);
5559 WB (lang->u.fn.immediate_fn_p);
5560 WB (lang->u.fn.maybe_deleted);
5561 goto lds_min;
5563 case lds_decomp: /* lang_decl_decomp. */
5564 /* No bools. */
5565 goto lds_min;
5567 case lds_min: /* lang_decl_min. */
5568 lds_min:
5569 /* No bools. */
5570 break;
5572 case lds_ns: /* lang_decl_ns. */
5573 /* No bools. */
5574 break;
5576 case lds_parm: /* lang_decl_parm. */
5577 /* No bools. */
5578 break;
5580 #undef WB
5583 bool
5584 trees_in::lang_decl_bools (tree t)
5586 #define RB(X) ((X) = b ())
5587 struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
5589 lang->u.base.language = b () ? lang_cplusplus : lang_c;
5590 unsigned v;
5591 v = b () << 0;
5592 v |= b () << 1;
5593 lang->u.base.use_template = v;
5594 /* lang->u.base.not_really_extern is not streamed. */
5595 RB (lang->u.base.initialized_in_class);
5596 RB (lang->u.base.threadprivate_or_deleted_p);
5597 /* lang->u.base.anticipated_p is not streamed. */
5598 RB (lang->u.base.friend_or_tls);
5599 RB (lang->u.base.unknown_bound_p);
5600 /* lang->u.base.odr_used is not streamed. */
5601 RB (lang->u.base.concept_p);
5602 RB (lang->u.base.var_declared_inline_p);
5603 RB (lang->u.base.dependent_init_p);
5604 RB (lang->u.base.module_purview_p);
5605 if (VAR_OR_FUNCTION_DECL_P (t))
5606 RB (lang->u.base.module_attached_p);
5607 switch (lang->u.base.selector)
5609 default:
5610 gcc_unreachable ();
5612 case lds_fn: /* lang_decl_fn. */
5613 RB (lang->u.fn.global_ctor_p);
5614 RB (lang->u.fn.global_dtor_p);
5615 RB (lang->u.fn.static_function);
5616 RB (lang->u.fn.pure_virtual);
5617 RB (lang->u.fn.defaulted_p);
5618 RB (lang->u.fn.has_in_charge_parm_p);
5619 RB (lang->u.fn.has_vtt_parm_p);
5620 RB (lang->u.fn.nonconverting);
5621 RB (lang->u.fn.thunk_p);
5622 RB (lang->u.fn.this_thunk_p);
5623 /* lang->u.fn.hidden_friend_p is not streamed. */
5624 RB (lang->u.fn.omp_declare_reduction_p);
5625 RB (lang->u.fn.has_dependent_explicit_spec_p);
5626 RB (lang->u.fn.immediate_fn_p);
5627 RB (lang->u.fn.maybe_deleted);
5628 goto lds_min;
5630 case lds_decomp: /* lang_decl_decomp. */
5631 /* No bools. */
5632 goto lds_min;
5634 case lds_min: /* lang_decl_min. */
5635 lds_min:
5636 /* No bools. */
5637 break;
5639 case lds_ns: /* lang_decl_ns. */
5640 /* No bools. */
5641 break;
5643 case lds_parm: /* lang_decl_parm. */
5644 /* No bools. */
5645 break;
5647 #undef RB
5648 return !get_overrun ();
5651 void
5652 trees_out::lang_type_bools (tree t)
5654 #define WB(X) (b (X))
5655 const struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
5657 WB (lang->has_type_conversion);
5658 WB (lang->has_copy_ctor);
5659 WB (lang->has_default_ctor);
5660 WB (lang->const_needs_init);
5661 WB (lang->ref_needs_init);
5662 WB (lang->has_const_copy_assign);
5663 WB ((lang->use_template >> 0) & 1);
5664 WB ((lang->use_template >> 1) & 1);
5666 WB (lang->has_mutable);
5667 WB (lang->com_interface);
5668 WB (lang->non_pod_class);
5669 WB (lang->nearly_empty_p);
5670 WB (lang->user_align);
5671 WB (lang->has_copy_assign);
5672 WB (lang->has_new);
5673 WB (lang->has_array_new);
5675 WB ((lang->gets_delete >> 0) & 1);
5676 WB ((lang->gets_delete >> 1) & 1);
5677 // Interfaceness is recalculated upon reading. May have to revisit?
5678 // How do dllexport and dllimport interact across a module?
5679 // lang->interface_only
5680 // lang->interface_unknown
5681 WB (lang->contains_empty_class_p);
5682 WB (lang->anon_aggr);
5683 WB (lang->non_zero_init);
5684 WB (lang->empty_p);
5686 WB (lang->vec_new_uses_cookie);
5687 WB (lang->declared_class);
5688 WB (lang->diamond_shaped);
5689 WB (lang->repeated_base);
5690 gcc_assert (!lang->being_defined);
5691 // lang->debug_requested
5692 WB (lang->fields_readonly);
5693 WB (lang->ptrmemfunc_flag);
5695 WB (lang->lazy_default_ctor);
5696 WB (lang->lazy_copy_ctor);
5697 WB (lang->lazy_copy_assign);
5698 WB (lang->lazy_destructor);
5699 WB (lang->has_const_copy_ctor);
5700 WB (lang->has_complex_copy_ctor);
5701 WB (lang->has_complex_copy_assign);
5702 WB (lang->non_aggregate);
5704 WB (lang->has_complex_dflt);
5705 WB (lang->has_list_ctor);
5706 WB (lang->non_std_layout);
5707 WB (lang->is_literal);
5708 WB (lang->lazy_move_ctor);
5709 WB (lang->lazy_move_assign);
5710 WB (lang->has_complex_move_ctor);
5711 WB (lang->has_complex_move_assign);
5713 WB (lang->has_constexpr_ctor);
5714 WB (lang->unique_obj_representations);
5715 WB (lang->unique_obj_representations_set);
5716 #undef WB
5719 bool
5720 trees_in::lang_type_bools (tree t)
5722 #define RB(X) ((X) = b ())
5723 struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
5725 RB (lang->has_type_conversion);
5726 RB (lang->has_copy_ctor);
5727 RB (lang->has_default_ctor);
5728 RB (lang->const_needs_init);
5729 RB (lang->ref_needs_init);
5730 RB (lang->has_const_copy_assign);
5731 unsigned v;
5732 v = b () << 0;
5733 v |= b () << 1;
5734 lang->use_template = v;
5736 RB (lang->has_mutable);
5737 RB (lang->com_interface);
5738 RB (lang->non_pod_class);
5739 RB (lang->nearly_empty_p);
5740 RB (lang->user_align);
5741 RB (lang->has_copy_assign);
5742 RB (lang->has_new);
5743 RB (lang->has_array_new);
5745 v = b () << 0;
5746 v |= b () << 1;
5747 lang->gets_delete = v;
5748 // lang->interface_only
5749 // lang->interface_unknown
5750 lang->interface_unknown = true; // Redetermine interface
5751 RB (lang->contains_empty_class_p);
5752 RB (lang->anon_aggr);
5753 RB (lang->non_zero_init);
5754 RB (lang->empty_p);
5756 RB (lang->vec_new_uses_cookie);
5757 RB (lang->declared_class);
5758 RB (lang->diamond_shaped);
5759 RB (lang->repeated_base);
5760 gcc_assert (!lang->being_defined);
5761 gcc_assert (!lang->debug_requested);
5762 RB (lang->fields_readonly);
5763 RB (lang->ptrmemfunc_flag);
5765 RB (lang->lazy_default_ctor);
5766 RB (lang->lazy_copy_ctor);
5767 RB (lang->lazy_copy_assign);
5768 RB (lang->lazy_destructor);
5769 RB (lang->has_const_copy_ctor);
5770 RB (lang->has_complex_copy_ctor);
5771 RB (lang->has_complex_copy_assign);
5772 RB (lang->non_aggregate);
5774 RB (lang->has_complex_dflt);
5775 RB (lang->has_list_ctor);
5776 RB (lang->non_std_layout);
5777 RB (lang->is_literal);
5778 RB (lang->lazy_move_ctor);
5779 RB (lang->lazy_move_assign);
5780 RB (lang->has_complex_move_ctor);
5781 RB (lang->has_complex_move_assign);
5783 RB (lang->has_constexpr_ctor);
5784 RB (lang->unique_obj_representations);
5785 RB (lang->unique_obj_representations_set);
5786 #undef RB
5787 return !get_overrun ();
5790 /* Read & write the core values and pointers. */
5792 void
5793 trees_out::core_vals (tree t)
5795 #define WU(X) (u (X))
5796 #define WT(X) (tree_node (X))
5797 tree_code code = TREE_CODE (t);
5799 /* First by shape of the tree. */
5801 if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
5803 /* Write this early, for better log information. */
5804 WT (t->decl_minimal.name);
5805 if (!DECL_TEMPLATE_PARM_P (t))
5806 WT (t->decl_minimal.context);
5808 if (state)
5809 state->write_location (*this, t->decl_minimal.locus);
5812 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
5814 /* The only types we write also have TYPE_NON_COMMON. */
5815 gcc_checking_assert (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON));
5817 /* We only stream the main variant. */
5818 gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
5820 /* Stream the name & context first, for better log information */
5821 WT (t->type_common.name);
5822 WT (t->type_common.context);
5824 /* By construction we want to make sure we have the canonical
5825 and main variants already in the type table, so emit them
5826 now. */
5827 WT (t->type_common.main_variant);
5829 tree canonical = t->type_common.canonical;
5830 if (canonical && DECL_TEMPLATE_PARM_P (TYPE_NAME (t)))
5831 /* We do not want to wander into different templates.
5832 Reconstructed on stream in. */
5833 canonical = t;
5834 WT (canonical);
5836 /* type_common.next_variant is internally manipulated. */
5837 /* type_common.pointer_to, type_common.reference_to. */
5839 if (streaming_p ())
5841 WU (t->type_common.precision);
5842 WU (t->type_common.contains_placeholder_bits);
5843 WU (t->type_common.mode);
5844 WU (t->type_common.align);
5847 if (!RECORD_OR_UNION_CODE_P (code))
5849 WT (t->type_common.size);
5850 WT (t->type_common.size_unit);
5852 WT (t->type_common.attributes);
5854 WT (t->type_common.common.chain); /* TYPE_STUB_DECL. */
5857 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5859 if (streaming_p ())
5861 WU (t->decl_common.mode);
5862 WU (t->decl_common.off_align);
5863 WU (t->decl_common.align);
5866 /* For templates these hold instantiation (partial and/or
5867 specialization) information. */
5868 if (code != TEMPLATE_DECL)
5870 WT (t->decl_common.size);
5871 WT (t->decl_common.size_unit);
5874 WT (t->decl_common.attributes);
5875 // FIXME: Does this introduce cross-decl links? For instance
5876 // from instantiation to the template. If so, we'll need more
5877 // deduplication logic. I think we'll need to walk the blocks
5878 // of the owning function_decl's abstract origin in tandem, to
5879 // generate the locating data needed?
5880 WT (t->decl_common.abstract_origin);
5883 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5885 WT (t->decl_with_vis.assembler_name);
5886 if (streaming_p ())
5887 WU (t->decl_with_vis.visibility);
5890 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
5892 /* Records and unions hold FIELDS, VFIELD & BINFO on these
5893 things. */
5894 if (!RECORD_OR_UNION_CODE_P (code) && code != ENUMERAL_TYPE)
5896 // FIXME: These are from tpl_parm_value's 'type' writing.
5897 // Perhaps it should just be doing them directly?
5898 gcc_checking_assert (code == TEMPLATE_TYPE_PARM
5899 || code == TEMPLATE_TEMPLATE_PARM
5900 || code == BOUND_TEMPLATE_TEMPLATE_PARM);
5901 gcc_checking_assert (!TYPE_CACHED_VALUES_P (t));
5902 WT (t->type_non_common.values);
5903 WT (t->type_non_common.maxval);
5904 WT (t->type_non_common.minval);
5907 WT (t->type_non_common.lang_1);
5910 if (CODE_CONTAINS_STRUCT (code, TS_EXP))
5912 if (state)
5913 state->write_location (*this, t->exp.locus);
5915 /* Walk in forward order, as (for instance) REQUIRES_EXPR has a
5916 bunch of unscoped parms on its first operand. It's safer to
5917 create those in order. */
5918 bool vl = TREE_CODE_CLASS (code) == tcc_vl_exp;
5919 for (unsigned limit = (vl ? VL_EXP_OPERAND_LENGTH (t)
5920 : TREE_OPERAND_LENGTH (t)),
5921 ix = unsigned (vl); ix != limit; ix++)
5922 WT (TREE_OPERAND (t, ix));
5924 else
5925 /* The CODE_CONTAINS tables were inaccurate when I started. */
5926 gcc_checking_assert (TREE_CODE_CLASS (code) != tcc_expression
5927 && TREE_CODE_CLASS (code) != tcc_binary
5928 && TREE_CODE_CLASS (code) != tcc_unary
5929 && TREE_CODE_CLASS (code) != tcc_reference
5930 && TREE_CODE_CLASS (code) != tcc_comparison
5931 && TREE_CODE_CLASS (code) != tcc_statement
5932 && TREE_CODE_CLASS (code) != tcc_vl_exp);
5934 /* Then by CODE. Special cases and/or 1:1 tree shape
5935 correspondance. */
5936 switch (code)
5938 default:
5939 break;
5941 case ARGUMENT_PACK_SELECT: /* Transient during instantiation. */
5942 case DEFERRED_PARSE: /* Expanded upon completion of
5943 outermost class. */
5944 case IDENTIFIER_NODE: /* Streamed specially. */
5945 case BINDING_VECTOR: /* Only in namespace-scope symbol
5946 table. */
5947 case SSA_NAME:
5948 case TRANSLATION_UNIT_DECL: /* There is only one, it is a
5949 global_tree. */
5950 case USERDEF_LITERAL: /* Expanded during parsing. */
5951 gcc_unreachable (); /* Should never meet. */
5953 /* Constants. */
5954 case COMPLEX_CST:
5955 WT (TREE_REALPART (t));
5956 WT (TREE_IMAGPART (t));
5957 break;
5959 case FIXED_CST:
5960 gcc_unreachable (); /* Not supported in C++. */
5962 case INTEGER_CST:
5963 if (streaming_p ())
5965 unsigned num = TREE_INT_CST_EXT_NUNITS (t);
5966 for (unsigned ix = 0; ix != num; ix++)
5967 wu (TREE_INT_CST_ELT (t, ix));
5969 break;
5971 case POLY_INT_CST:
5972 gcc_unreachable (); /* Not supported in C++. */
5974 case REAL_CST:
5975 if (streaming_p ())
5976 buf (TREE_REAL_CST_PTR (t), sizeof (real_value));
5977 break;
5979 case STRING_CST:
5980 /* Streamed during start. */
5981 break;
5983 case VECTOR_CST:
5984 for (unsigned ix = vector_cst_encoded_nelts (t); ix--;)
5985 WT (VECTOR_CST_ENCODED_ELT (t, ix));
5986 break;
5988 /* Decls. */
5989 case VAR_DECL:
5990 if (DECL_CONTEXT (t)
5991 && TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
5992 break;
5993 /* FALLTHROUGH */
5995 case RESULT_DECL:
5996 case PARM_DECL:
5997 if (DECL_HAS_VALUE_EXPR_P (t))
5998 WT (DECL_VALUE_EXPR (t));
5999 /* FALLTHROUGH */
6001 case CONST_DECL:
6002 case IMPORTED_DECL:
6003 WT (t->decl_common.initial);
6004 break;
6006 case FIELD_DECL:
6007 WT (t->field_decl.offset);
6008 WT (t->field_decl.bit_field_type);
6009 WT (t->field_decl.qualifier); /* bitfield unit. */
6010 WT (t->field_decl.bit_offset);
6011 WT (t->field_decl.fcontext);
6012 WT (t->decl_common.initial);
6013 break;
6015 case LABEL_DECL:
6016 if (streaming_p ())
6018 WU (t->label_decl.label_decl_uid);
6019 WU (t->label_decl.eh_landing_pad_nr);
6021 break;
6023 case FUNCTION_DECL:
6024 if (streaming_p ())
6026 /* Builtins can be streamed by value when a header declares
6027 them. */
6028 WU (DECL_BUILT_IN_CLASS (t));
6029 if (DECL_BUILT_IN_CLASS (t) != NOT_BUILT_IN)
6030 WU (DECL_UNCHECKED_FUNCTION_CODE (t));
6033 WT (t->function_decl.personality);
6034 WT (t->function_decl.function_specific_target);
6035 WT (t->function_decl.function_specific_optimization);
6036 WT (t->function_decl.vindex);
6037 break;
6039 case USING_DECL:
6040 /* USING_DECL_DECLS */
6041 WT (t->decl_common.initial);
6042 /* FALLTHROUGH */
6044 case TYPE_DECL:
6045 /* USING_DECL: USING_DECL_SCOPE */
6046 /* TYPE_DECL: DECL_ORIGINAL_TYPE */
6047 WT (t->decl_non_common.result);
6048 break;
6050 /* Miscellaneous common nodes. */
6051 case BLOCK:
6052 if (state)
6054 state->write_location (*this, t->block.locus);
6055 state->write_location (*this, t->block.end_locus);
6058 /* DECL_LOCAL_DECL_P decls are first encountered here and
6059 streamed by value. */
6060 chained_decls (t->block.vars);
6061 /* nonlocalized_vars is a middle-end thing. */
6062 WT (t->block.subblocks);
6063 WT (t->block.supercontext);
6064 // FIXME: As for decl's abstract_origin, does this introduce crosslinks?
6065 WT (t->block.abstract_origin);
6066 /* fragment_origin, fragment_chain are middle-end things. */
6067 WT (t->block.chain);
6068 /* nonlocalized_vars, block_num & die are middle endy/debug
6069 things. */
6070 break;
6072 case CALL_EXPR:
6073 if (streaming_p ())
6074 WU (t->base.u.ifn);
6075 break;
6077 case CONSTRUCTOR:
6079 unsigned len = vec_safe_length (t->constructor.elts);
6080 if (streaming_p ())
6081 WU (len);
6082 if (len)
6083 for (unsigned ix = 0; ix != len; ix++)
6085 const constructor_elt &elt = (*t->constructor.elts)[ix];
6087 WT (elt.index);
6088 WT (elt.value);
6091 break;
6093 case OMP_CLAUSE:
6095 /* The ompcode is serialized in start. */
6096 if (streaming_p ())
6097 WU (t->omp_clause.subcode.map_kind);
6098 if (state)
6099 state->write_location (*this, t->omp_clause.locus);
6101 unsigned len = omp_clause_num_ops[OMP_CLAUSE_CODE (t)];
6102 for (unsigned ix = 0; ix != len; ix++)
6103 WT (t->omp_clause.ops[ix]);
6105 break;
6107 case STATEMENT_LIST:
6108 for (tree stmt : tsi_range (t))
6109 if (stmt)
6110 WT (stmt);
6111 WT (NULL_TREE);
6112 break;
6114 case OPTIMIZATION_NODE:
6115 case TARGET_OPTION_NODE:
6116 // FIXME: Our representation for these two nodes is a cache of
6117 // the resulting set of options. Not a record of the options
6118 // that got changed by a particular attribute or pragma. Should
6119 // we record that, or should we record the diff from the command
6120 // line options? The latter seems the right behaviour, but is
6121 // (a) harder, and I guess could introduce strangeness if the
6122 // importer has set some incompatible set of optimization flags?
6123 gcc_unreachable ();
6124 break;
6126 case TREE_BINFO:
6128 WT (t->binfo.common.chain);
6129 WT (t->binfo.offset);
6130 WT (t->binfo.inheritance);
6131 WT (t->binfo.vptr_field);
6133 WT (t->binfo.vtable);
6134 WT (t->binfo.virtuals);
6135 WT (t->binfo.vtt_subvtt);
6136 WT (t->binfo.vtt_vptr);
6138 tree_vec (BINFO_BASE_ACCESSES (t));
6139 unsigned num = vec_safe_length (BINFO_BASE_ACCESSES (t));
6140 for (unsigned ix = 0; ix != num; ix++)
6141 WT (BINFO_BASE_BINFO (t, ix));
6143 break;
6145 case TREE_LIST:
6146 WT (t->list.purpose);
6147 WT (t->list.value);
6148 WT (t->list.common.chain);
6149 break;
6151 case TREE_VEC:
6152 for (unsigned ix = TREE_VEC_LENGTH (t); ix--;)
6153 WT (TREE_VEC_ELT (t, ix));
6154 /* We stash NON_DEFAULT_TEMPLATE_ARGS_COUNT on TREE_CHAIN! */
6155 gcc_checking_assert (!t->type_common.common.chain
6156 || (TREE_CODE (t->type_common.common.chain)
6157 == INTEGER_CST));
6158 WT (t->type_common.common.chain);
6159 break;
6161 /* C++-specific nodes ... */
6162 case BASELINK:
6163 WT (((lang_tree_node *)t)->baselink.binfo);
6164 WT (((lang_tree_node *)t)->baselink.functions);
6165 WT (((lang_tree_node *)t)->baselink.access_binfo);
6166 break;
6168 case CONSTRAINT_INFO:
6169 WT (((lang_tree_node *)t)->constraint_info.template_reqs);
6170 WT (((lang_tree_node *)t)->constraint_info.declarator_reqs);
6171 WT (((lang_tree_node *)t)->constraint_info.associated_constr);
6172 break;
6174 case DEFERRED_NOEXCEPT:
6175 WT (((lang_tree_node *)t)->deferred_noexcept.pattern);
6176 WT (((lang_tree_node *)t)->deferred_noexcept.args);
6177 break;
6179 case LAMBDA_EXPR:
6180 WT (((lang_tree_node *)t)->lambda_expression.capture_list);
6181 WT (((lang_tree_node *)t)->lambda_expression.this_capture);
6182 WT (((lang_tree_node *)t)->lambda_expression.extra_scope);
6183 /* pending_proxies is a parse-time thing. */
6184 gcc_assert (!((lang_tree_node *)t)->lambda_expression.pending_proxies);
6185 if (state)
6186 state->write_location
6187 (*this, ((lang_tree_node *)t)->lambda_expression.locus);
6188 if (streaming_p ())
6190 WU (((lang_tree_node *)t)->lambda_expression.default_capture_mode);
6191 WU (((lang_tree_node *)t)->lambda_expression.discriminator);
6193 break;
6195 case OVERLOAD:
6196 WT (((lang_tree_node *)t)->overload.function);
6197 WT (t->common.chain);
6198 break;
6200 case PTRMEM_CST:
6201 WT (((lang_tree_node *)t)->ptrmem.member);
6202 break;
6204 case STATIC_ASSERT:
6205 WT (((lang_tree_node *)t)->static_assertion.condition);
6206 WT (((lang_tree_node *)t)->static_assertion.message);
6207 if (state)
6208 state->write_location
6209 (*this, ((lang_tree_node *)t)->static_assertion.location);
6210 break;
6212 case TEMPLATE_DECL:
6213 /* Streamed with the template_decl node itself. */
6214 gcc_checking_assert
6215 (TREE_VISITED (((lang_tree_node *)t)->template_decl.arguments));
6216 gcc_checking_assert
6217 (TREE_VISITED (((lang_tree_node *)t)->template_decl.result)
6218 || dep_hash->find_dependency (t)->is_alias_tmpl_inst ());
6219 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (t))
6220 WT (DECL_CHAIN (t));
6221 break;
6223 case TEMPLATE_INFO:
6225 WT (((lang_tree_node *)t)->template_info.tmpl);
6226 WT (((lang_tree_node *)t)->template_info.args);
6228 const auto *ac = (((lang_tree_node *)t)
6229 ->template_info.deferred_access_checks);
6230 unsigned len = vec_safe_length (ac);
6231 if (streaming_p ())
6232 u (len);
6233 if (len)
6235 for (unsigned ix = 0; ix != len; ix++)
6237 const auto &m = (*ac)[ix];
6238 WT (m.binfo);
6239 WT (m.decl);
6240 WT (m.diag_decl);
6241 if (state)
6242 state->write_location (*this, m.loc);
6246 break;
6248 case TEMPLATE_PARM_INDEX:
6249 if (streaming_p ())
6251 WU (((lang_tree_node *)t)->tpi.index);
6252 WU (((lang_tree_node *)t)->tpi.level);
6253 WU (((lang_tree_node *)t)->tpi.orig_level);
6255 WT (((lang_tree_node *)t)->tpi.decl);
6256 /* TEMPLATE_PARM_DESCENDANTS (AKA TREE_CHAIN) is an internal
6257 cache, do not stream. */
6258 break;
6260 case TRAIT_EXPR:
6261 WT (((lang_tree_node *)t)->trait_expression.type1);
6262 WT (((lang_tree_node *)t)->trait_expression.type2);
6263 if (streaming_p ())
6264 WU (((lang_tree_node *)t)->trait_expression.kind);
6265 break;
6268 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
6270 /* We want to stream the type of a expression-like nodes /after/
6271 we've streamed the operands. The type often contains (bits
6272 of the) types of the operands, and with things like decltype
6273 and noexcept in play, we really want to stream the decls
6274 defining the type before we try and stream the type on its
6275 own. Otherwise we can find ourselves trying to read in a
6276 decl, when we're already partially reading in a component of
6277 its type. And that's bad. */
6278 tree type = t->typed.type;
6279 unsigned prec = 0;
6281 switch (code)
6283 default:
6284 break;
6286 case TEMPLATE_DECL:
6287 /* We fill in the template's type separately. */
6288 type = NULL_TREE;
6289 break;
6291 case TYPE_DECL:
6292 if (DECL_ORIGINAL_TYPE (t) && t == TYPE_NAME (type))
6293 /* This is a typedef. We set its type separately. */
6294 type = NULL_TREE;
6295 break;
6297 case ENUMERAL_TYPE:
6298 if (type && !ENUM_FIXED_UNDERLYING_TYPE_P (t))
6300 /* Type is a restricted range integer type derived from the
6301 integer_types. Find the right one. */
6302 prec = TYPE_PRECISION (type);
6303 tree name = DECL_NAME (TYPE_NAME (type));
6305 for (unsigned itk = itk_none; itk--;)
6306 if (integer_types[itk]
6307 && DECL_NAME (TYPE_NAME (integer_types[itk])) == name)
6309 type = integer_types[itk];
6310 break;
6312 gcc_assert (type != t->typed.type);
6314 break;
6317 WT (type);
6318 if (prec && streaming_p ())
6319 WU (prec);
6322 #undef WT
6323 #undef WU
6326 // Streaming in a reference to a decl can cause that decl to be
6327 // TREE_USED, which is the mark_used behaviour we need most of the
6328 // time. The trees_in::unused can be incremented to inhibit this,
6329 // which is at least needed for vtables.
6331 bool
6332 trees_in::core_vals (tree t)
6334 #define RU(X) ((X) = u ())
6335 #define RUC(T,X) ((X) = T (u ()))
6336 #define RT(X) ((X) = tree_node ())
6337 #define RTU(X) ((X) = tree_node (true))
6338 tree_code code = TREE_CODE (t);
6340 /* First by tree shape. */
6341 if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
6343 RT (t->decl_minimal.name);
6344 if (!DECL_TEMPLATE_PARM_P (t))
6345 RT (t->decl_minimal.context);
6347 /* Don't zap the locus just yet, we don't record it correctly
6348 and thus lose all location information. */
6349 t->decl_minimal.locus = state->read_location (*this);
6352 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
6354 RT (t->type_common.name);
6355 RT (t->type_common.context);
6357 RT (t->type_common.main_variant);
6358 RT (t->type_common.canonical);
6360 /* type_common.next_variant is internally manipulated. */
6361 /* type_common.pointer_to, type_common.reference_to. */
6363 RU (t->type_common.precision);
6364 RU (t->type_common.contains_placeholder_bits);
6365 RUC (machine_mode, t->type_common.mode);
6366 RU (t->type_common.align);
6368 if (!RECORD_OR_UNION_CODE_P (code))
6370 RT (t->type_common.size);
6371 RT (t->type_common.size_unit);
6373 RT (t->type_common.attributes);
6375 RT (t->type_common.common.chain); /* TYPE_STUB_DECL. */
6378 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
6380 RUC (machine_mode, t->decl_common.mode);
6381 RU (t->decl_common.off_align);
6382 RU (t->decl_common.align);
6384 if (code != TEMPLATE_DECL)
6386 RT (t->decl_common.size);
6387 RT (t->decl_common.size_unit);
6390 RT (t->decl_common.attributes);
6391 RT (t->decl_common.abstract_origin);
6394 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
6396 RT (t->decl_with_vis.assembler_name);
6397 RUC (symbol_visibility, t->decl_with_vis.visibility);
6400 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
6402 /* Records and unions hold FIELDS, VFIELD & BINFO on these
6403 things. */
6404 if (!RECORD_OR_UNION_CODE_P (code) && code != ENUMERAL_TYPE)
6406 /* This is not clobbering TYPE_CACHED_VALUES, because this
6407 is a type that doesn't have any. */
6408 gcc_checking_assert (!TYPE_CACHED_VALUES_P (t));
6409 RT (t->type_non_common.values);
6410 RT (t->type_non_common.maxval);
6411 RT (t->type_non_common.minval);
6414 RT (t->type_non_common.lang_1);
6417 if (CODE_CONTAINS_STRUCT (code, TS_EXP))
6419 t->exp.locus = state->read_location (*this);
6421 bool vl = TREE_CODE_CLASS (code) == tcc_vl_exp;
6422 for (unsigned limit = (vl ? VL_EXP_OPERAND_LENGTH (t)
6423 : TREE_OPERAND_LENGTH (t)),
6424 ix = unsigned (vl); ix != limit; ix++)
6425 RTU (TREE_OPERAND (t, ix));
6428 /* Then by CODE. Special cases and/or 1:1 tree shape
6429 correspondance. */
6430 switch (code)
6432 default:
6433 break;
6435 case ARGUMENT_PACK_SELECT:
6436 case DEFERRED_PARSE:
6437 case IDENTIFIER_NODE:
6438 case BINDING_VECTOR:
6439 case SSA_NAME:
6440 case TRANSLATION_UNIT_DECL:
6441 case USERDEF_LITERAL:
6442 return false; /* Should never meet. */
6444 /* Constants. */
6445 case COMPLEX_CST:
6446 RT (TREE_REALPART (t));
6447 RT (TREE_IMAGPART (t));
6448 break;
6450 case FIXED_CST:
6451 /* Not suported in C++. */
6452 return false;
6454 case INTEGER_CST:
6456 unsigned num = TREE_INT_CST_EXT_NUNITS (t);
6457 for (unsigned ix = 0; ix != num; ix++)
6458 TREE_INT_CST_ELT (t, ix) = wu ();
6460 break;
6462 case POLY_INT_CST:
6463 /* Not suported in C++. */
6464 return false;
6466 case REAL_CST:
6467 if (const void *bytes = buf (sizeof (real_value)))
6468 TREE_REAL_CST_PTR (t)
6469 = reinterpret_cast<real_value *> (memcpy (ggc_alloc<real_value> (),
6470 bytes, sizeof (real_value)));
6471 break;
6473 case STRING_CST:
6474 /* Streamed during start. */
6475 break;
6477 case VECTOR_CST:
6478 for (unsigned ix = vector_cst_encoded_nelts (t); ix--;)
6479 RT (VECTOR_CST_ENCODED_ELT (t, ix));
6480 break;
6482 /* Decls. */
6483 case VAR_DECL:
6484 if (DECL_CONTEXT (t)
6485 && TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
6486 break;
6487 /* FALLTHROUGH */
6489 case RESULT_DECL:
6490 case PARM_DECL:
6491 if (DECL_HAS_VALUE_EXPR_P (t))
6493 /* The DECL_VALUE hash table is a cache, thus if we're
6494 reading a duplicate (which we end up discarding), the
6495 value expr will also be cleaned up at the next gc. */
6496 tree val = tree_node ();
6497 SET_DECL_VALUE_EXPR (t, val);
6499 /* FALLTHROUGH */
6501 case CONST_DECL:
6502 case IMPORTED_DECL:
6503 RT (t->decl_common.initial);
6504 break;
6506 case FIELD_DECL:
6507 RT (t->field_decl.offset);
6508 RT (t->field_decl.bit_field_type);
6509 RT (t->field_decl.qualifier);
6510 RT (t->field_decl.bit_offset);
6511 RT (t->field_decl.fcontext);
6512 RT (t->decl_common.initial);
6513 break;
6515 case LABEL_DECL:
6516 RU (t->label_decl.label_decl_uid);
6517 RU (t->label_decl.eh_landing_pad_nr);
6518 break;
6520 case FUNCTION_DECL:
6522 unsigned bltin = u ();
6523 t->function_decl.built_in_class = built_in_class (bltin);
6524 if (bltin != NOT_BUILT_IN)
6526 bltin = u ();
6527 DECL_UNCHECKED_FUNCTION_CODE (t) = built_in_function (bltin);
6530 RT (t->function_decl.personality);
6531 RT (t->function_decl.function_specific_target);
6532 RT (t->function_decl.function_specific_optimization);
6533 RT (t->function_decl.vindex);
6535 break;
6537 case USING_DECL:
6538 /* USING_DECL_DECLS */
6539 RT (t->decl_common.initial);
6540 /* FALLTHROUGH */
6542 case TYPE_DECL:
6543 /* USING_DECL: USING_DECL_SCOPE */
6544 /* TYPE_DECL: DECL_ORIGINAL_TYPE */
6545 RT (t->decl_non_common.result);
6546 break;
6548 /* Miscellaneous common nodes. */
6549 case BLOCK:
6550 t->block.locus = state->read_location (*this);
6551 t->block.end_locus = state->read_location (*this);
6552 t->block.vars = chained_decls ();
6553 /* nonlocalized_vars is middle-end. */
6554 RT (t->block.subblocks);
6555 RT (t->block.supercontext);
6556 RT (t->block.abstract_origin);
6557 /* fragment_origin, fragment_chain are middle-end. */
6558 RT (t->block.chain);
6559 /* nonlocalized_vars, block_num, die are middle endy/debug
6560 things. */
6561 break;
6563 case CALL_EXPR:
6564 RUC (internal_fn, t->base.u.ifn);
6565 break;
6567 case CONSTRUCTOR:
6568 if (unsigned len = u ())
6570 vec_alloc (t->constructor.elts, len);
6571 for (unsigned ix = 0; ix != len; ix++)
6573 constructor_elt elt;
6575 RT (elt.index);
6576 RTU (elt.value);
6577 t->constructor.elts->quick_push (elt);
6580 break;
6582 case OMP_CLAUSE:
6584 RU (t->omp_clause.subcode.map_kind);
6585 t->omp_clause.locus = state->read_location (*this);
6587 unsigned len = omp_clause_num_ops[OMP_CLAUSE_CODE (t)];
6588 for (unsigned ix = 0; ix != len; ix++)
6589 RT (t->omp_clause.ops[ix]);
6591 break;
6593 case STATEMENT_LIST:
6595 tree_stmt_iterator iter = tsi_start (t);
6596 for (tree stmt; RT (stmt);)
6597 tsi_link_after (&iter, stmt, TSI_CONTINUE_LINKING);
6599 break;
6601 case OPTIMIZATION_NODE:
6602 case TARGET_OPTION_NODE:
6603 /* Not yet implemented, see trees_out::core_vals. */
6604 gcc_unreachable ();
6605 break;
6607 case TREE_BINFO:
6608 RT (t->binfo.common.chain);
6609 RT (t->binfo.offset);
6610 RT (t->binfo.inheritance);
6611 RT (t->binfo.vptr_field);
6613 /* Do not mark the vtables as USED in the address expressions
6614 here. */
6615 unused++;
6616 RT (t->binfo.vtable);
6617 RT (t->binfo.virtuals);
6618 RT (t->binfo.vtt_subvtt);
6619 RT (t->binfo.vtt_vptr);
6620 unused--;
6622 BINFO_BASE_ACCESSES (t) = tree_vec ();
6623 if (!get_overrun ())
6625 unsigned num = vec_safe_length (BINFO_BASE_ACCESSES (t));
6626 for (unsigned ix = 0; ix != num; ix++)
6627 BINFO_BASE_APPEND (t, tree_node ());
6629 break;
6631 case TREE_LIST:
6632 RT (t->list.purpose);
6633 RT (t->list.value);
6634 RT (t->list.common.chain);
6635 break;
6637 case TREE_VEC:
6638 for (unsigned ix = TREE_VEC_LENGTH (t); ix--;)
6639 RT (TREE_VEC_ELT (t, ix));
6640 RT (t->type_common.common.chain);
6641 break;
6643 /* C++-specific nodes ... */
6644 case BASELINK:
6645 RT (((lang_tree_node *)t)->baselink.binfo);
6646 RTU (((lang_tree_node *)t)->baselink.functions);
6647 RT (((lang_tree_node *)t)->baselink.access_binfo);
6648 break;
6650 case CONSTRAINT_INFO:
6651 RT (((lang_tree_node *)t)->constraint_info.template_reqs);
6652 RT (((lang_tree_node *)t)->constraint_info.declarator_reqs);
6653 RT (((lang_tree_node *)t)->constraint_info.associated_constr);
6654 break;
6656 case DEFERRED_NOEXCEPT:
6657 RT (((lang_tree_node *)t)->deferred_noexcept.pattern);
6658 RT (((lang_tree_node *)t)->deferred_noexcept.args);
6659 break;
6661 case LAMBDA_EXPR:
6662 RT (((lang_tree_node *)t)->lambda_expression.capture_list);
6663 RT (((lang_tree_node *)t)->lambda_expression.this_capture);
6664 RT (((lang_tree_node *)t)->lambda_expression.extra_scope);
6665 /* lambda_expression.pending_proxies is NULL */
6666 ((lang_tree_node *)t)->lambda_expression.locus
6667 = state->read_location (*this);
6668 RUC (cp_lambda_default_capture_mode_type,
6669 ((lang_tree_node *)t)->lambda_expression.default_capture_mode);
6670 RU (((lang_tree_node *)t)->lambda_expression.discriminator);
6671 break;
6673 case OVERLOAD:
6674 RT (((lang_tree_node *)t)->overload.function);
6675 RT (t->common.chain);
6676 break;
6678 case PTRMEM_CST:
6679 RT (((lang_tree_node *)t)->ptrmem.member);
6680 break;
6682 case STATIC_ASSERT:
6683 RT (((lang_tree_node *)t)->static_assertion.condition);
6684 RT (((lang_tree_node *)t)->static_assertion.message);
6685 ((lang_tree_node *)t)->static_assertion.location
6686 = state->read_location (*this);
6687 break;
6689 case TEMPLATE_DECL:
6690 /* Streamed when reading the raw template decl itself. */
6691 gcc_assert (((lang_tree_node *)t)->template_decl.arguments);
6692 gcc_assert (((lang_tree_node *)t)->template_decl.result);
6693 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (t))
6694 RT (DECL_CHAIN (t));
6695 break;
6697 case TEMPLATE_INFO:
6698 RT (((lang_tree_node *)t)->template_info.tmpl);
6699 RT (((lang_tree_node *)t)->template_info.args);
6700 if (unsigned len = u ())
6702 auto &ac = (((lang_tree_node *)t)
6703 ->template_info.deferred_access_checks);
6704 vec_alloc (ac, len);
6705 for (unsigned ix = 0; ix != len; ix++)
6707 deferred_access_check m;
6709 RT (m.binfo);
6710 RT (m.decl);
6711 RT (m.diag_decl);
6712 m.loc = state->read_location (*this);
6713 ac->quick_push (m);
6716 break;
6718 case TEMPLATE_PARM_INDEX:
6719 RU (((lang_tree_node *)t)->tpi.index);
6720 RU (((lang_tree_node *)t)->tpi.level);
6721 RU (((lang_tree_node *)t)->tpi.orig_level);
6722 RT (((lang_tree_node *)t)->tpi.decl);
6723 break;
6725 case TRAIT_EXPR:
6726 RT (((lang_tree_node *)t)->trait_expression.type1);
6727 RT (((lang_tree_node *)t)->trait_expression.type2);
6728 RUC (cp_trait_kind, ((lang_tree_node *)t)->trait_expression.kind);
6729 break;
6732 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
6734 tree type = tree_node ();
6736 if (type && code == ENUMERAL_TYPE && !ENUM_FIXED_UNDERLYING_TYPE_P (t))
6738 unsigned precision = u ();
6740 type = build_distinct_type_copy (type);
6741 TYPE_PRECISION (type) = precision;
6742 set_min_and_max_values_for_integral_type (type, precision,
6743 TYPE_SIGN (type));
6746 if (code != TEMPLATE_DECL)
6747 t->typed.type = type;
6750 #undef RT
6751 #undef RM
6752 #undef RU
6753 return !get_overrun ();
6756 void
6757 trees_out::lang_decl_vals (tree t)
6759 const struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
6760 #define WU(X) (u (X))
6761 #define WT(X) (tree_node (X))
6762 /* Module index already written. */
6763 switch (lang->u.base.selector)
6765 default:
6766 gcc_unreachable ();
6768 case lds_fn: /* lang_decl_fn. */
6769 if (streaming_p ())
6771 if (DECL_NAME (t) && IDENTIFIER_OVL_OP_P (DECL_NAME (t)))
6772 WU (lang->u.fn.ovl_op_code);
6775 if (DECL_CLASS_SCOPE_P (t))
6776 WT (lang->u.fn.context);
6778 if (lang->u.fn.thunk_p)
6780 /* The thunked-to function. */
6781 WT (lang->u.fn.befriending_classes);
6782 if (streaming_p ())
6783 wi (lang->u.fn.u5.fixed_offset);
6785 else
6786 WT (lang->u.fn.u5.cloned_function);
6788 if (FNDECL_USED_AUTO (t))
6789 WT (lang->u.fn.u.saved_auto_return_type);
6791 goto lds_min;
6793 case lds_decomp: /* lang_decl_decomp. */
6794 WT (lang->u.decomp.base);
6795 goto lds_min;
6797 case lds_min: /* lang_decl_min. */
6798 lds_min:
6799 WT (lang->u.min.template_info);
6801 tree access = lang->u.min.access;
6803 /* DECL_ACCESS needs to be maintained by the definition of the
6804 (derived) class that changes the access. The other users
6805 of DECL_ACCESS need to write it here. */
6806 if (!DECL_THUNK_P (t)
6807 && (DECL_CONTEXT (t) && TYPE_P (DECL_CONTEXT (t))))
6808 access = NULL_TREE;
6810 WT (access);
6812 break;
6814 case lds_ns: /* lang_decl_ns. */
6815 break;
6817 case lds_parm: /* lang_decl_parm. */
6818 if (streaming_p ())
6820 WU (lang->u.parm.level);
6821 WU (lang->u.parm.index);
6823 break;
6825 #undef WU
6826 #undef WT
6829 bool
6830 trees_in::lang_decl_vals (tree t)
6832 struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
6833 #define RU(X) ((X) = u ())
6834 #define RT(X) ((X) = tree_node ())
6836 /* Module index already read. */
6837 switch (lang->u.base.selector)
6839 default:
6840 gcc_unreachable ();
6842 case lds_fn: /* lang_decl_fn. */
6843 if (DECL_NAME (t) && IDENTIFIER_OVL_OP_P (DECL_NAME (t)))
6845 unsigned code = u ();
6847 /* Check consistency. */
6848 if (code >= OVL_OP_MAX
6849 || (ovl_op_info[IDENTIFIER_ASSIGN_OP_P (DECL_NAME (t))][code]
6850 .ovl_op_code) == OVL_OP_ERROR_MARK)
6851 set_overrun ();
6852 else
6853 lang->u.fn.ovl_op_code = code;
6856 if (DECL_CLASS_SCOPE_P (t))
6857 RT (lang->u.fn.context);
6859 if (lang->u.fn.thunk_p)
6861 RT (lang->u.fn.befriending_classes);
6862 lang->u.fn.u5.fixed_offset = wi ();
6864 else
6865 RT (lang->u.fn.u5.cloned_function);
6867 if (FNDECL_USED_AUTO (t))
6868 RT (lang->u.fn.u.saved_auto_return_type);
6869 goto lds_min;
6871 case lds_decomp: /* lang_decl_decomp. */
6872 RT (lang->u.decomp.base);
6873 goto lds_min;
6875 case lds_min: /* lang_decl_min. */
6876 lds_min:
6877 RT (lang->u.min.template_info);
6878 RT (lang->u.min.access);
6879 break;
6881 case lds_ns: /* lang_decl_ns. */
6882 break;
6884 case lds_parm: /* lang_decl_parm. */
6885 RU (lang->u.parm.level);
6886 RU (lang->u.parm.index);
6887 break;
6889 #undef RU
6890 #undef RT
6891 return !get_overrun ();
6894 /* Most of the value contents of lang_type is streamed in
6895 define_class. */
6897 void
6898 trees_out::lang_type_vals (tree t)
6900 const struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
6901 #define WU(X) (u (X))
6902 #define WT(X) (tree_node (X))
6903 if (streaming_p ())
6904 WU (lang->align);
6905 #undef WU
6906 #undef WT
6909 bool
6910 trees_in::lang_type_vals (tree t)
6912 struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
6913 #define RU(X) ((X) = u ())
6914 #define RT(X) ((X) = tree_node ())
6915 RU (lang->align);
6916 #undef RU
6917 #undef RT
6918 return !get_overrun ();
6921 /* Write out the bools of T, including information about any
6922 LANG_SPECIFIC information. Including allocation of any lang
6923 specific object. */
6925 void
6926 trees_out::tree_node_bools (tree t)
6928 gcc_checking_assert (streaming_p ());
6930 /* We should never stream a namespace. */
6931 gcc_checking_assert (TREE_CODE (t) != NAMESPACE_DECL
6932 || DECL_NAMESPACE_ALIAS (t));
6934 core_bools (t);
6936 switch (TREE_CODE_CLASS (TREE_CODE (t)))
6938 case tcc_declaration:
6940 bool specific = DECL_LANG_SPECIFIC (t) != NULL;
6941 b (specific);
6942 if (specific && VAR_P (t))
6943 b (DECL_DECOMPOSITION_P (t));
6944 if (specific)
6945 lang_decl_bools (t);
6947 break;
6949 case tcc_type:
6951 bool specific = (TYPE_MAIN_VARIANT (t) == t
6952 && TYPE_LANG_SPECIFIC (t) != NULL);
6953 gcc_assert (TYPE_LANG_SPECIFIC (t)
6954 == TYPE_LANG_SPECIFIC (TYPE_MAIN_VARIANT (t)));
6956 b (specific);
6957 if (specific)
6958 lang_type_bools (t);
6960 break;
6962 default:
6963 break;
6966 bflush ();
6969 bool
6970 trees_in::tree_node_bools (tree t)
6972 bool ok = core_bools (t);
6974 if (ok)
6975 switch (TREE_CODE_CLASS (TREE_CODE (t)))
6977 case tcc_declaration:
6978 if (b ())
6980 bool decomp = VAR_P (t) && b ();
6982 ok = maybe_add_lang_decl_raw (t, decomp);
6983 if (ok)
6984 ok = lang_decl_bools (t);
6986 break;
6988 case tcc_type:
6989 if (b ())
6991 ok = maybe_add_lang_type_raw (t);
6992 if (ok)
6993 ok = lang_type_bools (t);
6995 break;
6997 default:
6998 break;
7001 bflush ();
7002 if (!ok || get_overrun ())
7003 return false;
7005 return true;
7009 /* Write out the lang-specifc vals of node T. */
7011 void
7012 trees_out::lang_vals (tree t)
7014 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7016 case tcc_declaration:
7017 if (DECL_LANG_SPECIFIC (t))
7018 lang_decl_vals (t);
7019 break;
7021 case tcc_type:
7022 if (TYPE_MAIN_VARIANT (t) == t && TYPE_LANG_SPECIFIC (t))
7023 lang_type_vals (t);
7024 break;
7026 default:
7027 break;
7031 bool
7032 trees_in::lang_vals (tree t)
7034 bool ok = true;
7036 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7038 case tcc_declaration:
7039 if (DECL_LANG_SPECIFIC (t))
7040 ok = lang_decl_vals (t);
7041 break;
7043 case tcc_type:
7044 if (TYPE_LANG_SPECIFIC (t))
7045 ok = lang_type_vals (t);
7046 else
7047 TYPE_LANG_SPECIFIC (t) = TYPE_LANG_SPECIFIC (TYPE_MAIN_VARIANT (t));
7048 break;
7050 default:
7051 break;
7054 return ok;
7057 /* Write out the value fields of node T. */
7059 void
7060 trees_out::tree_node_vals (tree t)
7062 core_vals (t);
7063 lang_vals (t);
7066 bool
7067 trees_in::tree_node_vals (tree t)
7069 bool ok = core_vals (t);
7070 if (ok)
7071 ok = lang_vals (t);
7073 return ok;
7077 /* If T is a back reference, fixed reference or NULL, write out it's
7078 code and return WK_none. Otherwise return WK_value if we must write
7079 by value, or WK_normal otherwise. */
7081 walk_kind
7082 trees_out::ref_node (tree t)
7084 if (!t)
7086 if (streaming_p ())
7088 /* NULL_TREE -> tt_null. */
7089 null_count++;
7090 i (tt_null);
7092 return WK_none;
7095 if (!TREE_VISITED (t))
7096 return WK_normal;
7098 /* An already-visited tree. It must be in the map. */
7099 int val = get_tag (t);
7101 if (val == tag_value)
7102 /* An entry we should walk into. */
7103 return WK_value;
7105 const char *kind;
7107 if (val <= tag_backref)
7109 /* Back reference -> -ve number */
7110 if (streaming_p ())
7111 i (val);
7112 kind = "backref";
7114 else if (val >= tag_fixed)
7116 /* Fixed reference -> tt_fixed */
7117 val -= tag_fixed;
7118 if (streaming_p ())
7119 i (tt_fixed), u (val);
7120 kind = "fixed";
7123 if (streaming_p ())
7125 back_ref_count++;
7126 dump (dumper::TREE)
7127 && dump ("Wrote %s:%d %C:%N%S", kind, val, TREE_CODE (t), t, t);
7129 return WK_none;
7132 tree
7133 trees_in::back_ref (int tag)
7135 tree res = NULL_TREE;
7137 if (tag < 0 && unsigned (~tag) < back_refs.length ())
7138 res = back_refs[~tag];
7140 if (!res
7141 /* Checking TREE_CODE is a dereference, so we know this is not a
7142 wild pointer. Checking the code provides evidence we've not
7143 corrupted something. */
7144 || TREE_CODE (res) >= MAX_TREE_CODES)
7145 set_overrun ();
7146 else
7147 dump (dumper::TREE) && dump ("Read backref:%d found %C:%N%S", tag,
7148 TREE_CODE (res), res, res);
7149 return res;
7152 unsigned
7153 trees_out::add_indirect_tpl_parms (tree parms)
7155 unsigned len = 0;
7156 for (; parms; parms = TREE_CHAIN (parms), len++)
7158 if (TREE_VISITED (parms))
7159 break;
7161 int tag = insert (parms);
7162 if (streaming_p ())
7163 dump (dumper::TREE)
7164 && dump ("Indirect:%d template's parameter %u %C:%N",
7165 tag, len, TREE_CODE (parms), parms);
7168 if (streaming_p ())
7169 u (len);
7171 return len;
7174 unsigned
7175 trees_in::add_indirect_tpl_parms (tree parms)
7177 unsigned len = u ();
7178 for (unsigned ix = 0; ix != len; parms = TREE_CHAIN (parms), ix++)
7180 int tag = insert (parms);
7181 dump (dumper::TREE)
7182 && dump ("Indirect:%d template's parameter %u %C:%N",
7183 tag, ix, TREE_CODE (parms), parms);
7186 return len;
7189 /* We've just found DECL by name. Insert nodes that come with it, but
7190 cannot be found by name, so we'll not accidentally walk into them. */
7192 void
7193 trees_out::add_indirects (tree decl)
7195 unsigned count = 0;
7197 // FIXME:OPTIMIZATION We'll eventually want default fn parms of
7198 // templates and perhaps default template parms too. The former can
7199 // be referenced from instantiations (as they are lazily
7200 // instantiated). Also (deferred?) exception specifications of
7201 // templates. See the note about PARM_DECLs in trees_out::decl_node.
7202 tree inner = decl;
7203 if (TREE_CODE (decl) == TEMPLATE_DECL)
7205 count += add_indirect_tpl_parms (DECL_TEMPLATE_PARMS (decl));
7207 inner = DECL_TEMPLATE_RESULT (decl);
7208 int tag = insert (inner);
7209 if (streaming_p ())
7210 dump (dumper::TREE)
7211 && dump ("Indirect:%d template's result %C:%N",
7212 tag, TREE_CODE (inner), inner);
7213 count++;
7216 if (TREE_CODE (inner) == TYPE_DECL)
7218 /* Make sure the type is in the map too. Otherwise we get
7219 different RECORD_TYPEs for the same type, and things go
7220 south. */
7221 tree type = TREE_TYPE (inner);
7222 gcc_checking_assert (DECL_ORIGINAL_TYPE (inner)
7223 || TYPE_NAME (type) == inner);
7224 int tag = insert (type);
7225 if (streaming_p ())
7226 dump (dumper::TREE) && dump ("Indirect:%d decl's type %C:%N", tag,
7227 TREE_CODE (type), type);
7228 count++;
7231 if (streaming_p ())
7233 u (count);
7234 dump (dumper::TREE) && dump ("Inserted %u indirects", count);
7238 bool
7239 trees_in::add_indirects (tree decl)
7241 unsigned count = 0;
7243 tree inner = decl;
7244 if (TREE_CODE (inner) == TEMPLATE_DECL)
7246 count += add_indirect_tpl_parms (DECL_TEMPLATE_PARMS (decl));
7248 inner = DECL_TEMPLATE_RESULT (decl);
7249 int tag = insert (inner);
7250 dump (dumper::TREE)
7251 && dump ("Indirect:%d templates's result %C:%N", tag,
7252 TREE_CODE (inner), inner);
7253 count++;
7256 if (TREE_CODE (inner) == TYPE_DECL)
7258 tree type = TREE_TYPE (inner);
7259 gcc_checking_assert (DECL_ORIGINAL_TYPE (inner)
7260 || TYPE_NAME (type) == inner);
7261 int tag = insert (type);
7262 dump (dumper::TREE)
7263 && dump ("Indirect:%d decl's type %C:%N", tag, TREE_CODE (type), type);
7264 count++;
7267 dump (dumper::TREE) && dump ("Inserted %u indirects", count);
7268 return count == u ();
7271 /* Stream a template parameter. There are 4.5 kinds of parameter:
7272 a) Template - TEMPLATE_DECL->TYPE_DECL->TEMPLATE_TEMPLATE_PARM
7273 TEMPLATE_TYPE_PARM_INDEX TPI
7274 b) Type - TYPE_DECL->TEMPLATE_TYPE_PARM TEMPLATE_TYPE_PARM_INDEX TPI
7275 c.1) NonTYPE - PARM_DECL DECL_INITIAL TPI We meet this first
7276 c.2) NonTYPE - CONST_DECL DECL_INITIAL Same TPI
7277 d) BoundTemplate - TYPE_DECL->BOUND_TEMPLATE_TEMPLATE_PARM
7278 TEMPLATE_TYPE_PARM_INDEX->TPI
7279 TEMPLATE_TEMPLATE_PARM_INFO->TEMPLATE_INFO
7281 All of these point to a TEMPLATE_PARM_INDEX, and #B also has a TEMPLATE_INFO
7284 void
7285 trees_out::tpl_parm_value (tree parm)
7287 gcc_checking_assert (DECL_P (parm) && DECL_TEMPLATE_PARM_P (parm));
7289 int parm_tag = insert (parm);
7290 if (streaming_p ())
7292 i (tt_tpl_parm);
7293 dump (dumper::TREE) && dump ("Writing template parm:%d %C:%N",
7294 parm_tag, TREE_CODE (parm), parm);
7295 start (parm);
7296 tree_node_bools (parm);
7299 tree inner = parm;
7300 if (TREE_CODE (inner) == TEMPLATE_DECL)
7302 inner = DECL_TEMPLATE_RESULT (inner);
7303 int inner_tag = insert (inner);
7304 if (streaming_p ())
7306 dump (dumper::TREE) && dump ("Writing inner template parm:%d %C:%N",
7307 inner_tag, TREE_CODE (inner), inner);
7308 start (inner);
7309 tree_node_bools (inner);
7313 tree type = NULL_TREE;
7314 if (TREE_CODE (inner) == TYPE_DECL)
7316 type = TREE_TYPE (inner);
7317 int type_tag = insert (type);
7318 if (streaming_p ())
7320 dump (dumper::TREE) && dump ("Writing template parm type:%d %C:%N",
7321 type_tag, TREE_CODE (type), type);
7322 start (type);
7323 tree_node_bools (type);
7327 if (inner != parm)
7329 /* This is a template-template parameter. */
7330 unsigned tpl_levels = 0;
7331 tpl_header (parm, &tpl_levels);
7332 tpl_parms_fini (parm, tpl_levels);
7335 tree_node_vals (parm);
7336 if (inner != parm)
7337 tree_node_vals (inner);
7338 if (type)
7340 tree_node_vals (type);
7341 if (DECL_NAME (inner) == auto_identifier
7342 || DECL_NAME (inner) == decltype_auto_identifier)
7344 /* Placeholder auto. */
7345 tree_node (DECL_INITIAL (inner));
7346 tree_node (DECL_SIZE_UNIT (inner));
7350 if (streaming_p ())
7351 dump (dumper::TREE) && dump ("Wrote template parm:%d %C:%N",
7352 parm_tag, TREE_CODE (parm), parm);
7355 tree
7356 trees_in::tpl_parm_value ()
7358 tree parm = start ();
7359 if (!parm || !tree_node_bools (parm))
7360 return NULL_TREE;
7362 int parm_tag = insert (parm);
7363 dump (dumper::TREE) && dump ("Reading template parm:%d %C:%N",
7364 parm_tag, TREE_CODE (parm), parm);
7366 tree inner = parm;
7367 if (TREE_CODE (inner) == TEMPLATE_DECL)
7369 inner = start ();
7370 if (!inner || !tree_node_bools (inner))
7371 return NULL_TREE;
7372 int inner_tag = insert (inner);
7373 dump (dumper::TREE) && dump ("Reading inner template parm:%d %C:%N",
7374 inner_tag, TREE_CODE (inner), inner);
7375 DECL_TEMPLATE_RESULT (parm) = inner;
7378 tree type = NULL_TREE;
7379 if (TREE_CODE (inner) == TYPE_DECL)
7381 type = start ();
7382 if (!type || !tree_node_bools (type))
7383 return NULL_TREE;
7384 int type_tag = insert (type);
7385 dump (dumper::TREE) && dump ("Reading template parm type:%d %C:%N",
7386 type_tag, TREE_CODE (type), type);
7388 TREE_TYPE (inner) = TREE_TYPE (parm) = type;
7389 TYPE_NAME (type) = parm;
7392 if (inner != parm)
7394 /* A template template parameter. */
7395 unsigned tpl_levels = 0;
7396 tpl_header (parm, &tpl_levels);
7397 tpl_parms_fini (parm, tpl_levels);
7400 tree_node_vals (parm);
7401 if (inner != parm)
7402 tree_node_vals (inner);
7403 if (type)
7405 tree_node_vals (type);
7406 if (DECL_NAME (inner) == auto_identifier
7407 || DECL_NAME (inner) == decltype_auto_identifier)
7409 /* Placeholder auto. */
7410 DECL_INITIAL (inner) = tree_node ();
7411 DECL_SIZE_UNIT (inner) = tree_node ();
7413 if (TYPE_CANONICAL (type))
7415 gcc_checking_assert (TYPE_CANONICAL (type) == type);
7416 TYPE_CANONICAL (type) = canonical_type_parameter (type);
7420 dump (dumper::TREE) && dump ("Read template parm:%d %C:%N",
7421 parm_tag, TREE_CODE (parm), parm);
7423 return parm;
7426 void
7427 trees_out::install_entity (tree decl, depset *dep)
7429 gcc_checking_assert (streaming_p ());
7431 /* Write the entity index, so we can insert it as soon as we
7432 know this is new. */
7433 u (dep ? dep->cluster + 1 : 0);
7434 if (CHECKING_P && dep)
7436 /* Add it to the entity map, such that we can tell it is
7437 part of us. */
7438 bool existed;
7439 unsigned *slot = &entity_map->get_or_insert
7440 (DECL_UID (decl), &existed);
7441 if (existed)
7442 /* If it existed, it should match. */
7443 gcc_checking_assert (decl == (*entity_ary)[*slot]);
7444 *slot = ~dep->cluster;
7448 bool
7449 trees_in::install_entity (tree decl)
7451 unsigned entity_index = u ();
7452 if (!entity_index)
7453 return false;
7455 if (entity_index > state->entity_num)
7457 set_overrun ();
7458 return false;
7461 /* Insert the real decl into the entity ary. */
7462 unsigned ident = state->entity_lwm + entity_index - 1;
7463 (*entity_ary)[ident] = decl;
7465 /* And into the entity map, if it's not already there. */
7466 tree not_tmpl = STRIP_TEMPLATE (decl);
7467 if (!DECL_LANG_SPECIFIC (not_tmpl)
7468 || !DECL_MODULE_ENTITY_P (not_tmpl))
7470 retrofit_lang_decl (not_tmpl);
7471 DECL_MODULE_ENTITY_P (not_tmpl) = true;
7473 /* Insert into the entity hash (it cannot already be there). */
7474 bool existed;
7475 unsigned &slot = entity_map->get_or_insert (DECL_UID (decl), &existed);
7476 gcc_checking_assert (!existed);
7477 slot = ident;
7480 return true;
7483 static bool has_definition (tree decl);
7485 /* DECL is a decl node that must be written by value. DEP is the
7486 decl's depset. */
7488 void
7489 trees_out::decl_value (tree decl, depset *dep)
7491 /* We should not be writing clones or template parms. */
7492 gcc_checking_assert (DECL_P (decl)
7493 && !DECL_CLONED_FUNCTION_P (decl)
7494 && !DECL_TEMPLATE_PARM_P (decl));
7496 /* We should never be writing non-typedef ptrmemfuncs by value. */
7497 gcc_checking_assert (TREE_CODE (decl) != TYPE_DECL
7498 || DECL_ORIGINAL_TYPE (decl)
7499 || !TYPE_PTRMEMFUNC_P (TREE_TYPE (decl)));
7501 merge_kind mk = get_merge_kind (decl, dep);
7503 if (CHECKING_P)
7505 /* Never start in the middle of a template. */
7506 int use_tpl = -1;
7507 if (tree ti = node_template_info (decl, use_tpl))
7508 gcc_checking_assert (TREE_CODE (TI_TEMPLATE (ti)) == OVERLOAD
7509 || TREE_CODE (TI_TEMPLATE (ti)) == FIELD_DECL
7510 || (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti))
7511 != decl));
7514 if (streaming_p ())
7516 /* A new node -> tt_decl. */
7517 decl_val_count++;
7518 i (tt_decl);
7519 u (mk);
7520 start (decl);
7522 if (mk != MK_unique)
7524 if (!(mk & MK_template_mask) && !state->is_header ())
7526 /* Tell the importer whether this is a global module entity,
7527 or a module entity. This bool merges into the next block
7528 of bools. Sneaky. */
7529 tree o = get_originating_module_decl (decl);
7530 bool is_mod = false;
7532 tree not_tmpl = STRIP_TEMPLATE (o);
7533 if (DECL_LANG_SPECIFIC (not_tmpl)
7534 && DECL_MODULE_PURVIEW_P (not_tmpl))
7535 is_mod = true;
7537 b (is_mod);
7539 b (dep && dep->has_defn ());
7541 tree_node_bools (decl);
7544 int tag = insert (decl, WK_value);
7545 if (streaming_p ())
7546 dump (dumper::TREE)
7547 && dump ("Writing %s:%d %C:%N%S", merge_kind_name[mk], tag,
7548 TREE_CODE (decl), decl, decl);
7550 tree inner = decl;
7551 int inner_tag = 0;
7552 if (TREE_CODE (decl) == TEMPLATE_DECL)
7554 inner = DECL_TEMPLATE_RESULT (decl);
7555 inner_tag = insert (inner, WK_value);
7557 if (streaming_p ())
7559 int code = TREE_CODE (inner);
7560 u (code);
7561 start (inner, true);
7562 tree_node_bools (inner);
7563 dump (dumper::TREE)
7564 && dump ("Writing %s:%d %C:%N%S", merge_kind_name[mk], inner_tag,
7565 TREE_CODE (inner), inner, inner);
7569 tree type = NULL_TREE;
7570 int type_tag = 0;
7571 tree stub_decl = NULL_TREE;
7572 int stub_tag = 0;
7573 if (TREE_CODE (inner) == TYPE_DECL)
7575 type = TREE_TYPE (inner);
7576 bool has_type = (type == TYPE_MAIN_VARIANT (type)
7577 && TYPE_NAME (type) == inner);
7579 if (streaming_p ())
7580 u (has_type ? TREE_CODE (type) : 0);
7582 if (has_type)
7584 type_tag = insert (type, WK_value);
7585 if (streaming_p ())
7587 start (type, true);
7588 tree_node_bools (type);
7589 dump (dumper::TREE)
7590 && dump ("Writing type:%d %C:%N", type_tag,
7591 TREE_CODE (type), type);
7594 stub_decl = TYPE_STUB_DECL (type);
7595 bool has_stub = inner != stub_decl;
7596 if (streaming_p ())
7597 u (has_stub ? TREE_CODE (stub_decl) : 0);
7598 if (has_stub)
7600 stub_tag = insert (stub_decl);
7601 if (streaming_p ())
7603 start (stub_decl, true);
7604 tree_node_bools (stub_decl);
7605 dump (dumper::TREE)
7606 && dump ("Writing stub_decl:%d %C:%N", stub_tag,
7607 TREE_CODE (stub_decl), stub_decl);
7610 else
7611 stub_decl = NULL_TREE;
7613 else
7614 /* Regular typedef. */
7615 type = NULL_TREE;
7618 /* Stream the container, we want it correctly canonicalized before
7619 we start emitting keys for this decl. */
7620 tree container = decl_container (decl);
7622 unsigned tpl_levels = 0;
7623 if (decl != inner)
7624 tpl_header (decl, &tpl_levels);
7625 if (TREE_CODE (inner) == FUNCTION_DECL)
7626 fn_parms_init (inner);
7628 /* Now write out the merging information, and then really
7629 install the tag values. */
7630 key_mergeable (tag, mk, decl, inner, container, dep);
7632 if (streaming_p ())
7633 dump (dumper::MERGE)
7634 && dump ("Wrote:%d's %s merge key %C:%N", tag,
7635 merge_kind_name[mk], TREE_CODE (decl), decl);
7637 if (TREE_CODE (inner) == FUNCTION_DECL)
7638 fn_parms_fini (inner);
7640 if (!is_key_order ())
7641 tree_node_vals (decl);
7643 if (inner_tag)
7645 if (!is_key_order ())
7646 tree_node_vals (inner);
7647 tpl_parms_fini (decl, tpl_levels);
7650 if (type && !is_key_order ())
7652 tree_node_vals (type);
7653 if (stub_decl)
7654 tree_node_vals (stub_decl);
7657 if (!is_key_order ())
7659 if (mk & MK_template_mask
7660 || mk == MK_partial
7661 || mk == MK_friend_spec)
7663 if (mk != MK_partial)
7665 // FIXME: We should make use of the merge-key by
7666 // exposing it outside of key_mergeable. But this gets
7667 // the job done.
7668 auto *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
7670 if (streaming_p ())
7671 u (get_mergeable_specialization_flags (entry->tmpl, decl));
7672 tree_node (entry->tmpl);
7673 tree_node (entry->args);
7675 else
7677 tree_node (CLASSTYPE_TI_TEMPLATE (TREE_TYPE (inner)));
7678 tree_node (CLASSTYPE_TI_ARGS (TREE_TYPE (inner)));
7681 tree_node (get_constraints (decl));
7684 if (streaming_p ())
7686 /* Do not stray outside this section. */
7687 gcc_checking_assert (!dep || dep->section == dep_hash->section);
7689 /* Write the entity index, so we can insert it as soon as we
7690 know this is new. */
7691 install_entity (decl, dep);
7694 if (VAR_OR_FUNCTION_DECL_P (inner)
7695 && DECL_LANG_SPECIFIC (inner)
7696 && DECL_MODULE_ATTACHMENTS_P (inner)
7697 && !is_key_order ())
7699 /* Stream the attached entities. */
7700 auto *attach_vec = attached_table->get (inner);
7701 unsigned num = attach_vec->length ();
7702 if (streaming_p ())
7703 u (num);
7704 for (unsigned ix = 0; ix != num; ix++)
7706 tree attached = (*attach_vec)[ix];
7707 tree_node (attached);
7708 if (streaming_p ())
7709 dump (dumper::MERGE)
7710 && dump ("Written %d[%u] attached decl %N", tag, ix, attached);
7714 bool is_typedef = false;
7715 if (!type && TREE_CODE (inner) == TYPE_DECL)
7717 tree t = TREE_TYPE (inner);
7718 unsigned tdef_flags = 0;
7719 if (DECL_ORIGINAL_TYPE (inner)
7720 && TYPE_NAME (TREE_TYPE (inner)) == inner)
7722 tdef_flags |= 1;
7723 if (TYPE_STRUCTURAL_EQUALITY_P (t)
7724 && TYPE_DEPENDENT_P_VALID (t)
7725 && TYPE_DEPENDENT_P (t))
7726 tdef_flags |= 2;
7728 if (streaming_p ())
7729 u (tdef_flags);
7731 if (tdef_flags & 1)
7733 /* A typedef type. */
7734 int type_tag = insert (t);
7735 if (streaming_p ())
7736 dump (dumper::TREE)
7737 && dump ("Cloned:%d %s %C:%N", type_tag,
7738 tdef_flags & 2 ? "depalias" : "typedef",
7739 TREE_CODE (t), t);
7741 is_typedef = true;
7745 if (streaming_p () && DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
7747 bool cloned_p
7748 = (DECL_CHAIN (decl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
7749 bool needs_vtt_parm_p
7750 = (cloned_p && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (decl)));
7751 bool omit_inherited_parms_p
7752 = (cloned_p && DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)
7753 && base_ctor_omit_inherited_parms (decl));
7754 unsigned flags = (int (cloned_p) << 0
7755 | int (needs_vtt_parm_p) << 1
7756 | int (omit_inherited_parms_p) << 2);
7757 u (flags);
7758 dump (dumper::TREE) && dump ("CDTOR %N is %scloned",
7759 decl, cloned_p ? "" : "not ");
7762 if (streaming_p ())
7763 dump (dumper::TREE) && dump ("Written decl:%d %C:%N", tag,
7764 TREE_CODE (decl), decl);
7766 if (NAMESPACE_SCOPE_P (inner))
7767 gcc_checking_assert (!dep == (VAR_OR_FUNCTION_DECL_P (inner)
7768 && DECL_LOCAL_DECL_P (inner)));
7769 else if ((TREE_CODE (inner) == TYPE_DECL
7770 && !is_typedef
7771 && TYPE_NAME (TREE_TYPE (inner)) == inner)
7772 || TREE_CODE (inner) == FUNCTION_DECL)
7774 bool write_defn = !dep && has_definition (decl);
7775 if (streaming_p ())
7776 u (write_defn);
7777 if (write_defn)
7778 write_definition (decl);
7782 tree
7783 trees_in::decl_value ()
7785 int tag = 0;
7786 bool is_mod = false;
7787 bool has_defn = false;
7788 unsigned mk_u = u ();
7789 if (mk_u >= MK_hwm || !merge_kind_name[mk_u])
7791 set_overrun ();
7792 return NULL_TREE;
7795 unsigned saved_unused = unused;
7796 unused = 0;
7798 merge_kind mk = merge_kind (mk_u);
7800 tree decl = start ();
7801 if (decl)
7803 if (mk != MK_unique)
7805 if (!(mk & MK_template_mask) && !state->is_header ())
7806 /* See note in trees_out about where this bool is sequenced. */
7807 is_mod = b ();
7809 has_defn = b ();
7812 if (!tree_node_bools (decl))
7813 decl = NULL_TREE;
7816 /* Insert into map. */
7817 tag = insert (decl);
7818 if (decl)
7819 dump (dumper::TREE)
7820 && dump ("Reading:%d %C", tag, TREE_CODE (decl));
7822 tree inner = decl;
7823 int inner_tag = 0;
7824 if (decl && TREE_CODE (decl) == TEMPLATE_DECL)
7826 int code = u ();
7827 inner = start (code);
7828 if (inner && tree_node_bools (inner))
7829 DECL_TEMPLATE_RESULT (decl) = inner;
7830 else
7831 decl = NULL_TREE;
7833 inner_tag = insert (inner);
7834 if (decl)
7835 dump (dumper::TREE)
7836 && dump ("Reading:%d %C", inner_tag, TREE_CODE (inner));
7839 tree type = NULL_TREE;
7840 int type_tag = 0;
7841 tree stub_decl = NULL_TREE;
7842 int stub_tag = 0;
7843 if (decl && TREE_CODE (inner) == TYPE_DECL)
7845 if (unsigned type_code = u ())
7847 type = start (type_code);
7848 if (type && tree_node_bools (type))
7850 TREE_TYPE (inner) = type;
7851 TYPE_NAME (type) = inner;
7853 else
7854 decl = NULL_TREE;
7856 type_tag = insert (type);
7857 if (decl)
7858 dump (dumper::TREE)
7859 && dump ("Reading type:%d %C", type_tag, TREE_CODE (type));
7861 if (unsigned stub_code = u ())
7863 stub_decl = start (stub_code);
7864 if (stub_decl && tree_node_bools (stub_decl))
7866 TREE_TYPE (stub_decl) = type;
7867 TYPE_STUB_DECL (type) = stub_decl;
7869 else
7870 decl = NULL_TREE;
7872 stub_tag = insert (stub_decl);
7873 if (decl)
7874 dump (dumper::TREE)
7875 && dump ("Reading stub_decl:%d %C", stub_tag,
7876 TREE_CODE (stub_decl));
7881 if (!decl)
7883 bail:
7884 if (inner_tag != 0)
7885 back_refs[~inner_tag] = NULL_TREE;
7886 if (type_tag != 0)
7887 back_refs[~type_tag] = NULL_TREE;
7888 if (stub_tag != 0)
7889 back_refs[~stub_tag] = NULL_TREE;
7890 if (tag != 0)
7891 back_refs[~tag] = NULL_TREE;
7892 set_overrun ();
7893 /* Bail. */
7894 unused = saved_unused;
7895 return NULL_TREE;
7898 /* Read the container, to ensure it's already been streamed in. */
7899 tree container = decl_container ();
7900 unsigned tpl_levels = 0;
7902 /* Figure out if this decl is already known about. */
7903 int parm_tag = 0;
7905 if (decl != inner)
7906 if (!tpl_header (decl, &tpl_levels))
7907 goto bail;
7908 if (TREE_CODE (inner) == FUNCTION_DECL)
7909 parm_tag = fn_parms_init (inner);
7911 tree existing = key_mergeable (tag, mk, decl, inner, type, container, is_mod);
7912 tree existing_inner = existing;
7913 if (existing)
7915 if (existing == error_mark_node)
7916 goto bail;
7918 if (TREE_CODE (STRIP_TEMPLATE (existing)) == TYPE_DECL)
7920 tree etype = TREE_TYPE (existing);
7921 if (TYPE_LANG_SPECIFIC (etype)
7922 && COMPLETE_TYPE_P (etype)
7923 && !CLASSTYPE_MEMBER_VEC (etype))
7924 /* Give it a member vec, we're likely gonna be looking
7925 inside it. */
7926 set_class_bindings (etype, -1);
7929 /* Install the existing decl into the back ref array. */
7930 register_duplicate (decl, existing);
7931 back_refs[~tag] = existing;
7932 if (inner_tag != 0)
7934 existing_inner = DECL_TEMPLATE_RESULT (existing);
7935 back_refs[~inner_tag] = existing_inner;
7938 if (type_tag != 0)
7940 tree existing_type = TREE_TYPE (existing);
7941 back_refs[~type_tag] = existing_type;
7942 if (stub_tag != 0)
7943 back_refs[~stub_tag] = TYPE_STUB_DECL (existing_type);
7947 if (parm_tag)
7948 fn_parms_fini (parm_tag, inner, existing_inner, has_defn);
7950 if (!tree_node_vals (decl))
7951 goto bail;
7953 if (inner_tag)
7955 gcc_checking_assert (DECL_TEMPLATE_RESULT (decl) == inner);
7957 if (!tree_node_vals (inner))
7958 goto bail;
7960 if (!tpl_parms_fini (decl, tpl_levels))
7961 goto bail;
7964 if (type && (!tree_node_vals (type)
7965 || (stub_decl && !tree_node_vals (stub_decl))))
7966 goto bail;
7968 spec_entry spec;
7969 unsigned spec_flags = 0;
7970 if (mk & MK_template_mask
7971 || mk == MK_partial
7972 || mk == MK_friend_spec)
7974 if (mk == MK_partial)
7975 spec_flags = 2;
7976 else
7977 spec_flags = u ();
7979 spec.tmpl = tree_node ();
7980 spec.args = tree_node ();
7982 /* Hold constraints on the spec field, for a short while. */
7983 spec.spec = tree_node ();
7985 dump (dumper::TREE) && dump ("Read:%d %C:%N", tag, TREE_CODE (decl), decl);
7987 existing = back_refs[~tag];
7988 bool installed = install_entity (existing);
7989 bool is_new = existing == decl;
7991 if (VAR_OR_FUNCTION_DECL_P (inner)
7992 && DECL_LANG_SPECIFIC (inner)
7993 && DECL_MODULE_ATTACHMENTS_P (inner))
7995 /* Read and maybe install the attached entities. */
7996 bool existed;
7997 auto &set = attached_table->get_or_insert (STRIP_TEMPLATE (existing),
7998 &existed);
7999 unsigned num = u ();
8000 if (is_new == existed)
8001 set_overrun ();
8002 if (is_new)
8003 set.reserve (num);
8004 for (unsigned ix = 0; !get_overrun () && ix != num; ix++)
8006 tree attached = tree_node ();
8007 dump (dumper::MERGE)
8008 && dump ("Read %d[%u] %s attached decl %N", tag, ix,
8009 is_new ? "new" : "matched", attached);
8010 if (is_new)
8011 set.quick_push (attached);
8012 else if (set[ix] != attached)
8013 set_overrun ();
8017 /* Regular typedefs will have a NULL TREE_TYPE at this point. */
8018 unsigned tdef_flags = 0;
8019 bool is_typedef = false;
8020 if (!type && TREE_CODE (inner) == TYPE_DECL)
8022 tdef_flags = u ();
8023 if (tdef_flags & 1)
8024 is_typedef = true;
8027 if (is_new)
8029 /* A newly discovered node. */
8030 if (TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))
8031 /* Mark this identifier as naming a virtual function --
8032 lookup_overrides relies on this optimization. */
8033 IDENTIFIER_VIRTUAL_P (DECL_NAME (decl)) = true;
8035 if (installed)
8037 /* Mark the entity as imported. */
8038 retrofit_lang_decl (inner);
8039 DECL_MODULE_IMPORT_P (inner) = true;
8042 if (spec.spec)
8043 set_constraints (decl, spec.spec);
8045 if (TREE_CODE (decl) == INTEGER_CST && !TREE_OVERFLOW (decl))
8047 decl = cache_integer_cst (decl, true);
8048 back_refs[~tag] = decl;
8051 if (is_typedef)
8053 /* Frob it to be ready for cloning. */
8054 TREE_TYPE (inner) = DECL_ORIGINAL_TYPE (inner);
8055 DECL_ORIGINAL_TYPE (inner) = NULL_TREE;
8056 set_underlying_type (inner);
8057 if (tdef_flags & 2)
8059 /* Match instantiate_alias_template's handling. */
8060 tree type = TREE_TYPE (inner);
8061 TYPE_DEPENDENT_P (type) = true;
8062 TYPE_DEPENDENT_P_VALID (type) = true;
8063 SET_TYPE_STRUCTURAL_EQUALITY (type);
8067 if (inner_tag)
8068 /* Set the TEMPLATE_DECL's type. */
8069 TREE_TYPE (decl) = TREE_TYPE (inner);
8071 if (mk & MK_template_mask
8072 || mk == MK_partial)
8074 /* Add to specialization tables now that constraints etc are
8075 added. */
8076 bool is_type = mk == MK_partial || !(mk & MK_tmpl_decl_mask);
8078 spec.spec = is_type ? type : mk & MK_tmpl_tmpl_mask ? inner : decl;
8079 add_mergeable_specialization (!is_type,
8080 !is_type && mk & MK_tmpl_alias_mask,
8081 &spec, decl, spec_flags);
8084 if (NAMESPACE_SCOPE_P (decl)
8085 && (mk == MK_named || mk == MK_unique
8086 || mk == MK_enum || mk == MK_friend_spec)
8087 && !(VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl)))
8088 add_module_namespace_decl (CP_DECL_CONTEXT (decl), decl);
8090 if (DECL_ARTIFICIAL (decl)
8091 && TREE_CODE (decl) == FUNCTION_DECL
8092 && !DECL_TEMPLATE_INFO (decl)
8093 && DECL_CONTEXT (decl) && TYPE_P (DECL_CONTEXT (decl))
8094 && TYPE_SIZE (DECL_CONTEXT (decl))
8095 && !DECL_THUNK_P (decl))
8096 /* A new implicit member function, when the class is
8097 complete. This means the importee declared it, and
8098 we must now add it to the class. Note that implicit
8099 member fns of template instantiations do not themselves
8100 look like templates. */
8101 if (!install_implicit_member (inner))
8102 set_overrun ();
8104 else
8106 /* DECL is the to-be-discarded decl. Its internal pointers will
8107 be to the EXISTING's structure. Frob it to point to its
8108 own other structures, so loading its definition will alter
8109 it, and not the existing decl. */
8110 dump (dumper::MERGE) && dump ("Deduping %N", existing);
8112 if (inner_tag)
8113 DECL_TEMPLATE_RESULT (decl) = inner;
8115 if (type)
8117 /* Point at the to-be-discarded type & decl. */
8118 TYPE_NAME (type) = inner;
8119 TREE_TYPE (inner) = type;
8121 TYPE_STUB_DECL (type) = stub_decl ? stub_decl : inner;
8122 if (stub_decl)
8123 TREE_TYPE (stub_decl) = type;
8126 if (inner_tag)
8127 /* Set the TEMPLATE_DECL's type. */
8128 TREE_TYPE (decl) = TREE_TYPE (inner);
8130 if (!is_matching_decl (existing, decl, is_typedef))
8131 unmatched_duplicate (existing);
8133 if (TREE_CODE (inner) == FUNCTION_DECL)
8135 tree e_inner = STRIP_TEMPLATE (existing);
8136 for (auto parm = DECL_ARGUMENTS (inner);
8137 parm; parm = DECL_CHAIN (parm))
8138 DECL_CONTEXT (parm) = e_inner;
8141 /* And our result is the existing node. */
8142 decl = existing;
8145 if (mk == MK_friend_spec)
8147 tree e = match_mergeable_specialization (true, &spec);
8148 if (!e)
8150 spec.spec = inner;
8151 add_mergeable_specialization (true, false, &spec, decl, spec_flags);
8153 else if (e != existing)
8154 set_overrun ();
8157 if (is_typedef)
8159 /* Insert the type into the array now. */
8160 tag = insert (TREE_TYPE (decl));
8161 dump (dumper::TREE)
8162 && dump ("Cloned:%d typedef %C:%N",
8163 tag, TREE_CODE (TREE_TYPE (decl)), TREE_TYPE (decl));
8166 unused = saved_unused;
8168 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
8170 unsigned flags = u ();
8172 if (is_new)
8174 bool cloned_p = flags & 1;
8175 dump (dumper::TREE) && dump ("CDTOR %N is %scloned",
8176 decl, cloned_p ? "" : "not ");
8177 if (cloned_p)
8178 build_cdtor_clones (decl, flags & 2, flags & 4,
8179 /* Update the member vec, if there is
8180 one (we're in a different cluster
8181 to the class defn). */
8182 CLASSTYPE_MEMBER_VEC (DECL_CONTEXT (decl)));
8186 if (!NAMESPACE_SCOPE_P (inner)
8187 && ((TREE_CODE (inner) == TYPE_DECL
8188 && !is_typedef
8189 && TYPE_NAME (TREE_TYPE (inner)) == inner)
8190 || TREE_CODE (inner) == FUNCTION_DECL)
8191 && u ())
8192 read_definition (decl);
8194 return decl;
8197 /* DECL is an unnameable member of CTX. Return a suitable identifying
8198 index. */
8200 static unsigned
8201 get_field_ident (tree ctx, tree decl)
8203 gcc_checking_assert (TREE_CODE (decl) == USING_DECL
8204 || !DECL_NAME (decl)
8205 || IDENTIFIER_ANON_P (DECL_NAME (decl)));
8207 unsigned ix = 0;
8208 for (tree fields = TYPE_FIELDS (ctx);
8209 fields; fields = DECL_CHAIN (fields))
8211 if (fields == decl)
8212 return ix;
8214 if (DECL_CONTEXT (fields) == ctx
8215 && (TREE_CODE (fields) == USING_DECL
8216 || (TREE_CODE (fields) == FIELD_DECL
8217 && (!DECL_NAME (fields)
8218 || IDENTIFIER_ANON_P (DECL_NAME (fields))))))
8219 /* Count this field. */
8220 ix++;
8222 gcc_unreachable ();
8225 static tree
8226 lookup_field_ident (tree ctx, unsigned ix)
8228 for (tree fields = TYPE_FIELDS (ctx);
8229 fields; fields = DECL_CHAIN (fields))
8230 if (DECL_CONTEXT (fields) == ctx
8231 && (TREE_CODE (fields) == USING_DECL
8232 || (TREE_CODE (fields) == FIELD_DECL
8233 && (!DECL_NAME (fields)
8234 || IDENTIFIER_ANON_P (DECL_NAME (fields))))))
8235 if (!ix--)
8236 return fields;
8238 return NULL_TREE;
8241 /* Reference DECL. REF indicates the walk kind we are performing.
8242 Return true if we should write this decl by value. */
8244 bool
8245 trees_out::decl_node (tree decl, walk_kind ref)
8247 gcc_checking_assert (DECL_P (decl) && !DECL_TEMPLATE_PARM_P (decl)
8248 && DECL_CONTEXT (decl));
8250 if (ref == WK_value)
8252 depset *dep = dep_hash->find_dependency (decl);
8253 decl_value (decl, dep);
8254 return false;
8257 switch (TREE_CODE (decl))
8259 default:
8260 break;
8262 case FUNCTION_DECL:
8263 gcc_checking_assert (!DECL_LOCAL_DECL_P (decl));
8264 break;
8266 case RESULT_DECL:
8267 /* Unlike PARM_DECLs, RESULT_DECLs are only generated and
8268 referenced when we're inside the function itself. */
8269 return true;
8271 case PARM_DECL:
8273 if (streaming_p ())
8274 i (tt_parm);
8275 tree_node (DECL_CONTEXT (decl));
8276 if (streaming_p ())
8278 /* That must have put this in the map. */
8279 walk_kind ref = ref_node (decl);
8280 if (ref != WK_none)
8281 // FIXME:OPTIMIZATION We can wander into bits of the
8282 // template this was instantiated from. For instance
8283 // deferred noexcept and default parms. Currently we'll
8284 // end up cloning those bits of tree. It would be nice
8285 // to reference those specific nodes. I think putting
8286 // those things in the map when we reference their
8287 // template by name. See the note in add_indirects.
8288 return true;
8290 dump (dumper::TREE)
8291 && dump ("Wrote %s reference %N",
8292 TREE_CODE (decl) == PARM_DECL ? "parameter" : "result",
8293 decl);
8296 return false;
8298 case IMPORTED_DECL:
8299 /* This describes a USING_DECL to the ME's debug machinery. It
8300 originates from the fortran FE, and has nothing to do with
8301 C++ modules. */
8302 return true;
8304 case LABEL_DECL:
8305 return true;
8307 case CONST_DECL:
8309 /* If I end up cloning enum decls, implementing C++20 using
8310 E::v, this will need tweaking. */
8311 if (streaming_p ())
8312 i (tt_enum_decl);
8313 tree ctx = DECL_CONTEXT (decl);
8314 gcc_checking_assert (TREE_CODE (ctx) == ENUMERAL_TYPE);
8315 tree_node (ctx);
8316 tree_node (DECL_NAME (decl));
8318 int tag = insert (decl);
8319 if (streaming_p ())
8320 dump (dumper::TREE)
8321 && dump ("Wrote enum decl:%d %C:%N", tag, TREE_CODE (decl), decl);
8322 return false;
8324 break;
8326 case USING_DECL:
8327 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
8328 break;
8329 /* FALLTHROUGH */
8331 case FIELD_DECL:
8333 if (streaming_p ())
8334 i (tt_data_member);
8336 tree ctx = DECL_CONTEXT (decl);
8337 tree_node (ctx);
8339 tree name = NULL_TREE;
8341 if (TREE_CODE (decl) == USING_DECL)
8343 else
8345 name = DECL_NAME (decl);
8346 if (name && IDENTIFIER_ANON_P (name))
8347 name = NULL_TREE;
8350 tree_node (name);
8351 if (!name && streaming_p ())
8353 unsigned ix = get_field_ident (ctx, decl);
8354 u (ix);
8357 int tag = insert (decl);
8358 if (streaming_p ())
8359 dump (dumper::TREE)
8360 && dump ("Wrote member:%d %C:%N", tag, TREE_CODE (decl), decl);
8361 return false;
8363 break;
8365 case VAR_DECL:
8366 gcc_checking_assert (!DECL_LOCAL_DECL_P (decl));
8367 if (DECL_VTABLE_OR_VTT_P (decl))
8369 /* VTT or VTABLE, they are all on the vtables list. */
8370 tree ctx = CP_DECL_CONTEXT (decl);
8371 tree vtable = CLASSTYPE_VTABLES (ctx);
8372 for (unsigned ix = 0; ; vtable = DECL_CHAIN (vtable), ix++)
8373 if (vtable == decl)
8375 gcc_checking_assert (DECL_VIRTUAL_P (decl));
8376 if (streaming_p ())
8378 u (tt_vtable);
8379 u (ix);
8380 dump (dumper::TREE)
8381 && dump ("Writing vtable %N[%u]", ctx, ix);
8383 tree_node (ctx);
8384 return false;
8386 gcc_unreachable ();
8389 if (DECL_TINFO_P (decl))
8391 tinfo:
8392 /* A typeinfo, tt_tinfo_typedef or tt_tinfo_var. */
8393 bool is_var = TREE_CODE (decl) == VAR_DECL;
8394 tree type = TREE_TYPE (decl);
8395 unsigned ix = get_pseudo_tinfo_index (type);
8396 if (streaming_p ())
8398 i (is_var ? tt_tinfo_var : tt_tinfo_typedef);
8399 u (ix);
8402 if (is_var)
8404 /* We also need the type it is for and mangled name, so
8405 the reader doesn't need to complete the type (which
8406 would break section ordering). The type it is for is
8407 stashed on the name's TREE_TYPE. */
8408 tree name = DECL_NAME (decl);
8409 tree_node (name);
8410 type = TREE_TYPE (name);
8411 tree_node (type);
8414 int tag = insert (decl);
8415 if (streaming_p ())
8416 dump (dumper::TREE)
8417 && dump ("Wrote tinfo_%s:%d %u %N", is_var ? "var" : "type",
8418 tag, ix, type);
8420 if (!is_var)
8422 tag = insert (type);
8423 if (streaming_p ())
8424 dump (dumper::TREE)
8425 && dump ("Wrote tinfo_type:%d %u %N", tag, ix, type);
8427 return false;
8429 break;
8431 case TYPE_DECL:
8432 if (DECL_TINFO_P (decl))
8433 goto tinfo;
8434 break;
8437 if (DECL_THUNK_P (decl))
8439 /* Thunks are similar to binfos -- write the thunked-to decl and
8440 then thunk-specific key info. */
8441 if (streaming_p ())
8443 i (tt_thunk);
8444 i (THUNK_FIXED_OFFSET (decl));
8447 tree target = decl;
8448 while (DECL_THUNK_P (target))
8449 target = THUNK_TARGET (target);
8450 tree_node (target);
8451 tree_node (THUNK_VIRTUAL_OFFSET (decl));
8452 int tag = insert (decl);
8453 if (streaming_p ())
8454 dump (dumper::TREE)
8455 && dump ("Wrote:%d thunk %N to %N", tag, DECL_NAME (decl), target);
8456 return false;
8459 if (DECL_CLONED_FUNCTION_P (decl))
8461 tree target = get_clone_target (decl);
8462 if (streaming_p ())
8463 i (tt_clone_ref);
8465 tree_node (target);
8466 tree_node (DECL_NAME (decl));
8467 int tag = insert (decl);
8468 if (streaming_p ())
8469 dump (dumper::TREE)
8470 && dump ("Wrote:%d clone %N of %N", tag, DECL_NAME (decl), target);
8471 return false;
8474 /* Everything left should be a thing that is in the entity table.
8475 Mostly things that can be defined outside of their (original
8476 declaration) context. */
8477 gcc_checking_assert (TREE_CODE (decl) == TEMPLATE_DECL
8478 || TREE_CODE (decl) == VAR_DECL
8479 || TREE_CODE (decl) == FUNCTION_DECL
8480 || TREE_CODE (decl) == TYPE_DECL
8481 || TREE_CODE (decl) == USING_DECL
8482 || TREE_CODE (decl) == CONCEPT_DECL
8483 || TREE_CODE (decl) == NAMESPACE_DECL);
8485 int use_tpl = -1;
8486 tree ti = node_template_info (decl, use_tpl);
8487 tree tpl = NULL_TREE;
8489 /* If this is the TEMPLATE_DECL_RESULT of a TEMPLATE_DECL, get the
8490 TEMPLATE_DECL. Note TI_TEMPLATE is not a TEMPLATE_DECL for
8491 (some) friends, so we need to check that. */
8492 // FIXME: Should local friend template specializations be by value?
8493 // They don't get idents so we'll never know they're imported, but I
8494 // think we can only reach them from the TU that defines the
8495 // befriending class?
8496 if (ti && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL
8497 && DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == decl)
8499 tpl = TI_TEMPLATE (ti);
8500 partial_template:
8501 if (streaming_p ())
8503 i (tt_template);
8504 dump (dumper::TREE)
8505 && dump ("Writing implicit template %C:%N%S",
8506 TREE_CODE (tpl), tpl, tpl);
8508 tree_node (tpl);
8510 /* Streaming TPL caused us to visit DECL and maybe its type. */
8511 gcc_checking_assert (TREE_VISITED (decl));
8512 if (DECL_IMPLICIT_TYPEDEF_P (decl))
8513 gcc_checking_assert (TREE_VISITED (TREE_TYPE (decl)));
8514 return false;
8517 tree ctx = CP_DECL_CONTEXT (decl);
8518 depset *dep = NULL;
8519 if (streaming_p ())
8520 dep = dep_hash->find_dependency (decl);
8521 else if (TREE_CODE (ctx) != FUNCTION_DECL
8522 || TREE_CODE (decl) == TEMPLATE_DECL
8523 || (dep_hash->sneakoscope && DECL_IMPLICIT_TYPEDEF_P (decl))
8524 || (DECL_LANG_SPECIFIC (decl)
8525 && DECL_MODULE_IMPORT_P (decl)))
8527 auto kind = (TREE_CODE (decl) == NAMESPACE_DECL
8528 && !DECL_NAMESPACE_ALIAS (decl)
8529 ? depset::EK_NAMESPACE : depset::EK_DECL);
8530 dep = dep_hash->add_dependency (decl, kind);
8533 if (!dep)
8535 /* Some internal entity of context. Do by value. */
8536 decl_value (decl, NULL);
8537 return false;
8540 if (dep->get_entity_kind () == depset::EK_REDIRECT)
8542 /* The DECL_TEMPLATE_RESULT of a partial specialization.
8543 Write the partial specialization's template. */
8544 depset *redirect = dep->deps[0];
8545 gcc_checking_assert (redirect->get_entity_kind () == depset::EK_PARTIAL);
8546 tpl = redirect->get_entity ();
8547 goto partial_template;
8550 if (streaming_p ())
8552 /* Locate the entity. */
8553 unsigned index = dep->cluster;
8554 unsigned import = 0;
8556 if (dep->is_import ())
8557 import = dep->section;
8558 else if (CHECKING_P)
8559 /* It should be what we put there. */
8560 gcc_checking_assert (index == ~import_entity_index (decl));
8562 #if CHECKING_P
8563 gcc_assert (!import || importedness >= 0);
8564 #endif
8565 i (tt_entity);
8566 u (import);
8567 u (index);
8570 int tag = insert (decl);
8571 if (streaming_p () && dump (dumper::TREE))
8573 char const *kind = "import";
8574 module_state *from = (*modules)[0];
8575 if (dep->is_import ())
8576 /* Rediscover the unremapped index. */
8577 from = import_entity_module (import_entity_index (decl));
8578 else
8580 tree o = get_originating_module_decl (decl);
8581 o = STRIP_TEMPLATE (o);
8582 kind = (DECL_LANG_SPECIFIC (o) && DECL_MODULE_PURVIEW_P (o)
8583 ? "purview" : "GMF");
8585 dump ("Wrote %s:%d %C:%N@%M", kind,
8586 tag, TREE_CODE (decl), decl, from);
8589 add_indirects (decl);
8591 return false;
8594 void
8595 trees_out::type_node (tree type)
8597 gcc_assert (TYPE_P (type));
8599 tree root = (TYPE_NAME (type)
8600 ? TREE_TYPE (TYPE_NAME (type)) : TYPE_MAIN_VARIANT (type));
8602 if (type != root)
8604 if (streaming_p ())
8605 i (tt_variant_type);
8606 tree_node (root);
8608 int flags = -1;
8610 if (TREE_CODE (type) == FUNCTION_TYPE
8611 || TREE_CODE (type) == METHOD_TYPE)
8613 int quals = type_memfn_quals (type);
8614 int rquals = type_memfn_rqual (type);
8615 tree raises = TYPE_RAISES_EXCEPTIONS (type);
8616 bool late = TYPE_HAS_LATE_RETURN_TYPE (type);
8618 if (raises != TYPE_RAISES_EXCEPTIONS (root)
8619 || rquals != type_memfn_rqual (root)
8620 || quals != type_memfn_quals (root)
8621 || late != TYPE_HAS_LATE_RETURN_TYPE (root))
8622 flags = rquals | (int (late) << 2) | (quals << 3);
8624 else
8626 if (TYPE_USER_ALIGN (type))
8627 flags = TYPE_ALIGN_RAW (type);
8630 if (streaming_p ())
8631 i (flags);
8633 if (flags < 0)
8635 else if (TREE_CODE (type) == FUNCTION_TYPE
8636 || TREE_CODE (type) == METHOD_TYPE)
8638 tree raises = TYPE_RAISES_EXCEPTIONS (type);
8639 if (raises == TYPE_RAISES_EXCEPTIONS (root))
8640 raises = error_mark_node;
8641 tree_node (raises);
8644 tree_node (TYPE_ATTRIBUTES (type));
8646 if (streaming_p ())
8648 /* Qualifiers. */
8649 int rquals = cp_type_quals (root);
8650 int quals = cp_type_quals (type);
8651 if (quals == rquals)
8652 quals = -1;
8653 i (quals);
8656 if (ref_node (type) != WK_none)
8658 int tag = insert (type);
8659 if (streaming_p ())
8661 i (0);
8662 dump (dumper::TREE)
8663 && dump ("Wrote:%d variant type %C", tag, TREE_CODE (type));
8666 return;
8669 if (tree name = TYPE_NAME (type))
8670 if ((TREE_CODE (name) == TYPE_DECL && DECL_ORIGINAL_TYPE (name))
8671 || DECL_TEMPLATE_PARM_P (name)
8672 || TREE_CODE (type) == RECORD_TYPE
8673 || TREE_CODE (type) == UNION_TYPE
8674 || TREE_CODE (type) == ENUMERAL_TYPE)
8676 /* We can meet template parms that we didn't meet in the
8677 tpl_parms walk, because we're referring to a derived type
8678 that was previously constructed from equivalent template
8679 parms. */
8680 if (streaming_p ())
8682 i (tt_typedef_type);
8683 dump (dumper::TREE)
8684 && dump ("Writing %stypedef %C:%N",
8685 DECL_IMPLICIT_TYPEDEF_P (name) ? "implicit " : "",
8686 TREE_CODE (name), name);
8688 tree_node (name);
8689 if (streaming_p ())
8690 dump (dumper::TREE) && dump ("Wrote typedef %C:%N%S",
8691 TREE_CODE (name), name, name);
8692 gcc_checking_assert (TREE_VISITED (type));
8693 return;
8696 if (TYPE_PTRMEMFUNC_P (type))
8698 /* This is a distinct type node, masquerading as a structure. */
8699 tree fn_type = TYPE_PTRMEMFUNC_FN_TYPE (type);
8700 if (streaming_p ())
8701 i (tt_ptrmem_type);
8702 tree_node (fn_type);
8703 int tag = insert (type);
8704 if (streaming_p ())
8705 dump (dumper::TREE) && dump ("Written:%d ptrmem type", tag);
8706 return;
8709 if (streaming_p ())
8711 u (tt_derived_type);
8712 u (TREE_CODE (type));
8715 tree_node (TREE_TYPE (type));
8716 switch (TREE_CODE (type))
8718 default:
8719 /* We should never meet a type here that is indescribable in
8720 terms of other types. */
8721 gcc_unreachable ();
8723 case ARRAY_TYPE:
8724 tree_node (TYPE_DOMAIN (type));
8725 if (streaming_p ())
8726 /* Dependent arrays are constructed with TYPE_DEPENENT_P
8727 already set. */
8728 u (TYPE_DEPENDENT_P (type));
8729 break;
8731 case COMPLEX_TYPE:
8732 /* No additional data. */
8733 break;
8735 case BOOLEAN_TYPE:
8736 /* A non-standard boolean type. */
8737 if (streaming_p ())
8738 u (TYPE_PRECISION (type));
8739 break;
8741 case INTEGER_TYPE:
8742 if (TREE_TYPE (type))
8744 /* A range type (representing an array domain). */
8745 tree_node (TYPE_MIN_VALUE (type));
8746 tree_node (TYPE_MAX_VALUE (type));
8748 else
8750 /* A new integral type (representing a bitfield). */
8751 if (streaming_p ())
8753 unsigned prec = TYPE_PRECISION (type);
8754 bool unsigned_p = TYPE_UNSIGNED (type);
8756 u ((prec << 1) | unsigned_p);
8759 break;
8761 case METHOD_TYPE:
8762 case FUNCTION_TYPE:
8764 gcc_checking_assert (type_memfn_rqual (type) == REF_QUAL_NONE);
8766 tree arg_types = TYPE_ARG_TYPES (type);
8767 if (TREE_CODE (type) == METHOD_TYPE)
8769 tree_node (TREE_TYPE (TREE_VALUE (arg_types)));
8770 arg_types = TREE_CHAIN (arg_types);
8772 tree_node (arg_types);
8774 break;
8776 case OFFSET_TYPE:
8777 tree_node (TYPE_OFFSET_BASETYPE (type));
8778 break;
8780 case POINTER_TYPE:
8781 /* No additional data. */
8782 break;
8784 case REFERENCE_TYPE:
8785 if (streaming_p ())
8786 u (TYPE_REF_IS_RVALUE (type));
8787 break;
8789 case DECLTYPE_TYPE:
8790 case TYPEOF_TYPE:
8791 case UNDERLYING_TYPE:
8792 tree_node (TYPE_VALUES_RAW (type));
8793 if (TREE_CODE (type) == DECLTYPE_TYPE)
8794 /* We stash a whole bunch of things into decltype's
8795 flags. */
8796 if (streaming_p ())
8797 tree_node_bools (type);
8798 break;
8800 case TYPE_ARGUMENT_PACK:
8801 /* No additional data. */
8802 break;
8804 case TYPE_PACK_EXPANSION:
8805 if (streaming_p ())
8806 u (PACK_EXPANSION_LOCAL_P (type));
8807 tree_node (PACK_EXPANSION_PARAMETER_PACKS (type));
8808 break;
8810 case TYPENAME_TYPE:
8812 tree_node (TYPE_CONTEXT (type));
8813 tree_node (DECL_NAME (TYPE_NAME (type)));
8814 tree_node (TYPENAME_TYPE_FULLNAME (type));
8815 if (streaming_p ())
8817 enum tag_types tag_type = none_type;
8818 if (TYPENAME_IS_ENUM_P (type))
8819 tag_type = enum_type;
8820 else if (TYPENAME_IS_CLASS_P (type))
8821 tag_type = class_type;
8822 u (int (tag_type));
8825 break;
8827 case UNBOUND_CLASS_TEMPLATE:
8829 tree decl = TYPE_NAME (type);
8830 tree_node (DECL_CONTEXT (decl));
8831 tree_node (DECL_NAME (decl));
8832 tree_node (DECL_TEMPLATE_PARMS (decl));
8834 break;
8836 case VECTOR_TYPE:
8837 if (streaming_p ())
8839 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (type);
8840 /* to_constant asserts that only coeff[0] is of interest. */
8841 wu (static_cast<unsigned HOST_WIDE_INT> (nunits.to_constant ()));
8843 break;
8846 /* We may have met the type during emitting the above. */
8847 if (ref_node (type) != WK_none)
8849 int tag = insert (type);
8850 if (streaming_p ())
8852 i (0);
8853 dump (dumper::TREE)
8854 && dump ("Wrote:%d derived type %C", tag, TREE_CODE (type));
8858 return;
8861 /* T is (mostly*) a non-mergeable node that must be written by value.
8862 The mergeable case is a BINFO, which are as-if DECLSs. */
8864 void
8865 trees_out::tree_value (tree t)
8867 /* We should never be writing a type by value. tree_type should
8868 have streamed it, or we're going via its TYPE_DECL. */
8869 gcc_checking_assert (!TYPE_P (t));
8871 if (DECL_P (t))
8872 /* No template, type, var or function, except anonymous
8873 non-context vars. */
8874 gcc_checking_assert ((TREE_CODE (t) != TEMPLATE_DECL
8875 && TREE_CODE (t) != TYPE_DECL
8876 && (TREE_CODE (t) != VAR_DECL
8877 || (!DECL_NAME (t) && !DECL_CONTEXT (t)))
8878 && TREE_CODE (t) != FUNCTION_DECL));
8880 if (streaming_p ())
8882 /* A new node -> tt_node. */
8883 tree_val_count++;
8884 i (tt_node);
8885 start (t);
8886 tree_node_bools (t);
8889 if (TREE_CODE (t) == TREE_BINFO)
8890 /* Binfos are decl-like and need merging information. */
8891 binfo_mergeable (t);
8893 int tag = insert (t, WK_value);
8894 if (streaming_p ())
8895 dump (dumper::TREE)
8896 && dump ("Writing tree:%d %C:%N", tag, TREE_CODE (t), t);
8898 tree_node_vals (t);
8900 if (streaming_p ())
8901 dump (dumper::TREE) && dump ("Written tree:%d %C:%N", tag, TREE_CODE (t), t);
8904 tree
8905 trees_in::tree_value ()
8907 tree t = start ();
8908 if (!t || !tree_node_bools (t))
8909 return NULL_TREE;
8911 tree existing = t;
8912 if (TREE_CODE (t) == TREE_BINFO)
8914 tree type;
8915 unsigned ix = binfo_mergeable (&type);
8916 if (TYPE_BINFO (type))
8918 /* We already have a definition, this must be a duplicate. */
8919 dump (dumper::MERGE)
8920 && dump ("Deduping binfo %N[%u]", type, ix);
8921 existing = TYPE_BINFO (type);
8922 while (existing && ix--)
8923 existing = TREE_CHAIN (existing);
8924 if (existing)
8925 register_duplicate (t, existing);
8926 else
8927 /* Error, mismatch -- diagnose in read_class_def's
8928 checking. */
8929 existing = t;
8933 /* Insert into map. */
8934 int tag = insert (existing);
8935 dump (dumper::TREE)
8936 && dump ("Reading tree:%d %C", tag, TREE_CODE (t));
8938 if (!tree_node_vals (t))
8940 back_refs[~tag] = NULL_TREE;
8941 set_overrun ();
8942 /* Bail. */
8943 return NULL_TREE;
8946 dump (dumper::TREE) && dump ("Read tree:%d %C:%N", tag, TREE_CODE (t), t);
8948 if (TREE_CODE (existing) == INTEGER_CST && !TREE_OVERFLOW (existing))
8950 existing = cache_integer_cst (t, true);
8951 back_refs[~tag] = existing;
8954 return existing;
8957 /* Stream out tree node T. We automatically create local back
8958 references, which is essentially a single pass lisp
8959 self-referential structure pretty-printer. */
8961 void
8962 trees_out::tree_node (tree t)
8964 dump.indent ();
8965 walk_kind ref = ref_node (t);
8966 if (ref == WK_none)
8967 goto done;
8969 if (ref != WK_normal)
8970 goto skip_normal;
8972 if (TREE_CODE (t) == IDENTIFIER_NODE)
8974 /* An identifier node -> tt_id, tt_conv_id, tt_anon_id, tt_lambda_id. */
8975 int code = tt_id;
8976 if (IDENTIFIER_ANON_P (t))
8977 code = IDENTIFIER_LAMBDA_P (t) ? tt_lambda_id : tt_anon_id;
8978 else if (IDENTIFIER_CONV_OP_P (t))
8979 code = tt_conv_id;
8981 if (streaming_p ())
8982 i (code);
8984 if (code == tt_conv_id)
8986 tree type = TREE_TYPE (t);
8987 gcc_checking_assert (type || t == conv_op_identifier);
8988 tree_node (type);
8990 else if (code == tt_id && streaming_p ())
8991 str (IDENTIFIER_POINTER (t), IDENTIFIER_LENGTH (t));
8993 int tag = insert (t);
8994 if (streaming_p ())
8996 /* We know the ordering of the 4 id tags. */
8997 static const char *const kinds[] =
8998 {"", "conv_op ", "anon ", "lambda "};
8999 dump (dumper::TREE)
9000 && dump ("Written:%d %sidentifier:%N", tag,
9001 kinds[code - tt_id],
9002 code == tt_conv_id ? TREE_TYPE (t) : t);
9004 goto done;
9007 if (TREE_CODE (t) == TREE_BINFO)
9009 /* A BINFO -> tt_binfo.
9010 We must do this by reference. We stream the binfo tree
9011 itself when streaming its owning RECORD_TYPE. That we got
9012 here means the dominating type is not in this SCC. */
9013 if (streaming_p ())
9014 i (tt_binfo);
9015 binfo_mergeable (t);
9016 gcc_checking_assert (!TREE_VISITED (t));
9017 int tag = insert (t);
9018 if (streaming_p ())
9019 dump (dumper::TREE) && dump ("Inserting binfo:%d %N", tag, t);
9020 goto done;
9023 if (TREE_CODE (t) == INTEGER_CST
9024 && !TREE_OVERFLOW (t)
9025 && TREE_CODE (TREE_TYPE (t)) == ENUMERAL_TYPE)
9027 /* An integral constant of enumeral type. See if it matches one
9028 of the enumeration values. */
9029 for (tree values = TYPE_VALUES (TREE_TYPE (t));
9030 values; values = TREE_CHAIN (values))
9032 tree decl = TREE_VALUE (values);
9033 if (tree_int_cst_equal (DECL_INITIAL (decl), t))
9035 if (streaming_p ())
9036 u (tt_enum_value);
9037 tree_node (decl);
9038 dump (dumper::TREE) && dump ("Written enum value %N", decl);
9039 goto done;
9042 /* It didn't match. We'll write it a an explicit INTEGER_CST
9043 node. */
9046 if (TYPE_P (t))
9048 type_node (t);
9049 goto done;
9052 if (DECL_P (t))
9054 if (DECL_TEMPLATE_PARM_P (t))
9056 tpl_parm_value (t);
9057 goto done;
9060 if (!DECL_CONTEXT (t))
9062 /* There are a few cases of decls with no context. We'll write
9063 these by value, but first assert they are cases we expect. */
9064 gcc_checking_assert (ref == WK_normal);
9065 switch (TREE_CODE (t))
9067 default: gcc_unreachable ();
9069 case LABEL_DECL:
9070 /* CASE_LABEL_EXPRs contain uncontexted LABEL_DECLs. */
9071 gcc_checking_assert (!DECL_NAME (t));
9072 break;
9074 case VAR_DECL:
9075 /* AGGR_INIT_EXPRs cons up anonymous uncontexted VAR_DECLs. */
9076 gcc_checking_assert (!DECL_NAME (t)
9077 && DECL_ARTIFICIAL (t));
9078 break;
9080 case PARM_DECL:
9081 /* REQUIRES_EXPRs have a tree list of uncontexted
9082 PARM_DECLS. It'd be nice if they had a
9083 distinguishing flag to double check. */
9084 break;
9086 goto by_value;
9090 skip_normal:
9091 if (DECL_P (t) && !decl_node (t, ref))
9092 goto done;
9094 /* Otherwise by value */
9095 by_value:
9096 tree_value (t);
9098 done:
9099 /* And, breath out. */
9100 dump.outdent ();
9103 /* Stream in a tree node. */
9105 tree
9106 trees_in::tree_node (bool is_use)
9108 if (get_overrun ())
9109 return NULL_TREE;
9111 dump.indent ();
9112 int tag = i ();
9113 tree res = NULL_TREE;
9114 switch (tag)
9116 default:
9117 /* backref, pull it out of the map. */
9118 res = back_ref (tag);
9119 break;
9121 case tt_null:
9122 /* NULL_TREE. */
9123 break;
9125 case tt_fixed:
9126 /* A fixed ref, find it in the fixed_ref array. */
9128 unsigned fix = u ();
9129 if (fix < (*fixed_trees).length ())
9131 res = (*fixed_trees)[fix];
9132 dump (dumper::TREE) && dump ("Read fixed:%u %C:%N%S", fix,
9133 TREE_CODE (res), res, res);
9136 if (!res)
9137 set_overrun ();
9139 break;
9141 case tt_parm:
9143 tree fn = tree_node ();
9144 if (fn && TREE_CODE (fn) == FUNCTION_DECL)
9145 res = tree_node ();
9146 if (res)
9147 dump (dumper::TREE)
9148 && dump ("Read %s reference %N",
9149 TREE_CODE (res) == PARM_DECL ? "parameter" : "result",
9150 res);
9152 break;
9154 case tt_node:
9155 /* A new node. Stream it in. */
9156 res = tree_value ();
9157 break;
9159 case tt_decl:
9160 /* A new decl. Stream it in. */
9161 res = decl_value ();
9162 break;
9164 case tt_tpl_parm:
9165 /* A template parameter. Stream it in. */
9166 res = tpl_parm_value ();
9167 break;
9169 case tt_id:
9170 /* An identifier node. */
9172 size_t l;
9173 const char *chars = str (&l);
9174 res = get_identifier_with_length (chars, l);
9175 int tag = insert (res);
9176 dump (dumper::TREE)
9177 && dump ("Read identifier:%d %N", tag, res);
9179 break;
9181 case tt_conv_id:
9182 /* A conversion operator. Get the type and recreate the
9183 identifier. */
9185 tree type = tree_node ();
9186 if (!get_overrun ())
9188 res = type ? make_conv_op_name (type) : conv_op_identifier;
9189 int tag = insert (res);
9190 dump (dumper::TREE)
9191 && dump ("Created conv_op:%d %S for %N", tag, res, type);
9194 break;
9196 case tt_anon_id:
9197 case tt_lambda_id:
9198 /* An anonymous or lambda id. */
9200 res = make_anon_name ();
9201 if (tag == tt_lambda_id)
9202 IDENTIFIER_LAMBDA_P (res) = true;
9203 int tag = insert (res);
9204 dump (dumper::TREE)
9205 && dump ("Read %s identifier:%d %N",
9206 IDENTIFIER_LAMBDA_P (res) ? "lambda" : "anon", tag, res);
9208 break;
9210 case tt_typedef_type:
9211 res = tree_node ();
9212 if (res)
9214 dump (dumper::TREE)
9215 && dump ("Read %stypedef %C:%N",
9216 DECL_IMPLICIT_TYPEDEF_P (res) ? "implicit " : "",
9217 TREE_CODE (res), res);
9218 res = TREE_TYPE (res);
9220 break;
9222 case tt_derived_type:
9223 /* A type derived from some other type. */
9225 enum tree_code code = tree_code (u ());
9226 res = tree_node ();
9228 switch (code)
9230 default:
9231 set_overrun ();
9232 break;
9234 case ARRAY_TYPE:
9236 tree domain = tree_node ();
9237 int dep = u ();
9238 if (!get_overrun ())
9239 res = build_cplus_array_type (res, domain, dep);
9241 break;
9243 case COMPLEX_TYPE:
9244 if (!get_overrun ())
9245 res = build_complex_type (res);
9246 break;
9248 case BOOLEAN_TYPE:
9250 unsigned precision = u ();
9251 if (!get_overrun ())
9252 res = build_nonstandard_boolean_type (precision);
9254 break;
9256 case INTEGER_TYPE:
9257 if (res)
9259 /* A range type (representing an array domain). */
9260 tree min = tree_node ();
9261 tree max = tree_node ();
9263 if (!get_overrun ())
9264 res = build_range_type (res, min, max);
9266 else
9268 /* A new integral type (representing a bitfield). */
9269 unsigned enc = u ();
9270 if (!get_overrun ())
9271 res = build_nonstandard_integer_type (enc >> 1, enc & 1);
9273 break;
9275 case FUNCTION_TYPE:
9276 case METHOD_TYPE:
9278 tree klass = code == METHOD_TYPE ? tree_node () : NULL_TREE;
9279 tree args = tree_node ();
9280 if (!get_overrun ())
9282 if (klass)
9283 res = build_method_type_directly (klass, res, args);
9284 else
9285 res = build_function_type (res, args);
9288 break;
9290 case OFFSET_TYPE:
9292 tree base = tree_node ();
9293 if (!get_overrun ())
9294 res = build_offset_type (base, res);
9296 break;
9298 case POINTER_TYPE:
9299 if (!get_overrun ())
9300 res = build_pointer_type (res);
9301 break;
9303 case REFERENCE_TYPE:
9305 bool rval = bool (u ());
9306 if (!get_overrun ())
9307 res = cp_build_reference_type (res, rval);
9309 break;
9311 case DECLTYPE_TYPE:
9312 case TYPEOF_TYPE:
9313 case UNDERLYING_TYPE:
9315 tree expr = tree_node ();
9316 if (!get_overrun ())
9318 res = cxx_make_type (code);
9319 TYPE_VALUES_RAW (res) = expr;
9320 if (code == DECLTYPE_TYPE)
9321 tree_node_bools (res);
9322 SET_TYPE_STRUCTURAL_EQUALITY (res);
9325 break;
9327 case TYPE_ARGUMENT_PACK:
9328 if (!get_overrun ())
9330 tree pack = cxx_make_type (TYPE_ARGUMENT_PACK);
9331 SET_ARGUMENT_PACK_ARGS (pack, res);
9332 res = pack;
9334 break;
9336 case TYPE_PACK_EXPANSION:
9338 bool local = u ();
9339 tree param_packs = tree_node ();
9340 if (!get_overrun ())
9342 tree expn = cxx_make_type (TYPE_PACK_EXPANSION);
9343 SET_TYPE_STRUCTURAL_EQUALITY (expn);
9344 SET_PACK_EXPANSION_PATTERN (expn, res);
9345 PACK_EXPANSION_PARAMETER_PACKS (expn) = param_packs;
9346 PACK_EXPANSION_LOCAL_P (expn) = local;
9347 res = expn;
9350 break;
9352 case TYPENAME_TYPE:
9354 tree ctx = tree_node ();
9355 tree name = tree_node ();
9356 tree fullname = tree_node ();
9357 enum tag_types tag_type = tag_types (u ());
9359 if (!get_overrun ())
9360 res = build_typename_type (ctx, name, fullname, tag_type);
9362 break;
9364 case UNBOUND_CLASS_TEMPLATE:
9366 tree ctx = tree_node ();
9367 tree name = tree_node ();
9368 tree parms = tree_node ();
9370 if (!get_overrun ())
9371 res = make_unbound_class_template_raw (ctx, name, parms);
9373 break;
9375 case VECTOR_TYPE:
9377 unsigned HOST_WIDE_INT nunits = wu ();
9378 if (!get_overrun ())
9379 res = build_vector_type (res, static_cast<poly_int64> (nunits));
9381 break;
9384 int tag = i ();
9385 if (!tag)
9387 tag = insert (res);
9388 if (res)
9389 dump (dumper::TREE)
9390 && dump ("Created:%d derived type %C", tag, code);
9392 else
9393 res = back_ref (tag);
9395 break;
9397 case tt_variant_type:
9398 /* Variant of some type. */
9400 res = tree_node ();
9401 int flags = i ();
9402 if (get_overrun ())
9404 else if (flags < 0)
9405 /* No change. */;
9406 else if (TREE_CODE (res) == FUNCTION_TYPE
9407 || TREE_CODE (res) == METHOD_TYPE)
9409 cp_ref_qualifier rqual = cp_ref_qualifier (flags & 3);
9410 bool late = (flags >> 2) & 1;
9411 cp_cv_quals quals = cp_cv_quals (flags >> 3);
9413 tree raises = tree_node ();
9414 if (raises == error_mark_node)
9415 raises = TYPE_RAISES_EXCEPTIONS (res);
9417 res = build_cp_fntype_variant (res, rqual, raises, late);
9418 if (TREE_CODE (res) == FUNCTION_TYPE)
9419 res = apply_memfn_quals (res, quals, rqual);
9421 else
9423 res = build_aligned_type (res, (1u << flags) >> 1);
9424 TYPE_USER_ALIGN (res) = true;
9427 if (tree attribs = tree_node ())
9428 res = cp_build_type_attribute_variant (res, attribs);
9430 int quals = i ();
9431 if (quals >= 0 && !get_overrun ())
9432 res = cp_build_qualified_type (res, quals);
9434 int tag = i ();
9435 if (!tag)
9437 tag = insert (res);
9438 if (res)
9439 dump (dumper::TREE)
9440 && dump ("Created:%d variant type %C", tag, TREE_CODE (res));
9442 else
9443 res = back_ref (tag);
9445 break;
9447 case tt_tinfo_var:
9448 case tt_tinfo_typedef:
9449 /* A tinfo var or typedef. */
9451 bool is_var = tag == tt_tinfo_var;
9452 unsigned ix = u ();
9453 tree type = NULL_TREE;
9455 if (is_var)
9457 tree name = tree_node ();
9458 type = tree_node ();
9460 if (!get_overrun ())
9461 res = get_tinfo_decl_direct (type, name, int (ix));
9463 else
9465 if (!get_overrun ())
9467 type = get_pseudo_tinfo_type (ix);
9468 res = TYPE_NAME (type);
9471 if (res)
9473 int tag = insert (res);
9474 dump (dumper::TREE)
9475 && dump ("Created tinfo_%s:%d %S:%u for %N",
9476 is_var ? "var" : "decl", tag, res, ix, type);
9477 if (!is_var)
9479 tag = insert (type);
9480 dump (dumper::TREE)
9481 && dump ("Created tinfo_type:%d %u %N", tag, ix, type);
9485 break;
9487 case tt_ptrmem_type:
9488 /* A pointer to member function. */
9490 tree type = tree_node ();
9491 if (type && TREE_CODE (type) == POINTER_TYPE
9492 && TREE_CODE (TREE_TYPE (type)) == METHOD_TYPE)
9494 res = build_ptrmemfunc_type (type);
9495 int tag = insert (res);
9496 dump (dumper::TREE) && dump ("Created:%d ptrmem type", tag);
9498 else
9499 set_overrun ();
9501 break;
9503 case tt_enum_value:
9504 /* An enum const value. */
9506 if (tree decl = tree_node ())
9508 dump (dumper::TREE) && dump ("Read enum value %N", decl);
9509 res = DECL_INITIAL (decl);
9512 if (!res)
9513 set_overrun ();
9515 break;
9517 case tt_enum_decl:
9518 /* An enum decl. */
9520 tree ctx = tree_node ();
9521 tree name = tree_node ();
9523 if (!get_overrun ()
9524 && TREE_CODE (ctx) == ENUMERAL_TYPE)
9525 res = find_enum_member (ctx, name);
9527 if (!res)
9528 set_overrun ();
9529 else
9531 int tag = insert (res);
9532 dump (dumper::TREE)
9533 && dump ("Read enum decl:%d %C:%N", tag, TREE_CODE (res), res);
9536 break;
9538 case tt_data_member:
9539 /* A data member. */
9541 tree ctx = tree_node ();
9542 tree name = tree_node ();
9544 if (!get_overrun ()
9545 && RECORD_OR_UNION_TYPE_P (ctx))
9547 if (name)
9548 res = lookup_class_binding (ctx, name);
9549 else
9550 res = lookup_field_ident (ctx, u ());
9552 if (!res
9553 || TREE_CODE (res) != FIELD_DECL
9554 || DECL_CONTEXT (res) != ctx)
9555 res = NULL_TREE;
9558 if (!res)
9559 set_overrun ();
9560 else
9562 int tag = insert (res);
9563 dump (dumper::TREE)
9564 && dump ("Read member:%d %C:%N", tag, TREE_CODE (res), res);
9567 break;
9569 case tt_binfo:
9570 /* A BINFO. Walk the tree of the dominating type. */
9572 tree type;
9573 unsigned ix = binfo_mergeable (&type);
9574 if (type)
9576 res = TYPE_BINFO (type);
9577 for (; ix && res; res = TREE_CHAIN (res))
9578 ix--;
9579 if (!res)
9580 set_overrun ();
9583 if (get_overrun ())
9584 break;
9586 /* Insert binfo into backreferences. */
9587 tag = insert (res);
9588 dump (dumper::TREE) && dump ("Read binfo:%d %N", tag, res);
9590 break;
9592 case tt_vtable:
9594 unsigned ix = u ();
9595 tree ctx = tree_node ();
9596 dump (dumper::TREE) && dump ("Reading vtable %N[%u]", ctx, ix);
9597 if (TREE_CODE (ctx) == RECORD_TYPE && TYPE_LANG_SPECIFIC (ctx))
9598 for (res = CLASSTYPE_VTABLES (ctx); res; res = DECL_CHAIN (res))
9599 if (!ix--)
9600 break;
9601 if (!res)
9602 set_overrun ();
9604 break;
9606 case tt_thunk:
9608 int fixed = i ();
9609 tree target = tree_node ();
9610 tree virt = tree_node ();
9612 for (tree thunk = DECL_THUNKS (target);
9613 thunk; thunk = DECL_CHAIN (thunk))
9614 if (THUNK_FIXED_OFFSET (thunk) == fixed
9615 && !THUNK_VIRTUAL_OFFSET (thunk) == !virt
9616 && (!virt
9617 || tree_int_cst_equal (virt, THUNK_VIRTUAL_OFFSET (thunk))))
9619 res = thunk;
9620 break;
9623 int tag = insert (res);
9624 if (res)
9625 dump (dumper::TREE)
9626 && dump ("Read:%d thunk %N to %N", tag, DECL_NAME (res), target);
9627 else
9628 set_overrun ();
9630 break;
9632 case tt_clone_ref:
9634 tree target = tree_node ();
9635 tree name = tree_node ();
9637 if (DECL_P (target) && DECL_MAYBE_IN_CHARGE_CDTOR_P (target))
9639 tree clone;
9640 FOR_EVERY_CLONE (clone, target)
9641 if (DECL_NAME (clone) == name)
9643 res = clone;
9644 break;
9648 if (!res)
9649 set_overrun ();
9650 int tag = insert (res);
9651 if (res)
9652 dump (dumper::TREE)
9653 && dump ("Read:%d clone %N of %N", tag, DECL_NAME (res), target);
9654 else
9655 set_overrun ();
9657 break;
9659 case tt_entity:
9660 /* Index into the entity table. Perhaps not loaded yet! */
9662 unsigned origin = state->slurp->remap_module (u ());
9663 unsigned ident = u ();
9664 module_state *from = (*modules)[origin];
9666 if (!origin || ident >= from->entity_num)
9667 set_overrun ();
9668 if (!get_overrun ())
9670 binding_slot *slot = &(*entity_ary)[from->entity_lwm + ident];
9671 if (slot->is_lazy ())
9672 if (!from->lazy_load (ident, slot))
9673 set_overrun ();
9674 res = *slot;
9677 if (res)
9679 const char *kind = (origin != state->mod ? "Imported" : "Named");
9680 int tag = insert (res);
9681 dump (dumper::TREE)
9682 && dump ("%s:%d %C:%N@%M", kind, tag, TREE_CODE (res),
9683 res, (*modules)[origin]);
9685 if (!add_indirects (res))
9687 set_overrun ();
9688 res = NULL_TREE;
9692 break;
9694 case tt_template:
9695 /* A template. */
9696 if (tree tpl = tree_node ())
9698 res = DECL_TEMPLATE_RESULT (tpl);
9699 dump (dumper::TREE)
9700 && dump ("Read template %C:%N", TREE_CODE (res), res);
9702 break;
9705 if (is_use && !unused && res && DECL_P (res) && !TREE_USED (res))
9707 /* Mark decl used as mark_used does -- we cannot call
9708 mark_used in the middle of streaming, we only need a subset
9709 of its functionality. */
9710 TREE_USED (res) = true;
9712 /* And for structured bindings also the underlying decl. */
9713 if (DECL_DECOMPOSITION_P (res) && DECL_DECOMP_BASE (res))
9714 TREE_USED (DECL_DECOMP_BASE (res)) = true;
9716 if (DECL_CLONED_FUNCTION_P (res))
9717 TREE_USED (DECL_CLONED_FUNCTION (res)) = true;
9720 dump.outdent ();
9721 return res;
9724 void
9725 trees_out::tpl_parms (tree parms, unsigned &tpl_levels)
9727 if (!parms)
9728 return;
9730 if (TREE_VISITED (parms))
9732 ref_node (parms);
9733 return;
9736 tpl_parms (TREE_CHAIN (parms), tpl_levels);
9738 tree vec = TREE_VALUE (parms);
9739 unsigned len = TREE_VEC_LENGTH (vec);
9740 /* Depth. */
9741 int tag = insert (parms);
9742 if (streaming_p ())
9744 i (len + 1);
9745 dump (dumper::TREE)
9746 && dump ("Writing template parms:%d level:%N length:%d",
9747 tag, TREE_PURPOSE (parms), len);
9749 tree_node (TREE_PURPOSE (parms));
9751 for (unsigned ix = 0; ix != len; ix++)
9753 tree parm = TREE_VEC_ELT (vec, ix);
9754 tree decl = TREE_VALUE (parm);
9756 gcc_checking_assert (DECL_TEMPLATE_PARM_P (decl));
9757 if (CHECKING_P)
9758 switch (TREE_CODE (decl))
9760 default: gcc_unreachable ();
9762 case TEMPLATE_DECL:
9763 gcc_assert ((TREE_CODE (TREE_TYPE (decl)) == TEMPLATE_TEMPLATE_PARM)
9764 && (TREE_CODE (DECL_TEMPLATE_RESULT (decl)) == TYPE_DECL)
9765 && (TYPE_NAME (TREE_TYPE (decl)) == decl));
9766 break;
9768 case TYPE_DECL:
9769 gcc_assert ((TREE_CODE (TREE_TYPE (decl)) == TEMPLATE_TYPE_PARM)
9770 && (TYPE_NAME (TREE_TYPE (decl)) == decl));
9771 break;
9773 case PARM_DECL:
9774 gcc_assert ((TREE_CODE (DECL_INITIAL (decl)) == TEMPLATE_PARM_INDEX)
9775 && (TREE_CODE (TEMPLATE_PARM_DECL (DECL_INITIAL (decl)))
9776 == CONST_DECL)
9777 && (DECL_TEMPLATE_PARM_P
9778 (TEMPLATE_PARM_DECL (DECL_INITIAL (decl)))));
9779 break;
9782 tree_node (decl);
9783 tree_node (TEMPLATE_PARM_CONSTRAINTS (parm));
9786 tpl_levels++;
9789 tree
9790 trees_in::tpl_parms (unsigned &tpl_levels)
9792 tree parms = NULL_TREE;
9794 while (int len = i ())
9796 if (len < 0)
9798 parms = back_ref (len);
9799 continue;
9802 len -= 1;
9803 parms = tree_cons (NULL_TREE, NULL_TREE, parms);
9804 int tag = insert (parms);
9805 TREE_PURPOSE (parms) = tree_node ();
9807 dump (dumper::TREE)
9808 && dump ("Reading template parms:%d level:%N length:%d",
9809 tag, TREE_PURPOSE (parms), len);
9811 tree vec = make_tree_vec (len);
9812 for (int ix = 0; ix != len; ix++)
9814 tree decl = tree_node ();
9815 if (!decl)
9816 return NULL_TREE;
9818 tree parm = build_tree_list (NULL, decl);
9819 TEMPLATE_PARM_CONSTRAINTS (parm) = tree_node ();
9821 TREE_VEC_ELT (vec, ix) = parm;
9824 TREE_VALUE (parms) = vec;
9825 tpl_levels++;
9828 return parms;
9831 void
9832 trees_out::tpl_parms_fini (tree tmpl, unsigned tpl_levels)
9834 for (tree parms = DECL_TEMPLATE_PARMS (tmpl);
9835 tpl_levels--; parms = TREE_CHAIN (parms))
9837 tree vec = TREE_VALUE (parms);
9839 tree_node (TREE_TYPE (vec));
9840 tree dflt = error_mark_node;
9841 for (unsigned ix = TREE_VEC_LENGTH (vec); ix--;)
9843 tree parm = TREE_VEC_ELT (vec, ix);
9844 if (dflt)
9846 dflt = TREE_PURPOSE (parm);
9847 tree_node (dflt);
9850 if (streaming_p ())
9852 tree decl = TREE_VALUE (parm);
9853 if (TREE_CODE (decl) == TEMPLATE_DECL)
9855 tree ctx = DECL_CONTEXT (decl);
9856 tree inner = DECL_TEMPLATE_RESULT (decl);
9857 tree tpi = (TREE_CODE (inner) == TYPE_DECL
9858 ? TEMPLATE_TYPE_PARM_INDEX (TREE_TYPE (decl))
9859 : DECL_INITIAL (inner));
9860 bool original = (TEMPLATE_PARM_LEVEL (tpi)
9861 == TEMPLATE_PARM_ORIG_LEVEL (tpi));
9862 /* Original template template parms have a context
9863 of their owning template. Reduced ones do not. */
9864 gcc_checking_assert (original ? ctx == tmpl : !ctx);
9871 bool
9872 trees_in::tpl_parms_fini (tree tmpl, unsigned tpl_levels)
9874 for (tree parms = DECL_TEMPLATE_PARMS (tmpl);
9875 tpl_levels--; parms = TREE_CHAIN (parms))
9877 tree vec = TREE_VALUE (parms);
9878 tree dflt = error_mark_node;
9880 TREE_TYPE (vec) = tree_node ();
9881 for (unsigned ix = TREE_VEC_LENGTH (vec); ix--;)
9883 tree parm = TREE_VEC_ELT (vec, ix);
9884 if (dflt)
9886 dflt = tree_node ();
9887 if (get_overrun ())
9888 return false;
9889 TREE_PURPOSE (parm) = dflt;
9892 tree decl = TREE_VALUE (parm);
9893 if (TREE_CODE (decl) == TEMPLATE_DECL)
9895 tree inner = DECL_TEMPLATE_RESULT (decl);
9896 tree tpi = (TREE_CODE (inner) == TYPE_DECL
9897 ? TEMPLATE_TYPE_PARM_INDEX (TREE_TYPE (decl))
9898 : DECL_INITIAL (inner));
9899 bool original = (TEMPLATE_PARM_LEVEL (tpi)
9900 == TEMPLATE_PARM_ORIG_LEVEL (tpi));
9901 /* Original template template parms have a context
9902 of their owning template. Reduced ones do not. */
9903 if (original)
9904 DECL_CONTEXT (decl) = tmpl;
9908 return true;
9911 /* PARMS is a LIST, one node per level.
9912 TREE_VALUE is a TREE_VEC of parm info for that level.
9913 each ELT is a TREE_LIST
9914 TREE_VALUE is PARM_DECL, TYPE_DECL or TEMPLATE_DECL
9915 TREE_PURPOSE is the default value. */
9917 void
9918 trees_out::tpl_header (tree tpl, unsigned *tpl_levels)
9920 tree parms = DECL_TEMPLATE_PARMS (tpl);
9921 tpl_parms (parms, *tpl_levels);
9923 /* Mark end. */
9924 if (streaming_p ())
9925 u (0);
9927 if (*tpl_levels)
9928 tree_node (TEMPLATE_PARMS_CONSTRAINTS (parms));
9931 bool
9932 trees_in::tpl_header (tree tpl, unsigned *tpl_levels)
9934 tree parms = tpl_parms (*tpl_levels);
9935 if (!parms)
9936 return false;
9938 DECL_TEMPLATE_PARMS (tpl) = parms;
9940 if (*tpl_levels)
9941 TEMPLATE_PARMS_CONSTRAINTS (parms) = tree_node ();
9943 return true;
9946 /* Stream skeleton parm nodes, with their flags, type & parm indices.
9947 All the parms will have consecutive tags. */
9949 void
9950 trees_out::fn_parms_init (tree fn)
9952 /* First init them. */
9953 int base_tag = ref_num - 1;
9954 int ix = 0;
9955 for (tree parm = DECL_ARGUMENTS (fn);
9956 parm; parm = DECL_CHAIN (parm), ix++)
9958 if (streaming_p ())
9960 start (parm);
9961 tree_node_bools (parm);
9963 int tag = insert (parm);
9964 gcc_checking_assert (base_tag - ix == tag);
9966 /* Mark the end. */
9967 if (streaming_p ())
9968 u (0);
9970 /* Now stream their contents. */
9971 ix = 0;
9972 for (tree parm = DECL_ARGUMENTS (fn);
9973 parm; parm = DECL_CHAIN (parm), ix++)
9975 if (streaming_p ())
9976 dump (dumper::TREE)
9977 && dump ("Writing parm:%d %u (%N) of %N",
9978 base_tag - ix, ix, parm, fn);
9979 tree_node_vals (parm);
9983 /* Build skeleton parm nodes, read their flags, type & parm indices. */
9986 trees_in::fn_parms_init (tree fn)
9988 int base_tag = ~(int)back_refs.length ();
9990 tree *parm_ptr = &DECL_ARGUMENTS (fn);
9991 int ix = 0;
9992 for (; int code = u (); ix++)
9994 tree parm = start (code);
9995 if (!tree_node_bools (parm))
9996 return 0;
9998 int tag = insert (parm);
9999 gcc_checking_assert (base_tag - ix == tag);
10000 *parm_ptr = parm;
10001 parm_ptr = &DECL_CHAIN (parm);
10004 ix = 0;
10005 for (tree parm = DECL_ARGUMENTS (fn);
10006 parm; parm = DECL_CHAIN (parm), ix++)
10008 dump (dumper::TREE)
10009 && dump ("Reading parm:%d %u (%N) of %N",
10010 base_tag - ix, ix, parm, fn);
10011 if (!tree_node_vals (parm))
10012 return 0;
10015 return base_tag;
10018 /* Read the remaining parm node data. Replace with existing (if
10019 non-null) in the map. */
10021 void
10022 trees_in::fn_parms_fini (int tag, tree fn, tree existing, bool is_defn)
10024 tree existing_parm = existing ? DECL_ARGUMENTS (existing) : NULL_TREE;
10025 tree parms = DECL_ARGUMENTS (fn);
10026 unsigned ix = 0;
10027 for (tree parm = parms; parm; parm = DECL_CHAIN (parm), ix++)
10029 if (existing_parm)
10031 if (is_defn && !DECL_SAVED_TREE (existing))
10033 /* If we're about to become the definition, set the
10034 names of the parms from us. */
10035 DECL_NAME (existing_parm) = DECL_NAME (parm);
10036 DECL_SOURCE_LOCATION (existing_parm) = DECL_SOURCE_LOCATION (parm);
10039 back_refs[~tag] = existing_parm;
10040 existing_parm = DECL_CHAIN (existing_parm);
10042 tag--;
10046 /* DEP is the depset of some decl we're streaming by value. Determine
10047 the merging behaviour. */
10049 merge_kind
10050 trees_out::get_merge_kind (tree decl, depset *dep)
10052 if (!dep)
10054 if (VAR_OR_FUNCTION_DECL_P (decl))
10056 /* Any var or function with template info should have DEP. */
10057 gcc_checking_assert (!DECL_LANG_SPECIFIC (decl)
10058 || !DECL_TEMPLATE_INFO (decl));
10059 if (DECL_LOCAL_DECL_P (decl))
10060 return MK_unique;
10063 /* Either unique, or some member of a class that cannot have an
10064 out-of-class definition. For instance a FIELD_DECL. */
10065 tree ctx = CP_DECL_CONTEXT (decl);
10066 if (TREE_CODE (ctx) == FUNCTION_DECL)
10068 /* USING_DECLs cannot have DECL_TEMPLATE_INFO -- this isn't
10069 permitting them to have one. */
10070 gcc_checking_assert (TREE_CODE (decl) == USING_DECL
10071 || !DECL_LANG_SPECIFIC (decl)
10072 || !DECL_TEMPLATE_INFO (decl));
10074 return MK_unique;
10077 if (TREE_CODE (decl) == TEMPLATE_DECL
10078 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10079 return MK_local_friend;
10081 gcc_checking_assert (TYPE_P (ctx));
10082 if (TREE_CODE (decl) == USING_DECL)
10083 return MK_field;
10085 if (TREE_CODE (decl) == FIELD_DECL)
10087 if (DECL_NAME (decl))
10089 /* Anonymous FIELD_DECLs have a NULL name. */
10090 gcc_checking_assert (!IDENTIFIER_ANON_P (DECL_NAME (decl)));
10091 return MK_named;
10094 if (!DECL_NAME (decl)
10095 && !RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl))
10096 && !DECL_BIT_FIELD_REPRESENTATIVE (decl))
10098 /* The underlying storage unit for a bitfield. We do not
10099 need to dedup it, because it's only reachable through
10100 the bitfields it represents. And those are deduped. */
10101 // FIXME: Is that assertion correct -- do we ever fish it
10102 // out and put it in an expr?
10103 gcc_checking_assert ((TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
10104 ? TREE_CODE (TREE_TYPE (TREE_TYPE (decl)))
10105 : TREE_CODE (TREE_TYPE (decl)))
10106 == INTEGER_TYPE);
10107 return MK_unique;
10110 return MK_field;
10113 if (TREE_CODE (decl) == CONST_DECL)
10114 return MK_named;
10116 if (TREE_CODE (decl) == VAR_DECL
10117 && DECL_VTABLE_OR_VTT_P (decl))
10118 return MK_vtable;
10120 if (DECL_THUNK_P (decl))
10121 /* Thunks are unique-enough, because they're only referenced
10122 from the vtable. And that's either new (so we want the
10123 thunks), or it's a duplicate (so it will be dropped). */
10124 return MK_unique;
10126 /* There should be no other cases. */
10127 gcc_unreachable ();
10130 gcc_checking_assert (TREE_CODE (decl) != FIELD_DECL
10131 && TREE_CODE (decl) != USING_DECL
10132 && TREE_CODE (decl) != CONST_DECL);
10134 if (is_key_order ())
10136 /* When doing the mergeablilty graph, there's an indirection to
10137 the actual depset. */
10138 gcc_assert (dep->is_special ());
10139 dep = dep->deps[0];
10142 gcc_checking_assert (decl == dep->get_entity ());
10144 merge_kind mk = MK_named;
10145 switch (dep->get_entity_kind ())
10147 default:
10148 gcc_unreachable ();
10150 case depset::EK_PARTIAL:
10151 mk = MK_partial;
10152 break;
10154 case depset::EK_DECL:
10156 tree ctx = CP_DECL_CONTEXT (decl);
10158 switch (TREE_CODE (ctx))
10160 default:
10161 gcc_unreachable ();
10163 case FUNCTION_DECL:
10164 // FIXME: This can occur for (a) voldemorty TYPE_DECLS
10165 // (which are returned from a function), or (b)
10166 // block-scope class definitions in template functions.
10167 // These are as unique as the containing function. While
10168 // on read-back we can discover if the CTX was a
10169 // duplicate, we don't have a mechanism to get from the
10170 // existing CTX to the existing version of this decl.
10171 gcc_checking_assert
10172 (DECL_IMPLICIT_TYPEDEF_P (STRIP_TEMPLATE (decl)));
10174 mk = MK_unique;
10175 break;
10177 case RECORD_TYPE:
10178 case UNION_TYPE:
10179 if (DECL_NAME (decl) == as_base_identifier)
10180 mk = MK_as_base;
10181 else if (IDENTIFIER_ANON_P (DECL_NAME (decl)))
10182 mk = MK_field;
10183 break;
10185 case NAMESPACE_DECL:
10186 if (DECL_IMPLICIT_TYPEDEF_P (STRIP_TEMPLATE (decl))
10187 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
10188 if (tree scope
10189 = LAMBDA_EXPR_EXTRA_SCOPE (CLASSTYPE_LAMBDA_EXPR
10190 (TREE_TYPE (decl))))
10191 if (TREE_CODE (scope) == VAR_DECL
10192 && DECL_MODULE_ATTACHMENTS_P (scope))
10194 mk = MK_attached;
10195 break;
10198 if (TREE_CODE (decl) == TEMPLATE_DECL
10199 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10200 mk = MK_local_friend;
10201 else if (IDENTIFIER_ANON_P (DECL_NAME (decl)))
10203 if (DECL_IMPLICIT_TYPEDEF_P (decl)
10204 && UNSCOPED_ENUM_P (TREE_TYPE (decl))
10205 && TYPE_VALUES (TREE_TYPE (decl)))
10206 /* Keyed by first enum value, and underlying type. */
10207 mk = MK_enum;
10208 else
10209 /* No way to merge it, it is an ODR land-mine. */
10210 mk = MK_unique;
10214 break;
10216 case depset::EK_SPECIALIZATION:
10218 gcc_checking_assert (dep->is_special ());
10220 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
10221 /* An block-scope classes of templates are themselves
10222 templates. */
10223 gcc_checking_assert (DECL_IMPLICIT_TYPEDEF_P (decl));
10225 if (dep->is_friend_spec ())
10226 mk = MK_friend_spec;
10227 else if (dep->is_type_spec ())
10228 mk = MK_type_spec;
10229 else if (dep->is_alias ())
10230 mk = MK_alias_spec;
10231 else
10232 mk = MK_decl_spec;
10234 if (TREE_CODE (decl) == TEMPLATE_DECL)
10236 spec_entry *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
10237 if (TREE_CODE (entry->spec) != TEMPLATE_DECL)
10238 mk = merge_kind (mk | MK_tmpl_tmpl_mask);
10241 break;
10244 return mk;
10248 /* The container of DECL -- not necessarily its context! */
10250 tree
10251 trees_out::decl_container (tree decl)
10253 int use_tpl;
10254 tree tpl = NULL_TREE;
10255 if (tree template_info = node_template_info (decl, use_tpl))
10256 tpl = TI_TEMPLATE (template_info);
10257 if (tpl == decl)
10258 tpl = nullptr;
10260 /* Stream the template we're instantiated from. */
10261 tree_node (tpl);
10263 tree container = NULL_TREE;
10264 if (TREE_CODE (decl) == TEMPLATE_DECL
10265 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10266 container = DECL_CHAIN (decl);
10267 else
10268 container = CP_DECL_CONTEXT (decl);
10270 if (TYPE_P (container))
10271 container = TYPE_NAME (container);
10273 tree_node (container);
10275 return container;
10278 tree
10279 trees_in::decl_container ()
10281 /* The maybe-template. */
10282 (void)tree_node ();
10284 tree container = tree_node ();
10286 return container;
10289 /* Write out key information about a mergeable DEP. Does not write
10290 the contents of DEP itself. The context has already been
10291 written. The container has already been streamed. */
10293 void
10294 trees_out::key_mergeable (int tag, merge_kind mk, tree decl, tree inner,
10295 tree container, depset *dep)
10297 if (dep && is_key_order ())
10299 gcc_checking_assert (dep->is_special ());
10300 dep = dep->deps[0];
10303 if (streaming_p ())
10304 dump (dumper::MERGE)
10305 && dump ("Writing:%d's %s merge key (%s) %C:%N", tag, merge_kind_name[mk],
10306 dep ? dep->entity_kind_name () : "contained",
10307 TREE_CODE (decl), decl);
10309 /* Now write the locating information. */
10310 if (mk & MK_template_mask)
10312 /* Specializations are located via their originating template,
10313 and the set of template args they specialize. */
10314 gcc_checking_assert (dep && dep->is_special ());
10315 spec_entry *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
10317 tree_node (entry->tmpl);
10318 tree_node (entry->args);
10319 if (mk & MK_tmpl_decl_mask)
10320 if (flag_concepts && TREE_CODE (inner) == VAR_DECL)
10322 /* Variable template partial specializations might need
10323 constraints (see spec_hasher::equal). It's simpler to
10324 write NULL when we don't need them. */
10325 tree constraints = NULL_TREE;
10327 if (uses_template_parms (entry->args))
10328 constraints = get_constraints (inner);
10329 tree_node (constraints);
10332 if (CHECKING_P)
10334 /* Make sure we can locate the decl. */
10335 tree existing = match_mergeable_specialization
10336 (bool (mk & MK_tmpl_decl_mask), entry);
10338 gcc_assert (existing);
10339 if (mk & MK_tmpl_decl_mask)
10341 if (mk & MK_tmpl_alias_mask)
10342 /* It should be in both tables. */
10343 gcc_checking_assert
10344 (same_type_p (match_mergeable_specialization (false, entry),
10345 TREE_TYPE (existing)));
10346 if (mk & MK_tmpl_tmpl_mask)
10347 existing = DECL_TI_TEMPLATE (existing);
10349 else
10351 if (mk & MK_tmpl_tmpl_mask)
10352 existing = CLASSTYPE_TI_TEMPLATE (existing);
10353 else
10354 existing = TYPE_NAME (existing);
10357 /* The walkabout should have found ourselves. */
10358 gcc_checking_assert (TREE_CODE (decl) == TYPE_DECL
10359 ? same_type_p (TREE_TYPE (decl),
10360 TREE_TYPE (existing))
10361 : existing == decl);
10364 else if (mk != MK_unique)
10366 merge_key key;
10367 tree name = DECL_NAME (decl);
10369 switch (mk)
10371 default:
10372 gcc_unreachable ();
10374 case MK_named:
10375 case MK_friend_spec:
10376 if (IDENTIFIER_CONV_OP_P (name))
10377 name = conv_op_identifier;
10379 if (TREE_CODE (inner) == FUNCTION_DECL)
10381 /* Functions are distinguished by parameter types. */
10382 tree fn_type = TREE_TYPE (inner);
10384 key.ref_q = type_memfn_rqual (fn_type);
10385 key.args = TYPE_ARG_TYPES (fn_type);
10387 if (tree reqs = get_constraints (inner))
10389 if (cxx_dialect < cxx20)
10390 reqs = CI_ASSOCIATED_CONSTRAINTS (reqs);
10391 else
10392 reqs = CI_DECLARATOR_REQS (reqs);
10393 key.constraints = reqs;
10396 if (IDENTIFIER_CONV_OP_P (name)
10397 || (decl != inner
10398 && !(name == fun_identifier
10399 /* In case the user names something _FUN */
10400 && LAMBDA_TYPE_P (DECL_CONTEXT (inner)))))
10401 /* And a function template, or conversion operator needs
10402 the return type. Except for the _FUN thunk of a
10403 generic lambda, which has a recursive decl_type'd
10404 return type. */
10405 // FIXME: What if the return type is a voldemort?
10406 key.ret = fndecl_declared_return_type (inner);
10408 break;
10410 case MK_field:
10412 unsigned ix = 0;
10413 if (TREE_CODE (inner) != FIELD_DECL)
10414 name = NULL_TREE;
10415 else
10416 gcc_checking_assert (!name || !IDENTIFIER_ANON_P (name));
10418 for (tree field = TYPE_FIELDS (TREE_TYPE (container));
10419 ; field = DECL_CHAIN (field))
10421 tree finner = STRIP_TEMPLATE (field);
10422 if (TREE_CODE (finner) == TREE_CODE (inner))
10424 if (finner == inner)
10425 break;
10426 ix++;
10429 key.index = ix;
10431 break;
10433 case MK_vtable:
10435 tree vtable = CLASSTYPE_VTABLES (TREE_TYPE (container));
10436 for (unsigned ix = 0; ; vtable = DECL_CHAIN (vtable), ix++)
10437 if (vtable == decl)
10439 key.index = ix;
10440 break;
10442 name = NULL_TREE;
10444 break;
10446 case MK_as_base:
10447 gcc_checking_assert
10448 (decl == TYPE_NAME (CLASSTYPE_AS_BASE (TREE_TYPE (container))));
10449 break;
10451 case MK_local_friend:
10453 /* Find by index on the class's DECL_LIST */
10454 unsigned ix = 0;
10455 for (tree decls = CLASSTYPE_DECL_LIST (TREE_CHAIN (decl));
10456 decls; decls = TREE_CHAIN (decls))
10457 if (!TREE_PURPOSE (decls))
10459 tree frnd = friend_from_decl_list (TREE_VALUE (decls));
10460 if (frnd == decl)
10461 break;
10462 ix++;
10464 key.index = ix;
10465 name = NULL_TREE;
10467 break;
10469 case MK_enum:
10471 /* Anonymous enums are located by their first identifier,
10472 and underlying type. */
10473 tree type = TREE_TYPE (decl);
10475 gcc_checking_assert (UNSCOPED_ENUM_P (type));
10476 /* Using the type name drops the bit precision we might
10477 have been using on the enum. */
10478 key.ret = TYPE_NAME (ENUM_UNDERLYING_TYPE (type));
10479 if (tree values = TYPE_VALUES (type))
10480 name = DECL_NAME (TREE_VALUE (values));
10482 break;
10484 case MK_attached:
10486 gcc_checking_assert (LAMBDA_TYPE_P (TREE_TYPE (inner)));
10487 tree scope = LAMBDA_EXPR_EXTRA_SCOPE (CLASSTYPE_LAMBDA_EXPR
10488 (TREE_TYPE (inner)));
10489 gcc_checking_assert (TREE_CODE (scope) == VAR_DECL);
10490 auto *root = attached_table->get (scope);
10491 unsigned ix = root->length ();
10492 /* If we don't find it, we'll write a really big number
10493 that the reader will ignore. */
10494 while (ix--)
10495 if ((*root)[ix] == inner)
10496 break;
10498 /* Use the attached-to decl as the 'name'. */
10499 name = scope;
10500 key.index = ix;
10502 break;
10504 case MK_partial:
10506 key.constraints = get_constraints (inner);
10507 key.ret = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (inner));
10508 key.args = CLASSTYPE_TI_ARGS (TREE_TYPE (inner));
10510 break;
10513 tree_node (name);
10514 if (streaming_p ())
10516 unsigned code = (key.ref_q << 0) | (key.index << 2);
10517 u (code);
10520 if (mk == MK_enum)
10521 tree_node (key.ret);
10522 else if (mk == MK_partial
10523 || (mk == MK_named && inner
10524 && TREE_CODE (inner) == FUNCTION_DECL))
10526 tree_node (key.ret);
10527 tree arg = key.args;
10528 if (mk == MK_named)
10529 while (arg && arg != void_list_node)
10531 tree_node (TREE_VALUE (arg));
10532 arg = TREE_CHAIN (arg);
10534 tree_node (arg);
10535 tree_node (key.constraints);
10540 /* DECL is a new declaration that may be duplicated in OVL. Use RET &
10541 ARGS to find its clone, or NULL. If DECL's DECL_NAME is NULL, this
10542 has been found by a proxy. It will be an enum type located by it's
10543 first member.
10545 We're conservative with matches, so ambiguous decls will be
10546 registered as different, then lead to a lookup error if the two
10547 modules are both visible. Perhaps we want to do something similar
10548 to duplicate decls to get ODR errors on loading? We already have
10549 some special casing for namespaces. */
10551 static tree
10552 check_mergeable_decl (merge_kind mk, tree decl, tree ovl, merge_key const &key)
10554 tree found = NULL_TREE;
10555 for (ovl_iterator iter (ovl); !found && iter; ++iter)
10557 tree match = *iter;
10559 tree d_inner = decl;
10560 tree m_inner = match;
10562 again:
10563 if (TREE_CODE (d_inner) != TREE_CODE (m_inner))
10565 if (TREE_CODE (match) == NAMESPACE_DECL
10566 && !DECL_NAMESPACE_ALIAS (match))
10567 /* Namespaces are never overloaded. */
10568 found = match;
10570 continue;
10573 switch (TREE_CODE (d_inner))
10575 case TEMPLATE_DECL:
10576 if (template_heads_equivalent_p (d_inner, m_inner))
10578 d_inner = DECL_TEMPLATE_RESULT (d_inner);
10579 m_inner = DECL_TEMPLATE_RESULT (m_inner);
10580 if (d_inner == error_mark_node
10581 && TYPE_DECL_ALIAS_P (m_inner))
10583 found = match;
10584 break;
10586 goto again;
10588 break;
10590 case FUNCTION_DECL:
10591 if (tree m_type = TREE_TYPE (m_inner))
10592 if ((!key.ret
10593 || same_type_p (key.ret, fndecl_declared_return_type (m_inner)))
10594 && type_memfn_rqual (m_type) == key.ref_q
10595 && compparms (key.args, TYPE_ARG_TYPES (m_type))
10596 /* Reject if old is a "C" builtin and new is not "C".
10597 Matches decls_match behaviour. */
10598 && (!DECL_IS_UNDECLARED_BUILTIN (m_inner)
10599 || !DECL_EXTERN_C_P (m_inner)
10600 || DECL_EXTERN_C_P (d_inner)))
10602 tree m_reqs = get_constraints (m_inner);
10603 if (m_reqs)
10605 if (cxx_dialect < cxx20)
10606 m_reqs = CI_ASSOCIATED_CONSTRAINTS (m_reqs);
10607 else
10608 m_reqs = CI_DECLARATOR_REQS (m_reqs);
10611 if (cp_tree_equal (key.constraints, m_reqs))
10612 found = match;
10614 break;
10616 case TYPE_DECL:
10617 if (DECL_IMPLICIT_TYPEDEF_P (d_inner)
10618 == DECL_IMPLICIT_TYPEDEF_P (m_inner))
10620 if (!IDENTIFIER_ANON_P (DECL_NAME (m_inner)))
10621 return match;
10622 else if (mk == MK_enum
10623 && (TYPE_NAME (ENUM_UNDERLYING_TYPE (TREE_TYPE (m_inner)))
10624 == key.ret))
10625 found = match;
10627 break;
10629 default:
10630 found = match;
10631 break;
10635 return found;
10638 /* DECL, INNER & TYPE are a skeleton set of nodes for a decl. Only
10639 the bools have been filled in. Read its merging key and merge it.
10640 Returns the existing decl if there is one. */
10642 tree
10643 trees_in::key_mergeable (int tag, merge_kind mk, tree decl, tree inner,
10644 tree type, tree container, bool is_mod)
10646 const char *kind = "new";
10647 tree existing = NULL_TREE;
10649 if (mk & MK_template_mask)
10651 // FIXME: We could stream the specialization hash?
10652 spec_entry spec;
10653 spec.tmpl = tree_node ();
10654 spec.args = tree_node ();
10656 if (get_overrun ())
10657 return error_mark_node;
10659 DECL_NAME (decl) = DECL_NAME (spec.tmpl);
10660 DECL_CONTEXT (decl) = DECL_CONTEXT (spec.tmpl);
10661 DECL_NAME (inner) = DECL_NAME (decl);
10662 DECL_CONTEXT (inner) = DECL_CONTEXT (decl);
10664 tree constr = NULL_TREE;
10665 bool is_decl = mk & MK_tmpl_decl_mask;
10666 if (is_decl)
10668 if (flag_concepts && TREE_CODE (inner) == VAR_DECL)
10670 constr = tree_node ();
10671 if (constr)
10672 set_constraints (inner, constr);
10674 spec.spec = (mk & MK_tmpl_tmpl_mask) ? inner : decl;
10676 else
10677 spec.spec = type;
10678 existing = match_mergeable_specialization (is_decl, &spec);
10679 if (constr)
10680 /* We'll add these back later, if this is the new decl. */
10681 remove_constraints (inner);
10683 if (!existing)
10684 ; /* We'll add to the table once read. */
10685 else if (mk & MK_tmpl_decl_mask)
10687 /* A declaration specialization. */
10688 if (mk & MK_tmpl_tmpl_mask)
10689 existing = DECL_TI_TEMPLATE (existing);
10691 else
10693 /* A type specialization. */
10694 if (mk & MK_tmpl_tmpl_mask)
10695 existing = CLASSTYPE_TI_TEMPLATE (existing);
10696 else
10697 existing = TYPE_NAME (existing);
10700 else if (mk == MK_unique)
10701 kind = "unique";
10702 else
10704 tree name = tree_node ();
10706 merge_key key;
10707 unsigned code = u ();
10708 key.ref_q = cp_ref_qualifier ((code >> 0) & 3);
10709 key.index = code >> 2;
10711 if (mk == MK_enum)
10712 key.ret = tree_node ();
10713 else if (mk == MK_partial
10714 || ((mk == MK_named || mk == MK_friend_spec)
10715 && TREE_CODE (inner) == FUNCTION_DECL))
10717 key.ret = tree_node ();
10718 tree arg, *arg_ptr = &key.args;
10719 while ((arg = tree_node ())
10720 && arg != void_list_node
10721 && mk != MK_partial)
10723 *arg_ptr = tree_cons (NULL_TREE, arg, NULL_TREE);
10724 arg_ptr = &TREE_CHAIN (*arg_ptr);
10726 *arg_ptr = arg;
10727 key.constraints = tree_node ();
10730 if (get_overrun ())
10731 return error_mark_node;
10733 if (mk < MK_indirect_lwm)
10735 DECL_NAME (decl) = name;
10736 DECL_CONTEXT (decl) = FROB_CONTEXT (container);
10738 DECL_NAME (inner) = DECL_NAME (decl);
10739 DECL_CONTEXT (inner) = DECL_CONTEXT (decl);
10741 if (mk == MK_partial)
10743 for (tree spec = DECL_TEMPLATE_SPECIALIZATIONS (key.ret);
10744 spec; spec = TREE_CHAIN (spec))
10746 tree tmpl = TREE_VALUE (spec);
10747 if (template_args_equal (key.args,
10748 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)))
10749 && cp_tree_equal (key.constraints,
10750 get_constraints
10751 (DECL_TEMPLATE_RESULT (tmpl))))
10753 existing = tmpl;
10754 break;
10758 else
10759 switch (TREE_CODE (container))
10761 default:
10762 gcc_unreachable ();
10764 case NAMESPACE_DECL:
10765 if (mk == MK_attached)
10767 if (DECL_LANG_SPECIFIC (name)
10768 && VAR_OR_FUNCTION_DECL_P (name)
10769 && DECL_MODULE_ATTACHMENTS_P (name))
10770 if (auto *set = attached_table->get (name))
10771 if (key.index < set->length ())
10773 existing = (*set)[key.index];
10774 if (existing)
10776 gcc_checking_assert
10777 (DECL_IMPLICIT_TYPEDEF_P (existing));
10778 if (inner != decl)
10779 existing
10780 = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (existing));
10784 else if (is_mod && !(state->is_module () || state->is_partition ()))
10785 kind = "unique";
10786 else
10788 gcc_checking_assert (mk == MK_named || mk == MK_enum);
10789 tree mvec;
10790 tree *vslot = mergeable_namespace_slots (container, name,
10791 !is_mod, &mvec);
10792 existing = check_mergeable_decl (mk, decl, *vslot, key);
10793 if (!existing)
10794 add_mergeable_namespace_entity (vslot, decl);
10795 else
10797 /* Note that we now have duplicates to deal with in
10798 name lookup. */
10799 if (is_mod)
10800 BINDING_VECTOR_PARTITION_DUPS_P (mvec) = true;
10801 else
10802 BINDING_VECTOR_GLOBAL_DUPS_P (mvec) = true;
10805 break;
10807 case FUNCTION_DECL:
10808 // FIXME: What about a voldemort? how do we find what it
10809 // duplicates? Do we have to number vmorts relative to
10810 // their containing function? But how would that work
10811 // when matching an in-TU declaration?
10812 kind = "unique";
10813 break;
10815 case TYPE_DECL:
10816 if (is_mod && !(state->is_module () || state->is_partition ())
10817 /* Implicit member functions can come from
10818 anywhere. */
10819 && !(DECL_ARTIFICIAL (decl)
10820 && TREE_CODE (decl) == FUNCTION_DECL
10821 && !DECL_THUNK_P (decl)))
10822 kind = "unique";
10823 else
10825 tree ctx = TREE_TYPE (container);
10827 /* For some reason templated enumeral types are not marked
10828 as COMPLETE_TYPE_P, even though they have members.
10829 This may well be a bug elsewhere. */
10830 if (TREE_CODE (ctx) == ENUMERAL_TYPE)
10831 existing = find_enum_member (ctx, name);
10832 else if (COMPLETE_TYPE_P (ctx))
10834 switch (mk)
10836 default:
10837 gcc_unreachable ();
10839 case MK_named:
10840 existing = lookup_class_binding (ctx, name);
10841 if (existing)
10843 tree inner = decl;
10844 if (TREE_CODE (inner) == TEMPLATE_DECL
10845 && !DECL_MEMBER_TEMPLATE_P (inner))
10846 inner = DECL_TEMPLATE_RESULT (inner);
10848 existing = check_mergeable_decl
10849 (mk, inner, existing, key);
10851 if (!existing && DECL_ALIAS_TEMPLATE_P (decl))
10852 {} // FIXME: Insert into specialization
10853 // tables, we'll need the arguments for that!
10855 break;
10857 case MK_field:
10859 unsigned ix = key.index;
10860 for (tree field = TYPE_FIELDS (ctx);
10861 field; field = DECL_CHAIN (field))
10863 tree finner = STRIP_TEMPLATE (field);
10864 if (TREE_CODE (finner) == TREE_CODE (inner))
10865 if (!ix--)
10867 existing = field;
10868 break;
10872 break;
10874 case MK_vtable:
10876 unsigned ix = key.index;
10877 for (tree vtable = CLASSTYPE_VTABLES (ctx);
10878 vtable; vtable = DECL_CHAIN (vtable))
10879 if (!ix--)
10881 existing = vtable;
10882 break;
10885 break;
10887 case MK_as_base:
10889 tree as_base = CLASSTYPE_AS_BASE (ctx);
10890 if (as_base && as_base != ctx)
10891 existing = TYPE_NAME (as_base);
10893 break;
10895 case MK_local_friend:
10897 unsigned ix = key.index;
10898 for (tree decls = CLASSTYPE_DECL_LIST (ctx);
10899 decls; decls = TREE_CHAIN (decls))
10900 if (!TREE_PURPOSE (decls) && !ix--)
10902 existing
10903 = friend_from_decl_list (TREE_VALUE (decls));
10904 break;
10907 break;
10910 if (existing && mk < MK_indirect_lwm && mk != MK_partial
10911 && TREE_CODE (decl) == TEMPLATE_DECL
10912 && !DECL_MEMBER_TEMPLATE_P (decl))
10914 tree ti;
10915 if (DECL_IMPLICIT_TYPEDEF_P (existing))
10916 ti = TYPE_TEMPLATE_INFO (TREE_TYPE (existing));
10917 else
10918 ti = DECL_TEMPLATE_INFO (existing);
10919 existing = TI_TEMPLATE (ti);
10926 dump (dumper::MERGE)
10927 && dump ("Read:%d's %s merge key (%s) %C:%N", tag, merge_kind_name[mk],
10928 existing ? "matched" : kind, TREE_CODE (decl), decl);
10930 return existing;
10933 void
10934 trees_out::binfo_mergeable (tree binfo)
10936 tree dom = binfo;
10937 while (tree parent = BINFO_INHERITANCE_CHAIN (dom))
10938 dom = parent;
10939 tree type = BINFO_TYPE (dom);
10940 gcc_checking_assert (TYPE_BINFO (type) == dom);
10941 tree_node (type);
10942 if (streaming_p ())
10944 unsigned ix = 0;
10945 for (; dom != binfo; dom = TREE_CHAIN (dom))
10946 ix++;
10947 u (ix);
10951 unsigned
10952 trees_in::binfo_mergeable (tree *type)
10954 *type = tree_node ();
10955 return u ();
10958 /* DECL is a just streamed mergeable decl that should match EXISTING. Check
10959 it does and issue an appropriate diagnostic if not. Merge any
10960 bits from DECL to EXISTING. This is stricter matching than
10961 decls_match, because we can rely on ODR-sameness, and we cannot use
10962 decls_match because it can cause instantiations of constraints. */
10964 bool
10965 trees_in::is_matching_decl (tree existing, tree decl, bool is_typedef)
10967 // FIXME: We should probably do some duplicate decl-like stuff here
10968 // (beware, default parms should be the same?) Can we just call
10969 // duplicate_decls and teach it how to handle the module-specific
10970 // permitted/required duplications?
10972 // We know at this point that the decls have matched by key, so we
10973 // can elide some of the checking
10974 gcc_checking_assert (TREE_CODE (existing) == TREE_CODE (decl));
10976 tree d_inner = decl;
10977 tree e_inner = existing;
10978 if (TREE_CODE (decl) == TEMPLATE_DECL)
10980 d_inner = DECL_TEMPLATE_RESULT (d_inner);
10981 e_inner = DECL_TEMPLATE_RESULT (e_inner);
10982 gcc_checking_assert (TREE_CODE (e_inner) == TREE_CODE (d_inner));
10985 if (TREE_CODE (d_inner) == FUNCTION_DECL)
10987 tree e_ret = fndecl_declared_return_type (existing);
10988 tree d_ret = fndecl_declared_return_type (decl);
10990 if (decl != d_inner && DECL_NAME (d_inner) == fun_identifier
10991 && LAMBDA_TYPE_P (DECL_CONTEXT (d_inner)))
10992 /* This has a recursive type that will compare different. */;
10993 else if (!same_type_p (d_ret, e_ret))
10994 goto mismatch;
10996 tree e_type = TREE_TYPE (e_inner);
10997 tree d_type = TREE_TYPE (d_inner);
10999 if (DECL_EXTERN_C_P (d_inner) != DECL_EXTERN_C_P (e_inner))
11000 goto mismatch;
11002 for (tree e_args = TYPE_ARG_TYPES (e_type),
11003 d_args = TYPE_ARG_TYPES (d_type);
11004 e_args != d_args && (e_args || d_args);
11005 e_args = TREE_CHAIN (e_args), d_args = TREE_CHAIN (d_args))
11007 if (!(e_args && d_args))
11008 goto mismatch;
11010 if (!same_type_p (TREE_VALUE (d_args), TREE_VALUE (e_args)))
11011 goto mismatch;
11013 // FIXME: Check default values
11016 /* If EXISTING has an undeduced or uninstantiated exception
11017 specification, but DECL does not, propagate the exception
11018 specification. Otherwise we end up asserting or trying to
11019 instantiate it in the middle of loading. */
11020 tree e_spec = TYPE_RAISES_EXCEPTIONS (e_type);
11021 tree d_spec = TYPE_RAISES_EXCEPTIONS (d_type);
11022 if (DEFERRED_NOEXCEPT_SPEC_P (e_spec))
11024 if (!DEFERRED_NOEXCEPT_SPEC_P (d_spec)
11025 || (UNEVALUATED_NOEXCEPT_SPEC_P (e_spec)
11026 && !UNEVALUATED_NOEXCEPT_SPEC_P (d_spec)))
11028 dump (dumper::MERGE)
11029 && dump ("Propagating instantiated noexcept to %N", existing);
11030 TREE_TYPE (existing) = d_type;
11032 /* Propagate to existing clones. */
11033 tree clone;
11034 FOR_EACH_CLONE (clone, existing)
11036 if (TREE_TYPE (clone) == e_type)
11037 TREE_TYPE (clone) = d_type;
11038 else
11039 TREE_TYPE (clone)
11040 = build_exception_variant (TREE_TYPE (clone), d_spec);
11044 else if (!DEFERRED_NOEXCEPT_SPEC_P (d_spec)
11045 && !comp_except_specs (d_spec, e_spec, ce_type))
11046 goto mismatch;
11048 else if (is_typedef)
11050 if (!DECL_ORIGINAL_TYPE (e_inner)
11051 || !same_type_p (DECL_ORIGINAL_TYPE (d_inner),
11052 DECL_ORIGINAL_TYPE (e_inner)))
11053 goto mismatch;
11055 /* Using cp_tree_equal because we can meet TYPE_ARGUMENT_PACKs
11056 here. I suspect the entities that directly do that are things
11057 that shouldn't go to duplicate_decls (FIELD_DECLs etc). */
11058 else if (!cp_tree_equal (TREE_TYPE (decl), TREE_TYPE (existing)))
11060 mismatch:
11061 if (DECL_IS_UNDECLARED_BUILTIN (existing))
11062 /* Just like duplicate_decls, presum the user knows what
11063 they're doing in overriding a builtin. */
11064 TREE_TYPE (existing) = TREE_TYPE (decl);
11065 else
11067 // FIXME:QOI Might be template specialization from a module,
11068 // not necessarily global module
11069 error_at (DECL_SOURCE_LOCATION (decl),
11070 "conflicting global module declaration %#qD", decl);
11071 inform (DECL_SOURCE_LOCATION (existing),
11072 "existing declaration %#qD", existing);
11073 return false;
11077 if (DECL_IS_UNDECLARED_BUILTIN (existing)
11078 && !DECL_IS_UNDECLARED_BUILTIN (decl))
11080 /* We're matching a builtin that the user has yet to declare.
11081 We are the one! This is very much duplicate-decl
11082 shenanigans. */
11083 DECL_SOURCE_LOCATION (existing) = DECL_SOURCE_LOCATION (decl);
11084 if (TREE_CODE (decl) != TYPE_DECL)
11086 /* Propagate exceptions etc. */
11087 TREE_TYPE (existing) = TREE_TYPE (decl);
11088 TREE_NOTHROW (existing) = TREE_NOTHROW (decl);
11090 /* This is actually an import! */
11091 DECL_MODULE_IMPORT_P (existing) = true;
11093 /* Yay, sliced! */
11094 existing->base = decl->base;
11096 if (TREE_CODE (decl) == FUNCTION_DECL)
11098 /* Ew :( */
11099 memcpy (&existing->decl_common.size,
11100 &decl->decl_common.size,
11101 (offsetof (tree_decl_common, pt_uid)
11102 - offsetof (tree_decl_common, size)));
11103 auto bltin_class = DECL_BUILT_IN_CLASS (decl);
11104 existing->function_decl.built_in_class = bltin_class;
11105 auto fncode = DECL_UNCHECKED_FUNCTION_CODE (decl);
11106 DECL_UNCHECKED_FUNCTION_CODE (existing) = fncode;
11107 if (existing->function_decl.built_in_class == BUILT_IN_NORMAL)
11109 if (builtin_decl_explicit_p (built_in_function (fncode)))
11110 switch (fncode)
11112 case BUILT_IN_STPCPY:
11113 set_builtin_decl_implicit_p
11114 (built_in_function (fncode), true);
11115 break;
11116 default:
11117 set_builtin_decl_declared_p
11118 (built_in_function (fncode), true);
11119 break;
11121 copy_attributes_to_builtin (decl);
11126 if (VAR_OR_FUNCTION_DECL_P (decl)
11127 && DECL_TEMPLATE_INSTANTIATED (decl))
11128 /* Don't instantiate again! */
11129 DECL_TEMPLATE_INSTANTIATED (existing) = true;
11131 if (TREE_CODE (d_inner) == FUNCTION_DECL
11132 && DECL_DECLARED_INLINE_P (d_inner))
11133 DECL_DECLARED_INLINE_P (e_inner) = true;
11134 if (!DECL_EXTERNAL (d_inner))
11135 DECL_EXTERNAL (e_inner) = false;
11137 // FIXME: Check default tmpl and fn parms here
11139 return true;
11142 /* FN is an implicit member function that we've discovered is new to
11143 the class. Add it to the TYPE_FIELDS chain and the method vector.
11144 Reset the appropriate classtype lazy flag. */
11146 bool
11147 trees_in::install_implicit_member (tree fn)
11149 tree ctx = DECL_CONTEXT (fn);
11150 tree name = DECL_NAME (fn);
11151 /* We know these are synthesized, so the set of expected prototypes
11152 is quite restricted. We're not validating correctness, just
11153 distinguishing beteeen the small set of possibilities. */
11154 tree parm_type = TREE_VALUE (FUNCTION_FIRST_USER_PARMTYPE (fn));
11155 if (IDENTIFIER_CTOR_P (name))
11157 if (CLASSTYPE_LAZY_DEFAULT_CTOR (ctx)
11158 && VOID_TYPE_P (parm_type))
11159 CLASSTYPE_LAZY_DEFAULT_CTOR (ctx) = false;
11160 else if (!TYPE_REF_P (parm_type))
11161 return false;
11162 else if (CLASSTYPE_LAZY_COPY_CTOR (ctx)
11163 && !TYPE_REF_IS_RVALUE (parm_type))
11164 CLASSTYPE_LAZY_COPY_CTOR (ctx) = false;
11165 else if (CLASSTYPE_LAZY_MOVE_CTOR (ctx))
11166 CLASSTYPE_LAZY_MOVE_CTOR (ctx) = false;
11167 else
11168 return false;
11170 else if (IDENTIFIER_DTOR_P (name))
11172 if (CLASSTYPE_LAZY_DESTRUCTOR (ctx))
11173 CLASSTYPE_LAZY_DESTRUCTOR (ctx) = false;
11174 else
11175 return false;
11176 if (DECL_VIRTUAL_P (fn))
11177 /* A virtual dtor should have been created when the class
11178 became complete. */
11179 return false;
11181 else if (name == assign_op_identifier)
11183 if (!TYPE_REF_P (parm_type))
11184 return false;
11185 else if (CLASSTYPE_LAZY_COPY_ASSIGN (ctx)
11186 && !TYPE_REF_IS_RVALUE (parm_type))
11187 CLASSTYPE_LAZY_COPY_ASSIGN (ctx) = false;
11188 else if (CLASSTYPE_LAZY_MOVE_ASSIGN (ctx))
11189 CLASSTYPE_LAZY_MOVE_ASSIGN (ctx) = false;
11190 else
11191 return false;
11193 else
11194 return false;
11196 dump (dumper::MERGE) && dump ("Adding implicit member %N", fn);
11198 DECL_CHAIN (fn) = TYPE_FIELDS (ctx);
11199 TYPE_FIELDS (ctx) = fn;
11201 add_method (ctx, fn, false);
11203 /* Propagate TYPE_FIELDS. */
11204 fixup_type_variants (ctx);
11206 return true;
11209 /* Return non-zero if DECL has a definition that would be interesting to
11210 write out. */
11212 static bool
11213 has_definition (tree decl)
11215 bool is_tmpl = TREE_CODE (decl) == TEMPLATE_DECL;
11216 if (is_tmpl)
11217 decl = DECL_TEMPLATE_RESULT (decl);
11219 switch (TREE_CODE (decl))
11221 default:
11222 break;
11224 case FUNCTION_DECL:
11225 if (!DECL_SAVED_TREE (decl))
11226 /* Not defined. */
11227 break;
11229 if (DECL_DECLARED_INLINE_P (decl))
11230 return true;
11232 if (DECL_THIS_STATIC (decl)
11233 && (header_module_p ()
11234 || (!DECL_LANG_SPECIFIC (decl) || !DECL_MODULE_PURVIEW_P (decl))))
11235 /* GM static function. */
11236 return true;
11238 if (DECL_TEMPLATE_INFO (decl))
11240 int use_tpl = DECL_USE_TEMPLATE (decl);
11242 // FIXME: Partial specializations have definitions too.
11243 if (use_tpl < 2)
11244 return true;
11246 break;
11248 case TYPE_DECL:
11250 tree type = TREE_TYPE (decl);
11251 if (type == TYPE_MAIN_VARIANT (type)
11252 && decl == TYPE_NAME (type)
11253 && (TREE_CODE (type) == ENUMERAL_TYPE
11254 ? TYPE_VALUES (type) : TYPE_FIELDS (type)))
11255 return true;
11257 break;
11259 case VAR_DECL:
11260 if (DECL_LANG_SPECIFIC (decl)
11261 && DECL_TEMPLATE_INFO (decl)
11262 && DECL_USE_TEMPLATE (decl) < 2)
11263 return DECL_INITIAL (decl);
11264 else
11266 if (!DECL_INITIALIZED_P (decl))
11267 return false;
11269 if (header_module_p ()
11270 || (!DECL_LANG_SPECIFIC (decl) || !DECL_MODULE_PURVIEW_P (decl)))
11271 /* GM static variable. */
11272 return true;
11274 if (!TREE_CONSTANT (decl))
11275 return false;
11277 return true;
11279 break;
11281 case CONCEPT_DECL:
11282 if (DECL_INITIAL (decl))
11283 return true;
11285 break;
11288 return false;
11291 uintptr_t *
11292 trees_in::find_duplicate (tree existing)
11294 if (!duplicates)
11295 return NULL;
11297 return duplicates->get (existing);
11300 /* We're starting to read a duplicate DECL. EXISTING is the already
11301 known node. */
11303 void
11304 trees_in::register_duplicate (tree decl, tree existing)
11306 if (!duplicates)
11307 duplicates = new duplicate_hash_map (40);
11309 bool existed;
11310 uintptr_t &slot = duplicates->get_or_insert (existing, &existed);
11311 gcc_checking_assert (!existed);
11312 slot = reinterpret_cast<uintptr_t> (decl);
11315 /* We've read a definition of MAYBE_EXISTING. If not a duplicate,
11316 return MAYBE_EXISTING (into which the definition should be
11317 installed). Otherwise return NULL if already known bad, or the
11318 duplicate we read (for ODR checking, or extracting additional merge
11319 information). */
11321 tree
11322 trees_in::odr_duplicate (tree maybe_existing, bool has_defn)
11324 tree res = NULL_TREE;
11326 if (uintptr_t *dup = find_duplicate (maybe_existing))
11328 if (!(*dup & 1))
11329 res = reinterpret_cast<tree> (*dup);
11331 else
11332 res = maybe_existing;
11334 assert_definition (maybe_existing, res && !has_defn);
11336 // FIXME: We probably need to return the template, so that the
11337 // template header can be checked?
11338 return res ? STRIP_TEMPLATE (res) : NULL_TREE;
11341 /* The following writer functions rely on the current behaviour of
11342 depset::hash::add_dependency making the decl and defn depset nodes
11343 depend on eachother. That way we don't have to worry about seeding
11344 the tree map with named decls that cannot be looked up by name (I.e
11345 template and function parms). We know the decl and definition will
11346 be in the same cluster, which is what we want. */
11348 void
11349 trees_out::write_function_def (tree decl)
11351 tree_node (DECL_RESULT (decl));
11352 tree_node (DECL_INITIAL (decl));
11353 tree_node (DECL_SAVED_TREE (decl));
11354 tree_node (DECL_FRIEND_CONTEXT (decl));
11356 constexpr_fundef *cexpr = retrieve_constexpr_fundef (decl);
11357 int tag = 0;
11358 if (cexpr)
11360 if (cexpr->result == error_mark_node)
11361 /* We'll stream the RESULT_DECL naturally during the
11362 serialization. We never need to fish it back again, so
11363 that's ok. */
11364 tag = 0;
11365 else
11366 tag = insert (cexpr->result);
11368 if (streaming_p ())
11370 i (tag);
11371 if (tag)
11372 dump (dumper::TREE)
11373 && dump ("Constexpr:%d result %N", tag, cexpr->result);
11375 if (tag)
11377 unsigned ix = 0;
11378 for (tree parm = cexpr->parms; parm; parm = DECL_CHAIN (parm), ix++)
11380 tag = insert (parm);
11381 if (streaming_p ())
11382 dump (dumper::TREE)
11383 && dump ("Constexpr:%d parm:%u %N", tag, ix, parm);
11385 tree_node (cexpr->body);
11388 if (streaming_p ())
11390 unsigned flags = 0;
11392 if (DECL_NOT_REALLY_EXTERN (decl))
11393 flags |= 1;
11395 u (flags);
11399 void
11400 trees_out::mark_function_def (tree)
11404 bool
11405 trees_in::read_function_def (tree decl, tree maybe_template)
11407 dump () && dump ("Reading function definition %N", decl);
11408 tree result = tree_node ();
11409 tree initial = tree_node ();
11410 tree saved = tree_node ();
11411 tree context = tree_node ();
11412 constexpr_fundef cexpr;
11414 tree maybe_dup = odr_duplicate (maybe_template, DECL_SAVED_TREE (decl));
11415 bool installing = maybe_dup && !DECL_SAVED_TREE (decl);
11417 if (int wtag = i ())
11419 int tag = 1;
11420 cexpr.result = error_mark_node;
11422 cexpr.result = copy_decl (result);
11423 tag = insert (cexpr.result);
11425 if (wtag != tag)
11426 set_overrun ();
11427 dump (dumper::TREE)
11428 && dump ("Constexpr:%d result %N", tag, cexpr.result);
11430 cexpr.parms = NULL_TREE;
11431 tree *chain = &cexpr.parms;
11432 unsigned ix = 0;
11433 for (tree parm = DECL_ARGUMENTS (maybe_dup ? maybe_dup : decl);
11434 parm; parm = DECL_CHAIN (parm), ix++)
11436 tree p = copy_decl (parm);
11437 tag = insert (p);
11438 dump (dumper::TREE)
11439 && dump ("Constexpr:%d parm:%u %N", tag, ix, p);
11440 *chain = p;
11441 chain = &DECL_CHAIN (p);
11443 cexpr.body = tree_node ();
11444 cexpr.decl = decl;
11446 else
11447 cexpr.decl = NULL_TREE;
11449 unsigned flags = u ();
11451 if (get_overrun ())
11452 return NULL_TREE;
11454 if (installing)
11456 DECL_NOT_REALLY_EXTERN (decl) = flags & 1;
11457 DECL_RESULT (decl) = result;
11458 DECL_INITIAL (decl) = initial;
11459 DECL_SAVED_TREE (decl) = saved;
11460 if (maybe_dup)
11461 DECL_ARGUMENTS (decl) = DECL_ARGUMENTS (maybe_dup);
11463 if (context)
11464 SET_DECL_FRIEND_CONTEXT (decl, context);
11465 if (cexpr.decl)
11466 register_constexpr_fundef (cexpr);
11467 post_process (maybe_template);
11469 else if (maybe_dup)
11471 // FIXME:QOI Check matching defn
11474 return true;
11477 /* Also for CONCEPT_DECLs. */
11479 void
11480 trees_out::write_var_def (tree decl)
11482 tree init = DECL_INITIAL (decl);
11483 tree_node (init);
11484 if (!init)
11486 tree dyn_init = NULL_TREE;
11488 if (DECL_NONTRIVIALLY_INITIALIZED_P (decl))
11490 dyn_init = value_member (decl,
11491 CP_DECL_THREAD_LOCAL_P (decl)
11492 ? tls_aggregates : static_aggregates);
11493 gcc_checking_assert (dyn_init);
11494 /* Mark it so write_inits knows this is needed. */
11495 TREE_LANG_FLAG_0 (dyn_init) = true;
11496 dyn_init = TREE_PURPOSE (dyn_init);
11498 tree_node (dyn_init);
11502 void
11503 trees_out::mark_var_def (tree)
11507 bool
11508 trees_in::read_var_def (tree decl, tree maybe_template)
11510 /* Do not mark the virtual table entries as used. */
11511 bool vtable = TREE_CODE (decl) == VAR_DECL && DECL_VTABLE_OR_VTT_P (decl);
11512 unused += vtable;
11513 tree init = tree_node ();
11514 tree dyn_init = init ? NULL_TREE : tree_node ();
11515 unused -= vtable;
11517 if (get_overrun ())
11518 return false;
11520 bool initialized = (VAR_P (decl) ? bool (DECL_INITIALIZED_P (decl))
11521 : bool (DECL_INITIAL (decl)));
11522 tree maybe_dup = odr_duplicate (maybe_template, initialized);
11523 bool installing = maybe_dup && !initialized;
11524 if (installing)
11526 if (DECL_EXTERNAL (decl))
11527 DECL_NOT_REALLY_EXTERN (decl) = true;
11528 if (VAR_P (decl))
11530 DECL_INITIALIZED_P (decl) = true;
11531 if (maybe_dup && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (maybe_dup))
11532 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
11534 DECL_INITIAL (decl) = init;
11535 if (!dyn_init)
11537 else if (CP_DECL_THREAD_LOCAL_P (decl))
11538 tls_aggregates = tree_cons (dyn_init, decl, tls_aggregates);
11539 else
11540 static_aggregates = tree_cons (dyn_init, decl, static_aggregates);
11542 else if (maybe_dup)
11544 // FIXME:QOI Check matching defn
11547 return true;
11550 /* If MEMBER doesn't have an independent life outside the class,
11551 return it (or it's TEMPLATE_DECL). Otherwise NULL. */
11553 static tree
11554 member_owned_by_class (tree member)
11556 gcc_assert (DECL_P (member));
11558 /* Clones are owned by their origin. */
11559 if (DECL_CLONED_FUNCTION_P (member))
11560 return NULL;
11562 if (TREE_CODE (member) == FIELD_DECL)
11563 /* FIELD_DECLS can have template info in some cases. We always
11564 want the FIELD_DECL though, as there's never a TEMPLATE_DECL
11565 wrapping them. */
11566 return member;
11568 int use_tpl = -1;
11569 if (tree ti = node_template_info (member, use_tpl))
11571 // FIXME: Don't bail on things that CANNOT have their own
11572 // template header. No, make sure they're in the same cluster.
11573 if (use_tpl > 0)
11574 return NULL_TREE;
11576 if (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == member)
11577 member = TI_TEMPLATE (ti);
11579 return member;
11582 void
11583 trees_out::write_class_def (tree defn)
11585 gcc_assert (DECL_P (defn));
11586 if (streaming_p ())
11587 dump () && dump ("Writing class definition %N", defn);
11589 tree type = TREE_TYPE (defn);
11590 tree_node (TYPE_SIZE (type));
11591 tree_node (TYPE_SIZE_UNIT (type));
11592 tree_node (TYPE_VFIELD (type));
11593 tree_node (TYPE_BINFO (type));
11595 vec_chained_decls (TYPE_FIELDS (type));
11597 /* Every class but __as_base has a type-specific. */
11598 gcc_checking_assert (!TYPE_LANG_SPECIFIC (type) == IS_FAKE_BASE_TYPE (type));
11600 if (TYPE_LANG_SPECIFIC (type))
11603 vec<tree, va_gc> *v = CLASSTYPE_MEMBER_VEC (type);
11604 if (!v)
11606 gcc_checking_assert (!streaming_p ());
11607 /* Force a class vector. */
11608 v = set_class_bindings (type, -1);
11609 gcc_checking_assert (v);
11612 unsigned len = v->length ();
11613 if (streaming_p ())
11614 u (len);
11615 for (unsigned ix = 0; ix != len; ix++)
11617 tree m = (*v)[ix];
11618 if (TREE_CODE (m) == TYPE_DECL
11619 && DECL_ARTIFICIAL (m)
11620 && TYPE_STUB_DECL (TREE_TYPE (m)) == m)
11621 /* This is a using-decl for a type, or an anonymous
11622 struct (maybe with a typedef name). Write the type. */
11623 m = TREE_TYPE (m);
11624 tree_node (m);
11627 tree_node (CLASSTYPE_LAMBDA_EXPR (type));
11629 /* TYPE_CONTAINS_VPTR_P looks at the vbase vector, which the
11630 reader won't know at this point. */
11631 int has_vptr = TYPE_CONTAINS_VPTR_P (type);
11633 if (streaming_p ())
11635 unsigned nvbases = vec_safe_length (CLASSTYPE_VBASECLASSES (type));
11636 u (nvbases);
11637 i (has_vptr);
11640 if (has_vptr)
11642 tree_vec (CLASSTYPE_PURE_VIRTUALS (type));
11643 tree_pair_vec (CLASSTYPE_VCALL_INDICES (type));
11644 tree_node (CLASSTYPE_KEY_METHOD (type));
11648 if (TYPE_LANG_SPECIFIC (type))
11650 tree_node (CLASSTYPE_PRIMARY_BINFO (type));
11652 tree as_base = CLASSTYPE_AS_BASE (type);
11653 if (as_base)
11654 as_base = TYPE_NAME (as_base);
11655 tree_node (as_base);
11657 /* Write the vtables. */
11658 tree vtables = CLASSTYPE_VTABLES (type);
11659 vec_chained_decls (vtables);
11660 for (; vtables; vtables = TREE_CHAIN (vtables))
11661 write_definition (vtables);
11663 /* Write the friend classes. */
11664 tree_list (CLASSTYPE_FRIEND_CLASSES (type), false);
11666 /* Write the friend functions. */
11667 for (tree friends = DECL_FRIENDLIST (defn);
11668 friends; friends = TREE_CHAIN (friends))
11670 /* Name of these friends. */
11671 tree_node (TREE_PURPOSE (friends));
11672 tree_list (TREE_VALUE (friends), false);
11674 /* End of friend fns. */
11675 tree_node (NULL_TREE);
11677 /* Write the decl list. */
11678 tree_list (CLASSTYPE_DECL_LIST (type), true);
11680 if (TYPE_CONTAINS_VPTR_P (type))
11682 /* Write the thunks. */
11683 for (tree decls = TYPE_FIELDS (type);
11684 decls; decls = DECL_CHAIN (decls))
11685 if (TREE_CODE (decls) == FUNCTION_DECL
11686 && DECL_VIRTUAL_P (decls)
11687 && DECL_THUNKS (decls))
11689 tree_node (decls);
11690 /* Thunks are always unique, so chaining is ok. */
11691 chained_decls (DECL_THUNKS (decls));
11693 tree_node (NULL_TREE);
11698 void
11699 trees_out::mark_class_member (tree member, bool do_defn)
11701 gcc_assert (DECL_P (member));
11703 member = member_owned_by_class (member);
11704 if (member)
11705 mark_declaration (member, do_defn && has_definition (member));
11708 void
11709 trees_out::mark_class_def (tree defn)
11711 gcc_assert (DECL_P (defn));
11712 tree type = TREE_TYPE (defn);
11713 /* Mark the class members that are not type-decls and cannot have
11714 independent definitions. */
11715 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
11716 if (TREE_CODE (member) == FIELD_DECL
11717 || TREE_CODE (member) == USING_DECL
11718 /* A cloned enum-decl from 'using enum unrelated;' */
11719 || (TREE_CODE (member) == CONST_DECL
11720 && DECL_CONTEXT (member) == type))
11722 mark_class_member (member);
11723 if (TREE_CODE (member) == FIELD_DECL)
11724 if (tree repr = DECL_BIT_FIELD_REPRESENTATIVE (member))
11725 mark_declaration (repr, false);
11728 /* Mark the binfo hierarchy. */
11729 for (tree child = TYPE_BINFO (type); child; child = TREE_CHAIN (child))
11730 mark_by_value (child);
11732 if (TYPE_LANG_SPECIFIC (type))
11734 for (tree vtable = CLASSTYPE_VTABLES (type);
11735 vtable; vtable = TREE_CHAIN (vtable))
11736 mark_declaration (vtable, true);
11738 if (TYPE_CONTAINS_VPTR_P (type))
11739 /* Mark the thunks, they belong to the class definition,
11740 /not/ the thunked-to function. */
11741 for (tree decls = TYPE_FIELDS (type);
11742 decls; decls = DECL_CHAIN (decls))
11743 if (TREE_CODE (decls) == FUNCTION_DECL)
11744 for (tree thunks = DECL_THUNKS (decls);
11745 thunks; thunks = DECL_CHAIN (thunks))
11746 mark_declaration (thunks, false);
11750 /* Nop sorting, needed for resorting the member vec. */
11752 static void
11753 nop (void *, void *)
11757 bool
11758 trees_in::read_class_def (tree defn, tree maybe_template)
11760 gcc_assert (DECL_P (defn));
11761 dump () && dump ("Reading class definition %N", defn);
11762 tree type = TREE_TYPE (defn);
11763 tree size = tree_node ();
11764 tree size_unit = tree_node ();
11765 tree vfield = tree_node ();
11766 tree binfo = tree_node ();
11767 vec<tree, va_gc> *vbase_vec = NULL;
11768 vec<tree, va_gc> *member_vec = NULL;
11769 vec<tree, va_gc> *pure_virts = NULL;
11770 vec<tree_pair_s, va_gc> *vcall_indices = NULL;
11771 tree key_method = NULL_TREE;
11772 tree lambda = NULL_TREE;
11774 /* Read the fields. */
11775 vec<tree, va_heap> *fields = vec_chained_decls ();
11777 if (TYPE_LANG_SPECIFIC (type))
11779 if (unsigned len = u ())
11781 vec_alloc (member_vec, len);
11782 for (unsigned ix = 0; ix != len; ix++)
11784 tree m = tree_node ();
11785 if (get_overrun ())
11786 break;
11787 if (TYPE_P (m))
11788 m = TYPE_STUB_DECL (m);
11789 member_vec->quick_push (m);
11792 lambda = tree_node ();
11794 if (!get_overrun ())
11796 unsigned nvbases = u ();
11797 if (nvbases)
11799 vec_alloc (vbase_vec, nvbases);
11800 for (tree child = binfo; child; child = TREE_CHAIN (child))
11801 if (BINFO_VIRTUAL_P (child))
11802 vbase_vec->quick_push (child);
11806 if (!get_overrun ())
11808 int has_vptr = i ();
11809 if (has_vptr)
11811 pure_virts = tree_vec ();
11812 vcall_indices = tree_pair_vec ();
11813 key_method = tree_node ();
11818 tree maybe_dup = odr_duplicate (maybe_template, TYPE_SIZE (type));
11819 bool installing = maybe_dup && !TYPE_SIZE (type);
11820 if (installing)
11822 if (DECL_EXTERNAL (defn) && TYPE_LANG_SPECIFIC (type))
11824 /* We don't deal with not-really-extern, because, for a
11825 module you want the import to be the interface, and for a
11826 header-unit, you're doing it wrong. */
11827 CLASSTYPE_INTERFACE_UNKNOWN (type) = false;
11828 CLASSTYPE_INTERFACE_ONLY (type) = true;
11831 if (maybe_dup != defn)
11833 // FIXME: This is needed on other defns too, almost
11834 // duplicate-decl like? See is_matching_decl too.
11835 /* Copy flags from the duplicate. */
11836 tree type_dup = TREE_TYPE (maybe_dup);
11838 /* Core pieces. */
11839 TYPE_MODE_RAW (type) = TYPE_MODE_RAW (type_dup);
11840 SET_DECL_MODE (defn, DECL_MODE (maybe_dup));
11841 TREE_ADDRESSABLE (type) = TREE_ADDRESSABLE (type_dup);
11842 DECL_SIZE (defn) = DECL_SIZE (maybe_dup);
11843 DECL_SIZE_UNIT (defn) = DECL_SIZE_UNIT (maybe_dup);
11844 DECL_ALIGN_RAW (defn) = DECL_ALIGN_RAW (maybe_dup);
11845 DECL_WARN_IF_NOT_ALIGN_RAW (defn)
11846 = DECL_WARN_IF_NOT_ALIGN_RAW (maybe_dup);
11847 DECL_USER_ALIGN (defn) = DECL_USER_ALIGN (maybe_dup);
11849 /* C++ pieces. */
11850 TYPE_POLYMORPHIC_P (type) = TYPE_POLYMORPHIC_P (type_dup);
11851 TYPE_HAS_USER_CONSTRUCTOR (type)
11852 = TYPE_HAS_USER_CONSTRUCTOR (type_dup);
11853 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
11854 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type_dup);
11856 if (auto ls = TYPE_LANG_SPECIFIC (type_dup))
11858 if (TYPE_LANG_SPECIFIC (type))
11860 CLASSTYPE_BEFRIENDING_CLASSES (type_dup)
11861 = CLASSTYPE_BEFRIENDING_CLASSES (type);
11862 if (!ANON_AGGR_TYPE_P (type))
11863 CLASSTYPE_TYPEINFO_VAR (type_dup)
11864 = CLASSTYPE_TYPEINFO_VAR (type);
11866 for (tree v = type; v; v = TYPE_NEXT_VARIANT (v))
11867 TYPE_LANG_SPECIFIC (v) = ls;
11871 TYPE_SIZE (type) = size;
11872 TYPE_SIZE_UNIT (type) = size_unit;
11874 if (fields)
11876 tree *chain = &TYPE_FIELDS (type);
11877 unsigned len = fields->length ();
11878 for (unsigned ix = 0; ix != len; ix++)
11880 tree decl = (*fields)[ix];
11882 if (!decl)
11884 /* An anonymous struct with typedef name. */
11885 tree tdef = (*fields)[ix+1];
11886 decl = TYPE_STUB_DECL (TREE_TYPE (tdef));
11887 gcc_checking_assert (IDENTIFIER_ANON_P (DECL_NAME (decl))
11888 && decl != tdef);
11891 gcc_checking_assert (!*chain == !DECL_CLONED_FUNCTION_P (decl));
11892 *chain = decl;
11893 chain = &DECL_CHAIN (decl);
11895 if (TREE_CODE (decl) == FIELD_DECL
11896 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11897 ANON_AGGR_TYPE_FIELD
11898 (TYPE_MAIN_VARIANT (TREE_TYPE (decl))) = decl;
11900 if (TREE_CODE (decl) == USING_DECL
11901 && TREE_CODE (USING_DECL_SCOPE (decl)) == RECORD_TYPE)
11903 /* Reconstruct DECL_ACCESS. */
11904 tree decls = USING_DECL_DECLS (decl);
11905 tree access = declared_access (decl);
11907 for (ovl_iterator iter (decls); iter; ++iter)
11909 tree d = *iter;
11911 retrofit_lang_decl (d);
11912 tree list = DECL_ACCESS (d);
11914 if (!purpose_member (type, list))
11915 DECL_ACCESS (d) = tree_cons (type, access, list);
11921 TYPE_VFIELD (type) = vfield;
11922 TYPE_BINFO (type) = binfo;
11924 if (TYPE_LANG_SPECIFIC (type))
11926 CLASSTYPE_LAMBDA_EXPR (type) = lambda;
11928 CLASSTYPE_MEMBER_VEC (type) = member_vec;
11929 CLASSTYPE_PURE_VIRTUALS (type) = pure_virts;
11930 CLASSTYPE_VCALL_INDICES (type) = vcall_indices;
11932 CLASSTYPE_KEY_METHOD (type) = key_method;
11934 CLASSTYPE_VBASECLASSES (type) = vbase_vec;
11936 /* Resort the member vector. */
11937 resort_type_member_vec (member_vec, NULL, nop, NULL);
11940 else if (maybe_dup)
11942 // FIXME:QOI Check matching defn
11945 if (TYPE_LANG_SPECIFIC (type))
11947 tree primary = tree_node ();
11948 tree as_base = tree_node ();
11950 if (as_base)
11951 as_base = TREE_TYPE (as_base);
11953 /* Read the vtables. */
11954 vec<tree, va_heap> *vtables = vec_chained_decls ();
11955 if (vtables)
11957 unsigned len = vtables->length ();
11958 for (unsigned ix = 0; ix != len; ix++)
11960 tree vtable = (*vtables)[ix];
11961 read_var_def (vtable, vtable);
11965 tree friend_classes = tree_list (false);
11966 tree friend_functions = NULL_TREE;
11967 for (tree *chain = &friend_functions;
11968 tree name = tree_node (); chain = &TREE_CHAIN (*chain))
11970 tree val = tree_list (false);
11971 *chain = build_tree_list (name, val);
11973 tree decl_list = tree_list (true);
11975 if (installing)
11977 CLASSTYPE_PRIMARY_BINFO (type) = primary;
11978 CLASSTYPE_AS_BASE (type) = as_base;
11980 if (vtables)
11982 if (!CLASSTYPE_KEY_METHOD (type)
11983 /* Sneaky user may have defined it inline
11984 out-of-class. */
11985 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type)))
11986 vec_safe_push (keyed_classes, type);
11987 unsigned len = vtables->length ();
11988 tree *chain = &CLASSTYPE_VTABLES (type);
11989 for (unsigned ix = 0; ix != len; ix++)
11991 tree vtable = (*vtables)[ix];
11992 gcc_checking_assert (!*chain);
11993 *chain = vtable;
11994 chain = &DECL_CHAIN (vtable);
11997 CLASSTYPE_FRIEND_CLASSES (type) = friend_classes;
11998 DECL_FRIENDLIST (defn) = friend_functions;
11999 CLASSTYPE_DECL_LIST (type) = decl_list;
12001 for (; friend_classes; friend_classes = TREE_CHAIN (friend_classes))
12003 tree f = TREE_VALUE (friend_classes);
12005 if (TYPE_P (f))
12007 CLASSTYPE_BEFRIENDING_CLASSES (f)
12008 = tree_cons (NULL_TREE, type,
12009 CLASSTYPE_BEFRIENDING_CLASSES (f));
12010 dump () && dump ("Class %N befriending %C:%N",
12011 type, TREE_CODE (f), f);
12015 for (; friend_functions;
12016 friend_functions = TREE_CHAIN (friend_functions))
12017 for (tree friend_decls = TREE_VALUE (friend_functions);
12018 friend_decls; friend_decls = TREE_CHAIN (friend_decls))
12020 tree f = TREE_VALUE (friend_decls);
12022 DECL_BEFRIENDING_CLASSES (f)
12023 = tree_cons (NULL_TREE, type, DECL_BEFRIENDING_CLASSES (f));
12024 dump () && dump ("Class %N befriending %C:%N",
12025 type, TREE_CODE (f), f);
12029 if (TYPE_CONTAINS_VPTR_P (type))
12030 /* Read and install the thunks. */
12031 while (tree vfunc = tree_node ())
12033 tree thunks = chained_decls ();
12034 if (installing)
12035 SET_DECL_THUNKS (vfunc, thunks);
12038 vec_free (vtables);
12041 /* Propagate to all variants. */
12042 if (installing)
12043 fixup_type_variants (type);
12045 /* IS_FAKE_BASE_TYPE is inaccurate at this point, because if this is
12046 the fake base, we've not hooked it into the containing class's
12047 data structure yet. Fortunately it has a unique name. */
12048 if (installing
12049 && DECL_NAME (defn) != as_base_identifier
12050 && (!CLASSTYPE_TEMPLATE_INFO (type)
12051 || !uses_template_parms (TI_ARGS (CLASSTYPE_TEMPLATE_INFO (type)))))
12052 /* Emit debug info. It'd be nice to know if the interface TU
12053 already emitted this. */
12054 rest_of_type_compilation (type, !LOCAL_CLASS_P (type));
12056 vec_free (fields);
12058 return !get_overrun ();
12061 void
12062 trees_out::write_enum_def (tree decl)
12064 tree type = TREE_TYPE (decl);
12066 tree_node (TYPE_VALUES (type));
12067 tree_node (TYPE_MIN_VALUE (type));
12068 tree_node (TYPE_MAX_VALUE (type));
12071 void
12072 trees_out::mark_enum_def (tree decl)
12074 tree type = TREE_TYPE (decl);
12076 for (tree values = TYPE_VALUES (type); values; values = TREE_CHAIN (values))
12078 tree cst = TREE_VALUE (values);
12079 mark_by_value (cst);
12080 /* We must mark the init to avoid circularity in tt_enum_int. */
12081 if (tree init = DECL_INITIAL (cst))
12082 if (TREE_CODE (init) == INTEGER_CST)
12083 mark_by_value (init);
12087 bool
12088 trees_in::read_enum_def (tree defn, tree maybe_template)
12090 tree type = TREE_TYPE (defn);
12091 tree values = tree_node ();
12092 tree min = tree_node ();
12093 tree max = tree_node ();
12095 if (get_overrun ())
12096 return false;
12098 tree maybe_dup = odr_duplicate (maybe_template, TYPE_VALUES (type));
12099 bool installing = maybe_dup && !TYPE_VALUES (type);
12101 if (installing)
12103 TYPE_VALUES (type) = values;
12104 TYPE_MIN_VALUE (type) = min;
12105 TYPE_MAX_VALUE (type) = max;
12107 rest_of_type_compilation (type, DECL_NAMESPACE_SCOPE_P (defn));
12109 else if (maybe_dup)
12111 tree known = TYPE_VALUES (type);
12112 for (; known && values;
12113 known = TREE_CHAIN (known), values = TREE_CHAIN (values))
12115 tree known_decl = TREE_VALUE (known);
12116 tree new_decl = TREE_VALUE (values);
12118 if (DECL_NAME (known_decl) != DECL_NAME (new_decl))
12119 goto bad;
12121 new_decl = maybe_duplicate (new_decl);
12123 if (!cp_tree_equal (DECL_INITIAL (known_decl),
12124 DECL_INITIAL (new_decl)))
12125 goto bad;
12128 if (known || values)
12129 goto bad;
12131 if (!cp_tree_equal (TYPE_MIN_VALUE (type), min)
12132 || !cp_tree_equal (TYPE_MAX_VALUE (type), max))
12134 bad:;
12135 error_at (DECL_SOURCE_LOCATION (maybe_dup),
12136 "definition of %qD does not match", maybe_dup);
12137 inform (DECL_SOURCE_LOCATION (defn),
12138 "existing definition %qD", defn);
12140 tree known_decl = NULL_TREE, new_decl = NULL_TREE;
12142 if (known)
12143 known_decl = TREE_VALUE (known);
12144 if (values)
12145 new_decl = maybe_duplicate (TREE_VALUE (values));
12147 if (known_decl && new_decl)
12149 inform (DECL_SOURCE_LOCATION (new_decl),
12150 "... this enumerator %qD", new_decl);
12151 inform (DECL_SOURCE_LOCATION (known_decl),
12152 "enumerator %qD does not match ...", known_decl);
12154 else if (known_decl || new_decl)
12156 tree extra = known_decl ? known_decl : new_decl;
12157 inform (DECL_SOURCE_LOCATION (extra),
12158 "additional enumerators beginning with %qD", extra);
12160 else
12161 inform (DECL_SOURCE_LOCATION (maybe_dup),
12162 "enumeration range differs");
12164 /* Mark it bad. */
12165 unmatched_duplicate (maybe_template);
12169 return true;
12172 /* Write out the body of DECL. See above circularity note. */
12174 void
12175 trees_out::write_definition (tree decl)
12177 if (streaming_p ())
12179 assert_definition (decl);
12180 dump ()
12181 && dump ("Writing definition %C:%N", TREE_CODE (decl), decl);
12183 else
12184 dump (dumper::DEPEND)
12185 && dump ("Depending definition %C:%N", TREE_CODE (decl), decl);
12187 again:
12188 switch (TREE_CODE (decl))
12190 default:
12191 gcc_unreachable ();
12193 case TEMPLATE_DECL:
12194 decl = DECL_TEMPLATE_RESULT (decl);
12195 goto again;
12197 case FUNCTION_DECL:
12198 write_function_def (decl);
12199 break;
12201 case TYPE_DECL:
12203 tree type = TREE_TYPE (decl);
12204 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12205 && TYPE_NAME (type) == decl);
12206 if (TREE_CODE (type) == ENUMERAL_TYPE)
12207 write_enum_def (decl);
12208 else
12209 write_class_def (decl);
12211 break;
12213 case VAR_DECL:
12214 case CONCEPT_DECL:
12215 write_var_def (decl);
12216 break;
12220 /* Mark a declaration for by-value walking. If DO_DEFN is true, mark
12221 its body too. */
12223 void
12224 trees_out::mark_declaration (tree decl, bool do_defn)
12226 mark_by_value (decl);
12228 if (TREE_CODE (decl) == TEMPLATE_DECL)
12229 decl = DECL_TEMPLATE_RESULT (decl);
12231 if (!do_defn)
12232 return;
12234 switch (TREE_CODE (decl))
12236 default:
12237 gcc_unreachable ();
12239 case FUNCTION_DECL:
12240 mark_function_def (decl);
12241 break;
12243 case TYPE_DECL:
12245 tree type = TREE_TYPE (decl);
12246 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12247 && TYPE_NAME (type) == decl);
12248 if (TREE_CODE (type) == ENUMERAL_TYPE)
12249 mark_enum_def (decl);
12250 else
12251 mark_class_def (decl);
12253 break;
12255 case VAR_DECL:
12256 case CONCEPT_DECL:
12257 mark_var_def (decl);
12258 break;
12262 /* Read in the body of DECL. See above circularity note. */
12264 bool
12265 trees_in::read_definition (tree decl)
12267 dump () && dump ("Reading definition %C %N", TREE_CODE (decl), decl);
12269 tree maybe_template = decl;
12271 again:
12272 switch (TREE_CODE (decl))
12274 default:
12275 break;
12277 case TEMPLATE_DECL:
12278 decl = DECL_TEMPLATE_RESULT (decl);
12279 goto again;
12281 case FUNCTION_DECL:
12282 return read_function_def (decl, maybe_template);
12284 case TYPE_DECL:
12286 tree type = TREE_TYPE (decl);
12287 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12288 && TYPE_NAME (type) == decl);
12289 if (TREE_CODE (type) == ENUMERAL_TYPE)
12290 return read_enum_def (decl, maybe_template);
12291 else
12292 return read_class_def (decl, maybe_template);
12294 break;
12296 case VAR_DECL:
12297 case CONCEPT_DECL:
12298 return read_var_def (decl, maybe_template);
12301 return false;
12304 /* Lookup an maybe insert a slot for depset for KEY. */
12306 depset **
12307 depset::hash::entity_slot (tree entity, bool insert)
12309 traits::compare_type key (entity, NULL);
12310 depset **slot = find_slot_with_hash (key, traits::hash (key),
12311 insert ? INSERT : NO_INSERT);
12313 return slot;
12316 depset **
12317 depset::hash::binding_slot (tree ctx, tree name, bool insert)
12319 traits::compare_type key (ctx, name);
12320 depset **slot = find_slot_with_hash (key, traits::hash (key),
12321 insert ? INSERT : NO_INSERT);
12323 return slot;
12326 depset *
12327 depset::hash::find_dependency (tree decl)
12329 depset **slot = entity_slot (decl, false);
12331 return slot ? *slot : NULL;
12334 depset *
12335 depset::hash::find_binding (tree ctx, tree name)
12337 depset **slot = binding_slot (ctx, name, false);
12339 return slot ? *slot : NULL;
12342 /* DECL is a newly discovered dependency. Create the depset, if it
12343 doesn't already exist. Add it to the worklist if so.
12345 DECL will be an OVL_USING_P OVERLOAD, if it's from a binding that's
12346 a using decl.
12348 We do not have to worry about adding the same dependency more than
12349 once. First it's harmless, but secondly the TREE_VISITED marking
12350 prevents us wanting to do it anyway. */
12352 depset *
12353 depset::hash::make_dependency (tree decl, entity_kind ek)
12355 /* Make sure we're being told consistent information. */
12356 gcc_checking_assert ((ek == EK_NAMESPACE)
12357 == (TREE_CODE (decl) == NAMESPACE_DECL
12358 && !DECL_NAMESPACE_ALIAS (decl)));
12359 gcc_checking_assert (ek != EK_BINDING && ek != EK_REDIRECT);
12360 gcc_checking_assert (TREE_CODE (decl) != FIELD_DECL
12361 && (TREE_CODE (decl) != USING_DECL
12362 || TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL));
12363 gcc_checking_assert (!is_key_order ());
12364 if (ek == EK_USING)
12365 gcc_checking_assert (TREE_CODE (decl) == OVERLOAD);
12367 if (TREE_CODE (decl) == TEMPLATE_DECL)
12368 /* The template should have copied these from its result decl. */
12369 gcc_checking_assert (DECL_MODULE_EXPORT_P (decl)
12370 == DECL_MODULE_EXPORT_P (DECL_TEMPLATE_RESULT (decl)));
12372 depset **slot = entity_slot (decl, true);
12373 depset *dep = *slot;
12374 bool for_binding = ek == EK_FOR_BINDING;
12376 if (!dep)
12378 if (DECL_IMPLICIT_TYPEDEF_P (decl)
12379 /* ... not an enum, for instance. */
12380 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl))
12381 && TYPE_LANG_SPECIFIC (TREE_TYPE (decl))
12382 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
12384 /* A partial or explicit specialization. Partial
12385 specializations might not be in the hash table, because
12386 there can be multiple differently-constrained variants.
12388 template<typename T> class silly;
12389 template<typename T> requires true class silly {};
12391 We need to find them, insert their TEMPLATE_DECL in the
12392 dep_hash, and then convert the dep we just found into a
12393 redirect. */
12395 tree ti = TYPE_TEMPLATE_INFO (TREE_TYPE (decl));
12396 tree tmpl = TI_TEMPLATE (ti);
12397 tree partial = NULL_TREE;
12398 for (tree spec = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
12399 spec; spec = TREE_CHAIN (spec))
12400 if (DECL_TEMPLATE_RESULT (TREE_VALUE (spec)) == decl)
12402 partial = TREE_VALUE (spec);
12403 break;
12406 if (partial)
12408 /* Eagerly create an empty redirect. The following
12409 make_dependency call could cause hash reallocation,
12410 and invalidate slot's value. */
12411 depset *redirect = make_entity (decl, EK_REDIRECT);
12413 /* Redirects are never reached -- always snap to their target. */
12414 redirect->set_flag_bit<DB_UNREACHED_BIT> ();
12416 *slot = redirect;
12418 depset *tmpl_dep = make_dependency (partial, EK_PARTIAL);
12419 gcc_checking_assert (tmpl_dep->get_entity_kind () == EK_PARTIAL);
12421 redirect->deps.safe_push (tmpl_dep);
12423 return redirect;
12427 bool has_def = ek != EK_USING && has_definition (decl);
12428 if (ek > EK_BINDING)
12429 ek = EK_DECL;
12431 /* The only OVERLOADS we should see are USING decls from
12432 bindings. */
12433 *slot = dep = make_entity (decl, ek, has_def);
12435 if (TREE_CODE (decl) == TEMPLATE_DECL)
12437 if (DECL_ALIAS_TEMPLATE_P (decl) && DECL_TEMPLATE_INFO (decl))
12438 dep->set_flag_bit<DB_ALIAS_TMPL_INST_BIT> ();
12439 else if (CHECKING_P)
12440 /* The template_result should otherwise not be in the
12441 table, or be an empty redirect (created above). */
12442 if (auto *eslot = entity_slot (DECL_TEMPLATE_RESULT (decl), false))
12443 gcc_checking_assert ((*eslot)->get_entity_kind () == EK_REDIRECT
12444 && !(*eslot)->deps.length ());
12447 if (ek != EK_USING)
12449 tree not_tmpl = STRIP_TEMPLATE (decl);
12451 if (DECL_LANG_SPECIFIC (not_tmpl)
12452 && DECL_MODULE_IMPORT_P (not_tmpl))
12454 /* Store the module number and index in cluster/section,
12455 so we don't have to look them up again. */
12456 unsigned index = import_entity_index (decl);
12457 module_state *from = import_entity_module (index);
12458 /* Remap will be zero for imports from partitions, which
12459 we want to treat as-if declared in this TU. */
12460 if (from->remap)
12462 dep->cluster = index - from->entity_lwm;
12463 dep->section = from->remap;
12464 dep->set_flag_bit<DB_IMPORTED_BIT> ();
12468 if (ek == EK_DECL
12469 && !dep->is_import ()
12470 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL
12471 && !(TREE_CODE (decl) == TEMPLATE_DECL
12472 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl)))
12474 tree ctx = CP_DECL_CONTEXT (decl);
12476 if (!TREE_PUBLIC (ctx))
12477 /* Member of internal namespace. */
12478 dep->set_flag_bit<DB_IS_INTERNAL_BIT> ();
12479 else if (VAR_OR_FUNCTION_DECL_P (not_tmpl)
12480 && DECL_THIS_STATIC (not_tmpl))
12482 /* An internal decl. This is ok in a GM entity. */
12483 if (!(header_module_p ()
12484 || !DECL_LANG_SPECIFIC (not_tmpl)
12485 || !DECL_MODULE_PURVIEW_P (not_tmpl)))
12486 dep->set_flag_bit<DB_IS_INTERNAL_BIT> ();
12491 if (!dep->is_import ())
12492 worklist.safe_push (dep);
12495 dump (dumper::DEPEND)
12496 && dump ("%s on %s %C:%N found",
12497 ek == EK_REDIRECT ? "Redirect"
12498 : for_binding ? "Binding" : "Dependency",
12499 dep->entity_kind_name (), TREE_CODE (decl), decl);
12501 return dep;
12504 /* DEP is a newly discovered dependency. Append it to current's
12505 depset. */
12507 void
12508 depset::hash::add_dependency (depset *dep)
12510 gcc_checking_assert (current && !is_key_order ());
12511 current->deps.safe_push (dep);
12513 if (dep->is_internal () && !current->is_internal ())
12514 current->set_flag_bit<DB_REFS_INTERNAL_BIT> ();
12516 if (current->get_entity_kind () == EK_USING
12517 && DECL_IMPLICIT_TYPEDEF_P (dep->get_entity ())
12518 && TREE_CODE (TREE_TYPE (dep->get_entity ())) == ENUMERAL_TYPE)
12520 /* CURRENT is an unwrapped using-decl and DECL is an enum's
12521 implicit typedef. Is CURRENT a member of the enum? */
12522 tree c_decl = OVL_FUNCTION (current->get_entity ());
12524 if (TREE_CODE (c_decl) == CONST_DECL
12525 && (current->deps[0]->get_entity ()
12526 == CP_DECL_CONTEXT (dep->get_entity ())))
12527 /* Make DECL depend on CURRENT. */
12528 dep->deps.safe_push (current);
12531 if (dep->is_unreached ())
12533 /* The dependency is reachable now. */
12534 reached_unreached = true;
12535 dep->clear_flag_bit<DB_UNREACHED_BIT> ();
12536 dump (dumper::DEPEND)
12537 && dump ("Reaching unreached %s %C:%N", dep->entity_kind_name (),
12538 TREE_CODE (dep->get_entity ()), dep->get_entity ());
12542 depset *
12543 depset::hash::add_dependency (tree decl, entity_kind ek)
12545 depset *dep;
12547 if (is_key_order ())
12549 dep = find_dependency (decl);
12550 if (dep)
12552 current->deps.safe_push (dep);
12553 dump (dumper::MERGE)
12554 && dump ("Key dependency on %s %C:%N found",
12555 dep->entity_kind_name (), TREE_CODE (decl), decl);
12557 else
12559 /* It's not a mergeable decl, look for it in the original
12560 table. */
12561 dep = chain->find_dependency (decl);
12562 gcc_checking_assert (dep);
12565 else
12567 dep = make_dependency (decl, ek);
12568 if (dep->get_entity_kind () != EK_REDIRECT)
12569 add_dependency (dep);
12572 return dep;
12575 void
12576 depset::hash::add_namespace_context (depset *dep, tree ns)
12578 depset *ns_dep = make_dependency (ns, depset::EK_NAMESPACE);
12579 dep->deps.safe_push (ns_dep);
12581 /* Mark it as special if imported so we don't walk connect when
12582 SCCing. */
12583 if (!dep->is_binding () && ns_dep->is_import ())
12584 dep->set_special ();
12587 struct add_binding_data
12589 tree ns;
12590 bitmap partitions;
12591 depset *binding;
12592 depset::hash *hash;
12593 bool met_namespace;
12596 /* Return true if we are, or contain something that is exported. */
12598 bool
12599 depset::hash::add_binding_entity (tree decl, WMB_Flags flags, void *data_)
12601 auto data = static_cast <add_binding_data *> (data_);
12603 if (!(TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl)))
12605 tree inner = decl;
12607 if (TREE_CODE (inner) == CONST_DECL
12608 && TREE_CODE (DECL_CONTEXT (inner)) == ENUMERAL_TYPE)
12609 inner = TYPE_NAME (DECL_CONTEXT (inner));
12610 else if (TREE_CODE (inner) == TEMPLATE_DECL)
12611 inner = DECL_TEMPLATE_RESULT (inner);
12613 if (!DECL_LANG_SPECIFIC (inner) || !DECL_MODULE_PURVIEW_P (inner))
12614 /* Ignore global module fragment entities. */
12615 return false;
12617 if (VAR_OR_FUNCTION_DECL_P (inner)
12618 && DECL_THIS_STATIC (inner))
12620 if (!header_module_p ())
12621 /* Ignore internal-linkage entitites. */
12622 return false;
12625 if ((TREE_CODE (decl) == VAR_DECL
12626 || TREE_CODE (decl) == TYPE_DECL)
12627 && DECL_TINFO_P (decl))
12628 /* Ignore TINFO things. */
12629 return false;
12631 if (!(flags & WMB_Using) && CP_DECL_CONTEXT (decl) != data->ns)
12633 /* A using that lost its wrapper or an unscoped enum
12634 constant. */
12635 flags = WMB_Flags (flags | WMB_Using);
12636 if (DECL_MODULE_EXPORT_P (TREE_CODE (decl) == CONST_DECL
12637 ? TYPE_NAME (TREE_TYPE (decl))
12638 : STRIP_TEMPLATE (decl)))
12639 flags = WMB_Flags (flags | WMB_Export);
12642 if (!data->binding)
12643 /* No binding to check. */;
12644 else if (flags & WMB_Using)
12646 /* Look in the binding to see if we already have this
12647 using. */
12648 for (unsigned ix = data->binding->deps.length (); --ix;)
12650 depset *d = data->binding->deps[ix];
12651 if (d->get_entity_kind () == EK_USING
12652 && OVL_FUNCTION (d->get_entity ()) == decl)
12654 if (!(flags & WMB_Hidden))
12655 d->clear_hidden_binding ();
12656 if (flags & WMB_Export)
12657 OVL_EXPORT_P (d->get_entity ()) = true;
12658 return bool (flags & WMB_Export);
12662 else if (flags & WMB_Dups)
12664 /* Look in the binding to see if we already have this decl. */
12665 for (unsigned ix = data->binding->deps.length (); --ix;)
12667 depset *d = data->binding->deps[ix];
12668 if (d->get_entity () == decl)
12670 if (!(flags & WMB_Hidden))
12671 d->clear_hidden_binding ();
12672 return false;
12677 /* We're adding something. */
12678 if (!data->binding)
12680 data->binding = make_binding (data->ns, DECL_NAME (decl));
12681 data->hash->add_namespace_context (data->binding, data->ns);
12683 depset **slot = data->hash->binding_slot (data->ns,
12684 DECL_NAME (decl), true);
12685 gcc_checking_assert (!*slot);
12686 *slot = data->binding;
12689 /* Make sure nobody left a tree visited lying about. */
12690 gcc_checking_assert (!TREE_VISITED (decl));
12692 if (flags & WMB_Using)
12694 decl = ovl_make (decl, NULL_TREE);
12695 if (flags & WMB_Export)
12696 OVL_EXPORT_P (decl) = true;
12699 depset *dep = data->hash->make_dependency
12700 (decl, flags & WMB_Using ? EK_USING : EK_FOR_BINDING);
12701 if (flags & WMB_Hidden)
12702 dep->set_hidden_binding ();
12703 data->binding->deps.safe_push (dep);
12704 /* Binding and contents are mutually dependent. */
12705 dep->deps.safe_push (data->binding);
12707 return (flags & WMB_Using
12708 ? flags & WMB_Export : DECL_MODULE_EXPORT_P (decl));
12710 else if (DECL_NAME (decl) && !data->met_namespace)
12712 /* Namespace, walk exactly once. */
12713 gcc_checking_assert (TREE_PUBLIC (decl));
12714 data->met_namespace = true;
12715 if (data->hash->add_namespace_entities (decl, data->partitions))
12717 /* It contains an exported thing, so it is exported. */
12718 gcc_checking_assert (DECL_MODULE_PURVIEW_P (decl));
12719 DECL_MODULE_EXPORT_P (decl) = true;
12722 if (DECL_MODULE_PURVIEW_P (decl))
12724 data->hash->make_dependency (decl, depset::EK_NAMESPACE);
12726 return DECL_MODULE_EXPORT_P (decl);
12730 return false;
12733 /* Recursively find all the namespace bindings of NS. Add a depset
12734 for every binding that contains an export or module-linkage entity.
12735 Add a defining depset for every such decl that we need to write a
12736 definition. Such defining depsets depend on the binding depset.
12737 Returns true if we contain something exported. */
12739 bool
12740 depset::hash::add_namespace_entities (tree ns, bitmap partitions)
12742 dump () && dump ("Looking for writables in %N", ns);
12743 dump.indent ();
12745 unsigned count = 0;
12746 add_binding_data data;
12747 data.ns = ns;
12748 data.partitions = partitions;
12749 data.hash = this;
12751 hash_table<named_decl_hash>::iterator end
12752 (DECL_NAMESPACE_BINDINGS (ns)->end ());
12753 for (hash_table<named_decl_hash>::iterator iter
12754 (DECL_NAMESPACE_BINDINGS (ns)->begin ()); iter != end; ++iter)
12756 data.binding = nullptr;
12757 data.met_namespace = false;
12758 if (walk_module_binding (*iter, partitions, add_binding_entity, &data))
12759 count++;
12762 if (count)
12763 dump () && dump ("Found %u entries", count);
12764 dump.outdent ();
12766 return count != 0;
12769 void
12770 depset::hash::add_partial_entities (vec<tree, va_gc> *partial_classes)
12772 for (unsigned ix = 0; ix != partial_classes->length (); ix++)
12774 tree inner = (*partial_classes)[ix];
12776 depset *dep = make_dependency (inner, depset::EK_DECL);
12778 if (dep->get_entity_kind () == depset::EK_REDIRECT)
12779 /* We should have recorded the template as a partial
12780 specialization. */
12781 gcc_checking_assert (dep->deps[0]->get_entity_kind ()
12782 == depset::EK_PARTIAL);
12783 else
12784 /* It was an explicit specialization, not a partial one. */
12785 gcc_checking_assert (dep->get_entity_kind ()
12786 == depset::EK_SPECIALIZATION);
12790 /* Add the members of imported classes that we defined in this TU.
12791 This will also include lazily created implicit member function
12792 declarations. (All others will be definitions.) */
12794 void
12795 depset::hash::add_class_entities (vec<tree, va_gc> *class_members)
12797 for (unsigned ix = 0; ix != class_members->length (); ix++)
12799 tree defn = (*class_members)[ix];
12800 depset *dep = make_dependency (defn, EK_INNER_DECL);
12802 if (dep->get_entity_kind () == EK_REDIRECT)
12803 dep = dep->deps[0];
12805 /* Only non-instantiations need marking as members. */
12806 if (dep->get_entity_kind () == EK_DECL)
12807 dep->set_flag_bit <DB_IS_MEMBER_BIT> ();
12811 /* We add the partial & explicit specializations, and the explicit
12812 instantiations. */
12814 static void
12815 specialization_add (bool decl_p, spec_entry *entry, void *data_)
12817 vec<spec_entry *> *data = reinterpret_cast <vec<spec_entry *> *> (data_);
12819 if (!decl_p)
12821 /* We exclusively use decls to locate things. Make sure there's
12822 no mismatch between the two specialization tables we keep.
12823 pt.c optimizes instantiation lookup using a complicated
12824 heuristic. We don't attempt to replicate that algorithm, but
12825 observe its behaviour and reproduce it upon read back. */
12827 gcc_checking_assert (DECL_ALIAS_TEMPLATE_P (entry->tmpl)
12828 || TREE_CODE (entry->spec) == ENUMERAL_TYPE
12829 || DECL_CLASS_TEMPLATE_P (entry->tmpl));
12831 /* Only alias templates can appear in both tables (and
12832 if they're in the type table they must also be in the decl
12833 table). */
12834 gcc_checking_assert
12835 (!match_mergeable_specialization (true, entry)
12836 == !DECL_ALIAS_TEMPLATE_P (entry->tmpl));
12838 else if (VAR_OR_FUNCTION_DECL_P (entry->spec))
12839 gcc_checking_assert (!DECL_LOCAL_DECL_P (entry->spec));
12841 data->safe_push (entry);
12844 /* Arbitrary stable comparison. */
12846 static int
12847 specialization_cmp (const void *a_, const void *b_)
12849 const spec_entry *ea = *reinterpret_cast<const spec_entry *const *> (a_);
12850 const spec_entry *eb = *reinterpret_cast<const spec_entry *const *> (b_);
12852 if (ea == eb)
12853 return 0;
12855 tree a = ea->spec;
12856 tree b = eb->spec;
12857 if (TYPE_P (a))
12859 a = TYPE_NAME (a);
12860 b = TYPE_NAME (b);
12863 if (a == b)
12864 /* This can happen with friend specializations. Just order by
12865 entry address. See note in depset_cmp. */
12866 return ea < eb ? -1 : +1;
12868 return DECL_UID (a) < DECL_UID (b) ? -1 : +1;
12871 /* We add all kinds of specialializations. Implicit specializations
12872 should only streamed and walked if they are reachable from
12873 elsewhere. Hence the UNREACHED flag. This is making the
12874 assumption that it is cheaper to reinstantiate them on demand
12875 elsewhere, rather than stream them in when we instantiate their
12876 general template. Also, if we do stream them, we can only do that
12877 if they are not internal (which they can become if they themselves
12878 touch an internal entity?). */
12880 void
12881 depset::hash::add_specializations (bool decl_p)
12883 vec<spec_entry *> data;
12884 data.create (100);
12885 walk_specializations (decl_p, specialization_add, &data);
12886 data.qsort (specialization_cmp);
12887 while (data.length ())
12889 spec_entry *entry = data.pop ();
12890 tree spec = entry->spec;
12891 int use_tpl = 0;
12892 bool is_alias = false;
12893 bool is_friend = false;
12895 if (decl_p && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (entry->tmpl))
12896 /* A friend of a template. This is keyed to the
12897 instantiation. */
12898 is_friend = true;
12900 if (!decl_p && DECL_ALIAS_TEMPLATE_P (entry->tmpl))
12902 spec = TYPE_NAME (spec);
12903 is_alias = true;
12906 if (decl_p || is_alias)
12908 if (tree ti = DECL_TEMPLATE_INFO (spec))
12910 tree tmpl = TI_TEMPLATE (ti);
12912 use_tpl = DECL_USE_TEMPLATE (spec);
12913 if (spec == DECL_TEMPLATE_RESULT (tmpl))
12915 spec = tmpl;
12916 gcc_checking_assert (DECL_USE_TEMPLATE (spec) == use_tpl);
12918 else if (is_friend)
12920 if (TI_TEMPLATE (ti) != entry->tmpl
12921 || !template_args_equal (TI_ARGS (ti), entry->tmpl))
12922 goto template_friend;
12925 else
12927 template_friend:;
12928 gcc_checking_assert (is_friend);
12929 /* This is a friend of a template class, but not the one
12930 that generated entry->spec itself (i.e. it's an
12931 equivalent clone). We do not need to record
12932 this. */
12933 continue;
12936 else
12938 if (TREE_CODE (spec) == ENUMERAL_TYPE)
12940 tree ctx = DECL_CONTEXT (TYPE_NAME (spec));
12942 if (TYPE_P (ctx))
12943 use_tpl = CLASSTYPE_USE_TEMPLATE (ctx);
12944 else
12945 use_tpl = DECL_USE_TEMPLATE (ctx);
12947 else
12948 use_tpl = CLASSTYPE_USE_TEMPLATE (spec);
12950 tree ti = TYPE_TEMPLATE_INFO (spec);
12951 tree tmpl = TI_TEMPLATE (ti);
12953 spec = TYPE_NAME (spec);
12954 if (spec == DECL_TEMPLATE_RESULT (tmpl))
12956 spec = tmpl;
12957 use_tpl = DECL_USE_TEMPLATE (spec);
12961 bool needs_reaching = false;
12962 if (use_tpl == 1)
12963 /* Implicit instantiations only walked if we reach them. */
12964 needs_reaching = true;
12965 else if (!DECL_LANG_SPECIFIC (spec)
12966 || !DECL_MODULE_PURVIEW_P (spec))
12967 /* Likewise, GMF explicit or partial specializations. */
12968 needs_reaching = true;
12970 #if false && CHECKING_P
12971 /* The instantiation isn't always on
12972 DECL_TEMPLATE_INSTANTIATIONS, */
12973 // FIXME: we probably need to remember this information?
12974 /* Verify the specialization is on the
12975 DECL_TEMPLATE_INSTANTIATIONS of the template. */
12976 for (tree cons = DECL_TEMPLATE_INSTANTIATIONS (entry->tmpl);
12977 cons; cons = TREE_CHAIN (cons))
12978 if (TREE_VALUE (cons) == entry->spec)
12980 gcc_assert (entry->args == TREE_PURPOSE (cons));
12981 goto have_spec;
12983 gcc_unreachable ();
12984 have_spec:;
12985 #endif
12987 /* Make sure nobody left a tree visited lying about. */
12988 gcc_checking_assert (!TREE_VISITED (spec));
12989 depset *dep = make_dependency (spec, depset::EK_SPECIALIZATION);
12990 if (dep->is_special ())
12992 /* An already located specialization, this must be the TYPE
12993 corresponding to an alias_decl we found in the decl
12994 table. */
12995 spec_entry *other = reinterpret_cast <spec_entry *> (dep->deps[0]);
12996 gcc_checking_assert (!decl_p && is_alias && !dep->is_type_spec ());
12997 gcc_checking_assert (other->tmpl == entry->tmpl
12998 && template_args_equal (other->args, entry->args)
12999 && TREE_TYPE (other->spec) == entry->spec);
13000 dep->set_flag_bit<DB_ALIAS_SPEC_BIT> ();
13002 else
13004 gcc_checking_assert (decl_p || !is_alias);
13005 if (dep->get_entity_kind () == depset::EK_REDIRECT)
13006 dep = dep->deps[0];
13007 else if (dep->get_entity_kind () == depset::EK_SPECIALIZATION)
13009 dep->set_special ();
13010 dep->deps.safe_push (reinterpret_cast<depset *> (entry));
13011 if (!decl_p)
13012 dep->set_flag_bit<DB_TYPE_SPEC_BIT> ();
13015 if (needs_reaching)
13016 dep->set_flag_bit<DB_UNREACHED_BIT> ();
13017 if (is_friend)
13018 dep->set_flag_bit<DB_FRIEND_SPEC_BIT> ();
13021 data.release ();
13024 /* Add a depset into the mergeable hash. */
13026 void
13027 depset::hash::add_mergeable (depset *mergeable)
13029 gcc_checking_assert (is_key_order ());
13030 entity_kind ek = mergeable->get_entity_kind ();
13031 tree decl = mergeable->get_entity ();
13032 gcc_checking_assert (ek < EK_DIRECT_HWM);
13034 depset **slot = entity_slot (decl, true);
13035 gcc_checking_assert (!*slot);
13036 depset *dep = make_entity (decl, ek);
13037 *slot = dep;
13039 worklist.safe_push (dep);
13041 /* So we can locate the mergeable depset this depset refers to,
13042 mark the first dep. */
13043 dep->set_special ();
13044 dep->deps.safe_push (mergeable);
13047 /* Find the innermost-namespace scope of DECL, and that
13048 namespace-scope decl. */
13050 tree
13051 find_pending_key (tree decl, tree *decl_p = nullptr)
13053 tree ns = decl;
13056 decl = ns;
13057 ns = CP_DECL_CONTEXT (ns);
13058 if (TYPE_P (ns))
13059 ns = TYPE_NAME (ns);
13061 while (TREE_CODE (ns) != NAMESPACE_DECL);
13063 if (decl_p)
13064 *decl_p = decl;
13066 return ns;
13069 /* Iteratively find dependencies. During the walk we may find more
13070 entries on the same binding that need walking. */
13072 void
13073 depset::hash::find_dependencies (module_state *module)
13075 trees_out walker (NULL, module, *this);
13076 vec<depset *> unreached;
13077 unreached.create (worklist.length ());
13079 for (;;)
13081 reached_unreached = false;
13082 while (worklist.length ())
13084 depset *item = worklist.pop ();
13086 gcc_checking_assert (!item->is_binding ());
13087 if (item->is_unreached ())
13088 unreached.quick_push (item);
13089 else
13091 current = item;
13092 tree decl = current->get_entity ();
13093 dump (is_key_order () ? dumper::MERGE : dumper::DEPEND)
13094 && dump ("Dependencies of %s %C:%N",
13095 is_key_order () ? "key-order"
13096 : current->entity_kind_name (), TREE_CODE (decl), decl);
13097 dump.indent ();
13098 walker.begin ();
13099 if (current->get_entity_kind () == EK_USING)
13100 walker.tree_node (OVL_FUNCTION (decl));
13101 else if (TREE_VISITED (decl))
13102 /* A global tree. */;
13103 else if (item->get_entity_kind () == EK_NAMESPACE)
13104 add_namespace_context (current, CP_DECL_CONTEXT (decl));
13105 else
13107 walker.mark_declaration (decl, current->has_defn ());
13109 if (!walker.is_key_order ()
13110 && (item->get_entity_kind () == EK_SPECIALIZATION
13111 || item->get_entity_kind () == EK_PARTIAL
13112 || (item->get_entity_kind () == EK_DECL
13113 && item->is_member ())))
13115 tree ns = find_pending_key (decl, nullptr);
13116 add_namespace_context (item, ns);
13119 // FIXME: Perhaps p1815 makes this redundant? Or at
13120 // least simplifies it. Voldemort types are only
13121 // ever emissable when containing (inline) function
13122 // definition is emitted?
13123 /* Turn the Sneakoscope on when depending the decl. */
13124 sneakoscope = true;
13125 walker.decl_value (decl, current);
13126 sneakoscope = false;
13127 if (current->has_defn ())
13128 walker.write_definition (decl);
13130 walker.end ();
13132 if (!walker.is_key_order ()
13133 && TREE_CODE (decl) == TEMPLATE_DECL
13134 && !DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
13135 /* Mark all the explicit & partial specializations as
13136 reachable. */
13137 for (tree cons = DECL_TEMPLATE_INSTANTIATIONS (decl);
13138 cons; cons = TREE_CHAIN (cons))
13140 tree spec = TREE_VALUE (cons);
13141 if (TYPE_P (spec))
13142 spec = TYPE_NAME (spec);
13143 int use_tpl;
13144 node_template_info (spec, use_tpl);
13145 if (use_tpl & 2)
13147 depset *spec_dep = find_dependency (spec);
13148 if (spec_dep->get_entity_kind () == EK_REDIRECT)
13149 spec_dep = spec_dep->deps[0];
13150 if (spec_dep->is_unreached ())
13152 reached_unreached = true;
13153 spec_dep->clear_flag_bit<DB_UNREACHED_BIT> ();
13154 dump (dumper::DEPEND)
13155 && dump ("Reaching unreached specialization"
13156 " %C:%N", TREE_CODE (spec), spec);
13161 dump.outdent ();
13162 current = NULL;
13166 if (!reached_unreached)
13167 break;
13169 /* It's possible the we reached the unreached before we
13170 processed it in the above loop, so we'll be doing this an
13171 extra time. However, to avoid that we have to do some
13172 bit shuffling that also involves a scan of the list.
13173 Swings & roundabouts I guess. */
13174 std::swap (worklist, unreached);
13177 unreached.release ();
13180 /* Compare two entries of a single binding. TYPE_DECL before
13181 non-exported before exported. */
13183 static int
13184 binding_cmp (const void *a_, const void *b_)
13186 depset *a = *(depset *const *)a_;
13187 depset *b = *(depset *const *)b_;
13189 tree a_ent = a->get_entity ();
13190 tree b_ent = b->get_entity ();
13191 gcc_checking_assert (a_ent != b_ent
13192 && !a->is_binding ()
13193 && !b->is_binding ());
13195 /* Implicit typedefs come first. */
13196 bool a_implicit = DECL_IMPLICIT_TYPEDEF_P (a_ent);
13197 bool b_implicit = DECL_IMPLICIT_TYPEDEF_P (b_ent);
13198 if (a_implicit || b_implicit)
13200 /* A binding with two implicit type decls? That's unpossible! */
13201 gcc_checking_assert (!(a_implicit && b_implicit));
13202 return a_implicit ? -1 : +1; /* Implicit first. */
13205 /* Hidden before non-hidden. */
13206 bool a_hidden = a->is_hidden ();
13207 bool b_hidden = b->is_hidden ();
13208 if (a_hidden != b_hidden)
13209 return a_hidden ? -1 : +1;
13211 bool a_using = a->get_entity_kind () == depset::EK_USING;
13212 bool a_export;
13213 if (a_using)
13215 a_export = OVL_EXPORT_P (a_ent);
13216 a_ent = OVL_FUNCTION (a_ent);
13218 else
13219 a_export = DECL_MODULE_EXPORT_P (TREE_CODE (a_ent) == CONST_DECL
13220 ? TYPE_NAME (TREE_TYPE (a_ent))
13221 : STRIP_TEMPLATE (a_ent));
13223 bool b_using = b->get_entity_kind () == depset::EK_USING;
13224 bool b_export;
13225 if (b_using)
13227 b_export = OVL_EXPORT_P (b_ent);
13228 b_ent = OVL_FUNCTION (b_ent);
13230 else
13231 b_export = DECL_MODULE_EXPORT_P (TREE_CODE (b_ent) == CONST_DECL
13232 ? TYPE_NAME (TREE_TYPE (b_ent))
13233 : STRIP_TEMPLATE (b_ent));
13235 /* Non-exports before exports. */
13236 if (a_export != b_export)
13237 return a_export ? +1 : -1;
13239 /* At this point we don't care, but want a stable sort. */
13241 if (a_using != b_using)
13242 /* using first. */
13243 return a_using? -1 : +1;
13245 return DECL_UID (a_ent) < DECL_UID (b_ent) ? -1 : +1;
13248 /* Sort the bindings, issue errors about bad internal refs. */
13250 bool
13251 depset::hash::finalize_dependencies ()
13253 bool ok = true;
13254 depset::hash::iterator end (this->end ());
13255 for (depset::hash::iterator iter (begin ()); iter != end; ++iter)
13257 depset *dep = *iter;
13258 if (dep->is_binding ())
13260 /* Keep the containing namespace dep first. */
13261 gcc_checking_assert (dep->deps.length () > 1
13262 && (dep->deps[0]->get_entity_kind ()
13263 == EK_NAMESPACE)
13264 && (dep->deps[0]->get_entity ()
13265 == dep->get_entity ()));
13266 if (dep->deps.length () > 2)
13267 gcc_qsort (&dep->deps[1], dep->deps.length () - 1,
13268 sizeof (dep->deps[1]), binding_cmp);
13270 else if (dep->refs_internal ())
13272 for (unsigned ix = dep->deps.length (); ix--;)
13274 depset *rdep = dep->deps[ix];
13275 if (rdep->is_internal ())
13277 // FIXME:QOI Better location information? We're
13278 // losing, so it doesn't matter about efficiency
13279 tree decl = dep->get_entity ();
13280 error_at (DECL_SOURCE_LOCATION (decl),
13281 "%q#D references internal linkage entity %q#D",
13282 decl, rdep->get_entity ());
13283 break;
13286 ok = false;
13290 return ok;
13293 /* Core of TARJAN's algorithm to find Strongly Connected Components
13294 within a graph. See https://en.wikipedia.org/wiki/
13295 Tarjan%27s_strongly_connected_components_algorithm for details.
13297 We use depset::section as lowlink. Completed nodes have
13298 depset::cluster containing the cluster number, with the top
13299 bit set.
13301 A useful property is that the output vector is a reverse
13302 topological sort of the resulting DAG. In our case that means
13303 dependent SCCs are found before their dependers. We make use of
13304 that property. */
13306 void
13307 depset::tarjan::connect (depset *v)
13309 gcc_checking_assert (v->is_binding ()
13310 || !(v->is_unreached () || v->is_import ()));
13312 v->cluster = v->section = ++index;
13313 stack.safe_push (v);
13315 /* Walk all our dependencies, ignore a first marked slot */
13316 for (unsigned ix = v->is_special (); ix != v->deps.length (); ix++)
13318 depset *dep = v->deps[ix];
13320 if (dep->is_binding () || !dep->is_import ())
13322 unsigned lwm = dep->cluster;
13324 if (!dep->cluster)
13326 /* A new node. Connect it. */
13327 connect (dep);
13328 lwm = dep->section;
13331 if (dep->section && v->section > lwm)
13332 v->section = lwm;
13336 if (v->section == v->cluster)
13338 /* Root of a new SCC. Push all the members onto the result list. */
13339 unsigned num = v->cluster;
13340 depset *p;
13343 p = stack.pop ();
13344 p->cluster = num;
13345 p->section = 0;
13346 result.quick_push (p);
13348 while (p != v);
13352 /* Compare two depsets. The specific ordering is unimportant, we're
13353 just trying to get consistency. */
13355 static int
13356 depset_cmp (const void *a_, const void *b_)
13358 depset *a = *(depset *const *)a_;
13359 depset *b = *(depset *const *)b_;
13361 depset::entity_kind a_kind = a->get_entity_kind ();
13362 depset::entity_kind b_kind = b->get_entity_kind ();
13364 if (a_kind != b_kind)
13365 /* Different entity kinds, order by that. */
13366 return a_kind < b_kind ? -1 : +1;
13368 tree a_decl = a->get_entity ();
13369 tree b_decl = b->get_entity ();
13370 if (a_kind == depset::EK_USING)
13372 /* If one is a using, the other must be too. */
13373 a_decl = OVL_FUNCTION (a_decl);
13374 b_decl = OVL_FUNCTION (b_decl);
13377 if (a_decl != b_decl)
13378 /* Different entities, order by their UID. */
13379 return DECL_UID (a_decl) < DECL_UID (b_decl) ? -1 : +1;
13381 if (a_kind == depset::EK_BINDING)
13383 /* Both are bindings. Order by identifier hash. */
13384 gcc_checking_assert (a->get_name () != b->get_name ());
13385 return (IDENTIFIER_HASH_VALUE (a->get_name ())
13386 < IDENTIFIER_HASH_VALUE (b->get_name ())
13387 ? -1 : +1);
13390 /* They are the same decl. This can happen with two using decls
13391 pointing to the same target. The best we can aim for is
13392 consistently telling qsort how to order them. Hopefully we'll
13393 never have to debug a case that depends on this. Oh, who am I
13394 kidding? Good luck. */
13395 gcc_checking_assert (a_kind == depset::EK_USING);
13397 /* Order by depset address. Not the best, but it is something. */
13398 return a < b ? -1 : +1;
13401 /* Sort the clusters in SCC such that those that depend on one another
13402 are placed later. */
13404 // FIXME: I am not convinced this is needed and, if needed,
13405 // sufficient. We emit the decls in this order but that emission
13406 // could walk into later decls (from the body of the decl, or default
13407 // arg-like things). Why doesn't that walk do the right thing? And
13408 // if it DTRT why do we need to sort here -- won't things naturally
13409 // work? I think part of the issue is that when we're going to refer
13410 // to an entity by name, and that entity is in the same cluster as us,
13411 // we need to actually walk that entity, if we've not already walked
13412 // it.
13413 static void
13414 sort_cluster (depset::hash *original, depset *scc[], unsigned size)
13416 depset::hash table (size, original);
13418 dump.indent ();
13420 /* Place bindings last, usings before that. It's not strictly
13421 necessary, but it does make things neater. Says Mr OCD. */
13422 unsigned bind_lwm = size;
13423 unsigned use_lwm = size;
13424 for (unsigned ix = 0; ix != use_lwm;)
13426 depset *dep = scc[ix];
13427 switch (dep->get_entity_kind ())
13429 case depset::EK_BINDING:
13430 /* Move to end. No increment. Notice this could be moving
13431 a using decl, which we'll then move again. */
13432 if (--bind_lwm != ix)
13434 scc[ix] = scc[bind_lwm];
13435 scc[bind_lwm] = dep;
13437 if (use_lwm > bind_lwm)
13439 use_lwm--;
13440 break;
13442 /* We must have copied a using, so move it too. */
13443 dep = scc[ix];
13444 gcc_checking_assert (dep->get_entity_kind () == depset::EK_USING);
13445 /* FALLTHROUGH */
13447 case depset::EK_USING:
13448 if (--use_lwm != ix)
13450 scc[ix] = scc[use_lwm];
13451 scc[use_lwm] = dep;
13453 break;
13455 case depset::EK_DECL:
13456 case depset::EK_SPECIALIZATION:
13457 case depset::EK_PARTIAL:
13458 table.add_mergeable (dep);
13459 ix++;
13460 break;
13462 default:
13463 gcc_unreachable ();
13467 gcc_checking_assert (use_lwm <= bind_lwm);
13468 dump (dumper::MERGE) && dump ("Ordering %u/%u depsets", use_lwm, size);
13470 table.find_dependencies (nullptr);
13472 vec<depset *> order = table.connect ();
13473 gcc_checking_assert (order.length () == use_lwm);
13475 /* Now rewrite entries [0,lwm), in the dependency order we
13476 discovered. Usually each entity is in its own cluster. Rarely,
13477 we can get multi-entity clusters, in which case all but one must
13478 only be reached from within the cluster. This happens for
13479 something like:
13481 template<typename T>
13482 auto Foo (const T &arg) -> TPL<decltype (arg)>;
13484 The instantiation of TPL will be in the specialization table, and
13485 refer to Foo via arg. But we can only get to that specialization
13486 from Foo's declaration, so we only need to treat Foo as mergable
13487 (We'll do structural comparison of TPL<decltype (arg)>).
13489 Finding the single cluster entry dep is very tricky and
13490 expensive. Let's just not do that. It's harmless in this case
13491 anyway. */
13492 unsigned pos = 0;
13493 unsigned cluster = ~0u;
13494 for (unsigned ix = 0; ix != order.length (); ix++)
13496 gcc_checking_assert (order[ix]->is_special ());
13497 depset *dep = order[ix]->deps[0];
13498 scc[pos++] = dep;
13499 dump (dumper::MERGE)
13500 && dump ("Mergeable %u is %N%s", ix, dep->get_entity (),
13501 order[ix]->cluster == cluster ? " (tight)" : "");
13502 cluster = order[ix]->cluster;
13505 gcc_checking_assert (pos == use_lwm);
13507 order.release ();
13508 dump (dumper::MERGE) && dump ("Ordered %u keys", pos);
13509 dump.outdent ();
13512 /* Reduce graph to SCCS clusters. SCCS will be populated with the
13513 depsets in dependency order. Each depset's CLUSTER field contains
13514 its cluster number. Each SCC has a unique cluster number, and are
13515 contiguous in SCCS. Cluster numbers are otherwise arbitrary. */
13517 vec<depset *>
13518 depset::hash::connect ()
13520 tarjan connector (size ());
13521 vec<depset *> deps;
13522 deps.create (size ());
13523 iterator end (this->end ());
13524 for (iterator iter (begin ()); iter != end; ++iter)
13526 depset *item = *iter;
13528 entity_kind kind = item->get_entity_kind ();
13529 if (kind == EK_BINDING
13530 || !(kind == EK_REDIRECT
13531 || item->is_unreached ()
13532 || item->is_import ()))
13533 deps.quick_push (item);
13536 /* Iteration over the hash table is an unspecified ordering. While
13537 that has advantages, it causes 2 problems. Firstly repeatable
13538 builds are tricky. Secondly creating testcases that check
13539 dependencies are correct by making sure a bad ordering would
13540 happen if that was wrong. */
13541 deps.qsort (depset_cmp);
13543 while (deps.length ())
13545 depset *v = deps.pop ();
13546 dump (dumper::CLUSTER) &&
13547 (v->is_binding ()
13548 ? dump ("Connecting binding %P", v->get_entity (), v->get_name ())
13549 : dump ("Connecting %s %s %C:%N",
13550 is_key_order () ? "key-order"
13551 : !v->has_defn () ? "declaration" : "definition",
13552 v->entity_kind_name (), TREE_CODE (v->get_entity ()),
13553 v->get_entity ()));
13554 if (!v->cluster)
13555 connector.connect (v);
13558 deps.release ();
13559 return connector.result;
13562 /* Initialize location spans. */
13564 void
13565 loc_spans::init (const line_maps *lmaps, const line_map_ordinary *map)
13567 gcc_checking_assert (!init_p ());
13568 spans = new vec<span> ();
13569 spans->reserve (20);
13571 span interval;
13572 interval.ordinary.first = 0;
13573 interval.macro.second = MAX_LOCATION_T + 1;
13574 interval.ordinary_delta = interval.macro_delta = 0;
13576 /* A span for reserved fixed locs. */
13577 interval.ordinary.second
13578 = MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0));
13579 interval.macro.first = interval.macro.second;
13580 dump (dumper::LOCATION)
13581 && dump ("Fixed span %u ordinary:[%u,%u) macro:[%u,%u)", spans->length (),
13582 interval.ordinary.first, interval.ordinary.second,
13583 interval.macro.first, interval.macro.second);
13584 spans->quick_push (interval);
13586 /* A span for command line & forced headers. */
13587 interval.ordinary.first = interval.ordinary.second;
13588 interval.macro.second = interval.macro.first;
13589 if (map)
13591 interval.ordinary.second = map->start_location;
13592 interval.macro.first = LINEMAPS_MACRO_LOWEST_LOCATION (lmaps);
13594 dump (dumper::LOCATION)
13595 && dump ("Pre span %u ordinary:[%u,%u) macro:[%u,%u)", spans->length (),
13596 interval.ordinary.first, interval.ordinary.second,
13597 interval.macro.first, interval.macro.second);
13598 spans->quick_push (interval);
13600 /* Start an interval for the main file. */
13601 interval.ordinary.first = interval.ordinary.second;
13602 interval.macro.second = interval.macro.first;
13603 dump (dumper::LOCATION)
13604 && dump ("Main span %u ordinary:[%u,*) macro:[*,%u)", spans->length (),
13605 interval.ordinary.first, interval.macro.second);
13606 spans->quick_push (interval);
13609 /* Reopen the span, if we want the about-to-be-inserted set of maps to
13610 be propagated in our own location table. I.e. we are the primary
13611 interface and we're importing a partition. */
13613 bool
13614 loc_spans::maybe_propagate (module_state *import, location_t hwm)
13616 bool opened = (module_interface_p () && !module_partition_p ()
13617 && import->is_partition ());
13618 if (opened)
13619 open (hwm);
13620 return opened;
13623 /* Open a new linemap interval. The just-created ordinary map is the
13624 first map of the interval. */
13626 void
13627 loc_spans::open (location_t hwm)
13629 span interval;
13630 interval.ordinary.first = interval.ordinary.second = hwm;
13631 interval.macro.first = interval.macro.second
13632 = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
13633 interval.ordinary_delta = interval.macro_delta = 0;
13634 dump (dumper::LOCATION)
13635 && dump ("Opening span %u ordinary:[%u,... macro:...,%u)",
13636 spans->length (), interval.ordinary.first,
13637 interval.macro.second);
13638 if (spans->length ())
13640 /* No overlapping! */
13641 auto &last = spans->last ();
13642 gcc_checking_assert (interval.ordinary.first >= last.ordinary.second);
13643 gcc_checking_assert (interval.macro.second <= last.macro.first);
13645 spans->safe_push (interval);
13648 /* Close out the current linemap interval. The last maps are within
13649 the interval. */
13651 void
13652 loc_spans::close ()
13654 span &interval = spans->last ();
13656 interval.ordinary.second
13657 = ((line_table->highest_location + (1 << line_table->default_range_bits))
13658 & ~((1u << line_table->default_range_bits) - 1));
13659 interval.macro.first = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
13660 dump (dumper::LOCATION)
13661 && dump ("Closing span %u ordinary:[%u,%u) macro:[%u,%u)",
13662 spans->length () - 1,
13663 interval.ordinary.first,interval.ordinary.second,
13664 interval.macro.first, interval.macro.second);
13667 /* Given an ordinary location LOC, return the lmap_interval it resides
13668 in. NULL if it is not in an interval. */
13670 const loc_spans::span *
13671 loc_spans::ordinary (location_t loc)
13673 unsigned len = spans->length ();
13674 unsigned pos = 0;
13675 while (len)
13677 unsigned half = len / 2;
13678 const span &probe = (*spans)[pos + half];
13679 if (loc < probe.ordinary.first)
13680 len = half;
13681 else if (loc < probe.ordinary.second)
13682 return &probe;
13683 else
13685 pos += half + 1;
13686 len = len - (half + 1);
13689 return NULL;
13692 /* Likewise, given a macro location LOC, return the lmap interval it
13693 resides in. */
13695 const loc_spans::span *
13696 loc_spans::macro (location_t loc)
13698 unsigned len = spans->length ();
13699 unsigned pos = 0;
13700 while (len)
13702 unsigned half = len / 2;
13703 const span &probe = (*spans)[pos + half];
13704 if (loc >= probe.macro.second)
13705 len = half;
13706 else if (loc >= probe.macro.first)
13707 return &probe;
13708 else
13710 pos += half + 1;
13711 len = len - (half + 1);
13714 return NULL;
13717 /* Return the ordinary location closest to FROM. */
13719 static location_t
13720 ordinary_loc_of (line_maps *lmaps, location_t from)
13722 while (!IS_ORDINARY_LOC (from))
13724 if (IS_ADHOC_LOC (from))
13725 from = get_location_from_adhoc_loc (lmaps, from);
13726 if (from >= LINEMAPS_MACRO_LOWEST_LOCATION (lmaps))
13728 /* Find the ordinary location nearest FROM. */
13729 const line_map *map = linemap_lookup (lmaps, from);
13730 const line_map_macro *mac_map = linemap_check_macro (map);
13731 from = MACRO_MAP_EXPANSION_POINT_LOCATION (mac_map);
13734 return from;
13737 static module_state **
13738 get_module_slot (tree name, module_state *parent, bool partition, bool insert)
13740 module_state_hash::compare_type ct (name, uintptr_t (parent) | partition);
13741 hashval_t hv = module_state_hash::hash (ct);
13743 return modules_hash->find_slot_with_hash (ct, hv, insert ? INSERT : NO_INSERT);
13746 static module_state *
13747 get_primary (module_state *parent)
13749 while (parent->is_partition ())
13750 parent = parent->parent;
13752 if (!parent->name)
13753 // Implementation unit has null name
13754 parent = parent->parent;
13756 return parent;
13759 /* Find or create module NAME & PARENT in the hash table. */
13761 module_state *
13762 get_module (tree name, module_state *parent, bool partition)
13764 if (partition)
13766 if (!parent)
13767 parent = get_primary ((*modules)[0]);
13769 if (!parent->is_partition () && !parent->flatname)
13770 parent->set_flatname ();
13773 module_state **slot = get_module_slot (name, parent, partition, true);
13774 module_state *state = *slot;
13775 if (!state)
13777 state = (new (ggc_alloc<module_state> ())
13778 module_state (name, parent, partition));
13779 *slot = state;
13781 return state;
13784 /* Process string name PTR into a module_state. */
13786 static module_state *
13787 get_module (const char *ptr)
13789 if (ptr[0] == '.' ? IS_DIR_SEPARATOR (ptr[1]) : IS_ABSOLUTE_PATH (ptr))
13790 /* A header name. */
13791 return get_module (build_string (strlen (ptr), ptr));
13793 bool partition = false;
13794 module_state *mod = NULL;
13796 for (const char *probe = ptr;; probe++)
13797 if (!*probe || *probe == '.' || *probe == ':')
13799 if (probe == ptr)
13800 return NULL;
13802 mod = get_module (get_identifier_with_length (ptr, probe - ptr),
13803 mod, partition);
13804 ptr = probe;
13805 if (*ptr == ':')
13807 if (partition)
13808 return NULL;
13809 partition = true;
13812 if (!*ptr++)
13813 break;
13815 else if (!(ISALPHA (*probe) || *probe == '_'
13816 || (probe != ptr && ISDIGIT (*probe))))
13817 return NULL;
13819 return mod;
13822 /* Create a new mapper connecting to OPTION. */
13824 module_client *
13825 make_mapper (location_t loc)
13827 timevar_start (TV_MODULE_MAPPER);
13828 const char *option = module_mapper_name;
13829 if (!option)
13830 option = getenv ("CXX_MODULE_MAPPER");
13832 mapper = module_client::open_module_client
13833 (loc, option, &set_cmi_repo,
13834 (save_decoded_options[0].opt_index == OPT_SPECIAL_program_name)
13835 && save_decoded_options[0].arg != progname
13836 ? save_decoded_options[0].arg : nullptr);
13838 timevar_stop (TV_MODULE_MAPPER);
13840 return mapper;
13843 static unsigned lazy_snum;
13845 static bool
13846 recursive_lazy (unsigned snum = ~0u)
13848 if (lazy_snum)
13850 error_at (input_location, "recursive lazy load");
13851 return true;
13854 lazy_snum = snum;
13855 return false;
13858 /* If THIS is the current purview, issue an import error and return false. */
13860 bool
13861 module_state::check_not_purview (location_t from)
13863 module_state *imp = (*modules)[0];
13864 if (imp && !imp->name)
13865 imp = imp->parent;
13866 if (imp == this)
13868 /* Cannot import the current module. */
13869 error_at (from, "cannot import module in its own purview");
13870 inform (loc, "module %qs declared here", get_flatname ());
13871 return false;
13873 return true;
13876 /* Module name substitutions. */
13877 static vec<module_state *,va_heap> substs;
13879 void
13880 module_state::mangle (bool include_partition)
13882 if (subst)
13883 mangle_module_substitution (subst - 1);
13884 else
13886 if (parent)
13887 parent->mangle (include_partition);
13888 if (include_partition || !is_partition ())
13890 char p = 0;
13891 // Partitions are significant for global initializer functions
13892 if (is_partition () && !parent->is_partition ())
13893 p = 'P';
13894 substs.safe_push (this);
13895 subst = substs.length ();
13896 mangle_identifier (p, name);
13901 void
13902 mangle_module (int mod, bool include_partition)
13904 module_state *imp = (*modules)[mod];
13906 if (!imp->name)
13907 /* Set when importing the primary module interface. */
13908 imp = imp->parent;
13910 imp->mangle (include_partition);
13913 /* Clean up substitutions. */
13914 void
13915 mangle_module_fini ()
13917 while (substs.length ())
13918 substs.pop ()->subst = 0;
13921 /* Announce WHAT about the module. */
13923 void
13924 module_state::announce (const char *what) const
13926 if (noisy_p ())
13928 fprintf (stderr, " %s:%s", what, get_flatname ());
13929 fflush (stderr);
13933 /* A human-readable README section. The contents of this section to
13934 not contribute to the CRC, so the contents can change per
13935 compilation. That allows us to embed CWD, hostname, build time and
13936 what not. It is a STRTAB that may be extracted with:
13937 readelf -pgnu.c++.README $(module).gcm */
13939 void
13940 module_state::write_readme (elf_out *to, cpp_reader *reader,
13941 const char *dialect, unsigned extensions)
13943 bytes_out readme (to);
13945 readme.begin (false);
13947 readme.printf ("GNU C++ %smodule%s%s",
13948 is_header () ? "header " : is_partition () ? "" : "primary ",
13949 is_header () ? ""
13950 : is_interface () ? " interface" : " implementation",
13951 is_partition () ? " partition" : "");
13953 /* Compiler's version. */
13954 readme.printf ("compiler: %s", version_string);
13956 /* Module format version. */
13957 verstr_t string;
13958 version2string (MODULE_VERSION, string);
13959 readme.printf ("version: %s", string);
13961 /* Module information. */
13962 readme.printf ("module: %s", get_flatname ());
13963 readme.printf ("source: %s", main_input_filename);
13964 readme.printf ("dialect: %s", dialect);
13965 if (extensions)
13966 readme.printf ("extensions: %s",
13967 extensions & SE_OPENMP ? "-fopenmp" : "");
13969 /* The following fields could be expected to change between
13970 otherwise identical compilations. Consider a distributed build
13971 system. We should have a way of overriding that. */
13972 if (char *cwd = getcwd (NULL, 0))
13974 readme.printf ("cwd: %s", cwd);
13975 free (cwd);
13977 readme.printf ("repository: %s", cmi_repo ? cmi_repo : ".");
13978 #if NETWORKING
13980 char hostname[64];
13981 if (!gethostname (hostname, sizeof (hostname)))
13982 readme.printf ("host: %s", hostname);
13984 #endif
13986 /* This of course will change! */
13987 time_t stampy;
13988 auto kind = cpp_get_date (reader, &stampy);
13989 if (kind != CPP_time_kind::UNKNOWN)
13991 struct tm *time;
13993 time = gmtime (&stampy);
13994 readme.print_time ("build", time, "UTC");
13996 if (kind == CPP_time_kind::DYNAMIC)
13998 time = localtime (&stampy);
13999 readme.print_time ("local", time,
14000 #if defined (__USE_MISC) || defined (__USE_BSD) /* Is there a better way? */
14001 time->tm_zone
14002 #else
14004 #endif
14010 /* Its direct imports. */
14011 for (unsigned ix = 1; ix < modules->length (); ix++)
14013 module_state *state = (*modules)[ix];
14015 if (state->is_direct ())
14016 readme.printf ("%s: %s %s", state->exported_p ? "export" : "import",
14017 state->get_flatname (), state->filename);
14020 readme.end (to, to->name (MOD_SNAME_PFX ".README"), NULL);
14023 /* Sort environment var names in reverse order. */
14025 static int
14026 env_var_cmp (const void *a_, const void *b_)
14028 const unsigned char *a = *(const unsigned char *const *)a_;
14029 const unsigned char *b = *(const unsigned char *const *)b_;
14031 for (unsigned ix = 0; ; ix++)
14033 bool a_end = !a[ix] || a[ix] == '=';
14034 if (a[ix] == b[ix])
14036 if (a_end)
14037 break;
14039 else
14041 bool b_end = !b[ix] || b[ix] == '=';
14043 if (!a_end && !b_end)
14044 return a[ix] < b[ix] ? +1 : -1;
14045 if (a_end && b_end)
14046 break;
14047 return a_end ? +1 : -1;
14051 return 0;
14054 /* Write the environment. It is a STRTAB that may be extracted with:
14055 readelf -pgnu.c++.ENV $(module).gcm */
14057 void
14058 module_state::write_env (elf_out *to)
14060 vec<const char *> vars;
14061 vars.create (20);
14063 extern char **environ;
14064 while (const char *var = environ[vars.length ()])
14065 vars.safe_push (var);
14066 vars.qsort (env_var_cmp);
14068 bytes_out env (to);
14069 env.begin (false);
14070 while (vars.length ())
14071 env.printf ("%s", vars.pop ());
14072 env.end (to, to->name (MOD_SNAME_PFX ".ENV"), NULL);
14074 vars.release ();
14077 /* Write the direct or indirect imports.
14080 u:index
14081 s:name
14082 u32:crc
14083 s:filename (direct)
14084 u:exported (direct)
14085 } imports[N]
14088 void
14089 module_state::write_imports (bytes_out &sec, bool direct)
14091 unsigned count = 0;
14093 for (unsigned ix = 1; ix < modules->length (); ix++)
14095 module_state *imp = (*modules)[ix];
14097 if (imp->remap && imp->is_direct () == direct)
14098 count++;
14101 gcc_assert (!direct || count);
14103 sec.u (count);
14104 for (unsigned ix = 1; ix < modules->length (); ix++)
14106 module_state *imp = (*modules)[ix];
14108 if (imp->remap && imp->is_direct () == direct)
14110 dump () && dump ("Writing %simport:%u->%u %M (crc=%x)",
14111 !direct ? "indirect "
14112 : imp->exported_p ? "exported " : "",
14113 ix, imp->remap, imp, imp->crc);
14114 sec.u (imp->remap);
14115 sec.str (imp->get_flatname ());
14116 sec.u32 (imp->crc);
14117 if (direct)
14119 write_location (sec, imp->imported_from ());
14120 sec.str (imp->filename);
14121 int exportedness = 0;
14122 if (imp->exported_p)
14123 exportedness = +1;
14124 else if (!imp->is_purview_direct ())
14125 exportedness = -1;
14126 sec.i (exportedness);
14132 /* READER, LMAPS != NULL == direct imports,
14133 == NUL == indirect imports. */
14135 unsigned
14136 module_state::read_imports (bytes_in &sec, cpp_reader *reader, line_maps *lmaps)
14138 unsigned count = sec.u ();
14139 unsigned loaded = 0;
14141 while (count--)
14143 unsigned ix = sec.u ();
14144 if (ix >= slurp->remap->length () || !ix || (*slurp->remap)[ix])
14146 sec.set_overrun ();
14147 break;
14150 const char *name = sec.str (NULL);
14151 module_state *imp = get_module (name);
14152 unsigned crc = sec.u32 ();
14153 int exportedness = 0;
14155 /* If the import is a partition, it must be the same primary
14156 module as this TU. */
14157 if (imp && imp->is_partition () &&
14158 (!named_module_p ()
14159 || (get_primary ((*modules)[0]) != get_primary (imp))))
14160 imp = NULL;
14162 if (!imp)
14163 sec.set_overrun ();
14164 if (sec.get_overrun ())
14165 break;
14167 if (lmaps)
14169 /* A direct import, maybe load it. */
14170 location_t floc = read_location (sec);
14171 const char *fname = sec.str (NULL);
14172 exportedness = sec.i ();
14174 if (sec.get_overrun ())
14175 break;
14177 if (!imp->check_not_purview (loc))
14178 continue;
14180 if (imp->loadedness == ML_NONE)
14182 imp->loc = floc;
14183 imp->crc = crc;
14184 if (!imp->get_flatname ())
14185 imp->set_flatname ();
14187 unsigned n = dump.push (imp);
14189 if (!imp->filename && fname)
14190 imp->filename = xstrdup (fname);
14192 if (imp->is_partition ())
14193 dump () && dump ("Importing elided partition %M", imp);
14195 if (!imp->do_import (reader, false))
14196 imp = NULL;
14197 dump.pop (n);
14198 if (!imp)
14199 continue;
14202 if (is_partition ())
14204 if (!imp->is_direct ())
14205 imp->directness = MD_PARTITION_DIRECT;
14206 if (exportedness > 0)
14207 imp->exported_p = true;
14210 else
14212 /* An indirect import, find it, it should already be here. */
14213 if (imp->loadedness == ML_NONE)
14215 error_at (loc, "indirect import %qs is not already loaded", name);
14216 continue;
14220 if (imp->crc != crc)
14221 error_at (loc, "import %qs has CRC mismatch", imp->get_flatname ());
14223 (*slurp->remap)[ix] = (imp->mod << 1) | (lmaps != NULL);
14225 if (lmaps && exportedness >= 0)
14226 set_import (imp, bool (exportedness));
14227 dump () && dump ("Found %simport:%u %M->%u", !lmaps ? "indirect "
14228 : exportedness > 0 ? "exported "
14229 : exportedness < 0 ? "gmf" : "", ix, imp,
14230 imp->mod);
14231 loaded++;
14234 return loaded;
14237 /* Write the import table to MOD_SNAME_PFX.imp. */
14239 void
14240 module_state::write_imports (elf_out *to, unsigned *crc_ptr)
14242 dump () && dump ("Writing imports");
14243 dump.indent ();
14245 bytes_out sec (to);
14246 sec.begin ();
14248 write_imports (sec, true);
14249 write_imports (sec, false);
14251 sec.end (to, to->name (MOD_SNAME_PFX ".imp"), crc_ptr);
14252 dump.outdent ();
14255 bool
14256 module_state::read_imports (cpp_reader *reader, line_maps *lmaps)
14258 bytes_in sec;
14260 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".imp"))
14261 return false;
14263 dump () && dump ("Reading %u imports", slurp->remap->length () - 1);
14264 dump.indent ();
14266 /* Read the imports. */
14267 unsigned direct = read_imports (sec, reader, lmaps);
14268 unsigned indirect = read_imports (sec, NULL, NULL);
14269 if (direct + indirect + 1 != slurp->remap->length ())
14270 from ()->set_error (elf::E_BAD_IMPORT);
14272 dump.outdent ();
14273 if (!sec.end (from ()))
14274 return false;
14275 return true;
14278 /* We're the primary module interface, but have partitions. Document
14279 them so that non-partition module implementation units know which
14280 have already been loaded. */
14282 void
14283 module_state::write_partitions (elf_out *to, unsigned count, unsigned *crc_ptr)
14285 dump () && dump ("Writing %u elided partitions", count);
14286 dump.indent ();
14288 bytes_out sec (to);
14289 sec.begin ();
14291 for (unsigned ix = 1; ix != modules->length (); ix++)
14293 module_state *imp = (*modules)[ix];
14294 if (imp->is_partition ())
14296 dump () && dump ("Writing elided partition %M (crc=%x)",
14297 imp, imp->crc);
14298 sec.str (imp->get_flatname ());
14299 sec.u32 (imp->crc);
14300 write_location (sec, imp->is_direct ()
14301 ? imp->imported_from () : UNKNOWN_LOCATION);
14302 sec.str (imp->filename);
14306 sec.end (to, to->name (MOD_SNAME_PFX ".prt"), crc_ptr);
14307 dump.outdent ();
14310 bool
14311 module_state::read_partitions (unsigned count)
14313 bytes_in sec;
14314 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".prt"))
14315 return false;
14317 dump () && dump ("Reading %u elided partitions", count);
14318 dump.indent ();
14320 while (count--)
14322 const char *name = sec.str (NULL);
14323 unsigned crc = sec.u32 ();
14324 location_t floc = read_location (sec);
14325 const char *fname = sec.str (NULL);
14327 if (sec.get_overrun ())
14328 break;
14330 dump () && dump ("Reading elided partition %s (crc=%x)", name, crc);
14332 module_state *imp = get_module (name);
14333 if (!imp /* Partition should be ... */
14334 || !imp->is_partition () /* a partition ... */
14335 || imp->loadedness != ML_NONE /* that is not yet loaded ... */
14336 || get_primary (imp) != this) /* whose primary is this. */
14338 sec.set_overrun ();
14339 break;
14342 if (!imp->has_location ())
14343 imp->loc = floc;
14344 imp->crc = crc;
14345 if (!imp->filename && fname[0])
14346 imp->filename = xstrdup (fname);
14349 dump.outdent ();
14350 if (!sec.end (from ()))
14351 return false;
14352 return true;
14355 /* Counter indices. */
14356 enum module_state_counts
14358 MSC_sec_lwm,
14359 MSC_sec_hwm,
14360 MSC_pendings,
14361 MSC_entities,
14362 MSC_namespaces,
14363 MSC_bindings,
14364 MSC_macros,
14365 MSC_inits,
14366 MSC_HWM
14369 /* Data for config reading and writing. */
14370 struct module_state_config {
14371 const char *dialect_str;
14372 unsigned num_imports;
14373 unsigned num_partitions;
14374 unsigned num_entities;
14375 unsigned ordinary_locs;
14376 unsigned macro_locs;
14377 unsigned ordinary_loc_align;
14379 public:
14380 module_state_config ()
14381 :dialect_str (get_dialect ()),
14382 num_imports (0), num_partitions (0), num_entities (0),
14383 ordinary_locs (0), macro_locs (0), ordinary_loc_align (0)
14387 static void release ()
14389 XDELETEVEC (dialect);
14390 dialect = NULL;
14393 private:
14394 static const char *get_dialect ();
14395 static char *dialect;
14398 char *module_state_config::dialect;
14400 /* Generate a string of the significant compilation options.
14401 Generally assume the user knows what they're doing, in the same way
14402 that object files can be mixed. */
14404 const char *
14405 module_state_config::get_dialect ()
14407 if (!dialect)
14408 dialect = concat (get_cxx_dialect_name (cxx_dialect),
14409 /* C++ implies these, only show if disabled. */
14410 flag_exceptions ? "" : "/no-exceptions",
14411 flag_rtti ? "" : "/no-rtti",
14412 flag_new_inheriting_ctors ? "" : "/old-inheriting-ctors",
14413 /* C++ 20 implies concepts. */
14414 cxx_dialect < cxx20 && flag_concepts ? "/concepts" : "",
14415 flag_coroutines ? "/coroutines" : "",
14416 flag_module_implicit_inline ? "/implicit-inline" : "",
14417 NULL);
14419 return dialect;
14422 /* Contents of a cluster. */
14423 enum cluster_tag {
14424 ct_decl, /* A decl. */
14425 ct_defn, /* A definition. */
14426 ct_bind, /* A binding. */
14427 ct_hwm
14430 /* Binding modifiers. */
14431 enum ct_bind_flags
14433 cbf_export = 0x1, /* An exported decl. */
14434 cbf_hidden = 0x2, /* A hidden (friend) decl. */
14435 cbf_using = 0x4, /* A using decl. */
14436 cbf_wrapped = 0x8, /* ... that is wrapped. */
14439 /* DEP belongs to a different cluster, seed it to prevent
14440 unfortunately timed duplicate import. */
14441 // FIXME: QOI For inter-cluster references we could just only pick
14442 // one entity from an earlier cluster. Even better track
14443 // dependencies between earlier clusters
14445 void
14446 module_state::intercluster_seed (trees_out &sec, unsigned index_hwm, depset *dep)
14448 if (dep->is_import ()
14449 || dep->cluster < index_hwm)
14451 tree ent = dep->get_entity ();
14452 if (!TREE_VISITED (ent))
14454 sec.tree_node (ent);
14455 dump (dumper::CLUSTER)
14456 && dump ("Seeded %s %N",
14457 dep->is_import () ? "import" : "intercluster", ent);
14462 /* Write the cluster of depsets in SCC[0-SIZE).
14463 dep->section -> section number
14464 dep->cluster -> entity number
14467 unsigned
14468 module_state::write_cluster (elf_out *to, depset *scc[], unsigned size,
14469 depset::hash &table, unsigned *counts,
14470 unsigned *crc_ptr)
14472 dump () && dump ("Writing section:%u %u depsets", table.section, size);
14473 dump.indent ();
14475 trees_out sec (to, this, table, table.section);
14476 sec.begin ();
14477 unsigned index_lwm = counts[MSC_entities];
14479 /* Determine entity numbers, mark for writing. */
14480 dump (dumper::CLUSTER) && dump ("Cluster members:") && (dump.indent (), true);
14481 for (unsigned ix = 0; ix != size; ix++)
14483 depset *b = scc[ix];
14485 switch (b->get_entity_kind ())
14487 default:
14488 gcc_unreachable ();
14490 case depset::EK_BINDING:
14492 dump (dumper::CLUSTER)
14493 && dump ("[%u]=%s %P", ix, b->entity_kind_name (),
14494 b->get_entity (), b->get_name ());
14495 depset *ns_dep = b->deps[0];
14496 gcc_checking_assert (ns_dep->get_entity_kind ()
14497 == depset::EK_NAMESPACE
14498 && ns_dep->get_entity () == b->get_entity ());
14499 for (unsigned jx = b->deps.length (); --jx;)
14501 depset *dep = b->deps[jx];
14502 // We could be declaring something that is also a
14503 // (merged) import
14504 gcc_checking_assert (dep->is_import ()
14505 || TREE_VISITED (dep->get_entity ())
14506 || (dep->get_entity_kind ()
14507 == depset::EK_USING));
14510 break;
14512 case depset::EK_DECL:
14513 case depset::EK_SPECIALIZATION:
14514 case depset::EK_PARTIAL:
14515 b->cluster = counts[MSC_entities]++;
14516 sec.mark_declaration (b->get_entity (), b->has_defn ());
14517 /* FALLTHROUGH */
14519 case depset::EK_USING:
14520 gcc_checking_assert (!b->is_import ()
14521 && !b->is_unreached ());
14522 dump (dumper::CLUSTER)
14523 && dump ("[%u]=%s %s %N", ix, b->entity_kind_name (),
14524 b->has_defn () ? "definition" : "declaration",
14525 b->get_entity ());
14526 break;
14529 dump (dumper::CLUSTER) && (dump.outdent (), true);
14531 /* Ensure every out-of-cluster decl is referenced before we start
14532 streaming. We must do both imports *and* earlier clusters,
14533 because the latter could reach into the former and cause a
14534 duplicate loop. */
14535 sec.set_importing (+1);
14536 for (unsigned ix = 0; ix != size; ix++)
14538 depset *b = scc[ix];
14539 for (unsigned jx = (b->get_entity_kind () == depset::EK_BINDING
14540 || b->is_special ()) ? 1 : 0;
14541 jx != b->deps.length (); jx++)
14543 depset *dep = b->deps[jx];
14545 if (dep->is_binding ())
14547 for (unsigned ix = dep->deps.length (); --ix;)
14549 depset *bind = dep->deps[ix];
14550 if (bind->get_entity_kind () == depset::EK_USING)
14551 bind = bind->deps[1];
14553 intercluster_seed (sec, index_lwm, bind);
14555 /* Also check the namespace itself. */
14556 dep = dep->deps[0];
14559 intercluster_seed (sec, index_lwm, dep);
14562 sec.tree_node (NULL_TREE);
14563 /* We're done importing now. */
14564 sec.set_importing (-1);
14566 /* Write non-definitions. */
14567 for (unsigned ix = 0; ix != size; ix++)
14569 depset *b = scc[ix];
14570 tree decl = b->get_entity ();
14571 switch (b->get_entity_kind ())
14573 default:
14574 gcc_unreachable ();
14575 break;
14577 case depset::EK_BINDING:
14579 gcc_assert (TREE_CODE (decl) == NAMESPACE_DECL);
14580 dump () && dump ("Depset:%u binding %C:%P", ix, TREE_CODE (decl),
14581 decl, b->get_name ());
14582 sec.u (ct_bind);
14583 sec.tree_node (decl);
14584 sec.tree_node (b->get_name ());
14586 /* Write in reverse order, so reading will see the exports
14587 first, thus building the overload chain will be
14588 optimized. */
14589 for (unsigned jx = b->deps.length (); --jx;)
14591 depset *dep = b->deps[jx];
14592 tree bound = dep->get_entity ();
14593 unsigned flags = 0;
14594 if (dep->get_entity_kind () == depset::EK_USING)
14596 tree ovl = bound;
14597 bound = OVL_FUNCTION (bound);
14598 if (!(TREE_CODE (bound) == CONST_DECL
14599 && UNSCOPED_ENUM_P (TREE_TYPE (bound))
14600 && decl == TYPE_NAME (TREE_TYPE (bound))))
14602 /* An unscope enumerator in its enumeration's
14603 scope is not a using. */
14604 flags |= cbf_using;
14605 if (OVL_USING_P (ovl))
14606 flags |= cbf_wrapped;
14608 if (OVL_EXPORT_P (ovl))
14609 flags |= cbf_export;
14611 else
14613 /* An implicit typedef must be at one. */
14614 gcc_assert (!DECL_IMPLICIT_TYPEDEF_P (bound) || jx == 1);
14615 if (dep->is_hidden ())
14616 flags |= cbf_hidden;
14617 else if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (bound)))
14618 flags |= cbf_export;
14621 gcc_checking_assert (DECL_P (bound));
14623 sec.i (flags);
14624 sec.tree_node (bound);
14627 /* Terminate the list. */
14628 sec.i (-1);
14630 break;
14632 case depset::EK_USING:
14633 dump () && dump ("Depset:%u %s %C:%N", ix, b->entity_kind_name (),
14634 TREE_CODE (decl), decl);
14635 break;
14637 case depset::EK_SPECIALIZATION:
14638 case depset::EK_PARTIAL:
14639 case depset::EK_DECL:
14640 dump () && dump ("Depset:%u %s entity:%u %C:%N", ix,
14641 b->entity_kind_name (), b->cluster,
14642 TREE_CODE (decl), decl);
14644 sec.u (ct_decl);
14645 sec.tree_node (decl);
14647 dump () && dump ("Wrote declaration entity:%u %C:%N",
14648 b->cluster, TREE_CODE (decl), decl);
14649 break;
14653 depset *namer = NULL;
14655 /* Write out definitions */
14656 for (unsigned ix = 0; ix != size; ix++)
14658 depset *b = scc[ix];
14659 tree decl = b->get_entity ();
14660 switch (b->get_entity_kind ())
14662 default:
14663 break;
14665 case depset::EK_SPECIALIZATION:
14666 case depset::EK_PARTIAL:
14667 case depset::EK_DECL:
14668 if (!namer)
14669 namer = b;
14671 if (b->has_defn ())
14673 sec.u (ct_defn);
14674 sec.tree_node (decl);
14675 dump () && dump ("Writing definition %N", decl);
14676 sec.write_definition (decl);
14678 if (!namer->has_defn ())
14679 namer = b;
14681 break;
14685 /* We don't find the section by name. Use depset's decl's name for
14686 human friendliness. */
14687 unsigned name = 0;
14688 tree naming_decl = NULL_TREE;
14689 if (namer)
14691 naming_decl = namer->get_entity ();
14692 if (namer->get_entity_kind () == depset::EK_USING)
14693 /* This unfortunately names the section from the target of the
14694 using decl. But the name is only a guide, so Do Not Care. */
14695 naming_decl = OVL_FUNCTION (naming_decl);
14696 if (DECL_IMPLICIT_TYPEDEF_P (naming_decl))
14697 /* Lose any anonymousness. */
14698 naming_decl = TYPE_NAME (TREE_TYPE (naming_decl));
14699 name = to->qualified_name (naming_decl, namer->has_defn ());
14702 unsigned bytes = sec.pos;
14703 unsigned snum = sec.end (to, name, crc_ptr);
14705 for (unsigned ix = size; ix--;)
14706 gcc_checking_assert (scc[ix]->section == snum);
14708 dump.outdent ();
14709 dump () && dump ("Wrote section:%u named-by:%N", table.section, naming_decl);
14711 return bytes;
14714 /* Read a cluster from section SNUM. */
14716 bool
14717 module_state::read_cluster (unsigned snum)
14719 trees_in sec (this);
14721 if (!sec.begin (loc, from (), snum))
14722 return false;
14724 dump () && dump ("Reading section:%u", snum);
14725 dump.indent ();
14727 /* We care about structural equality. */
14728 comparing_dependent_aliases++;
14730 /* First seed the imports. */
14731 while (tree import = sec.tree_node ())
14732 dump (dumper::CLUSTER) && dump ("Seeded import %N", import);
14734 while (!sec.get_overrun () && sec.more_p ())
14736 unsigned ct = sec.u ();
14737 switch (ct)
14739 default:
14740 sec.set_overrun ();
14741 break;
14743 case ct_bind:
14744 /* A set of namespace bindings. */
14746 tree ns = sec.tree_node ();
14747 tree name = sec.tree_node ();
14748 tree decls = NULL_TREE;
14749 tree visible = NULL_TREE;
14750 tree type = NULL_TREE;
14751 bool dedup = false;
14753 /* We rely on the bindings being in the reverse order of
14754 the resulting overload set. */
14755 for (;;)
14757 int flags = sec.i ();
14758 if (flags < 0)
14759 break;
14761 if ((flags & cbf_hidden)
14762 && (flags & (cbf_using | cbf_export)))
14763 sec.set_overrun ();
14765 tree decl = sec.tree_node ();
14766 if (sec.get_overrun ())
14767 break;
14769 if (decls && TREE_CODE (decl) == TYPE_DECL)
14771 /* Stat hack. */
14772 if (type || !DECL_IMPLICIT_TYPEDEF_P (decl))
14773 sec.set_overrun ();
14774 type = decl;
14776 else
14778 if (decls
14779 || (flags & (cbf_hidden | cbf_wrapped))
14780 || DECL_FUNCTION_TEMPLATE_P (decl))
14782 decls = ovl_make (decl, decls);
14783 if (flags & cbf_using)
14785 dedup = true;
14786 OVL_USING_P (decls) = true;
14787 if (flags & cbf_export)
14788 OVL_EXPORT_P (decls) = true;
14791 if (flags & cbf_hidden)
14792 OVL_HIDDEN_P (decls) = true;
14793 else if (dedup)
14794 OVL_DEDUP_P (decls) = true;
14796 else
14797 decls = decl;
14799 if (flags & cbf_export
14800 || (!(flags & cbf_hidden)
14801 && (is_module () || is_partition ())))
14802 visible = decls;
14806 if (!decls)
14807 sec.set_overrun ();
14809 if (sec.get_overrun ())
14810 break; /* Bail. */
14812 dump () && dump ("Binding of %P", ns, name);
14813 if (!set_module_binding (ns, name, mod,
14814 is_header () ? -1
14815 : is_module () || is_partition () ? 1
14816 : 0,
14817 decls, type, visible))
14818 sec.set_overrun ();
14820 break;
14822 case ct_decl:
14823 /* A decl. */
14825 tree decl = sec.tree_node ();
14826 dump () && dump ("Read declaration of %N", decl);
14828 break;
14830 case ct_defn:
14832 tree decl = sec.tree_node ();
14833 dump () && dump ("Reading definition of %N", decl);
14834 sec.read_definition (decl);
14836 break;
14840 /* When lazy loading is in effect, we can be in the middle of
14841 parsing or instantiating a function. Save it away.
14842 push_function_context does too much work. */
14843 tree old_cfd = current_function_decl;
14844 struct function *old_cfun = cfun;
14845 while (tree decl = sec.post_process ())
14847 bool abstract = false;
14848 if (TREE_CODE (decl) == TEMPLATE_DECL)
14850 abstract = true;
14851 decl = DECL_TEMPLATE_RESULT (decl);
14854 current_function_decl = decl;
14855 allocate_struct_function (decl, abstract);
14856 cfun->language = ggc_cleared_alloc<language_function> ();
14857 cfun->language->base.x_stmt_tree.stmts_are_full_exprs_p = 1;
14859 if (abstract)
14861 else if (DECL_ABSTRACT_P (decl))
14862 vec_safe_push (post_load_decls, decl);
14863 else
14865 bool aggr = aggregate_value_p (DECL_RESULT (decl), decl);
14866 #ifdef PCC_STATIC_STRUCT_RETURN
14867 cfun->returns_pcc_struct = aggr;
14868 #endif
14869 cfun->returns_struct = aggr;
14871 if (DECL_COMDAT (decl))
14872 // FIXME: Comdat grouping?
14873 comdat_linkage (decl);
14874 note_vague_linkage_fn (decl);
14875 cgraph_node::finalize_function (decl, true);
14879 /* Look, function.c's interface to cfun does too much for us, we
14880 just need to restore the old value. I do not want to go
14881 redesigning that API right now. */
14882 #undef cfun
14883 cfun = old_cfun;
14884 current_function_decl = old_cfd;
14885 comparing_dependent_aliases--;
14887 dump.outdent ();
14888 dump () && dump ("Read section:%u", snum);
14890 loaded_clusters++;
14892 if (!sec.end (from ()))
14893 return false;
14895 return true;
14898 void
14899 module_state::write_namespace (bytes_out &sec, depset *dep)
14901 unsigned ns_num = dep->cluster;
14902 unsigned ns_import = 0;
14904 if (dep->is_import ())
14905 ns_import = dep->section;
14906 else if (dep->get_entity () != global_namespace)
14907 ns_num++;
14909 sec.u (ns_import);
14910 sec.u (ns_num);
14913 tree
14914 module_state::read_namespace (bytes_in &sec)
14916 unsigned ns_import = sec.u ();
14917 unsigned ns_num = sec.u ();
14918 tree ns = NULL_TREE;
14920 if (ns_import || ns_num)
14922 if (!ns_import)
14923 ns_num--;
14925 if (unsigned origin = slurp->remap_module (ns_import))
14927 module_state *from = (*modules)[origin];
14928 if (ns_num < from->entity_num)
14930 binding_slot &slot = (*entity_ary)[from->entity_lwm + ns_num];
14932 if (!slot.is_lazy ())
14933 ns = slot;
14936 else
14937 sec.set_overrun ();
14939 else
14940 ns = global_namespace;
14942 return ns;
14945 /* SPACES is a sorted vector of namespaces. Write out the namespaces
14946 to MOD_SNAME_PFX.nms section. */
14948 void
14949 module_state::write_namespaces (elf_out *to, vec<depset *> spaces,
14950 unsigned num, unsigned *crc_p)
14952 dump () && dump ("Writing namespaces");
14953 dump.indent ();
14955 bytes_out sec (to);
14956 sec.begin ();
14958 for (unsigned ix = 0; ix != num; ix++)
14960 depset *b = spaces[ix];
14961 tree ns = b->get_entity ();
14963 gcc_checking_assert (TREE_CODE (ns) == NAMESPACE_DECL);
14964 /* P1815 may have something to say about this. */
14965 gcc_checking_assert (TREE_PUBLIC (ns));
14967 unsigned flags = 0;
14968 if (TREE_PUBLIC (ns))
14969 flags |= 1;
14970 if (DECL_NAMESPACE_INLINE_P (ns))
14971 flags |= 2;
14972 if (DECL_MODULE_PURVIEW_P (ns))
14973 flags |= 4;
14974 if (DECL_MODULE_EXPORT_P (ns))
14975 flags |= 8;
14977 dump () && dump ("Writing namespace:%u %N%s%s%s%s",
14978 b->cluster, ns,
14979 flags & 1 ? ", public" : "",
14980 flags & 2 ? ", inline" : "",
14981 flags & 4 ? ", purview" : "",
14982 flags & 8 ? ", export" : "");
14983 sec.u (b->cluster);
14984 sec.u (to->name (DECL_NAME (ns)));
14985 write_namespace (sec, b->deps[0]);
14987 sec.u (flags);
14988 write_location (sec, DECL_SOURCE_LOCATION (ns));
14991 sec.end (to, to->name (MOD_SNAME_PFX ".nms"), crc_p);
14992 dump.outdent ();
14995 /* Read the namespace hierarchy from MOD_SNAME_PFX.namespace. Fill in
14996 SPACES from that data. */
14998 bool
14999 module_state::read_namespaces (unsigned num)
15001 bytes_in sec;
15003 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".nms"))
15004 return false;
15006 dump () && dump ("Reading namespaces");
15007 dump.indent ();
15009 for (unsigned ix = 0; ix != num; ix++)
15011 unsigned entity_index = sec.u ();
15012 unsigned name = sec.u ();
15014 tree parent = read_namespace (sec);
15016 /* See comment in write_namespace about why not bits. */
15017 unsigned flags = sec.u ();
15018 location_t src_loc = read_location (sec);
15020 if (entity_index >= entity_num
15021 || !parent
15022 || (flags & 0xc) == 0x8)
15023 sec.set_overrun ();
15024 if (sec.get_overrun ())
15025 break;
15027 tree id = name ? get_identifier (from ()->name (name)) : NULL_TREE;
15029 dump () && dump ("Read namespace:%u %P%s%s%s%s",
15030 entity_index, parent, id,
15031 flags & 1 ? ", public" : "",
15032 flags & 2 ? ", inline" : "",
15033 flags & 4 ? ", purview" : "",
15034 flags & 8 ? ", export" : "");
15035 bool visible_p = ((flags & 8)
15036 || ((flags & 1)
15037 && (flags & 4)
15038 && (is_partition () || is_module ())));
15039 tree inner = add_imported_namespace (parent, id, src_loc, mod,
15040 bool (flags & 2), visible_p);
15041 if (!inner)
15043 sec.set_overrun ();
15044 break;
15047 if (is_partition ())
15049 if (flags & 4)
15050 DECL_MODULE_PURVIEW_P (inner) = true;
15051 if (flags & 8)
15052 DECL_MODULE_EXPORT_P (inner) = true;
15055 /* Install the namespace. */
15056 (*entity_ary)[entity_lwm + entity_index] = inner;
15057 if (DECL_MODULE_IMPORT_P (inner))
15059 bool existed;
15060 unsigned *slot = &entity_map->get_or_insert
15061 (DECL_UID (inner), &existed);
15062 if (existed)
15063 /* If it existed, it should match. */
15064 gcc_checking_assert (inner == (*entity_ary)[*slot]);
15065 else
15066 *slot = entity_lwm + entity_index;
15069 dump.outdent ();
15070 if (!sec.end (from ()))
15071 return false;
15072 return true;
15075 /* Write the binding TABLE to MOD_SNAME_PFX.bnd */
15077 unsigned
15078 module_state::write_bindings (elf_out *to, vec<depset *> sccs, unsigned *crc_p)
15080 dump () && dump ("Writing binding table");
15081 dump.indent ();
15083 unsigned num = 0;
15084 bytes_out sec (to);
15085 sec.begin ();
15087 for (unsigned ix = 0; ix != sccs.length (); ix++)
15089 depset *b = sccs[ix];
15090 if (b->is_binding ())
15092 tree ns = b->get_entity ();
15093 dump () && dump ("Bindings %P section:%u", ns, b->get_name (),
15094 b->section);
15095 sec.u (to->name (b->get_name ()));
15096 write_namespace (sec, b->deps[0]);
15097 sec.u (b->section);
15098 num++;
15102 sec.end (to, to->name (MOD_SNAME_PFX ".bnd"), crc_p);
15103 dump.outdent ();
15105 return num;
15108 /* Read the binding table from MOD_SNAME_PFX.bind. */
15110 bool
15111 module_state::read_bindings (unsigned num, unsigned lwm, unsigned hwm)
15113 bytes_in sec;
15115 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".bnd"))
15116 return false;
15118 dump () && dump ("Reading binding table");
15119 dump.indent ();
15120 for (; !sec.get_overrun () && num--;)
15122 const char *name = from ()->name (sec.u ());
15123 tree ns = read_namespace (sec);
15124 unsigned snum = sec.u ();
15126 if (!ns || !name || (snum - lwm) >= (hwm - lwm))
15127 sec.set_overrun ();
15128 if (!sec.get_overrun ())
15130 tree id = get_identifier (name);
15131 dump () && dump ("Bindings %P section:%u", ns, id, snum);
15132 if (mod && !import_module_binding (ns, id, mod, snum))
15133 break;
15137 dump.outdent ();
15138 if (!sec.end (from ()))
15139 return false;
15140 return true;
15143 /* Write the entity table to MOD_SNAME_PFX.ent
15145 Each entry is a section number. */
15147 void
15148 module_state::write_entities (elf_out *to, vec<depset *> depsets,
15149 unsigned count, unsigned *crc_p)
15151 dump () && dump ("Writing entities");
15152 dump.indent ();
15154 bytes_out sec (to);
15155 sec.begin ();
15157 unsigned current = 0;
15158 for (unsigned ix = 0; ix < depsets.length (); ix++)
15160 depset *d = depsets[ix];
15162 switch (d->get_entity_kind ())
15164 default:
15165 break;
15167 case depset::EK_NAMESPACE:
15168 if (!d->is_import () && d->get_entity () != global_namespace)
15170 gcc_checking_assert (d->cluster == current);
15171 current++;
15172 sec.u (0);
15174 break;
15176 case depset::EK_DECL:
15177 case depset::EK_SPECIALIZATION:
15178 case depset::EK_PARTIAL:
15179 gcc_checking_assert (!d->is_unreached ()
15180 && !d->is_import ()
15181 && d->cluster == current
15182 && d->section);
15183 current++;
15184 sec.u (d->section);
15185 break;
15188 gcc_assert (count == current);
15189 sec.end (to, to->name (MOD_SNAME_PFX ".ent"), crc_p);
15190 dump.outdent ();
15193 bool
15194 module_state::read_entities (unsigned count, unsigned lwm, unsigned hwm)
15196 trees_in sec (this);
15198 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".ent"))
15199 return false;
15201 dump () && dump ("Reading entities");
15202 dump.indent ();
15204 for (binding_slot *slot = entity_ary->begin () + entity_lwm; count--; slot++)
15206 unsigned snum = sec.u ();
15207 if (snum && (snum - lwm) >= (hwm - lwm))
15208 sec.set_overrun ();
15209 if (sec.get_overrun ())
15210 break;
15212 if (snum)
15213 slot->set_lazy (snum << 2);
15216 dump.outdent ();
15217 if (!sec.end (from ()))
15218 return false;
15219 return true;
15222 /* Write the pending table to MOD_SNAME_PFX.pnd
15224 The pending table holds information about clusters that need to be
15225 loaded because they contain information about something that is not
15226 found by namespace-scope lookup.
15228 The three cases are:
15230 (a) Template (maybe-partial) specializations that we have
15231 instantiated or defined. When an importer needs to instantiate
15232 that template, they /must have/ the partial, explicit & extern
15233 specializations available. If they have the other specializations
15234 available, they'll have less work to do. Thus, when we're about to
15235 instantiate FOO, we have to be able to ask 'are there any
15236 specialization of FOO in our imports?'.
15238 (b) (Maybe-implicit) member functions definitions. A class could
15239 be defined in one header, and an inline member defined in a
15240 different header (this occurs in the STL). Similarly, like the
15241 specialization case, an implicit member function could have been
15242 'instantiated' in one module, and it'd be nice to not have to
15243 reinstantiate it in another.
15245 (c) A member classes completed elsewhere. A member class could be
15246 declared in one header and defined in another. We need to know to
15247 load the class definition before looking in it. This turns out to
15248 be a specific case of #b, so we can treat these the same. But it
15249 does highlight an issue -- there could be an intermediate import
15250 between the outermost containing namespace-scope class and the
15251 innermost being-defined member class. This is actually possible
15252 with all of these cases, so be aware -- we're not just talking of
15253 one level of import to get to the innermost namespace.
15255 This gets complicated fast, it took me multiple attempts to even
15256 get something remotely working. Partially because I focussed on
15257 optimizing what I think turns out to be a smaller problem, given
15258 the known need to do the more general case *anyway*. I document
15259 the smaller problem, because it does appear to be the natural way
15260 to do it. It's trap!
15262 **** THE TRAP
15264 Let's refer to the primary template or the containing class as the
15265 KEY. And the specialization or member as the PENDING-ENTITY. (To
15266 avoid having to say those mouthfuls all the time.)
15268 In either case, we have an entity and we need some way of mapping
15269 that to a set of entities that need to be loaded before we can
15270 proceed with whatever processing of the entity we were going to do.
15272 We need to link the key to the pending-entity in some way. Given a
15273 key, tell me the pending-entities I need to have loaded. However
15274 we tie the key to the pending-entity must not rely on the key being
15275 loaded -- that'd defeat the lazy loading scheme.
15277 As the key will be an import in we know its entity number (either
15278 because we imported it, or we're writing it out too). Thus we can
15279 generate a map of key-indices to pending-entities. The
15280 pending-entity indices will be into our span of the entity table,
15281 and thus allow them to be lazily loaded. The key index will be
15282 into another slot of the entity table. Notice that this checking
15283 could be expensive, we don't want to iterate over a bunch of
15284 pending-entity indices (across multiple imports), every time we're
15285 about do to the thing with the key. We need to quickly determine
15286 'definitely nothing needed'.
15288 That's almost good enough, except that key indices are not unique
15289 in a couple of cases :( Specifically the Global Module or a module
15290 partition can result in multiple modules assigning an entity index
15291 for the key. The decl-merging on loading will detect that so we
15292 only have one Key loaded, and in the entity hash it'll indicate the
15293 entity index of first load. Which might be different to how we
15294 know it. Notice this is restricted to GM entities or this-module
15295 entities. Foreign imports cannot have this.
15297 We can simply resolve this in the direction of how this module
15298 referred to the key to how the importer knows it. Look in the
15299 entity table slot that we nominate, maybe lazy load it, and then
15300 lookup the resultant entity in the entity hash to learn how the
15301 importer knows it.
15303 But we need to go in the other direction :( Given the key, find all
15304 the index-aliases of that key. We can partially solve that by
15305 adding an alias hash table. Whenever we load a merged decl, add or
15306 augment a mapping from the entity (or its entity-index) to the
15307 newly-discovered index. Then when we look for pending entities of
15308 a key, we also iterate over this aliases this mapping provides.
15310 But that requires the alias to be loaded. And that's not
15311 necessarily true.
15313 *** THE SIMPLER WAY
15315 The remaining fixed thing we have is the innermost namespace
15316 containing the ultimate namespace-scope container of the key and
15317 the name of that container (which might be the key itself). I.e. a
15318 namespace-decl/identifier/module tuple. Let's call this the
15319 top-key. We'll discover that the module is not important here,
15320 because of cross-module possibilities mentioned in case #c above.
15321 We can't markup namespace-binding slots. The best we can do is
15322 mark the binding vector with 'there's something here', and have
15323 another map from namespace/identifier pairs to a vector of pending
15324 entity indices.
15326 Maintain a pending-entity map. This is keyed by top-key, and
15327 maps to a vector of pending-entity indices. On the binding vector
15328 have flags saying whether the pending-name-entity map has contents.
15329 (We might want to further extend the key to be GM-vs-Partition and
15330 specialization-vs-member, but let's not get ahead of ourselves.)
15332 For every key-like entity, find the outermost namespace-scope
15333 name. Use that to lookup in the pending-entity map and then make
15334 sure the specified entities are loaded.
15336 An optimization might be to have a flag in each key-entity saying
15337 that it's top key might be in the entity table. It's not clear to
15338 me how to set that flag cheaply -- cheaper than just looking.
15340 FIXME: It'd be nice to have a bit in decls to tell us whether to
15341 even try this. We can have a 'already done' flag, that we set when
15342 we've done KLASS's lazy pendings. When we import a module that
15343 registers pendings on the same top-key as KLASS we need to clear
15344 the flag. A recursive walk of the top-key clearing the bit will
15345 suffice. Plus we only need to recurse on classes that have the bit
15346 set. (That means we need to set the bit on parents of KLASS here,
15347 don't forget.) However, first: correctness, second: efficiency. */
15349 unsigned
15350 module_state::write_pendings (elf_out *to, vec<depset *> depsets,
15351 depset::hash &table, unsigned *crc_p)
15353 dump () && dump ("Writing pending-entities");
15354 dump.indent ();
15356 trees_out sec (to, this, table);
15357 sec.begin ();
15359 unsigned count = 0;
15360 tree cache_ns = NULL_TREE;
15361 tree cache_id = NULL_TREE;
15362 unsigned cache_section = ~0;
15363 for (unsigned ix = 0; ix < depsets.length (); ix++)
15365 depset *d = depsets[ix];
15367 if (d->is_binding ())
15368 continue;
15370 if (d->is_import ())
15371 continue;
15373 if (!(d->get_entity_kind () == depset::EK_SPECIALIZATION
15374 || d->get_entity_kind () == depset::EK_PARTIAL
15375 || (d->get_entity_kind () == depset::EK_DECL && d->is_member ())))
15376 continue;
15378 tree key_decl = nullptr;
15379 tree key_ns = find_pending_key (d->get_entity (), &key_decl);
15380 tree key_name = DECL_NAME (key_decl);
15382 if (IDENTIFIER_ANON_P (key_name))
15384 gcc_checking_assert (IDENTIFIER_LAMBDA_P (key_name));
15385 if (tree attached = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (key_decl)))
15386 key_name = DECL_NAME (attached);
15387 else
15389 /* There's nothing to attach it to. Must
15390 always reinstantiate. */
15391 dump ()
15392 && dump ("Unattached lambda %N[%u] section:%u",
15393 d->get_entity_kind () == depset::EK_DECL
15394 ? "Member" : "Specialization", d->get_entity (),
15395 d->cluster, d->section);
15396 continue;
15400 char const *also = "";
15401 if (d->section == cache_section
15402 && key_ns == cache_ns
15403 && key_name == cache_id)
15404 /* Same section & key as previous, no need to repeat ourselves. */
15405 also = "also ";
15406 else
15408 cache_ns = key_ns;
15409 cache_id = key_name;
15410 cache_section = d->section;
15411 gcc_checking_assert (table.find_dependency (cache_ns));
15412 sec.tree_node (cache_ns);
15413 sec.tree_node (cache_id);
15414 sec.u (d->cluster);
15415 count++;
15417 dump () && dump ("Pending %s %N entity:%u section:%u %skeyed to %P",
15418 d->get_entity_kind () == depset::EK_DECL
15419 ? "member" : "specialization", d->get_entity (),
15420 d->cluster, cache_section, also, cache_ns, cache_id);
15422 sec.end (to, to->name (MOD_SNAME_PFX ".pnd"), crc_p);
15423 dump.outdent ();
15425 return count;
15428 bool
15429 module_state::read_pendings (unsigned count)
15431 trees_in sec (this);
15433 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".pnd"))
15434 return false;
15436 dump () && dump ("Reading %u pendings", count);
15437 dump.indent ();
15439 for (unsigned ix = 0; ix != count; ix++)
15441 pending_key key;
15442 unsigned index;
15444 key.ns = sec.tree_node ();
15445 key.id = sec.tree_node ();
15446 index = sec.u ();
15448 if (!key.ns || !key.id
15449 || !(TREE_CODE (key.ns) == NAMESPACE_DECL
15450 && !DECL_NAMESPACE_ALIAS (key.ns))
15451 || !identifier_p (key.id)
15452 || index >= entity_num)
15453 sec.set_overrun ();
15455 if (sec.get_overrun ())
15456 break;
15458 dump () && dump ("Pending:%u keyed to %P", index, key.ns, key.id);
15460 index += entity_lwm;
15461 auto &vec = pending_table->get_or_insert (key);
15462 vec.safe_push (index);
15465 dump.outdent ();
15466 if (!sec.end (from ()))
15467 return false;
15468 return true;
15471 /* Read & write locations. */
15472 enum loc_kind {
15473 LK_ORDINARY,
15474 LK_MACRO,
15475 LK_IMPORT_ORDINARY,
15476 LK_IMPORT_MACRO,
15477 LK_ADHOC,
15478 LK_RESERVED,
15481 static const module_state *
15482 module_for_ordinary_loc (location_t loc)
15484 unsigned pos = 0;
15485 unsigned len = ool->length () - pos;
15487 while (len)
15489 unsigned half = len / 2;
15490 module_state *probe = (*ool)[pos + half];
15491 if (loc < probe->ordinary_locs.first)
15492 len = half;
15493 else if (loc < probe->ordinary_locs.second)
15494 return probe;
15495 else
15497 pos += half + 1;
15498 len = len - (half + 1);
15502 return nullptr;
15505 static const module_state *
15506 module_for_macro_loc (location_t loc)
15508 unsigned pos = 1;
15509 unsigned len = modules->length () - pos;
15511 while (len)
15513 unsigned half = len / 2;
15514 module_state *probe = (*modules)[pos + half];
15515 if (loc >= probe->macro_locs.second)
15516 len = half;
15517 else if (loc >= probe->macro_locs.first)
15518 return probe;
15519 else
15521 pos += half + 1;
15522 len = len - (half + 1);
15526 return NULL;
15529 location_t
15530 module_state::imported_from () const
15532 location_t from = loc;
15533 line_map_ordinary const *fmap
15534 = linemap_check_ordinary (linemap_lookup (line_table, from));
15536 if (MAP_MODULE_P (fmap))
15537 from = linemap_included_from (fmap);
15539 return from;
15542 /* If we're not streaming, record that we need location LOC.
15543 Otherwise stream it. */
15545 void
15546 module_state::write_location (bytes_out &sec, location_t loc)
15548 if (!sec.streaming_p ())
15549 /* This is where we should note we use this location. See comment
15550 about write_ordinary_maps. */
15551 return;
15553 if (loc < RESERVED_LOCATION_COUNT)
15555 dump (dumper::LOCATION) && dump ("Reserved location %u", unsigned (loc));
15556 sec.u (LK_RESERVED + loc);
15558 else if (IS_ADHOC_LOC (loc))
15560 dump (dumper::LOCATION) && dump ("Adhoc location");
15561 sec.u (LK_ADHOC);
15562 location_t locus = get_location_from_adhoc_loc (line_table, loc);
15563 write_location (sec, locus);
15564 source_range range = get_range_from_loc (line_table, loc);
15565 if (range.m_start == locus)
15566 /* Compress. */
15567 range.m_start = UNKNOWN_LOCATION;
15568 write_location (sec, range.m_start);
15569 write_location (sec, range.m_finish);
15571 else if (loc >= LINEMAPS_MACRO_LOWEST_LOCATION (line_table))
15573 if (const loc_spans::span *span = spans.macro (loc))
15575 unsigned off = MAX_LOCATION_T - loc;
15577 off -= span->macro_delta;
15579 sec.u (LK_MACRO);
15580 sec.u (off);
15581 dump (dumper::LOCATION)
15582 && dump ("Macro location %u output %u", loc, off);
15584 else if (const module_state *import = module_for_macro_loc (loc))
15586 unsigned off = import->macro_locs.second - loc - 1;
15587 sec.u (LK_IMPORT_MACRO);
15588 sec.u (import->remap);
15589 sec.u (off);
15590 dump (dumper::LOCATION)
15591 && dump ("Imported macro location %u output %u:%u",
15592 loc, import->remap, off);
15594 else
15595 gcc_unreachable ();
15597 else if (IS_ORDINARY_LOC (loc))
15599 if (const loc_spans::span *span = spans.ordinary (loc))
15601 unsigned off = loc;
15603 off += span->ordinary_delta;
15604 sec.u (LK_ORDINARY);
15605 sec.u (off);
15607 dump (dumper::LOCATION)
15608 && dump ("Ordinary location %u output %u", loc, off);
15610 else if (const module_state *import = module_for_ordinary_loc (loc))
15612 unsigned off = loc - import->ordinary_locs.first;
15613 sec.u (LK_IMPORT_ORDINARY);
15614 sec.u (import->remap);
15615 sec.u (off);
15616 dump (dumper::LOCATION)
15617 && dump ("Imported ordinary location %u output %u:%u",
15618 import->remap, import->remap, off);
15620 else
15621 gcc_unreachable ();
15623 else
15624 gcc_unreachable ();
15627 location_t
15628 module_state::read_location (bytes_in &sec) const
15630 location_t locus = UNKNOWN_LOCATION;
15631 unsigned kind = sec.u ();
15632 switch (kind)
15634 default:
15636 if (kind < LK_RESERVED + RESERVED_LOCATION_COUNT)
15637 locus = location_t (kind - LK_RESERVED);
15638 else
15639 sec.set_overrun ();
15640 dump (dumper::LOCATION)
15641 && dump ("Reserved location %u", unsigned (locus));
15643 break;
15645 case LK_ADHOC:
15647 dump (dumper::LOCATION) && dump ("Adhoc location");
15648 locus = read_location (sec);
15649 source_range range;
15650 range.m_start = read_location (sec);
15651 if (range.m_start == UNKNOWN_LOCATION)
15652 range.m_start = locus;
15653 range.m_finish = read_location (sec);
15654 if (locus != loc && range.m_start != loc && range.m_finish != loc)
15655 locus = get_combined_adhoc_loc (line_table, locus, range, NULL);
15657 break;
15659 case LK_MACRO:
15661 unsigned off = sec.u ();
15663 if (macro_locs.first)
15665 location_t adjusted = MAX_LOCATION_T - off;
15666 adjusted -= slurp->loc_deltas.second;
15667 if (adjusted < macro_locs.first)
15668 sec.set_overrun ();
15669 else if (adjusted < macro_locs.second)
15670 locus = adjusted;
15671 else
15672 sec.set_overrun ();
15674 else
15675 locus = loc;
15676 dump (dumper::LOCATION)
15677 && dump ("Macro %u becoming %u", off, locus);
15679 break;
15681 case LK_ORDINARY:
15683 unsigned off = sec.u ();
15684 if (ordinary_locs.second)
15686 location_t adjusted = off;
15688 adjusted += slurp->loc_deltas.first;
15689 if (adjusted >= ordinary_locs.second)
15690 sec.set_overrun ();
15691 else if (adjusted >= ordinary_locs.first)
15692 locus = adjusted;
15693 else if (adjusted < spans.main_start ())
15694 locus = off;
15696 else
15697 locus = loc;
15699 dump (dumper::LOCATION)
15700 && dump ("Ordinary location %u becoming %u", off, locus);
15702 break;
15704 case LK_IMPORT_MACRO:
15705 case LK_IMPORT_ORDINARY:
15707 unsigned mod = sec.u ();
15708 unsigned off = sec.u ();
15709 const module_state *import = NULL;
15711 if (!mod && !slurp->remap)
15712 /* This is an early read of a partition location during the
15713 read of our ordinary location map. */
15714 import = this;
15715 else
15717 mod = slurp->remap_module (mod);
15718 if (!mod)
15719 sec.set_overrun ();
15720 else
15721 import = (*modules)[mod];
15724 if (import)
15726 if (kind == LK_IMPORT_MACRO)
15728 if (!import->macro_locs.first)
15729 locus = import->loc;
15730 else if (off < import->macro_locs.second - macro_locs.first)
15731 locus = import->macro_locs.second - off - 1;
15732 else
15733 sec.set_overrun ();
15735 else
15737 if (!import->ordinary_locs.second)
15738 locus = import->loc;
15739 else if (off < (import->ordinary_locs.second
15740 - import->ordinary_locs.first))
15741 locus = import->ordinary_locs.first + off;
15742 else
15743 sec.set_overrun ();
15747 break;
15750 return locus;
15753 /* Prepare the span adjustments. */
15755 // FIXME:QOI I do not prune the unreachable locations. Modules with
15756 // textually-large GMFs could well cause us to run out of locations.
15757 // Regular single-file modules could also be affected. We should
15758 // determine which locations we need to represent, so that we do not
15759 // grab more locations than necessary. An example is in
15760 // write_macro_maps where we work around macro expansions that are not
15761 // covering any locations -- the macro expands to nothing. Perhaps we
15762 // should decompose locations so that we can have a more graceful
15763 // degradation upon running out?
15765 location_map_info
15766 module_state::write_prepare_maps (module_state_config *)
15768 dump () && dump ("Preparing locations");
15769 dump.indent ();
15771 dump () && dump ("Reserved locations [%u,%u) macro [%u,%u)",
15772 spans[loc_spans::SPAN_RESERVED].ordinary.first,
15773 spans[loc_spans::SPAN_RESERVED].ordinary.second,
15774 spans[loc_spans::SPAN_RESERVED].macro.first,
15775 spans[loc_spans::SPAN_RESERVED].macro.second);
15777 location_map_info info;
15779 info.num_maps.first = info.num_maps.second = 0;
15781 /* Figure the alignment of ordinary location spans. */
15782 unsigned max_range = 0;
15783 for (unsigned ix = loc_spans::SPAN_FIRST; ix != spans.length (); ix++)
15785 loc_spans::span &span = spans[ix];
15787 if (span.ordinary.first != span.ordinary.second)
15789 line_map_ordinary const *omap
15790 = linemap_check_ordinary (linemap_lookup (line_table,
15791 span.ordinary.first));
15793 /* We should exactly match up. */
15794 gcc_checking_assert (MAP_START_LOCATION (omap) == span.ordinary.first);
15796 line_map_ordinary const *fmap = omap;
15797 for (; MAP_START_LOCATION (omap) < span.ordinary.second; omap++)
15799 /* We should never find a module linemap in an interval. */
15800 gcc_checking_assert (!MAP_MODULE_P (omap));
15802 if (max_range < omap->m_range_bits)
15803 max_range = omap->m_range_bits;
15806 info.num_maps.first += omap - fmap;
15809 if (span.macro.first != span.macro.second)
15811 /* Iterate over the span's macros, to elide the empty
15812 expansions. */
15813 unsigned count = 0;
15814 for (unsigned macro
15815 = linemap_lookup_macro_index (line_table,
15816 span.macro.second - 1);
15817 macro < LINEMAPS_MACRO_USED (line_table);
15818 macro++)
15820 line_map_macro const *mmap
15821 = LINEMAPS_MACRO_MAP_AT (line_table, macro);
15822 if (MAP_START_LOCATION (mmap) < span.macro.first)
15823 /* Fallen out of the span. */
15824 break;
15826 if (mmap->n_tokens)
15827 count++;
15829 dump (dumper::LOCATION) && dump ("Span:%u %u macro maps", ix, count);
15830 info.num_maps.second += count;
15834 /* Adjust the maps. Ordinary ones ascend, and we must maintain
15835 alignment. Macro ones descend, but are unaligned. */
15836 location_t ord_off = spans[loc_spans::SPAN_FIRST].ordinary.first;
15837 location_t mac_off = spans[loc_spans::SPAN_FIRST].macro.second;
15838 location_t range_mask = (1u << max_range) - 1;
15840 dump () && dump ("Ordinary maps range bits:%u, preserve:%x, zero:%u",
15841 max_range, ord_off & range_mask, ord_off & ~range_mask);
15843 for (unsigned ix = loc_spans::SPAN_FIRST; ix != spans.length (); ix++)
15845 loc_spans::span &span = spans[ix];
15847 span.macro_delta = mac_off - span.macro.second;
15848 mac_off -= span.macro.second - span.macro.first;
15849 dump () && dump ("Macro span:%u [%u,%u):%u->%d(%u)", ix,
15850 span.macro.first, span.macro.second,
15851 span.macro.second - span.macro.first,
15852 span.macro_delta, span.macro.first + span.macro_delta);
15854 line_map_ordinary const *omap
15855 = linemap_check_ordinary (linemap_lookup (line_table,
15856 span.ordinary.first));
15857 location_t base = MAP_START_LOCATION (omap);
15859 /* Preserve the low MAX_RANGE bits of base by incrementing ORD_OFF. */
15860 unsigned low_bits = base & range_mask;
15861 if ((ord_off & range_mask) > low_bits)
15862 low_bits += range_mask + 1;
15863 ord_off = (ord_off & ~range_mask) + low_bits;
15864 span.ordinary_delta = ord_off - base;
15866 for (; MAP_START_LOCATION (omap) < span.ordinary.second; omap++)
15868 location_t start_loc = MAP_START_LOCATION (omap);
15869 unsigned to = start_loc + span.ordinary_delta;
15870 location_t end_loc = MAP_START_LOCATION (omap + 1);
15872 dump () && dump ("Ordinary span:%u [%u,%u):%u->%d(%u)",
15873 ix, start_loc,
15874 end_loc, end_loc - start_loc,
15875 span.ordinary_delta, to);
15877 /* There should be no change in the low order bits. */
15878 gcc_checking_assert (((start_loc ^ to) & range_mask) == 0);
15881 /* The ending serialized value. */
15882 ord_off = span.ordinary.second + span.ordinary_delta;
15885 dump () && dump ("Ordinary:%u maps hwm:%u macro:%u maps lwm:%u ",
15886 info.num_maps.first, ord_off,
15887 info.num_maps.second, mac_off);
15889 dump.outdent ();
15891 info.max_range = max_range;
15893 return info;
15896 bool
15897 module_state::read_prepare_maps (const module_state_config *cfg)
15899 location_t ordinary = line_table->highest_location + 1;
15900 ordinary = ((ordinary + (1u << cfg->ordinary_loc_align))
15901 & ~((1u << cfg->ordinary_loc_align) - 1));
15902 ordinary += cfg->ordinary_locs;
15904 location_t macro = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
15905 macro -= cfg->macro_locs;
15907 if (ordinary < LINE_MAP_MAX_LOCATION_WITH_COLS
15908 && macro >= LINE_MAP_MAX_LOCATION)
15909 /* OK, we have enough locations. */
15910 return true;
15912 ordinary_locs.first = ordinary_locs.second = 0;
15913 macro_locs.first = macro_locs.second = 0;
15915 static bool informed = false;
15916 if (!informed)
15918 /* Just give the notice once. */
15919 informed = true;
15920 inform (loc, "unable to represent further imported source locations");
15923 return false;
15926 /* Write the location maps. This also determines the shifts for the
15927 location spans. */
15929 void
15930 module_state::write_ordinary_maps (elf_out *to, location_map_info &info,
15931 module_state_config *cfg, bool has_partitions,
15932 unsigned *crc_p)
15934 dump () && dump ("Writing ordinary location maps");
15935 dump.indent ();
15937 vec<const char *> filenames;
15938 filenames.create (20);
15940 /* Determine the unique filenames. */
15941 // FIXME:QOI We should find the set of filenames when working out
15942 // which locations we actually need. See write_prepare_maps.
15943 for (unsigned ix = loc_spans::SPAN_FIRST; ix != spans.length (); ix++)
15945 loc_spans::span &span = spans[ix];
15946 line_map_ordinary const *omap
15947 = linemap_check_ordinary (linemap_lookup (line_table,
15948 span.ordinary.first));
15950 /* We should exactly match up. */
15951 gcc_checking_assert (MAP_START_LOCATION (omap) == span.ordinary.first);
15953 for (; MAP_START_LOCATION (omap) < span.ordinary.second; omap++)
15955 const char *fname = ORDINARY_MAP_FILE_NAME (omap);
15957 /* We should never find a module linemap in an interval. */
15958 gcc_checking_assert (!MAP_MODULE_P (omap));
15960 /* We expect very few filenames, so just an array.
15961 (Not true when headers are still in play :() */
15962 for (unsigned jx = filenames.length (); jx--;)
15964 const char *name = filenames[jx];
15965 if (0 == strcmp (name, fname))
15967 /* Reset the linemap's name, because for things like
15968 preprocessed input we could have multiple
15969 instances of the same name, and we'd rather not
15970 percolate that. */
15971 const_cast<line_map_ordinary *> (omap)->to_file = name;
15972 fname = NULL;
15973 break;
15976 if (fname)
15977 filenames.safe_push (fname);
15981 bytes_out sec (to);
15982 sec.begin ();
15984 /* Write the filenames. */
15985 unsigned len = filenames.length ();
15986 sec.u (len);
15987 dump () && dump ("%u source file names", len);
15988 for (unsigned ix = 0; ix != len; ix++)
15990 const char *fname = filenames[ix];
15991 dump (dumper::LOCATION) && dump ("Source file[%u]=%s", ix, fname);
15992 sec.str (fname);
15995 location_t offset = spans[loc_spans::SPAN_FIRST].ordinary.first;
15996 location_t range_mask = (1u << info.max_range) - 1;
15998 dump () && dump ("Ordinary maps:%u, range bits:%u, preserve:%x, zero:%u",
15999 info.num_maps.first, info.max_range, offset & range_mask,
16000 offset & ~range_mask);
16001 sec.u (info.num_maps.first); /* Num maps. */
16002 sec.u (info.max_range); /* Maximum range bits */
16003 sec.u (offset & range_mask); /* Bits to preserve. */
16004 sec.u (offset & ~range_mask);
16006 for (unsigned ix = loc_spans::SPAN_FIRST; ix != spans.length (); ix++)
16008 loc_spans::span &span = spans[ix];
16009 line_map_ordinary const *omap
16010 = linemap_check_ordinary (linemap_lookup (line_table,
16011 span.ordinary.first));
16012 for (; MAP_START_LOCATION (omap) < span.ordinary.second; omap++)
16014 location_t start_loc = MAP_START_LOCATION (omap);
16015 unsigned to = start_loc + span.ordinary_delta;
16017 dump (dumper::LOCATION)
16018 && dump ("Span:%u ordinary [%u,%u)->%u", ix, start_loc,
16019 MAP_START_LOCATION (omap + 1), to);
16021 /* There should be no change in the low order bits. */
16022 gcc_checking_assert (((start_loc ^ to) & range_mask) == 0);
16023 sec.u (to);
16025 /* Making accessors just for here, seems excessive. */
16026 sec.u (omap->reason);
16027 sec.u (omap->sysp);
16028 sec.u (omap->m_range_bits);
16029 sec.u (omap->m_column_and_range_bits - omap->m_range_bits);
16031 const char *fname = ORDINARY_MAP_FILE_NAME (omap);
16032 for (unsigned ix = 0; ix != filenames.length (); ix++)
16033 if (filenames[ix] == fname)
16035 sec.u (ix);
16036 break;
16038 sec.u (ORDINARY_MAP_STARTING_LINE_NUMBER (omap));
16040 /* Write the included from location, which means reading it
16041 while reading in the ordinary maps. So we'd better not
16042 be getting ahead of ourselves. */
16043 location_t from = linemap_included_from (omap);
16044 gcc_checking_assert (from < MAP_START_LOCATION (omap));
16045 if (from != UNKNOWN_LOCATION && has_partitions)
16047 /* A partition's span will have a from pointing at a
16048 MODULE_INC. Find that map's from. */
16049 line_map_ordinary const *fmap
16050 = linemap_check_ordinary (linemap_lookup (line_table, from));
16051 if (MAP_MODULE_P (fmap))
16052 from = linemap_included_from (fmap);
16054 write_location (sec, from);
16056 /* The ending serialized value. */
16057 offset = MAP_START_LOCATION (omap) + span.ordinary_delta;
16059 dump () && dump ("Ordinary location hwm:%u", offset);
16060 sec.u (offset);
16062 // Record number of locations and alignment.
16063 cfg->ordinary_loc_align = info.max_range;
16064 cfg->ordinary_locs = offset;
16066 filenames.release ();
16068 sec.end (to, to->name (MOD_SNAME_PFX ".olm"), crc_p);
16069 dump.outdent ();
16072 void
16073 module_state::write_macro_maps (elf_out *to, location_map_info &info,
16074 module_state_config *cfg, unsigned *crc_p)
16076 dump () && dump ("Writing macro location maps");
16077 dump.indent ();
16079 bytes_out sec (to);
16080 sec.begin ();
16082 dump () && dump ("Macro maps:%u", info.num_maps.second);
16083 sec.u (info.num_maps.second);
16085 location_t offset = spans[loc_spans::SPAN_FIRST].macro.second;
16086 sec.u (offset);
16088 unsigned macro_num = 0;
16089 for (unsigned ix = loc_spans::SPAN_FIRST; ix != spans.length (); ix++)
16091 loc_spans::span &span = spans[ix];
16092 if (span.macro.first == span.macro.second)
16093 /* Empty span. */
16094 continue;
16096 for (unsigned macro
16097 = linemap_lookup_macro_index (line_table, span.macro.second - 1);
16098 macro < LINEMAPS_MACRO_USED (line_table);
16099 macro++)
16101 line_map_macro const *mmap
16102 = LINEMAPS_MACRO_MAP_AT (line_table, macro);
16103 location_t start_loc = MAP_START_LOCATION (mmap);
16104 if (start_loc < span.macro.first)
16105 /* Fallen out of the span. */
16106 break;
16108 if (!mmap->n_tokens)
16109 /* Empty expansion. */
16110 continue;
16112 sec.u (offset);
16113 sec.u (mmap->n_tokens);
16114 sec.cpp_node (mmap->macro);
16115 write_location (sec, mmap->expansion);
16116 const location_t *locs = mmap->macro_locations;
16117 /* There are lots of identical runs. */
16118 location_t prev = UNKNOWN_LOCATION;
16119 unsigned count = 0;
16120 unsigned runs = 0;
16121 for (unsigned jx = mmap->n_tokens * 2; jx--;)
16123 location_t tok_loc = locs[jx];
16124 if (tok_loc == prev)
16126 count++;
16127 continue;
16129 runs++;
16130 sec.u (count);
16131 count = 1;
16132 prev = tok_loc;
16133 write_location (sec, tok_loc);
16135 sec.u (count);
16136 dump (dumper::LOCATION)
16137 && dump ("Span:%u macro:%u %I %u/%u*2 locations [%u,%u)->%u",
16138 ix, macro_num, identifier (mmap->macro),
16139 runs, mmap->n_tokens,
16140 start_loc, start_loc + mmap->n_tokens,
16141 start_loc + span.macro_delta);
16142 macro_num++;
16143 offset -= mmap->n_tokens;
16144 gcc_checking_assert (offset == start_loc + span.macro_delta);
16147 dump () && dump ("Macro location lwm:%u", offset);
16148 sec.u (offset);
16149 gcc_assert (macro_num == info.num_maps.second);
16151 cfg->macro_locs = MAX_LOCATION_T + 1 - offset;
16153 sec.end (to, to->name (MOD_SNAME_PFX ".mlm"), crc_p);
16154 dump.outdent ();
16157 bool
16158 module_state::read_ordinary_maps ()
16160 bytes_in sec;
16162 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".olm"))
16163 return false;
16164 dump () && dump ("Reading ordinary location maps");
16165 dump.indent ();
16167 /* Read the filename table. */
16168 unsigned len = sec.u ();
16169 dump () && dump ("%u source file names", len);
16170 vec<const char *> filenames;
16171 filenames.create (len);
16172 for (unsigned ix = 0; ix != len; ix++)
16174 size_t l;
16175 const char *buf = sec.str (&l);
16176 char *fname = XNEWVEC (char, l + 1);
16177 memcpy (fname, buf, l + 1);
16178 dump (dumper::LOCATION) && dump ("Source file[%u]=%s", ix, fname);
16179 /* We leak these names into the line-map table. But it
16180 doesn't own them. */
16181 filenames.quick_push (fname);
16184 unsigned num_ordinary = sec.u ();
16185 unsigned max_range = sec.u ();
16186 unsigned low_bits = sec.u ();
16187 location_t zero = sec.u ();
16188 location_t range_mask = (1u << max_range) - 1;
16190 dump () && dump ("Ordinary maps:%u, range bits:%u, preserve:%x, zero:%u",
16191 num_ordinary, max_range, low_bits, zero);
16193 location_t offset = line_table->highest_location + 1;
16194 /* Ensure offset doesn't go backwards at the start. */
16195 if ((offset & range_mask) > low_bits)
16196 offset += range_mask + 1;
16197 offset = (offset & ~range_mask);
16199 bool propagated = spans.maybe_propagate (this, offset + low_bits);
16201 line_map_ordinary *maps = static_cast<line_map_ordinary *>
16202 (line_map_new_raw (line_table, false, num_ordinary));
16204 location_t lwm = offset;
16205 slurp->loc_deltas.first = offset - zero;
16206 ordinary_locs.first = zero + low_bits + slurp->loc_deltas.first;
16207 dump () && dump ("Ordinary loc delta %d", slurp->loc_deltas.first);
16209 for (unsigned ix = 0; ix != num_ordinary && !sec.get_overrun (); ix++)
16211 line_map_ordinary *map = &maps[ix];
16212 unsigned hwm = sec.u ();
16214 /* Record the current HWM so that the below read_location is
16215 ok. */
16216 ordinary_locs.second = hwm + slurp->loc_deltas.first;
16217 map->start_location = hwm + (offset - zero);
16218 if (map->start_location < lwm)
16219 sec.set_overrun ();
16220 lwm = map->start_location;
16221 dump (dumper::LOCATION) && dump ("Map:%u %u->%u", ix, hwm, lwm);
16222 map->reason = lc_reason (sec.u ());
16223 map->sysp = sec.u ();
16224 map->m_range_bits = sec.u ();
16225 map->m_column_and_range_bits = map->m_range_bits + sec.u ();
16227 unsigned fnum = sec.u ();
16228 map->to_file = (fnum < filenames.length () ? filenames[fnum] : "");
16229 map->to_line = sec.u ();
16231 /* Root the outermost map at our location. */
16232 location_t from = read_location (sec);
16233 map->included_from = from != UNKNOWN_LOCATION ? from : loc;
16236 location_t hwm = sec.u ();
16237 ordinary_locs.second = hwm + slurp->loc_deltas.first;
16239 /* highest_location is the one handed out, not the next one to
16240 hand out. */
16241 line_table->highest_location = ordinary_locs.second - 1;
16243 if (line_table->highest_location >= LINE_MAP_MAX_LOCATION_WITH_COLS)
16244 /* We shouldn't run out of locations, as we checked before
16245 starting. */
16246 sec.set_overrun ();
16247 dump () && dump ("Ordinary location hwm:%u", ordinary_locs.second);
16249 if (propagated)
16250 spans.close ();
16252 filenames.release ();
16254 dump.outdent ();
16255 if (!sec.end (from ()))
16256 return false;
16258 return true;
16261 bool
16262 module_state::read_macro_maps ()
16264 bytes_in sec;
16266 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".mlm"))
16267 return false;
16268 dump () && dump ("Reading macro location maps");
16269 dump.indent ();
16271 unsigned num_macros = sec.u ();
16272 location_t zero = sec.u ();
16273 dump () && dump ("Macro maps:%u zero:%u", num_macros, zero);
16275 bool propagated = spans.maybe_propagate (this,
16276 line_table->highest_location + 1);
16278 location_t offset = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
16279 slurp->loc_deltas.second = zero - offset;
16280 macro_locs.second = zero - slurp->loc_deltas.second;
16281 dump () && dump ("Macro loc delta %d", slurp->loc_deltas.second);
16283 for (unsigned ix = 0; ix != num_macros && !sec.get_overrun (); ix++)
16285 unsigned lwm = sec.u ();
16286 /* Record the current LWM so that the below read_location is
16287 ok. */
16288 macro_locs.first = lwm - slurp->loc_deltas.second;
16290 unsigned n_tokens = sec.u ();
16291 cpp_hashnode *node = sec.cpp_node ();
16292 location_t exp_loc = read_location (sec);
16294 const line_map_macro *macro
16295 = linemap_enter_macro (line_table, node, exp_loc, n_tokens);
16296 if (!macro)
16297 /* We shouldn't run out of locations, as we checked that we
16298 had enough before starting. */
16299 break;
16301 location_t *locs = macro->macro_locations;
16302 location_t tok_loc = UNKNOWN_LOCATION;
16303 unsigned count = sec.u ();
16304 unsigned runs = 0;
16305 for (unsigned jx = macro->n_tokens * 2; jx-- && !sec.get_overrun ();)
16307 while (!count-- && !sec.get_overrun ())
16309 runs++;
16310 tok_loc = read_location (sec);
16311 count = sec.u ();
16313 locs[jx] = tok_loc;
16315 if (count)
16316 sec.set_overrun ();
16317 dump (dumper::LOCATION)
16318 && dump ("Macro:%u %I %u/%u*2 locations [%u,%u)",
16319 ix, identifier (node), runs, n_tokens,
16320 MAP_START_LOCATION (macro),
16321 MAP_START_LOCATION (macro) + n_tokens);
16323 location_t lwm = sec.u ();
16324 macro_locs.first = lwm - slurp->loc_deltas.second;
16326 dump () && dump ("Macro location lwm:%u", macro_locs.first);
16328 if (propagated)
16329 spans.close ();
16331 dump.outdent ();
16332 if (!sec.end (from ()))
16333 return false;
16335 return true;
16338 /* Serialize the definition of MACRO. */
16340 void
16341 module_state::write_define (bytes_out &sec, const cpp_macro *macro, bool located)
16343 sec.u (macro->count);
16345 sec.b (macro->fun_like);
16346 sec.b (macro->variadic);
16347 sec.b (macro->syshdr);
16348 sec.bflush ();
16350 if (located)
16351 write_location (sec, macro->line);
16352 if (macro->fun_like)
16354 sec.u (macro->paramc);
16355 const cpp_hashnode *const *parms = macro->parm.params;
16356 for (unsigned ix = 0; ix != macro->paramc; ix++)
16357 sec.cpp_node (parms[ix]);
16360 unsigned len = 0;
16361 for (unsigned ix = 0; ix != macro->count; ix++)
16363 const cpp_token *token = &macro->exp.tokens[ix];
16364 if (located)
16365 write_location (sec, token->src_loc);
16366 sec.u (token->type);
16367 sec.u (token->flags);
16368 switch (cpp_token_val_index (token))
16370 default:
16371 gcc_unreachable ();
16373 case CPP_TOKEN_FLD_ARG_NO:
16374 /* An argument reference. */
16375 sec.u (token->val.macro_arg.arg_no);
16376 sec.cpp_node (token->val.macro_arg.spelling);
16377 break;
16379 case CPP_TOKEN_FLD_NODE:
16380 /* An identifier. */
16381 sec.cpp_node (token->val.node.node);
16382 if (token->val.node.spelling == token->val.node.node)
16383 /* The spelling will usually be the same. so optimize
16384 that. */
16385 sec.str (NULL, 0);
16386 else
16387 sec.cpp_node (token->val.node.spelling);
16388 break;
16390 case CPP_TOKEN_FLD_NONE:
16391 break;
16393 case CPP_TOKEN_FLD_STR:
16394 /* A string, number or comment. Not always NUL terminated,
16395 we stream out in a single contatenation with embedded
16396 NULs as that's a safe default. */
16397 len += token->val.str.len + 1;
16398 sec.u (token->val.str.len);
16399 break;
16401 case CPP_TOKEN_FLD_SOURCE:
16402 case CPP_TOKEN_FLD_TOKEN_NO:
16403 case CPP_TOKEN_FLD_PRAGMA:
16404 /* These do not occur inside a macro itself. */
16405 gcc_unreachable ();
16409 if (len)
16411 char *ptr = reinterpret_cast<char *> (sec.buf (len));
16412 len = 0;
16413 for (unsigned ix = 0; ix != macro->count; ix++)
16415 const cpp_token *token = &macro->exp.tokens[ix];
16416 if (cpp_token_val_index (token) == CPP_TOKEN_FLD_STR)
16418 memcpy (ptr + len, token->val.str.text,
16419 token->val.str.len);
16420 len += token->val.str.len;
16421 ptr[len++] = 0;
16427 /* Read a macro definition. */
16429 cpp_macro *
16430 module_state::read_define (bytes_in &sec, cpp_reader *reader, bool located) const
16432 unsigned count = sec.u ();
16433 /* We rely on knowing cpp_reader's hash table is ident_hash, and
16434 it's subobject allocator is stringpool_ggc_alloc and that is just
16435 a wrapper for ggc_alloc_atomic. */
16436 cpp_macro *macro
16437 = (cpp_macro *)ggc_alloc_atomic (sizeof (cpp_macro)
16438 + sizeof (cpp_token) * (count - !!count));
16439 memset (macro, 0, sizeof (cpp_macro) + sizeof (cpp_token) * (count - !!count));
16441 macro->count = count;
16442 macro->kind = cmk_macro;
16443 macro->imported_p = true;
16445 macro->fun_like = sec.b ();
16446 macro->variadic = sec.b ();
16447 macro->syshdr = sec.b ();
16448 sec.bflush ();
16450 macro->line = located ? read_location (sec) : loc;
16452 if (macro->fun_like)
16454 unsigned paramc = sec.u ();
16455 cpp_hashnode **params
16456 = (cpp_hashnode **)ggc_alloc_atomic (sizeof (cpp_hashnode *) * paramc);
16457 macro->paramc = paramc;
16458 macro->parm.params = params;
16459 for (unsigned ix = 0; ix != paramc; ix++)
16460 params[ix] = sec.cpp_node ();
16463 unsigned len = 0;
16464 for (unsigned ix = 0; ix != count && !sec.get_overrun (); ix++)
16466 cpp_token *token = &macro->exp.tokens[ix];
16467 token->src_loc = located ? read_location (sec) : loc;
16468 token->type = cpp_ttype (sec.u ());
16469 token->flags = sec.u ();
16470 switch (cpp_token_val_index (token))
16472 default:
16473 sec.set_overrun ();
16474 break;
16476 case CPP_TOKEN_FLD_ARG_NO:
16477 /* An argument reference. */
16479 unsigned arg_no = sec.u ();
16480 if (arg_no - 1 >= macro->paramc)
16481 sec.set_overrun ();
16482 token->val.macro_arg.arg_no = arg_no;
16483 token->val.macro_arg.spelling = sec.cpp_node ();
16485 break;
16487 case CPP_TOKEN_FLD_NODE:
16488 /* An identifier. */
16489 token->val.node.node = sec.cpp_node ();
16490 token->val.node.spelling = sec.cpp_node ();
16491 if (!token->val.node.spelling)
16492 token->val.node.spelling = token->val.node.node;
16493 break;
16495 case CPP_TOKEN_FLD_NONE:
16496 break;
16498 case CPP_TOKEN_FLD_STR:
16499 /* A string, number or comment. */
16500 token->val.str.len = sec.u ();
16501 len += token->val.str.len + 1;
16502 break;
16506 if (len)
16507 if (const char *ptr = reinterpret_cast<const char *> (sec.buf (len)))
16509 /* There should be a final NUL. */
16510 if (ptr[len-1])
16511 sec.set_overrun ();
16512 /* cpp_alloc_token_string will add a final NUL. */
16513 const unsigned char *buf
16514 = cpp_alloc_token_string (reader, (const unsigned char *)ptr, len - 1);
16515 len = 0;
16516 for (unsigned ix = 0; ix != count && !sec.get_overrun (); ix++)
16518 cpp_token *token = &macro->exp.tokens[ix];
16519 if (cpp_token_val_index (token) == CPP_TOKEN_FLD_STR)
16521 token->val.str.text = buf + len;
16522 len += token->val.str.len;
16523 if (buf[len++])
16524 sec.set_overrun ();
16529 if (sec.get_overrun ())
16530 return NULL;
16531 return macro;
16534 /* Exported macro data. */
16535 struct GTY(()) macro_export {
16536 cpp_macro *def;
16537 location_t undef_loc;
16539 macro_export ()
16540 :def (NULL), undef_loc (UNKNOWN_LOCATION)
16545 /* Imported macro data. */
16546 class macro_import {
16547 public:
16548 struct slot {
16549 #if defined (WORDS_BIGENDIAN) && SIZEOF_VOID_P == 8
16550 int offset;
16551 #endif
16552 /* We need to ensure we don't use the LSB for representation, as
16553 that's the union discriminator below. */
16554 unsigned bits;
16556 #if !(defined (WORDS_BIGENDIAN) && SIZEOF_VOID_P == 8)
16557 int offset;
16558 #endif
16560 public:
16561 enum Layout {
16562 L_DEF = 1,
16563 L_UNDEF = 2,
16564 L_BOTH = 3,
16565 L_MODULE_SHIFT = 2
16568 public:
16569 /* Not a regular ctor, because we put it in a union, and that's
16570 not allowed in C++ 98. */
16571 static slot ctor (unsigned module, unsigned defness)
16573 gcc_checking_assert (defness);
16574 slot s;
16575 s.bits = defness | (module << L_MODULE_SHIFT);
16576 s.offset = -1;
16577 return s;
16580 public:
16581 unsigned get_defness () const
16583 return bits & L_BOTH;
16585 unsigned get_module () const
16587 return bits >> L_MODULE_SHIFT;
16589 void become_undef ()
16591 bits &= ~unsigned (L_DEF);
16592 bits |= unsigned (L_UNDEF);
16596 private:
16597 typedef vec<slot, va_heap, vl_embed> ary_t;
16598 union either {
16599 /* Discriminated by bits 0|1 != 0. The expected case is that
16600 there will be exactly one slot per macro, hence the effort of
16601 packing that. */
16602 ary_t *ary;
16603 slot single;
16604 } u;
16606 public:
16607 macro_import ()
16609 u.ary = NULL;
16612 private:
16613 bool single_p () const
16615 return u.single.bits & slot::L_BOTH;
16617 bool occupied_p () const
16619 return u.ary != NULL;
16622 public:
16623 unsigned length () const
16625 gcc_checking_assert (occupied_p ());
16626 return single_p () ? 1 : u.ary->length ();
16628 slot &operator[] (unsigned ix)
16630 gcc_checking_assert (occupied_p ());
16631 if (single_p ())
16633 gcc_checking_assert (!ix);
16634 return u.single;
16636 else
16637 return (*u.ary)[ix];
16640 public:
16641 slot &exported ();
16642 slot &append (unsigned module, unsigned defness);
16645 /* O is a new import to append to the list for. If we're an empty
16646 set, initialize us. */
16648 macro_import::slot &
16649 macro_import::append (unsigned module, unsigned defness)
16651 if (!occupied_p ())
16653 u.single = slot::ctor (module, defness);
16654 return u.single;
16656 else
16658 bool single = single_p ();
16659 ary_t *m = single ? NULL : u.ary;
16660 vec_safe_reserve (m, 1 + single);
16661 if (single)
16662 m->quick_push (u.single);
16663 u.ary = m;
16664 return *u.ary->quick_push (slot::ctor (module, defness));
16668 /* We're going to export something. Make sure the first import slot
16669 is us. */
16671 macro_import::slot &
16672 macro_import::exported ()
16674 if (occupied_p () && !(*this)[0].get_module ())
16676 slot &res = (*this)[0];
16677 res.bits |= slot::L_DEF;
16678 return res;
16681 slot *a = &append (0, slot::L_DEF);
16682 if (!single_p ())
16684 slot &f = (*this)[0];
16685 std::swap (f, *a);
16686 a = &f;
16688 return *a;
16691 /* The import (&exported) macros. cpp_hasnode's deferred field
16692 indexes this array (offset by 1, so zero means 'not present'. */
16694 static vec<macro_import, va_heap, vl_embed> *macro_imports;
16696 /* The exported macros. A macro_import slot's zeroth element's offset
16697 indexes this array. If the zeroth slot is not for module zero,
16698 there is no export. */
16700 static GTY(()) vec<macro_export, va_gc> *macro_exports;
16702 /* The reachable set of header imports from this TU. */
16704 static GTY(()) bitmap headers;
16706 /* Get the (possibly empty) macro imports for NODE. */
16708 static macro_import &
16709 get_macro_imports (cpp_hashnode *node)
16711 if (node->deferred)
16712 return (*macro_imports)[node->deferred - 1];
16714 vec_safe_reserve (macro_imports, 1);
16715 node->deferred = macro_imports->length () + 1;
16716 return *vec_safe_push (macro_imports, macro_import ());
16719 /* Get the macro export for export EXP of NODE. */
16721 static macro_export &
16722 get_macro_export (macro_import::slot &slot)
16724 if (slot.offset >= 0)
16725 return (*macro_exports)[slot.offset];
16727 vec_safe_reserve (macro_exports, 1);
16728 slot.offset = macro_exports->length ();
16729 return *macro_exports->quick_push (macro_export ());
16732 /* If NODE is an exportable macro, add it to the export set. */
16734 static int
16735 maybe_add_macro (cpp_reader *, cpp_hashnode *node, void *data_)
16737 bool exporting = false;
16739 if (cpp_user_macro_p (node))
16740 if (cpp_macro *macro = node->value.macro)
16741 /* Ignore imported, builtins, command line and forced header macros. */
16742 if (!macro->imported_p
16743 && !macro->lazy && macro->line >= spans.main_start ())
16745 gcc_checking_assert (macro->kind == cmk_macro);
16746 /* I don't want to deal with this corner case, that I suspect is
16747 a devil's advocate reading of the standard. */
16748 gcc_checking_assert (!macro->extra_tokens);
16750 macro_import::slot &slot = get_macro_imports (node).exported ();
16751 macro_export &exp = get_macro_export (slot);
16752 exp.def = macro;
16753 exporting = true;
16756 if (!exporting && node->deferred)
16758 macro_import &imports = (*macro_imports)[node->deferred - 1];
16759 macro_import::slot &slot = imports[0];
16760 if (!slot.get_module ())
16762 gcc_checking_assert (slot.get_defness ());
16763 exporting = true;
16767 if (exporting)
16768 static_cast<vec<cpp_hashnode *> *> (data_)->safe_push (node);
16770 return 1; /* Don't stop. */
16773 /* Order cpp_hashnodes A_ and B_ by their exported macro locations. */
16775 static int
16776 macro_loc_cmp (const void *a_, const void *b_)
16778 const cpp_hashnode *node_a = *(const cpp_hashnode *const *)a_;
16779 macro_import &import_a = (*macro_imports)[node_a->deferred - 1];
16780 const macro_export &export_a = (*macro_exports)[import_a[0].offset];
16781 location_t loc_a = export_a.def ? export_a.def->line : export_a.undef_loc;
16783 const cpp_hashnode *node_b = *(const cpp_hashnode *const *)b_;
16784 macro_import &import_b = (*macro_imports)[node_b->deferred - 1];
16785 const macro_export &export_b = (*macro_exports)[import_b[0].offset];
16786 location_t loc_b = export_b.def ? export_b.def->line : export_b.undef_loc;
16788 if (loc_a < loc_b)
16789 return +1;
16790 else if (loc_a > loc_b)
16791 return -1;
16792 else
16793 return 0;
16796 /* Write out the exported defines. This is two sections, one
16797 containing the definitions, the other a table of node names. */
16799 unsigned
16800 module_state::write_macros (elf_out *to, cpp_reader *reader, unsigned *crc_p)
16802 dump () && dump ("Writing macros");
16803 dump.indent ();
16805 vec<cpp_hashnode *> macros;
16806 macros.create (100);
16807 cpp_forall_identifiers (reader, maybe_add_macro, &macros);
16809 dump (dumper::MACRO) && dump ("No more than %u macros", macros.length ());
16811 macros.qsort (macro_loc_cmp);
16813 /* Write the defs */
16814 bytes_out sec (to);
16815 sec.begin ();
16817 unsigned count = 0;
16818 for (unsigned ix = macros.length (); ix--;)
16820 cpp_hashnode *node = macros[ix];
16821 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
16822 gcc_assert (!slot.get_module () && slot.get_defness ());
16824 macro_export &mac = (*macro_exports)[slot.offset];
16825 gcc_assert (!!(slot.get_defness () & macro_import::slot::L_UNDEF)
16826 == (mac.undef_loc != UNKNOWN_LOCATION)
16827 && !!(slot.get_defness () & macro_import::slot::L_DEF)
16828 == (mac.def != NULL));
16830 if (IDENTIFIER_KEYWORD_P (identifier (node)))
16832 warning_at (mac.def->line, 0,
16833 "not exporting %<#define %E%> as it is a keyword",
16834 identifier (node));
16835 slot.offset = 0;
16836 continue;
16839 count++;
16840 slot.offset = sec.pos;
16841 dump (dumper::MACRO)
16842 && dump ("Writing macro %s%s%s %I at %u",
16843 slot.get_defness () & macro_import::slot::L_UNDEF
16844 ? "#undef" : "",
16845 slot.get_defness () == macro_import::slot::L_BOTH
16846 ? " & " : "",
16847 slot.get_defness () & macro_import::slot::L_DEF
16848 ? "#define" : "",
16849 identifier (node), slot.offset);
16850 if (mac.undef_loc != UNKNOWN_LOCATION)
16851 write_location (sec, mac.undef_loc);
16852 if (mac.def)
16853 write_define (sec, mac.def);
16855 sec.end (to, to->name (MOD_SNAME_PFX ".def"), crc_p);
16857 if (count)
16859 /* Write the table. */
16860 bytes_out sec (to);
16861 sec.begin ();
16862 sec.u (count);
16864 for (unsigned ix = macros.length (); ix--;)
16866 const cpp_hashnode *node = macros[ix];
16867 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
16869 if (slot.offset)
16871 sec.cpp_node (node);
16872 sec.u (slot.get_defness ());
16873 sec.u (slot.offset);
16876 sec.end (to, to->name (MOD_SNAME_PFX ".mac"), crc_p);
16879 macros.release ();
16880 dump.outdent ();
16881 return count;
16884 bool
16885 module_state::read_macros ()
16887 /* Get the def section. */
16888 if (!slurp->macro_defs.begin (loc, from (), MOD_SNAME_PFX ".def"))
16889 return false;
16891 /* Get the tbl section, if there are defs. */
16892 if (slurp->macro_defs.more_p ()
16893 && !slurp->macro_tbl.begin (loc, from (), MOD_SNAME_PFX ".mac"))
16894 return false;
16896 return true;
16899 /* Install the macro name table. */
16901 void
16902 module_state::install_macros ()
16904 bytes_in &sec = slurp->macro_tbl;
16905 if (!sec.size)
16906 return;
16908 dump () && dump ("Reading macro table %M", this);
16909 dump.indent ();
16911 unsigned count = sec.u ();
16912 dump () && dump ("%u macros", count);
16913 while (count--)
16915 cpp_hashnode *node = sec.cpp_node ();
16916 macro_import &imp = get_macro_imports (node);
16917 unsigned flags = sec.u () & macro_import::slot::L_BOTH;
16918 if (!flags)
16919 sec.set_overrun ();
16921 if (sec.get_overrun ())
16922 break;
16924 macro_import::slot &slot = imp.append (mod, flags);
16925 slot.offset = sec.u ();
16927 dump (dumper::MACRO)
16928 && dump ("Read %s macro %s%s%s %I at %u",
16929 imp.length () > 1 ? "add" : "new",
16930 flags & macro_import::slot::L_UNDEF ? "#undef" : "",
16931 flags == macro_import::slot::L_BOTH ? " & " : "",
16932 flags & macro_import::slot::L_DEF ? "#define" : "",
16933 identifier (node), slot.offset);
16935 /* We'll leak an imported definition's TOKEN_FLD_STR's data
16936 here. But that only happens when we've had to resolve the
16937 deferred macro before this import -- why are you doing
16938 that? */
16939 if (cpp_macro *cur = cpp_set_deferred_macro (node))
16940 if (!cur->imported_p)
16942 macro_import::slot &slot = imp.exported ();
16943 macro_export &exp = get_macro_export (slot);
16944 exp.def = cur;
16945 dump (dumper::MACRO)
16946 && dump ("Saving current #define %I", identifier (node));
16950 /* We're now done with the table. */
16951 elf_in::release (slurp->from, sec);
16953 dump.outdent ();
16956 /* Import the transitive macros. */
16958 void
16959 module_state::import_macros ()
16961 bitmap_ior_into (headers, slurp->headers);
16963 bitmap_iterator bititer;
16964 unsigned bitnum;
16965 EXECUTE_IF_SET_IN_BITMAP (slurp->headers, 0, bitnum, bititer)
16966 (*modules)[bitnum]->install_macros ();
16969 /* NODE is being undefined at LOC. Record it in the export table, if
16970 necessary. */
16972 void
16973 module_state::undef_macro (cpp_reader *, location_t loc, cpp_hashnode *node)
16975 if (!node->deferred)
16976 /* The macro is not imported, so our undef is irrelevant. */
16977 return;
16979 unsigned n = dump.push (NULL);
16981 macro_import::slot &slot = (*macro_imports)[node->deferred - 1].exported ();
16982 macro_export &exp = get_macro_export (slot);
16984 exp.undef_loc = loc;
16985 slot.become_undef ();
16986 exp.def = NULL;
16988 dump (dumper::MACRO) && dump ("Recording macro #undef %I", identifier (node));
16990 dump.pop (n);
16993 /* NODE is a deferred macro node. Determine the definition and return
16994 it, with NULL if undefined. May issue diagnostics.
16996 This can leak memory, when merging declarations -- the string
16997 contents (TOKEN_FLD_STR) of each definition are allocated in
16998 unreclaimable cpp objstack. Only one will win. However, I do not
16999 expect this to be common -- mostly macros have a single point of
17000 definition. Perhaps we could restore the objstack to its position
17001 after the first imported definition (if that wins)? The macros
17002 themselves are GC'd. */
17004 cpp_macro *
17005 module_state::deferred_macro (cpp_reader *reader, location_t loc,
17006 cpp_hashnode *node)
17008 macro_import &imports = (*macro_imports)[node->deferred - 1];
17010 unsigned n = dump.push (NULL);
17011 dump (dumper::MACRO) && dump ("Deferred macro %I", identifier (node));
17013 bitmap visible (BITMAP_GGC_ALLOC ());
17015 if (!((imports[0].get_defness () & macro_import::slot::L_UNDEF)
17016 && !imports[0].get_module ()))
17018 /* Calculate the set of visible header imports. */
17019 bitmap_copy (visible, headers);
17020 for (unsigned ix = imports.length (); ix--;)
17022 const macro_import::slot &slot = imports[ix];
17023 unsigned mod = slot.get_module ();
17024 if ((slot.get_defness () & macro_import::slot::L_UNDEF)
17025 && bitmap_bit_p (visible, mod))
17027 bitmap arg = mod ? (*modules)[mod]->slurp->headers : headers;
17028 bitmap_and_compl_into (visible, arg);
17029 bitmap_set_bit (visible, mod);
17033 bitmap_set_bit (visible, 0);
17035 /* Now find the macros that are still visible. */
17036 bool failed = false;
17037 cpp_macro *def = NULL;
17038 vec<macro_export> defs;
17039 defs.create (imports.length ());
17040 for (unsigned ix = imports.length (); ix--;)
17042 const macro_import::slot &slot = imports[ix];
17043 unsigned mod = slot.get_module ();
17044 if (bitmap_bit_p (visible, mod))
17046 macro_export *pushed = NULL;
17047 if (mod)
17049 const module_state *imp = (*modules)[mod];
17050 bytes_in &sec = imp->slurp->macro_defs;
17051 if (!sec.get_overrun ())
17053 dump (dumper::MACRO)
17054 && dump ("Reading macro %s%s%s %I module %M at %u",
17055 slot.get_defness () & macro_import::slot::L_UNDEF
17056 ? "#undef" : "",
17057 slot.get_defness () == macro_import::slot::L_BOTH
17058 ? " & " : "",
17059 slot.get_defness () & macro_import::slot::L_DEF
17060 ? "#define" : "",
17061 identifier (node), imp, slot.offset);
17062 sec.random_access (slot.offset);
17064 macro_export exp;
17065 if (slot.get_defness () & macro_import::slot::L_UNDEF)
17066 exp.undef_loc = imp->read_location (sec);
17067 if (slot.get_defness () & macro_import::slot::L_DEF)
17068 exp.def = imp->read_define (sec, reader);
17069 if (sec.get_overrun ())
17070 error_at (loc, "macro definitions of %qE corrupted",
17071 imp->name);
17072 else
17073 pushed = defs.quick_push (exp);
17076 else
17077 pushed = defs.quick_push ((*macro_exports)[slot.offset]);
17078 if (pushed && pushed->def)
17080 if (!def)
17081 def = pushed->def;
17082 else if (cpp_compare_macros (def, pushed->def))
17083 failed = true;
17088 if (failed)
17090 /* If LOC is the first loc, this is the end of file check, which
17091 is a warning. */
17092 if (loc == MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0)))
17093 warning_at (loc, OPT_Winvalid_imported_macros,
17094 "inconsistent imported macro definition %qE",
17095 identifier (node));
17096 else
17097 error_at (loc, "inconsistent imported macro definition %qE",
17098 identifier (node));
17099 for (unsigned ix = defs.length (); ix--;)
17101 macro_export &exp = defs[ix];
17102 if (exp.undef_loc)
17103 inform (exp.undef_loc, "%<#undef %E%>", identifier (node));
17104 if (exp.def)
17105 inform (exp.def->line, "%<#define %s%>",
17106 cpp_macro_definition (reader, node, exp.def));
17108 def = NULL;
17111 defs.release ();
17113 dump.pop (n);
17115 return def;
17118 /* Stream the static aggregates. Sadly some headers (ahem:
17119 iostream) contain static vars, and rely on them to run global
17120 ctors. */
17121 unsigned
17122 module_state::write_inits (elf_out *to, depset::hash &table, unsigned *crc_ptr)
17124 if (!static_aggregates && !tls_aggregates)
17125 return 0;
17127 dump () && dump ("Writing initializers");
17128 dump.indent ();
17130 static_aggregates = nreverse (static_aggregates);
17131 tls_aggregates = nreverse (tls_aggregates);
17133 unsigned count = 0;
17134 trees_out sec (to, this, table, ~0u);
17135 sec.begin ();
17137 tree list = static_aggregates;
17138 for (int passes = 0; passes != 2; passes++)
17140 for (tree init = list; init; init = TREE_CHAIN (init), count++)
17141 if (TREE_LANG_FLAG_0 (init))
17143 tree decl = TREE_VALUE (init);
17145 dump ("Initializer:%u for %N", count, decl);
17146 sec.tree_node (decl);
17149 list = tls_aggregates;
17152 sec.end (to, to->name (MOD_SNAME_PFX ".ini"), crc_ptr);
17153 dump.outdent ();
17155 return count;
17158 /* We have to defer some post-load processing until we've completed
17159 reading, because they can cause more reading. */
17161 static void
17162 post_load_processing ()
17164 /* We mustn't cause a GC, our caller should have arranged for that
17165 not to happen. */
17166 gcc_checking_assert (function_depth);
17168 if (!post_load_decls)
17169 return;
17171 tree old_cfd = current_function_decl;
17172 struct function *old_cfun = cfun;
17173 while (post_load_decls->length ())
17175 tree decl = post_load_decls->pop ();
17177 dump () && dump ("Post-load processing of %N", decl);
17179 gcc_checking_assert (DECL_ABSTRACT_P (decl));
17180 /* Cloning can cause loading -- specifically operator delete for
17181 the deleting dtor. */
17182 maybe_clone_body (decl);
17185 cfun = old_cfun;
17186 current_function_decl = old_cfd;
17189 bool
17190 module_state::read_inits (unsigned count)
17192 trees_in sec (this);
17193 if (!sec.begin (loc, from (), from ()->find (MOD_SNAME_PFX ".ini")))
17194 return false;
17195 dump () && dump ("Reading %u initializers", count);
17196 dump.indent ();
17198 lazy_snum = ~0u;
17199 for (unsigned ix = 0; ix != count; ix++)
17201 /* Merely referencing the decl causes its initializer to be read
17202 and added to the correct list. */
17203 tree decl = sec.tree_node ();
17205 if (sec.get_overrun ())
17206 break;
17207 if (decl)
17208 dump ("Initializer:%u for %N", count, decl);
17210 lazy_snum = 0;
17211 post_load_processing ();
17212 dump.outdent ();
17213 if (!sec.end (from ()))
17214 return false;
17215 return true;
17218 void
17219 module_state::write_counts (elf_out *to, unsigned counts[MSC_HWM],
17220 unsigned *crc_ptr)
17222 bytes_out cfg (to);
17224 cfg.begin ();
17226 for (unsigned ix = MSC_HWM; ix--;)
17227 cfg.u (counts[ix]);
17229 if (dump ())
17231 dump ("Cluster sections are [%u,%u)",
17232 counts[MSC_sec_lwm], counts[MSC_sec_hwm]);
17233 dump ("Bindings %u", counts[MSC_bindings]);
17234 dump ("Pendings %u", counts[MSC_pendings]);
17235 dump ("Entities %u", counts[MSC_entities]);
17236 dump ("Namespaces %u", counts[MSC_namespaces]);
17237 dump ("Macros %u", counts[MSC_macros]);
17238 dump ("Initializers %u", counts[MSC_inits]);
17241 cfg.end (to, to->name (MOD_SNAME_PFX ".cnt"), crc_ptr);
17244 bool
17245 module_state::read_counts (unsigned counts[MSC_HWM])
17247 bytes_in cfg;
17249 if (!cfg.begin (loc, from (), MOD_SNAME_PFX ".cnt"))
17250 return false;
17252 for (unsigned ix = MSC_HWM; ix--;)
17253 counts[ix] = cfg.u ();
17255 if (dump ())
17257 dump ("Declaration sections are [%u,%u)",
17258 counts[MSC_sec_lwm], counts[MSC_sec_hwm]);
17259 dump ("Bindings %u", counts[MSC_bindings]);
17260 dump ("Pendings %u", counts[MSC_pendings]);
17261 dump ("Entities %u", counts[MSC_entities]);
17262 dump ("Namespaces %u", counts[MSC_namespaces]);
17263 dump ("Macros %u", counts[MSC_macros]);
17264 dump ("Initializers %u", counts[MSC_inits]);
17267 return cfg.end (from ());
17270 /* Tool configuration: MOD_SNAME_PFX .config
17272 This is data that confirms current state (or fails). */
17274 void
17275 module_state::write_config (elf_out *to, module_state_config &config,
17276 unsigned inner_crc)
17278 bytes_out cfg (to);
17280 cfg.begin ();
17282 /* Write version and inner crc as u32 values, for easier
17283 debug inspection. */
17284 dump () && dump ("Writing version=%V, inner_crc=%x",
17285 MODULE_VERSION, inner_crc);
17286 cfg.u32 (unsigned (MODULE_VERSION));
17287 cfg.u32 (inner_crc);
17289 cfg.u (to->name (is_header () ? "" : get_flatname ()));
17291 /* Configuration. */
17292 dump () && dump ("Writing target='%s', host='%s'",
17293 TARGET_MACHINE, HOST_MACHINE);
17294 unsigned target = to->name (TARGET_MACHINE);
17295 unsigned host = (!strcmp (TARGET_MACHINE, HOST_MACHINE)
17296 ? target : to->name (HOST_MACHINE));
17297 cfg.u (target);
17298 cfg.u (host);
17300 cfg.str (config.dialect_str);
17301 cfg.u (extensions);
17303 /* Global tree information. We write the globals crc separately,
17304 rather than mix it directly into the overall crc, as it is used
17305 to ensure data match between instances of the compiler, not
17306 integrity of the file. */
17307 dump () && dump ("Writing globals=%u, crc=%x",
17308 fixed_trees->length (), global_crc);
17309 cfg.u (fixed_trees->length ());
17310 cfg.u32 (global_crc);
17312 if (is_partition ())
17313 cfg.u (is_interface ());
17315 cfg.u (config.num_imports);
17316 cfg.u (config.num_partitions);
17317 cfg.u (config.num_entities);
17319 cfg.u (config.ordinary_locs);
17320 cfg.u (config.macro_locs);
17321 cfg.u (config.ordinary_loc_align);
17323 /* Now generate CRC, we'll have incorporated the inner CRC because
17324 of its serialization above. */
17325 cfg.end (to, to->name (MOD_SNAME_PFX ".cfg"), &crc);
17326 dump () && dump ("Writing CRC=%x", crc);
17329 void
17330 module_state::note_cmi_name ()
17332 if (!cmi_noted_p && filename)
17334 cmi_noted_p = true;
17335 inform (loc, "compiled module file is %qs",
17336 maybe_add_cmi_prefix (filename));
17340 bool
17341 module_state::read_config (module_state_config &config)
17343 bytes_in cfg;
17345 if (!cfg.begin (loc, from (), MOD_SNAME_PFX ".cfg"))
17346 return false;
17348 /* Check version. */
17349 unsigned my_ver = MODULE_VERSION;
17350 unsigned their_ver = cfg.u32 ();
17351 dump () && dump (my_ver == their_ver ? "Version %V"
17352 : "Expecting %V found %V", my_ver, their_ver);
17353 if (their_ver != my_ver)
17355 /* The compiler versions differ. Close enough? */
17356 verstr_t my_string, their_string;
17358 version2string (my_ver, my_string);
17359 version2string (their_ver, their_string);
17361 /* Reject when either is non-experimental or when experimental
17362 major versions differ. */
17363 bool reject_p = ((!IS_EXPERIMENTAL (my_ver)
17364 || !IS_EXPERIMENTAL (their_ver)
17365 || MODULE_MAJOR (my_ver) != MODULE_MAJOR (their_ver))
17366 /* The 'I know what I'm doing' switch. */
17367 && !flag_module_version_ignore);
17368 bool inform_p = true;
17369 if (reject_p)
17371 cfg.set_overrun ();
17372 error_at (loc, "compiled module is %sversion %s",
17373 IS_EXPERIMENTAL (their_ver) ? "experimental " : "",
17374 their_string);
17376 else
17377 inform_p = warning_at (loc, 0, "compiled module is %sversion %s",
17378 IS_EXPERIMENTAL (their_ver) ? "experimental " : "",
17379 their_string);
17381 if (inform_p)
17383 inform (loc, "compiler is %sversion %s%s%s",
17384 IS_EXPERIMENTAL (my_ver) ? "experimental " : "",
17385 my_string,
17386 reject_p ? "" : flag_module_version_ignore
17387 ? ", be it on your own head!" : ", close enough?",
17388 reject_p ? "" : " \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf");
17389 note_cmi_name ();
17392 if (reject_p)
17393 goto done;
17396 /* We wrote the inner crc merely to merge it, so simply read it
17397 back and forget it. */
17398 cfg.u32 ();
17400 /* Check module name. */
17402 const char *their_name = from ()->name (cfg.u ());
17403 const char *our_name = "";
17405 if (!is_header ())
17406 our_name = get_flatname ();
17408 /* Header units can be aliased, so name checking is
17409 inappropriate. */
17410 if (0 != strcmp (their_name, our_name))
17412 error_at (loc,
17413 their_name[0] && our_name[0] ? G_("module %qs found")
17414 : their_name[0]
17415 ? G_("header module expected, module %qs found")
17416 : G_("module %qs expected, header module found"),
17417 their_name[0] ? their_name : our_name);
17418 cfg.set_overrun ();
17419 goto done;
17423 /* Check the CRC after the above sanity checks, so that the user is
17424 clued in. */
17426 unsigned e_crc = crc;
17427 crc = cfg.get_crc ();
17428 dump () && dump ("Reading CRC=%x", crc);
17429 if (!is_direct () && crc != e_crc)
17431 error_at (loc, "module %qs CRC mismatch", get_flatname ());
17432 cfg.set_overrun ();
17433 goto done;
17437 /* Check target & host. */
17439 const char *their_target = from ()->name (cfg.u ());
17440 const char *their_host = from ()->name (cfg.u ());
17441 dump () && dump ("Read target='%s', host='%s'", their_target, their_host);
17442 if (strcmp (their_target, TARGET_MACHINE)
17443 || strcmp (their_host, HOST_MACHINE))
17445 error_at (loc, "target & host is %qs:%qs, expected %qs:%qs",
17446 their_target, TARGET_MACHINE, their_host, HOST_MACHINE);
17447 cfg.set_overrun ();
17448 goto done;
17452 /* Check compilation dialect. This must match. */
17454 const char *their_dialect = cfg.str ();
17455 if (strcmp (their_dialect, config.dialect_str))
17457 error_at (loc, "language dialect differs %qs, expected %qs",
17458 their_dialect, config.dialect_str);
17459 cfg.set_overrun ();
17460 goto done;
17464 /* Check for extensions. If they set any, we must have them set
17465 too. */
17467 unsigned ext = cfg.u ();
17468 unsigned allowed = (flag_openmp ? SE_OPENMP : 0);
17470 if (unsigned bad = ext & ~allowed)
17472 if (bad & SE_OPENMP)
17473 error_at (loc, "module contains OpenMP, use %<-fopenmp%> to enable");
17474 cfg.set_overrun ();
17475 goto done;
17477 extensions = ext;
17480 /* Check global trees. */
17482 unsigned their_fixed_length = cfg.u ();
17483 unsigned their_fixed_crc = cfg.u32 ();
17484 dump () && dump ("Read globals=%u, crc=%x",
17485 their_fixed_length, their_fixed_crc);
17486 if (!flag_preprocess_only
17487 && (their_fixed_length != fixed_trees->length ()
17488 || their_fixed_crc != global_crc))
17490 error_at (loc, "fixed tree mismatch");
17491 cfg.set_overrun ();
17492 goto done;
17496 /* All non-partitions are interfaces. */
17497 interface_p = !is_partition () || cfg.u ();
17499 config.num_imports = cfg.u ();
17500 config.num_partitions = cfg.u ();
17501 config.num_entities = cfg.u ();
17503 config.ordinary_locs = cfg.u ();
17504 config.macro_locs = cfg.u ();
17505 config.ordinary_loc_align = cfg.u ();
17507 done:
17508 return cfg.end (from ());
17511 /* Comparator for ordering the Ordered Ordinary Location array. */
17513 static int
17514 ool_cmp (const void *a_, const void *b_)
17516 auto *a = *static_cast<const module_state *const *> (a_);
17517 auto *b = *static_cast<const module_state *const *> (b_);
17518 if (a == b)
17519 return 0;
17520 else if (a->ordinary_locs.first < b->ordinary_locs.second)
17521 return -1;
17522 else
17523 return +1;
17526 /* Use ELROND format to record the following sections:
17527 qualified-names : binding value(s)
17528 MOD_SNAME_PFX.README : human readable, strings
17529 MOD_SNAME_PFX.ENV : environment strings, strings
17530 MOD_SNAME_PFX.nms : namespace hierarchy
17531 MOD_SNAME_PFX.bnd : binding table
17532 MOD_SNAME_PFX.spc : specialization table
17533 MOD_SNAME_PFX.imp : import table
17534 MOD_SNAME_PFX.ent : entity table
17535 MOD_SNAME_PFX.prt : partitions table
17536 MOD_SNAME_PFX.olm : ordinary line maps
17537 MOD_SNAME_PFX.mlm : macro line maps
17538 MOD_SNAME_PFX.def : macro definitions
17539 MOD_SNAME_PFX.mac : macro index
17540 MOD_SNAME_PFX.ini : inits
17541 MOD_SNAME_PFX.cnt : counts
17542 MOD_SNAME_PFX.cfg : config data
17545 void
17546 module_state::write (elf_out *to, cpp_reader *reader)
17548 /* Figure out remapped module numbers, which might elide
17549 partitions. */
17550 bitmap partitions = NULL;
17551 if (!is_header () && !is_partition ())
17552 partitions = BITMAP_GGC_ALLOC ();
17554 unsigned mod_hwm = 1;
17555 for (unsigned ix = 1; ix != modules->length (); ix++)
17557 module_state *imp = (*modules)[ix];
17559 /* Promote any non-partition direct import from a partition, unless
17560 we're a partition. */
17561 if (!is_partition () && !imp->is_partition ()
17562 && imp->is_partition_direct ())
17563 imp->directness = MD_PURVIEW_DIRECT;
17565 /* Write any import that is not a partition, unless we're a
17566 partition. */
17567 if (!partitions || !imp->is_partition ())
17568 imp->remap = mod_hwm++;
17569 else
17571 dump () && dump ("Partition %M %u", imp, ix);
17572 bitmap_set_bit (partitions, ix);
17573 imp->remap = 0;
17574 /* All interface partitions must be exported. */
17575 if (imp->is_interface () && !bitmap_bit_p (exports, imp->mod))
17577 error_at (imp->loc, "interface partition is not exported");
17578 bitmap_set_bit (exports, imp->mod);
17581 /* All the partition entities should have been loaded when
17582 loading the partition. */
17583 if (CHECKING_P)
17584 for (unsigned jx = 0; jx != imp->entity_num; jx++)
17586 binding_slot *slot = &(*entity_ary)[imp->entity_lwm + jx];
17587 gcc_checking_assert (!slot->is_lazy ());
17592 if (partitions && bitmap_empty_p (partitions))
17593 /* No partitions present. */
17594 partitions = nullptr;
17596 /* Find the set of decls we must write out. */
17597 depset::hash table (DECL_NAMESPACE_BINDINGS (global_namespace)->size () * 8);
17598 /* Add the specializations before the writables, so that we can
17599 detect injected friend specializations. */
17600 table.add_specializations (true);
17601 table.add_specializations (false);
17602 if (partial_specializations)
17604 table.add_partial_entities (partial_specializations);
17605 partial_specializations = NULL;
17607 table.add_namespace_entities (global_namespace, partitions);
17608 if (class_members)
17610 table.add_class_entities (class_members);
17611 class_members = NULL;
17614 /* Now join everything up. */
17615 table.find_dependencies (this);
17617 if (!table.finalize_dependencies ())
17619 to->set_error ();
17620 return;
17623 #if CHECKING_P
17624 /* We're done verifying at-most once reading, reset to verify
17625 at-most once writing. */
17626 note_defs = note_defs_table_t::create_ggc (1000);
17627 #endif
17629 /* Determine Strongy Connected Components. */
17630 vec<depset *> sccs = table.connect ();
17632 vec_alloc (ool, modules->length ());
17633 for (unsigned ix = modules->length (); --ix;)
17635 auto *import = (*modules)[ix];
17636 if (import->loadedness > ML_NONE
17637 && !(partitions && bitmap_bit_p (partitions, import->mod)))
17638 ool->quick_push (import);
17640 ool->qsort (ool_cmp);
17642 unsigned crc = 0;
17643 module_state_config config;
17644 location_map_info map_info = write_prepare_maps (&config);
17645 unsigned counts[MSC_HWM];
17647 config.num_imports = mod_hwm;
17648 config.num_partitions = modules->length () - mod_hwm;
17649 memset (counts, 0, sizeof (counts));
17651 /* depset::cluster is the cluster number,
17652 depset::section is unspecified scratch value.
17654 The following loops make use of the tarjan property that
17655 dependencies will be earlier in the SCCS array. */
17657 /* This first loop determines the number of depsets in each SCC, and
17658 also the number of namespaces we're dealing with. During the
17659 loop, the meaning of a couple of depset fields now change:
17661 depset::cluster -> size_of cluster, if first of cluster & !namespace
17662 depset::section -> section number of cluster (if !namespace). */
17664 unsigned n_spaces = 0;
17665 counts[MSC_sec_lwm] = counts[MSC_sec_hwm] = to->get_section_limit ();
17666 for (unsigned size, ix = 0; ix < sccs.length (); ix += size)
17668 depset **base = &sccs[ix];
17670 if (base[0]->get_entity_kind () == depset::EK_NAMESPACE)
17672 n_spaces++;
17673 size = 1;
17675 else
17677 /* Count the members in this cluster. */
17678 for (size = 1; ix + size < sccs.length (); size++)
17679 if (base[size]->cluster != base[0]->cluster)
17680 break;
17682 for (unsigned jx = 0; jx != size; jx++)
17684 /* Set the section number. */
17685 base[jx]->cluster = ~(~0u >> 1); /* A bad value. */
17686 base[jx]->section = counts[MSC_sec_hwm];
17689 /* Save the size in the first member's cluster slot. */
17690 base[0]->cluster = size;
17692 counts[MSC_sec_hwm]++;
17696 /* Write the clusters. Namespace decls are put in the spaces array.
17697 The meaning of depset::cluster changes to provide the
17698 unnamed-decl count of the depset's decl (and remains zero for
17699 non-decls and non-unnamed). */
17700 unsigned bytes = 0;
17701 vec<depset *> spaces;
17702 spaces.create (n_spaces);
17704 for (unsigned size, ix = 0; ix < sccs.length (); ix += size)
17706 depset **base = &sccs[ix];
17708 if (base[0]->get_entity_kind () == depset::EK_NAMESPACE)
17710 tree decl = base[0]->get_entity ();
17711 if (decl == global_namespace)
17712 base[0]->cluster = 0;
17713 else if (!base[0]->is_import ())
17715 base[0]->cluster = counts[MSC_entities]++;
17716 spaces.quick_push (base[0]);
17717 counts[MSC_namespaces]++;
17718 if (CHECKING_P)
17720 /* Add it to the entity map, such that we can tell it is
17721 part of us. */
17722 bool existed;
17723 unsigned *slot = &entity_map->get_or_insert
17724 (DECL_UID (decl), &existed);
17725 if (existed)
17726 /* It must have come from a partition. */
17727 gcc_checking_assert
17728 (import_entity_module (*slot)->is_partition ());
17729 *slot = ~base[0]->cluster;
17731 dump (dumper::CLUSTER) && dump ("Cluster namespace %N", decl);
17733 size = 1;
17735 else
17737 size = base[0]->cluster;
17739 /* Cluster is now used to number entities. */
17740 base[0]->cluster = ~(~0u >> 1); /* A bad value. */
17742 sort_cluster (&table, base, size);
17744 /* Record the section for consistency checking during stream
17745 out -- we don't want to start writing decls in different
17746 sections. */
17747 table.section = base[0]->section;
17748 bytes += write_cluster (to, base, size, table, counts, &crc);
17749 table.section = 0;
17753 /* depset::cluster - entity number (on entities)
17754 depset::section - cluster number */
17755 /* We'd better have written as many sections and found as many
17756 namespaces as we predicted. */
17757 gcc_assert (counts[MSC_sec_hwm] == to->get_section_limit ()
17758 && spaces.length () == counts[MSC_namespaces]);
17760 /* Write the entitites. None happens if we contain namespaces or
17761 nothing. */
17762 config.num_entities = counts[MSC_entities];
17763 if (counts[MSC_entities])
17764 write_entities (to, sccs, counts[MSC_entities], &crc);
17766 /* Write the namespaces. */
17767 if (counts[MSC_namespaces])
17768 write_namespaces (to, spaces, counts[MSC_namespaces], &crc);
17770 /* Write the bindings themselves. */
17771 counts[MSC_bindings] = write_bindings (to, sccs, &crc);
17773 /* Write the unnamed. */
17774 counts[MSC_pendings] = write_pendings (to, sccs, table, &crc);
17776 /* Write the import table. */
17777 if (config.num_imports > 1)
17778 write_imports (to, &crc);
17780 /* Write elided partition table. */
17781 if (config.num_partitions)
17782 write_partitions (to, config.num_partitions, &crc);
17784 /* Write the line maps. */
17785 write_ordinary_maps (to, map_info, &config, config.num_partitions, &crc);
17786 write_macro_maps (to, map_info, &config, &crc);
17788 if (is_header ())
17790 counts[MSC_macros] = write_macros (to, reader, &crc);
17791 counts[MSC_inits] = write_inits (to, table, &crc);
17794 unsigned clusters = counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
17795 dump () && dump ("Wrote %u clusters, average %u bytes/cluster",
17796 clusters, (bytes + clusters / 2) / (clusters + !clusters));
17798 write_counts (to, counts, &crc);
17800 /* And finish up. */
17801 write_config (to, config, crc);
17803 spaces.release ();
17804 sccs.release ();
17806 vec_free (ool);
17808 /* Human-readable info. */
17809 write_readme (to, reader, config.dialect_str, extensions);
17811 // FIXME:QOI: Have a command line switch to control more detailed
17812 // information (which might leak data you do not want to leak).
17813 // Perhaps (some of) the write_readme contents should also be
17814 // so-controlled.
17815 if (false)
17816 write_env (to);
17818 trees_out::instrument ();
17819 dump () && dump ("Wrote %u sections", to->get_section_limit ());
17822 /* Initial read of a CMI. Checks config, loads up imports and line
17823 maps. */
17825 bool
17826 module_state::read_initial (cpp_reader *reader)
17828 module_state_config config;
17829 bool ok = true;
17831 if (ok && !from ()->begin (loc))
17832 ok = false;
17834 if (ok && !read_config (config))
17835 ok = false;
17837 bool have_locs = ok && read_prepare_maps (&config);
17839 /* Ordinary maps before the imports. */
17840 if (have_locs && !read_ordinary_maps ())
17841 ok = false;
17843 /* Allocate the REMAP vector. */
17844 slurp->alloc_remap (config.num_imports);
17846 if (ok)
17848 /* Read the import table. Decrement current to stop this CMI
17849 from being evicted during the import. */
17850 slurp->current--;
17851 if (config.num_imports > 1 && !read_imports (reader, line_table))
17852 ok = false;
17853 slurp->current++;
17856 /* Read the elided partition table, if we're the primary partition. */
17857 if (ok && config.num_partitions && is_module ()
17858 && !read_partitions (config.num_partitions))
17859 ok = false;
17861 /* Determine the module's number. */
17862 gcc_checking_assert (mod == MODULE_UNKNOWN);
17863 gcc_checking_assert (this != (*modules)[0]);
17866 /* Allocate space in the entities array now -- that array must be
17867 monotionically in step with the modules array. */
17868 entity_lwm = vec_safe_length (entity_ary);
17869 entity_num = config.num_entities;
17870 gcc_checking_assert (modules->length () == 1
17871 || modules->last ()->entity_lwm <= entity_lwm);
17872 vec_safe_reserve (entity_ary, config.num_entities);
17874 binding_slot slot;
17875 slot.u.binding = NULL_TREE;
17876 for (unsigned count = config.num_entities; count--;)
17877 entity_ary->quick_push (slot);
17880 /* We'll run out of other resources before we run out of module
17881 indices. */
17882 mod = modules->length ();
17883 vec_safe_push (modules, this);
17885 /* We always import and export ourselves. */
17886 bitmap_set_bit (imports, mod);
17887 bitmap_set_bit (exports, mod);
17889 if (ok)
17890 (*slurp->remap)[0] = mod << 1;
17891 dump () && dump ("Assigning %M module number %u", this, mod);
17893 /* We should not have been frozen during the importing done by
17894 read_config. */
17895 gcc_assert (!from ()->is_frozen ());
17897 /* Macro maps after the imports. */
17898 if (ok && have_locs && !read_macro_maps ())
17899 ok = false;
17901 gcc_assert (slurp->current == ~0u);
17902 return ok;
17905 /* Read a preprocessor state. */
17907 bool
17908 module_state::read_preprocessor (bool outermost)
17910 gcc_checking_assert (is_header () && slurp
17911 && slurp->remap_module (0) == mod);
17913 if (loadedness == ML_PREPROCESSOR)
17914 return !(from () && from ()->get_error ());
17916 bool ok = true;
17918 /* Read direct header imports. */
17919 unsigned len = slurp->remap->length ();
17920 for (unsigned ix = 1; ok && ix != len; ix++)
17922 unsigned map = (*slurp->remap)[ix];
17923 if (map & 1)
17925 module_state *import = (*modules)[map >> 1];
17926 if (import->is_header ())
17928 ok = import->read_preprocessor (false);
17929 bitmap_ior_into (slurp->headers, import->slurp->headers);
17934 /* Record as a direct header. */
17935 if (ok)
17936 bitmap_set_bit (slurp->headers, mod);
17938 if (ok && !read_macros ())
17939 ok = false;
17941 loadedness = ML_PREPROCESSOR;
17942 announce ("macros");
17944 if (flag_preprocess_only)
17945 /* We're done with the string table. */
17946 from ()->release ();
17948 return check_read (outermost, ok);
17951 /* Read language state. */
17953 bool
17954 module_state::read_language (bool outermost)
17956 gcc_checking_assert (!lazy_snum);
17958 if (loadedness == ML_LANGUAGE)
17959 return !(slurp && from () && from ()->get_error ());
17961 gcc_checking_assert (slurp && slurp->current == ~0u
17962 && slurp->remap_module (0) == mod);
17964 bool ok = true;
17966 /* Read direct imports. */
17967 unsigned len = slurp->remap->length ();
17968 for (unsigned ix = 1; ok && ix != len; ix++)
17970 unsigned map = (*slurp->remap)[ix];
17971 if (map & 1)
17973 module_state *import = (*modules)[map >> 1];
17974 if (!import->read_language (false))
17975 ok = false;
17979 unsigned counts[MSC_HWM];
17981 if (ok && !read_counts (counts))
17982 ok = false;
17984 function_depth++; /* Prevent unexpected GCs. */
17986 if (ok && counts[MSC_entities] != entity_num)
17987 ok = false;
17988 if (ok && counts[MSC_entities]
17989 && !read_entities (counts[MSC_entities],
17990 counts[MSC_sec_lwm], counts[MSC_sec_hwm]))
17991 ok = false;
17993 /* Read the namespace hierarchy. */
17994 if (ok && counts[MSC_namespaces]
17995 && !read_namespaces (counts[MSC_namespaces]))
17996 ok = false;
17998 if (ok && !read_bindings (counts[MSC_bindings],
17999 counts[MSC_sec_lwm], counts[MSC_sec_hwm]))
18000 ok = false;
18002 /* And unnamed. */
18003 if (ok && counts[MSC_pendings] && !read_pendings (counts[MSC_pendings]))
18004 ok = false;
18006 if (ok)
18008 slurp->remaining = counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
18009 available_clusters += counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
18012 if (!flag_module_lazy
18013 || (is_partition ()
18014 && module_interface_p ()
18015 && !module_partition_p ()))
18017 /* Read the sections in forward order, so that dependencies are read
18018 first. See note about tarjan_connect. */
18019 ggc_collect ();
18021 lazy_snum = ~0u;
18023 unsigned hwm = counts[MSC_sec_hwm];
18024 for (unsigned ix = counts[MSC_sec_lwm]; ok && ix != hwm; ix++)
18025 if (!load_section (ix, NULL))
18027 ok = false;
18028 break;
18030 lazy_snum = 0;
18031 post_load_processing ();
18033 ggc_collect ();
18035 if (ok && CHECKING_P)
18036 for (unsigned ix = 0; ix != entity_num; ix++)
18037 gcc_assert (!(*entity_ary)[ix + entity_lwm].is_lazy ());
18040 // If the import is a header-unit, we need to register initializers
18041 // of any static objects it contains (looking at you _Ioinit).
18042 // Notice, the ordering of these initializers will be that of a
18043 // dynamic initializer at this point in the current TU. (Other
18044 // instances of these objects in other TUs will be initialized as
18045 // part of that TU's global initializers.)
18046 if (ok && counts[MSC_inits] && !read_inits (counts[MSC_inits]))
18047 ok = false;
18049 function_depth--;
18051 announce (flag_module_lazy ? "lazy" : "imported");
18052 loadedness = ML_LANGUAGE;
18054 gcc_assert (slurp->current == ~0u);
18056 /* We're done with the string table. */
18057 from ()->release ();
18059 return check_read (outermost, ok);
18062 bool
18063 module_state::maybe_defrost ()
18065 bool ok = true;
18066 if (from ()->is_frozen ())
18068 if (lazy_open >= lazy_limit)
18069 freeze_an_elf ();
18070 dump () && dump ("Defrosting '%s'", filename);
18071 ok = from ()->defrost (maybe_add_cmi_prefix (filename));
18072 lazy_open++;
18075 return ok;
18078 /* Load section SNUM, dealing with laziness. It doesn't matter if we
18079 have multiple concurrent loads, because we do not use TREE_VISITED
18080 when reading back in. */
18082 bool
18083 module_state::load_section (unsigned snum, binding_slot *mslot)
18085 if (from ()->get_error ())
18086 return false;
18088 if (snum >= slurp->current)
18089 from ()->set_error (elf::E_BAD_LAZY);
18090 else if (maybe_defrost ())
18092 unsigned old_current = slurp->current;
18093 slurp->current = snum;
18094 slurp->lru = 0; /* Do not swap out. */
18095 slurp->remaining--;
18096 read_cluster (snum);
18097 slurp->lru = ++lazy_lru;
18098 slurp->current = old_current;
18101 if (mslot && mslot->is_lazy ())
18103 /* Oops, the section didn't set this slot. */
18104 from ()->set_error (elf::E_BAD_DATA);
18105 *mslot = NULL_TREE;
18108 bool ok = !from ()->get_error ();
18109 if (!ok)
18111 error_at (loc, "failed to read compiled module cluster %u: %s",
18112 snum, from ()->get_error (filename));
18113 note_cmi_name ();
18116 maybe_completed_reading ();
18118 return ok;
18121 void
18122 module_state::maybe_completed_reading ()
18124 if (loadedness == ML_LANGUAGE && slurp->current == ~0u && !slurp->remaining)
18126 lazy_open--;
18127 /* We no longer need the macros, all tokenizing has been done. */
18128 slurp->release_macros ();
18130 from ()->end ();
18131 slurp->close ();
18132 slurped ();
18136 /* After a reading operation, make sure things are still ok. If not,
18137 emit an error and clean up. */
18139 bool
18140 module_state::check_read (bool outermost, bool ok)
18142 gcc_checking_assert (!outermost || slurp->current == ~0u);
18144 if (!ok)
18145 from ()->set_error ();
18147 if (int e = from ()->get_error ())
18149 error_at (loc, "failed to read compiled module: %s",
18150 from ()->get_error (filename));
18151 note_cmi_name ();
18153 if (e == EMFILE
18154 || e == ENFILE
18155 #if MAPPED_READING
18156 || e == ENOMEM
18157 #endif
18158 || false)
18159 inform (loc, "consider using %<-fno-module-lazy%>,"
18160 " increasing %<-param-lazy-modules=%u%> value,"
18161 " or increasing the per-process file descriptor limit",
18162 param_lazy_modules);
18163 else if (e == ENOENT)
18164 inform (loc, "imports must be built before being imported");
18166 if (outermost)
18167 fatal_error (loc, "returning to the gate for a mechanical issue");
18169 ok = false;
18172 maybe_completed_reading ();
18174 return ok;
18177 /* Return the IDENTIFIER_NODE naming module IX. This is the name
18178 including dots. */
18180 char const *
18181 module_name (unsigned ix, bool header_ok)
18183 if (modules)
18185 module_state *imp = (*modules)[ix];
18187 if (ix && !imp->name)
18188 imp = imp->parent;
18190 if (header_ok || !imp->is_header ())
18191 return imp->get_flatname ();
18194 return NULL;
18197 /* Return the bitmap describing what modules are imported. Remember,
18198 we always import ourselves. */
18200 bitmap
18201 get_import_bitmap ()
18203 return (*modules)[0]->imports;
18206 /* Return the visible imports and path of instantiation for an
18207 instantiation at TINST. If TINST is nullptr, we're not in an
18208 instantiation, and thus will return the visible imports of the
18209 current TU (and NULL *PATH_MAP_P). We cache the information on
18210 the tinst level itself. */
18212 static bitmap
18213 path_of_instantiation (tinst_level *tinst, bitmap *path_map_p)
18215 gcc_checking_assert (modules_p ());
18217 if (!tinst)
18219 /* Not inside an instantiation, just the regular case. */
18220 *path_map_p = nullptr;
18221 return get_import_bitmap ();
18224 if (!tinst->path)
18226 /* Calculate. */
18227 bitmap visible = path_of_instantiation (tinst->next, path_map_p);
18228 bitmap path_map = *path_map_p;
18230 if (!path_map)
18232 path_map = BITMAP_GGC_ALLOC ();
18233 bitmap_set_bit (path_map, 0);
18236 tree decl = tinst->tldcl;
18237 if (TREE_CODE (decl) == TREE_LIST)
18238 decl = TREE_PURPOSE (decl);
18239 if (TYPE_P (decl))
18240 decl = TYPE_NAME (decl);
18242 if (unsigned mod = get_originating_module (decl))
18243 if (!bitmap_bit_p (path_map, mod))
18245 /* This is brand new information! */
18246 bitmap new_path = BITMAP_GGC_ALLOC ();
18247 bitmap_copy (new_path, path_map);
18248 bitmap_set_bit (new_path, mod);
18249 path_map = new_path;
18251 bitmap imports = (*modules)[mod]->imports;
18252 if (bitmap_intersect_compl_p (imports, visible))
18254 /* IMPORTS contains additional modules to VISIBLE. */
18255 bitmap new_visible = BITMAP_GGC_ALLOC ();
18257 bitmap_ior (new_visible, visible, imports);
18258 visible = new_visible;
18262 tinst->path = path_map;
18263 tinst->visible = visible;
18266 *path_map_p = tinst->path;
18267 return tinst->visible;
18270 /* Return the bitmap describing what modules are visible along the
18271 path of instantiation. If we're not an instantiation, this will be
18272 the visible imports of the TU. *PATH_MAP_P is filled in with the
18273 modules owning the instantiation path -- we see the module-linkage
18274 entities of those modules. */
18276 bitmap
18277 visible_instantiation_path (bitmap *path_map_p)
18279 if (!modules_p ())
18280 return NULL;
18282 return path_of_instantiation (current_instantiation (), path_map_p);
18285 /* We've just directly imported IMPORT. Update our import/export
18286 bitmaps. IS_EXPORT is true if we're reexporting the OTHER. */
18288 void
18289 module_state::set_import (module_state const *import, bool is_export)
18291 gcc_checking_assert (this != import);
18293 /* We see IMPORT's exports (which includes IMPORT). If IMPORT is
18294 the primary interface or a partition we'll see its imports. */
18295 bitmap_ior_into (imports, import->is_module () || import->is_partition ()
18296 ? import->imports : import->exports);
18298 if (is_export)
18299 /* We'll export OTHER's exports. */
18300 bitmap_ior_into (exports, import->exports);
18303 /* Return the declaring entity of DECL. That is the decl determining
18304 how to decorate DECL with module information. Returns NULL_TREE if
18305 it's the global module. */
18307 tree
18308 get_originating_module_decl (tree decl)
18310 /* An enumeration constant. */
18311 if (TREE_CODE (decl) == CONST_DECL
18312 && DECL_CONTEXT (decl)
18313 && (TREE_CODE (DECL_CONTEXT (decl)) == ENUMERAL_TYPE))
18314 decl = TYPE_NAME (DECL_CONTEXT (decl));
18315 else if (TREE_CODE (decl) == FIELD_DECL
18316 || TREE_CODE (decl) == USING_DECL)
18318 decl = DECL_CONTEXT (decl);
18319 if (TREE_CODE (decl) != FUNCTION_DECL)
18320 decl = TYPE_NAME (decl);
18323 gcc_checking_assert (TREE_CODE (decl) == TEMPLATE_DECL
18324 || TREE_CODE (decl) == FUNCTION_DECL
18325 || TREE_CODE (decl) == TYPE_DECL
18326 || TREE_CODE (decl) == VAR_DECL
18327 || TREE_CODE (decl) == CONCEPT_DECL
18328 || TREE_CODE (decl) == NAMESPACE_DECL);
18330 for (;;)
18332 /* Uninstantiated template friends are owned by the befriending
18333 class -- not their context. */
18334 if (TREE_CODE (decl) == TEMPLATE_DECL
18335 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
18336 decl = TYPE_NAME (DECL_CHAIN (decl));
18338 int use;
18339 if (tree ti = node_template_info (decl, use))
18341 decl = TI_TEMPLATE (ti);
18342 if (TREE_CODE (decl) != TEMPLATE_DECL)
18344 /* A friend template specialization. */
18345 gcc_checking_assert (OVL_P (decl));
18346 return global_namespace;
18349 else
18351 tree ctx = CP_DECL_CONTEXT (decl);
18352 if (TREE_CODE (ctx) == NAMESPACE_DECL)
18353 break;
18355 if (TYPE_P (ctx))
18357 ctx = TYPE_NAME (ctx);
18358 if (!ctx)
18360 /* Some kind of internal type. */
18361 gcc_checking_assert (DECL_ARTIFICIAL (decl));
18362 return global_namespace;
18365 decl = ctx;
18369 return decl;
18373 get_originating_module (tree decl, bool for_mangle)
18375 tree owner = get_originating_module_decl (decl);
18376 tree not_tmpl = STRIP_TEMPLATE (owner);
18378 if (!DECL_LANG_SPECIFIC (not_tmpl))
18379 return for_mangle ? -1 : 0;
18381 if (for_mangle
18382 && (DECL_MODULE_EXPORT_P (owner) || !DECL_MODULE_PURVIEW_P (not_tmpl)))
18383 return -1;
18385 if (!DECL_MODULE_IMPORT_P (not_tmpl))
18386 return 0;
18388 return get_importing_module (owner);
18391 unsigned
18392 get_importing_module (tree decl, bool flexible)
18394 unsigned index = import_entity_index (decl, flexible);
18395 if (index == ~(~0u >> 1))
18396 return -1;
18397 module_state *module = import_entity_module (index);
18399 return module->mod;
18402 /* Is it permissible to redeclare DECL. */
18404 bool
18405 module_may_redeclare (tree decl)
18407 module_state *me = (*modules)[0];
18408 module_state *them = me;
18409 tree not_tmpl = STRIP_TEMPLATE (decl);
18410 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_IMPORT_P (not_tmpl))
18412 /* We can be given the TEMPLATE_RESULT. We want the
18413 TEMPLATE_DECL. */
18414 int use_tpl = -1;
18415 if (tree ti = node_template_info (decl, use_tpl))
18417 tree tmpl = TI_TEMPLATE (ti);
18418 if (use_tpl == 2)
18420 /* A partial specialization. Find that specialization's
18421 template_decl. */
18422 for (tree list = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
18423 list; list = TREE_CHAIN (list))
18424 if (DECL_TEMPLATE_RESULT (TREE_VALUE (list)) == decl)
18426 decl = TREE_VALUE (list);
18427 break;
18430 else if (DECL_TEMPLATE_RESULT (tmpl) == decl)
18431 decl = tmpl;
18433 unsigned index = import_entity_index (decl);
18434 them = import_entity_module (index);
18437 if (them->is_header ())
18439 if (!header_module_p ())
18440 return !module_purview_p ();
18442 if (DECL_SOURCE_LOCATION (decl) == BUILTINS_LOCATION)
18443 /* This is a builtin, being declared in header-unit. We
18444 now need to mark it as an export. */
18445 DECL_MODULE_EXPORT_P (decl) = true;
18447 /* If it came from a header, it's in the global module. */
18448 return true;
18451 if (me == them)
18452 return ((DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_PURVIEW_P (not_tmpl))
18453 == module_purview_p ());
18455 if (!me->name)
18456 me = me->parent;
18458 /* We can't have found a GMF entity from a named module. */
18459 gcc_checking_assert (DECL_LANG_SPECIFIC (not_tmpl)
18460 && DECL_MODULE_PURVIEW_P (not_tmpl));
18462 return me && get_primary (them) == get_primary (me);
18465 /* DECL is being created by this TU. Record it came from here. We
18466 record module purview, so we can see if partial or explicit
18467 specialization needs to be written out, even though its purviewness
18468 comes from the most general template. */
18470 void
18471 set_instantiating_module (tree decl)
18473 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
18474 || TREE_CODE (decl) == VAR_DECL
18475 || TREE_CODE (decl) == TYPE_DECL
18476 || TREE_CODE (decl) == CONCEPT_DECL
18477 || TREE_CODE (decl) == TEMPLATE_DECL
18478 || (TREE_CODE (decl) == NAMESPACE_DECL
18479 && DECL_NAMESPACE_ALIAS (decl)));
18481 if (!modules_p ())
18482 return;
18484 decl = STRIP_TEMPLATE (decl);
18486 if (!DECL_LANG_SPECIFIC (decl) && module_purview_p ())
18487 retrofit_lang_decl (decl);
18489 if (DECL_LANG_SPECIFIC (decl))
18491 DECL_MODULE_PURVIEW_P (decl) = module_purview_p ();
18492 /* If this was imported, we'll still be in the entity_hash. */
18493 DECL_MODULE_IMPORT_P (decl) = false;
18497 /* If DECL is a class member, whose class is not defined in this TU
18498 (it was imported), remember this decl. */
18500 void
18501 set_defining_module (tree decl)
18503 gcc_checking_assert (!DECL_LANG_SPECIFIC (decl)
18504 || !DECL_MODULE_IMPORT_P (decl));
18506 if (module_has_cmi_p ())
18508 tree ctx = DECL_CONTEXT (decl);
18509 if (ctx
18510 && (TREE_CODE (ctx) == RECORD_TYPE || TREE_CODE (ctx) == UNION_TYPE)
18511 && DECL_LANG_SPECIFIC (TYPE_NAME (ctx))
18512 && DECL_MODULE_IMPORT_P (TYPE_NAME (ctx)))
18514 /* This entity's context is from an import. We may need to
18515 record this entity to make sure we emit it in the CMI.
18516 Template specializations are in the template hash tables,
18517 so we don't need to record them here as well. */
18518 int use_tpl = -1;
18519 tree ti = node_template_info (decl, use_tpl);
18520 if (use_tpl <= 0)
18522 if (ti)
18524 gcc_checking_assert (!use_tpl);
18525 /* Get to the TEMPLATE_DECL. */
18526 decl = TI_TEMPLATE (ti);
18529 /* Record it on the class_members list. */
18530 vec_safe_push (class_members, decl);
18533 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18534 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
18535 /* This is a partial or explicit specialization. */
18536 vec_safe_push (partial_specializations, decl);
18540 void
18541 set_originating_module (tree decl, bool friend_p ATTRIBUTE_UNUSED)
18543 set_instantiating_module (decl);
18545 if (TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
18546 return;
18548 gcc_checking_assert (friend_p || decl == get_originating_module_decl (decl));
18550 if (!module_exporting_p ())
18551 return;
18553 // FIXME: Check ill-formed linkage
18554 DECL_MODULE_EXPORT_P (decl) = true;
18557 /* DECL is attached to ROOT for odr purposes. */
18559 void
18560 maybe_attach_decl (tree ctx, tree decl)
18562 if (!modules_p ())
18563 return;
18565 // FIXME: For now just deal with lambdas attached to var decls.
18566 // This might be sufficient?
18567 if (TREE_CODE (ctx) != VAR_DECL)
18568 return;
18570 gcc_checking_assert (DECL_NAMESPACE_SCOPE_P (ctx));
18572 if (!attached_table)
18573 attached_table = new attached_map_t (EXPERIMENT (1, 400));
18575 auto &vec = attached_table->get_or_insert (ctx);
18576 if (!vec.length ())
18578 retrofit_lang_decl (ctx);
18579 DECL_MODULE_ATTACHMENTS_P (ctx) = true;
18581 vec.safe_push (decl);
18584 /* Create the flat name string. It is simplest to have it handy. */
18586 void
18587 module_state::set_flatname ()
18589 gcc_checking_assert (!flatname);
18590 if (parent)
18592 auto_vec<tree,5> ids;
18593 size_t len = 0;
18594 char const *primary = NULL;
18595 size_t pfx_len = 0;
18597 for (module_state *probe = this;
18598 probe;
18599 probe = probe->parent)
18600 if (is_partition () && !probe->is_partition ())
18602 primary = probe->get_flatname ();
18603 pfx_len = strlen (primary);
18604 break;
18606 else
18608 ids.safe_push (probe->name);
18609 len += IDENTIFIER_LENGTH (probe->name) + 1;
18612 char *flat = XNEWVEC (char, pfx_len + len + is_partition ());
18613 flatname = flat;
18615 if (primary)
18617 memcpy (flat, primary, pfx_len);
18618 flat += pfx_len;
18619 *flat++ = ':';
18622 for (unsigned len = 0; ids.length ();)
18624 if (len)
18625 flat[len++] = '.';
18626 tree elt = ids.pop ();
18627 unsigned l = IDENTIFIER_LENGTH (elt);
18628 memcpy (flat + len, IDENTIFIER_POINTER (elt), l + 1);
18629 len += l;
18632 else if (is_header ())
18633 flatname = TREE_STRING_POINTER (name);
18634 else
18635 flatname = IDENTIFIER_POINTER (name);
18638 /* Read the CMI file for a module. */
18640 bool
18641 module_state::do_import (cpp_reader *reader, bool outermost)
18643 gcc_assert (global_namespace == current_scope () && loadedness == ML_NONE);
18645 loc = linemap_module_loc (line_table, loc, get_flatname ());
18647 if (lazy_open >= lazy_limit)
18648 freeze_an_elf ();
18650 int fd = -1;
18651 int e = ENOENT;
18652 if (filename)
18654 const char *file = maybe_add_cmi_prefix (filename);
18655 dump () && dump ("CMI is %s", file);
18656 if (note_module_cmi_yes || inform_cmi_p)
18657 inform (loc, "reading CMI %qs", file);
18658 fd = open (file, O_RDONLY | O_CLOEXEC | O_BINARY);
18659 e = errno;
18662 gcc_checking_assert (!slurp);
18663 slurp = new slurping (new elf_in (fd, e));
18665 bool ok = true;
18666 if (!from ()->get_error ())
18668 announce ("importing");
18669 loadedness = ML_CONFIG;
18670 lazy_open++;
18671 ok = read_initial (reader);
18672 slurp->lru = ++lazy_lru;
18675 gcc_assert (slurp->current == ~0u);
18677 return check_read (outermost, ok);
18680 /* Attempt to increase the file descriptor limit. */
18682 static bool
18683 try_increase_lazy (unsigned want)
18685 gcc_checking_assert (lazy_open >= lazy_limit);
18687 /* If we're increasing, saturate at hard limit. */
18688 if (want > lazy_hard_limit && lazy_limit < lazy_hard_limit)
18689 want = lazy_hard_limit;
18691 #if HAVE_SETRLIMIT
18692 if ((!lazy_limit || !param_lazy_modules)
18693 && lazy_hard_limit
18694 && want <= lazy_hard_limit)
18696 struct rlimit rlimit;
18697 rlimit.rlim_cur = want + LAZY_HEADROOM;
18698 rlimit.rlim_max = lazy_hard_limit + LAZY_HEADROOM;
18699 if (!setrlimit (RLIMIT_NOFILE, &rlimit))
18700 lazy_limit = want;
18702 #endif
18704 return lazy_open < lazy_limit;
18707 /* Pick a victim module to freeze its reader. */
18709 void
18710 module_state::freeze_an_elf ()
18712 if (try_increase_lazy (lazy_open * 2))
18713 return;
18715 module_state *victim = NULL;
18716 for (unsigned ix = modules->length (); ix--;)
18718 module_state *candidate = (*modules)[ix];
18719 if (candidate && candidate->slurp && candidate->slurp->lru
18720 && candidate->from ()->is_freezable ()
18721 && (!victim || victim->slurp->lru > candidate->slurp->lru))
18722 victim = candidate;
18725 if (victim)
18727 dump () && dump ("Freezing '%s'", victim->filename);
18728 if (victim->slurp->macro_defs.size)
18729 /* Save the macro definitions to a buffer. */
18730 victim->from ()->preserve (victim->slurp->macro_defs);
18731 if (victim->slurp->macro_tbl.size)
18732 /* Save the macro definitions to a buffer. */
18733 victim->from ()->preserve (victim->slurp->macro_tbl);
18734 victim->from ()->freeze ();
18735 lazy_open--;
18737 else
18738 dump () && dump ("No module available for freezing");
18741 /* Load the lazy slot *MSLOT, INDEX'th slot of the module. */
18743 bool
18744 module_state::lazy_load (unsigned index, binding_slot *mslot)
18746 unsigned n = dump.push (this);
18748 gcc_checking_assert (function_depth);
18750 unsigned cookie = mslot->get_lazy ();
18751 unsigned snum = cookie >> 2;
18752 dump () && dump ("Loading entity %M[%u] section:%u", this, index, snum);
18754 bool ok = load_section (snum, mslot);
18756 dump.pop (n);
18758 return ok;
18761 /* Load MOD's binding for NS::ID into *MSLOT. *MSLOT contains the
18762 lazy cookie. OUTER is true if this is the outermost lazy, (used
18763 for diagnostics). */
18765 void
18766 lazy_load_binding (unsigned mod, tree ns, tree id, binding_slot *mslot)
18768 int count = errorcount + warningcount;
18770 timevar_start (TV_MODULE_IMPORT);
18772 /* Stop GC happening, even in outermost loads (because our caller
18773 could well be building up a lookup set). */
18774 function_depth++;
18776 gcc_checking_assert (mod);
18777 module_state *module = (*modules)[mod];
18778 unsigned n = dump.push (module);
18780 unsigned snum = mslot->get_lazy ();
18781 dump () && dump ("Lazily binding %P@%N section:%u", ns, id,
18782 module->name, snum);
18784 bool ok = !recursive_lazy (snum);
18785 if (ok)
18787 ok = module->load_section (snum, mslot);
18788 lazy_snum = 0;
18789 post_load_processing ();
18792 dump.pop (n);
18794 function_depth--;
18796 timevar_stop (TV_MODULE_IMPORT);
18798 if (!ok)
18799 fatal_error (input_location,
18800 module->is_header ()
18801 ? G_("failed to load binding %<%E%s%E%>")
18802 : G_("failed to load binding %<%E%s%E@%s%>"),
18803 ns, &"::"[ns == global_namespace ? 2 : 0], id,
18804 module->get_flatname ());
18806 if (count != errorcount + warningcount)
18807 inform (input_location,
18808 module->is_header ()
18809 ? G_("during load of binding %<%E%s%E%>")
18810 : G_("during load of binding %<%E%s%E@%s%>"),
18811 ns, &"::"[ns == global_namespace ? 2 : 0], id,
18812 module->get_flatname ());
18815 /* Load any pending entities keyed to the top-key of DECL. */
18817 void
18818 lazy_load_pendings (tree decl)
18820 tree key_decl;
18821 pending_key key;
18822 key.ns = find_pending_key (decl, &key_decl);
18823 key.id = DECL_NAME (key_decl);
18825 auto *pending_vec = pending_table ? pending_table->get (key) : nullptr;
18826 if (!pending_vec)
18827 return;
18829 int count = errorcount + warningcount;
18831 timevar_start (TV_MODULE_IMPORT);
18832 bool ok = !recursive_lazy ();
18833 if (ok)
18835 function_depth++; /* Prevent GC */
18836 unsigned n = dump.push (NULL);
18837 dump () && dump ("Reading %u pending entities keyed to %P",
18838 pending_vec->length (), key.ns, key.id);
18839 for (unsigned ix = pending_vec->length (); ix--;)
18841 unsigned index = (*pending_vec)[ix];
18842 binding_slot *slot = &(*entity_ary)[index];
18844 if (slot->is_lazy ())
18846 module_state *import = import_entity_module (index);
18847 if (!import->lazy_load (index - import->entity_lwm, slot))
18848 ok = false;
18850 else if (dump ())
18852 module_state *import = import_entity_module (index);
18853 dump () && dump ("Entity %M[%u] already loaded",
18854 import, index - import->entity_lwm);
18858 pending_table->remove (key);
18859 dump.pop (n);
18860 lazy_snum = 0;
18861 post_load_processing ();
18862 function_depth--;
18865 timevar_stop (TV_MODULE_IMPORT);
18867 if (!ok)
18868 fatal_error (input_location, "failed to load pendings for %<%E%s%E%>",
18869 key.ns, &"::"[key.ns == global_namespace ? 2 : 0], key.id);
18871 if (count != errorcount + warningcount)
18872 inform (input_location, "during load of pendings for %<%E%s%E%>",
18873 key.ns, &"::"[key.ns == global_namespace ? 2 : 0], key.id);
18876 static void
18877 direct_import (module_state *import, cpp_reader *reader)
18879 timevar_start (TV_MODULE_IMPORT);
18880 unsigned n = dump.push (import);
18882 gcc_checking_assert (import->is_direct () && import->has_location ());
18883 if (import->loadedness == ML_NONE)
18884 if (!import->do_import (reader, true))
18885 gcc_unreachable ();
18887 if (import->loadedness < ML_LANGUAGE)
18889 if (!attached_table)
18890 attached_table = new attached_map_t (EXPERIMENT (1, 400));
18891 import->read_language (true);
18894 (*modules)[0]->set_import (import, import->exported_p);
18896 dump.pop (n);
18897 timevar_stop (TV_MODULE_IMPORT);
18900 /* Import module IMPORT. */
18902 void
18903 import_module (module_state *import, location_t from_loc, bool exporting_p,
18904 tree, cpp_reader *reader)
18906 if (!import->check_not_purview (from_loc))
18907 return;
18909 if (!import->is_header () && current_lang_depth ())
18910 /* Only header units should appear inside language
18911 specifications. The std doesn't specify this, but I think
18912 that's an error in resolving US 033, because language linkage
18913 is also our escape clause to getting things into the global
18914 module, so we don't want to confuse things by having to think
18915 about whether 'extern "C++" { import foo; }' puts foo's
18916 contents into the global module all of a sudden. */
18917 warning (0, "import of named module %qs inside language-linkage block",
18918 import->get_flatname ());
18920 if (exporting_p || module_exporting_p ())
18921 import->exported_p = true;
18923 if (import->loadedness != ML_NONE)
18925 from_loc = ordinary_loc_of (line_table, from_loc);
18926 linemap_module_reparent (line_table, import->loc, from_loc);
18928 gcc_checking_assert (!import->module_p);
18929 gcc_checking_assert (import->is_direct () && import->has_location ());
18931 direct_import (import, reader);
18934 /* Declare the name of the current module to be NAME. EXPORTING_p is
18935 true if this TU is the exporting module unit. */
18937 void
18938 declare_module (module_state *module, location_t from_loc, bool exporting_p,
18939 tree, cpp_reader *reader)
18941 gcc_assert (global_namespace == current_scope ());
18943 module_state *current = (*modules)[0];
18944 if (module_purview_p () || module->loadedness > ML_CONFIG)
18946 error_at (from_loc, module_purview_p ()
18947 ? G_("module already declared")
18948 : G_("module already imported"));
18949 if (module_purview_p ())
18950 module = current;
18951 inform (module->loc, module_purview_p ()
18952 ? G_("module %qs declared here")
18953 : G_("module %qs imported here"),
18954 module->get_flatname ());
18955 return;
18958 gcc_checking_assert (module->module_p);
18959 gcc_checking_assert (module->is_direct () && module->has_location ());
18961 /* Yer a module, 'arry. */
18962 module_kind &= ~MK_GLOBAL;
18963 module_kind |= MK_MODULE;
18965 if (module->is_partition () || exporting_p)
18967 gcc_checking_assert (module->get_flatname ());
18969 if (module->is_partition ())
18970 module_kind |= MK_PARTITION;
18972 if (exporting_p)
18974 module->interface_p = true;
18975 module_kind |= MK_INTERFACE;
18978 if (module->is_header ())
18979 module_kind |= MK_GLOBAL | MK_EXPORTING;
18981 /* Copy the importing information we may have already done. We
18982 do not need to separate out the imports that only happen in
18983 the GMF, inspite of what the literal wording of the std
18984 might imply. See p2191, the core list had a discussion
18985 where the module implementors agreed that the GMF of a named
18986 module is invisible to importers. */
18987 module->imports = current->imports;
18989 module->mod = 0;
18990 (*modules)[0] = module;
18992 else
18994 module->interface_p = true;
18995 current->parent = module; /* So mangler knows module identity. */
18996 direct_import (module, reader);
19000 /* +1, we're the primary or a partition. Therefore emitting a
19001 globally-callable idemportent initializer function.
19002 -1, we have direct imports. Therefore emitting calls to their
19003 initializers. */
19006 module_initializer_kind ()
19008 int result = 0;
19010 if (module_has_cmi_p () && !header_module_p ())
19011 result = +1;
19012 else if (num_init_calls_needed)
19013 result = -1;
19015 return result;
19018 /* Emit calls to each direct import's global initializer. Including
19019 direct imports of directly imported header units. The initializers
19020 of (static) entities in header units will be called by their
19021 importing modules (for the instance contained within that), or by
19022 the current TU (for the instances we've brought in). Of course
19023 such header unit behaviour is evil, but iostream went through that
19024 door some time ago. */
19026 void
19027 module_add_import_initializers ()
19029 unsigned calls = 0;
19030 if (modules)
19032 tree fntype = build_function_type (void_type_node, void_list_node);
19033 releasing_vec args; // There are no args
19035 for (unsigned ix = modules->length (); --ix;)
19037 module_state *import = (*modules)[ix];
19038 if (import->call_init_p)
19040 tree name = mangle_module_global_init (ix);
19041 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
19043 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
19044 SET_DECL_ASSEMBLER_NAME (fndecl, name);
19045 TREE_PUBLIC (fndecl) = true;
19046 determine_visibility (fndecl);
19048 tree call = cp_build_function_call_vec (fndecl, &args,
19049 tf_warning_or_error);
19050 finish_expr_stmt (call);
19052 calls++;
19057 gcc_checking_assert (calls == num_init_calls_needed);
19060 /* NAME & LEN are a preprocessed header name, possibly including the
19061 surrounding "" or <> characters. Return the raw string name of the
19062 module to which it refers. This will be an absolute path, or begin
19063 with ./, so it is immediately distinguishable from a (non-header
19064 unit) module name. If READER is non-null, ask the preprocessor to
19065 locate the header to which it refers using the appropriate include
19066 path. Note that we do never do \ processing of the string, as that
19067 matches the preprocessor's behaviour. */
19069 static const char *
19070 canonicalize_header_name (cpp_reader *reader, location_t loc, bool unquoted,
19071 const char *str, size_t &len_r)
19073 size_t len = len_r;
19074 static char *buf = 0;
19075 static size_t alloc = 0;
19077 if (!unquoted)
19079 gcc_checking_assert (len >= 2
19080 && ((reader && str[0] == '<' && str[len-1] == '>')
19081 || (str[0] == '"' && str[len-1] == '"')));
19082 str += 1;
19083 len -= 2;
19086 if (reader)
19088 gcc_assert (!unquoted);
19090 if (len >= alloc)
19092 alloc = len + 1;
19093 buf = XRESIZEVEC (char, buf, alloc);
19095 memcpy (buf, str, len);
19096 buf[len] = 0;
19098 if (const char *hdr
19099 = cpp_probe_header_unit (reader, buf, str[-1] == '<', loc))
19101 len = strlen (hdr);
19102 str = hdr;
19104 else
19105 str = buf;
19108 if (!(str[0] == '.' ? IS_DIR_SEPARATOR (str[1]) : IS_ABSOLUTE_PATH (str)))
19110 /* Prepend './' */
19111 if (len + 3 > alloc)
19113 alloc = len + 3;
19114 buf = XRESIZEVEC (char, buf, alloc);
19117 buf[0] = '.';
19118 buf[1] = DIR_SEPARATOR;
19119 memmove (buf + 2, str, len);
19120 len += 2;
19121 buf[len] = 0;
19122 str = buf;
19125 len_r = len;
19126 return str;
19129 /* Set the CMI name from a cody packet. Issue an error if
19130 ill-formed. */
19132 void module_state::set_filename (const Cody::Packet &packet)
19134 gcc_checking_assert (!filename);
19135 if (packet.GetCode () == Cody::Client::PC_PATHNAME)
19136 filename = xstrdup (packet.GetString ().c_str ());
19137 else
19139 gcc_checking_assert (packet.GetCode () == Cody::Client::PC_ERROR);
19140 error_at (loc, "unknown Compiled Module Interface: %s",
19141 packet.GetString ().c_str ());
19145 /* Figure out whether to treat HEADER as an include or an import. */
19147 static char *
19148 maybe_translate_include (cpp_reader *reader, line_maps *lmaps, location_t loc,
19149 const char *path)
19151 if (!modules_p ())
19153 /* Turn off. */
19154 cpp_get_callbacks (reader)->translate_include = NULL;
19155 return nullptr;
19158 if (!spans.init_p ())
19159 /* Before the main file, don't divert. */
19160 return nullptr;
19162 dump.push (NULL);
19164 dump () && dump ("Checking include translation '%s'", path);
19165 auto *mapper = get_mapper (cpp_main_loc (reader));
19167 size_t len = strlen (path);
19168 path = canonicalize_header_name (NULL, loc, true, path, len);
19169 auto packet = mapper->IncludeTranslate (path, Cody::Flags::None, len);
19170 int xlate = false;
19171 if (packet.GetCode () == Cody::Client::PC_BOOL)
19172 xlate = -int (packet.GetInteger ());
19173 else if (packet.GetCode () == Cody::Client::PC_PATHNAME)
19175 /* Record the CMI name for when we do the import. */
19176 module_state *import = get_module (build_string (len, path));
19177 import->set_filename (packet);
19178 xlate = +1;
19180 else
19182 gcc_checking_assert (packet.GetCode () == Cody::Client::PC_ERROR);
19183 error_at (loc, "cannot determine %<#include%> translation of %s: %s",
19184 path, packet.GetString ().c_str ());
19187 bool note = false;
19188 if (note_include_translate_yes && xlate > 1)
19189 note = true;
19190 else if (note_include_translate_no && xlate == 0)
19191 note = true;
19192 else if (note_includes)
19193 /* We do not expect the note_includes vector to be large, so O(N)
19194 iteration. */
19195 for (unsigned ix = note_includes->length (); !note && ix--;)
19196 if (!strcmp ((*note_includes)[ix], path))
19197 note = true;
19199 if (note)
19200 inform (loc, xlate
19201 ? G_("include %qs translated to import")
19202 : G_("include %qs processed textually") , path);
19204 dump () && dump (xlate ? "Translating include to import"
19205 : "Keeping include as include");
19206 dump.pop (0);
19208 if (!(xlate > 0))
19209 return nullptr;
19211 /* Create the translation text. */
19212 loc = ordinary_loc_of (lmaps, loc);
19213 const line_map_ordinary *map
19214 = linemap_check_ordinary (linemap_lookup (lmaps, loc));
19215 unsigned col = SOURCE_COLUMN (map, loc);
19216 col -= (col != 0); /* Columns are 1-based. */
19218 unsigned alloc = len + col + 60;
19219 char *res = XNEWVEC (char, alloc);
19221 strcpy (res, "__import");
19222 unsigned actual = 8;
19223 if (col > actual)
19225 /* Pad out so the filename appears at the same position. */
19226 memset (res + actual, ' ', col - actual);
19227 actual = col;
19229 /* No need to encode characters, that's not how header names are
19230 handled. */
19231 actual += snprintf (res + actual, alloc - actual,
19232 "\"%s\" [[__translated]];\n", path);
19233 gcc_checking_assert (actual < alloc);
19235 /* cpplib will delete the buffer. */
19236 return res;
19239 static void
19240 begin_header_unit (cpp_reader *reader)
19242 /* Set the module header name from the main_input_filename. */
19243 const char *main = main_input_filename;
19244 size_t len = strlen (main);
19245 main = canonicalize_header_name (NULL, 0, true, main, len);
19246 module_state *module = get_module (build_string (len, main));
19248 preprocess_module (module, cpp_main_loc (reader), false, false, true, reader);
19251 /* We've just properly entered the main source file. I.e. after the
19252 command line, builtins and forced headers. Record the line map and
19253 location of this map. Note we may be called more than once. The
19254 first call sticks. */
19256 void
19257 module_begin_main_file (cpp_reader *reader, line_maps *lmaps,
19258 const line_map_ordinary *map)
19260 gcc_checking_assert (lmaps == line_table);
19261 if (modules_p () && !spans.init_p ())
19263 unsigned n = dump.push (NULL);
19264 spans.init (lmaps, map);
19265 dump.pop (n);
19266 if (flag_header_unit && !cpp_get_options (reader)->preprocessed)
19268 /* Tell the preprocessor this is an include file. */
19269 cpp_retrofit_as_include (reader);
19270 begin_header_unit (reader);
19275 /* Process the pending_import queue, making sure we know the
19276 filenames. */
19278 static void
19279 name_pending_imports (cpp_reader *reader)
19281 auto *mapper = get_mapper (cpp_main_loc (reader));
19283 if (!vec_safe_length (pending_imports))
19284 /* Not doing anything. */
19285 return;
19287 timevar_start (TV_MODULE_MAPPER);
19289 auto n = dump.push (NULL);
19290 dump () && dump ("Resolving direct import names");
19291 bool want_deps = (bool (mapper->get_flags () & Cody::Flags::NameOnly)
19292 || cpp_get_deps (reader));
19293 bool any = false;
19295 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
19297 module_state *module = (*pending_imports)[ix];
19298 gcc_checking_assert (module->is_direct ());
19299 if (!module->filename && !module->visited_p)
19301 bool export_p = (module->module_p
19302 && (module->is_partition () || module->exported_p));
19304 Cody::Flags flags = Cody::Flags::None;
19305 if (flag_preprocess_only
19306 && !(module->is_header () && !export_p))
19308 if (!want_deps)
19309 continue;
19310 flags = Cody::Flags::NameOnly;
19313 if (!any)
19315 any = true;
19316 mapper->Cork ();
19318 if (export_p)
19319 mapper->ModuleExport (module->get_flatname (), flags);
19320 else
19321 mapper->ModuleImport (module->get_flatname (), flags);
19322 module->visited_p = true;
19326 if (any)
19328 auto response = mapper->Uncork ();
19329 auto r_iter = response.begin ();
19330 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
19332 module_state *module = (*pending_imports)[ix];
19333 if (module->visited_p)
19335 module->visited_p = false;
19336 gcc_checking_assert (!module->filename);
19338 module->set_filename (*r_iter);
19339 ++r_iter;
19344 dump.pop (n);
19346 timevar_stop (TV_MODULE_MAPPER);
19349 /* We've just lexed a module-specific control line for MODULE. Mark
19350 the module as a direct import, and possibly load up its macro
19351 state. Returns the primary module, if this is a module
19352 declaration. */
19353 /* Perhaps we should offer a preprocessing mode where we read the
19354 directives from the header unit, rather than require the header's
19355 CMI. */
19357 module_state *
19358 preprocess_module (module_state *module, location_t from_loc,
19359 bool in_purview, bool is_import, bool is_export,
19360 cpp_reader *reader)
19362 if (!is_import)
19364 if (module->loc)
19365 /* It's already been mentioned, so ignore its module-ness. */
19366 is_import = true;
19367 else
19369 /* Record it is the module. */
19370 module->module_p = true;
19371 if (is_export)
19373 module->exported_p = true;
19374 module->interface_p = true;
19379 if (module->directness < MD_DIRECT + in_purview)
19381 /* Mark as a direct import. */
19382 module->directness = module_directness (MD_DIRECT + in_purview);
19384 /* Set the location to be most informative for users. */
19385 from_loc = ordinary_loc_of (line_table, from_loc);
19386 if (module->loadedness != ML_NONE)
19387 linemap_module_reparent (line_table, module->loc, from_loc);
19388 else
19390 module->loc = from_loc;
19391 if (!module->flatname)
19392 module->set_flatname ();
19396 auto desired = ML_CONFIG;
19397 if (is_import
19398 && module->is_header ()
19399 && (!cpp_get_options (reader)->preprocessed
19400 || cpp_get_options (reader)->directives_only))
19401 /* We need preprocessor state now. */
19402 desired = ML_PREPROCESSOR;
19404 if (!is_import || module->loadedness < desired)
19406 vec_safe_push (pending_imports, module);
19408 if (desired == ML_PREPROCESSOR)
19410 unsigned n = dump.push (NULL);
19412 dump () && dump ("Reading %M preprocessor state", module);
19413 name_pending_imports (reader);
19415 /* Preserve the state of the line-map. */
19416 unsigned pre_hwm = LINEMAPS_ORDINARY_USED (line_table);
19418 /* We only need to close the span, if we're going to emit a
19419 CMI. But that's a little tricky -- our token scanner
19420 needs to be smarter -- and this isn't much state.
19421 Remember, we've not parsed anything at this point, so
19422 our module state flags are inadequate. */
19423 spans.maybe_init ();
19424 spans.close ();
19426 timevar_start (TV_MODULE_IMPORT);
19428 /* Load the config of each pending import -- we must assign
19429 module numbers monotonically. */
19430 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
19432 auto *import = (*pending_imports)[ix];
19433 if (!(import->module_p
19434 && (import->is_partition () || import->exported_p))
19435 && import->loadedness == ML_NONE
19436 && (import->is_header () || !flag_preprocess_only))
19438 unsigned n = dump.push (import);
19439 import->do_import (reader, true);
19440 dump.pop (n);
19443 vec_free (pending_imports);
19445 /* Restore the line-map state. */
19446 spans.open (linemap_module_restore (line_table, pre_hwm));
19448 /* Now read the preprocessor state of this particular
19449 import. */
19450 if (module->loadedness == ML_CONFIG
19451 && module->read_preprocessor (true))
19452 module->import_macros ();
19454 timevar_stop (TV_MODULE_IMPORT);
19456 dump.pop (n);
19460 return is_import ? NULL : get_primary (module);
19463 /* We've completed phase-4 translation. Emit any dependency
19464 information for the not-yet-loaded direct imports, and fill in
19465 their file names. We'll have already loaded up the direct header
19466 unit wavefront. */
19468 void
19469 preprocessed_module (cpp_reader *reader)
19471 unsigned n = dump.push (NULL);
19473 dump () && dump ("Completed phase-4 (tokenization) processing");
19475 name_pending_imports (reader);
19476 vec_free (pending_imports);
19478 spans.maybe_init ();
19479 spans.close ();
19481 using iterator = hash_table<module_state_hash>::iterator;
19482 if (mkdeps *deps = cpp_get_deps (reader))
19484 /* Walk the module hash, informing the dependency machinery. */
19485 iterator end = modules_hash->end ();
19486 for (iterator iter = modules_hash->begin (); iter != end; ++iter)
19488 module_state *module = *iter;
19490 if (module->is_direct ())
19492 if (module->is_module ()
19493 && (module->is_interface () || module->is_partition ()))
19494 deps_add_module_target (deps, module->get_flatname (),
19495 maybe_add_cmi_prefix (module->filename),
19496 module->is_header());
19497 else
19498 deps_add_module_dep (deps, module->get_flatname ());
19503 if (flag_header_unit && !flag_preprocess_only)
19505 /* Find the main module -- remember, it's not yet in the module
19506 array. */
19507 iterator end = modules_hash->end ();
19508 for (iterator iter = modules_hash->begin (); iter != end; ++iter)
19510 module_state *module = *iter;
19511 if (module->is_module ())
19513 declare_module (module, cpp_main_loc (reader), true, NULL, reader);
19514 break;
19519 dump.pop (n);
19522 /* VAL is a global tree, add it to the global vec if it is
19523 interesting. Add some of its targets, if they too are
19524 interesting. We do not add identifiers, as they can be re-found
19525 via the identifier hash table. There is a cost to the number of
19526 global trees. */
19528 static int
19529 maybe_add_global (tree val, unsigned &crc)
19531 int v = 0;
19533 if (val && !(identifier_p (val) || TREE_VISITED (val)))
19535 TREE_VISITED (val) = true;
19536 crc = crc32_unsigned (crc, fixed_trees->length ());
19537 vec_safe_push (fixed_trees, val);
19538 v++;
19540 if (CODE_CONTAINS_STRUCT (TREE_CODE (val), TS_TYPED))
19541 v += maybe_add_global (TREE_TYPE (val), crc);
19542 if (CODE_CONTAINS_STRUCT (TREE_CODE (val), TS_TYPE_COMMON))
19543 v += maybe_add_global (TYPE_NAME (val), crc);
19546 return v;
19549 /* Initialize module state. Create the hash table, determine the
19550 global trees. Create the module for current TU. */
19552 void
19553 init_modules (cpp_reader *reader)
19555 /* PCH should not be reachable because of lang-specs, but the
19556 user could have overriden that. */
19557 if (pch_file)
19558 fatal_error (input_location,
19559 "C++ modules are incompatible with precompiled headers");
19561 if (cpp_get_options (reader)->traditional)
19562 fatal_error (input_location,
19563 "C++ modules are incompatible with traditional preprocessing");
19565 if (flag_preprocess_only)
19567 cpp_options *cpp_opts = cpp_get_options (reader);
19568 if (flag_no_output
19569 || (cpp_opts->deps.style != DEPS_NONE
19570 && !cpp_opts->deps.need_preprocessor_output))
19572 warning (0, flag_dump_macros == 'M'
19573 ? G_("macro debug output may be incomplete with modules")
19574 : G_("module dependencies require preprocessing"));
19575 if (cpp_opts->deps.style != DEPS_NONE)
19576 inform (input_location, "you should use the %<-%s%> option",
19577 cpp_opts->deps.style == DEPS_SYSTEM ? "MD" : "MMD");
19581 /* :: is always exported. */
19582 DECL_MODULE_EXPORT_P (global_namespace) = true;
19584 modules_hash = hash_table<module_state_hash>::create_ggc (31);
19585 vec_safe_reserve (modules, 20);
19587 /* Create module for current TU. */
19588 module_state *current
19589 = new (ggc_alloc<module_state> ()) module_state (NULL_TREE, NULL, false);
19590 current->mod = 0;
19591 bitmap_set_bit (current->imports, 0);
19592 modules->quick_push (current);
19594 gcc_checking_assert (!fixed_trees);
19596 headers = BITMAP_GGC_ALLOC ();
19598 if (note_includes)
19599 /* Canonicalize header names. */
19600 for (unsigned ix = 0; ix != note_includes->length (); ix++)
19602 const char *hdr = (*note_includes)[ix];
19603 size_t len = strlen (hdr);
19605 bool system = hdr[0] == '<';
19606 bool user = hdr[0] == '"';
19607 bool delimed = system || user;
19609 if (len <= (delimed ? 2 : 0)
19610 || (delimed && hdr[len-1] != (system ? '>' : '"')))
19611 error ("invalid header name %qs", hdr);
19613 hdr = canonicalize_header_name (delimed ? reader : NULL,
19614 0, !delimed, hdr, len);
19615 char *path = XNEWVEC (char, len + 1);
19616 memcpy (path, hdr, len);
19617 path[len] = 0;
19619 (*note_includes)[ix] = path;
19622 if (note_cmis)
19623 /* Canonicalize & mark module names. */
19624 for (unsigned ix = 0; ix != note_cmis->length (); ix++)
19626 const char *name = (*note_cmis)[ix];
19627 size_t len = strlen (name);
19629 bool is_system = name[0] == '<';
19630 bool is_user = name[0] == '"';
19631 bool is_pathname = false;
19632 if (!(is_system || is_user))
19633 for (unsigned ix = len; !is_pathname && ix--;)
19634 is_pathname = IS_DIR_SEPARATOR (name[ix]);
19635 if (is_system || is_user || is_pathname)
19637 if (len <= (is_pathname ? 0 : 2)
19638 || (!is_pathname && name[len-1] != (is_system ? '>' : '"')))
19640 error ("invalid header name %qs", name);
19641 continue;
19643 else
19644 name = canonicalize_header_name (is_pathname ? nullptr : reader,
19645 0, is_pathname, name, len);
19647 if (auto module = get_module (name))
19648 module->inform_cmi_p = 1;
19649 else
19650 error ("invalid module name %qs", name);
19653 dump.push (NULL);
19655 /* Determine lazy handle bound. */
19657 unsigned limit = 1000;
19658 #if HAVE_GETRLIMIT
19659 struct rlimit rlimit;
19660 if (!getrlimit (RLIMIT_NOFILE, &rlimit))
19662 lazy_hard_limit = (rlimit.rlim_max < 1000000
19663 ? unsigned (rlimit.rlim_max) : 1000000);
19664 lazy_hard_limit = (lazy_hard_limit > LAZY_HEADROOM
19665 ? lazy_hard_limit - LAZY_HEADROOM : 0);
19666 if (rlimit.rlim_cur < limit)
19667 limit = unsigned (rlimit.rlim_cur);
19669 #endif
19670 limit = limit > LAZY_HEADROOM ? limit - LAZY_HEADROOM : 1;
19672 if (unsigned parm = param_lazy_modules)
19674 if (parm <= limit || !lazy_hard_limit || !try_increase_lazy (parm))
19675 lazy_limit = parm;
19677 else
19678 lazy_limit = limit;
19681 if (dump ())
19683 verstr_t ver;
19684 version2string (MODULE_VERSION, ver);
19685 dump ("Source: %s", main_input_filename);
19686 dump ("Compiler: %s", version_string);
19687 dump ("Modules: %s", ver);
19688 dump ("Checking: %s",
19689 #if CHECKING_P
19690 "checking"
19691 #elif ENABLE_ASSERT_CHECKING
19692 "asserting"
19693 #else
19694 "release"
19695 #endif
19697 dump ("Compiled by: "
19698 #ifdef __GNUC__
19699 "GCC %d.%d, %s", __GNUC__, __GNUC_MINOR__,
19700 #ifdef __OPTIMIZE__
19701 "optimizing"
19702 #else
19703 "not optimizing"
19704 #endif
19705 #else
19706 "not GCC"
19707 #endif
19709 dump ("Reading: %s", MAPPED_READING ? "mmap" : "fileio");
19710 dump ("Writing: %s", MAPPED_WRITING ? "mmap" : "fileio");
19711 dump ("Lazy limit: %u", lazy_limit);
19712 dump ("Lazy hard limit: %u", lazy_hard_limit);
19713 dump ("");
19716 /* Construct the global tree array. This is an array of unique
19717 global trees (& types). Do this now, rather than lazily, as
19718 some global trees are lazily created and we don't want that to
19719 mess with our syndrome of fixed trees. */
19720 unsigned crc = 0;
19721 vec_alloc (fixed_trees, 200);
19723 dump () && dump ("+Creating globals");
19724 /* Insert the TRANSLATION_UNIT_DECL. */
19725 TREE_VISITED (DECL_CONTEXT (global_namespace)) = true;
19726 fixed_trees->quick_push (DECL_CONTEXT (global_namespace));
19727 for (unsigned jx = 0; global_tree_arys[jx].first; jx++)
19729 const tree *ptr = global_tree_arys[jx].first;
19730 unsigned limit = global_tree_arys[jx].second;
19732 for (unsigned ix = 0; ix != limit; ix++, ptr++)
19734 !(ix & 31) && dump ("") && dump ("+\t%u:%u:", jx, ix);
19735 unsigned v = maybe_add_global (*ptr, crc);
19736 dump () && dump ("+%u", v);
19739 global_crc = crc32_unsigned (crc, fixed_trees->length ());
19740 dump ("") && dump ("Created %u unique globals, crc=%x",
19741 fixed_trees->length (), global_crc);
19742 for (unsigned ix = fixed_trees->length (); ix--;)
19743 TREE_VISITED ((*fixed_trees)[ix]) = false;
19745 dump.pop (0);
19747 if (!flag_module_lazy)
19748 /* Get the mapper now, if we're not being lazy. */
19749 get_mapper (cpp_main_loc (reader));
19751 if (!flag_preprocess_only)
19753 pending_table = new pending_map_t (EXPERIMENT (1, 400));
19754 entity_map = new entity_map_t (EXPERIMENT (1, 400));
19755 vec_safe_reserve (entity_ary, EXPERIMENT (1, 400));
19758 #if CHECKING_P
19759 note_defs = note_defs_table_t::create_ggc (1000);
19760 #endif
19762 if (flag_header_unit && cpp_get_options (reader)->preprocessed)
19763 begin_header_unit (reader);
19765 /* Collect here to make sure things are tagged correctly (when
19766 aggressively GC'd). */
19767 ggc_collect ();
19770 /* If NODE is a deferred macro, load it. */
19772 static int
19773 load_macros (cpp_reader *reader, cpp_hashnode *node, void *)
19775 location_t main_loc
19776 = MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0));
19778 if (cpp_user_macro_p (node)
19779 && !node->value.macro)
19781 cpp_macro *macro = cpp_get_deferred_macro (reader, node, main_loc);
19782 dump () && dump ("Loaded macro #%s %I",
19783 macro ? "define" : "undef", identifier (node));
19786 return 1;
19789 /* At the end of tokenizing, we no longer need the macro tables of
19790 imports. But the user might have requested some checking. */
19792 void
19793 maybe_check_all_macros (cpp_reader *reader)
19795 if (!warn_imported_macros)
19796 return;
19798 /* Force loading of any remaining deferred macros. This will
19799 produce diagnostics if they are ill-formed. */
19800 unsigned n = dump.push (NULL);
19801 cpp_forall_identifiers (reader, load_macros, NULL);
19802 dump.pop (n);
19805 /* Write the CMI, if we're a module interface. */
19807 void
19808 finish_module_processing (cpp_reader *reader)
19810 if (header_module_p ())
19811 module_kind &= ~MK_EXPORTING;
19813 if (!modules || !(*modules)[0]->name)
19815 if (flag_module_only)
19816 warning (0, "%<-fmodule-only%> used for non-interface");
19818 else if (!flag_syntax_only)
19820 int fd = -1;
19821 int e = ENOENT;
19823 timevar_start (TV_MODULE_EXPORT);
19825 /* Force a valid but empty line map at the end. This simplifies
19826 the line table preparation and writing logic. */
19827 linemap_add (line_table, LC_ENTER, false, "", 0);
19829 /* We write to a tmpname, and then atomically rename. */
19830 const char *path = NULL;
19831 char *tmp_name = NULL;
19832 module_state *state = (*modules)[0];
19834 unsigned n = dump.push (state);
19835 state->announce ("creating");
19836 if (state->filename)
19838 size_t len = 0;
19839 path = maybe_add_cmi_prefix (state->filename, &len);
19840 tmp_name = XNEWVEC (char, len + 3);
19841 memcpy (tmp_name, path, len);
19842 strcpy (&tmp_name[len], "~");
19844 if (!errorcount)
19845 for (unsigned again = 2; ; again--)
19847 fd = open (tmp_name,
19848 O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY,
19849 S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
19850 e = errno;
19851 if (fd >= 0 || !again || e != ENOENT)
19852 break;
19853 create_dirs (tmp_name);
19855 if (note_module_cmi_yes || state->inform_cmi_p)
19856 inform (state->loc, "writing CMI %qs", path);
19857 dump () && dump ("CMI is %s", path);
19860 if (errorcount)
19861 warning_at (state->loc, 0, "not writing module %qs due to errors",
19862 state->get_flatname ());
19863 else
19865 elf_out to (fd, e);
19866 if (to.begin ())
19868 auto loc = input_location;
19869 /* So crashes finger-point the module decl. */
19870 input_location = state->loc;
19871 state->write (&to, reader);
19872 input_location = loc;
19874 if (to.end ())
19876 /* Some OS's do not replace NEWNAME if it already
19877 exists. This'll have a race condition in erroneous
19878 concurrent builds. */
19879 unlink (path);
19880 if (rename (tmp_name, path))
19882 dump () && dump ("Rename ('%s','%s') errno=%u", errno);
19883 to.set_error (errno);
19887 if (to.get_error ())
19889 error_at (state->loc, "failed to write compiled module: %s",
19890 to.get_error (state->filename));
19891 state->note_cmi_name ();
19895 if (!errorcount)
19897 auto *mapper = get_mapper (cpp_main_loc (reader));
19899 mapper->ModuleCompiled (state->get_flatname ());
19901 else if (path)
19903 /* We failed, attempt to erase all evidence we even tried. */
19904 unlink (tmp_name);
19905 unlink (path);
19906 XDELETEVEC (tmp_name);
19909 dump.pop (n);
19910 timevar_stop (TV_MODULE_EXPORT);
19912 ggc_collect ();
19915 if (modules)
19917 unsigned n = dump.push (NULL);
19918 dump () && dump ("Imported %u modules", modules->length () - 1);
19919 dump () && dump ("Containing %u clusters", available_clusters);
19920 dump () && dump ("Loaded %u clusters (%u%%)", loaded_clusters,
19921 (loaded_clusters * 100 + available_clusters / 2) /
19922 (available_clusters + !available_clusters));
19923 dump.pop (n);
19926 if (modules && !header_module_p ())
19928 /* Determine call_init_p. We need the same bitmap allocation
19929 scheme as for the imports member. */
19930 function_depth++; /* Disable GC. */
19931 bitmap indirect_imports (BITMAP_GGC_ALLOC ());
19933 /* Because indirect imports are before their direct import, and
19934 we're scanning the array backwards, we only need one pass! */
19935 for (unsigned ix = modules->length (); --ix;)
19937 module_state *import = (*modules)[ix];
19939 if (!import->is_header ()
19940 && !bitmap_bit_p (indirect_imports, ix))
19942 /* Everything this imports is therefore indirectly
19943 imported. */
19944 bitmap_ior_into (indirect_imports, import->imports);
19945 /* We don't have to worry about the self-import bit,
19946 because of the single pass. */
19948 import->call_init_p = true;
19949 num_init_calls_needed++;
19952 function_depth--;
19956 void
19957 fini_modules ()
19959 /* We're done with the macro tables now. */
19960 vec_free (macro_exports);
19961 vec_free (macro_imports);
19962 headers = NULL;
19964 /* We're now done with everything but the module names. */
19965 set_cmi_repo (NULL);
19966 if (mapper)
19968 timevar_start (TV_MODULE_MAPPER);
19969 module_client::close_module_client (0, mapper);
19970 mapper = nullptr;
19971 timevar_stop (TV_MODULE_MAPPER);
19973 module_state_config::release ();
19975 #if CHECKING_P
19976 note_defs = NULL;
19977 #endif
19979 if (modules)
19980 for (unsigned ix = modules->length (); --ix;)
19981 if (module_state *state = (*modules)[ix])
19982 state->release ();
19984 /* No need to lookup modules anymore. */
19985 modules_hash = NULL;
19987 /* Or entity array. We still need the entity map to find import numbers. */
19988 vec_free (entity_ary);
19989 entity_ary = NULL;
19991 /* Or remember any pending entities. */
19992 delete pending_table;
19993 pending_table = NULL;
19995 /* Or any attachments -- Let it go! */
19996 delete attached_table;
19997 attached_table = NULL;
19999 /* Allow a GC, we've possibly made much data unreachable. */
20000 ggc_collect ();
20003 /* If CODE is a module option, handle it & return true. Otherwise
20004 return false. For unknown reasons I cannot get the option
20005 generation machinery to set fmodule-mapper or -fmodule-header to
20006 make a string type option variable. */
20008 bool
20009 handle_module_option (unsigned code, const char *str, int)
20011 auto hdr = CMS_header;
20013 switch (opt_code (code))
20015 case OPT_fmodule_mapper_:
20016 module_mapper_name = str;
20017 return true;
20019 case OPT_fmodule_header_:
20021 if (!strcmp (str, "user"))
20022 hdr = CMS_user;
20023 else if (!strcmp (str, "system"))
20024 hdr = CMS_system;
20025 else
20026 error ("unknown header kind %qs", str);
20028 /* Fallthrough. */
20030 case OPT_fmodule_header:
20031 flag_header_unit = hdr;
20032 flag_modules = 1;
20033 return true;
20035 case OPT_flang_info_include_translate_:
20036 vec_safe_push (note_includes, str);
20037 return true;
20039 case OPT_flang_info_module_cmi_:
20040 vec_safe_push (note_cmis, str);
20041 return true;
20043 default:
20044 return false;
20048 /* Set preprocessor callbacks and options for modules. */
20050 void
20051 module_preprocess_options (cpp_reader *reader)
20053 gcc_checking_assert (!lang_hooks.preprocess_undef);
20054 if (modules_p ())
20056 auto *cb = cpp_get_callbacks (reader);
20058 cb->translate_include = maybe_translate_include;
20059 cb->user_deferred_macro = module_state::deferred_macro;
20060 if (flag_header_unit)
20062 /* If the preprocessor hook is already in use, that
20063 implementation will call the undef langhook. */
20064 if (cb->undef)
20065 lang_hooks.preprocess_undef = module_state::undef_macro;
20066 else
20067 cb->undef = module_state::undef_macro;
20069 auto *opt = cpp_get_options (reader);
20070 opt->module_directives = true;
20071 opt->main_search = cpp_main_search (flag_header_unit);
20075 #include "gt-cp-module.h"