aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/minikql/comp_nodes/mkql_wide_chopper.cpp
blob: 4172e6caec3d54659a027571fca3bdfc71db98b6 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#include "mkql_chopper.h"

#include <yql/essentials/minikql/computation/mkql_computation_node_codegen.h>  // Y_IGNORE
#include <yql/essentials/minikql/mkql_node_cast.h>
#include <yql/essentials/utils/cast.h>

namespace NKikimr {
namespace NMiniKQL {

using NYql::EnsureDynamicCast;

namespace {

using namespace std::placeholders;

class TWideChopperWrapper : public TStatefulWideFlowCodegeneratorNode<TWideChopperWrapper> {
using TBaseComputation = TStatefulWideFlowCodegeneratorNode<TWideChopperWrapper>;
public:
    enum class EState : ui64 {
        Work,
        Chop,
        Next,
        Skip
    };

    TWideChopperWrapper(TComputationMutables& mutables, IComputationWideFlowNode* flow,  TComputationExternalNodePtrVector&& itemArgs, TComputationNodePtrVector&& keys, TComputationExternalNodePtrVector&& keyArgs, IComputationNode* chop, IComputationWideFlowProxyNode* input, IComputationWideFlowNode* output)
        : TBaseComputation(mutables, flow, EValueRepresentation::Any)
        , Flow(flow)
        , ItemArgs(std::move(itemArgs))
        , Keys(std::move(keys))
        , KeyArgs(std::move(keyArgs))
        , Chop(chop)
        , Input(input)
        , Output(output)
        , ItemsOnKeys(GetPasstroughtMap(ItemArgs, Keys))
        , KeysOnItems(GetPasstroughtMap(Keys, ItemArgs))
        , SwitchItem(IsPasstrought(Chop, ItemArgs))
        , WideFieldsIndex(mutables.IncrementWideFieldsIndex(ItemArgs.size()))
    {
        Input->SetFetcher(std::bind(&TWideChopperWrapper::DoCalculateInput, this, std::bind(&TWideChopperWrapper::RefState, this, _1), _1, _2));
    }

