mem_utils.txx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * \file mat_utils.txx
  3. * \author Dhairya Malhotra, dhairya.malhotra@gmail.com
  4. * \date 11-5-2013
  5. * \brief This file contains implementation of mem_utils.hpp.
  6. */
  7. #include <cassert>
  8. #include <cstring>
  9. #include <cstdlib>
  10. #include <stdint.h>
  11. #ifdef __INTEL_OFFLOAD
  12. #pragma offload_attribute(push,target(mic))
  13. #endif
  14. namespace pvfmm{
  15. namespace mem{
  16. // For fundamental data types.
  17. template <class T>
  18. T* aligned_malloc_f(size_t size_, size_t alignment){
  19. assert(alignment <= 0x8000);
  20. size_t size=size_*sizeof(T);
  21. uintptr_t r = (uintptr_t)malloc(size + --alignment + 2);
  22. //if (!r) return NULL;
  23. ASSERT_WITH_MSG(r!=0, "malloc failed.");
  24. uintptr_t o = (uintptr_t)(r + 2 + alignment) & ~(uintptr_t)alignment;
  25. ((uint16_t*)o)[-1] = (uint16_t)(o-r);
  26. return (T*)o;
  27. //return (T*)fftw_malloc(size);
  28. }
  29. template <class T>
  30. void aligned_free_f(T* p_){
  31. void* p=(void*)p_;
  32. if (!p) return;
  33. free((void*)((uintptr_t)p-((uint16_t*)p)[-1]));
  34. //fftw_free(p);
  35. }
  36. template <class T>
  37. T* aligned_malloc(size_t size_, size_t alignment){
  38. //void* p=aligned_malloc_f<T>(size_,alignment);
  39. //return new(p) T[size_];
  40. T* A=new T[size_];
  41. assert(A!=NULL);
  42. return A;
  43. }
  44. template <>
  45. inline double* aligned_malloc<double>(size_t size_, size_t alignment){
  46. return aligned_malloc_f<double>(size_,alignment);
  47. }
  48. template <>
  49. inline float* aligned_malloc<float>(size_t size_, size_t alignment){
  50. return aligned_malloc_f<float>(size_,alignment);
  51. }
  52. template <>
  53. inline char* aligned_malloc<char>(size_t size_, size_t alignment){
  54. return aligned_malloc_f<char>(size_,alignment);
  55. }
  56. template <class T>
  57. void aligned_free(T* p_){
  58. delete[] p_;
  59. }
  60. template <>
  61. inline void aligned_free<double>(double* p_){
  62. aligned_free_f<double>(p_);
  63. }
  64. template <>
  65. inline void aligned_free<float>(float* p_){
  66. aligned_free_f<float>(p_);
  67. }
  68. template <>
  69. inline void aligned_free<char>(char* p_){
  70. aligned_free_f<char>(p_);
  71. }
  72. inline void * memcopy ( void * destination, const void * source, size_t num ){
  73. if(destination==source || num==0) return destination;
  74. return memcpy ( destination, source, num );
  75. }
  76. }//end namespace
  77. }//end namespace
  78. #ifdef __INTEL_OFFLOAD
  79. #pragma offload_attribute(pop)
  80. #endif