OSDN Git Service

2006-09-08 Benjamin Kosnik <bkoz@redhat.com>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / include / ext / bitmap_allocator.h
1 // Bitmap Allocator. -*- C++ -*-
2
3 // Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library.  This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 2, or (at your option)
9 // any later version.
10
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15
16 // You should have received a copy of the GNU General Public License along
17 // with this library; see the file COPYING.  If not, write to the Free
18 // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 // USA.
20
21 // As a special exception, you may use this file as part of a free software
22 // library without restriction.  Specifically, if other files instantiate
23 // templates or use macros or inline functions from this file, or you compile
24 // this file and link it with other files to produce an executable, this
25 // file does not by itself cause the resulting executable to be covered by
26 // the GNU General Public License.  This exception does not however
27 // invalidate any other reasons why the executable file might be covered by
28 // the GNU General Public License.
29
30 /** @file ext/bitmap_allocator.h
31  *  This file is a GNU extension to the Standard C++ Library.
32  */
33
34 #ifndef _BITMAP_ALLOCATOR_H
35 #define _BITMAP_ALLOCATOR_H 1
36
37 // For std::size_t, and ptrdiff_t.
38 #include <cstddef>
39
40 // For __throw_bad_alloc().
41 #include <bits/functexcept.h>
42
43 // For std::pair.
44 #include <utility>
45
46 // For greater_equal, and less_equal.
47 #include <functional>
48
49 // For operator new.
50 #include <new>
51
52 // For __gthread_mutex_t, __gthread_mutex_lock and __gthread_mutex_unlock.
53 #include <bits/gthr.h>
54
55 #include <debug/debug.h> // _GLIBCXX_DEBUG_ASSERT
56
57
58 /** @brief The constant in the expression below is the alignment
59  * required in bytes.
60  */
61 #define _BALLOC_ALIGN_BYTES 8
62
63 _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
64
65   using std::size_t;
66   using std::ptrdiff_t;
67
68 #if defined __GTHREADS
69   namespace
70   {
71     /** @brief  If true, then the application being compiled will be
72      *  using threads, so use mutexes as a synchronization primitive,
73      *  else do no use any synchronization primitives.
74      */
75     bool const __threads_enabled = __gthread_active_p();
76   } // anonymous namespace
77 #endif
78
79 #if defined __GTHREADS
80   /** @class  _Mutex bitmap_allocator.h bitmap_allocator.h
81    *
82    *  @brief  _Mutex is an OO-Wrapper for __gthread_mutex_t. 
83    *
84    *  It does not allow you to copy or assign an already initialized
85    *  mutex. This is used merely as a convenience for the locking
86    *  classes.
87    */
88   class _Mutex 
89   {
90     __gthread_mutex_t _M_mut;
91
92     // Prevent Copying and assignment.
93     _Mutex(_Mutex const&);
94     _Mutex& operator=(_Mutex const&);
95
96   public:
97     _Mutex()
98     {
99       if (__threads_enabled)
100         {
101 #if !defined __GTHREAD_MUTEX_INIT
102           __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mut);
103 #else
104           __gthread_mutex_t __mtemp = __GTHREAD_MUTEX_INIT;
105           _M_mut = __mtemp;
106 #endif
107         }
108     }
109
110     ~_Mutex()
111     {
112       // Gthreads does not define a Mutex Destruction Function.
113     }
114
115     __gthread_mutex_t*
116     _M_get() { return &_M_mut; }
117   };
118
119   /** @class  _Lock bitmap_allocator.h bitmap_allocator.h
120    *
121    *  @brief  _Lock is a simple manual locking class which allows you to
122    *  manually lock and unlock a mutex associated with the lock. 
123    *
124    *  There is no automatic locking or unlocking happening without the
125    *  programmer's explicit instructions. This class unlocks the mutex
126    *  ONLY if it has not been locked. However, this check does not
127    *  apply for locking, and wayward use may cause dead-locks.
128    */
129   class _Lock 
130   {
131     _Mutex* _M_pmt;
132     bool _M_locked;
133
134     // Prevent Copying and assignment.
135     _Lock(_Lock const&);
136     _Lock& operator=(_Lock const&);
137
138   public:
139     _Lock(_Mutex* __mptr)
140     : _M_pmt(__mptr), _M_locked(false)
141     { }
142
143     void
144     _M_lock()
145     {
146       if (__threads_enabled)
147         {
148           _M_locked = true;
149           __gthread_mutex_lock(_M_pmt->_M_get());
150         }
151     }
152
153     void
154     _M_unlock()
155     {
156       if (__threads_enabled)
157         {
158           if (__builtin_expect(_M_locked, true))
159             {
160               __gthread_mutex_unlock(_M_pmt->_M_get());
161               _M_locked = false;
162             }
163         }
164     }
165     
166     ~_Lock() { }
167   };
168
169   /** @class  _Auto_Lock bitmap_allocator.h bitmap_allocator.h
170    *
171    *  @brief  _Auto_Lock locks the associated mutex on construction, and
172    *  unlocks on destruction.
173    *
174    *  There are no checks performed, and this class follows the RAII
175    *  principle.
176    */
177   class _Auto_Lock 
178   {
179     _Mutex* _M_pmt;
180     // Prevent Copying and assignment.
181     _Auto_Lock(_Auto_Lock const&);
182     _Auto_Lock& operator=(_Auto_Lock const&);
183
184     void
185     _M_lock()
186     {
187       if (__threads_enabled)
188         __gthread_mutex_lock(_M_pmt->_M_get());
189     }
190
191     void
192     _M_unlock()
193     {
194       if (__threads_enabled)
195         __gthread_mutex_unlock(_M_pmt->_M_get());
196     }
197
198   public:
199     _Auto_Lock(_Mutex* __mptr) : _M_pmt(__mptr)
200     { this->_M_lock(); }
201
202     ~_Auto_Lock() { this->_M_unlock(); }
203   };
204 #endif 
205
206   namespace balloc
207   {
208     /** @class  __mini_vector bitmap_allocator.h bitmap_allocator.h
209      *
210      *  @brief  __mini_vector<> is a stripped down version of the
211      *  full-fledged std::vector<>.
212      *
213      *  It is to be used only for built-in types or PODs. Notable
214      *  differences are:
215      * 
216      *  @detail
217      *  1. Not all accessor functions are present.
218      *  2. Used ONLY for PODs.
219      *  3. No Allocator template argument. Uses ::operator new() to get
220      *  memory, and ::operator delete() to free it.
221      *  Caveat: The dtor does NOT free the memory allocated, so this a
222      *  memory-leaking vector!
223      */
224     template<typename _Tp>
225       class __mini_vector
226       {
227         __mini_vector(const __mini_vector&);
228         __mini_vector& operator=(const __mini_vector&);
229
230       public:
231         typedef _Tp value_type;
232         typedef _Tp* pointer;
233         typedef _Tp& reference;
234         typedef const _Tp& const_reference;
235         typedef size_t size_type;
236         typedef ptrdiff_t difference_type;
237         typedef pointer iterator;
238
239       private:
240         pointer _M_start;
241         pointer _M_finish;
242         pointer _M_end_of_storage;
243
244         size_type
245         _M_space_left() const throw()
246         { return _M_end_of_storage - _M_finish; }
247
248         pointer
249         allocate(size_type __n)
250         { return static_cast<pointer>(::operator new(__n * sizeof(_Tp))); }
251
252         void
253         deallocate(pointer __p, size_type)
254         { ::operator delete(__p); }
255
256       public:
257         // Members used: size(), push_back(), pop_back(),
258         // insert(iterator, const_reference), erase(iterator),
259         // begin(), end(), back(), operator[].
260
261         __mini_vector() : _M_start(0), _M_finish(0), 
262                           _M_end_of_storage(0)
263         { }
264
265 #if 0
266         ~__mini_vector()
267         {
268           if (this->_M_start)
269             {
270               this->deallocate(this->_M_start, this->_M_end_of_storage 
271                                - this->_M_start);
272             }
273         }
274 #endif
275
276         size_type
277         size() const throw()
278         { return _M_finish - _M_start; }
279
280         iterator
281         begin() const throw()
282         { return this->_M_start; }
283
284         iterator
285         end() const throw()
286         { return this->_M_finish; }
287
288         reference
289         back() const throw()
290         { return *(this->end() - 1); }
291
292         reference
293         operator[](const size_type __pos) const throw()
294         { return this->_M_start[__pos]; }
295
296         void
297         insert(iterator __pos, const_reference __x);
298
299         void
300         push_back(const_reference __x)
301         {
302           if (this->_M_space_left())
303             {
304               *this->end() = __x;
305               ++this->_M_finish;
306             }
307           else
308             this->insert(this->end(), __x);
309         }
310
311         void
312         pop_back() throw()
313         { --this->_M_finish; }
314
315         void
316         erase(iterator __pos) throw();
317
318         void
319         clear() throw()
320         { this->_M_finish = this->_M_start; }
321       };
322
323     // Out of line function definitions.
324     template<typename _Tp>
325       void __mini_vector<_Tp>::
326       insert(iterator __pos, const_reference __x)
327       {
328         if (this->_M_space_left())
329           {
330             size_type __to_move = this->_M_finish - __pos;
331             iterator __dest = this->end();
332             iterator __src = this->end() - 1;
333
334             ++this->_M_finish;
335             while (__to_move)
336               {
337                 *__dest = *__src;
338                 --__dest; --__src; --__to_move;
339               }
340             *__pos = __x;
341           }
342         else
343           {
344             size_type __new_size = this->size() ? this->size() * 2 : 1;
345             iterator __new_start = this->allocate(__new_size);
346             iterator __first = this->begin();
347             iterator __start = __new_start;
348             while (__first != __pos)
349               {
350                 *__start = *__first;
351                 ++__start; ++__first;
352               }
353             *__start = __x;
354             ++__start;
355             while (__first != this->end())
356               {
357                 *__start = *__first;
358                 ++__start; ++__first;
359               }
360             if (this->_M_start)
361               this->deallocate(this->_M_start, this->size());
362
363             this->_M_start = __new_start;
364             this->_M_finish = __start;
365             this->_M_end_of_storage = this->_M_start + __new_size;
366           }
367       }
368
369     template<typename _Tp>
370       void __mini_vector<_Tp>::
371       erase(iterator __pos) throw()
372       {
373         while (__pos + 1 != this->end())
374           {
375             *__pos = __pos[1];
376             ++__pos;
377           }
378         --this->_M_finish;
379       }
380
381
382     template<typename _Tp>
383       struct __mv_iter_traits
384       {
385         typedef typename _Tp::value_type value_type;
386         typedef typename _Tp::difference_type difference_type;
387       };
388
389     template<typename _Tp>
390       struct __mv_iter_traits<_Tp*>
391       {
392         typedef _Tp value_type;
393         typedef ptrdiff_t difference_type;
394       };
395
396     enum 
397       { 
398         bits_per_byte = 8,
399         bits_per_block = sizeof(size_t) * size_t(bits_per_byte) 
400       };
401
402     template<typename _ForwardIterator, typename _Tp, typename _Compare>
403       _ForwardIterator
404       __lower_bound(_ForwardIterator __first, _ForwardIterator __last,
405                     const _Tp& __val, _Compare __comp)
406       {
407         typedef typename __mv_iter_traits<_ForwardIterator>::value_type
408           _ValueType;
409         typedef typename __mv_iter_traits<_ForwardIterator>::difference_type
410           _DistanceType;
411
412         _DistanceType __len = __last - __first;
413         _DistanceType __half;
414         _ForwardIterator __middle;
415
416         while (__len > 0)
417           {
418             __half = __len >> 1;
419             __middle = __first;
420             __middle += __half;
421             if (__comp(*__middle, __val))
422               {
423                 __first = __middle;
424                 ++__first;
425                 __len = __len - __half - 1;
426               }
427             else
428               __len = __half;
429           }
430         return __first;
431       }
432
433     template<typename _InputIterator, typename _Predicate>
434       inline _InputIterator
435       __find_if(_InputIterator __first, _InputIterator __last, _Predicate __p)
436       {
437         while (__first != __last && !__p(*__first))
438           ++__first;
439         return __first;
440       }
441
442     /** @brief The number of Blocks pointed to by the address pair
443      *  passed to the function.
444      */
445     template<typename _AddrPair>
446       inline size_t
447       __num_blocks(_AddrPair __ap)
448       { return (__ap.second - __ap.first) + 1; }
449
450     /** @brief The number of Bit-maps pointed to by the address pair
451      *  passed to the function.
452      */
453     template<typename _AddrPair>
454       inline size_t
455       __num_bitmaps(_AddrPair __ap)
456       { return __num_blocks(__ap) / size_t(bits_per_block); }
457
458     // _Tp should be a pointer type.
459     template<typename _Tp>
460       class _Inclusive_between 
461       : public std::unary_function<typename std::pair<_Tp, _Tp>, bool>
462       {
463         typedef _Tp pointer;
464         pointer _M_ptr_value;
465         typedef typename std::pair<_Tp, _Tp> _Block_pair;
466         
467       public:
468         _Inclusive_between(pointer __ptr) : _M_ptr_value(__ptr) 
469         { }
470         
471         bool 
472         operator()(_Block_pair __bp) const throw()
473         {
474           if (std::less_equal<pointer>()(_M_ptr_value, __bp.second) 
475               && std::greater_equal<pointer>()(_M_ptr_value, __bp.first))
476             return true;
477           else
478             return false;
479         }
480       };
481   
482     // Used to pass a Functor to functions by reference.
483     template<typename _Functor>
484       class _Functor_Ref 
485       : public std::unary_function<typename _Functor::argument_type, 
486                                    typename _Functor::result_type>
487       {
488         _Functor& _M_fref;
489         
490       public:
491         typedef typename _Functor::argument_type argument_type;
492         typedef typename _Functor::result_type result_type;
493
494         _Functor_Ref(_Functor& __fref) : _M_fref(__fref) 
495         { }
496
497         result_type 
498         operator()(argument_type __arg) 
499         { return _M_fref(__arg); }
500       };
501
502     /** @class  _Ffit_finder bitmap_allocator.h bitmap_allocator.h
503      *
504      *  @brief  The class which acts as a predicate for applying the
505      *  first-fit memory allocation policy for the bitmap allocator.
506      */
507     // _Tp should be a pointer type, and _Alloc is the Allocator for
508     // the vector.
509     template<typename _Tp>
510       class _Ffit_finder 
511       : public std::unary_function<typename std::pair<_Tp, _Tp>, bool>
512       {
513         typedef typename std::pair<_Tp, _Tp> _Block_pair;
514         typedef typename balloc::__mini_vector<_Block_pair> _BPVector;
515         typedef typename _BPVector::difference_type _Counter_type;
516
517         size_t* _M_pbitmap;
518         _Counter_type _M_data_offset;
519
520       public:
521         _Ffit_finder() : _M_pbitmap(0), _M_data_offset(0)
522         { }
523
524         bool 
525         operator()(_Block_pair __bp) throw()
526         {
527           // Set the _rover to the last physical location bitmap,
528           // which is the bitmap which belongs to the first free
529           // block. Thus, the bitmaps are in exact reverse order of
530           // the actual memory layout. So, we count down the bimaps,
531           // which is the same as moving up the memory.
532
533           // If the used count stored at the start of the Bit Map headers
534           // is equal to the number of Objects that the current Block can
535           // store, then there is definitely no space for another single
536           // object, so just return false.
537           _Counter_type __diff = 
538             __gnu_cxx::balloc::__num_bitmaps(__bp);
539
540           if (*(reinterpret_cast<size_t*>
541                 (__bp.first) - (__diff + 1))
542               == __gnu_cxx::balloc::__num_blocks(__bp))
543             return false;
544
545           size_t* __rover = reinterpret_cast<size_t*>(__bp.first) - 1;
546
547           for (_Counter_type __i = 0; __i < __diff; ++__i)
548             {
549               _M_data_offset = __i;
550               if (*__rover)
551                 {
552                   _M_pbitmap = __rover;
553                   return true;
554                 }
555               --__rover;
556             }
557           return false;
558         }
559
560     
561         size_t*
562         _M_get() const throw()
563         { return _M_pbitmap; }
564
565         _Counter_type
566         _M_offset() const throw()
567         { return _M_data_offset * size_t(bits_per_block); }
568       };
569
570
571     /** @class  _Bitmap_counter bitmap_allocator.h bitmap_allocator.h
572      *
573      *  @brief  The bitmap counter which acts as the bitmap
574      *  manipulator, and manages the bit-manipulation functions and
575      *  the searching and identification functions on the bit-map.
576      */
577     // _Tp should be a pointer type.
578     template<typename _Tp>
579       class _Bitmap_counter
580       {
581         typedef typename balloc::__mini_vector<typename std::pair<_Tp, _Tp> > 
582         _BPVector;
583         typedef typename _BPVector::size_type _Index_type;
584         typedef _Tp pointer;
585     
586         _BPVector& _M_vbp;
587         size_t* _M_curr_bmap;
588         size_t* _M_last_bmap_in_block;
589         _Index_type _M_curr_index;
590     
591       public:
592         // Use the 2nd parameter with care. Make sure that such an
593         // entry exists in the vector before passing that particular
594         // index to this ctor.
595         _Bitmap_counter(_BPVector& Rvbp, long __index = -1) : _M_vbp(Rvbp)
596         { this->_M_reset(__index); }
597     
598         void 
599         _M_reset(long __index = -1) throw()
600         {
601           if (__index == -1)
602             {
603               _M_curr_bmap = 0;
604               _M_curr_index = static_cast<_Index_type>(-1);
605               return;
606             }
607
608           _M_curr_index = __index;
609           _M_curr_bmap = reinterpret_cast<size_t*>
610             (_M_vbp[_M_curr_index].first) - 1;
611           
612           _GLIBCXX_DEBUG_ASSERT(__index <= (long)_M_vbp.size() - 1);
613         
614           _M_last_bmap_in_block = _M_curr_bmap
615             - ((_M_vbp[_M_curr_index].second 
616                 - _M_vbp[_M_curr_index].first + 1) 
617                / size_t(bits_per_block) - 1);
618         }
619     
620         // Dangerous Function! Use with extreme care. Pass to this
621         // function ONLY those values that are known to be correct,
622         // otherwise this will mess up big time.
623         void
624         _M_set_internal_bitmap(size_t* __new_internal_marker) throw()
625         { _M_curr_bmap = __new_internal_marker; }
626     
627         bool
628         _M_finished() const throw()
629         { return(_M_curr_bmap == 0); }
630     
631         _Bitmap_counter&
632         operator++() throw()
633         {
634           if (_M_curr_bmap == _M_last_bmap_in_block)
635             {
636               if (++_M_curr_index == _M_vbp.size())
637                 _M_curr_bmap = 0;
638               else
639                 this->_M_reset(_M_curr_index);
640             }
641           else
642             --_M_curr_bmap;
643           return *this;
644         }
645     
646         size_t*
647         _M_get() const throw()
648         { return _M_curr_bmap; }
649     
650         pointer 
651         _M_base() const throw()
652         { return _M_vbp[_M_curr_index].first; }
653
654         _Index_type
655         _M_offset() const throw()
656         {
657           return size_t(bits_per_block)
658             * ((reinterpret_cast<size_t*>(this->_M_base()) 
659                 - _M_curr_bmap) - 1);
660         }
661     
662         _Index_type
663         _M_where() const throw()
664         { return _M_curr_index; }
665       };
666
667     /** @brief  Mark a memory address as allocated by re-setting the
668      *  corresponding bit in the bit-map.
669      */
670     inline void 
671     __bit_allocate(size_t* __pbmap, size_t __pos) throw()
672     {
673       size_t __mask = 1 << __pos;
674       __mask = ~__mask;
675       *__pbmap &= __mask;
676     }
677   
678     /** @brief  Mark a memory address as free by setting the
679      *  corresponding bit in the bit-map.
680      */
681     inline void 
682     __bit_free(size_t* __pbmap, size_t __pos) throw()
683     {
684       size_t __mask = 1 << __pos;
685       *__pbmap |= __mask;
686     }
687   } // namespace balloc
688
689   /** @brief  Generic Version of the bsf instruction.
690    */
691   inline size_t 
692   _Bit_scan_forward(size_t __num)
693   { return static_cast<size_t>(__builtin_ctzl(__num)); }
694
695   /** @class  free_list bitmap_allocator.h bitmap_allocator.h
696    *
697    *  @brief  The free list class for managing chunks of memory to be
698    *  given to and returned by the bitmap_allocator.
699    */
700   class free_list
701   {
702     typedef size_t* value_type;
703     typedef balloc::__mini_vector<value_type> vector_type;
704     typedef vector_type::iterator iterator;
705
706     struct _LT_pointer_compare
707     {
708       bool
709       operator()(const size_t* __pui, 
710                  const size_t __cui) const throw()
711       { return *__pui < __cui; }
712     };
713
714 #if defined __GTHREADS
715     _Mutex*
716     _M_get_mutex()
717     {
718       static _Mutex _S_mutex;
719       return &_S_mutex;
720     }
721 #endif
722
723     vector_type&
724     _M_get_free_list()
725     {
726       static vector_type _S_free_list;
727       return _S_free_list;
728     }
729
730     /** @brief  Performs validation of memory based on their size.
731      *
732      *  @param  __addr The pointer to the memory block to be
733      *  validated.
734      *
735      *  @detail  Validates the memory block passed to this function and
736      *  appropriately performs the action of managing the free list of
737      *  blocks by adding this block to the free list or deleting this
738      *  or larger blocks from the free list.
739      */
740     void
741     _M_validate(size_t* __addr) throw()
742     {
743       vector_type& __free_list = _M_get_free_list();
744       const vector_type::size_type __max_size = 64;
745       if (__free_list.size() >= __max_size)
746         {
747           // Ok, the threshold value has been reached.  We determine
748           // which block to remove from the list of free blocks.
749           if (*__addr >= *__free_list.back())
750             {
751               // Ok, the new block is greater than or equal to the
752               // last block in the list of free blocks. We just free
753               // the new block.
754               ::operator delete(static_cast<void*>(__addr));
755               return;
756             }
757           else
758             {
759               // Deallocate the last block in the list of free lists,
760               // and insert the new one in it's correct position.
761               ::operator delete(static_cast<void*>(__free_list.back()));
762               __free_list.pop_back();
763             }
764         }
765           
766       // Just add the block to the list of free lists unconditionally.
767       iterator __temp = __gnu_cxx::balloc::__lower_bound
768         (__free_list.begin(), __free_list.end(), 
769          *__addr, _LT_pointer_compare());
770
771       // We may insert the new free list before _temp;
772       __free_list.insert(__temp, __addr);
773     }
774
775     /** @brief  Decides whether the wastage of memory is acceptable for
776      *  the current memory request and returns accordingly.
777      *
778      *  @param __block_size The size of the block available in the free
779      *  list.
780      *
781      *  @param __required_size The required size of the memory block.
782      *
783      *  @return true if the wastage incurred is acceptable, else returns
784      *  false.
785      */
786     bool 
787     _M_should_i_give(size_t __block_size, 
788                      size_t __required_size) throw()
789     {
790       const size_t __max_wastage_percentage = 36;
791       if (__block_size >= __required_size && 
792           (((__block_size - __required_size) * 100 / __block_size)
793            < __max_wastage_percentage))
794         return true;
795       else
796         return false;
797     }
798
799   public:
800     /** @brief This function returns the block of memory to the
801      *  internal free list.
802      *
803      *  @param  __addr The pointer to the memory block that was given
804      *  by a call to the _M_get function.
805      */
806     inline void 
807     _M_insert(size_t* __addr) throw()
808     {
809 #if defined __GTHREADS
810       _Auto_Lock __bfl_lock(_M_get_mutex());
811 #endif
812       // Call _M_validate to decide what should be done with
813       // this particular free list.
814       this->_M_validate(reinterpret_cast<size_t*>(__addr) - 1);
815       // See discussion as to why this is 1!
816     }
817     
818     /** @brief  This function gets a block of memory of the specified
819      *  size from the free list.
820      *
821      *  @param  __sz The size in bytes of the memory required.
822      *
823      *  @return  A pointer to the new memory block of size at least
824      *  equal to that requested.
825      */
826     size_t*
827     _M_get(size_t __sz) throw(std::bad_alloc);
828
829     /** @brief  This function just clears the internal Free List, and
830      *  gives back all the memory to the OS.
831      */
832     void 
833     _M_clear();
834   };
835
836
837   // Forward declare the class.
838   template<typename _Tp> 
839     class bitmap_allocator;
840
841   // Specialize for void:
842   template<>
843     class bitmap_allocator<void>
844     {
845     public:
846       typedef void*       pointer;
847       typedef const void* const_pointer;
848
849       // Reference-to-void members are impossible.
850       typedef void  value_type;
851       template<typename _Tp1>
852         struct rebind
853         {
854           typedef bitmap_allocator<_Tp1> other;
855         };
856     };
857
858   template<typename _Tp>
859     class bitmap_allocator : private free_list
860     {
861     public:
862       typedef size_t    size_type;
863       typedef ptrdiff_t difference_type;
864       typedef _Tp*        pointer;
865       typedef const _Tp*  const_pointer;
866       typedef _Tp&        reference;
867       typedef const _Tp&  const_reference;
868       typedef _Tp         value_type;
869       template<typename _Tp1>
870         struct rebind
871         {
872           typedef bitmap_allocator<_Tp1> other;
873         };
874
875     private:
876       template<size_t _BSize, size_t _AlignSize>
877         struct aligned_size
878         {
879           enum
880             { 
881               modulus = _BSize % _AlignSize,
882               value = _BSize + (modulus ? _AlignSize - (modulus) : 0)
883             };
884         };
885
886       struct _Alloc_block
887       {
888         char __M_unused[aligned_size<sizeof(value_type),
889                         _BALLOC_ALIGN_BYTES>::value];
890       };
891
892
893       typedef typename std::pair<_Alloc_block*, _Alloc_block*> _Block_pair;
894
895       typedef typename 
896       balloc::__mini_vector<_Block_pair> _BPVector;
897
898 #if defined _GLIBCXX_DEBUG
899       // Complexity: O(lg(N)). Where, N is the number of block of size
900       // sizeof(value_type).
901       void 
902       _S_check_for_free_blocks() throw()
903       {
904         typedef typename 
905           __gnu_cxx::balloc::_Ffit_finder<_Alloc_block*> _FFF;
906         _FFF __fff;
907         typedef typename _BPVector::iterator _BPiter;
908         _BPiter __bpi = 
909           __gnu_cxx::balloc::__find_if
910           (_S_mem_blocks.begin(), _S_mem_blocks.end(), 
911            __gnu_cxx::balloc::_Functor_Ref<_FFF>(__fff));
912
913         _GLIBCXX_DEBUG_ASSERT(__bpi == _S_mem_blocks.end());
914       }
915 #endif
916
917       /** @brief  Responsible for exponentially growing the internal
918        *  memory pool.
919        *
920        *  @throw  std::bad_alloc. If memory can not be allocated.
921        *
922        *  @detail  Complexity: O(1), but internally depends upon the
923        *  complexity of the function free_list::_M_get. The part where
924        *  the bitmap headers are written has complexity: O(X),where X
925        *  is the number of blocks of size sizeof(value_type) within
926        *  the newly acquired block. Having a tight bound.
927        */
928       void 
929       _S_refill_pool() throw(std::bad_alloc)
930       {
931 #if defined _GLIBCXX_DEBUG
932         _S_check_for_free_blocks();
933 #endif
934
935         const size_t __num_bitmaps = (_S_block_size
936                                       / size_t(balloc::bits_per_block));
937         const size_t __size_to_allocate = sizeof(size_t) 
938           + _S_block_size * sizeof(_Alloc_block) 
939           + __num_bitmaps * sizeof(size_t);
940
941         size_t* __temp = 
942           reinterpret_cast<size_t*>
943           (this->_M_get(__size_to_allocate));
944         *__temp = 0;
945         ++__temp;
946
947         // The Header information goes at the Beginning of the Block.
948         _Block_pair __bp = 
949           std::make_pair(reinterpret_cast<_Alloc_block*>
950                          (__temp + __num_bitmaps), 
951                          reinterpret_cast<_Alloc_block*>
952                          (__temp + __num_bitmaps) 
953                          + _S_block_size - 1);
954         
955         // Fill the Vector with this information.
956         _S_mem_blocks.push_back(__bp);
957
958         size_t __bit_mask = 0; // 0 Indicates all Allocated.
959         __bit_mask = ~__bit_mask; // 1 Indicates all Free.
960
961         for (size_t __i = 0; __i < __num_bitmaps; ++__i)
962           __temp[__i] = __bit_mask;
963
964         _S_block_size *= 2;
965       }
966
967
968       static _BPVector _S_mem_blocks;
969       static size_t _S_block_size;
970       static __gnu_cxx::balloc::
971       _Bitmap_counter<_Alloc_block*> _S_last_request;
972       static typename _BPVector::size_type _S_last_dealloc_index;
973 #if defined __GTHREADS
974       static _Mutex _S_mut;
975 #endif
976
977     public:
978
979       /** @brief  Allocates memory for a single object of size
980        *  sizeof(_Tp).
981        *
982        *  @throw  std::bad_alloc. If memory can not be allocated.
983        *
984        *  @detail  Complexity: Worst case complexity is O(N), but that
985        *  is hardly ever hit. If and when this particular case is
986        *  encountered, the next few cases are guaranteed to have a
987        *  worst case complexity of O(1)!  That's why this function
988        *  performs very well on average. You can consider this
989        *  function to have a complexity referred to commonly as:
990        *  Amortized Constant time.
991        */
992       pointer 
993       _M_allocate_single_object() throw(std::bad_alloc)
994       {
995 #if defined __GTHREADS
996         _Auto_Lock __bit_lock(&_S_mut);
997 #endif
998
999         // The algorithm is something like this: The last_request
1000         // variable points to the last accessed Bit Map. When such a
1001         // condition occurs, we try to find a free block in the
1002         // current bitmap, or succeeding bitmaps until the last bitmap
1003         // is reached. If no free block turns up, we resort to First
1004         // Fit method.
1005
1006         // WARNING: Do not re-order the condition in the while
1007         // statement below, because it relies on C++'s short-circuit
1008         // evaluation. The return from _S_last_request->_M_get() will
1009         // NOT be dereference able if _S_last_request->_M_finished()
1010         // returns true. This would inevitably lead to a NULL pointer
1011         // dereference if tinkered with.
1012         while (_S_last_request._M_finished() == false
1013                && (*(_S_last_request._M_get()) == 0))
1014           {
1015             _S_last_request.operator++();
1016           }
1017
1018         if (__builtin_expect(_S_last_request._M_finished() == true, false))
1019           {
1020             // Fall Back to First Fit algorithm.
1021             typedef typename 
1022               __gnu_cxx::balloc::_Ffit_finder<_Alloc_block*> _FFF;
1023             _FFF __fff;
1024             typedef typename _BPVector::iterator _BPiter;
1025             _BPiter __bpi = 
1026               __gnu_cxx::balloc::__find_if
1027               (_S_mem_blocks.begin(), _S_mem_blocks.end(), 
1028                __gnu_cxx::balloc::_Functor_Ref<_FFF>(__fff));
1029
1030             if (__bpi != _S_mem_blocks.end())
1031               {
1032                 // Search was successful. Ok, now mark the first bit from
1033                 // the right as 0, meaning Allocated. This bit is obtained
1034                 // by calling _M_get() on __fff.
1035                 size_t __nz_bit = _Bit_scan_forward(*__fff._M_get());
1036                 balloc::__bit_allocate(__fff._M_get(), __nz_bit);
1037
1038                 _S_last_request._M_reset(__bpi - _S_mem_blocks.begin());
1039
1040                 // Now, get the address of the bit we marked as allocated.
1041                 pointer __ret = reinterpret_cast<pointer>
1042                   (__bpi->first + __fff._M_offset() + __nz_bit);
1043                 size_t* __puse_count = 
1044                   reinterpret_cast<size_t*>
1045                   (__bpi->first) 
1046                   - (__gnu_cxx::balloc::__num_bitmaps(*__bpi) + 1);
1047                 
1048                 ++(*__puse_count);
1049                 return __ret;
1050               }
1051             else
1052               {
1053                 // Search was unsuccessful. We Add more memory to the
1054                 // pool by calling _S_refill_pool().
1055                 _S_refill_pool();
1056
1057                 // _M_Reset the _S_last_request structure to the first
1058                 // free block's bit map.
1059                 _S_last_request._M_reset(_S_mem_blocks.size() - 1);
1060
1061                 // Now, mark that bit as allocated.
1062               }
1063           }
1064
1065         // _S_last_request holds a pointer to a valid bit map, that
1066         // points to a free block in memory.
1067         size_t __nz_bit = _Bit_scan_forward(*_S_last_request._M_get());
1068         balloc::__bit_allocate(_S_last_request._M_get(), __nz_bit);
1069
1070         pointer __ret = reinterpret_cast<pointer>
1071           (_S_last_request._M_base() + _S_last_request._M_offset() + __nz_bit);
1072
1073         size_t* __puse_count = reinterpret_cast<size_t*>
1074           (_S_mem_blocks[_S_last_request._M_where()].first)
1075           - (__gnu_cxx::balloc::
1076              __num_bitmaps(_S_mem_blocks[_S_last_request._M_where()]) + 1);
1077
1078         ++(*__puse_count);
1079         return __ret;
1080       }
1081
1082       /** @brief  Deallocates memory that belongs to a single object of
1083        *  size sizeof(_Tp).
1084        *
1085        *  @detail  Complexity: O(lg(N)), but the worst case is not hit
1086        *  often!  This is because containers usually deallocate memory
1087        *  close to each other and this case is handled in O(1) time by
1088        *  the deallocate function.
1089        */
1090       void 
1091       _M_deallocate_single_object(pointer __p) throw()
1092       {
1093 #if defined __GTHREADS
1094         _Auto_Lock __bit_lock(&_S_mut);
1095 #endif
1096         _Alloc_block* __real_p = reinterpret_cast<_Alloc_block*>(__p);
1097
1098         typedef typename _BPVector::iterator _Iterator;
1099         typedef typename _BPVector::difference_type _Difference_type;
1100
1101         _Difference_type __diff;
1102         long __displacement;
1103
1104         _GLIBCXX_DEBUG_ASSERT(_S_last_dealloc_index >= 0);
1105
1106         
1107         if (__gnu_cxx::balloc::_Inclusive_between<_Alloc_block*>
1108             (__real_p)
1109             (_S_mem_blocks[_S_last_dealloc_index]))
1110           {
1111             _GLIBCXX_DEBUG_ASSERT(_S_last_dealloc_index <= _S_mem_blocks.size() - 1);
1112
1113             // Initial Assumption was correct!
1114             __diff = _S_last_dealloc_index;
1115             __displacement = __real_p - _S_mem_blocks[__diff].first;
1116           }
1117         else
1118           {
1119             _Iterator _iter = 
1120               __gnu_cxx::balloc::
1121               __find_if(_S_mem_blocks.begin(), 
1122                         _S_mem_blocks.end(), 
1123                         __gnu_cxx::balloc::
1124                         _Inclusive_between<_Alloc_block*>(__real_p));
1125
1126             _GLIBCXX_DEBUG_ASSERT(_iter != _S_mem_blocks.end());
1127
1128             __diff = _iter - _S_mem_blocks.begin();
1129             __displacement = __real_p - _S_mem_blocks[__diff].first;
1130             _S_last_dealloc_index = __diff;
1131           }
1132
1133         // Get the position of the iterator that has been found.
1134         const size_t __rotate = (__displacement
1135                                  % size_t(balloc::bits_per_block));
1136         size_t* __bitmapC = 
1137           reinterpret_cast<size_t*>
1138           (_S_mem_blocks[__diff].first) - 1;
1139         __bitmapC -= (__displacement / size_t(balloc::bits_per_block));
1140       
1141         balloc::__bit_free(__bitmapC, __rotate);
1142         size_t* __puse_count = reinterpret_cast<size_t*>
1143           (_S_mem_blocks[__diff].first)
1144           - (__gnu_cxx::balloc::__num_bitmaps(_S_mem_blocks[__diff]) + 1);
1145         
1146         _GLIBCXX_DEBUG_ASSERT(*__puse_count != 0);
1147
1148         --(*__puse_count);
1149
1150         if (__builtin_expect(*__puse_count == 0, false))
1151           {
1152             _S_block_size /= 2;
1153           
1154             // We can safely remove this block.
1155             // _Block_pair __bp = _S_mem_blocks[__diff];
1156             this->_M_insert(__puse_count);
1157             _S_mem_blocks.erase(_S_mem_blocks.begin() + __diff);
1158
1159             // Reset the _S_last_request variable to reflect the
1160             // erased block. We do this to protect future requests
1161             // after the last block has been removed from a particular
1162             // memory Chunk, which in turn has been returned to the
1163             // free list, and hence had been erased from the vector,
1164             // so the size of the vector gets reduced by 1.
1165             if ((_Difference_type)_S_last_request._M_where() >= __diff--)
1166               _S_last_request._M_reset(__diff); 
1167
1168             // If the Index into the vector of the region of memory
1169             // that might hold the next address that will be passed to
1170             // deallocated may have been invalidated due to the above
1171             // erase procedure being called on the vector, hence we
1172             // try to restore this invariant too.
1173             if (_S_last_dealloc_index >= _S_mem_blocks.size())
1174               {
1175                 _S_last_dealloc_index =(__diff != -1 ? __diff : 0);
1176                 _GLIBCXX_DEBUG_ASSERT(_S_last_dealloc_index >= 0);
1177               }
1178           }
1179       }
1180
1181     public:
1182       bitmap_allocator() throw()
1183       { }
1184
1185       bitmap_allocator(const bitmap_allocator&)
1186       { }
1187
1188       template<typename _Tp1>
1189         bitmap_allocator(const bitmap_allocator<_Tp1>&) throw()
1190         { }
1191
1192       ~bitmap_allocator() throw()
1193       { }
1194
1195       pointer 
1196       allocate(size_type __n)
1197       {
1198         if (__builtin_expect(__n > this->max_size(), false))
1199           std::__throw_bad_alloc();
1200
1201         if (__builtin_expect(__n == 1, true))
1202           return this->_M_allocate_single_object();
1203         else
1204           { 
1205             const size_type __b = __n * sizeof(value_type);
1206             return reinterpret_cast<pointer>(::operator new(__b));
1207           }
1208       }
1209
1210       pointer 
1211       allocate(size_type __n, typename bitmap_allocator<void>::const_pointer)
1212       { return allocate(__n); }
1213
1214       void 
1215       deallocate(pointer __p, size_type __n) throw()
1216       {
1217         if (__builtin_expect(__p != 0, true))
1218           {
1219             if (__builtin_expect(__n == 1, true))
1220               this->_M_deallocate_single_object(__p);
1221             else
1222               ::operator delete(__p);
1223           }
1224       }
1225
1226       pointer 
1227       address(reference __r) const
1228       { return &__r; }
1229
1230       const_pointer 
1231       address(const_reference __r) const
1232       { return &__r; }
1233
1234       size_type 
1235       max_size() const throw()
1236       { return size_type(-1) / sizeof(value_type); }
1237
1238       void 
1239       construct(pointer __p, const_reference __data)
1240       { ::new(__p) value_type(__data); }
1241
1242       void 
1243       destroy(pointer __p)
1244       { __p->~value_type(); }
1245     };
1246
1247   template<typename _Tp1, typename _Tp2>
1248     bool 
1249     operator==(const bitmap_allocator<_Tp1>&, 
1250                const bitmap_allocator<_Tp2>&) throw()
1251     { return true; }
1252   
1253   template<typename _Tp1, typename _Tp2>
1254     bool 
1255     operator!=(const bitmap_allocator<_Tp1>&, 
1256                const bitmap_allocator<_Tp2>&) throw() 
1257   { return false; }
1258
1259   // Static member definitions.
1260   template<typename _Tp>
1261     typename bitmap_allocator<_Tp>::_BPVector
1262     bitmap_allocator<_Tp>::_S_mem_blocks;
1263
1264   template<typename _Tp>
1265     size_t bitmap_allocator<_Tp>::_S_block_size = 
1266     2 * size_t(balloc::bits_per_block);
1267
1268   template<typename _Tp>
1269     typename __gnu_cxx::bitmap_allocator<_Tp>::_BPVector::size_type 
1270     bitmap_allocator<_Tp>::_S_last_dealloc_index = 0;
1271
1272   template<typename _Tp>
1273     __gnu_cxx::balloc::_Bitmap_counter 
1274   <typename bitmap_allocator<_Tp>::_Alloc_block*>
1275     bitmap_allocator<_Tp>::_S_last_request(_S_mem_blocks);
1276
1277 #if defined __GTHREADS
1278   template<typename _Tp>
1279     __gnu_cxx::_Mutex
1280     bitmap_allocator<_Tp>::_S_mut;
1281 #endif
1282
1283 _GLIBCXX_END_NAMESPACE
1284
1285 #endif 
1286
1287 //  LocalWords:  namespace GTHREADS bool const gthread endif Mutex mutex