    EFetchResult DoCalculate(NUdf::TUnboxedValue& state, TComputationContext& ctx, NUdf::TUnboxedValue*const* output) const {
        auto** fields = ctx.WideFields.data() + WideFieldsIndex;

        if (state.IsInvalid()) {
            for (auto i = 0U; i < ItemArgs.size(); ++i)
                fields[i] = &ItemArgs[i]->RefValue(ctx);
            if (const auto result = Flow->FetchValues(ctx, fields); EFetchResult::One != result)
                return result;

            for (ui32 i = 0U; i < Keys.size(); ++i)
                if (KeyArgs[i]->GetDependencesCount() > 0U)
                    KeyArgs[i]->SetValue(ctx, Keys[i]->GetValue(ctx));
            state = NUdf::TUnboxedValuePod(ui64(EState::Next));
        } else if (EState::Skip == EState(state.Get<ui64>())) {
            do {
                for (auto i = 0U; i < ItemArgs.size(); ++i)
                    fields[i] = &ItemArgs[i]->RefValue(ctx);
                if (const auto result = Flow->FetchValues(ctx, fields); EFetchResult::One != result)
                    return result;

            } while (!Chop->GetValue(ctx).Get<bool>());

            for (ui32 i = 0U; i < Keys.size(); ++i)
                if (KeyArgs[i]->GetDependencesCount() > 0U)
                    KeyArgs[i]->SetValue(ctx, Keys[i]->GetValue(ctx));
            state = NUdf::TUnboxedValuePod(ui64(EState::Next));
        }

        while (true) {
            if (const auto result = Output->FetchValues(ctx, output); EFetchResult::Finish == result) {
                Input->InvalidateValue(ctx);
                switch (EState(state.Get<ui64>())) {
                    case EState::Work:
                    case EState::Next:
                        do {
                            for (auto i = 0U; i < ItemArgs.size(); ++i)
                                fields[i] = &ItemArgs[i]->RefValue(ctx);
                            switch (const auto next = Flow->FetchValues(ctx, fields)) {
                                case EFetchResult::Yield:
                                    state = NUdf::TUnboxedValuePod(ui64(EState::Skip));
                                case EFetchResult::Finish:
                                    return next;
                                case EFetchResult::One:
                                    break;
                            }
                        } while (!Chop->GetValue(ctx).Get<bool>());
                    case EState::Chop:
                        for (ui32 i = 0U; i < Keys.size(); ++i)
                            if (KeyArgs[i]->GetDependencesCount() > 0U)
                                KeyArgs[i]->SetValue(ctx, Keys[i]->GetValue(ctx));
                        state = NUdf::TUnboxedValuePod(ui64(EState::Next));
                    default:
                        continue;
                }
            } else
                return result;
        }
    }
private:
    EFetchResult DoCalculateInput(NUdf::TUnboxedValue& state, TComputationContext& ctx, NUdf::TUnboxedValue*const* output) const {
        if (EState::Next == EState(state.Get<ui64>())) {
            state = NUdf::TUnboxedValuePod(ui64(EState::Work));
            for (auto i = 0U; i < ItemArgs.size(); ++i)
                if (const auto out = output[i])
                    *out = ItemArgs[i]->GetValue(ctx);
            return EFetchResult::One;
        }

        auto** fields = ctx.WideFields.data() + WideFieldsIndex;

        for (auto i = 0U; i < ItemArgs.size(); ++i)
            fields[i] = &ItemArgs[i]->RefValue(ctx);

        if (const auto result = Flow->FetchValues(ctx, fields); EFetchResult::One != result)
            return result;

        for (auto i = 0U; i < ItemArgs.size(); ++i)
            if (const auto out = output[i])
                *out = *fields[i];

        if (Chop->GetValue(ctx).Get<bool>()) {
            state = NUdf::TUnboxedValuePod(ui64(EState::Chop));
            return EFetchResult::Finish;
        }

        return EFetchResult::One;
    }
#ifndef MKQL_DISABLE_CODEGEN
    TGenerateResult DoGenGetValuesInput(const TCodegenContext& ctx, BasicBlock*& block) const {
        auto& context = ctx.Codegen.GetContext();

        const auto load = BasicBlock::Create(context, "load", ctx.Func);
        const auto work = BasicBlock::Create(context, "work", ctx.Func);
        const auto done = BasicBlock::Create(context, "done", ctx.Func);

        const auto resultType = Type::getInt32Ty(context);
        const auto result = PHINode::Create(resultType, 4U, "result", done);

        const auto valueType = Type::getInt128Ty(context);
        const auto statePtr = GetElementPtrInst::CreateInBounds(valueType, ctx.GetMutables(), {ConstantInt::get(Type::getInt32Ty(context), static_cast<const IComputationNode*>(this)->GetIndex())}, "state_ptr", block);
        const auto entry = new LoadInst(valueType, statePtr, "entry", block);
        const auto next = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, entry, GetConstant(ui64(EState::Next), context), "next", block);

        BranchInst::Create(load, work, next, block);

        block = load;

        new StoreInst(GetConstant(ui64(EState::Work), context), statePtr, block);
        result->addIncoming(ConstantInt::get(resultType, i32(EFetchResult::One)), block);

        BranchInst::Create(done, block);

        const auto good = BasicBlock::Create(context, "good", ctx.Func);
        const auto step = BasicBlock::Create(context, "step", ctx.Func);

        block = work;

        auto getres = GetNodeValues(Flow, ctx, block);
        const auto special = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_SLE, getres.first, ConstantInt::get(getres.first->getType(), 0), "special", block);
        result->addIncoming(getres.first, block);
        BranchInst::Create(done, good, special, block);

        block = good;

        std::vector<Value*> items(ItemArgs.size(), nullptr);
        for (ui32 i = 0U; i < items.size(); ++i) {
            EnsureDynamicCast<ICodegeneratorExternalNode*>(ItemArgs[i])->CreateSetValue(ctx, block, items[i] = getres.second[i](ctx, block));
        }

        const auto chop = SwitchItem ? items[*SwitchItem] : GetNodeValue(Chop, ctx, block);
        const auto cast = CastInst::Create(Instruction::Trunc, chop, Type::getInt1Ty(context), "bool", block);
        result->addIncoming(ConstantInt::get(resultType, i32(EFetchResult::One)), block);
        BranchInst::Create(step, done, cast, block);

        block = step;

        new StoreInst(GetConstant(ui64(EState::Chop), context), statePtr, block);
        result->addIncoming(ConstantInt::get(resultType, i32(EFetchResult::Finish)), block);
        BranchInst::Create(done, block);

        block = done;

