aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/minikql/invoke_builtins/mkql_builtins_countbits.cpp
blob: d434e1fac7e2aafa572493d06849d5c786f594e6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "mkql_builtins_impl.h"  // Y_IGNORE  // Y_IGNORE

#include <bit>
#include <type_traits>

namespace NKikimr {
namespace NMiniKQL {

namespace {

template<typename TInput, typename TOutput>
struct TCountBits : public TSimpleArithmeticUnary<TInput, TOutput, TCountBits<TInput, TOutput>> {
    static TOutput Do(TInput val)
    {
        if constexpr (std::is_signed_v<TInput>) {
            return std::popcount(static_cast<std::make_unsigned_t<TInput>>(val));
        } else {
            return std::popcount(val);
        }
    }

#ifndef MKQL_DISABLE_CODEGEN
    static Value* Gen(Value* arg, const TCodegenContext& ctx, BasicBlock*& block)
    {
        auto& context = ctx.Codegen.GetContext();
        auto& module = ctx.Codegen.GetModule();
        const auto fnType = FunctionType::get(arg->getType(), {arg->getType()}, false);
        const auto& name = GetFuncNameForType<TInput>("llvm.ctpop");
        const auto func = module.getOrInsertFunction(name, fnType).getCallee();
        const auto result = CallInst::Create(fnType, func, {arg}, "popcount", block);
        return StaticCast<TInput, TOutput>(result, context, block);
    }
#endif
};

}

void RegisterCountBits(IBuiltinFunctionRegistry& registry) {
    RegisterUnaryIntegralFunctionOpt<TCountBits, TUnaryArgsOpt>(registry, "CountBits");
}

} // namespace NMiniKQL
} // namespace NKikimr