/**
 * 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.
 */

/* Generated By CANNBot */

/*!
 * \file test_geir_population_count.cpp
 * \brief PopulationCount 算子 GE IR 测试示例
 */

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdint.h>
#include <vector>
#include <string>
#include <map>
#include "assert.h"

#include "graph.h"
#include "types.h"
#include "tensor.h"
#include "ge_error_codes.h"
#include "ge_api_types.h"
#include "ge_api.h"
#include "array_ops.h"
#include "ge_ir_build.h"

#include "../op_graph/population_count_proto.h"

#define FAILED -1
#define SUCCESS 0

using namespace ge;
using std::map;
using std::string;
using std::vector;

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

string GetTime()
{
    time_t timep;
    time(&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S,000", localtime(&timep));
    return tmp;
}

uint32_t GetDataTypeSize(DataType dt)
{
    if (dt == ge::DT_FLOAT || dt == ge::DT_INT32 || dt == ge::DT_UINT32) {
        return 4;
    } else if (dt == ge::DT_FLOAT16 || dt == ge::DT_BF16 || dt == ge::DT_INT16 || dt == ge::DT_UINT16) {
        return 2;
    } else if (dt == ge::DT_INT64 || dt == ge::DT_UINT64) {
        return 8;
    }
    return 1;
}

int32_t GenInt16Data(
    vector<int64_t> shapes, Tensor& input_tensor, TensorDesc& input_tensor_desc, const int16_t* values, size_t nval)
{
    input_tensor_desc.SetRealDimCnt(shapes.size());
    size_t size = 1;
    for (uint32_t i = 0; i < shapes.size(); i++) {
        size *= shapes[i];
    }
    uint32_t data_len = size * sizeof(int16_t);
    int16_t* pData = new (std::nothrow) int16_t[size];
    for (size_t i = 0; i < size; ++i) {
        pData[i] = values[i % nval];
    }
    input_tensor = Tensor(input_tensor_desc, reinterpret_cast<uint8_t*>(pData), data_len);
    delete[] pData;
    return SUCCESS;
}

static inline uint8_t CpuPopcount16(uint16_t v)
{
    return static_cast<uint8_t>(__builtin_popcount(static_cast<uint32_t>(v)));
}

int32_t CreateOppInGraph(
    std::vector<ge::Tensor>& input, std::vector<Operator>& inputs, std::vector<Operator>& outputs,
    Graph& graph)
{
    Status ret = SUCCESS;
    auto popcount1 = op::PopulationCount("popcount1");

    vector<int64_t> xShape = {16};

    // 覆盖正数 / 负数 / 边界值的 16 个 INT16 测试点
    int16_t testValues[16] = {
        0,                     // 0x0000 -> 0
        1,                     // 0x0001 -> 1
        2,                     // 0x0002 -> 1
        3,                     // 0x0003 -> 2
        7,                     // 0x0007 -> 3
        15,                    // 0x000F -> 4
        255,                   // 0x00FF -> 8
        256,                   // 0x0100 -> 1
        21845,                 // 0x5555 -> 8
        (int16_t)0xAAAA,       // 0xAAAA -> 8
        (int16_t)0x7FFF,       // 0x7FFF -> 15
        (int16_t)0x8000,       // 0x8000 -> 1
        -1,                    // 0xFFFF -> 16
        -2,                    // 0xFFFE -> 15
        16,                    // 0x0010 -> 1
        4660,                  // 0x1234 -> 5
    };

    auto placeholder1 = op::Data("placeholder1").set_attr_index(0);
    TensorDesc placeholder1_desc = TensorDesc(ge::Shape(xShape), FORMAT_ND, DT_INT16);
    placeholder1_desc.SetPlacement(ge::kPlacementHost);
    placeholder1_desc.SetFormat(FORMAT_ND);
    Tensor tensor_placeholder1;
    ret = GenInt16Data(xShape, tensor_placeholder1, placeholder1_desc, testValues, 16);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str());
        return FAILED;
    }
    placeholder1.update_input_desc_x(placeholder1_desc);
    placeholder1.update_output_desc_y(placeholder1_desc);
    input.push_back(tensor_placeholder1);
    graph.AddOp(placeholder1);
    popcount1.set_input_x(placeholder1);
    inputs.push_back(placeholder1);

    outputs.push_back(popcount1);
    return SUCCESS;
}