        ICodegeneratorInlineWideNode::TGettersList getters;
        getters.reserve(ItemArgs.size());
        std::transform(ItemArgs.cbegin(), ItemArgs.cend(), std::back_inserter(getters), [&](IComputationNode* node) {
            return [node](const TCodegenContext& ctx, BasicBlock*& block){ return GetNodeValue(node, ctx, block); };
        });
        return {result, std::move(getters)};
    }
public:
    TGenerateResult DoGenGetValues(const TCodegenContext& ctx, Value* statePtr, BasicBlock*& block) const {
        EnsureDynamicCast<IWideFlowProxyCodegeneratorNode*>(Input)->SetGenerator(std::bind(&TWideChopperWrapper::DoGenGetValuesInput, this, _1, _2));

        auto& context = ctx.Codegen.GetContext();

        const auto init = BasicBlock::Create(context, "init", ctx.Func);
        const auto loop = BasicBlock::Create(context, "loop", ctx.Func);
        const auto exit = BasicBlock::Create(context, "exit", ctx.Func);
        const auto pass = BasicBlock::Create(context, "pass", ctx.Func);

        const auto resultType = Type::getInt32Ty(context);
        const auto result = PHINode::Create(resultType, 5U, "result", exit);

        const auto valueType = Type::getInt128Ty(context);
        const auto first = new LoadInst(valueType, statePtr, "first", block);
        const auto enter = SwitchInst::Create(first, loop, 2U, block);
        enter->addCase(GetInvalid(context), init);
        enter->addCase(GetConstant(ui64(EState::Skip), context), pass);


        {
            const auto next = BasicBlock::Create(context, "next", ctx.Func);

            block = init;

            const auto getfirst = GetNodeValues(Flow, ctx, block);
            const auto special = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_SLE, getfirst.first, ConstantInt::get(getfirst.first->getType(), 0), "special", block);
            result->addIncoming(getfirst.first, block);
            BranchInst::Create(exit, next, special, block);

            block = next;

            new StoreInst(GetConstant(ui64(EState::Next), context), statePtr, block);

            std::vector<Value*> items(ItemArgs.size(), nullptr);
            for (ui32 i = 0U; i < items.size(); ++i) {
                EnsureDynamicCast<ICodegeneratorExternalNode*>(ItemArgs[i])->CreateSetValue(ctx, block, items[i] = getfirst.second[i](ctx, block));
            }

            for (ui32 i = 0U; i < Keys.size(); ++i) {
                if (KeyArgs[i]->GetDependencesCount() > 0U) {
                    const auto map = KeysOnItems[i];
                    const auto key = map ? items[*map] : GetNodeValue(Keys[i], ctx, block);
                    EnsureDynamicCast<ICodegeneratorExternalNode*>(KeyArgs[i])->CreateSetValue(ctx, block, key);
                }
            }

            BranchInst::Create(loop, block);
        }

        const auto part = BasicBlock::Create(context, "part", ctx.Func);
        const auto good = BasicBlock::Create(context, "good", ctx.Func);
        const auto step = BasicBlock::Create(context, "step", ctx.Func);
        const auto skip = BasicBlock::Create(context, "skip", ctx.Func);

        block = loop;

        auto getres = GetNodeValues(Output, ctx, block);
        const auto state = new LoadInst(valueType, statePtr, "state", block);
        const auto finish = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_SLT, getres.first, ConstantInt::get(getres.first->getType(), 0), "finish", block);
        result->addIncoming(getres.first, block);
        BranchInst::Create(part, exit, finish, block);

        block = part;

        EnsureDynamicCast<IWideFlowProxyCodegeneratorNode*>(Input)->CreateInvalidate(ctx, block);

        result->addIncoming(ConstantInt::get(resultType, i32(EFetchResult::Finish)), block);

        const auto choise = SwitchInst::Create(state, exit, 3U, block);
        choise->addCase(GetConstant(ui64(EState::Next), context), pass);
        choise->addCase(GetConstant(ui64(EState::Work), context), pass);
        choise->addCase(GetConstant(ui64(EState::Chop), context), step);

        block = pass;

        const auto getnext = GetNodeValues(Flow, ctx, block);

        result->addIncoming(getnext.first, block);

        const auto way = SwitchInst::Create(getnext.first, good, 2U, block);
        way->addCase(ConstantInt::get(resultType, i32(EFetchResult::Finish)), exit);
        way->addCase(ConstantInt::get(resultType, i32(EFetchResult::Yield)), skip);

        block = good;

