OSDN Git Service

69ba34b40b1134369c961eaa2df2fb4225a6a27c
[pf3gnuchains/gcc-fork.git] / gcc / ggc-page.c
1 /* "Bag-of-pages" garbage collector for the GNU compiler.
2    Copyright (C) 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING.  If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "toplev.h"
29 #include "varray.h"
30 #include "flags.h"
31 #include "ggc.h"
32 #include "timevar.h"
33 #include "params.h"
34 #ifdef ENABLE_VALGRIND_CHECKING
35 # ifdef HAVE_MEMCHECK_H
36 # include <memcheck.h>
37 # else
38 # include <valgrind.h>
39 # endif
40 #else
41 /* Avoid #ifdef:s when we can help it.  */
42 #define VALGRIND_DISCARD(x)
43 #endif
44
45 /* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a
46    file open.  Prefer either to valloc.  */
47 #ifdef HAVE_MMAP_ANON
48 # undef HAVE_MMAP_DEV_ZERO
49
50 # include <sys/mman.h>
51 # ifndef MAP_FAILED
52 #  define MAP_FAILED -1
53 # endif
54 # if !defined (MAP_ANONYMOUS) && defined (MAP_ANON)
55 #  define MAP_ANONYMOUS MAP_ANON
56 # endif
57 # define USING_MMAP
58
59 #endif
60
61 #ifdef HAVE_MMAP_DEV_ZERO
62
63 # include <sys/mman.h>
64 # ifndef MAP_FAILED
65 #  define MAP_FAILED -1
66 # endif
67 # define USING_MMAP
68
69 #endif
70
71 #ifndef USING_MMAP
72 #define USING_MALLOC_PAGE_GROUPS
73 #endif
74
75 /* Stategy:
76
77    This garbage-collecting allocator allocates objects on one of a set
78    of pages.  Each page can allocate objects of a single size only;
79    available sizes are powers of two starting at four bytes.  The size
80    of an allocation request is rounded up to the next power of two
81    (`order'), and satisfied from the appropriate page.
82
83    Each page is recorded in a page-entry, which also maintains an
84    in-use bitmap of object positions on the page.  This allows the
85    allocation state of a particular object to be flipped without
86    touching the page itself.
87
88    Each page-entry also has a context depth, which is used to track
89    pushing and popping of allocation contexts.  Only objects allocated
90    in the current (highest-numbered) context may be collected.
91
92    Page entries are arranged in an array of singly-linked lists.  The
93    array is indexed by the allocation size, in bits, of the pages on
94    it; i.e. all pages on a list allocate objects of the same size.
95    Pages are ordered on the list such that all non-full pages precede
96    all full pages, with non-full pages arranged in order of decreasing
97    context depth.
98
99    Empty pages (of all orders) are kept on a single page cache list,
100    and are considered first when new pages are required; they are
101    deallocated at the start of the next collection if they haven't
102    been recycled by then.  */
103
104 /* Define GGC_DEBUG_LEVEL to print debugging information.
105      0: No debugging output.
106      1: GC statistics only.
107      2: Page-entry allocations/deallocations as well.
108      3: Object allocations as well.
109      4: Object marks as well.  */
110 #define GGC_DEBUG_LEVEL (0)
111 \f
112 #ifndef HOST_BITS_PER_PTR
113 #define HOST_BITS_PER_PTR  HOST_BITS_PER_LONG
114 #endif
115
116 \f
117 /* A two-level tree is used to look up the page-entry for a given
118    pointer.  Two chunks of the pointer's bits are extracted to index
119    the first and second levels of the tree, as follows:
120
121                                    HOST_PAGE_SIZE_BITS
122                            32           |      |
123        msb +----------------+----+------+------+ lsb
124                             |    |      |
125                          PAGE_L1_BITS   |
126                                  |      |
127                                PAGE_L2_BITS
128
129    The bottommost HOST_PAGE_SIZE_BITS are ignored, since page-entry
130    pages are aligned on system page boundaries.  The next most
131    significant PAGE_L2_BITS and PAGE_L1_BITS are the second and first
132    index values in the lookup table, respectively.
133
134    For 32-bit architectures and the settings below, there are no
135    leftover bits.  For architectures with wider pointers, the lookup
136    tree points to a list of pages, which must be scanned to find the
137    correct one.  */
138
139 #define PAGE_L1_BITS    (8)
140 #define PAGE_L2_BITS    (32 - PAGE_L1_BITS - G.lg_pagesize)
141 #define PAGE_L1_SIZE    ((size_t) 1 << PAGE_L1_BITS)
142 #define PAGE_L2_SIZE    ((size_t) 1 << PAGE_L2_BITS)
143
144 #define LOOKUP_L1(p) \
145   (((size_t) (p) >> (32 - PAGE_L1_BITS)) & ((1 << PAGE_L1_BITS) - 1))
146
147 #define LOOKUP_L2(p) \
148   (((size_t) (p) >> G.lg_pagesize) & ((1 << PAGE_L2_BITS) - 1))
149
150 /* The number of objects per allocation page, for objects on a page of
151    the indicated ORDER.  */
152 #define OBJECTS_PER_PAGE(ORDER) objects_per_page_table[ORDER]
153
154 /* The number of objects in P.  */
155 #define OBJECTS_IN_PAGE(P) ((P)->bytes / OBJECT_SIZE ((P)->order))
156
157 /* The size of an object on a page of the indicated ORDER.  */
158 #define OBJECT_SIZE(ORDER) object_size_table[ORDER]
159
160 /* For speed, we avoid doing a general integer divide to locate the
161    offset in the allocation bitmap, by precalculating numbers M, S
162    such that (O * M) >> S == O / Z (modulo 2^32), for any offset O
163    within the page which is evenly divisible by the object size Z.  */
164 #define DIV_MULT(ORDER) inverse_table[ORDER].mult
165 #define DIV_SHIFT(ORDER) inverse_table[ORDER].shift
166 #define OFFSET_TO_BIT(OFFSET, ORDER) \
167   (((OFFSET) * DIV_MULT (ORDER)) >> DIV_SHIFT (ORDER))
168
169 /* The number of extra orders, not corresponding to power-of-two sized
170    objects.  */
171
172 #define NUM_EXTRA_ORDERS ARRAY_SIZE (extra_order_size_table)
173
174 #define RTL_SIZE(NSLOTS) \
175   (sizeof (struct rtx_def) + ((NSLOTS) - 1) * sizeof (rtunion))
176
177 /* The Ith entry is the maximum size of an object to be stored in the
178    Ith extra order.  Adding a new entry to this array is the *only*
179    thing you need to do to add a new special allocation size.  */
180
181 static const size_t extra_order_size_table[] = {
182   sizeof (struct tree_decl),
183   sizeof (struct tree_list),
184   RTL_SIZE (2),                 /* REG, MEM, PLUS, etc.  */
185   RTL_SIZE (10),                /* INSN, CALL_INSN, JUMP_INSN */
186 };
187
188 /* The total number of orders.  */
189
190 #define NUM_ORDERS (HOST_BITS_PER_PTR + NUM_EXTRA_ORDERS)
191
192 /* We use this structure to determine the alignment required for
193    allocations.  For power-of-two sized allocations, that's not a
194    problem, but it does matter for odd-sized allocations.  */
195
196 struct max_alignment {
197   char c;
198   union {
199     HOST_WIDEST_INT i;
200 #ifdef HAVE_LONG_DOUBLE
201     long double d;
202 #else
203     double d;
204 #endif
205   } u;
206 };
207
208 /* The biggest alignment required.  */
209
210 #define MAX_ALIGNMENT (offsetof (struct max_alignment, u))
211
212 /* Compute the smallest nonnegative number which when added to X gives
213    a multiple of F.  */
214
215 #define ROUND_UP_VALUE(x, f) ((f) - 1 - ((f) - 1 + (x)) % (f))
216
217 /* Compute the smallest multiple of F that is >= X.  */
218
219 #define ROUND_UP(x, f) (CEIL (x, f) * (f))
220
221 /* The Ith entry is the number of objects on a page or order I.  */
222
223 static unsigned objects_per_page_table[NUM_ORDERS];
224
225 /* The Ith entry is the size of an object on a page of order I.  */
226
227 static size_t object_size_table[NUM_ORDERS];
228
229 /* The Ith entry is a pair of numbers (mult, shift) such that
230    ((k * mult) >> shift) mod 2^32 == (k / OBJECT_SIZE(I)) mod 2^32,
231    for all k evenly divisible by OBJECT_SIZE(I).  */
232
233 static struct
234 {
235   unsigned int mult;
236   unsigned int shift;
237 }
238 inverse_table[NUM_ORDERS];
239
240 /* A page_entry records the status of an allocation page.  This
241    structure is dynamically sized to fit the bitmap in_use_p.  */
242 typedef struct page_entry
243 {
244   /* The next page-entry with objects of the same size, or NULL if
245      this is the last page-entry.  */
246   struct page_entry *next;
247
248   /* The number of bytes allocated.  (This will always be a multiple
249      of the host system page size.)  */
250   size_t bytes;
251
252   /* The address at which the memory is allocated.  */
253   char *page;
254
255 #ifdef USING_MALLOC_PAGE_GROUPS
256   /* Back pointer to the page group this page came from.  */
257   struct page_group *group;
258 #endif
259
260   /* Saved in-use bit vector for pages that aren't in the topmost
261      context during collection.  */
262   unsigned long *save_in_use_p;
263
264   /* Context depth of this page.  */
265   unsigned short context_depth;
266
267   /* The number of free objects remaining on this page.  */
268   unsigned short num_free_objects;
269
270   /* A likely candidate for the bit position of a free object for the
271      next allocation from this page.  */
272   unsigned short next_bit_hint;
273
274   /* The lg of size of objects allocated from this page.  */
275   unsigned char order;
276
277   /* A bit vector indicating whether or not objects are in use.  The
278      Nth bit is one if the Nth object on this page is allocated.  This
279      array is dynamically sized.  */
280   unsigned long in_use_p[1];
281 } page_entry;
282
283 #ifdef USING_MALLOC_PAGE_GROUPS
284 /* A page_group describes a large allocation from malloc, from which
285    we parcel out aligned pages.  */
286 typedef struct page_group
287 {
288   /* A linked list of all extant page groups.  */
289   struct page_group *next;
290
291   /* The address we received from malloc.  */
292   char *allocation;
293
294   /* The size of the block.  */
295   size_t alloc_size;
296
297   /* A bitmask of pages in use.  */
298   unsigned int in_use;
299 } page_group;
300 #endif
301
302 #if HOST_BITS_PER_PTR <= 32
303
304 /* On 32-bit hosts, we use a two level page table, as pictured above.  */
305 typedef page_entry **page_table[PAGE_L1_SIZE];
306
307 #else
308
309 /* On 64-bit hosts, we use the same two level page tables plus a linked
310    list that disambiguates the top 32-bits.  There will almost always be
311    exactly one entry in the list.  */
312 typedef struct page_table_chain
313 {
314   struct page_table_chain *next;
315   size_t high_bits;
316   page_entry **table[PAGE_L1_SIZE];
317 } *page_table;
318
319 #endif
320
321 /* The rest of the global variables.  */
322 static struct globals
323 {
324   /* The Nth element in this array is a page with objects of size 2^N.
325      If there are any pages with free objects, they will be at the
326      head of the list.  NULL if there are no page-entries for this
327      object size.  */
328   page_entry *pages[NUM_ORDERS];
329
330   /* The Nth element in this array is the last page with objects of
331      size 2^N.  NULL if there are no page-entries for this object
332      size.  */
333   page_entry *page_tails[NUM_ORDERS];
334
335   /* Lookup table for associating allocation pages with object addresses.  */
336   page_table lookup;
337
338   /* The system's page size.  */
339   size_t pagesize;
340   size_t lg_pagesize;
341
342   /* Bytes currently allocated.  */
343   size_t allocated;
344
345   /* Bytes currently allocated at the end of the last collection.  */
346   size_t allocated_last_gc;
347
348   /* Total amount of memory mapped.  */
349   size_t bytes_mapped;
350
351   /* Bit N set if any allocations have been done at context depth N.  */
352   unsigned long context_depth_allocations;
353
354   /* Bit N set if any collections have been done at context depth N.  */
355   unsigned long context_depth_collections;
356
357   /* The current depth in the context stack.  */
358   unsigned short context_depth;
359
360   /* A file descriptor open to /dev/zero for reading.  */
361 #if defined (HAVE_MMAP_DEV_ZERO)
362   int dev_zero_fd;
363 #endif
364
365   /* A cache of free system pages.  */
366   page_entry *free_pages;
367
368 #ifdef USING_MALLOC_PAGE_GROUPS
369   page_group *page_groups;
370 #endif
371
372   /* The file descriptor for debugging output.  */
373   FILE *debug_file;
374 } G;
375
376 /* The size in bytes required to maintain a bitmap for the objects
377    on a page-entry.  */
378 #define BITMAP_SIZE(Num_objects) \
379   (CEIL ((Num_objects), HOST_BITS_PER_LONG) * sizeof(long))
380
381 /* Allocate pages in chunks of this size, to throttle calls to memory
382    allocation routines.  The first page is used, the rest go onto the
383    free list.  This cannot be larger than HOST_BITS_PER_INT for the
384    in_use bitmask for page_group.  */
385 #define GGC_QUIRE_SIZE 16
386 \f
387 static int ggc_allocated_p PARAMS ((const void *));
388 static page_entry *lookup_page_table_entry PARAMS ((const void *));
389 static void set_page_table_entry PARAMS ((void *, page_entry *));
390 #ifdef USING_MMAP
391 static char *alloc_anon PARAMS ((char *, size_t));
392 #endif
393 #ifdef USING_MALLOC_PAGE_GROUPS
394 static size_t page_group_index PARAMS ((char *, char *));
395 static void set_page_group_in_use PARAMS ((page_group *, char *));
396 static void clear_page_group_in_use PARAMS ((page_group *, char *));
397 #endif
398 static struct page_entry * alloc_page PARAMS ((unsigned));
399 static void free_page PARAMS ((struct page_entry *));
400 static void release_pages PARAMS ((void));
401 static void clear_marks PARAMS ((void));
402 static void sweep_pages PARAMS ((void));
403 static void ggc_recalculate_in_use_p PARAMS ((page_entry *));
404 static void compute_inverse PARAMS ((unsigned));
405
406 #ifdef ENABLE_GC_CHECKING
407 static void poison_pages PARAMS ((void));
408 #endif
409
410 void debug_print_page_list PARAMS ((int));
411 \f
412 /* Returns nonzero if P was allocated in GC'able memory.  */
413
414 static inline int
415 ggc_allocated_p (p)
416      const void *p;
417 {
418   page_entry ***base;
419   size_t L1, L2;
420
421 #if HOST_BITS_PER_PTR <= 32
422   base = &G.lookup[0];
423 #else
424   page_table table = G.lookup;
425   size_t high_bits = (size_t) p & ~ (size_t) 0xffffffff;
426   while (1)
427     {
428       if (table == NULL)
429         return 0;
430       if (table->high_bits == high_bits)
431         break;
432       table = table->next;
433     }
434   base = &table->table[0];
435 #endif
436
437   /* Extract the level 1 and 2 indices.  */
438   L1 = LOOKUP_L1 (p);
439   L2 = LOOKUP_L2 (p);
440
441   return base[L1] && base[L1][L2];
442 }
443
444 /* Traverse the page table and find the entry for a page.
445    Die (probably) if the object wasn't allocated via GC.  */
446
447 static inline page_entry *
448 lookup_page_table_entry(p)
449      const void *p;
450 {
451   page_entry ***base;
452   size_t L1, L2;
453
454 #if HOST_BITS_PER_PTR <= 32
455   base = &G.lookup[0];
456 #else
457   page_table table = G.lookup;
458   size_t high_bits = (size_t) p & ~ (size_t) 0xffffffff;
459   while (table->high_bits != high_bits)
460     table = table->next;
461   base = &table->table[0];
462 #endif
463
464   /* Extract the level 1 and 2 indices.  */
465   L1 = LOOKUP_L1 (p);
466   L2 = LOOKUP_L2 (p);
467
468   return base[L1][L2];
469 }
470
471 /* Set the page table entry for a page.  */
472
473 static void
474 set_page_table_entry(p, entry)
475      void *p;
476      page_entry *entry;
477 {
478   page_entry ***base;
479   size_t L1, L2;
480
481 #if HOST_BITS_PER_PTR <= 32
482   base = &G.lookup[0];
483 #else
484   page_table table;
485   size_t high_bits = (size_t) p & ~ (size_t) 0xffffffff;
486   for (table = G.lookup; table; table = table->next)
487     if (table->high_bits == high_bits)
488       goto found;
489
490   /* Not found -- allocate a new table.  */
491   table = (page_table) xcalloc (1, sizeof(*table));
492   table->next = G.lookup;
493   table->high_bits = high_bits;
494   G.lookup = table;
495 found:
496   base = &table->table[0];
497 #endif
498
499   /* Extract the level 1 and 2 indices.  */
500   L1 = LOOKUP_L1 (p);
501   L2 = LOOKUP_L2 (p);
502
503   if (base[L1] == NULL)
504     base[L1] = (page_entry **) xcalloc (PAGE_L2_SIZE, sizeof (page_entry *));
505
506   base[L1][L2] = entry;
507 }
508
509 /* Prints the page-entry for object size ORDER, for debugging.  */
510
511 void
512 debug_print_page_list (order)
513      int order;
514 {
515   page_entry *p;
516   printf ("Head=%p, Tail=%p:\n", (PTR) G.pages[order],
517           (PTR) G.page_tails[order]);
518   p = G.pages[order];
519   while (p != NULL)
520     {
521       printf ("%p(%1d|%3d) -> ", (PTR) p, p->context_depth,
522               p->num_free_objects);
523       p = p->next;
524     }
525   printf ("NULL\n");
526   fflush (stdout);
527 }
528
529 #ifdef USING_MMAP
530 /* Allocate SIZE bytes of anonymous memory, preferably near PREF,
531    (if non-null).  The ifdef structure here is intended to cause a
532    compile error unless exactly one of the HAVE_* is defined.  */
533
534 static inline char *
535 alloc_anon (pref, size)
536      char *pref ATTRIBUTE_UNUSED;
537      size_t size;
538 {
539 #ifdef HAVE_MMAP_ANON
540   char *page = (char *) mmap (pref, size, PROT_READ | PROT_WRITE,
541                               MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
542 #endif
543 #ifdef HAVE_MMAP_DEV_ZERO
544   char *page = (char *) mmap (pref, size, PROT_READ | PROT_WRITE,
545                               MAP_PRIVATE, G.dev_zero_fd, 0);
546 #endif
547
548   if (page == (char *) MAP_FAILED)
549     {
550       perror ("virtual memory exhausted");
551       exit (FATAL_EXIT_CODE);
552     }
553
554   /* Remember that we allocated this memory.  */
555   G.bytes_mapped += size;
556
557   /* Pretend we don't have access to the allocated pages.  We'll enable
558      access to smaller pieces of the area in ggc_alloc.  Discard the
559      handle to avoid handle leak.  */
560   VALGRIND_DISCARD (VALGRIND_MAKE_NOACCESS (page, size));
561
562   return page;
563 }
564 #endif
565 #ifdef USING_MALLOC_PAGE_GROUPS
566 /* Compute the index for this page into the page group.  */
567
568 static inline size_t
569 page_group_index (allocation, page)
570      char *allocation, *page;
571 {
572   return (size_t) (page - allocation) >> G.lg_pagesize;
573 }
574
575 /* Set and clear the in_use bit for this page in the page group.  */
576
577 static inline void
578 set_page_group_in_use (group, page)
579      page_group *group;
580      char *page;
581 {
582   group->in_use |= 1 << page_group_index (group->allocation, page);
583 }
584
585 static inline void
586 clear_page_group_in_use (group, page)
587      page_group *group;
588      char *page;
589 {
590   group->in_use &= ~(1 << page_group_index (group->allocation, page));
591 }
592 #endif
593
594 /* Allocate a new page for allocating objects of size 2^ORDER,
595    and return an entry for it.  The entry is not added to the
596    appropriate page_table list.  */
597
598 static inline struct page_entry *
599 alloc_page (order)
600      unsigned order;
601 {
602   struct page_entry *entry, *p, **pp;
603   char *page;
604   size_t num_objects;
605   size_t bitmap_size;
606   size_t page_entry_size;
607   size_t entry_size;
608 #ifdef USING_MALLOC_PAGE_GROUPS
609   page_group *group;
610 #endif
611
612   num_objects = OBJECTS_PER_PAGE (order);
613   bitmap_size = BITMAP_SIZE (num_objects + 1);
614   page_entry_size = sizeof (page_entry) - sizeof (long) + bitmap_size;
615   entry_size = num_objects * OBJECT_SIZE (order);
616   if (entry_size < G.pagesize)
617     entry_size = G.pagesize;
618
619   entry = NULL;
620   page = NULL;
621
622   /* Check the list of free pages for one we can use.  */
623   for (pp = &G.free_pages, p = *pp; p; pp = &p->next, p = *pp)
624     if (p->bytes == entry_size)
625       break;
626
627   if (p != NULL)
628     {
629       /* Recycle the allocated memory from this page ...  */
630       *pp = p->next;
631       page = p->page;
632
633 #ifdef USING_MALLOC_PAGE_GROUPS
634       group = p->group;
635 #endif
636
637       /* ... and, if possible, the page entry itself.  */
638       if (p->order == order)
639         {
640           entry = p;
641           memset (entry, 0, page_entry_size);
642         }
643       else
644         free (p);
645     }
646 #ifdef USING_MMAP
647   else if (entry_size == G.pagesize)
648     {
649       /* We want just one page.  Allocate a bunch of them and put the
650          extras on the freelist.  (Can only do this optimization with
651          mmap for backing store.)  */
652       struct page_entry *e, *f = G.free_pages;
653       int i;
654
655       page = alloc_anon (NULL, G.pagesize * GGC_QUIRE_SIZE);
656
657       /* This loop counts down so that the chain will be in ascending
658          memory order.  */
659       for (i = GGC_QUIRE_SIZE - 1; i >= 1; i--)
660         {
661           e = (struct page_entry *) xcalloc (1, page_entry_size);
662           e->order = order;
663           e->bytes = G.pagesize;
664           e->page = page + (i << G.lg_pagesize);
665           e->next = f;
666           f = e;
667         }
668
669       G.free_pages = f;
670     }
671   else
672     page = alloc_anon (NULL, entry_size);
673 #endif
674 #ifdef USING_MALLOC_PAGE_GROUPS
675   else
676     {
677       /* Allocate a large block of memory and serve out the aligned
678          pages therein.  This results in much less memory wastage
679          than the traditional implementation of valloc.  */
680
681       char *allocation, *a, *enda;
682       size_t alloc_size, head_slop, tail_slop;
683       int multiple_pages = (entry_size == G.pagesize);
684
685       if (multiple_pages)
686         alloc_size = GGC_QUIRE_SIZE * G.pagesize;
687       else
688         alloc_size = entry_size + G.pagesize - 1;
689       allocation = xmalloc (alloc_size);
690
691       page = (char *) (((size_t) allocation + G.pagesize - 1) & -G.pagesize);
692       head_slop = page - allocation;
693       if (multiple_pages)
694         tail_slop = ((size_t) allocation + alloc_size) & (G.pagesize - 1);
695       else
696         tail_slop = alloc_size - entry_size - head_slop;
697       enda = allocation + alloc_size - tail_slop;
698
699       /* We allocated N pages, which are likely not aligned, leaving
700          us with N-1 usable pages.  We plan to place the page_group
701          structure somewhere in the slop.  */
702       if (head_slop >= sizeof (page_group))
703         group = (page_group *)page - 1;
704       else
705         {
706           /* We magically got an aligned allocation.  Too bad, we have
707              to waste a page anyway.  */
708           if (tail_slop == 0)
709             {
710               enda -= G.pagesize;
711               tail_slop += G.pagesize;
712             }
713           if (tail_slop < sizeof (page_group))
714             abort ();
715           group = (page_group *)enda;
716           tail_slop -= sizeof (page_group);
717         }
718
719       /* Remember that we allocated this memory.  */
720       group->next = G.page_groups;
721       group->allocation = allocation;
722       group->alloc_size = alloc_size;
723       group->in_use = 0;
724       G.page_groups = group;
725       G.bytes_mapped += alloc_size;
726
727       /* If we allocated multiple pages, put the rest on the free list.  */
728       if (multiple_pages)
729         {
730           struct page_entry *e, *f = G.free_pages;
731           for (a = enda - G.pagesize; a != page; a -= G.pagesize)
732             {
733               e = (struct page_entry *) xcalloc (1, page_entry_size);
734               e->order = order;
735               e->bytes = G.pagesize;
736               e->page = a;
737               e->group = group;
738               e->next = f;
739               f = e;
740             }
741           G.free_pages = f;
742         }
743     }
744 #endif
745
746   if (entry == NULL)
747     entry = (struct page_entry *) xcalloc (1, page_entry_size);
748
749   entry->bytes = entry_size;
750   entry->page = page;
751   entry->context_depth = G.context_depth;
752   entry->order = order;
753   entry->num_free_objects = num_objects;
754   entry->next_bit_hint = 1;
755
756   G.context_depth_allocations |= (unsigned long)1 << G.context_depth;
757
758 #ifdef USING_MALLOC_PAGE_GROUPS
759   entry->group = group;
760   set_page_group_in_use (group, page);
761 #endif
762
763   /* Set the one-past-the-end in-use bit.  This acts as a sentry as we
764      increment the hint.  */
765   entry->in_use_p[num_objects / HOST_BITS_PER_LONG]
766     = (unsigned long) 1 << (num_objects % HOST_BITS_PER_LONG);
767
768   set_page_table_entry (page, entry);
769
770   if (GGC_DEBUG_LEVEL >= 2)
771     fprintf (G.debug_file,
772              "Allocating page at %p, object size=%lu, data %p-%p\n",
773              (PTR) entry, (unsigned long) OBJECT_SIZE (order), page,
774              page + entry_size - 1);
775
776   return entry;
777 }
778
779 /* For a page that is no longer needed, put it on the free page list.  */
780
781 static inline void
782 free_page (entry)
783      page_entry *entry;
784 {
785   if (GGC_DEBUG_LEVEL >= 2)
786     fprintf (G.debug_file,
787              "Deallocating page at %p, data %p-%p\n", (PTR) entry,
788              entry->page, entry->page + entry->bytes - 1);
789
790   /* Mark the page as inaccessible.  Discard the handle to avoid handle
791      leak.  */
792   VALGRIND_DISCARD (VALGRIND_MAKE_NOACCESS (entry->page, entry->bytes));
793
794   set_page_table_entry (entry->page, NULL);
795
796 #ifdef USING_MALLOC_PAGE_GROUPS
797   clear_page_group_in_use (entry->group, entry->page);
798 #endif
799
800   entry->next = G.free_pages;
801   G.free_pages = entry;
802 }
803
804 /* Release the free page cache to the system.  */
805
806 static void
807 release_pages ()
808 {
809 #ifdef USING_MMAP
810   page_entry *p, *next;
811   char *start;
812   size_t len;
813
814   /* Gather up adjacent pages so they are unmapped together.  */
815   p = G.free_pages;
816
817   while (p)
818     {
819       start = p->page;
820       next = p->next;
821       len = p->bytes;
822       free (p);
823       p = next;
824
825       while (p && p->page == start + len)
826         {
827           next = p->next;
828           len += p->bytes;
829           free (p);
830           p = next;
831         }
832
833       munmap (start, len);
834       G.bytes_mapped -= len;
835     }
836
837   G.free_pages = NULL;
838 #endif
839 #ifdef USING_MALLOC_PAGE_GROUPS
840   page_entry **pp, *p;
841   page_group **gp, *g;
842
843   /* Remove all pages from free page groups from the list.  */
844   pp = &G.free_pages;
845   while ((p = *pp) != NULL)
846     if (p->group->in_use == 0)
847       {
848         *pp = p->next;
849         free (p);
850       }
851     else
852       pp = &p->next;
853
854   /* Remove all free page groups, and release the storage.  */
855   gp = &G.page_groups;
856   while ((g = *gp) != NULL)
857     if (g->in_use == 0)
858       {
859         *gp = g->next;
860         G.bytes_mapped -= g->alloc_size;
861         free (g->allocation);
862       }
863     else
864       gp = &g->next;
865 #endif
866 }
867
868 /* This table provides a fast way to determine ceil(log_2(size)) for
869    allocation requests.  The minimum allocation size is eight bytes.  */
870
871 static unsigned char size_lookup[257] =
872 {
873   3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4,
874   4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
875   5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
876   6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
877   6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
878   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
879   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
880   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
881   7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
882   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
883   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
884   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
885   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
886   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
887   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
888   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
889   8
890 };
891
892 /* Allocate a chunk of memory of SIZE bytes.  If ZERO is nonzero, the
893    memory is zeroed; otherwise, its contents are undefined.  */
894
895 void *
896 ggc_alloc (size)
897      size_t size;
898 {
899   unsigned order, word, bit, object_offset;
900   struct page_entry *entry;
901   void *result;
902
903   if (size <= 256)
904     order = size_lookup[size];
905   else
906     {
907       order = 9;
908       while (size > OBJECT_SIZE (order))
909         order++;
910     }
911
912   /* If there are non-full pages for this size allocation, they are at
913      the head of the list.  */
914   entry = G.pages[order];
915
916   /* If there is no page for this object size, or all pages in this
917      context are full, allocate a new page.  */
918   if (entry == NULL || entry->num_free_objects == 0)
919     {
920       struct page_entry *new_entry;
921       new_entry = alloc_page (order);
922
923       /* If this is the only entry, it's also the tail.  */
924       if (entry == NULL)
925         G.page_tails[order] = new_entry;
926
927       /* Put new pages at the head of the page list.  */
928       new_entry->next = entry;
929       entry = new_entry;
930       G.pages[order] = new_entry;
931
932       /* For a new page, we know the word and bit positions (in the
933          in_use bitmap) of the first available object -- they're zero.  */
934       new_entry->next_bit_hint = 1;
935       word = 0;
936       bit = 0;
937       object_offset = 0;
938     }
939   else
940     {
941       /* First try to use the hint left from the previous allocation
942          to locate a clear bit in the in-use bitmap.  We've made sure
943          that the one-past-the-end bit is always set, so if the hint
944          has run over, this test will fail.  */
945       unsigned hint = entry->next_bit_hint;
946       word = hint / HOST_BITS_PER_LONG;
947       bit = hint % HOST_BITS_PER_LONG;
948
949       /* If the hint didn't work, scan the bitmap from the beginning.  */
950       if ((entry->in_use_p[word] >> bit) & 1)
951         {
952           word = bit = 0;
953           while (~entry->in_use_p[word] == 0)
954             ++word;
955           while ((entry->in_use_p[word] >> bit) & 1)
956             ++bit;
957           hint = word * HOST_BITS_PER_LONG + bit;
958         }
959
960       /* Next time, try the next bit.  */
961       entry->next_bit_hint = hint + 1;
962
963       object_offset = hint * OBJECT_SIZE (order);
964     }
965
966   /* Set the in-use bit.  */
967   entry->in_use_p[word] |= ((unsigned long) 1 << bit);
968
969   /* Keep a running total of the number of free objects.  If this page
970      fills up, we may have to move it to the end of the list if the
971      next page isn't full.  If the next page is full, all subsequent
972      pages are full, so there's no need to move it.  */
973   if (--entry->num_free_objects == 0
974       && entry->next != NULL
975       && entry->next->num_free_objects > 0)
976     {
977       G.pages[order] = entry->next;
978       entry->next = NULL;
979       G.page_tails[order]->next = entry;
980       G.page_tails[order] = entry;
981     }
982
983   /* Calculate the object's address.  */
984   result = entry->page + object_offset;
985
986 #ifdef ENABLE_GC_CHECKING
987   /* Keep poisoning-by-writing-0xaf the object, in an attempt to keep the
988      exact same semantics in presence of memory bugs, regardless of
989      ENABLE_VALGRIND_CHECKING.  We override this request below.  Drop the
990      handle to avoid handle leak.  */
991   VALGRIND_DISCARD (VALGRIND_MAKE_WRITABLE (result, OBJECT_SIZE (order)));
992
993   /* `Poison' the entire allocated object, including any padding at
994      the end.  */
995   memset (result, 0xaf, OBJECT_SIZE (order));
996
997   /* Make the bytes after the end of the object unaccessible.  Discard the
998      handle to avoid handle leak.  */
999   VALGRIND_DISCARD (VALGRIND_MAKE_NOACCESS ((char *) result + size,
1000                                             OBJECT_SIZE (order) - size));
1001 #endif
1002
1003   /* Tell Valgrind that the memory is there, but its content isn't
1004      defined.  The bytes at the end of the object are still marked
1005      unaccessible.  */
1006   VALGRIND_DISCARD (VALGRIND_MAKE_WRITABLE (result, size));
1007
1008   /* Keep track of how many bytes are being allocated.  This
1009      information is used in deciding when to collect.  */
1010   G.allocated += OBJECT_SIZE (order);
1011
1012   if (GGC_DEBUG_LEVEL >= 3)
1013     fprintf (G.debug_file,
1014              "Allocating object, requested size=%lu, actual=%lu at %p on %p\n",
1015              (unsigned long) size, (unsigned long) OBJECT_SIZE (order), result,
1016              (PTR) entry);
1017
1018   return result;
1019 }
1020
1021 /* If P is not marked, marks it and return false.  Otherwise return true.
1022    P must have been allocated by the GC allocator; it mustn't point to
1023    static objects, stack variables, or memory allocated with malloc.  */
1024
1025 int
1026 ggc_set_mark (p)
1027      const void *p;
1028 {
1029   page_entry *entry;
1030   unsigned bit, word;
1031   unsigned long mask;
1032
1033   /* Look up the page on which the object is alloced.  If the object
1034      wasn't allocated by the collector, we'll probably die.  */
1035   entry = lookup_page_table_entry (p);
1036 #ifdef ENABLE_CHECKING
1037   if (entry == NULL)
1038     abort ();
1039 #endif
1040
1041   /* Calculate the index of the object on the page; this is its bit
1042      position in the in_use_p bitmap.  */
1043   bit = OFFSET_TO_BIT (((const char *) p) - entry->page, entry->order);
1044   word = bit / HOST_BITS_PER_LONG;
1045   mask = (unsigned long) 1 << (bit % HOST_BITS_PER_LONG);
1046
1047   /* If the bit was previously set, skip it.  */
1048   if (entry->in_use_p[word] & mask)
1049     return 1;
1050
1051   /* Otherwise set it, and decrement the free object count.  */
1052   entry->in_use_p[word] |= mask;
1053   entry->num_free_objects -= 1;
1054
1055   if (GGC_DEBUG_LEVEL >= 4)
1056     fprintf (G.debug_file, "Marking %p\n", p);
1057
1058   return 0;
1059 }
1060
1061 /* Return 1 if P has been marked, zero otherwise.
1062    P must have been allocated by the GC allocator; it mustn't point to
1063    static objects, stack variables, or memory allocated with malloc.  */
1064
1065 int
1066 ggc_marked_p (p)
1067      const void *p;
1068 {
1069   page_entry *entry;
1070   unsigned bit, word;
1071   unsigned long mask;
1072
1073   /* Look up the page on which the object is alloced.  If the object
1074      wasn't allocated by the collector, we'll probably die.  */
1075   entry = lookup_page_table_entry (p);
1076 #ifdef ENABLE_CHECKING
1077   if (entry == NULL)
1078     abort ();
1079 #endif
1080
1081   /* Calculate the index of the object on the page; this is its bit
1082      position in the in_use_p bitmap.  */
1083   bit = OFFSET_TO_BIT (((const char *) p) - entry->page, entry->order);
1084   word = bit / HOST_BITS_PER_LONG;
1085   mask = (unsigned long) 1 << (bit % HOST_BITS_PER_LONG);
1086
1087   return (entry->in_use_p[word] & mask) != 0;
1088 }
1089
1090 /* Return the size of the gc-able object P.  */
1091
1092 size_t
1093 ggc_get_size (p)
1094      const void *p;
1095 {
1096   page_entry *pe = lookup_page_table_entry (p);
1097   return OBJECT_SIZE (pe->order);
1098 }
1099 \f
1100 /* Subroutine of init_ggc which computes the pair of numbers used to
1101    perform division by OBJECT_SIZE (order) and fills in inverse_table[].
1102
1103    This algorithm is taken from Granlund and Montgomery's paper
1104    "Division by Invariant Integers using Multiplication"
1105    (Proc. SIGPLAN PLDI, 1994), section 9 (Exact division by
1106    constants).  */
1107
1108 static void
1109 compute_inverse (order)
1110      unsigned order;
1111 {
1112   unsigned size, inv, e;
1113
1114   /* There can be only one object per "page" in a bucket for sizes
1115      larger than half a machine page; it will always have offset zero.  */
1116   if (OBJECT_SIZE (order) > G.pagesize/2)
1117     {
1118       if (OBJECTS_PER_PAGE (order) != 1)
1119         abort ();
1120
1121       DIV_MULT (order) = 1;
1122       DIV_SHIFT (order) = 0;
1123       return;
1124     }
1125
1126   size = OBJECT_SIZE (order);
1127   e = 0;
1128   while (size % 2 == 0)
1129     {
1130       e++;
1131       size >>= 1;
1132     }
1133
1134   inv = size;
1135   while (inv * size != 1)
1136     inv = inv * (2 - inv*size);
1137
1138   DIV_MULT (order) = inv;
1139   DIV_SHIFT (order) = e;
1140 }
1141
1142 /* Initialize the ggc-mmap allocator.  */
1143 void
1144 init_ggc ()
1145 {
1146   unsigned order;
1147
1148   G.pagesize = getpagesize();
1149   G.lg_pagesize = exact_log2 (G.pagesize);
1150
1151 #ifdef HAVE_MMAP_DEV_ZERO
1152   G.dev_zero_fd = open ("/dev/zero", O_RDONLY);
1153   if (G.dev_zero_fd == -1)
1154     abort ();
1155 #endif
1156
1157 #if 0
1158   G.debug_file = fopen ("ggc-mmap.debug", "w");
1159 #else
1160   G.debug_file = stdout;
1161 #endif
1162
1163 #ifdef USING_MMAP
1164   /* StunOS has an amazing off-by-one error for the first mmap allocation
1165      after fiddling with RLIMIT_STACK.  The result, as hard as it is to
1166      believe, is an unaligned page allocation, which would cause us to
1167      hork badly if we tried to use it.  */
1168   {
1169     char *p = alloc_anon (NULL, G.pagesize);
1170     struct page_entry *e;
1171     if ((size_t)p & (G.pagesize - 1))
1172       {
1173         /* How losing.  Discard this one and try another.  If we still
1174            can't get something useful, give up.  */
1175
1176         p = alloc_anon (NULL, G.pagesize);
1177         if ((size_t)p & (G.pagesize - 1))
1178           abort ();
1179       }
1180
1181     /* We have a good page, might as well hold onto it...  */
1182     e = (struct page_entry *) xcalloc (1, sizeof (struct page_entry));
1183     e->bytes = G.pagesize;
1184     e->page = p;
1185     e->next = G.free_pages;
1186     G.free_pages = e;
1187   }
1188 #endif
1189
1190   /* Initialize the object size table.  */
1191   for (order = 0; order < HOST_BITS_PER_PTR; ++order)
1192     object_size_table[order] = (size_t) 1 << order;
1193   for (order = HOST_BITS_PER_PTR; order < NUM_ORDERS; ++order)
1194     {
1195       size_t s = extra_order_size_table[order - HOST_BITS_PER_PTR];
1196
1197       /* If S is not a multiple of the MAX_ALIGNMENT, then round it up
1198          so that we're sure of getting aligned memory.  */
1199       s = ROUND_UP (s, MAX_ALIGNMENT);
1200       object_size_table[order] = s;
1201     }
1202
1203   /* Initialize the objects-per-page and inverse tables.  */
1204   for (order = 0; order < NUM_ORDERS; ++order)
1205     {
1206       objects_per_page_table[order] = G.pagesize / OBJECT_SIZE (order);
1207       if (objects_per_page_table[order] == 0)
1208         objects_per_page_table[order] = 1;
1209       compute_inverse (order);
1210     }
1211
1212   /* Reset the size_lookup array to put appropriately sized objects in
1213      the special orders.  All objects bigger than the previous power
1214      of two, but no greater than the special size, should go in the
1215      new order.  */
1216   for (order = HOST_BITS_PER_PTR; order < NUM_ORDERS; ++order)
1217     {
1218       int o;
1219       int i;
1220
1221       o = size_lookup[OBJECT_SIZE (order)];
1222       for (i = OBJECT_SIZE (order); size_lookup [i] == o; --i)
1223         size_lookup[i] = order;
1224     }
1225 }
1226
1227 /* Increment the `GC context'.  Objects allocated in an outer context
1228    are never freed, eliminating the need to register their roots.  */
1229
1230 void
1231 ggc_push_context ()
1232 {
1233   ++G.context_depth;
1234
1235   /* Die on wrap.  */
1236   if (G.context_depth >= HOST_BITS_PER_LONG)
1237     abort ();
1238 }
1239
1240 /* Merge the SAVE_IN_USE_P and IN_USE_P arrays in P so that IN_USE_P
1241    reflects reality.  Recalculate NUM_FREE_OBJECTS as well.  */
1242
1243 static void
1244 ggc_recalculate_in_use_p (p)
1245      page_entry *p;
1246 {
1247   unsigned int i;
1248   size_t num_objects;
1249
1250   /* Because the past-the-end bit in in_use_p is always set, we
1251      pretend there is one additional object.  */
1252   num_objects = OBJECTS_IN_PAGE (p) + 1;
1253
1254   /* Reset the free object count.  */
1255   p->num_free_objects = num_objects;
1256
1257   /* Combine the IN_USE_P and SAVE_IN_USE_P arrays.  */
1258   for (i = 0;
1259        i < CEIL (BITMAP_SIZE (num_objects),
1260                  sizeof (*p->in_use_p));
1261        ++i)
1262     {
1263       unsigned long j;
1264
1265       /* Something is in use if it is marked, or if it was in use in a
1266          context further down the context stack.  */
1267       p->in_use_p[i] |= p->save_in_use_p[i];
1268
1269       /* Decrement the free object count for every object allocated.  */
1270       for (j = p->in_use_p[i]; j; j >>= 1)
1271         p->num_free_objects -= (j & 1);
1272     }
1273
1274   if (p->num_free_objects >= num_objects)
1275     abort ();
1276 }
1277
1278 /* Decrement the `GC context'.  All objects allocated since the
1279    previous ggc_push_context are migrated to the outer context.  */
1280
1281 void
1282 ggc_pop_context ()
1283 {
1284   unsigned long omask;
1285   unsigned order, depth;
1286
1287   depth = --G.context_depth;
1288   omask = (unsigned long)1 << (depth + 1);
1289
1290   if (!((G.context_depth_allocations | G.context_depth_collections) & omask))
1291     return;
1292
1293   G.context_depth_allocations |= (G.context_depth_allocations & omask) >> 1;
1294   G.context_depth_allocations &= omask - 1;
1295   G.context_depth_collections &= omask - 1;
1296
1297   /* Any remaining pages in the popped context are lowered to the new
1298      current context; i.e. objects allocated in the popped context and
1299      left over are imported into the previous context.  */
1300   for (order = 2; order < NUM_ORDERS; order++)
1301     {
1302       page_entry *p;
1303
1304       for (p = G.pages[order]; p != NULL; p = p->next)
1305         {
1306           if (p->context_depth > depth)
1307             p->context_depth = depth;
1308
1309           /* If this page is now in the topmost context, and we'd
1310              saved its allocation state, restore it.  */
1311           else if (p->context_depth == depth && p->save_in_use_p)
1312             {
1313               ggc_recalculate_in_use_p (p);
1314               free (p->save_in_use_p);
1315               p->save_in_use_p = 0;
1316             }
1317         }
1318     }
1319 }
1320 \f
1321 /* Unmark all objects.  */
1322
1323 static inline void
1324 clear_marks ()
1325 {
1326   unsigned order;
1327
1328   for (order = 2; order < NUM_ORDERS; order++)
1329     {
1330       page_entry *p;
1331
1332       for (p = G.pages[order]; p != NULL; p = p->next)
1333         {
1334           size_t num_objects = OBJECTS_IN_PAGE (p);
1335           size_t bitmap_size = BITMAP_SIZE (num_objects + 1);
1336
1337 #ifdef ENABLE_CHECKING
1338           /* The data should be page-aligned.  */
1339           if ((size_t) p->page & (G.pagesize - 1))
1340             abort ();
1341 #endif
1342
1343           /* Pages that aren't in the topmost context are not collected;
1344              nevertheless, we need their in-use bit vectors to store GC
1345              marks.  So, back them up first.  */
1346           if (p->context_depth < G.context_depth)
1347             {
1348               if (! p->save_in_use_p)
1349                 p->save_in_use_p = xmalloc (bitmap_size);
1350               memcpy (p->save_in_use_p, p->in_use_p, bitmap_size);
1351             }
1352
1353           /* Reset reset the number of free objects and clear the
1354              in-use bits.  These will be adjusted by mark_obj.  */
1355           p->num_free_objects = num_objects;
1356           memset (p->in_use_p, 0, bitmap_size);
1357
1358           /* Make sure the one-past-the-end bit is always set.  */
1359           p->in_use_p[num_objects / HOST_BITS_PER_LONG]
1360             = ((unsigned long) 1 << (num_objects % HOST_BITS_PER_LONG));
1361         }
1362     }
1363 }
1364
1365 /* Free all empty pages.  Partially empty pages need no attention
1366    because the `mark' bit doubles as an `unused' bit.  */
1367
1368 static inline void
1369 sweep_pages ()
1370 {
1371   unsigned order;
1372
1373   for (order = 2; order < NUM_ORDERS; order++)
1374     {
1375       /* The last page-entry to consider, regardless of entries
1376          placed at the end of the list.  */
1377       page_entry * const last = G.page_tails[order];
1378
1379       size_t num_objects;
1380       size_t live_objects;
1381       page_entry *p, *previous;
1382       int done;
1383
1384       p = G.pages[order];
1385       if (p == NULL)
1386         continue;
1387
1388       previous = NULL;
1389       do
1390         {
1391           page_entry *next = p->next;
1392
1393           /* Loop until all entries have been examined.  */
1394           done = (p == last);
1395           
1396           num_objects = OBJECTS_IN_PAGE (p);
1397
1398           /* Add all live objects on this page to the count of
1399              allocated memory.  */
1400           live_objects = num_objects - p->num_free_objects;
1401
1402           G.allocated += OBJECT_SIZE (order) * live_objects;
1403
1404           /* Only objects on pages in the topmost context should get
1405              collected.  */
1406           if (p->context_depth < G.context_depth)
1407             ;
1408
1409           /* Remove the page if it's empty.  */
1410           else if (live_objects == 0)
1411             {
1412               if (! previous)
1413                 G.pages[order] = next;
1414               else
1415                 previous->next = next;
1416
1417               /* Are we removing the last element?  */
1418               if (p == G.page_tails[order])
1419                 G.page_tails[order] = previous;
1420               free_page (p);
1421               p = previous;
1422             }
1423
1424           /* If the page is full, move it to the end.  */
1425           else if (p->num_free_objects == 0)
1426             {
1427               /* Don't move it if it's already at the end.  */
1428               if (p != G.page_tails[order])
1429                 {
1430                   /* Move p to the end of the list.  */
1431                   p->next = NULL;
1432                   G.page_tails[order]->next = p;
1433
1434                   /* Update the tail pointer...  */
1435                   G.page_tails[order] = p;
1436
1437                   /* ... and the head pointer, if necessary.  */
1438                   if (! previous)
1439                     G.pages[order] = next;
1440                   else
1441                     previous->next = next;
1442                   p = previous;
1443                 }
1444             }
1445
1446           /* If we've fallen through to here, it's a page in the
1447              topmost context that is neither full nor empty.  Such a
1448              page must precede pages at lesser context depth in the
1449              list, so move it to the head.  */
1450           else if (p != G.pages[order])
1451             {
1452               previous->next = p->next;
1453               p->next = G.pages[order];
1454               G.pages[order] = p;
1455               /* Are we moving the last element?  */
1456               if (G.page_tails[order] == p)
1457                 G.page_tails[order] = previous;
1458               p = previous;
1459             }
1460
1461           previous = p;
1462           p = next;
1463         }
1464       while (! done);
1465
1466       /* Now, restore the in_use_p vectors for any pages from contexts
1467          other than the current one.  */
1468       for (p = G.pages[order]; p; p = p->next)
1469         if (p->context_depth != G.context_depth)
1470           ggc_recalculate_in_use_p (p);
1471     }
1472 }
1473
1474 #ifdef ENABLE_GC_CHECKING
1475 /* Clobber all free objects.  */
1476
1477 static inline void
1478 poison_pages ()
1479 {
1480   unsigned order;
1481
1482   for (order = 2; order < NUM_ORDERS; order++)
1483     {
1484       size_t size = OBJECT_SIZE (order);
1485       page_entry *p;
1486
1487       for (p = G.pages[order]; p != NULL; p = p->next)
1488         {
1489           size_t num_objects;
1490           size_t i;
1491
1492           if (p->context_depth != G.context_depth)
1493             /* Since we don't do any collection for pages in pushed
1494                contexts, there's no need to do any poisoning.  And
1495                besides, the IN_USE_P array isn't valid until we pop
1496                contexts.  */
1497             continue;
1498
1499           num_objects = OBJECTS_IN_PAGE (p);
1500           for (i = 0; i < num_objects; i++)
1501             {
1502               size_t word, bit;
1503               word = i / HOST_BITS_PER_LONG;
1504               bit = i % HOST_BITS_PER_LONG;
1505               if (((p->in_use_p[word] >> bit) & 1) == 0)
1506                 {
1507                   char *object = p->page + i * size;
1508
1509                   /* Keep poison-by-write when we expect to use Valgrind,
1510                      so the exact same memory semantics is kept, in case
1511                      there are memory errors.  We override this request
1512                      below.  */
1513                   VALGRIND_DISCARD (VALGRIND_MAKE_WRITABLE (object, size));
1514                   memset (object, 0xa5, size);
1515
1516                   /* Drop the handle to avoid handle leak.  */
1517                   VALGRIND_DISCARD (VALGRIND_MAKE_NOACCESS (object, size));
1518                 }
1519             }
1520         }
1521     }
1522 }
1523 #endif
1524
1525 /* Top level mark-and-sweep routine.  */
1526
1527 void
1528 ggc_collect ()
1529 {
1530   /* Avoid frequent unnecessary work by skipping collection if the
1531      total allocations haven't expanded much since the last
1532      collection.  */
1533   float allocated_last_gc =
1534     MAX (G.allocated_last_gc, (size_t)PARAM_VALUE (GGC_MIN_HEAPSIZE) * 1024);
1535
1536   float min_expand = allocated_last_gc * PARAM_VALUE (GGC_MIN_EXPAND) / 100;
1537
1538   if (G.allocated < allocated_last_gc + min_expand)
1539     return;
1540
1541   timevar_push (TV_GC);
1542   if (!quiet_flag)
1543     fprintf (stderr, " {GC %luk -> ", (unsigned long) G.allocated / 1024);
1544
1545   /* Zero the total allocated bytes.  This will be recalculated in the
1546      sweep phase.  */
1547   G.allocated = 0;
1548
1549   /* Release the pages we freed the last time we collected, but didn't
1550      reuse in the interim.  */
1551   release_pages ();
1552
1553   /* Indicate that we've seen collections at this context depth.  */
1554   G.context_depth_collections = ((unsigned long)1 << (G.context_depth + 1)) - 1;
1555
1556   clear_marks ();
1557   ggc_mark_roots ();
1558
1559 #ifdef ENABLE_GC_CHECKING
1560   poison_pages ();
1561 #endif
1562
1563   sweep_pages ();
1564
1565   G.allocated_last_gc = G.allocated;
1566
1567   timevar_pop (TV_GC);
1568
1569   if (!quiet_flag)
1570     fprintf (stderr, "%luk}", (unsigned long) G.allocated / 1024);
1571 }
1572
1573 /* Print allocation statistics.  */
1574 #define SCALE(x) ((unsigned long) ((x) < 1024*10 \
1575                   ? (x) \
1576                   : ((x) < 1024*1024*10 \
1577                      ? (x) / 1024 \
1578                      : (x) / (1024*1024))))
1579 #define LABEL(x) ((x) < 1024*10 ? ' ' : ((x) < 1024*1024*10 ? 'k' : 'M'))
1580
1581 void
1582 ggc_print_statistics ()
1583 {
1584   struct ggc_statistics stats;
1585   unsigned int i;
1586   size_t total_overhead = 0;
1587
1588   /* Clear the statistics.  */
1589   memset (&stats, 0, sizeof (stats));
1590
1591   /* Make sure collection will really occur.  */
1592   G.allocated_last_gc = 0;
1593
1594   /* Collect and print the statistics common across collectors.  */
1595   ggc_print_common_statistics (stderr, &stats);
1596
1597   /* Release free pages so that we will not count the bytes allocated
1598      there as part of the total allocated memory.  */
1599   release_pages ();
1600
1601   /* Collect some information about the various sizes of
1602      allocation.  */
1603   fprintf (stderr, "\n%-5s %10s  %10s  %10s\n",
1604            "Size", "Allocated", "Used", "Overhead");
1605   for (i = 0; i < NUM_ORDERS; ++i)
1606     {
1607       page_entry *p;
1608       size_t allocated;
1609       size_t in_use;
1610       size_t overhead;
1611
1612       /* Skip empty entries.  */
1613       if (!G.pages[i])
1614         continue;
1615
1616       overhead = allocated = in_use = 0;
1617
1618       /* Figure out the total number of bytes allocated for objects of
1619          this size, and how many of them are actually in use.  Also figure
1620          out how much memory the page table is using.  */
1621       for (p = G.pages[i]; p; p = p->next)
1622         {
1623           allocated += p->bytes;
1624           in_use += 
1625             (OBJECTS_IN_PAGE (p) - p->num_free_objects) * OBJECT_SIZE (i);
1626
1627           overhead += (sizeof (page_entry) - sizeof (long)
1628                        + BITMAP_SIZE (OBJECTS_IN_PAGE (p) + 1));
1629         }
1630       fprintf (stderr, "%-5lu %10lu%c %10lu%c %10lu%c\n",
1631                (unsigned long) OBJECT_SIZE (i),
1632                SCALE (allocated), LABEL (allocated),
1633                SCALE (in_use), LABEL (in_use),
1634                SCALE (overhead), LABEL (overhead));
1635       total_overhead += overhead;
1636     }
1637   fprintf (stderr, "%-5s %10lu%c %10lu%c %10lu%c\n", "Total",
1638            SCALE (G.bytes_mapped), LABEL (G.bytes_mapped),
1639            SCALE (G.allocated), LABEL(G.allocated),
1640            SCALE (total_overhead), LABEL (total_overhead));
1641 }
1642 \f
1643 struct ggc_pch_data
1644 {
1645   struct ggc_pch_ondisk 
1646   {
1647     unsigned totals[NUM_ORDERS];
1648   } d;
1649   size_t base[NUM_ORDERS];
1650   size_t written[NUM_ORDERS];
1651 };
1652
1653 struct ggc_pch_data *
1654 init_ggc_pch ()
1655 {
1656   return xcalloc (sizeof (struct ggc_pch_data), 1);
1657 }
1658
1659 void 
1660 ggc_pch_count_object (d, x, size)
1661      struct ggc_pch_data *d;
1662      void *x ATTRIBUTE_UNUSED;
1663      size_t size;
1664 {
1665   unsigned order;
1666
1667   if (size <= 256)
1668     order = size_lookup[size];
1669   else
1670     {
1671       order = 9;
1672       while (size > OBJECT_SIZE (order))
1673         order++;
1674     }
1675   
1676   d->d.totals[order]++;
1677 }
1678      
1679 size_t
1680 ggc_pch_total_size (d)
1681      struct ggc_pch_data *d;
1682 {
1683   size_t a = 0;
1684   unsigned i;
1685
1686   for (i = 0; i < NUM_ORDERS; i++)
1687     a += ROUND_UP (d->d.totals[i] * OBJECT_SIZE (i), G.pagesize);
1688   return a;
1689 }
1690
1691 void
1692 ggc_pch_this_base (d, base)
1693      struct ggc_pch_data *d;
1694      void *base;
1695 {
1696   size_t a = (size_t) base;
1697   unsigned i;
1698   
1699   for (i = 0; i < NUM_ORDERS; i++)
1700     {
1701       d->base[i] = a;
1702       a += ROUND_UP (d->d.totals[i] * OBJECT_SIZE (i), G.pagesize);
1703     }
1704 }
1705
1706
1707 char *
1708 ggc_pch_alloc_object (d, x, size)
1709      struct ggc_pch_data *d;
1710      void *x ATTRIBUTE_UNUSED;
1711      size_t size;
1712 {
1713   unsigned order;
1714   char *result;
1715   
1716   if (size <= 256)
1717     order = size_lookup[size];
1718   else
1719     {
1720       order = 9;
1721       while (size > OBJECT_SIZE (order))
1722         order++;
1723     }
1724
1725   result = (char *) d->base[order];
1726   d->base[order] += OBJECT_SIZE (order);
1727   return result;
1728 }
1729
1730 void 
1731 ggc_pch_prepare_write (d, f)
1732      struct ggc_pch_data * d ATTRIBUTE_UNUSED;
1733      FILE * f ATTRIBUTE_UNUSED;
1734 {
1735   /* Nothing to do.  */
1736 }
1737
1738 void
1739 ggc_pch_write_object (d, f, x, newx, size)
1740      struct ggc_pch_data * d ATTRIBUTE_UNUSED;
1741      FILE *f;
1742      void *x;
1743      void *newx ATTRIBUTE_UNUSED;
1744      size_t size;
1745 {
1746   unsigned order;
1747
1748   if (size <= 256)
1749     order = size_lookup[size];
1750   else
1751     {
1752       order = 9;
1753       while (size > OBJECT_SIZE (order))
1754         order++;
1755     }
1756   
1757   if (fwrite (x, size, 1, f) != 1)
1758     fatal_io_error ("can't write PCH file");
1759
1760   /* In the current implementation, SIZE is always equal to
1761      OBJECT_SIZE (order) and so the fseek is never executed.  */
1762   if (size != OBJECT_SIZE (order)
1763       && fseek (f, OBJECT_SIZE (order) - size, SEEK_CUR) != 0)
1764     fatal_io_error ("can't write PCH file");
1765
1766   d->written[order]++;
1767   if (d->written[order] == d->d.totals[order]
1768       && fseek (f, ROUND_UP_VALUE (d->d.totals[order] * OBJECT_SIZE (order),
1769                                    G.pagesize),
1770                 SEEK_CUR) != 0)
1771     fatal_io_error ("can't write PCH file");
1772 }
1773
1774 void
1775 ggc_pch_finish (d, f)
1776      struct ggc_pch_data * d;
1777      FILE *f;
1778 {
1779   if (fwrite (&d->d, sizeof (d->d), 1, f) != 1)
1780     fatal_io_error ("can't write PCH file");
1781   free (d);
1782 }
1783
1784 void
1785 ggc_pch_read (f, addr)
1786      FILE *f;
1787      void *addr;
1788 {
1789   struct ggc_pch_ondisk d;
1790   unsigned i;
1791   char *offs = addr;
1792   
1793   /* We've just read in a PCH file.  So, every object that used to be allocated
1794      is now free.  */
1795   clear_marks ();
1796 #ifdef GGC_POISON
1797   poison_pages ();
1798 #endif
1799
1800   /* No object read from a PCH file should ever be freed.  So, set the
1801      context depth to 1, and set the depth of all the currently-allocated
1802      pages to be 1 too.  PCH pages will have depth 0.  */
1803   if (G.context_depth != 0)
1804     abort ();
1805   G.context_depth = 1;
1806   for (i = 0; i < NUM_ORDERS; i++)
1807     {
1808       page_entry *p;
1809       for (p = G.pages[i]; p != NULL; p = p->next)
1810         p->context_depth = G.context_depth;
1811     }
1812
1813   /* Allocate the appropriate page-table entries for the pages read from
1814      the PCH file.  */
1815   if (fread (&d, sizeof (d), 1, f) != 1)
1816     fatal_io_error ("can't read PCH file");
1817   
1818   for (i = 0; i < NUM_ORDERS; i++)
1819     {
1820       struct page_entry *entry;
1821       char *pte;
1822       size_t bytes;
1823       size_t num_objs;
1824       size_t j;
1825       
1826       if (d.totals[i] == 0)
1827         continue;
1828       
1829       bytes = ROUND_UP (d.totals[i] * OBJECT_SIZE (i), G.pagesize);
1830       num_objs = bytes / OBJECT_SIZE (i);
1831       entry = xcalloc (1, (sizeof (struct page_entry) 
1832                            - sizeof (long)
1833                            + BITMAP_SIZE (num_objs + 1)));
1834       entry->bytes = bytes;
1835       entry->page = offs;
1836       entry->context_depth = 0;
1837       offs += bytes;
1838       entry->num_free_objects = 0;
1839       entry->order = i;
1840
1841       for (j = 0; 
1842            j + HOST_BITS_PER_LONG <= num_objs + 1;
1843            j += HOST_BITS_PER_LONG)
1844         entry->in_use_p[j / HOST_BITS_PER_LONG] = -1;
1845       for (; j < num_objs + 1; j++)
1846         entry->in_use_p[j / HOST_BITS_PER_LONG] 
1847           |= 1L << (j % HOST_BITS_PER_LONG);
1848
1849       for (pte = entry->page; 
1850            pte < entry->page + entry->bytes; 
1851            pte += G.pagesize)
1852         set_page_table_entry (pte, entry);
1853
1854       if (G.page_tails[i] != NULL)
1855         G.page_tails[i]->next = entry;
1856       else
1857         G.pages[i] = entry;
1858       G.page_tails[i] = entry;
1859     }
1860
1861   /* Update the statistics.  */
1862   G.allocated = G.allocated_last_gc = offs - (char *)addr;
1863 }