OmniSciDB  fe05a0c208
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
BaselineJoinHashTable.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017 MapD Technologies, 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 
18 
19 #include <future>
20 
24 #include "QueryEngine/Execute.h"
31 
32 std::unique_ptr<
36 
38 std::shared_ptr<BaselineJoinHashTable> BaselineJoinHashTable::getInstance(
39  const std::shared_ptr<Analyzer::BinOper> condition,
40  const std::vector<InputTableInfo>& query_infos,
41  const Data_Namespace::MemoryLevel memory_level,
42  const HashType preferred_hash_type,
43  const int device_count,
44  ColumnCacheMap& column_cache,
45  Executor* executor) {
46  decltype(std::chrono::steady_clock::now()) ts1, ts2;
47 
48  if (VLOGGING(1)) {
49  VLOG(1) << "Building keyed hash table " << getHashTypeString(preferred_hash_type)
50  << " for qual: " << condition->toString();
51  ts1 = std::chrono::steady_clock::now();
52  }
53  auto inner_outer_pairs = normalize_column_pairs(
54  condition.get(), *executor->getCatalog(), executor->getTemporaryTables());
55 
56  auto join_hash_table =
57  std::shared_ptr<BaselineJoinHashTable>(new BaselineJoinHashTable(condition,
58  query_infos,
59  memory_level,
60  column_cache,
61  executor,
62  inner_outer_pairs,
63  device_count));
64  try {
65  join_hash_table->reify(preferred_hash_type);
66  } catch (const TableMustBeReplicated& e) {
67  // Throw a runtime error to abort the query
68  join_hash_table->freeHashBufferMemory();
69  throw std::runtime_error(e.what());
70  } catch (const HashJoinFail& e) {
71  // HashJoinFail exceptions log an error and trigger a retry with a join loop (if
72  // possible)
73  join_hash_table->freeHashBufferMemory();
74  throw HashJoinFail(std::string("Could not build a 1-to-1 correspondence for columns "
75  "involved in equijoin | ") +
76  e.what());
77  } catch (const ColumnarConversionNotSupported& e) {
78  throw HashJoinFail(std::string("Could not build hash tables for equijoin | ") +
79  e.what());
80  } catch (const OutOfMemory& e) {
81  throw HashJoinFail(
82  std::string("Ran out of memory while building hash tables for equijoin | ") +
83  e.what());
84  } catch (const std::exception& e) {
85  throw std::runtime_error(
86  std::string("Fatal error while attempting to build hash tables for join: ") +
87  e.what());
88  }
89  if (VLOGGING(1)) {
90  ts2 = std::chrono::steady_clock::now();
91  VLOG(1) << "Built keyed hash table "
92  << getHashTypeString(join_hash_table->getHashType()) << " in "
93  << std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1).count()
94  << " ms";
95  }
96  return join_hash_table;
97 }
98 
100  const std::shared_ptr<Analyzer::BinOper> condition,
101  const std::vector<InputTableInfo>& query_infos,
102  const Data_Namespace::MemoryLevel memory_level,
103  ColumnCacheMap& column_cache,
104  Executor* executor,
105  const std::vector<InnerOuter>& inner_outer_pairs,
106  const int device_count)
107  : condition_(condition)
108  , query_infos_(query_infos)
109  , memory_level_(memory_level)
110  , executor_(executor)
111  , column_cache_(column_cache)
112  , inner_outer_pairs_(inner_outer_pairs)
113  , catalog_(executor->getCatalog())
114  , device_count_(device_count) {
116  hash_tables_for_device_.resize(std::max(device_count_, 1));
117 }
118 
120  const Analyzer::BinOper* condition,
121  const Executor* executor,
122  const std::vector<InnerOuter>& inner_outer_pairs) {
123  for (const auto& inner_outer_pair : inner_outer_pairs) {
124  const auto pair_shard_count = get_shard_count(inner_outer_pair, executor);
125  if (pair_shard_count) {
126  return pair_shard_count;
127  }
128  }
129  return 0;
130 }
131 
133  const int device_id,
134  bool raw) const {
135  auto buffer = getJoinHashBuffer(device_type, device_id);
136  CHECK_LT(device_id, hash_tables_for_device_.size());
137  auto hash_table = hash_tables_for_device_[device_id];
138  CHECK(hash_table);
139  auto buffer_size = hash_table->getHashTableBufferSize(device_type);
140 #ifdef HAVE_CUDA
141  std::unique_ptr<int8_t[]> buffer_copy;
142  if (device_type == ExecutorDeviceType::GPU) {
143  buffer_copy = std::make_unique<int8_t[]>(buffer_size);
144 
146  buffer_copy.get(),
147  reinterpret_cast<CUdeviceptr>(reinterpret_cast<int8_t*>(buffer)),
148  buffer_size,
149  device_id);
150  }
151  auto ptr1 = buffer_copy ? buffer_copy.get() : reinterpret_cast<const int8_t*>(buffer);
152 #else
153  auto ptr1 = reinterpret_cast<const int8_t*>(buffer);
154 #endif // HAVE_CUDA
155  auto ptr2 = ptr1 + offsetBufferOff();
156  auto ptr3 = ptr1 + countBufferOff();
157  auto ptr4 = ptr1 + payloadBufferOff();
158  CHECK(hash_table);
159  const auto layout = getHashType();
160  return HashTable::toString(
161  "keyed",
162  getHashTypeString(layout),
163  getKeyComponentCount() + (layout == HashType::OneToOne ? 1 : 0),
165  hash_table->getEntryCount(),
166  ptr1,
167  ptr2,
168  ptr3,
169  ptr4,
170  buffer_size,
171  raw);
172 }
173 
174 std::set<DecodedJoinHashBufferEntry> BaselineJoinHashTable::toSet(
175  const ExecutorDeviceType device_type,
176  const int device_id) const {
177  auto buffer = getJoinHashBuffer(device_type, device_id);
178  auto hash_table = getHashTableForDevice(device_id);
179  CHECK(hash_table);
180  auto buffer_size = hash_table->getHashTableBufferSize(device_type);
181 #ifdef HAVE_CUDA
182  std::unique_ptr<int8_t[]> buffer_copy;
183  if (device_type == ExecutorDeviceType::GPU) {
184  buffer_copy = std::make_unique<int8_t[]>(buffer_size);
185 
187  buffer_copy.get(),
188  reinterpret_cast<CUdeviceptr>(reinterpret_cast<int8_t*>(buffer)),
189  buffer_size,
190  device_id);
191  }
192  auto ptr1 = buffer_copy ? buffer_copy.get() : reinterpret_cast<const int8_t*>(buffer);
193 #else
194  auto ptr1 = reinterpret_cast<const int8_t*>(buffer);
195 #endif // HAVE_CUDA
196  auto ptr2 = ptr1 + offsetBufferOff();
197  auto ptr3 = ptr1 + countBufferOff();
198  auto ptr4 = ptr1 + payloadBufferOff();
199  const auto layout = hash_table->getLayout();
200  return HashTable::toSet(getKeyComponentCount() + (layout == HashType::OneToOne ? 1 : 0),
202  hash_table->getEntryCount(),
203  ptr1,
204  ptr2,
205  ptr3,
206  ptr4,
207  buffer_size);
208 }
209 
210 void BaselineJoinHashTable::reify(const HashType preferred_layout) {
211  auto timer = DEBUG_TIMER(__func__);
213  const auto composite_key_info =
215  const auto type_and_found = HashTypeCache::get(composite_key_info.cache_key_chunks);
216  const auto layout = type_and_found.second ? type_and_found.first : preferred_layout;
217 
222  executor_);
223 
224  if (condition_->is_overlaps_oper()) {
225  CHECK_EQ(inner_outer_pairs_.size(), size_t(1));
226  HashType layout;
227 
228  if (inner_outer_pairs_[0].second->get_type_info().is_array()) {
229  layout = HashType::ManyToMany;
230  } else {
231  layout = HashType::OneToMany;
232  }
233  try {
234  reifyWithLayout(layout);
235  return;
236  } catch (const std::exception& e) {
237  VLOG(1) << "Caught exception while building overlaps baseline hash table: "
238  << e.what();
239  throw;
240  }
241  }
242 
243  try {
244  reifyWithLayout(layout);
245  } catch (const std::exception& e) {
246  VLOG(1) << "Caught exception while building baseline hash table: " << e.what();
248  HashTypeCache::set(composite_key_info.cache_key_chunks, HashType::OneToMany);
250  }
251 }
252 
254  const auto& query_info = get_inner_query_info(getInnerTableId(), query_infos_).info;
255  if (query_info.fragments.empty()) {
256  return;
257  }
258 
259  const auto total_entries = 2 * query_info.getNumTuplesUpperBound();
260  if (total_entries > static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
261  throw TooManyHashEntries();
262  }
263 
264  auto& data_mgr = catalog_->getDataMgr();
265  std::vector<std::unique_ptr<CudaAllocator>> dev_buff_owners;
267  for (int device_id = 0; device_id < device_count_; ++device_id) {
268  dev_buff_owners.emplace_back(std::make_unique<CudaAllocator>(&data_mgr, device_id));
269  }
270  }
271  std::vector<ColumnsForDevice> columns_per_device;
272  const auto shard_count = shardCount();
273  auto entries_per_device =
274  get_entries_per_device(total_entries, shard_count, device_count_, memory_level_);
275 
276  for (int device_id = 0; device_id < device_count_; ++device_id) {
277  const auto fragments =
278  shard_count
279  ? only_shards_for_device(query_info.fragments, device_id, device_count_)
280  : query_info.fragments;
281  const auto columns_for_device =
282  fetchColumnsForDevice(fragments,
283  device_id,
285  ? dev_buff_owners[device_id].get()
286  : nullptr);
287  columns_per_device.push_back(columns_for_device);
288  }
289  size_t emitted_keys_count = 0;
290  if (layout == HashType::OneToMany) {
291  CHECK(!columns_per_device.front().join_columns.empty());
292  emitted_keys_count = columns_per_device.front().join_columns.front().num_elems;
293  size_t tuple_count;
294  std::tie(tuple_count, std::ignore) = approximateTupleCount(columns_per_device);
295  const auto entry_count = 2 * std::max(tuple_count, size_t(1));
296 
297  // reset entries per device with one to many info
298  entries_per_device =
299  get_entries_per_device(entry_count, shard_count, device_count_, memory_level_);
300  }
301  std::vector<std::future<void>> init_threads;
302  for (int device_id = 0; device_id < device_count_; ++device_id) {
303  const auto fragments =
304  shard_count
305  ? only_shards_for_device(query_info.fragments, device_id, device_count_)
306  : query_info.fragments;
307  init_threads.push_back(std::async(std::launch::async,
309  this,
310  columns_per_device[device_id],
311  layout,
312  device_id,
313  entries_per_device,
314  emitted_keys_count,
315  logger::thread_id()));
316  }
317  for (auto& init_thread : init_threads) {
318  init_thread.wait();
319  }
320  for (auto& init_thread : init_threads) {
321  init_thread.get();
322  }
323 }
324 
326  const std::vector<ColumnsForDevice>& columns_per_device) const {
327  const auto effective_memory_level = getEffectiveMemoryLevel(inner_outer_pairs_);
328  CountDistinctDescriptor count_distinct_desc{
330  0,
331  11,
332  true,
333  effective_memory_level == Data_Namespace::MemoryLevel::GPU_LEVEL
336  1};
337  const auto padded_size_bytes = count_distinct_desc.bitmapPaddedSizeBytes();
338 
339  CHECK(!columns_per_device.empty() && !columns_per_device.front().join_columns.empty());
340 
341  if (effective_memory_level == Data_Namespace::MemoryLevel::CPU_LEVEL) {
342  const auto composite_key_info =
344  HashTableCacheKey cache_key{columns_per_device.front().join_columns.front().num_elems,
345  composite_key_info.cache_key_chunks,
346  condition_->get_optype()};
347  const auto cached_count_info = getApproximateTupleCountFromCache(cache_key);
348  if (cached_count_info.first) {
349  VLOG(1) << "Using a cached tuple count: " << *cached_count_info.first
350  << ", emitted keys count: " << cached_count_info.second;
351  return std::make_pair(*cached_count_info.first, cached_count_info.second);
352  }
353  int thread_count = cpu_threads();
354  std::vector<uint8_t> hll_buffer_all_cpus(thread_count * padded_size_bytes);
355  auto hll_result = &hll_buffer_all_cpus[0];
356 
357  approximate_distinct_tuples(hll_result,
358  count_distinct_desc.bitmap_sz_bits,
359  padded_size_bytes,
360  columns_per_device.front().join_columns,
361  columns_per_device.front().join_column_types,
362  thread_count);
363  for (int i = 1; i < thread_count; ++i) {
364  hll_unify(hll_result,
365  hll_result + i * padded_size_bytes,
366  1 << count_distinct_desc.bitmap_sz_bits);
367  }
368  return std::make_pair(hll_size(hll_result, count_distinct_desc.bitmap_sz_bits), 0);
369  }
370 #ifdef HAVE_CUDA
371  auto& data_mgr = catalog_->getDataMgr();
372  std::vector<std::vector<uint8_t>> host_hll_buffers(device_count_);
373  for (auto& host_hll_buffer : host_hll_buffers) {
374  host_hll_buffer.resize(count_distinct_desc.bitmapPaddedSizeBytes());
375  }
376  std::vector<std::future<void>> approximate_distinct_device_threads;
377  for (int device_id = 0; device_id < device_count_; ++device_id) {
378  approximate_distinct_device_threads.emplace_back(std::async(
379  std::launch::async,
380  [device_id,
381  &columns_per_device,
382  &count_distinct_desc,
383  &data_mgr,
384  &host_hll_buffers] {
385  CudaAllocator allocator(&data_mgr, device_id);
386  auto device_hll_buffer =
387  allocator.alloc(count_distinct_desc.bitmapPaddedSizeBytes());
388  data_mgr.getCudaMgr()->zeroDeviceMem(
389  device_hll_buffer, count_distinct_desc.bitmapPaddedSizeBytes(), device_id);
390  const auto& columns_for_device = columns_per_device[device_id];
391  auto join_columns_gpu = transfer_vector_of_flat_objects_to_gpu(
392  columns_for_device.join_columns, allocator);
393  auto join_column_types_gpu = transfer_vector_of_flat_objects_to_gpu(
394  columns_for_device.join_column_types, allocator);
395  const auto key_handler =
396  GenericKeyHandler(columns_for_device.join_columns.size(),
397  true,
398  join_columns_gpu,
399  join_column_types_gpu,
400  nullptr,
401  nullptr);
402  const auto key_handler_gpu =
403  transfer_flat_object_to_gpu(key_handler, allocator);
405  reinterpret_cast<uint8_t*>(device_hll_buffer),
406  count_distinct_desc.bitmap_sz_bits,
407  key_handler_gpu,
408  columns_for_device.join_columns[0].num_elems);
409 
410  auto& host_hll_buffer = host_hll_buffers[device_id];
411  copy_from_gpu(&data_mgr,
412  &host_hll_buffer[0],
413  reinterpret_cast<CUdeviceptr>(device_hll_buffer),
414  count_distinct_desc.bitmapPaddedSizeBytes(),
415  device_id);
416  }));
417  }
418  for (auto& child : approximate_distinct_device_threads) {
419  child.get();
420  }
421  CHECK_EQ(Data_Namespace::MemoryLevel::GPU_LEVEL, effective_memory_level);
422  auto& result_hll_buffer = host_hll_buffers.front();
423  auto hll_result = reinterpret_cast<int32_t*>(&result_hll_buffer[0]);
424  for (int device_id = 1; device_id < device_count_; ++device_id) {
425  auto& host_hll_buffer = host_hll_buffers[device_id];
426  hll_unify(hll_result,
427  reinterpret_cast<int32_t*>(&host_hll_buffer[0]),
428  1 << count_distinct_desc.bitmap_sz_bits);
429  }
430  return std::make_pair(hll_size(hll_result, count_distinct_desc.bitmap_sz_bits), 0);
431 #else
432  UNREACHABLE();
433  return {0, 0};
434 #endif // HAVE_CUDA
435 }
436 
438  const std::vector<Fragmenter_Namespace::FragmentInfo>& fragments,
439  const int device_id,
440  DeviceAllocator* dev_buff_owner) {
441  const auto effective_memory_level = getEffectiveMemoryLevel(inner_outer_pairs_);
442 
443  std::vector<JoinColumn> join_columns;
444  std::vector<std::shared_ptr<Chunk_NS::Chunk>> chunks_owner;
445  std::vector<JoinColumnTypeInfo> join_column_types;
446  std::vector<JoinBucketInfo> join_bucket_info;
447  std::vector<std::shared_ptr<void>> malloc_owner;
448  for (const auto& inner_outer_pair : inner_outer_pairs_) {
449  const auto inner_col = inner_outer_pair.first;
450  const auto inner_cd = get_column_descriptor_maybe(
451  inner_col->get_column_id(), inner_col->get_table_id(), *catalog_);
452  if (inner_cd && inner_cd->isVirtualCol) {
454  }
455  join_columns.emplace_back(fetchJoinColumn(inner_col,
456  fragments,
457  effective_memory_level,
458  device_id,
459  chunks_owner,
460  dev_buff_owner,
461  malloc_owner,
462  executor_,
463  &column_cache_));
464  const auto& ti = inner_col->get_type_info();
465  join_column_types.emplace_back(JoinColumnTypeInfo{static_cast<size_t>(ti.get_size()),
466  0,
467  0,
469  isBitwiseEq(),
470  0,
472  }
473  return {join_columns, join_column_types, chunks_owner, join_bucket_info, malloc_owner};
474 }
475 
477  const HashType layout,
478  const int device_id,
479  const size_t entry_count,
480  const size_t emitted_keys_count,
481  const logger::ThreadId parent_thread_id) {
482  DEBUG_TIMER_NEW_THREAD(parent_thread_id);
483  const auto effective_memory_level = getEffectiveMemoryLevel(inner_outer_pairs_);
484  const auto err = initHashTableForDevice(columns_for_device.join_columns,
485  columns_for_device.join_column_types,
486  columns_for_device.join_buckets,
487  layout,
488  effective_memory_level,
489  entry_count,
490  emitted_keys_count,
491  device_id);
492  if (err) {
493  throw HashJoinFail(
494  std::string("Unrecognized error when initializing baseline hash table (") +
495  std::to_string(err) + std::string(")"));
496  }
497 }
498 
501  return 0;
502  }
505 }
506 
508  for (const auto& inner_outer_pair : inner_outer_pairs_) {
509  const auto inner_col = inner_outer_pair.first;
510  const auto& inner_col_ti = inner_col->get_type_info();
511  if (inner_col_ti.get_logical_size() > 4) {
512  CHECK_EQ(8, inner_col_ti.get_logical_size());
513  return 8;
514  }
515  }
516  return 4;
517 }
518 
520  return inner_outer_pairs_.size();
521 }
522 
524  const std::vector<InnerOuter>& inner_outer_pairs) const {
525  for (const auto& inner_outer_pair : inner_outer_pairs) {
527  inner_outer_pair.first, inner_outer_pair.second, executor_)) {
529  }
530  }
531  return memory_level_;
532 }
533 
535  const std::vector<JoinColumn>& join_columns,
536  const std::vector<JoinColumnTypeInfo>& join_column_types,
537  const std::vector<JoinBucketInfo>& join_bucket_info,
538  const HashType layout,
539  const Data_Namespace::MemoryLevel effective_memory_level,
540  const size_t entry_count,
541  const size_t emitted_keys_count,
542  const int device_id) {
543  auto timer = DEBUG_TIMER(__func__);
544  const auto key_component_count = getKeyComponentCount();
545  int err = 0;
546 
547  if (effective_memory_level == Data_Namespace::CPU_LEVEL) {
548  std::lock_guard<std::mutex> cpu_hash_table_buff_lock(cpu_hash_table_buff_mutex_);
549 
550  const auto composite_key_info =
552 
553  CHECK(!join_columns.empty());
554  HashTableCacheKey cache_key{join_columns.front().num_elems,
555  composite_key_info.cache_key_chunks,
556  condition_->get_optype()};
557 
559  CHECK_EQ(device_id, size_t(0));
560  }
561  CHECK_LT(static_cast<size_t>(device_id), hash_tables_for_device_.size());
562 
563  auto hash_table = initHashTableOnCpuFromCache(cache_key);
564  if (hash_table) {
565  hash_tables_for_device_[device_id] = hash_table;
566  } else {
568 
569  const auto key_handler =
570  GenericKeyHandler(key_component_count,
571  true,
572  &join_columns[0],
573  &join_column_types[0],
574  &composite_key_info.sd_inner_proxy_per_key[0],
575  &composite_key_info.sd_outer_proxy_per_key[0]);
576  err = builder.initHashTableOnCpu(&key_handler,
577  composite_key_info,
578  join_columns,
579  join_column_types,
580  join_bucket_info,
581  entry_count,
582  join_columns.front().num_elems,
583  layout,
586  hash_tables_for_device_[device_id] = builder.getHashTable();
587 
588  if (!err) {
589  if (getInnerTableId() > 0) {
590  putHashTableOnCpuToCache(cache_key, hash_tables_for_device_[device_id]);
591  }
592  }
593  }
594  // Transfer the hash table on the GPU if we've only built it on CPU
595  // but the query runs on GPU (join on dictionary encoded columns).
596  // Don't transfer the buffer if there was an error since we'll bail anyway.
597  if (memory_level_ == Data_Namespace::GPU_LEVEL && !err) {
598 #ifdef HAVE_CUDA
600 
601  builder.allocateDeviceMemory(layout,
604  entry_count,
605  emitted_keys_count,
606  device_id);
607 
608  CHECK_LT(size_t(device_id), hash_tables_for_device_.size());
609  auto cpu_source_hash_table = hash_tables_for_device_[device_id];
610  CHECK(cpu_source_hash_table);
611  auto gpu_target_hash_table = builder.getHashTable();
612  CHECK(gpu_target_hash_table);
613 
614  const auto gpu_buff = gpu_target_hash_table->getGpuBuffer();
615  CHECK(gpu_buff);
616  auto& data_mgr = catalog_->getDataMgr();
617  copy_to_gpu(&data_mgr,
618  reinterpret_cast<CUdeviceptr>(gpu_buff),
619  cpu_source_hash_table->getCpuBuffer(),
620  cpu_source_hash_table->getHashTableBufferSize(ExecutorDeviceType::CPU),
621  device_id);
622  hash_tables_for_device_[device_id] = std::move(gpu_target_hash_table);
623 #else
624  CHECK(false);
625 #endif
626  }
627  } else {
628 #ifdef HAVE_CUDA
630 
631  auto& data_mgr = catalog_->getDataMgr();
632  CudaAllocator allocator(&data_mgr, device_id);
633  auto join_column_types_gpu =
634  transfer_vector_of_flat_objects_to_gpu(join_column_types, allocator);
635  auto join_columns_gpu =
636  transfer_vector_of_flat_objects_to_gpu(join_columns, allocator);
637  const auto key_handler = GenericKeyHandler(key_component_count,
638  true,
639  join_columns_gpu,
640  join_column_types_gpu,
641  nullptr,
642  nullptr);
643 
644  err = builder.initHashTableOnGpu(&key_handler,
645  join_columns,
646  layout,
649  entry_count,
650  emitted_keys_count,
651  device_id);
652  CHECK_LT(size_t(device_id), hash_tables_for_device_.size());
653  hash_tables_for_device_[device_id] = builder.getHashTable();
654 #else
655  UNREACHABLE();
656 #endif
657  }
658  return err;
659 }
660 
661 #define LL_CONTEXT executor_->cgen_state_->context_
662 #define LL_BUILDER executor_->cgen_state_->ir_builder_
663 #define LL_INT(v) executor_->cgen_state_->llInt(v)
664 #define LL_FP(v) executor_->cgen_state_->llFp(v)
665 #define ROW_FUNC executor_->cgen_state_->row_func_
666 
668  const size_t index) {
669  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
671  const auto key_component_width = getKeyComponentWidth();
672  CHECK(key_component_width == 4 || key_component_width == 8);
673  auto key_buff_lv = codegenKey(co);
674  const auto hash_ptr = hashPtr(index);
675  const auto key_ptr_lv =
676  LL_BUILDER.CreatePointerCast(key_buff_lv, llvm::Type::getInt8PtrTy(LL_CONTEXT));
677  const auto key_size_lv = LL_INT(getKeyComponentCount() * key_component_width);
678  const auto hash_table = getHashTableForDevice(size_t(0));
679  return executor_->cgen_state_->emitExternalCall(
680  "baseline_hash_join_idx_" + std::to_string(key_component_width * 8),
682  {hash_ptr, key_ptr_lv, key_size_lv, LL_INT(hash_table->getEntryCount())});
683 }
684 
686  const CompilationOptions& co,
687  const size_t index) {
688  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
689  const auto hash_table = getHashTableForDevice(size_t(0));
690  CHECK(hash_table);
691  const auto key_component_width = getKeyComponentWidth();
692  CHECK(key_component_width == 4 || key_component_width == 8);
693  auto key_buff_lv = codegenKey(co);
695  auto hash_ptr = HashJoin::codegenHashTableLoad(index, executor_);
696  const auto composite_dict_ptr_type =
697  llvm::Type::getIntNPtrTy(LL_CONTEXT, key_component_width * 8);
698  const auto composite_key_dict =
699  hash_ptr->getType()->isPointerTy()
700  ? LL_BUILDER.CreatePointerCast(hash_ptr, composite_dict_ptr_type)
701  : LL_BUILDER.CreateIntToPtr(hash_ptr, composite_dict_ptr_type);
702  const auto key_component_count = getKeyComponentCount();
703  const auto key = executor_->cgen_state_->emitExternalCall(
704  "get_composite_key_index_" + std::to_string(key_component_width * 8),
706  {key_buff_lv,
707  LL_INT(key_component_count),
708  composite_key_dict,
709  LL_INT(hash_table->getEntryCount())});
710  auto one_to_many_ptr = hash_ptr;
711  if (one_to_many_ptr->getType()->isPointerTy()) {
712  one_to_many_ptr =
713  LL_BUILDER.CreatePtrToInt(hash_ptr, llvm::Type::getInt64Ty(LL_CONTEXT));
714  } else {
715  CHECK(one_to_many_ptr->getType()->isIntegerTy(64));
716  }
717  const auto composite_key_dict_size = offsetBufferOff();
718  one_to_many_ptr =
719  LL_BUILDER.CreateAdd(one_to_many_ptr, LL_INT(composite_key_dict_size));
721  {one_to_many_ptr, key, LL_INT(int64_t(0)), LL_INT(hash_table->getEntryCount() - 1)},
722  false,
723  false,
724  false,
726  executor_);
727 }
728 
730  return getKeyBufferSize();
731 }
732 
736  } else {
737  return getKeyBufferSize();
738  }
739 }
740 
744  } else {
745  return getKeyBufferSize();
746  }
747 }
748 
750  const auto key_component_width = getKeyComponentWidth();
751  CHECK(key_component_width == 4 || key_component_width == 8);
752  const auto key_component_count = getKeyComponentCount();
753  auto hash_table = getHashTableForDevice(size_t(0));
754  CHECK(hash_table);
755  if (layoutRequiresAdditionalBuffers(hash_table->getLayout())) {
756  return hash_table->getEntryCount() * key_component_count * key_component_width;
757  } else {
758  return hash_table->getEntryCount() * (key_component_count + 1) * key_component_width;
759  }
760 }
761 
763  const auto hash_table = getHashTableForDevice(size_t(0));
764  return hash_table->getEntryCount() * sizeof(int32_t);
765 }
766 
768  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
769  const auto key_component_width = getKeyComponentWidth();
770  CHECK(key_component_width == 4 || key_component_width == 8);
771  const auto key_size_lv = LL_INT(getKeyComponentCount() * key_component_width);
772  llvm::Value* key_buff_lv{nullptr};
773  switch (key_component_width) {
774  case 4:
775  key_buff_lv =
776  LL_BUILDER.CreateAlloca(llvm::Type::getInt32Ty(LL_CONTEXT), key_size_lv);
777  break;
778  case 8:
779  key_buff_lv =
780  LL_BUILDER.CreateAlloca(llvm::Type::getInt64Ty(LL_CONTEXT), key_size_lv);
781  break;
782  default:
783  CHECK(false);
784  }
785 
786  CodeGenerator code_generator(executor_);
787  for (size_t i = 0; i < getKeyComponentCount(); ++i) {
788  const auto key_comp_dest_lv = LL_BUILDER.CreateGEP(key_buff_lv, LL_INT(i));
789  const auto& inner_outer_pair = inner_outer_pairs_[i];
790  const auto outer_col = inner_outer_pair.second;
791  const auto key_col_var = dynamic_cast<const Analyzer::ColumnVar*>(outer_col);
792  const auto val_col_var =
793  dynamic_cast<const Analyzer::ColumnVar*>(inner_outer_pair.first);
794  if (key_col_var && val_col_var &&
796  key_col_var,
797  val_col_var,
798  get_max_rte_scan_table(executor_->cgen_state_->scan_idx_to_hash_pos_))) {
799  throw std::runtime_error(
800  "Query execution fails because the query contains not supported self-join "
801  "pattern. We suspect the query requires multiple left-deep join tree due to "
802  "the join condition of the self-join and is not supported for now. Please "
803  "consider rewriting table order in "
804  "FROM clause.");
805  }
806  const auto col_lvs = code_generator.codegen(outer_col, true, co);
807  CHECK_EQ(size_t(1), col_lvs.size());
808  const auto col_lv = LL_BUILDER.CreateSExt(
809  col_lvs.front(), get_int_type(key_component_width * 8, LL_CONTEXT));
810  LL_BUILDER.CreateStore(col_lv, key_comp_dest_lv);
811  }
812  return key_buff_lv;
813 }
814 
815 llvm::Value* BaselineJoinHashTable::hashPtr(const size_t index) {
816  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
817  auto hash_ptr = HashJoin::codegenHashTableLoad(index, executor_);
818  const auto pi8_type = llvm::Type::getInt8PtrTy(LL_CONTEXT);
819  return hash_ptr->getType()->isPointerTy()
820  ? LL_BUILDER.CreatePointerCast(hash_ptr, pi8_type)
821  : LL_BUILDER.CreateIntToPtr(hash_ptr, pi8_type);
822 }
823 
824 #undef ROW_FUNC
825 #undef LL_INT
826 #undef LL_BUILDER
827 #undef LL_CONTEXT
828 
830  try {
832  } catch (...) {
833  CHECK(false);
834  }
835  return 0;
836 }
837 
839  CHECK(!inner_outer_pairs_.empty());
840  const auto first_inner_col = inner_outer_pairs_.front().first;
841  return first_inner_col->get_rte_idx();
842 }
843 
845  auto hash_table = getHashTableForDevice(size_t(0));
846  CHECK(hash_table);
847  if (layout_override_) {
848  return *layout_override_;
849  } else {
850  return hash_table->getLayout();
851  }
852 }
853 
855  const std::vector<InnerOuter>& inner_outer_pairs) {
856  CHECK(!inner_outer_pairs.empty());
857  const auto first_inner_col = inner_outer_pairs.front().first;
858  return first_inner_col->get_table_id();
859 }
860 
862  const HashTableCacheKey& key) {
863  auto timer = DEBUG_TIMER(__func__);
864  VLOG(1) << "Checking CPU hash table cache.";
866  auto hash_table_opt = (hash_table_cache_->get(key));
867  return hash_table_opt ? *hash_table_opt : nullptr;
868 }
869 
871  const HashTableCacheKey& key,
872  std::shared_ptr<HashTable>& hash_table) {
873  for (auto chunk_key : key.chunk_keys) {
874  CHECK_GE(chunk_key.size(), size_t(2));
875  if (chunk_key[1] < 0) {
876  return;
877  }
878  }
880  hash_table_cache_->insert(key, hash_table);
881 }
882 
883 std::pair<std::optional<size_t>, size_t>
885  const HashTableCacheKey& key) const {
886  for (auto chunk_key : key.chunk_keys) {
887  CHECK_GE(chunk_key.size(), size_t(2));
888  if (chunk_key[1] < 0) {
889  return std::make_pair(std::nullopt, 0);
890  ;
891  }
892  }
893 
895  auto hash_table_opt = hash_table_cache_->get(key);
896  if (hash_table_opt) {
897  auto hash_table = *hash_table_opt;
898  return std::make_pair(hash_table->getEntryCount() / 2,
899  hash_table->getEmittedKeysCount());
900  }
901  return std::make_pair(std::nullopt, 0);
902 }
903 
905  return condition_->get_optype() == kBW_EQ;
906 }
907 
908 std::map<std::vector<ChunkKey>, HashType> HashTypeCache::hash_type_cache_;
910 
911 void HashTypeCache::set(const std::vector<ChunkKey>& key, const HashType hash_type) {
912  for (auto chunk_key : key) {
913  CHECK_GE(chunk_key.size(), size_t(2));
914  if (chunk_key[1] < 0) {
915  return;
916  }
917  }
918  std::lock_guard<std::mutex> hash_type_cache_lock(hash_type_cache_mutex_);
919  hash_type_cache_[key] = hash_type;
920 }
921 
922 std::pair<HashType, bool> HashTypeCache::get(const std::vector<ChunkKey>& key) {
923  std::lock_guard<std::mutex> hash_type_cache_lock(hash_type_cache_mutex_);
924  const auto it = hash_type_cache_.find(key);
925  if (it == hash_type_cache_.end()) {
926  return {HashType::OneToOne, false};
927  }
928  return {it->second, true};
929 }
930 
932  std::lock_guard<std::mutex> hash_type_cache_lock(hash_type_cache_mutex_);
933  hash_type_cache_.clear();
934 }
size_t offsetBufferOff() const noexceptoverride
catalog_(nullptr)
std::set< DecodedJoinHashBufferEntry > toSet(const ExecutorDeviceType device_type, const int device_id) const override
void putHashTableOnCpuToCache(const HashTableCacheKey &, std::shared_ptr< HashTable > &hash_table)
#define CHECK_EQ(x, y)
Definition: Logger.h:211
static std::unique_ptr< HashTableCache< HashTableCacheKey, HashTableCacheValue > > hash_table_cache_
virtual HashJoinMatchingSet codegenMatchingSet(const CompilationOptions &, const size_t)=0
int64_t getJoinHashBuffer(const ExecutorDeviceType device_type, const int device_id) const
Definition: HashJoin.h:233
Fragmenter_Namespace::TableInfo info
Definition: InputMetadata.h:35
std::string toString(const ExecutorDeviceType device_type, const int device_id=0, bool raw=false) const override
static llvm::Value * codegenHashTableLoad(const size_t table_idx, Executor *executor)
Definition: HashJoin.cpp:215
bool self_join_not_covered_by_left_deep_tree(const Analyzer::ColumnVar *key_side, const Analyzer::ColumnVar *val_side, const int max_rte_covered)
Data_Namespace::MemoryLevel getEffectiveMemoryLevel(const std::vector< InnerOuter > &inner_outer_pairs) const
static std::mutex hash_type_cache_mutex_
ExecutorDeviceType
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:223
#define const
static std::map< std::vector< ChunkKey >, HashType > hash_type_cache_
HashJoinMatchingSet codegenMatchingSet(const CompilationOptions &, const size_t) override
void hll_unify(T1 *lhs, T2 *rhs, const size_t m)
Definition: HyperLogLog.h:109
JoinColumn fetchJoinColumn(const Analyzer::ColumnVar *hash_col, const std::vector< Fragmenter_Namespace::FragmentInfo > &fragment_info, const Data_Namespace::MemoryLevel effective_memory_level, const int device_id, std::vector< std::shared_ptr< Chunk_NS::Chunk >> &chunks_owner, DeviceAllocator *dev_buff_owner, std::vector< std::shared_ptr< void >> &malloc_owner, Executor *executor, ColumnCacheMap *column_cache)
Definition: HashJoin.cpp:54
unsigned long long CUdeviceptr
Definition: nocuda.h:27
std::vector< std::shared_ptr< HashTable > > hash_tables_for_device_
Definition: HashJoin.h:269
#define UNREACHABLE()
Definition: Logger.h:247
#define CHECK_GE(x, y)
Definition: Logger.h:216
size_t getKeyBufferSize() const noexcept
#define DEBUG_TIMER_NEW_THREAD(parent_thread_id)
Definition: Logger.h:324
bool needs_dictionary_translation(const Analyzer::ColumnVar *inner_col, const Analyzer::Expr *outer_col_expr, const Executor *executor)
size_t getComponentBufferSize() const noexceptoverride
void freeHashBufferMemory()
Definition: HashJoin.h:256
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
size_t hll_size(const T *M, const size_t bitmap_sz_bits)
Definition: HyperLogLog.h:90
#define CHECK_GT(x, y)
Definition: Logger.h:215
static std::shared_ptr< BaselineJoinHashTable > getInstance(const std::shared_ptr< Analyzer::BinOper > condition, const std::vector< InputTableInfo > &query_infos, const Data_Namespace::MemoryLevel memory_level, const HashType preferred_hash_type, const int device_count, ColumnCacheMap &column_cache, Executor *executor)
Make hash table from an in-flight SQL query&#39;s parse tree etc.
const int get_max_rte_scan_table(std::unordered_map< int, llvm::Value * > &scan_idx_to_hash_pos)
int getInnerTableRteIdx() const noexceptoverride
static std::pair< HashType, bool > get(const std::vector< ChunkKey > &key)
std::string to_string(char const *&&v)
virtual void reifyForDevice(const ColumnsForDevice &columns_for_device, const HashType layout, const int device_id, const size_t entry_count, const size_t emitted_keys_count, const logger::ThreadId parent_thread_id)
virtual ColumnsForDevice fetchColumnsForDevice(const std::vector< Fragmenter_Namespace::FragmentInfo > &fragments, const int device_id, DeviceAllocator *dev_buff_owner)
const std::vector< InputTableInfo > & query_infos_
std::pair< std::optional< size_t >, size_t > getApproximateTupleCountFromCache(const HashTableCacheKey &) const
virtual llvm::Value * codegenKey(const CompilationOptions &)
size_t payloadBufferOff() const noexceptoverride
std::vector< InnerOuter > inner_outer_pairs_
const std::vector< JoinColumnTypeInfo > join_column_types
Definition: HashJoin.h:80
void reify(const HashType preferred_layout)
void approximate_distinct_tuples(uint8_t *hll_buffer_all_cpus, const uint32_t b, const size_t padded_size_bytes, const std::vector< JoinColumn > &join_column_per_key, const std::vector< JoinColumnTypeInfo > &type_info_per_key, const int thread_count)
HashType getHashType() const noexceptoverride
void copy_to_gpu(Data_Namespace::DataMgr *data_mgr, CUdeviceptr dst, const void *src, const size_t num_bytes, const int device_id)
Definition: GpuMemUtils.cpp:30
const ColumnDescriptor * get_column_descriptor_maybe(const int col_id, const int table_id, const Catalog_Namespace::Catalog &cat)
Definition: Execute.h:221
ColumnCacheMap & column_cache_
#define LL_INT(v)
void copy_from_gpu(Data_Namespace::DataMgr *data_mgr, void *dst, const CUdeviceptr src, const size_t num_bytes, const int device_id)
T * transfer_flat_object_to_gpu(const T &object, CudaAllocator &allocator)
BaselineJoinHashTable(const std::shared_ptr< Analyzer::BinOper > condition, const std::vector< InputTableInfo > &query_infos, const Data_Namespace::MemoryLevel memory_level, ColumnCacheMap &column_cache, Executor *executor, const std::vector< InnerOuter > &inner_outer_pairs, const int device_count)
std::vector< Fragmenter_Namespace::FragmentInfo > only_shards_for_device(const std::vector< Fragmenter_Namespace::FragmentInfo > &fragments, const int device_id, const int device_count)
int initHashTableOnGpu(KEY_HANDLER *key_handler, const std::vector< JoinColumn > &join_columns, const HashType layout, const size_t key_component_width, const size_t key_component_count, const size_t keyspace_entry_count, const size_t emitted_keys_count, const int device_id)
virtual std::pair< size_t, size_t > approximateTupleCount(const std::vector< ColumnsForDevice > &) const
std::vector< InnerOuter > normalize_column_pairs(const Analyzer::BinOper *condition, const Catalog_Namespace::Catalog &cat, const TemporaryTables *temporary_tables)
Definition: HashJoin.cpp:705
int initHashTableOnCpu(KEY_HANDLER *key_handler, const CompositeKeyInfo &composite_key_info, const std::vector< JoinColumn > &join_columns, const std::vector< JoinColumnTypeInfo > &join_column_types, const std::vector< JoinBucketInfo > &join_bucket_info, const size_t keyspace_entry_count, const size_t keys_for_all_rows, const HashType layout, const size_t key_component_width, const size_t key_component_count)
#define LL_CONTEXT
#define AUTOMATIC_IR_METADATA(CGENSTATE)
static void checkHashJoinReplicationConstraint(const int table_id, const size_t shard_count, const Executor *executor)
Definition: HashJoin.cpp:525
virtual void reifyWithLayout(const HashType layout)
std::unordered_map< int, std::unordered_map< int, std::shared_ptr< const ColumnarResults >>> ColumnCacheMap
HashTable * getHashTableForDevice(const size_t device_id) const
Definition: HashJoin.h:214
#define VLOGGING(n)
Definition: Logger.h:201
const InputTableInfo & get_inner_query_info(const int inner_table_id, const std::vector< InputTableInfo > &query_infos)
std::vector< llvm::Value * > codegen(const Analyzer::Expr *, const bool fetch_columns, const CompilationOptions &)
Definition: IRCodegen.cpp:28
static CompositeKeyInfo getCompositeKeyInfo(const std::vector< InnerOuter > &inner_outer_pairs, const Executor *executor)
Definition: HashJoin.cpp:319
#define CHECK_LT(x, y)
Definition: Logger.h:213
int getInnerTableId() const noexceptoverride
int8_t * alloc(const size_t num_bytes) override
#define LL_BUILDER
void allocateDeviceMemory(const HashType layout, const size_t key_component_width, const size_t key_component_count, const size_t keyspace_entry_count, const size_t emitted_keys_count, const int device_id)
std::unique_ptr< BaselineHashTable > getHashTable()
static std::string getHashTypeString(HashType ht) noexcept
Definition: HashJoin.h:133
std::optional< HashType > layout_override_
static std::string toString(const std::string &type, const std::string &layout_type, size_t key_component_count, size_t key_component_width, size_t entry_count, const int8_t *ptr1, const int8_t *ptr2, const int8_t *ptr3, const int8_t *ptr4, size_t buffer_size, bool raw=false)
Decode hash table into a human-readable string.
Definition: HashTable.cpp:226
size_t get_entries_per_device(const size_t total_entries, const size_t shard_count, const size_t device_count, const Data_Namespace::MemoryLevel memory_level)
const Catalog_Namespace::Catalog * catalog_
std::shared_ptr< HashTable > initHashTableOnCpuFromCache(const HashTableCacheKey &)
uint64_t ThreadId
Definition: Logger.h:312
const Data_Namespace::MemoryLevel memory_level_
llvm::Value * hashPtr(const size_t index)
ThreadId thread_id()
Definition: Logger.cpp:732
virtual int initHashTableForDevice(const std::vector< JoinColumn > &join_columns, const std::vector< JoinColumnTypeInfo > &join_column_types, const std::vector< JoinBucketInfo > &join_buckets, const HashType layout, const Data_Namespace::MemoryLevel effective_memory_level, const size_t entry_count, const size_t emitted_keys_count, const int device_id)
void approximate_distinct_tuples_on_device(uint8_t *hll_buffer, const uint32_t b, const GenericKeyHandler *key_handler, const int64_t num_elems)
ColumnType get_join_column_type_kind(const SQLTypeInfo &ti)
llvm::Value * codegenSlot(const CompilationOptions &, const size_t) override
#define CHECK(condition)
Definition: Logger.h:203
T * transfer_vector_of_flat_objects_to_gpu(const std::vector< T > &vec, CudaAllocator &allocator)
#define DEBUG_TIMER(name)
Definition: Logger.h:319
Definition: sqldefs.h:31
virtual size_t getKeyComponentCount() const
int64_t inline_fixed_encoding_null_val(const SQL_TYPE_INFO &ti)
virtual size_t getKeyComponentWidth() const
static DecodedJoinHashBufferSet toSet(size_t key_component_count, size_t key_component_width, size_t entry_count, const int8_t *ptr1, const int8_t *ptr2, const int8_t *ptr3, const int8_t *ptr4, size_t buffer_size)
Decode hash table into a std::set for easy inspection and validation.
Definition: HashTable.cpp:139
Allocate GPU memory using GpuBuffers via DataMgr.
static size_t getShardCountForCondition(const Analyzer::BinOper *condition, const Executor *executor, const std::vector< InnerOuter > &inner_outer_pairs)
static void set(const std::vector< ChunkKey > &key, const HashType hash_type)
std::vector< JoinBucketInfo > join_buckets
Definition: HashJoin.h:82
int cpu_threads()
Definition: thread_count.h:24
size_t get_shard_count(const Analyzer::BinOper *join_condition, const Executor *executor)
Definition: HashJoin.cpp:553
HashType
Definition: HashTable.h:19
const std::vector< JoinColumn > join_columns
Definition: HashJoin.h:79
#define VLOG(n)
Definition: Logger.h:297
static bool layoutRequiresAdditionalBuffers(HashType layout) noexcept
Definition: HashJoin.h:129
const std::shared_ptr< Analyzer::BinOper > condition_
size_t countBufferOff() const noexceptoverride
const std::vector< ChunkKey > chunk_keys