        std::vector<Value*> items(ItemArgs.size(), nullptr);
        for (ui32 i = 0U; i < items.size(); ++i) {
            EnsureDynamicCast<ICodegeneratorExternalNode*>(ItemArgs[i])->CreateSetValue(ctx, block, items[i] = getnext.second[i](ctx, block));
        }

        const auto chop = SwitchItem ? items[*SwitchItem] : GetNodeValue(Chop, ctx, block);
        const auto cast = CastInst::Create(Instruction::Trunc, chop, Type::getInt1Ty(context), "bool", block);

        BranchInst::Create(step, pass, cast, block);

        block = step;

        new StoreInst(GetConstant(ui64(EState::Next), context), statePtr, block);

        for (ui32 i = 0U; i < Keys.size(); ++i) {
            if (KeyArgs[i]->GetDependencesCount() > 0U) {
                const auto key = GetNodeValue(Keys[i], ctx, block);
                EnsureDynamicCast<ICodegeneratorExternalNode*>(KeyArgs[i])->CreateSetValue(ctx, block, key);
            }
        }

        BranchInst::Create(loop, block);

        block = skip;
        new StoreInst(GetConstant(ui64(EState::Skip), context), statePtr, block);
        result->addIncoming(ConstantInt::get(resultType, i32(EFetchResult::Yield)), block);
        BranchInst::Create(exit, block);

        block = exit;
        return {result, std::move(getres.second)};
    }
#endif
private:
    void RegisterDependencies() const final {
        if (const auto flow = FlowDependsOn(Flow)) {
            std::for_each(ItemArgs.cbegin(), ItemArgs.cend(), std::bind(&TWideChopperWrapper::Own, flow, std::placeholders::_1));
            std::for_each(Keys.cbegin(), Keys.cend(), std::bind(&TWideChopperWrapper::DependsOn, flow, std::placeholders::_1));
            std::for_each(KeyArgs.cbegin(), KeyArgs.cend(), std::bind(&TWideChopperWrapper::Own, flow, std::placeholders::_1));
            OwnProxy(flow, Input);
            DependsOn(flow, Output);
        }
    }

    IComputationWideFlowNode *const Flow;

    const TComputationExternalNodePtrVector ItemArgs;
    const TComputationNodePtrVector Keys;
    const TComputationExternalNodePtrVector KeyArgs;

    IComputationNode *const Chop;

    IComputationWideFlowProxyNode *const Input;
    IComputationWideFlowNode *const Output;

    const TPasstroughtMap ItemsOnKeys, KeysOnItems;

    const std::optional<size_t> SwitchItem;

    const ui32 WideFieldsIndex;
};

}

IComputationNode* WrapWideChopper(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
    MKQL_ENSURE(callable.GetInputsCount() >= 4U, "Expected at least four args.");

    const auto wideComponents = GetWideComponents(AS_TYPE(TFlowType, callable.GetInput(0U).GetStaticType()));
    const ui32 width = wideComponents.size();
    const auto flow = LocateNode(ctx.NodeLocator, callable, 0U);
    const auto keysSize = (callable.GetInputsCount() - width - 4U) >> 1U;

    TComputationNodePtrVector keys;
    keys.reserve(keysSize);
    auto index = width;
    std::generate_n(std::back_inserter(keys), keysSize, [&](){ return LocateNode(ctx.NodeLocator, callable, ++index); } );

    index += keysSize;

    const auto switchResult = LocateNode(ctx.NodeLocator, callable, ++index);
    const auto input = LocateNode(ctx.NodeLocator, callable, ++index, true);
    const auto output = LocateNode(ctx.NodeLocator, callable, ++index, true);

    TComputationExternalNodePtrVector itemArgs, keyArgs;
    itemArgs.reserve(width);
    index = 0U;
    std::generate_n(std::back_inserter(itemArgs), width, [&](){ return LocateExternalNode(ctx.NodeLocator, callable, ++index); } );

    index += keysSize;
    keyArgs.reserve(keysSize);
    std::generate_n(std::back_inserter(keyArgs), keysSize, [&](){ return LocateExternalNode(ctx.NodeLocator, callable, ++index); } );

    if (const auto wide = dynamic_cast<IComputationWideFlowNode*>(flow)) {
        return new TWideChopperWrapper(ctx.Mutables, wide, std::move(itemArgs), std::move(keys), std::move(keyArgs), switchResult,
                                       EnsureDynamicCast<IComputationWideFlowProxyNode*>(input),
                                       EnsureDynamicCast<IComputationWideFlowNode*>(output));
    }

    THROW yexception() << "Expected wide flow.";
}

}
}