OmniSciDB  c0231cc57d
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
ColumnIR.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 "CodeGenerator.h"
18 #include "Codec.h"
19 #include "Execute.h"
20 #include "WindowContext.h"
21 
22 // Code generation routines and helpers for working with column expressions.
23 
24 namespace {
25 
26 // Return the right decoder for a given column expression. Doesn't handle
27 // variable length data. The decoder encapsulates the code generation logic.
28 std::shared_ptr<Decoder> get_col_decoder(const Analyzer::ColumnVar* col_var) {
29  const auto enc_type = col_var->get_compression();
30  const auto& ti = col_var->get_type_info();
31  switch (enc_type) {
32  case kENCODING_NONE: {
33  const auto int_type = ti.is_decimal() ? decimal_to_int_type(ti) : ti.get_type();
34  switch (int_type) {
35  case kBOOLEAN:
36  return std::make_shared<FixedWidthInt>(1);
37  case kTINYINT:
38  return std::make_shared<FixedWidthInt>(1);
39  case kSMALLINT:
40  return std::make_shared<FixedWidthInt>(2);
41  case kINT:
42  return std::make_shared<FixedWidthInt>(4);
43  case kBIGINT:
44  return std::make_shared<FixedWidthInt>(8);
45  case kFLOAT:
46  return std::make_shared<FixedWidthReal>(false);
47  case kDOUBLE:
48  return std::make_shared<FixedWidthReal>(true);
49  case kTIME:
50  case kTIMESTAMP:
51  case kDATE:
52  return std::make_shared<FixedWidthInt>(8);
53  default:
54  CHECK(false);
55  }
56  }
57  case kENCODING_DICT:
58  CHECK(ti.is_string());
59  // For dictionary-encoded columns encoded on less than 4 bytes, we can use
60  // unsigned representation for double the maximum cardinality. The inline
61  // null value is going to be the maximum value of the underlying type.
62  if (ti.get_size() < ti.get_logical_size()) {
63  return std::make_shared<FixedWidthUnsigned>(ti.get_size());
64  }
65  return std::make_shared<FixedWidthInt>(ti.get_size());
66  case kENCODING_FIXED: {
67  const auto bit_width = col_var->get_comp_param();
68  CHECK_EQ(0, bit_width % 8);
69  return std::make_shared<FixedWidthInt>(bit_width / 8);
70  }
72  CHECK(ti.is_date_in_days());
73  return col_var->get_comp_param() == 16 ? std::make_shared<FixedWidthSmallDate>(2)
74  : std::make_shared<FixedWidthSmallDate>(4);
75  }
76  default:
77  abort();
78  }
79 }
80 
81 size_t get_col_bit_width(const Analyzer::ColumnVar* col_var) {
82  const auto& type_info = col_var->get_type_info();
83  return get_bit_width(type_info);
84 }
85 
87  return col_var->get_rte_idx() == -1 ? 0 : col_var->get_rte_idx();
88 }
89 
90 } // namespace
91 
92 std::vector<llvm::Value*> CodeGenerator::codegenColumn(const Analyzer::ColumnVar* col_var,
93  const bool fetch_column,
94  const CompilationOptions& co) {
96  if (col_var->get_rte_idx() <= 0 ||
98  !foundOuterJoinMatch(col_var->get_rte_idx())) {
99  return codegenColVar(col_var, fetch_column, true, co);
100  }
101  return codegenOuterJoinNullPlaceholder(col_var, fetch_column, co);
102 }
103 
104 std::vector<llvm::Value*> CodeGenerator::codegenColVar(const Analyzer::ColumnVar* col_var,
105  const bool fetch_column,
106  const bool update_query_plan,
107  const CompilationOptions& co) {
109  const bool hoist_literals = co.hoist_literals;
110  auto col_id = col_var->get_column_id();
111  const int rte_idx = adjusted_range_table_index(col_var);
112  CHECK_LT(static_cast<size_t>(rte_idx), cgen_state_->frag_offsets_.size());
113  const auto catalog = executor()->getCatalog();
114  CHECK(catalog);
115  if (col_var->get_table_id() > 0) {
116  auto cd = get_column_descriptor(col_id, col_var->get_table_id(), *catalog);
117  if (cd->isVirtualCol) {
118  CHECK(cd->columnName == "rowid");
119  return {codegenRowId(col_var, co)};
120  }
121  auto col_ti = cd->columnType;
122  if (col_ti.get_physical_coord_cols() > 0) {
123  std::vector<llvm::Value*> cols;
124  for (auto i = 0; i < col_ti.get_physical_coord_cols(); i++) {
125  auto cd0 =
126  get_column_descriptor(col_id + i + 1, col_var->get_table_id(), *catalog);
127  auto col0_ti = cd0->columnType;
128  CHECK(!cd0->isVirtualCol);
129  auto col0_var = makeExpr<Analyzer::ColumnVar>(
130  col0_ti, col_var->get_table_id(), cd0->columnId, rte_idx);
131  auto col = codegenColVar(col0_var.get(), fetch_column, false, co);
132  cols.insert(cols.end(), col.begin(), col.end());
133  if (!fetch_column && plan_state_->isLazyFetchColumn(col_var)) {
135  std::make_pair(col_var->get_table_id(), col0_var->get_column_id()));
136  }
137  }
138  if (!fetch_column && plan_state_->isLazyFetchColumn(col_var)) {
140  std::make_pair(col_var->get_table_id(), col_var->get_column_id()));
141  } else {
143  std::make_pair(col_var->get_table_id(), col_var->get_column_id()));
144  }
145  return cols;
146  }
147  } else {
148  if (col_var->get_type_info().is_geometry()) {
149  throw std::runtime_error(
150  "Geospatial columns not supported in temporary tables yet");
151  }
152  }
153  const auto grouped_col_lv = resolveGroupedColumnReference(col_var);
154  if (grouped_col_lv) {
155  return {grouped_col_lv};
156  }
157  const auto col_var_hash = boost::hash_value(col_var->toString());
158  const auto window_func_context =
160  // only generate the decoding code once; if a column has been previously
161  // fetched in the generated IR, we'll reuse it
162  // here, we do not just use (local) column id since our analyzer may cast the same
163  // col_var with different types depending on the (aggregate) function that the col_var
164  // is used i.e., SELECT COUNT(DISTINCT x), MIN(x) FROM ...
165  if (!window_func_context) {
166  auto it = cgen_state_->fetch_cache_.find(col_var_hash);
167  if (it != cgen_state_->fetch_cache_.end()) {
168  return {it->second};
169  }
170  }
171  const auto hash_join_lhs = hashJoinLhs(col_var);
172  // Note(jclay): This has been prone to cause failures in some overlaps joins.
173  // I believe most of the issues are worked out now, but a good place to check if
174  // failures are happening.
175 
176  // Use the already fetched left-hand side of an equi-join if the types are identical.
177  // Currently, types can only be different because of different underlying dictionaries.
178  if (hash_join_lhs && hash_join_lhs->get_type_info() == col_var->get_type_info()) {
179  if (plan_state_->isLazyFetchColumn(col_var)) {
181  std::make_pair(col_var->get_table_id(), col_var->get_column_id()));
182  }
183  return codegen(hash_join_lhs.get(), fetch_column, co);
184  }
185  auto pos_arg = posArg(col_var);
186  if (window_func_context) {
187  pos_arg = codegenWindowPosition(window_func_context, pos_arg);
188  }
189  auto col_byte_stream = colByteStream(col_var, fetch_column, hoist_literals);
190  if (plan_state_->isLazyFetchColumn(col_var)) {
191  if (update_query_plan) {
193  std::make_pair(col_var->get_table_id(), col_var->get_column_id()));
194  }
195  if (rte_idx > 0) {
196  const auto offset = cgen_state_->frag_offsets_[rte_idx];
197  if (offset) {
198  return {cgen_state_->ir_builder_.CreateAdd(pos_arg, offset)};
199  } else {
200  return {pos_arg};
201  }
202  }
203  return {pos_arg};
204  }
205  const auto& col_ti = col_var->get_type_info();
206  if (col_ti.is_string() && col_ti.get_compression() == kENCODING_NONE) {
207  const auto varlen_str_column_lvs =
208  codegenVariableLengthStringColVar(col_byte_stream, pos_arg);
209  if (!window_func_context) {
210  auto it_ok = cgen_state_->fetch_cache_.insert(
211  std::make_pair(col_var_hash, varlen_str_column_lvs));
212  CHECK(it_ok.second);
213  }
214  return varlen_str_column_lvs;
215  }
216  if (col_ti.is_array()) {
217  return {col_byte_stream};
218  }
219  if (window_func_context) {
221  col_var, col_byte_stream, pos_arg, window_func_context)};
222  }
223  const auto fixed_length_column_lv =
224  codegenFixedLengthColVar(col_var, col_byte_stream, pos_arg);
225  auto it_ok = cgen_state_->fetch_cache_.insert(
226  std::make_pair(col_var_hash, std::vector<llvm::Value*>{fixed_length_column_lv}));
227  return {it_ok.first->second};
228 }
229 
231  const WindowFunctionContext* window_func_context,
232  llvm::Value* pos_arg) {
234  const auto window_position = cgen_state_->emitCall(
235  "row_number_window_func",
236  {cgen_state_->llInt(reinterpret_cast<const int64_t>(window_func_context->output())),
237  pos_arg});
238  return window_position;
239 }
240 
241 // Generate code for fixed length column types (number, timestamp or date,
242 // dictionary-encoded string)
244  const Analyzer::ColumnVar* col_var,
245  llvm::Value* col_byte_stream,
246  llvm::Value* pos_arg,
247  const WindowFunctionContext* window_function_context) {
249  const auto decoder = get_col_decoder(col_var);
250  auto dec_val = decoder->codegenDecode(col_byte_stream, pos_arg, cgen_state_->module_);
251  cgen_state_->ir_builder_.Insert(dec_val);
252  auto dec_type = dec_val->getType();
253  llvm::Value* dec_val_cast{nullptr};
254  const auto& col_ti = col_var->get_type_info();
255  if (dec_type->isIntegerTy()) {
256  auto dec_width = static_cast<llvm::IntegerType*>(dec_type)->getBitWidth();
257  auto col_width = get_col_bit_width(col_var);
258  dec_val_cast = cgen_state_->ir_builder_.CreateCast(
259  static_cast<size_t>(col_width) > dec_width ? llvm::Instruction::CastOps::SExt
260  : llvm::Instruction::CastOps::Trunc,
261  dec_val,
262  get_int_type(col_width, cgen_state_->context_));
263  bool adjust_fixed_enc_null = true;
264  if (window_function_context &&
265  window_function_context->getWindowFunction()->hasRangeModeFraming()) {
266  // we only need to cast it to 8 byte iff it is encoded type
267  // (i.e., the size of non-encoded timestamp type is 8 byte)
268  const auto order_key_ti =
269  window_function_context->getOrderKeyColumnBufferTypes().front();
270  if (order_key_ti.is_timestamp() && order_key_ti.get_size() == 4) {
271  adjust_fixed_enc_null = false;
272  }
273  }
274  if (adjust_fixed_enc_null &&
275  (col_ti.get_compression() == kENCODING_FIXED ||
276  (col_ti.get_compression() == kENCODING_DICT && col_ti.get_size() < 4)) &&
277  !col_ti.get_notnull()) {
278  dec_val_cast = codgenAdjustFixedEncNull(dec_val_cast, col_ti);
279  }
280  } else {
281  CHECK_EQ(kENCODING_NONE, col_ti.get_compression());
282  CHECK(dec_type->isFloatTy() || dec_type->isDoubleTy());
283  if (dec_type->isDoubleTy()) {
284  CHECK(col_ti.get_type() == kDOUBLE);
285  } else if (dec_type->isFloatTy()) {
286  CHECK(col_ti.get_type() == kFLOAT);
287  }
288  dec_val_cast = dec_val;
289  }
290  CHECK(dec_val_cast);
291  return dec_val_cast;
292 }
293 
295  const Analyzer::ColumnVar* col_var,
296  llvm::Value* col_byte_stream,
297  llvm::Value* pos_arg,
298  const WindowFunctionContext* window_function_context) {
300  const auto orig_bb = cgen_state_->ir_builder_.GetInsertBlock();
301  const auto pos_is_valid =
302  cgen_state_->ir_builder_.CreateICmpSGE(pos_arg, cgen_state_->llInt(int64_t(0)));
303  const auto pos_valid_bb = llvm::BasicBlock::Create(
304  cgen_state_->context_, "window.pos_valid", cgen_state_->current_func_);
305  const auto pos_notvalid_bb = llvm::BasicBlock::Create(
306  cgen_state_->context_, "window.pos_notvalid", cgen_state_->current_func_);
307  cgen_state_->ir_builder_.CreateCondBr(pos_is_valid, pos_valid_bb, pos_notvalid_bb);
308  cgen_state_->ir_builder_.SetInsertPoint(pos_valid_bb);
309  const auto fixed_length_column_lv = codegenFixedLengthColVar(
310  col_var, col_byte_stream, pos_arg, window_function_context);
311  cgen_state_->ir_builder_.CreateBr(pos_notvalid_bb);
312  cgen_state_->ir_builder_.SetInsertPoint(pos_notvalid_bb);
313  const auto window_func_call_phi =
314  cgen_state_->ir_builder_.CreatePHI(fixed_length_column_lv->getType(), 2);
315  window_func_call_phi->addIncoming(fixed_length_column_lv, pos_valid_bb);
316  const auto& col_ti = col_var->get_type_info();
317  const auto null_lv =
318  col_ti.is_fp() ? static_cast<llvm::Value*>(cgen_state_->inlineFpNull(col_ti))
319  : static_cast<llvm::Value*>(cgen_state_->inlineIntNull(col_ti));
320  window_func_call_phi->addIncoming(null_lv, orig_bb);
321  return window_func_call_phi;
322 }
323 
325  llvm::Value* col_byte_stream,
326  llvm::Value* pos_arg) {
328  // real (not dictionary-encoded) strings; store the pointer to the payload
329  auto ptr_and_len =
330  cgen_state_->emitExternalCall("string_decode",
332  {col_byte_stream, pos_arg});
333  // Unpack the pointer + length, see string_decode function.
334  auto str_lv = cgen_state_->emitCall("extract_str_ptr", {ptr_and_len});
335  auto len_lv = cgen_state_->emitCall("extract_str_len", {ptr_and_len});
336  return {ptr_and_len, str_lv, len_lv};
337 }
338 
340  const CompilationOptions& co) {
342  const auto offset_lv = cgen_state_->frag_offsets_[adjusted_range_table_index(col_var)];
343  llvm::Value* start_rowid_lv{nullptr};
344  const auto& table_generation = executor()->getTableGeneration(col_var->get_table_id());
345  if (table_generation.start_rowid > 0) {
346  // Handle the multi-node case: each leaf receives a start rowid used
347  // to offset the local rowid and generate a cluster-wide unique rowid.
348  Datum d;
349  d.bigintval = table_generation.start_rowid;
350  const auto start_rowid = makeExpr<Analyzer::Constant>(kBIGINT, false, d);
351  const auto start_rowid_lvs = codegen(start_rowid.get(), kENCODING_NONE, -1, co);
352  CHECK_EQ(size_t(1), start_rowid_lvs.size());
353  start_rowid_lv = start_rowid_lvs.front();
354  }
355  auto rowid_lv = posArg(col_var);
356  if (offset_lv) {
357  rowid_lv = cgen_state_->ir_builder_.CreateAdd(rowid_lv, offset_lv);
358  } else if (col_var->get_rte_idx() > 0) {
359  auto frag_off_ptr = get_arg_by_name(cgen_state_->row_func_, "frag_row_off");
360  auto input_off_ptr = cgen_state_->ir_builder_.CreateGEP(
361  frag_off_ptr->getType()->getScalarType()->getPointerElementType(),
362  frag_off_ptr,
363  cgen_state_->llInt(int32_t(col_var->get_rte_idx())));
364  auto rowid_offset_lv = cgen_state_->ir_builder_.CreateLoad(
365  input_off_ptr->getType()->getPointerElementType(), input_off_ptr);
366  rowid_lv = cgen_state_->ir_builder_.CreateAdd(rowid_lv, rowid_offset_lv);
367  }
368  if (table_generation.start_rowid > 0) {
369  CHECK(start_rowid_lv);
370  rowid_lv = cgen_state_->ir_builder_.CreateAdd(rowid_lv, start_rowid_lv);
371  }
372  return rowid_lv;
373 }
374 
375 namespace {
376 
377 SQLTypes get_phys_int_type(const size_t byte_sz) {
378  switch (byte_sz) {
379  case 1:
380  return kBOOLEAN;
381  // TODO: kTINYINT
382  case 2:
383  return kSMALLINT;
384  case 4:
385  return kINT;
386  case 8:
387  return kBIGINT;
388  default:
389  CHECK(false);
390  }
391  return kNULLT;
392 }
393 
394 } // namespace
395 
396 llvm::Value* CodeGenerator::codgenAdjustFixedEncNull(llvm::Value* val,
397  const SQLTypeInfo& col_ti) {
399  CHECK_LT(col_ti.get_size(), col_ti.get_logical_size());
400  const auto col_phys_width = col_ti.get_size() * 8;
401  auto from_typename = "int" + std::to_string(col_phys_width) + "_t";
402  auto adjusted = cgen_state_->ir_builder_.CreateCast(
403  llvm::Instruction::CastOps::Trunc,
404  val,
405  get_int_type(col_phys_width, cgen_state_->context_));
406  if (col_ti.get_compression() == kENCODING_DICT) {
407  from_typename = "u" + from_typename;
408  llvm::Value* from_null{nullptr};
409  switch (col_ti.get_size()) {
410  case 1:
411  from_null = cgen_state_->llInt(std::numeric_limits<uint8_t>::max());
412  break;
413  case 2:
414  from_null = cgen_state_->llInt(std::numeric_limits<uint16_t>::max());
415  break;
416  default:
417  CHECK(false);
418  }
419  return cgen_state_->emitCall(
420  "cast_" + from_typename + "_to_" + numeric_type_name(col_ti) + "_nullable",
421  {adjusted, from_null, cgen_state_->inlineIntNull(col_ti)});
422  }
423  SQLTypeInfo col_from_phys_ti(get_phys_int_type(col_ti.get_size()),
424  col_ti.get_dimension(),
425  col_ti.get_scale(),
426  false,
428  0,
429  col_ti.get_subtype());
430  SQLTypeInfo col_to_phys_ti(col_ti.get_type(),
431  col_ti.get_dimension(),
432  col_ti.get_scale(),
433  col_ti.get_notnull(),
435  0,
436  col_ti.get_subtype());
437  const auto to_typename = numeric_type_name(col_to_phys_ti);
438  return cgen_state_->emitCall(
439  "cast_" + from_typename + "_to_" + to_typename + "_nullable",
440  {adjusted,
441  cgen_state_->inlineIntNull(col_from_phys_ti),
442  cgen_state_->inlineIntNull(col_to_phys_ti)});
443 }
444 
445 llvm::Value* CodeGenerator::foundOuterJoinMatch(const size_t nesting_level) const {
446  CHECK_GE(nesting_level, size_t(1));
447  CHECK_LE(nesting_level,
448  static_cast<size_t>(cgen_state_->outer_join_match_found_per_level_.size()));
449  return cgen_state_->outer_join_match_found_per_level_[nesting_level - 1];
450 }
451 
453  const Analyzer::ColumnVar* col_var,
454  const bool fetch_column,
455  const CompilationOptions& co) {
457  const auto grouped_col_lv = resolveGroupedColumnReference(col_var);
458  if (grouped_col_lv) {
459  return {grouped_col_lv};
460  }
461  const auto outer_join_args_bb = llvm::BasicBlock::Create(
462  cgen_state_->context_, "outer_join_args", cgen_state_->current_func_);
463  const auto outer_join_nulls_bb = llvm::BasicBlock::Create(
464  cgen_state_->context_, "outer_join_nulls", cgen_state_->current_func_);
465  const auto phi_bb = llvm::BasicBlock::Create(
466  cgen_state_->context_, "outer_join_phi", cgen_state_->current_func_);
467  const auto outer_join_match_lv = foundOuterJoinMatch(col_var->get_rte_idx());
468  CHECK(outer_join_match_lv);
469  cgen_state_->ir_builder_.CreateCondBr(
470  outer_join_match_lv, outer_join_args_bb, outer_join_nulls_bb);
471  const auto back_from_outer_join_bb = llvm::BasicBlock::Create(
472  cgen_state_->context_, "back_from_outer_join", cgen_state_->current_func_);
473  cgen_state_->ir_builder_.SetInsertPoint(outer_join_args_bb);
475  const auto orig_lvs = codegenColVar(col_var, fetch_column, true, co);
476  // sometimes col_var used in the join qual needs to cast its column to sync with
477  // the target join column's type which generates a code with a new bb like cast_bb
478  // if so, we need to keep that bb to correctly construct phi_bb
479  // i.e., use cast_bb instead of outer_join_args_bb for the "casted" column
480  // which is the right end point
481  const auto needs_casting_col_var = needCastForHashJoinLhs(col_var);
482  auto* cast_bb = cgen_state_->ir_builder_.GetInsertBlock();
483  cgen_state_->ir_builder_.CreateBr(phi_bb);
484  cgen_state_->ir_builder_.SetInsertPoint(outer_join_nulls_bb);
485  const auto& null_ti = col_var->get_type_info();
486  if ((null_ti.is_string() && null_ti.get_compression() == kENCODING_NONE) ||
487  null_ti.is_array() || null_ti.is_geometry()) {
488  throw std::runtime_error("Projection type " + null_ti.get_type_name() +
489  " not supported for outer joins yet");
490  }
491  const auto null_constant = makeExpr<Analyzer::Constant>(null_ti, true, Datum{0});
492  const auto null_target_lvs =
493  codegen(null_constant.get(),
494  false,
497  cgen_state_->ir_builder_.CreateBr(phi_bb);
498  CHECK_EQ(orig_lvs.size(), null_target_lvs.size());
499  cgen_state_->ir_builder_.SetInsertPoint(phi_bb);
500  std::vector<llvm::Value*> target_lvs;
501  for (size_t i = 0; i < orig_lvs.size(); ++i) {
502  const auto target_type = orig_lvs[i]->getType();
503  CHECK_EQ(target_type, null_target_lvs[i]->getType());
504  auto target_phi = cgen_state_->ir_builder_.CreatePHI(target_type, 2);
505  const auto orig_lvs_bb = needs_casting_col_var ? cast_bb : outer_join_args_bb;
506  target_phi->addIncoming(orig_lvs[i], orig_lvs_bb);
507  target_phi->addIncoming(null_target_lvs[i], outer_join_nulls_bb);
508  target_lvs.push_back(target_phi);
509  }
510  cgen_state_->ir_builder_.CreateBr(back_from_outer_join_bb);
511  cgen_state_->ir_builder_.SetInsertPoint(back_from_outer_join_bb);
512  return target_lvs;
513 }
514 
516  const Analyzer::ColumnVar* col_var) {
517  auto col_id = col_var->get_column_id();
518  if (col_var->get_rte_idx() >= 0) {
519  return nullptr;
520  }
521  CHECK((col_id == 0) || (col_var->get_rte_idx() >= 0 && col_var->get_table_id() > 0));
522  const auto var = dynamic_cast<const Analyzer::Var*>(col_var);
523  CHECK(var);
524  col_id = var->get_varno();
525  CHECK_GE(col_id, 1);
526  if (var->get_which_row() == Analyzer::Var::kGROUPBY) {
527  CHECK_LE(static_cast<size_t>(col_id), cgen_state_->group_by_expr_cache_.size());
528  return cgen_state_->group_by_expr_cache_[col_id - 1];
529  }
530  return nullptr;
531 }
532 
533 // returns the byte stream argument and the position for the given column
535  const bool fetch_column,
536  const bool hoist_literals) {
537  CHECK_GE(cgen_state_->row_func_->arg_size(), size_t(3));
538  const auto stream_arg_name =
539  "col_buf" + std::to_string(plan_state_->getLocalColumnId(col_var, fetch_column));
540  for (auto& arg : cgen_state_->row_func_->args()) {
541  if (arg.getName() == stream_arg_name) {
542  CHECK(arg.getType() == llvm::Type::getInt8PtrTy(cgen_state_->context_));
543  return &arg;
544  }
545  }
546  CHECK(false);
547  return nullptr;
548 }
549 
550 llvm::Value* CodeGenerator::posArg(const Analyzer::Expr* expr) const {
552  const auto col_var = dynamic_cast<const Analyzer::ColumnVar*>(expr);
553  if (col_var && col_var->get_rte_idx() > 0) {
554  const auto hash_pos_it =
555  cgen_state_->scan_idx_to_hash_pos_.find(col_var->get_rte_idx());
556  CHECK(hash_pos_it != cgen_state_->scan_idx_to_hash_pos_.end());
557  if (hash_pos_it->second->getType()->isPointerTy()) {
558  CHECK(hash_pos_it->second->getType()->getPointerElementType()->isIntegerTy(32));
559  llvm::Value* result = cgen_state_->ir_builder_.CreateLoad(
560  hash_pos_it->second->getType()->getPointerElementType(), hash_pos_it->second);
561  result = cgen_state_->ir_builder_.CreateSExt(
562  result, get_int_type(64, cgen_state_->context_));
563  return result;
564  }
565  return hash_pos_it->second;
566  }
567  for (auto& arg : cgen_state_->row_func_->args()) {
568  if (arg.getName() == "pos") {
569  CHECK(arg.getType()->isIntegerTy(64));
570  return &arg;
571  }
572  }
573  abort();
574 }
575 
577  const auto uoper = dynamic_cast<const Analyzer::UOper*>(expr);
578  if (!uoper || uoper->get_optype() != kCAST) {
579  return nullptr;
580  }
581  const auto& target_ti = uoper->get_type_info();
582  if (!target_ti.is_integer()) {
583  return nullptr;
584  }
585  return uoper->get_operand();
586 }
587 
588 std::shared_ptr<const Analyzer::Expr> CodeGenerator::hashJoinLhs(
589  const Analyzer::ColumnVar* rhs) const {
590  for (const auto& tautological_eq : plan_state_->join_info_.equi_join_tautologies_) {
591  CHECK(IS_EQUIVALENCE(tautological_eq->get_optype()));
592  if (dynamic_cast<const Analyzer::ExpressionTuple*>(
593  tautological_eq->get_left_operand())) {
594  auto lhs_col = hashJoinLhsTuple(rhs, tautological_eq.get());
595  if (lhs_col) {
596  return lhs_col;
597  }
598  } else {
599  auto eq_right_op = tautological_eq->get_right_operand();
600  if (!rhs->get_type_info().is_string()) {
601  eq_right_op = remove_cast_to_int(eq_right_op);
602  }
603  if (!eq_right_op) {
604  eq_right_op = tautological_eq->get_right_operand();
605  }
606  if (*eq_right_op == *rhs) {
607  auto eq_left_op = tautological_eq->get_left_operand();
608  if (!eq_left_op->get_type_info().is_string()) {
609  eq_left_op = remove_cast_to_int(eq_left_op);
610  }
611  if (!eq_left_op) {
612  eq_left_op = tautological_eq->get_left_operand();
613  }
614  if (eq_left_op->get_type_info().is_geometry()) {
615  // skip cast for a geospatial lhs, since the rhs is likely to be a geospatial
616  // physical col without geospatial type info
617  return nullptr;
618  }
619  if (is_constructed_point(eq_left_op)) {
620  // skip cast for a constructed point lhs
621  return nullptr;
622  }
623  auto eq_left_op_col = dynamic_cast<const Analyzer::ColumnVar*>(eq_left_op);
624  if (!eq_left_op_col) {
625  if (dynamic_cast<const Analyzer::StringOper*>(eq_left_op)) {
626  return nullptr;
627  }
628  if (dynamic_cast<const Analyzer::FunctionOper*>(eq_left_op)) {
629  return nullptr;
630  }
631  }
632  CHECK(eq_left_op_col);
633  if (eq_left_op_col->get_rte_idx() != 0) {
634  return nullptr;
635  }
636  if (rhs->get_type_info().is_string()) {
637  return eq_left_op->deep_copy();
638  }
639  if (rhs->get_type_info().is_array()) {
640  // Note(jclay): Can this be restored from copy as above?
641  // If we fall through to the below return statement,
642  // a superfulous cast from DOUBLE[] to DOUBLE[] is made and
643  // this fails at a later stage in codegen.
644  return nullptr;
645  }
646  return makeExpr<Analyzer::UOper>(
647  rhs->get_type_info(), false, kCAST, eq_left_op->deep_copy());
648  }
649  }
650  }
651  return nullptr;
652 }
653 
655  for (const auto& tautological_eq : plan_state_->join_info_.equi_join_tautologies_) {
656  CHECK(IS_EQUIVALENCE(tautological_eq->get_optype()));
657  if (dynamic_cast<const Analyzer::ExpressionTuple*>(
658  tautological_eq->get_left_operand())) {
659  auto lhs_col = hashJoinLhsTuple(rhs, tautological_eq.get());
660  if (lhs_col) {
661  // our join column normalizer falls back to the loop join
662  // when columns of two join tables do not have the same types
663  // todo (yoonmin): relax this
664  return false;
665  }
666  } else {
667  auto eq_right_op = tautological_eq->get_right_operand();
668  if (!rhs->get_type_info().is_string()) {
669  eq_right_op = remove_cast_to_int(eq_right_op);
670  }
671  if (!eq_right_op) {
672  eq_right_op = tautological_eq->get_right_operand();
673  }
674  if (*eq_right_op == *rhs) {
675  auto eq_left_op = tautological_eq->get_left_operand();
676  if (!eq_left_op->get_type_info().is_string()) {
677  eq_left_op = remove_cast_to_int(eq_left_op);
678  }
679  if (!eq_left_op) {
680  eq_left_op = tautological_eq->get_left_operand();
681  }
682  if (eq_left_op->get_type_info().is_geometry()) {
683  // skip cast for a geospatial lhs, since the rhs is likely to be a geospatial
684  // physical col without geospatial type info
685  return false;
686  }
687  if (is_constructed_point(eq_left_op)) {
688  // skip cast for a constructed point lhs
689  return false;
690  }
691  auto eq_left_op_col = dynamic_cast<const Analyzer::ColumnVar*>(eq_left_op);
692  if (!eq_left_op_col) {
693  if (dynamic_cast<const Analyzer::StringOper*>(eq_left_op)) {
694  return false;
695  }
696  if (dynamic_cast<const Analyzer::FunctionOper*>(eq_left_op)) {
697  return false;
698  }
699  }
700  CHECK(eq_left_op_col);
701  if (eq_left_op_col->get_rte_idx() != 0) {
702  return false;
703  }
704  if (rhs->get_type_info().is_string()) {
705  return false;
706  }
707  if (rhs->get_type_info().is_array()) {
708  return false;
709  }
710  return true;
711  }
712  }
713  }
714  return false;
715 }
716 
717 std::shared_ptr<const Analyzer::ColumnVar> CodeGenerator::hashJoinLhsTuple(
718  const Analyzer::ColumnVar* rhs,
719  const Analyzer::BinOper* tautological_eq) const {
720  const auto lhs_tuple_expr =
721  dynamic_cast<const Analyzer::ExpressionTuple*>(tautological_eq->get_left_operand());
722  const auto rhs_tuple_expr = dynamic_cast<const Analyzer::ExpressionTuple*>(
723  tautological_eq->get_right_operand());
724  CHECK(lhs_tuple_expr && rhs_tuple_expr);
725  const auto& lhs_tuple = lhs_tuple_expr->getTuple();
726  const auto& rhs_tuple = rhs_tuple_expr->getTuple();
727  CHECK_EQ(lhs_tuple.size(), rhs_tuple.size());
728  for (size_t i = 0; i < lhs_tuple.size(); ++i) {
729  if (*rhs_tuple[i] == *rhs) {
730  const auto lhs_col =
731  std::static_pointer_cast<const Analyzer::ColumnVar>(lhs_tuple[i]);
732  return lhs_col->get_rte_idx() == 0 ? lhs_col : nullptr;
733  }
734  }
735  return nullptr;
736 }
int get_table_id() const
Definition: Analyzer.h:201
bool hasRangeModeFraming() const
Definition: Analyzer.h:2440
JoinInfo join_info_
Definition: PlanState.h:66
HOST DEVICE SQLTypes get_subtype() const
Definition: sqltypes.h:405
#define CHECK_EQ(x, y)
Definition: Logger.h:230
std::vector< llvm::Value * > outer_join_match_found_per_level_
Definition: CgenState.h:452
HOST DEVICE int get_size() const
Definition: sqltypes.h:414
const Analyzer::Expr * remove_cast_to_int(const Analyzer::Expr *expr)
Definition: ColumnIR.cpp:576
std::unordered_map< size_t, std::vector< llvm::Value * > > fetch_cache_
Definition: CgenState.h:442
Definition: sqltypes.h:63
SQLTypes
Definition: sqltypes.h:52
#define IS_EQUIVALENCE(X)
Definition: sqldefs.h:68
CgenState * cgen_state_
llvm::Value * codegenRowId(const Analyzer::ColumnVar *col_var, const CompilationOptions &co)
Definition: ColumnIR.cpp:339
llvm::Value * codegenFixedLengthColVarInWindow(const Analyzer::ColumnVar *col_var, llvm::Value *col_byte_stream, llvm::Value *pos_arg, const WindowFunctionContext *window_function_context=nullptr)
Definition: ColumnIR.cpp:294
bool is_fp() const
Definition: sqltypes.h:604
HOST DEVICE int get_scale() const
Definition: sqltypes.h:409
llvm::Value * emitExternalCall(const std::string &fname, llvm::Type *ret_type, const std::vector< llvm::Value * > args, const std::vector< llvm::Attribute::AttrKind > &fnattrs={}, const bool has_struct_return=false)
Definition: CgenState.h:217
const Expr * get_right_operand() const
Definition: Analyzer.h:451
bool is_constructed_point(const Analyzer::Expr *expr)
Definition: Execute.h:1459
llvm::IRBuilder ir_builder_
Definition: CgenState.h:441
std::vector< llvm::Value * > codegenOuterJoinNullPlaceholder(const Analyzer::ColumnVar *col_var, const bool fetch_column, const CompilationOptions &co)
Definition: ColumnIR.cpp:452
const std::vector< SQLTypeInfo > & getOrderKeyColumnBufferTypes() const
llvm::Value * posArg(const Analyzer::Expr *) const
Definition: ColumnIR.cpp:550
std::set< std::pair< TableId, ColumnId > > columns_to_fetch_
Definition: PlanState.h:61
#define CHECK_GE(x, y)
Definition: Logger.h:235
llvm::Value * codgenAdjustFixedEncNull(llvm::Value *, const SQLTypeInfo &)
Definition: ColumnIR.cpp:396
Definition: sqldefs.h:48
const int8_t * output() const
llvm::Value * foundOuterJoinMatch(const size_t nesting_level) const
Definition: ColumnIR.cpp:445
virtual std::vector< llvm::Value * > codegenColumn(const Analyzer::ColumnVar *, const bool fetch_column, const CompilationOptions &)
Definition: ColumnIR.cpp:92
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:404
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
std::shared_ptr< Decoder > get_col_decoder(const Analyzer::ColumnVar *col_var)
Definition: ColumnIR.cpp:28
EncodingType get_compression() const
Definition: Analyzer.h:205
static WindowFunctionContext * getActiveWindowFunctionContext(Executor *executor)
std::string to_string(char const *&&v)
llvm::Function * row_func_
Definition: CgenState.h:431
std::set< std::pair< TableId, ColumnId > > columns_to_not_fetch_
Definition: PlanState.h:62
std::vector< llvm::Value * > group_by_expr_cache_
Definition: CgenState.h:448
std::shared_ptr< const Analyzer::Expr > hashJoinLhs(const Analyzer::ColumnVar *rhs) const
Definition: ColumnIR.cpp:588
llvm::Value * codegenWindowPosition(const WindowFunctionContext *window_func_context, llvm::Value *pos_arg)
Definition: ColumnIR.cpp:230
llvm::Module * module_
Definition: CgenState.h:430
int getLocalColumnId(const Analyzer::ColumnVar *col_var, const bool fetch_column)
Definition: PlanState.cpp:62
size_t get_bit_width(const SQLTypeInfo &ti)
llvm::LLVMContext & context_
Definition: CgenState.h:439
llvm::Function * current_func_
Definition: CgenState.h:433
llvm::Value * get_arg_by_name(llvm::Function *func, const std::string &name)
Definition: Execute.h:166
bool isLazyFetchColumn(const Analyzer::Expr *target_expr) const
Definition: PlanState.cpp:20
int get_logical_size() const
Definition: sqltypes.h:424
size_t get_col_bit_width(const Analyzer::ColumnVar *col_var)
Definition: ColumnIR.cpp:81
llvm::ConstantInt * inlineIntNull(const SQLTypeInfo &)
Definition: CgenState.cpp:64
std::string toString() const override
Definition: Analyzer.cpp:2585
int64_t bigintval
Definition: sqltypes.h:235
std::unordered_map< int, llvm::Value * > scan_idx_to_hash_pos_
Definition: CgenState.h:453
#define AUTOMATIC_IR_METADATA(CGENSTATE)
std::vector< llvm::Value * > codegenColVar(const Analyzer::ColumnVar *, const bool fetch_column, const bool update_query_plan, const CompilationOptions &)
Definition: ColumnIR.cpp:104
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:82
llvm::Value * emitCall(const std::string &fname, const std::vector< llvm::Value * > &args)
Definition: CgenState.cpp:219
SQLTypes decimal_to_int_type(const SQLTypeInfo &ti)
Definition: Datum.cpp:499
PlanState * plan_state_
std::vector< llvm::Value * > codegen(const Analyzer::Expr *, const bool fetch_columns, const CompilationOptions &)
Definition: IRCodegen.cpp:30
#define CHECK_LT(x, y)
Definition: Logger.h:232
Definition: sqltypes.h:67
#define CHECK_LE(x, y)
Definition: Logger.h:233
int get_comp_param() const
Definition: Analyzer.h:206
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:412
std::vector< llvm::Value * > frag_offsets_
Definition: CgenState.h:450
int get_rte_idx() const
Definition: Analyzer.h:203
HOST DEVICE int get_dimension() const
Definition: sqltypes.h:406
bool needCastForHashJoinLhs(const Analyzer::ColumnVar *rhs) const
Definition: ColumnIR.cpp:654
llvm::ConstantInt * llInt(const T v) const
Definition: CgenState.h:306
#define CHECK(condition)
Definition: Logger.h:222
bool is_geometry() const
Definition: sqltypes.h:612
llvm::Value * colByteStream(const Analyzer::ColumnVar *col_var, const bool fetch_column, const bool hoist_literals)
Definition: ColumnIR.cpp:534
const Expr * get_left_operand() const
Definition: Analyzer.h:450
const Analyzer::WindowFunction * getWindowFunction() const
std::string numeric_type_name(const SQLTypeInfo &ti)
Definition: Execute.h:209
Definition: sqltypes.h:59
SQLTypeInfo columnType
int get_column_id() const
Definition: Analyzer.h:202
bool is_string() const
Definition: sqltypes.h:600
std::shared_ptr< const Analyzer::ColumnVar > hashJoinLhsTuple(const Analyzer::ColumnVar *rhs, const Analyzer::BinOper *tautological_eq) const
Definition: ColumnIR.cpp:717
llvm::Value * codegenFixedLengthColVar(const Analyzer::ColumnVar *col_var, llvm::Value *col_byte_stream, llvm::Value *pos_arg, const WindowFunctionContext *window_function_context=nullptr)
Definition: ColumnIR.cpp:243
std::vector< llvm::Value * > codegenVariableLengthStringColVar(llvm::Value *col_byte_stream, llvm::Value *pos_arg)
Definition: ColumnIR.cpp:324
HOST DEVICE bool get_notnull() const
Definition: sqltypes.h:411
SQLTypes get_phys_int_type(const size_t byte_sz)
Definition: ColumnIR.cpp:377
int adjusted_range_table_index(const Analyzer::ColumnVar *col_var)
Definition: ColumnIR.cpp:86
bool is_array() const
Definition: sqltypes.h:608
const ColumnDescriptor * get_column_descriptor(const int col_id, const int table_id, const Catalog_Namespace::Catalog &cat)
Definition: Execute.h:191
llvm::Value * resolveGroupedColumnReference(const Analyzer::ColumnVar *)
Definition: ColumnIR.cpp:515
llvm::ConstantFP * inlineFpNull(const SQLTypeInfo &)
Definition: CgenState.cpp:106
Executor * executor() const