diff --git a/projects/hip/cmake/FindHIP.cmake b/projects/hip/cmake/FindHIP.cmake index 109c9f65ec..24e475d35b 100644 --- a/projects/hip/cmake/FindHIP.cmake +++ b/projects/hip/cmake/FindHIP.cmake @@ -67,7 +67,7 @@ if(HIP_CXX_COMPILER MATCHES ".*hipcc") elseif (HIP_CXX_COMPILER MATCHES ".*clang\\+\\+") get_filename_component(_HIP_CLANG_REAL_PATH "${HIP_CXX_COMPILER}" REALPATH) get_filename_component(_HIP_CLANG_BIN_PATH "${_HIP_CLANG_REAL_PATH}" DIRECTORY) - get_filename_component(HIP_CLANG_INSTALL_DIR "${_HIP_CLANG_BIN_PATH}" DIRECTORY) + set(HIP_CLANG_PATH "${_HIP_CLANG_BIN_PATH}") endif() diff --git a/projects/hip/tests/catch/unit/errorHandling/hipGetErrorString.cc b/projects/hip/include/hip/hip_bf16.h similarity index 58% rename from projects/hip/tests/catch/unit/errorHandling/hipGetErrorString.cc rename to projects/hip/include/hip/hip_bf16.h index fe3f5523c2..09da636047 100644 --- a/projects/hip/tests/catch/unit/errorHandling/hipGetErrorString.cc +++ b/projects/hip/include/hip/hip_bf16.h @@ -1,5 +1,5 @@ /* -Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved. +Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -20,22 +20,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#include "errorEnumerators.h" -#include -#include +#ifndef HIP_INCLUDE_HIP_HIP_BF16_H +#define HIP_INCLUDE_HIP_HIP_BF16_H -TEST_CASE("Unit_hipGetErrorString_Positive_Basic") { - const char* error_string = nullptr; - const auto enumerator = - GENERATE(from_range(std::begin(kErrorEnumerators), std::end(kErrorEnumerators))); +#include - error_string = hipGetErrorString(enumerator); +#if (defined(__HIP_PLATFORM_HCC__) || defined(__HIP_PLATFORM_AMD__)) && \ + !(defined(__HIP_PLATFORM_NVCC__) || defined(__HIP_PLATFORM_NVIDIA__)) +#include +#elif !(defined(__HIP_PLATFORM_HCC__) || defined(__HIP_PLATFORM_AMD__)) && \ + (defined(__HIP_PLATFORM_NVCC__) || defined(__HIP_PLATFORM_NVIDIA__)) +#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif - REQUIRE(error_string != nullptr); - REQUIRE(strlen(error_string) > 0); -} - -TEST_CASE("Unit_hipGetErrorString_Negative_Parameters") { - const char* error_string = hipGetErrorString(static_cast(-1)); - REQUIRE(error_string != nullptr); -} \ No newline at end of file +#endif // HIP_INCLUDE_HIP_HIP_BF16_H diff --git a/projects/hip/include/hip/hip_ext.h b/projects/hip/include/hip/hip_ext.h index e129e6fd19..2548cbe1e5 100644 --- a/projects/hip/include/hip/hip_ext.h +++ b/projects/hip/include/hip/hip_ext.h @@ -36,15 +36,15 @@ THE SOFTWARE. * to kernel params or extra arguments. * * @param [in] f Kernel to launch. - * @param [in] gridDimX X grid dimension specified in work-items. - * @param [in] gridDimY Y grid dimension specified in work-items. - * @param [in] gridDimZ Z grid dimension specified in work-items. - * @param [in] blockDimX X block dimension specified in work-items. - * @param [in] blockDimY Y grid dimension specified in work-items. - * @param [in] blockDimZ Z grid dimension specified in work-items. + * @param [in] globalWorkSizeX X grid dimension specified in work-items. + * @param [in] globalWorkSizeY Y grid dimension specified in work-items. + * @param [in] globalWorkSizeZ Z grid dimension specified in work-items. + * @param [in] localWorkSizeX X block dimension specified in work-items. + * @param [in] localWorkSizeY Y block dimension specified in work-items. + * @param [in] localWorkSizeZ Z block dimension specified in work-items. * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. * HIP-Clang compiler provides support for extern shared declarations. - * @param [in] stream Stream where the kernel should be dispatched. + * @param [in] hStream Stream where the kernel should be dispatched. * May be 0, in which case the default stream is used with associated synchronization rules. * @param [in] kernelParams pointer to kernel parameters. * @param [in] extra Pointer to kernel arguments. These are passed directly to the kernel and @@ -53,11 +53,11 @@ THE SOFTWARE. * the kernel launch. The event must be created before calling this API. * @param [in] stopEvent If non-null, specified event will be updated to track the stop time of * the kernel launch. The event must be created before calling this API. - * @param [in] flags. The value of hipExtAnyOrderLaunch, signifies if kernel can be + * @param [in] flags The value of hipExtAnyOrderLaunch, signifies if kernel can be * launched in any order. - * @returns hipSuccess, hipInvalidDevice, hipErrorNotInitialized, hipErrorInvalidValue. + * @returns #hipSuccess, #hipInvalidDeviceId, #hipErrorNotInitialized, #hipErrorInvalidValue. * - * @warning kernellParams argument is not yet implemented in HIP, use extra instead. + * @warning kernellParams argument is not yet implemented in HIP, use extra instead. * Please refer to hip_porting_driver_api.md for sample usage. * HIP/ROCm actually updates the start event when the associated kernel completes. * Currently, timing between startEvent and stopEvent does not include the time it takes to perform @@ -104,9 +104,9 @@ hipError_t hipHccModuleLaunchKernel(hipFunction_t f, uint32_t globalWorkSizeX, * the kernel launch. The event must be created before calling this API. * @param [in] stopEvent If non-null, specified event will be updated to track the stop time of * the kernel launch. The event must be created before calling this API. - * @param [in] flags. The value of hipExtAnyOrderLaunch, signifies if kernel can be + * @param [in] flags The value of hipExtAnyOrderLaunch, signifies if kernel can be * launched in any order. - * @returns hipSuccess, hipInvalidDevice, hipErrorNotInitialized, hipErrorInvalidValue. + * @returns #hipSuccess, #hipInvalidDeviceId, #hipErrorNotInitialized, #hipErrorInvalidValue. * */ extern "C" hipError_t hipExtLaunchKernel(const void* function_address, dim3 numBlocks, @@ -117,9 +117,9 @@ extern "C" hipError_t hipExtLaunchKernel(const void* function_address, dim3 numB /** * @brief Launches kernel with dimention parameters and shared memory on stream with templated kernel and arguments. * - * @param [in] f Kernel to launch. - * @param [in] numBlocks const number of blocks. - * @param [in] dimBlocks const dimension of a block. + * @param [in] kernel Kernel to launch. + * @param [in] numBlocks const number of blocks. + * @param [in] dimBlocks const dimension of a block. * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. * HIP-Clang compiler provides support for extern shared declarations. * @param [in] stream Stream where the kernel should be dispatched. @@ -128,10 +128,11 @@ extern "C" hipError_t hipExtLaunchKernel(const void* function_address, dim3 numB * the kernel launch. The event must be created before calling this API. * @param [in] stopEvent If non-null, specified event will be updated to track the stop time of * the kernel launch. The event must be created before calling this API. - * @param [in] flags. The value of hipExtAnyOrderLaunch, signifies if kernel can be + * @param [in] flags The value of hipExtAnyOrderLaunch, signifies if kernel can be * launched in any order. - * @param [in] args templated kernel arguments. - * @returns hipSuccess, hipInvalidDevice, hipErrorNotInitialized, hipErrorInvalidValue. + * @param [in] args templated kernel arguments. + * + * * Please refer to the application for sample usage at, * (https://github.com/ROCm-Developer-Tools/HIP/blob/rocm-4.5.x/tests/src/kernel/hipExtLaunchKernelGGL.cpp). */ diff --git a/projects/hip/include/hip/hip_runtime_api.h b/projects/hip/include/hip/hip_runtime_api.h index f49f7410b4..3a44460942 100644 --- a/projects/hip/include/hip/hip_runtime_api.h +++ b/projects/hip/include/hip/hip_runtime_api.h @@ -619,7 +619,10 @@ enum hipLimit_t { * most CPUs. It's a good option for data tranfer from host to device via mapped pinned memory.*/ #define hipHostMallocWriteCombined 0x4 -/** Host memory allocation will follow numa policy set by user.*/ +/** +* Host memory allocation will follow numa policy set by user. +* @note This numa allocation falg is applicable on Linux, under development on Windows. +*/ #define hipHostMallocNumaUser 0x20000000 /** Allocate coherent memory. Overrides HIP_COHERENT_HOST_ALLOC for specific allocation.*/ @@ -1495,7 +1498,7 @@ hipError_t hipDeviceGetP2PAttribute(int* value, hipDeviceP2PAttr attr, int srcDevice, int dstDevice); /** * @brief Returns a PCI Bus Id string for the device, overloaded to take int device ID. - * @param [out] pciBusId The string of PCI Bus Id format for the device + * @param [out] pciBusId The string of PCI Bus Id format for the device * @param [in] len Maximum length of string * @param [in] device The device ordinal * @@ -1505,7 +1508,7 @@ hipError_t hipDeviceGetPCIBusId(char* pciBusId, int len, int device); /** * @brief Returns a handle to a compute device. * @param [out] device The handle of the device - * @param [in] PCI The string of PCI Bus Id for the device + * @param [in] pciBusId The string of PCI Bus Id for the device * * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue */ @@ -1585,7 +1588,7 @@ hipError_t hipSetDevice(int deviceId); /** * @brief Return the default device id for the calling host thread. * - * @param [out] device *device is written with the default device + * @param [out] deviceId *device is written with the default device * * HIP maintains an default device for each thread using thread-local-storage. * This device is used implicitly for HIP runtime APIs called by this thread. @@ -1599,7 +1602,7 @@ hipError_t hipGetDevice(int* deviceId); /** * @brief Return number of compute-capable devices. * - * @param [output] count Returns number of compute-capable devices. + * @param [out] count Returns number of compute-capable devices. * * @returns #hipSuccess, #hipErrorNoDevice * @@ -1625,7 +1628,7 @@ hipError_t hipDeviceGetAttribute(int* pi, hipDeviceAttribute_t attr, int deviceI * @param [out] mem_pool Default memory pool to return * @param [in] device Device index for query the default memory pool * - * @returns #chipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, #hipErrorNotSupported + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, #hipErrorNotSupported * * @see hipDeviceGetDefaultMemPool, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess @@ -1837,10 +1840,12 @@ hipError_t hipExtGetLinkTypeAndHopCount(int device1, int device2, uint32_t* link * @param devPtr - Base pointer to previously allocated device memory * * @returns - * hipSuccess, - * hipErrorInvalidHandle, - * hipErrorOutOfMemory, - * hipErrorMapFailed, + * #hipSuccess + * #hipErrorInvalidHandle + * #hipErrorOutOfMemory + * #hipErrorMapFailed + * + * @note This IPC memory related feature API on Windows may behave differently from Linux. * */ hipError_t hipIpcGetMemHandle(hipIpcMemHandle_t* handle, void* devPtr); @@ -1871,14 +1876,15 @@ hipError_t hipIpcGetMemHandle(hipIpcMemHandle_t* handle, void* devPtr); * @param flags - Flags for this operation. Must be specified as hipIpcMemLazyEnablePeerAccess * * @returns - * hipSuccess, - * hipErrorMapFailed, - * hipErrorInvalidHandle, - * hipErrorTooManyPeers + * #hipSuccess, + * #hipErrorMapFailed, + * #hipErrorInvalidHandle, + * #hipErrorTooManyPeers * * @note During multiple processes, using the same memory handle opened by the current context, * there is no guarantee that the same device poiter will be returned in @p *devPtr. * This is diffrent from CUDA. + * @note This IPC memory related feature API on Windows may behave differently from Linux. * */ hipError_t hipIpcOpenMemHandle(void** devPtr, hipIpcMemHandle_t handle, unsigned int flags); @@ -1895,9 +1901,11 @@ hipError_t hipIpcOpenMemHandle(void** devPtr, hipIpcMemHandle_t handle, unsigned * @param devPtr - Device pointer returned by hipIpcOpenMemHandle * * @returns - * hipSuccess, - * hipErrorMapFailed, - * hipErrorInvalidHandle, + * #hipSuccess, + * #hipErrorMapFailed, + * #hipErrorInvalidHandle + * + * @note This IPC memory related feature API on Windows may behave differently from Linux. * */ hipError_t hipIpcCloseMemHandle(void* devPtr); @@ -1915,6 +1923,8 @@ hipError_t hipIpcCloseMemHandle(void* devPtr); * * @returns #hipSuccess, #hipErrorInvalidConfiguration, #hipErrorInvalidValue * + * @note This IPC event related feature API is currently applicable on Linux. + * */ hipError_t hipIpcGetEventHandle(hipIpcEventHandle_t* handle, hipEvent_t event); @@ -1932,6 +1942,8 @@ hipError_t hipIpcGetEventHandle(hipIpcEventHandle_t* handle, hipEvent_t event); * * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext * + * @note This IPC event related feature API is currently applicable on Linux. + * */ hipError_t hipIpcOpenEventHandle(hipEvent_t* event, hipIpcEventHandle_t handle); @@ -1963,7 +1975,8 @@ hipError_t hipFuncSetAttribute(const void* func, hipFuncAttribute attr, int valu /** * @brief Set Cache configuration for a specific function * - * @param [in] config Configuration to set + * @param [in] func Pointer of the function. + * @param [in] config Configuration to set. * * @returns #hipSuccess, #hipErrorNotInitialized * Note: AMD devices and some Nvidia GPUS do not support reconfigurable cache. This hint is ignored @@ -2040,7 +2053,7 @@ const char* hipGetErrorString(hipError_t hipError); * @brief Return hip error as text string form. * * @param [in] hipError Error code to convert to string. - * @param [out] const char pointer to the NULL-terminated error string + * @param [out] errorString char pointer to the NULL-terminated error string * @return #hipSuccess, #hipErrorInvalidValue * * @see hipGetErrorName, hipGetLastError, hipPeakAtLastError, hipError_t @@ -2050,7 +2063,7 @@ hipError_t hipDrvGetErrorName(hipError_t hipError, const char** errorString); * @brief Return handy text string message to explain the error which occurred * * @param [in] hipError Error code to convert to string. - * @param [out] const char pointer to the NULL-terminated error string + * @param [out] errorString char pointer to the NULL-terminated error string * @return #hipSuccess, #hipErrorInvalidValue * * @see hipGetErrorName, hipGetLastError, hipPeakAtLastError, hipError_t @@ -2242,7 +2255,7 @@ hipError_t hipStreamGetPriority(hipStream_t stream, int* priority); * @brief Get the device assocaited with the stream * * @param[in] stream stream to be queried - * @param[out] hipDevice_t device associated with the stream + * @param[out] device device associated with the stream * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorContextIsDestroyed, #hipErrorInvalidHandle, * #hipErrorNotInitialized, #hipErrorDeinitialized, #hipErrorInvalidContext * @@ -2666,6 +2679,16 @@ hipError_t hipPointerGetAttribute(void* data, hipPointer_attribute attribute, */ hipError_t hipDrvPointerGetAttributes(unsigned int numAttributes, hipPointer_attribute* attributes, void** data, hipDeviceptr_t ptr); +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup External External Resource Interoperability + * @{ + * @ingroup API + * + * This section describes the external resource interoperability functions of HIP runtime API. + * + */ /** * @brief Imports an external semaphore. * @@ -2765,6 +2788,10 @@ hipError_t hipDestroyExternalMemory(hipExternalMemory_t extMem); * @see hipMallocPitch, hipFree, hipMallocArray, hipFreeArray, hipMalloc3D, hipMalloc3DArray, * hipHostFree, hipHostMalloc */ + // end of external resource + /** + * @} + */ hipError_t hipMalloc(void** ptr, size_t size); /** * @brief Allocate memory on the default accelerator @@ -2827,10 +2854,13 @@ hipError_t hipHostMalloc(void** ptr, size_t size, unsigned int flags); /** *------------------------------------------------------------------------------------------------- *------------------------------------------------------------------------------------------------- - * @addtogroup MemoryM Managed Memory - * @{ + * @defgroup MemoryM Managed Memory + * * @ingroup Memory - * This section describes the managed memory management functions of HIP runtime API. + * @{ + * This section describes the managed memory management functions of HIP runtime API. + * + * @note The managed memory management APIs are implemented on Linux, under developement on Windows. * */ /** @@ -2842,6 +2872,7 @@ hipError_t hipHostMalloc(void** ptr, size_t size, unsigned int flags); * (defaults to hipMemAttachGlobal) * * @returns #hipSuccess, #hipErrorMemoryAllocation, #hipErrorNotSupported, #hipErrorInvalidValue + * */ hipError_t hipMallocManaged(void** dev_ptr, size_t size, @@ -2855,6 +2886,8 @@ hipError_t hipMallocManaged(void** dev_ptr, * @param [in] stream stream to enqueue prefetch operation * * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPrefetchAsync(const void* dev_ptr, size_t count, @@ -2869,6 +2902,8 @@ hipError_t hipMemPrefetchAsync(const void* dev_ptr, * @param [in] device device to apply the advice for * * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemAdvise(const void* dev_ptr, size_t count, @@ -2885,6 +2920,8 @@ hipError_t hipMemAdvise(const void* dev_ptr, * @param [in] count size of the range to query * * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemRangeGetAttribute(void* data, size_t data_size, @@ -2904,6 +2941,8 @@ hipError_t hipMemRangeGetAttribute(void* data, * @param [in] count size of the range to query * * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemRangeGetAttributes(void** data, size_t* data_sizes, @@ -2922,6 +2961,8 @@ hipError_t hipMemRangeGetAttributes(void** data, * hipMemAttachSingle (defaults to hipMemAttachSingle) * * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipStreamAttachMemAsync(hipStream_t stream, void* dev_ptr, @@ -2935,7 +2976,7 @@ hipError_t hipStreamAttachMemAsync(hipStream_t stream, /** *------------------------------------------------------------------------------------------------- *------------------------------------------------------------------------------------------------- - * @addtogroup StreamO Ordered Memory Allocator + * @defgroup StreamO Stream Ordered Memory Allocator * @{ * @ingroup Memory * This section describes Stream Ordered Memory Allocator functions of HIP runtime API. @@ -2952,6 +2993,8 @@ hipError_t hipStreamAttachMemAsync(hipStream_t stream, * the temporal guarantee. Whether or not a device supports the integrated stream ordered memory * allocator may be queried by calling @p hipDeviceGetAttribute with the device attribute * @p hipDeviceAttributeMemoryPoolsSupported + * + * @note APIs in this section are implemented on Linux, under development on Windows. */ /** @@ -2982,6 +3025,8 @@ hipError_t hipStreamAttachMemAsync(hipStream_t stream, * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMallocAsync(void** dev_ptr, size_t size, hipStream_t stream); /** @@ -2998,13 +3043,15 @@ hipError_t hipMallocAsync(void** dev_ptr, size_t size, hipStream_t stream); * @param [in] dev_ptr Pointer to device memory to free * @param [in] stream The stream, where the destruciton will occur according to the execution order * - * @returns hipSuccess, hipErrorInvalidValue, hipErrorNotSupported + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * * @see hipMallocFromPoolAsync, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipFreeAsync(void* dev_ptr, hipStream_t stream); /** @@ -3031,6 +3078,8 @@ hipError_t hipFreeAsync(void* dev_ptr, hipStream_t stream); * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolTrimTo(hipMemPool_t mem_pool, size_t min_bytes_to_hold); /** @@ -3068,6 +3117,8 @@ hipError_t hipMemPoolTrimTo(hipMemPool_t mem_pool, size_t min_bytes_to_hold); * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolSetAttribute(hipMemPool_t mem_pool, hipMemPoolAttr attr, void* value); /** @@ -3105,6 +3156,8 @@ hipError_t hipMemPoolSetAttribute(hipMemPool_t mem_pool, hipMemPoolAttr attr, vo * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolGetAttribute(hipMemPool_t mem_pool, hipMemPoolAttr attr, void* value); /** @@ -3121,6 +3174,8 @@ hipError_t hipMemPoolGetAttribute(hipMemPool_t mem_pool, hipMemPoolAttr attr, vo * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolSetAccess(hipMemPool_t mem_pool, const hipMemAccessDesc* desc_list, size_t count); /** @@ -3139,6 +3194,8 @@ hipError_t hipMemPoolSetAccess(hipMemPool_t mem_pool, const hipMemAccessDesc* de * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolGetAccess(hipMemAccessFlags* flags, hipMemPool_t mem_pool, hipMemLocation* location); /** @@ -3161,6 +3218,8 @@ hipError_t hipMemPoolGetAccess(hipMemAccessFlags* flags, hipMemPool_t mem_pool, * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolCreate(hipMemPool_t* mem_pool, const hipMemPoolProps* pool_props); /** @@ -3186,6 +3245,8 @@ hipError_t hipMemPoolCreate(hipMemPool_t* mem_pool, const hipMemPoolProps* pool_ * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolDestroy(hipMemPool_t mem_pool); /** @@ -3218,6 +3279,8 @@ hipError_t hipMemPoolDestroy(hipMemPool_t mem_pool); * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMallocFromPoolAsync(void** dev_ptr, size_t size, hipMemPool_t mem_pool, hipStream_t stream); /** @@ -3243,6 +3306,8 @@ hipError_t hipMallocFromPoolAsync(void** dev_ptr, size_t size, hipMemPool_t mem_ * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolExportToShareableHandle( void* shared_handle, @@ -3269,6 +3334,8 @@ hipError_t hipMemPoolExportToShareableHandle( * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolImportFromShareableHandle( hipMemPool_t* mem_pool, @@ -3291,6 +3358,8 @@ hipError_t hipMemPoolImportFromShareableHandle( * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolExportPointer(hipMemPoolPtrExportData* export_data, void* dev_ptr); /** @@ -3318,6 +3387,8 @@ hipError_t hipMemPoolExportPointer(hipMemPoolPtrExportData* export_data, void* d * * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemPoolImportPointer( void** dev_ptr, @@ -3511,7 +3582,7 @@ hipError_t hipHostFree(void* ptr); * @param[in] src Data being copy from * @param[in] sizeBytes Data size in bytes * @param[in] copyType Memory copy type - * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryFree, #hipErrorUnknowni + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryFree, #hipErrorUnknown * * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, @@ -3521,7 +3592,20 @@ hipError_t hipHostFree(void* ptr); * hipMemHostAlloc, hipMemHostGetDevicePointer */ hipError_t hipMemcpy(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind); -// TODO: Add description +/** + * @brief Memory copy on the stream. + * It allows single or multiple devices to do memory copy on single or multiple streams. + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] copyType Memory copy type + * @param[in] stream Valid stream + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryFree, #hipErrorUnknown, #hipErrorContextIsDestroyed + * + * @see hipMemcpy, hipStreamCreate, hipStreamSynchronize, hipStreamDestroy, hipSetDevice, hipLaunchKernelGGL + * + */ hipError_t hipMemcpyWithStream(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind, hipStream_t stream); /** @@ -3932,14 +4016,25 @@ hipError_t hipMemset3DAsync(hipPitchedPtr pitchedDevPtr, int value, hipExtent e * @warning On Windows, the free memory only accounts for memory allocated by this process and may * be optimistic. * - * @param[out] free returns free memory on the current device in bytes - * @param[out] total returns total allocatable memory on the current device in bytes + * @param[out] free Returns free memory on the current device in bytes + * @param[out] total Returns total allocatable memory on the current device in bytes * * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue * **/ hipError_t hipMemGetInfo(size_t* free, size_t* total); +/** + * @brief Get allocated memory size via memory pointer. + * + * This function gets the allocated shared virtual memory size from memory pointer. + * + * @param[in] ptr Pointer to allocated memory + * @param[out] size Returns the allocated memory size in bytes + * + * @return #hipSuccess, #hipErrorInvalidValue + * + **/ hipError_t hipMemPtrGetInfo(void* ptr, size_t* size); /** * @brief Allocate an array on the device. @@ -3955,9 +4050,48 @@ hipError_t hipMemPtrGetInfo(void* ptr, size_t* size); */ hipError_t hipMallocArray(hipArray** array, const hipChannelFormatDesc* desc, size_t width, size_t height __dparm(0), unsigned int flags __dparm(hipArrayDefault)); +/** + * @brief Create an array memory pointer on the device. + * + * @param[out] pHandle Pointer to the array memory + * @param[in] pAllocateArray Requested array desciptor + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocArray, hipArrayDestroy, hipFreeArray + */ hipError_t hipArrayCreate(hipArray** pHandle, const HIP_ARRAY_DESCRIPTOR* pAllocateArray); + /** + * @brief Destroy an array memory pointer on the device. + * + * @param[in] array Pointer to the array memory + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipFreeArray + */ hipError_t hipArrayDestroy(hipArray* array); +/** + * @brief Create a 3D array memory pointer on the device. + * + * @param[out] array Pointer to the 3D array memory + * @param[in] pAllocateArray Requested array desciptor + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocArray, hipArrayDestroy, hipFreeArray + */ hipError_t hipArray3DCreate(hipArray** array, const HIP_ARRAY3D_DESCRIPTOR* pAllocateArray); +/** + * @brief Create a 3D memory pointer on the device. + * + * @param[out] pitchedDevPtr Pointer to the 3D memory + * @param[in] extent Requested extent + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocPitch, hipMemGetInfo, hipFree + */ hipError_t hipMalloc3D(hipPitchedPtr* pitchedDevPtr, hipExtent extent); /** * @brief Frees an array on the device. @@ -4436,16 +4570,18 @@ hipError_t hipMemcpyPeerAsync(void* dst, int dstDeviceId, const void* src, int s * This section describes the deprecated context management functions of HIP runtime API. */ /** - * @brief Create a context and set it as current/ default context + * @brief Create a context and set it as current/default context * - * @param [out] ctx - * @param [in] flags - * @param [in] associated device handle + * @param [out] ctx Context to create + * @param [in] flags Context creation flags + * @param [in] device device handle * * @return #hipSuccess * * @see hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, hipCtxPushCurrent, * hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxCreate(hipCtx_t* ctx, unsigned int flags, hipDevice_t device); @@ -4458,6 +4594,8 @@ hipError_t hipCtxCreate(hipCtx_t* ctx, unsigned int flags, hipDevice_t device); * * @see hipCtxCreate, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent,hipCtxSetCurrent, * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxDestroy(hipCtx_t ctx); @@ -4470,6 +4608,8 @@ hipError_t hipCtxDestroy(hipCtx_t ctx); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxSetCurrent, hipCtxGetCurrent, * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxPopCurrent(hipCtx_t* ctx); @@ -4482,6 +4622,8 @@ hipError_t hipCtxPopCurrent(hipCtx_t* ctx); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxPushCurrent(hipCtx_t ctx); @@ -4494,6 +4636,8 @@ hipError_t hipCtxPushCurrent(hipCtx_t ctx); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxSetCurrent(hipCtx_t ctx); @@ -4506,6 +4650,8 @@ hipError_t hipCtxSetCurrent(hipCtx_t ctx); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetDevice, hipCtxGetFlags, hipCtxPopCurrent, * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxGetCurrent(hipCtx_t* ctx); @@ -4518,6 +4664,8 @@ hipError_t hipCtxGetCurrent(hipCtx_t* ctx); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxGetDevice(hipDevice_t* device); @@ -4537,13 +4685,15 @@ hipError_t hipCtxGetDevice(hipDevice_t* device); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetDevice, hipCtxGetFlags, hipCtxPopCurrent, * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxGetApiVersion(hipCtx_t ctx, int* apiVersion); /** - * @brief Set Cache configuration for a specific function + * @brief Get Cache configuration for a specific function * - * @param [out] cacheConfiguration + * @param [out] cacheConfig Cache configuration * * @return #hipSuccess * @@ -4552,13 +4702,15 @@ hipError_t hipCtxGetApiVersion(hipCtx_t ctx, int* apiVersion); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxGetCacheConfig(hipFuncCache_t* cacheConfig); /** * @brief Set L1/Shared cache partition. * - * @param [in] cacheConfiguration + * @param [in] cacheConfig Cache configuration to set * * @return #hipSuccess * @@ -4567,13 +4719,15 @@ hipError_t hipCtxGetCacheConfig(hipFuncCache_t* cacheConfig); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxSetCacheConfig(hipFuncCache_t cacheConfig); /** * @brief Set Shared memory bank configuration. * - * @param [in] sharedMemoryConfiguration + * @param [in] config Shared memory configuration to set * * @return #hipSuccess * @@ -4582,13 +4736,15 @@ hipError_t hipCtxSetCacheConfig(hipFuncCache_t cacheConfig); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxSetSharedMemConfig(hipSharedMemConfig config); /** * @brief Get Shared memory bank configuration. * - * @param [out] sharedMemoryConfiguration + * @param [out] pConfig Pointer of shared memory configuration * * @return #hipSuccess * @@ -4597,6 +4753,8 @@ hipError_t hipCtxSetSharedMemConfig(hipSharedMemConfig config); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxGetSharedMemConfig(hipSharedMemConfig* pConfig); @@ -4610,18 +4768,22 @@ hipError_t hipCtxGetSharedMemConfig(hipSharedMemConfig* pConfig); * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxSynchronize(void); /** * @brief Return flags used for creating default context. * - * @param [out] flags + * @param [out] flags Pointer of flags * * @returns #hipSuccess * * @see hipCtxCreate, hipCtxDestroy, hipCtxPopCurrent, hipCtxGetCurrent, hipCtxGetCurrent, * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxGetFlags(unsigned int* flags); @@ -4634,8 +4796,8 @@ hipError_t hipCtxGetFlags(unsigned int* flags); * accessible from the current device until a call to hipDeviceDisablePeerAccess or hipDeviceReset. * * - * @param [in] peerCtx - * @param [in] flags + * @param [in] peerCtx Peer context + * @param [in] flags flags, need to set as 0 * * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, * #hipErrorPeerAccessAlreadyEnabled @@ -4643,6 +4805,8 @@ hipError_t hipCtxGetFlags(unsigned int* flags); * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice * @warning PeerToPeer support is experimental. + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxEnablePeerAccess(hipCtx_t peerCtx, unsigned int flags); @@ -4651,16 +4815,18 @@ hipError_t hipCtxEnablePeerAccess(hipCtx_t peerCtx, unsigned int flags); * physically located on a peer context.Disables direct access to memory allocations in a peer * context and unregisters any registered allocations. * - * Returns hipErrorPeerAccessNotEnabled if direct access to memory on peerDevice has not yet been + * Returns #hipErrorPeerAccessNotEnabled if direct access to memory on peerDevice has not yet been * enabled from the current device. * - * @param [in] peerCtx + * @param [in] peerCtx Peer context to be disabled * * @returns #hipSuccess, #hipErrorPeerAccessNotEnabled * * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice * @warning PeerToPeer support is experimental. + * + * @warning : This HIP API is deprecated. */ DEPRECATED(DEPRECATED_MSG) hipError_t hipCtxDisablePeerAccess(hipCtx_t peerCtx); @@ -4671,9 +4837,9 @@ hipError_t hipCtxDisablePeerAccess(hipCtx_t peerCtx); /** * @brief Get the state of the primary context. * - * @param [in] Device to get primary context flags for - * @param [out] Pointer to store flags - * @param [out] Pointer to store context state; 0 = inactive, 1 = active + * @param [in] dev Device to get primary context flags for + * @param [out] flags Pointer to store flags + * @param [out] active Pointer to store context state; 0 = inactive, 1 = active * * @returns #hipSuccess * @@ -4684,7 +4850,7 @@ hipError_t hipDevicePrimaryCtxGetState(hipDevice_t dev, unsigned int* flags, int /** * @brief Release the primary context on the GPU. * - * @param [in] Device which primary context is released + * @param [in] dev Device which primary context is released * * @returns #hipSuccess * @@ -4697,8 +4863,9 @@ hipError_t hipDevicePrimaryCtxRelease(hipDevice_t dev); /** * @brief Retain the primary context on the GPU. * - * @param [out] Returned context handle of the new context - * @param [in] Device which primary context is released +hipError_t hipDevicePrimaryCtxRetain(hipCtx_t* pctx, hipDevice_t dev); + * @param [out] pctx Returned context handle of the new context + * @param [in] dev Device which primary context is released * * @returns #hipSuccess * @@ -4709,7 +4876,7 @@ hipError_t hipDevicePrimaryCtxRetain(hipCtx_t* pctx, hipDevice_t dev); /** * @brief Resets the primary context on the GPU. * - * @param [in] Device which primary context is reset + * @param [in] dev Device which primary context is reset * * @returns #hipSuccess * @@ -4720,8 +4887,8 @@ hipError_t hipDevicePrimaryCtxReset(hipDevice_t dev); /** * @brief Set flags for the primary context. * - * @param [in] Device for which the primary context flags are set - * @param [in] New flags for the device + * @param [in] dev Device for which the primary context flags are set + * @param [in] flags New flags for the device * * @returns #hipSuccess, #hipErrorContextAlreadyInUse * @@ -4734,74 +4901,77 @@ hipError_t hipDevicePrimaryCtxSetFlags(hipDevice_t dev, unsigned int flags); * @} */ /** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- * * @defgroup Module Module Management * @{ + * @ingroup API * This section describes the module management functions of HIP runtime API. * */ /** - * @brief Loads code object from file into a hipModule_t + * @brief Loads code object from file into a module the currrent context. * - * @param [in] fname - * @param [out] module + * @param [in] fname Filename of code object to load + + * @param [out] module Module * * @warning File/memory resources allocated in this function are released only in hipModuleUnload. * - * @returns hipSuccess, hipErrorInvalidValue, hipErrorInvalidContext, hipErrorFileNotFound, - * hipErrorOutOfMemory, hipErrorSharedObjectInitFailed, hipErrorNotInitialized - * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext, #hipErrorFileNotFound, + * #hipErrorOutOfMemory, #hipErrorSharedObjectInitFailed, #hipErrorNotInitialized * */ hipError_t hipModuleLoad(hipModule_t* module, const char* fname); /** * @brief Frees the module * - * @param [in] module + * @param [in] module Module to free * - * @returns hipSuccess, hipInvalidValue - * module is freed and the code objects associated with it are destroyed + * @returns #hipSuccess, #hipErrorInvalidResourceHandle * + * The module is freed, and the code objects associated with it are destroyed. */ hipError_t hipModuleUnload(hipModule_t module); /** * @brief Function with kname will be extracted if present in module * - * @param [in] module - * @param [in] kname - * @param [out] function + * @param [in] module Module to get function from + * @param [in] kname Pointer to the name of function + * @param [out] function Pointer to function handle * - * @returns hipSuccess, hipErrorInvalidValue, hipErrorInvalidContext, hipErrorNotInitialized, - * hipErrorNotFound, + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext, #hipErrorNotInitialized, + * #hipErrorNotFound, */ hipError_t hipModuleGetFunction(hipFunction_t* function, hipModule_t module, const char* kname); /** * @brief Find out attributes for a given function. * - * @param [out] attr - * @param [in] func + * @param [out] attr Attributes of funtion + * @param [in] func Pointer to the function handle * - * @returns hipSuccess, hipErrorInvalidValue, hipErrorInvalidDeviceFunction + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDeviceFunction */ hipError_t hipFuncGetAttributes(struct hipFuncAttributes* attr, const void* func); /** * @brief Find out a specific attribute for a given function. * - * @param [out] value - * @param [in] attrib - * @param [in] hfunc + * @param [out] value Pointer to the value + * @param [in] attrib Attributes of the given funtion + * @param [in] hfunc Function to get attributes from * - * @returns hipSuccess, hipErrorInvalidValue, hipErrorInvalidDeviceFunction + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDeviceFunction */ hipError_t hipFuncGetAttribute(int* value, hipFunction_attribute attrib, hipFunction_t hfunc); /** * @brief returns the handle of the texture reference with the name from the module. * - * @param [in] hmod - * @param [in] name - * @param [out] texRef + * @param [in] hmod Module + * @param [in] name Pointer of name of texture reference + * @param [out] texRef Pointer of texture reference * - * @returns hipSuccess, hipErrorNotInitialized, hipErrorNotFound, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorNotFound, #hipErrorInvalidValue */ hipError_t hipModuleGetTexRef(textureReference** texRef, hipModule_t hmod, const char* name); /** @@ -4958,8 +5128,10 @@ hipError_t hipExtLaunchMultiKernelMultiDevice(hipLaunchParams* launchParamsList, /** * @} */ + /** - * + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- * @defgroup Occupancy Occupancy * @{ * This section describes the occupancy functions of HIP runtime API. @@ -5267,7 +5439,7 @@ hipError_t hipExtLaunchKernel(const void* function_address, dim3 numBlocks, dim3 * @param [in] mipmappedArray memory mipmapped array on the device * @param [in] desc opointer to the channel format * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue * */ hipError_t hipBindTextureToMipmappedArray( @@ -5283,7 +5455,7 @@ hipError_t hipBindTextureToMipmappedArray( * @param [in] pTexDesc pointer to texture descriptor * @param [in] pResViewDesc pointer to resource view descriptor * - * @returns hipSuccess, hipErrorInvalidValue, hipErrorNotSupported, hipErrorOutOfMemory + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported, #hipErrorOutOfMemory * * @note 3D liner filter isn't supported on GFX90A boards, on which the API @p hipCreateTextureObject will * return hipErrorNotSupported. @@ -5300,7 +5472,7 @@ hipError_t hipCreateTextureObject( * * @param [in] textureObject texture object to destroy * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue * */ hipError_t hipDestroyTextureObject(hipTextureObject_t textureObject); @@ -5311,7 +5483,7 @@ hipError_t hipDestroyTextureObject(hipTextureObject_t textureObject); * @param [in] desc pointer to channel format descriptor * @param [out] array memory array on the device * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue * */ hipError_t hipGetChannelDesc( @@ -5324,7 +5496,7 @@ hipError_t hipGetChannelDesc( * @param [out] pResDesc pointer to resource descriptor * @param [in] textureObject texture object * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue * */ hipError_t hipGetTextureObjectResourceDesc( @@ -5337,7 +5509,7 @@ hipError_t hipGetTextureObjectResourceDesc( * @param [out] pResViewDesc pointer to resource view descriptor * @param [in] textureObject texture object * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue * */ hipError_t hipGetTextureObjectResourceViewDesc( @@ -5350,7 +5522,7 @@ hipError_t hipGetTextureObjectResourceViewDesc( * @param [out] pTexDesc pointer to texture descriptor * @param [in] textureObject texture object * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue * */ hipError_t hipGetTextureObjectTextureDesc( @@ -5365,7 +5537,7 @@ hipError_t hipGetTextureObjectTextureDesc( * @param [in] pTexDesc pointer to texture descriptor * @param [in] pResViewDesc pointer to resource view descriptor * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue * */ hipError_t hipTexObjectCreate( @@ -5379,7 +5551,7 @@ hipError_t hipTexObjectCreate( * * @param [in] texObject texture object to destroy * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue * */ hipError_t hipTexObjectDestroy( @@ -5391,7 +5563,7 @@ hipError_t hipTexObjectDestroy( * @param [out] pResDesc pointer to resource descriptor * @param [in] texObject texture object * - * @returns hipSuccess, hipErrorNotSupported, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue * */ hipError_t hipTexObjectGetResourceDesc( @@ -5404,7 +5576,7 @@ hipError_t hipTexObjectGetResourceDesc( * @param [out] pResViewDesc pointer to resource view descriptor * @param [in] texObject texture object * - * @returns hipSuccess, hipErrorNotSupported, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue * */ hipError_t hipTexObjectGetResourceViewDesc( @@ -5417,7 +5589,7 @@ hipError_t hipTexObjectGetResourceViewDesc( * @param [out] pTexDesc pointer to texture descriptor * @param [in] texObject texture object * - * @returns hipSuccess, hipErrorNotSupported, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue * */ hipError_t hipTexObjectGetTextureDesc( @@ -5437,37 +5609,106 @@ hipError_t hipTexObjectGetTextureDesc( * @param [out] texref texture reference * @param [in] symbol pointer to the symbol related with the texture for the reference * - * @returns hipSuccess, hipErrorInvalidValue + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. * */ DEPRECATED(DEPRECATED_MSG) hipError_t hipGetTextureReference( const textureReference** texref, const void* symbol); - +/** + * @brief Sets address mode for a texture reference. + * + * @param [in] texRef texture reference. + * @param [in] dim Dimension of the texture. + * @param [in] am Value of the texture address mode. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetAddressMode( textureReference* texRef, int dim, enum hipTextureAddressMode am); +/** + * @brief Binds an array as a texture reference. + * + * @param [in] tex Pointer texture reference. + * @param [in] array Array to bind. + * @param [in] flags Flags should be set as HIP_TRSA_OVERRIDE_FORMAT, as a valid value. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetArray( textureReference* tex, hipArray_const_t array, unsigned int flags); +/** + * @brief Set filter mode for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] fm Value of texture filter mode. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetFilterMode( textureReference* texRef, enum hipTextureFilterMode fm); +/** + * @brief Set flags for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] Flags Value of flags. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetFlags( textureReference* texRef, unsigned int Flags); +/** + * @brief Set format for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] fmt Value of format. + * @param [in] NumPackedComponents Number of components per array. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetFormat( textureReference* texRef, hipArray_Format fmt, int NumPackedComponents); +/** + * @brief Binds a memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] desc Pointer of channel format descriptor. + * @param [in] size Size of memory in bites. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipBindTexture( size_t* offset, @@ -5475,6 +5716,20 @@ hipError_t hipBindTexture( const void* devPtr, const hipChannelFormatDesc* desc, size_t size __dparm(UINT_MAX)); +/** + * @brief Binds a 2D memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] desc Pointer of channel format descriptor. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipBindTexture2D( size_t* offset, @@ -5484,93 +5739,291 @@ hipError_t hipBindTexture2D( size_t width, size_t height, size_t pitch); +/** + * @brief Binds a memory area to a texture. + * + * @param [in] tex Pointer of texture reference. + * @param [in] array Array to bind. + * @param [in] desc Pointer of channel format descriptor. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipBindTextureToArray( const textureReference* tex, hipArray_const_t array, const hipChannelFormatDesc* desc); +/** + * @brief Get the offset of the alignment in a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] texref Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipGetTextureAlignmentOffset( size_t* offset, const textureReference* texref); +/** + * @brief Unbinds a texture. + * + * @param [in] tex Texture to unbind. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipUnbindTexture(const textureReference* tex); +/** + * @brief Gets the the address for a texture reference. + * + * @param [out] dev_ptr Pointer of device address. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetAddress( hipDeviceptr_t* dev_ptr, const textureReference* texRef); +/** + * @brief Gets the address mode for a texture reference. + * + * @param [out] pam Pointer of address mode. + * @param [in] texRef Pointer of texture reference. + * @param [in] dim Dimension. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetAddressMode( enum hipTextureAddressMode* pam, const textureReference* texRef, int dim); +/** + * @brief Gets filter mode for a texture reference. + * + * @param [out] pfm Pointer of filter mode. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetFilterMode( enum hipTextureFilterMode* pfm, const textureReference* texRef); +/** + * @brief Gets flags for a texture reference. + * + * @param [out] pFlags Pointer of flags. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetFlags( unsigned int* pFlags, const textureReference* texRef); +/** + * @brief Gets texture format for a texture reference. + * + * @param [out] pFormat Pointer of the format. + * @param [out] pNumChannels Pointer of number of channels. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetFormat( hipArray_Format* pFormat, int* pNumChannels, const textureReference* texRef); +/** + * @brief Gets the maximum anisotropy for a texture reference. + * + * @param [out] pmaxAnsio Pointer of the maximum anisotropy. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetMaxAnisotropy( int* pmaxAnsio, const textureReference* texRef); +/** + * @brief Gets the mipmap filter mode for a texture reference. + * + * @param [out] pfm Pointer of the mipmap filter mode. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetMipmapFilterMode( enum hipTextureFilterMode* pfm, const textureReference* texRef); DEPRECATED(DEPRECATED_MSG) +/** + * @brief Gets the mipmap level bias for a texture reference. + * + * @param [out] pbias Pointer of the mipmap level bias. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ hipError_t hipTexRefGetMipmapLevelBias( float* pbias, const textureReference* texRef); +/** + * @brief Gets the minimum and maximum mipmap level clamps for a texture reference. + * + * @param [out] pminMipmapLevelClamp Pointer of the minimum mipmap level clamp. + * @param [out] pmaxMipmapLevelClamp Pointer of the maximum mipmap level clamp. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetMipmapLevelClamp( float* pminMipmapLevelClamp, float* pmaxMipmapLevelClamp, const textureReference* texRef); +/** + * @brief Gets the mipmapped array bound to a texture reference. + * + * @param [out] pArray Pointer of the mipmapped array. + * @param [in] texRef Pointer of texture reference. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefGetMipMappedArray( hipMipmappedArray_t* pArray, const textureReference* texRef); +/** + * @brief Sets an bound address for a texture reference. + * + * @param [out] ByteOffset Pointer of the offset in bytes. + * @param [in] texRef Pointer of texture reference. + * @param [in] dptr Pointer of device address to bind. + * @param [in] bytes Size in bytes. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetAddress( size_t* ByteOffset, textureReference* texRef, hipDeviceptr_t dptr, size_t bytes); +/** + * @brief Set a bind an address as a 2D texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] desc Pointer of array descriptor. + * @param [in] dptr Pointer of device address to bind. + * @param [in] Pitch Pitch in bytes. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetAddress2D( textureReference* texRef, const HIP_ARRAY_DESCRIPTOR* desc, hipDeviceptr_t dptr, size_t Pitch); +/** + * @brief Sets the maximum anisotropy for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [out] maxAniso Value of the maximum anisotropy. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetMaxAnisotropy( textureReference* texRef, unsigned int maxAniso); - DEPRECATED(DEPRECATED_MSG) +/** + * @brief Sets border color for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] pBorderColor Pointer of border color. + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetBorderColor( textureReference* texRef, float* pBorderColor); +/** + * @brief Sets mipmap filter mode for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] fm Value of filter mode. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetMipmapFilterMode( textureReference* texRef, enum hipTextureFilterMode fm); +/** + * @brief Sets mipmap level bias for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] bias Value of mipmap bias. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetMipmapLevelBias( textureReference* texRef, float bias); +/** + * @brief Sets mipmap level clamp for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] minMipMapLevelClamp Value of minimum mipmap level clamp. + * @param [in] maxMipMapLevelClamp Value of maximum mipmap level clamp. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetMipmapLevelClamp( textureReference* texRef, float minMipMapLevelClamp, float maxMipMapLevelClamp); +/** + * @brief Binds mipmapped array to a texture reference. + * + * @param [in] texRef Pointer of texture reference to bind. + * @param [in] mipmappedArray Pointer of mipmapped array to bind. + * @param [in] Flags Flags should be set as HIP_TRSA_OVERRIDE_FORMAT, as a valid value. + * + * @warning This API is deprecated. + * + */ DEPRECATED(DEPRECATED_MSG) hipError_t hipTexRefSetMipmappedArray( textureReference* texRef, @@ -5590,13 +6043,39 @@ hipError_t hipTexRefSetMipmappedArray( * @ingroup Texture * This section describes the texture management functions currently unsupported in HIP runtime. */ - +/** + * @brief Create a mipmapped array. + * + * @param [out] pHandle pointer to mipmapped array + * @param [in] pMipmappedArrayDesc mipmapped array descriptor + * @param [in] numMipmapLevels mipmap level + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ hipError_t hipMipmappedArrayCreate( hipMipmappedArray_t* pHandle, HIP_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, unsigned int numMipmapLevels); -hipError_t hipMipmappedArrayDestroy( - hipMipmappedArray_t hMipmappedArray); +/** + * @brief Destroy a mipmapped array. + * + * @param [out] hMipmappedArray pointer to mipmapped array to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMipmappedArrayDestroy(hipMipmappedArray_t hMipmappedArray); +/** + * @brief Get a mipmapped array on a mipmapped level. + * + * @param [in] pLevelArray Pointer of array + * @param [out] hMipMappedArray Pointer of mipmapped array on the requested mipmap level + * @param [out] level Mipmap level + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ hipError_t hipMipmappedArrayGetLevel( hipArray_t* pLevelArray, hipMipmappedArray_t hMipMappedArray, @@ -5631,9 +6110,42 @@ hipError_t hipMipmappedArrayGetLevel( * @{ * This section describes the callback/Activity of HIP runtime API. */ +/** + * @brief Returns HIP API name by ID. + * + * @param [in] id ID of HIP API + * + * @returns hipSuccess, hipErrorInvalidValue + * + */ const char* hipApiName(uint32_t id); +/** + * @brief Returns kernel name reference by function name. + * + * @param [in] f name of function + * + * @returns hipSuccess, hipErrorInvalidValue + * + */ const char* hipKernelNameRef(const hipFunction_t f); +/** + * @brief Retrives kernel for a given host pointer, unless stated otherwise. + * + * @param [in] hostFunction Pointer of host function. + * @param [in] stream stream the kernel is executed on. + * + * @returns hipSuccess, hipErrorInvalidValue + * + */ const char* hipKernelNameRefByPtr(const void* hostFunction, hipStream_t stream); +/** + * @brief Returns device ID on the stream. + * + * @param [in] stream stream of device executed on. + * + * @returns hipSuccess, hipErrorInvalidValue + * + */ int hipGetStreamDeviceId(hipStream_t stream); // doxygen end Callback @@ -6026,7 +6538,7 @@ hipError_t hipGraphUpload(hipGraphExec_t graphExec, hipStream_t stream); /** * @brief Destroys an executable graph * - * @param [in] pGraphExec - instance of executable graph to destry. + * @param [in] graphExec - instance of executable graph to destry. * * @returns #hipSuccess. * @@ -6840,6 +7352,9 @@ hipError_t hipGraphNodeGetEnabled(hipGraphExec_t hGraphExec, hipGraphNode_t hNod * @defgroup Virtual Virtual Memory Management * @{ * This section describes the virtual memory management functions of HIP runtime API. + * + * @note Please note, the virtual memory management functions of HIP runtime API are implemented + * on Linux, under development on Windows. */ /** @@ -6850,6 +7365,8 @@ hipError_t hipGraphNodeGetEnabled(hipGraphExec_t hGraphExec, hipGraphNode_t hNod * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemAddressFree(void* devPtr, size_t size); @@ -6864,6 +7381,8 @@ hipError_t hipMemAddressFree(void* devPtr, size_t size); * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemAddressReserve(void** ptr, size_t size, size_t alignment, void* addr, unsigned long long flags); @@ -6877,6 +7396,8 @@ hipError_t hipMemAddressReserve(void** ptr, size_t size, size_t alignment, void* * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemCreate(hipMemGenericAllocationHandle_t* handle, size_t size, const hipMemAllocationProp* prop, unsigned long long flags); @@ -6890,6 +7411,8 @@ hipError_t hipMemCreate(hipMemGenericAllocationHandle_t* handle, size_t size, co * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemExportToShareableHandle(void* shareableHandle, hipMemGenericAllocationHandle_t handle, hipMemAllocationHandleType handleType, unsigned long long flags); @@ -6902,6 +7425,8 @@ hipError_t hipMemExportToShareableHandle(void* shareableHandle, hipMemGenericAll * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemGetAccess(unsigned long long* flags, const hipMemLocation* location, void* ptr); @@ -6914,6 +7439,9 @@ hipError_t hipMemGetAccess(unsigned long long* flags, const hipMemLocation* loca * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + * */ hipError_t hipMemGetAllocationGranularity(size_t* granularity, const hipMemAllocationProp* prop, hipMemAllocationGranularity_flags option); @@ -6925,6 +7453,8 @@ hipError_t hipMemGetAllocationGranularity(size_t* granularity, const hipMemAlloc * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux under development on Windows. */ hipError_t hipMemGetAllocationPropertiesFromHandle(hipMemAllocationProp* prop, hipMemGenericAllocationHandle_t handle); @@ -6937,6 +7467,8 @@ hipError_t hipMemGetAllocationPropertiesFromHandle(hipMemAllocationProp* prop, h * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemImportFromShareableHandle(hipMemGenericAllocationHandle_t* handle, void* osHandle, hipMemAllocationHandleType shHandleType); @@ -6951,6 +7483,8 @@ hipError_t hipMemImportFromShareableHandle(hipMemGenericAllocationHandle_t* hand * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemMap(void* ptr, size_t size, size_t offset, hipMemGenericAllocationHandle_t handle, unsigned long long flags); @@ -6963,6 +7497,8 @@ hipError_t hipMemMap(void* ptr, size_t size, size_t offset, hipMemGenericAllocat * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemMapArrayAsync(hipArrayMapInfo* mapInfoList, unsigned int count, hipStream_t stream); @@ -6973,6 +7509,8 @@ hipError_t hipMemMapArrayAsync(hipArrayMapInfo* mapInfoList, unsigned int count * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemRelease(hipMemGenericAllocationHandle_t handle); @@ -6984,6 +7522,8 @@ hipError_t hipMemRelease(hipMemGenericAllocationHandle_t handle); * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemRetainAllocationHandle(hipMemGenericAllocationHandle_t* handle, void* addr); @@ -6997,6 +7537,8 @@ hipError_t hipMemRetainAllocationHandle(hipMemGenericAllocationHandle_t* handle, * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemSetAccess(void* ptr, size_t size, const hipMemAccessDesc* desc, size_t count); @@ -7008,6 +7550,8 @@ hipError_t hipMemSetAccess(void* ptr, size_t size, const hipMemAccessDesc* desc, * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported * @warning : This API is marked as beta, meaning, while this is feature complete, * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. */ hipError_t hipMemUnmap(void* ptr, size_t size); @@ -7019,35 +7563,112 @@ hipError_t hipMemUnmap(void* ptr, size_t size); /** *------------------------------------------------------------------------------------------------- *------------------------------------------------------------------------------------------------- - * @defgroup GL Interop + * @defgroup GL OpenGL Interop * @{ - * This section describes Stream Memory Wait and Write functions of HIP runtime API. + * This section describes the OpenGL and graphics interoperability functions of HIP runtime API. */ +/** GLuint as uint.*/ typedef unsigned int GLuint; +/** GLenum as uint.*/ typedef unsigned int GLenum; -// Queries devices associated with GL Context. +/** + * @brief Queries devices associated with the current OpenGL context. + * + * @param [out] pHipDeviceCount - Pointer of number of devices on the current GL context. + * @param [out] pHipDevices - Pointer of devices on the current OpenGL context. + * @param [in] hipDeviceCount - Size of device. + * @param [in] deviceList - The setting of devices. It could be either hipGLDeviceListCurrentFrame + * for the devices used to render the current frame, or hipGLDeviceListAll for all devices. + * The default setting is Invalid deviceList value. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + */ hipError_t hipGLGetDevices(unsigned int* pHipDeviceCount, int* pHipDevices, unsigned int hipDeviceCount, hipGLDeviceList deviceList); -// Registers a GL Buffer for interop and returns corresponding graphics resource. +/** + * @brief Registers a GL Buffer for interop and returns corresponding graphics resource. + * + * @param [out] resource - Returns pointer of graphics resource. + * @param [in] buffer - Buffer to be registered. + * @param [in] flags - Register flags. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorInvalidResourceHandle + * + */ hipError_t hipGraphicsGLRegisterBuffer(hipGraphicsResource** resource, GLuint buffer, unsigned int flags); -// Register a GL Image for interop and returns the corresponding graphic resource +/** + * @brief Register a GL Image for interop and returns the corresponding graphic resource. + * + * @param [out] resource - Returns pointer of graphics resource. + * @param [in] image - Image to be registered. + * @param [in] target - Valid target value Id. + * @param [in] flags - Register flags. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorInvalidResourceHandle + * + */ hipError_t hipGraphicsGLRegisterImage(hipGraphicsResource** resource, GLuint image, GLenum target, unsigned int flags); -// Maps a graphics resource for hip access. +/** + * @brief Maps a graphics resource for access. + * + * @param [in] count - Number of resources to map. + * @param [in] resources - Pointer of resources to map. + * @param [in] stream - Stream for synchronization. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorInvalidResourceHandle + * + */ hipError_t hipGraphicsMapResources(int count, hipGraphicsResource_t* resources, hipStream_t stream __dparm(0) ); -// Get an array through which to access a subresource of a mapped graphics resource. +/** + * @brief Get an array through which to access a subresource of a mapped graphics resource. + * + * @param [out] array - Pointer of array through which a subresource of resource may be accessed. + * @param [in] resource - Mapped resource to access. + * @param [in] arrayIndex - Array index for the subresource to access. + * @param [in] mipLevel - Mipmap level for the subresource to access. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ hipError_t hipGraphicsSubResourceGetMappedArray(hipArray_t* array, hipGraphicsResource_t resource, unsigned int arrayIndex, unsigned int mipLevel); -// Gets device accessible address of a graphics resource. +/** + * @brief Gets device accessible address of a graphics resource. + * + * @param [out] devPtr - Pointer of device through which graphic resource may be accessed. + * @param [out] size - Size of the buffer accessible from devPtr. + * @param [in] resource - Mapped resource to access. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ hipError_t hipGraphicsResourceGetMappedPointer(void** devPtr, size_t* size, hipGraphicsResource_t resource); -// Unmaps a graphics resource for hip access. +/** + * @brief Unmaps graphics resources. + * + * @param [in] count - Number of resources to unmap. + * @param [in] resources - Pointer of resources to unmap. + * @param [in] stream - Stream for synchronization. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorContextIsDestroyed + * + */ hipError_t hipGraphicsUnmapResources(int count, hipGraphicsResource_t* resources, - hipStream_t stream __dparm(0)); -// Unregisters a graphics resource. + hipStream_t stream __dparm(0)); +/** + * @brief Unregisters a graphics resource. + * + * @param [in] resource - Graphics resources to unregister. + * + * @returns #hipSuccess + * + */ hipError_t hipGraphicsUnregisterResource(hipGraphicsResource_t resource); // doxygen end GL Interop /** @@ -7071,42 +7692,118 @@ static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeWithFlags(int return hipOccupancyMaxPotentialBlockSize(gridSize, blockSize, reinterpret_cast(f),dynSharedMemPerBlk,blockSizeLimit); } #endif // defined(__clang__) && defined(__HIP__) + +/** + * @brief Gets the address of a symbol. + * @ingroup Memory + * @param [out] devPtr - Returns device pointer associated with symbol. + * @param [in] symbol - Device symbol. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ template hipError_t hipGetSymbolAddress(void** devPtr, const T &symbol) { return ::hipGetSymbolAddress(devPtr, (const void *)&symbol); } +/** + * @ingroup Memory + * @brief Gets the size of a symbol. + * + * @param [out] size - Returns the size of a symbol. + * @param [in] symbol - Device symbol address. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ template hipError_t hipGetSymbolSize(size_t* size, const T &symbol) { return ::hipGetSymbolSize(size, (const void *)&symbol); } + +/** + * @ingroup Memory + * @brief Copies data to the given symbol on the device. + * + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyToSymbol + */ template hipError_t hipMemcpyToSymbol(const T& symbol, const void* src, size_t sizeBytes, size_t offset __dparm(0), hipMemcpyKind kind __dparm(hipMemcpyHostToDevice)) { return ::hipMemcpyToSymbol((const void*)&symbol, src, sizeBytes, offset, kind); } +/** + * @ingroup Memory + * @brief Copies data to the given symbol on the device asynchronously on the stream. + * + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyToSymbolAsync + */ template hipError_t hipMemcpyToSymbolAsync(const T& symbol, const void* src, size_t sizeBytes, size_t offset, hipMemcpyKind kind, hipStream_t stream __dparm(0)) { return ::hipMemcpyToSymbolAsync((const void*)&symbol, src, sizeBytes, offset, kind, stream); } +/** + * @brief Copies data from the given symbol on the device. + * @ingroup Memory + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyFromSymbol + */ template hipError_t hipMemcpyFromSymbol(void* dst, const T &symbol, size_t sizeBytes, size_t offset __dparm(0), hipMemcpyKind kind __dparm(hipMemcpyDeviceToHost)) { return ::hipMemcpyFromSymbol(dst, (const void*)&symbol, sizeBytes, offset, kind); } +/** + * @brief Copies data from the given symbol on the device asynchronously on the stream. + * @ingroup Memory + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyFromSymbolAsync + */ template hipError_t hipMemcpyFromSymbolAsync(void* dst, const T& symbol, size_t sizeBytes, size_t offset, hipMemcpyKind kind, hipStream_t stream __dparm(0)) { return ::hipMemcpyFromSymbolAsync(dst, (const void*)&symbol, sizeBytes, offset, kind, stream); } + +/** + * @brief Returns occupancy for a kernel function. + * @ingroup Occupancy + * @param [out] numBlocks - Pointer of occupancy in number of blocks. + * @param [in] f - The kernel function to launch on the device. + * @param [in] blockSize - The block size as kernel launched. + * @param [in] dynSharedMemPerBlk - Dynamic shared memory in bytes per block. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ template inline hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessor( int* numBlocks, T f, int blockSize, size_t dynSharedMemPerBlk) { return hipOccupancyMaxActiveBlocksPerMultiprocessor( numBlocks, reinterpret_cast(f), blockSize, dynSharedMemPerBlk); } +/** + * @brief Returns occupancy for a device function with the specified flags. + * + * @ingroup Occupancy + * @param [out] numBlocks - Pointer of occupancy in number of blocks. + * @param [in] f - The kernel function to launch on the device. + * @param [in] blockSize - The block size as kernel launched. + * @param [in] dynSharedMemPerBlk - Dynamic shared memory in bytes per block. + * @param [in] flags - Flag to handle the behavior for the occupancy calculator. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ template inline hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( int* numBlocks, T f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags) { @@ -7116,6 +7813,7 @@ inline hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( /** * @brief Returns grid and block size that achieves maximum potential occupancy for a device function * + * @ingroup Occupancy * Returns in \p *min_grid_size and \p *block_size a suggested grid / * block size pair that achieves the best potential occupancy * (i.e. the maximum number of active warps on the current device with the smallest number @@ -7228,6 +7926,7 @@ static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeVariableSMemW /** * @brief Returns grid and block size that achieves maximum potential occupancy for a device function * + * @ingroup Occupancy * Returns in \p *min_grid_size and \p *block_size a suggested grid / * block size pair that achieves the best potential occupancy * (i.e. the maximum number of active warps on the current device with the smallest number @@ -7254,36 +7953,150 @@ static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeVariableSMem( return hipOccupancyMaxPotentialBlockSizeVariableSMemWithFlags(min_grid_size, block_size, func, block_size_to_dynamic_smem_size, block_size_limit); } - +/** + * @brief Returns grid and block size that achieves maximum potential occupancy for a device function + * + * @ingroup Occupancy + * + * Returns in \p *min_grid_size and \p *block_size a suggested grid / + * block size pair that achieves the best potential occupancy + * (i.e. the maximum number of active warps on the current device with the smallest number + * of blocks for a particular function). + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see hipOccupancyMaxPotentialBlockSize + */ template inline hipError_t hipOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, F kernel, size_t dynSharedMemPerBlk, uint32_t blockSizeLimit) { return hipOccupancyMaxPotentialBlockSize(gridSize, blockSize,(hipFunction_t)kernel, dynSharedMemPerBlk, blockSizeLimit); } +/** + * @brief Launches a device function + * + * @ingroup Execution + * + * @param [in] f device function symbol + * @param [in] gridDim grid dimentions + * @param [in] blockDim block dimentions + * @param [in] kernelParams kernel parameters + * @param [in] sharedMemBytes shared memory in bytes + * @param [in] stream stream on which kernel launched + * + * @return #hipSuccess, #hipErrorLaunchFailure, #hipErrorInvalidValue, + * #hipErrorInvalidResourceHandle + * + */ template inline hipError_t hipLaunchCooperativeKernel(T f, dim3 gridDim, dim3 blockDim, void** kernelParams, unsigned int sharedMemBytes, hipStream_t stream) { return hipLaunchCooperativeKernel(reinterpret_cast(f), gridDim, blockDim, kernelParams, sharedMemBytes, stream); } +/** + * @brief Launches device function on multiple devices where thread blocks can cooperate and + * synchronize on execution. + * + * @ingroup Execution + * + * @param [in] launchParamsList list of kernel launch parameters, one per device + * @param [in] numDevices size of launchParamsList array + * @param [in] flags flag to handle launch behavior + * + * @return #hipSuccess, #hipErrorLaunchFailure, #hipErrorInvalidValue, + * #hipErrorInvalidResourceHandle + * + */ template inline hipError_t hipLaunchCooperativeKernelMultiDevice(hipLaunchParams* launchParamsList, unsigned int numDevices, unsigned int flags = 0) { return hipLaunchCooperativeKernelMultiDevice(launchParamsList, numDevices, flags); } +/** + * + * @ingroup Module + * + * @brief Launches kernels on multiple devices and guarantees all specified kernels are dispatched + * on respective streams before enqueuing any other work on the specified streams from any other threads + * + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ template inline hipError_t hipExtLaunchMultiKernelMultiDevice(hipLaunchParams* launchParamsList, unsigned int numDevices, unsigned int flags = 0) { return hipExtLaunchMultiKernelMultiDevice(launchParamsList, numDevices, flags); } + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Surface Surface Object + * @{ + * + * This section describes surface object functions of HIP runtime API. + * + * @note APIs in this section are under development. + * + */ + +/** + * @brief Create a surface object. + * + * @param [out] pSurfObject Pointer of surface object to be created. + * @param [in] pResDesc Pointer of suface object descriptor. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ hipError_t hipCreateSurfaceObject(hipSurfaceObject_t* pSurfObject, const hipResourceDesc* pResDesc); +/** + * @brief Destroy a surface object. + * + * @param [in] surfaceObject Surface object to be destroyed. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ hipError_t hipDestroySurfaceObject(hipSurfaceObject_t surfaceObject); +// end of surface +/** +* @} +*/ + +/** + * @brief Binds a memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] size Size of memory in bites. + * + * @warning This API is deprecated. + * + */ template DEPRECATED(DEPRECATED_MSG) static inline hipError_t hipBindTexture(size_t* offset, const struct texture& tex, const void* devPtr, size_t size = UINT_MAX) { return hipBindTexture(offset, &tex, devPtr, &tex.channelDesc, size); } +/** + * @brief Binds a memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] desc Texture channel format. + * @param [in] size Size of memory in bites. + * + * @warning This API is deprecated. + * + */ template DEPRECATED(DEPRECATED_MSG) static inline hipError_t @@ -7291,6 +8104,19 @@ static inline hipError_t const struct hipChannelFormatDesc& desc, size_t size = UINT_MAX) { return hipBindTexture(offset, &tex, devPtr, &desc, size); } +/** + * @brief Binds a 2D memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @warning This API is deprecated. + * + */ template DEPRECATED(DEPRECATED_MSG) static inline hipError_t hipBindTexture2D( @@ -7303,6 +8129,20 @@ static inline hipError_t hipBindTexture2D( { return hipBindTexture2D(offset, &tex, devPtr, &tex.channelDesc, width, height, pitch); } +/** + * @brief Binds a 2D memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] desc Texture channel format. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @warning This API is deprecated. + * + */ template DEPRECATED(DEPRECATED_MSG) static inline hipError_t hipBindTexture2D( @@ -7316,6 +8156,15 @@ static inline hipError_t hipBindTexture2D( { return hipBindTexture2D(offset, &tex, devPtr, &desc, width, height, pitch); } +/** + * @brief Binds an array to a texture. + * + * @param [in] tex Texture to bind. + * @param [in] array Array of memory on the device. + * + * @warning This API is deprecated. + * + */ template DEPRECATED(DEPRECATED_MSG) static inline hipError_t hipBindTextureToArray( @@ -7326,6 +8175,16 @@ static inline hipError_t hipBindTextureToArray( hipError_t err = hipGetChannelDesc(&desc, array); return (err == hipSuccess) ? hipBindTextureToArray(&tex, array, &desc) : err; } +/** + * @brief Binds an array to a texture. + * + * @param [in] tex Texture to bind. + * @param [in] array Array of memory on the device. + * @param [in] desc Texture channel format. + * + * @warning This API is deprecated. + * + */ template DEPRECATED(DEPRECATED_MSG) static inline hipError_t hipBindTextureToArray( @@ -7335,6 +8194,15 @@ static inline hipError_t hipBindTextureToArray( { return hipBindTextureToArray(&tex, array, &desc); } +/** + * @brief Binds a mipmapped array to a texture. + * + * @param [in] tex Texture to bind. + * @param [in] mipmappedArray Mipmapped Array of memory on the device. + * + * @warning This API is deprecated. + * + */ template static inline hipError_t hipBindTextureToMipmappedArray( const struct texture &tex, @@ -7349,6 +8217,16 @@ static inline hipError_t hipBindTextureToMipmappedArray( err = hipGetChannelDesc(&desc, levelArray); return (err == hipSuccess) ? hipBindTextureToMipmappedArray(&tex, mipmappedArray, &desc) : err; } +/** + * @brief Binds a mipmapped array to a texture. + * + * @param [in] tex Texture to bind. + * @param [in] mipmappedArray Mipmapped Array of memory on the device. + * @param [in] desc Texture channel format. + * + * @warning This API is deprecated. + * + */ template static inline hipError_t hipBindTextureToMipmappedArray( const struct texture &tex, @@ -7357,6 +8235,14 @@ static inline hipError_t hipBindTextureToMipmappedArray( { return hipBindTextureToMipmappedArray(&tex, mipmappedArray, &desc); } +/** + * @brief Unbinds a texture. + * + * @param [in] tex Texture to unbind. + * + * @warning This API is deprecated. + * + */ template DEPRECATED(DEPRECATED_MSG) static inline hipError_t hipUnbindTexture( @@ -7364,12 +8250,28 @@ static inline hipError_t hipUnbindTexture( { return hipUnbindTexture(&tex); } +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @ingroup StreamO + * @{ + * + * This section describes wrappers for stream Ordered allocation from memory pool functions of + * HIP runtime API. + * + * @note APIs in this section are implemented on Linux, under development on Windows. + * + */ + /** * @brief C++ wrappers for allocations from a memory pool * - * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through function overloading. + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. * * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. */ static inline hipError_t hipMallocAsync( void** dev_ptr, @@ -7378,7 +8280,16 @@ static inline hipError_t hipMallocAsync( hipStream_t stream) { return hipMallocFromPoolAsync(dev_ptr, size, mem_pool, stream); } - +/** + * @brief C++ wrappers for allocations from a memory pool on the stream + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ template static inline hipError_t hipMallocAsync( T** dev_ptr, @@ -7387,7 +8298,16 @@ static inline hipError_t hipMallocAsync( hipStream_t stream) { return hipMallocFromPoolAsync(reinterpret_cast(dev_ptr), size, mem_pool, stream); } - +/** + * @brief C++ wrappers for allocations from a memory pool + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ template static inline hipError_t hipMallocAsync( T** dev_ptr, @@ -7395,7 +8315,16 @@ static inline hipError_t hipMallocAsync( hipStream_t stream) { return hipMallocAsync(reinterpret_cast(dev_ptr), size, stream); } - +/** + * @brief C++ wrappers for allocations from a memory pool + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ template static inline hipError_t hipMallocFromPoolAsync( T** dev_ptr, @@ -7404,15 +8333,15 @@ static inline hipError_t hipMallocFromPoolAsync( hipStream_t stream) { return hipMallocFromPoolAsync(reinterpret_cast(dev_ptr), size, mem_pool, stream); } +/** +* @} +*/ #endif // __cplusplus #ifdef __GNUC__ #pragma GCC visibility pop #endif -// doxygen end HIP API -/** - * @} - */ + #elif !(defined(__HIP_PLATFORM_HCC__) || defined(__HIP_PLATFORM_AMD__)) && (defined(__HIP_PLATFORM_NVCC__) || defined(__HIP_PLATFORM_NVIDIA__)) #include "hip/nvidia_detail/nvidia_hip_runtime_api.h" @@ -7423,7 +8352,7 @@ static inline hipError_t hipMallocFromPoolAsync( /** * @brief: C++ wrapper for hipMalloc - * + * @ingroup Memory * Perform automatic type conversion to eliminate need for excessive typecasting (ie void**) * * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these @@ -7437,15 +8366,37 @@ template static inline hipError_t hipMalloc(T** devPtr, size_t size) { return hipMalloc((void**)devPtr, size); } - -// Provide an override to automatically typecast the pointer type from void**, and also provide a -// default for the flags. +/** + * @brief: C++ wrapper for hipHostMalloc + * @ingroup Memory + * Provide an override to automatically typecast the pointer type from void**, and also provide a + * default for the flags. + * + * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these + * wrappers. It is useful for applications which need to obtain decltypes of + * HIP runtime APIs. + * + * @see hipHostMalloc + */ template static inline hipError_t hipHostMalloc(T** ptr, size_t size, unsigned int flags = hipHostMallocDefault) { return hipHostMalloc((void**)ptr, size, flags); } - +/** + * @brief: C++ wrapper for hipMallocManaged + * + * @ingroup MemoryM + * Provide an override to automatically typecast the pointer type from void**, and also provide a + * default for the flags. + * + * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these + * wrappers. It is useful for applications which need to obtain decltypes of + * HIP runtime APIs. + * + * @see hipMallocManaged + * + */ template static inline hipError_t hipMallocManaged(T** devPtr, size_t size, unsigned int flags = hipMemAttachGlobal) { @@ -7454,7 +8405,10 @@ static inline hipError_t hipMallocManaged(T** devPtr, size_t size, #endif #endif - +// doxygen end HIP API +/** + * @} + */ #include #if USE_PROF_API diff --git a/projects/hip/include/hip/hiprtc.h b/projects/hip/include/hip/hiprtc.h index 4eb5ee6bdc..cfc3a862ba 100644 --- a/projects/hip/include/hip/hiprtc.h +++ b/projects/hip/include/hip/hiprtc.h @@ -29,11 +29,6 @@ THE SOFTWARE. #elif (defined(__HIP_PLATFORM_HCC__) || defined(__HIP_PLATFORM_AMD__)) && \ !(defined(__HIP_PLATFORM_NVCC__) || defined(__HIP_PLATFORM_NVIDIA__)) -/** - * @addtogroup Runtime Runtime Compilation - * @{ - * @ingroup Runtime - */ #ifdef __cplusplus extern "C" { @@ -46,86 +41,93 @@ extern "C" { #endif /** - * @brief hiprtcResult - * @enum * + * @addtogroup GlobalDefs + * @{ + * + */ + /** + * hiprtc error code */ - typedef enum hiprtcResult { - HIPRTC_SUCCESS = 0, - HIPRTC_ERROR_OUT_OF_MEMORY = 1, - HIPRTC_ERROR_PROGRAM_CREATION_FAILURE = 2, - HIPRTC_ERROR_INVALID_INPUT = 3, - HIPRTC_ERROR_INVALID_PROGRAM = 4, - HIPRTC_ERROR_INVALID_OPTION = 5, - HIPRTC_ERROR_COMPILATION = 6, - HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE = 7, - HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION = 8, - HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION = 9, - HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID = 10, - HIPRTC_ERROR_INTERNAL_ERROR = 11, - HIPRTC_ERROR_LINKING = 100 + HIPRTC_SUCCESS = 0, ///< Success + HIPRTC_ERROR_OUT_OF_MEMORY = 1, ///< Out of memory + HIPRTC_ERROR_PROGRAM_CREATION_FAILURE = 2, ///< Failed to create program + HIPRTC_ERROR_INVALID_INPUT = 3, ///< Invalid input + HIPRTC_ERROR_INVALID_PROGRAM = 4, ///< Invalid program + HIPRTC_ERROR_INVALID_OPTION = 5, ///< Invalid option + HIPRTC_ERROR_COMPILATION = 6, ///< Compilation error + HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE = 7, ///< Failed in builtin operation + HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION = 8, ///< No name expression after compilation + HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION = 9, ///< No lowered names before compilation + HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID = 10, ///< Invalid name expression + HIPRTC_ERROR_INTERNAL_ERROR = 11, ///< Internal error + HIPRTC_ERROR_LINKING = 100 ///< Error in linking } hiprtcResult; /** - * @brief hiprtcJIT_option - * @enum - * + * hiprtc JIT option */ typedef enum hiprtcJIT_option { - HIPRTC_JIT_MAX_REGISTERS = 0, - HIPRTC_JIT_THREADS_PER_BLOCK, - HIPRTC_JIT_WALL_TIME, - HIPRTC_JIT_INFO_LOG_BUFFER, - HIPRTC_JIT_INFO_LOG_BUFFER_SIZE_BYTES, - HIPRTC_JIT_ERROR_LOG_BUFFER, - HIPRTC_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, - HIPRTC_JIT_OPTIMIZATION_LEVEL, - HIPRTC_JIT_TARGET_FROM_HIPCONTEXT, - HIPRTC_JIT_TARGET, - HIPRTC_JIT_FALLBACK_STRATEGY, - HIPRTC_JIT_GENERATE_DEBUG_INFO, - HIPRTC_JIT_LOG_VERBOSE, - HIPRTC_JIT_GENERATE_LINE_INFO, - HIPRTC_JIT_CACHE_MODE, - HIPRTC_JIT_NEW_SM3X_OPT, - HIPRTC_JIT_FAST_COMPILE, - HIPRTC_JIT_GLOBAL_SYMBOL_NAMES, - HIPRTC_JIT_GLOBAL_SYMBOL_ADDRESS, - HIPRTC_JIT_GLOBAL_SYMBOL_COUNT, - HIPRTC_JIT_LTO, - HIPRTC_JIT_FTZ, - HIPRTC_JIT_PREC_DIV, - HIPRTC_JIT_PREC_SQRT, - HIPRTC_JIT_FMA, - HIPRTC_JIT_NUM_OPTIONS, - HIPRTC_JIT_IR_TO_ISA_OPT_EXT = 10000, //! AMD only. Linker options to be passed on to - HIPRTC_JIT_IR_TO_ISA_OPT_COUNT_EXT, //! AMD only. Count of linker options + HIPRTC_JIT_MAX_REGISTERS = 0, ///< Maximum registers + HIPRTC_JIT_THREADS_PER_BLOCK, ///< Thread per block + HIPRTC_JIT_WALL_TIME, ///< Time from aall clock + HIPRTC_JIT_INFO_LOG_BUFFER, ///< Log buffer info + HIPRTC_JIT_INFO_LOG_BUFFER_SIZE_BYTES, ///< Log buffer size in bytes + HIPRTC_JIT_ERROR_LOG_BUFFER, ///< Log buffer error + HIPRTC_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, ///< Log buffer size in bytes + HIPRTC_JIT_OPTIMIZATION_LEVEL, ///< Optimization level + HIPRTC_JIT_TARGET_FROM_HIPCONTEXT, ///< + HIPRTC_JIT_TARGET, ///< JIT target + HIPRTC_JIT_FALLBACK_STRATEGY, ///< Fallback strategy + HIPRTC_JIT_GENERATE_DEBUG_INFO, ///< Generate debug information + HIPRTC_JIT_LOG_VERBOSE, ///< Log verbose + HIPRTC_JIT_GENERATE_LINE_INFO, ///< Generate line information + HIPRTC_JIT_CACHE_MODE, ///< Cache mode + HIPRTC_JIT_NEW_SM3X_OPT, ///< New SM3X option + HIPRTC_JIT_FAST_COMPILE, ///< Fast compile + HIPRTC_JIT_GLOBAL_SYMBOL_NAMES, ///< Global symbol names + HIPRTC_JIT_GLOBAL_SYMBOL_ADDRESS, ///< Global symbol address + HIPRTC_JIT_GLOBAL_SYMBOL_COUNT, ///< Global symbol count + HIPRTC_JIT_LTO, ///< LTO + HIPRTC_JIT_FTZ, ///< FTZ + HIPRTC_JIT_PREC_DIV, ///< Prec_VIV + HIPRTC_JIT_PREC_SQRT, ///< PREC_SQRT + HIPRTC_JIT_FMA, ///< FMA + HIPRTC_JIT_NUM_OPTIONS, ///< Number of options + HIPRTC_JIT_IR_TO_ISA_OPT_EXT = 10000, //< AMD only. Linker options to be passed on to + HIPRTC_JIT_IR_TO_ISA_OPT_COUNT_EXT, //< AMD only. Count of linker options } hiprtcJIT_option; /** - * @brief hiprtcJITInputType - * @enum - * + * hiprtc JIT input type */ typedef enum hiprtcJITInputType { - HIPRTC_JIT_INPUT_CUBIN = 0, - HIPRTC_JIT_INPUT_PTX, - HIPRTC_JIT_INPUT_FATBINARY, - HIPRTC_JIT_INPUT_OBJECT, - HIPRTC_JIT_INPUT_LIBRARY, - HIPRTC_JIT_INPUT_NVVM, - HIPRTC_JIT_NUM_LEGACY_INPUT_TYPES, - HIPRTC_JIT_INPUT_LLVM_BITCODE = 100, - HIPRTC_JIT_INPUT_LLVM_BUNDLED_BITCODE = 101, - HIPRTC_JIT_INPUT_LLVM_ARCHIVES_OF_BUNDLED_BITCODE = 102, + HIPRTC_JIT_INPUT_CUBIN = 0, ///< Input cubin + HIPRTC_JIT_INPUT_PTX, ///< Input PTX + HIPRTC_JIT_INPUT_FATBINARY, ///< Input fat binary + HIPRTC_JIT_INPUT_OBJECT, ///< Input object + HIPRTC_JIT_INPUT_LIBRARY, ///< Input library + HIPRTC_JIT_INPUT_NVVM, ///< Input NVVM + HIPRTC_JIT_NUM_LEGACY_INPUT_TYPES, ///< Number of legacy input type + HIPRTC_JIT_INPUT_LLVM_BITCODE = 100, ///< LLVM bitcode + HIPRTC_JIT_INPUT_LLVM_BUNDLED_BITCODE = 101, ///< LLVM bundled bitcode + HIPRTC_JIT_INPUT_LLVM_ARCHIVES_OF_BUNDLED_BITCODE = 102, ///< LLVM archives of boundled bitcode HIPRTC_JIT_NUM_INPUT_TYPES = (HIPRTC_JIT_NUM_LEGACY_INPUT_TYPES + 3) } hiprtcJITInputType; - -typedef struct ihiprtcLinkState* hiprtcLinkState; +/** +* @} +*/ /** + * hiprtc link state + * + */ +typedef struct ihiprtcLinkState* hiprtcLinkState; +/** + * @ingroup Runtime + * * @brief Returns text string message to explain the error which occurred * * @param [in] result code to convert to string. @@ -139,6 +141,7 @@ typedef struct ihiprtcLinkState* hiprtcLinkState; const char* hiprtcGetErrorString(hiprtcResult result); /** + * @ingroup Runtime * @brief Sets the parameters as major and minor version. * * @param [out] major HIP Runtime Compilation major version. @@ -146,38 +149,47 @@ const char* hiprtcGetErrorString(hiprtcResult result); * */ hiprtcResult hiprtcVersion(int* major, int* minor); - +/** + * hiprtc program + * + */ typedef struct _hiprtcProgram* hiprtcProgram; /** + * @ingroup Runtime * @brief Adds the given name exprssion to the runtime compilation program. * * @param [in] prog runtime compilation program instance. * @param [in] name_expression const char pointer to the name expression. - * @return HIPRTC_SUCCESS + * @return #HIPRTC_SUCCESS * - * If const char pointer is NULL, it will return HIPRTC_ERROR_INVALID_INPUT. + * If const char pointer is NULL, it will return #HIPRTC_ERROR_INVALID_INPUT. * * @see hiprtcResult */ -hiprtcResult hiprtcAddNameExpression(hiprtcProgram prog, const char* name_expression); +hiprtcResult hiprtcAddNameExpression(hiprtcProgram prog, + const char* name_expression); /** + * @ingroup Runtime * @brief Compiles the given runtime compilation program. * * @param [in] prog runtime compilation program instance. * @param [in] numOptions number of compiler options. * @param [in] options compiler options as const array of strins. - * @return HIPRTC_SUCCESS + * @return #HIPRTC_SUCCESS * * If the compiler failed to build the runtime compilation program, - * it will return HIPRTC_ERROR_COMPILATION. + * it will return #HIPRTC_ERROR_COMPILATION. * * @see hiprtcResult */ -hiprtcResult hiprtcCompileProgram(hiprtcProgram prog, int numOptions, const char** options); +hiprtcResult hiprtcCompileProgram(hiprtcProgram prog, + int numOptions, + const char** options); /** + * @ingroup Runtime * @brief Creates an instance of hiprtcProgram with the given input parameters, * and sets the output hiprtcProgram prog with it. * @@ -187,53 +199,58 @@ hiprtcResult hiprtcCompileProgram(hiprtcProgram prog, int numOptions, const char * @param [in] numHeaders number of headers. * @param [in] headers array of strings pointing to headers. * @param [in] includeNames array of strings pointing to names included in program source. - * @return HIPRTC_SUCCESS + * @return #HIPRTC_SUCCESS * - * Any invalide input parameter, it will return HIPRTC_ERROR_INVALID_INPUT - * or HIPRTC_ERROR_INVALID_PROGRAM. + * Any invalide input parameter, it will return #HIPRTC_ERROR_INVALID_INPUT + * or #HIPRTC_ERROR_INVALID_PROGRAM. * - * If failed to create the program, it will return HIPRTC_ERROR_PROGRAM_CREATION_FAILURE. + * If failed to create the program, it will return #HIPRTC_ERROR_PROGRAM_CREATION_FAILURE. * * @see hiprtcResult */ -hiprtcResult hiprtcCreateProgram(hiprtcProgram* prog, const char* src, const char* name, - int numHeaders, const char** headers, const char** includeNames); +hiprtcResult hiprtcCreateProgram(hiprtcProgram* prog, + const char* src, + const char* name, + int numHeaders, + const char** headers, + const char** includeNames); /** * @brief Destroys an instance of given hiprtcProgram. - * + * @ingroup Runtime * @param [in] prog runtime compilation program instance. - * @return HIPRTC_SUCCESS + * @return #HIPRTC_SUCCESS * - * If prog is NULL, it will return HIPRTC_ERROR_INVALID_INPUT. + * If prog is NULL, it will return #HIPRTC_ERROR_INVALID_INPUT. * * @see hiprtcResult */ hiprtcResult hiprtcDestroyProgram(hiprtcProgram* prog); /** - * @brief Gets the lowered (mangled) name from an instance of hiprtcProgram with the given input - * parameters, and sets the output lowered_name with it. - * + * @brief Gets the lowered (mangled) name from an instance of hiprtcProgram with the given input parameters, + * and sets the output lowered_name with it. + * @ingroup Runtime * @param [in] prog runtime compilation program instance. * @param [in] name_expression const char pointer to the name expression. * @param [in, out] lowered_name const char array to the lowered (mangled) name. - * @return HIPRTC_SUCCESS + * @return #HIPRTC_SUCCESS * - * If any invalide nullptr input parameters, it will return HIPRTC_ERROR_INVALID_INPUT + * If any invalide nullptr input parameters, it will return #HIPRTC_ERROR_INVALID_INPUT * - * If name_expression is not found, it will return HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID + * If name_expression is not found, it will return #HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID * - * If failed to get lowered_name from the program, it will return HIPRTC_ERROR_COMPILATION. + * If failed to get lowered_name from the program, it will return #HIPRTC_ERROR_COMPILATION. * * @see hiprtcResult */ -hiprtcResult hiprtcGetLoweredName(hiprtcProgram prog, const char* name_expression, +hiprtcResult hiprtcGetLoweredName(hiprtcProgram prog, + const char* name_expression, const char** lowered_name); /** * @brief Gets the log generated by the runtime compilation program instance. - * + * @ingroup Runtime * @param [in] prog runtime compilation program instance. * @param [out] log memory pointer to the generated log. * @return HIPRTC_SUCCESS @@ -251,11 +268,12 @@ hiprtcResult hiprtcGetProgramLog(hiprtcProgram prog, char* log); * * @see hiprtcResult */ -hiprtcResult hiprtcGetProgramLogSize(hiprtcProgram prog, size_t* logSizeRet); +hiprtcResult hiprtcGetProgramLogSize(hiprtcProgram prog, + size_t* logSizeRet); /** * @brief Gets the pointer of compilation binary by the runtime compilation program instance. - * + * @ingroup Runtime * @param [in] prog runtime compilation program instance. * @param [out] code char pointer to binary. * @return HIPRTC_SUCCESS @@ -266,9 +284,9 @@ hiprtcResult hiprtcGetCode(hiprtcProgram prog, char* code); /** * @brief Gets the size of compilation binary by the runtime compilation program instance. - * + * @ingroup Runtime * @param [in] prog runtime compilation program instance. - * @param [out] code the size of binary. + * @param [out] codeSizeRet the size of binary. * @return HIPRTC_SUCCESS * * @see hiprtcResult @@ -279,7 +297,7 @@ hiprtcResult hiprtcGetCodeSize(hiprtcProgram prog, size_t* codeSizeRet); * @brief Gets the pointer of compiled bitcode by the runtime compilation program instance. * * @param [in] prog runtime compilation program instance. - * @param [out] code char pointer to bitcode. + * @param [out] bitcode char pointer to bitcode. * @return HIPRTC_SUCCESS * * @see hiprtcResult @@ -288,11 +306,11 @@ hiprtcResult hiprtcGetBitcode(hiprtcProgram prog, char* bitcode); /** * @brief Gets the size of compiled bitcode by the runtime compilation program instance. - * + * @ingroup Runtime * * @param [in] prog runtime compilation program instance. - * @param [out] code the size of bitcode. - * @return HIPRTC_SUCCESS + * @param [out] bitcode_size the size of bitcode. + * @return #HIPRTC_SUCCESS * * @see hiprtcResult */ @@ -300,10 +318,13 @@ hiprtcResult hiprtcGetBitcodeSize(hiprtcProgram prog, size_t* bitcode_size); /** * @brief Creates the link instance via hiprtc APIs. - * - * @param [in] hip_jit_options - * @param [out] hiprtc link state instance - * @return HIPRTC_SUCCESS + * @ingroup Runtime + * @param [in] num_options Number of options + * @param [in] option_ptr Array of options + * @param [in] option_vals_pptr Array of option values cast to void* + * @param [out] hip_link_state_ptr hiprtc link state created upon success + * + * @return #HIPRTC_SUCCESS, #HIPRTC_ERROR_INVALID_INPUT, #HIPRTC_ERROR_INVALID_OPTION * * @see hiprtcResult */ @@ -312,14 +333,18 @@ hiprtcResult hiprtcLinkCreate(unsigned int num_options, hiprtcJIT_option* option /** * @brief Adds a file with bit code to be linked with options + * @ingroup Runtime + * @param [in] hip_link_state hiprtc link state + * @param [in] input_type Type of the input data or bitcode + * @param [in] file_path Path to the input file where bitcode is present + * @param [in] num_options Size of the options + * @param [in] options_ptr Array of options applied to this input + * @param [in] option_values Array of option values cast to void* * - * @param [in] hiprtc link state, jit input type, file path, - * option reated parameters. - * @param [out] None. - * @return HIPRTC_SUCCESS + * @return #HIPRTC_SUCCESS * * If input values are invalid, it will - * @return HIPRTC_ERROR_INVALID_INPUT + * @return #HIPRTC_ERROR_INVALID_INPUT * * @see hiprtcResult */ @@ -330,14 +355,20 @@ hiprtcResult hiprtcLinkAddFile(hiprtcLinkState hip_link_state, hiprtcJITInputTyp /** * @brief Completes the linking of the given program. + * @ingroup Runtime + * @param [in] hip_link_state hiprtc link state + * @param [in] input_type Type of the input data or bitcode + * @param [in] image Input data which is null terminated + * @param [in] image_size Size of the input data + * @param [in] name Optional name for this input + * @param [in] num_options Size of the options + * @param [in] options_ptr Array of options applied to this input + * @param [in] option_values Array of option values cast to void* * - * @param [in] hiprtc link state, jit input type, image_ptr , - * option reated parameters. - * @param [out] None. - * @return HIPRTC_SUCCESS + * @return #HIPRTC_SUCCESS, #HIPRTC_ERROR_INVALID_INPUT * * If adding the file fails, it will - * @return HIPRTC_ERROR_PROGRAM_CREATION_FAILURE + * @return #HIPRTC_ERROR_PROGRAM_CREATION_FAILURE * * @see hiprtcResult */ @@ -349,13 +380,15 @@ hiprtcResult hiprtcLinkAddData(hiprtcLinkState hip_link_state, hiprtcJITInputTyp /** * @brief Completes the linking of the given program. + * @ingroup Runtime + * @param [in] hip_link_state hiprtc link state + * @param [out] bin_out Upon success, points to the output binary + * @param [out] size_out Size of the binary is stored (optional) * - * @param [in] hiprtc link state instance - * @param [out] linked_binary, linked_binary_size. - * @return HIPRTC_SUCCESS + * @return #HIPRTC_SUCCESS * * If adding the data fails, it will - * @return HIPRTC_ERROR_PROGRAM_CREATION_FAILURE + * @return #HIPRTC_ERROR_LINKING * * @see hiprtcResult */ @@ -363,13 +396,10 @@ hiprtcResult hiprtcLinkComplete(hiprtcLinkState hip_link_state, void** bin_out, /** * @brief Deletes the link instance via hiprtc APIs. + * @ingroup Runtime + * @param [in] hip_link_state link state instance * - * @param [in] hiprtc link state instance - * @param [out] code the size of binary. - * @return HIPRTC_SUCCESS - * - * If linking fails, it will - * @return HIPRTC_ERROR_LINKING + * @return #HIPRTC_SUCCESS * * @see hiprtcResult */ @@ -382,10 +412,7 @@ hiprtcResult hiprtcLinkDestroy(hiprtcLinkState hip_link_state); #ifdef __cplusplus } #endif /* __cplusplus */ -// doxygen end HIPrtc feature -/** - * @} - */ + #else #error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); #endif diff --git a/projects/hip/samples/0_Intro/bit_extract/CMakeLists.txt b/projects/hip/samples/0_Intro/bit_extract/CMakeLists.txt deleted file mode 100644 index d51e4d974a..0000000000 --- a/projects/hip/samples/0_Intro/bit_extract/CMakeLists.txt +++ /dev/null @@ -1,52 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(bit_extract) - -cmake_minimum_required(VERSION 3.10) - -if(NOT WIN32 AND NOT DEFINED __HIP_ENABLE_PCH) - set(__HIP_ENABLE_PCH ON CACHE BOOL "enable/disable pre-compiled hip headers") -endif() - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -if(${__HIP_ENABLE_PCH}) - add_definitions(-D__HIP_ENABLE_PCH) -endif() - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) - -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(bit_extract bit_extract.cpp) - -# Link with HIP -target_link_libraries(bit_extract hip::host) diff --git a/projects/hip/samples/0_Intro/bit_extract/Makefile b/projects/hip/samples/0_Intro/bit_extract/Makefile deleted file mode 100644 index 6f4d824ba8..0000000000 --- a/projects/hip/samples/0_Intro/bit_extract/Makefile +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -#Dependencies : [MYHIP]/bin must be in user's path. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIP_PLATFORM=$(shell $(HIP_PATH)/bin/hipconfig --platform) -HIPCC=$(HIP_PATH)/bin/hipcc - -# Show how to use PLATFORM to specify different options for each compiler: -ifeq (${HIP_PLATFORM}, nvcc) - HIPCC_FLAGS = -gencode=arch=compute_20,code=sm_20 -endif - -EXE=bit_extract - -$(EXE): bit_extract.cpp - $(HIPCC) $(HIPCC_FLAGS) $< -o $@ - -all: $(EXE) - -clean: - rm -f *.o $(EXE) diff --git a/projects/hip/samples/0_Intro/bit_extract/README.md b/projects/hip/samples/0_Intro/bit_extract/README.md deleted file mode 100644 index 69995721b0..0000000000 --- a/projects/hip/samples/0_Intro/bit_extract/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# bit_extract - -Show an application written directly in HIP which uses platform-specific check on __HIP_PLATFORM_AMD__ to enable use of -an instruction that only exists on the HCC platform. - -See related [blog](http://gpuopen.com/platform-aware-coding-inside-hip/) demonstrating platform specialization. diff --git a/projects/hip/samples/0_Intro/bit_extract/bit_extract.cpp b/projects/hip/samples/0_Intro/bit_extract/bit_extract.cpp deleted file mode 100644 index cf0440dd57..0000000000 --- a/projects/hip/samples/0_Intro/bit_extract/bit_extract.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include -#include -#include "hip/hip_runtime.h" - -#define CHECK(cmd) \ - { \ - hipError_t error = cmd; \ - if (error != hipSuccess) { \ - fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), error, \ - __FILE__, __LINE__); \ - exit(EXIT_FAILURE); \ - } \ - } - -__global__ void bit_extract_kernel(uint32_t* C_d, const uint32_t* A_d, size_t N) { - size_t offset = (blockIdx.x * blockDim.x + threadIdx.x); - size_t stride = blockDim.x * gridDim.x; - - for (size_t i = offset; i < N; i += stride) { -#ifdef __HIP_PLATFORM_AMD__ - C_d[i] = __bitextract_u32(A_d[i], 8, 4); -#else /* defined __HIP_PLATFORM_NVIDIA__ or other path */ - C_d[i] = ((A_d[i] & 0xf00) >> 8); -#endif - } -} - - -int main(int argc, char* argv[]) { - uint32_t *A_d, *C_d; - uint32_t *A_h, *C_h; - size_t N = 1000000; - size_t Nbytes = N * sizeof(uint32_t); - -#ifdef __HIP_ENABLE_PCH - // Verify hip_pch.o - const char* pch = nullptr; - unsigned int size = 0; - __hipGetPCH(&pch, &size); - printf("pch size: %u\n", size); - if (size == 0) { - printf("__hipGetPCH failed!\n"); - return -1; - } else { - printf("__hipGetPCH succeeded!\n"); - } -#endif - - int deviceId; - CHECK(hipGetDevice(&deviceId)); - hipDeviceProp_t props; - CHECK(hipGetDeviceProperties(&props, deviceId)); - printf("info: running on device #%d %s\n", deviceId, props.name); - - - printf("info: allocate host mem (%6.2f MB)\n", 2 * Nbytes / 1024.0 / 1024.0); - A_h = (uint32_t*)malloc(Nbytes); - CHECK(A_h == 0 ? hipErrorOutOfMemory : hipSuccess); - C_h = (uint32_t*)malloc(Nbytes); - CHECK(C_h == 0 ? hipErrorOutOfMemory : hipSuccess); - - for (size_t i = 0; i < N; i++) { - A_h[i] = i; - } - - printf("info: allocate device mem (%6.2f MB)\n", 2 * Nbytes / 1024.0 / 1024.0); - CHECK(hipMalloc(&A_d, Nbytes)); - CHECK(hipMalloc(&C_d, Nbytes)); - - printf("info: copy Host2Device\n"); - CHECK(hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice)); - - printf("info: launch 'bit_extract_kernel' \n"); - const unsigned blocks = 512; - const unsigned threadsPerBlock = 256; - hipLaunchKernelGGL(bit_extract_kernel, dim3(blocks), dim3(threadsPerBlock), 0, 0, C_d, A_d, N); - - printf("info: copy Device2Host\n"); - CHECK(hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost)); - - printf("info: check result\n"); - for (size_t i = 0; i < N; i++) { - unsigned Agold = ((A_h[i] & 0xf00) >> 8); - if (C_h[i] != Agold) { - fprintf(stderr, "mismatch detected.\n"); - printf("%zu: %08x =? %08x (Ain=%08x)\n", i, C_h[i], Agold, A_h[i]); - CHECK(hipErrorUnknown); - } - } - printf("PASSED!\n"); -} diff --git a/projects/hip/samples/0_Intro/module_api/CMakeLists.txt b/projects/hip/samples/0_Intro/module_api/CMakeLists.txt deleted file mode 100644 index cefe6e2c79..0000000000 --- a/projects/hip/samples/0_Intro/module_api/CMakeLists.txt +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(module_api) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) - -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(runKernel.hip.out runKernel.cpp) -add_executable(launchKernelHcc.hip.out launchKernelHcc.cpp) -add_executable(defaultDriver.hip.out defaultDriver.cpp) - -# Generate code object -add_custom_target( - codeobj - ALL - COMMAND ${HIP_HIPCC_EXECUTABLE} --genco ../vcpy_kernel.cpp -o vcpy_kernel.code - COMMENT "codeobj generated" -) - -add_dependencies(runKernel.hip.out codeobj) -add_dependencies(launchKernelHcc.hip.out codeobj) -add_dependencies(defaultDriver.hip.out codeobj) - -# Link with HIP -target_link_libraries(runKernel.hip.out hip::host) -target_link_libraries(launchKernelHcc.hip.out hip::host) -target_link_libraries(defaultDriver.hip.out hip::host) diff --git a/projects/hip/samples/0_Intro/module_api/Makefile b/projects/hip/samples/0_Intro/module_api/Makefile deleted file mode 100644 index 118d16a7ef..0000000000 --- a/projects/hip/samples/0_Intro/module_api/Makefile +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc -HIP_PLATFORM=$(shell $(HIP_PATH)/bin/hipconfig --compiler) - -all: vcpy_kernel.code runKernel.hip.out launchKernelHcc.hip.out defaultDriver.hip.out - -runKernel.hip.out: runKernel.cpp - $(HIPCC) $(HIPCC_FLAGS) $< -o $@ - -launchKernelHcc.hip.out: launchKernelHcc.cpp - $(HIPCC) $(HIPCC_FLAGS) $< -o $@ - -defaultDriver.hip.out: defaultDriver.cpp - $(HIPCC) $(HIPCC_FLAGS) $< -o $@ - -vcpy_kernel.code: vcpy_kernel.cpp - $(HIPCC) --genco $(GENCO_FLAGS) $^ -o $@ - -clean: - rm -f *.code *.out diff --git a/projects/hip/samples/0_Intro/module_api/defaultDriver.cpp b/projects/hip/samples/0_Intro/module_api/defaultDriver.cpp deleted file mode 100644 index 9443842026..0000000000 --- a/projects/hip/samples/0_Intro/module_api/defaultDriver.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" -#include -#include -#include - -#define LEN 64 -#define SIZE LEN << 2 - -#define fileName "vcpy_kernel.code" -#define kernel_name "hello_world" - -int main() { - float *A, *B; - hipDeviceptr_t Ad, Bd; - A = new float[LEN]; - B = new float[LEN]; - - for (uint32_t i = 0; i < LEN; i++) { - A[i] = i * 1.0f; - B[i] = 0.0f; - } - - hipInit(0); - hipDevice_t device; - hipCtx_t context; - hipDeviceGet(&device, 0); - hipCtxCreate(&context, 0, device); - - hipMalloc((void**)&Ad, SIZE); - hipMalloc((void**)&Bd, SIZE); - - hipMemcpyHtoD(Ad, A, SIZE); - hipMemcpyHtoD(Bd, B, SIZE); - - hipModule_t Module; - hipFunction_t Function; - hipModuleLoad(&Module, fileName); - hipModuleGetFunction(&Function, Module, kernel_name); - - void* args[2] = {&Ad, &Bd}; - - hipModuleLaunchKernel(Function, 1, 1, 1, LEN, 1, 1, 0, 0, args, nullptr); - - hipMemcpyDtoH(B, Bd, SIZE); - int mismatchCount = 0; - for (uint32_t i = 0; i < LEN; i++) { - if (A[i] != B[i]) { - mismatchCount++; - std::cout << "error: mismatch " << A[i] << " != " << B[i] << std::endl; - } - } - - if (mismatchCount == 0) { - std::cout << "PASSED!\n"; - } else { - std::cout << "FAILED!\n"; - }; - - hipFree(Ad); - hipFree(Bd); - delete[] A; - delete[] B; - hipCtxDestroy(context); - return 0; -} diff --git a/projects/hip/samples/0_Intro/module_api/launchKernelHcc.cpp b/projects/hip/samples/0_Intro/module_api/launchKernelHcc.cpp deleted file mode 100644 index 464f6d8851..0000000000 --- a/projects/hip/samples/0_Intro/module_api/launchKernelHcc.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" -#include "hip/hip_runtime_api.h" -#include -#include -#include - -#ifdef __HIP_PLATFORM_AMD__ -#include -#endif - -#define LEN 64 -#define SIZE LEN << 2 - -#define fileName "vcpy_kernel.code" -#define kernel_name "hello_world" - -#define HIP_CHECK(status) \ - if (status != hipSuccess) { \ - std::cout << "Got Status: " << status << " at Line: " << __LINE__ << std::endl; \ - exit(0); \ - } - -int main() { - float *A, *B; - hipDeviceptr_t Ad, Bd; - A = new float[LEN]; - B = new float[LEN]; - - for (uint32_t i = 0; i < LEN; i++) { - A[i] = i * 1.0f; - B[i] = 0.0f; - } - - hipInit(0); - hipDevice_t device; - hipCtx_t context; - hipDeviceGet(&device, 0); - hipCtxCreate(&context, 0, device); - - hipMalloc((void**)&Ad, SIZE); - hipMalloc((void**)&Bd, SIZE); - - hipMemcpyHtoD(Ad, A, SIZE); - hipMemcpyHtoD(Bd, B, SIZE); - hipModule_t Module; - hipFunction_t Function; - HIP_CHECK(hipModuleLoad(&Module, fileName)); - HIP_CHECK(hipModuleGetFunction(&Function, Module, kernel_name)); - - struct { - void* _Ad; - void* _Bd; - } args; - - args._Ad = Ad; - args._Bd = Bd; - - - size_t size = sizeof(args); - - void* config[] = {HIP_LAUNCH_PARAM_BUFFER_POINTER, &args, HIP_LAUNCH_PARAM_BUFFER_SIZE, &size, - HIP_LAUNCH_PARAM_END}; - - HIP_CHECK( - hipExtModuleLaunchKernel(Function, LEN, 1, 1, LEN, 1, 1, 0, 0, NULL, (void**)&config, 0)); - - hipMemcpyDtoH(B, Bd, SIZE); - - int mismatchCount = 0; - for (uint32_t i = 0; i < LEN; i++) { - if (A[i] != B[i]) { - mismatchCount++; - std::cout << "error: mismatch " << A[i] << " != " << B[i] << std::endl; - } - } - - if (mismatchCount == 0) { - std::cout << "PASSED!\n"; - } else { - std::cout << "FAILED!\n"; - }; - - hipFree(Ad); - hipFree(Bd); - delete[] A; - delete[] B; - hipCtxDestroy(context); - return 0; -} diff --git a/projects/hip/samples/0_Intro/module_api/runKernel.cpp b/projects/hip/samples/0_Intro/module_api/runKernel.cpp deleted file mode 100644 index c2de0c6c0d..0000000000 --- a/projects/hip/samples/0_Intro/module_api/runKernel.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" -#include "hip/hip_runtime_api.h" -#include -#include -#include -#include - -#define LEN 64 -#define SIZE LEN << 2 - -#define fileName "vcpy_kernel.code" -#define kernel_name "hello_world" - -#define HIP_CHECK(status) \ - if (status != hipSuccess) { \ - std::cout << "Got Status: " << status << " at Line: " << __LINE__ << std::endl; \ - exit(0); \ - } - -int main() { - float *A, *B; - hipDeviceptr_t Ad, Bd; - A = new float[LEN]; - B = new float[LEN]; - - for (uint32_t i = 0; i < LEN; i++) { - A[i] = i * 1.0f; - B[i] = 0.0f; - } - - hipInit(0); - hipDevice_t device; - hipCtx_t context; - hipDeviceGet(&device, 0); - hipCtxCreate(&context, 0, device); - - hipMalloc((void**)&Ad, SIZE); - hipMalloc((void**)&Bd, SIZE); - - hipMemcpyHtoD(Ad, A, SIZE); - hipMemcpyHtoD(Bd, B, SIZE); - hipModule_t Module; - hipFunction_t Function; - HIP_CHECK(hipModuleLoad(&Module, fileName)); - HIP_CHECK(hipModuleGetFunction(&Function, Module, kernel_name)); - - struct { - void* _Ad; - void* _Bd; - } args; - - args._Ad = (void*) Ad; - args._Bd = (void*) Bd; - - size_t size = sizeof(args); - - void* config[] = {HIP_LAUNCH_PARAM_BUFFER_POINTER, &args, HIP_LAUNCH_PARAM_BUFFER_SIZE, &size, - HIP_LAUNCH_PARAM_END}; - - HIP_CHECK(hipModuleLaunchKernel(Function, 1, 1, 1, LEN, 1, 1, 0, 0, NULL, (void**)&config)); - - hipMemcpyDtoH(B, Bd, SIZE); - - int mismatchCount = 0; - for (uint32_t i = 0; i < LEN; i++) { - if (A[i] != B[i]) { - mismatchCount++; - std::cout << "error: mismatch " << A[i] << " != " << B[i] << std::endl; - } - } - - if (mismatchCount == 0) { - std::cout << "PASSED!\n"; - } else { - std::cout << "FAILED!\n"; - }; - - hipFree(Ad); - hipFree(Bd); - delete[] A; - delete[] B; - hipCtxDestroy(context); - return 0; -} diff --git a/projects/hip/samples/0_Intro/module_api/vcpy_kernel.cpp b/projects/hip/samples/0_Intro/module_api/vcpy_kernel.cpp deleted file mode 100644 index 214a869b22..0000000000 --- a/projects/hip/samples/0_Intro/module_api/vcpy_kernel.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" - -extern "C" __global__ void hello_world(float* a, float* b) { - int tx = threadIdx.x; - b[tx] = a[tx]; -} diff --git a/projects/hip/samples/0_Intro/module_api_global/CMakeLists.txt b/projects/hip/samples/0_Intro/module_api_global/CMakeLists.txt deleted file mode 100644 index c3b147c60c..0000000000 --- a/projects/hip/samples/0_Intro/module_api_global/CMakeLists.txt +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(modile_api_global) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) - -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(runKernel.hip.out runKernel.cpp) - -# Generate code object -add_custom_target( - codeobj - ALL - COMMAND ${HIP_HIPCC_EXECUTABLE} --genco ../vcpy_kernel.cpp -o vcpy_kernel.code - COMMENT "codeobj generated" -) - -add_dependencies(runKernel.hip.out codeobj) - -# Link with HIP -target_link_libraries(runKernel.hip.out hip::host) \ No newline at end of file diff --git a/projects/hip/samples/0_Intro/module_api_global/Makefile b/projects/hip/samples/0_Intro/module_api_global/Makefile deleted file mode 100644 index fdbc77f65f..0000000000 --- a/projects/hip/samples/0_Intro/module_api_global/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2017 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc -HIP_PLATFORM=$(shell $(HIP_PATH)/bin/hipconfig --compiler) - -all: vcpy_kernel.code runKernel.hip.out - -runKernel.hip.out: runKernel.cpp - $(HIPCC) $(HIPCC_FLAGS) $< -o $@ - -vcpy_kernel.code: vcpy_kernel.cpp - $(HIPCC) --genco $(GENCO_FLAGS) $^ -o $@ - -clean: - rm -f *.code *.out diff --git a/projects/hip/samples/0_Intro/module_api_global/runKernel.cpp b/projects/hip/samples/0_Intro/module_api_global/runKernel.cpp deleted file mode 100644 index 23f4ec2750..0000000000 --- a/projects/hip/samples/0_Intro/module_api_global/runKernel.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* -Copyright (c) 2017 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" -#include "hip/hip_runtime_api.h" -#include -#include -#include -#include - -#define LEN 64 -#define SIZE LEN * sizeof(float) - -#define fileName "vcpy_kernel.code" -#define HIP_CHECK(cmd) \ - { \ - hipError_t status = cmd; \ - if (status != hipSuccess) { \ - std::cout << "error: #" << status << " (" << hipGetErrorString(status) \ - << ") at line:" << __LINE__ << ": " << #cmd << std::endl; \ - abort(); \ - } \ - } - -int main() { - float *A, *B; - float *Ad, *Bd; - A = new float[LEN]; - B = new float[LEN]; - - for (uint32_t i = 0; i < LEN; i++) { - A[i] = i * 1.0f; - B[i] = 0.0f; - } - - hipInit(0); - hipDevice_t device; - hipCtx_t context; - hipDeviceGet(&device, 0); - hipCtxCreate(&context, 0, device); - - hipMalloc((void**)&Ad, SIZE); - hipMalloc((void**)&Bd, SIZE); - - hipMemcpyHtoD(hipDeviceptr_t(Ad), A, SIZE); - hipMemcpyHtoD((hipDeviceptr_t)(Bd), B, SIZE); - hipModule_t Module; - HIP_CHECK(hipModuleLoad(&Module, fileName)); - - float myDeviceGlobal_h = 42.0; - float* deviceGlobal; - size_t deviceGlobalSize; - HIP_CHECK(hipModuleGetGlobal((void**)&deviceGlobal, &deviceGlobalSize, Module, "myDeviceGlobal")); - HIP_CHECK(hipMemcpyHtoD(hipDeviceptr_t(deviceGlobal), &myDeviceGlobal_h, deviceGlobalSize)); - -#define ARRAY_SIZE 16 - - float myDeviceGlobalArray_h[ARRAY_SIZE]; - float *myDeviceGlobalArray; - size_t myDeviceGlobalArraySize; - HIP_CHECK(hipModuleGetGlobal((void**)&myDeviceGlobalArray, &myDeviceGlobalArraySize, Module, "myDeviceGlobalArray")); - for (int i = 0; i < ARRAY_SIZE; i++) { - myDeviceGlobalArray_h[i] = i * 1000.0f; - HIP_CHECK(hipMemcpyHtoD(hipDeviceptr_t(myDeviceGlobalArray), &myDeviceGlobalArray_h, myDeviceGlobalArraySize)); - } - - struct { - void* _Ad; - void* _Bd; - } args; - - args._Ad = (void*) Ad; - args._Bd = (void*) Bd; - - size_t size = sizeof(args); - - void* config[] = {HIP_LAUNCH_PARAM_BUFFER_POINTER, &args, HIP_LAUNCH_PARAM_BUFFER_SIZE, &size, - HIP_LAUNCH_PARAM_END}; - - { - hipFunction_t Function; - HIP_CHECK(hipModuleGetFunction(&Function, Module, "hello_world")); - HIP_CHECK(hipModuleLaunchKernel(Function, 1, 1, 1, LEN, 1, 1, 0, 0, NULL, (void**)&config)); - - hipMemcpyDtoH(B, Bd, SIZE); - - int mismatchCount = 0; - for (uint32_t i = 0; i < LEN; i++) { - if (A[i] != B[i]) { - mismatchCount++; - std::cout << "error: mismatch " << A[i] << " != " << B[i] << std::endl; - if (mismatchCount >= 10) { - break; - } - } - } - - if (mismatchCount == 0) { - std::cout << "PASSED!\n"; - } else { - std::cout << "FAILED!\n"; - }; - } - - { - hipFunction_t Function; - HIP_CHECK(hipModuleGetFunction(&Function, Module, "test_globals")); - int val =-1; - HIP_CHECK(hipFuncGetAttribute(&val, HIP_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES,Function)); - printf("Shared Size Bytes = %d\n",val); - HIP_CHECK(hipFuncGetAttribute(&val, HIP_FUNC_ATTRIBUTE_NUM_REGS, Function)); - printf("Num Regs = %d\n",val); - HIP_CHECK(hipModuleLaunchKernel(Function, 1, 1, 1, LEN, 1, 1, 0, 0, NULL, (void**)&config)); - - hipMemcpyDtoH(B, Bd, SIZE); - - int mismatchCount = 0; - for (uint32_t i = 0; i < LEN; i++) { - float expected = A[i] + myDeviceGlobal_h + myDeviceGlobalArray_h[i % 16]; - if (expected != B[i]) { - mismatchCount++; - std::cout << "error: mismatch " << expected << " != " << B[i] << std::endl; - if (mismatchCount >= 10) { - break; - } - } - } - - if (mismatchCount == 0) { - std::cout << "PASSED!\n"; - } else { - std::cout << "FAILED!\n"; - }; - } - - hipFree(Ad); - hipFree(Bd); - delete[] A; - delete[] B; - hipCtxDestroy(context); - return 0; -} diff --git a/projects/hip/samples/0_Intro/module_api_global/vcpy_kernel.cpp b/projects/hip/samples/0_Intro/module_api_global/vcpy_kernel.cpp deleted file mode 100644 index c0e820a4b7..0000000000 --- a/projects/hip/samples/0_Intro/module_api_global/vcpy_kernel.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright (c) 2017 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" - -#define ARRAY_SIZE (16) - -__device__ float myDeviceGlobal; -__device__ float myDeviceGlobalArray[16]; - -extern "C" __global__ void hello_world(const float* a, float* b) { - int tx = threadIdx.x; - b[tx] = a[tx]; -} - -extern "C" __global__ void test_globals(const float* a, float* b) { - int tx = threadIdx.x; - b[tx] = a[tx] + myDeviceGlobal + myDeviceGlobalArray[tx % ARRAY_SIZE]; -} diff --git a/projects/hip/samples/0_Intro/square/CMakeLists.txt b/projects/hip/samples/0_Intro/square/CMakeLists.txt deleted file mode 100644 index 104f828698..0000000000 --- a/projects/hip/samples/0_Intro/square/CMakeLists.txt +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -#Follow "README.md" to generate square.cpp if it's missing - -project(square) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# create square.cpp -execute_process(COMMAND sh -c "${ROCM_PATH}/hip/bin/hipify-perl ../square.cu > ../square.cpp") - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(square square.cpp) - -# Link with HIP -target_link_libraries(square hip::host) \ No newline at end of file diff --git a/projects/hip/samples/0_Intro/square/Makefile b/projects/hip/samples/0_Intro/square/Makefile deleted file mode 100644 index 83a37326ad..0000000000 --- a/projects/hip/samples/0_Intro/square/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIP_PLATFORM=$(shell $(HIP_PATH)/bin/hipconfig --platform) -HIPCC=$(HIP_PATH)/bin/hipcc - -ifeq (${HIP_PLATFORM}, nvidia) - SOURCES=square.cu -else - SOURCES=square.cpp -endif - -all: square.out - -# Step -square.cpp: square.cu - $(HIP_PATH)/bin/hipify-perl square.cu > square.cpp - -square.out: $(SOURCES) - $(HIPCC) $(CXXFLAGS) $(SOURCES) -o $@ - -clean: - rm -f *.o *.out square.cpp diff --git a/projects/hip/samples/0_Intro/square/README.md b/projects/hip/samples/0_Intro/square/README.md deleted file mode 100644 index e06fbceda1..0000000000 --- a/projects/hip/samples/0_Intro/square/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# Square.md - -Simple test below is an example, shows how to use hipify-perl to port CUDA code to HIP: - -- Add hip/bin path to the PATH - -``` -$ export PATH=$PATH:[MYHIP]/bin -``` - -- Define environment variable - -``` -$ export HIP_PATH=[MYHIP] -``` - -- Build executible file - -``` -$ cd ~/hip/samples/0_Intro/square -$ make -/opt/rocm/hip/bin/hipify-perl square.cu > square.cpp -/opt/rocm/hip/bin/hipcc square.cpp -o square.out -/opt/rocm/hip/bin/hipcc square.cpp -o square.out -``` -- Execute file -``` -$ ./square.out -info: running on device Navi 14 [Radeon Pro W5500] -info: allocate host mem ( 7.63 MB) -info: allocate device mem ( 7.63 MB) -info: copy Host2Device -info: launch 'vector_square' kernel -info: copy Device2Host -info: check result -PASSED! -``` diff --git a/projects/hip/samples/0_Intro/square/square.cu b/projects/hip/samples/0_Intro/square/square.cu deleted file mode 100644 index eba054b353..0000000000 --- a/projects/hip/samples/0_Intro/square/square.cu +++ /dev/null @@ -1,98 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include -#include - -#define CHECK(cmd) \ -{\ - cudaError_t error = cmd;\ - if (error != cudaSuccess) { \ - fprintf(stderr, "error: '%s'(%d) at %s:%d\n", cudaGetErrorString(error), error,__FILE__, __LINE__); \ - exit(EXIT_FAILURE);\ - }\ -} - - -/* - * Square each element in the array A and write to array C. - */ -template -__global__ void -vector_square(T *C_d, T *A_d, size_t N) -{ - size_t offset = (blockIdx.x * blockDim.x + threadIdx.x); - size_t stride = blockDim.x * gridDim.x ; - - for (size_t i=offset; i>> (C_d, A_d, N); - - printf ("info: copy Device2Host\n"); - CHECK ( cudaMemcpy(C_h, C_d, Nbytes, cudaMemcpyDeviceToHost)); - - printf ("info: check result\n"); - for (size_t i=0; i -#include "hip/hip_runtime.h" - -#define CHECK(cmd) \ - { \ - hipError_t error = cmd; \ - if (error != hipSuccess) { \ - fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), error, \ - __FILE__, __LINE__); \ - exit(EXIT_FAILURE); \ - } \ - } - -/* - * Square each element in the array A and write to array C. - */ -template -__global__ void vector_square(T* C_d, const T* A_d, size_t N) { - size_t offset = (blockIdx.x * blockDim.x + threadIdx.x); - size_t stride = blockDim.x * gridDim.x; - - for (size_t i = offset; i < N; i += stride) { - C_d[i] = A_d[i] * A_d[i]; - } -} - - -int main(int argc, char* argv[]) { - float *A_d, *C_d; - float *A_h, *C_h; - size_t N = 1000000; - size_t Nbytes = N * sizeof(float); - static int device = 0; - CHECK(hipSetDevice(device)); - hipDeviceProp_t props; - CHECK(hipGetDeviceProperties(&props, device /*deviceID*/)); - printf("info: running on device %s\n", props.name); -#ifdef __HIP_PLATFORM_AMD__ - printf("info: architecture on AMD GPU device is: %s\n", props.gcnArchName); -#endif - printf("info: allocate host mem (%6.2f MB)\n", 2 * Nbytes / 1024.0 / 1024.0); - A_h = (float*)malloc(Nbytes); - CHECK(A_h == 0 ? hipErrorOutOfMemory : hipSuccess); - C_h = (float*)malloc(Nbytes); - CHECK(C_h == 0 ? hipErrorOutOfMemory : hipSuccess); - // Fill with Phi + i - for (size_t i = 0; i < N; i++) { - A_h[i] = 1.618f + i; - } - - printf("info: allocate device mem (%6.2f MB)\n", 2 * Nbytes / 1024.0 / 1024.0); - CHECK(hipMalloc(&A_d, Nbytes)); - CHECK(hipMalloc(&C_d, Nbytes)); - - printf("info: copy Host2Device\n"); - CHECK(hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice)); - - const unsigned blocks = 512; - const unsigned threadsPerBlock = 256; - - printf("info: launch 'vector_square' kernel\n"); - hipLaunchKernelGGL(vector_square, dim3(blocks), dim3(threadsPerBlock), 0, 0, C_d, A_d, N); - - printf("info: copy Device2Host\n"); - CHECK(hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost)); - - printf("info: check result\n"); - for (size_t i = 0; i < N; i++) { - if (C_h[i] != A_h[i] * A_h[i]) { - CHECK(hipErrorUnknown); - } - } - printf("PASSED!\n"); -} diff --git a/projects/hip/samples/1_Utils/hipBusBandwidth/CMakeLists.txt b/projects/hip/samples/1_Utils/hipBusBandwidth/CMakeLists.txt deleted file mode 100644 index bfebb89e56..0000000000 --- a/projects/hip/samples/1_Utils/hipBusBandwidth/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(hipBusBandwidth) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(hipBusBandwidth hipBusBandwidth.cpp ResultDatabase.cpp) - -# Link with HIP -target_link_libraries(hipBusBandwidth hip::host) \ No newline at end of file diff --git a/projects/hip/samples/1_Utils/hipBusBandwidth/LICENSE.txt b/projects/hip/samples/1_Utils/hipBusBandwidth/LICENSE.txt deleted file mode 100644 index 5d0d603232..0000000000 --- a/projects/hip/samples/1_Utils/hipBusBandwidth/LICENSE.txt +++ /dev/null @@ -1,27 +0,0 @@ - -Copyright (c) 2011, UT-Battelle, LLC -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -* Neither the name of Oak Ridge National Laboratory, nor UT-Battelle, LLC, nor - the names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/projects/hip/samples/1_Utils/hipBusBandwidth/Makefile b/projects/hip/samples/1_Utils/hipBusBandwidth/Makefile deleted file mode 100644 index 5aad9411e3..0000000000 --- a/projects/hip/samples/1_Utils/hipBusBandwidth/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc - -EXE=hipBusBandwidth -CXXFLAGS = -O3 - -all: install - -$(EXE): hipBusBandwidth.cpp ResultDatabase.cpp - $(HIPCC) $(CXXFLAGS) $^ -o $@ - -install: $(EXE) - cp $(EXE) $(HIP_PATH)/bin - - -clean: - rm -f *.o $(EXE) diff --git a/projects/hip/samples/1_Utils/hipBusBandwidth/ResultDatabase.cpp b/projects/hip/samples/1_Utils/hipBusBandwidth/ResultDatabase.cpp deleted file mode 100644 index e094f70d07..0000000000 --- a/projects/hip/samples/1_Utils/hipBusBandwidth/ResultDatabase.cpp +++ /dev/null @@ -1,462 +0,0 @@ -#include "ResultDatabase.h" - -#include -#include -#include -#include - -using namespace std; - -#define SORT_RETAIN_ATTS_ORDER 1 - - -bool ResultDatabase::Result::operator<(const Result& rhs) const { - if (test < rhs.test) return true; - if (test > rhs.test) return false; -#if (SORT_RETAIN_ATTS_ORDER == 0) - // For ties, sort by the value of the attribute: - if (atts < rhs.atts) return true; - if (atts > rhs.atts) return false; -#endif - return false; // less-operator returns false on equal -} - -double ResultDatabase::Result::GetMin() const { - double r = FLT_MAX; - for (int i = 0; i < value.size(); i++) { - r = min(r, value[i]); - } - return r; -} - -double ResultDatabase::Result::GetMax() const { - double r = -FLT_MAX; - for (int i = 0; i < value.size(); i++) { - r = max(r, value[i]); - } - return r; -} - -double ResultDatabase::Result::GetMedian() const { return GetPercentile(50); } - -double ResultDatabase::Result::GetPercentile(double q) const { - int n = value.size(); - if (n == 0) return FLT_MAX; - if (n == 1) return value[0]; - - if (q <= 0) return value[0]; - if (q >= 100) return value[n - 1]; - - double index = ((n + 1.) * q / 100.) - 1; - - vector sorted = value; - sort(sorted.begin(), sorted.end()); - - if (n == 2) return (sorted[0] * (1 - q / 100.) + sorted[1] * (q / 100.)); - - int index_lo = int(index); - double frac = index - index_lo; - if (frac == 0) return sorted[index_lo]; - - double lo = sorted[index_lo]; - double hi = sorted[index_lo + 1]; - return lo + (hi - lo) * frac; -} - -double ResultDatabase::Result::GetMean() const { - double r = 0; - for (int i = 0; i < value.size(); i++) { - r += value[i]; - } - return r / double(value.size()); -} - -double ResultDatabase::Result::GetStdDev() const { - double r = 0; - double u = GetMean(); - if (u == FLT_MAX) return FLT_MAX; - for (int i = 0; i < value.size(); i++) { - r += (value[i] - u) * (value[i] - u); - } - r = sqrt(r / value.size()); - return r; -} - - -void ResultDatabase::AddResults(const string& test, const string& atts, const string& unit, - const vector& values) { - for (int i = 0; i < values.size(); i++) { - AddResult(test, atts, unit, values[i]); - } -} - -static string RemoveAllButLeadingSpaces(const string& a) { - string b; - int n = a.length(); - int i = 0; - while (i < n && a[i] == ' ') { - b += a[i]; - ++i; - } - for (; i < n; i++) { - if (a[i] != ' ' && a[i] != '\t') b += a[i]; - } - return b; -} - -void ResultDatabase::AddResult(const string& test_orig, const string& atts_orig, - const string& unit_orig, double value) { - string test = RemoveAllButLeadingSpaces(test_orig); - string atts = RemoveAllButLeadingSpaces(atts_orig); - string unit = RemoveAllButLeadingSpaces(unit_orig); - int index; - for (index = 0; index < results.size(); index++) { - if (results[index].test == test && results[index].atts == atts) { - if (results[index].unit != unit) throw "Internal error: mixed units"; - - break; - } - } - - if (index >= results.size()) { - Result r; - r.test = test; - r.atts = atts; - r.unit = unit; - results.push_back(r); - } - - results[index].value.push_back(value); -} - -// **************************************************************************** -// Method: ResultDatabase::DumpDetailed -// -// Purpose: -// Writes the full results, including all trials. -// -// Arguments: -// out where to print -// -// Programmer: Jeremy Meredith -// Creation: August 14, 2009 -// -// Modifications: -// Jeremy Meredith, Wed Nov 10 14:25:17 EST 2010 -// Renamed to DumpDetailed to make room for a DumpSummary. -// -// Jeremy Meredith, Thu Nov 11 11:39:57 EST 2010 -// Added note about (*) missing value tag. -// -// Jeremy Meredith, Tue Nov 23 13:57:02 EST 2010 -// Changed note about missing values to be worded a little better. -// -// **************************************************************************** -void ResultDatabase::DumpDetailed(ostream& out) { - vector sorted(results); - - stable_sort(sorted.begin(), sorted.end()); - - const int testNameW = 24; - const int attW = 12; - const int fieldW = 11; - out << std::fixed << right << std::setprecision(4); - - int maxtrials = 1; - for (int i = 0; i < sorted.size(); i++) { - if (sorted[i].value.size() > maxtrials) maxtrials = sorted[i].value.size(); - } - - // TODO: in big parallel runs, the "trials" are the procs - // and we really don't want to print them all out.... - out << setw(testNameW) << "test\t" << setw(attW) << "atts\t" << setw(fieldW) << "median\t" - << "mean\t" - << "stddev\t" - << "min\t" - << "max\t"; - for (int i = 0; i < maxtrials; i++) out << "trial" << i << "\t"; - out << endl; - - for (int i = 0; i < sorted.size(); i++) { - Result& r = sorted[i]; - out << setw(testNameW) << r.test + "\t"; - out << setw(attW) << r.atts + "\t"; - out << setw(fieldW) << r.unit + "\t"; - if (r.GetMedian() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMedian() << "\t"; - if (r.GetMean() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMean() << "\t"; - if (r.GetStdDev() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetStdDev() << "\t"; - if (r.GetMin() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMin() << "\t"; - if (r.GetMax() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMax() << "\t"; - for (int j = 0; j < r.value.size(); j++) { - if (r.value[j] == FLT_MAX) - out << "N/A\t"; - else - out << r.value[j] << "\t"; - } - - out << endl; - } - out << endl - << "Note: Any results marked with (*) had missing values." << endl - << " This can occur on systems with a mixture of" << endl - << " device types or architectural capabilities." << endl; -} - - -// **************************************************************************** -// Method: ResultDatabase::DumpDetailed -// -// Purpose: -// Writes the summary results (min/max/stddev/med/mean), but not -// every individual trial. -// -// Arguments: -// out where to print -// -// Programmer: Jeremy Meredith -// Creation: November 10, 2010 -// -// Modifications: -// Jeremy Meredith, Thu Nov 11 11:39:57 EST 2010 -// Added note about (*) missing value tag. -// -// **************************************************************************** -void ResultDatabase::DumpSummary(ostream& out) { - vector sorted(results); - - stable_sort(sorted.begin(), sorted.end()); - - const int testNameW = 24; - const int attW = 12; - const int fieldW = 9; - out << std::fixed << right << std::setprecision(4); - - // TODO: in big parallel runs, the "trials" are the procs - // and we really don't want to print them all out.... - out << setw(testNameW) << "test\t" << setw(attW) << "atts\t" << setw(fieldW) << "units\t" - << "median\t" - << "mean\t" - << "stddev\t" - << "min\t" - << "max\t"; - out << endl; - - for (int i = 0; i < sorted.size(); i++) { - Result& r = sorted[i]; - out << setw(testNameW) << r.test + "\t"; - out << setw(attW) << r.atts + "\t"; - out << setw(fieldW) << r.unit + "\t"; - if (r.GetMedian() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMedian() << "\t"; - if (r.GetMean() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMean() << "\t"; - if (r.GetStdDev() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetStdDev() << "\t"; - if (r.GetMin() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMin() << "\t"; - if (r.GetMax() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMax() << "\t"; - - out << endl; - } - out << endl - << "Note: results marked with (*) had missing values such as" << endl - << "might occur with a mixture of architectural capabilities." << endl; -} - -// **************************************************************************** -// Method: ResultDatabase::ClearAllResults -// -// Purpose: -// Clears all existing results from the ResultDatabase; used for multiple passes -// of the same test or multiple tests. -// -// Arguments: -// -// Programmer: Jeffrey Young -// Creation: September 10th, 2014 -// -// Modifications: -// -// -// **************************************************************************** -void ResultDatabase::ClearAllResults() { results.clear(); } - -// **************************************************************************** -// Method: ResultDatabase::DumpCsv -// -// Purpose: -// Writes either detailed or summary results (min/max/stddev/med/mean), but not -// every individual trial. -// -// Arguments: -// out file to print CSV results -// -// Programmer: Jeffrey Young -// Creation: August 28th, 2014 -// -// Modifications: -// -// **************************************************************************** -void ResultDatabase::DumpCsv(string fileName) { - bool emptyFile; - vector sorted(results); - - stable_sort(sorted.begin(), sorted.end()); - - // Check to see if the file is empty - if so, add the headers - emptyFile = this->IsFileEmpty(fileName); - - // Open file and append by default - ofstream out; - out.open(fileName.c_str(), std::ofstream::out | std::ofstream::app); - - // Add headers only for empty files - if (emptyFile) { - // TODO: in big parallel runs, the "trials" are the procs - // and we really don't want to print them all out.... - out << "test, " - << "atts, " - << "units, " - << "median, " - << "mean, " - << "stddev, " - << "min, " - << "max, "; - out << endl; - } - - for (int i = 0; i < sorted.size(); i++) { - Result& r = sorted[i]; - out << r.test << ", "; - out << r.atts << ", "; - out << r.unit << ", "; - if (r.GetMedian() == FLT_MAX) - out << "N/A, "; - else - out << r.GetMedian() << ", "; - if (r.GetMean() == FLT_MAX) - out << "N/A, "; - else - out << r.GetMean() << ", "; - if (r.GetStdDev() == FLT_MAX) - out << "N/A, "; - else - out << r.GetStdDev() << ", "; - if (r.GetMin() == FLT_MAX) - out << "N/A, "; - else - out << r.GetMin() << ", "; - if (r.GetMax() == FLT_MAX) - out << "N/A, "; - else - out << r.GetMax() << ", "; - - out << endl; - } - out << endl; - - out.close(); -} - -// **************************************************************************** -// Method: ResultDatabase::IsFileEmpty -// -// Purpose: -// Returns whether a file is empty - used as a helper for CSV printing -// -// Arguments: -// file The input file to check for emptiness -// -// Programmer: Jeffrey Young -// Creation: August 28th, 2014 -// -// Modifications: -// -// **************************************************************************** - -bool ResultDatabase::IsFileEmpty(string fileName) { - - ifstream file(fileName.c_str()); - - // If the file doesn't exist it is by definition empty - if (!file.good()) { - return true; - } else { - bool fileEmpty; - fileEmpty = (bool)(file.peek() == ifstream::traits_type::eof()); - file.close(); - - return fileEmpty; - } - - // Otherwise, return false - return false; -} - - -// **************************************************************************** -// Method: ResultDatabase::GetResultsForTest -// -// Purpose: -// Returns a vector of results for just one test name. -// -// Arguments: -// test the name of the test results to search for -// -// Programmer: Jeremy Meredith -// Creation: December 3, 2010 -// -// Modifications: -// -// **************************************************************************** -vector ResultDatabase::GetResultsForTest(const string& test) { - // get only the given test results - vector retval; - for (int i = 0; i < results.size(); i++) { - Result& r = results[i]; - if (r.test == test) retval.push_back(r); - } - return retval; -} - -// **************************************************************************** -// Method: ResultDatabase::GetResults -// -// Purpose: -// Returns all the results. -// -// Arguments: -// -// Programmer: Jeremy Meredith -// Creation: December 3, 2010 -// -// Modifications: -// -// **************************************************************************** -const vector& ResultDatabase::GetResults() const { return results; } diff --git a/projects/hip/samples/1_Utils/hipBusBandwidth/ResultDatabase.h b/projects/hip/samples/1_Utils/hipBusBandwidth/ResultDatabase.h deleted file mode 100644 index ca6a00fc91..0000000000 --- a/projects/hip/samples/1_Utils/hipBusBandwidth/ResultDatabase.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef RESULT_DATABASE_H -#define RESULT_DATABASE_H - -#include -#include -#include -#include -#include -using std::ifstream; -using std::ofstream; -using std::ostream; -using std::string; -using std::vector; - - -// **************************************************************************** -// Class: ResultDatabase -// -// Purpose: -// Track numerical results as they are generated. -// Print statistics of raw results. -// -// Programmer: Jeremy Meredith -// Creation: June 12, 2009 -// -// Modifications: -// Jeremy Meredith, Wed Nov 10 14:20:47 EST 2010 -// Split timing reports into detailed and summary. E.g. for serial code, -// we might report all trial values, but skip them in parallel. -// -// Jeremy Meredith, Thu Nov 11 11:40:18 EST 2010 -// Added check for missing value tag. -// -// Jeremy Meredith, Mon Nov 22 13:37:10 EST 2010 -// Added percentile statistic. -// -// Jeremy Meredith, Fri Dec 3 16:30:31 EST 2010 -// Added a method to extract a subset of results based on test name. Also, -// the Result class is now public, so that clients can use them directly. -// Added a GetResults method as well, and made several functions const. -// -// **************************************************************************** -class ResultDatabase { - public: - // - // A performance result for a single SHOC benchmark run. - // - struct Result { - string test; // e.g. "readback" - string atts; // e.g. "pagelocked 4k^2" - string unit; // e.g. "MB/sec" - vector value; // e.g. "837.14" - double GetMin() const; - double GetMax() const; - double GetMedian() const; - double GetPercentile(double q) const; - double GetMean() const; - double GetStdDev() const; - - bool operator<(const Result& rhs) const; - - bool HadAnyFLTMAXValues() const { - for (int i = 0; i < value.size(); ++i) { - if (value[i] >= FLT_MAX) return true; - } - return false; - } - }; - - protected: - vector results; - - public: - void AddResult(const string& test, const string& atts, const string& unit, double value); - void AddResults(const string& test, const string& atts, const string& unit, - const vector& values); - vector GetResultsForTest(const string& test); - const vector& GetResults() const; - void ClearAllResults(); - void DumpDetailed(ostream&); - void DumpSummary(ostream&); - void DumpCsv(string fileName); - - private: - bool IsFileEmpty(string fileName); -}; - - -#endif diff --git a/projects/hip/samples/1_Utils/hipBusBandwidth/hipBusBandwidth.cpp b/projects/hip/samples/1_Utils/hipBusBandwidth/hipBusBandwidth.cpp deleted file mode 100644 index 5a7e45f6bf..0000000000 --- a/projects/hip/samples/1_Utils/hipBusBandwidth/hipBusBandwidth.cpp +++ /dev/null @@ -1,1072 +0,0 @@ -#include -#include -#include -#include -#include "hip/hip_runtime.h" - -#include "ResultDatabase.h" - -enum MallocMode { MallocPinned, MallocUnpinned, MallocRegistered }; - -// Cmdline parms: -bool p_verbose = false; -MallocMode p_malloc_mode = MallocPinned; -int p_numa_ctl = -1; -int p_iterations = 0; -int p_beatsperiteration = 1; -int p_device = 0; -int p_detailed = 0; -bool p_async = 0; -int p_alignedhost = - 0; // align host allocs to this granularity, in bytes. 64 or 4096 are good values to try. -int p_onesize = 0; - -bool p_h2d = true; -bool p_d2h = true; -bool p_bidir = true; -bool p_p2p = false; - - -//#define NO_CHECK - - -#define CHECK_HIP_ERROR() \ - { \ - hipError_t err = hipGetLastError(); \ - if (err != hipSuccess) { \ - printf( \ - "error=%d name=%s at " \ - "ln: %d\n ", \ - err, hipGetErrorString(err), __LINE__); \ - exit(EXIT_FAILURE); \ - } \ - } - - -std::string mallocModeString(int mallocMode) { - switch (mallocMode) { - case MallocPinned: - return "pinned"; - case MallocUnpinned: - return "unpinned"; - case MallocRegistered: - return "registered"; - default: - return "mallocmode-UNKNOWN"; - }; -}; - -// **************************************************************************** -int sizeToBytes(int size) { return (size < 0) ? -size : size * 1024; } - - -// **************************************************************************** -std::string sizeToString(int size) { - using namespace std; - stringstream ss; - if (size < 0) { - // char (-) lexically sorts before " " so will cause Byte values to be displayed before kB. - ss << "+" << setfill('0') << setw(3) << -size << "By"; - } else { - ss << size << "kB"; - } - return ss.str(); -} - - -// **************************************************************************** -hipError_t memcopy(void* dst, const void* src, size_t sizeBytes, enum hipMemcpyKind kind) { - if (p_async) { - return hipMemcpyAsync(dst, src, sizeBytes, kind, NULL); - } else { - return hipMemcpy(dst, src, sizeBytes, kind); - } -} - - -// **************************************************************************** -// -sizes are in bytes, +sizes are in kb, last size must be largest -int sizes[] = {-64, -256, -512, 1, 2, 4, 8, 16, 32, 64, 128, 256, - 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288}; -int nSizes = sizeof(sizes) / sizeof(int); -// iterations to be run for the corresponding sizes, less number as the size increases -int iterations[] = {1000, 1000, 1000, 1000, 500, 500, 500, 500, 500, 200, 200, 200, - 200, 200, 100, 100, 100, 100, 50, 50, 50, 20, 20}; - -// **************************************************************************** -// Function: RunBenchmark_H2D -// -// Purpose: -// Measures the bandwidth of the bus connecting the host processor to the -// OpenCL device. This benchmark repeatedly transfers data chunks of various -// sizes across the bus to the OpenCL device, and calculates the bandwidth. -// -// -// Arguments: -// -// Returns: nothing -// -// Programmer: Jeremy Meredith -// Creation: September 08, 2009 -// -// Modifications: -// Jeremy Meredith, Wed Dec 1 17:05:27 EST 2010 -// Added calculation of latency estimate. -// Ben Sander - moved to standalone test -// -// **************************************************************************** -void RunBenchmark_H2D(ResultDatabase& resultDB) { - long long numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - - hipSetDevice(p_device); - - // Create some host memory pattern - float* hostMem = NULL; - if (p_malloc_mode == MallocPinned) { - hipHostMalloc((void**)&hostMem, sizeof(float) * numMaxFloats); - while (hipGetLastError() != hipSuccess) { - // drop the size and try again - if (p_verbose) std::cout << " - dropping size allocating pinned mem\n"; - --nSizes; - if (nSizes < 1) { - std::cerr << "Error: Couldn't allocate any pinned buffer\n"; - return; - } - numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - hipHostMalloc((void**)&hostMem, sizeof(float) * numMaxFloats); - } - } else if (p_malloc_mode == MallocUnpinned) { - if (p_alignedhost) { - #ifdef _WIN32 - hostMem = (float*)_aligned_malloc(numMaxFloats * sizeof(float),p_alignedhost); - #else - hostMem = (float*)aligned_alloc(p_alignedhost, numMaxFloats * sizeof(float)); - #endif - } else { - hostMem = new float[numMaxFloats]; - } - } else if (p_malloc_mode == MallocRegistered) { - if (p_numa_ctl == -1) { - hostMem = (float*)malloc(numMaxFloats * sizeof(float)); - } - - hipHostRegister(hostMem, numMaxFloats * sizeof(float), 0); - CHECK_HIP_ERROR(); - } else { - assert(0); - } - - for (int i = 0; i < numMaxFloats; i++) { - hostMem[i] = i % 77; - } - - float* device; - hipMalloc((void**)&device, sizeof(float) * numMaxFloats); - while (hipGetLastError() != hipSuccess) { - // drop the size and try again - if (p_verbose) std::cout << " - dropping size allocating device mem\n"; - --nSizes; - if (nSizes < 1) { - std::cerr << "Error: Couldn't allocate any device buffer\n"; - return; - } - numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - hipMalloc((void**)&device, sizeof(float) * numMaxFloats); - } - - - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - CHECK_HIP_ERROR(); - - // store the times temporarily to estimate latency - // float times[nSizes]; - for (int i = 0; i < nSizes; i++) { - int sizeIndex, iterIndex; - sizeIndex = i; - iterIndex = i; - - const int thisSize = p_onesize ? p_onesize : sizes[sizeIndex]; - const int nbytes = sizeToBytes(thisSize); - const int niter = p_iterations ? p_iterations : iterations[iterIndex]; - for (int pass = 0; pass < niter; pass++) { - - hipEventRecord(start, 0); - for (int j = 0; j < p_beatsperiteration; j++) { - memcopy(device, hostMem, nbytes, hipMemcpyHostToDevice); - } - hipEventRecord(stop, 0); - hipEventSynchronize(stop); - float t = 0; - hipEventElapsedTime(&t, start, stop); - // times[sizeIndex] = t; - // Convert to GB/sec - if (p_verbose) { - std::cerr << "size " << sizeToString(thisSize) << " took " << t << " ms\n"; - } - - double speed = - (double(double(sizeToBytes(thisSize)/1000) * p_beatsperiteration) / 1000) / t; - char sizeStr[256]; - if (p_beatsperiteration > 1) { - sprintf(sizeStr, "%9sx%d", sizeToString(thisSize).c_str(), p_beatsperiteration); - } else { - sprintf(sizeStr, "%9s", sizeToString(thisSize).c_str()); - } - resultDB.AddResult(std::string("H2D_Bandwidth") + "_" + mallocModeString(p_malloc_mode), - sizeStr, "GB/sec", speed); - resultDB.AddResult(std::string("H2D_Time") + mallocModeString(p_malloc_mode), sizeStr, "ms", t); - - } - if (p_onesize) { - break; - } - } - - if (p_onesize) { - numMaxFloats = sizeToBytes(p_onesize) / sizeof(float); - } - -#ifndef NO_CHECK - - // Check. First reset the host memory, then copy-back result. Then compare against original - // ref value. - for (int i = 0; i < numMaxFloats; i++) { - hostMem[i] = 0; - } - hipMemcpy(hostMem, device, numMaxFloats * sizeof(float), hipMemcpyDeviceToHost); - for (int i = 0; i < numMaxFloats; i++) { - float ref = i % 77; - if (ref != hostMem[i]) { - printf("error: H2D. i=%d reference:%6.f != copyback:%6.2f\n", i, ref, hostMem[i]); - } - } -#endif - - - // Cleanup - hipFree((void*)device); - CHECK_HIP_ERROR(); - switch (p_malloc_mode) { - case MallocPinned: - hipHostFree((void*)hostMem); - CHECK_HIP_ERROR(); - break; - - case MallocUnpinned: - if (p_alignedhost) { - free(hostMem); - } else { - delete[] hostMem; - } - break; - - case MallocRegistered: - hipHostUnregister(hostMem); - CHECK_HIP_ERROR(); - free(hostMem); - break; - default: - assert(0); - } - - - hipEventDestroy(start); - hipEventDestroy(stop); -} - - -// **************************************************************************** -void RunBenchmark_D2H(ResultDatabase& resultDB) { - long long numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - - // Create some host memory pattern - float* hostMem1; - float* hostMem2; - if (p_malloc_mode == MallocPinned) { - hipHostMalloc((void**)&hostMem1, sizeof(float) * numMaxFloats); - hipError_t err1 = hipGetLastError(); - hipHostMalloc((void**)&hostMem2, sizeof(float) * numMaxFloats); - hipError_t err2 = hipGetLastError(); - while (err1 != hipSuccess || err2 != hipSuccess) { - // free the first buffer if only the second failed - if (err1 == hipSuccess) hipHostFree((void*)hostMem1); - - // drop the size and try again - if (p_verbose) std::cout << " - dropping size allocating pinned mem\n"; - --nSizes; - if (nSizes < 1) { - std::cerr << "Error: Couldn't allocate any pinned buffer\n"; - return; - } - numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - hipHostMalloc((void**)&hostMem1, sizeof(float) * numMaxFloats); - err1 = hipGetLastError(); - hipHostMalloc((void**)&hostMem2, sizeof(float) * numMaxFloats); - err2 = hipGetLastError(); - } - } else if (p_malloc_mode == MallocUnpinned) { - hostMem1 = new float[numMaxFloats]; - hostMem2 = new float[numMaxFloats]; - } else if (p_malloc_mode == MallocRegistered) { - if (p_numa_ctl == -1) { - hostMem1 = (float*)malloc(numMaxFloats * sizeof(float)); - hostMem2 = (float*)malloc(numMaxFloats * sizeof(float)); - } - - hipHostRegister(hostMem1, numMaxFloats * sizeof(float), 0); - CHECK_HIP_ERROR(); - hipHostRegister(hostMem2, numMaxFloats * sizeof(float), 0); - CHECK_HIP_ERROR(); - } else { - assert(0); - } - - - for (int i = 0; i < numMaxFloats; i++) hostMem1[i] = i % 77; - - float* device; - hipMalloc((void**)&device, sizeof(float) * numMaxFloats); - while (hipGetLastError() != hipSuccess) { - // drop the size and try again - if (p_verbose) std::cout << " - dropping size allocating device mem\n"; - --nSizes; - if (nSizes < 1) { - std::cerr << "Error: Couldn't allocate any device buffer\n"; - return; - } - numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - hipMalloc((void**)&device, sizeof(float) * numMaxFloats); - } - - hipMemcpy(device, hostMem1, numMaxFloats * sizeof(float), hipMemcpyHostToDevice); - hipDeviceSynchronize(); - - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - CHECK_HIP_ERROR(); - - // store the times temporarily to estimate latency - // float times[nSizes]; - for (int i = 0; i < nSizes; i++) { - int sizeIndex, iterIndex; - sizeIndex = i; - iterIndex = i; - - const int thisSize = p_onesize ? p_onesize : sizes[sizeIndex]; - const int nbytes = sizeToBytes(thisSize); - const int niter = p_iterations ? p_iterations : iterations[iterIndex]; - for (int pass = 0; pass < niter; pass++) { - - hipEventRecord(start, 0); - for (int j = 0; j < p_beatsperiteration; j++) { - memcopy(hostMem2, device, nbytes, hipMemcpyDeviceToHost); - } - hipEventRecord(stop, 0); - hipEventSynchronize(stop); - float t = 0; - hipEventElapsedTime(&t, start, stop); - // times[sizeIndex] = t; - // Convert to GB/sec - if (p_verbose) { - std::cerr << "size " << sizeToString(thisSize) << " took " << t << " ms\n"; - } - - double speed = - (double(double(sizeToBytes(thisSize)/1000) * p_beatsperiteration) / 1000) / t; - char sizeStr[256]; - sprintf(sizeStr, "%9s", sizeToString(thisSize).c_str()); - if (p_beatsperiteration > 1) { - sprintf(sizeStr, "%9sx%d", sizeToString(thisSize).c_str(), p_beatsperiteration); - } else { - sprintf(sizeStr, "%9s", sizeToString(thisSize).c_str()); - } - resultDB.AddResult(std::string("D2H_Bandwidth") + "_" + mallocModeString(p_malloc_mode), - sizeStr, "GB/sec", speed); - resultDB.AddResult(std::string("D2H_Time") + "_" + mallocModeString(p_malloc_mode), - sizeStr, "ms", t); - - } - if (p_onesize) { - break; - } - } - - if (p_onesize) { - numMaxFloats = sizeToBytes(p_onesize) / sizeof(float); - } - // Check. First reset the host memory, then copy-back result. Then compare against original - // ref value. - for (int i = 0; i < numMaxFloats; i++) { - float ref = i % 77; - if (ref != hostMem2[i]) { - printf("error: D2H. i=%d reference:%6.f != copyback:%6.2f\n", i, ref, hostMem2[i]); - } - } - - // Cleanup - hipFree((void*)device); - CHECK_HIP_ERROR(); - - switch (p_malloc_mode) { - case MallocPinned: - hipHostFree((void*)hostMem1); - CHECK_HIP_ERROR(); - hipHostFree((void*)hostMem2); - CHECK_HIP_ERROR(); - break; - case MallocUnpinned: - delete[] hostMem1; - delete[] hostMem2; - break; - case MallocRegistered: - hipHostUnregister(hostMem1); - CHECK_HIP_ERROR(); - free(hostMem1); - hipHostUnregister(hostMem2); - free(hostMem2); - break; - default: - assert(0); - } - - hipEventDestroy(start); - hipEventDestroy(stop); -} - - -void RunBenchmark_Bidir(ResultDatabase& resultDB) { - long long numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - - hipSetDevice(p_device); - - hipStream_t stream[2]; - - - // Create some host memory pattern - float* hostMem[2] = {NULL, NULL}; - if (p_malloc_mode == MallocPinned) { - while (1) { - hipError_t e1 = hipHostMalloc((void**)&hostMem[0], sizeof(float) * numMaxFloats); - hipError_t e2 = hipHostMalloc((void**)&hostMem[1], sizeof(float) * numMaxFloats); - - if ((e1 == hipSuccess) && (e2 == hipSuccess)) { - break; - } else { - // drop the size and try again - if (p_verbose) std::cout << " - dropping size allocating pinned mem\n"; - --nSizes; - if (nSizes < 1) { - std::cerr << "Error: Couldn't allocate any pinned buffer\n"; - return; - } - numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - } - } - } else if (p_malloc_mode == MallocUnpinned) { - hostMem[0] = new float[numMaxFloats]; - hostMem[1] = new float[numMaxFloats]; - } else if (p_malloc_mode == MallocRegistered) { - if (p_numa_ctl == -1) { - hostMem[0] = (float*)malloc(numMaxFloats * sizeof(float)); - hostMem[1] = (float*)malloc(numMaxFloats * sizeof(float)); - } - hipHostRegister(hostMem[0], numMaxFloats * sizeof(float), 0); - CHECK_HIP_ERROR(); - hipHostRegister(hostMem[1], numMaxFloats * sizeof(float), 0); - CHECK_HIP_ERROR(); - } else { - assert(0); - } - - - for (int i = 0; i < numMaxFloats; i++) { - hostMem[0][i] = i % 77; - } - - float* deviceMem[2]; - while (1) { - hipError_t e1 = hipMalloc((void**)&deviceMem[0], sizeof(float) * numMaxFloats); - hipError_t e2 = hipMalloc((void**)&deviceMem[1], sizeof(float) * numMaxFloats); - - if ((e1 == hipSuccess) && (e2 == hipSuccess)) { - break; - } else { - if (e1) { - // First alloc succeeded, so free it before trying again - hipFree(&deviceMem[0]); - } - // drop the size and try again - if (p_verbose) std::cout << " - dropping size allocating device mem\n"; - --nSizes; - if (nSizes < 1) { - std::cerr << "Error: Couldn't allocate any device buffer\n"; - return; - } - numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - } - }; - - - hipMemset(deviceMem[1], 0xFA, numMaxFloats); - - - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - CHECK_HIP_ERROR(); - hipStreamCreate(&stream[0]); - hipStreamCreate(&stream[1]); - - // store the times temporarily to estimate latency - // float times[nSizes]; - for (int i = 0; i < nSizes; i++) { - int sizeIndex, iterIndex; - sizeIndex = i; - iterIndex = i; - - const int thisSize = p_onesize ? p_onesize : sizes[sizeIndex]; - const int nbytes = sizeToBytes(thisSize); - const int niter = p_iterations ? p_iterations : iterations[iterIndex]; - for (int pass = 0; pass < niter; pass++) { - - hipEventRecord(start, 0); - hipMemcpyAsync(deviceMem[0], hostMem[0], nbytes, hipMemcpyHostToDevice, stream[0]); - hipMemcpyAsync(hostMem[1], deviceMem[1], nbytes, hipMemcpyDeviceToHost, stream[1]); - hipEventRecord(stop, 0); - hipEventSynchronize(stop); - float t = 0; - hipEventElapsedTime(&t, start, stop); - - // Convert to GB/sec - if (p_verbose) { - std::cerr << "size " << sizeToString(thisSize) << " took " << t << " ms\n"; - } - - double speed = (double(sizeToBytes(2 * thisSize)) / (1000 * 1000)) / t; - char sizeStr[256]; - sprintf(sizeStr, "%9s", sizeToString(thisSize).c_str()); - resultDB.AddResult( - std::string("Bidir_Bandwidth") + "_" + mallocModeString(p_malloc_mode), sizeStr, - "GB/sec", speed); - resultDB.AddResult(std::string("Bidir_Time") + "_" + mallocModeString(p_malloc_mode), - sizeStr, "ms", t); - } - if (p_onesize) { - break; - } - } - - // Cleanup - hipFree((void*)deviceMem[0]); - hipFree((void*)deviceMem[1]); - CHECK_HIP_ERROR(); - switch (p_malloc_mode) { - case MallocPinned: - hipHostFree((void*)hostMem[0]); - hipHostFree((void*)hostMem[1]); - CHECK_HIP_ERROR(); - break; - case MallocUnpinned: - delete[] hostMem[0]; - delete[] hostMem[1]; - break; - case MallocRegistered: - for (int i = 0; i < 2; i++) { - hipHostUnregister(hostMem[i]); - CHECK_HIP_ERROR(); - free(hostMem[i]); - } - break; - default: - assert(0); - }; - - hipEventDestroy(start); - hipEventDestroy(stop); - hipStreamDestroy(stream[0]); - hipStreamDestroy(stream[1]); -} - - -#define failed(...) \ - printf("error: "); \ - printf(__VA_ARGS__); \ - printf("\n"); \ - exit(EXIT_FAILURE); - -int parseInt(const char* str, int* output) { - char* next; - *output = strtol(str, &next, 0); - return !strlen(next); -} - - -void checkPeer2PeerSupport() { - int deviceCnt; - hipGetDeviceCount(&deviceCnt); - std::cout << "Total no. of available gpu #" << deviceCnt << "\n" << std::endl; - - for (int deviceId = 0; deviceId < deviceCnt; deviceId++) { - hipDeviceProp_t props; - hipGetDeviceProperties(&props, deviceId); - std::cout << "for gpu#" << deviceId << " " << props.name << std::endl; - std::cout << " peer2peer supported : "; - int PeerCnt = 0; - for (int i = 0; i < deviceCnt; i++) { - int isPeer; - hipDeviceCanAccessPeer(&isPeer, i, deviceId); - if (isPeer) { - std::cout << "gpu#" << i << " "; - ++PeerCnt; - } - } - if (PeerCnt == 0) - std::cout << "NONE" - << " "; - - std::cout << std::endl; - std::cout << " peer2peer not supported : "; - int nonPeerCnt = 0; - for (int i = 0; i < deviceCnt; i++) { - int isPeer; - hipDeviceCanAccessPeer(&isPeer, i, deviceId); - if (!isPeer && (i != deviceId)) { - std::cout << "gpu#" << i << " "; - ++nonPeerCnt; - } - } - if (nonPeerCnt == 0) - std::cout << "NONE" - << " "; - - std::cout << "\n" << std::endl; - } - - std::cout << "\nNote: For non-supported peer2peer devices, memcopy will use/follow the normal " - "behaviour (GPU1-->host then host-->GPU2)\n\n" - << std::endl; -} - -void enablePeer2Peer(int currentGpu, int peerGpu) { - int canAccessPeer; - - hipSetDevice(currentGpu); - hipDeviceCanAccessPeer(&canAccessPeer, currentGpu, peerGpu); - - if (canAccessPeer == 1) { - hipDeviceEnablePeerAccess(peerGpu, 0); - } -} - -void disablePeer2Peer(int currentGpu, int peerGpu) { - int canAccessPeer; - - hipSetDevice(currentGpu); - hipDeviceCanAccessPeer(&canAccessPeer, currentGpu, peerGpu); - - if (canAccessPeer == 1) { - hipDeviceDisablePeerAccess(peerGpu); - } -} - -std::string gpuIDToString(int gpuID) { - using namespace std; - stringstream ss; - ss << gpuID; - return ss.str(); -} - -void RunBenchmark_P2P_Unidir(ResultDatabase& resultDB) { - int gpuCount; - hipGetDeviceCount(&gpuCount); - - int currentGpu, peerGpu; - - long long numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - - for (currentGpu = 0; currentGpu < gpuCount; currentGpu++) { - for (peerGpu = 0; peerGpu < gpuCount; peerGpu++) { - if (currentGpu == peerGpu) continue; - - float *currentGpuMem, *peerGpuMem; - - hipSetDevice(currentGpu); - hipMalloc((void**)¤tGpuMem, sizeof(float) * numMaxFloats); - - hipSetDevice(peerGpu); - hipMalloc((void**)&peerGpuMem, sizeof(float) * numMaxFloats); - - enablePeer2Peer(currentGpu, peerGpu); - - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - CHECK_HIP_ERROR(); - - // store the times temporarily to estimate latency - // float times[nSizes]; - for (int i = 0; i < nSizes; i++) { - int sizeIndex, iterIndex; - sizeIndex = i; - iterIndex = i; - - const int thisSize = p_onesize ? p_onesize : sizes[sizeIndex]; - const int nbytes = sizeToBytes(thisSize); - const int niter = p_iterations ? p_iterations : iterations[iterIndex]; - for (int pass = 0; pass < niter; pass++) { - - hipDeviceSynchronize(); - - hipEventRecord(start, 0); - - for (int j = 0; j < p_beatsperiteration; j++) { - hipMemcpy(peerGpuMem, currentGpuMem, nbytes, hipMemcpyDeviceToDevice); - } - - hipEventRecord(stop, 0); - - hipEventSynchronize(stop); - - float t = 0; - hipEventElapsedTime(&t, start, stop); - // times[sizeIndex] = t; - - // Convert to GB/sec - if (p_verbose) { - std::cerr << "size " << sizeToString(thisSize) << " took " << t << " ms\n"; - } - - double speed = - (double(double(sizeToBytes(thisSize)/1000) * p_beatsperiteration) / 1000) / t; - char sizeStr[256]; - if (p_beatsperiteration > 1) { - sprintf(sizeStr, "%9sx%d", sizeToString(thisSize).c_str(), - p_beatsperiteration); - } else { - sprintf(sizeStr, "%9s", sizeToString(thisSize).c_str()); - } - - string cGpu, pGpu; - cGpu = gpuIDToString(currentGpu); - pGpu = gpuIDToString(peerGpu); - - resultDB.AddResult(std::string("p2p_uni") + "_gpu" + std::string(cGpu) + - "_gpu" + std::string(pGpu), - sizeStr, "GB/sec", speed); - resultDB.AddResult(std::string("P2P_uni") + "_gpu" + std::string(cGpu) + - "_gpu" + std::string(pGpu), - sizeStr, "ms", t); - - } - if (p_onesize) { - break; - } - } - - if (p_onesize) { - numMaxFloats = sizeToBytes(p_onesize) / sizeof(float); - } - - disablePeer2Peer(currentGpu, peerGpu); - - hipEventDestroy(start); - hipEventDestroy(stop); - - // Cleanup - hipFree((void*)currentGpuMem); - hipFree((void*)peerGpuMem); - CHECK_HIP_ERROR(); - - hipSetDevice(peerGpu); - hipDeviceReset(); - - hipSetDevice(currentGpu); - hipDeviceReset(); - } - } -} - -void RunBenchmark_P2P_Bidir(ResultDatabase& resultDB) { - int gpuCount; - hipGetDeviceCount(&gpuCount); - - hipStream_t stream[2]; - - int currentGpu, peerGpu; - - long long numMaxFloats = 1024 * (sizes[nSizes - 1]) / 4; - - for (currentGpu = 0; currentGpu < gpuCount; currentGpu++) { - for (peerGpu = 0; peerGpu < gpuCount; peerGpu++) { - if (currentGpu == peerGpu) continue; - - float *currentGpuMem[2], *peerGpuMem[2]; - - hipSetDevice(currentGpu); - hipMalloc((void**)¤tGpuMem[0], sizeof(float) * numMaxFloats); - hipMalloc((void**)¤tGpuMem[1], sizeof(float) * numMaxFloats); - enablePeer2Peer(peerGpu,currentGpu); - - hipSetDevice(peerGpu); - hipMalloc((void**)&peerGpuMem[0], sizeof(float) * numMaxFloats); - hipMalloc((void**)&peerGpuMem[1], sizeof(float) * numMaxFloats); - - enablePeer2Peer(currentGpu, peerGpu); - - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - CHECK_HIP_ERROR(); - - hipStreamCreate(&stream[0]); - hipStreamCreate(&stream[1]); - - // store the times temporarily to estimate latency - // float times[nSizes]; - for (int i = 0; i < nSizes; i++) { - int sizeIndex, iterIndex; - sizeIndex = i; - iterIndex = i; - - const int thisSize = p_onesize ? p_onesize : sizes[sizeIndex]; - const int nbytes = sizeToBytes(thisSize); - const int niter = p_iterations ? p_iterations : iterations[iterIndex]; - for (int pass = 0; pass < niter; pass++) { - - hipDeviceSynchronize(); - - hipEventRecord(start, 0); - - for (int j = 0; j < p_beatsperiteration; j++) { - hipMemcpyAsync(peerGpuMem[0], currentGpuMem[0], nbytes, - hipMemcpyDeviceToDevice, stream[0]); - hipMemcpyAsync(currentGpuMem[1], peerGpuMem[1], nbytes, - hipMemcpyDeviceToDevice, stream[1]); - } - - hipEventRecord(stop, 0); - - hipEventSynchronize(stop); - - float t = 0; - hipEventElapsedTime(&t, start, stop); - // times[sizeIndex] = t; - - // Convert to GB/sec - if (p_verbose) { - std::cerr << "size " << sizeToString(thisSize) << " took " << t << " ms\n"; - } - - double speed = - (double(double(sizeToBytes(2 * thisSize)/1000) * p_beatsperiteration) / 1000) / - t; - char sizeStr[256]; - if (p_beatsperiteration > 1) { - sprintf(sizeStr, "%9sx%d", sizeToString(thisSize).c_str(), - p_beatsperiteration); - } else { - sprintf(sizeStr, "%9s", sizeToString(thisSize).c_str()); - } - - string cGpu, pGpu; - cGpu = gpuIDToString(currentGpu); - pGpu = gpuIDToString(peerGpu); - - resultDB.AddResult(std::string("p2p_bi") + "_gpu" + std::string(cGpu) + "_gpu" + - std::string(pGpu), - sizeStr, "GB/sec", speed); - resultDB.AddResult(std::string("P2P_bi") + "_gpu" + std::string(cGpu) + "_gpu" + - std::string(pGpu), - sizeStr, "ms", t); - - } - if (p_onesize) { - break; - } - } - - if (p_onesize) { - numMaxFloats = sizeToBytes(p_onesize) / sizeof(float); - } - - disablePeer2Peer(currentGpu, peerGpu); - disablePeer2Peer(peerGpu, currentGpu); - - hipEventDestroy(start); - hipEventDestroy(stop); - - for (int i = 0; i < 2; i++) { - hipStreamDestroy(stream[i]); - - hipFree((void*)currentGpuMem[i]); - hipFree((void*)peerGpuMem[i]); - CHECK_HIP_ERROR(); - } - - hipSetDevice(peerGpu); - hipDeviceReset(); - - hipSetDevice(currentGpu); - hipDeviceReset(); - } - } -} - - -void printConfig() { - hipDeviceProp_t props; - hipGetDeviceProperties(&props, p_device); - - printf("Device:%s Mem=%.1fGB #CUs=%d Freq=%.0fMhz MallocMode=%s\n", props.name, - props.totalGlobalMem / 1024.0 / 1024.0 / 1024.0, props.multiProcessorCount, - props.clockRate / 1000.0, mallocModeString(p_malloc_mode).c_str()); -} - -void help() { - printf("Usage: hipBusBandwidth [OPTIONS]\n"); - printf(" --iterations, -i : Number of copy iterations to run.\n"); - printf( - " --beatsperiterations, -b : Number of beats (back-to-back copies of same size) per " - "iteration to run.\n"); - printf(" --device, -d : Device ID to use (0..numDevices).\n"); - printf(" --unpinned : Use unpinned host memory.\n"); - printf(" --d2h : Run only device-to-host test.\n"); - printf(" --h2d : Run only host-to-device test.\n"); - printf(" --bidir : Run only bidir copy test.\n"); - printf(" --p2p : Run only peer2peer unidir and bidir copy tests.\n"); - printf(" --verbose : Print verbose status messages as test is run.\n"); - printf(" --detailed : Print detailed report (including all trials).\n"); - printf( - " --async : Use hipMemcpyAsync(with NULL stream) for H2D/D2H. Default " - "uses hipMemcpy.\n"); - printf( - " --onesize, -o : Only run one measurement, at specified size (in KB, or if " - "negative in bytes)\n"); -}; - -int parseStandardArguments(int argc, char* argv[]) { - for (int i = 1; i < argc; i++) { - const char* arg = argv[i]; - - if (!strcmp(arg, " ")) { - // skip NULL args. - } else if (!strcmp(arg, "--iterations") || (!strcmp(arg, "-i"))) { - if (++i >= argc || !parseInt(argv[i], &p_iterations)) { - failed("Bad iterations argument"); - } - } else if (!strcmp(arg, "--beatsperiteration") || (!strcmp(arg, "-b"))) { - if (++i >= argc || !parseInt(argv[i], &p_beatsperiteration)) { - failed("Bad beatsperiteration argument"); - } - } else if (!strcmp(arg, "--device") || (!strcmp(arg, "-d"))) { - if (++i >= argc || !parseInt(argv[i], &p_device)) { - failed("Bad device argument"); - } - } else if (!strcmp(arg, "--onesize") || (!strcmp(arg, "-o"))) { - if (++i >= argc || !parseInt(argv[i], &p_onesize)) { - failed("Bad onesize argument"); - } - } else if (!strcmp(arg, "--unpinned")) { - p_malloc_mode = MallocUnpinned; - } else if (!strcmp(arg, "--registered")) { - p_malloc_mode = MallocRegistered; - } else if (!strcmp(arg, "--h2d")) { - p_h2d = true; - p_d2h = false; - p_bidir = false; - - } else if (!strcmp(arg, "--d2h")) { - p_h2d = false; - p_d2h = true; - p_bidir = false; - - } else if (!strcmp(arg, "--bidir")) { - p_h2d = false; - p_d2h = false; - p_bidir = true; - - } else if (!strcmp(arg, "--p2p")) { - p_h2d = false; - p_d2h = false; - p_bidir = false; - p_p2p = true; - - } else if (!strcmp(arg, "--help") || (!strcmp(arg, "-h"))) { - help(); - exit(EXIT_SUCCESS); - - - } else if (!strcmp(arg, "--verbose")) { - p_verbose = 1; - } else if (!strcmp(arg, "--async")) { - p_async = 1; - } else if (!strcmp(arg, "--detailed")) { - p_detailed = 1; - } else { - failed("Bad argument '%s'", arg); - } - } - - return 0; -}; - - -int main(int argc, char* argv[]) { - parseStandardArguments(argc, argv); - - if (p_p2p) { - checkPeer2PeerSupport(); - - ResultDatabase resultDB_Unidir, resultDB_Bidir; - - RunBenchmark_P2P_Unidir(resultDB_Unidir); - RunBenchmark_P2P_Bidir(resultDB_Bidir); - - resultDB_Unidir.DumpSummary(std::cout); - resultDB_Bidir.DumpSummary(std::cout); - - if (p_detailed) { - resultDB_Unidir.DumpDetailed(std::cout); - resultDB_Bidir.DumpDetailed(std::cout); - } - } else { - printConfig(); - - if (p_h2d) { - ResultDatabase resultDB; - RunBenchmark_H2D(resultDB); - - resultDB.DumpSummary(std::cout); - - if (p_detailed) { - resultDB.DumpDetailed(std::cout); - } - } - - if (p_d2h) { - ResultDatabase resultDB; - RunBenchmark_D2H(resultDB); - - resultDB.DumpSummary(std::cout); - - if (p_detailed) { - resultDB.DumpDetailed(std::cout); - } - } - - - if (p_bidir) { - ResultDatabase resultDB; - RunBenchmark_Bidir(resultDB); - - resultDB.DumpSummary(std::cout); - - if (p_detailed) { - resultDB.DumpDetailed(std::cout); - } - } - } -} diff --git a/projects/hip/samples/1_Utils/hipCommander/CMakeLists.txt b/projects/hip/samples/1_Utils/hipCommander/CMakeLists.txt deleted file mode 100644 index 2719619f36..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/CMakeLists.txt +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(hipCommander) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(hipCommander hipCommander.cpp) - -# Generate code object -add_custom_target( - codeobj - ALL - COMMAND ${HIP_HIPCC_EXECUTABLE} --genco ../nullkernel.hip.cpp -o nullkernel.hsaco - COMMENT "codeobj generated" -) - -add_dependencies(hipCommander codeobj) - -# Link with HIP -target_link_libraries(hipCommander hip::host) -set_property(TARGET hipCommander PROPERTY CXX_STANDARD 11) diff --git a/projects/hip/samples/1_Utils/hipCommander/LICENSE.txt b/projects/hip/samples/1_Utils/hipCommander/LICENSE.txt deleted file mode 100644 index 5d0d603232..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/LICENSE.txt +++ /dev/null @@ -1,27 +0,0 @@ - -Copyright (c) 2011, UT-Battelle, LLC -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -* Neither the name of Oak Ridge National Laboratory, nor UT-Battelle, LLC, nor - the names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/projects/hip/samples/1_Utils/hipCommander/Makefile b/projects/hip/samples/1_Utils/hipCommander/Makefile deleted file mode 100644 index fef6bfc946..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/Makefile +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc - -EXE=hipCommander -OPT=-O3 -#CXXFLAGS = -O3 -g -CXXFLAGS = $(OPT) --std=c++11 - -HIP_PLATFORM=$(shell $(HIP_PATH)/bin/hipconfig --platform) - -CODE_OBJECTS=nullkernel.hsaco - -all: ${EXE} ${CODE_OBJECTS} - -$(EXE): hipCommander.cpp - $(HIPCC) $(CXXFLAGS) $^ -o $@ - -nullkernel.hsaco : nullkernel.hip.cpp - $(HIPCC) --genco nullkernel.hip.cpp -o nullkernel.hsaco - - -install: $(EXE) - cp $(EXE) $(HIP_PATH)/bin - - -clean: - rm -f *.o *.co $(EXE) diff --git a/projects/hip/samples/1_Utils/hipCommander/ResultDatabase.cpp b/projects/hip/samples/1_Utils/hipCommander/ResultDatabase.cpp deleted file mode 100644 index 51ced81fae..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/ResultDatabase.cpp +++ /dev/null @@ -1,454 +0,0 @@ -#include "ResultDatabase.h" - -#include -#include -#include -#include - -using namespace std; - -bool ResultDatabase::Result::operator<(const Result& rhs) const { - if (test < rhs.test) return true; - if (test > rhs.test) return false; - if (atts < rhs.atts) return true; - if (atts > rhs.atts) return false; - return false; // less-operator returns false on equal -} - -double ResultDatabase::Result::GetMin() const { - double r = FLT_MAX; - for (int i = 0; i < value.size(); i++) { - r = min(r, value[i]); - } - return r; -} - -double ResultDatabase::Result::GetMax() const { - double r = -FLT_MAX; - for (int i = 0; i < value.size(); i++) { - r = max(r, value[i]); - } - return r; -} - -double ResultDatabase::Result::GetMedian() const { return GetPercentile(50); } - -double ResultDatabase::Result::GetPercentile(double q) const { - int n = value.size(); - if (n == 0) return FLT_MAX; - if (n == 1) return value[0]; - - if (q <= 0) return value[0]; - if (q >= 100) return value[n - 1]; - - double index = ((n + 1.) * q / 100.) - 1; - - vector sorted = value; - sort(sorted.begin(), sorted.end()); - - if (n == 2) return (sorted[0] * (1 - q / 100.) + sorted[1] * (q / 100.)); - - int index_lo = int(index); - double frac = index - index_lo; - if (frac == 0) return sorted[index_lo]; - - double lo = sorted[index_lo]; - double hi = sorted[index_lo + 1]; - return lo + (hi - lo) * frac; -} - -double ResultDatabase::Result::GetMean() const { - double r = 0; - for (int i = 0; i < value.size(); i++) { - r += value[i]; - } - return r / double(value.size()); -} - -double ResultDatabase::Result::GetStdDev() const { - double r = 0; - double u = GetMean(); - if (u == FLT_MAX) return FLT_MAX; - for (int i = 0; i < value.size(); i++) { - r += (value[i] - u) * (value[i] - u); - } - r = sqrt(r / value.size()); - return r; -} - - -void ResultDatabase::AddResults(const string& test, const string& atts, const string& unit, - const vector& values) { - for (int i = 0; i < values.size(); i++) { - AddResult(test, atts, unit, values[i]); - } -} - -static string RemoveAllButLeadingSpaces(const string& a) { - string b; - int n = a.length(); - int i = 0; - while (i < n && a[i] == ' ') { - b += a[i]; - ++i; - } - for (; i < n; i++) { - if (a[i] != ' ' && a[i] != '\t') b += a[i]; - } - return b; -} - -void ResultDatabase::AddResult(const string& test_orig, const string& atts_orig, - const string& unit_orig, double value) { - string test = RemoveAllButLeadingSpaces(test_orig); - string atts = RemoveAllButLeadingSpaces(atts_orig); - string unit = RemoveAllButLeadingSpaces(unit_orig); - int index; - for (index = 0; index < results.size(); index++) { - if (results[index].test == test && results[index].atts == atts) { - if (results[index].unit != unit) throw "Internal error: mixed units"; - - break; - } - } - - if (index >= results.size()) { - Result r; - r.test = test; - r.atts = atts; - r.unit = unit; - results.push_back(r); - } - - results[index].value.push_back(value); -} - -// **************************************************************************** -// Method: ResultDatabase::DumpDetailed -// -// Purpose: -// Writes the full results, including all trials. -// -// Arguments: -// out where to print -// -// Programmer: Jeremy Meredith -// Creation: August 14, 2009 -// -// Modifications: -// Jeremy Meredith, Wed Nov 10 14:25:17 EST 2010 -// Renamed to DumpDetailed to make room for a DumpSummary. -// -// Jeremy Meredith, Thu Nov 11 11:39:57 EST 2010 -// Added note about (*) missing value tag. -// -// Jeremy Meredith, Tue Nov 23 13:57:02 EST 2010 -// Changed note about missing values to be worded a little better. -// -// **************************************************************************** -void ResultDatabase::DumpDetailed(ostream& out) { - vector sorted(results); - sort(sorted.begin(), sorted.end()); - - const int testNameW = 24; - const int attW = 12; - const int fieldW = 11; - out << std::fixed << right << std::setprecision(4); - - int maxtrials = 1; - for (int i = 0; i < sorted.size(); i++) { - if (sorted[i].value.size() > maxtrials) maxtrials = sorted[i].value.size(); - } - - // TODO: in big parallel runs, the "trials" are the procs - // and we really don't want to print them all out.... - out << setw(testNameW) << "test\t" << setw(attW) << "atts\t" << setw(fieldW) << "median\t" - << "mean\t" - << "stddev\t" - << "min\t" - << "max\t"; - for (int i = 0; i < maxtrials; i++) out << "trial" << i << "\t"; - out << endl; - - for (int i = 0; i < sorted.size(); i++) { - Result& r = sorted[i]; - out << setw(testNameW) << r.test + "\t"; - out << setw(attW) << r.atts + "\t"; - out << setw(fieldW) << r.unit + "\t"; - if (r.GetMedian() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMedian() << "\t"; - if (r.GetMean() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMean() << "\t"; - if (r.GetStdDev() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetStdDev() << "\t"; - if (r.GetMin() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMin() << "\t"; - if (r.GetMax() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMax() << "\t"; - for (int j = 0; j < r.value.size(); j++) { - if (r.value[j] == FLT_MAX) - out << "N/A\t"; - else - out << r.value[j] << "\t"; - } - - out << endl; - } - out << endl - << "Note: Any results marked with (*) had missing values." << endl - << " This can occur on systems with a mixture of" << endl - << " device types or architectural capabilities." << endl; -} - - -// **************************************************************************** -// Method: ResultDatabase::DumpDetailed -// -// Purpose: -// Writes the summary results (min/max/stddev/med/mean), but not -// every individual trial. -// -// Arguments: -// out where to print -// -// Programmer: Jeremy Meredith -// Creation: November 10, 2010 -// -// Modifications: -// Jeremy Meredith, Thu Nov 11 11:39:57 EST 2010 -// Added note about (*) missing value tag. -// -// **************************************************************************** -void ResultDatabase::DumpSummary(ostream& out) { - vector sorted(results); - sort(sorted.begin(), sorted.end()); - - const int testNameW = 24; - const int attW = 12; - const int fieldW = 9; - out << std::fixed << right << std::setprecision(4); - - // TODO: in big parallel runs, the "trials" are the procs - // and we really don't want to print them all out.... - out << setw(testNameW) << "test\t" << setw(attW) << "atts\t" << setw(fieldW) << "units\t" - << "median\t" - << "mean\t" - << "stddev\t" - << "min\t" - << "max\t"; - out << endl; - - for (int i = 0; i < sorted.size(); i++) { - Result& r = sorted[i]; - out << setw(testNameW) << r.test + "\t"; - out << setw(attW) << r.atts + "\t"; - out << setw(fieldW) << r.unit + "\t"; - if (r.GetMedian() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMedian() << "\t"; - if (r.GetMean() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMean() << "\t"; - if (r.GetStdDev() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetStdDev() << "\t"; - if (r.GetMin() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMin() << "\t"; - if (r.GetMax() == FLT_MAX) - out << "N/A\t"; - else - out << r.GetMax() << "\t"; - - out << endl; - } - out << endl - << "Note: results marked with (*) had missing values such as" << endl - << "might occur with a mixture of architectural capabilities." << endl; -} - -// **************************************************************************** -// Method: ResultDatabase::ClearAllResults -// -// Purpose: -// Clears all existing results from the ResultDatabase; used for multiple passes -// of the same test or multiple tests. -// -// Arguments: -// -// Programmer: Jeffrey Young -// Creation: September 10th, 2014 -// -// Modifications: -// -// -// **************************************************************************** -void ResultDatabase::ClearAllResults() { results.clear(); } - -// **************************************************************************** -// Method: ResultDatabase::DumpCsv -// -// Purpose: -// Writes either detailed or summary results (min/max/stddev/med/mean), but not -// every individual trial. -// -// Arguments: -// out file to print CSV results -// -// Programmer: Jeffrey Young -// Creation: August 28th, 2014 -// -// Modifications: -// -// **************************************************************************** -void ResultDatabase::DumpCsv(string fileName) { - bool emptyFile; - vector sorted(results); - - sort(sorted.begin(), sorted.end()); - - // Check to see if the file is empty - if so, add the headers - emptyFile = this->IsFileEmpty(fileName); - - // Open file and append by default - ofstream out; - out.open(fileName.c_str(), std::ofstream::out | std::ofstream::app); - - // Add headers only for empty files - if (emptyFile) { - // TODO: in big parallel runs, the "trials" are the procs - // and we really don't want to print them all out.... - out << "test, " - << "atts, " - << "units, " - << "median, " - << "mean, " - << "stddev, " - << "min, " - << "max, "; - out << endl; - } - - for (int i = 0; i < sorted.size(); i++) { - Result& r = sorted[i]; - out << r.test << ", "; - out << r.atts << ", "; - out << r.unit << ", "; - if (r.GetMedian() == FLT_MAX) - out << "N/A, "; - else - out << r.GetMedian() << ", "; - if (r.GetMean() == FLT_MAX) - out << "N/A, "; - else - out << r.GetMean() << ", "; - if (r.GetStdDev() == FLT_MAX) - out << "N/A, "; - else - out << r.GetStdDev() << ", "; - if (r.GetMin() == FLT_MAX) - out << "N/A, "; - else - out << r.GetMin() << ", "; - if (r.GetMax() == FLT_MAX) - out << "N/A, "; - else - out << r.GetMax() << ", "; - - out << endl; - } - out << endl; - - out.close(); -} - -// **************************************************************************** -// Method: ResultDatabase::IsFileEmpty -// -// Purpose: -// Returns whether a file is empty - used as a helper for CSV printing -// -// Arguments: -// file The input file to check for emptiness -// -// Programmer: Jeffrey Young -// Creation: August 28th, 2014 -// -// Modifications: -// -// **************************************************************************** - -bool ResultDatabase::IsFileEmpty(string fileName) { - - ifstream file(fileName.c_str()); - - // If the file doesn't exist it is by definition empty - if (!file.good()) { - return true; - } else { - bool fileEmpty; - fileEmpty = (bool)(file.peek() == ifstream::traits_type::eof()); - file.close(); - - return fileEmpty; - } - - // Otherwise, return false - return false; -} - - -// **************************************************************************** -// Method: ResultDatabase::GetResultsForTest -// -// Purpose: -// Returns a vector of results for just one test name. -// -// Arguments: -// test the name of the test results to search for -// -// Programmer: Jeremy Meredith -// Creation: December 3, 2010 -// -// Modifications: -// -// **************************************************************************** -vector ResultDatabase::GetResultsForTest(const string& test) { - // get only the given test results - vector retval; - for (int i = 0; i < results.size(); i++) { - Result& r = results[i]; - if (r.test == test) retval.push_back(r); - } - return retval; -} - -// **************************************************************************** -// Method: ResultDatabase::GetResults -// -// Purpose: -// Returns all the results. -// -// Arguments: -// -// Programmer: Jeremy Meredith -// Creation: December 3, 2010 -// -// Modifications: -// -// **************************************************************************** -const vector& ResultDatabase::GetResults() const { return results; } diff --git a/projects/hip/samples/1_Utils/hipCommander/ResultDatabase.h b/projects/hip/samples/1_Utils/hipCommander/ResultDatabase.h deleted file mode 100644 index ca6a00fc91..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/ResultDatabase.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef RESULT_DATABASE_H -#define RESULT_DATABASE_H - -#include -#include -#include -#include -#include -using std::ifstream; -using std::ofstream; -using std::ostream; -using std::string; -using std::vector; - - -// **************************************************************************** -// Class: ResultDatabase -// -// Purpose: -// Track numerical results as they are generated. -// Print statistics of raw results. -// -// Programmer: Jeremy Meredith -// Creation: June 12, 2009 -// -// Modifications: -// Jeremy Meredith, Wed Nov 10 14:20:47 EST 2010 -// Split timing reports into detailed and summary. E.g. for serial code, -// we might report all trial values, but skip them in parallel. -// -// Jeremy Meredith, Thu Nov 11 11:40:18 EST 2010 -// Added check for missing value tag. -// -// Jeremy Meredith, Mon Nov 22 13:37:10 EST 2010 -// Added percentile statistic. -// -// Jeremy Meredith, Fri Dec 3 16:30:31 EST 2010 -// Added a method to extract a subset of results based on test name. Also, -// the Result class is now public, so that clients can use them directly. -// Added a GetResults method as well, and made several functions const. -// -// **************************************************************************** -class ResultDatabase { - public: - // - // A performance result for a single SHOC benchmark run. - // - struct Result { - string test; // e.g. "readback" - string atts; // e.g. "pagelocked 4k^2" - string unit; // e.g. "MB/sec" - vector value; // e.g. "837.14" - double GetMin() const; - double GetMax() const; - double GetMedian() const; - double GetPercentile(double q) const; - double GetMean() const; - double GetStdDev() const; - - bool operator<(const Result& rhs) const; - - bool HadAnyFLTMAXValues() const { - for (int i = 0; i < value.size(); ++i) { - if (value[i] >= FLT_MAX) return true; - } - return false; - } - }; - - protected: - vector results; - - public: - void AddResult(const string& test, const string& atts, const string& unit, double value); - void AddResults(const string& test, const string& atts, const string& unit, - const vector& values); - vector GetResultsForTest(const string& test); - const vector& GetResults() const; - void ClearAllResults(); - void DumpDetailed(ostream&); - void DumpSummary(ostream&); - void DumpCsv(string fileName); - - private: - bool IsFileEmpty(string fileName); -}; - - -#endif diff --git a/projects/hip/samples/1_Utils/hipCommander/c.cmd b/projects/hip/samples/1_Utils/hipCommander/c.cmd deleted file mode 100644 index 4cb980eccb..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/c.cmd +++ /dev/null @@ -1,3 +0,0 @@ -loop(1000); H2D; NullKernel; D2H; endloop; -streamsync; -printTiming(1000) diff --git a/projects/hip/samples/1_Utils/hipCommander/classic.cmd b/projects/hip/samples/1_Utils/hipCommander/classic.cmd deleted file mode 100644 index 7b1e4273c9..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/classic.cmd +++ /dev/null @@ -1 +0,0 @@ -H2D; NullKernel; D2H; streamsync diff --git a/projects/hip/samples/1_Utils/hipCommander/hipCommander.cpp b/projects/hip/samples/1_Utils/hipCommander/hipCommander.cpp deleted file mode 100644 index 0743641214..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/hipCommander.cpp +++ /dev/null @@ -1,865 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include -#ifndef _WIN32 - #include -#endif - -#include "ResultDatabase.h" -#include "nullkernel.hip.cpp" - -bool g_printedTiming = false; - -// Cmdline parms: -int p_device = 0; -const char* p_command = "setstream(1); H2D; NullKernel; D2H;"; -const char* p_file = nullptr; -unsigned p_verbose = 0x0; -unsigned p_db = 0x0; -unsigned p_blockingSync = 0x0; - -//--- -int p_iterations = 1; - -#define KNRM "\x1B[0m" -#define KRED "\x1B[31m" -#define KGRN "\x1B[32m" - - -#define failed(...) \ - printf("error: "); \ - printf(__VA_ARGS__); \ - printf("\n"); \ - abort(); - - -#define HIPCHECK(error) \ - { \ - hipError_t localError = error; \ - if (localError != hipSuccess) { \ - printf("%serror: '%s'(%d) from %s at %s:%d%s\n", KRED, hipGetErrorString(localError), \ - localError, #error, __FILE__, __LINE__, KNRM); \ - failed("API returned error code."); \ - } \ - } -#define HIPASSERT(condition, msg) \ - if (!(condition)) { \ - failed("%sassertion %s at %s:%d: %s%s\n", KRED, #condition, __FILE__, __LINE__, msg, \ - KNRM); \ - } - - -int parseInt(const char* str, int* output) { - char* next; - *output = strtol(str, &next, 0); - return !strlen(next); -} - - -void printConfig() { - hipDeviceProp_t props; - HIPCHECK(hipGetDeviceProperties(&props, p_device)); - - printf("Device:%s Mem=%.1fGB #CUs=%d Freq=%.0fMhz\n", props.name, - props.totalGlobalMem / 1024.0 / 1024.0 / 1024.0, props.multiProcessorCount, - props.clockRate / 1000.0); -} - - -void help() { - printf("Usage: hipBusBandwidth [OPTIONS]\n"); - printf(" --file, -f : Read string of commands from file\n"); - printf(" --command, -c : String specifying commands to run.\n"); - printf(" --iterations, -i : Number of copy iterations to run.\n"); - printf(" --device, -d : Device ID to use (0..numDevices).\n"); - printf( - " --verbose, -v : Verbose printing of status. Fore more info, combine with " - "HIP_TRACE_API on ROCm\n"); -}; - - -int parseStandardArguments(int argc, char* argv[]) { - for (int i = 1; i < argc; i++) { - const char* arg = argv[i]; - - if (!strcmp(arg, " ")) { - // skip NULL args. - } else if (!strcmp(arg, "--iterations") || (!strcmp(arg, "-i"))) { - if (++i >= argc || !parseInt(argv[i], &p_iterations)) { - failed("Bad --iterations argument"); - } - - } else if (!strcmp(arg, "--device") || (!strcmp(arg, "-d"))) { - if (++i >= argc || !parseInt(argv[i], &p_device)) { - failed("Bad --device argument"); - } - - } else if (!strcmp(arg, "--file") || (!strcmp(arg, "-f"))) { - if (++i >= argc) { - failed("Bad --file argument"); - } else { - p_file = argv[i]; - } - - } else if (!strcmp(arg, "--commands") || (!strcmp(arg, "-c"))) { - if (++i >= argc) { - failed("Bad --commands argument"); - } else { - p_command = argv[i]; - } - - } else if (!strcmp(arg, "--verbose") || (!strcmp(arg, "-v"))) { - p_verbose = 1; - - } else if (!strcmp(arg, "--blockingSync") || (!strcmp(arg, "-B"))) { - p_blockingSync = 1; - - - } else if (!strcmp(arg, "--help") || (!strcmp(arg, "-h"))) { - help(); - exit(EXIT_SUCCESS); - - } else { - failed("Bad argument '%s'", arg); - } - } - - return 0; -}; - -// Returns the current system time in microseconds -inline long long get_time() { -#ifdef _WIN32 - struct timespec ts; - timespec_get(&ts, TIME_UTC); - return (ts.tv_sec * 1000000) + (ts.tv_nsec/1000); -#else - struct timeval tv; - gettimeofday(&tv, 0); - return (tv.tv_sec * 1000000) + tv.tv_usec; -#endif -} - - -class Command; - - -//================================================================================================= -// A stream of commands , specified as a string. -class CommandStream { - public: - // State that is inherited by sub-blocks: - struct CommandStreamState { - hipStream_t _currentStream; - std::vector _streams; - vector _subBlocks; - }; - - public: - CommandStream(std::string commandStreamString, int iterations); - ~CommandStream(); - - hipStream_t currentStream() const { return _state._currentStream; }; - - void print(const std::string& indent = "") const; - void printBrief(std::ostream& s = std::cout) const; - void run(); - void recordTime(); - void printTiming(int iterations = 0); - - CommandStream* currentCommandStream() { - return _parseInSubBlock ? _state._subBlocks.back() : this; - }; - - void enterSubBlock(CommandStream* commandStream) { - _parseInSubBlock = true; - _state._subBlocks.push_back(commandStream); - }; - - void exitSubBlock() { _parseInSubBlock = false; }; - - - void setParent(CommandStream* parentCmdStream) { - _parentCommandStream = parentCmdStream; - _state = parentCmdStream->_state; - }; - CommandStream* getParent() { return _parentCommandStream; }; - - void setStream(int streamIndex); - - CommandStreamState& getState() { return _state; }; - - private: - static void tokenize(const std::string& s, char delim, std::vector& tokens); - void parse(const std::string fullCmd); - - protected: - CommandStreamState _state; - - private: - // List of commands to run in this stream: - std::vector _commands; - - - // Number of iterations to run the command loop - int _iterations; - - - // Us to run the the command-stream. Only valid after run is called. - long long _startTime; - double _elapsedUs; - - // Track nested loop of command streams: - CommandStream* _parentCommandStream; - - // Track if we are parsing commands in the subblock. - bool _parseInSubBlock; -}; - - -//================================================================================================= -class Command { - public: - // @p minArgs : Minimum arguments for command. -1 = don't check. - // @p maxArgs : Minimum arguments for command. 0 means min=max, ie exact #arguments expected. - // -1 = don't check max. - Command(CommandStream* cmdStream, const std::vector& args, int minArgs = 0, - int maxArgs = 0) - : _commandStream(cmdStream), _args(args) { - int numArgs = args.size() - 1; - - if ((minArgs != -1) && (numArgs < minArgs)) { - // TODO - print full command here. - failed("Not enough arguments for command %s. (Expected %d, got %d)", args[0].c_str(), - minArgs, numArgs); - } - - // Check for an exact number of arguments: - if (maxArgs == 0) { - maxArgs = minArgs; - } - if ((maxArgs != -1) && (numArgs > maxArgs)) { - failed("Too many arguments for command %s. (Expected %d, got %d)", args[0].c_str(), - maxArgs, numArgs); - } - }; - - void printBrief(std::ostream& s = std::cout) const { s << _args[0]; } - - virtual ~Command(){}; - - virtual void print(const std::string& indent = "") const { - std::cout << indent << "["; - std::for_each(_args.begin(), _args.end(), [](const std::string& s) { std::cout << s; }); - std::cout << "]"; - }; - - - virtual void run() = 0; - - protected: - int readIntArg(int argIndex, const std::string& argName) { - // TODO - catch references to non-existant arguments here. - int argVal; - try { - argVal = std::stoi(_args[argIndex]); - } catch (std::invalid_argument) { - failed("Command %s has bad %s argument ('%s')", _args[0].c_str(), argName.c_str(), - _args[argIndex].c_str()); - } - return argVal; - } - - protected: - CommandStream* _commandStream; - std::vector _args; -}; - - -#define FILENAME "nullkernel.hsaco" -#define KERNEL_NAME "NullKernel" - -//================================================================================================= -// HCC optimizes away fully NULL kernel calls, so run one that is nearly null: -class ModuleKernelCommand : public Command { - public: - ModuleKernelCommand(CommandStream* cmdStream, const std::vector& args) - : Command(cmdStream, args), _stream(cmdStream->currentStream()) { - hipModule_t module; - HIPCHECK(hipModuleLoad(&module, FILENAME)); - HIPCHECK(hipModuleGetFunction(&_function, module, KERNEL_NAME)); - }; - ~ModuleKernelCommand(){}; - - void run() override { -#define LEN 64 - float *X = NULL; - HIPCHECK(hipMalloc((void**)&X, sizeof(float))); - struct { - float *Ad; - }args; - args.Ad = X; - size_t argSize = sizeof(args); - - void* config[] = {HIP_LAUNCH_PARAM_BUFFER_POINTER, &args, - HIP_LAUNCH_PARAM_BUFFER_SIZE, &argSize, HIP_LAUNCH_PARAM_END}; - - hipModuleLaunchKernel(_function, 1, 1, 1, LEN, 1, 1, 0, 0, NULL, (void**)&config); - }; - - - public: - hipFunction_t _function; - hipStream_t _stream; -}; - - -class KernelCommand : public Command { - public: - enum Type { Null, VectorAdd }; - KernelCommand(CommandStream* cmdStream, const std::vector& args, Type kind) - : Command(cmdStream, args), _kind(kind), _stream(cmdStream->currentStream()){}; - ~KernelCommand(){}; - - - void run() override { - static const int gridX = 64; - static const int groupX = 64; - - switch (_kind) { - case Null: - hipLaunchKernelGGL(NullKernel, dim3(gridX / groupX), dim3(gridX), 0, _stream, nullptr); - break; - case VectorAdd: - assert(0); // TODO - break; - }; - } - - private: - Type _kind; - hipStream_t _stream; -}; - -//================================================================================================= -class CopyCommand : public Command { - enum MemType { PinnedHost, UnpinnedHost, Device }; - - public: - CopyCommand(CommandStream* cmdStream, const std::vector& args, hipMemcpyKind kind, - bool isAsync, bool isPinnedHost); - - ~CopyCommand() { - if (_dst) { - dealloc(_dst, _dstType); - _dst = NULL; - }; - - if (_src) { - dealloc(_src, _srcType); - _src = NULL; - } - } - - - void run() override { - if (_isAsync) { - HIPCHECK(hipMemcpyAsync(_dst, _src, _sizeBytes, _kind, _stream)); - } else { - HIPCHECK(hipMemcpy(_dst, _src, _sizeBytes, _kind)); - } - }; - - private: - void* alloc(size_t size, MemType memType) { - void* p; - if (memType == Device) { - HIPCHECK(hipMalloc(&p, size)); - - } else if (memType == PinnedHost) { - HIPCHECK(hipHostMalloc(&p, size)); - - } else if (memType == UnpinnedHost) { - p = (char*)malloc(size); - HIPASSERT(p, "malloc failed"); - - } else { - HIPASSERT(0, "unsupported memType"); - } - - return p; - }; - - - static void dealloc(void* p, MemType memType) { - if (memType == Device) { - HIPCHECK(hipFree(p)); - } else if (memType == PinnedHost) { - HIPCHECK(hipHostFree(p)); - } else if (memType == UnpinnedHost) { - free(p); - } else { - HIPASSERT(0, "unsupported memType"); - } - } - - - private: - bool _isAsync; - hipStream_t _stream; - hipMemcpyKind _kind; - - size_t _sizeBytes; - void* _dst; - MemType _dstType; - - void* _src; - MemType _srcType; -}; - - -//================================================================================================= -class DeviceSyncCommand : public Command { - public: - DeviceSyncCommand(CommandStream* cmdStream, const std::vector& args) - : Command(cmdStream, args){}; - - void run() override { HIPCHECK(hipDeviceSynchronize()); }; -}; - - -//================================================================================================= -class StreamSyncCommand : public Command { - public: - StreamSyncCommand(CommandStream* cmdStream, const std::vector& args) - : Command(cmdStream, args), _stream(cmdStream->currentStream()){}; - - static const char* help() { return "synchronizes the current stream"; }; - - - void run() override { HIPCHECK(hipStreamSynchronize(_stream)); }; - - private: - hipStream_t _stream; -}; - - -//================================================================================================= - -//================================================================================================= -class LoopCommand : public Command { - public: - LoopCommand(CommandStream* parentCmdStream, const std::vector& args) - : Command(parentCmdStream, args, 1) { - int loopCnt; - try { - loopCnt = std::stoi(args[1]); - } catch (std::invalid_argument) { - failed("bad LOOP_CNT=%s", args[1].c_str()); - } - - _commandStream = new CommandStream("", loopCnt); - _commandStream->setParent(parentCmdStream); - parentCmdStream->enterSubBlock(_commandStream); - }; - - - void print(const std::string& indent = "") const override { - Command::print(); - _commandStream->print(indent + " "); - }; - - void run() override { _commandStream->run(); }; -}; - - -//================================================================================================= -class EndBlockCommand : public Command { - public: - EndBlockCommand(CommandStream* blockCmdStream, CommandStream* parentCmdStream, - const std::vector& args) - : Command(parentCmdStream, args, 0, 1), _blockCmdStream(blockCmdStream), _printTiming(0) { - int argCnt = args.size() - 1; - if (argCnt >= 1) { - _printTiming = readIntArg(1, "PRINT_TIMING"); - } - - if (parentCmdStream == nullptr) { - failed("%s without corresponding command to start block", args[0].c_str()); - } - parentCmdStream->exitSubBlock(); - }; - - void run() override { - if (_printTiming) { - _blockCmdStream->printTiming(); - } - }; - - private: - CommandStream* _blockCmdStream; - - // print the stream when loop exits. - int _printTiming; -}; - - -//================================================================================================= -class SetStreamCommand : public Command { - public: - SetStreamCommand(CommandStream* cmdStream, const std::vector& args) - : Command(cmdStream, args, 1) { - int streamIndex = readIntArg(1, "STREAM_INDEX"); - - cmdStream->setStream(streamIndex); - }; - - void run() override{}; -}; - - -//================================================================================================= -class PrintTimingCommand : public Command { - public: - PrintTimingCommand(CommandStream* cmdStream, const std::vector& args) - : Command(cmdStream, args, 1) { - _iterations = readIntArg(1, "ITERATIONS"); - }; - - void run() override { _commandStream->printTiming(_iterations); }; - - private: - int _iterations; -}; - - -//================================================================================================= -CopyCommand::CopyCommand(CommandStream* cmdStream, const std::vector& args, - hipMemcpyKind kind, bool isAsync, bool isPinnedHost) - : Command(cmdStream, args), - _isAsync(isAsync), - _stream(cmdStream->currentStream()), - _kind(kind) { - switch (kind) { - case hipMemcpyDeviceToHost: - _srcType = Device; - _dstType = isPinnedHost ? PinnedHost : UnpinnedHost; - break; - case hipMemcpyHostToDevice: - _srcType = isPinnedHost ? PinnedHost : UnpinnedHost; - _dstType = Device; - break; - default: - HIPASSERT(0, "Unknown hipMemcpyKind"); - }; - - _sizeBytes = 64; // TODO, support reading from arg. - - _dst = alloc(_sizeBytes, _dstType); - _src = alloc(_sizeBytes, _srcType); -}; - - -//================================================================================================= -//================================================================================================= -// Implementations: -//================================================================================================= - -//================================================================================================= -CommandStream::CommandStream(std::string commandStreamString, int iterations) - : _iterations(iterations), - _startTime(0), - _elapsedUs(0.0), - _parentCommandStream(nullptr), - _parseInSubBlock(false) { - std::vector tokens; - tokenize(commandStreamString, ';', tokens); - - setStream(0); - std::for_each(tokens.begin(), tokens.end(), [&](const std::string s) { this->parse(s); }); -} - - -CommandStream::~CommandStream() { - std::for_each(_state._streams.begin(), _state._streams.end(), [&](hipStream_t s) { - if (s) { - HIPCHECK(hipStreamDestroy(s)); - } - }); - - std::for_each(_commands.begin(), _commands.end(), [&](Command* c) { delete c; }); -} - - -void CommandStream::setStream(int streamIndex) { - if (streamIndex >= _state._streams.size()) { - _state._streams.resize(streamIndex + 1); - } - - if (streamIndex && (_state._streams[streamIndex] == nullptr)) { - // Create new stream: - hipStream_t stream; - HIPCHECK(hipStreamCreate(&stream)); - _state._streams[streamIndex] = stream; - _state._currentStream = stream; - } else { - // Use existing stream: - - _state._currentStream = _state._streams[streamIndex]; - } -} - - -void CommandStream::tokenize(const std::string& s, char delim, std::vector& tokens) { - std::stringstream ss; - ss.str(s); - std::string item; - while (getline(ss, item, delim)) { - item.erase(std::remove(item.begin(), item.end(), ' '), item.end()); // remove whitespace. - tokens.push_back(item); - } -} - -void trim(std::string* s) { - // trim whitespace from begin and end: - const char* t = "\t\n\r\f\v"; - s->erase(0, s->find_first_not_of(t)); - s->erase(s->find_last_not_of(t) + 1); -} - -void ltrim(std::string* s) { - // trim whitespace from begin and end: - const char* t = "\t\n\r\f\v"; - s->erase(0, s->find_first_not_of(t)); -} - -void CommandStream::parse(std::string fullCmd) { - // convert to lower-case: - std::transform(fullCmd.begin(), fullCmd.end(), fullCmd.begin(), ::tolower); - trim(&fullCmd); - - if (p_db) { - printf("parse: <%s>\n", fullCmd.c_str()); - } - - - std::string c; - std::vector args; - size_t leftParenZ = fullCmd.find_first_of('('); - if (leftParenZ == string::npos) { - c = fullCmd; - args.push_back(c); - } else { - c = fullCmd.substr(0, leftParenZ); - args.push_back(c); - size_t rightParenZ = fullCmd.find_first_of(')', leftParenZ); - std::string argStr = fullCmd.substr(leftParenZ + 1, rightParenZ - leftParenZ - 1); - // printf ("c=%s argstr='%s' leftParenZ=%zu rightParenZ=%zu\n", c.c_str(), argStr.c_str(), - // leftParenZ, rightParenZ); - tokenize(argStr, ',', args); - } - - - if ((args.size() == 0) || (fullCmd.c_str()[0] == '#')) { - if (p_db) { - printf(" skip comment\n"); - } - return; - } - - - Command* cmd = NULL; - CommandStream* cmdStream = currentCommandStream(); - - if (c == "h2d") { - cmd = new CopyCommand(cmdStream, args, hipMemcpyHostToDevice, true /*isAsync*/, - true /*isPinned*/); - //= h2d - //= Performs an async host-to-device copy of array A_h to A_d. - //= The size of these arrays may be set with the datasize command. - - } else if (c == "d2h") { - cmd = new CopyCommand(cmdStream, args, hipMemcpyDeviceToHost, true /*isAsync*/, - true /*isPinned*/); - //= d2h - //= Performs an async device-to-host copy of array A_d to A_h. - //= The size of these arrays may be set with the datasize command. - - } else if (c == "modulekernel") { - cmd = new ModuleKernelCommand(cmdStream, args); - - } else if (c == "nullkernel") { - cmd = new KernelCommand(cmdStream, args, KernelCommand::Null); - //= nullkernel - //= Dispatches a null kernel to the device. - - } else if (c == "vectoraddkernel") { - cmd = new KernelCommand(cmdStream, args, KernelCommand::VectorAdd); - - } else if (c == "devicesync") { - cmd = new DeviceSyncCommand(cmdStream, args); - - } else if (c == "streamsync") { - //= streamsync - //= Execute hipStreamSynchronize. - //= This will cause the host thread to wait until the current stream - //= completes all pending operations. - cmd = new StreamSyncCommand(cmdStream, args); - - } else if (c == "setstream") { - //= setstream(STREAM_INDEX); - //= Set current stream used by subsequent commands. - //= STREAM_INDEX is index starting from 0...N. - //= This function will create new stream on first call to setstream or re-use previous - //= stream if setstream has already been called with STREAM_INDEX. - //= STREAM_INDEX=0 will use the default "null" stream associated with the device, and will - //not create a new stream. = The default stream has special, conservative synchronization - //properties. - - cmd = new SetStreamCommand(cmdStream, args); - - } else if (c == "printtiming") { - cmd = new PrintTimingCommand(cmdStream, args); - - } else if (c == "loop") { - //= loop(LOOP_CNT) - //= Loop over next set of commands (until 'endloop' command) for LOOP_CNT iterations. - //= Loops can be nested. - - cmd = new LoopCommand(cmdStream, args); - - } else if (c == "endloop") { - //= endloop - //= End a looped sequence. Must be paired with a preceding loop command. - //= Command between the `loop` and `endloop` must be executed - - CommandStream* parentCmdStream = cmdStream->getParent(); - cmd = new EndBlockCommand(cmdStream, parentCmdStream, args); - cmdStream = parentCmdStream; - - } else { - std::cerr << "error: Bad command '" << fullCmd << "\n"; - HIPASSERT(0, "bad command in command-stream"); - } - - if (cmd) { - cmdStream->_commands.push_back(cmd); - } -} - - -void CommandStream::print(const std::string& indent) const { - for (auto cmdI = _commands.begin(); cmdI != _commands.end(); cmdI++) { - (*cmdI)->print(indent); - }; -} - - -void CommandStream::printBrief(std::ostream& s) const { - for (auto cmdI = _commands.begin(); cmdI != _commands.end(); cmdI++) { - (*cmdI)->printBrief(s); - s << ";"; - }; -} - -void CommandStream::run() { - _startTime = get_time(); - for (int i = 0; i < _iterations; i++) { - for (auto cmdI = _commands.begin(); cmdI != _commands.end(); cmdI++) { - if (p_verbose) { - (*cmdI)->print(); - } - (*cmdI)->run(); - } - } - - // Record time, if not already stored. (an earlier printTime command will also store the time) - recordTime(); -}; - -void CommandStream::recordTime() { - if (_elapsedUs == 0.0) { - auto stopTime = get_time(); - _elapsedUs = stopTime - _startTime; - } -} - - -void CommandStream::printTiming(int iterations) { - if ((_state._subBlocks.size() == 1) && (_commands.size() == 1)) { - // printf ("print just the loop\n"); - _state._subBlocks.front()->printTiming(iterations); - } else { - g_printedTiming = true; - - recordTime(); - if (iterations == 0) { - iterations = _iterations; - } - std::cout << "command<"; - printBrief(std::cout); - std::cout << ">,"; - printf(" iterations,%d, total_time,%6.3f, time/iteration,%6.3f\n", iterations, - _elapsedUs, _elapsedUs / iterations); - } -}; - - -//================================================================================================= -int main(int argc, char* argv[]) { - parseStandardArguments(argc, argv); - - printConfig(); - - CommandStream* cs; - - if (p_blockingSync) { -#ifdef __HIP_PLATFORM_AMD__ - printf("setting BlockingSync for AMD\n"); - #ifdef _WIN32 - _putenv_s("HIP_BLOCKING_SYNC", "1"); - #else - setenv("HIP_BLOCKING_SYNC", "1", 1); - #endif -#endif -#ifdef __HIP_PLATFORM_NVIDIA__ - printf("setting cudaDeviceBlockingSync\n"); - HIPCHECK(hipSetDeviceFlags(cudaDeviceBlockingSync)); -#endif - }; - - - if (p_file) { - // TODO - catch exception on file IO here: - std::ifstream file(p_file); - std::string str; - std::string file_contents; - while (std::getline(file, str)) { - file_contents += str; - } - - cs = new CommandStream(file_contents, p_iterations); - - } else { - cs = new CommandStream(p_command, p_iterations); - } - - cs->print(); - printf("------\n"); - - cs->run(); - if (!g_printedTiming) { - cs->printTiming(); - } - - delete cs; -} - - -// TODO - add error checking for arguments. diff --git a/projects/hip/samples/1_Utils/hipCommander/l2.hcm b/projects/hip/samples/1_Utils/hipCommander/l2.hcm deleted file mode 100644 index 6b14f7b829..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/l2.hcm +++ /dev/null @@ -1,3 +0,0 @@ -setstream(1); -NullKernel; streamsync; -loop(10000); H2D; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/loop.hcm b/projects/hip/samples/1_Utils/hipCommander/loop.hcm deleted file mode 100644 index 4cb980eccb..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/loop.hcm +++ /dev/null @@ -1,3 +0,0 @@ -loop(1000); H2D; NullKernel; D2H; endloop; -streamsync; -printTiming(1000) diff --git a/projects/hip/samples/1_Utils/hipCommander/loop2.hcm b/projects/hip/samples/1_Utils/hipCommander/loop2.hcm deleted file mode 100644 index ae753d0722..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/loop2.hcm +++ /dev/null @@ -1,2 +0,0 @@ -setstream(1); -loop(1000); NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/nullkernel.hip.cpp b/projects/hip/samples/1_Utils/hipCommander/nullkernel.hip.cpp deleted file mode 100644 index 8016f109c7..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/nullkernel.hip.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include "hip/hip_runtime.h" - -extern "C" __global__ void NullKernel(float* Ad) { - if (Ad) { - Ad[0] = 42; - } -} diff --git a/projects/hip/samples/1_Utils/hipCommander/nullkernel.hsaco b/projects/hip/samples/1_Utils/hipCommander/nullkernel.hsaco deleted file mode 100755 index da6a3e6823..0000000000 Binary files a/projects/hip/samples/1_Utils/hipCommander/nullkernel.hsaco and /dev/null differ diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/latency2.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/latency2.hcm deleted file mode 100644 index e43960dc5a..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/latency2.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -NullKernel; streamsync; -loop(30000); NullKernel; streamsync; endloop(1); -loop(30000); H2D; H2D; NullKernel; streamsync; endloop(1); -loop(30000); H2D; H2D; H2D; NullKernel; streamsync; endloop(1); - -loop(30000); H2D; NullKernel; D2H; streamsync; endloop(1); -loop(30000); NullKernel; D2H; streamsync; endloop(1); -loop(30000); NullKernel; D2H; D2H; streamsync; endloop(1); -loop(30000); NullKernel; D2H; D2H; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/latency_hostsync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/latency_hostsync.hcm deleted file mode 100644 index f042b446e3..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/latency_hostsync.hcm +++ /dev/null @@ -1,8 +0,0 @@ -setstream(1); -NullKernel; streamsync; -loop(100000); NullKernel; streamsync; endloop(1); - -loop(100000); H2D; streamsync; NullKernel; streamsync; endloop(1); - -loop(100000); H2D; streamsync; NullKernel; streamsync; D2H; streamsync; endloop(1); - diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/latency_nosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/latency_nosync.hcm deleted file mode 100644 index 682d9d8b30..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/latency_nosync.hcm +++ /dev/null @@ -1,5 +0,0 @@ -setstream(1); -NullKernel; streamsync; -loop(100000); NullKernel; streamsync; endloop(1); -loop(100000); H2D; NullKernel; streamsync; endloop(1); -loop(100000); H2D; NullKernel; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/latency_nullstream.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/latency_nullstream.hcm deleted file mode 100644 index 87968a4df9..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/latency_nullstream.hcm +++ /dev/null @@ -1,7 +0,0 @@ -setstream(0); -NullKernel; streamsync; -loop(100000); NullKernel; streamsync; endloop(1); - -loop(100000); H2D; NullKernel; streamsync; endloop(1); - -loop(100000); H2D; NullKernel; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/modulelaunch_latency.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/modulelaunch_latency.hcm deleted file mode 100644 index 576208135c..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/modulelaunch_latency.hcm +++ /dev/null @@ -1,5 +0,0 @@ -setstream(1); -NullKernel; streamsync; -loop(100); ModuleKernel; streamsync; endloop(1); -loop(100); streamsync; endloop(1); -loop(3000); NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_h2d.hcm deleted file mode 100644 index 640bb2be79..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; H2D; streamsync;D2H; H2D; streamsync; endloop(1); -loop(10); D2H; H2D; streamsync;D2H; H2D; streamsync; endloop(1); -loop(100); D2H; H2D; streamsync;D2H; H2D; streamsync; endloop(1); -loop(100); D2H; H2D; streamsync;D2H; H2D; streamsync; endloop(1); -loop(1000); D2H; H2D; streamsync;D2H; H2D; streamsync; endloop(1); -loop(1000); D2H; H2D; streamsync;D2H; H2D; streamsync; endloop(1); -loop(10000); D2H; H2D; streamsync;D2H; H2D; streamsync; endloop(1); -loop(10000); D2H; H2D; streamsync;D2H; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_kernel.hcm deleted file mode 100644 index c1bc0f6702..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync; endloop(1); -loop(10); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync; endloop(1); -loop(100); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync; endloop(1); -loop(100); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync; endloop(1); -loop(1000); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync; endloop(1); -loop(1000); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync; endloop(1); -loop(10000); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync; endloop(1); -loop(10000); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_sync_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_sync_h2d.hcm deleted file mode 100644 index 0e787f9bd0..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_sync_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; endloop(1); -loop(10); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; endloop(1); -loop(100); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; endloop(1); -loop(100); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; endloop(1); -loop(1000); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; endloop(1); -loop(1000); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; endloop(1); -loop(10000); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; endloop(1); -loop(10000); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_sync_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_sync_kernel.hcm deleted file mode 100644 index 8d7fddc146..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_d2h_sync_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; endloop(1); -loop(10); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; endloop(1); -loop(100); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; endloop(1); -loop(100); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_d2h.hcm deleted file mode 100644 index 7d845d03a4..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; D2H; streamsync;H2D; D2H; streamsync; endloop(1); -loop(10); H2D; D2H; streamsync;H2D; D2H; streamsync; endloop(1); -loop(100); H2D; D2H; streamsync;H2D; D2H; streamsync; endloop(1); -loop(100); H2D; D2H; streamsync;H2D; D2H; streamsync; endloop(1); -loop(1000); H2D; D2H; streamsync;H2D; D2H; streamsync; endloop(1); -loop(1000); H2D; D2H; streamsync;H2D; D2H; streamsync; endloop(1); -loop(10000); H2D; D2H; streamsync;H2D; D2H; streamsync; endloop(1); -loop(10000); H2D; D2H; streamsync;H2D; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_kernel.hcm deleted file mode 100644 index 49c0d77146..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync; endloop(1); -loop(10); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync;endloop(1); -loop(100); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync;endloop(1); -loop(100); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_sync_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_sync_d2h.hcm deleted file mode 100644 index fe1f14bee5..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_sync_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; endloop(1); -loop(10); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; endloop(1); -loop(100); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; endloop(1); -loop(100); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; endloop(1); -loop(1000); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; endloop(1); -loop(1000); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; endloop(1); -loop(10000); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; endloop(1); -loop(10000); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_sync_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_sync_kernel.hcm deleted file mode 100644 index 0762001daa..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_h2d_sync_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(10); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_d2h.hcm deleted file mode 100644 index 88003ba476..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; endloop(1); -loop(10); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; endloop(1); -loop(100); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; endloop(1); -loop(100); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; endloop(1); -loop(1000); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; endloop(1); -loop(1000); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; endloop(1); -loop(10000); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; endloop(1); -loop(10000); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_h2d.hcm deleted file mode 100644 index 01913f8481..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; endloop(1); -loop(10); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; endloop(1); -loop(100); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; endloop(1); -loop(100); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; endloop(1); -loop(1000); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; endloop(1); -loop(1000); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; endloop(1); -loop(10000); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; endloop(1); -loop(10000); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_sync_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_sync_d2h.hcm deleted file mode 100644 index 530eb8f68e..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_sync_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(100); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(100); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_sync_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_sync_h2d.hcm deleted file mode 100644 index 6d83ee87c9..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_kernel_sync_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(100); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(100); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_sync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_sync.hcm deleted file mode 100644 index 8b9e233a9e..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2_sync.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); streamsync; streamsync; endloop(1); -loop(10); streamsync; streamsync; endloop(1); -loop(100); streamsync; streamsync; endloop(1); -loop(100); streamsync; streamsync; endloop(1); -loop(1000); streamsync; streamsync; endloop(1); -loop(1000); streamsync; streamsync; endloop(1); -loop(10000); streamsync; streamsync; endloop(1); -loop(10000); streamsync; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2d2h.hcm deleted file mode 100644 index 83cdc4ff75..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2d2h.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync; D2H; streamsync; endloop(1); -loop(10); D2H; streamsync; D2H; streamsync; endloop(1); -loop(100); D2H; streamsync; D2H; streamsync; endloop(1); -loop(100); D2H; streamsync; D2H; streamsync; endloop(1); -loop(1000); D2H;streamsync; D2H; streamsync; endloop(1); -loop(1000); D2H; streamsync; D2H; streamsync; endloop(1); -loop(1000); D2H; streamsync; D2H; streamsync; endloop(1); -loop(10000); D2H; streamsync; D2H; streamsync; endloop(1); -loop(10000); D2H; streamsync; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2d2h_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2d2h_wosync.hcm deleted file mode 100644 index 4b91403582..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2d2h_wosync.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); D2H; D2H; streamsync; endloop(1); -loop(10); D2H; D2H; streamsync; endloop(1); -loop(100); D2H; D2H; streamsync; endloop(1); -loop(100); D2H; D2H; streamsync; endloop(1); -loop(1000); D2H; D2H; streamsync; endloop(1); -loop(1000); D2H; D2H; streamsync; endloop(1); -loop(1000); D2H; D2H; streamsync; endloop(1); -loop(10000); D2H; D2H; streamsync; endloop(1); -loop(10000); D2H; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d.hcm deleted file mode 100644 index a2e4311bf6..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; H2D; streamsync; endloop(1); -loop(10); H2D; streamsync; H2D; streamsync; endloop(1); -loop(100); H2D; streamsync; H2D; streamsync; endloop(1); -loop(100); H2D; streamsync; H2D; streamsync; endloop(1); -loop(1000); H2D;streamsync; H2D; streamsync; endloop(1); -loop(1000); H2D; streamsync; H2D; streamsync; endloop(1); -loop(1000); H2D; streamsync; H2D; streamsync; endloop(1); -loop(10000); H2D; streamsync; H2D; streamsync; endloop(1); -loop(10000); H2D; streamsync; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_kernel.hcm deleted file mode 100644 index 0c622614cc..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel; streamsync;endloop(1); -loop(10); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel; streamsync;endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel; streamsync;endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel; streamsync;endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel; streamsync;endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel; streamsync;endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_kernel_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_kernel_wosync.hcm deleted file mode 100644 index d73467da10..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_kernel_wosync.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync; endloop(1); -loop(10); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync;endloop(1); -loop(100); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync;endloop(1); -loop(100); H2D; NullKernel; streamsync; H2D; NullKernel; streamsync;endloop(1); -loop(1000); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D ; NullKernel; streamsync;H2D; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_wosync.hcm deleted file mode 100644 index 35f5e68522..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2h2d_wosync.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); H2D; H2D; streamsync; endloop(1); -loop(10); H2D; H2D; streamsync; endloop(1); -loop(100); H2D; H2D; streamsync; endloop(1); -loop(100); H2D; H2D; streamsync; endloop(1); -loop(1000); H2D; H2D; streamsync; endloop(1); -loop(1000); H2D; H2D; streamsync; endloop(1); -loop(1000); H2D; H2D; streamsync; endloop(1); -loop(10000); H2D; H2D; streamsync; endloop(1); -loop(10000); H2D; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2kernels.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2kernels.hcm deleted file mode 100644 index 3b85c6bef8..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2kernels.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(10); NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2kernels_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2kernels_wosync.hcm deleted file mode 100644 index 584d6b8021..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_2kernels_wosync.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); NullKernel; NullKernel; streamsync; endloop(1); -loop(10); NullKernel; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_h2d.hcm deleted file mode 100644 index 7f0fce96c5..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; H2D; streamsync;D2H; H2D; streamsync; D2H; H2D; streamsync; endloop(1); -loop(10); D2H; H2D; streamsync;D2H; H2D; streamsync; D2H; H2D; streamsync; endloop(1); -loop(100); D2H; H2D; streamsync;D2H; H2D; streamsync; D2H; H2D; streamsync; endloop(1); -loop(100); D2H; H2D; streamsync;D2H; H2D; streamsync; D2H; H2D; streamsync; endloop(1); -loop(1000); D2H; H2D; streamsync;D2H; H2D; streamsync; D2H; H2D; streamsync; endloop(1); -loop(1000); D2H; H2D; streamsync;D2H; H2D; streamsync; D2H; H2D; streamsync; endloop(1); -loop(10000); D2H; H2D; streamsync;D2H; H2D; streamsync; D2H; H2D; streamsync; endloop(1); -loop(10000); D2H; H2D; streamsync;D2H; H2D; streamsync; D2H; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_kernel.hcm deleted file mode 100644 index a384439b5c..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync;streamsync; D2H; NullKernel; streamsync; endloop(1); -loop(10); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync;streamsync; D2H; NullKernel; streamsync; endloop(1); -loop(100); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync;streamsync; D2H; NullKernel; streamsync; endloop(1); -loop(100); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync;streamsync; D2H; NullKernel; streamsync; endloop(1); -loop(1000); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync;streamsync; D2H; NullKernel; streamsync; endloop(1); -loop(1000); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync;streamsync; D2H; NullKernel; streamsync; endloop(1); -loop(10000); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync;streamsync; D2H; NullKernel; streamsync; endloop(1); -loop(10000); D2H; NullKernel; streamsync;D2H; NullKernel; streamsync;streamsync; D2H; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_sync_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_sync_h2d.hcm deleted file mode 100644 index 1cab6ff0d2..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_sync_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; D2H; streamsync; H2D;streamsync; endloop(1); -loop(10); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; D2H; streamsync; H2D;streamsync; endloop(1); -loop(100); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; D2H; streamsync; H2D;streamsync; endloop(1); -loop(100); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; D2H; streamsync; H2D;streamsync; endloop(1); -loop(1000); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; D2H; streamsync; H2D;streamsync; endloop(1); -loop(1000); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; D2H; streamsync; H2D;streamsync; endloop(1); -loop(10000); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; D2H; streamsync; H2D;streamsync; endloop(1); -loop(10000); D2H; streamsync; H2D; streamsync;D2H; streamsync; H2D; streamsync; D2H; streamsync; H2D;streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_sync_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_sync_kernel.hcm deleted file mode 100644 index ff5b09a3dc..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_d2h_sync_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; D2H; streamsync; NullKernel;streamsync; endloop(1); -loop(10); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; D2H; streamsync; NullKernel;streamsync; endloop(1); -loop(100); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; D2H; streamsync; NullKernel;streamsync; endloop(1); -loop(100); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; D2H; streamsync; NullKernel;streamsync; endloop(1); -loop(1000); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; D2H; streamsync; NullKernel;streamsync; endloop(1); -loop(1000); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; D2H; streamsync; NullKernel;streamsync; endloop(1); -loop(10000); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; D2H; streamsync; NullKernel;streamsync; endloop(1); -loop(10000); D2H; streamsync; NullKernel; streamsync;D2H; streamsync; NullKernel; streamsync; D2H; streamsync; NullKernel;streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_d2h.hcm deleted file mode 100644 index d8921a64e7..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_d2h.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); H2D; D2H; streamsync;H2D; D2H; streamsync; H2D; D2H; streamsync; endloop(1); -loop(10); H2D; D2H; streamsync;H2D; D2H; streamsync; H2D; D2H; streamsync; endloop(1); -loop(100); H2D; D2H; streamsync;H2D; D2H; streamsync; H2D; D2H; streamsync; endloop(1); -loop(100); H2D; D2H; streamsync;H2D; D2H; streamsync; H2D; D2H; streamsync; endloop(1); -loop(1000); H2D; D2H; streamsync;H2D; D2H; streamsync; H2D; D2H; streamsync; endloop(1); -loop(1000); H2D; D2H; streamsync;H2D; D2H; streamsync; H2D; D2H; streamsync; endloop(1); -loop(10000); H2D; D2H; streamsync;H2D; D2H; streamsync; H2D; D2H; streamsync; endloop(1); -loop(10000); H2D; D2H; streamsync;H2D; D2H; streamsync; H2D; D2H; streamsync; endloop(1); - diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_kernel.hcm deleted file mode 100644 index 4ccbf9a83c..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync;streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(10); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync;streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(100); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync;streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(100); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync;streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync;streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync;streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync;streamsync; H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D; NullKernel; streamsync;H2D; NullKernel; streamsync;streamsync; H2D; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_sync_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_sync_d2h.hcm deleted file mode 100644 index a3d9a282f5..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_sync_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; H2D; streamsync; D2H;streamsync; endloop(1); -loop(10); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; H2D; streamsync; D2H;streamsync; endloop(1); -loop(100); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; H2D; streamsync; D2H;streamsync; endloop(1); -loop(100); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; H2D; streamsync; D2H;streamsync; endloop(1); -loop(1000); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; H2D; streamsync; D2H;streamsync; endloop(1); -loop(1000); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; H2D; streamsync; D2H;streamsync; endloop(1); -loop(10000); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; H2D; streamsync; D2H;streamsync; endloop(1); -loop(10000); H2D; streamsync; D2H; streamsync;H2D; streamsync; D2H; streamsync; H2D; streamsync; D2H;streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_sync_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_sync_kernel.hcm deleted file mode 100644 index 56554d15fd..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_h2d_sync_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel;streamsync; endloop(1); -loop(10); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel;streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel;streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel;streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel;streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel;streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel;streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync;H2D; streamsync; NullKernel; streamsync; H2D; streamsync; NullKernel;streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_d2h.hcm deleted file mode 100644 index a6e3a683d2..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; NullKernel; D2H; streamsync;endloop(1); -loop(10); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; NullKernel; D2H; streamsync;endloop(1); -loop(100); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; NullKernel; D2H; streamsync;endloop(1); -loop(100); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; NullKernel; D2H; streamsync;endloop(1); -loop(1000); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; NullKernel; D2H; streamsync;endloop(1); -loop(1000); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; NullKernel; D2H; streamsync;endloop(1); -loop(10000); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; NullKernel; D2H; streamsync;endloop(1); -loop(10000); NullKernel; D2H; streamsync;NullKernel; D2H; streamsync; NullKernel; D2H; streamsync;endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_h2d.hcm deleted file mode 100644 index eae3eadc5b..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; NullKernel; H2D; streamsync;endloop(1); -loop(10); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; NullKernel; H2D; streamsync;endloop(1); -loop(100); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; NullKernel; H2D; streamsync;endloop(1); -loop(100); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; NullKernel; H2D; streamsync;endloop(1); -loop(1000); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; NullKernel; H2D; streamsync;endloop(1); -loop(1000); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; NullKernel; H2D; streamsync;endloop(1); -loop(10000); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; NullKernel; H2D; streamsync;endloop(1); -loop(10000); NullKernel; H2D; streamsync;NullKernel; H2D; streamsync; NullKernel; H2D; streamsync;endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_sync_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_sync_d2h.hcm deleted file mode 100644 index 9e21709b0b..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_sync_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(100); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(100); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync;NullKernel; streamsync; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_sync_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_sync_h2d.hcm deleted file mode 100644 index b1ef7ef9f4..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_kernel_sync_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(100); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(100); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync;NullKernel; streamsync; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_sync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_sync.hcm deleted file mode 100644 index bc8d21c594..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3_sync.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10);streamsync; streamsync; streamsync; endloop(1); -loop(10);streamsync; streamsync; streamsync; endloop(1); -loop(100);streamsync; streamsync; streamsync; endloop(1); -loop(100);streamsync; streamsync; streamsync; endloop(1); -loop(1000);streamsync; streamsync; streamsync; endloop(1); -loop(1000);streamsync; streamsync; streamsync; endloop(1); -loop(10000);streamsync; streamsync; streamsync; endloop(1); -loop(10000);streamsync; streamsync; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3d2h.hcm deleted file mode 100644 index 4e07574b99..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync; D2H; streamsync; D2H; streamsync; endloop(1); -loop(10); D2H; streamsync; D2H; streamsync; D2H; streamsync; endloop(1); -loop(100); D2H; streamsync; D2H; streamsync; D2H; streamsync; endloop(1); -loop(100); D2H; streamsync; D2H; streamsync; D2H; streamsync; endloop(1); -loop(1000); D2H;streamsync; D2H; streamsync; D2H; streamsync; endloop(1); -loop(1000); D2H; streamsync; D2H; streamsync; D2H; streamsync; endloop(1); -loop(10000); D2H; streamsync; D2H; streamsync; D2H; streamsync; endloop(1); -loop(10000); D2H; streamsync; D2H; streamsync; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3d2h_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3d2h_wosync.hcm deleted file mode 100644 index e96707fed9..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3d2h_wosync.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; D2H; D2H; streamsync; endloop(1); -loop(10); D2H; D2H; D2H; streamsync; endloop(1); -loop(100); D2H; D2H; D2H; streamsync; endloop(1); -loop(100); D2H; D2H; D2H; streamsync; endloop(1); -loop(1000); D2H; D2H; D2H; streamsync; endloop(1); -loop(1000); D2H; D2H; D2H; streamsync; endloop(1); -loop(10000); D2H; D2H; D2H; streamsync; endloop(1); -loop(10000); D2H; D2H; D2H;streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3h2d.hcm deleted file mode 100644 index 82151adb8b..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3h2d.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync;H2D;streamsync; H2D; streamsync; endloop(1); -loop(10); H2D; streamsync;H2D;streamsync; H2D; streamsync; endloop(1); -loop(100); H2D; streamsync;H2D; streamsync;H2D; streamsync; endloop(1); -loop(100); H2D;streamsync; H2D; streamsync;H2D; streamsync; endloop(1); -loop(1000); H2D;streamsync; H2D;streamsync; H2D; streamsync; endloop(1); -loop(1000); H2D;streamsync; H2D; streamsync;H2D; streamsync; endloop(1); -loop(1000); H2D;streamsync; H2D; streamsync;H2D; streamsync; endloop(1); -loop(10000); H2D;streamsync; H2D; streamsync;H2D; streamsync; endloop(1); -loop(10000); H2D;streamsync; H2D;streamsync; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3h2d_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3h2d_wosync.hcm deleted file mode 100644 index 7d96bfcfab..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3h2d_wosync.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); H2D; H2D; H2D; streamsync; endloop(1); -loop(10); H2D; H2D; H2D; streamsync; endloop(1); -loop(100); H2D; H2D; H2D; streamsync; endloop(1); -loop(100); H2D; H2D; H2D; streamsync; endloop(1); -loop(1000); H2D; H2D; H2D; streamsync; endloop(1); -loop(1000); H2D; H2D; H2D; streamsync; endloop(1); -loop(1000); H2D; H2D; H2D; streamsync; endloop(1); -loop(10000); H2D; H2D; H2D; streamsync; endloop(1); -loop(10000); H2D; H2D; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3kernels.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3kernels.hcm deleted file mode 100644 index 2e8306dfde..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3kernels.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(10); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; NullKernel; streamsync; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3kernels_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3kernels_wosync.hcm deleted file mode 100644 index 85cd0dd4d2..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_3kernels_wosync.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(10); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_4kernels.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_4kernels.hcm deleted file mode 100644 index 48a8223626..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_4kernels.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(10); NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); -loop(100); NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_5kernels.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_5kernels.hcm deleted file mode 100644 index 70ad00c248..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_5kernels.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); NullKernel; NullKernel; NullKernel; NullKernel;NullKernel; streamsync; endloop(1); -loop(10); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(100); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); -loop(100); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_6kernels.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_6kernels.hcm deleted file mode 100644 index 1bbb5694b1..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_6kernels.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); NullKernel; NullKernel; NullKernel; NullKernel;NullKernel;NullKernel; streamsync; endloop(1); -loop(10); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); -loop(100); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;NullKernel;streamsync; endloop(1); -loop(100); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); -loop(1000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); -loop(10000); NullKernel; NullKernel; NullKernel; NullKernel; NullKernel; NullKernel;streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h.hcm deleted file mode 100644 index 54f06a3481..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync; endloop(1); -loop(10); D2H; streamsync; endloop(1); -loop(100); D2H; streamsync; endloop(1); -loop(100); D2H; streamsync; endloop(1); -loop(1000); D2H; streamsync; endloop(1); -loop(1000); D2H; streamsync; endloop(1); -loop(10000); D2H; streamsync; endloop(1); -loop(10000); D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_h2d.hcm deleted file mode 100644 index 6667ba95fa..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; H2D; streamsync; endloop(1); -loop(10); D2H; H2D; streamsync; endloop(1); -loop(100); D2H; H2D; streamsync; endloop(1); -loop(100); D2H; H2D; streamsync; endloop(1); -loop(1000); D2H; H2D; streamsync; endloop(1); -loop(1000); D2H; H2D; streamsync; endloop(1); -loop(10000); D2H; H2D; streamsync; endloop(1); -loop(10000); D2H; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_kernel.hcm deleted file mode 100644 index fe770c5e9d..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; NullKernel; streamsync; endloop(1); -loop(10); D2H; NullKernel; streamsync; endloop(1); -loop(100); D2H; NullKernel; streamsync; endloop(1); -loop(100); D2H; NullKernel; streamsync; endloop(1); -loop(1000); D2H; NullKernel; streamsync; endloop(1); -loop(1000); D2H; NullKernel; streamsync; endloop(1); -loop(10000); D2H; NullKernel; streamsync; endloop(1); -loop(10000); D2H; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_sync_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_sync_h2d.hcm deleted file mode 100644 index 20ec951509..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_sync_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync; H2D; streamsync; endloop(1); -loop(10); D2H; streamsync; H2D; streamsync; endloop(1); -loop(100); D2H; streamsync; H2D; streamsync; endloop(1); -loop(100); D2H; streamsync; H2D; streamsync; endloop(1); -loop(1000); D2H; streamsync; H2D; streamsync; endloop(1); -loop(1000); D2H; streamsync; H2D; streamsync; endloop(1); -loop(10000); D2H; streamsync; H2D; streamsync; endloop(1); -loop(10000); D2H; streamsync; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_sync_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_sync_kernel.hcm deleted file mode 100644 index 77e483b3df..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_d2h_sync_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); D2H; streamsync;NullKernel; streamsync; endloop(1); -loop(10); D2H; streamsync;NullKernel; streamsync; endloop(1); -loop(100); D2H; streamsync;NullKernel; streamsync; endloop(1); -loop(100); D2H; streamsync;NullKernel; streamsync; endloop(1); -loop(1000); D2H; streamsync;NullKernel; streamsync; endloop(1); -loop(1000); D2H; streamsync;NullKernel; streamsync; endloop(1); -loop(10000); D2H; streamsync;NullKernel; streamsync; endloop(1); -loop(10000); D2H; streamsync;NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d.hcm deleted file mode 100644 index f5642bfdf0..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; endloop(1); -loop(10); H2D; streamsync; endloop(1); -loop(100); H2D; streamsync; endloop(1); -loop(100); H2D; streamsync; endloop(1); -loop(1000); H2D; streamsync; endloop(1); -loop(1000); H2D; streamsync; endloop(1); -loop(1000); H2D; streamsync; endloop(1); -loop(10000); H2D; streamsync; endloop(1); -loop(10000); H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_10.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_10.hcm deleted file mode 100644 index 05452b9c87..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_10.hcm +++ /dev/null @@ -1,2 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_d2h.hcm deleted file mode 100644 index dad9fc7437..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; D2H; streamsync; endloop(1); -loop(10); H2D; D2H; streamsync; endloop(1); -loop(100); H2D; D2H; streamsync; endloop(1); -loop(100); H2D; D2H; streamsync; endloop(1); -loop(1000); H2D; D2H; streamsync; endloop(1); -loop(1000); H2D; D2H; streamsync; endloop(1); -loop(10000); H2D; D2H; streamsync; endloop(1); -loop(10000); H2D; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel.hcm deleted file mode 100644 index 1b60640b9e..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; NullKernel; streamsync; endloop(1); -loop(10); H2D; NullKernel; streamsync; endloop(1); -loop(100); H2D; NullKernel; streamsync; endloop(1); -loop(100); H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_d2h.hcm deleted file mode 100644 index 6e4e9f3544..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10);H2D; streamsync; NullKernel; D2H; streamsync;endloop(1); -loop(10); H2D; streamsync; NullKernel; D2H; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; D2H; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; D2H; streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; D2H; streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; D2H; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; D2H; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_d2h_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_d2h_wosync.hcm deleted file mode 100644 index 4e94a26ebf..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_d2h_wosync.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10);H2D; NullKernel; D2H; streamsync;endloop(1); -loop(10); H2D; NullKernel; D2H; streamsync; endloop(1); -loop(100); H2D; NullKernel; D2H; streamsync; endloop(1); -loop(100); H2D; NullKernel; D2H; streamsync; endloop(1); -loop(1000); H2D; NullKernel; D2H; streamsync; endloop(1); -loop(1000); H2D; NullKernel; D2H; streamsync; endloop(1); -loop(10000); H2D; NullKernel; D2H; streamsync; endloop(1); -loop(10000); H2D; NullKernel; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_wosync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_wosync.hcm deleted file mode 100644 index b3b40d3190..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_kernel_wosync.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; NullKernel; streamsync; endloop(1); -loop(10); H2D; NullKernel; streamsync; endloop(1); -loop(100); H2D; NullKernel; streamsync; endloop(1); -loop(100); H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync; endloop(1); -loop(1000); H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D; NullKernel; streamsync; endloop(1); -loop(10000); H2D ; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_d2h.hcm deleted file mode 100644 index 030213d1b3..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; D2H; streamsync; endloop(1); -loop(10); H2D; streamsync; D2H; streamsync; endloop(1); -loop(100); H2D; streamsync; D2H; streamsync; endloop(1); -loop(100); H2D; streamsync; D2H; streamsync; endloop(1); -loop(1000); H2D; streamsync; D2H; streamsync; endloop(1); -loop(1000); H2D; streamsync; D2H; streamsync; endloop(1); -loop(10000); H2D; streamsync; D2H; streamsync; endloop(1); -loop(10000); H2D; streamsync; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_kernel_sync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_kernel_sync.hcm deleted file mode 100644 index 146c74bcae..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_kernel_sync.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(10); H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_kernel_sync_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_kernel_sync_d2h.hcm deleted file mode 100644 index 366d04f469..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_h2d_sync_kernel_sync_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10);H2D; streamsync; NullKernel;streamsync; D2H; streamsync;endloop(1); -loop(10); H2D; streamsync; NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(100); H2D; streamsync; NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(1000); H2D; streamsync; NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10000); H2D; streamsync; NullKernel; streamsync; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel.hcm deleted file mode 100644 index 027d89aad0..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel.hcm +++ /dev/null @@ -1,10 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; endloop(1); -loop(10); NullKernel; streamsync; endloop(1); -loop(100); NullKernel; streamsync; endloop(1); -loop(100); NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_barrier.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_barrier.hcm deleted file mode 100644 index fb6a867e7f..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_barrier.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; streamsync; endloop(1); -loop(10); NullKernel; streamsync; streamsync; endloop(1); -loop(100); NullKernel; streamsync; streamsync; endloop(1); -loop(100); NullKernel; streamsync; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_d2h.hcm deleted file mode 100644 index 2e64472dbd..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; D2H; streamsync; endloop(1); -loop(10); NullKernel; D2H; streamsync; endloop(1); -loop(100); NullKernel; D2H; streamsync; endloop(1); -loop(100); NullKernel; D2H; streamsync; endloop(1); -loop(1000); NullKernel; D2H; streamsync; endloop(1); -loop(1000); NullKernel; D2H; streamsync; endloop(1); -loop(10000); NullKernel; D2H; streamsync; endloop(1); -loop(10000); NullKernel; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_h2d.hcm deleted file mode 100644 index b220a69c68..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; H2D; streamsync; endloop(1); -loop(10); NullKernel; H2D; streamsync; endloop(1); -loop(100); NullKernel; H2D; streamsync; endloop(1); -loop(100); NullKernel; H2D; streamsync; endloop(1); -loop(1000); NullKernel; H2D; streamsync; endloop(1); -loop(1000); NullKernel; H2D; streamsync; endloop(1); -loop(10000); NullKernel; H2D; streamsync; endloop(1); -loop(10000); NullKernel; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_sync_d2h.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_sync_d2h.hcm deleted file mode 100644 index 48b332b1c3..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_sync_d2h.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10); NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(100); NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(100); NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; D2H; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; D2H; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_sync_h2d.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_sync_h2d.hcm deleted file mode 100644 index 5a45d55376..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_kernel_sync_h2d.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10); NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(100); NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(100); NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(1000); NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; H2D; streamsync; endloop(1); -loop(10000); NullKernel; streamsync; H2D; streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_streamcreate.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_streamcreate.hcm deleted file mode 100644 index 1e6aef5dc1..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_streamcreate.hcm +++ /dev/null @@ -1,2 +0,0 @@ -setstream(1); -loop(10);setstream(1);setstream(2);setstream(3);setstream(4);setstream(5);streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_sync.hcm b/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_sync.hcm deleted file mode 100644 index a784013b1a..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/perf/scripts/latency_sync.hcm +++ /dev/null @@ -1,9 +0,0 @@ -setstream(1); -loop(10); streamsync; endloop(1); -loop(10); streamsync; endloop(1); -loop(100); streamsync; endloop(1); -loop(100); streamsync; endloop(1); -loop(1000); streamsync; endloop(1); -loop(1000); streamsync; endloop(1); -loop(10000); streamsync; endloop(1); -loop(10000); streamsync; endloop(1); diff --git a/projects/hip/samples/1_Utils/hipCommander/setstream.hcm b/projects/hip/samples/1_Utils/hipCommander/setstream.hcm deleted file mode 100644 index 22f1931ac4..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/setstream.hcm +++ /dev/null @@ -1,3 +0,0 @@ -setstream(1); -setstream(2); H2D; NullKernel; D2H; -streamsync diff --git a/projects/hip/samples/1_Utils/hipCommander/testcase.cpp b/projects/hip/samples/1_Utils/hipCommander/testcase.cpp deleted file mode 100644 index 9be1c0c644..0000000000 --- a/projects/hip/samples/1_Utils/hipCommander/testcase.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include - -static const int BLOCKSIZEX = 32; -static const int BLOCKSIZEY = 16; - -__global__ void fails(float* pErrorI) { - if (pErrorI != 0) { - pErrorI[0] = 1; - } -} - -int main() { - dim3 blocks(1, 1); - dim3 threads(BLOCKSIZEX, BLOCKSIZEY); - float error; - - hipLaunchKernelGGL(HIP_KERNEL_NAME(fails), blocks, threads, 0, 0, &error); -} diff --git a/projects/hip/samples/1_Utils/hipDispatchLatency/CMakeLists.txt b/projects/hip/samples/1_Utils/hipDispatchLatency/CMakeLists.txt deleted file mode 100644 index d0a453f1d5..0000000000 --- a/projects/hip/samples/1_Utils/hipDispatchLatency/CMakeLists.txt +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(hipDispatchLatency) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(hipDispatchLatency hipDispatchLatency.cpp) -add_executable(hipDispatchEnqueueRateMT hipDispatchEnqueueRateMT.cpp) - -# Generate code object -add_custom_target( - codeobj - ALL - COMMAND ${HIP_HIPCC_EXECUTABLE} --genco ../test_kernel.cpp -o test_kernel.code - COMMENT "codeobj generated" -) - -add_dependencies(hipDispatchLatency codeobj) -add_dependencies(hipDispatchEnqueueRateMT codeobj) - -# Link with HIP -target_link_libraries(hipDispatchLatency hip::host) -target_link_libraries(hipDispatchEnqueueRateMT hip::host) -set_property(TARGET hipDispatchLatency PROPERTY CXX_STANDARD 11) -set_property(TARGET hipDispatchEnqueueRateMT PROPERTY CXX_STANDARD 11) diff --git a/projects/hip/samples/1_Utils/hipDispatchLatency/Makefile b/projects/hip/samples/1_Utils/hipDispatchLatency/Makefile deleted file mode 100644 index fbe37d2932..0000000000 --- a/projects/hip/samples/1_Utils/hipDispatchLatency/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc -std=c++11 - -CXXFLAGS = -O3 - -all: test_kernel.code hipDispatchLatency.out hipDispatchEnqueueRateMT.out - -hipDispatchLatency.out: hipDispatchLatency.cpp - $(HIPCC) $(CXXFLAGS) hipDispatchLatency.cpp -o $@ - -hipDispatchEnqueueRateMT.out: hipDispatchEnqueueRateMT.cpp - $(HIPCC) $(CXXFLAGS) hipDispatchEnqueueRateMT.cpp -o $@ - -test_kernel.code: test_kernel.cpp - $(HIP_PATH)/bin/hipcc --genco $(GENCO_FLAGS) $^ -o $@ -clean: - rm -f *.o *.out diff --git a/projects/hip/samples/1_Utils/hipDispatchLatency/hipDispatchEnqueueRateMT.cpp b/projects/hip/samples/1_Utils/hipDispatchLatency/hipDispatchEnqueueRateMT.cpp deleted file mode 100644 index 9bc3258b4d..0000000000 --- a/projects/hip/samples/1_Utils/hipDispatchLatency/hipDispatchEnqueueRateMT.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/* -Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include -#include "hip/hip_runtime.h" -#ifdef __HIP_PLATFORM_AMD__ -#include "hip/hip_ext.h" -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define NUM_GROUPS 1 -#define GROUP_SIZE 1 -#define WARMUP_RUN_COUNT 10 -#define TIMING_RUN_COUNT 100 -#define TOTAL_RUN_COUNT WARMUP_RUN_COUNT + TIMING_RUN_COUNT -#define FILENAME "test_kernel.code" -#define failed(...) \ - abort(); - -#define HIPCHECK(error) \ - { \ - hipError_t localError = error; \ - if ((localError != hipSuccess) && (localError != hipErrorPeerAccessAlreadyEnabled)) { \ - printf("error: '%s'(%d) from %s at %s:%d\n", hipGetErrorString(localError), \ - localError, #error, __FILE__, __LINE__); \ - failed("API returned error code."); \ - } \ - } - - -__global__ void EmptyKernel() {} - -// Helper to print various timing metrics -void print_timing(std::string test, std::array &results, int batch = 1) -{ - - float total_us = 0.0f, mean_us = 0.0f, stddev_us = 0.0f; - - // remove top outliers due to nature of variability across large number of multi-threaded runs - std::sort(results.begin(), results.end(), std::greater()); - auto start_iter = std::next(results.begin(), WARMUP_RUN_COUNT); - auto end_iter = results.end(); - - // mean - std::for_each(start_iter, end_iter, [&](const float &run_ms) { - total_us += (run_ms * 1000) / batch; - }); - mean_us = total_us / TIMING_RUN_COUNT; - - // stddev - total_us = 0; - std::for_each(start_iter, end_iter, [&](const float &run_ms) { - float dev_us = ((run_ms * 1000) / batch) - mean_us; - total_us += dev_us * dev_us; - }); - stddev_us = sqrt(total_us / TIMING_RUN_COUNT); - - printf("\n %s: %.1f us, std: %.1f us\n", test.c_str(), mean_us, stddev_us); -} - -// Measure time taken to enqueue a kernel on the GPU using hipModuleLaunchKernel -void hipModuleLaunchKernel_enqueue_rate(const std::vector& buffer, std::atomic_int* shared, int max_threads) -{ - //resources necessary for this thread - hipStream_t stream; - HIPCHECK(hipStreamCreate(&stream)); - hipModule_t module; - hipFunction_t function; - - HIPCHECK(hipModuleLoadData(&module, &buffer[0])); - HIPCHECK(hipModuleGetFunction(&function, module, "test")); - - void* kernel_params = nullptr; - std::array results; - - //synchronize all threads, before running - int tid = shared->fetch_add(1, std::memory_order_release); - while (max_threads != shared->load(std::memory_order_acquire)) {} - - for (auto i = 0; i < TOTAL_RUN_COUNT; ++i) { - auto start = std::chrono::high_resolution_clock::now(); - HIPCHECK(hipModuleLaunchKernel(function, 1, 1, 1, 1, 1, 1, 0, stream, &kernel_params, nullptr)); - auto stop = std::chrono::high_resolution_clock::now(); - results[i] = std::chrono::duration(stop - start).count(); - } - HIPCHECK(hipModuleUnload(module)); - print_timing("Thread ID : " + std::to_string(tid) + " , " + "hipModuleLaunchKernel enqueue rate", results); - HIPCHECK(hipStreamDestroy(stream)); -} - -// Measure time taken to enqueue a kernel on the GPU using hipLaunchKernelGGL -void hipLaunchKernelGGL_enqueue_rate(const std::vector& buffer, std::atomic_int* shared, int max_threads) -{ - //resources necessary for this thread - hipStream_t stream; - HIPCHECK(hipStreamCreate(&stream)); - std::array results; - - //synchronize all threads, before running - int tid = shared->fetch_add(1, std::memory_order_release); - while (max_threads != shared->load(std::memory_order_acquire)) {} - - for (auto i = 0; i < TOTAL_RUN_COUNT; ++i) { - auto start = std::chrono::high_resolution_clock::now(); - hipLaunchKernelGGL((EmptyKernel), dim3(NUM_GROUPS), dim3(GROUP_SIZE), 0, stream); - auto stop = std::chrono::high_resolution_clock::now(); - results[i] = std::chrono::duration(stop - start).count(); - } - print_timing("Thread ID : " + std::to_string(tid) + " , " + "hipLaunchKernelGGL enqueue rate", results); - HIPCHECK(hipStreamDestroy(stream)); -} - -// Simple thread pool -struct thread_pool { - thread_pool(int total_threads) : max_threads(total_threads) { - std::ifstream file(FILENAME, std::ios::binary | std::ios::ate); - std::streamsize fsize = file.tellg(); - file.seekg(0, std::ios::beg); - - buffer.resize(fsize); - if (!file.read(buffer.data(), fsize)) { - failed("could not open code object '%s'\n", FILENAME); - } - file.close(); - } - void start(std::function&, std::atomic_int*, int)> f) { - for (int i = 0; i < max_threads; ++i) { - threads.push_back(std::async(std::launch::async, f, std::ref(buffer), &shared, max_threads)); - } - } - void finish() { - for (auto&&thread : threads) { - thread.get(); - } - threads.clear(); - shared = 0; - } - ~thread_pool() { - finish(); - } -private: - std::atomic_int shared {0}; - std::vector buffer; - std::vector> threads; - int max_threads = 1; -}; - - -int main(int argc, char* argv[]) -{ - if (argc != 3) { - std::cerr << "Run test as 'hipDispatchEnqueueRateMT <0-hipModuleLaunchKernel /1-hipLaunchKernelGGL>'\n"; - return -1; - } - int max_threads = atoi(argv[1]); - int run_module_test = atoi(argv[2]); - if(max_threads < 1 || run_module_test < 0 || run_module_test > 1) { - std::cerr << "Invalid Input.\n"; - std::cerr << "Run test as 'hipDispatchEnqueueRateMT <0-hipModuleLaunchKernel /1-hipLaunchKernelGGL>'\n"; - return -1; - } - thread_pool task(max_threads); - - if(run_module_test == 0) { - task.start(hipModuleLaunchKernel_enqueue_rate); - task.finish(); - } else { - task.start(hipLaunchKernelGGL_enqueue_rate); - task.finish(); - } - return 0; -} diff --git a/projects/hip/samples/1_Utils/hipDispatchLatency/hipDispatchLatency.cpp b/projects/hip/samples/1_Utils/hipDispatchLatency/hipDispatchLatency.cpp deleted file mode 100644 index 5b96f3a199..0000000000 --- a/projects/hip/samples/1_Utils/hipDispatchLatency/hipDispatchLatency.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" -#ifdef __HIP_PLATFORM_AMD__ -#include "hip/hip_ext.h" -#endif -#include -#include -#include - -#define NUM_GROUPS 1 -#define GROUP_SIZE 1 -#define WARMUP_RUN_COUNT 10 -#define TIMING_RUN_COUNT 100 -#define TOTAL_RUN_COUNT WARMUP_RUN_COUNT + TIMING_RUN_COUNT -#define BATCH_SIZE 1000 - -#define FILE_NAME "test_kernel.code" -#define KERNEL_NAME "test" - -__global__ void EmptyKernel() { } - -void print_timing(std::string test, const std::array &results, int batch = 1) { - - float total_us = 0.0f, mean_us = 0.0f, stddev_us = 0.0f; - - // skip warm-up runs - auto start_iter = std::next(results.begin(), WARMUP_RUN_COUNT); - auto end_iter = results.end(); - - // mean - std::for_each(start_iter, end_iter, [&](const float &run_ms) { - total_us += (run_ms * 1000) / batch; - }); - mean_us = total_us / TIMING_RUN_COUNT; - - // stddev - total_us = 0; - std::for_each(start_iter, end_iter, [&](const float &run_ms) { - float dev_us = ((run_ms * 1000) / batch) - mean_us; - total_us += dev_us * dev_us; - }); - stddev_us = sqrt(total_us / TIMING_RUN_COUNT); - - // display - printf("\n %s: %.1f us, std: %.1f us\n", test.c_str(), mean_us, stddev_us); -} - -int main() { - hipStream_t stream0 = 0; - hipDevice_t device; - hipDeviceGet(&device, 0); - hipCtx_t context; - hipCtxCreate(&context, 0, device); - hipModule_t module; - hipFunction_t function; - hipModuleLoad(&module, FILE_NAME); - hipModuleGetFunction(&function, module, KERNEL_NAME); - void* params = nullptr; - - std::array results; - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - - /************************************************************************************/ - /* HIP kernel launch enqueue rate: */ - /* Measure time taken to enqueue a kernel on the GPU */ - /************************************************************************************/ - - // Timing hipModuleLaunchKernel - for (auto i = 0; i < TOTAL_RUN_COUNT; ++i) { - auto start = std::chrono::high_resolution_clock::now(); - hipModuleLaunchKernel(function, 1, 1, 1, 1, 1, 1, 0, 0, ¶ms, nullptr); - auto stop = std::chrono::high_resolution_clock::now(); - results[i] = std::chrono::duration(stop - start).count(); - } - print_timing("hipModuleLaunchKernel enqueue rate", results); - - // Timing hipLaunchKernelGGL - for (auto i = 0; i < TOTAL_RUN_COUNT; ++i) { - auto start = std::chrono::high_resolution_clock::now(); - hipLaunchKernelGGL((EmptyKernel), dim3(NUM_GROUPS), dim3(GROUP_SIZE), 0, stream0); - auto stop = std::chrono::high_resolution_clock::now(); - results[i] = std::chrono::duration(stop - start).count(); - } - print_timing("hipLaunchKernelGGL enqueue rate", results); - - /***********************************************************************************/ - /* Single dispatch execution latency using HIP events: */ - /* Measures latency to start & finish executing a kernel with GPU-scope visibility */ - /***********************************************************************************/ - - //Timing around the dispatch - for (auto i = 0; i < TOTAL_RUN_COUNT; ++i) { - hipEventRecord(start, 0); - hipLaunchKernelGGL((EmptyKernel), dim3(NUM_GROUPS), dim3(GROUP_SIZE), 0, stream0); - hipEventRecord(stop, 0); - hipEventSynchronize(stop); - hipEventElapsedTime(&results[i], start, stop); - } - print_timing("Timing around single dispatch latency", results); - - /*********************************************************************************/ - /* Batch dispatch execution latency using HIP events: */ - /* Measures latency to start & finish executing each dispatch in a batch */ - /*********************************************************************************/ - - for (auto i = 0; i < TOTAL_RUN_COUNT; ++i) { - hipEventRecord(start, 0); - for (int j = 0; j < BATCH_SIZE; j++) { - hipLaunchKernelGGL((EmptyKernel), dim3(NUM_GROUPS), dim3(GROUP_SIZE), 0, stream0); - } - hipEventRecord(stop, 0); - hipEventSynchronize(stop); - hipEventElapsedTime(&results[i], start, stop); - } - print_timing("Batch dispatch latency", results, BATCH_SIZE); - - hipEventDestroy(start); - hipEventDestroy(stop); - hipCtxDestroy(context); -} - diff --git a/projects/hip/samples/1_Utils/hipDispatchLatency/test_kernel.cpp b/projects/hip/samples/1_Utils/hipDispatchLatency/test_kernel.cpp deleted file mode 100644 index c396b711fd..0000000000 --- a/projects/hip/samples/1_Utils/hipDispatchLatency/test_kernel.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" - -extern "C" __global__ void test() { -} - diff --git a/projects/hip/samples/1_Utils/hipInfo/CMakeLists.txt b/projects/hip/samples/1_Utils/hipInfo/CMakeLists.txt deleted file mode 100644 index 6192c8ecff..0000000000 --- a/projects/hip/samples/1_Utils/hipInfo/CMakeLists.txt +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -# hipcc.bat fails to qualify as a valid compiler for CMAKE_CXX_COMPILER_ID = ROCMClang -# so the simple compiler test is skipped and forced to use hipcc.bat as compiler -set(CMAKE_C_COMPILER_WORKS 1) -set(CMAKE_CXX_COMPILER_WORKS 1) - -project(hipInfo) - -cmake_minimum_required(VERSION 3.10) - -# flag is set to ON in compute build for windows -option(HIPINFO_INTERNAL_BUILD "Enable building hipInfo from compute" OFF) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# need to set rocm_path for windows -# since clang and hip are two different folders during build/install step -if (WIN32 AND HIPINFO_INTERNAL_BUILD) - set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --rocm-path=${HIP_PATH}") -endif() - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(hipInfo hipInfo.cpp) - -# Link with HIP -target_link_libraries(hipInfo hip::host) - -# Used only when make install is called -# when hipInfo is built as part of compute project -# hipInfo.exe will be installed to install/hip/bin path -if (WIN32 AND HIPINFO_INTERNAL_BUILD) - install(FILES ${PROJECT_BINARY_DIR}/hipInfo.exe DESTINATION .) -endif() diff --git a/projects/hip/samples/1_Utils/hipInfo/Makefile b/projects/hip/samples/1_Utils/hipInfo/Makefile deleted file mode 100644 index c6c343dbd1..0000000000 --- a/projects/hip/samples/1_Utils/hipInfo/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc - -EXE=hipInfo - -all: install - -$(EXE): hipInfo.cpp - $(HIPCC) hipInfo.cpp -o $@ - -install: $(EXE) - cp $(EXE) $(HIP_PATH)/bin - - -clean: - rm -f *.o $(EXE) diff --git a/projects/hip/samples/1_Utils/hipInfo/README.md b/projects/hip/samples/1_Utils/hipInfo/README.md deleted file mode 100644 index d52f8d8fef..0000000000 --- a/projects/hip/samples/1_Utils/hipInfo/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# hipInfo - -Simple tool that prints properties for each device (from hipGetDeviceProperties), and compiler info. - Properties includes all of the architectural feature flags for each device. - -Also demonstrates how to use platform-specific compilation path (testing `__HIP_PLATFORM_AMD__` or `__HIP_PLATFORM_NVIDIA__`) diff --git a/projects/hip/samples/1_Utils/hipInfo/hipInfo.cpp b/projects/hip/samples/1_Utils/hipInfo/hipInfo.cpp deleted file mode 100644 index 28128b6d33..0000000000 --- a/projects/hip/samples/1_Utils/hipInfo/hipInfo.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include -#include -#include "hip/hip_runtime.h" - -#define KNRM "\x1B[0m" -#define KRED "\x1B[31m" -#define KGRN "\x1B[32m" -#define KYEL "\x1B[33m" -#define KBLU "\x1B[34m" -#define KMAG "\x1B[35m" -#define KCYN "\x1B[36m" -#define KWHT "\x1B[37m" - -#define failed(...) \ - printf("%serror: ", KRED); \ - printf(__VA_ARGS__); \ - printf("\n"); \ - printf("error: TEST FAILED\n%s", KNRM); \ - exit(EXIT_FAILURE); - -#define HIPCHECK(error) \ - if (error != hipSuccess) { \ - printf("%serror: '%s'(%d) at %s:%d%s\n", KRED, hipGetErrorString(error), error, __FILE__, \ - __LINE__, KNRM); \ - failed("API returned error code."); \ - } - -void printCompilerInfo() { -#ifdef __NVCC__ - printf("compiler: nvcc\n"); -#endif -} - -double bytesToKB(size_t s) { return (double)s / (1024.0); } -double bytesToGB(size_t s) { return (double)s / (1024.0 * 1024.0 * 1024.0); } - -#define printLimit(w1, limit, units) \ - { \ - size_t val; \ - cudaDeviceGetLimit(&val, limit); \ - std::cout << setw(w1) << #limit ": " << val << " " << units << std::endl; \ - } - - -void printDeviceProp(int deviceId) { - using namespace std; - const int w1 = 34; - - cout << left; - - cout << setw(w1) - << "--------------------------------------------------------------------------------" - << endl; - cout << setw(w1) << "device#" << deviceId << endl; - - hipDeviceProp_t props = {0}; - HIPCHECK(hipGetDeviceProperties(&props, deviceId)); - - cout << setw(w1) << "Name: " << props.name << endl; - cout << setw(w1) << "pciBusID: " << props.pciBusID << endl; - cout << setw(w1) << "pciDeviceID: " << props.pciDeviceID << endl; - cout << setw(w1) << "pciDomainID: " << props.pciDomainID << endl; - cout << setw(w1) << "multiProcessorCount: " << props.multiProcessorCount << endl; - cout << setw(w1) << "maxThreadsPerMultiProcessor: " << props.maxThreadsPerMultiProcessor - << endl; - cout << setw(w1) << "isMultiGpuBoard: " << props.isMultiGpuBoard << endl; - cout << setw(w1) << "clockRate: " << (float)props.clockRate / 1000.0 << " Mhz" << endl; - cout << setw(w1) << "memoryClockRate: " << (float)props.memoryClockRate / 1000.0 << " Mhz" - << endl; - cout << setw(w1) << "memoryBusWidth: " << props.memoryBusWidth << endl; - cout << setw(w1) << "totalGlobalMem: " << fixed << setprecision(2) - << bytesToGB(props.totalGlobalMem) << " GB" << endl; - cout << setw(w1) << "totalConstMem: " << props.totalConstMem << endl; - cout << setw(w1) << "sharedMemPerBlock: " << (float)props.sharedMemPerBlock / 1024.0 << " KB" - << endl; - cout << setw(w1) << "canMapHostMemory: " << props.canMapHostMemory << endl; - cout << setw(w1) << "regsPerBlock: " << props.regsPerBlock << endl; - cout << setw(w1) << "warpSize: " << props.warpSize << endl; - cout << setw(w1) << "l2CacheSize: " << props.l2CacheSize << endl; - cout << setw(w1) << "computeMode: " << props.computeMode << endl; - cout << setw(w1) << "maxThreadsPerBlock: " << props.maxThreadsPerBlock << endl; - cout << setw(w1) << "maxThreadsDim.x: " << props.maxThreadsDim[0] << endl; - cout << setw(w1) << "maxThreadsDim.y: " << props.maxThreadsDim[1] << endl; - cout << setw(w1) << "maxThreadsDim.z: " << props.maxThreadsDim[2] << endl; - cout << setw(w1) << "maxGridSize.x: " << props.maxGridSize[0] << endl; - cout << setw(w1) << "maxGridSize.y: " << props.maxGridSize[1] << endl; - cout << setw(w1) << "maxGridSize.z: " << props.maxGridSize[2] << endl; - cout << setw(w1) << "major: " << props.major << endl; - cout << setw(w1) << "minor: " << props.minor << endl; - cout << setw(w1) << "concurrentKernels: " << props.concurrentKernels << endl; - cout << setw(w1) << "cooperativeLaunch: " << props.cooperativeLaunch << endl; - cout << setw(w1) << "cooperativeMultiDeviceLaunch: " << props.cooperativeMultiDeviceLaunch << endl; - cout << setw(w1) << "isIntegrated: " << props.integrated << endl; - cout << setw(w1) << "maxTexture1D: " << props.maxTexture1D << endl; - cout << setw(w1) << "maxTexture2D.width: " << props.maxTexture2D[0] << endl; - cout << setw(w1) << "maxTexture2D.height: " << props.maxTexture2D[1] << endl; - cout << setw(w1) << "maxTexture3D.width: " << props.maxTexture3D[0] << endl; - cout << setw(w1) << "maxTexture3D.height: " << props.maxTexture3D[1] << endl; - cout << setw(w1) << "maxTexture3D.depth: " << props.maxTexture3D[2] << endl; - -#ifdef __HIP_PLATFORM_AMD__ - cout << setw(w1) << "isLargeBar: " << props.isLargeBar << endl; - cout << setw(w1) << "asicRevision: " << props.asicRevision << endl; - cout << setw(w1) << "maxSharedMemoryPerMultiProcessor: " << fixed << setprecision(2) - << bytesToKB(props.maxSharedMemoryPerMultiProcessor) << " KB" << endl; - cout << setw(w1) << "clockInstructionRate: " << (float)props.clockInstructionRate / 1000.0 - << " Mhz" << endl; - cout << setw(w1) << "arch.hasGlobalInt32Atomics: " << props.arch.hasGlobalInt32Atomics << endl; - cout << setw(w1) << "arch.hasGlobalFloatAtomicExch: " << props.arch.hasGlobalFloatAtomicExch - << endl; - cout << setw(w1) << "arch.hasSharedInt32Atomics: " << props.arch.hasSharedInt32Atomics << endl; - cout << setw(w1) << "arch.hasSharedFloatAtomicExch: " << props.arch.hasSharedFloatAtomicExch - << endl; - cout << setw(w1) << "arch.hasFloatAtomicAdd: " << props.arch.hasFloatAtomicAdd << endl; - cout << setw(w1) << "arch.hasGlobalInt64Atomics: " << props.arch.hasGlobalInt64Atomics << endl; - cout << setw(w1) << "arch.hasSharedInt64Atomics: " << props.arch.hasSharedInt64Atomics << endl; - cout << setw(w1) << "arch.hasDoubles: " << props.arch.hasDoubles << endl; - cout << setw(w1) << "arch.hasWarpVote: " << props.arch.hasWarpVote << endl; - cout << setw(w1) << "arch.hasWarpBallot: " << props.arch.hasWarpBallot << endl; - cout << setw(w1) << "arch.hasWarpShuffle: " << props.arch.hasWarpShuffle << endl; - cout << setw(w1) << "arch.hasFunnelShift: " << props.arch.hasFunnelShift << endl; - cout << setw(w1) << "arch.hasThreadFenceSystem: " << props.arch.hasThreadFenceSystem << endl; - cout << setw(w1) << "arch.hasSyncThreadsExt: " << props.arch.hasSyncThreadsExt << endl; - cout << setw(w1) << "arch.hasSurfaceFuncs: " << props.arch.hasSurfaceFuncs << endl; - cout << setw(w1) << "arch.has3dGrid: " << props.arch.has3dGrid << endl; - cout << setw(w1) << "arch.hasDynamicParallelism: " << props.arch.hasDynamicParallelism << endl; - cout << setw(w1) << "gcnArchName: " << props.gcnArchName << endl; -#endif - int deviceCnt; - hipGetDeviceCount(&deviceCnt); - cout << setw(w1) << "peers: "; - for (int i = 0; i < deviceCnt; i++) { - int isPeer; - hipDeviceCanAccessPeer(&isPeer, i, deviceId); - if (isPeer) { - cout << "device#" << i << " "; - } - } - cout << endl; - cout << setw(w1) << "non-peers: "; - for (int i = 0; i < deviceCnt; i++) { - int isPeer; - hipDeviceCanAccessPeer(&isPeer, i, deviceId); - if (!isPeer) { - cout << "device#" << i << " "; - } - } - cout << endl; - - -#ifdef __HIP_PLATFORM_NVIDIA__ - // Limits: - cout << endl; - printLimit(w1, cudaLimitStackSize, "bytes/thread"); - printLimit(w1, cudaLimitPrintfFifoSize, "bytes/device"); - printLimit(w1, cudaLimitMallocHeapSize, "bytes/device"); - printLimit(w1, cudaLimitDevRuntimeSyncDepth, "grids"); - printLimit(w1, cudaLimitDevRuntimePendingLaunchCount, "launches"); -#endif - - - cout << endl; - - - size_t free, total; - hipMemGetInfo(&free, &total); - - cout << fixed << setprecision(2); - cout << setw(w1) << "memInfo.total: " << bytesToGB(total) << " GB" << endl; - cout << setw(w1) << "memInfo.free: " << bytesToGB(free) << " GB (" << setprecision(0) - << (float)free / total * 100.0 << "%)" << endl; -} - -int main(int argc, char* argv[]) { - using namespace std; - - cout << endl; - - printCompilerInfo(); - - int deviceCnt; - - HIPCHECK(hipGetDeviceCount(&deviceCnt)); - - for (int i = 0; i < deviceCnt; i++) { - hipSetDevice(i); - printDeviceProp(i); - } - - std::cout << std::endl; -} diff --git a/projects/hip/samples/2_Cookbook/0_MatrixTranspose/CMakeLists.txt b/projects/hip/samples/2_Cookbook/0_MatrixTranspose/CMakeLists.txt deleted file mode 100644 index ae4735c1ae..0000000000 --- a/projects/hip/samples/2_Cookbook/0_MatrixTranspose/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(MatrixTranspose) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(MatrixTranspose MatrixTranspose.cpp) - -# Link with HIP -target_link_libraries(MatrixTranspose hip::host) diff --git a/projects/hip/samples/2_Cookbook/0_MatrixTranspose/Makefile b/projects/hip/samples/2_Cookbook/0_MatrixTranspose/Makefile deleted file mode 100644 index 6d5b787510..0000000000 --- a/projects/hip/samples/2_Cookbook/0_MatrixTranspose/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = MatrixTranspose.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./MatrixTranspose - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o - diff --git a/projects/hip/samples/2_Cookbook/0_MatrixTranspose/MatrixTranspose.cpp b/projects/hip/samples/2_Cookbook/0_MatrixTranspose/MatrixTranspose.cpp deleted file mode 100644 index 8444cff851..0000000000 --- a/projects/hip/samples/2_Cookbook/0_MatrixTranspose/MatrixTranspose.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - - -#define WIDTH 1024 - - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - out[y * width + x] = in[x * width + y]; -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix, - gpuMatrix, WIDTH); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/0_MatrixTranspose/Readme.md b/projects/hip/samples/2_Cookbook/0_MatrixTranspose/Readme.md deleted file mode 100644 index b53549ada7..0000000000 --- a/projects/hip/samples/2_Cookbook/0_MatrixTranspose/Readme.md +++ /dev/null @@ -1,101 +0,0 @@ -## Writing first HIP program ### - -This tutorial shows how to get write simple HIP application. We will write the simplest Matrix Transpose program. - -## HIP Introduction: - -HIP is a C++ runtime API and kernel language that allows developers to create portable applications that can run on AMD and other GPU’s. Our goal was to rise above the lowest-common-denominator paths and deliver a solution that allows you, the developer, to use essential hardware features and maximize your application’s performance on GPU hardware. - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -Here is simple example showing how to write your first program in HIP. -In order to use the HIP framework, we need to add the "hip_runtime.h" header file. SInce its c++ api you can add any header file you have been using earlier while writing your c/c++ program. For gpgpu programming, we have host(microprocessor) and the device(gpu). - -## Device-side code -We will work on device side code first, Here is simple example showing a snippet of HIP device side code: - -``` -__global__ void matrixTranspose(float *out, - float *in, - const int width, - const int height) -{ - int x = blockDim.x * blockIdx.x + bhreadIdx.x; - int y = blockDim.y * blockIdx.y + bhreadIdx.y; - - out[y * width + x] = in[x * height + y]; -} -``` - -`__global__` keyword is the Function-Type Qualifiers, it is used with functions that are executed on device and are called/launched from the hosts. -other function-type qualifiers are: -`__device__` functions are Executed on the device and Called from the device only -`__host__` functions are Executed on the host and Called from the host - -`__host__` can combine with `__device__`, in which case the function compiles for both the host and device. These functions cannot use the HIP grid coordinate functions (for example, "threadIdx.x", will talk about it latter). A possible workaround is to pass the necessary coordinate info as an argument to the function. -`__host__` cannot combine with `__global__`. - -`__global__` functions are often referred to as *kernels*, and calling one is termed *launching the kernel*. - -Next keyword is `void`. HIP `__global__` functions must have a `void` return type. Global functions require the caller to specify an "execution configuration" that includes the grid and block dimensions. The execution configuration can also include other information for the launch, such as the amount of additional shared memory to allocate and the stream where the kernel should execute. - -The kernel function begins with -` int x = blockDim.x * blockIdx.x + threadIdx.x;` -` int y = blockDim.y * blockIdx.y + threadIdx.y;` -here the keyword blockIdx.x, blockIdx.y and blockIdx.z(not used here) are the built-in functions to identify the threads in a block. The keyword blockDim.x, blockDim.y and blockDim.z(not used here) are to identify the dimensions of the block. - -We are familiar with rest of the code on device-side. - -## Host-side code - -Now, we'll see how to call the kernel from the host. Inside the main() function, we first defined the pointers(for both, the host-side as well as device). The declaration of device pointer is similar to that of the host. Next, we have `hipDeviceProp_t`, it is the pre-defined struct for hip device properties. This is followed by `hipGetDeviceProperties(&devProp, 0)` It is used to extract the device information. The first parameter is the struct, second parameter is the device number to get properties for. Next line print the name of the device. - -We allocated memory to the Matrix on host side by using malloc and initiallized it. While in order to allocate memory on device side we will be using `hipMalloc`, it's quiet similar to that of malloc instruction. After this, we will copy the data to the allocated memory on device-side using `hipMemcpy`. -` hipMemcpy(gpuMatrix, Matrix, NUM*sizeof(float), hipMemcpyHostToDevice);` -here the first parameter is the destination pointer, second is the source pointer, third is the size of memory copy and the last specify the direction on memory copy(which is in this case froom host to device). While in order to transfer memory from device to host, use `hipMemcpyDeviceToHost` and for device to device memory copy use `hipMemcpyDeviceToDevice`. - -Now, we'll see how to launch the kernel. -``` - hipLaunchKernelGGL(matrixTranspose, - dim3(WIDTH/THREADS_PER_BLOCK_X, HEIGHT/THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), - 0, 0, - gpuTransposeMatrix , gpuMatrix, WIDTH ,HEIGHT); -``` - -HIP introduces a standard C++ calling convention to pass the execution configuration to the kernel (this convention replaces the `Cuda <<< >>>` syntax). In HIP, -- Kernels launch with the `"hipLaunchKernelGGL"` function -- The first five parameters to hipLaunchKernelGGL are the following: - - **symbol kernelName**: the name of the kernel to launch. To support template kernels which contains "," use the HIP_KERNEL_NAME macro. In current application it's "matrixTranspose". - - **dim3 gridDim**: 3D-grid dimensions specifying the number of blocks to launch. In MatrixTranspose sample, it's "dim3(WIDTH/THREADS_PER_BLOCK_X, HEIGHT/THREADS_PER_BLOCK_Y)". - - **dim3 blockDim**: 3D-block dimensions specifying the number of threads in each block.In MatrixTranspose sample, it's "dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y)". - - **size_t dynamicShared**: amount of additional shared memory to allocate when launching the kernel. In MatrixTranspose sample, it's '0'. - - **hipStream_t**: stream where the kernel should execute. A value of 0 corresponds to the NULL stream.In MatrixTranspose sample, it's '0'. -- Kernel arguments follow these first five parameters. Here, these are "gpuTransposeMatrix , gpuMatrix, WIDTH ,HEIGHT". - -Next, we'll copy the computed values/data back to the device using the `hipMemcpy`. Here the last parameter will be `hipMemcpyDeviceToHost` - -After, copying the data from device to memory, we will verify it with the one we computed with the cpu reference funtion. - -Finally, we will free the memory allocated earlier by using free() for host while for devices we will use `hipFree`. - -## How to build and run: -Use the make command and execute it using ./exe -Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia. - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/10_inline_asm/CMakeLists.txt b/projects/hip/samples/2_Cookbook/10_inline_asm/CMakeLists.txt deleted file mode 100644 index ac4e586772..0000000000 --- a/projects/hip/samples/2_Cookbook/10_inline_asm/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(inline_asm) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(inline_asm inline_asm.cpp) - -# Link with HIP -target_link_libraries(inline_asm hip::host) diff --git a/projects/hip/samples/2_Cookbook/10_inline_asm/Makefile b/projects/hip/samples/2_Cookbook/10_inline_asm/Makefile deleted file mode 100644 index 58f013a2ba..0000000000 --- a/projects/hip/samples/2_Cookbook/10_inline_asm/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) 2017 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = inline_asm.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./inline_asm - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - diff --git a/projects/hip/samples/2_Cookbook/10_inline_asm/Readme.md b/projects/hip/samples/2_Cookbook/10_inline_asm/Readme.md deleted file mode 100644 index e86085b648..0000000000 --- a/projects/hip/samples/2_Cookbook/10_inline_asm/Readme.md +++ /dev/null @@ -1,60 +0,0 @@ -## inline asm ### - -This tutorial is about how to use inline GCN asm in kernel. In this tutorial, we'll explain how to by using the simple Matrix Transpose. - -## Introduction: - -If you want to take advantage of the extra performance benefits of writing in assembly as well as take advantage of special GPU hardware features that were only available through assemby, then this tutorial is for you. In this tutorial we'll be explaining how to start writing inline asm in kernel. - -For more insight Please read the following blogs by Ben Sander -[The Art of AMDGCN Assembly: How to Bend the Machine to Your Will](gpuopen.com/amdgcn-assembly) -[AMD GCN Assembly: Cross-Lane Operations](http://gpuopen.com/amd-gcn-assembly-cross-lane-operations/) - -For more information: -[AMD GCN3 ISA Architecture Manual](http://gpuopen.com/compute-product/amd-gcn3-isa-architecture-manual/) -[User Guide for AMDGPU Back-end](llvm.org/docs/AMDGPUUsage.html) - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -We will be using the Simple Matrix Transpose application from the our very first tutorial. - -## asm() Assembler statement - -In the same sourcecode, we used for MatrixTranspose. We'll add the following: - -` asm volatile ("v_mov_b32_e32 %0, %1" : "=v" (out[x*width + y]) : "v" (in[y*width + x])); ` - -GCN ISA In-line assembly, is supported. For example: - -``` -asm volatile ("v_mac_f32_e32 %0, %2, %3" : "=v" (out[i]) : "0"(out[i]), "v" (a), "v" (in[i])); -``` - -We insert the GCN isa into the kernel using `asm()` Assembler statement. -`volatile` keyword is used so that the optimizers must not change the number of volatile operations or change their order of execution relative to other volatile operations. -`v_mac_f32_e32` is the GCN instruction, for more information please refer - [AMD GCN3 ISA architecture manual](http://gpuopen.com/compute-product/amd-gcn3-isa-architecture-manual/) -Index for the respective operand in the ordered fashion is provided by `%` followed by position in the list of operands -`"v"` is the constraint code (for target-specific AMDGPU) for 32-bit VGPR register, for more info please refer - [Supported Constraint Code List for AMDGPU](https://llvm.org/docs/LangRef.html#supported-constraint-code-list) -Output Constraints are specified by an `"="` prefix as shown above ("=v"). This indicate that assemby will write to this operand, and the operand will then be made available as a return value of the asm expression. Input constraints do not have a prefix - just the constraint code. The constraint string of `"0"` says to use the assigned register for output as an input as well (it being the 0'th constraint). - -## How to build and run: -Use the make command and execute it using ./exe -Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia. - - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/10_inline_asm/inline_asm.cpp b/projects/hip/samples/2_Cookbook/10_inline_asm/inline_asm.cpp deleted file mode 100644 index 8145b3c86e..0000000000 --- a/projects/hip/samples/2_Cookbook/10_inline_asm/inline_asm.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - -#define WIDTH 1024 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - asm volatile("v_mov_b32_e32 %0, %1" : "=v"(out[x * width + y]) : "v"(in[y * width + x])); -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - float eventMs = 1.0f; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Record the start event - hipEventRecord(start, NULL); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - - hipEventElapsedTime(&eventMs, start, stop); - - printf("hipMemcpyHostToDevice time taken = %6.3fms\n", eventMs); - - // Record the start event - hipEventRecord(start, NULL); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix, - gpuMatrix, WIDTH); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - - hipEventElapsedTime(&eventMs, start, stop); - - printf("kernel Execution time = %6.3fms\n", eventMs); - - // Record the start event - hipEventRecord(start, NULL); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - - hipEventElapsedTime(&eventMs, start, stop); - - printf("hipMemcpyDeviceToHost time taken = %6.3fms\n", eventMs); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - printf("gpu%f cpu %f \n", TransposeMatrix[i], cpuTransposeMatrix[i]); - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/11_texture_driver/CMakeLists.txt b/projects/hip/samples/2_Cookbook/11_texture_driver/CMakeLists.txt deleted file mode 100644 index f93b2e791e..0000000000 --- a/projects/hip/samples/2_Cookbook/11_texture_driver/CMakeLists.txt +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(texture2dDrv) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(texture2dDrv texture2dDrv.cpp) - -# Generate code object -add_custom_target( - codeobj - ALL - COMMAND ${HIP_HIPCC_EXECUTABLE} --genco ../tex2dKernel.cpp -o tex2dKernel.code - COMMENT "codeobj generated" -) - -add_dependencies(texture2dDrv codeobj) - -# Link with HIP -target_link_libraries(texture2dDrv hip::host) diff --git a/projects/hip/samples/2_Cookbook/11_texture_driver/Makefile b/projects/hip/samples/2_Cookbook/11_texture_driver/Makefile deleted file mode 100644 index f149005aa5..0000000000 --- a/projects/hip/samples/2_Cookbook/11_texture_driver/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2017 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc -HIP_PLATFORM=$(shell $(HIP_PATH)/bin/hipconfig --compiler) - -all: tex2dKernel.code texture2dDrv.out - -texture2dDrv.out: texture2dDrv.cpp - $(HIPCC) $(HIPCC_FLAGS) $< -o $@ - -tex2dKernel.code: tex2dKernel.cpp - $(HIPCC) --genco $(GENCO_FLAGS) $^ -o $@ - -clean: - rm -f *.code *.out diff --git a/projects/hip/samples/2_Cookbook/11_texture_driver/tex2dKernel.cpp b/projects/hip/samples/2_Cookbook/11_texture_driver/tex2dKernel.cpp deleted file mode 100644 index a1d3985de5..0000000000 --- a/projects/hip/samples/2_Cookbook/11_texture_driver/tex2dKernel.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ -#include "hip/hip_runtime.h" - -texture texChar; -texture texShort; -texture texInt; -texture texFloat; - -texture texChar4; -texture texShort4; -texture texInt4; -texture texFloat4; - -extern "C" __global__ void tex2dKernelChar(char* outputData, int width, int height) { - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - outputData[y * width + x] = tex2D(texChar, x, y); -} - -extern "C" __global__ void tex2dKernelShort(short* outputData, int width, int height) { - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - outputData[y * width + x] = tex2D(texShort, x, y); -} - -extern "C" __global__ void tex2dKernelInt(int* outputData, int width, int height) { - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - outputData[y * width + x] = tex2D(texInt, x, y); -} - -extern "C" __global__ void tex2dKernelFloat(float* outputData, int width, int height) { - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - outputData[y * width + x] = tex2D(texFloat, x, y); -} - -extern "C" __global__ void tex2dKernelChar4(char4* outputData, int width, int height) { - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - outputData[y * width + x] = tex2D(texChar4, x, y); -} - -extern "C" __global__ void tex2dKernelShort4(short4* outputData, int width, int height) { - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - outputData[y * width + x] = tex2D(texShort4, x, y); -} - -extern "C" __global__ void tex2dKernelInt4(int4* outputData, int width, int height) { - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - outputData[y * width + x] = tex2D(texInt4, x, y); -} - -extern "C" __global__ void tex2dKernelFloat4(float4* outputData, int width, int height) { - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - outputData[y * width + x] = tex2D(texFloat4, x, y); -} diff --git a/projects/hip/samples/2_Cookbook/11_texture_driver/texture2dDrv.cpp b/projects/hip/samples/2_Cookbook/11_texture_driver/texture2dDrv.cpp deleted file mode 100644 index fbeac3d41a..0000000000 --- a/projects/hip/samples/2_Cookbook/11_texture_driver/texture2dDrv.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" -#include -#include -#include - -#define fileName "tex2dKernel.code" - -bool testResult = true; - -#define HIP_CHECK(cmd) \ - { \ - hipError_t status = cmd; \ - if (status != hipSuccess) { \ - std::cout << "error: #" << status << " (" << hipGetErrorString(status) \ - << ") at line:" << __LINE__ << ": " << #cmd << std::endl; \ - abort(); \ - } \ - } - -template::value>::type *t = nullptr> -static inline hipArray_Format getArrayFormat() { - if (std::is_same::value) { - return HIP_AD_FORMAT_SIGNED_INT8; - } else if (std::is_same::value) { - return HIP_AD_FORMAT_SIGNED_INT16; - } else if (std::is_same::value) { - return HIP_AD_FORMAT_SIGNED_INT32; - } else if (std::is_same::value) { - return HIP_AD_FORMAT_FLOAT; - } - return HIP_AD_FORMAT_HALF; -} - -template::value>::type *t = nullptr> -static inline hipArray_Format getArrayFormat() { - return getArrayFormat(); -} - -template -static inline constexpr int rank() { - return sizeof(T) / sizeof(decltype(T::x)); -} - -template -static inline T getRandom() { - double r = 0; - if (std::is_signed < T > ::value) { - r = (std::rand() - RAND_MAX / 2.0) / (RAND_MAX / 2.0 + 1.); - } else { - r = std::rand() / (RAND_MAX + 1.); - } - return static_cast(std::numeric_limits < T > ::max() * r); -} - -template::value>::type* = nullptr> -static inline constexpr int getChannels() { - return 1; -} - -template::value>::type *t = nullptr, - typename std::enable_if() != 0>::type *r = nullptr> -static inline constexpr int getChannels() { - return rank(); -} - -template::value>::type* = nullptr> -static inline void printDiff(const int &i, const int &j, const T &expected, - const T &output) { - std::cout << "Difference [" << i << " " << j << "]: " << expected << " - " - << output << "\n"; -} - -template::value>::type* = nullptr, - typename std::enable_if() == 4>::type* = nullptr> -static inline void printDiff(const int &i, const int &j, const T &expected, - const T &output) { - std::cout << "Difference [" << i << " " << j << "]: " << expected.x << "," - << expected.y << "," << expected.z << "," << expected.w << " - " - << output.x << "," << output.y << "," << output.z << "," << output.w - << "\n"; -} - -template::value>::type* = nullptr> -static inline void initVal(T &val) { - val = getRandom(); -} - -template::value>::type* = nullptr, - typename std::enable_if() == 4>::type* = nullptr> -static inline void initVal(T &val) { - val.x = getRandom(); - val.y = getRandom(); - val.z = getRandom(); - val.w = getRandom(); -} - -template -bool runTest(hipModule_t &module, const char *refName, const char *funcName) { - hipArray_Format format = getArrayFormat(); - int channels = getChannels(); - unsigned int width = 256; - unsigned int height = 256; - unsigned int size = width * height * sizeof(T); - T *hData = (T*) malloc(size); - memset(hData, 0, size); - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j++) { - initVal(hData[i * width + j]); - } - } - - hipArray *array; - HIP_ARRAY_DESCRIPTOR desc; - desc.Format = format; - desc.NumChannels = channels; - desc.Width = width; - desc.Height = height; - HIP_CHECK(hipArrayCreate(&array, &desc)); - - hip_Memcpy2D copyParam; - memset(©Param, 0, sizeof(copyParam)); - copyParam.dstMemoryType = hipMemoryTypeArray; - copyParam.dstArray = array; - copyParam.srcMemoryType = hipMemoryTypeHost; - copyParam.srcHost = hData; - copyParam.srcPitch = width * sizeof(T); - copyParam.WidthInBytes = copyParam.srcPitch; - copyParam.Height = height; - HIP_CHECK(hipMemcpyParam2D(©Param)); - - textureReference *texref; - HIP_CHECK(hipModuleGetTexRef(&texref, module, refName)); - HIP_CHECK(hipTexRefSetAddressMode(texref, 0, hipAddressModeClamp)); - HIP_CHECK(hipTexRefSetAddressMode(texref, 1, hipAddressModeClamp)); - HIP_CHECK(hipTexRefSetFilterMode(texref, hipFilterModePoint)); - HIP_CHECK(hipTexRefSetFlags(texref, HIP_TRSF_READ_AS_INTEGER)); - HIP_CHECK(hipTexRefSetFormat(texref, format, channels)); - HIP_CHECK(hipTexRefSetArray(texref, array, HIP_TRSA_OVERRIDE_FORMAT)); - - T *dData = NULL; - HIP_CHECK(hipMalloc((void** )&dData, size)); - - struct { - void *_Ad; - unsigned int _Bd; - unsigned int _Cd; - } args; - args._Ad = (void*) dData; - args._Bd = width; - args._Cd = height; - - size_t sizeTemp = sizeof(args); - - void *config[] = { HIP_LAUNCH_PARAM_BUFFER_POINTER, &args, - HIP_LAUNCH_PARAM_BUFFER_SIZE, &sizeTemp, HIP_LAUNCH_PARAM_END }; - - hipFunction_t Function; - HIP_CHECK(hipModuleGetFunction(&Function, module, funcName)); - - int temp1 = width / 16; - int temp2 = height / 16; - HIP_CHECK( - hipModuleLaunchKernel(Function, 16, 16, 1, temp1, temp2, 1, 0, 0, NULL, - (void** )&config)); - hipDeviceSynchronize(); - - T *hOutputData = (T*) malloc(size); - memset(hOutputData, 0, size); - HIP_CHECK(hipMemcpy(hOutputData, dData, size, hipMemcpyDeviceToHost)); - - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j++) { - if (hData[i * width + j] != hOutputData[i * width + j]) { - printDiff(i, j, hData[i * width + j], hOutputData[i * width + j]); - testResult = false; - break; - } - } - } - HIP_CHECK(hipUnbindTexture(texref)); - HIP_CHECK(hipFree(dData)); - HIP_CHECK(hipFreeArray(array)); - free(hOutputData); - free(hData); - printf("%s test %s ...\n", funcName, testResult ? "PASSED" : "FAILED"); - return testResult; -} - -inline bool isImageSupported() { - int imageSupport = 1; -#ifdef __HIP_PLATFORM_AMD__ - HIP_CHECK(hipDeviceGetAttribute(&imageSupport, hipDeviceAttributeImageSupport, - 0)); -#endif - return imageSupport != 0; -} - -int main(int argc, char** argv) { - if (!isImageSupported()) { - printf("Texture is not support on the device. Skipped.\n"); - return 0; - } - hipInit(0); - hipModule_t module; - HIP_CHECK(hipModuleLoad(&module, fileName)); - testResult = testResult && runTest(module, "texChar", "tex2dKernelChar"); - testResult = testResult && runTest(module, "texShort", "tex2dKernelShort"); - testResult = testResult && runTest(module, "texInt", "tex2dKernelInt"); - testResult = testResult && runTest(module, "texFloat", "tex2dKernelFloat"); - testResult = testResult && runTest(module, "texChar4", "tex2dKernelChar4"); - testResult = testResult && runTest(module, "texShort4", "tex2dKernelShort4"); - testResult = testResult && runTest(module, "texInt4", "tex2dKernelInt4"); - testResult = testResult && runTest(module, "texFloat4", "tex2dKernelFloat4"); - - HIP_CHECK(hipModuleUnload(module)); - printf("texture2dDrv %s ...\n", testResult ? "PASSED" : "FAILED"); - return testResult ? EXIT_SUCCESS : EXIT_FAILURE; -} diff --git a/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/CMakeLists.txt b/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/CMakeLists.txt deleted file mode 100644 index f1a8bf8a82..0000000000 --- a/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/CMakeLists.txt +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -cmake_minimum_required(VERSION 2.8.3) -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -if(NOT DEFINED HIP_PATH) - if(NOT DEFINED ENV{HIP_PATH}) - set(HIP_PATH "${ROCM_PATH}/hip" CACHE PATH "Path to which HIP has been installed") - else() - set(HIP_PATH $ENV{HIP_PATH} CACHE PATH "Path to which HIP has been installed") - endif() -endif() -set(CMAKE_MODULE_PATH "${HIP_PATH}/cmake" ${CMAKE_MODULE_PATH}) -set(CMAKE_HIP_ARCHITECTURES OFF) -project(12_cmake) - -set(HIP_CLANG_NUM_PARALLEL_JOBS 2) -find_package(HIP QUIET) -if(HIP_FOUND) - message(STATUS "Found HIP: " ${HIP_VERSION}) -else() - message(FATAL_ERROR "Could not find HIP. Ensure that HIP is either installed in ${ROCM_PATH}/hip or the variable HIP_PATH is set to point to the right location.") -endif() - -set(MY_SOURCE_FILES MatrixTranspose.cpp) -set(MY_TARGET_NAME MatrixTranspose) -set(MY_HIPCC_OPTIONS) -set(MY_HCC_OPTIONS) -set(MY_CLANG_OPTIONS) -set(MY_NVCC_OPTIONS) - -set_source_files_properties(${MY_SOURCE_FILES} PROPERTIES HIP_SOURCE_PROPERTY_FORMAT 1) -hip_add_executable(${MY_TARGET_NAME} ${MY_SOURCE_FILES} HIPCC_OPTIONS ${MY_HIPCC_OPTIONS} HCC_OPTIONS ${MY_HCC_OPTIONS} CLANG_OPTIONS ${MY_CLANG_OPTIONS} NVCC_OPTIONS ${MY_NVCC_OPTIONS}) - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${HIP_PATH} ${ROCM_PATH}) -find_package(hip QUIET) -if(TARGET hip::host) - message(STATUS "Found hip::host at ${hip_DIR}") - target_link_libraries(${MY_TARGET_NAME} hip::host) -endif() diff --git a/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/MatrixTranspose.cpp b/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/MatrixTranspose.cpp deleted file mode 100644 index 8444cff851..0000000000 --- a/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/MatrixTranspose.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - - -#define WIDTH 1024 - - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - out[y * width + x] = in[x * width + y]; -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix, - gpuMatrix, WIDTH); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/Readme.md b/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/Readme.md deleted file mode 100644 index b2a4547670..0000000000 --- a/projects/hip/samples/2_Cookbook/12_cmake_hip_add_executable/Readme.md +++ /dev/null @@ -1,59 +0,0 @@ -## hip_add_executable ### -This tutorial shows how to use the FindHIP cmake module and create an executable using ```hip_add_executable``` macro. - -## Including FindHIP cmake module in the project -Since FindHIP cmake module is not yet a part of the default cmake distribution, ```CMAKE_MODULE_PATH``` needs to be updated to contain the path to FindHIP.cmake. - -The simplest approach is to use -``` -set(CMAKE_MODULE_PATH "/opt/rocm/hip/cmake" ${CMAKE_MODULE_PATH}) -find_package(HIP) -``` - -A more generic solution that allows for a user specified location for the HIP installation would look something like -``` -if(NOT DEFINED HIP_PATH) - if(NOT DEFINED ENV{HIP_PATH}) - set(HIP_PATH "/opt/rocm/hip" CACHE PATH "Path to which HIP has been installed") - else() - set(HIP_PATH $ENV{HIP_PATH} CACHE PATH "Path to which HIP has been installed") - endif() -endif() -set(CMAKE_MODULE_PATH "${HIP_PATH}/cmake" ${CMAKE_MODULE_PATH}) -find_package(HIP) -``` - -If your project already modifies ```CMAKE_MODULE_PATH```, you will need to append the path to FindHIP.cmake instead of replacing it. - -## Using the hip_add_executable macro -FindHIP provides the ```hip_add_executable``` macro that is similar to the ```cuda_add_executable``` macro that is provided by FindCUDA. -The syntax is also similar. The ```hip_add_executable``` macro uses the hipcc wrapper as the compiler. -The macro supports specifying CLANG-specific, NVCC-specific compiler options using the ```CLANG_OPTIONS``` and ```NVCC_OPTIONS``` keywords. -Common options targeting both compilers can be specificed after the ```HIPCC_OPTIONS``` keyword. - -## How to build and run: -Use the following commands to build and execute the sample - -``` -mkdir build -cd build - -For shared lib of hip rt, -cmake .. -Or for static lib of hip rt, -cmake -DCMAKE_PREFIX_PATH="/opt/rocm/llvm/lib/cmake" .. - -Then, -make -./MatrixTranspose -``` - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/13_occupancy/CMakeLists.txt b/projects/hip/samples/2_Cookbook/13_occupancy/CMakeLists.txt deleted file mode 100644 index 481cf58b26..0000000000 --- a/projects/hip/samples/2_Cookbook/13_occupancy/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(occupancy) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(occupancy occupancy.cpp) - -# Link with HIP -target_link_libraries(occupancy hip::host) diff --git a/projects/hip/samples/2_Cookbook/13_occupancy/Makefile b/projects/hip/samples/2_Cookbook/13_occupancy/Makefile deleted file mode 100644 index 73f0753afb..0000000000 --- a/projects/hip/samples/2_Cookbook/13_occupancy/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2019 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc - -EXE=./occupancy - -.PHONY: test - -all: test - -$(EXE): occupancy.cpp - $(HIPCC) $^ -o $@ - -test: $(EXE) - $(EXE) - -clean: - rm -f *.o $(EXE) diff --git a/projects/hip/samples/2_Cookbook/13_occupancy/occupancy.cpp b/projects/hip/samples/2_Cookbook/13_occupancy/occupancy.cpp deleted file mode 100644 index 4f51b61c6e..0000000000 --- a/projects/hip/samples/2_Cookbook/13_occupancy/occupancy.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR -IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" -#include -#define NUM 1000000 - -#define HIP_CHECK(status) \ - if (status != hipSuccess) { \ - std::cout << "Got Status: " << status << " at Line: " << __LINE__ << std::endl; \ - exit(0); \ - } - -// Device (Kernel) function -__global__ void multiply(float* C, float* A, float* B, int N){ - - int tx = blockDim.x*blockIdx.x+threadIdx.x; - - if (tx < N){ - C[tx] = A[tx] * B[tx]; - } -} -// CPU implementation -void multiplyCPU(float* C, float* A, float* B, int N){ - - for(unsigned int i=0; i eps) { - errors++; - } - } - - if (errors != 0){ - printf("\nManual Test FAILED: %d errors\n", errors); - errors=0; - } else { - printf("\nManual Test PASSED!\n"); - } - - for (i = 0; i < NUM; i++) { - if (std::abs(C1[i] - cpuC[i]) > eps) { - errors++; - } - } - - if (errors != 0){ - printf("\n Automatic Test FAILED: %d errors\n", errors); - } else { - printf("\nAutomatic Test PASSED!\n"); - } - - HIP_CHECK(hipFree(Ad)); - HIP_CHECK(hipFree(Bd)); - HIP_CHECK(hipFree(C0d)); - HIP_CHECK(hipFree(C1d)); - - free(A); - free(B); - free(C0); - free(C1); - free(cpuC); - return 0; -} diff --git a/projects/hip/samples/2_Cookbook/14_gpu_arch/CMakeLists.txt b/projects/hip/samples/2_Cookbook/14_gpu_arch/CMakeLists.txt deleted file mode 100644 index 084f273096..0000000000 --- a/projects/hip/samples/2_Cookbook/14_gpu_arch/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(gpuarch) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(gpuarch gpuarch.cpp) - -# Link with HIP -target_link_libraries(gpuarch hip::host) diff --git a/projects/hip/samples/2_Cookbook/14_gpu_arch/Makefile b/projects/hip/samples/2_Cookbook/14_gpu_arch/Makefile deleted file mode 100644 index c730c10a06..0000000000 --- a/projects/hip/samples/2_Cookbook/14_gpu_arch/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif -HIPCC=$(HIP_PATH)/bin/hipcc - -EXE=./gpuarch - -.PHONY: test - -all: test - -$(EXE): gpuarch.cpp - $(HIPCC) $^ -o $@ - -test: $(EXE) - $(EXE) - -clean: - rm -f *.o $(EXE) diff --git a/projects/hip/samples/2_Cookbook/14_gpu_arch/gpuarch.cpp b/projects/hip/samples/2_Cookbook/14_gpu_arch/gpuarch.cpp deleted file mode 100644 index f1b521fcd1..0000000000 --- a/projects/hip/samples/2_Cookbook/14_gpu_arch/gpuarch.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR -IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include "hip/hip_runtime.h" -#include - -#define THREADS_PER_BLOCK 64 -#define BLOCKS_PER_GRID 4 -#define SIZE (BLOCKS_PER_GRID * THREADS_PER_BLOCK) -#define NOT_SUPPORTED -99 // dummy number indicates unsupported operation - -#define HIP_STATUS_CHECK(status) \ - if (status != hipSuccess) { \ - std::cout << "Got Status: " << status << " at Line: " << __LINE__ << std::endl; \ - exit(0); \ - } - -// Using __gfx*__ macro one can have GPU architecture specific code flow -// For example: If below kernel runs on gfx908 it will increment 'in' by 'value' and store into -// 'out' -// but it will update with "NOT_SUPPORTED" for any other gfx archs. -__global__ void incrementKernel(int32_t* in, int32_t* out, int32_t value, size_t buffSize) { - int index = blockDim.x * blockIdx.x + threadIdx.x; - if (index < buffSize) { -#if defined(__gfx908__) - out[index] = in[index] + value; -#else - out[index] = NOT_SUPPORTED; -#endif - } -} - -int main() { - int32_t incrementValue = 10; - // Device pointers - int32_t* dInput = nullptr; - int32_t* dOutput = nullptr; - - size_t NBytes = SIZE * sizeof(int32_t); - // Host pointers - int32_t* hInput = static_cast(malloc(NBytes)); - int32_t* hOutput = static_cast(malloc(NBytes)); - - HIP_STATUS_CHECK(hipMalloc(&dInput, NBytes)); - HIP_STATUS_CHECK(hipMalloc(&dOutput, NBytes)); - - // Initialize host input/output buffers - for (int i = 0; i < SIZE; ++i) { - hInput[i] = i; - hOutput[i] = 0; - } - - // Initialize device input buffer - HIP_STATUS_CHECK(hipMemcpy(dInput, hInput, NBytes, hipMemcpyHostToDevice)); - - // Launch kernel - hipLaunchKernelGGL(incrementKernel, dim3(BLOCKS_PER_GRID), dim3(THREADS_PER_BLOCK), 0, 0, dInput, - dOutput, incrementValue, SIZE); - - // Copy result back to host buffer - HIP_STATUS_CHECK(hipMemcpy(hOutput, dOutput, NBytes, hipMemcpyDeviceToHost)); - - bool flag = true; - // verify data - for (int i = 0; i < SIZE; ++i) { - if (hOutput[i] != NOT_SUPPORTED && hOutput[i] != (hInput[i] + incrementValue)) { - std::cout << "Error : Data mismatch found"; - exit(0); - } else if (hOutput[i] == NOT_SUPPORTED) { - flag &= false; - } - } - if (flag == false) { - std::cout << "Error: Kernel is supported for gfx908 architecture\n"; - } else { - std::cout << "success\n"; - } - return 0; -} diff --git a/projects/hip/samples/2_Cookbook/15_static_library/README.md b/projects/hip/samples/2_Cookbook/15_static_library/README.md deleted file mode 100644 index a38dc93451..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/README.md +++ /dev/null @@ -1,179 +0,0 @@ -# Emitting Static Library - -This sample shows how to generate a static library for a simple HIP application. We will evaluate two types of static libraries: the first type exports host functions in a static library generated with --emit-static-lib and is compatible with host linkers, and second type exports device functions in a static library made with system ar. - -Please refer to the hip_programming_guide for limitations. - -## Static libraries with host functions - -### Source files -The static library source files may contain host functions and kernel `__global__` and `__device__` functions. Here is an example (please refer to the directory host_functions). - -hipOptLibrary.cpp: -``` -#define HIP_ASSERT(status) assert(status == hipSuccess) -#define LEN 512 - -__global__ void copy(uint32_t* A, uint32_t* B) { - size_t tid = threadIdx.x + blockIdx.x * blockDim.x; - B[tid] = A[tid]; -} - -void run_test1() { - uint32_t *A_h, *B_h, *A_d, *B_d; - size_t valbytes = LEN * sizeof(uint32_t); - - A_h = (uint32_t*)malloc(valbytes); - B_h = (uint32_t*)malloc(valbytes); - for (uint32_t i = 0; i < LEN; i++) { - A_h[i] = i; - B_h[i] = 0; - } - - HIP_ASSERT(hipMalloc((void**)&A_d, valbytes)); - HIP_ASSERT(hipMalloc((void**)&B_d, valbytes)); - - HIP_ASSERT(hipMemcpy(A_d, A_h, valbytes, hipMemcpyHostToDevice)); - hipLaunchKernelGGL(copy, dim3(LEN/64), dim3(64), 0, 0, A_d, B_d); - HIP_ASSERT(hipMemcpy(B_h, B_d, valbytes, hipMemcpyDeviceToHost)); - - for (uint32_t i = 0; i < LEN; i++) { - assert(A_h[i] == B_h[i]); - } - - HIP_ASSERT(hipFree(A_d)); - HIP_ASSERT(hipFree(B_d)); - free(A_h); - free(B_h); - std::cout << "Test Passed!\n"; -} -``` - -The above source file can be compiled into a static library, libHipOptLibrary.a, using the --emit-static-lib flag, like so: -``` -hipcc hipOptLibrary.cpp --emit-static-lib -fPIC -o libHipOptLibrary.a -``` - -### Main source files -The main() program source file may link with the above static library using either hipcc or a host compiler (such as g++). A simple source file that calls the host function inside libHipOptLibrary.a: - -hipMain1.cpp: -``` -extern void run_test1(); - -int main(){ - run_test1(); -} -``` - -To link to the static library: - -Using hipcc: -``` -hipcc hipMain1.cpp -L. -lHipOptLibrary -o test_emit_static_hipcc_linker.out -``` -Using g++: -``` -ROCM_PATH is the path where ROCM is installed. default path is /opt/rocm. -g++ hipMain1.cpp -L. -lHipOptLibrary -L/hip/lib -lamdhip64 -o test_emit_static_host_linker.out -``` - -## Static libraries with device functions - -### Source files -The static library source files which contain only `__device__` functions need to be created using ar. Here is an example (please refer to the directory device_functions). - -hipDevice.cpp: -``` -#include - -__device__ int square_me(int A) { - return A*A; -} -``` - -The above source file may be compiled into a static library, libHipDevice.a, by first compiling into a relocatable object, and then placed in an archive using ar: -``` -hipcc hipDevice.cpp -c -fgpu-rdc -fPIC -o hipDevice.o -ar rcsD libHipDevice.a hipDevice.o -``` - -### Main source files -The main() program source file can link with the static library using hipcc. A simple source file that calls the device function inside libHipDevice.a: - -hipMain2.cpp: -``` -#include -#include -#include - -#define HIP_ASSERT(status) assert(status == hipSuccess) -#define LEN 512 - -extern __device__ int square_me(int); - -__global__ void square_and_save(int* A, int* B) { - int tid = threadIdx.x + blockIdx.x * blockDim.x; - B[tid] = square_me(A[tid]); -} - -void run_test2() { - int *A_h, *B_h, *A_d, *B_d; - A_h = new int[LEN]; - B_h = new int[LEN]; - for (unsigned i = 0; i < LEN; i++) { - A_h[i] = i; - B_h[i] = 0; - } - size_t valbytes = LEN*sizeof(int); - - HIP_ASSERT(hipMalloc((void**)&A_d, valbytes)); - HIP_ASSERT(hipMalloc((void**)&B_d, valbytes)); - - HIP_ASSERT(hipMemcpy(A_d, A_h, valbytes, hipMemcpyHostToDevice)); - hipLaunchKernelGGL(square_and_save, dim3(LEN/64), dim3(64), - 0, 0, A_d, B_d); - HIP_ASSERT(hipMemcpy(B_h, B_d, valbytes, hipMemcpyDeviceToHost)); - - for (unsigned i = 0; i < LEN; i++) { - assert(A_h[i]*A_h[i] == B_h[i]); - } - - HIP_ASSERT(hipFree(A_d)); - HIP_ASSERT(hipFree(B_d)); - free(A_h); - free(B_h); - std::cout << "Test Passed!\n"; -} - -int main(){ - // Run test that generates static lib with ar - run_test2(); -} -``` - -To link to the static library: -``` -hipcc libHipDevice.a hipMain2.cpp -fgpu-rdc -o test_device_static_hipcc.out -``` - -## How to build and run this sample: -Use the make command to build the static libraries, link with it, and execute it. -- Change directory to either host or device functions folder. -- To build the static library and link the main executable, use `make all`. -- To execute, run the generated executable `./test_*.out`. - -Alternatively, use these CMake commands. -``` -cd device_functions -mkdir -p build -cd build -cmake .. -make -./test_*.out -``` -It is recommended to use Visual Studio's command prompt for this sample due to requirement of MS Librarian tool - LIB.exe on windows platform. -Override CMAKE_C_COMPILER and CMAKE_CXX_COMPILER to hipcc as Visual Studio's compiler would use cl.exe as default compiler. -i.e. cmake.exe -GNinja -DCMAKE_CXX_COMPILER_ID=ROCMClang -DCMAKE_C_COMPILER_ID=ROCMClang -DCMAKE_PREFIX_PATH=%HIP_PATH% -DCMAKE_C_COMPILER=%HIP_PATH%/bin/hipcc.bat -DCMAKE_CXX_COMPILER=%HIP_PATH%/bin/hipcc.bat .. - -## For More Infomation, please refer to the HIP FAQ. diff --git a/projects/hip/samples/2_Cookbook/15_static_library/device_functions/CMakeLists.txt b/projects/hip/samples/2_Cookbook/15_static_library/device_functions/CMakeLists.txt deleted file mode 100644 index 317b7a819e..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/device_functions/CMakeLists.txt +++ /dev/null @@ -1,58 +0,0 @@ -project(static_lib) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip REQUIRED) - -# For windows, AR is MS Librarian and that is picked by Visual Studio's command prompt. -if (WIN32) - find_program(libpath NAMES lib.exe) - set (CMAKE_AR ${libpath}) -endif() - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Turn static library generation ON -option(BUILD_SHARED_LIBS "Build as a shared library" OFF) - -set(CPP_SOURCES hipDevice.cpp) - -# For windows, We need to tell cmake how to create static library. -if (WIN32) - set (CMAKE_CXX_CREATE_STATIC_LIBRARY " /out: ") -endif() - -# Generate static lib libHipDevice.a -add_library(HipDevice STATIC ${CPP_SOURCES}) - -target_compile_options(HipDevice PRIVATE -fgpu-rdc) -target_link_libraries(HipDevice PRIVATE -fgpu-rdc) -target_include_directories(HipDevice PRIVATE ${ROCM_PATH}/hsa/include) - -# Create test executable that uses libHipDevice.a -set(TEST_SOURCES ${CMAKE_SOURCE_DIR}/hipMain2.cpp) - -add_executable(test_device_static ${TEST_SOURCES}) -add_dependencies(test_device_static HipDevice) -target_compile_options(test_device_static PRIVATE -fgpu-rdc) - -# For windows, Change in a way to pass lib details -if (WIN32) - target_link_libraries(test_device_static PRIVATE -lHipDevice -L${CMAKE_BINARY_DIR}) -else() - target_link_libraries(test_device_static PRIVATE HipDevice) -endif() - -target_link_libraries(test_device_static PRIVATE -fgpu-rdc amdhip64 amd_comgr) - diff --git a/projects/hip/samples/2_Cookbook/15_static_library/device_functions/Makefile b/projects/hip/samples/2_Cookbook/15_static_library/device_functions/Makefile deleted file mode 100644 index aaf7abb3c6..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/device_functions/Makefile +++ /dev/null @@ -1,35 +0,0 @@ -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -.PHONY: test - -all: $(RDC_EXE) test - -STATIC_LIB_SRC=hipDevice.cpp -STATIC_LIB=./libHipDevice.a -STATIC_MAIN_SRC=hipMain2.cpp -RDC_EXE=./test_device_static.out - -$(STATIC_LIB): - $(HIPCC) $(STATIC_LIB_SRC) -c -fgpu-rdc -fPIC -o hipDevice.o - ar rcsD $@ hipDevice.o - -# Compiles hipMain2 with hipcc and links with libHipDevice.a which contains device function. -$(RDC_EXE): $(STATIC_LIB) - $(HIPCC) $(STATIC_LIB) $(STATIC_MAIN_SRC) -fgpu-rdc -o $@ - -test: $(RDC_EXE) - $(RDC_EXE) - -clean: - rm -f $(RDC_EXE) - rm -f $(STATIC_LIB) - rm -f *.o diff --git a/projects/hip/samples/2_Cookbook/15_static_library/device_functions/hipDevice.cpp b/projects/hip/samples/2_Cookbook/15_static_library/device_functions/hipDevice.cpp deleted file mode 100644 index ff4fe85bdb..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/device_functions/hipDevice.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * */ - -#include - -__device__ int square_me(int A) { - return A*A; -} - diff --git a/projects/hip/samples/2_Cookbook/15_static_library/device_functions/hipMain2.cpp b/projects/hip/samples/2_Cookbook/15_static_library/device_functions/hipMain2.cpp deleted file mode 100644 index a3c3f8f164..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/device_functions/hipMain2.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * */ - -#include -#include -#include - -#define HIP_ASSERT(status) assert(status == hipSuccess) -#define LEN 512 - -extern __device__ int square_me(int); - -__global__ void square_and_save(int* A, int* B) { - int tid = threadIdx.x + blockIdx.x * blockDim.x; - B[tid] = square_me(A[tid]); -} - -void run_test2() { - int *A_h, *B_h, *A_d, *B_d; - A_h = new int[LEN]; - B_h = new int[LEN]; - for (unsigned i = 0; i < LEN; i++) { - A_h[i] = i; - B_h[i] = 0; - } - size_t valbytes = LEN*sizeof(int); - - HIP_ASSERT(hipMalloc((void**)&A_d, valbytes)); - HIP_ASSERT(hipMalloc((void**)&B_d, valbytes)); - - HIP_ASSERT(hipMemcpy(A_d, A_h, valbytes, hipMemcpyHostToDevice)); - hipLaunchKernelGGL(square_and_save, dim3(LEN/64), dim3(64), - 0, 0, A_d, B_d); - HIP_ASSERT(hipMemcpy(B_h, B_d, valbytes, hipMemcpyDeviceToHost)); - - for (unsigned i = 0; i < LEN; i++) { - assert(A_h[i]*A_h[i] == B_h[i]); - } - - HIP_ASSERT(hipFree(A_d)); - HIP_ASSERT(hipFree(B_d)); - delete [] A_h; - delete [] B_h; - std::cout << "Test Passed!\n"; -} - -int main(){ - // Run test that generates static lib with ar - run_test2(); -} diff --git a/projects/hip/samples/2_Cookbook/15_static_library/host_functions/CMakeLists.txt b/projects/hip/samples/2_Cookbook/15_static_library/host_functions/CMakeLists.txt deleted file mode 100644 index 3c7c306866..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/host_functions/CMakeLists.txt +++ /dev/null @@ -1,55 +0,0 @@ -project(static_lib) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip REQUIRED) - -# For windows, AR is MS Librarian and that is pickedby Visual Studio's command prompt. -if (WIN32) - find_program(libpath NAMES lib.exe) - set (CMAKE_AR ${libpath}) -endif() - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Turn static library generation ON -option(BUILD_SHARED_LIBS "Build as a shared library" OFF) - -set(CPP_SOURCES hipOptLibrary.cpp) - -# For windows, We need to tell cmake how to create static library. -if (WIN32) - set (CMAKE_CXX_CREATE_STATIC_LIBRARY " /out: ") -endif() - -# Generate static lib libHipOptLibrary.a. -add_library(HipOptLibrary STATIC ${CPP_SOURCES}) - -# Set-up the correct flags to generate the static library. -target_link_libraries(HipOptLibrary PRIVATE --emit-static-lib) -target_include_directories(HipOptLibrary PRIVATE /opt/rocm/hsa/include) - -# Create test executable that uses libHipOptLibrary.a -set(TEST_SOURCES ${CMAKE_SOURCE_DIR}/hipMain1.cpp) - -add_executable(test_opt_static ${TEST_SOURCES}) -add_dependencies(test_opt_static HipOptLibrary) -target_link_libraries(test_opt_static PRIVATE -lHipOptLibrary -L${CMAKE_BINARY_DIR}) - -if (WIN32) - target_link_libraries(test_opt_static PRIVATE amdhip64 amd_comgr) -else() - target_link_libraries(test_opt_static PRIVATE amdhip64 amd_comgr hsa-runtime64::hsa-runtime64) -endif() - diff --git a/projects/hip/samples/2_Cookbook/15_static_library/host_functions/Makefile b/projects/hip/samples/2_Cookbook/15_static_library/host_functions/Makefile deleted file mode 100644 index e6daa41da6..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/host_functions/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc -GXX=g++ - -EMIT_STATIC_LIB_SRC=hipOptLibrary.cpp -EMIT_STATIC_LIB=./libHipOptLibrary.a -EMIT_STATIC_MAIN_SRC=hipMain1.cpp -HIPCC_EXE=./test_emit_static_hipcc_linker.out -HOST_EXE=./test_emit_static_host_linker.out - -.PHONY: test - -all: $(HIPCC_EXE) $(HOST_EXE) test - -$(EMIT_STATIC_LIB): - $(HIPCC) $(EMIT_STATIC_LIB_SRC) --emit-static-lib -fPIC -o $@ - -# Compiles hipMain1 with hipcc and links with libHipOptLibrary.a which contains host function. -$(HIPCC_EXE): $(EMIT_STATIC_LIB) - $(HIPCC) $(EMIT_STATIC_MAIN_SRC) -L. -lHipOptLibrary -o $@ - -# Compiles hipMain1 with g++ and links with libHipOptLibrary.a which contains host function. -$(HOST_EXE): $(EMIT_STATIC_LIB) - $(GXX) $(EMIT_STATIC_MAIN_SRC) -L. -lHipOptLibrary -L$(HIP_PATH)/lib -lamdhip64 -Wl,-rpath=$(HIP_PATH)/lib -o $@ - -test: $(HIPCC_EXE) $(HOST_EXE) - $(HIPCC_EXE) - $(HOST_EXE) - -clean: - rm -f $(HIPCC_EXE) - rm -f $(HOST_EXE) - rm -f $(EMIT_STATIC_LIB) - rm -f *.o diff --git a/projects/hip/samples/2_Cookbook/15_static_library/host_functions/hipMain1.cpp b/projects/hip/samples/2_Cookbook/15_static_library/host_functions/hipMain1.cpp deleted file mode 100644 index 52b7ce4169..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/host_functions/hipMain1.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * */ - -extern void run_test1(); - -int main(){ - // Run test that generates static lib with -emit-static-lib - run_test1(); -} diff --git a/projects/hip/samples/2_Cookbook/15_static_library/host_functions/hipOptLibrary.cpp b/projects/hip/samples/2_Cookbook/15_static_library/host_functions/hipOptLibrary.cpp deleted file mode 100644 index 68f54184b4..0000000000 --- a/projects/hip/samples/2_Cookbook/15_static_library/host_functions/hipOptLibrary.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * */ - -#include -#include -#include - -#define HIP_ASSERT(status) assert(status == hipSuccess) -#define LEN 512 - -__global__ void copy(uint32_t* A, uint32_t* B) { - size_t tid = threadIdx.x + blockIdx.x * blockDim.x; - B[tid] = A[tid]; -} - -void run_test1() { - uint32_t *A_h, *B_h, *A_d, *B_d; - size_t valbytes = LEN * sizeof(uint32_t); - - A_h = (uint32_t*)malloc(valbytes); - B_h = (uint32_t*)malloc(valbytes); - for (uint32_t i = 0; i < LEN; i++) { - A_h[i] = i; - B_h[i] = 0; - } - - HIP_ASSERT(hipMalloc((void**)&A_d, valbytes)); - HIP_ASSERT(hipMalloc((void**)&B_d, valbytes)); - - HIP_ASSERT(hipMemcpy(A_d, A_h, valbytes, hipMemcpyHostToDevice)); - hipLaunchKernelGGL(copy, dim3(LEN/64), dim3(64), 0, 0, A_d, B_d); - HIP_ASSERT(hipMemcpy(B_h, B_d, valbytes, hipMemcpyDeviceToHost)); - - for (uint32_t i = 0; i < LEN; i++) { - assert(A_h[i] == B_h[i]); - } - - HIP_ASSERT(hipFree(A_d)); - HIP_ASSERT(hipFree(B_d)); - free(A_h); - free(B_h); - std::cout << "Test Passed!\n"; -} diff --git a/projects/hip/samples/2_Cookbook/16_assembly_to_executable/Makefile b/projects/hip/samples/2_Cookbook/16_assembly_to_executable/Makefile deleted file mode 100644 index b82ec8fdbe..0000000000 --- a/projects/hip/samples/2_Cookbook/16_assembly_to_executable/Makefile +++ /dev/null @@ -1,82 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc -CLANG=$(HIP_PATH)/../llvm/bin/clang -LLVM_MC=$(HIP_PATH)/../llvm/bin/llvm-mc -CLANG_OFFLOAD_BUNDLER=$(HIP_PATH)/../llvm/bin/clang-offload-bundler - -SRCS=square.cpp - -# Extracting ASM code, then creating an executable with the modified asm. - -SQ_HOST_ASM=square_host.s -SQ_HOST_OBJ=square_host.o -SQ_DEVICE_HIPFB=offload_bundle.hipfb -SQ_DEVICE_OBJ=square_device.o -SQ_ASM_EXE=square_asm.out - -MCIN_OBJ_GEN=hip_obj_gen.mcin -GPU_ARCH1=gfx900 -GPU_ARCH2=gfx906 -GPU_ARCH3=gfx908 -GPU_ARCH4=gfx1010 -GPU_ARCH5=gfx1030 - -.PHONY: test - -all: src_to_asm asm_to_exec - -src_to_asm: - $(HIPCC) -c -S --cuda-host-only -target x86_64-linux-gnu -o $(SQ_HOST_ASM) $(SRCS) - $(HIPCC) -c -S --cuda-device-only --offload-arch=$(GPU_ARCH1) --offload-arch=$(GPU_ARCH2) --offload-arch=$(GPU_ARCH3) --offload-arch=$(GPU_ARCH4) --offload-arch=$(GPU_ARCH5) $(SRCS) - -# You may modify the .s assembly files before the next step -# By default, their names will be: -# square-hip-amdgcn-amd-amdhsa-gfx900.s -# square-hip-amdgcn-amd-amdhsa-gfx906.s -# square-hip-amdgcn-amd-amdhsa-gfx908.s -# square-hip-amdgcn-amd-amdhsa-gfx1010.s -# square-hip-amdgcn-amd-amdhsa-gfx1030.s -# -# Note: hipcc does not work to convert .s to .o, use clang instead. - -asm_to_exec: - $(HIPCC) -c $(SQ_HOST_ASM) -o $(SQ_HOST_OBJ) - $(CLANG) -target amdgcn-amd-amdhsa -mcpu=$(GPU_ARCH1) square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH1).s -o square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH1).o - $(CLANG) -target amdgcn-amd-amdhsa -mcpu=$(GPU_ARCH2) square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH2).s -o square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH2).o - $(CLANG) -target amdgcn-amd-amdhsa -mcpu=$(GPU_ARCH3) square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH3).s -o square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH3).o - $(CLANG) -target amdgcn-amd-amdhsa -mcpu=$(GPU_ARCH4) square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH4).s -o square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH4).o - $(CLANG) -target amdgcn-amd-amdhsa -mcpu=$(GPU_ARCH5) square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH5).s -o square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH5).o - $(CLANG_OFFLOAD_BUNDLER) -type=o -bundle-align=4096 -targets=host-x86_64-unknown-linux,hip-amdgcn-amd-amdhsa-$(GPU_ARCH1),hip-amdgcn-amd-amdhsa-$(GPU_ARCH2),hip-amdgcn-amd-amdhsa-$(GPU_ARCH3),hip-amdgcn-amd-amdhsa-$(GPU_ARCH4),hip-amdgcn-amd-amdhsa-$(GPU_ARCH5) -inputs=/dev/null,square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH1).o,square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH2).o,square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH3).o,square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH4).o,square-hip-amdgcn-amd-amdhsa-$(GPU_ARCH5).o -outputs=$(SQ_DEVICE_HIPFB) - $(LLVM_MC) $(MCIN_OBJ_GEN) -o $(SQ_DEVICE_OBJ) --filetype=obj - $(HIPCC) $(SQ_HOST_OBJ) $(SQ_DEVICE_OBJ) -o $(SQ_ASM_EXE) - -clean: - rm -f *.o *.out *.hipfb *.s *.ll *.bc - diff --git a/projects/hip/samples/2_Cookbook/16_assembly_to_executable/README.md b/projects/hip/samples/2_Cookbook/16_assembly_to_executable/README.md deleted file mode 100644 index 6a2ce15a10..0000000000 --- a/projects/hip/samples/2_Cookbook/16_assembly_to_executable/README.md +++ /dev/null @@ -1,53 +0,0 @@ -ROCM_PATH is the path where ROCM is installed. default path is /opt/rocm. -# Compile to assembly and create an executable from modified asm - -This sample shows how to generate the assembly code for a simple HIP source application, then re-compiling it and generating a valid HIP executable. - -This sample uses a previous HIP application sample, please see [0_Intro/square](https://github.com/ROCm-Developer-Tools/HIP/blob/master/samples/0_Intro/square). - -## Compiling the HIP source into assembly -Using HIP flags `-c -S` will help generate the host x86_64 and the device AMDGCN assembly code when paired with `--cuda-host-only` and `--cuda-device-only` respectively. In this sample we use these commands: -``` -/hip/bin/hipcc -c -S --cuda-host-only -target x86_64-linux-gnu -o square_host.s square.cpp -/hip/bin/hipcc -c -S --cuda-device-only --offload-arch=gfx900 --offload-arch=gfx906 square.cpp -``` - -The device assembly will be output into two separate files: -- square-hip-amdgcn-amd-amdhsa-gfx900.s -- square-hip-amdgcn-amd-amdhsa-gfx906.s - -You may modify `--offload-arch` flag to build other archs and choose to enable or disable xnack and sram-ecc. - -**Note:** At this point, you may evaluate the assembly code, and make modifications if you are familiar with the AMDGCN assembly language and architecture. - -## Compiling the assembly into a valid HIP executable -If valid, the modified host and device assembly may be compiled into a HIP executable. The host assembly can be compiled into an object using this command: -``` -/hip/bin/hipcc -c square_host.s -o square_host.o -``` - -However, the device assembly code will require a few extra steps. The device assemblies needs to be compiled into device objects, then offload-bundled into a HIP fat binary using the clang-offload-bundler, then llvm-mc embeds the binary inside of a host object using the MC directives provided in `hip_obj_gen.mcin`. The output is a host object with an embedded device object. Here are the steps for device side compilation into an object: -``` -/hip/../llvm/bin/clang -target amdgcn-amd-amdhsa -mcpu=gfx900 square-hip-amdgcn-amd-amdhsa-gfx900.s -o square-hip-amdgcn-amd-amdhsa-gfx900.o -/hip/../llvm/bin/clang -target amdgcn-amd-amdhsa -mcpu=gfx906 square-hip-amdgcn-amd-amdhsa-gfx906.s -o square-hip-amdgcn-amd-amdhsa-gfx906.o -/llvm/bin/clang-offload-bundler -type=o -bundle-align=4096 -targets=host-x86_64-unknown-linux,hip-amdgcn-amd-amdhsa-gfx900,hip-amdgcn-amd-amdhsa-gfx906 -inputs=/dev/null,square-hip-amdgcn-amd-amdhsa-gfx900.o,square-hip-amdgcn-amd-amdhsa-gfx906.o -outputs=offload_bundle.hipfb -/llvm/bin/llvm-mc -triple x86_64-unknown-linux-gnu hip_obj_gen.mcin -o square_device.o --filetype=obj -``` - -**Note:** Using option `-bundle-align=4096` only works on ROCm 4.0 and newer compilers. Also, the architecture must match the same arch as when compiling to assembly. - -Finally, using the system linker, hipcc, or clang, link the host and device objects into an executable: -``` -/hip/bin/hipcc square_host.o square_device.o -o square_asm.out -``` -If you haven't modified the GPU archs, this executable should run on both `gfx900` and `gfx906`. - -## How to build and run this sample: -Use these make commands to compile into assembly, compile assembly into executable, and execute it. -- To compile the HIP application into host and device assembly: `make src_to_asm`. -- To compile the assembly files into an executable: `make asm_to_exec`. -- To execute, run `./square_asm.out`. - -**Note:** The default arch is `gfx900` and `gfx906`, this can be modified with make argument `GPU_ARCH1` and `GPU_ARCH2`. - -## For More Information, please refer to the HIP FAQ. diff --git a/projects/hip/samples/2_Cookbook/16_assembly_to_executable/hip_obj_gen.mcin b/projects/hip/samples/2_Cookbook/16_assembly_to_executable/hip_obj_gen.mcin deleted file mode 100644 index 4551e5a1c4..0000000000 --- a/projects/hip/samples/2_Cookbook/16_assembly_to_executable/hip_obj_gen.mcin +++ /dev/null @@ -1,20 +0,0 @@ -# HIP Object Generator -# Use this generator to create a host bundled object file -# with the input of an offload bundled fat binary. -# -# Input: Bundled Object file .hipfb file -# Output: Host Bundled Object File .o -# -# Add MC directives to embed target binaries. We ensure that each -# section and image is 4096-byte aligned. This facilitates faster -# loading of device binaries. It has been verified this align does -# not cause significant overall file size increase. -# -# Note: log 2 of 4096 is 12. -# - .type __hip_fatbin,@object - .section .hip_fatbin,"a",@progbits - .globl __hip_fatbin - .p2align 12 -__hip_fatbin: - .incbin "offload_bundle.hipfb" diff --git a/projects/hip/samples/2_Cookbook/16_assembly_to_executable/square.cpp b/projects/hip/samples/2_Cookbook/16_assembly_to_executable/square.cpp deleted file mode 100644 index a04bf625ca..0000000000 --- a/projects/hip/samples/2_Cookbook/16_assembly_to_executable/square.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include -#include - -#define CHECK(cmd) \ -{\ - hipError_t error = cmd;\ - if (error != hipSuccess) { \ - fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), error,__FILE__, __LINE__); \ - exit(EXIT_FAILURE);\ - }\ -} - -/* This kernel is a placeholder for the kernel in assembly generated by this - * sample. It will be replaced by the kernel in assembly. - * - * Square each element in the array A and write to array C. - */ -template -__global__ void -vector_square(T *C_d, T *A_d, size_t N) -{ - size_t offset = (blockIdx.x * blockDim.x + threadIdx.x); - size_t stride = blockDim.x * gridDim.x ; - - for (size_t i=offset; i>> (C_d, A_d, N); - - printf ("info: copy Device2Host\n"); - CHECK ( hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost)); - - printf ("info: check result\n"); - for (size_t i=0; i/hip/bin/hipcc -c -emit-llvm --cuda-host-only -target x86_64-linux-gnu -o square_host.bc square.cpp -/hip/bin/hipcc -c -emit-llvm --cuda-device-only --offload-arch=gfx900 --offload-arch=gfx906 square.cpp -``` -The device LLVM IR bitcode will be output into two separate files: -- square-hip-amdgcn-amd-amdhsa-gfx900.bc -- square-hip-amdgcn-amd-amdhsa-gfx906.bc - -You may modify `--offload-arch` flag to build other archs and choose to enable or disable xnack and sram-ecc. - -To transform the LLVM bitcode into human readable LLVM IR, use these commands: -``` -/llvm/bin/llvm-dis square-hip-amdgcn-amd-amdhsa-gfx900.bc -o square-hip-amdgcn-amd-amdhsa-gfx900.ll -/llvm/bin/llvm-dis square-hip-amdgcn-amd-amdhsa-gfx906.bc -o square-hip-amdgcn-amd-amdhsa-gfx906.ll -``` - -**Warning:** We cannot ensure any compiler besides the ROCm hipcc and clang will be compatible with this process. Also, there is no guarantee that the starting IR produced with `-x cl` will run with HIP runtime. Experimenting with other compilers or starting IR will be the responsibility of the developer. - -## Modifying the LLVM IR -***Warning: The LLVM Language Specification may change across LLVM major releases, therefore the user must make sure the modified LLVM IR conforms to the LLVM Language Specification corresponding to the used LLVM version.*** - -At this point, you may evaluate the LLVM IR and make modifications if you are familiar with the LLVM IR language. Since the LLVM IR can vary between compiler versions, the safest approach would be to use the same compiler to consume the IR as the compiler producing it. It is the responsibility of the developer to ensure the IR is valid when manually modifying it. - -## Compiling the LLVM IR into a valid HIP executable -If valid, the modified host and device IR may be compiled into a HIP executable. First, the readable IR must be compiled back in LLVM bitcode. The host IR can be compiled into an object using this command: -``` -/llvm/bin/llvm-as square_host.ll -o square_host.bc -/hip/bin/hipcc -c square_host.bc -o square_host.o -``` - -However, the device IR will require a few extra steps. The device bitcodes needs to be compiled into device objects, then offload-bundled into a HIP fat binary using the clang-offload-bundler, then llvm-mc embeds the binary inside of a host object using the MC directives provided in `hip_obj_gen.mcin`. The output is a host object with an embedded device object. Here are the steps for device side compilation into an object: -``` -/hip/../llvm/bin/llvm-as square-hip-amdgcn-amd-amdhsa-gfx900.ll -o square-hip-amdgcn-amd-amdhsa-gfx900.bc -/hip/../llvm/bin/llvm-as square-hip-amdgcn-amd-amdhsa-gfx906.ll -o square-hip-amdgcn-amd-amdhsa-gfx906.bc -/hip/../llvm/bin/clang -target amdgcn-amd-amdhsa -mcpu=gfx900 square-hip-amdgcn-amd-amdhsa-gfx900.bc -o square-hip-amdgcn-amd-amdhsa-gfx900.o -/hip/../llvm/bin/clang -target amdgcn-amd-amdhsa -mcpu=gfx906 square-hip-amdgcn-amd-amdhsa-gfx906.bc -o square-hip-amdgcn-amd-amdhsa-gfx906.o -/hip/../llvm/bin/clang-offload-bundler -type=o -bundle-align=4096 -targets=host-x86_64-unknown-linux,hip-amdgcn-amd-amdhsa-gfx900,hip-amdgcn-amd-amdhsa-gfx906 -inputs=/dev/null,square-hip-amdgcn-amd-amdhsa-gfx900.o,square-hip-amdgcn-amd-amdhsa-gfx906.o -outputs=offload_bundle.hipfb -/llvm/bin/llvm-mc hip_obj_gen.mcin -o square_device.o --filetype=obj -``` - -**Note:** Using option `-bundle-align=4096` only works on ROCm 4.0 and newer compilers. Also, the architecture must match the same arch as when compiling to LLVM IR. - -Finally, using the system linker, hipcc, or clang, link the host and device objects into an executable: -``` -/hip/bin/hipcc square_host.o square_device.o -o square_ir.out -``` -If you haven't modified the GPU archs, this executable should run on both `gfx900` and `gfx906`. - -## How to build and run this sample: -Use these make commands to compile into LLVM IR, compile IR into executable, and execute it. -- To compile the HIP application into host and device LLVM IR: `make src_to_ir`. -- To disassembly the LLVM IR bitcode into human readable LLVM IR: `make bc_to_ll`. -- To assembly the human readable LLVM IR bitcode back into LLVM IR bitcode: `make ll_to_bc`. -- To compile the LLVM IR files into an executable: `make ir_to_exec`. -- To execute, run `./square_ir.out`. - -**Note:** The default arch is `gfx900` and `gfx906`, this can be modified with make argument `GPU_ARCH1` and `GPU_ARCH2`. - -## For More Information, please refer to the HIP FAQ. diff --git a/projects/hip/samples/2_Cookbook/17_llvm_ir_to_executable/hip_obj_gen.mcin b/projects/hip/samples/2_Cookbook/17_llvm_ir_to_executable/hip_obj_gen.mcin deleted file mode 100644 index 4551e5a1c4..0000000000 --- a/projects/hip/samples/2_Cookbook/17_llvm_ir_to_executable/hip_obj_gen.mcin +++ /dev/null @@ -1,20 +0,0 @@ -# HIP Object Generator -# Use this generator to create a host bundled object file -# with the input of an offload bundled fat binary. -# -# Input: Bundled Object file .hipfb file -# Output: Host Bundled Object File .o -# -# Add MC directives to embed target binaries. We ensure that each -# section and image is 4096-byte aligned. This facilitates faster -# loading of device binaries. It has been verified this align does -# not cause significant overall file size increase. -# -# Note: log 2 of 4096 is 12. -# - .type __hip_fatbin,@object - .section .hip_fatbin,"a",@progbits - .globl __hip_fatbin - .p2align 12 -__hip_fatbin: - .incbin "offload_bundle.hipfb" diff --git a/projects/hip/samples/2_Cookbook/17_llvm_ir_to_executable/square.cpp b/projects/hip/samples/2_Cookbook/17_llvm_ir_to_executable/square.cpp deleted file mode 100644 index 7ffc8d0916..0000000000 --- a/projects/hip/samples/2_Cookbook/17_llvm_ir_to_executable/square.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include -#include - -#define CHECK(cmd) \ -{\ - hipError_t error = cmd;\ - if (error != hipSuccess) { \ - fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), error,__FILE__, __LINE__); \ - exit(EXIT_FAILURE);\ - }\ -} - -/* This kernel is a placeholder for the kernel in LLVM IR generated by this - * sample. It will be replaced by the kernel in LLVM IR. - * - * Square each element in the array A and write to array C. - */ -template -__global__ void -vector_square(T *C_d, T *A_d, size_t N) -{ - size_t offset = (blockIdx.x * blockDim.x + threadIdx.x); - size_t stride = blockDim.x * gridDim.x ; - - for (size_t i=offset; i>> (C_d, A_d, N); - - printf ("info: copy Device2Host\n"); - CHECK ( hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost)); - - printf ("info: check result\n"); - for (size_t i=0; i -#include - -#define CHECK(cmd) \ -{\ - hipError_t error = cmd;\ - if (error != hipSuccess) { \ - fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), error,__FILE__, __LINE__); \ - exit(EXIT_FAILURE);\ - }\ -} - - -/* - * Square each element in the array A and write to array C. - */ -template -__global__ void -vector_square(T *C_d, T *A_d, size_t N) -{ - size_t offset = (blockIdx.x * blockDim.x + threadIdx.x); - size_t stride = blockDim.x * gridDim.x ; - - for (size_t i=offset; i - -// hip header file -#include "hip/hip_runtime.h" - - -#define WIDTH 1024 - - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - out[y * width + x] = in[x * width + y]; -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix, - gpuMatrix, WIDTH); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/19_cmake_lang/README.md b/projects/hip/samples/2_Cookbook/19_cmake_lang/README.md deleted file mode 100644 index 5ba5ef98e8..0000000000 --- a/projects/hip/samples/2_Cookbook/19_cmake_lang/README.md +++ /dev/null @@ -1,20 +0,0 @@ -### This will test cmake lang support: CXX and Fortran -I. Prepare -1) You must install cmake version 3.18 or above to support LINK_LANGUAGE. - Otherwise, Fortran build will fail. - To download the latest cmake, see https://cmake.org/download/. -2) If there is no Fortran on your system, you must install it via, - sudo apt install gfortran - -II. Build -mkdir -p build; cd build -rm -rf *; CXX=`hipconfig -l`/clang++ FC=$(which gfortran) cmake .. -make - -III. Test -# ./test_fortran - Succeeded testing Fortran! - -# ./test_cpp -Device name Device 66a7 -PASSED! diff --git a/projects/hip/samples/2_Cookbook/19_cmake_lang/TestFortran.F90 b/projects/hip/samples/2_Cookbook/19_cmake_lang/TestFortran.F90 deleted file mode 100644 index 14f29f7270..0000000000 --- a/projects/hip/samples/2_Cookbook/19_cmake_lang/TestFortran.F90 +++ /dev/null @@ -1,3 +0,0 @@ - program fortran_test_program - print *, "Succeeded testing Fortran!" - end program \ No newline at end of file diff --git a/projects/hip/samples/2_Cookbook/1_hipEvent/CMakeLists.txt b/projects/hip/samples/2_Cookbook/1_hipEvent/CMakeLists.txt deleted file mode 100644 index 9ac1aba1ca..0000000000 --- a/projects/hip/samples/2_Cookbook/1_hipEvent/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(hipEvent) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(hipEvent hipEvent.cpp) - -# Link with HIP -target_link_libraries(hipEvent hip::host) diff --git a/projects/hip/samples/2_Cookbook/1_hipEvent/Makefile b/projects/hip/samples/2_Cookbook/1_hipEvent/Makefile deleted file mode 100644 index 01655bde5b..0000000000 --- a/projects/hip/samples/2_Cookbook/1_hipEvent/Makefile +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = hipEvent.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./hipEvent - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o - diff --git a/projects/hip/samples/2_Cookbook/1_hipEvent/Readme.md b/projects/hip/samples/2_Cookbook/1_hipEvent/Readme.md deleted file mode 100644 index 2bd389e25e..0000000000 --- a/projects/hip/samples/2_Cookbook/1_hipEvent/Readme.md +++ /dev/null @@ -1,80 +0,0 @@ -## Using hipEvents to measure performance ### - -This tutorial is follow-up of the previous one where we learn how to write our first hip program, in which we compute Matrix Transpose. In this tutorial, we'll explain how to use the hipEvent to get the performance score for memory transfer and kernel execution time. - -## Introduction: - -Memory transfer and kernel execution are the most important parameter in parallel computing (specially HPC and machine learning). Memory bottlenecks is the main problem why we are not able to get the highest performance, therefore obtaining the memory transfer timing and kernel execution timing plays key role in application optimization. - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -We will be using the Simple Matrix Transpose application from the previous tutorial and modify it to learn how to get the performance score for memory transfer and kernel execution time. - -## hipEvent_t - -We'll learn how to use the event management functionality of HIP runtime api. In the same sourcecode, we used for MatrixTranspose we will declare the following events as follows: - -``` - hipEvent_t start, stop; -``` - -We'll create the event with the help of following code: - -``` - hipEventCreate(&start); - hipEventCreate(&stop); -``` - -We'll use the "eventMs" variable to store the time taken value: -` float eventMs = 1.0f;` - -## Time taken measurement by using hipEvents: - -We'll start the timer by calling: -` hipEventRecord(start, NULL);` -in this, the first parameter is the hipEvent_t, will will mark the start of the time from which the measurement has to be performed, while the second parameter has to be of the type hipStream_t. In current situation, we have passed NULL (the default stream). We will learn about the `hipStream_t` in more detail latter. - -Now, we'll have the operation for which we need to compute the time taken. For the case of memory transfer, we'll place the `hipMemcpy`: -` hipMemcpy(gpuMatrix, Matrix, NUM*sizeof(float), hipMemcpyHostToDevice);` - -and for kernel execution time we'll use `hipKernelLaunch`: -``` -hipLaunchKernelGGL(matrixTranspose, - dim3(WIDTH/THREADS_PER_BLOCK_X, HEIGHT/THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), - 0, 0, - gpuTransposeMatrix , gpuMatrix, WIDTH ,HEIGHT); -``` - -Now to mark the end of the eventRecord, we will again use the hipEventRecord by passing the stop event: -` hipEventRecord(stop, NULL);` - -Will synchronize the event with the help of: -` hipEventSynchronize(stop);` - -In order to calculate the time taken by measuring the difference of occurance marked by the start and stop event, we'll use: -` hipEventElapsedTime(&eventMs, start, stop);` -Here the first parameter will store the time taken value, second parameter is the starting marker for the event while the third one is marking the end. - -We can print the value of time take comfortably since eventMs is float variable. - -## How to build and run: -Use the make command and execute it using ./exe -Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia. - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/1_hipEvent/hipEvent.cpp b/projects/hip/samples/2_Cookbook/1_hipEvent/hipEvent.cpp deleted file mode 100644 index 81013c1dd1..0000000000 --- a/projects/hip/samples/2_Cookbook/1_hipEvent/hipEvent.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - -#define WIDTH 1024 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - out[y * width + x] = in[x * width + y]; -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - float eventMs = 1.0f; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Record the start event - hipEventRecord(start, NULL); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - - hipEventElapsedTime(&eventMs, start, stop); - - printf("hipMemcpyHostToDevice time taken = %6.3fms\n", eventMs); - - // Record the start event - hipEventRecord(start, NULL); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix, - gpuMatrix, WIDTH); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - - hipEventElapsedTime(&eventMs, start, stop); - - printf("kernel Execution time = %6.3fms\n", eventMs); - - // Record the start event - hipEventRecord(start, NULL); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - - hipEventElapsedTime(&eventMs, start, stop); - - printf("hipMemcpyDeviceToHost time taken = %6.3fms\n", eventMs); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/CMakeLists.txt b/projects/hip/samples/2_Cookbook/20_hip_vulkan/CMakeLists.txt deleted file mode 100644 index 288c47c3d2..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/CMakeLists.txt +++ /dev/null @@ -1,97 +0,0 @@ - -# Copyright (c) 2020 - 2022 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -# hipcc.bat fails to qualify as a valid compiler for CMAKE_CXX_COMPILER_ID = ROCMClang -# so the simple compiler test is skipped and forced to use hipcc.bat as compiler -set(CMAKE_C_COMPILER_WORKS 1) -set(CMAKE_CXX_COMPILER_WORKS 1) -set(CMAKE_CXX_STANDARD 14) -project(hipVulkan) - -cmake_minimum_required(VERSION 3.10) -set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake;${CMAKE_MODULE_PATH}") - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# need to set rocm_path for windows -# since clang and hip are two different folders during build/install step -if (WIN32 AND HIPINFO_INTERNAL_BUILD) - set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --rocm-path=${HIP_PATH}") -endif() - - - -# Find hip -find_package(hip REQUIRED) -if (WIN32) -find_package(GLFW3) -if(NOT GLFW_FOUND) - if(EXISTS "${GLFW_PATH}") - message(STATUS "FOUND GLFW SDK: ${GLFW_PATH}") - elseif (EXISTS "$ENV{GLFW_PATH}") - message(STATUS "FOUND GLFW SDK: $ENV{GLFW_PATH}") - set(GLFW_PATH $ENV{GLFW_PATH}) - else() - message("Error: Unable to locate GLFW SDK. please specify GLFW_PATH") - return() - endif() -endif() -endif(WIN32) -find_package(Vulkan) -if(NOT Vulkan_FOUND) - if(EXISTS "${VULKAN_PATH}") - message(STATUS "Vulkan SDK: ${VULKAN_PATH}") - elseif (EXISTS "$ENV{VULKAN_SDK}") - message(STATUS "FOUND VULKAN SDK: $ENV{VULKAN_SDK}") - set(VULKAN_PATH $ENV{VULKAN_SDK}) - else() - message("Error: Unable to locate Vulkan SDK. please specify VULKAN_PATH") - return() - endif() -endif() -set(VULKAN_PATH ${Vulkan_INCLUDE_DIRS}) -STRING(REGEX REPLACE "/[Ii]nclude" "" VULKAN_PATH ${VULKAN_PATH}) -# Include Vulkan header files from Vulkan SDK -include_directories(AFTER ${VULKAN_PATH}/include) -link_directories(${VULKAN_PATH}/bin;${VULKAN_PATH}/lib;) -link_directories(${GLFW_PATH}/lib-vc2019) -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(hipVulkan VulkanBaseApp.cpp VulkanBaseApp.h main.cpp SineWaveSimulation.cpp SineWaveSimulation.h linmath.h) -include_directories(${HIP_PATH}/include) -include_directories(${GLFW_PATH}/include) - -# Link with HIP -if (WIN32) - target_link_libraries(hipVulkan advapi32 hip::host vulkan-1 glfw3dll) -else (WIN32) - target_link_libraries(hipVulkan hip::host vulkan glfw) -endif (WIN32) - diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.cpp b/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.cpp deleted file mode 100644 index 41adae8065..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of NVIDIA CORPORATION nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * Modifications Copyright (C)2021 Advanced - * Micro Devices, Inc. All rights reserved. - */ - -#include "SineWaveSimulation.h" -#include -//#include -#include "hip/hip_runtime.h" - - -__global__ void sinewave(float *heightMap, unsigned int width, unsigned int height, float time) -{ - const float freq = 4.0f; - const size_t stride = gridDim.x * blockDim.x; - - // Iterate through the entire array in a way that is - // independent of the grid configuration - for (size_t tid = blockIdx.x * blockDim.x + threadIdx.x; tid < width * height; tid += stride) { - // Calculate the x, y coordinates - const size_t y = tid / width; - const size_t x = tid - y * width; - // Normalize x, y to [0,1] - const float u = ((2.0f * x) / width) - 1.0f; - const float v = ((2.0f * y) / height) - 1.0f; - // Calculate the new height value - const float w = 0.5f * sinf(u * freq + time) * cosf(v * freq + time); - // Store this new height value - heightMap[tid] = w; - } -} - -SineWaveSimulation::SineWaveSimulation(size_t width, size_t height) - : m_heightMap(nullptr), m_width(width), m_height(height) -{ -} - -void SineWaveSimulation::initCudaLaunchConfig(int device) -{ - hipDeviceProp_t prop = {}; - checkHIPErrors(hipSetDevice(device)); - checkHIPErrors(hipGetDeviceProperties(&prop, device)); - - // We don't need large block sizes, since there's not much inter-thread communication - m_threads = prop.warpSize; - - // Use the occupancy calculator and fill the gpu as best as we can - checkHIPErrors(hipOccupancyMaxActiveBlocksPerMultiprocessor(&m_blocks, sinewave, prop.warpSize, 0)); - m_blocks *= prop.multiProcessorCount; - - // Go ahead and the clamp the blocks to the minimum needed for this height/width - m_blocks = std::min(m_blocks, (int)((m_width * m_height + m_threads - 1) / m_threads)); -} - -int SineWaveSimulation::initCuda(uint8_t *vkDeviceUUID, size_t UUID_SIZE) -{ - int current_device = 0; - int device_count = 0; - int devices_prohibited = 0; - - hipDeviceProp_t deviceProp; - checkHIPErrors(hipGetDeviceCount(&device_count)); - - if (device_count == 0) { - fprintf(stderr, "CUDA error: no devices supporting CUDA.\n"); - exit(EXIT_FAILURE); - } - - // Find the GPU which is selected by Vulkan - while (current_device < device_count) { - hipGetDeviceProperties(&deviceProp, current_device); - - if ((deviceProp.computeMode != hipComputeModeProhibited)) { - // Compare the cuda device UUID with vulkan UUID - // FIXME - int ret = 0; // memcmp((void*)&deviceProp.uuid, vkDeviceUUID, UUID_SIZE); - if (ret == 0) - { - checkHIPErrors(hipSetDevice(current_device)); - checkHIPErrors(hipGetDeviceProperties(&deviceProp, current_device)); - printf("GPU Device %d: \"%s\" with compute capability %d.%d\n\n", - current_device, deviceProp.name, deviceProp.major, - deviceProp.minor); - - return current_device; - } - - } else { - devices_prohibited++; - } - - current_device++; - } - - if (devices_prohibited == device_count) { - fprintf(stderr, - "HIP error:" - " No Vulkan-HIP Interop capable GPU found.\n"); - exit(EXIT_FAILURE); - } - - return -1; -} - -SineWaveSimulation::~SineWaveSimulation() -{ - m_heightMap = NULL; -} - -void SineWaveSimulation::initSimulation(float *heights) -{ - m_heightMap = heights; -} - -void SineWaveSimulation::stepSimulation(float time, hipStream_t stream) -{ - hipLaunchKernelGGL(sinewave, dim3(m_blocks), dim3(m_threads), 0, stream , m_heightMap, m_width, m_height, time); - getLastHIPError("Failed to launch CUDA simulation"); - //hipStreamSynchronize(stream); -} diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.h b/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.h deleted file mode 100644 index 9126cb3e14..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.h +++ /dev/null @@ -1,101 +0,0 @@ -/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of NVIDIA CORPORATION nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * Modifications Copyright (C)2021 Advanced - * Micro Devices, Inc. All rights reserved. - */ - -#pragma once -#ifndef __SINESIM_H__ -#define __SINESIM_H__ - -#include -#include -#include -#include "linmath.h" - -class SineWaveSimulation -{ - float *m_heightMap; - size_t m_width, m_height; - int m_blocks, m_threads; -public: - SineWaveSimulation(size_t width, size_t height); - ~SineWaveSimulation(); - void initSimulation(float *heightMap); - void stepSimulation(float time, hipStream_t stream = 0); - void initCudaLaunchConfig(int device); - int initCuda(uint8_t *vkDeviceUUID, size_t UUID_SIZE); - - size_t getWidth() const { - return m_width; - } - size_t getHeight() const { - return m_height; - } -}; - -template -void check(T result, char const* const func, const char* const file, - int const line) { - if (result) { - fprintf(stderr, "HIP error at %s:%d code=%d \"%s\" \n", file, line, static_cast(result), func); - // static_cast(result), _cudaGetErrorEnum(result), func); - exit(EXIT_FAILURE); - } -} - -// This will output the proper CUDA error strings in the event -// that a CUDA host call returns an error -#define checkHIPErrors(val) check((val), #val, __FILE__, __LINE__) - -// This will output the proper error string when calling cudaGetLastError -#define getLastHIPError(msg) __getLastHIPError(msg, __FILE__, __LINE__) - -inline void __getLastHIPError(const char* errorMessage, const char* file, - const int line) { - hipError_t err = hipGetLastError(); - - if (hipSuccess != err) { - fprintf(stderr, - "%s(%i) : getLastHIPError() HIP error :" - " %s : (%d) %s.\n", - file, line, errorMessage, static_cast(err), - hipGetErrorString(err)); - exit(EXIT_FAILURE); - } - -} - - - -#ifndef MAX -#define MAX(a, b) (a > b ? a : b) -#endif - -#endif // __SINESIM_H__ diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.hip b/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.hip deleted file mode 100644 index 41adae8065..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/SineWaveSimulation.hip +++ /dev/null @@ -1,147 +0,0 @@ -/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of NVIDIA CORPORATION nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * Modifications Copyright (C)2021 Advanced - * Micro Devices, Inc. All rights reserved. - */ - -#include "SineWaveSimulation.h" -#include -//#include -#include "hip/hip_runtime.h" - - -__global__ void sinewave(float *heightMap, unsigned int width, unsigned int height, float time) -{ - const float freq = 4.0f; - const size_t stride = gridDim.x * blockDim.x; - - // Iterate through the entire array in a way that is - // independent of the grid configuration - for (size_t tid = blockIdx.x * blockDim.x + threadIdx.x; tid < width * height; tid += stride) { - // Calculate the x, y coordinates - const size_t y = tid / width; - const size_t x = tid - y * width; - // Normalize x, y to [0,1] - const float u = ((2.0f * x) / width) - 1.0f; - const float v = ((2.0f * y) / height) - 1.0f; - // Calculate the new height value - const float w = 0.5f * sinf(u * freq + time) * cosf(v * freq + time); - // Store this new height value - heightMap[tid] = w; - } -} - -SineWaveSimulation::SineWaveSimulation(size_t width, size_t height) - : m_heightMap(nullptr), m_width(width), m_height(height) -{ -} - -void SineWaveSimulation::initCudaLaunchConfig(int device) -{ - hipDeviceProp_t prop = {}; - checkHIPErrors(hipSetDevice(device)); - checkHIPErrors(hipGetDeviceProperties(&prop, device)); - - // We don't need large block sizes, since there's not much inter-thread communication - m_threads = prop.warpSize; - - // Use the occupancy calculator and fill the gpu as best as we can - checkHIPErrors(hipOccupancyMaxActiveBlocksPerMultiprocessor(&m_blocks, sinewave, prop.warpSize, 0)); - m_blocks *= prop.multiProcessorCount; - - // Go ahead and the clamp the blocks to the minimum needed for this height/width - m_blocks = std::min(m_blocks, (int)((m_width * m_height + m_threads - 1) / m_threads)); -} - -int SineWaveSimulation::initCuda(uint8_t *vkDeviceUUID, size_t UUID_SIZE) -{ - int current_device = 0; - int device_count = 0; - int devices_prohibited = 0; - - hipDeviceProp_t deviceProp; - checkHIPErrors(hipGetDeviceCount(&device_count)); - - if (device_count == 0) { - fprintf(stderr, "CUDA error: no devices supporting CUDA.\n"); - exit(EXIT_FAILURE); - } - - // Find the GPU which is selected by Vulkan - while (current_device < device_count) { - hipGetDeviceProperties(&deviceProp, current_device); - - if ((deviceProp.computeMode != hipComputeModeProhibited)) { - // Compare the cuda device UUID with vulkan UUID - // FIXME - int ret = 0; // memcmp((void*)&deviceProp.uuid, vkDeviceUUID, UUID_SIZE); - if (ret == 0) - { - checkHIPErrors(hipSetDevice(current_device)); - checkHIPErrors(hipGetDeviceProperties(&deviceProp, current_device)); - printf("GPU Device %d: \"%s\" with compute capability %d.%d\n\n", - current_device, deviceProp.name, deviceProp.major, - deviceProp.minor); - - return current_device; - } - - } else { - devices_prohibited++; - } - - current_device++; - } - - if (devices_prohibited == device_count) { - fprintf(stderr, - "HIP error:" - " No Vulkan-HIP Interop capable GPU found.\n"); - exit(EXIT_FAILURE); - } - - return -1; -} - -SineWaveSimulation::~SineWaveSimulation() -{ - m_heightMap = NULL; -} - -void SineWaveSimulation::initSimulation(float *heights) -{ - m_heightMap = heights; -} - -void SineWaveSimulation::stepSimulation(float time, hipStream_t stream) -{ - hipLaunchKernelGGL(sinewave, dim3(m_blocks), dim3(m_threads), 0, stream , m_heightMap, m_width, m_height, time); - getLastHIPError("Failed to launch CUDA simulation"); - //hipStreamSynchronize(stream); -} diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/VulkanBaseApp.cpp b/projects/hip/samples/2_Cookbook/20_hip_vulkan/VulkanBaseApp.cpp deleted file mode 100644 index deb86adeb8..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/VulkanBaseApp.cpp +++ /dev/null @@ -1,1724 +0,0 @@ -/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of NVIDIA CORPORATION nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This file contains basic cross-platform setup paths in working with Vulkan - * and rendering window. It is largely based off of tutorials provided here: - * https://vulkan-tutorial.com/ -*/ - -/* - * Modifications Copyright (C)2021 Advanced - * Micro Devices, Inc. All rights reserved. - */ - -#include -#include -#include -#include -#include -#include -#include - -#include "VulkanBaseApp.h" - -#define GLFW_INCLUDE_VULKAN -#define GLM_FORCE_DEPTH_ZERO_TO_ONE -#include - -#ifdef _WIN64 -#include -#include -#include -#endif /* _WIN64 */ - -#ifndef countof -#define countof(x) (sizeof(x) / sizeof(*(x))) -#endif - -static const char *validationLayers[] = { "VK_LAYER_KHRONOS_validation" }; -static const size_t MAX_FRAMES_IN_FLIGHT = 5; - -void VulkanBaseApp::resizeCallback(GLFWwindow *window, int width, int height) -{ - VulkanBaseApp *app = reinterpret_cast(glfwGetWindowUserPointer(window)); - app->m_framebufferResized = true; -} - -static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, void *pUserData) -{ - std::cerr << "validation layer: " << pCallbackData->pMessage << std::endl; - - return VK_FALSE; -} - -VulkanBaseApp::VulkanBaseApp(const std::string& appName, bool enableValidation) : - m_appName(appName), - m_enableValidation(enableValidation), - m_instance(VK_NULL_HANDLE), - m_window(nullptr), - m_debugMessenger(VK_NULL_HANDLE), - m_surface(VK_NULL_HANDLE), - m_physicalDevice(VK_NULL_HANDLE), - m_device(VK_NULL_HANDLE), - m_graphicsQueue(VK_NULL_HANDLE), - m_presentQueue(VK_NULL_HANDLE), - m_swapChain(VK_NULL_HANDLE), - m_vkDeviceUUID(), - m_swapChainImages(), - m_swapChainFormat(), - m_swapChainExtent(), - m_swapChainImageViews(), - m_shaderFiles(), - m_renderPass(), - m_pipelineLayout(VK_NULL_HANDLE), - m_graphicsPipeline(VK_NULL_HANDLE), - m_swapChainFramebuffers(), - m_commandPool(VK_NULL_HANDLE), - m_commandBuffers(), - m_imageAvailableSemaphores(), - m_renderFinishedSemaphores(), - m_inFlightFences(), - m_uniformBuffers(), - m_uniformMemory(), - m_descriptorSetLayout(VK_NULL_HANDLE), - m_descriptorPool(VK_NULL_HANDLE), - m_descriptorSets(), - m_depthImage(VK_NULL_HANDLE), - m_depthImageMemory(VK_NULL_HANDLE), - m_depthImageView(VK_NULL_HANDLE), - m_currentFrame(0), - m_framebufferResized(false) -{ -} - -VkExternalSemaphoreHandleTypeFlagBits VulkanBaseApp::getDefaultSemaphoreHandleType() -{ -#ifdef _WIN64 - return IsWindows8OrGreater() ? - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT : - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT; -#else - return VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT; -#endif -} - -VkExternalMemoryHandleTypeFlagBits VulkanBaseApp::getDefaultMemHandleType() -{ -#ifdef _WIN64 - return IsWindows8Point1OrGreater() ? - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT : - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT; -#else - return VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT; -#endif -} - -VulkanBaseApp::~VulkanBaseApp() -{ - cleanupSwapChain(); - - if (m_descriptorSetLayout != VK_NULL_HANDLE) { - vkDestroyDescriptorSetLayout(m_device, m_descriptorSetLayout, nullptr); - } - - for (size_t i = 0; i < m_renderFinishedSemaphores.size(); i++) { - vkDestroySemaphore(m_device, m_renderFinishedSemaphores[i], nullptr); - vkDestroySemaphore(m_device, m_imageAvailableSemaphores[i], nullptr); - vkDestroyFence(m_device, m_inFlightFences[i], nullptr); - } - if (m_commandPool != VK_NULL_HANDLE) { - vkDestroyCommandPool(m_device, m_commandPool, nullptr); - } - - if (m_device != VK_NULL_HANDLE) { - vkDestroyDevice(m_device, nullptr); - } - - if (m_enableValidation) { - PFN_vkDestroyDebugUtilsMessengerEXT func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(m_instance, "vkDestroyDebugUtilsMessengerEXT"); - if (func != nullptr) { - func(m_instance, m_debugMessenger, nullptr); - } - } - - if (m_surface != VK_NULL_HANDLE) { - vkDestroySurfaceKHR(m_instance, m_surface, nullptr); - } - - if (m_instance != VK_NULL_HANDLE) { - vkDestroyInstance(m_instance, nullptr); - } - - if (m_window) { - glfwDestroyWindow(m_window); - } - - glfwTerminate(); -} - -void VulkanBaseApp::init() -{ - initWindow(); - initVulkan(); -} - -VkCommandBuffer VulkanBaseApp::beginSingleTimeCommands() -{ - VkCommandBufferAllocateInfo allocInfo = {}; - allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - allocInfo.commandPool = m_commandPool; - allocInfo.commandBufferCount = 1; - - VkCommandBuffer commandBuffer; - vkAllocateCommandBuffers(m_device, &allocInfo, &commandBuffer); - - VkCommandBufferBeginInfo beginInfo = {}; - beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - - vkBeginCommandBuffer(commandBuffer, &beginInfo); - - return commandBuffer; -} - -void VulkanBaseApp::endSingleTimeCommands(VkCommandBuffer commandBuffer) -{ - vkEndCommandBuffer(commandBuffer); - - VkSubmitInfo submitInfo = {}; - submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &commandBuffer; - - vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); - vkQueueWaitIdle(m_graphicsQueue); - - vkFreeCommandBuffers(m_device, m_commandPool, 1, &commandBuffer); -} - -void VulkanBaseApp::initWindow() -{ - glfwInit(); - - glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); - - m_window = glfwCreateWindow(1280, 800, m_appName.c_str(), nullptr, nullptr); - glfwSetWindowUserPointer(m_window, this); - glfwSetFramebufferSizeCallback(m_window, resizeCallback); -} - - -std::vector VulkanBaseApp::getRequiredExtensions() const -{ - return std::vector(); -} - -std::vector VulkanBaseApp::getRequiredDeviceExtensions() const -{ - return std::vector(); -} - -void VulkanBaseApp::initVulkan() -{ - createInstance(); - createSurface(); - createDevice(); - createSwapChain(); - createImageViews(); - createRenderPass(); - createDescriptorSetLayout(); - createGraphicsPipeline(); - createCommandPool(); - createDepthResources(); - createFramebuffers(); - initVulkanApp(); - createUniformBuffers(); - createDescriptorPool(); - createDescriptorSets(); - createCommandBuffers(); - createSyncObjects(); -} - -#ifdef _WIN64 -class WindowsSecurityAttributes -{ -protected: - SECURITY_ATTRIBUTES m_winSecurityAttributes; - PSECURITY_DESCRIPTOR m_winPSecurityDescriptor; - -public: - WindowsSecurityAttributes(); - SECURITY_ATTRIBUTES *operator&(); - ~WindowsSecurityAttributes(); -}; - -WindowsSecurityAttributes::WindowsSecurityAttributes() -{ - m_winPSecurityDescriptor = (PSECURITY_DESCRIPTOR)calloc(1, SECURITY_DESCRIPTOR_MIN_LENGTH + 2 * sizeof(void **)); - if (!m_winPSecurityDescriptor) { - throw std::runtime_error("Failed to allocate memory for security descriptor"); - } - - PSID *ppSID = (PSID *)((PBYTE)m_winPSecurityDescriptor + SECURITY_DESCRIPTOR_MIN_LENGTH); - PACL *ppACL = (PACL *)((PBYTE)ppSID + sizeof(PSID *)); - - InitializeSecurityDescriptor(m_winPSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION); - - SID_IDENTIFIER_AUTHORITY sidIdentifierAuthority = SECURITY_WORLD_SID_AUTHORITY; - AllocateAndInitializeSid(&sidIdentifierAuthority, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, ppSID); - - EXPLICIT_ACCESS explicitAccess; - ZeroMemory(&explicitAccess, sizeof(EXPLICIT_ACCESS)); - explicitAccess.grfAccessPermissions = STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL; - explicitAccess.grfAccessMode = SET_ACCESS; - explicitAccess.grfInheritance = INHERIT_ONLY; - explicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID; - explicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; - explicitAccess.Trustee.ptstrName = (LPTSTR) * ppSID; - - SetEntriesInAcl(1, &explicitAccess, NULL, ppACL); - - SetSecurityDescriptorDacl(m_winPSecurityDescriptor, TRUE, *ppACL, FALSE); - - m_winSecurityAttributes.nLength = sizeof(m_winSecurityAttributes); - m_winSecurityAttributes.lpSecurityDescriptor = m_winPSecurityDescriptor; - m_winSecurityAttributes.bInheritHandle = TRUE; -} - -SECURITY_ATTRIBUTES * -WindowsSecurityAttributes::operator&() -{ - return &m_winSecurityAttributes; -} - -WindowsSecurityAttributes::~WindowsSecurityAttributes() -{ - PSID *ppSID = (PSID *)((PBYTE)m_winPSecurityDescriptor + SECURITY_DESCRIPTOR_MIN_LENGTH); - PACL *ppACL = (PACL *)((PBYTE)ppSID + sizeof(PSID *)); - - if (*ppSID) { - FreeSid(*ppSID); - } - if (*ppACL) { - LocalFree(*ppACL); - } - free(m_winPSecurityDescriptor); -} -#endif /* _WIN64 */ - - -static VkFormat findSupportedFormat(VkPhysicalDevice physicalDevice, const std::vector& candidates, VkImageTiling tiling, VkFormatFeatureFlags features) -{ - for (VkFormat format : candidates) { - VkFormatProperties props; - vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props); - if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features) { - return format; - } - else if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features) { - return format; - } - } - throw std::runtime_error("Failed to find supported format!"); -} - -static uint32_t findMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties) -{ - VkPhysicalDeviceMemoryProperties memProperties; - vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); - for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { - if (typeFilter & (1 << i) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { - return i; - } - } - return ~0; -} - -static bool supportsValidationLayers() -{ - std::vector availableLayers; - uint32_t layerCount; - - vkEnumerateInstanceLayerProperties(&layerCount, nullptr); - availableLayers.resize(layerCount); - vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); - - for (const char * layerName : validationLayers) { - bool layerFound = false; - - for (const auto & layerProperties : availableLayers) { - if (strcmp(layerName, layerProperties.layerName) == 0) { - layerFound = true; - break; - } - } - - if (!layerFound) { - return false; - } - } - - return true; -} - -void VulkanBaseApp::createInstance() -{ - if (m_enableValidation && !supportsValidationLayers()) { - throw std::runtime_error("Validation requested, but not supported!"); - } - - VkApplicationInfo appInfo = {}; - appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; - appInfo.pApplicationName = m_appName.c_str(); - appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); - appInfo.pEngineName = "No Engine"; - appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); - appInfo.apiVersion = VK_API_VERSION_1_0; - - VkInstanceCreateInfo createInfo = {}; - createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; - createInfo.pApplicationInfo = &appInfo; - - std::vector exts = getRequiredExtensions(); - - { - uint32_t glfwExtensionCount = 0; - const char **glfwExtensions; - - glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); - - exts.insert(exts.begin(), glfwExtensions, glfwExtensions + glfwExtensionCount); - - if (m_enableValidation) { - exts.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); - } - } - - createInfo.enabledExtensionCount = static_cast(exts.size()); - createInfo.ppEnabledExtensionNames = exts.data(); - VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo = {}; - if (m_enableValidation) { - createInfo.enabledLayerCount = static_cast(countof(validationLayers)); - createInfo.ppEnabledLayerNames = validationLayers; - - debugCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; - debugCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; - debugCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; - debugCreateInfo.pfnUserCallback = debugCallback; - - createInfo.pNext = &debugCreateInfo; - } - else { - createInfo.enabledLayerCount = 0; - createInfo.pNext = nullptr; - } - - if (vkCreateInstance(&createInfo, nullptr, &m_instance) != VK_SUCCESS) { - throw std::runtime_error("Failed to create Vulkan instance!"); - } - - if (m_enableValidation) { - PFN_vkCreateDebugUtilsMessengerEXT func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(m_instance, "vkCreateDebugUtilsMessengerEXT"); - if (func == nullptr || func(m_instance, &debugCreateInfo, nullptr, &m_debugMessenger) != VK_SUCCESS) { - throw std::runtime_error("Failed to set up debug messenger!"); - } - } -} - -void VulkanBaseApp::createSurface() -{ - if (glfwCreateWindowSurface(m_instance, m_window, nullptr, &m_surface) != VK_SUCCESS) { - throw std::runtime_error("failed to create window surface!"); - } -} - -static bool findGraphicsQueueIndicies(VkPhysicalDevice device, VkSurfaceKHR surface, uint32_t& graphicsFamily, uint32_t& presentFamily) -{ - uint32_t queueFamilyCount = 0; - - vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr); - - std::vector queueFamilies(queueFamilyCount); - vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data()); - - graphicsFamily = presentFamily = ~0; - - for (uint32_t i = 0; i < queueFamilyCount; i++) { - - if (queueFamilies[i].queueCount > 0) { - if (graphicsFamily == ~0 && queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { - graphicsFamily = i; - } - uint32_t presentSupport = 0; - vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport); - if (presentFamily == ~0 && presentSupport) { - presentFamily = i; - } - if (presentFamily != ~0 && graphicsFamily != ~0) { - break; - } - } - } - - return graphicsFamily != ~0 && presentFamily != ~0; -} - -static bool hasAllExtensions(VkPhysicalDevice device, const std::vector& deviceExtensions) -{ - uint32_t extensionCount; - vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); - std::vector availableExtensions(extensionCount); - vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data()); - - std::set requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); - - for (const auto & extension : availableExtensions) { - requiredExtensions.erase(extension.extensionName); - } - - return requiredExtensions.empty(); -} - -static void getSwapChainProperties(VkPhysicalDevice device, VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR& capabilities, std::vector& formats, std::vector& presentModes) -{ - vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &capabilities); - uint32_t formatCount; - vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); - if (formatCount != 0) { - formats.resize(formatCount); - vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, formats.data()); - } - uint32_t presentModeCount; - vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); - if (presentModeCount != 0) { - presentModes.resize(presentModeCount); - vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, presentModes.data()); - } -} - -bool VulkanBaseApp::isSuitableDevice(VkPhysicalDevice dev) const -{ - uint32_t graphicsQueueIndex, presentQueueIndex; - std::vector deviceExtensions = getRequiredDeviceExtensions(); - VkSurfaceCapabilitiesKHR caps; - std::vector formats; - std::vector presentModes; - deviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); - getSwapChainProperties(dev, m_surface, caps, formats, presentModes); - return hasAllExtensions(dev, deviceExtensions) - && !formats.empty() && !presentModes.empty() - && findGraphicsQueueIndicies(dev, m_surface, graphicsQueueIndex, presentQueueIndex); -} - -void VulkanBaseApp::createDevice() -{ - { - uint32_t deviceCount = 0; - vkEnumeratePhysicalDevices(m_instance, &deviceCount, nullptr); - if (deviceCount == 0) { - throw std::runtime_error("Failed to find Vulkan capable GPUs!"); - } - std::vector phyDevs(deviceCount); - vkEnumeratePhysicalDevices(m_instance, &deviceCount, phyDevs.data()); - std::vector::iterator it = std::find_if(phyDevs.begin(), phyDevs.end(), - std::bind(&VulkanBaseApp::isSuitableDevice, this, std::placeholders::_1)); - if (it == phyDevs.end()) { - throw std::runtime_error("No suitable device found!"); - } - m_physicalDevice = *it; - } - - uint32_t graphicsQueueIndex, presentQueueIndex; - findGraphicsQueueIndicies(m_physicalDevice, m_surface, graphicsQueueIndex, presentQueueIndex); - - std::vector queueCreateInfos; - std::set uniqueFamilyIndices = { graphicsQueueIndex, presentQueueIndex }; - - float queuePriority = 1.0f; - - for (uint32_t queueFamily : uniqueFamilyIndices) { - VkDeviceQueueCreateInfo queueCreateInfo = {}; - queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; - queueCreateInfo.queueFamilyIndex = graphicsQueueIndex; - queueCreateInfo.queueCount = 1; - queueCreateInfo.pQueuePriorities = &queuePriority; - queueCreateInfos.push_back(queueCreateInfo); - } - - VkPhysicalDeviceFeatures deviceFeatures = {}; - deviceFeatures.fillModeNonSolid = true; - - VkDeviceCreateInfo createInfo = {}; - createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; - - createInfo.pQueueCreateInfos = queueCreateInfos.data(); - createInfo.queueCreateInfoCount = static_cast(queueCreateInfos.size()); - - createInfo.pEnabledFeatures = &deviceFeatures; - - std::vector deviceExtensions = getRequiredDeviceExtensions(); - deviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); - - createInfo.enabledExtensionCount = static_cast(deviceExtensions.size()); - createInfo.ppEnabledExtensionNames = deviceExtensions.data(); - - if (m_enableValidation) { - createInfo.enabledLayerCount = static_cast(countof(validationLayers)); - createInfo.ppEnabledLayerNames = validationLayers; - } - else { - createInfo.enabledLayerCount = 0; - } - VkResult asdf = vkCreateDevice(m_physicalDevice, &createInfo, nullptr, &m_device); - if (asdf != VK_SUCCESS) { - throw std::runtime_error("failed to create logical device!"); - } - - vkGetDeviceQueue(m_device, graphicsQueueIndex, 0, &m_graphicsQueue); - vkGetDeviceQueue(m_device, presentQueueIndex, 0, &m_presentQueue); - - VkPhysicalDeviceIDProperties vkPhysicalDeviceIDProperties = {}; - vkPhysicalDeviceIDProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES; - vkPhysicalDeviceIDProperties.pNext = NULL; - - VkPhysicalDeviceProperties2 vkPhysicalDeviceProperties2 = {}; - vkPhysicalDeviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; - vkPhysicalDeviceProperties2.pNext = &vkPhysicalDeviceIDProperties; - - PFN_vkGetPhysicalDeviceProperties2 fpGetPhysicalDeviceProperties2; - fpGetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2)vkGetInstanceProcAddr(m_instance, "vkGetPhysicalDeviceProperties2"); - if (fpGetPhysicalDeviceProperties2 == NULL) { - throw std::runtime_error("Vulkan: Proc address for \"vkGetPhysicalDeviceProperties2KHR\" not found.\n"); - } - - //fpGetPhysicalDeviceProperties2(m_physicalDevice, &vkPhysicalDeviceProperties2); - - memcpy(m_vkDeviceUUID, vkPhysicalDeviceIDProperties.deviceUUID, VK_UUID_SIZE); -} - -static VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector& availableFormats) -{ - if (availableFormats.size() == 1 && availableFormats[0].format == VK_FORMAT_UNDEFINED) { - return { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }; - } - - for (const auto & availableFormat : availableFormats) { - if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { - return availableFormat; - } - } - - return availableFormats[0]; -} - -static VkPresentModeKHR chooseSwapPresentMode(const std::vector& availablePresentModes) -{ - VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR; - - for (const auto & availablePresentMode : availablePresentModes) { - if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { - return availablePresentMode; - } - else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) { - bestMode = availablePresentMode; - } - } - - return bestMode; -} - -static VkExtent2D chooseSwapExtent(GLFWwindow *window, const VkSurfaceCapabilitiesKHR& capabilities) -{ - if (capabilities.currentExtent.width != std::numeric_limits::max()) { - return capabilities.currentExtent; - } - else { - int width, height; - glfwGetFramebufferSize(window, &width, &height); - VkExtent2D actualExtent = { static_cast(width), static_cast(height) }; - - actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); - actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); - - return actualExtent; - } -} - -void VulkanBaseApp::createSwapChain() -{ - VkSurfaceCapabilitiesKHR capabilities; - VkSurfaceFormatKHR format; - VkPresentModeKHR presentMode; - VkExtent2D extent; - uint32_t imageCount; - - { - std::vector formats; - std::vector presentModes; - - getSwapChainProperties(m_physicalDevice, m_surface, capabilities, formats, presentModes); - format = chooseSwapSurfaceFormat(formats); - presentMode = chooseSwapPresentMode(presentModes); - extent = chooseSwapExtent(m_window, capabilities); - imageCount = capabilities.minImageCount + 1; - if (capabilities.maxImageCount > 0 && imageCount > capabilities.maxImageCount) { - imageCount = capabilities.maxImageCount; - } - } - - VkSwapchainCreateInfoKHR createInfo = {}; - createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; - createInfo.surface = m_surface; - - createInfo.minImageCount = imageCount; - createInfo.imageFormat = format.format; - createInfo.imageColorSpace = format.colorSpace; - createInfo.imageExtent = extent; - createInfo.imageArrayLayers = 1; - createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - - uint32_t queueFamilyIndices[2]; - findGraphicsQueueIndicies(m_physicalDevice, m_surface, queueFamilyIndices[0], queueFamilyIndices[1]); - - if (queueFamilyIndices[0] != queueFamilyIndices[1]) { - createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; - createInfo.queueFamilyIndexCount = countof(queueFamilyIndices); - createInfo.pQueueFamilyIndices = queueFamilyIndices; - } - else { - createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; - } - - createInfo.preTransform = capabilities.currentTransform; - createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; - createInfo.presentMode = presentMode; - createInfo.clipped = VK_TRUE; - - createInfo.oldSwapchain = VK_NULL_HANDLE; - - if (vkCreateSwapchainKHR(m_device, &createInfo, nullptr, &m_swapChain) != VK_SUCCESS) { - throw std::runtime_error("failed to create swap chain!"); - } - - vkGetSwapchainImagesKHR(m_device, m_swapChain, &imageCount, nullptr); - m_swapChainImages.resize(imageCount); - vkGetSwapchainImagesKHR(m_device, m_swapChain, &imageCount, m_swapChainImages.data()); - - m_swapChainFormat = format.format; - m_swapChainExtent = extent; -} - -static VkImageView createImageView(VkDevice dev, VkImage image, VkFormat format, VkImageAspectFlags aspectFlags) -{ - VkImageView imageView; - VkImageViewCreateInfo createInfo = {}; - createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - createInfo.image = image; - createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; - createInfo.format = format; - createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; - createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; - createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; - createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; - createInfo.subresourceRange.aspectMask = aspectFlags; - createInfo.subresourceRange.baseMipLevel = 0; - createInfo.subresourceRange.levelCount = 1; - createInfo.subresourceRange.baseArrayLayer = 0; - createInfo.subresourceRange.layerCount = 1; - if (vkCreateImageView(dev, &createInfo, nullptr, &imageView) != VK_SUCCESS) { - throw std::runtime_error("Failed to create image views!"); - } - - return imageView; -} - -static void createImage(VkPhysicalDevice physicalDevice, VkDevice device, uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory) -{ - VkImageCreateInfo imageInfo = {}; - imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - imageInfo.imageType = VK_IMAGE_TYPE_2D; - imageInfo.extent.width = width; - imageInfo.extent.height = height; - imageInfo.extent.depth = 1; - imageInfo.mipLevels = 1; - imageInfo.arrayLayers = 1; - imageInfo.format = format; - imageInfo.tiling = tiling; - imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - imageInfo.usage = usage; - imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; - imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - - if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS) { - throw std::runtime_error("failed to create image!"); - } - - VkMemoryRequirements memRequirements; - vkGetImageMemoryRequirements(device, image, &memRequirements); - - VkMemoryAllocateInfo allocInfo = {}; - allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - allocInfo.allocationSize = memRequirements.size; - allocInfo.memoryTypeIndex = findMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties); - - if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS) { - throw std::runtime_error("failed to allocate image memory!"); - } - - vkBindImageMemory(device, image, imageMemory, 0); -} - -void VulkanBaseApp::createImageViews() -{ - m_swapChainImageViews.resize(m_swapChainImages.size()); - - for (uint32_t i = 0; i < m_swapChainImages.size(); i++) { - m_swapChainImageViews[i] = createImageView(m_device, m_swapChainImages[i], m_swapChainFormat, VK_IMAGE_ASPECT_COLOR_BIT); - } -} - -void VulkanBaseApp::createRenderPass() -{ - VkAttachmentDescription colorAttachment = {}; - colorAttachment.format = m_swapChainFormat; - colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; - colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - - VkAttachmentReference colorAttachmentRef = {}; - colorAttachmentRef.attachment = 0; - colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - - VkAttachmentDescription depthAttachment = {}; - depthAttachment.format = findSupportedFormat(m_physicalDevice, - { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT }, - VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT); - depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT; - depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - - VkAttachmentReference depthAttachmentRef = {}; - depthAttachmentRef.attachment = 1; - depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - - VkSubpassDescription subpass = {}; - subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpass.colorAttachmentCount = 1; - subpass.pColorAttachments = &colorAttachmentRef; - subpass.pDepthStencilAttachment = &depthAttachmentRef; - - - VkSubpassDependency dependency = {}; - dependency.srcSubpass = VK_SUBPASS_EXTERNAL; - dependency.dstSubpass = 0; - dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependency.srcAccessMask = 0; - dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - - VkAttachmentDescription attachments[] = {colorAttachment, depthAttachment}; - VkRenderPassCreateInfo renderPassInfo = {}; - renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; - renderPassInfo.attachmentCount = countof(attachments); - renderPassInfo.pAttachments = attachments; - renderPassInfo.subpassCount = 1; - renderPassInfo.pSubpasses = &subpass; - renderPassInfo.dependencyCount = 1; - renderPassInfo.pDependencies = &dependency; - - if (vkCreateRenderPass(m_device, &renderPassInfo, nullptr, &m_renderPass) != VK_SUCCESS) { - throw std::runtime_error("failed to create render pass!"); - } -} - -void VulkanBaseApp::createDescriptorSetLayout() -{ - VkDescriptorSetLayoutBinding uboLayoutBinding = {}; - uboLayoutBinding.binding = 0; - uboLayoutBinding.descriptorCount = 1; - uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; - uboLayoutBinding.pImmutableSamplers = nullptr; - uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; - - VkDescriptorSetLayoutCreateInfo layoutInfo = {}; - layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - layoutInfo.bindingCount = 1; - layoutInfo.pBindings = &uboLayoutBinding; - - if (vkCreateDescriptorSetLayout(m_device, &layoutInfo, nullptr, &m_descriptorSetLayout) != VK_SUCCESS) { - throw std::runtime_error("failed to create descriptor set layout!"); - } -} - -VkShaderModule createShaderModule(VkDevice device, const char *filename) -{ - std::vector shaderContents; - std::ifstream shaderFile(filename, std::ios_base::in | std::ios_base::binary); - VkShaderModuleCreateInfo createInfo = {}; - VkShaderModule shaderModule; - - if (!shaderFile.good()) { - throw std::runtime_error("Failed to load shader contents"); - } - readFile(shaderFile, shaderContents); - - createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - createInfo.codeSize = shaderContents.size(); - createInfo.pCode = reinterpret_cast(shaderContents.data()); - VkResult asdf = vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule); - if ( asdf != VK_SUCCESS) { - throw std::runtime_error("Failed to create shader module!"); - } - - return shaderModule; -} - -void VulkanBaseApp::getVertexDescriptions(std::vector& bindingDesc, std::vector& attribDesc) -{ -} - -void VulkanBaseApp::getAssemblyStateInfo(VkPipelineInputAssemblyStateCreateInfo& info) -{ - -} - -void VulkanBaseApp::createGraphicsPipeline() -{ - std::vector shaderStageInfos(m_shaderFiles.size()); - for (size_t i = 0; i < m_shaderFiles.size(); i++) { - shaderStageInfos[i] = {}; - shaderStageInfos[i].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStageInfos[i].stage = m_shaderFiles[i].first; - shaderStageInfos[i].module = createShaderModule(m_device, m_shaderFiles[i].second.c_str()); - shaderStageInfos[i].pName = "main"; - } - - VkPipelineVertexInputStateCreateInfo vertexInputInfo = {}; - - std::vector vertexBindingDescriptions; - std::vector vertexAttributeDescriptions; - - getVertexDescriptions(vertexBindingDescriptions, vertexAttributeDescriptions); - - vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - vertexInputInfo.vertexBindingDescriptionCount = static_cast(vertexBindingDescriptions.size()); - vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); - vertexInputInfo.vertexAttributeDescriptionCount = static_cast(vertexAttributeDescriptions.size()); - vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); - - VkPipelineInputAssemblyStateCreateInfo inputAssembly = {}; - getAssemblyStateInfo(inputAssembly); - - VkViewport viewport = {}; - viewport.x = 0.0f; - viewport.y = 0.0f; - viewport.width = (float)m_swapChainExtent.width; - viewport.height = (float)m_swapChainExtent.height; - viewport.minDepth = 0.0f; - viewport.maxDepth = 1.0f; - - VkRect2D scissor = {}; - scissor.offset = { 0, 0 }; - scissor.extent = m_swapChainExtent; - - VkPipelineViewportStateCreateInfo viewportState = {}; - viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; - viewportState.viewportCount = 1; - viewportState.pViewports = &viewport; - viewportState.scissorCount = 1; - viewportState.pScissors = &scissor; - - VkPipelineRasterizationStateCreateInfo rasterizer = {}; - rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; - rasterizer.depthClampEnable = VK_FALSE; - rasterizer.rasterizerDiscardEnable = VK_FALSE; - rasterizer.polygonMode = VK_POLYGON_MODE_LINE; - rasterizer.lineWidth = 1.0f; - rasterizer.cullMode = VK_CULL_MODE_NONE; - rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; - rasterizer.depthBiasEnable = VK_FALSE; - - VkPipelineMultisampleStateCreateInfo multisampling = {}; - multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - multisampling.sampleShadingEnable = VK_FALSE; - multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - multisampling.minSampleShading = 1.0f; // Optional - multisampling.pSampleMask = nullptr; // Optional - multisampling.alphaToCoverageEnable = VK_FALSE; // Optional - multisampling.alphaToOneEnable = VK_FALSE; // Optional - - VkPipelineDepthStencilStateCreateInfo depthStencil = {}; - depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; - depthStencil.depthTestEnable = VK_TRUE; - depthStencil.depthWriteEnable = VK_TRUE; - depthStencil.depthCompareOp = VK_COMPARE_OP_LESS; - depthStencil.depthBoundsTestEnable = VK_FALSE; - depthStencil.stencilTestEnable = VK_FALSE; - - VkPipelineColorBlendAttachmentState colorBlendAttachment = {}; - colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; - colorBlendAttachment.blendEnable = VK_FALSE; - - VkPipelineColorBlendStateCreateInfo colorBlending = {}; - colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - colorBlending.logicOpEnable = VK_FALSE; - colorBlending.logicOp = VK_LOGIC_OP_COPY; - colorBlending.attachmentCount = 1; - colorBlending.pAttachments = &colorBlendAttachment; - colorBlending.blendConstants[0] = 0.0f; - colorBlending.blendConstants[1] = 0.0f; - colorBlending.blendConstants[2] = 0.0f; - colorBlending.blendConstants[3] = 0.0f; - - VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; - pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - pipelineLayoutInfo.setLayoutCount = 1; // Optional - pipelineLayoutInfo.pSetLayouts = &m_descriptorSetLayout; // Optional - pipelineLayoutInfo.pushConstantRangeCount = 0; // Optional - pipelineLayoutInfo.pPushConstantRanges = nullptr; // Optional - - if (vkCreatePipelineLayout(m_device, &pipelineLayoutInfo, nullptr, &m_pipelineLayout) != VK_SUCCESS) { - throw std::runtime_error("failed to create pipeline layout!"); - } - - VkGraphicsPipelineCreateInfo pipelineInfo = {}; - pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - pipelineInfo.stageCount = static_cast(shaderStageInfos.size()); - pipelineInfo.pStages = shaderStageInfos.data(); - - pipelineInfo.pVertexInputState = &vertexInputInfo; - pipelineInfo.pInputAssemblyState = &inputAssembly; - pipelineInfo.pViewportState = &viewportState; - pipelineInfo.pRasterizationState = &rasterizer; - pipelineInfo.pMultisampleState = &multisampling; - pipelineInfo.pDepthStencilState = &depthStencil; // Optional - pipelineInfo.pColorBlendState = &colorBlending; - pipelineInfo.pDynamicState = nullptr; // Optional - - pipelineInfo.layout = m_pipelineLayout; - - pipelineInfo.renderPass = m_renderPass; - pipelineInfo.subpass = 0; - - pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // Optional - pipelineInfo.basePipelineIndex = -1; // Optional - - if (vkCreateGraphicsPipelines(m_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &m_graphicsPipeline) != VK_SUCCESS) { - throw std::runtime_error("failed to create graphics pipeline!"); - } - - for (size_t i = 0; i < shaderStageInfos.size(); i++) { - vkDestroyShaderModule(m_device, shaderStageInfos[i].module, nullptr); - } -} - -void VulkanBaseApp::createFramebuffers() -{ - m_swapChainFramebuffers.resize(m_swapChainImageViews.size()); - for (size_t i = 0; i < m_swapChainImageViews.size(); i++) { - VkImageView attachments[] = { - m_swapChainImageViews[i], - m_depthImageView - }; - - VkFramebufferCreateInfo framebufferInfo = {}; - framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; - framebufferInfo.renderPass = m_renderPass; - framebufferInfo.attachmentCount = countof(attachments); - framebufferInfo.pAttachments = attachments; - framebufferInfo.width = m_swapChainExtent.width; - framebufferInfo.height = m_swapChainExtent.height; - framebufferInfo.layers = 1; - - if (vkCreateFramebuffer(m_device, &framebufferInfo, nullptr, &m_swapChainFramebuffers[i]) != VK_SUCCESS) { - throw std::runtime_error("failed to create framebuffer!"); - } - } -} - -void VulkanBaseApp::createCommandPool() -{ - VkCommandPoolCreateInfo poolInfo = {}; - uint32_t graphicsIndex, presentIndex; - - findGraphicsQueueIndicies(m_physicalDevice, m_surface, graphicsIndex, presentIndex); - - poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; - poolInfo.queueFamilyIndex = graphicsIndex; - poolInfo.flags = 0; // Optional - - if (vkCreateCommandPool(m_device, &poolInfo, nullptr, &m_commandPool) != VK_SUCCESS) { - throw std::runtime_error("Failed to create command pool!"); - } -} - -static void transitionImageLayout(VulkanBaseApp *app, VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout) -{ - VkCommandBuffer commandBuffer = app->beginSingleTimeCommands(); - - VkImageMemoryBarrier barrier = {}; - barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barrier.oldLayout = oldLayout; - barrier.newLayout = newLayout; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = image; - - if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { - barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; - - if (format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT) { - barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; - } - } - else { - barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - } - - barrier.subresourceRange.baseMipLevel = 0; - barrier.subresourceRange.levelCount = 1; - barrier.subresourceRange.baseArrayLayer = 0; - barrier.subresourceRange.layerCount = 1; - - VkPipelineStageFlags sourceStage; - VkPipelineStageFlags destinationStage; - - if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { - barrier.srcAccessMask = 0; - barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - - sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT; - } - else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - - sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT; - destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - } - else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { - barrier.srcAccessMask = 0; - barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - - sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; - } - else { - throw std::invalid_argument("unsupported layout transition!"); - } - - vkCmdPipelineBarrier( - commandBuffer, - sourceStage, destinationStage, - 0, - 0, nullptr, - 0, nullptr, - 1, &barrier - ); - - app->endSingleTimeCommands(commandBuffer); -} - -void VulkanBaseApp::createDepthResources() -{ - VkFormat depthFormat = findSupportedFormat(m_physicalDevice, - { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT }, - VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT); - createImage(m_physicalDevice, m_device, m_swapChainExtent.width, m_swapChainExtent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, m_depthImage, m_depthImageMemory); - m_depthImageView = createImageView(m_device, m_depthImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT); - transitionImageLayout(this, m_depthImage, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); -} - -void VulkanBaseApp::createUniformBuffers() -{ - VkDeviceSize size = getUniformSize(); - if (size > 0) { - m_uniformBuffers.resize(m_swapChainImages.size()); - m_uniformMemory.resize(m_swapChainImages.size()); - for (size_t i = 0; i < m_uniformBuffers.size(); i++) { - createBuffer(getUniformSize(), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - m_uniformBuffers[i], m_uniformMemory[i]); - } - } -} - -void VulkanBaseApp::createDescriptorPool() -{ - VkDescriptorPoolSize poolSize = {}; - poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; - poolSize.descriptorCount = static_cast(m_swapChainImages.size()); - VkDescriptorPoolCreateInfo poolInfo = {}; - poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; - poolInfo.poolSizeCount = 1; - poolInfo.pPoolSizes = &poolSize; - poolInfo.maxSets = static_cast(m_swapChainImages.size());; - if (vkCreateDescriptorPool(m_device, &poolInfo, nullptr, &m_descriptorPool) != VK_SUCCESS) { - throw std::runtime_error("failed to create descriptor pool!"); - } -} - -void VulkanBaseApp::createDescriptorSets() -{ - std::vector layouts(m_swapChainImages.size(), m_descriptorSetLayout); - VkDescriptorSetAllocateInfo allocInfo = {}; - allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - allocInfo.descriptorPool = m_descriptorPool; - allocInfo.descriptorSetCount = static_cast(m_swapChainImages.size()); - allocInfo.pSetLayouts = layouts.data(); - m_descriptorSets.resize(m_swapChainImages.size()); - - if (vkAllocateDescriptorSets(m_device, &allocInfo, m_descriptorSets.data()) != VK_SUCCESS) { - throw std::runtime_error("failed to allocate descriptor sets!"); - } - - VkDescriptorBufferInfo bufferInfo = {}; - bufferInfo.offset = 0; - bufferInfo.range = VK_WHOLE_SIZE; - VkWriteDescriptorSet descriptorWrite = {}; - descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descriptorWrite.dstBinding = 0; - descriptorWrite.dstArrayElement = 0; - descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; - descriptorWrite.descriptorCount = 1; - descriptorWrite.pBufferInfo = &bufferInfo; - descriptorWrite.pImageInfo = nullptr; // Optional - descriptorWrite.pTexelBufferView = nullptr; // Optional - - for (size_t i = 0; i < m_swapChainImages.size(); i++) { - bufferInfo.buffer = m_uniformBuffers[i]; - descriptorWrite.dstSet = m_descriptorSets[i]; - vkUpdateDescriptorSets(m_device, 1, &descriptorWrite, 0, nullptr); - } -} - -void VulkanBaseApp::createCommandBuffers() -{ - m_commandBuffers.resize(m_swapChainFramebuffers.size()); - VkCommandBufferAllocateInfo allocInfo = {}; - allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - allocInfo.commandPool = m_commandPool; - allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - allocInfo.commandBufferCount = (uint32_t)m_commandBuffers.size(); - - if (vkAllocateCommandBuffers(m_device, &allocInfo, m_commandBuffers.data()) != VK_SUCCESS) { - throw std::runtime_error("failed to allocate command buffers!"); - } - - for (size_t i = 0; i < m_commandBuffers.size(); i++) { - VkCommandBufferBeginInfo beginInfo = {}; - beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; - beginInfo.pInheritanceInfo = nullptr; // Optional - - if (vkBeginCommandBuffer(m_commandBuffers[i], &beginInfo) != VK_SUCCESS) { - throw std::runtime_error("failed to begin recording command buffer!"); - } - - VkRenderPassBeginInfo renderPassInfo = {}; - renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; - renderPassInfo.renderPass = m_renderPass; - renderPassInfo.framebuffer = m_swapChainFramebuffers[i]; - - renderPassInfo.renderArea.offset = { 0, 0 }; - renderPassInfo.renderArea.extent = m_swapChainExtent; - - VkClearValue clearColors[2]; - clearColors[0].color = { 0.0f, 0.0f, 0.0f, 1.0f }; - clearColors[1].depthStencil = { 1.0f, 0 }; - renderPassInfo.clearValueCount = countof(clearColors); - renderPassInfo.pClearValues = clearColors; - - vkCmdBeginRenderPass(m_commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); - - vkCmdBindPipeline(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_graphicsPipeline); - - vkCmdBindDescriptorSets(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1, &m_descriptorSets[i], 0, nullptr); - - fillRenderingCommandBuffer(m_commandBuffers[i]); - - vkCmdEndRenderPass(m_commandBuffers[i]); - - if (vkEndCommandBuffer(m_commandBuffers[i]) != VK_SUCCESS) { - throw std::runtime_error("failed to record command buffer!"); - } - } -} - -void VulkanBaseApp::createSyncObjects() -{ - VkSemaphoreCreateInfo semaphoreInfo = {}; - semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; - VkFenceCreateInfo fenceInfo = {}; - fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; - fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; - - m_inFlightFences.resize(MAX_FRAMES_IN_FLIGHT); - m_imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT); - m_renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT); - - for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { - if (vkCreateSemaphore(m_device, &semaphoreInfo, nullptr, &m_imageAvailableSemaphores[i]) != VK_SUCCESS) { - throw std::runtime_error("Failed to create image available semaphore!"); - } - if (vkCreateSemaphore(m_device, &semaphoreInfo, nullptr, &m_renderFinishedSemaphores[i]) != VK_SUCCESS) { - throw std::runtime_error("Failed to create image available semaphore!"); - } - if (vkCreateFence(m_device, &fenceInfo, nullptr, &m_inFlightFences[i]) != VK_SUCCESS) { - throw std::runtime_error("Failed to create image available semaphore!"); - } - } -} - -void VulkanBaseApp::getWaitFrameSemaphores(std::vector& wait, std::vector& waitStages) const -{ -} - -void VulkanBaseApp::getSignalFrameSemaphores(std::vector& signal) const -{ -} - -VkDeviceSize VulkanBaseApp::getUniformSize() const -{ - return VkDeviceSize(0); -} - -void VulkanBaseApp::updateUniformBuffer(uint32_t imageIndex) -{ -} - -void VulkanBaseApp::createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) -{ - VkBufferCreateInfo bufferInfo = {}; - bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufferInfo.size = size; - bufferInfo.usage = usage; - bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - - if (vkCreateBuffer(m_device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { - throw std::runtime_error("failed to create buffer!"); - } - - VkMemoryRequirements memRequirements; - vkGetBufferMemoryRequirements(m_device, buffer, &memRequirements); - - VkMemoryAllocateInfo allocInfo = {}; - allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - allocInfo.allocationSize = memRequirements.size; - allocInfo.memoryTypeIndex = findMemoryType(m_physicalDevice, memRequirements.memoryTypeBits, properties); - - if (vkAllocateMemory(m_device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { - throw std::runtime_error("failed to allocate buffer memory!"); - } - - vkBindBufferMemory(m_device, buffer, bufferMemory, 0); -} - -void VulkanBaseApp::createExternalBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkExternalMemoryHandleTypeFlagsKHR extMemHandleType, VkBuffer& buffer, VkDeviceMemory& bufferMemory) -{ - VkBufferCreateInfo bufferInfo = {}; - bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufferInfo.size = size; - bufferInfo.usage = usage; - bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - - if (vkCreateBuffer(m_device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { - throw std::runtime_error("failed to create buffer!"); - } - - VkMemoryRequirements memRequirements; - vkGetBufferMemoryRequirements(m_device, buffer, &memRequirements); - -#ifdef _WIN64 - WindowsSecurityAttributes winSecurityAttributes; - - VkExportMemoryWin32HandleInfoKHR vulkanExportMemoryWin32HandleInfoKHR = {}; - vulkanExportMemoryWin32HandleInfoKHR.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR; - vulkanExportMemoryWin32HandleInfoKHR.pNext = NULL; - vulkanExportMemoryWin32HandleInfoKHR.pAttributes = &winSecurityAttributes; - vulkanExportMemoryWin32HandleInfoKHR.dwAccess = DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE; - vulkanExportMemoryWin32HandleInfoKHR.name = (LPCWSTR)NULL; -#endif - VkExportMemoryAllocateInfoKHR vulkanExportMemoryAllocateInfoKHR = {}; - vulkanExportMemoryAllocateInfoKHR.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR; -#ifdef _WIN64 - vulkanExportMemoryAllocateInfoKHR.pNext = extMemHandleType & VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR ? &vulkanExportMemoryWin32HandleInfoKHR : NULL; - vulkanExportMemoryAllocateInfoKHR.handleTypes = extMemHandleType; -#else - vulkanExportMemoryAllocateInfoKHR.pNext = NULL; - vulkanExportMemoryAllocateInfoKHR.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT; -#endif - VkMemoryAllocateInfo allocInfo = {}; - allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - allocInfo.pNext = &vulkanExportMemoryAllocateInfoKHR; - allocInfo.allocationSize = memRequirements.size; - allocInfo.memoryTypeIndex = findMemoryType(m_physicalDevice, memRequirements.memoryTypeBits, properties); - - if (vkAllocateMemory(m_device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { - throw std::runtime_error("failed to allocate external buffer memory!"); - } - - vkBindBufferMemory(m_device, buffer, bufferMemory, 0); -} - -void *VulkanBaseApp::getMemHandle(VkDeviceMemory memory, VkExternalMemoryHandleTypeFlagBits handleType) -{ -#ifdef _WIN64 - HANDLE handle = 0; - - VkMemoryGetWin32HandleInfoKHR vkMemoryGetWin32HandleInfoKHR = {}; - vkMemoryGetWin32HandleInfoKHR.sType = VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR; - vkMemoryGetWin32HandleInfoKHR.pNext = NULL; - vkMemoryGetWin32HandleInfoKHR.memory = memory; - vkMemoryGetWin32HandleInfoKHR.handleType = handleType; - - PFN_vkGetMemoryWin32HandleKHR fpGetMemoryWin32HandleKHR; - fpGetMemoryWin32HandleKHR = (PFN_vkGetMemoryWin32HandleKHR)vkGetDeviceProcAddr(m_device, "vkGetMemoryWin32HandleKHR"); - if (!fpGetMemoryWin32HandleKHR) { - throw std::runtime_error("Failed to retrieve vkGetMemoryWin32HandleKHR!"); - } - if (fpGetMemoryWin32HandleKHR(m_device, &vkMemoryGetWin32HandleInfoKHR, &handle) != VK_SUCCESS) { - throw std::runtime_error("Failed to retrieve handle for buffer!"); - } - return (void *)handle; -#else - int fd = -1; - - VkMemoryGetFdInfoKHR vkMemoryGetFdInfoKHR = {}; - vkMemoryGetFdInfoKHR.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR; - vkMemoryGetFdInfoKHR.pNext = NULL; - vkMemoryGetFdInfoKHR.memory = memory; - vkMemoryGetFdInfoKHR.handleType = handleType; - - PFN_vkGetMemoryFdKHR fpGetMemoryFdKHR; - fpGetMemoryFdKHR = (PFN_vkGetMemoryFdKHR)vkGetDeviceProcAddr(m_device, "vkGetMemoryFdKHR"); - if (!fpGetMemoryFdKHR) { - throw std::runtime_error("Failed to retrieve vkGetMemoryWin32HandleKHR!"); - } - if (fpGetMemoryFdKHR(m_device, &vkMemoryGetFdInfoKHR, &fd) != VK_SUCCESS) { - throw std::runtime_error("Failed to retrieve handle for buffer!"); - } - return (void *)(uintptr_t)fd; -#endif /* _WIN64 */ -} - -void *VulkanBaseApp::getSemaphoreHandle(VkSemaphore semaphore, VkExternalSemaphoreHandleTypeFlagBits handleType) -{ -#ifdef _WIN64 - HANDLE handle; - - VkSemaphoreGetWin32HandleInfoKHR semaphoreGetWin32HandleInfoKHR = {}; - semaphoreGetWin32HandleInfoKHR.sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR; - semaphoreGetWin32HandleInfoKHR.pNext = NULL; - semaphoreGetWin32HandleInfoKHR.semaphore = semaphore; - semaphoreGetWin32HandleInfoKHR.handleType = handleType; - - PFN_vkGetSemaphoreWin32HandleKHR fpGetSemaphoreWin32HandleKHR; - fpGetSemaphoreWin32HandleKHR = (PFN_vkGetSemaphoreWin32HandleKHR)vkGetDeviceProcAddr(m_device, "vkGetSemaphoreWin32HandleKHR"); - if (!fpGetSemaphoreWin32HandleKHR) { - throw std::runtime_error("Failed to retrieve vkGetMemoryWin32HandleKHR!"); - } - if (fpGetSemaphoreWin32HandleKHR(m_device, &semaphoreGetWin32HandleInfoKHR, &handle) != VK_SUCCESS) { - throw std::runtime_error("Failed to retrieve handle for buffer!"); - } - - return (void *)handle; -#else - int fd; - - VkSemaphoreGetFdInfoKHR semaphoreGetFdInfoKHR = {}; - semaphoreGetFdInfoKHR.sType =VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR; - semaphoreGetFdInfoKHR.pNext = NULL; - semaphoreGetFdInfoKHR.semaphore = semaphore; - semaphoreGetFdInfoKHR.handleType = handleType; - - PFN_vkGetSemaphoreFdKHR fpGetSemaphoreFdKHR; - fpGetSemaphoreFdKHR = (PFN_vkGetSemaphoreFdKHR)vkGetDeviceProcAddr(m_device, "vkGetSemaphoreFdKHR"); - if (!fpGetSemaphoreFdKHR) { - throw std::runtime_error("Failed to retrieve vkGetMemoryWin32HandleKHR!"); - } - if (fpGetSemaphoreFdKHR(m_device, &semaphoreGetFdInfoKHR, &fd) != VK_SUCCESS) { - throw std::runtime_error("Failed to retrieve handle for buffer!"); - } - - return (void *)(uintptr_t)fd; -#endif -} - -void VulkanBaseApp::createExternalSemaphore(VkSemaphore& semaphore, VkExternalSemaphoreHandleTypeFlagBits handleType) -{ - VkSemaphoreCreateInfo semaphoreInfo = {}; - semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; - VkExportSemaphoreCreateInfoKHR exportSemaphoreCreateInfo = {}; - exportSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR; - -#ifdef _WIN64 - WindowsSecurityAttributes winSecurityAttributes; - - VkExportSemaphoreWin32HandleInfoKHR exportSemaphoreWin32HandleInfoKHR = {}; - exportSemaphoreWin32HandleInfoKHR.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR; - exportSemaphoreWin32HandleInfoKHR.pNext = NULL; - exportSemaphoreWin32HandleInfoKHR.pAttributes = &winSecurityAttributes; - exportSemaphoreWin32HandleInfoKHR.dwAccess = DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE; - exportSemaphoreWin32HandleInfoKHR.name = (LPCWSTR)NULL; - exportSemaphoreCreateInfo.pNext = (handleType & VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT) ? &exportSemaphoreWin32HandleInfoKHR : NULL; -#else - exportSemaphoreCreateInfo.pNext = NULL; -#endif - exportSemaphoreCreateInfo.handleTypes = handleType; - semaphoreInfo.pNext = &exportSemaphoreCreateInfo; - - if (vkCreateSemaphore(m_device, &semaphoreInfo, nullptr, &semaphore) != VK_SUCCESS) { - throw std::runtime_error("failed to create synchronization objects for a CUDA-Vulkan!"); - } -} - -void VulkanBaseApp::importExternalBuffer(void *handle, VkExternalMemoryHandleTypeFlagBits handleType, size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& memory) -{ - VkBufferCreateInfo bufferInfo = {}; - bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufferInfo.size = size; - bufferInfo.usage = usage; - bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - - if (vkCreateBuffer(m_device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { - throw std::runtime_error("failed to create buffer!"); - } - - VkMemoryRequirements memRequirements; - vkGetBufferMemoryRequirements(m_device, buffer, &memRequirements); - -#ifdef _WIN64 - VkImportMemoryWin32HandleInfoKHR handleInfo = {}; - handleInfo.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR; - handleInfo.pNext = NULL; - handleInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT; - handleInfo.handle = handle; - handleInfo.name = NULL; -#else - VkImportMemoryFdInfoKHR handleInfo = {}; - handleInfo.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR; - handleInfo.pNext = NULL; - handleInfo.fd = (int)(uintptr_t)handle; - handleInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT; -#endif /* _WIN64 */ - - VkMemoryAllocateInfo memAllocation = {}; - memAllocation.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - memAllocation.pNext = (void *)&handleInfo; - memAllocation.allocationSize = size; - memAllocation.memoryTypeIndex = findMemoryType(m_physicalDevice, memRequirements.memoryTypeBits, properties); - - if (vkAllocateMemory(m_device, &memAllocation, nullptr, &memory) != VK_SUCCESS) { - throw std::runtime_error("Failed to import allocation!"); - } - - vkBindBufferMemory(m_device, buffer, memory, 0); -} - -void VulkanBaseApp::copyBuffer(VkBuffer dst, VkBuffer src, VkDeviceSize size) -{ - - VkCommandBuffer commandBuffer = beginSingleTimeCommands(); - - VkBufferCopy copyRegion = {}; - copyRegion.size = size; - vkCmdCopyBuffer(commandBuffer, src, dst, 1, ©Region); - - endSingleTimeCommands(commandBuffer); -} - -void VulkanBaseApp::drawFrame() -{ - size_t currentFrameIdx = m_currentFrame % MAX_FRAMES_IN_FLIGHT; - vkWaitForFences(m_device, 1, &m_inFlightFences[currentFrameIdx], VK_TRUE, std::numeric_limits::max()); - - uint32_t imageIndex; - VkResult result = vkAcquireNextImageKHR(m_device, m_swapChain, std::numeric_limits::max(), m_imageAvailableSemaphores[currentFrameIdx], VK_NULL_HANDLE, &imageIndex); - if (result == VK_ERROR_OUT_OF_DATE_KHR) { - recreateSwapChain(); - } - else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { - throw std::runtime_error("Failed to acquire swap chain image!"); - } - - updateUniformBuffer(imageIndex); - - VkSubmitInfo submitInfo = {}; - submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - - std::vector waitSemaphores; - std::vector waitStages; - - waitSemaphores.push_back(m_imageAvailableSemaphores[currentFrameIdx]); - waitStages.push_back(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); - //getWaitFrameSemaphores(waitSemaphores, waitStages); - - submitInfo.waitSemaphoreCount = (uint32_t)waitSemaphores.size(); - submitInfo.pWaitSemaphores = waitSemaphores.data(); - submitInfo.pWaitDstStageMask = waitStages.data(); - - submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &m_commandBuffers[imageIndex]; - - std::vector signalSemaphores; - //getSignalFrameSemaphores(signalSemaphores); - signalSemaphores.push_back(m_renderFinishedSemaphores[currentFrameIdx]); - submitInfo.signalSemaphoreCount = (uint32_t)signalSemaphores.size(); - submitInfo.pSignalSemaphores = signalSemaphores.data(); - - vkResetFences(m_device, 1, &m_inFlightFences[currentFrameIdx]); - - if (vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, m_inFlightFences[currentFrameIdx]) != VK_SUCCESS) { - throw std::runtime_error("failed to submit draw command buffer!"); - } - - VkPresentInfoKHR presentInfo = {}; - presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; - presentInfo.waitSemaphoreCount = 1; - presentInfo.pWaitSemaphores = &m_renderFinishedSemaphores[currentFrameIdx]; - - VkSwapchainKHR swapChains[] = { m_swapChain }; - presentInfo.swapchainCount = 1; - presentInfo.pSwapchains = swapChains; - presentInfo.pImageIndices = &imageIndex; - - result = vkQueuePresentKHR(m_presentQueue, &presentInfo); - if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || m_framebufferResized) { - recreateSwapChain(); - m_framebufferResized = false; - } - else if (result != VK_SUCCESS) { - throw std::runtime_error("Failed to acquire swap chain image!"); - } - - m_currentFrame++; -} - -void VulkanBaseApp::cleanupSwapChain() -{ - - if (m_depthImageView != VK_NULL_HANDLE) { - vkDestroyImageView(m_device, m_depthImageView, nullptr); - } - if (m_depthImage != VK_NULL_HANDLE) { - vkDestroyImage(m_device, m_depthImage, nullptr); - } - if (m_depthImageMemory != VK_NULL_HANDLE) { - vkFreeMemory(m_device, m_depthImageMemory, nullptr); - } - - for (size_t i = 0; i < m_uniformBuffers.size(); i++) { - vkDestroyBuffer(m_device, m_uniformBuffers[i], nullptr); - vkFreeMemory(m_device, m_uniformMemory[i], nullptr); - } - - if (m_descriptorPool != VK_NULL_HANDLE) { - vkDestroyDescriptorPool(m_device, m_descriptorPool, nullptr); - } - - for (size_t i = 0; i < m_swapChainFramebuffers.size(); i++) { - vkDestroyFramebuffer(m_device, m_swapChainFramebuffers[i], nullptr); - } - - if (m_graphicsPipeline != VK_NULL_HANDLE) { - vkDestroyPipeline(m_device, m_graphicsPipeline, nullptr); - } - - if (m_pipelineLayout != VK_NULL_HANDLE) { - vkDestroyPipelineLayout(m_device, m_pipelineLayout, nullptr); - } - - if (m_renderPass != VK_NULL_HANDLE) { - vkDestroyRenderPass(m_device, m_renderPass, nullptr); - } - - for (size_t i = 0; i < m_swapChainImageViews.size(); i++) { - vkDestroyImageView(m_device, m_swapChainImageViews[i], nullptr); - } - - if (m_swapChain != VK_NULL_HANDLE) { - vkDestroySwapchainKHR(m_device, m_swapChain, nullptr); - } -} - -void VulkanBaseApp::recreateSwapChain() -{ - int width, height; - - glfwGetFramebufferSize(m_window, &width, &height); - while (width == 0 || height == 0) { - glfwWaitEvents(); - glfwGetFramebufferSize(m_window, &width, &height); - } - - vkDeviceWaitIdle(m_device); - - cleanupSwapChain(); - - createSwapChain(); - createImageViews(); - createRenderPass(); - createGraphicsPipeline(); - createDepthResources(); - createFramebuffers(); - createUniformBuffers(); - createDescriptorPool(); - createDescriptorSets(); - createCommandBuffers(); -} - -void VulkanBaseApp::mainLoop() -{ - while (!glfwWindowShouldClose(m_window)) { - glfwPollEvents(); - drawFrame(); - } - vkDeviceWaitIdle(m_device); -} - -void readFile(std::istream& s, std::vector& data) -{ - s.seekg(0, std::ios_base::end); - data.resize(s.tellg()); - s.clear(); - s.seekg(0, std::ios_base::beg); - s.read(data.data(), data.size()); -} diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/VulkanBaseApp.h b/projects/hip/samples/2_Cookbook/20_hip_vulkan/VulkanBaseApp.h deleted file mode 100644 index 03007db309..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/VulkanBaseApp.h +++ /dev/null @@ -1,146 +0,0 @@ -/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of NVIDIA CORPORATION nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -/* - * Modifications Copyright (C)2021 Advanced - * Micro Devices, Inc. All rights reserved. - */ - -#pragma once -#ifndef __VULKANBASEAPP_H__ -#define __VULKANBASEAPP_H__ - -#include -#include -#include -#ifdef _WIN64 -#define NOMINMAX -#include -#include -#endif /* _WIN64 */ - -struct GLFWwindow; - -class VulkanBaseApp -{ -public: - VulkanBaseApp(const std::string& appName, bool enableValidation = false); - static VkExternalSemaphoreHandleTypeFlagBits getDefaultSemaphoreHandleType(); - static VkExternalMemoryHandleTypeFlagBits getDefaultMemHandleType(); - virtual ~VulkanBaseApp(); - void init(); - void *getMemHandle(VkDeviceMemory memory, VkExternalMemoryHandleTypeFlagBits handleType); - void *getSemaphoreHandle(VkSemaphore semaphore, VkExternalSemaphoreHandleTypeFlagBits handleType); - void createExternalSemaphore(VkSemaphore& semaphore, VkExternalSemaphoreHandleTypeFlagBits handleType); - void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory); - void createExternalBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkExternalMemoryHandleTypeFlagsKHR extMemHandleType, VkBuffer& buffer, VkDeviceMemory& bufferMemory); - void importExternalBuffer(void *handle, VkExternalMemoryHandleTypeFlagBits handleType, size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& memory); - void copyBuffer(VkBuffer dst, VkBuffer src, VkDeviceSize size); - VkCommandBuffer beginSingleTimeCommands(); - void endSingleTimeCommands(VkCommandBuffer commandBuffer); - void mainLoop(); -protected: - const std::string m_appName; - const bool m_enableValidation; - VkInstance m_instance; - VkDebugUtilsMessengerEXT m_debugMessenger; - VkSurfaceKHR m_surface; - VkPhysicalDevice m_physicalDevice; - VkDevice m_device; - VkQueue m_graphicsQueue; - VkQueue m_presentQueue; - VkSwapchainKHR m_swapChain; - std::vector m_swapChainImages; - VkFormat m_swapChainFormat; - VkExtent2D m_swapChainExtent; - std::vector m_swapChainImageViews; - std::vector > m_shaderFiles; - VkRenderPass m_renderPass; - VkPipelineLayout m_pipelineLayout; - VkPipeline m_graphicsPipeline; - std::vector m_swapChainFramebuffers; - VkCommandPool m_commandPool; - std::vector m_commandBuffers; - std::vector m_imageAvailableSemaphores; - std::vector m_renderFinishedSemaphores; - std::vector m_inFlightFences; - std::vector m_uniformBuffers; - std::vector m_uniformMemory; - VkDescriptorSetLayout m_descriptorSetLayout; - VkDescriptorPool m_descriptorPool; - std::vector m_descriptorSets; - VkImage m_depthImage; - VkDeviceMemory m_depthImageMemory; - VkImageView m_depthImageView; - size_t m_currentFrame; - bool m_framebufferResized; - uint8_t m_vkDeviceUUID[VK_UUID_SIZE]; - - virtual void initVulkanApp() {} - virtual void fillRenderingCommandBuffer(VkCommandBuffer& buffer) {} - virtual std::vector getRequiredExtensions() const; - virtual std::vector getRequiredDeviceExtensions() const; - virtual void getVertexDescriptions(std::vector& bindingDesc, std::vector& attribDesc); - virtual void getAssemblyStateInfo(VkPipelineInputAssemblyStateCreateInfo& info); - virtual void getWaitFrameSemaphores(std::vector& wait, std::vector< VkPipelineStageFlags>& waitStages) const; - virtual void getSignalFrameSemaphores(std::vector& signal) const; - virtual VkDeviceSize getUniformSize() const; - virtual void updateUniformBuffer(uint32_t imageIndex); - virtual void drawFrame(); -private: - GLFWwindow *m_window; - - void initWindow(); - void initVulkan(); - void createInstance(); - void createSurface(); - void createDevice(); - void createSwapChain(); - void createImageViews(); - void createRenderPass(); - void createDescriptorSetLayout(); - void createGraphicsPipeline(); - void createFramebuffers(); - void createCommandPool(); - void createDepthResources(); - void createUniformBuffers(); - void createDescriptorPool(); - void createDescriptorSets(); - void createCommandBuffers(); - void createSyncObjects(); - - void cleanupSwapChain(); - void recreateSwapChain(); - - bool isSuitableDevice(VkPhysicalDevice dev) const; - static void resizeCallback(GLFWwindow *window, int width, int height); -}; - -void readFile(std::istream& s, std::vector& data); - -#endif /* __VULKANBASEAPP_H__ */ diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/buildcmd.txt b/projects/hip/samples/2_Cookbook/20_hip_vulkan/buildcmd.txt deleted file mode 100644 index 791466ec42..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/buildcmd.txt +++ /dev/null @@ -1,16 +0,0 @@ -• Install hip and visual studio -• Install vulkan sdk from vulkan.lunarg.com -• Download GLFW binaries from glfw.org -• Convert sinwave.farg and vert files to spv -o c:\VulkanSDK\1.2.182.0\bin\glslangValidator.exe sinewave.vert -V -o vert.spv -o c:\VulkanSDK\1.2.182.0\bin\glslangValidator.exe sinewave.frag -V -o frag.spv - -to build without cmake: -• set HCC_AMDGPU_TARGET=gfx906:sramecc-:xnack- (for your graphic card, you can get the name from hipinfo ) -• hipcc -v *.cpp *.hip -Ic:\VulkanSDK\1.2.182.0\include -L c:\VulkanSDK\1.2.182.0\lib -Ic:\glfw-3.3.4.bin.WIN64\include -L c:\glfw-3.3.4.bin.WIN64\lib-vc2019 -Ic:\hip\include\hip -lglfw3dll -lvulkan-1 -ladvapi32 -std=c++14 -• run a.exe, you should see a 3D sinewave simulation - -to build with cmake on windows: -• mkdir build; cd build -• cmake.exe -GNinja -DCMAKE_CXX_COMPILER_ID=ROCMClang -DCMAKE_C_COMPILER_ID=ROCMClang -DCMAKE_PREFIX_PATH=d:\driver2\drivers\drivers\compute\hip_sdk - diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/linmath.h b/projects/hip/samples/2_Cookbook/20_hip_vulkan/linmath.h deleted file mode 100644 index dbedbc163a..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/linmath.h +++ /dev/null @@ -1,502 +0,0 @@ -/* - * Copyright (c) 2015-2016 The Khronos Group Inc. - * Copyright (c) 2015-2016 Valve Corporation - * Copyright (c) 2015-2016 LunarG, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Relicensed from the WTFPL (http://www.wtfpl.net/faq/). - */ - -#ifndef LINMATH_H -#define LINMATH_H - -#define _USE_MATH_DEFINES -#include - -// Converts degrees to radians. -#define degreesToRadians(angleDegrees) (angleDegrees * M_PI / 180.0) - -// Converts radians to degrees. -#define radiansToDegrees(angleRadians) (angleRadians * 180.0 / M_PI) - -typedef float vec3[3]; -static inline void vec3_add(vec3 r, vec3 const a, vec3 const b) { - int i; - for (i = 0; i < 3; ++i) r[i] = a[i] + b[i]; -} -static inline void vec3_sub(vec3 r, vec3 const a, vec3 const b) { - int i; - for (i = 0; i < 3; ++i) r[i] = a[i] - b[i]; -} -static inline void vec3_scale(vec3 r, vec3 const v, float const s) { - int i; - for (i = 0; i < 3; ++i) r[i] = v[i] * s; -} -static inline float vec3_mul_inner(vec3 const a, vec3 const b) { - float p = 0.f; - int i; - for (i = 0; i < 3; ++i) p += b[i] * a[i]; - return p; -} -static inline void vec3_mul_cross(vec3 r, vec3 const a, vec3 const b) { - r[0] = a[1] * b[2] - a[2] * b[1]; - r[1] = a[2] * b[0] - a[0] * b[2]; - r[2] = a[0] * b[1] - a[1] * b[0]; -} -static inline float vec3_len(vec3 const v) { return sqrtf(vec3_mul_inner(v, v)); } -static inline void vec3_norm(vec3 r, vec3 const v) { - float k = 1.f / vec3_len(v); - vec3_scale(r, v, k); -} -static inline void vec3_reflect(vec3 r, vec3 const v, vec3 const n) { - float p = 2.f * vec3_mul_inner(v, n); - int i; - for (i = 0; i < 3; ++i) r[i] = v[i] - p * n[i]; -} - -typedef float vec4[4]; -static inline void vec4_add(vec4 r, vec4 const a, vec4 const b) { - int i; - for (i = 0; i < 4; ++i) r[i] = a[i] + b[i]; -} -static inline void vec4_sub(vec4 r, vec4 const a, vec4 const b) { - int i; - for (i = 0; i < 4; ++i) r[i] = a[i] - b[i]; -} -static inline void vec4_scale(vec4 r, vec4 v, float s) { - int i; - for (i = 0; i < 4; ++i) r[i] = v[i] * s; -} -static inline float vec4_mul_inner(vec4 a, vec4 b) { - float p = 0.f; - int i; - for (i = 0; i < 4; ++i) p += b[i] * a[i]; - return p; -} -static inline void vec4_mul_cross(vec4 r, vec4 a, vec4 b) { - r[0] = a[1] * b[2] - a[2] * b[1]; - r[1] = a[2] * b[0] - a[0] * b[2]; - r[2] = a[0] * b[1] - a[1] * b[0]; - r[3] = 1.f; -} -static inline float vec4_len(vec4 v) { return sqrtf(vec4_mul_inner(v, v)); } -static inline void vec4_norm(vec4 r, vec4 v) { - float k = 1.f / vec4_len(v); - vec4_scale(r, v, k); -} -static inline void vec4_reflect(vec4 r, vec4 v, vec4 n) { - float p = 2.f * vec4_mul_inner(v, n); - int i; - for (i = 0; i < 4; ++i) r[i] = v[i] - p * n[i]; -} - -typedef vec4 mat4x4[4]; -static inline void mat4x4_identity(mat4x4 M) { - int i, j; - for (i = 0; i < 4; ++i) - for (j = 0; j < 4; ++j) M[i][j] = i == j ? 1.f : 0.f; -} -static inline void mat4x4_dup(mat4x4 M, mat4x4 N) { - int i, j; - for (i = 0; i < 4; ++i) - for (j = 0; j < 4; ++j) M[i][j] = N[i][j]; -} -static inline void mat4x4_row(vec4 r, mat4x4 M, int i) { - int k; - for (k = 0; k < 4; ++k) r[k] = M[k][i]; -} -static inline void mat4x4_col(vec4 r, mat4x4 M, int i) { - int k; - for (k = 0; k < 4; ++k) r[k] = M[i][k]; -} -static inline void mat4x4_transpose(mat4x4 M, mat4x4 N) { - int i, j; - for (j = 0; j < 4; ++j) - for (i = 0; i < 4; ++i) M[i][j] = N[j][i]; -} -static inline void mat4x4_add(mat4x4 M, mat4x4 a, mat4x4 b) { - int i; - for (i = 0; i < 4; ++i) vec4_add(M[i], a[i], b[i]); -} -static inline void mat4x4_sub(mat4x4 M, mat4x4 a, mat4x4 b) { - int i; - for (i = 0; i < 4; ++i) vec4_sub(M[i], a[i], b[i]); -} -static inline void mat4x4_scale(mat4x4 M, mat4x4 a, float k) { - int i; - for (i = 0; i < 4; ++i) vec4_scale(M[i], a[i], k); -} -static inline void mat4x4_scale_aniso(mat4x4 M, mat4x4 a, float x, float y, float z) { - int i; - vec4_scale(M[0], a[0], x); - vec4_scale(M[1], a[1], y); - vec4_scale(M[2], a[2], z); - for (i = 0; i < 4; ++i) { - M[3][i] = a[3][i]; - } -} -static inline void mat4x4_mul(mat4x4 M, mat4x4 a, mat4x4 b) { - int k, r, c; - for (c = 0; c < 4; ++c) - for (r = 0; r < 4; ++r) { - M[c][r] = 0.f; - for (k = 0; k < 4; ++k) M[c][r] += a[k][r] * b[c][k]; - } -} -static inline void mat4x4_mul_vec4(vec4 r, mat4x4 M, vec4 v) { - int i, j; - for (j = 0; j < 4; ++j) { - r[j] = 0.f; - for (i = 0; i < 4; ++i) r[j] += M[i][j] * v[i]; - } -} -static inline void mat4x4_translate(mat4x4 T, float x, float y, float z) { - mat4x4_identity(T); - T[3][0] = x; - T[3][1] = y; - T[3][2] = z; -} -static inline void mat4x4_translate_in_place(mat4x4 M, float x, float y, float z) { - vec4 t = {x, y, z, 0}; - vec4 r; - int i; - for (i = 0; i < 4; ++i) { - mat4x4_row(r, M, i); - M[3][i] += vec4_mul_inner(r, t); - } -} -static inline void mat4x4_from_vec3_mul_outer(mat4x4 M, vec3 a, vec3 b) { - int i, j; - for (i = 0; i < 4; ++i) - for (j = 0; j < 4; ++j) M[i][j] = i < 3 && j < 3 ? a[i] * b[j] : 0.f; -} -static inline void mat4x4_rotate(mat4x4 R, mat4x4 M, float x, float y, float z, float angle) { - float s = sinf(angle); - float c = cosf(angle); - vec3 u = {x, y, z}; - - if (vec3_len(u) > 1e-4) { - vec3_norm(u, u); - mat4x4 T; - mat4x4_from_vec3_mul_outer(T, u, u); - - mat4x4 S = {{0, u[2], -u[1], 0}, {-u[2], 0, u[0], 0}, {u[1], -u[0], 0, 0}, {0, 0, 0, 0}}; - mat4x4_scale(S, S, s); - - mat4x4 C; - mat4x4_identity(C); - mat4x4_sub(C, C, T); - - mat4x4_scale(C, C, c); - - mat4x4_add(T, T, C); - mat4x4_add(T, T, S); - - T[3][3] = 1.; - mat4x4_mul(R, M, T); - } else { - mat4x4_dup(R, M); - } -} -static inline void mat4x4_rotate_X(mat4x4 Q, mat4x4 M, float angle) { - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = {{1.f, 0.f, 0.f, 0.f}, {0.f, c, s, 0.f}, {0.f, -s, c, 0.f}, {0.f, 0.f, 0.f, 1.f}}; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_rotate_Y(mat4x4 Q, mat4x4 M, float angle) { - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = {{c, 0.f, s, 0.f}, {0.f, 1.f, 0.f, 0.f}, {-s, 0.f, c, 0.f}, {0.f, 0.f, 0.f, 1.f}}; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_rotate_Z(mat4x4 Q, mat4x4 M, float angle) { - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = {{c, s, 0.f, 0.f}, {-s, c, 0.f, 0.f}, {0.f, 0.f, 1.f, 0.f}, {0.f, 0.f, 0.f, 1.f}}; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_invert(mat4x4 T, mat4x4 M) { - float s[6]; - float c[6]; - s[0] = M[0][0] * M[1][1] - M[1][0] * M[0][1]; - s[1] = M[0][0] * M[1][2] - M[1][0] * M[0][2]; - s[2] = M[0][0] * M[1][3] - M[1][0] * M[0][3]; - s[3] = M[0][1] * M[1][2] - M[1][1] * M[0][2]; - s[4] = M[0][1] * M[1][3] - M[1][1] * M[0][3]; - s[5] = M[0][2] * M[1][3] - M[1][2] * M[0][3]; - - c[0] = M[2][0] * M[3][1] - M[3][0] * M[2][1]; - c[1] = M[2][0] * M[3][2] - M[3][0] * M[2][2]; - c[2] = M[2][0] * M[3][3] - M[3][0] * M[2][3]; - c[3] = M[2][1] * M[3][2] - M[3][1] * M[2][2]; - c[4] = M[2][1] * M[3][3] - M[3][1] * M[2][3]; - c[5] = M[2][2] * M[3][3] - M[3][2] * M[2][3]; - - /* Assumes it is invertible */ - float idet = 1.0f / (s[0] * c[5] - s[1] * c[4] + s[2] * c[3] + s[3] * c[2] - s[4] * c[1] + s[5] * c[0]); - - T[0][0] = (M[1][1] * c[5] - M[1][2] * c[4] + M[1][3] * c[3]) * idet; - T[0][1] = (-M[0][1] * c[5] + M[0][2] * c[4] - M[0][3] * c[3]) * idet; - T[0][2] = (M[3][1] * s[5] - M[3][2] * s[4] + M[3][3] * s[3]) * idet; - T[0][3] = (-M[2][1] * s[5] + M[2][2] * s[4] - M[2][3] * s[3]) * idet; - - T[1][0] = (-M[1][0] * c[5] + M[1][2] * c[2] - M[1][3] * c[1]) * idet; - T[1][1] = (M[0][0] * c[5] - M[0][2] * c[2] + M[0][3] * c[1]) * idet; - T[1][2] = (-M[3][0] * s[5] + M[3][2] * s[2] - M[3][3] * s[1]) * idet; - T[1][3] = (M[2][0] * s[5] - M[2][2] * s[2] + M[2][3] * s[1]) * idet; - - T[2][0] = (M[1][0] * c[4] - M[1][1] * c[2] + M[1][3] * c[0]) * idet; - T[2][1] = (-M[0][0] * c[4] + M[0][1] * c[2] - M[0][3] * c[0]) * idet; - T[2][2] = (M[3][0] * s[4] - M[3][1] * s[2] + M[3][3] * s[0]) * idet; - T[2][3] = (-M[2][0] * s[4] + M[2][1] * s[2] - M[2][3] * s[0]) * idet; - - T[3][0] = (-M[1][0] * c[3] + M[1][1] * c[1] - M[1][2] * c[0]) * idet; - T[3][1] = (M[0][0] * c[3] - M[0][1] * c[1] + M[0][2] * c[0]) * idet; - T[3][2] = (-M[3][0] * s[3] + M[3][1] * s[1] - M[3][2] * s[0]) * idet; - T[3][3] = (M[2][0] * s[3] - M[2][1] * s[1] + M[2][2] * s[0]) * idet; -} -static inline void mat4x4_orthonormalize(mat4x4 R, mat4x4 M) { - mat4x4_dup(R, M); - float s = 1.; - vec3 h; - - vec3_norm(R[2], R[2]); - - s = vec3_mul_inner(R[1], R[2]); - vec3_scale(h, R[2], s); - vec3_sub(R[1], R[1], h); - vec3_norm(R[2], R[2]); - - s = vec3_mul_inner(R[1], R[2]); - vec3_scale(h, R[2], s); - vec3_sub(R[1], R[1], h); - vec3_norm(R[1], R[1]); - - s = vec3_mul_inner(R[0], R[1]); - vec3_scale(h, R[1], s); - vec3_sub(R[0], R[0], h); - vec3_norm(R[0], R[0]); -} - -static inline void mat4x4_frustum(mat4x4 M, float l, float r, float b, float t, float n, float f) { - M[0][0] = 2.f * n / (r - l); - M[0][1] = M[0][2] = M[0][3] = 0.f; - - M[1][1] = 2.f * n / (t - b); - M[1][0] = M[1][2] = M[1][3] = 0.f; - - M[2][0] = (r + l) / (r - l); - M[2][1] = (t + b) / (t - b); - M[2][2] = -(f + n) / (f - n); - M[2][3] = -1.f; - - M[3][2] = -2.f * (f * n) / (f - n); - M[3][0] = M[3][1] = M[3][3] = 0.f; -} -static inline void mat4x4_ortho(mat4x4 M, float l, float r, float b, float t, float n, float f) { - M[0][0] = 2.f / (r - l); - M[0][1] = M[0][2] = M[0][3] = 0.f; - - M[1][1] = 2.f / (t - b); - M[1][0] = M[1][2] = M[1][3] = 0.f; - - M[2][2] = -2.f / (f - n); - M[2][0] = M[2][1] = M[2][3] = 0.f; - - M[3][0] = -(r + l) / (r - l); - M[3][1] = -(t + b) / (t - b); - M[3][2] = -(f + n) / (f - n); - M[3][3] = 1.f; -} -static inline void mat4x4_perspective(mat4x4 m, float y_fov, float aspect, float n, float f) { - /* NOTE: Degrees are an unhandy unit to work with. - * linmath.h uses radians for everything! */ - float const a = (float)(1.f / tan(y_fov / 2.f)); - - m[0][0] = a / aspect; - m[0][1] = 0.f; - m[0][2] = 0.f; - m[0][3] = 0.f; - - m[1][0] = 0.f; - m[1][1] = a; - m[1][2] = 0.f; - m[1][3] = 0.f; - - m[2][0] = 0.f; - m[2][1] = 0.f; - m[2][2] = -((f + n) / (f - n)); - m[2][3] = -1.f; - - m[3][0] = 0.f; - m[3][1] = 0.f; - m[3][2] = -((2.f * f * n) / (f - n)); - m[3][3] = 0.f; -} -static inline void mat4x4_look_at(mat4x4 m, vec3 eye, vec3 center, vec3 up) { - /* Adapted from Android's OpenGL Matrix.java. */ - /* See the OpenGL GLUT documentation for gluLookAt for a description */ - /* of the algorithm. We implement it in a straightforward way: */ - - /* TODO: The negation of of can be spared by swapping the order of - * operands in the following cross products in the right way. */ - vec3 f; - vec3_sub(f, center, eye); - vec3_norm(f, f); - - vec3 s; - vec3_mul_cross(s, f, up); - vec3_norm(s, s); - - vec3 t; - vec3_mul_cross(t, s, f); - - m[0][0] = s[0]; - m[0][1] = t[0]; - m[0][2] = -f[0]; - m[0][3] = 0.f; - - m[1][0] = s[1]; - m[1][1] = t[1]; - m[1][2] = -f[1]; - m[1][3] = 0.f; - - m[2][0] = s[2]; - m[2][1] = t[2]; - m[2][2] = -f[2]; - m[2][3] = 0.f; - - m[3][0] = 0.f; - m[3][1] = 0.f; - m[3][2] = 0.f; - m[3][3] = 1.f; - - mat4x4_translate_in_place(m, -eye[0], -eye[1], -eye[2]); -} - -typedef float quat[4]; -static inline void quat_identity(quat q) { - q[0] = q[1] = q[2] = 0.f; - q[3] = 1.f; -} -static inline void quat_add(quat r, quat a, quat b) { - int i; - for (i = 0; i < 4; ++i) r[i] = a[i] + b[i]; -} -static inline void quat_sub(quat r, quat a, quat b) { - int i; - for (i = 0; i < 4; ++i) r[i] = a[i] - b[i]; -} -static inline void quat_mul(quat r, quat p, quat q) { - vec3 w; - vec3_mul_cross(r, p, q); - vec3_scale(w, p, q[3]); - vec3_add(r, r, w); - vec3_scale(w, q, p[3]); - vec3_add(r, r, w); - r[3] = p[3] * q[3] - vec3_mul_inner(p, q); -} -static inline void quat_scale(quat r, quat v, float s) { - int i; - for (i = 0; i < 4; ++i) r[i] = v[i] * s; -} -static inline float quat_inner_product(quat a, quat b) { - float p = 0.f; - int i; - for (i = 0; i < 4; ++i) p += b[i] * a[i]; - return p; -} -static inline void quat_conj(quat r, quat q) { - int i; - for (i = 0; i < 3; ++i) r[i] = -q[i]; - r[3] = q[3]; -} -#define quat_norm vec4_norm -static inline void quat_mul_vec3(vec3 r, quat q, vec3 v) { - quat v_ = {v[0], v[1], v[2], 0.f}; - - quat_conj(r, q); - quat_norm(r, r); - quat_mul(r, v_, r); - quat_mul(r, q, r); -} -static inline void mat4x4_from_quat(mat4x4 M, quat q) { - float a = q[3]; - float b = q[0]; - float c = q[1]; - float d = q[2]; - float a2 = a * a; - float b2 = b * b; - float c2 = c * c; - float d2 = d * d; - - M[0][0] = a2 + b2 - c2 - d2; - M[0][1] = 2.f * (b * c + a * d); - M[0][2] = 2.f * (b * d - a * c); - M[0][3] = 0.f; - - M[1][0] = 2 * (b * c - a * d); - M[1][1] = a2 - b2 + c2 - d2; - M[1][2] = 2.f * (c * d + a * b); - M[1][3] = 0.f; - - M[2][0] = 2.f * (b * d + a * c); - M[2][1] = 2.f * (c * d - a * b); - M[2][2] = a2 - b2 - c2 + d2; - M[2][3] = 0.f; - - M[3][0] = M[3][1] = M[3][2] = 0.f; - M[3][3] = 1.f; -} - -static inline void mat4x4o_mul_quat(mat4x4 R, mat4x4 M, quat q) { - /* XXX: The way this is written only works for othogonal matrices. */ - /* TODO: Take care of non-orthogonal case. */ - quat_mul_vec3(R[0], q, M[0]); - quat_mul_vec3(R[1], q, M[1]); - quat_mul_vec3(R[2], q, M[2]); - - R[3][0] = R[3][1] = R[3][2] = 0.f; - R[3][3] = 1.f; -} -static inline void quat_from_mat4x4(quat q, mat4x4 M) { - float r = 0.f; - int i; - - int perm[] = {0, 1, 2, 0, 1}; - int *p = perm; - - for (i = 0; i < 3; i++) { - float m = M[i][i]; - if (m < r) continue; - m = r; - p = &perm[i]; - } - - r = sqrtf(1.f + M[p[0]][p[0]] - M[p[1]][p[1]] - M[p[2]][p[2]]); - - if (r < 1e-6) { - q[0] = 1.f; - q[1] = q[2] = q[3] = 0.f; - return; - } - - q[0] = r / 2.f; - q[1] = (M[p[0]][p[1]] - M[p[1]][p[0]]) / (2.f * r); - q[2] = (M[p[2]][p[0]] - M[p[0]][p[2]]) / (2.f * r); - q[3] = (M[p[2]][p[1]] - M[p[1]][p[2]]) / (2.f * r); -} - -#endif diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/main.cpp b/projects/hip/samples/2_Cookbook/20_hip_vulkan/main.cpp deleted file mode 100644 index 93c8db75db..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/main.cpp +++ /dev/null @@ -1,466 +0,0 @@ -/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of NVIDIA CORPORATION nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * Modifications Copyright (C)2021 Advanced - * Micro Devices, Inc. All rights reserved. - */ - -#include "VulkanBaseApp.h" - -#include -#include -#include -#include -#include "linmath.h" -#include "hip/hip_runtime.h" -#include "SineWaveSimulation.h" - - -typedef float vec2[2]; -std::string execution_path; - -#ifndef NDEBUG -#define ENABLE_VALIDATION (false) -#else -#define ENABLE_VALIDATION (true) -#endif - -#ifndef _WIN64 -#define MAX_PATH 260 - -int GetModuleFileName(void* hndl, char* name, int size) -{ - FILE* stream = fopen("/proc/self/cmdline", "r"); - fgets(name, size, stream); - fclose(stream); - return strlen(name); -} -#endif - -class VulkanCudaSineWave : public VulkanBaseApp -{ - - typedef struct UniformBufferObject_st { - mat4x4 modelViewProj; - } UniformBufferObject; - - VkBuffer m_heightBuffer, m_xyBuffer, m_indexBuffer; - VkDeviceMemory m_heightMemory, m_xyMemory, m_indexMemory; - UniformBufferObject m_ubo; - VkSemaphore m_vkWaitSemaphore, m_vkSignalSemaphore; - SineWaveSimulation m_sim; - hipStream_t m_stream; - hipExternalSemaphore_t m_cudaWaitSemaphore, m_cudaSignalSemaphore; - hipExternalMemory_t m_cudaVertMem; - float *m_cudaHeightMap; - using chrono_tp = std::chrono::time_point; - chrono_tp m_lastTime; - size_t m_lastFrame; -public: - VulkanCudaSineWave(size_t width, size_t height) : - VulkanBaseApp("vulkanCudaSineWave", ENABLE_VALIDATION), - m_heightBuffer(VK_NULL_HANDLE), - m_xyBuffer(VK_NULL_HANDLE), - m_indexBuffer(VK_NULL_HANDLE), - m_heightMemory(VK_NULL_HANDLE), - m_xyMemory(VK_NULL_HANDLE), - m_indexMemory(VK_NULL_HANDLE), - m_ubo(), - m_sim(width, height), - m_stream(0), - m_vkWaitSemaphore(VK_NULL_HANDLE), - m_vkSignalSemaphore(VK_NULL_HANDLE), - m_cudaWaitSemaphore(), - m_cudaSignalSemaphore(), - m_cudaVertMem(), - m_cudaHeightMap(nullptr), - m_lastFrame(0) { - // Our index buffer can only index 32-bits of the vertex buffer - if ((width * height) > (1ULL << 32ULL)) { - throw std::runtime_error("Requested height and width is too large for this sample!"); - } - // Add our compiled vulkan shader files - char buffer[MAX_PATH] = { 0 }; //assuming none unicode - GetModuleFileName(NULL, buffer, MAX_PATH); - std::string str3 = std::string(buffer); - std::string str1 = "vert.spv" ; //sdkFindFilePath("sinewave.vert", execution_path.c_str()); - char* vertex_shader_path = strdup(str1.c_str()); - - std::string str2 = "frag.spv" ; //sdkFindFilePath("sinewave.frag", execution_path.c_str()); - char* fragment_shader_path = strdup(str2.c_str()); - - m_shaderFiles.push_back(std::make_pair(VK_SHADER_STAGE_VERTEX_BIT, vertex_shader_path)); - m_shaderFiles.push_back(std::make_pair(VK_SHADER_STAGE_FRAGMENT_BIT, fragment_shader_path)); - - } - ~VulkanCudaSineWave() { - // Make sure there's no pending work before we start tearing down - checkHIPErrors(hipStreamSynchronize(m_stream)); - - if (m_vkSignalSemaphore != VK_NULL_HANDLE) { - checkHIPErrors(hipDestroyExternalSemaphore(m_cudaSignalSemaphore)); - vkDestroySemaphore(m_device, m_vkSignalSemaphore, nullptr); - } - if (m_vkWaitSemaphore != VK_NULL_HANDLE) { - checkHIPErrors(hipDestroyExternalSemaphore(m_cudaWaitSemaphore)); - vkDestroySemaphore(m_device, m_vkWaitSemaphore, nullptr); - } - - if (m_xyBuffer != VK_NULL_HANDLE) { - vkDestroyBuffer(m_device, m_xyBuffer, nullptr); - } - if (m_xyMemory != VK_NULL_HANDLE) { - vkFreeMemory(m_device, m_xyMemory, nullptr); - } - - if (m_heightBuffer != VK_NULL_HANDLE) { - vkDestroyBuffer(m_device, m_heightBuffer, nullptr); - } - if (m_heightMemory != VK_NULL_HANDLE) { - vkFreeMemory(m_device, m_heightMemory, nullptr); - } - if (m_cudaHeightMap) { - checkHIPErrors(hipDestroyExternalMemory(m_cudaVertMem)); - } - - if (m_indexBuffer != VK_NULL_HANDLE) { - vkDestroyBuffer(m_device, m_indexBuffer, nullptr); - } - if (m_indexMemory != VK_NULL_HANDLE) { - vkFreeMemory(m_device, m_indexMemory, nullptr); - } - } - - void fillRenderingCommandBuffer(VkCommandBuffer& commandBuffer) { - VkBuffer vertexBuffers[] = { m_heightBuffer, m_xyBuffer }; - VkDeviceSize offsets[] = { 0, 0 }; - vkCmdBindVertexBuffers(commandBuffer, 0, sizeof(vertexBuffers) / sizeof(vertexBuffers[0]), vertexBuffers, offsets); - vkCmdBindIndexBuffer(commandBuffer, m_indexBuffer, 0, VK_INDEX_TYPE_UINT32); - vkCmdDrawIndexed(commandBuffer, (uint32_t)((m_sim.getWidth() - 1) * (m_sim.getHeight() - 1) * 6), 1, 0, 0, 0); - } - - void getVertexDescriptions(std::vector& bindingDesc, std::vector& attribDesc) { - bindingDesc.resize(2); - attribDesc.resize(2); - - bindingDesc[0].binding = 0; - bindingDesc[0].stride = sizeof(float); - bindingDesc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; - - bindingDesc[1].binding = 1; - bindingDesc[1].stride = sizeof(vec2); - bindingDesc[1].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; - - attribDesc[0].binding = 0; - attribDesc[0].location = 0; - attribDesc[0].format = VK_FORMAT_R32_SFLOAT; - attribDesc[0].offset = 0; - - attribDesc[1].binding = 1; - attribDesc[1].location = 1; - attribDesc[1].format = VK_FORMAT_R32G32_SFLOAT; - attribDesc[1].offset = 0; - } - - void getAssemblyStateInfo(VkPipelineInputAssemblyStateCreateInfo& info) { - info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; - info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - info.primitiveRestartEnable = VK_FALSE; - } - - void getWaitFrameSemaphores(std::vector& wait, std::vector< VkPipelineStageFlags>& waitStages) const { - if (m_currentFrame != 0) { - // Have vulkan wait until cuda is done with the vertex buffer before rendering - // We don't do this on the first frame, as the wait semaphore hasn't been initialized yet - wait.push_back(m_vkWaitSemaphore); - // We want to wait until all the pipeline commands are complete before letting cuda work - waitStages.push_back(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } - } - - void getSignalFrameSemaphores(std::vector& signal) const { - // Add this semaphore for vulkan to signal once the vertex buffer is ready for cuda to modify - signal.push_back(m_vkSignalSemaphore); - } - - void initVulkanApp() { - int cuda_device = -1; - - // Select cuda device where vulkan is running. - cuda_device = m_sim.initCuda(m_vkDeviceUUID, VK_UUID_SIZE); - if (cuda_device == -1) - { - printf("Error: No CUDA-Vulkan interop capable device found\n"); - exit(EXIT_FAILURE); - } - - m_sim.initCudaLaunchConfig(cuda_device); - - // Create the cuda stream we'll be using - checkHIPErrors(hipStreamCreateWithFlags(&m_stream, hipStreamNonBlocking)); - - const size_t nVerts = m_sim.getWidth() * m_sim.getHeight(); - const size_t nInds = (m_sim.getWidth() - 1) * (m_sim.getHeight() - 1) * 6; - - // Create the height map cuda will write to - createExternalBuffer(nVerts * sizeof(float), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - getDefaultMemHandleType(), - m_heightBuffer, m_heightMemory); - - // Create the vertex buffer that will hold the xy coordinates for the grid - createBuffer(nVerts * sizeof(vec2), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - m_xyBuffer, m_xyMemory); - - // Create the index buffer that references from both buffers above - createBuffer(nInds * sizeof(uint32_t), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - m_indexBuffer, m_indexMemory); - - // Import the height map into cuda and retrieve a device pointer to use - importHipExternalMemory((void **)&m_cudaHeightMap, m_cudaVertMem, m_heightMemory, nVerts * sizeof(*m_cudaHeightMap), getDefaultMemHandleType()); - // Set the height map to use in the simulation - m_sim.initSimulation(m_cudaHeightMap); - - { - // Set up the initial values for the vertex buffers with Vulkan - void *stagingBase; - VkBuffer stagingBuffer; - VkDeviceMemory stagingMemory; - VkDeviceSize stagingSz = std::max(nVerts * sizeof(vec2), nInds * sizeof(uint32_t)); - createBuffer(stagingSz, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingMemory); - - vkMapMemory(m_device, stagingMemory, 0, stagingSz, 0, &stagingBase); - - memset(stagingBase, 0, nVerts * sizeof(float)); - copyBuffer(m_heightBuffer, stagingBuffer, nVerts * sizeof(float)); - - for (size_t y = 0; y < m_sim.getHeight(); y++) { - for (size_t x = 0; x < m_sim.getWidth(); x++) { - vec2 *stagedVert = (vec2 *)stagingBase; - stagedVert[y * m_sim.getWidth() + x][0] = (2.0f * x) / (m_sim.getWidth() - 1) - 1; - stagedVert[y * m_sim.getWidth() + x][1] = (2.0f * y) / (m_sim.getHeight() - 1) - 1; - } - } - copyBuffer(m_xyBuffer, stagingBuffer, nVerts * sizeof(vec2)); - - { - uint32_t *indices = (uint32_t *)stagingBase; - for (size_t y = 0; y < m_sim.getHeight() - 1; y++) { - for (size_t x = 0; x < m_sim.getWidth() - 1; x++) { - indices[0] = (uint32_t)((y + 0) * m_sim.getWidth() + (x + 0)); - indices[1] = (uint32_t)((y + 1) * m_sim.getWidth() + (x + 0)); - indices[2] = (uint32_t)((y + 0) * m_sim.getWidth() + (x + 1)); - indices[3] = (uint32_t)((y + 1) * m_sim.getWidth() + (x + 0)); - indices[4] = (uint32_t)((y + 1) * m_sim.getWidth() + (x + 1)); - indices[5] = (uint32_t)((y + 0) * m_sim.getWidth() + (x + 1)); - indices += 6; - } - } - } - copyBuffer(m_indexBuffer, stagingBuffer, nInds * sizeof(uint32_t)); - - vkUnmapMemory(m_device, stagingMemory); - vkDestroyBuffer(m_device, stagingBuffer, nullptr); - vkFreeMemory(m_device, stagingMemory, nullptr); - } - - // Create the semaphore vulkan will signal when it's done with the vertex buffer - createExternalSemaphore(m_vkSignalSemaphore, getDefaultSemaphoreHandleType()); - // Create the semaphore vulkan will wait for before using the vertex buffer - createExternalSemaphore(m_vkWaitSemaphore, getDefaultSemaphoreHandleType()); - // Import the semaphore cuda will use -- vulkan's signal will be cuda's wait - importCudaExternalSemaphore(m_cudaWaitSemaphore, m_vkSignalSemaphore, getDefaultSemaphoreHandleType()); - // Import the semaphore cuda will use -- cuda's signal will be vulkan's wait - importCudaExternalSemaphore(m_cudaSignalSemaphore, m_vkWaitSemaphore, getDefaultSemaphoreHandleType()); - - } - - void importHipExternalMemory(void **cudaPtr, hipExternalMemory_t& cudaMem, VkDeviceMemory& vkMem, VkDeviceSize size, VkExternalMemoryHandleTypeFlagBits handleType) { - hipExternalMemoryHandleDesc externalMemoryHandleDesc = {}; - - if (handleType & VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT) { - externalMemoryHandleDesc.type = hipExternalMemoryHandleTypeOpaqueWin32; - } - else if (handleType & VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT) { - externalMemoryHandleDesc.type = hipExternalMemoryHandleTypeOpaqueWin32Kmt; - } - else if (handleType & VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) { - externalMemoryHandleDesc.type = hipExternalMemoryHandleTypeOpaqueFd; - } - else { - throw std::runtime_error("Unknown handle type requested!"); - } - - externalMemoryHandleDesc.size = size; - -#ifdef _WIN64 - externalMemoryHandleDesc.handle.win32.handle = (HANDLE)getMemHandle(vkMem, handleType); -#else - externalMemoryHandleDesc.handle.fd = (int)(uintptr_t)getMemHandle(vkMem, handleType); -#endif - checkHIPErrors(hipImportExternalMemory(&cudaMem, &externalMemoryHandleDesc)); - - hipExternalMemoryBufferDesc externalMemBufferDesc = {}; - externalMemBufferDesc.offset = 0; - externalMemBufferDesc.size = size; - externalMemBufferDesc.flags = 0; - - checkHIPErrors(hipExternalMemoryGetMappedBuffer(cudaPtr, cudaMem, &externalMemBufferDesc)); - } - - void importCudaExternalSemaphore(hipExternalSemaphore_t& cudaSem, VkSemaphore& vkSem, VkExternalSemaphoreHandleTypeFlagBits handleType) { - hipExternalSemaphoreHandleDesc externalSemaphoreHandleDesc = {}; - - if (handleType & VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT) { - externalSemaphoreHandleDesc.type = hipExternalSemaphoreHandleTypeOpaqueWin32; - } - else if (handleType & VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT) { - externalSemaphoreHandleDesc.type = hipExternalSemaphoreHandleTypeOpaqueWin32Kmt; - } - else if (handleType & VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) { - externalSemaphoreHandleDesc.type = hipExternalSemaphoreHandleTypeOpaqueFd; - } - else { - throw std::runtime_error("Unknown handle type requested!"); - } - -#ifdef _WIN64 - externalSemaphoreHandleDesc.handle.win32.handle = (HANDLE)getSemaphoreHandle(vkSem, handleType); -#else - externalSemaphoreHandleDesc.handle.fd = (int)(uintptr_t)getSemaphoreHandle(vkSem, handleType); -#endif - - externalSemaphoreHandleDesc.flags = 0; - - checkHIPErrors(hipImportExternalSemaphore(&cudaSem, &externalSemaphoreHandleDesc)); - } - - VkDeviceSize getUniformSize() const { - return sizeof(UniformBufferObject); - } - - void updateUniformBuffer(uint32_t imageIndex) { - { - mat4x4 view, proj; - vec3 eye = { 1.75f, 1.75f, 1.25f }; - vec3 center = { 0.0f, 0.0f, -0.25f }; - vec3 up = { 0.0f, 0.0f, 1.0f }; - - mat4x4_perspective(proj, (float)degreesToRadians(45.0f), m_swapChainExtent.width / (float)m_swapChainExtent.height, 0.1f, 10.0f); - proj[1][1] *= -1.0f; // Flip y axis - - mat4x4_look_at(view, eye, center, up); - mat4x4_mul(m_ubo.modelViewProj, proj, view); - } - - void *data; - vkMapMemory(m_device, m_uniformMemory[imageIndex], 0, getUniformSize(), 0, &data); - memcpy(data, &m_ubo, sizeof(m_ubo)); - vkUnmapMemory(m_device, m_uniformMemory[imageIndex]); - } - - std::vector getRequiredExtensions() const { - std::vector extensions; - extensions.push_back(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME); - extensions.push_back(VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME); - return extensions; - } - - std::vector getRequiredDeviceExtensions() const { - std::vector extensions; - extensions.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME); - extensions.push_back(VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME); -#ifdef _WIN64 - extensions.push_back(VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME); - extensions.push_back(VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME); -#else - extensions.push_back(VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME); - extensions.push_back(VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME); -#endif /* _WIN64 */ - return extensions; - } - - void drawFrame() { - static chrono_tp startTime = std::chrono::high_resolution_clock::now(); - - chrono_tp currentTime = std::chrono::high_resolution_clock::now(); - float time = std::chrono::duration(currentTime - startTime).count(); - - if (m_currentFrame == 0) { - m_lastTime = startTime; - } - - float frame_time = std::chrono::duration(currentTime - m_lastTime).count(); - - hipExternalSemaphoreWaitParams waitParams = {}; - waitParams.flags = 0; - waitParams.params.fence.value = 1; - - hipExternalSemaphoreSignalParams signalParams = {}; - signalParams.flags = 0; - signalParams.params.fence.value = 0; - - - // Have vulkan draw the current frame... - VulkanBaseApp::drawFrame(); - // Wait for vulkan to complete it's work - checkHIPErrors(hipWaitExternalSemaphoresAsync(&m_cudaWaitSemaphore, &waitParams, 1, m_stream)); - // Now step the simulation - m_sim.stepSimulation(time, m_stream); - - // Signal vulkan to continue with the updated buffers - checkHIPErrors(hipSignalExternalSemaphoresAsync(&m_cudaSignalSemaphore, &signalParams, 1, m_stream)); - - // Output a naive measurement of the frames per second every five seconds - if (frame_time > 5) { - std::cout << "Average FPS (over " - << std::fixed << std::setprecision(2) << frame_time - << " seconds): " - << std::fixed << std::setprecision(2) - << ((m_currentFrame - m_lastFrame) / frame_time) - << std::endl; - m_lastFrame = m_currentFrame; - m_lastTime = currentTime; - } - } -}; - -int main(int argc, char **argv) -{ - execution_path = argv[0]; - VulkanCudaSineWave app((1ULL << 8ULL), (1ULL << 8ULL)); - app.init(); - app.mainLoop(); - return 0; -} diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/sinewave.frag b/projects/hip/samples/2_Cookbook/20_hip_vulkan/sinewave.frag deleted file mode 100644 index c850c7a248..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/sinewave.frag +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of NVIDIA CORPORATION nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#version 450 -#extension GL_ARB_separate_shader_objects : enable - -layout(location = 0) in vec3 fragColor; - -layout(location = 0) out vec4 outColor; - -void main() { - outColor = vec4(fragColor, 1.0); -} \ No newline at end of file diff --git a/projects/hip/samples/2_Cookbook/20_hip_vulkan/sinewave.vert b/projects/hip/samples/2_Cookbook/20_hip_vulkan/sinewave.vert deleted file mode 100644 index 9157430756..0000000000 --- a/projects/hip/samples/2_Cookbook/20_hip_vulkan/sinewave.vert +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of NVIDIA CORPORATION nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#version 450 -#extension GL_ARB_separate_shader_objects : enable - -layout(binding = 0) uniform UniformBufferObject { - mat4 modelViewProj; -} ubo; - -layout(location = 0) in float height; -layout(location = 1) in vec2 xyPos; - -layout(location = 0) out vec3 fragColor; - -void main() { - gl_Position = ubo.modelViewProj * vec4(xyPos.xy, height, 1.0f); - fragColor = vec3(0.0f, (height + 0.5f), 0.0f); -} diff --git a/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/CMakeLists.txt b/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/CMakeLists.txt deleted file mode 100644 index 3cf4f35336..0000000000 --- a/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright (C) 2022 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -cmake_minimum_required(VERSION 3.21.3) - -project(cmake_cxx_amdclang++_test - DESCRIPTION "Verifies CXX Language Support with amdclang++" - LANGUAGES CXX) - -# Find HIP -find_package(hip REQUIRED) - -# Create the excutable -add_executable(square square.cpp) - -# Link with HIP -target_link_libraries(square hip::device) diff --git a/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/README.md b/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/README.md deleted file mode 100644 index 3d9765308c..0000000000 --- a/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/README.md +++ /dev/null @@ -1,19 +0,0 @@ -### This sample tests CXX Language support with amdclang++ -I. Build -mkdir -p build; cd build -rm -rf *; -CXX=`hipconfig -l`/amdclang++ cmake .. (or) -cmake -DCMAKE_CXX_COMPILER=/opt/rocm/bin/amdclang++ .. (or) -cmake -DCMAKE_CXX_COMPILER=/opt/rocm-X.Y.Z/llvm/bin/amdclang++ .. -make - -II. Test -$ ./square -info: running on device Vega 20 [Radeon Pro Vega 20] -info: allocate host mem ( 7.63 MB) -info: allocate device mem ( 7.63 MB) -info: copy Host2Device -info: launch 'vector_square' kernel -info: copy Device2Host -info: check result -PASSED! diff --git a/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/square.cpp b/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/square.cpp deleted file mode 100644 index c3ed799edc..0000000000 --- a/projects/hip/samples/2_Cookbook/21_cmake_hip_cxx_clang/square.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* -Copyright (c) 2015-2022 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include -#include - -#define CHECK(cmd) \ -{\ - hipError_t error = cmd;\ - if (error != hipSuccess) { \ - fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), error,__FILE__, __LINE__); \ - exit(EXIT_FAILURE);\ - }\ -} - - -/* - * Square each element in the array A and write to array C. - */ -template -__global__ void -vector_square(T *C_d, T *A_d, size_t N) -{ - size_t offset = (blockIdx.x * blockDim.x + threadIdx.x); - size_t stride = blockDim.x * gridDim.x ; - - for (size_t i=offset; i -#include - -#define CHECK(cmd) \ -{\ - hipError_t error = cmd;\ - if (error != hipSuccess) { \ - fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), error,__FILE__, __LINE__); \ - exit(EXIT_FAILURE);\ - }\ -} - - -/* - * Square each element in the array A and write to array C. - */ -template -__global__ void -vector_square(T *C_d, T *A_d, size_t N) -{ - size_t offset = (blockIdx.x * blockDim.x + threadIdx.x); - size_t stride = blockDim.x * gridDim.x ; - - for (size_t i=offset; i -#include - -#include -#include -#include -#include -#include -#include - -static constexpr auto NUM_THREADS{128}; -static constexpr auto NUM_BLOCKS{32}; - -static constexpr auto saxpy{ -R"( -#include "test_header.h" -#include "test_header1.h" -extern "C" -__global__ -void saxpy(real a, realptr x, realptr y, realptr out, size_t n) -{ - size_t tid = blockIdx.x * blockDim.x + threadIdx.x; - if (tid < n) { - out[tid] = a * x[tid] + y[tid] ; - } -} -)"}; - -int main() -{ - using namespace std; - - hiprtcProgram prog; - int num_headers = 2; - vector header_names; - vector header_sources; - header_names.push_back("test_header.h"); - header_names.push_back("test_header1.h"); - header_sources.push_back("#ifndef HIPRTC_TEST_HEADER_H\n#define HIPRTC_TEST_HEADER_H\ntypedef float real;\n#endif //HIPRTC_TEST_HEADER_H\n"); - header_sources.push_back("#ifndef HIPRTC_TEST_HEADER1_H\n#define HIPRTC_TEST_HEADER1_H\ntypedef float* realptr;\n#endif //HIPRTC_TEST_HEADER1_H\n"); - hiprtcCreateProgram(&prog, // prog - saxpy, // buffer - "saxpy.cu", // name - num_headers, // numHeaders - &header_sources[0], // headers - &header_names[0]); // includeNames - - hipDeviceProp_t props; - int device = 0; - hipGetDeviceProperties(&props, device); - - const char* options[] = {}; - - hiprtcResult compileResult{hiprtcCompileProgram(prog, 0, options)}; - - size_t logSize; - hiprtcGetProgramLogSize(prog, &logSize); - - if (logSize) { - string log(logSize, '\0'); - hiprtcGetProgramLog(prog, &log[0]); - - cout << log << '\n'; - } - - if (compileResult != HIPRTC_SUCCESS) { - cout << "Compilation failed." << endl; - } - - size_t codeSize; - hiprtcGetCodeSize(prog, &codeSize); - - vector code(codeSize); - hiprtcGetCode(prog, code.data()); - - hiprtcDestroyProgram(&prog); - - hipModule_t module; - hipFunction_t kernel; - - hipModuleLoadData(&module, code.data()); - hipModuleGetFunction(&kernel, module, "saxpy"); - - size_t n = NUM_THREADS * NUM_BLOCKS; - size_t bufferSize = n * sizeof(float); - - float a = 5.1f; - unique_ptr hX{new float[n]}; - unique_ptr hY{new float[n]}; - unique_ptr hOut{new float[n]}; - - for (size_t i = 0; i < n; ++i) { - hX[i] = static_cast(i); - hY[i] = static_cast(i * 2); - } - - hipDeviceptr_t dX, dY, dOut; - hipMalloc((void **)&dX, bufferSize); - hipMalloc((void **)&dY, bufferSize); - hipMalloc((void **)&dOut, bufferSize); - hipMemcpyHtoD(dX, hX.get(), bufferSize); - hipMemcpyHtoD(dY, hY.get(), bufferSize); - - struct { - float a_; - hipDeviceptr_t b_; - hipDeviceptr_t c_; - hipDeviceptr_t d_; - size_t e_; - } args{a, dX, dY, dOut, n}; - - auto size = sizeof(args); - void* config[] = {HIP_LAUNCH_PARAM_BUFFER_POINTER, &args, - HIP_LAUNCH_PARAM_BUFFER_SIZE, &size, - HIP_LAUNCH_PARAM_END}; - - hipModuleLaunchKernel(kernel, NUM_BLOCKS, 1, 1, NUM_THREADS, 1, 1, - 0, nullptr, nullptr, config); - hipMemcpyDtoH(hOut.get(), dOut, bufferSize); - - for (size_t i = 0; i < n; ++i) { - if (fabs(a * hX[i] + hY[i] - hOut[i]) > fabs(hOut[i])* 1e-6) { - cout << "Validation failed." << endl; - } - } - - hipFree((void *)dX); - hipFree((void *)dY); - hipFree((void *)dOut); - - hipModuleUnload(module); - - cout << "SAXPY test completed" << endl; -} diff --git a/projects/hip/samples/2_Cookbook/3_shared_memory/CMakeLists.txt b/projects/hip/samples/2_Cookbook/3_shared_memory/CMakeLists.txt deleted file mode 100644 index f2f5196373..0000000000 --- a/projects/hip/samples/2_Cookbook/3_shared_memory/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(sharedMemory) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(sharedMemory sharedMemory.cpp) - -# Link with HIP -target_link_libraries(sharedMemory hip::host) diff --git a/projects/hip/samples/2_Cookbook/3_shared_memory/Makefile b/projects/hip/samples/2_Cookbook/3_shared_memory/Makefile deleted file mode 100644 index bbd7daace3..0000000000 --- a/projects/hip/samples/2_Cookbook/3_shared_memory/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = sharedMemory.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./sharedMemory - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o - diff --git a/projects/hip/samples/2_Cookbook/3_shared_memory/Readme.md b/projects/hip/samples/2_Cookbook/3_shared_memory/Readme.md deleted file mode 100644 index 756cb6e7f2..0000000000 --- a/projects/hip/samples/2_Cookbook/3_shared_memory/Readme.md +++ /dev/null @@ -1,42 +0,0 @@ -## Using shared memory ### - -Earlier we learned how to write our first hip program, in which we compute Matrix Transpose. In this tutorial, we'll explain how to use the shared memory to improve the performance. - -## Introduction: - -As we mentioned earlier that Memory bottlenecks is the main problem why we are not able to get the highest performance, therefore minimizing the latency for memory access plays prominent role in application optimization. In this tutorial, we'll learn how to use static shared memory and will explain the dynamic one latter. - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -We will be using the Simple Matrix Transpose application from the previous tutorial and modify it to learn how to use shared memory. - -## Shared Memory - -Shared memory is way more faster than that of global and constant memory and accessible to all the threads in the block. If the size of shared memory is known at compile time, we can specify the size and will use the static shared memory. In the same sourcecode, we will use the `__shared__` variable type qualifier as follows: - -` __shared__ float sharedMem[1024*1024];` - -Be careful while using shared memory, since all threads within the block can access the shared memory, we need to sync the operation of individual threads by using: - -` __syncthreads();` - -## How to build and run: -Use the make command and execute it using ./exe -Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia. - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/3_shared_memory/sharedMemory.cpp b/projects/hip/samples/2_Cookbook/3_shared_memory/sharedMemory.cpp deleted file mode 100644 index 8bd489dbf3..0000000000 --- a/projects/hip/samples/2_Cookbook/3_shared_memory/sharedMemory.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - - -#define WIDTH 64 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - __shared__ float sharedMem[WIDTH * WIDTH]; - - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - sharedMem[y * width + x] = in[x * width + y]; - - __syncthreads(); - - out[y * width + x] = sharedMem[y * width + x]; -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix, - gpuMatrix, WIDTH); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - printf("%d cpu: %f gpu %f\n", i, cpuTransposeMatrix[i], TransposeMatrix[i]); - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/4_shfl/CMakeLists.txt b/projects/hip/samples/2_Cookbook/4_shfl/CMakeLists.txt deleted file mode 100644 index 394d5852fb..0000000000 --- a/projects/hip/samples/2_Cookbook/4_shfl/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(shfl) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_BUILD_TYPE Release) - -# Create the excutable -add_executable(shfl shfl.cpp) - -# Link with HIP -target_link_libraries(shfl hip::host) diff --git a/projects/hip/samples/2_Cookbook/4_shfl/Makefile b/projects/hip/samples/2_Cookbook/4_shfl/Makefile deleted file mode 100644 index de94a3e546..0000000000 --- a/projects/hip/samples/2_Cookbook/4_shfl/Makefile +++ /dev/null @@ -1,62 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -ifeq (gfx701, $(findstring gfx701,$(HCC_AMDGPU_TARGET))) - $(error gfx701 is not a supported device for this sample) -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = shfl.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./shfl - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o diff --git a/projects/hip/samples/2_Cookbook/4_shfl/Readme.md b/projects/hip/samples/2_Cookbook/4_shfl/Readme.md deleted file mode 100644 index ac5dff9292..0000000000 --- a/projects/hip/samples/2_Cookbook/4_shfl/Readme.md +++ /dev/null @@ -1,53 +0,0 @@ -## Warp shfl operations ### - -In this tutorial, we'll explain how to use the warp shfl operations to improve the performance. - -## Introduction: - -Let's talk about Warp first. The kernel code is executed in groups of fixed number of threads known as Warp. For nvidia WarpSize is 32 while for AMD, 32 for Polaris architecture and 64 for rest. Threads in a warp are referred to as lanes and are numbered from 0 to warpSize -1. With the help of shfl ops, we can directly exchange values of variable between threads without using any memory ops within a warp. There are four types of shfl ops: -``` - int __shfl (int var, int srcLane, int width=warpSize); - float __shfl (float var, int srcLane, int width=warpSize); - int __shfl_up (int var, unsigned int delta, int width=warpSize); - float __shfl_up (float var, unsigned int delta, int width=warpSize); - int __shfl_down (int var, unsigned int delta, int width=warpSize); - float __shfl_down (float var, unsigned int delta, int width=warpSize); - int __shfl_xor (int var, int laneMask, int width=warpSize) - float __shfl_xor (float var, int laneMask, int width=warpSize); -``` - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -We will be using the Simple Matrix Transpose application from the previous tutorial and modify it to learn how to use shared memory. - -## __shfl ops - -In this tutorial, we'll use `__shfl()` ops. In the same sourcecode, we used for MatrixTranspose. We'll add the following: - -` out[i*width + j] = __shfl(val,j*width + i);` - -Be careful while using shfl operations, since all exchanges are possible between the threads of corresponding warp only. - -## How to build and run: -Use the make command and execute it using ./exe -Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia. - -## requirement for nvidia -please make sure you have a 3.0 or higher compute capable device in order to use warp shfl operations and add `-gencode arch=compute=30, code=sm_30` nvcc flag in the Makefile while using this application. - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/4_shfl/shfl.cpp b/projects/hip/samples/2_Cookbook/4_shfl/shfl.cpp deleted file mode 100644 index de1ff7a950..0000000000 --- a/projects/hip/samples/2_Cookbook/4_shfl/shfl.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - - -#define WIDTH 4 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - int x = blockDim.x * blockIdx.x + threadIdx.x; - - float val = in[x]; - - for (int i = 0; i < width; i++) { - for (int j = 0; j < width; j++) out[i * width + j] = __shfl(val, j * width + i); - } -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(1), dim3(THREADS_PER_BLOCK_X * THREADS_PER_BLOCK_Y), 0, 0, - gpuTransposeMatrix, gpuMatrix, WIDTH); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - printf("%d cpu: %f gpu %f\n", i, cpuTransposeMatrix[i], TransposeMatrix[i]); - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/5_2dshfl/2dshfl.cpp b/projects/hip/samples/2_Cookbook/5_2dshfl/2dshfl.cpp deleted file mode 100644 index 269ad58383..0000000000 --- a/projects/hip/samples/2_Cookbook/5_2dshfl/2dshfl.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - - -#define WIDTH 4 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - float val = in[y * width + x]; - - out[x * width + y] = __shfl(val, y * width + x); -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(1), dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, - gpuTransposeMatrix, gpuMatrix, WIDTH); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - printf("%d cpu: %f gpu %f\n", i, cpuTransposeMatrix[i], TransposeMatrix[i]); - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/5_2dshfl/CMakeLists.txt b/projects/hip/samples/2_Cookbook/5_2dshfl/CMakeLists.txt deleted file mode 100644 index d0ab52859d..0000000000 --- a/projects/hip/samples/2_Cookbook/5_2dshfl/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(2dshfl) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(2dshfl 2dshfl.cpp) - -# Link with HIP -target_link_libraries(2dshfl hip::host) diff --git a/projects/hip/samples/2_Cookbook/5_2dshfl/Makefile b/projects/hip/samples/2_Cookbook/5_2dshfl/Makefile deleted file mode 100644 index 91afcfc53a..0000000000 --- a/projects/hip/samples/2_Cookbook/5_2dshfl/Makefile +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -ifeq (gfx701, $(findstring gfx701,$(HCC_AMDGPU_TARGET))) - $(error gfx701 is not a supported device for this sample) -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = 2dshfl.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./2dshfl - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o - diff --git a/projects/hip/samples/2_Cookbook/5_2dshfl/Readme.md b/projects/hip/samples/2_Cookbook/5_2dshfl/Readme.md deleted file mode 100644 index 0419ef736c..0000000000 --- a/projects/hip/samples/2_Cookbook/5_2dshfl/Readme.md +++ /dev/null @@ -1,55 +0,0 @@ -## Warp shfl operations in 2D ### - -This tutorial is follow-up of the previous tutorial, where we learned how to use shfl ops. In this tutorial, we'll explain how to scale similar kind of operations to multi-dimensional space by using previous tutorial source-code. - -## Introduction: - -Let's talk about Warp first. The kernel code is executed in groups of fixed number of threads known as Warp. For nvidia WarpSize is 32 while for AMD, 32 for Polaris architecture and 64 for rest. Threads in a warp are referred to as lanes and are numbered from 0 to warpSize -1. With the help of shfl ops, we can directly exchange values of variable between threads without using any memory ops within a warp. There are four types of shfl ops: -``` - int __shfl (int var, int srcLane, int width=warpSize); - float __shfl (float var, int srcLane, int width=warpSize); - int __shfl_up (int var, unsigned int delta, int width=warpSize); - float __shfl_up (float var, unsigned int delta, int width=warpSize); - int __shfl_down (int var, unsigned int delta, int width=warpSize); - float __shfl_down (float var, unsigned int delta, int width=warpSize); - int __shfl_xor (int var, int laneMask, int width=warpSize); - float __shfl_xor (float var, int laneMask, int width=warpSize); -``` - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -We will be using the Simple Matrix Transpose application from the previous tutorial and modify it to learn how to use shared memory. - -## __shfl ops in 2D - -In the same sourcecode, we used for MatrixTranspose. We'll add the following: -``` - int y = blockDim.y * blockIdx.y + threadIdx.y; - out[x*width + y] = __shfl(val,y*width + x); -``` - -With the help of this application, we can say that kernel code can be converted into multi-dimensional threads with ease. - -## How to build and run: -Use the make command and execute it using ./exe -Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia. - -## requirement for nvidia -please make sure you have a 3.0 or higher compute capable device in order to use warp shfl operations and add `-gencode arch=compute=30, code=sm_30` nvcc flag in the Makefile while using this application. - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/6_dynamic_shared/CMakeLists.txt b/projects/hip/samples/2_Cookbook/6_dynamic_shared/CMakeLists.txt deleted file mode 100644 index 73c4fe621b..0000000000 --- a/projects/hip/samples/2_Cookbook/6_dynamic_shared/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(dynamic_shared) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(dynamic_shared dynamic_shared.cpp) - -# Link with HIP -target_link_libraries(dynamic_shared hip::host) diff --git a/projects/hip/samples/2_Cookbook/6_dynamic_shared/Makefile b/projects/hip/samples/2_Cookbook/6_dynamic_shared/Makefile deleted file mode 100644 index d95ca76085..0000000000 --- a/projects/hip/samples/2_Cookbook/6_dynamic_shared/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = dynamic_shared.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./dynamic_shared - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o - diff --git a/projects/hip/samples/2_Cookbook/6_dynamic_shared/Readme.md b/projects/hip/samples/2_Cookbook/6_dynamic_shared/Readme.md deleted file mode 100644 index 02a8cb3da2..0000000000 --- a/projects/hip/samples/2_Cookbook/6_dynamic_shared/Readme.md +++ /dev/null @@ -1,52 +0,0 @@ -## Using Dynamic shared memory ### - -Earlier we learned how to use static shared memory. In this tutorial, we'll explain how to use the dynamic version of shared memory to improve the performance. - -## Introduction: - -As we mentioned earlier that Memory bottlenecks is the main problem why we are not able to get the highest performance, therefore minimizing the latency for memory access plays prominent role in application optimization. In this tutorial, we'll learn how to use dynamic shared memory. - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -We will be using the Simple Matrix Transpose application from the previous tutorial and modify it to learn how to use shared memory. - -## Shared Memory - -Shared memory is way more faster than that of global and constant memory and accessible to all the threads in the block. - -Previously, it was essential to declare dynamic shared memory using the HIP_DYNAMIC_SHARED macro for accuracy, as using static shared memory in the same kernel could result in overlapping memory ranges and data-races. - -Now, the HIP-Clang compiler provides support for extern shared declarations, and the HIP_DYNAMIC_SHARED option is no longer required. You may use the standard extern definition: -extern __shared__ type var[]; - - -The other important change is: -``` - hipLaunchKernelGGL(matrixTranspose, - dim3(WIDTH/THREADS_PER_BLOCK_X, WIDTH/THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), - sizeof(float)*WIDTH*WIDTH, 0, - gpuTransposeMatrix , gpuMatrix, WIDTH); -``` -here we replaced 4th parameter with amount of additional shared memory to allocate when launching the kernel. - -## How to build and run: -Use the make command and execute it using ./exe -Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia. - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/6_dynamic_shared/dynamic_shared.cpp b/projects/hip/samples/2_Cookbook/6_dynamic_shared/dynamic_shared.cpp deleted file mode 100644 index 531d94c5be..0000000000 --- a/projects/hip/samples/2_Cookbook/6_dynamic_shared/dynamic_shared.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - -#define WIDTH 16 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - extern __shared__ float sharedMem[]; - - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - sharedMem[y * width + x] = in[x * width + y]; - - __syncthreads(); - - out[y * width + x] = sharedMem[y * width + x]; -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - -int main() { - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - int i; - int errors; - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), sizeof(float) * WIDTH * WIDTH, - 0, gpuTransposeMatrix, gpuMatrix, WIDTH); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - errors = 0; - double eps = 1.0E-6; - for (i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - printf("%d cpu: %f gpu %f\n", i, cpuTransposeMatrix[i], TransposeMatrix[i]); - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("dynamic_shared PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - return errors; -} diff --git a/projects/hip/samples/2_Cookbook/7_streams/CMakeLists.txt b/projects/hip/samples/2_Cookbook/7_streams/CMakeLists.txt deleted file mode 100644 index 2d95541905..0000000000 --- a/projects/hip/samples/2_Cookbook/7_streams/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(stream) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(stream stream.cpp) - -# Link with HIP -target_link_libraries(stream hip::host) diff --git a/projects/hip/samples/2_Cookbook/7_streams/Makefile b/projects/hip/samples/2_Cookbook/7_streams/Makefile deleted file mode 100644 index 70dcd4c879..0000000000 --- a/projects/hip/samples/2_Cookbook/7_streams/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = stream.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./stream - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o - diff --git a/projects/hip/samples/2_Cookbook/7_streams/Readme.md b/projects/hip/samples/2_Cookbook/7_streams/Readme.md deleted file mode 100644 index 14b6a9762a..0000000000 --- a/projects/hip/samples/2_Cookbook/7_streams/Readme.md +++ /dev/null @@ -1,63 +0,0 @@ -## Streams ### - -In all Earlier tutorial we used single stream, In this tutorial, we'll explain how to launch multiple streams. - -## Introduction: - -The various instances of kernel to be executed on device in exact launch order defined by Host are called streams. We can launch multiple streams on a single device. We will learn how to learn two streams which can we scaled with ease. - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -We will be using the Simple Matrix Transpose application from the previous tutorial and modify it to learn how to launch multiple streams. - -## Streams - -In this tutorial, we'll use both instances of shared memory (i.e., static and dynamic) as different streams. We declare stream as follows: -` hipStream_t streams[num_streams]; ` - -and create stream using `hipStreamCreate` as follows: -``` -for(int i=0;i -#include - -#define WIDTH 32 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -using namespace std; - -__global__ void matrixTranspose_static_shared(float* out, float* in, - const int width) { - __shared__ float sharedMem[WIDTH * WIDTH]; - - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - sharedMem[y * width + x] = in[x * width + y]; - - __syncthreads(); - - out[y * width + x] = sharedMem[y * width + x]; -} - -__global__ void matrixTranspose_dynamic_shared(float* out, float* in, - const int width) { - extern __shared__ float sharedMem[]; - - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - sharedMem[y * width + x] = in[x * width + y]; - - __syncthreads(); - - out[y * width + x] = sharedMem[y * width + x]; -} - -void MultipleStream(float** data, float* randArray, float** gpuTransposeMatrix, - float** TransposeMatrix, int width) { - const int num_streams = 2; - hipStream_t streams[num_streams]; - - for (int i = 0; i < num_streams; i++) hipStreamCreate(&streams[i]); - - for (int i = 0; i < num_streams; i++) { - hipMalloc((void**)&data[i], NUM * sizeof(float)); - hipMemcpyAsync(data[i], randArray, NUM * sizeof(float), hipMemcpyHostToDevice, streams[i]); - } - - hipLaunchKernelGGL(matrixTranspose_static_shared, - dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, streams[0], - gpuTransposeMatrix[0], data[0], width); - - hipLaunchKernelGGL(matrixTranspose_dynamic_shared, - dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), sizeof(float) * WIDTH * WIDTH, - streams[1], gpuTransposeMatrix[1], data[1], width); - - for (int i = 0; i < num_streams; i++) - hipMemcpyAsync(TransposeMatrix[i], gpuTransposeMatrix[i], NUM * sizeof(float), - hipMemcpyDeviceToHost, streams[i]); -} - -int main() { - hipSetDevice(0); - - float *data[2], *TransposeMatrix[2], *gpuTransposeMatrix[2], *randArray; - - int width = WIDTH; - - randArray = (float*)malloc(NUM * sizeof(float)); - - TransposeMatrix[0] = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix[1] = (float*)malloc(NUM * sizeof(float)); - - hipMalloc((void**)&gpuTransposeMatrix[0], NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix[1], NUM * sizeof(float)); - - for (int i = 0; i < NUM; i++) { - randArray[i] = (float)i * 1.0f; - } - - MultipleStream(data, randArray, gpuTransposeMatrix, TransposeMatrix, width); - - hipDeviceSynchronize(); - - // verify the results - int errors = 0; - double eps = 1.0E-6; - for (int i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[0][i] - TransposeMatrix[1][i]) > eps) { - printf("%d stream0: %f stream1 %f\n", i, TransposeMatrix[0][i], TransposeMatrix[1][i]); - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("stream PASSED!\n"); - } - - free(randArray); - for (int i = 0; i < 2; i++) { - hipFree(data[i]); - hipFree(gpuTransposeMatrix[i]); - free(TransposeMatrix[i]); - } - - hipDeviceReset(); - return 0; -} diff --git a/projects/hip/samples/2_Cookbook/8_peer2peer/CMakeLists.txt b/projects/hip/samples/2_Cookbook/8_peer2peer/CMakeLists.txt deleted file mode 100644 index ad34ee44df..0000000000 --- a/projects/hip/samples/2_Cookbook/8_peer2peer/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(peer2peer) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(peer2peer peer2peer.cpp) - -# Link with HIP -target_link_libraries(peer2peer hip::host) diff --git a/projects/hip/samples/2_Cookbook/8_peer2peer/Makefile b/projects/hip/samples/2_Cookbook/8_peer2peer/Makefile deleted file mode 100644 index 4112c75696..0000000000 --- a/projects/hip/samples/2_Cookbook/8_peer2peer/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2016 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = peer2peer.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./peer2peer - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o - diff --git a/projects/hip/samples/2_Cookbook/8_peer2peer/peer2peer.cpp b/projects/hip/samples/2_Cookbook/8_peer2peer/peer2peer.cpp deleted file mode 100644 index 6b5c390b17..0000000000 --- a/projects/hip/samples/2_Cookbook/8_peer2peer/peer2peer.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANUMTY OF ANY KIND, EXPRESS OR -IMPLIED, INUMCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNUMESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANUMY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER INUM AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR INUM CONUMECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include -#include -#include -#define WIDTH 32 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -using namespace std; - -#define KNRM "\x1B[0m" -#define KRED "\x1B[31m" - -#define failed(...) \ - printf("%serror: ", KRED); \ - printf(__VA_ARGS__); \ - printf("\n"); \ - printf("error: TEST FAILED\n%s", KNRM); \ - abort(); - -#define HIPCHECK(error) \ - { \ - hipError_t localError = error; \ - if ((localError != hipSuccess)&& (localError != hipErrorPeerAccessAlreadyEnabled)&& \ - (localError != hipErrorPeerAccessNotEnabled )) { \ - printf("%serror: '%s'(%d) from %s at %s:%d%s\n", KRED, hipGetErrorString(localError), \ - localError, #error, __FILE__, __LINE__, KNRM); \ - failed("API returned error code."); \ - } \ - } - -void checkPeer2PeerSupport() { - int gpuCount; - int canAccessPeer; - - HIPCHECK(hipGetDeviceCount(&gpuCount)); - - for (int currentGpu = 0; currentGpu < gpuCount; currentGpu++) { - HIPCHECK(hipSetDevice(currentGpu)); - - for (int peerGpu = 0; peerGpu < currentGpu; peerGpu++) { - if (currentGpu != peerGpu) { - HIPCHECK(hipDeviceCanAccessPeer(&canAccessPeer, currentGpu, peerGpu)); - printf("currentGpu#%d canAccessPeer: peerGpu#%d=%d\n", currentGpu, peerGpu, - canAccessPeer); - } - - HIPCHECK(hipSetDevice(peerGpu)); - HIPCHECK(hipDeviceReset()); - } - HIPCHECK(hipSetDevice(currentGpu)); - HIPCHECK(hipDeviceReset()); - } -} - -void enablePeer2Peer(int currentGpu, int peerGpu) { - int canAccessPeer; - - // Must be on a multi-gpu system: - assert(currentGpu != peerGpu); - - HIPCHECK(hipSetDevice(currentGpu)); - hipDeviceCanAccessPeer(&canAccessPeer, currentGpu, peerGpu); - - if (canAccessPeer == 1) { - HIPCHECK(hipDeviceEnablePeerAccess(peerGpu, 0)); - } else - printf("peer2peer transfer not possible between the selected gpu devices"); -} - -void disablePeer2Peer(int currentGpu, int peerGpu) { - int canAccessPeer; - - // Must be on a multi-gpu system: - assert(currentGpu != peerGpu); - - HIPCHECK(hipSetDevice(currentGpu)); - hipDeviceCanAccessPeer(&canAccessPeer, currentGpu, peerGpu); - - if (canAccessPeer == 1) { - HIPCHECK(hipDeviceDisablePeerAccess(peerGpu)); - } else - printf("peer2peer disable not required"); -} - - -__global__ void matrixTranspose_static_shared(float* out, float* in, - const int width) { - __shared__ float sharedMem[WIDTH * WIDTH]; - - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - sharedMem[y * width + x] = in[x * width + y]; - - __syncthreads(); - - out[y * width + x] = sharedMem[y * width + x]; -} - -__global__ void matrixTranspose_dynamic_shared(float* out, float* in, - const int width) { - extern __shared__ float sharedMem[]; - - int x = blockDim.x * blockIdx.x + threadIdx.x; - int y = blockDim.y * blockIdx.y + threadIdx.y; - - sharedMem[y * width + x] = in[x * width + y]; - - __syncthreads(); - - out[y * width + x] = sharedMem[y * width + x]; -} - -int main() { - checkPeer2PeerSupport(); - - int gpuCount; - int currentGpu, peerGpu; - - HIPCHECK(hipGetDeviceCount(&gpuCount)); - - if (gpuCount < 2) { - printf("Peer2Peer application requires atleast 2 gpu devices"); - return 0; - } - - currentGpu = 0; - peerGpu = (currentGpu + 1); - - printf("currentGpu=%d peerGpu=%d (Total no. of gpu = %d)\n", currentGpu, peerGpu, gpuCount); - - float *data[2], *TransposeMatrix[2], *gpuTransposeMatrix[2], *randArray; - - int width = WIDTH; - - randArray = (float*)malloc(NUM * sizeof(float)); - - for (int i = 0; i < NUM; i++) { - randArray[i] = (float)i * 1.0f; - } - - enablePeer2Peer(currentGpu, peerGpu); - - HIPCHECK(hipSetDevice(currentGpu)); - TransposeMatrix[0] = (float*)malloc(NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix[0], NUM * sizeof(float)); - hipMalloc((void**)&data[0], NUM * sizeof(float)); - hipMemcpy(data[0], randArray, NUM * sizeof(float), hipMemcpyHostToDevice); - - hipLaunchKernelGGL(matrixTranspose_static_shared, - dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix[0], - data[0], width); - HIPCHECK(hipDeviceSynchronize()); - - HIPCHECK(hipSetDevice(peerGpu)); - TransposeMatrix[1] = (float*)malloc(NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix[1], NUM * sizeof(float)); - hipMalloc((void**)&data[1], NUM * sizeof(float)); - hipMemcpy(data[1], gpuTransposeMatrix[0], NUM * sizeof(float), hipMemcpyDeviceToDevice); - - hipLaunchKernelGGL(matrixTranspose_dynamic_shared, - dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), sizeof(float) * WIDTH * WIDTH, - 0, gpuTransposeMatrix[1], data[1], width); - - hipMemcpy(TransposeMatrix[1], gpuTransposeMatrix[1], NUM * sizeof(float), - hipMemcpyDeviceToHost); - - hipDeviceSynchronize(); - - disablePeer2Peer(currentGpu, peerGpu); - - // verify the results - int errors = 0; - double eps = 1.0E-6; - for (int i = 0; i < NUM; i++) { - if (std::abs(randArray[i] - TransposeMatrix[1][i]) > eps) { - printf("%d cpu: %f gpu peered data %f\n", i, randArray[i], TransposeMatrix[1][i]); - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("Peer2Peer PASSED!\n"); - } - - free(randArray); - for (int i = 0; i < 2; i++) { - hipFree(data[i]); - hipFree(gpuTransposeMatrix[i]); - free(TransposeMatrix[i]); - } - - HIPCHECK(hipSetDevice(peerGpu)); - HIPCHECK(hipDeviceReset()); - - HIPCHECK(hipSetDevice(currentGpu)); - HIPCHECK(hipDeviceReset()); - - return 0; -} diff --git a/projects/hip/samples/2_Cookbook/9_unroll/CMakeLists.txt b/projects/hip/samples/2_Cookbook/9_unroll/CMakeLists.txt deleted file mode 100644 index 258138f2b9..0000000000 --- a/projects/hip/samples/2_Cookbook/9_unroll/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -project(unroll) - -cmake_minimum_required(VERSION 3.10) - -if (NOT DEFINED ROCM_PATH ) - set ( ROCM_PATH "/opt/rocm" CACHE STRING "Default ROCM installation directory." ) -endif () - -# Search for rocm in common locations -list(APPEND CMAKE_PREFIX_PATH ${ROCM_PATH}/hip ${ROCM_PATH}) - -# Find hip -find_package(hip) - -# Set compiler and linker -set(CMAKE_CXX_COMPILER ${HIP_HIPCC_EXECUTABLE}) -set(CMAKE_CXX_LINKER ${HIP_HIPCC_EXECUTABLE}) - -# Create the excutable -add_executable(unroll unroll.cpp) - -# Link with HIP -target_link_libraries(unroll hip::host) diff --git a/projects/hip/samples/2_Cookbook/9_unroll/Makefile b/projects/hip/samples/2_Cookbook/9_unroll/Makefile deleted file mode 100644 index 657f879ac5..0000000000 --- a/projects/hip/samples/2_Cookbook/9_unroll/Makefile +++ /dev/null @@ -1,62 +0,0 @@ -# Copyright (c) 2017 - 2021 Advanced Micro Devices, Inc. All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -ifeq ($(OS),Windows_NT) - $(error Makefile is not supported on windows platform. Please use cmake instead to build sample.) -endif -ROCM_PATH?= $(wildcard /opt/rocm/) -HIP_PATH?= $(wildcard $(ROCM_PATH)/hip) -ifeq (,$(HIP_PATH)) - HIP_PATH=../../.. -endif - -ifeq (gfx701, $(findstring gfx701,$(HCC_AMDGPU_TARGET))) - $(error gfx701 is not a supported device for this sample) -endif - -HIPCC=$(HIP_PATH)/bin/hipcc - -TARGET=hcc - -SOURCES = unroll.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./unroll - -.PHONY: test - - -all: $(EXECUTABLE) test - -CXXFLAGS =-g -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -test: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o diff --git a/projects/hip/samples/2_Cookbook/9_unroll/Readme.md b/projects/hip/samples/2_Cookbook/9_unroll/Readme.md deleted file mode 100644 index 6fad55e3c9..0000000000 --- a/projects/hip/samples/2_Cookbook/9_unroll/Readme.md +++ /dev/null @@ -1,48 +0,0 @@ -## Using Pragma unroll ### - -In this tutorial, we'll explain how to use #pragma unroll to improve the performance. - -## Introduction: - -Loop unrolling optimization hints can be specified with #pragma unroll and #pragma nounroll. The pragma is placed immediately before a for loop. -Specifying #pragma unroll without a parameter directs the loop unroller to attempt to fully unroll the loop if the trip count is known at compile time and attempt to partially unroll the loop if the trip count is not known at compile time. - -## Requirement: -For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -For this tutorial we will be using an example which sums up the row of a 2D matrix and writes it in a 1D array. - -In this tutorial, we'll use `#pragma unroll`. In the same sourcecode, we used for gpuMatrixRowSum. We'll add it just before the for loop as following: - -``` -#pragma unroll -for (int i = 0; i < width; i++) { - output[index] += input[index * width + i] -} -``` - -Specifying the optional parameter, #pragma unroll value, directs the unroller to unroll the loop value times. Be careful while using it. -Specifying #pragma nounroll indicates that the loop should not be unroll. #pragma unroll 1 will show the same behaviour. - -## How to build and run: -Use the make command and execute it using ./exe -Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia. - -## requirement for nvidia -please make sure you have a 3.0 or higher compute capable device in order to use warp shfl operations and add `-gencode arch=compute=30, code=sm_30` nvcc flag in the Makefile while using this application. - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md) diff --git a/projects/hip/samples/2_Cookbook/9_unroll/unroll.cpp b/projects/hip/samples/2_Cookbook/9_unroll/unroll.cpp deleted file mode 100644 index 18f910a5dd..0000000000 --- a/projects/hip/samples/2_Cookbook/9_unroll/unroll.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" - -#define LENGTH 4 - -#define SIZE (LENGTH * LENGTH) - -#define THREADS_PER_BLOCK 1 -#define BLOCKS_PER_GRID LENGTH - -// CPU function - basically scan each row and save the output in array -void matrixRowSum(int* input, int* output, int width) { - for (int i = 0; i < width; i++) { - for (int j = 0; j < width; j++) { - output[i] += input[i * width + j]; - } - } -} - -// Device (kernel) function -__global__ void gpuMatrixRowSum(int* input, int* output, int width) { - int index = blockDim.x * blockIdx.x + threadIdx.x; -#pragma unroll - for (int i = 0; i < width; i++) { - output[index] += input[index * width + i]; - } -} - -int main() { - int* Matrix; - int* sumMatrix; - int* cpuSumMatrix; - - int* gpuMatrix; - int* gpuSumMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - Matrix = (int*)malloc(sizeof(int) * SIZE); - sumMatrix = (int*)malloc(sizeof(int) * LENGTH); - cpuSumMatrix = (int*)malloc(sizeof(int) * LENGTH); - - for (int i = 0; i < SIZE; i++) { - Matrix[i] = i * 2; - } - - for (int i = 0; i < LENGTH; i++) { - cpuSumMatrix[i] = 0; - } - - // Allocated Device Memory - hipMalloc((void**)&gpuMatrix, SIZE * sizeof(int)); - hipMalloc((void**)&gpuSumMatrix, LENGTH * sizeof(int)); - - // Memory Copy to Device - hipMemcpy(gpuMatrix, Matrix, SIZE * sizeof(int), hipMemcpyHostToDevice); - hipMemcpy(gpuSumMatrix, cpuSumMatrix, LENGTH * sizeof(float), hipMemcpyHostToDevice); - - // Launch device kernels - hipLaunchKernelGGL(gpuMatrixRowSum, dim3(BLOCKS_PER_GRID), dim3(THREADS_PER_BLOCK), 0, 0, - gpuMatrix, gpuSumMatrix, LENGTH); - - // Memory copy back to device - hipMemcpy(sumMatrix, gpuSumMatrix, LENGTH * sizeof(int), hipMemcpyDeviceToHost); - - // Cpu implementation - matrixRowSum(Matrix, cpuSumMatrix, LENGTH); - - - // verify the results - int errors = 0; - for (int i = 0; i < LENGTH; i++) { - if (sumMatrix[i] != cpuSumMatrix[i]) { - printf("%d - cpu: %d gpu: %d\n", i, sumMatrix[i], cpuSumMatrix[i]); - errors++; - } - } - - if (errors == 0) { - printf("PASSED\n"); - } else { - printf("FAILED with %d errors\n", errors); - } - - // GPU Free - hipFree(gpuMatrix); - hipFree(gpuSumMatrix); - - // CPU Free - free(Matrix); - free(sumMatrix); - free(cpuSumMatrix); - - return errors; -} diff --git a/projects/hip/samples/README.md b/projects/hip/samples/README.md deleted file mode 100644 index ac4bd1ca94..0000000000 --- a/projects/hip/samples/README.md +++ /dev/null @@ -1,33 +0,0 @@ -Build procedure - -We provide Makefile and CMakeLists.txt to build the samples seperately. - -1.Makefile supports shared lib of hip-rocclr runtime and nvcc. - -To build a sample, just type in sample folder, - -make - - - -2.CMakeLists.txt can support shared and static libs of hip-rocclr runtime. - -To build a sample, run in the sample folder, - -mkdir -p build && cd build - -rm -rf * (to clear up) - -a. to build with shared libs, run - -cmake .. - -b. to build with static libs, run - -cmake -DCMAKE_PREFIX_PATH="/llvm/lib/cmake" .. - -Then run, - -make - -Note that if you want debug version, add "-DCMAKE_BUILD_TYPE=Debug" in cmake cmd. \ No newline at end of file diff --git a/projects/hip/tests/catch/ABM/AddKernels/CMakeLists.txt b/projects/hip/tests/catch/ABM/AddKernels/CMakeLists.txt deleted file mode 100644 index 776f0fa5f1..0000000000 --- a/projects/hip/tests/catch/ABM/AddKernels/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -# Common Tests - Test independent of all platforms -set(TEST_SRC - add.cc -) - -hip_add_exe_to_target(NAME ABMAddKernels - TEST_SRC ${TEST_SRC} - TEST_TARGET_NAME build_tests) diff --git a/projects/hip/tests/catch/ABM/AddKernels/add.cc b/projects/hip/tests/catch/ABM/AddKernels/add.cc deleted file mode 100644 index 1b7c56cdfa..0000000000 --- a/projects/hip/tests/catch/ABM/AddKernels/add.cc +++ /dev/null @@ -1,41 +0,0 @@ -#include -#include - -template __global__ void add(T* a, T* b, T* c, size_t size) { - size_t i = threadIdx.x; - if (i < size) c[i] = a[i] + b[i]; -} - -TEMPLATE_TEST_CASE("ABM_AddKernel_MultiTypeMultiSize", "", int, long, float, long long, double) { - auto size = GENERATE(as{}, 100, 500, 1000); - TestType *d_a, *d_b, *d_c; - auto res = hipMalloc(&d_a, sizeof(TestType) * size); - REQUIRE(res == hipSuccess); - res = hipMalloc(&d_b, sizeof(TestType) * size); - REQUIRE(res == hipSuccess); - res = hipMalloc(&d_c, sizeof(TestType) * size); - REQUIRE(res == hipSuccess); - - std::vector a, b, c; - for (size_t i = 0; i < size; i++) { - a.push_back(i + 1); - b.push_back(i + 1); - c.push_back(2 * (i + 1)); - } - - res = hipMemcpy(d_a, a.data(), sizeof(TestType) * size, hipMemcpyHostToDevice); - REQUIRE(res == hipSuccess); - res = hipMemcpy(d_b, b.data(), sizeof(TestType) * size, hipMemcpyHostToDevice); - REQUIRE(res == hipSuccess); - - hipLaunchKernelGGL(add, 1, size, 0, 0, d_a, d_b, d_c, size); - HIP_CHECK(hipGetLastError()); - - res = hipMemcpy(a.data(), d_c, sizeof(TestType) * size, hipMemcpyDeviceToHost); - REQUIRE(res == hipSuccess); - - HIP_CHECK(hipFree(d_a)); - HIP_CHECK(hipFree(d_b)); - HIP_CHECK(hipFree(d_c)); - REQUIRE(a == c); -} diff --git a/projects/hip/tests/catch/ABM/CMakeLists.txt b/projects/hip/tests/catch/ABM/CMakeLists.txt deleted file mode 100644 index 53fa9e8b0f..0000000000 --- a/projects/hip/tests/catch/ABM/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(AddKernels) diff --git a/projects/hip/tests/catch/CMakeLists.txt b/projects/hip/tests/catch/CMakeLists.txt deleted file mode 100644 index 3f6c992059..0000000000 --- a/projects/hip/tests/catch/CMakeLists.txt +++ /dev/null @@ -1,252 +0,0 @@ -cmake_minimum_required(VERSION 3.16.8) - -# to skip the simple compiler test -set(CMAKE_C_COMPILER_WORKS 1) -set(CMAKE_CXX_COMPILER_WORKS 1) - -project(hiptests) - - -# Check if platform and compiler are set -if(HIP_PLATFORM STREQUAL "amd") - if(HIP_COMPILER STREQUAL "nvcc") - message(FATAL_ERROR "Unexpected HIP_COMPILER:${HIP_COMPILER} is set for HIP_PLATFOR:amd") - endif() -elseif(HIP_PLATFORM STREQUAL "nvidia") - if(DEFINED HIP_COMPILER AND NOT HIP_COMPILER STREQUAL "nvcc") - message(FATAL_ERROR "Unexpected HIP_COMPILER: ${HIP_COMPILER} is set for HIP_PLATFORM:nvidia") - endif() -else() - message(FATAL_ERROR "Unexpected HIP_PLATFORM: " ${HIP_PLATFORM}) -endif() - -# Set HIP Path -if(NOT DEFINED HIP_PATH) - if(DEFINED ENV{HIP_PATH}) - set(HIP_PATH $ENV{HIP_PATH} CACHE STRING "HIP Path") - else() - set(HIP_PATH "${PROJECT_BINARY_DIR}") - endif() -endif() -message(STATUS "HIP Path: ${HIP_PATH}") - -# Set ROCM Path -if(NOT DEFINED ROCM_PATH) - if(DEFINED ENV{ROCM_PATH}) - set(ROCM_PATH $ENV{ROCM_PATH} CACHE STRING "ROCM Path") - else() - cmake_path(GET HIP_PATH PARENT_PATH ROCM_PATH) - if (NOT EXISTS "${ROCM_PATH}/bin/rocm_agent_enumerator") - set(ROCM_PATH "/opt/rocm/") - endif() - endif() -endif() -file(TO_CMAKE_PATH "${ROCM_PATH}" ROCM_PATH) -message(STATUS "ROCM Path: ${ROCM_PATH}") - - -if(UNIX) - set(CMAKE_CXX_COMPILER "${HIP_PATH}/bin/hipcc") - set(CMAKE_C_COMPILER "${HIP_PATH}/bin/hipcc") - set(HIPCONFIG_EXECUTABLE "${HIP_PATH}/bin/hipconfig") - execute_process(COMMAND perl ${HIPCONFIG_EXECUTABLE} --version - OUTPUT_VARIABLE HIP_VERSION - OUTPUT_STRIP_TRAILING_WHITESPACE) -else() - # using cmake_path as it handles path correctly. - # Set both compilers else windows cmake complains of mismatch - cmake_path(SET CMAKE_CXX_COMPILER "${HIP_PATH}/bin/hipcc.bat") - cmake_path(SET CMAKE_C_COMPILER "${HIP_PATH}/bin/hipcc.bat") - set(HIPCONFIG_EXECUTABLE "${HIP_PATH}/bin/hipconfig.bat") - execute_process(COMMAND ${HIPCONFIG_EXECUTABLE} --version - OUTPUT_VARIABLE HIP_VERSION - OUTPUT_STRIP_TRAILING_WHITESPACE) -endif() -if(HIP_PLATFORM STREQUAL "amd") - # prioritize -DROCM_PATH over env{ROCM_PATH} for amd platform only - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --rocm-path=${ROCM_PATH}") -endif() -# enforce c++17 -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++17") - -string(REPLACE "." ";" VERSION_LIST ${HIP_VERSION}) -list(GET VERSION_LIST 0 HIP_VERSION_MAJOR) -list(GET VERSION_LIST 1 HIP_VERSION_MINOR) -list(GET VERSION_LIST 2 HIP_VERSION_PATCH_GITHASH) -string(REPLACE "-" ";" VERSION_LIST ${HIP_VERSION_PATCH_GITHASH}) -list(GET VERSION_LIST 0 HIP_VERSION_PATCH) - -if(NOT DEFINED CATCH2_PATH) - if(DEFINED ENV{CATCH2_PATH}) - set(CATCH2_PATH $ENV{CATCH2_PATH} CACHE STRING "Catch2 Path") - else() - set(CATCH2_PATH "${CMAKE_CURRENT_LIST_DIR}/external/Catch2") - endif() -endif() -message(STATUS "Catch2 Path: ${CATCH2_PATH}") - -# Set JSON Parser path -if(NOT DEFINED JSON_PARSER) - if(DEFINED ENV{JSON_PARSER}) - set(JSON_PARSER $ENV{JSON_PARSER} CACHE STRING "JSON Parser Path") - else() - set(JSON_PARSER "${CMAKE_CURRENT_LIST_DIR}/external/picojson") - endif() -endif() - -message(STATUS "Searching Catch2 in: ${CMAKE_CURRENT_LIST_DIR}/external") -find_package(Catch2 REQUIRED - PATHS - ${CMAKE_CURRENT_LIST_DIR}/external - PATH_SUFFIXES - Catch2/cmake/Catch2 -) -include(Catch) -include(CTest) - -# path used for generating the *_include.cmake file -set(CATCH2_INCLUDE ${CATCH2_PATH}/cmake/Catch2/catch_include.cmake.in) - -include_directories( - ${CATCH2_PATH} - "./include" - "./kernels" - ${HIP_PATH}/include - ${JSON_PARSER} -) - -option(RTC_TESTING "Run tests using HIP RTC to compile the kernels" OFF) -if (RTC_TESTING) - add_definitions(-DRTC_TESTING=ON) -endif() -add_definitions(-DKERNELS_PATH="${CMAKE_CURRENT_SOURCE_DIR}/kernels/") - -set(CATCH_BUILD_DIR catch_tests) -file(COPY ./hipTestMain/config DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/${CATCH_BUILD_DIR}/hipTestMain) -file(COPY ./external/Catch2/cmake/Catch2/CatchAddTests.cmake - DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/${CATCH_BUILD_DIR}/script) -set(ADD_SCRIPT_PATH ${CMAKE_CURRENT_BINARY_DIR}/${CATCH_BUILD_DIR}/script/CatchAddTests.cmake) - -if (WIN32) - configure_file(catchProp_in_rc.in ${CMAKE_CURRENT_BINARY_DIR}/catchProp.rc @ONLY) - cmake_path(SET LLVM_RC_PATH "${HIP_PATH}/../lc/bin/llvm-rc.exe") - cmake_path(SET LLVM_RC_PATH NORMALIZE "${LLVM_RC_PATH}") - - # generates the .res files to be used by executables to populate the properties - # expects LC folder with clang, llvm-rc to be present one level up of HIP - execute_process(COMMAND ${LLVM_RC_PATH} ${CMAKE_CURRENT_BINARY_DIR}/catchProp.rc - OUTPUT_VARIABLE RC_OUTPUT) - set(PROP_RC ${CMAKE_CURRENT_BINARY_DIR}) -endif() - -if(HIP_PLATFORM MATCHES "amd" AND HIP_COMPILER MATCHES "clang") - add_compile_options(-Wall -Wextra -pedantic -Werror -Wno-deprecated) -endif() - -cmake_policy(PUSH) -if(POLICY CMP0037) - cmake_policy(SET CMP0037 OLD) -endif() - -# Turn off CMAKE_HIP_ARCHITECTURES Feature if cmake version is 3.21+ -if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.21.0) - set(CMAKE_HIP_ARCHITECTURES OFF) -endif() -message(STATUS "CMAKE HIP ARCHITECTURES: ${CMAKE_HIP_ARCHITECTURES}") - -# Note to pass arch use format like -DOFFLOAD_ARCH_STR="--offload-arch=gfx900 --offload-arch=gfx906" -# having space at the start/end of OFFLOAD_ARCH_STR can cause build failures -# Identify the GPU Targets. -# This is done due to limitation of rocm_agent_enumerator -# While building test parallelly, rocm_agent_enumerator can fail and give out an empty target -# That results in hipcc building the test for gfx803 (the default target) -# preference to pass arch - -# OFFLOAD_ARCH_STR -# ENV{HCC_AMDGPU_TARGET} -# rocm_agent_enumerator -if(NOT DEFINED OFFLOAD_ARCH_STR - AND NOT DEFINED ENV{HCC_AMDGPU_TARGET} - AND EXISTS "${ROCM_PATH}/bin/rocm_agent_enumerator" - AND HIP_PLATFORM STREQUAL "amd" AND UNIX) - execute_process(COMMAND ${ROCM_PATH}/bin/rocm_agent_enumerator - OUTPUT_VARIABLE HIP_GPU_ARCH - RESULT_VARIABLE ROCM_AGENT_ENUM_RESULT) - # Trim out gfx000 - string(REPLACE "gfx000\n" "" HIP_GPU_ARCH ${HIP_GPU_ARCH}) - if (NOT HIP_GPU_ARCH STREQUAL "") - string(LENGTH ${HIP_GPU_ARCH} HIP_GPU_ARCH_LEN) - # If string has more gfx target except gfx000 - if(${HIP_GPU_ARCH_LEN} GREATER_EQUAL 1) - string(REGEX REPLACE "\n" ";" HIP_GPU_ARCH_LIST "${HIP_GPU_ARCH}") - set(OFFLOAD_ARCH_STR "") - foreach(_hip_gpu_arch ${HIP_GPU_ARCH_LIST}) - set(OFFLOAD_ARCH_STR "--offload-arch=${_hip_gpu_arch} ${OFFLOAD_ARCH_STR}") - endforeach() - endif() - else() - message(STATUS "ROCm Agent Enumurator found no valid architectures") - endif() -elseif(DEFINED OFFLOAD_ARCH_STR) - string(REPLACE "--offload-arch=" "" HIP_GPU_ARCH_LIST ${OFFLOAD_ARCH_STR}) -endif() - -if(DEFINED OFFLOAD_ARCH_STR) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OFFLOAD_ARCH_STR} ") -elseif(DEFINED ENV{HCC_AMDGPU_TARGET}) - # hipcc pl script appends it to the options - set(OFFLOAD_ARCH_STR " --offload-arch=$ENV{HCC_AMDGPU_TARGET}") - set(HIP_GPU_ARCH_LIST $ENV{HCC_AMDGPU_TARGET}) -endif() -message(STATUS "Using offload arch string: ${OFFLOAD_ARCH_STR}") - -# prints the catch info to a file -string(TIMESTAMP _timestamp UTC) -set(_catchInfo "# Auto-generated by cmake on ${_timestamp} UTC\n") -set(_catchInfo ${_catchInfo} "HIP_VERSION=${HIP_VERSION}\n") -set(_catchInfo ${_catchInfo} "HIP_PLATFORM=${HIP_PLATFORM}\n") -set(_catchInfo ${_catchInfo} "ARCHS=${HIP_GPU_ARCH_LIST}\n") -file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/${CATCH_BUILD_DIR}/catchInfo.txt ${_catchInfo}) - -# Enable device lambda on nvidia platforms -if(HIP_COMPILER MATCHES "nvcc") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --extended-lambda") -endif() - -# Disable CXX extensions (gnu++11 etc) -set(CMAKE_CXX_EXTENSIONS OFF) - -add_custom_target(build_tests) - - -# Tests folder -add_subdirectory(unit ${CATCH_BUILD_DIR}/unit) -add_subdirectory(ABM ${CATCH_BUILD_DIR}/ABM) -add_subdirectory(kernels ${CATCH_BUILD_DIR}/kernels) -add_subdirectory(hipTestMain ${CATCH_BUILD_DIR}/hipTestMain) -add_subdirectory(stress ${CATCH_BUILD_DIR}/stress) -add_subdirectory(TypeQualifiers ${CATCH_BUILD_DIR}/TypeQualifiers) -if(UNIX) - add_subdirectory(multiproc ${CATCH_BUILD_DIR}/multiproc) -endif() - -cmake_policy(POP) - -# packaging the tests -# make package_test to generate packages for test -set(BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/packages/) -configure_file(packaging/hip-tests.txt ${BUILD_DIR}/CMakeLists.txt @ONLY) -if(UNIX) -add_custom_target(package_test COMMAND ${CMAKE_COMMAND} . - COMMAND rm -rf *.deb *.rpm *.tar.gz - COMMAND make package - COMMAND cp *.deb ${PROJECT_BINARY_DIR} - COMMAND cp *.rpm ${PROJECT_BINARY_DIR} - COMMAND cp *.tar.gz ${PROJECT_BINARY_DIR} - WORKING_DIRECTORY ${BUILD_DIR}) -else() -file(TO_NATIVE_PATH ${PROJECT_BINARY_DIR} CATCH_BINARY_DIR) -add_custom_target(package_test COMMAND ${CMAKE_COMMAND} . - COMMAND cpack - COMMAND copy *.zip ${CATCH_BINARY_DIR} - WORKING_DIRECTORY ${BUILD_DIR}) -endif() diff --git a/projects/hip/tests/catch/README.md b/projects/hip/tests/catch/README.md deleted file mode 100644 index 5688f558d4..0000000000 --- a/projects/hip/tests/catch/README.md +++ /dev/null @@ -1,204 +0,0 @@ -# HIP Tests - with Catch2 - -## Intro and Motivation -HIP Tests were using HIT framework (a custom framework tailored for HIP) to add, build and run tests. As time progressed the frame got big and took substantial amount of effort to maintain and extend. It also took substantial amount of time to configure. We took this oppurtunity to rewrite the HIP's testing framework and porting the test infra to Catch2 format. - -## How to write tests -Tests in Catch2 are declared via ```TEST_CASE```. - -[Please read the Catch2 documentation on how to write test cases](https://github.com/catchorg/Catch2/blob/v2.13.6/docs/tutorial.md#top) - -[Catch2 Detailed Reference](https://github.com/catchorg/Catch2/blob/v2.13.6/docs/Readme.md#top) - -## Taking care of existing features -- Don’t build on platform: EXCLUDE_(HIP_PLATFORM/HIP_RUNTIME), can be done via CMAKE. Adding source in if(HIP_PLATFORM == amd/nvidia). -- HIPCC_OPTIONS/CLANG Options: Can be done via: set_source_files_properties(src.cc PROPERTIES COMPILE_FLAGS “…”). -- Additional libraries: Can be done via target_link_libraries() -- Multiple runs with different args: This can be done by Catch’s Feature: GENERATE(…) -Running Subtest: ctest –R “...” (Regex to match the subtest name) - -## New Features -- Skip test without recompiling tests, by addition of a json file. Default name is ```config.json``` , this can be overridden by using the variable ```HIP_CATCH_EXCLUDE_FILE=some_config.json```. -- Json file supports regex. Ex: All tests which has the word ‘Memset’ can be skipped using ‘*Memset*’ -- Support multiple skip test list which can be set via environment variable, so you can have multiple files containing different skip test lists and can pick and choose among them depending on your platform and os. -- Better CI integration via xunit compatible output - -## Testing Context -HIP testing framework gives you a context for each test. This context will have useful information about the environment your test is running. - -Some useful functions are: -- `bool isWindows()` : true if os is windows -- `bool isLinux()` : true if os is linux -- `bool isAmd()` : true if platform is AMD -- `bool isNvidia()` : true if platform is NVIDIA - -This information can be accessed in any test via using: `TestContext::get().isAmd()`. - -## Adding test for a specific platform -There might be some functionality which is not present on some platforms. Those tests can be hidden inside following macros. - -- ```HT_AMD``` is 1 when tests are running on AMD platform and 0 on NVIDIA. -- ```HT_NVIDIA``` is 1 when tests are running on NVIDIA platform and 0 on AMD - -Usage: - -```cpp -#if HT_AMD -TEST_CASE("hipExtAPIs") { - // ... -} -#endif -``` - -## Config file schema -Some tests can be skipped using a config file placed in hipTestMain/config folder. Multiple config files can be defined for different configurations. -The naming convention for the file needs to be "config_platform_os_archname.json" -Platform and os are mandatory. -Arch name is optional and takes precedence while loading the json file. -Currently the json files need to be manually chosen by the executor for the architecture of choice. - -example: -config_amd_windows.json -config_nvidia_windows.json - -The schema of the json file is as follows: -```json -{ - "DisabledTests": - [ - "TestName1", - "TestName2", - ... - ] -} -``` - -## Environment Variables -- `HIP_CATCH_EXCLUDE_FILE` : This variable can be set to the config file name or full path. Disabled tests will be read from this. -- `HT_LOG_ENABLE` : This is for debugging the HIP Test Framework itself. Setting it to 1, all `LogPrintf` will be printed on screen - -## Test Macros -### Single Thread Macros -These macros are to be used when your test is calling HIP APIs via the main thread. - -- `HIP_CHECK` : This macro takes in a HIP API and tests for its result to be either ```hipSuccess``` or ```hipErrorPeerAccessAlreadyEnabled```. - - - Usage: ```HIP_CHECK(hipMalloc(&dPtr, 10));``` - -- ```HIP_CHECK_ERROR``` : This macro takes in a HIP API and tests its result against a provided result. This can be used when the API is expected to fail with a particular result. - - - Usage: ```HIP_CHECK_ERROR(hipMalloc(&dPtr, 0), hipErrorInvalidValue);``` - -- ```HIPRTC_CHECK``` : This macro takes in a HIPRTC API and tests its result against HIPRTC_SUCCESS. - - - Usage: ```HIPRTC_CHECK(hiprtcCompileProgram(prog, count, options));``` - -- ```HIP_ASSERT``` : This macro takes in a bool condition as input and does a ```REQUIRE``` on the condition. - - - Usage: ```HIP_ASSERT(result == 10);``` - -### Multi Thread Macros -These macros are to be used when you call HIP APIs in a multi threaded way. They exist because Catch2 ```REQUIRE``` and ```CHECK``` macros can not handle multi threaded calls. To solve this problem, two macros are added```HIP_CHECK_THREAD``` and ```REQUIRE_THREAD``` which can be used to check result of HIP APIs and test assertions respectively. The results can be validate after the threads join via ```HIP_CHECK_THREAD_FINALIZE```. - -Note: These should used in ```std::thread``` only. For multi proc guidelines look at [MultiProc Macros](#multi-process-macros) and [SpawnProc Class](#multiproc-management-class) - -- ```HIP_CHECK_THREAD``` : This macro takes in a HIP API and tests for its result to be either ```hipSuccess``` or ```hipErrorPeerAccessAlreadyEnabled```. It can also tell other threads if an error has occured in one of the HIP API and can prematurely stop the threads. - -- ```REQUIRE_THREAD``` : This macro takes in a bool condition and tests for its result to be true. If this check fails, it can signal other threads to terminate early. - -- ```HIP_CHECK_THREAD_FINALIZE``` : This macro checks for the results logged by ```HIP_CHECK_THREAD```. This needs to be called after the threads have joined. - -Please also note that you can not return values in functions calling ```HIP_CHECK_THREAD``` or ```REQUIRE_THREAD``` macro. - - Usage: - - ```cpp - auto threadFunc = []() { - int *dPtr{nullptr}; - HIP_CHECK_THREAD(hipMalloc(&dPtr, 10)); - REQUIRE_THREAD(dPtr != nullptr); - // Some other work - }; - - // Launch threads - std::vector threadPool; - for(...) { - threadPool.emplace_back(std::thread(threadFunc)); - } - - // Join threads - for(auto &i : threadPool) { - i.join(); - } - - // Validate all results - HIP_CHECK_THREAD_FINALIZE(); - ``` - -### Skipping Tests if certain criteria is not met -If there arises a condition where certain flag is disabled and due to which a test can not run at that time, the following macro can be of use. It will highlight the test in ctest report as well. - -- ```HIP_SKIP_TEST``` : The api takes in an input of the reason as well and prints out the line HIP_SKIP_THIS_TEST. This causes ctest to mark the test as skipped and the test shows up in the report as skipped prompting proper response from the team. - - Usage: - - ```cpp - TEST_CASE("TestOnlyOnXnack") { - if(!XNACKEnabled) { - HipTest::HIP_SKIP_TEST("Test only runs on system with XNACK enabled"); - return; - } - // Rest of test functionality - } - ``` - -### Multi Process Macros -These macros are to be called in multi process tests, inside a process which gets spawned. The reasoning is the same, Catch2 does not support multi process checks. - -- ```HIPCHECK``` : Same as ```HIP_CHECK``` but will not call Catch2's ```REQUIRE``` on the HIP API. It will print if there is a mismatch and exit the process. - -- ```HIPASSERT``` : Same as ```HIP_ASSERT``` but will not call Catch2's ```REQUIRE``` on the HIP API. It will print if there is a mismatch and exit the process. - -## MultiProc Management Class -There is a special interface available for process isolation. ```hip::SpawnProc``` in ```hip_test_process.hh```. Using this interface test can spawn a process and place passing conditions on its return value or its output to stdout. This can be useful for testing printf output. -Sample Usage: -```cpp -hip::SpawnProc proc(, ); -REQUIRE(0 == proc.run()); // Test of return value of the proc -REQUIRE(exepctedOutput == proc.getOutput()); // Test on expected output of the process -``` -The process must be a standalone exe inside the same folder as other tests. - -## Enabling New Tests -Initially, the new tests can be enabled via using ```-DHIP_CATCH_TEST=1```. After porting existing tests, this will be turned on by default. - -## Building a single test -```bash -hipcc -I/tests/catch/include /tests/catch/hipTestMain/standalone_main.cc -I/tests/catch/external/Catch2 -g -o -``` - -## Debugging support -Catch2 allows multiple ways in which you can debug the test case. -- `-b` options breaks into a debugger as soon as there is a failure encountered [Catch2 Options Reference](https://github.com/catchorg/Catch2/blob/devel/docs/command-line.md#breaking-into-the-debugger) -- Catch2 provided [logging macro](https://github.com/catchorg/Catch2/blob/v2.13.6/docs/logging.md#top) that print useful information on test case failure -- User can also call [CATCH_BREAK_INTO_DEBUGGER](https://github.com/catchorg/Catch2/blob/devel/docs/configuration.md#overriding-catchs-debug-break--b) macro to break at a certain point in a test case. -- User can also mention filename.cc:__LineNumber__ to break into a test case via gdb. - -## External Libs being used -- [Catch2](https://github.com/catchorg/Catch2) - Testing framework -- [picojson](https://github.com/kazuho/picojson) - For config file parsing - -# Testing Guidelines -Tests fall in 5 categories and its file name prefix are as follows: - - Unit tests (Prefix: Unit_\*API\*_\*Optional Scenario\*, example : Unit_hipMalloc_Negative or Unit_hipMalloc): Unit Tests are simplest test for an API, the target here is to test the API with different types of input and different ways of calling. - - Application Behavior Modelling tests (Prefix: ABM_\*Intent\*_\*Optional Scenario\*, example: ABM_ModuleLoadAndRun): ABM tests are used to model a specific use case of HIP APIs, either seen in a customer app or a general purpose app. It mimics the calling behavior seen in aforementioned app. - - Stress/Scale tests (Prefix: Stress_\*API\*_\*Intent\*_\*Optional Scenario\*, example: Stress_hipMemset_ExhaustVRAM): These tests are used to see the behavior of HIP APIs in edge scenarios, for example what happens when we have exhausted vram and do a hipMalloc or run many instances of same API in parallel. - - Multi Process tests (Prefix: MultiProc_\*API\*_\*Optional Scenario\*, example: MultiProc_hipIPCMemHandle_GetDataFromProc): These tests are multi process tests and will only run on linux. They are used to test HIP APIs in multi process environment - - Performance tests(Prefix: Perf_\*Intent\*_\*Optional Scenario\*, example: Perf_DispatchLatenc y): Performance tests are used to get results of HIP APIs. - -# General Guidelines: - - Do not use the catch2 tags. Tags wont be used for filtering - - Add as many INFO() as you can in tests which prints state of the t est, this will help the debugger when the test fails (INFO macro only prints when the test fails) - - Check return of each HIP API and fail whenever there is a misma tch with hipSuccess or hiprtcSuccess. - - Each Category of test will hav e its own exe and catch_discover_test macro will be called on it to discover its tests - - Optional Scenario in test names are optional. For example you can test all Scenarios of hipMalloc API in one file, you can name the file Unit_hipMalloc, if you are having a file just for negative scenarios you can name it as Unit_hipMalloc_Negative. diff --git a/projects/hip/tests/catch/TypeQualifiers/CMakeLists.txt b/projects/hip/tests/catch/TypeQualifiers/CMakeLists.txt deleted file mode 100644 index 0219c0021b..0000000000 --- a/projects/hip/tests/catch/TypeQualifiers/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -# Common Tests -set(TEST_SRC - hipManagedKeyword.cc -) - -hip_add_exe_to_target(NAME TypeQualifiers - TEST_SRC ${TEST_SRC} - TEST_TARGET_NAME build_tests) diff --git a/projects/hip/tests/catch/TypeQualifiers/hipManagedKeyword.cc b/projects/hip/tests/catch/TypeQualifiers/hipManagedKeyword.cc deleted file mode 100644 index 4d6a97b119..0000000000 --- a/projects/hip/tests/catch/TypeQualifiers/hipManagedKeyword.cc +++ /dev/null @@ -1,76 +0,0 @@ -/* - Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved. - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR - IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - */ - -/* - This testcase verifies the hipManagedKeyword basic scenario - */ - -#include -#include - -#define N 1048576 -__managed__ float A[N]; // Accessible by ALL CPU and GPU functions !!! -__managed__ float B[N]; -__managed__ int x = 0; - -__global__ void add(const float *A, float *B) { - int index = blockIdx.x * blockDim.x + threadIdx.x; - int stride = blockDim.x * gridDim.x; - for (int i = index; i < N; i += stride) - B[i] = A[i] + B[i]; -} - -__global__ void GPU_func() { - x++; -} - -TEST_CASE("Unit_hipManagedKeyword_SingleGpu") { - for (int i = 0; i < N; i++) { - A[i] = 1.0f; - B[i] = 2.0f; - } - - int blockSize = 256; - int numBlocks = (N + blockSize - 1) / blockSize; - dim3 dimGrid(numBlocks, 1, 1); - dim3 dimBlock(blockSize, 1, 1); - hipLaunchKernelGGL(add, dimGrid, dimBlock, 0, 0, static_cast(A), - static_cast(B)); - - HIP_CHECK(hipGetLastError()); - HIP_CHECK(hipDeviceSynchronize()); - - float maxError = 0.0f; - for (int i = 0; i < N; i++) - maxError = fmax(maxError, fabs(B[i]-3.0f)); - - REQUIRE(maxError == 0.0f); -} - -TEST_CASE("Unit_hipManagedKeyword_MultiGpu") { - int numDevices = 0; - HIP_CHECK(hipGetDeviceCount(&numDevices)); - - for (int i = 0; i < numDevices; i++) { - HIP_CHECK(hipSetDevice(i)); - GPU_func<<< 1, 1 >>>(); - HIP_CHECK(hipDeviceSynchronize()); - } - REQUIRE(x == numDevices); -} diff --git a/projects/hip/tests/catch/catchProp_in_rc.in b/projects/hip/tests/catch/catchProp_in_rc.in deleted file mode 100644 index 74d2028180..0000000000 --- a/projects/hip/tests/catch/catchProp_in_rc.in +++ /dev/null @@ -1,40 +0,0 @@ -#include - -#define HIP_VERSION "@HIP_VERSION@" -#define HIP_VERSION_MAJOR @HIP_VERSION_MAJOR@ -#define HIP_VERSION_MINOR @HIP_VERSION_MINOR@ -#define HIP_VERSION_PATCH @HIP_VERSION_PATCH@ - -VS_VERSION_INFO VERSIONINFO -FILEVERSION HIP_VERSION_MAJOR, HIP_VERSION_MINOR , HIP_VERSION_PATCH -PRODUCTVERSION 10,1 -FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif -FILEOS VOS_NT_WINDOWS32 -FILETYPE VFT_APP -FILESUBTYPE VFT2_UNKNOWN -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "Advanced Micro Devices Inc.\0" - VALUE "FileDescription", "HIP unit tests" - VALUE "FileVersion", "amdhip64.dll" HIP_VERSION - VALUE "LegalCopyright", "Copyright (C) 2022 Advanced Micro Devices Inc.\0" - VALUE "ProductName", "HIP unit tests" - VALUE "ProductVersion", HIP_VERSION - VALUE "Comments", "\0" - VALUE "InternalName", "HIP unit tests" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1200 - END -END -/* End of Version info */ diff --git a/projects/hip/tests/catch/external/Catch2/LICENSE.txt b/projects/hip/tests/catch/external/Catch2/LICENSE.txt deleted file mode 100644 index 36b7cd93cd..0000000000 --- a/projects/hip/tests/catch/external/Catch2/LICENSE.txt +++ /dev/null @@ -1,23 +0,0 @@ -Boost Software License - Version 1.0 - August 17th, 2003 - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/projects/hip/tests/catch/external/Catch2/catch.hpp b/projects/hip/tests/catch/external/Catch2/catch.hpp deleted file mode 100644 index 6897dae0d0..0000000000 --- a/projects/hip/tests/catch/external/Catch2/catch.hpp +++ /dev/null @@ -1,17881 +0,0 @@ -/* - * Catch v2.13.4 - * Generated: 2020-12-29 14:48:00.116107 - * ---------------------------------------------------------- - * This file has been merged from multiple headers. Please don't edit it directly - * Copyright (c) 2020 Two Blue Cubes Ltd. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED -#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED -// start catch.hpp - - -#define CATCH_VERSION_MAJOR 2 -#define CATCH_VERSION_MINOR 13 -#define CATCH_VERSION_PATCH 4 - -#ifdef __clang__ -# pragma clang system_header -#elif defined __GNUC__ -# pragma GCC system_header -#endif - -// start catch_suppress_warnings.h - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(push) -# pragma warning(disable: 161 1682) -# else // __ICC -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -# pragma clang diagnostic ignored "-Wswitch-enum" -# pragma clang diagnostic ignored "-Wcovered-switch-default" -# endif -#elif defined __GNUC__ - // Because REQUIREs trigger GCC's -Wparentheses, and because still - // supported version of g++ have only buggy support for _Pragmas, - // Wparentheses have to be suppressed globally. -# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details - -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wunused-variable" -# pragma GCC diagnostic ignored "-Wpadded" -#endif -// end catch_suppress_warnings.h -#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) -# define CATCH_IMPL -# define CATCH_CONFIG_ALL_PARTS -#endif - -// In the impl file, we want to have access to all parts of the headers -// Can also be used to sanely support PCHs -#if defined(CATCH_CONFIG_ALL_PARTS) -# define CATCH_CONFIG_EXTERNAL_INTERFACES -# if defined(CATCH_CONFIG_DISABLE_MATCHERS) -# undef CATCH_CONFIG_DISABLE_MATCHERS -# endif -# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) -# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER -# endif -#endif - -#if !defined(CATCH_CONFIG_IMPL_ONLY) -// start catch_platform.h - -#ifdef __APPLE__ -# include -# if TARGET_OS_OSX == 1 -# define CATCH_PLATFORM_MAC -# elif TARGET_OS_IPHONE == 1 -# define CATCH_PLATFORM_IPHONE -# endif - -#elif defined(linux) || defined(__linux) || defined(__linux__) -# define CATCH_PLATFORM_LINUX - -#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) -# define CATCH_PLATFORM_WINDOWS -#endif - -// end catch_platform.h - -#ifdef CATCH_IMPL -# ifndef CLARA_CONFIG_MAIN -# define CLARA_CONFIG_MAIN_NOT_DEFINED -# define CLARA_CONFIG_MAIN -# endif -#endif - -// start catch_user_interfaces.h - -namespace Catch { - unsigned int rngSeed(); -} - -// end catch_user_interfaces.h -// start catch_tag_alias_autoregistrar.h - -// start catch_common.h - -// start catch_compiler_capabilities.h - -// Detect a number of compiler features - by compiler -// The following features are defined: -// -// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? -// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? -// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? -// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? -// **************** -// Note to maintainers: if new toggles are added please document them -// in configuration.md, too -// **************** - -// In general each macro has a _NO_ form -// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. -// Many features, at point of detection, define an _INTERNAL_ macro, so they -// can be combined, en-mass, with the _NO_ forms later. - -#ifdef __cplusplus - -# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) -# define CATCH_CPP14_OR_GREATER -# endif - -# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) -# define CATCH_CPP17_OR_GREATER -# endif - -#endif - -// We have to avoid both ICC and Clang, because they try to mask themselves -// as gcc, and we want only GCC in this block -#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) - -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) - -#endif - -#if defined(__clang__) - -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) - -// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug -// which results in calls to destructors being emitted for each temporary, -// without a matching initialization. In practice, this can result in something -// like `std::string::~string` being called on an uninitialized value. -// -// For example, this code will likely segfault under IBM XL: -// ``` -// REQUIRE(std::string("12") + "34" == "1234") -// ``` -// -// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. -# if !defined(__ibmxl__) && !defined(__CUDACC__) -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ -# endif - -# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ - _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") - -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) - -# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) - -# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) - -# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) - -#endif // __clang__ - -//////////////////////////////////////////////////////////////////////////////// -// Assume that non-Windows platforms support posix signals by default -#if !defined(CATCH_PLATFORM_WINDOWS) - #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS -#endif - -//////////////////////////////////////////////////////////////////////////////// -// We know some environments not to support full POSIX signals -#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) - #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS -#endif - -#ifdef __OS400__ -# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS -# define CATCH_CONFIG_COLOUR_NONE -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Android somehow still does not support std::to_string -#if defined(__ANDROID__) -# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING -# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Not all Windows environments support SEH properly -#if defined(__MINGW32__) -# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH -#endif - -//////////////////////////////////////////////////////////////////////////////// -// PS4 -#if defined(__ORBIS__) -# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Cygwin -#ifdef __CYGWIN__ - -// Required for some versions of Cygwin to declare gettimeofday -// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin -# define _BSD_SOURCE -// some versions of cygwin (most) do not support std::to_string. Use the libstd check. -// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 -# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ - && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) - -# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING - -# endif -#endif // __CYGWIN__ - -//////////////////////////////////////////////////////////////////////////////// -// Visual C++ -#if defined(_MSC_VER) - -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) - -// Universal Windows platform does not support SEH -// Or console colours (or console at all...) -# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) -# define CATCH_CONFIG_COLOUR_NONE -# else -# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH -# endif - -// MSVC traditional preprocessor needs some workaround for __VA_ARGS__ -// _MSVC_TRADITIONAL == 0 means new conformant preprocessor -// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor -# if !defined(__clang__) // Handle Clang masquerading for msvc -# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) -# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -# endif // MSVC_TRADITIONAL -# endif // __clang__ - -#endif // _MSC_VER - -#if defined(_REENTRANT) || defined(_MSC_VER) -// Enable async processing, as -pthread is specified or no additional linking is required -# define CATCH_INTERNAL_CONFIG_USE_ASYNC -#endif // _MSC_VER - -//////////////////////////////////////////////////////////////////////////////// -// Check if we are compiled with -fno-exceptions or equivalent -#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) -# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED -#endif - -//////////////////////////////////////////////////////////////////////////////// -// DJGPP -#ifdef __DJGPP__ -# define CATCH_INTERNAL_CONFIG_NO_WCHAR -#endif // __DJGPP__ - -//////////////////////////////////////////////////////////////////////////////// -// Embarcadero C++Build -#if defined(__BORLANDC__) - #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN -#endif - -//////////////////////////////////////////////////////////////////////////////// - -// Use of __COUNTER__ is suppressed during code analysis in -// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly -// handled by it. -// Otherwise all supported compilers support COUNTER macro, -// but user still might want to turn it off -#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) - #define CATCH_INTERNAL_CONFIG_COUNTER -#endif - -//////////////////////////////////////////////////////////////////////////////// - -// RTX is a special version of Windows that is real time. -// This means that it is detected as Windows, but does not provide -// the same set of capabilities as real Windows does. -#if defined(UNDER_RTSS) || defined(RTX64_BUILD) - #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH - #define CATCH_INTERNAL_CONFIG_NO_ASYNC - #define CATCH_CONFIG_COLOUR_NONE -#endif - -#if !defined(_GLIBCXX_USE_C99_MATH_TR1) -#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER -#endif - -// Various stdlib support checks that require __has_include -#if defined(__has_include) - // Check if string_view is available and usable - #if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW - #endif - - // Check if optional is available and usable - # if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL - # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) - - // Check if byte is available and usable - # if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # include - # if __cpp_lib_byte > 0 - # define CATCH_INTERNAL_CONFIG_CPP17_BYTE - # endif - # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) - - // Check if variant is available and usable - # if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # if defined(__clang__) && (__clang_major__ < 8) - // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 - // fix should be in clang 8, workaround in libstdc++ 8.2 - # include - # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) - # define CATCH_CONFIG_NO_CPP17_VARIANT - # else - # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT - # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) - # else - # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT - # endif // defined(__clang__) && (__clang_major__ < 8) - # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) -#endif // defined(__has_include) - -#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) -# define CATCH_CONFIG_COUNTER -#endif -#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) -# define CATCH_CONFIG_WINDOWS_SEH -#endif -// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. -#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) -# define CATCH_CONFIG_POSIX_SIGNALS -#endif -// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. -#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) -# define CATCH_CONFIG_WCHAR -#endif - -#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) -# define CATCH_CONFIG_CPP11_TO_STRING -#endif - -#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) -# define CATCH_CONFIG_CPP17_OPTIONAL -#endif - -#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) -# define CATCH_CONFIG_CPP17_STRING_VIEW -#endif - -#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) -# define CATCH_CONFIG_CPP17_VARIANT -#endif - -#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) -# define CATCH_CONFIG_CPP17_BYTE -#endif - -#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) -# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE -#endif - -#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) -# define CATCH_CONFIG_NEW_CAPTURE -#endif - -#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) -# define CATCH_CONFIG_DISABLE_EXCEPTIONS -#endif - -#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) -# define CATCH_CONFIG_POLYFILL_ISNAN -#endif - -#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) -# define CATCH_CONFIG_USE_ASYNC -#endif - -#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) -# define CATCH_CONFIG_ANDROID_LOGWRITE -#endif - -#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) -# define CATCH_CONFIG_GLOBAL_NEXTAFTER -#endif - -// Even if we do not think the compiler has that warning, we still have -// to provide a macro that can be used by the code. -#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION -#endif -#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS -#endif - -// The goal of this macro is to avoid evaluation of the arguments, but -// still have the compiler warn on problems inside... -#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) -#endif - -#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) -# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS -#elif defined(__clang__) && (__clang_major__ < 5) -# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS -#endif - -#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS -#endif - -#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) -#define CATCH_TRY if ((true)) -#define CATCH_CATCH_ALL if ((false)) -#define CATCH_CATCH_ANON(type) if ((false)) -#else -#define CATCH_TRY try -#define CATCH_CATCH_ALL catch (...) -#define CATCH_CATCH_ANON(type) catch (type) -#endif - -#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) -#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#endif - -// end catch_compiler_capabilities.h -#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line -#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) -#ifdef CATCH_CONFIG_COUNTER -# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) -#else -# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) -#endif - -#include -#include -#include - -// We need a dummy global operator<< so we can bring it into Catch namespace later -struct Catch_global_namespace_dummy {}; -std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); - -namespace Catch { - - struct CaseSensitive { enum Choice { - Yes, - No - }; }; - - class NonCopyable { - NonCopyable( NonCopyable const& ) = delete; - NonCopyable( NonCopyable && ) = delete; - NonCopyable& operator = ( NonCopyable const& ) = delete; - NonCopyable& operator = ( NonCopyable && ) = delete; - - protected: - NonCopyable(); - virtual ~NonCopyable(); - }; - - struct SourceLineInfo { - - SourceLineInfo() = delete; - SourceLineInfo( char const* _file, std::size_t _line ) noexcept - : file( _file ), - line( _line ) - {} - - SourceLineInfo( SourceLineInfo const& other ) = default; - SourceLineInfo& operator = ( SourceLineInfo const& ) = default; - SourceLineInfo( SourceLineInfo&& ) noexcept = default; - SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; - - bool empty() const noexcept { return file[0] == '\0'; } - bool operator == ( SourceLineInfo const& other ) const noexcept; - bool operator < ( SourceLineInfo const& other ) const noexcept; - - char const* file; - std::size_t line; - }; - - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); - - // Bring in operator<< from global namespace into Catch namespace - // This is necessary because the overload of operator<< above makes - // lookup stop at namespace Catch - using ::operator<<; - - // Use this in variadic streaming macros to allow - // >> +StreamEndStop - // as well as - // >> stuff +StreamEndStop - struct StreamEndStop { - std::string operator+() const; - }; - template - T const& operator + ( T const& value, StreamEndStop ) { - return value; - } -} - -#define CATCH_INTERNAL_LINEINFO \ - ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) - -// end catch_common.h -namespace Catch { - - struct RegistrarForTagAliases { - RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); - }; - -} // end namespace Catch - -#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION - -// end catch_tag_alias_autoregistrar.h -// start catch_test_registry.h - -// start catch_interfaces_testcase.h - -#include - -namespace Catch { - - class TestSpec; - - struct ITestInvoker { - virtual void invoke () const = 0; - virtual ~ITestInvoker(); - }; - - class TestCase; - struct IConfig; - - struct ITestCaseRegistry { - virtual ~ITestCaseRegistry(); - virtual std::vector const& getAllTests() const = 0; - virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; - }; - - bool isThrowSafe( TestCase const& testCase, IConfig const& config ); - bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); - std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); - std::vector const& getAllTestCasesSorted( IConfig const& config ); - -} - -// end catch_interfaces_testcase.h -// start catch_stringref.h - -#include -#include -#include -#include - -namespace Catch { - - /// A non-owning string class (similar to the forthcoming std::string_view) - /// Note that, because a StringRef may be a substring of another string, - /// it may not be null terminated. - class StringRef { - public: - using size_type = std::size_t; - using const_iterator = const char*; - - private: - static constexpr char const* const s_empty = ""; - - char const* m_start = s_empty; - size_type m_size = 0; - - public: // construction - constexpr StringRef() noexcept = default; - - StringRef( char const* rawChars ) noexcept; - - constexpr StringRef( char const* rawChars, size_type size ) noexcept - : m_start( rawChars ), - m_size( size ) - {} - - StringRef( std::string const& stdString ) noexcept - : m_start( stdString.c_str() ), - m_size( stdString.size() ) - {} - - explicit operator std::string() const { - return std::string(m_start, m_size); - } - - public: // operators - auto operator == ( StringRef const& other ) const noexcept -> bool; - auto operator != (StringRef const& other) const noexcept -> bool { - return !(*this == other); - } - - auto operator[] ( size_type index ) const noexcept -> char { - assert(index < m_size); - return m_start[index]; - } - - public: // named queries - constexpr auto empty() const noexcept -> bool { - return m_size == 0; - } - constexpr auto size() const noexcept -> size_type { - return m_size; - } - - // Returns the current start pointer. If the StringRef is not - // null-terminated, throws std::domain_exception - auto c_str() const -> char const*; - - public: // substrings and searches - // Returns a substring of [start, start + length). - // If start + length > size(), then the substring is [start, size()). - // If start > size(), then the substring is empty. - auto substr( size_type start, size_type length ) const noexcept -> StringRef; - - // Returns the current start pointer. May not be null-terminated. - auto data() const noexcept -> char const*; - - constexpr auto isNullTerminated() const noexcept -> bool { - return m_start[m_size] == '\0'; - } - - public: // iterators - constexpr const_iterator begin() const { return m_start; } - constexpr const_iterator end() const { return m_start + m_size; } - }; - - auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; - auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; - - constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { - return StringRef( rawChars, size ); - } -} // namespace Catch - -constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { - return Catch::StringRef( rawChars, size ); -} - -// end catch_stringref.h -// start catch_preprocessor.hpp - - -#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ -#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) - -#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ -// MSVC needs more evaluations -#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) -#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) -#else -#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) -#endif - -#define CATCH_REC_END(...) -#define CATCH_REC_OUT - -#define CATCH_EMPTY() -#define CATCH_DEFER(id) id CATCH_EMPTY() - -#define CATCH_REC_GET_END2() 0, CATCH_REC_END -#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 -#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 -#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT -#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) -#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) - -#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) - -#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) - -// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, -// and passes userdata as the first parameter to each invocation, -// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) -#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) - -#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) - -#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) -#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ -#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ -#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF -#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) -#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ -#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) -#else -// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF -#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) -#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ -#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) -#endif - -#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ -#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) - -#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) - -#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper()) -#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) -#else -#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper())) -#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) -#endif - -#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ - CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) - -#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) -#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) -#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) -#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) -#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) -#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) -#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) -#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) -#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) -#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) -#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) - -#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N - -#define INTERNAL_CATCH_TYPE_GEN\ - template struct TypeList {};\ - template\ - constexpr auto get_wrapper() noexcept -> TypeList { return {}; }\ - template class...> struct TemplateTypeList{};\ - template class...Cs>\ - constexpr auto get_wrapper() noexcept -> TemplateTypeList { return {}; }\ - template\ - struct append;\ - template\ - struct rewrap;\ - template class, typename...>\ - struct create;\ - template class, typename>\ - struct convert;\ - \ - template \ - struct append { using type = T; };\ - template< template class L1, typename...E1, template class L2, typename...E2, typename...Rest>\ - struct append, L2, Rest...> { using type = typename append, Rest...>::type; };\ - template< template class L1, typename...E1, typename...Rest>\ - struct append, TypeList, Rest...> { using type = L1; };\ - \ - template< template class Container, template class List, typename...elems>\ - struct rewrap, List> { using type = TypeList>; };\ - template< template class Container, template class List, class...Elems, typename...Elements>\ - struct rewrap, List, Elements...> { using type = typename append>, typename rewrap, Elements...>::type>::type; };\ - \ - template