OSDN Git Service

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