mkql_blocks.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. #include "mkql_blocks.h"
  2. #include <yql/essentials/minikql/computation/mkql_block_reader.h>
  3. #include <yql/essentials/minikql/computation/mkql_block_builder.h>
  4. #include <yql/essentials/minikql/computation/mkql_block_impl.h>
  5. #include <yql/essentials/minikql/computation/mkql_block_impl_codegen.h> // Y_IGNORE
  6. #include <yql/essentials/minikql/arrow/arrow_defs.h>
  7. #include <yql/essentials/minikql/arrow/arrow_util.h>
  8. #include <yql/essentials/minikql/mkql_type_builder.h>
  9. #include <yql/essentials/minikql/computation/mkql_computation_node_codegen.h> // Y_IGNORE
  10. #include <yql/essentials/minikql/mkql_node_builder.h>
  11. #include <yql/essentials/minikql/mkql_node_cast.h>
  12. #include <yql/essentials/parser/pg_wrapper/interface/arrow.h>
  13. #include <arrow/scalar.h>
  14. #include <arrow/array.h>
  15. #include <arrow/datum.h>
  16. namespace NKikimr {
  17. namespace NMiniKQL {
  18. namespace {
  19. class TToBlocksWrapper : public TStatelessFlowComputationNode<TToBlocksWrapper> {
  20. public:
  21. explicit TToBlocksWrapper(IComputationNode* flow, TType* itemType)
  22. : TStatelessFlowComputationNode(flow, EValueRepresentation::Boxed)
  23. , Flow_(flow)
  24. , ItemType_(itemType)
  25. {
  26. }
  27. NUdf::TUnboxedValuePod DoCalculate(TComputationContext& ctx) const {
  28. const auto maxLen = CalcBlockLen(CalcMaxBlockItemSize(ItemType_));
  29. const auto builder = MakeArrayBuilder(TTypeInfoHelper(), ItemType_, ctx.ArrowMemoryPool, maxLen, &ctx.Builder->GetPgBuilder());
  30. for (size_t i = 0; i < builder->MaxLength(); ++i) {
  31. auto result = Flow_->GetValue(ctx);
  32. if (result.IsSpecial()) {
  33. if (i == 0) {
  34. return result.Release();
  35. }
  36. break;
  37. }
  38. builder->Add(result);
  39. }
  40. return ctx.HolderFactory.CreateArrowBlock(builder->Build(true));
  41. }
  42. private:
  43. void RegisterDependencies() const final {
  44. FlowDependsOn(Flow_);
  45. }
  46. private:
  47. IComputationNode* const Flow_;
  48. TType* ItemType_;
  49. };
  50. class TWideToBlocksWrapper : public TStatefulWideFlowCodegeneratorNode<TWideToBlocksWrapper> {
  51. using TBaseComputation = TStatefulWideFlowCodegeneratorNode<TWideToBlocksWrapper>;
  52. public:
  53. TWideToBlocksWrapper(TComputationMutables& mutables,
  54. IComputationWideFlowNode* flow,
  55. TVector<TType*>&& types)
  56. : TBaseComputation(mutables, flow, EValueRepresentation::Boxed)
  57. , Flow_(flow)
  58. , Types_(std::move(types))
  59. , MaxLength_(CalcBlockLen(std::accumulate(Types_.cbegin(), Types_.cend(), 0ULL, [](size_t max, const TType* type){ return std::max(max, CalcMaxBlockItemSize(type)); })))
  60. , Width_(Types_.size())
  61. , WideFieldsIndex_(mutables.IncrementWideFieldsIndex(Width_))
  62. {
  63. }
  64. EFetchResult DoCalculate(NUdf::TUnboxedValue& state,
  65. TComputationContext& ctx,
  66. NUdf::TUnboxedValue*const* output) const {
  67. auto& s = GetState(state, ctx);
  68. const auto fields = ctx.WideFields.data() + WideFieldsIndex_;
  69. if (!s.Count) {
  70. if (!s.IsFinished_) do {
  71. switch (Flow_->FetchValues(ctx, fields)) {
  72. case EFetchResult::One:
  73. for (size_t i = 0; i < Types_.size(); ++i)
  74. s.Add(s.Values[i], i);
  75. continue;
  76. case EFetchResult::Yield:
  77. return EFetchResult::Yield;
  78. case EFetchResult::Finish:
  79. s.IsFinished_ = true;
  80. break;
  81. }
  82. break;
  83. } while (++s.Rows_ < MaxLength_ && s.BuilderAllocatedSize_ <= s.MaxBuilderAllocatedSize_);
  84. if (s.Rows_)
  85. s.MakeBlocks(ctx.HolderFactory);
  86. else
  87. return EFetchResult::Finish;
  88. }
  89. const auto sliceSize = s.Slice();
  90. for (size_t i = 0; i <= Types_.size(); ++i) {
  91. if (const auto out = output[i]) {
  92. *out = s.Get(sliceSize, ctx.HolderFactory, i);
  93. }
  94. }
  95. return EFetchResult::One;
  96. }
  97. #ifndef MKQL_DISABLE_CODEGEN
  98. ICodegeneratorInlineWideNode::TGenerateResult DoGenGetValues(const TCodegenContext& ctx, Value* statePtr, BasicBlock*& block) const {
  99. auto& context = ctx.Codegen.GetContext();
  100. const auto valueType = Type::getInt128Ty(context);
  101. const auto statusType = Type::getInt32Ty(context);
  102. const auto indexType = Type::getInt64Ty(context);
  103. TLLVMFieldsStructureState stateFields(context, Types_.size() + 1U);
  104. const auto stateType = StructType::get(context, stateFields.GetFieldsArray());
  105. const auto statePtrType = PointerType::getUnqual(stateType);
  106. const auto atTop = &ctx.Func->getEntryBlock().back();
  107. const auto addFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TState::Add));
  108. const auto addType = FunctionType::get(Type::getVoidTy(context), {statePtrType, valueType, indexType}, false);
  109. const auto addPtr = CastInst::Create(Instruction::IntToPtr, addFunc, PointerType::getUnqual(addType), "add", atTop);
  110. const auto getFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TState::Get));
  111. const auto getType = FunctionType::get(valueType, {statePtrType, indexType, ctx.GetFactory()->getType(), indexType}, false);
  112. const auto getPtr = CastInst::Create(Instruction::IntToPtr, getFunc, PointerType::getUnqual(getType), "get", atTop);
  113. const auto heightPtr = new AllocaInst(indexType, 0U, "height_ptr", atTop);
  114. const auto stateOnStack = new AllocaInst(statePtrType, 0U, "state_on_stack", atTop);
  115. new StoreInst(ConstantInt::get(indexType, 0), heightPtr, atTop);
  116. new StoreInst(ConstantPointerNull::get(statePtrType), stateOnStack, atTop);
  117. const auto make = BasicBlock::Create(context, "make", ctx.Func);
  118. const auto main = BasicBlock::Create(context, "main", ctx.Func);
  119. const auto more = BasicBlock::Create(context, "more", ctx.Func);
  120. const auto skip = BasicBlock::Create(context, "skip", ctx.Func);
  121. const auto read = BasicBlock::Create(context, "read", ctx.Func);
  122. const auto good = BasicBlock::Create(context, "good", ctx.Func);
  123. const auto stop = BasicBlock::Create(context, "stop", ctx.Func);
  124. const auto work = BasicBlock::Create(context, "work", ctx.Func);
  125. const auto fill = BasicBlock::Create(context, "fill", ctx.Func);
  126. const auto over = BasicBlock::Create(context, "over", ctx.Func);
  127. const auto second_cond = BasicBlock::Create(context, "second_cond", ctx.Func);
  128. BranchInst::Create(make, main, IsInvalid(statePtr, block), block);
  129. block = make;
  130. const auto ptrType = PointerType::getUnqual(StructType::get(context));
  131. const auto self = CastInst::Create(Instruction::IntToPtr, ConstantInt::get(Type::getInt64Ty(context), uintptr_t(this)), ptrType, "self", block);
  132. const auto makeFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TWideToBlocksWrapper::MakeState));
  133. const auto makeType = FunctionType::get(Type::getVoidTy(context), {self->getType(), ctx.Ctx->getType(), statePtr->getType()}, false);
  134. const auto makeFuncPtr = CastInst::Create(Instruction::IntToPtr, makeFunc, PointerType::getUnqual(makeType), "function", block);
  135. CallInst::Create(makeType, makeFuncPtr, {self, ctx.Ctx, statePtr}, "", block);
  136. BranchInst::Create(main, block);
  137. block = main;
  138. const auto state = new LoadInst(valueType, statePtr, "state", block);
  139. const auto half = CastInst::Create(Instruction::Trunc, state, Type::getInt64Ty(context), "half", block);
  140. const auto stateArg = CastInst::Create(Instruction::IntToPtr, half, statePtrType, "state_arg", block);
  141. const auto countPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetCount() }, "count_ptr", block);
  142. const auto count = new LoadInst(indexType, countPtr, "count", block);
  143. const auto none = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, count, ConstantInt::get(indexType, 0), "none", block);
  144. BranchInst::Create(more, fill, none, block);
  145. block = more;
  146. const auto rowsPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetRows() }, "rows_ptr", block);
  147. const auto finishedPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetIsFinished() }, "is_finished_ptr", block);
  148. const auto allocatedSizePtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetBuilderAllocatedSize() }, "allocated_size_ptr", block);
  149. const auto maxAllocatedSizePtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetMaxBuilderAllocatedSize() }, "max_allocated_size_ptr", block);
  150. const auto finished = new LoadInst(Type::getInt1Ty(context), finishedPtr, "finished", block);
  151. BranchInst::Create(skip, read, finished, block);
  152. block = read;
  153. const auto getres = GetNodeValues(Flow_, ctx, block);
  154. const auto way = SwitchInst::Create(getres.first, good, 2U, block);
  155. way->addCase(ConstantInt::get(statusType, i32(EFetchResult::Finish)), stop);
  156. way->addCase(ConstantInt::get(statusType, i32(EFetchResult::Yield)), over);
  157. const auto result = PHINode::Create(statusType, 3U, "result", over);
  158. result->addIncoming(getres.first, block);
  159. block = good;
  160. const auto read_rows = new LoadInst(indexType, rowsPtr, "read_rows", block);
  161. const auto increment = BinaryOperator::CreateAdd(read_rows, ConstantInt::get(indexType, 1), "increment", block);
  162. new StoreInst(increment, rowsPtr, block);
  163. for (size_t idx = 0U; idx < Types_.size(); ++idx) {
  164. const auto value = getres.second[idx](ctx, block);
  165. CallInst::Create(addType, addPtr, {stateArg, value, ConstantInt::get(indexType, idx)}, "", block);
  166. ValueCleanup(GetValueRepresentation(Types_[idx]), value, ctx, block);
  167. }
  168. const auto next = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT, increment, ConstantInt::get(indexType, MaxLength_), "next", block);
  169. BranchInst::Create(second_cond, work, next, block);
  170. block = second_cond;
  171. const auto read_allocated_size = new LoadInst(indexType, allocatedSizePtr, "read_allocated_size", block);
  172. const auto read_max_allocated_size = new LoadInst(indexType, maxAllocatedSizePtr, "read_max_allocated_size", block);
  173. const auto next2 = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULE, read_allocated_size, read_max_allocated_size, "next2", block);
  174. BranchInst::Create(read, work, next2, block);
  175. block = stop;
  176. new StoreInst(ConstantInt::getTrue(context), finishedPtr, block);
  177. BranchInst::Create(skip, block);
  178. block = skip;
  179. const auto rows = new LoadInst(indexType, rowsPtr, "rows", block);
  180. const auto empty = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, rows, ConstantInt::get(indexType, 0), "empty", block);
  181. result->addIncoming(ConstantInt::get(statusType, static_cast<i32>(EFetchResult::Finish)), block);
  182. BranchInst::Create(over, work, empty, block);
  183. block = work;
  184. const auto makeBlockFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TState::MakeBlocks));
  185. const auto makeBlockType = FunctionType::get(indexType, {statePtrType, ctx.GetFactory()->getType()}, false);
  186. const auto makeBlockPtr = CastInst::Create(Instruction::IntToPtr, makeBlockFunc, PointerType::getUnqual(makeBlockType), "make_blocks_func", block);
  187. CallInst::Create(makeBlockType, makeBlockPtr, {stateArg, ctx.GetFactory()}, "", block);
  188. BranchInst::Create(fill, block);
  189. block = fill;
  190. const auto sliceFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TState::Slice));
  191. const auto sliceType = FunctionType::get(indexType, {statePtrType}, false);
  192. const auto slicePtr = CastInst::Create(Instruction::IntToPtr, sliceFunc, PointerType::getUnqual(sliceType), "slice_func", block);
  193. const auto slice = CallInst::Create(sliceType, slicePtr, {stateArg}, "slice", block);
  194. new StoreInst(slice, heightPtr, block);
  195. new StoreInst(stateArg, stateOnStack, block);
  196. result->addIncoming(ConstantInt::get(statusType, static_cast<i32>(EFetchResult::One)), block);
  197. BranchInst::Create(over, block);
  198. block = over;
  199. ICodegeneratorInlineWideNode::TGettersList getters(Types_.size() + 1U);
  200. for (size_t idx = 0U; idx < getters.size(); ++idx) {
  201. getters[idx] = [idx, getType, getPtr, heightPtr, indexType, statePtrType, stateOnStack](const TCodegenContext& ctx, BasicBlock*& block) {
  202. const auto stateArg = new LoadInst(statePtrType, stateOnStack, "state", block);
  203. const auto heightArg = new LoadInst(indexType, heightPtr, "height", block);
  204. return CallInst::Create(getType, getPtr, {stateArg, heightArg, ctx.GetFactory(), ConstantInt::get(indexType, idx)}, "get", block);
  205. };
  206. }
  207. return {result, std::move(getters)};
  208. }
  209. #endif
  210. private:
  211. struct TState : public TBlockState {
  212. size_t Rows_ = 0;
  213. bool IsFinished_ = false;
  214. size_t BuilderAllocatedSize_ = 0;
  215. size_t MaxBuilderAllocatedSize_ = 0;
  216. std::vector<std::unique_ptr<IArrayBuilder>> Builders_;
  217. static const size_t MaxAllocatedFactor_ = 4;
  218. TState(TMemoryUsageInfo* memInfo, TComputationContext& ctx, const TVector<TType*>& types, size_t maxLength, NUdf::TUnboxedValue**const fields)
  219. : TBlockState(memInfo, types.size() + 1U)
  220. , Builders_(types.size())
  221. {
  222. for (size_t i = 0; i < types.size(); ++i) {
  223. fields[i] = &Values[i];
  224. Builders_[i] = MakeArrayBuilder(TTypeInfoHelper(), types[i], ctx.ArrowMemoryPool, maxLength, &ctx.Builder->GetPgBuilder(), &BuilderAllocatedSize_);
  225. }
  226. MaxBuilderAllocatedSize_ = MaxAllocatedFactor_ * BuilderAllocatedSize_;
  227. }
  228. void Add(const NUdf::TUnboxedValuePod value, size_t idx) {
  229. Builders_[idx]->Add(value);
  230. }
  231. void MakeBlocks(const THolderFactory& holderFactory) {
  232. Values.back() = holderFactory.CreateArrowBlock(arrow::Datum(std::make_shared<arrow::UInt64Scalar>(Rows_)));
  233. Rows_ = 0;
  234. BuilderAllocatedSize_ = 0;
  235. for (size_t i = 0; i < Builders_.size(); ++i) {
  236. if (const auto builder = Builders_[i].get()) {
  237. Values[i] = holderFactory.CreateArrowBlock(builder->Build(IsFinished_));
  238. }
  239. }
  240. FillArrays();
  241. }
  242. };
  243. #ifndef MKQL_DISABLE_CODEGEN
  244. class TLLVMFieldsStructureState: public TLLVMFieldsStructureBlockState {
  245. private:
  246. using TBase = TLLVMFieldsStructureBlockState;
  247. llvm::IntegerType*const RowsType;
  248. llvm::IntegerType*const IsFinishedType;
  249. llvm::IntegerType*const BuilderAllocatedSizeType;
  250. llvm::IntegerType*const MaxBuilderAllocatedSizeType;
  251. protected:
  252. using TBase::Context;
  253. public:
  254. std::vector<llvm::Type*> GetFieldsArray() {
  255. std::vector<llvm::Type*> result = TBase::GetFieldsArray();
  256. result.emplace_back(RowsType);
  257. result.emplace_back(IsFinishedType);
  258. result.emplace_back(BuilderAllocatedSizeType);
  259. result.emplace_back(MaxBuilderAllocatedSizeType);
  260. return result;
  261. }
  262. llvm::Constant* GetRows() {
  263. return ConstantInt::get(Type::getInt32Ty(Context), TBase::GetFieldsCount() + BaseFields);
  264. }
  265. llvm::Constant* GetIsFinished() {
  266. return ConstantInt::get(Type::getInt32Ty(Context), TBase::GetFieldsCount() + BaseFields + 1);
  267. }
  268. llvm::Constant* GetBuilderAllocatedSize() {
  269. return ConstantInt::get(Type::getInt32Ty(Context), TBase::GetFieldsCount() + BaseFields + 2);
  270. }
  271. llvm::Constant* GetMaxBuilderAllocatedSize() {
  272. return ConstantInt::get(Type::getInt32Ty(Context), TBase::GetFieldsCount() + BaseFields + 3);
  273. }
  274. TLLVMFieldsStructureState(llvm::LLVMContext& context, size_t width)
  275. : TBase(context, width)
  276. , RowsType(Type::getInt64Ty(Context))
  277. , IsFinishedType(Type::getInt1Ty(Context))
  278. , BuilderAllocatedSizeType(Type::getInt64Ty(Context))
  279. , MaxBuilderAllocatedSizeType(Type::getInt64Ty(Context))
  280. {}
  281. };
  282. #endif
  283. void RegisterDependencies() const final {
  284. FlowDependsOn(Flow_);
  285. }
  286. void MakeState(TComputationContext& ctx, NUdf::TUnboxedValue& state) const {
  287. state = ctx.HolderFactory.Create<TState>(ctx, Types_, MaxLength_, ctx.WideFields.data() + WideFieldsIndex_);
  288. }
  289. TState& GetState(NUdf::TUnboxedValue& state, TComputationContext& ctx) const {
  290. if (state.IsInvalid())
  291. MakeState(ctx, state);
  292. return *static_cast<TState*>(state.AsBoxed().Get());
  293. }
  294. private:
  295. IComputationWideFlowNode* const Flow_;
  296. const TVector<TType*> Types_;
  297. const size_t MaxLength_;
  298. const size_t Width_;
  299. const size_t WideFieldsIndex_;
  300. };
  301. class TFromBlocksWrapper : public TStatefulFlowCodegeneratorNode<TFromBlocksWrapper> {
  302. using TBaseComputation = TStatefulFlowCodegeneratorNode<TFromBlocksWrapper>;
  303. public:
  304. TFromBlocksWrapper(TComputationMutables& mutables, IComputationNode* flow, TType* itemType)
  305. : TBaseComputation(mutables, flow, EValueRepresentation::Boxed)
  306. , Flow_(flow)
  307. , ItemType_(itemType)
  308. {
  309. }
  310. NUdf::TUnboxedValuePod DoCalculate(NUdf::TUnboxedValue& state, TComputationContext& ctx) const {
  311. for (auto& s = GetState(state, ctx);;) {
  312. if (auto item = s.GetValue(ctx.HolderFactory); !item.IsInvalid())
  313. return item;
  314. if (const auto input = Flow_->GetValue(ctx).Release(); input.IsSpecial())
  315. return input;
  316. else
  317. s.Reset(input);
  318. }
  319. }
  320. #ifndef MKQL_DISABLE_CODEGEN
  321. Value* DoGenerateGetValue(const TCodegenContext& ctx, Value* statePtr, BasicBlock*& block) const {
  322. auto& context = ctx.Codegen.GetContext();
  323. const auto valueType = Type::getInt128Ty(context);
  324. const auto statePtrType = PointerType::getUnqual(StructType::get(context));
  325. const auto make = BasicBlock::Create(context, "make", ctx.Func);
  326. const auto work = BasicBlock::Create(context, "work", ctx.Func);
  327. const auto read = BasicBlock::Create(context, "read", ctx.Func);
  328. const auto init = BasicBlock::Create(context, "init", ctx.Func);
  329. const auto done = BasicBlock::Create(context, "done", ctx.Func);
  330. BranchInst::Create(make, work, IsInvalid(statePtr, block), block);
  331. block = make;
  332. const auto ptrType = PointerType::getUnqual(StructType::get(context));
  333. const auto self = CastInst::Create(Instruction::IntToPtr, ConstantInt::get(Type::getInt64Ty(context), uintptr_t(this)), ptrType, "self", block);
  334. const auto makeFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TFromBlocksWrapper::MakeState));
  335. const auto makeType = FunctionType::get(Type::getVoidTy(context), {self->getType(), ctx.Ctx->getType(), statePtr->getType()}, false);
  336. const auto makeFuncPtr = CastInst::Create(Instruction::IntToPtr, makeFunc, PointerType::getUnqual(makeType), "function", block);
  337. CallInst::Create(makeType, makeFuncPtr, {self, ctx.Ctx, statePtr}, "", block);
  338. BranchInst::Create(work, block);
  339. block = work;
  340. const auto state = new LoadInst(valueType, statePtr, "state", block);
  341. const auto half = CastInst::Create(Instruction::Trunc, state, Type::getInt64Ty(context), "half", block);
  342. const auto stateArg = CastInst::Create(Instruction::IntToPtr, half, statePtrType, "state_arg", block);
  343. const auto getFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TState::GetValue));
  344. const auto getType = FunctionType::get(valueType, {statePtrType, ctx.GetFactory()->getType()}, false);
  345. const auto getPtr = CastInst::Create(Instruction::IntToPtr, getFunc, PointerType::getUnqual(getType), "get", block);
  346. const auto value = CallInst::Create(getType, getPtr, {stateArg, ctx.GetFactory() }, "value", block);
  347. const auto result = PHINode::Create(valueType, 2U, "result", done);
  348. result->addIncoming(value, block);
  349. BranchInst::Create(read, done, IsInvalid(value, block), block);
  350. block = read;
  351. const auto input = GetNodeValue(Flow_, ctx, block);
  352. result->addIncoming(input, block);
  353. BranchInst::Create(done, init, IsSpecial(input, block), block);
  354. block = init;
  355. const auto setFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TState::Reset));
  356. const auto setType = FunctionType::get(valueType, {statePtrType, valueType}, false);
  357. const auto setPtr = CastInst::Create(Instruction::IntToPtr, setFunc, PointerType::getUnqual(setType), "set", block);
  358. CallInst::Create(setType, setPtr, {stateArg, input }, "", block);
  359. BranchInst::Create(work, block);
  360. block = done;
  361. return result;
  362. }
  363. #endif
  364. private:
  365. struct TState : public TComputationValue<TState> {
  366. using TComputationValue::TComputationValue;
  367. TState(TMemoryUsageInfo* memInfo, TType* itemType, const NUdf::IPgBuilder& pgBuilder)
  368. : TComputationValue(memInfo)
  369. , Reader_(MakeBlockReader(TTypeInfoHelper(), itemType))
  370. , Converter_(MakeBlockItemConverter(TTypeInfoHelper(), itemType, pgBuilder))
  371. {
  372. }
  373. NUdf::TUnboxedValuePod GetValue(const THolderFactory& holderFactory) {
  374. for (;;) {
  375. if (Arrays_.empty()) {
  376. return NUdf::TUnboxedValuePod::Invalid();
  377. }
  378. if (Index_ < ui64(Arrays_.front()->length)) {
  379. break;
  380. }
  381. Index_ = 0;
  382. Arrays_.pop_front();
  383. }
  384. return Converter_->MakeValue(Reader_->GetItem(*Arrays_.front(), Index_++), holderFactory);
  385. }
  386. void Reset(const NUdf::TUnboxedValuePod block) {
  387. const NUdf::TUnboxedValue v(block);
  388. const auto& datum = TArrowBlock::From(v).GetDatum();
  389. MKQL_ENSURE(datum.is_arraylike(), "Expecting array as FromBlocks argument");
  390. MKQL_ENSURE(Arrays_.empty(), "Not all input is processed");
  391. if (datum.is_array()) {
  392. Arrays_.push_back(datum.array());
  393. } else {
  394. for (const auto& chunk : datum.chunks()) {
  395. Arrays_.push_back(chunk->data());
  396. }
  397. }
  398. Index_ = 0;
  399. }
  400. private:
  401. const std::unique_ptr<IBlockReader> Reader_;
  402. const std::unique_ptr<IBlockItemConverter> Converter_;
  403. TDeque<std::shared_ptr<arrow::ArrayData>> Arrays_;
  404. size_t Index_ = 0;
  405. };
  406. private:
  407. void RegisterDependencies() const final {
  408. FlowDependsOn(Flow_);
  409. }
  410. void MakeState(TComputationContext& ctx, NUdf::TUnboxedValue& state) const {
  411. state = ctx.HolderFactory.Create<TState>(ItemType_, ctx.Builder->GetPgBuilder());
  412. }
  413. TState& GetState(NUdf::TUnboxedValue& state, TComputationContext& ctx) const {
  414. if (state.IsInvalid())
  415. MakeState(ctx, state);
  416. return *static_cast<TState*>(state.AsBoxed().Get());
  417. }
  418. private:
  419. IComputationNode* const Flow_;
  420. TType* ItemType_;
  421. };
  422. class TWideFromBlocksWrapper : public TStatefulWideFlowCodegeneratorNode<TWideFromBlocksWrapper> {
  423. using TBaseComputation = TStatefulWideFlowCodegeneratorNode<TWideFromBlocksWrapper>;
  424. public:
  425. TWideFromBlocksWrapper(TComputationMutables& mutables,
  426. IComputationWideFlowNode* flow,
  427. TVector<TType*>&& types)
  428. : TBaseComputation(mutables, flow, EValueRepresentation::Boxed)
  429. , Flow_(flow)
  430. , Types_(std::move(types))
  431. , WideFieldsIndex_(mutables.IncrementWideFieldsIndex(Types_.size() + 1U))
  432. {}
  433. EFetchResult DoCalculate(NUdf::TUnboxedValue& state,
  434. TComputationContext& ctx,
  435. NUdf::TUnboxedValue*const* output) const
  436. {
  437. auto& s = GetState(state, ctx);
  438. const auto fields = ctx.WideFields.data() + WideFieldsIndex_;
  439. if (s.Index_ == s.Count_) do {
  440. if (const auto result = Flow_->FetchValues(ctx, fields); result != EFetchResult::One)
  441. return result;
  442. s.Index_ = 0;
  443. s.Count_ = GetBlockCount(s.Values_.back());
  444. } while (!s.Count_);
  445. s.Current_ = s.Index_;
  446. ++s.Index_;
  447. for (size_t i = 0; i < Types_.size(); ++i)
  448. if (const auto out = output[i])
  449. *out = s.Get(ctx.HolderFactory, i);
  450. return EFetchResult::One;
  451. }
  452. #ifndef MKQL_DISABLE_CODEGEN
  453. ICodegeneratorInlineWideNode::TGenerateResult DoGenGetValues(const TCodegenContext& ctx, Value* statePtr, BasicBlock*& block) const {
  454. auto& context = ctx.Codegen.GetContext();
  455. const auto width = Types_.size();
  456. const auto valueType = Type::getInt128Ty(context);
  457. const auto ptrValueType = PointerType::getUnqual(valueType);
  458. const auto statusType = Type::getInt32Ty(context);
  459. const auto indexType = Type::getInt64Ty(context);
  460. const auto arrayType = ArrayType::get(valueType, width);
  461. const auto ptrValuesType = PointerType::getUnqual(ArrayType::get(valueType, width));
  462. TLLVMFieldsStructureState stateFields(context, width);
  463. const auto stateType = StructType::get(context, stateFields.GetFieldsArray());
  464. const auto statePtrType = PointerType::getUnqual(stateType);
  465. const auto getFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TState::Get));
  466. const auto getType = FunctionType::get(valueType, {statePtrType, ctx.GetFactory()->getType(), indexType}, false);
  467. const auto getPtr = CastInst::Create(Instruction::IntToPtr, getFunc, PointerType::getUnqual(getType), "get", &ctx.Func->getEntryBlock().back());
  468. const auto stateOnStack = new AllocaInst(statePtrType, 0U, "state_on_stack", &ctx.Func->getEntryBlock().back());
  469. new StoreInst(ConstantPointerNull::get(statePtrType), stateOnStack, &ctx.Func->getEntryBlock().back());
  470. const auto name = "GetBlockCount";
  471. ctx.Codegen.AddGlobalMapping(name, reinterpret_cast<const void*>(&GetBlockCount));
  472. const auto getCountType = NYql::NCodegen::ETarget::Windows != ctx.Codegen.GetEffectiveTarget() ?
  473. FunctionType::get(indexType, { valueType }, false):
  474. FunctionType::get(indexType, { ptrValueType }, false);
  475. const auto getCount = ctx.Codegen.GetModule().getOrInsertFunction(name, getCountType);
  476. const auto make = BasicBlock::Create(context, "make", ctx.Func);
  477. const auto main = BasicBlock::Create(context, "main", ctx.Func);
  478. const auto more = BasicBlock::Create(context, "more", ctx.Func);
  479. const auto good = BasicBlock::Create(context, "good", ctx.Func);
  480. const auto work = BasicBlock::Create(context, "work", ctx.Func);
  481. const auto over = BasicBlock::Create(context, "over", ctx.Func);
  482. BranchInst::Create(make, main, IsInvalid(statePtr, block), block);
  483. block = make;
  484. const auto ptrType = PointerType::getUnqual(StructType::get(context));
  485. const auto self = CastInst::Create(Instruction::IntToPtr, ConstantInt::get(Type::getInt64Ty(context), uintptr_t(this)), ptrType, "self", block);
  486. const auto makeFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TWideFromBlocksWrapper::MakeState));
  487. const auto makeType = FunctionType::get(Type::getVoidTy(context), {self->getType(), ctx.Ctx->getType(), statePtr->getType()}, false);
  488. const auto makeFuncPtr = CastInst::Create(Instruction::IntToPtr, makeFunc, PointerType::getUnqual(makeType), "function", block);
  489. CallInst::Create(makeType, makeFuncPtr, {self, ctx.Ctx, statePtr}, "", block);
  490. BranchInst::Create(main, block);
  491. block = main;
  492. const auto state = new LoadInst(valueType, statePtr, "state", block);
  493. const auto half = CastInst::Create(Instruction::Trunc, state, Type::getInt64Ty(context), "half", block);
  494. const auto stateArg = CastInst::Create(Instruction::IntToPtr, half, statePtrType, "state_arg", block);
  495. const auto countPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetCount() }, "count_ptr", block);
  496. const auto indexPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetIndex() }, "index_ptr", block);
  497. const auto count = new LoadInst(indexType, countPtr, "count", block);
  498. const auto index = new LoadInst(indexType, indexPtr, "index", block);
  499. const auto next = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, count, index, "next", block);
  500. BranchInst::Create(more, work, next, block);
  501. block = more;
  502. const auto clearFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TState::ClearValues));
  503. const auto clearType = FunctionType::get(Type::getVoidTy(context), {statePtrType}, false);
  504. const auto clearPtr = CastInst::Create(Instruction::IntToPtr, clearFunc, PointerType::getUnqual(clearType), "clear", block);
  505. CallInst::Create(clearType, clearPtr, {stateArg}, "", block);
  506. const auto getres = GetNodeValues(Flow_, ctx, block);
  507. const auto special = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_SLE, getres.first, ConstantInt::get(getres.first->getType(), static_cast<i32>(EFetchResult::Yield)), "special", block);
  508. const auto result = PHINode::Create(statusType, 2U, "result", over);
  509. result->addIncoming(getres.first, block);
  510. BranchInst::Create(over, good, special, block);
  511. block = good;
  512. const auto countValue = getres.second.back()(ctx, block);
  513. const auto height = CallInst::Create(getCount, { WrapArgumentForWindows(countValue, ctx, block) }, "height", block);
  514. new StoreInst(height, countPtr, block);
  515. new StoreInst(ConstantInt::get(indexType, 0), indexPtr, block);
  516. const auto empty = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, ConstantInt::get(indexType, 0), height, "empty", block);
  517. BranchInst::Create(more, work, empty, block);
  518. block = work;
  519. const auto current = new LoadInst(indexType, indexPtr, "current", block);
  520. const auto currentPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetCurrent() }, "current_ptr", block);
  521. new StoreInst(current, currentPtr, block);
  522. const auto increment = BinaryOperator::CreateAdd(current, ConstantInt::get(indexType, 1), "increment", block);
  523. new StoreInst(increment, indexPtr, block);
  524. new StoreInst(stateArg, stateOnStack, block);
  525. result->addIncoming(ConstantInt::get(statusType, static_cast<i32>(EFetchResult::One)), block);
  526. BranchInst::Create(over, block);
  527. block = over;
  528. ICodegeneratorInlineWideNode::TGettersList getters(width);
  529. for (size_t idx = 0U; idx < getters.size(); ++idx) {
  530. getters[idx] = [idx, width, getType, getPtr, indexType, arrayType, ptrValuesType, stateType, statePtrType, stateOnStack, getBlocks = getres.second](const TCodegenContext& ctx, BasicBlock*& block) {
  531. auto& context = ctx.Codegen.GetContext();
  532. const auto init = BasicBlock::Create(context, "init", ctx.Func);
  533. const auto call = BasicBlock::Create(context, "call", ctx.Func);
  534. TLLVMFieldsStructureState stateFields(context, width);
  535. const auto stateArg = new LoadInst(statePtrType, stateOnStack, "state", block);
  536. const auto valuesPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetPointer() }, "values_ptr", block);
  537. const auto values = new LoadInst(ptrValuesType, valuesPtr, "values", block);
  538. const auto index = ConstantInt::get(indexType, idx);
  539. const auto pointer = GetElementPtrInst::CreateInBounds(arrayType, values, { ConstantInt::get(indexType, 0), index }, "pointer", block);
  540. BranchInst::Create(call, init, HasValue(pointer, block), block);
  541. block = init;
  542. const auto value = getBlocks[idx](ctx, block);
  543. new StoreInst(value, pointer, block);
  544. AddRefBoxed(value, ctx, block);
  545. BranchInst::Create(call, block);
  546. block = call;
  547. return CallInst::Create(getType, getPtr, {stateArg, ctx.GetFactory(), index}, "get", block);
  548. };
  549. }
  550. return {result, std::move(getters)};
  551. }
  552. #endif
  553. private:
  554. struct TState : public TComputationValue<TState> {
  555. size_t Count_ = 0;
  556. size_t Index_ = 0;
  557. size_t Current_ = 0;
  558. NUdf::TUnboxedValue* Pointer_ = nullptr;
  559. TUnboxedValueVector Values_;
  560. std::vector<std::unique_ptr<IBlockReader>> Readers_;
  561. std::vector<std::unique_ptr<IBlockItemConverter>> Converters_;
  562. const std::vector<arrow::ValueDescr> ValuesDescr_;
  563. TState(TMemoryUsageInfo* memInfo, TComputationContext& ctx, const TVector<TType*>& types)
  564. : TComputationValue(memInfo)
  565. , Values_(types.size() + 1)
  566. , ValuesDescr_(ToValueDescr(types))
  567. {
  568. Pointer_ = Values_.data();
  569. const auto& pgBuilder = ctx.Builder->GetPgBuilder();
  570. for (size_t i = 0; i < types.size(); ++i) {
  571. const TType* blockItemType = AS_TYPE(TBlockType, types[i])->GetItemType();
  572. Readers_.push_back(MakeBlockReader(TTypeInfoHelper(), blockItemType));
  573. Converters_.push_back(MakeBlockItemConverter(TTypeInfoHelper(), blockItemType, pgBuilder));
  574. }
  575. }
  576. void ClearValues() {
  577. Values_.assign(Values_.size(), NUdf::TUnboxedValuePod());
  578. }
  579. NUdf::TUnboxedValuePod Get(const THolderFactory& holderFactory, size_t idx) const {
  580. TBlockItem item;
  581. const auto& datum = TArrowBlock::From(Values_[idx]).GetDatum();
  582. ARROW_DEBUG_CHECK_DATUM_TYPES(ValuesDescr_[idx], datum.descr());
  583. if (datum.is_scalar()) {
  584. item = Readers_[idx]->GetScalarItem(*datum.scalar());
  585. } else {
  586. MKQL_ENSURE(datum.is_array(), "Expecting array");
  587. item = Readers_[idx]->GetItem(*datum.array(), Current_);
  588. }
  589. return Converters_[idx]->MakeValue(item, holderFactory);
  590. }
  591. };
  592. #ifndef MKQL_DISABLE_CODEGEN
  593. class TLLVMFieldsStructureState: public TLLVMFieldsStructure<TComputationValue<TState>> {
  594. private:
  595. using TBase = TLLVMFieldsStructure<TComputationValue<TState>>;
  596. llvm::IntegerType*const CountType;
  597. llvm::IntegerType*const IndexType;
  598. llvm::IntegerType*const CurrentType;
  599. llvm::PointerType*const PointerType;
  600. protected:
  601. using TBase::Context;
  602. public:
  603. std::vector<llvm::Type*> GetFieldsArray() {
  604. std::vector<llvm::Type*> result = TBase::GetFields();
  605. result.emplace_back(CountType);
  606. result.emplace_back(IndexType);
  607. result.emplace_back(CurrentType);
  608. result.emplace_back(PointerType);
  609. return result;
  610. }
  611. llvm::Constant* GetCount() {
  612. return ConstantInt::get(Type::getInt32Ty(Context), TBase::GetFieldsCount() + 0);
  613. }
  614. llvm::Constant* GetIndex() {
  615. return ConstantInt::get(Type::getInt32Ty(Context), TBase::GetFieldsCount() + 1);
  616. }
  617. llvm::Constant* GetCurrent() {
  618. return ConstantInt::get(Type::getInt32Ty(Context), TBase::GetFieldsCount() + 2);
  619. }
  620. llvm::Constant* GetPointer() {
  621. return ConstantInt::get(Type::getInt32Ty(Context), TBase::GetFieldsCount() + 3);
  622. }
  623. TLLVMFieldsStructureState(llvm::LLVMContext& context, size_t width)
  624. : TBase(context)
  625. , CountType(Type::getInt64Ty(Context))
  626. , IndexType(Type::getInt64Ty(Context))
  627. , CurrentType(Type::getInt64Ty(Context))
  628. , PointerType(PointerType::getUnqual(ArrayType::get(Type::getInt128Ty(Context), width)))
  629. {}
  630. };
  631. #endif
  632. void RegisterDependencies() const final {
  633. FlowDependsOn(Flow_);
  634. }
  635. void MakeState(TComputationContext& ctx, NUdf::TUnboxedValue& state) const {
  636. state = ctx.HolderFactory.Create<TState>(ctx, Types_);
  637. }
  638. TState& GetState(NUdf::TUnboxedValue& state, TComputationContext& ctx) const {
  639. if (state.IsInvalid()) {
  640. MakeState(ctx, state);
  641. const auto s = static_cast<TState*>(state.AsBoxed().Get());
  642. auto**const fields = ctx.WideFields.data() + WideFieldsIndex_;
  643. for (size_t i = 0; i <= Types_.size(); ++i) {
  644. fields[i] = &s->Values_[i];
  645. }
  646. return *s;
  647. }
  648. return *static_cast<TState*>(state.AsBoxed().Get());
  649. }
  650. IComputationWideFlowNode* const Flow_;
  651. const TVector<TType*> Types_;
  652. const size_t WideFieldsIndex_;
  653. };
  654. class TPrecomputedArrowNode : public IArrowKernelComputationNode {
  655. public:
  656. TPrecomputedArrowNode(const arrow::Datum& datum, TStringBuf kernelName)
  657. : Kernel_({}, datum.type(), [datum](arrow::compute::KernelContext*, const arrow::compute::ExecBatch&, arrow::Datum* res) {
  658. *res = datum;
  659. return arrow::Status::OK();
  660. })
  661. , KernelName_(kernelName)
  662. {
  663. Kernel_.null_handling = arrow::compute::NullHandling::COMPUTED_NO_PREALLOCATE;
  664. Kernel_.mem_allocation = arrow::compute::MemAllocation::NO_PREALLOCATE;
  665. }
  666. TStringBuf GetKernelName() const final {
  667. return KernelName_;
  668. }
  669. const arrow::compute::ScalarKernel& GetArrowKernel() const {
  670. return Kernel_;
  671. }
  672. const std::vector<arrow::ValueDescr>& GetArgsDesc() const {
  673. return EmptyDesc_;
  674. }
  675. const IComputationNode* GetArgument(ui32 index) const {
  676. Y_UNUSED(index);
  677. ythrow yexception() << "No input arguments";
  678. }
  679. private:
  680. arrow::compute::ScalarKernel Kernel_;
  681. const TStringBuf KernelName_;
  682. const std::vector<arrow::ValueDescr> EmptyDesc_;
  683. };
  684. class TAsScalarWrapper : public TMutableCodegeneratorNode<TAsScalarWrapper> {
  685. using TBaseComputation = TMutableCodegeneratorNode<TAsScalarWrapper>;
  686. public:
  687. TAsScalarWrapper(TComputationMutables& mutables, IComputationNode* arg, TType* type)
  688. : TBaseComputation(mutables, EValueRepresentation::Boxed)
  689. , Arg_(arg)
  690. , Type_(type)
  691. {
  692. std::shared_ptr<arrow::DataType> arrowType;
  693. MKQL_ENSURE(ConvertArrowType(Type_, arrowType), "Unsupported type of scalar");
  694. }
  695. NUdf::TUnboxedValuePod DoCalculate(TComputationContext& ctx) const {
  696. return AsScalar(Arg_->GetValue(ctx).Release(), ctx);
  697. }
  698. #ifndef MKQL_DISABLE_CODEGEN
  699. Value* DoGenerateGetValue(const TCodegenContext& ctx, BasicBlock*& block) const {
  700. auto& context = ctx.Codegen.GetContext();
  701. const auto value = GetNodeValue(Arg_, ctx, block);
  702. const auto ptrType = PointerType::getUnqual(StructType::get(context));
  703. const auto self = CastInst::Create(Instruction::IntToPtr, ConstantInt::get(Type::getInt64Ty(context), uintptr_t(this)), ptrType, "self", block);
  704. const auto asScalarFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TAsScalarWrapper::AsScalar));
  705. if (NYql::NCodegen::ETarget::Windows != ctx.Codegen.GetEffectiveTarget()) {
  706. const auto asScalarType = FunctionType::get(Type::getInt128Ty(context), {self->getType(), value->getType(), ctx.Ctx->getType()}, false);
  707. const auto asScalarFuncPtr = CastInst::Create(Instruction::IntToPtr, asScalarFunc, PointerType::getUnqual(asScalarType), "function", block);
  708. return CallInst::Create(asScalarType, asScalarFuncPtr, {self, value, ctx.Ctx}, "scalar", block);
  709. } else {
  710. const auto valuePtr = new AllocaInst(value->getType(), 0U, "value", block);
  711. new StoreInst(value, valuePtr, block);
  712. const auto asScalarType = FunctionType::get(Type::getVoidTy(context), {self->getType(), valuePtr->getType(), valuePtr->getType(), ctx.Ctx->getType()}, false);
  713. const auto asScalarFuncPtr = CastInst::Create(Instruction::IntToPtr, asScalarFunc, PointerType::getUnqual(asScalarType), "function", block);
  714. CallInst::Create(asScalarType, asScalarFuncPtr, {self, valuePtr, valuePtr, ctx.Ctx}, "", block);
  715. return new LoadInst(value->getType(), valuePtr, "result", block);
  716. }
  717. }
  718. #endif
  719. private:
  720. std::unique_ptr<IArrowKernelComputationNode> PrepareArrowKernelComputationNode(TComputationContext& ctx) const final {
  721. return std::make_unique<TPrecomputedArrowNode>(DoAsScalar(Arg_->GetValue(ctx).Release(), ctx), "AsScalar");
  722. }
  723. arrow::Datum DoAsScalar(const NUdf::TUnboxedValuePod value, TComputationContext& ctx) const {
  724. const NUdf::TUnboxedValue v(value);
  725. return ConvertScalar(Type_, v, ctx.ArrowMemoryPool);
  726. }
  727. NUdf::TUnboxedValuePod AsScalar(const NUdf::TUnboxedValuePod value, TComputationContext& ctx) const {
  728. return ctx.HolderFactory.CreateArrowBlock(DoAsScalar(value, ctx));
  729. }
  730. void RegisterDependencies() const final {
  731. DependsOn(Arg_);
  732. }
  733. IComputationNode* const Arg_;
  734. TType* Type_;
  735. };
  736. class TReplicateScalarWrapper : public TMutableCodegeneratorNode<TReplicateScalarWrapper> {
  737. using TBaseComputation = TMutableCodegeneratorNode<TReplicateScalarWrapper>;
  738. public:
  739. TReplicateScalarWrapper(TComputationMutables& mutables, IComputationNode* value, IComputationNode* count, TType* type)
  740. : TBaseComputation(mutables, EValueRepresentation::Boxed)
  741. , Value_(value)
  742. , Count_(count)
  743. , Type_(type)
  744. {
  745. std::shared_ptr<arrow::DataType> arrowType;
  746. MKQL_ENSURE(ConvertArrowType(Type_, arrowType), "Unsupported type of scalar");
  747. }
  748. NUdf::TUnboxedValuePod DoCalculate(TComputationContext& ctx) const {
  749. const auto value = Value_->GetValue(ctx).Release();
  750. const auto count = Count_->GetValue(ctx).Release();
  751. return Replicate(value, count, ctx);
  752. }
  753. #ifndef MKQL_DISABLE_CODEGEN
  754. Value* DoGenerateGetValue(const TCodegenContext& ctx, BasicBlock*& block) const {
  755. auto& context = ctx.Codegen.GetContext();
  756. const auto value = GetNodeValue(Value_, ctx, block);
  757. const auto count = GetNodeValue(Count_, ctx, block);
  758. const auto ptrType = PointerType::getUnqual(StructType::get(context));
  759. const auto self = CastInst::Create(Instruction::IntToPtr, ConstantInt::get(Type::getInt64Ty(context), uintptr_t(this)), ptrType, "self", block);
  760. const auto replicateFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TReplicateScalarWrapper::Replicate));
  761. if (NYql::NCodegen::ETarget::Windows != ctx.Codegen.GetEffectiveTarget()) {
  762. const auto replicateType = FunctionType::get(Type::getInt128Ty(context), {self->getType(), value->getType(), count->getType(), ctx.Ctx->getType()}, false);
  763. const auto replicateFuncPtr = CastInst::Create(Instruction::IntToPtr, replicateFunc, PointerType::getUnqual(replicateType), "function", block);
  764. return CallInst::Create(replicateType, replicateFuncPtr, {self, value, count, ctx.Ctx}, "replicate", block);
  765. } else {
  766. const auto valuePtr = new AllocaInst(value->getType(), 0U, "value", block);
  767. const auto countPtr = new AllocaInst(count->getType(), 0U, "count", block);
  768. new StoreInst(value, valuePtr, block);
  769. new StoreInst(count, countPtr, block);
  770. const auto replicateType = FunctionType::get(Type::getVoidTy(context), {self->getType(), valuePtr->getType(), valuePtr->getType(), countPtr->getType(), ctx.Ctx->getType()}, false);
  771. const auto replicateFuncPtr = CastInst::Create(Instruction::IntToPtr, replicateFunc, PointerType::getUnqual(replicateType), "function", block);
  772. CallInst::Create(replicateType, replicateFuncPtr, {self, valuePtr, valuePtr, countPtr, ctx.Ctx}, "", block);
  773. return new LoadInst(value->getType(), valuePtr, "result", block);
  774. }
  775. }
  776. #endif
  777. private:
  778. std::unique_ptr<IArrowKernelComputationNode> PrepareArrowKernelComputationNode(TComputationContext& ctx) const final {
  779. const auto value = Value_->GetValue(ctx).Release();
  780. const auto count = Count_->GetValue(ctx).Release();
  781. return std::make_unique<TPrecomputedArrowNode>(DoReplicate(value, count, ctx), "ReplicateScalar");
  782. }
  783. arrow::Datum DoReplicate(const NUdf::TUnboxedValuePod val, const NUdf::TUnboxedValuePod cnt, TComputationContext& ctx) const {
  784. const NUdf::TUnboxedValue v(val), c(cnt);
  785. const auto value = TArrowBlock::From(v).GetDatum().scalar();
  786. const ui64 count = TArrowBlock::From(c).GetDatum().scalar_as<arrow::UInt64Scalar>().value;
  787. const auto reader = MakeBlockReader(TTypeInfoHelper(), Type_);
  788. const auto builder = MakeArrayBuilder(TTypeInfoHelper(), Type_, ctx.ArrowMemoryPool, count, &ctx.Builder->GetPgBuilder());
  789. TBlockItem item = reader->GetScalarItem(*value);
  790. builder->Add(item, count);
  791. return builder->Build(true);
  792. }
  793. NUdf::TUnboxedValuePod Replicate(const NUdf::TUnboxedValuePod value, const NUdf::TUnboxedValuePod count, TComputationContext& ctx) const {
  794. return ctx.HolderFactory.CreateArrowBlock(DoReplicate(value, count, ctx));
  795. }
  796. void RegisterDependencies() const final {
  797. DependsOn(Value_);
  798. DependsOn(Count_);
  799. }
  800. IComputationNode* const Value_;
  801. IComputationNode* const Count_;
  802. TType* Type_;
  803. };
  804. class TBlockExpandChunkedWrapper : public TStatefulWideFlowCodegeneratorNode<TBlockExpandChunkedWrapper> {
  805. using TBaseComputation = TStatefulWideFlowCodegeneratorNode<TBlockExpandChunkedWrapper>;
  806. public:
  807. TBlockExpandChunkedWrapper(TComputationMutables& mutables, IComputationWideFlowNode* flow, size_t width)
  808. : TBaseComputation(mutables, flow, EValueRepresentation::Boxed)
  809. , Flow_(flow)
  810. , Width_(width)
  811. , WideFieldsIndex_(mutables.IncrementWideFieldsIndex(Width_))
  812. {
  813. }
  814. EFetchResult DoCalculate(NUdf::TUnboxedValue& state, TComputationContext& ctx, NUdf::TUnboxedValue*const* output) const {
  815. auto& s = GetState(state, ctx);
  816. if (!s.Count) {
  817. const auto fields = ctx.WideFields.data() + WideFieldsIndex_;
  818. s.ClearValues();
  819. if (const auto result = Flow_->FetchValues(ctx, fields); result != EFetchResult::One)
  820. return result;
  821. s.FillArrays();
  822. }
  823. const auto sliceSize = s.Slice();
  824. for (size_t i = 0; i < Width_; ++i) {
  825. if (const auto out = output[i]) {
  826. *out = s.Get(sliceSize, ctx.HolderFactory, i);
  827. }
  828. }
  829. return EFetchResult::One;
  830. }
  831. #ifndef MKQL_DISABLE_CODEGEN
  832. ICodegeneratorInlineWideNode::TGenerateResult DoGenGetValues(const TCodegenContext& ctx, Value* statePtr, BasicBlock*& block) const {
  833. auto& context = ctx.Codegen.GetContext();
  834. const auto valueType = Type::getInt128Ty(context);
  835. const auto statusType = Type::getInt32Ty(context);
  836. const auto indexType = Type::getInt64Ty(context);
  837. const auto arrayType = ArrayType::get(valueType, Width_);
  838. const auto ptrValuesType = PointerType::getUnqual(arrayType);
  839. TLLVMFieldsStructureBlockState stateFields(context, Width_);
  840. const auto stateType = StructType::get(context, stateFields.GetFieldsArray());
  841. const auto statePtrType = PointerType::getUnqual(stateType);
  842. const auto atTop = &ctx.Func->getEntryBlock().back();
  843. const auto getFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TBlockState::Get));
  844. const auto getType = FunctionType::get(valueType, {statePtrType, indexType, ctx.GetFactory()->getType(), indexType}, false);
  845. const auto getPtr = CastInst::Create(Instruction::IntToPtr, getFunc, PointerType::getUnqual(getType), "get", atTop);
  846. const auto heightPtr = new AllocaInst(indexType, 0U, "height_ptr", atTop);
  847. const auto stateOnStack = new AllocaInst(statePtrType, 0U, "state_on_stack", atTop);
  848. new StoreInst(ConstantInt::get(indexType, 0), heightPtr, atTop);
  849. new StoreInst(ConstantPointerNull::get(statePtrType), stateOnStack, atTop);
  850. const auto make = BasicBlock::Create(context, "make", ctx.Func);
  851. const auto main = BasicBlock::Create(context, "main", ctx.Func);
  852. const auto read = BasicBlock::Create(context, "read", ctx.Func);
  853. const auto work = BasicBlock::Create(context, "work", ctx.Func);
  854. const auto fill = BasicBlock::Create(context, "fill", ctx.Func);
  855. const auto over = BasicBlock::Create(context, "over", ctx.Func);
  856. BranchInst::Create(make, main, IsInvalid(statePtr, block), block);
  857. block = make;
  858. const auto ptrType = PointerType::getUnqual(StructType::get(context));
  859. const auto self = CastInst::Create(Instruction::IntToPtr, ConstantInt::get(Type::getInt64Ty(context), uintptr_t(this)), ptrType, "self", block);
  860. const auto makeFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TBlockExpandChunkedWrapper::MakeState));
  861. const auto makeType = FunctionType::get(Type::getVoidTy(context), {self->getType(), ctx.Ctx->getType(), statePtr->getType()}, false);
  862. const auto makeFuncPtr = CastInst::Create(Instruction::IntToPtr, makeFunc, PointerType::getUnqual(makeType), "function", block);
  863. CallInst::Create(makeType, makeFuncPtr, {self, ctx.Ctx, statePtr}, "", block);
  864. BranchInst::Create(main, block);
  865. block = main;
  866. const auto state = new LoadInst(valueType, statePtr, "state", block);
  867. const auto half = CastInst::Create(Instruction::Trunc, state, Type::getInt64Ty(context), "half", block);
  868. const auto stateArg = CastInst::Create(Instruction::IntToPtr, half, statePtrType, "state_arg", block);
  869. const auto countPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetCount() }, "count_ptr", block);
  870. const auto count = new LoadInst(indexType, countPtr, "count", block);
  871. const auto next = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, count, ConstantInt::get(indexType, 0), "next", block);
  872. BranchInst::Create(read, fill, next, block);
  873. block = read;
  874. const auto clearFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TBlockState::ClearValues));
  875. const auto clearType = FunctionType::get(Type::getVoidTy(context), {statePtrType}, false);
  876. const auto clearPtr = CastInst::Create(Instruction::IntToPtr, clearFunc, PointerType::getUnqual(clearType), "clear", block);
  877. CallInst::Create(clearType, clearPtr, {stateArg}, "", block);
  878. const auto getres = GetNodeValues(Flow_, ctx, block);
  879. const auto special = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_SLE, getres.first, ConstantInt::get(getres.first->getType(), static_cast<i32>(EFetchResult::Yield)), "special", block);
  880. const auto result = PHINode::Create(statusType, 2U, "result", over);
  881. result->addIncoming(getres.first, block);
  882. BranchInst::Create(over, work, special, block);
  883. block = work;
  884. const auto valuesPtr = GetElementPtrInst::CreateInBounds(stateType, stateArg, { stateFields.This(), stateFields.GetPointer() }, "values_ptr", block);
  885. const auto values = new LoadInst(ptrValuesType, valuesPtr, "values", block);
  886. Value* array = UndefValue::get(arrayType);
  887. for (auto idx = 0U; idx < getres.second.size(); ++idx) {
  888. const auto value = getres.second[idx](ctx, block);
  889. AddRefBoxed(value, ctx, block);
  890. array = InsertValueInst::Create(array, value, {idx}, (TString("value_") += ToString(idx)).c_str(), block);
  891. }
  892. new StoreInst(array, values, block);
  893. const auto fillArraysFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TBlockState::FillArrays));
  894. const auto fillArraysType = FunctionType::get(Type::getVoidTy(context), {statePtrType}, false);
  895. const auto fillArraysPtr = CastInst::Create(Instruction::IntToPtr, fillArraysFunc, PointerType::getUnqual(fillArraysType), "fill_arrays_func", block);
  896. CallInst::Create(fillArraysType, fillArraysPtr, {stateArg}, "", block);
  897. BranchInst::Create(fill, block);
  898. block = fill;
  899. const auto sliceFunc = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TBlockState::Slice));
  900. const auto sliceType = FunctionType::get(indexType, {statePtrType}, false);
  901. const auto slicePtr = CastInst::Create(Instruction::IntToPtr, sliceFunc, PointerType::getUnqual(sliceType), "slice_func", block);
  902. const auto slice = CallInst::Create(sliceType, slicePtr, {stateArg}, "slice", block);
  903. new StoreInst(slice, heightPtr, block);
  904. new StoreInst(stateArg, stateOnStack, block);
  905. result->addIncoming(ConstantInt::get(statusType, static_cast<i32>(EFetchResult::One)), block);
  906. BranchInst::Create(over, block);
  907. block = over;
  908. ICodegeneratorInlineWideNode::TGettersList getters(Width_);
  909. for (size_t idx = 0U; idx < getters.size(); ++idx) {
  910. getters[idx] = [idx, getType, getPtr, heightPtr, indexType, statePtrType, stateOnStack](const TCodegenContext& ctx, BasicBlock*& block) {
  911. const auto stateArg = new LoadInst(statePtrType, stateOnStack, "state", block);
  912. const auto heightArg = new LoadInst(indexType, heightPtr, "height", block);
  913. return CallInst::Create(getType, getPtr, {stateArg, heightArg, ctx.GetFactory(), ConstantInt::get(indexType, idx)}, "get", block);
  914. };
  915. }
  916. return {result, std::move(getters)};
  917. }
  918. #endif
  919. private:
  920. void MakeState(TComputationContext& ctx, NUdf::TUnboxedValue& state) const {
  921. state = ctx.HolderFactory.Create<TBlockState>(Width_);
  922. }
  923. TBlockState& GetState(NUdf::TUnboxedValue& state, TComputationContext& ctx) const {
  924. if (state.IsInvalid()) {
  925. MakeState(ctx, state);
  926. auto& s = *static_cast<TBlockState*>(state.AsBoxed().Get());
  927. const auto fields = ctx.WideFields.data() + WideFieldsIndex_;
  928. for (size_t i = 0; i < Width_; ++i)
  929. fields[i] = &s.Values[i];
  930. return s;
  931. }
  932. return *static_cast<TBlockState*>(state.AsBoxed().Get());
  933. }
  934. void RegisterDependencies() const final {
  935. FlowDependsOn(Flow_);
  936. }
  937. IComputationWideFlowNode* const Flow_;
  938. const size_t Width_;
  939. const size_t WideFieldsIndex_;
  940. };
  941. class TBlockExpandChunkedStreamWrapper : public TMutableComputationNode<TBlockExpandChunkedStreamWrapper> {
  942. using TBaseComputation = TMutableComputationNode<TBlockExpandChunkedStreamWrapper>;
  943. class TExpanderState : public TComputationValue<TExpanderState> {
  944. using TBase = TComputationValue<TExpanderState>;
  945. public:
  946. TExpanderState(TMemoryUsageInfo* memInfo, TComputationContext& ctx, NUdf::TUnboxedValue&& stream, size_t width)
  947. : TBase(memInfo), HolderFactory_(ctx.HolderFactory), State_(ctx.HolderFactory.Create<TBlockState>(width)), Stream_(stream) {}
  948. NUdf::EFetchStatus WideFetch(NUdf::TUnboxedValue* output, ui32 width) {
  949. auto& s = *static_cast<TBlockState*>(State_.AsBoxed().Get());
  950. if (!s.Count) {
  951. s.ClearValues();
  952. auto result = Stream_.WideFetch(s.Values.data(), width);
  953. if (NUdf::EFetchStatus::Ok != result) {
  954. return result;
  955. }
  956. s.FillArrays();
  957. }
  958. const auto sliceSize = s.Slice();
  959. for (size_t i = 0; i < width; ++i) {
  960. output[i] = s.Get(sliceSize, HolderFactory_, i);
  961. }
  962. return NUdf::EFetchStatus::Ok;
  963. }
  964. private:
  965. const THolderFactory& HolderFactory_;
  966. NUdf::TUnboxedValue State_;
  967. NUdf::TUnboxedValue Stream_;
  968. };
  969. public:
  970. TBlockExpandChunkedStreamWrapper(TComputationMutables& mutables, IComputationNode* stream, size_t width)
  971. : TBaseComputation(mutables, EValueRepresentation::Boxed)
  972. , Stream_(stream)
  973. , Width_(width) {}
  974. NUdf::TUnboxedValuePod DoCalculate(TComputationContext& ctx) const {
  975. return ctx.HolderFactory.Create<TExpanderState>(ctx, std::move(Stream_->GetValue(ctx)), Width_);
  976. }
  977. void RegisterDependencies() const override {}
  978. private:
  979. IComputationNode* const Stream_;
  980. const size_t Width_;
  981. };
  982. } // namespace
  983. IComputationNode* WrapToBlocks(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
  984. MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 args, got " << callable.GetInputsCount());
  985. const auto flowType = AS_TYPE(TFlowType, callable.GetInput(0).GetStaticType());
  986. return new TToBlocksWrapper(LocateNode(ctx.NodeLocator, callable, 0), flowType->GetItemType());
  987. }
  988. IComputationNode* WrapWideToBlocks(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
  989. MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 args, got " << callable.GetInputsCount());
  990. const auto flowType = AS_TYPE(TFlowType, callable.GetInput(0).GetStaticType());
  991. const auto wideComponents = GetWideComponents(flowType);
  992. TVector<TType*> items(wideComponents.begin(), wideComponents.end());
  993. const auto wideFlow = dynamic_cast<IComputationWideFlowNode*>(LocateNode(ctx.NodeLocator, callable, 0));
  994. MKQL_ENSURE(wideFlow != nullptr, "Expected wide flow node");
  995. return new TWideToBlocksWrapper(ctx.Mutables, wideFlow, std::move(items));
  996. }
  997. IComputationNode* WrapFromBlocks(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
  998. MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 args, got " << callable.GetInputsCount());
  999. const auto flowType = AS_TYPE(TFlowType, callable.GetInput(0).GetStaticType());
  1000. const auto blockType = AS_TYPE(TBlockType, flowType->GetItemType());
  1001. return new TFromBlocksWrapper(ctx.Mutables, LocateNode(ctx.NodeLocator, callable, 0), blockType->GetItemType());
  1002. }
  1003. IComputationNode* WrapWideFromBlocks(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
  1004. MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 args, got " << callable.GetInputsCount());
  1005. const auto flowType = AS_TYPE(TFlowType, callable.GetInput(0).GetStaticType());
  1006. const auto wideComponents = GetWideComponents(flowType);
  1007. MKQL_ENSURE(wideComponents.size() > 0, "Expected at least one column");
  1008. TVector<TType*> items;
  1009. for (ui32 i = 0; i < wideComponents.size() - 1; ++i) {
  1010. items.push_back(AS_TYPE(TBlockType, wideComponents[i]));
  1011. }
  1012. const auto wideFlow = dynamic_cast<IComputationWideFlowNode*>(LocateNode(ctx.NodeLocator, callable, 0));
  1013. MKQL_ENSURE(wideFlow != nullptr, "Expected wide flow node");
  1014. return new TWideFromBlocksWrapper(ctx.Mutables, wideFlow, std::move(items));
  1015. }
  1016. IComputationNode* WrapAsScalar(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
  1017. MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 args, got " << callable.GetInputsCount());
  1018. return new TAsScalarWrapper(ctx.Mutables, LocateNode(ctx.NodeLocator, callable, 0), callable.GetInput(0).GetStaticType());
  1019. }
  1020. IComputationNode* WrapReplicateScalar(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
  1021. MKQL_ENSURE(callable.GetInputsCount() == 2, "Expected 2 args, got " << callable.GetInputsCount());
  1022. const auto valueType = AS_TYPE(TBlockType, callable.GetInput(0).GetStaticType());
  1023. MKQL_ENSURE(valueType->GetShape() == TBlockType::EShape::Scalar, "Expecting scalar as first arg");
  1024. const auto value = LocateNode(ctx.NodeLocator, callable, 0);
  1025. const auto count = LocateNode(ctx.NodeLocator, callable, 1);
  1026. return new TReplicateScalarWrapper(ctx.Mutables, value, count, valueType->GetItemType());
  1027. }
  1028. IComputationNode* WrapBlockExpandChunked(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
  1029. MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 args, got " << callable.GetInputsCount());
  1030. if (callable.GetInput(0).GetStaticType()->IsStream()) {
  1031. const auto streamType = AS_TYPE(TStreamType, callable.GetInput(0).GetStaticType());
  1032. const auto wideComponents = GetWideComponents(streamType);
  1033. const auto computation = dynamic_cast<IComputationNode*>(LocateNode(ctx.NodeLocator, callable, 0));
  1034. MKQL_ENSURE(computation != nullptr, "Expected computation node");
  1035. return new TBlockExpandChunkedStreamWrapper(ctx.Mutables, computation, wideComponents.size());
  1036. } else {
  1037. const auto flowType = AS_TYPE(TFlowType, callable.GetInput(0).GetStaticType());
  1038. const auto wideComponents = GetWideComponents(flowType);
  1039. const auto wideFlow = dynamic_cast<IComputationWideFlowNode*>(LocateNode(ctx.NodeLocator, callable, 0));
  1040. MKQL_ENSURE(wideFlow != nullptr, "Expected wide flow node");
  1041. return new TBlockExpandChunkedWrapper(ctx.Mutables, wideFlow, wideComponents.size());
  1042. }
  1043. }
  1044. }
  1045. }