/*
 * $Id: memblock.cc,v 1.1.1.1 1999-11-26 16:37:04 ansari Exp $
 *
 * Copyright (C) 1997 Todd Veldhuizen <tveldhui@seurat.uwaterloo.ca>
 * All rights reserved.  Please see <blitz/blitz.h> for terms and
 * conditions of use.
 *
 * $Log: not supported by cvs2svn $
// Revision 1.1.1.1  1999/04/09  17:58:58  ansari
// Creation module DPC/Blitz (blitz 0.4) Reza 09/04/99
//
 * Revision 1.4  1998/03/14 00:04:47  tveldhui
 * 0.2-alpha-05
 *
 * Revision 1.3  1997/07/16 14:51:20  tveldhui
 * Update: Alpha release 0.2 (Arrays)
 *
 * Revision 1.2  1997/01/24 14:42:00  tveldhui
 * Periodic RCS update
 *
 */

#ifndef BZ_MEMBLOCK_CC
#define BZ_MEMBLOCK_CC

#ifndef BZ_MEMBLOCK_H
 #include <blitz/memblock.h>
#endif

BZ_NAMESPACE(blitz)

// Null memory block for each (template) instantiation of MemoryBlockReference
template<class P_type> 
NullMemoryBlock<P_type> MemoryBlockReference<P_type>::nullBlock_;

template<class P_type>
inline void MemoryBlock<P_type>::allocate(int length)
{
    TAU_TYPE_STRING(p1, "MemoryBlock<T>::allocate() [T="
        + CT(P_type) + "]");
    TAU_PROFILE(p1, "void ()", TAU_BLITZ);

#ifndef BZ_ALIGN_BLOCKS_ON_CACHELINE_BOUNDARY
    data_ =  new T_type[length];
    dataBlockAddress_ = data_;
#else
    int numBytes = length * sizeof(T_type);

    if (numBytes < 1024)
    {
        data_ =  new T_type[length];
        dataBlockAddress_ = data_;
    }
    else
    {
        // We're allocating a large array.  For performance reasons,
        // it's advantageous to force the array to start on a
        // cache line boundary.  We do this by allocating a little
        // more memory than necessary, then shifting the pointer
        // to the next cache line boundary.
        // NB: This code assumes that T_type has a trivial
        // constructor.
        const int cacheBlockSize = 128;    // Will work for 32, 16 also

        dataBlockAddress_ = new T_type[length
            + (cacheBlockSize + sizeof(T_type) - 1) / sizeof(T_type)];

        // Shift to the next cache line boundary

        ptrdiff_t offset = ptrdiff_t(dataBlockAddress_) % cacheBlockSize;
        int shift = (offset == 0) ? 0 : (cacheBlockSize - offset);
        data_ = (T_type*)(((char *)dataBlockAddress_) + shift);
    }
#endif
}


BZ_NAMESPACE_END

#endif // BZ_MEMBLOCK_CC
