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