OmniSciDB  c0231cc57d
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
QueryTemplateGenerator.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "QueryTemplateGenerator.h"
18 #include "IRCodegenUtils.h"
19 #include "Logger/Logger.h"
20 
21 #include <llvm/IR/Constants.h>
22 #include <llvm/IR/IRBuilder.h>
23 #include <llvm/IR/Instructions.h>
24 #include <llvm/IR/Verifier.h>
25 
26 // This file was pretty much auto-generated by running:
27 // llc -march=cpp RuntimeFunctions.ll
28 // and formatting the results to be more readable.
29 
30 namespace {
31 
32 inline llvm::Type* get_pointer_element_type(llvm::Value* value) {
33  CHECK(value);
34  auto type = value->getType();
35  CHECK(type && type->isPointerTy());
36  auto pointer_type = llvm::dyn_cast<llvm::PointerType>(type);
37  CHECK(pointer_type);
38  return pointer_type->getPointerElementType();
39 }
40 
41 template <class Attributes>
42 llvm::Function* default_func_builder(llvm::Module* mod, const std::string& name) {
43  using namespace llvm;
44 
45  std::vector<Type*> func_args;
46  FunctionType* func_type = FunctionType::get(
47  /*Result=*/IntegerType::get(mod->getContext(), 32),
48  /*Params=*/func_args,
49  /*isVarArg=*/false);
50 
51  auto func_ptr = mod->getFunction(name);
52  if (!func_ptr) {
53  func_ptr = Function::Create(
54  /*Type=*/func_type,
55  /*Linkage=*/GlobalValue::ExternalLinkage,
56  /*Name=*/name,
57  mod); // (external, no body)
58  func_ptr->setCallingConv(CallingConv::C);
59  }
60 
61  Attributes func_pal;
62  {
63  SmallVector<Attributes, 4> Attrs;
64  Attributes PAS;
65  {
66 #if 14 <= LLVM_VERSION_MAJOR
67  AttrBuilder B(mod->getContext());
68 #else
69  AttrBuilder B;
70 #endif
71  PAS = Attributes::get(mod->getContext(), ~0U, B);
72  }
73 
74  Attrs.push_back(PAS);
75  func_pal = Attributes::get(mod->getContext(), Attrs);
76  }
77  func_ptr->setAttributes(func_pal);
78 
79  return func_ptr;
80 }
81 
82 template <class Attributes>
83 llvm::Function* pos_start(llvm::Module* mod) {
84  return default_func_builder<Attributes>(mod, "pos_start");
85 }
86 
87 template <class Attributes>
88 llvm::Function* group_buff_idx(llvm::Module* mod) {
89  return default_func_builder<Attributes>(mod, "group_buff_idx");
90 }
91 
92 template <class Attributes>
93 llvm::Function* pos_step(llvm::Module* mod) {
94  using namespace llvm;
95 
96  std::vector<Type*> func_args;
97  FunctionType* func_type = FunctionType::get(
98  /*Result=*/IntegerType::get(mod->getContext(), 32),
99  /*Params=*/func_args,
100  /*isVarArg=*/false);
101 
102  auto func_ptr = mod->getFunction("pos_step");
103  if (!func_ptr) {
104  func_ptr = Function::Create(
105  /*Type=*/func_type,
106  /*Linkage=*/GlobalValue::ExternalLinkage,
107  /*Name=*/"pos_step",
108  mod); // (external, no body)
109  func_ptr->setCallingConv(CallingConv::C);
110  }
111 
112  Attributes func_pal;
113  {
114  SmallVector<Attributes, 4> Attrs;
115  Attributes PAS;
116  {
117 #if 14 <= LLVM_VERSION_MAJOR
118  AttrBuilder B(mod->getContext());
119 #else
120  AttrBuilder B;
121 #endif
122  PAS = Attributes::get(mod->getContext(), ~0U, B);
123  }
124 
125  Attrs.push_back(PAS);
126  func_pal = Attributes::get(mod->getContext(), Attrs);
127  }
128  func_ptr->setAttributes(func_pal);
129 
130  return func_ptr;
131 }
132 
133 template <class Attributes>
134 llvm::Function* row_process(llvm::Module* mod,
135  const size_t aggr_col_count,
136  const bool hoist_literals) {
137  using namespace llvm;
138 
139  std::vector<Type*> func_args;
140  auto i8_type = IntegerType::get(mod->getContext(), 8);
141  auto i32_type = IntegerType::get(mod->getContext(), 32);
142  auto i64_type = IntegerType::get(mod->getContext(), 64);
143  auto pi32_type = PointerType::get(i32_type, 0);
144  auto pi64_type = PointerType::get(i64_type, 0);
145 
146  if (aggr_col_count) {
147  for (size_t i = 0; i < aggr_col_count; ++i) {
148  func_args.push_back(pi64_type);
149  }
150  } else { // group by query
151  func_args.push_back(pi64_type); // groups buffer
152  func_args.push_back(pi64_type); // varlen output buffer
153  func_args.push_back(pi32_type); // 1 iff current row matched, else 0
154  func_args.push_back(pi32_type); // total rows matched from the caller
155  func_args.push_back(pi32_type); // total rows matched before atomic increment
156  func_args.push_back(pi32_type); // max number of slots in the output buffer
157  }
158 
159  func_args.push_back(pi64_type); // aggregate init values
160 
161  func_args.push_back(i64_type);
162  func_args.push_back(pi64_type);
163  func_args.push_back(pi64_type);
164  if (hoist_literals) {
165  func_args.push_back(PointerType::get(i8_type, 0));
166  }
167  FunctionType* func_type = FunctionType::get(
168  /*Result=*/i32_type,
169  /*Params=*/func_args,
170  /*isVarArg=*/false);
171 
172  std::string func_name{"row_process"};
173  auto func_ptr = mod->getFunction(func_name);
174 
175  if (!func_ptr) {
176  func_ptr = Function::Create(
177  /*Type=*/func_type,
178  /*Linkage=*/GlobalValue::ExternalLinkage,
179  /*Name=*/func_name,
180  mod); // (external, no body)
181  func_ptr->setCallingConv(CallingConv::C);
182 
183  Attributes func_pal;
184  {
185  SmallVector<Attributes, 4> Attrs;
186  Attributes PAS;
187  {
188 #if 14 <= LLVM_VERSION_MAJOR
189  AttrBuilder B(mod->getContext());
190 #else
191  AttrBuilder B;
192 #endif
193  PAS = Attributes::get(mod->getContext(), ~0U, B);
194  }
195 
196  Attrs.push_back(PAS);
197  func_pal = Attributes::get(mod->getContext(), Attrs);
198  }
199  func_ptr->setAttributes(func_pal);
200  }
201 
202  return func_ptr;
203 }
204 
205 } // namespace
206 
207 template <class Attributes>
208 std::tuple<llvm::Function*, llvm::CallInst*> query_template_impl(
209  llvm::Module* mod,
210  const size_t aggr_col_count,
211  const bool hoist_literals,
212  const bool is_estimate_query,
213  const GpuSharedMemoryContext& gpu_smem_context) {
214  using namespace llvm;
215 
216  auto func_pos_start = pos_start<Attributes>(mod);
217  CHECK(func_pos_start);
218  auto func_pos_step = pos_step<Attributes>(mod);
219  CHECK(func_pos_step);
220  auto func_group_buff_idx = group_buff_idx<Attributes>(mod);
221  CHECK(func_group_buff_idx);
222  auto func_row_process = row_process<Attributes>(
223  mod, is_estimate_query ? 1 : aggr_col_count, hoist_literals);
224  CHECK(func_row_process);
225 
226  auto i8_type = IntegerType::get(mod->getContext(), 8);
227  auto i32_type = IntegerType::get(mod->getContext(), 32);
228  auto i64_type = IntegerType::get(mod->getContext(), 64);
229  auto pi8_type = PointerType::get(i8_type, 0);
230  auto ppi8_type = PointerType::get(pi8_type, 0);
231  auto pi32_type = PointerType::get(i32_type, 0);
232  auto pi64_type = PointerType::get(i64_type, 0);
233  auto ppi64_type = PointerType::get(pi64_type, 0);
234 
235  std::vector<Type*> query_args;
236  query_args.push_back(ppi8_type);
237  if (hoist_literals) {
238  query_args.push_back(pi8_type);
239  }
240  query_args.push_back(pi64_type);
241  query_args.push_back(pi64_type);
242  query_args.push_back(pi32_type);
243 
244  query_args.push_back(pi64_type);
245  query_args.push_back(ppi64_type);
246  query_args.push_back(i32_type);
247  query_args.push_back(pi64_type);
248  query_args.push_back(pi32_type);
249  query_args.push_back(pi32_type);
250 
251  FunctionType* query_func_type = FunctionType::get(
252  /*Result=*/Type::getVoidTy(mod->getContext()),
253  /*Params=*/query_args,
254  /*isVarArg=*/false);
255 
256  std::string query_template_name{"query_template"};
257  auto query_func_ptr = mod->getFunction(query_template_name);
258  CHECK(!query_func_ptr);
259 
260  query_func_ptr = Function::Create(
261  /*Type=*/query_func_type,
262  /*Linkage=*/GlobalValue::ExternalLinkage,
263  /*Name=*/query_template_name,
264  mod);
265  query_func_ptr->setCallingConv(CallingConv::C);
266 
267  Attributes query_func_pal;
268  {
269  SmallVector<Attributes, 4> Attrs;
270  Attributes PAS;
271  {
272 #if 14 <= LLVM_VERSION_MAJOR
273  AttrBuilder B(mod->getContext());
274 #else
275  AttrBuilder B;
276 #endif
277  B.addAttribute(Attribute::NoCapture);
278  PAS = Attributes::get(mod->getContext(), 1U, B);
279  }
280 
281  Attrs.push_back(PAS);
282  {
283 #if 14 <= LLVM_VERSION_MAJOR
284  AttrBuilder B(mod->getContext());
285 #else
286  AttrBuilder B;
287 #endif
288  B.addAttribute(Attribute::NoCapture);
289  PAS = Attributes::get(mod->getContext(), 2U, B);
290  }
291 
292  Attrs.push_back(PAS);
293 
294  {
295 #if 14 <= LLVM_VERSION_MAJOR
296  AttrBuilder B(mod->getContext());
297 #else
298  AttrBuilder B;
299 #endif
300  B.addAttribute(Attribute::NoCapture);
301  Attrs.push_back(Attributes::get(mod->getContext(), 3U, B));
302  }
303 
304  {
305 #if 14 <= LLVM_VERSION_MAJOR
306  AttrBuilder B(mod->getContext());
307 #else
308  AttrBuilder B;
309 #endif
310  B.addAttribute(Attribute::NoCapture);
311  Attrs.push_back(Attributes::get(mod->getContext(), 4U, B));
312  }
313 
314  Attrs.push_back(PAS);
315 
316  query_func_pal = Attributes::get(mod->getContext(), Attrs);
317  }
318  query_func_ptr->setAttributes(query_func_pal);
319 
320  Function::arg_iterator query_arg_it = query_func_ptr->arg_begin();
321  Value* byte_stream = &*query_arg_it;
322  byte_stream->setName("byte_stream");
323  Value* literals{nullptr};
324  if (hoist_literals) {
325  literals = &*(++query_arg_it);
326  literals->setName("literals");
327  }
328  Value* row_count_ptr = &*(++query_arg_it);
329  row_count_ptr->setName("row_count_ptr");
330  Value* frag_row_off_ptr = &*(++query_arg_it);
331  frag_row_off_ptr->setName("frag_row_off_ptr");
332  Value* max_matched_ptr = &*(++query_arg_it);
333  max_matched_ptr->setName("max_matched_ptr");
334  Value* agg_init_val = &*(++query_arg_it);
335  agg_init_val->setName("agg_init_val");
336  Value* out = &*(++query_arg_it);
337  out->setName("out");
338  Value* frag_idx = &*(++query_arg_it);
339  frag_idx->setName("frag_idx");
340  Value* join_hash_tables = &*(++query_arg_it);
341  join_hash_tables->setName("join_hash_tables");
342  Value* total_matched = &*(++query_arg_it);
343  total_matched->setName("total_matched");
344  Value* error_code = &*(++query_arg_it);
345  error_code->setName("error_code");
346 
347  auto bb_entry = BasicBlock::Create(mod->getContext(), ".entry", query_func_ptr, 0);
348  auto bb_preheader =
349  BasicBlock::Create(mod->getContext(), ".loop.preheader", query_func_ptr, 0);
350  auto bb_forbody = BasicBlock::Create(mod->getContext(), ".for.body", query_func_ptr, 0);
351  auto bb_crit_edge =
352  BasicBlock::Create(mod->getContext(), "._crit_edge", query_func_ptr, 0);
353  auto bb_exit = BasicBlock::Create(mod->getContext(), ".exit", query_func_ptr, 0);
354 
355  // Block (.entry)
356  std::vector<Value*> result_ptr_vec;
357  llvm::CallInst* smem_output_buffer{nullptr};
358  if (!is_estimate_query) {
359  for (size_t i = 0; i < aggr_col_count; ++i) {
360  auto result_ptr = new AllocaInst(i64_type, 0, "result", bb_entry);
361  result_ptr->setAlignment(LLVM_ALIGN(8));
362  result_ptr_vec.push_back(result_ptr);
363  }
364  if (gpu_smem_context.isSharedMemoryUsed()) {
365  auto init_smem_func = mod->getFunction("init_shared_mem");
366  CHECK(init_smem_func);
367  // only one slot per aggregate column is needed, and so we can initialize shared
368  // memory buffer for intermediate results to be exactly like the agg_init_val array
369  smem_output_buffer = CallInst::Create(
370  init_smem_func,
371  std::vector<llvm::Value*>{
372  agg_init_val,
373  llvm::ConstantInt::get(i32_type, aggr_col_count * sizeof(int64_t))},
374  "smem_buffer",
375  bb_entry);
376  }
377  }
378 
379  LoadInst* row_count = new LoadInst(get_pointer_element_type(row_count_ptr),
380  row_count_ptr,
381  "row_count",
382  false,
383  bb_entry);
384  row_count->setAlignment(LLVM_ALIGN(8));
385  row_count->setName("row_count");
386  std::vector<Value*> agg_init_val_vec;
387  if (!is_estimate_query) {
388  for (size_t i = 0; i < aggr_col_count; ++i) {
389  auto idx_lv = ConstantInt::get(i32_type, i);
390  auto agg_init_gep = GetElementPtrInst::CreateInBounds(
391  agg_init_val->getType()->getPointerElementType(),
392  agg_init_val,
393  idx_lv,
394  "",
395  bb_entry);
396  auto agg_init_val = new LoadInst(
397  get_pointer_element_type(agg_init_gep), agg_init_gep, "", false, bb_entry);
398  agg_init_val->setAlignment(LLVM_ALIGN(8));
399  agg_init_val_vec.push_back(agg_init_val);
400  auto init_val_st = new StoreInst(agg_init_val, result_ptr_vec[i], false, bb_entry);
401  init_val_st->setAlignment(LLVM_ALIGN(8));
402  }
403  }
404 
405  CallInst* pos_start = CallInst::Create(func_pos_start, "pos_start", bb_entry);
406  pos_start->setCallingConv(CallingConv::C);
407  pos_start->setTailCall(true);
408  Attributes pos_start_pal;
409  pos_start->setAttributes(pos_start_pal);
410 
411  CallInst* pos_step = CallInst::Create(func_pos_step, "pos_step", bb_entry);
412  pos_step->setCallingConv(CallingConv::C);
413  pos_step->setTailCall(true);
414  Attributes pos_step_pal;
415  pos_step->setAttributes(pos_step_pal);
416 
417  CallInst* group_buff_idx = nullptr;
418  if (!is_estimate_query) {
419  group_buff_idx = CallInst::Create(func_group_buff_idx, "group_buff_idx", bb_entry);
420  group_buff_idx->setCallingConv(CallingConv::C);
421  group_buff_idx->setTailCall(true);
422  Attributes group_buff_idx_pal;
423  group_buff_idx->setAttributes(group_buff_idx_pal);
424  }
425 
426  CastInst* pos_start_i64 = new SExtInst(pos_start, i64_type, "", bb_entry);
427  ICmpInst* enter_or_not =
428  new ICmpInst(*bb_entry, ICmpInst::ICMP_SLT, pos_start_i64, row_count, "");
429  BranchInst::Create(bb_preheader, bb_exit, enter_or_not, bb_entry);
430 
431  // Block .loop.preheader
432  CastInst* pos_step_i64 = new SExtInst(pos_step, i64_type, "", bb_preheader);
433  BranchInst::Create(bb_forbody, bb_preheader);
434 
435  // Block .forbody
436  Argument* pos_inc_pre = new Argument(i64_type);
437  PHINode* pos = PHINode::Create(i64_type, 2, "pos", bb_forbody);
438  pos->addIncoming(pos_start_i64, bb_preheader);
439  pos->addIncoming(pos_inc_pre, bb_forbody);
440 
441  std::vector<Value*> row_process_params;
442  row_process_params.insert(
443  row_process_params.end(), result_ptr_vec.begin(), result_ptr_vec.end());
444  if (is_estimate_query) {
445  row_process_params.push_back(
446  new LoadInst(get_pointer_element_type(out), out, "", false, bb_forbody));
447  }
448  row_process_params.push_back(agg_init_val);
449  row_process_params.push_back(pos);
450  row_process_params.push_back(frag_row_off_ptr);
451  row_process_params.push_back(row_count_ptr);
452  if (hoist_literals) {
453  CHECK(literals);
454  row_process_params.push_back(literals);
455  }
456  CallInst* row_process =
457  CallInst::Create(func_row_process, row_process_params, "", bb_forbody);
458  row_process->setCallingConv(CallingConv::C);
459  row_process->setTailCall(false);
460  Attributes row_process_pal;
461  row_process->setAttributes(row_process_pal);
462 
463  BinaryOperator* pos_inc =
464  BinaryOperator::CreateNSW(Instruction::Add, pos, pos_step_i64, "", bb_forbody);
465  ICmpInst* loop_or_exit =
466  new ICmpInst(*bb_forbody, ICmpInst::ICMP_SLT, pos_inc, row_count, "");
467  BranchInst::Create(bb_forbody, bb_crit_edge, loop_or_exit, bb_forbody);
468 
469  // Block ._crit_edge
470  std::vector<Instruction*> result_vec_pre;
471  if (!is_estimate_query) {
472  for (size_t i = 0; i < aggr_col_count; ++i) {
473  auto result = new LoadInst(get_pointer_element_type(result_ptr_vec[i]),
474  result_ptr_vec[i],
475  ".pre.result",
476  false,
477  bb_crit_edge);
478  result->setAlignment(LLVM_ALIGN(8));
479  result_vec_pre.push_back(result);
480  }
481  }
482 
483  BranchInst::Create(bb_exit, bb_crit_edge);
484 
485  // Block .exit
497  if (!is_estimate_query) {
498  std::vector<PHINode*> result_vec;
499  for (int64_t i = aggr_col_count - 1; i >= 0; --i) {
500  auto result =
501  PHINode::Create(IntegerType::get(mod->getContext(), 64), 2, "", bb_exit);
502  result->addIncoming(result_vec_pre[i], bb_crit_edge);
503  result->addIncoming(agg_init_val_vec[i], bb_entry);
504  result_vec.insert(result_vec.begin(), result);
505  }
506 
507  for (size_t i = 0; i < aggr_col_count; ++i) {
508  auto col_idx = ConstantInt::get(i32_type, i);
509  if (gpu_smem_context.isSharedMemoryUsed()) {
510  auto target_addr = GetElementPtrInst::CreateInBounds(
511  smem_output_buffer->getType()->getPointerElementType(),
512  smem_output_buffer,
513  col_idx,
514  "",
515  bb_exit);
516  // TODO: generalize this once we want to support other types of aggregate
517  // functions besides COUNT.
518  auto agg_func = mod->getFunction("agg_sum_shared");
519  CHECK(agg_func);
520  CallInst::Create(
521  agg_func, std::vector<llvm::Value*>{target_addr, result_vec[i]}, "", bb_exit);
522  } else {
523  auto out_gep = GetElementPtrInst::CreateInBounds(
524  out->getType()->getPointerElementType(), out, col_idx, "", bb_exit);
525  auto col_buffer =
526  new LoadInst(get_pointer_element_type(out_gep), out_gep, "", false, bb_exit);
527  col_buffer->setAlignment(LLVM_ALIGN(8));
528  auto slot_idx = BinaryOperator::CreateAdd(
530  BinaryOperator::CreateMul(frag_idx, pos_step, "", bb_exit),
531  "",
532  bb_exit);
533  auto target_addr = GetElementPtrInst::CreateInBounds(
534  col_buffer->getType()->getPointerElementType(),
535  col_buffer,
536  slot_idx,
537  "",
538  bb_exit);
539  StoreInst* result_st = new StoreInst(result_vec[i], target_addr, false, bb_exit);
540  result_st->setAlignment(LLVM_ALIGN(8));
541  }
542  }
543  if (gpu_smem_context.isSharedMemoryUsed()) {
544  // final reduction of results from shared memory buffer back into global memory.
545  auto sync_thread_func = mod->getFunction("sync_threadblock");
546  CHECK(sync_thread_func);
547  CallInst::Create(sync_thread_func, std::vector<llvm::Value*>{}, "", bb_exit);
548  auto reduce_smem_to_gmem_func = mod->getFunction("write_back_non_grouped_agg");
549  CHECK(reduce_smem_to_gmem_func);
550  // each thread reduce the aggregate target corresponding to its own thread ID.
551  // If there are more targets than threads we do not currently use shared memory
552  // optimization. This can be relaxed if necessary
553  for (size_t i = 0; i < aggr_col_count; i++) {
554  auto out_gep =
555  GetElementPtrInst::CreateInBounds(out->getType()->getPointerElementType(),
556  out,
557  ConstantInt::get(i32_type, i),
558  "",
559  bb_exit);
560  auto gmem_output_buffer = new LoadInst(get_pointer_element_type(out_gep),
561  out_gep,
562  "gmem_output_buffer_" + std::to_string(i),
563  false,
564  bb_exit);
565  CallInst::Create(
566  reduce_smem_to_gmem_func,
567  std::vector<llvm::Value*>{
568  smem_output_buffer, gmem_output_buffer, ConstantInt::get(i32_type, i)},
569  "",
570  bb_exit);
571  }
572  }
573  }
574 
575  ReturnInst::Create(mod->getContext(), bb_exit);
576 
577  // Resolve Forward References
578  pos_inc_pre->replaceAllUsesWith(pos_inc);
579  delete pos_inc_pre;
580 
581  if (verifyFunction(*query_func_ptr)) {
582  LOG(FATAL) << "Generated invalid code. ";
583  }
584 
585  return {query_func_ptr, row_process};
586 }
587 
588 template <class Attributes>
589 std::tuple<llvm::Function*, llvm::CallInst*> query_group_by_template_impl(
590  llvm::Module* mod,
591  const bool hoist_literals,
593  const ExecutorDeviceType device_type,
594  const bool check_scan_limit,
595  const GpuSharedMemoryContext& gpu_smem_context) {
596  if (gpu_smem_context.isSharedMemoryUsed()) {
597  CHECK(device_type == ExecutorDeviceType::GPU);
598  }
599  using namespace llvm;
600 
601  auto func_pos_start = pos_start<Attributes>(mod);
602  CHECK(func_pos_start);
603  auto func_pos_step = pos_step<Attributes>(mod);
604  CHECK(func_pos_step);
605  auto func_group_buff_idx = group_buff_idx<Attributes>(mod);
606  CHECK(func_group_buff_idx);
607  auto func_row_process = row_process<Attributes>(mod, 0, hoist_literals);
608  CHECK(func_row_process);
609  auto func_init_shared_mem = gpu_smem_context.isSharedMemoryUsed()
610  ? mod->getFunction("init_shared_mem")
611  : mod->getFunction("init_shared_mem_nop");
612  CHECK(func_init_shared_mem);
613 
614  auto func_write_back = mod->getFunction("write_back_nop");
615  CHECK(func_write_back);
616 
617  auto i32_type = IntegerType::get(mod->getContext(), 32);
618  auto i64_type = IntegerType::get(mod->getContext(), 64);
619  auto pi8_type = PointerType::get(IntegerType::get(mod->getContext(), 8), 0);
620  auto pi32_type = PointerType::get(i32_type, 0);
621  auto pi64_type = PointerType::get(i64_type, 0);
622  auto ppi64_type = PointerType::get(pi64_type, 0);
623  auto ppi8_type = PointerType::get(pi8_type, 0);
624 
625  std::vector<Type*> query_args;
626  query_args.push_back(ppi8_type);
627  if (hoist_literals) {
628  query_args.push_back(pi8_type);
629  }
630  query_args.push_back(pi64_type);
631  query_args.push_back(pi64_type);
632  query_args.push_back(pi32_type);
633  query_args.push_back(pi64_type);
634 
635  query_args.push_back(ppi64_type);
636  query_args.push_back(i32_type);
637  query_args.push_back(pi64_type);
638  query_args.push_back(pi32_type);
639  query_args.push_back(pi32_type);
640 
641  FunctionType* query_func_type = FunctionType::get(
642  /*Result=*/Type::getVoidTy(mod->getContext()),
643  /*Params=*/query_args,
644  /*isVarArg=*/false);
645 
646  std::string query_name{"query_group_by_template"};
647  auto query_func_ptr = mod->getFunction(query_name);
648  CHECK(!query_func_ptr);
649 
650  query_func_ptr = Function::Create(
651  /*Type=*/query_func_type,
652  /*Linkage=*/GlobalValue::ExternalLinkage,
653  /*Name=*/"query_group_by_template",
654  mod);
655 
656  query_func_ptr->setCallingConv(CallingConv::C);
657 
658  Attributes query_func_pal;
659  {
660  SmallVector<Attributes, 4> Attrs;
661  Attributes PAS;
662  {
663 #if 14 <= LLVM_VERSION_MAJOR
664  AttrBuilder B(mod->getContext());
665 #else
666  AttrBuilder B;
667 #endif
668  B.addAttribute(Attribute::ReadNone);
669  B.addAttribute(Attribute::NoCapture);
670  PAS = Attributes::get(mod->getContext(), 1U, B);
671  }
672 
673  Attrs.push_back(PAS);
674  {
675 #if 14 <= LLVM_VERSION_MAJOR
676  AttrBuilder B(mod->getContext());
677 #else
678  AttrBuilder B;
679 #endif
680  B.addAttribute(Attribute::ReadOnly);
681  B.addAttribute(Attribute::NoCapture);
682  PAS = Attributes::get(mod->getContext(), 2U, B);
683  }
684 
685  Attrs.push_back(PAS);
686  {
687 #if 14 <= LLVM_VERSION_MAJOR
688  AttrBuilder B(mod->getContext());
689 #else
690  AttrBuilder B;
691 #endif
692  B.addAttribute(Attribute::ReadNone);
693  B.addAttribute(Attribute::NoCapture);
694  PAS = Attributes::get(mod->getContext(), 3U, B);
695  }
696 
697  Attrs.push_back(PAS);
698  {
699 #if 14 <= LLVM_VERSION_MAJOR
700  AttrBuilder B(mod->getContext());
701 #else
702  AttrBuilder B;
703 #endif
704  B.addAttribute(Attribute::ReadOnly);
705  B.addAttribute(Attribute::NoCapture);
706  PAS = Attributes::get(mod->getContext(), 4U, B);
707  }
708 
709  Attrs.push_back(PAS);
710  {
711 #if 14 <= LLVM_VERSION_MAJOR
712  AttrBuilder B(mod->getContext());
713 #else
714  AttrBuilder B;
715 #endif
716  B.addAttribute(Attribute::UWTable);
717  PAS = Attributes::get(mod->getContext(), ~0U, B);
718  }
719 
720  Attrs.push_back(PAS);
721 
722  query_func_pal = Attributes::get(mod->getContext(), Attrs);
723  }
724  query_func_ptr->setAttributes(query_func_pal);
725 
726  Function::arg_iterator query_arg_it = query_func_ptr->arg_begin();
727  Value* byte_stream = &*query_arg_it;
728  byte_stream->setName("byte_stream");
729  Value* literals{nullptr};
730  if (hoist_literals) {
731  literals = &*(++query_arg_it);
732  ;
733  literals->setName("literals");
734  }
735  Value* row_count_ptr = &*(++query_arg_it);
736  row_count_ptr->setName("row_count_ptr");
737  Value* frag_row_off_ptr = &*(++query_arg_it);
738  frag_row_off_ptr->setName("frag_row_off_ptr");
739  Value* max_matched_ptr = &*(++query_arg_it);
740  max_matched_ptr->setName("max_matched_ptr");
741  Value* agg_init_val = &*(++query_arg_it);
742  agg_init_val->setName("agg_init_val");
743  Value* group_by_buffers = &*(++query_arg_it);
744  group_by_buffers->setName("group_by_buffers");
745  Value* frag_idx = &*(++query_arg_it);
746  frag_idx->setName("frag_idx");
747  Value* join_hash_tables = &*(++query_arg_it);
748  join_hash_tables->setName("join_hash_tables");
749  Value* total_matched = &*(++query_arg_it);
750  total_matched->setName("total_matched");
751  Value* error_code = &*(++query_arg_it);
752  error_code->setName("error_code");
753 
754  auto bb_entry = BasicBlock::Create(mod->getContext(), ".entry", query_func_ptr, 0);
755  auto bb_preheader =
756  BasicBlock::Create(mod->getContext(), ".loop.preheader", query_func_ptr, 0);
757  auto bb_forbody = BasicBlock::Create(mod->getContext(), ".forbody", query_func_ptr, 0);
758  auto bb_crit_edge =
759  BasicBlock::Create(mod->getContext(), "._crit_edge", query_func_ptr, 0);
760  auto bb_exit = BasicBlock::Create(mod->getContext(), ".exit", query_func_ptr, 0);
761 
762  // Block .entry
763  LoadInst* row_count = new LoadInst(
764  get_pointer_element_type(row_count_ptr), row_count_ptr, "", false, bb_entry);
765  row_count->setAlignment(LLVM_ALIGN(8));
766  row_count->setName("row_count");
767 
768  LoadInst* max_matched = new LoadInst(
769  get_pointer_element_type(max_matched_ptr), max_matched_ptr, "", false, bb_entry);
770  max_matched->setAlignment(LLVM_ALIGN(8));
771 
772  auto crt_matched_ptr = new AllocaInst(i32_type, 0, "crt_matched", bb_entry);
773  auto old_total_matched_ptr = new AllocaInst(i32_type, 0, "old_total_matched", bb_entry);
774  CallInst* pos_start = CallInst::Create(func_pos_start, "", bb_entry);
775  pos_start->setCallingConv(CallingConv::C);
776  pos_start->setTailCall(true);
777  Attributes pos_start_pal;
778  pos_start->setAttributes(pos_start_pal);
779 
780  CallInst* pos_step = CallInst::Create(func_pos_step, "", bb_entry);
781  pos_step->setCallingConv(CallingConv::C);
782  pos_step->setTailCall(true);
783  Attributes pos_step_pal;
784  pos_step->setAttributes(pos_step_pal);
785 
786  CallInst* group_buff_idx_call = CallInst::Create(func_group_buff_idx, "", bb_entry);
787  group_buff_idx_call->setCallingConv(CallingConv::C);
788  group_buff_idx_call->setTailCall(true);
789  Attributes group_buff_idx_pal;
790  group_buff_idx_call->setAttributes(group_buff_idx_pal);
791  Value* group_buff_idx = group_buff_idx_call;
792 
793  const PointerType* Ty = dyn_cast<PointerType>(group_by_buffers->getType());
794  CHECK(Ty);
795 
796  Value* varlen_output_buffer{nullptr};
797  if (query_mem_desc.hasVarlenOutput()) {
798  // make the varlen buffer the _first_ 8 byte value in the group by buffers double ptr,
799  // and offset the group by buffers index by 8 bytes
800  auto varlen_output_buffer_gep = GetElementPtrInst::Create(
801  Ty->getPointerElementType(),
802  group_by_buffers,
803  llvm::ConstantInt::get(llvm::Type::getInt32Ty(mod->getContext()), 0),
804  "",
805  bb_entry);
806  varlen_output_buffer =
807  new LoadInst(get_pointer_element_type(varlen_output_buffer_gep),
808  varlen_output_buffer_gep,
809  "varlen_output_buffer",
810  false,
811  bb_entry);
812 
813  group_buff_idx = BinaryOperator::Create(
814  Instruction::Add,
816  llvm::ConstantInt::get(llvm::Type::getInt32Ty(mod->getContext()), 1),
817  "group_buff_idx_varlen_offset",
818  bb_entry);
819  } else {
820  varlen_output_buffer =
821  ConstantPointerNull::get(Type::getInt64PtrTy(mod->getContext()));
822  }
823  CHECK(varlen_output_buffer);
824 
825  CastInst* pos_start_i64 = new SExtInst(pos_start, i64_type, "", bb_entry);
826  GetElementPtrInst* group_by_buffers_gep = GetElementPtrInst::Create(
827  Ty->getPointerElementType(), group_by_buffers, group_buff_idx, "", bb_entry);
828  LoadInst* col_buffer = new LoadInst(get_pointer_element_type(group_by_buffers_gep),
829  group_by_buffers_gep,
830  "",
831  false,
832  bb_entry);
833  col_buffer->setName("col_buffer");
834  col_buffer->setAlignment(LLVM_ALIGN(8));
835 
836  llvm::ConstantInt* shared_mem_bytes_lv =
837  ConstantInt::get(i32_type, gpu_smem_context.getSharedMemorySize());
838  // TODO(Saman): change this further, normal path should not go through this
839  llvm::CallInst* result_buffer =
840  CallInst::Create(func_init_shared_mem,
841  std::vector<llvm::Value*>{col_buffer, shared_mem_bytes_lv},
842  "result_buffer",
843  bb_entry);
844 
845  ICmpInst* enter_or_not =
846  new ICmpInst(*bb_entry, ICmpInst::ICMP_SLT, pos_start_i64, row_count, "");
847  BranchInst::Create(bb_preheader, bb_exit, enter_or_not, bb_entry);
848 
849  // Block .loop.preheader
850  CastInst* pos_step_i64 = new SExtInst(pos_step, i64_type, "", bb_preheader);
851  BranchInst::Create(bb_forbody, bb_preheader);
852 
853  // Block .forbody
854  Argument* pos_pre = new Argument(i64_type);
855  PHINode* pos = PHINode::Create(i64_type, check_scan_limit ? 3 : 2, "pos", bb_forbody);
856 
857  std::vector<Value*> row_process_params;
858  row_process_params.push_back(result_buffer);
859  row_process_params.push_back(varlen_output_buffer);
860  row_process_params.push_back(crt_matched_ptr);
861  row_process_params.push_back(total_matched);
862  row_process_params.push_back(old_total_matched_ptr);
863  row_process_params.push_back(max_matched_ptr);
864  row_process_params.push_back(agg_init_val);
865  row_process_params.push_back(pos);
866  row_process_params.push_back(frag_row_off_ptr);
867  row_process_params.push_back(row_count_ptr);
868  if (hoist_literals) {
869  CHECK(literals);
870  row_process_params.push_back(literals);
871  }
872  if (check_scan_limit) {
873  new StoreInst(ConstantInt::get(IntegerType::get(mod->getContext(), 32), 0),
874  crt_matched_ptr,
875  bb_forbody);
876  }
877  CallInst* row_process =
878  CallInst::Create(func_row_process, row_process_params, "", bb_forbody);
879  row_process->setCallingConv(CallingConv::C);
880  row_process->setTailCall(true);
881  Attributes row_process_pal;
882  row_process->setAttributes(row_process_pal);
883 
884  // Forcing all threads within a warp to be synchronized (Compute >= 7.x)
885  if (query_mem_desc.isWarpSyncRequired(device_type)) {
886  auto func_sync_warp_protected = mod->getFunction("sync_warp_protected");
887  CHECK(func_sync_warp_protected);
888  CallInst::Create(func_sync_warp_protected,
889  std::vector<llvm::Value*>{pos, row_count},
890  "",
891  bb_forbody);
892  }
893 
894  BinaryOperator* pos_inc =
895  BinaryOperator::Create(Instruction::Add, pos, pos_step_i64, "", bb_forbody);
896  ICmpInst* loop_or_exit =
897  new ICmpInst(*bb_forbody, ICmpInst::ICMP_SLT, pos_inc, row_count, "");
898  if (check_scan_limit) {
899  auto crt_matched = new LoadInst(get_pointer_element_type(crt_matched_ptr),
900  crt_matched_ptr,
901  "crt_matched",
902  false,
903  bb_forbody);
904  auto filter_match = BasicBlock::Create(
905  mod->getContext(), "filter_match", query_func_ptr, bb_crit_edge);
906  llvm::Value* new_total_matched =
907  new LoadInst(get_pointer_element_type(old_total_matched_ptr),
908  old_total_matched_ptr,
909  "",
910  false,
911  filter_match);
912  new_total_matched =
913  BinaryOperator::CreateAdd(new_total_matched, crt_matched, "", filter_match);
914  CHECK(new_total_matched);
915  ICmpInst* limit_not_reached = new ICmpInst(*filter_match,
916  ICmpInst::ICMP_SLT,
917  new_total_matched,
918  max_matched,
919  "limit_not_reached");
920  BranchInst::Create(
921  bb_forbody,
922  bb_crit_edge,
923  BinaryOperator::Create(
924  BinaryOperator::And, loop_or_exit, limit_not_reached, "", filter_match),
925  filter_match);
926  auto filter_nomatch = BasicBlock::Create(
927  mod->getContext(), "filter_nomatch", query_func_ptr, bb_crit_edge);
928  BranchInst::Create(bb_forbody, bb_crit_edge, loop_or_exit, filter_nomatch);
929  ICmpInst* crt_matched_nz = new ICmpInst(
930  *bb_forbody, ICmpInst::ICMP_NE, crt_matched, ConstantInt::get(i32_type, 0), "");
931  BranchInst::Create(filter_match, filter_nomatch, crt_matched_nz, bb_forbody);
932  pos->addIncoming(pos_start_i64, bb_preheader);
933  pos->addIncoming(pos_pre, filter_match);
934  pos->addIncoming(pos_pre, filter_nomatch);
935  } else {
936  pos->addIncoming(pos_start_i64, bb_preheader);
937  pos->addIncoming(pos_pre, bb_forbody);
938  BranchInst::Create(bb_forbody, bb_crit_edge, loop_or_exit, bb_forbody);
939  }
940 
941  // Block ._crit_edge
942  BranchInst::Create(bb_exit, bb_crit_edge);
943 
944  // Block .exit
945  CallInst::Create(func_write_back,
946  std::vector<Value*>{col_buffer, result_buffer, shared_mem_bytes_lv},
947  "",
948  bb_exit);
949 
950  ReturnInst::Create(mod->getContext(), bb_exit);
951 
952  // Resolve Forward References
953  pos_pre->replaceAllUsesWith(pos_inc);
954  delete pos_pre;
955 
956  if (verifyFunction(*query_func_ptr, &llvm::errs())) {
957  LOG(FATAL) << "Generated invalid code. ";
958  }
959 
960  return {query_func_ptr, row_process};
961 }
962 
963 std::tuple<llvm::Function*, llvm::CallInst*> query_template(
964  llvm::Module* mod,
965  const size_t aggr_col_count,
966  const bool hoist_literals,
967  const bool is_estimate_query,
968  const GpuSharedMemoryContext& gpu_smem_context) {
969  return query_template_impl<llvm::AttributeList>(
970  mod, aggr_col_count, hoist_literals, is_estimate_query, gpu_smem_context);
971 }
972 std::tuple<llvm::Function*, llvm::CallInst*> query_group_by_template(
973  llvm::Module* mod,
974  const bool hoist_literals,
976  const ExecutorDeviceType device_type,
977  const bool check_scan_limit,
978  const GpuSharedMemoryContext& gpu_smem_context) {
979  return query_group_by_template_impl<llvm::AttributeList>(mod,
980  hoist_literals,
982  device_type,
983  check_scan_limit,
984  gpu_smem_context);
985 }
std::tuple< llvm::Function *, llvm::CallInst * > query_group_by_template_impl(llvm::Module *mod, const bool hoist_literals, const QueryMemoryDescriptor &query_mem_desc, const ExecutorDeviceType device_type, const bool check_scan_limit, const GpuSharedMemoryContext &gpu_smem_context)
ExecutorDeviceType
#define LOG(tag)
Definition: Logger.h:216
size_t getSharedMemorySize() const
std::tuple< llvm::Function *, llvm::CallInst * > query_template(llvm::Module *mod, const size_t aggr_col_count, const bool hoist_literals, const bool is_estimate_query, const GpuSharedMemoryContext &gpu_smem_context)
Type pointer_type(const Type pointee)
#define LLVM_ALIGN(alignment)
std::tuple< llvm::Function *, llvm::CallInst * > query_group_by_template(llvm::Module *mod, const bool hoist_literals, const QueryMemoryDescriptor &query_mem_desc, const ExecutorDeviceType device_type, const bool check_scan_limit, const GpuSharedMemoryContext &gpu_smem_context)
std::string to_string(char const *&&v)
llvm::Function * group_buff_idx(llvm::Module *mod)
llvm::Function * default_func_builder(llvm::Module *mod, const std::string &name)
bool isWarpSyncRequired(const ExecutorDeviceType) const
#define CHECK(condition)
Definition: Logger.h:222
std::tuple< llvm::Function *, llvm::CallInst * > query_template_impl(llvm::Module *mod, const size_t aggr_col_count, const bool hoist_literals, const bool is_estimate_query, const GpuSharedMemoryContext &gpu_smem_context)
string name
Definition: setup.in.py:72
llvm::Type * get_pointer_element_type(llvm::Value *value)
llvm::Function * row_process(llvm::Module *mod, const size_t aggr_col_count, const bool hoist_literals)