/**
* Copyright (c) 2026 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/


/* !
 * \file assert.asc
 * \brief
 */

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "asc_simt.h"
#include "asc_printf.h"
#include "asc_assert.h"

__global__ void simt_assert(float* input, uint32_t in_shape)
{
    // Calculate global thread ID
    int32_t idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (threadIdx.x < 1) {
        printf("[SIMT] %s\n", "trap check start 1!");
        printf("[SIMT] %s\n", "trap check start 2!");
        printf("[SIMT] %s\n", "trap check start 3!");
        assert(in_shape < 1);
        printf("[SIMT] %s\n", "trap check 1!");
    } else if (threadIdx.x < 5) {
        printf("[SIMT] %s\n", "trap check 2!");
        assert(in_shape > 1);
        printf("[SIMT] %s\n", "trap check 3!");
    }
}

void host_func(std::vector<float>& input, const uint32_t in_shape)
{
    uint32_t input_total_length = input.size();
    size_t input_total_byte_size = in_shape * sizeof(float);

    int32_t device_id = 0;
    aclrtStream stream = nullptr;

    uint8_t* input_host = reinterpret_cast<uint8_t *>(input.data());
    float* input_device = nullptr;
    aclInit(nullptr);
    aclrtSetDevice(device_id);
    aclrtCreateStream(&stream);
    aclrtMalloc((void **)&input_device, input_total_byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMemcpy(input_device, input_total_byte_size, input_host, input_total_byte_size, ACL_MEMCPY_HOST_TO_DEVICE);

    uint32_t blocks_per_grid = 2;
    uint32_t threads_per_block = 32;
    uint32_t dyn_ubuf_size = 0;  // No need to alloc dynamic memory.
    simt_assert<<<blocks_per_grid, threads_per_block, dyn_ubuf_size, stream>>>(input_device, in_shape);
    aclrtSynchronizeStream(stream);

    const char* err = aclGetRecentErrMsg();
    if (err != nullptr) {
        fprintf(stderr, "%s\n", err);
    }

    aclrtFree(input_device);
    aclrtDestroyStream(stream);
    aclrtResetDevice(device_id);
    aclFinalize();

    return;
}


int32_t main(int32_t argc, char* argv[])
{
    constexpr uint32_t in_shape = 128;
    std::vector<float> input(in_shape);
    for (uint32_t i = 0; i < in_shape; i++) {
        input[i] = 1.118f + i;
    }

    host_func(input, in_shape);
    return 0;
}