OmniSciDB  6686921089
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
DateTimeIR.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 
17 #include "CodeGenerator.h"
18 
19 #include "DateTimeUtils.h"
20 #include "Execute.h"
21 
22 using namespace DateTimeUtils;
23 
24 namespace {
25 
27  switch (field) {
28  case kEPOCH:
29  return "extract_epoch";
30  case kDATEEPOCH:
31  return "extract_dateepoch";
32  case kQUARTERDAY:
33  return "extract_quarterday";
34  case kHOUR:
35  return "extract_hour";
36  case kMINUTE:
37  return "extract_minute";
38  case kSECOND:
39  return "extract_second";
40  case kMILLISECOND:
41  return "extract_millisecond";
42  case kMICROSECOND:
43  return "extract_microsecond";
44  case kNANOSECOND:
45  return "extract_nanosecond";
46  case kDOW:
47  return "extract_dow";
48  case kISODOW:
49  return "extract_isodow";
50  case kDAY:
51  return "extract_day";
52  case kWEEK:
53  return "extract_week_monday";
54  case kWEEK_SUNDAY:
55  return "extract_week_sunday";
56  case kWEEK_SATURDAY:
57  return "extract_week_saturday";
58  case kDOY:
59  return "extract_day_of_year";
60  case kMONTH:
61  return "extract_month";
62  case kQUARTER:
63  return "extract_quarter";
64  case kYEAR:
65  return "extract_year";
66  }
67  UNREACHABLE();
68  return "";
69 }
70 
71 } // namespace
72 
73 llvm::Value* CodeGenerator::codegen(const Analyzer::ExtractExpr* extract_expr,
74  const CompilationOptions& co) {
75  AUTOMATIC_IR_METADATA(cgen_state_);
76  auto from_expr = codegen(extract_expr->get_from_expr(), true, co).front();
77  const int32_t extract_field{extract_expr->get_field()};
78  const auto& extract_expr_ti = extract_expr->get_from_expr()->get_type_info();
79  if (extract_field == kEPOCH) {
80  CHECK(extract_expr_ti.get_type() == kTIMESTAMP ||
81  extract_expr_ti.get_type() == kDATE);
82  if (from_expr->getType()->isIntegerTy(32)) {
83  from_expr =
84  cgen_state_->ir_builder_.CreateCast(llvm::Instruction::CastOps::SExt,
85  from_expr,
86  get_int_type(64, cgen_state_->context_));
87  return from_expr;
88  }
89  }
90  CHECK(from_expr->getType()->isIntegerTy(64));
91  if (extract_expr_ti.is_high_precision_timestamp()) {
92  from_expr = codegenExtractHighPrecisionTimestamps(
93  from_expr, extract_expr_ti, extract_expr->get_field());
94  }
95  if (!extract_expr_ti.is_high_precision_timestamp() &&
96  is_subsecond_extract_field(extract_expr->get_field())) {
97  from_expr =
98  extract_expr_ti.get_notnull()
99  ? cgen_state_->ir_builder_.CreateMul(
100  from_expr,
101  cgen_state_->llInt(
103  : cgen_state_->emitCall(
104  "mul_int64_t_nullable_lhs",
105  {from_expr,
106  cgen_state_->llInt(
108  cgen_state_->inlineIntNull(extract_expr_ti)});
109  }
110  const auto extract_fname = get_extract_function_name(extract_expr->get_field());
111  if (!extract_expr_ti.get_notnull()) {
112  llvm::BasicBlock* extract_nullcheck_bb{nullptr};
113  llvm::PHINode* extract_nullcheck_value{nullptr};
114  {
115  DiamondCodegen null_check(cgen_state_->ir_builder_.CreateICmp(
116  llvm::ICmpInst::ICMP_EQ,
117  from_expr,
118  cgen_state_->inlineIntNull(extract_expr_ti)),
119  executor(),
120  false,
121  "extract_nullcheck",
122  nullptr,
123  false);
124  // generate a phi node depending on whether we got a null or not
125  extract_nullcheck_bb = llvm::BasicBlock::Create(
126  cgen_state_->context_, "extract_nullcheck_bb", cgen_state_->current_func_);
127 
128  // update the blocks created by diamond codegen to point to the newly created phi
129  // block
130  cgen_state_->ir_builder_.SetInsertPoint(null_check.cond_true_);
131  cgen_state_->ir_builder_.CreateBr(extract_nullcheck_bb);
132  cgen_state_->ir_builder_.SetInsertPoint(null_check.cond_false_);
133  auto extract_call =
134  cgen_state_->emitExternalCall(extract_fname,
135  get_int_type(64, cgen_state_->context_),
136  std::vector<llvm::Value*>{from_expr});
137  cgen_state_->ir_builder_.CreateBr(extract_nullcheck_bb);
138 
139  cgen_state_->ir_builder_.SetInsertPoint(extract_nullcheck_bb);
140  extract_nullcheck_value = cgen_state_->ir_builder_.CreatePHI(
141  get_int_type(64, cgen_state_->context_), 2, "extract_value");
142  extract_nullcheck_value->addIncoming(extract_call, null_check.cond_false_);
143  extract_nullcheck_value->addIncoming(cgen_state_->inlineIntNull(extract_expr_ti),
144  null_check.cond_true_);
145  }
146 
147  // diamond codegen will set the insert point in its destructor. override it to
148  // continue using the extract nullcheck bb
149  CHECK(extract_nullcheck_bb);
150  cgen_state_->ir_builder_.SetInsertPoint(extract_nullcheck_bb);
151  CHECK(extract_nullcheck_value);
152  return extract_nullcheck_value;
153  } else {
154  return cgen_state_->emitExternalCall(extract_fname,
155  get_int_type(64, cgen_state_->context_),
156  std::vector<llvm::Value*>{from_expr});
157  }
158 }
159 
160 llvm::Value* CodeGenerator::codegen(const Analyzer::DateaddExpr* dateadd_expr,
161  const CompilationOptions& co) {
163  const auto& dateadd_expr_ti = dateadd_expr->get_type_info();
164  CHECK(dateadd_expr_ti.get_type() == kTIMESTAMP || dateadd_expr_ti.get_type() == kDATE);
165  auto datetime = codegen(dateadd_expr->get_datetime_expr(), true, co).front();
166  CHECK(datetime->getType()->isIntegerTy(64));
167  auto number = codegen(dateadd_expr->get_number_expr(), true, co).front();
168 
169  const auto& datetime_ti = dateadd_expr->get_datetime_expr()->get_type_info();
170  std::vector<llvm::Value*> dateadd_args{
171  cgen_state_->llInt(static_cast<int32_t>(dateadd_expr->get_field())),
172  number,
173  datetime};
174  std::string dateadd_fname{"DateAdd"};
175  if (is_subsecond_dateadd_field(dateadd_expr->get_field()) ||
176  dateadd_expr_ti.is_high_precision_timestamp()) {
177  dateadd_fname += "HighPrecision";
178  dateadd_args.push_back(
179  cgen_state_->llInt(static_cast<int32_t>(datetime_ti.get_dimension())));
180  }
181  if (!datetime_ti.get_notnull()) {
182  dateadd_args.push_back(cgen_state_->inlineIntNull(datetime_ti));
183  dateadd_fname += "Nullable";
184  }
185  return cgen_state_->emitExternalCall(dateadd_fname,
187  dateadd_args,
188  {llvm::Attribute::NoUnwind,
189  llvm::Attribute::ReadNone,
190  llvm::Attribute::Speculatable});
191 }
192 
193 llvm::Value* CodeGenerator::codegen(const Analyzer::DatediffExpr* datediff_expr,
194  const CompilationOptions& co) {
196  auto start = codegen(datediff_expr->get_start_expr(), true, co).front();
197  CHECK(start->getType()->isIntegerTy(64));
198  auto end = codegen(datediff_expr->get_end_expr(), true, co).front();
199  CHECK(end->getType()->isIntegerTy(32) || end->getType()->isIntegerTy(64));
200  const auto& start_ti = datediff_expr->get_start_expr()->get_type_info();
201  const auto& end_ti = datediff_expr->get_end_expr()->get_type_info();
202  std::vector<llvm::Value*> datediff_args{
203  cgen_state_->llInt(static_cast<int32_t>(datediff_expr->get_field())), start, end};
204  std::string datediff_fname{"DateDiff"};
205  if (start_ti.is_high_precision_timestamp() || end_ti.is_high_precision_timestamp()) {
206  datediff_fname += "HighPrecision";
207  datediff_args.push_back(
208  cgen_state_->llInt(static_cast<int32_t>(start_ti.get_dimension())));
209  datediff_args.push_back(
210  cgen_state_->llInt(static_cast<int32_t>(end_ti.get_dimension())));
211  }
212  const auto& ret_ti = datediff_expr->get_type_info();
213  if (!start_ti.get_notnull() || !end_ti.get_notnull()) {
214  datediff_args.push_back(cgen_state_->inlineIntNull(ret_ti));
215  datediff_fname += "Nullable";
216  }
218  datediff_fname, get_int_type(64, cgen_state_->context_), datediff_args);
219 }
220 
221 llvm::Value* CodeGenerator::codegen(const Analyzer::DatetruncExpr* datetrunc_expr,
222  const CompilationOptions& co) {
224  auto from_expr = codegen(datetrunc_expr->get_from_expr(), true, co).front();
225  const auto& datetrunc_expr_ti = datetrunc_expr->get_from_expr()->get_type_info();
226  CHECK(from_expr->getType()->isIntegerTy(64));
227  DatetruncField const field = datetrunc_expr->get_field();
228  if (datetrunc_expr_ti.is_high_precision_timestamp()) {
229  return codegenDateTruncHighPrecisionTimestamps(from_expr, datetrunc_expr_ti, field);
230  }
231  static_assert(dtSECOND + 1 == dtMILLISECOND, "Please keep these consecutive.");
232  static_assert(dtMILLISECOND + 1 == dtMICROSECOND, "Please keep these consecutive.");
233  static_assert(dtMICROSECOND + 1 == dtNANOSECOND, "Please keep these consecutive.");
234  if (dtSECOND <= field && field <= dtNANOSECOND) {
235  return cgen_state_->ir_builder_.CreateCast(llvm::Instruction::CastOps::SExt,
236  from_expr,
238  }
239  std::unique_ptr<CodeGenerator::NullCheckCodegen> nullcheck_codegen;
240  const bool is_nullable = !datetrunc_expr_ti.get_notnull();
241  if (is_nullable) {
242  nullcheck_codegen = std::make_unique<NullCheckCodegen>(
243  cgen_state_, executor(), from_expr, datetrunc_expr_ti, "date_trunc_nullcheck");
244  }
245  char const* const fname = datetrunc_fname_lookup.at(field);
246  auto ret = cgen_state_->emitExternalCall(
247  fname, get_int_type(64, cgen_state_->context_), {from_expr});
248  if (is_nullable) {
249  ret = nullcheck_codegen->finalize(ll_int(NULL_BIGINT, cgen_state_->context_), ret);
250  }
251  return ret;
252 }
253 
255  llvm::Value* ts_lv,
256  const SQLTypeInfo& ti,
257  const ExtractField& field) {
260  CHECK(ts_lv->getType()->isIntegerTy(64));
261  if (is_subsecond_extract_field(field)) {
262  const auto result =
264  if (result.first == kMULTIPLY) {
265  return ti.get_notnull()
266  ? cgen_state_->ir_builder_.CreateMul(
267  ts_lv, cgen_state_->llInt(static_cast<int64_t>(result.second)))
269  "mul_int64_t_nullable_lhs",
270  {ts_lv,
271  cgen_state_->llInt(static_cast<int64_t>(result.second)),
272  cgen_state_->inlineIntNull(ti)});
273  } else if (result.first == kDIVIDE) {
274  return ti.get_notnull()
275  ? cgen_state_->ir_builder_.CreateSDiv(
276  ts_lv, cgen_state_->llInt(static_cast<int64_t>(result.second)))
278  "floor_div_nullable_lhs",
279  {ts_lv,
280  cgen_state_->llInt(static_cast<int64_t>(result.second)),
281  cgen_state_->inlineIntNull(ti)});
282  } else {
283  return ts_lv;
284  }
285  }
286  return ti.get_notnull()
287  ? cgen_state_->ir_builder_.CreateSDiv(
288  ts_lv,
289  cgen_state_->llInt(static_cast<int64_t>(
290  get_timestamp_precision_scale(ti.get_dimension()))))
291  : cgen_state_->emitCall(
292  "floor_div_nullable_lhs",
293  {ts_lv,
294  cgen_state_->llInt(get_timestamp_precision_scale(ti.get_dimension())),
295  cgen_state_->inlineIntNull(ti)});
296 }
297 
299  llvm::Value* ts_lv,
300  const SQLTypeInfo& ti,
301  const DatetruncField& field) {
302  // Only needed for i in { 0, 3, 6, 9 }.
303  constexpr int64_t pow10[10]{1, 0, 0, 1000, 0, 0, 1000000, 0, 0, 1000000000};
306  CHECK(ts_lv->getType()->isIntegerTy(64));
307  bool const is_nullable = !ti.get_notnull();
308  static_assert(dtSECOND + 1 == dtMILLISECOND, "Please keep these consecutive.");
309  static_assert(dtMILLISECOND + 1 == dtMICROSECOND, "Please keep these consecutive.");
310  static_assert(dtMICROSECOND + 1 == dtNANOSECOND, "Please keep these consecutive.");
311  if (dtSECOND <= field && field <= dtNANOSECOND) {
312  unsigned const start_dim = ti.get_dimension(); // 0, 3, 6, 9
313  unsigned const trunc_dim = (field - dtSECOND) * 3; // 0, 3, 6, 9
314  if (start_dim <= trunc_dim) {
315  return ts_lv; // Truncating to an equal or higher precision has no effect.
316  }
317  int64_t const dscale = pow10[start_dim - trunc_dim]; // 1e3, 1e6, 1e9
318  if (is_nullable) {
319  ts_lv = cgen_state_->emitCall(
320  "floor_div_nullable_lhs",
321  {ts_lv, cgen_state_->llInt(dscale), cgen_state_->inlineIntNull(ti)});
322  return cgen_state_->emitCall(
323  "mul_int64_t_nullable_lhs",
324  {ts_lv, cgen_state_->llInt(dscale), cgen_state_->inlineIntNull(ti)});
325  } else {
326  ts_lv = cgen_state_->ir_builder_.CreateSDiv(ts_lv, cgen_state_->llInt(dscale));
327  return cgen_state_->ir_builder_.CreateMul(ts_lv, cgen_state_->llInt(dscale));
328  }
329  }
330  int64_t const scale = pow10[ti.get_dimension()];
331  ts_lv = is_nullable
333  "floor_div_nullable_lhs",
334  {ts_lv, cgen_state_->llInt(scale), cgen_state_->inlineIntNull(ti)})
335  : cgen_state_->ir_builder_.CreateSDiv(ts_lv, cgen_state_->llInt(scale));
336 
337  std::unique_ptr<CodeGenerator::NullCheckCodegen> nullcheck_codegen;
338  if (is_nullable) {
339  nullcheck_codegen = std::make_unique<NullCheckCodegen>(
340  cgen_state_, executor(), ts_lv, ti, "date_trunc_hp_nullcheck");
341  }
342  char const* const fname = datetrunc_fname_lookup.at(field);
343  ts_lv = cgen_state_->emitExternalCall(
344  fname, get_int_type(64, cgen_state_->context_), {ts_lv});
345  if (is_nullable) {
346  ts_lv =
347  nullcheck_codegen->finalize(ll_int(NULL_BIGINT, cgen_state_->context_), ts_lv);
348  }
349 
350  return is_nullable
351  ? cgen_state_->emitCall(
352  "mul_int64_t_nullable_lhs",
353  {ts_lv, cgen_state_->llInt(scale), cgen_state_->inlineIntNull(ti)})
354  : cgen_state_->ir_builder_.CreateMul(ts_lv, cgen_state_->llInt(scale));
355 }
const Expr * get_from_expr() const
Definition: Analyzer.h:1352
constexpr int64_t get_extract_timestamp_precision_scale(const ExtractField field)
Definition: DateTimeUtils.h:81
CgenState * cgen_state_
#define NULL_BIGINT
ExtractField get_field() const
Definition: Analyzer.h:1351
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:228
llvm::ConstantInt * ll_int(const T v, llvm::LLVMContext &context)
llvm::IRBuilder ir_builder_
Definition: CgenState.h:340
const char * get_extract_function_name(ExtractField field)
Definition: DateTimeIR.cpp:26
#define UNREACHABLE()
Definition: Logger.h:253
llvm::Value * codegenExtractHighPrecisionTimestamps(llvm::Value *, const SQLTypeInfo &, const ExtractField &)
Definition: DateTimeIR.cpp:254
DatetruncField get_field() const
Definition: Analyzer.h:1476
const std::pair< SQLOps, int64_t > get_extract_high_precision_adjusted_scale(const ExtractField &field, const int32_t dimen)
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
llvm::LLVMContext & context_
Definition: CgenState.h:338
DatetruncField
Definition: DateTruncate.h:27
llvm::ConstantInt * inlineIntNull(const SQLTypeInfo &)
Definition: CgenState.cpp:29
#define AUTOMATIC_IR_METADATA(CGENSTATE)
const Expr * get_start_expr() const
Definition: Analyzer.h:1435
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:77
llvm::Value * emitCall(const std::string &fname, const std::vector< llvm::Value * > &args)
Definition: CgenState.cpp:175
std::vector< llvm::Value * > codegen(const Analyzer::Expr *, const bool fetch_columns, const CompilationOptions &)
Definition: IRCodegen.cpp:30
Definition: sqltypes.h:53
constexpr std::array< char const *, dtINVALID > datetrunc_fname_lookup
Definition: DateTruncate.h:49
const Expr * get_from_expr() const
Definition: Analyzer.h:1477
const Expr * get_datetime_expr() const
Definition: Analyzer.h:1394
HOST DEVICE int get_dimension() const
Definition: sqltypes.h:331
ExtractField
DateaddField get_field() const
Definition: Analyzer.h:1392
constexpr bool is_subsecond_dateadd_field(const DateaddField field)
Definition: DateTimeUtils.h:99
llvm::ConstantInt * llInt(const T v) const
Definition: CgenState.h:307
const Expr * get_end_expr() const
Definition: Analyzer.h:1436
#define CHECK(condition)
Definition: Logger.h:209
constexpr int64_t get_timestamp_precision_scale(const int32_t dimen)
Definition: DateTimeUtils.h:51
bool is_high_precision_timestamp() const
Definition: sqltypes.h:870
llvm::Value * codegenDateTruncHighPrecisionTimestamps(llvm::Value *, const SQLTypeInfo &, const DatetruncField &)
Definition: DateTimeIR.cpp:298
HOST DEVICE bool get_notnull() const
Definition: sqltypes.h:336
DatetruncField get_field() const
Definition: Analyzer.h:1434
constexpr bool is_subsecond_extract_field(const ExtractField &field)
Definition: DateTimeUtils.h:95
const Expr * get_number_expr() const
Definition: Analyzer.h:1393
Executor * executor() const