int main(int argc, char* argv[])
{
    const char* graph_name = "tc_ge_irrun_test_population_count";
    Graph graph(graph_name);
    std::vector<ge::Tensor> input;

    printf("%s - INFO - [XIR]: Start to initialize ge using ge global options\n", GetTime().c_str());
    std::map<AscendString, AscendString> global_options = {{"ge.exec.deviceId", "0"}, {"ge.graphRunMode", "1"}};
    Status ret = ge::GEInitialize(global_options);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Initialize ge failed\n", GetTime().c_str());
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Initialize ge success\n", GetTime().c_str());

    std::vector<Operator> inputs{};
    std::vector<Operator> outputs{};

    ret = CreateOppInGraph(input, inputs, outputs, graph);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Create graph failed\n", GetTime().c_str());
        return FAILED;
    }

    if (!inputs.empty() && !outputs.empty()) {
        graph.SetInputs(inputs).SetOutputs(outputs);
    }

    std::map<AscendString, AscendString> build_options = {};
    printf("%s - INFO - [XIR]: Start to create session\n", GetTime().c_str());
    ge::Session* session = new Session(build_options);
    if (session == nullptr) {
        printf("%s - ERROR - [XIR]: Create session failed\n", GetTime().c_str());
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Create session success\n", GetTime().c_str());

    std::map<AscendString, AscendString> graph_options = {};
    uint32_t graph_id = 0;
    ret = session->AddGraph(graph_id, graph, graph_options);
    printf("%s - INFO - [XIR]: Add graph success\n", GetTime().c_str());

    printf("%s - INFO - [XIR]: Start to run graph\n", GetTime().c_str());
    std::vector<ge::Tensor> output;
    ret = session->RunGraph(graph_id, input, output);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Run graph failed\n", GetTime().c_str());
        ge::AscendString error_msg = ge::GEGetErrorMsgV2();
        std::string error_str(error_msg.GetString());
        std::cout << "Error message: " << error_str << std::endl;
        delete session;
        GEFinalize();
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Run graph success\n", GetTime().c_str());

    // Verify output
    uint8_t expected[16] = {0, 1, 1, 2, 3, 4, 8, 1, 8, 8, 15, 1, 16, 15, 1, 5};
    int output_num = output.size();
    bool allPass = true;
    for (int i = 0; i < output_num; i++) {
        int64_t output_shape = output[i].GetTensorDesc().GetShape().GetShapeSize();
        std::cout << "output " << i << " shape size = " << output_shape
                  << ", dtype = " << output[i].GetTensorDesc().GetDataType() << std::endl;

        const uint8_t* odata = output[i].GetData();
        for (int64_t j = 0; j < output_shape && j < 16; j++) {
            bool pass = (odata[j] == expected[j]);
            if (!pass) allPass = false;
            LOG_PRINT("  result[%ld] = %u, expected = %u  %s\n", j,
                      (unsigned)odata[j], (unsigned)expected[j], pass ? "PASS" : "FAIL");
        }
    }

    if (allPass) {
        printf("%s - INFO - [XIR]: PopulationCount GE IR verification ALL PASS\n", GetTime().c_str());
    } else {
        printf("%s - ERROR - [XIR]: PopulationCount GE IR verification FAILED\n", GetTime().c_str());
    }

    ge::AscendString error_msg = ge::GEGetErrorMsgV2();
    std::string error_str(error_msg.GetString());
    std::cout << "Error message: " << error_str << std::endl;
    ge::AscendString warning_msg = ge::GEGetWarningMsgV2();
    std::string warning_str(warning_msg.GetString());
    std::cout << "Warning message: " << warning_str << std::endl;

    delete session;
    ret = ge::GEFinalize();
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Finalize failed\n", GetTime().c_str());
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Finalize success\n", GetTime().c_str());
    return allPass ? SUCCESS : FAILED;
}