OmniSciDB  a5dc49c757
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
NativeCodegen.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 "QueryEngine/Execute.h"
18 
19 #if LLVM_VERSION_MAJOR < 9
20 static_assert(false, "LLVM Version >= 9 is required.");
21 #endif
22 
23 #include <llvm/Analysis/ScopedNoAliasAA.h>
24 #include <llvm/Analysis/TypeBasedAliasAnalysis.h>
25 #include <llvm/Bitcode/BitcodeReader.h>
26 #include <llvm/Bitcode/BitcodeWriter.h>
27 #include <llvm/ExecutionEngine/MCJIT.h>
28 #include <llvm/IR/Attributes.h>
29 #include <llvm/IR/GlobalValue.h>
30 #include <llvm/IR/InstIterator.h>
31 #include <llvm/IR/IntrinsicInst.h>
32 #include <llvm/IR/Intrinsics.h>
33 #include <llvm/IR/LegacyPassManager.h>
34 #include <llvm/IR/Verifier.h>
35 #include <llvm/IRReader/IRReader.h>
36 #if 14 <= LLVM_VERSION_MAJOR
37 #include <llvm/MC/TargetRegistry.h>
38 #else
39 #include <llvm/Support/TargetRegistry.h>
40 #endif
41 #include <llvm/Support/Casting.h>
42 #include <llvm/Support/FileSystem.h>
43 #include <llvm/Support/FormattedStream.h>
44 #include <llvm/Support/MemoryBuffer.h>
45 #include <llvm/Support/SourceMgr.h>
46 #include <llvm/Support/TargetSelect.h>
47 #include <llvm/Support/raw_os_ostream.h>
48 #include <llvm/Support/raw_ostream.h>
49 #include <llvm/Transforms/IPO.h>
50 #include <llvm/Transforms/IPO/AlwaysInliner.h>
51 #include <llvm/Transforms/IPO/InferFunctionAttrs.h>
52 #include <llvm/Transforms/IPO/PassManagerBuilder.h>
53 #include <llvm/Transforms/InstCombine/InstCombine.h>
54 #include <llvm/Transforms/Instrumentation.h>
55 #include <llvm/Transforms/Scalar.h>
56 #include <llvm/Transforms/Scalar/GVN.h>
57 #include <llvm/Transforms/Scalar/InstSimplifyPass.h>
58 #include <llvm/Transforms/Utils.h>
59 #include <llvm/Transforms/Utils/BasicBlockUtils.h>
60 #include <llvm/Transforms/Utils/Cloning.h>
61 
62 #if LLVM_VERSION_MAJOR >= 11
63 #include <llvm/Support/Host.h>
64 #endif
65 
66 #include "CudaMgr/CudaMgr.h"
78 #include "Shared/MathUtils.h"
79 #include "StreamingTopN.h"
80 
81 using heavyai::ErrorCode;
82 
84 
85 #ifdef ENABLE_GEOS
86 
87 #include <llvm/Support/DynamicLibrary.h>
88 
89 // from Geospatial/GeosValidation.cpp
90 extern std::unique_ptr<std::string> g_libgeos_so_filename;
91 
92 static llvm::sys::DynamicLibrary geos_dynamic_library;
93 static std::mutex geos_init_mutex;
94 
95 namespace {
96 
97 void load_geos_dynamic_library() {
98  std::lock_guard<std::mutex> guard(geos_init_mutex);
99 
100  if (!geos_dynamic_library.isValid()) {
101  if (!g_libgeos_so_filename || g_libgeos_so_filename->empty()) {
102  LOG(WARNING) << "Misconfigured GEOS library file name, trying 'libgeos_c.so'";
103  g_libgeos_so_filename.reset(new std::string("libgeos_c.so"));
104  }
105  auto filename = *g_libgeos_so_filename;
106  std::string error_message;
107  geos_dynamic_library =
108  llvm::sys::DynamicLibrary::getPermanentLibrary(filename.c_str(), &error_message);
109  if (!geos_dynamic_library.isValid()) {
110  LOG(ERROR) << "Failed to load GEOS library '" + filename + "'";
111  std::string exception_message = "Failed to load GEOS library: " + error_message;
112  throw std::runtime_error(exception_message);
113  } else {
114  LOG(INFO) << "Loaded GEOS library '" + filename + "'";
115  }
116  }
117 }
118 
119 } // namespace
120 #endif
121 
122 namespace {
123 
124 void throw_parseIR_error(const llvm::SMDiagnostic& parse_error,
125  std::string src = "",
126  const bool is_gpu = false) {
127  std::string excname = (is_gpu ? "NVVM IR ParseError: " : "LLVM IR ParseError: ");
128  llvm::raw_string_ostream ss(excname);
129  parse_error.print(src.c_str(), ss, false, false);
130  throw ParseIRError(ss.str());
131 }
132 
133 /* SHOW_DEFINED(<llvm::Module instance>) prints the function names
134  that are defined in the given LLVM Module instance.
135 
136  SHOW_FUNCTIONS(<llvm::Module instance>) prints the function names
137  of all used functions in the given LLVM Module
138  instance. Declarations are marked with `[decl]` as a name suffix.
139 
140  Useful for debugging.
141 */
142 
143 #define SHOW_DEFINED(MODULE) \
144  { \
145  std::cout << __func__ << "#" << __LINE__ << ": " #MODULE << " "; \
146  ::show_defined(MODULE); \
147  }
148 
149 #define SHOW_FUNCTIONS(MODULE) \
150  { \
151  std::cout << __func__ << "#" << __LINE__ << ": " #MODULE << " "; \
152  ::show_functions(MODULE); \
153  }
154 
155 template <typename T = void>
156 void show_defined(llvm::Module& llvm_module) {
157  std::cout << "defines: ";
158  for (auto& f : llvm_module.getFunctionList()) {
159  if (!f.isDeclaration()) {
160  std::cout << f.getName().str() << ", ";
161  }
162  }
163  std::cout << std::endl;
164 }
165 
166 template <typename T = void>
167 void show_defined(llvm::Module* llvm_module) {
168  if (llvm_module == nullptr) {
169  std::cout << "is null" << std::endl;
170  } else {
171  show_defined(*llvm_module);
172  }
173 }
174 
175 template <typename T = void>
176 void show_defined(std::unique_ptr<llvm::Module>& llvm_module) {
177  show_defined(llvm_module.get());
178 }
179 
180 /*
181  scan_function_calls(module, defined, undefined, ignored) computes
182  defined and undefined sets of function names:
183 
184  - defined functions are those that are defined in the given module
185 
186  - undefined functions are those that are called by defined functions
187  but that are not defined in the given module
188 
189  - ignored functions are functions that may be undefined but will not
190  be listed in the set of undefined functions.
191 
192  Useful for debugging.
193 */
194 template <typename T = void>
195 void scan_function_calls(llvm::Function& F,
196  std::unordered_set<std::string>& defined,
197  std::unordered_set<std::string>& undefined,
198  const std::unordered_set<std::string>& ignored) {
199  for (llvm::inst_iterator I = llvm::inst_begin(F), E = llvm::inst_end(F); I != E; ++I) {
200  if (auto* CI = llvm::dyn_cast<llvm::CallInst>(&*I)) {
201  auto* F2 = CI->getCalledFunction();
202  if (F2 != nullptr) {
203  auto F2name = F2->getName().str();
204  if (F2->isDeclaration()) {
205  if (F2name.rfind("__", 0) !=
206  0 // assume symbols with double underscore are defined
207  && F2name.rfind("llvm.", 0) !=
208  0 // TODO: this may give false positive for NVVM intrinsics
209  && ignored.find(F2name) == ignored.end() // not in ignored list
210  ) {
211  undefined.emplace(F2name);
212  }
213  } else {
214  if (defined.find(F2name) == defined.end()) {
215  defined.emplace(F2name);
216  scan_function_calls<T>(*F2, defined, undefined, ignored);
217  }
218  }
219  }
220  }
221  }
222 }
223 
224 template <typename T = void>
225 void scan_function_calls(llvm::Module& llvm_module,
226  std::unordered_set<std::string>& defined,
227  std::unordered_set<std::string>& undefined,
228  const std::unordered_set<std::string>& ignored) {
229  for (auto& F : llvm_module) {
230  if (!F.isDeclaration()) {
231  scan_function_calls(F, defined, undefined, ignored);
232  }
233  }
234 }
235 
236 template <typename T = void>
237 std::tuple<std::unordered_set<std::string>, std::unordered_set<std::string>>
238 scan_function_calls(llvm::Module& llvm_module,
239  const std::unordered_set<std::string>& ignored = {}) {
240  std::unordered_set<std::string> defined, undefined;
241  scan_function_calls(llvm_module, defined, undefined, ignored);
242  return std::make_tuple(defined, undefined);
243 }
244 
245 #if defined(HAVE_CUDA) || !defined(WITH_JIT_DEBUG)
247  llvm::Module& M,
248  const std::unordered_set<llvm::Function*>& live_funcs) {
249  std::vector<llvm::Function*> dead_funcs;
250  for (auto& F : M) {
251  bool bAlive = false;
252  if (live_funcs.count(&F)) {
253  continue;
254  }
255  for (auto U : F.users()) {
256  auto* C = llvm::dyn_cast<const llvm::CallInst>(U);
257  if (!C || C->getParent()->getParent() != &F) {
258  bAlive = true;
259  break;
260  }
261  }
262  if (!bAlive) {
263  dead_funcs.push_back(&F);
264  }
265  }
266  for (auto pFn : dead_funcs) {
267  pFn->eraseFromParent();
268  }
269 }
270 
271 #ifdef HAVE_CUDA
272 
273 // check if linking with libdevice is required
274 // libdevice functions have a __nv_* prefix
275 bool check_module_requires_libdevice(llvm::Module* llvm_module) {
276  auto timer = DEBUG_TIMER(__func__);
277  for (llvm::Function& F : *llvm_module) {
278  if (F.hasName() && F.getName().startswith("__nv_")) {
279  LOG(INFO) << "Module requires linking with libdevice: " << std::string(F.getName());
280  return true;
281  }
282  }
283  LOG(DEBUG1) << "module does not require linking against libdevice";
284  return false;
285 }
286 
287 // Adds the missing intrinsics declarations to the given module
288 void add_intrinsics_to_module(llvm::Module* llvm_module) {
289  for (llvm::Function& F : *llvm_module) {
290  for (llvm::Instruction& I : instructions(F)) {
291  if (llvm::IntrinsicInst* ii = llvm::dyn_cast<llvm::IntrinsicInst>(&I)) {
292  if (llvm::Intrinsic::isOverloaded(ii->getIntrinsicID())) {
293  llvm::Type* Tys[] = {ii->getFunctionType()->getReturnType()};
294  llvm::Function& decl_fn =
295  *llvm::Intrinsic::getDeclaration(llvm_module, ii->getIntrinsicID(), Tys);
296  ii->setCalledFunction(&decl_fn);
297  } else {
298  // inserts the declaration into the module if not present
299  llvm::Intrinsic::getDeclaration(llvm_module, ii->getIntrinsicID());
300  }
301  }
302  }
303  }
304 }
305 
306 #endif
307 
308 void optimize_ir(llvm::Function* query_func,
309  llvm::Module* llvm_module,
310  llvm::legacy::PassManager& pass_manager,
311  const std::unordered_set<llvm::Function*>& live_funcs,
312  const bool is_gpu_smem_used,
313  const CompilationOptions& co) {
314  auto timer = DEBUG_TIMER(__func__);
315  // the always inliner legacy pass must always run first
316  pass_manager.add(llvm::createVerifierPass());
317  pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
318 
319  pass_manager.add(new AnnotateInternalFunctionsPass());
320 
321  pass_manager.add(llvm::createSROAPass());
322  // mem ssa drops unused load and store instructions, e.g. passing variables directly
323  // where possible
324  pass_manager.add(
325  llvm::createEarlyCSEPass(/*enable_mem_ssa=*/true)); // Catch trivial redundancies
326 
327  if (!is_gpu_smem_used) {
328  // thread jumps can change the execution order around SMEM sections guarded by
329  // `__syncthreads()`, which results in race conditions. For now, disable jump
330  // threading for shared memory queries. In the future, consider handling shared
331  // memory aggregations with a separate kernel launch
332  pass_manager.add(llvm::createJumpThreadingPass()); // Thread jumps.
333  }
334  pass_manager.add(llvm::createCFGSimplificationPass());
335 
336  // remove load/stores in PHIs if instructions can be accessed directly post thread jumps
337  pass_manager.add(llvm::createNewGVNPass());
338 
339  pass_manager.add(llvm::createDeadStoreEliminationPass());
340  pass_manager.add(llvm::createLICMPass());
341 
342  pass_manager.add(llvm::createInstructionCombiningPass());
343 
344  // module passes
345  pass_manager.add(llvm::createPromoteMemoryToRegisterPass());
346  pass_manager.add(llvm::createGlobalOptimizerPass());
347 
348  pass_manager.add(llvm::createCFGSimplificationPass()); // cleanup after everything
349 
350  pass_manager.run(*llvm_module);
351 
352  eliminate_dead_self_recursive_funcs(*llvm_module, live_funcs);
353 }
354 #endif
355 
356 } // namespace
357 
359 
360 ExecutionEngineWrapper::ExecutionEngineWrapper(llvm::ExecutionEngine* execution_engine)
361  : execution_engine_(execution_engine) {}
362 
363 ExecutionEngineWrapper::ExecutionEngineWrapper(llvm::ExecutionEngine* execution_engine,
364  const CompilationOptions& co)
365  : execution_engine_(execution_engine) {
366  if (execution_engine_) {
368 #ifdef ENABLE_INTEL_JIT_LISTENER
369  intel_jit_listener_.reset(llvm::JITEventListener::createIntelJITEventListener());
371  execution_engine_->RegisterJITEventListener(intel_jit_listener_.get());
372  LOG(INFO) << "Registered IntelJITEventListener";
373 #else
374  LOG(WARNING) << "This build is not Intel JIT Listener enabled. Ignoring Intel JIT "
375  "listener configuration parameter.";
376 #endif // ENABLE_INTEL_JIT_LISTENER
377  }
378  }
379 }
380 
382  llvm::ExecutionEngine* execution_engine) {
383  execution_engine_.reset(execution_engine);
384  intel_jit_listener_ = nullptr;
385  return *this;
386 }
387 
388 void verify_function_ir(const llvm::Function* func) {
389  std::stringstream err_ss;
390  llvm::raw_os_ostream err_os(err_ss);
391  err_os << "\n-----\n";
392  if (llvm::verifyFunction(*func, &err_os)) {
393  err_os << "\n-----\n";
394  func->print(err_os, nullptr);
395  err_os << "\n-----\n";
396  LOG(FATAL) << err_ss.str();
397  }
398 }
399 
400 namespace {
401 
402 std::string assemblyForCPU(ExecutionEngineWrapper& execution_engine,
403  llvm::Module* llvm_module) {
404  llvm::legacy::PassManager pass_manager;
405  auto cpu_target_machine = execution_engine->getTargetMachine();
406  CHECK(cpu_target_machine);
407  llvm::SmallString<256> code_str;
408  llvm::raw_svector_ostream os(code_str);
409 #if LLVM_VERSION_MAJOR >= 10
410  cpu_target_machine->addPassesToEmitFile(
411  pass_manager, os, nullptr, llvm::CGFT_AssemblyFile);
412 #else
413  cpu_target_machine->addPassesToEmitFile(
414  pass_manager, os, nullptr, llvm::TargetMachine::CGFT_AssemblyFile);
415 #endif
416  pass_manager.run(*llvm_module);
417  return "Assembly for the CPU:\n" + std::string(code_str.str()) + "\nEnd of assembly";
418 }
419 
421  llvm::EngineBuilder& eb,
422  const CompilationOptions& co) {
423  auto timer = DEBUG_TIMER(__func__);
424  ExecutionEngineWrapper execution_engine(eb.create(), co);
425  CHECK(execution_engine.get());
426  // Force the module data layout to match the layout for the selected target
427  llvm_module->setDataLayout(execution_engine->getDataLayout());
428 
429  LOG(ASM) << assemblyForCPU(execution_engine, llvm_module);
430 
431  execution_engine->finalizeObject();
432  return execution_engine;
433 }
434 
435 } // namespace
436 
438 
440  llvm::Function* func,
441  const std::unordered_set<llvm::Function*>& live_funcs,
442  const CompilationOptions& co) {
443  auto timer = DEBUG_TIMER(__func__);
444  llvm::Module* llvm_module = func->getParent();
445  CHECK(llvm_module);
446  // run optimizations
447 #ifndef WITH_JIT_DEBUG
448  llvm::legacy::PassManager pass_manager;
449  optimize_ir(
450  func, llvm_module, pass_manager, live_funcs, /*is_gpu_smem_used=*/false, co);
451 #endif // WITH_JIT_DEBUG
452 
453  // The following lock avoids a data race in two places:
454  // 1) in initializaiton of the CPU backend targets
455  // 1) in llvm::sys::DynamicLibrary::getPermanentLibrary and
456  // GDBJITRegistrationListener::notifyObjectLoaded while creating a
457  // new ExecutionEngine instance in the child call create_execution_engine.
458 
459  // Todo: Initialize backend CPU (and perhaps GPU?) targets at startup
460  // instead of for every compilation, and see if we can reduce
461  // the scope of the below lock
462 
463  std::lock_guard<std::mutex> lock(initialize_cpu_backend_mutex_);
464  auto init_err = llvm::InitializeNativeTarget();
465  CHECK(!init_err);
466 
467  llvm::InitializeAllTargetMCs();
468  llvm::InitializeNativeTargetAsmPrinter();
469  llvm::InitializeNativeTargetAsmParser();
470 
471  std::string err_str;
472  std::unique_ptr<llvm::Module> owner(llvm_module);
473  CHECK(owner);
474  llvm::EngineBuilder eb(std::move(owner));
475  eb.setErrorStr(&err_str);
476  eb.setEngineKind(llvm::EngineKind::JIT);
477  llvm::TargetOptions to;
478  to.EnableFastISel = true;
479  eb.setTargetOptions(to);
481  eb.setOptLevel(llvm::CodeGenOpt::None);
482  }
483 
484  return create_execution_engine(llvm_module, eb, co);
485 }
486 
487 std::shared_ptr<CompilationContext> Executor::optimizeAndCodegenCPU(
488  llvm::Function* query_func,
489  llvm::Function* multifrag_query_func,
490  const std::unordered_set<llvm::Function*>& live_funcs,
491  const CompilationOptions& co) {
492  CodeCacheKey key{serialize_llvm_object(query_func),
493  serialize_llvm_object(cgen_state_->row_func_)};
494 
495  llvm::Module* M = query_func->getParent();
496  auto* flag = llvm::mdconst::extract_or_null<llvm::ConstantInt>(
497  M->getModuleFlag("manage_memory_buffer"));
498  if (flag and flag->getZExtValue() == 1 and M->getFunction("allocate_varlen_buffer") and
499  M->getFunction("register_buffer_with_executor_rsm")) {
500  LOG(INFO) << "including executor addr to cache key\n";
501  key.push_back(std::to_string(reinterpret_cast<int64_t>(this)));
502  }
503  if (cgen_state_->filter_func_) {
504  key.push_back(serialize_llvm_object(cgen_state_->filter_func_));
505  }
506  for (const auto helper : cgen_state_->helper_functions_) {
507  key.push_back(serialize_llvm_object(helper));
508  }
509  auto cached_code = QueryEngine::getInstance()->cpu_code_accessor->get_value(key);
510  if (cached_code) {
511  return cached_code;
512  }
513 
514  if (cgen_state_->needs_geos_) {
515 #ifdef ENABLE_GEOS
516  auto llvm_module = multifrag_query_func->getParent();
517  load_geos_dynamic_library();
518 
519  // Read geos runtime module and bind GEOS API function references to GEOS library
520  auto rt_geos_module_copy = llvm::CloneModule(
521  *get_geos_module(), cgen_state_->vmap_, [](const llvm::GlobalValue* gv) {
522  auto func = llvm::dyn_cast<llvm::Function>(gv);
523  if (!func) {
524  return true;
525  }
526  switch (func->getLinkage()) {
527  case llvm::GlobalValue::LinkageTypes::InternalLinkage:
528  case llvm::GlobalValue::LinkageTypes::PrivateLinkage:
529  case llvm::GlobalValue::LinkageTypes::ExternalLinkage:
530  case llvm::GlobalValue::LinkageTypes::LinkOnceODRLinkage:
531  return true;
532  default:
533  return false;
534  }
535  });
536  CodeGenerator::link_udf_module(rt_geos_module_copy,
537  *llvm_module,
538  cgen_state_.get(),
539  llvm::Linker::Flags::LinkOnlyNeeded);
540 #else
541  throw std::runtime_error("GEOS is disabled in this build");
542 #endif
543  }
544 
545  auto execution_engine =
546  CodeGenerator::generateNativeCPUCode(query_func, live_funcs, co);
547  auto cpu_compilation_context =
548  std::make_shared<CpuCompilationContext>(std::move(execution_engine));
549  cpu_compilation_context->setFunctionPointer(multifrag_query_func);
550  QueryEngine::getInstance()->cpu_code_accessor->put(key, cpu_compilation_context);
551  return std::dynamic_pointer_cast<CompilationContext>(cpu_compilation_context);
552 }
553 
554 void CodeGenerator::link_udf_module(const std::unique_ptr<llvm::Module>& udf_module,
555  llvm::Module& llvm_module,
556  CgenState* cgen_state,
557  llvm::Linker::Flags flags) {
558  auto timer = DEBUG_TIMER(__func__);
559  // throw a runtime error if the target module contains functions
560  // with the same name as in module of UDF functions.
561  for (auto& f : *udf_module) {
562  auto func = llvm_module.getFunction(f.getName());
563  if (!(func == nullptr) && !f.isDeclaration() && flags == llvm::Linker::Flags::None) {
564  LOG(ERROR) << " Attempt to overwrite " << f.getName().str() << " in "
565  << llvm_module.getModuleIdentifier() << " from `"
566  << udf_module->getModuleIdentifier() << "`" << std::endl;
567  throw std::runtime_error(
568  "link_udf_module: *** attempt to overwrite a runtime function with a UDF "
569  "function ***");
570  } else {
571  VLOG(1) << " Adding " << f.getName().str() << " to "
572  << llvm_module.getModuleIdentifier() << " from `"
573  << udf_module->getModuleIdentifier() << "`" << std::endl;
574  }
575  }
576 
577  auto udf_module_copy = llvm::CloneModule(*udf_module, cgen_state->vmap_);
578 
579  udf_module_copy->setDataLayout(llvm_module.getDataLayout());
580  udf_module_copy->setTargetTriple(llvm_module.getTargetTriple());
581 
582  // Initialize linker with module for RuntimeFunctions.bc
583  llvm::Linker ld(llvm_module);
584  bool link_error = false;
585 
586  link_error = ld.linkInModule(std::move(udf_module_copy), flags);
587 
588  if (link_error) {
589  throw std::runtime_error("link_udf_module: *** error linking module ***");
590  }
591 }
592 
593 namespace {
594 
595 std::string cpp_to_llvm_name(const std::string& s) {
596  if (s == "int8_t") {
597  return "i8";
598  }
599  if (s == "int16_t") {
600  return "i16";
601  }
602  if (s == "int32_t") {
603  return "i32";
604  }
605  if (s == "int64_t") {
606  return "i64";
607  }
608  CHECK(s == "float" || s == "double");
609  return s;
610 }
611 
612 std::string gen_array_any_all_sigs() {
613  std::string result;
614  for (const std::string any_or_all : {"any", "all"}) {
615  for (const std::string elem_type :
616  {"int8_t", "int16_t", "int32_t", "int64_t", "float", "double"}) {
617  for (const std::string needle_type :
618  {"int8_t", "int16_t", "int32_t", "int64_t", "float", "double"}) {
619  for (const std::string op_name : {"eq", "ne", "lt", "le", "gt", "ge"}) {
620  result += ("declare i1 @array_" + any_or_all + "_" + op_name + "_" + elem_type +
621  "_" + needle_type + "(i8*, i64, " + cpp_to_llvm_name(needle_type) +
622  ", " + cpp_to_llvm_name(elem_type) + ");\n");
623  }
624  }
625  }
626  }
627  return result;
628 }
629 
631  std::string result;
632  for (const std::string key_type : {"int8_t", "int16_t", "int32_t", "int64_t"}) {
633  const auto key_llvm_type = cpp_to_llvm_name(key_type);
634  result += "declare i64 @translate_null_key_" + key_type + "(" + key_llvm_type + ", " +
635  key_llvm_type + ", i64);\n";
636  }
637  return result;
638 }
639 
640 const std::string cuda_rt_decls =
641  R"( declare void @llvm.dbg.declare(metadata, metadata, metadata) declare void @llvm.dbg.value(metadata, metadata, metadata) declare double @llvm.fmuladd.f64(double, double, double) declare void @llvm.lifetime.start(i64, i8* nocapture) nounwind declare void @llvm.lifetime.end(i64, i8* nocapture) nounwind declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) nounwind declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) nounwind declare i64 @get_thread_index(); declare i64 @get_block_index(); declare i32 @pos_start_impl(i32*); declare i32 @group_buff_idx_impl(); declare i32 @pos_step_impl(); declare i8 @thread_warp_idx(i8); declare i64* @init_shared_mem(i64*, i32); declare i64* @init_shared_mem_nop(i64*, i32); declare i64* @declare_dynamic_shared_memory(); declare void @write_back_nop(i64*, i64*, i32); declare void @write_back_non_grouped_agg(i64*, i64*, i32); declare void @init_group_by_buffer_gpu(i64*, i64*, i32, i32, i32, i1, i8); declare i64* @get_group_value(i64*, i32, i64*, i32, i32, i32); declare i64* @get_group_value_with_watchdog(i64*, i32, i64*, i32, i32, i32); declare i32 @get_group_value_columnar_slot(i64*, i32, i64*, i32, i32); declare i32 @get_group_value_columnar_slot_with_watchdog(i64*, i32, i64*, i32, i32); declare i64* @get_group_value_fast(i64*, i64, i64, i64, i32); declare i64* @get_group_value_fast_with_original_key(i64*, i64, i64, i64, i64, i32); declare i32 @get_columnar_group_bin_offset(i64*, i64, i64, i64); declare i64 @baseline_hash_join_idx_32(i8*, i8*, i64, i64); declare i64 @baseline_hash_join_idx_64(i8*, i8*, i64, i64); declare i64 @get_composite_key_index_32(i32*, i64, i32*, i64); declare i64 @get_composite_key_index_64(i64*, i64, i64*, i64); declare i64 @get_bucket_key_for_range_compressed(i8*, i64, double); declare i64 @get_bucket_key_for_range_double(i8*, i64, double); declare i32 @get_num_buckets_for_bounds(i8*, i32, double, double); declare i64 @get_candidate_rows(i32*, i32*, i32, i8*, i32, double, double, i32, i64, i64*, i64, i64, i64, i32); declare i64 @agg_count_shared(i64*, i64); declare i64 @agg_count_skip_val_shared(i64*, i64, i64); declare i32 @agg_count_int32_shared(i32*, i32); declare i32 @agg_count_int32_skip_val_shared(i32*, i32, i32); declare i64 @agg_count_double_shared(i64*, double); declare i64 @agg_count_double_skip_val_shared(i64*, double, double); declare i32 @agg_count_float_shared(i32*, float); declare i32 @agg_count_float_skip_val_shared(i32*, float, float); declare i64 @agg_count_if_shared(i64*, i64); declare i64 @agg_count_if_skip_val_shared(i64*, i64, i64); declare i32 @agg_count_if_int32_shared(i32*, i32); declare i32 @agg_count_if_int32_skip_val_shared(i32*, i32, i32); declare i64 @agg_sum_shared(i64*, i64); declare i64 @agg_sum_skip_val_shared(i64*, i64, i64); declare i32 @agg_sum_int32_shared(i32*, i32); declare i32 @agg_sum_int32_skip_val_shared(i32*, i32, i32); declare void @agg_sum_double_shared(i64*, double); declare void @agg_sum_double_skip_val_shared(i64*, double, double); declare void @agg_sum_float_shared(i32*, float); declare void @agg_sum_float_skip_val_shared(i32*, float, float); declare i64 @agg_sum_if_shared(i64*, i64, i8); declare i64 @agg_sum_if_skip_val_shared(i64*, i64, i64, i8); declare i32 @agg_sum_if_int32_shared(i32*, i32, i8); declare i32 @agg_sum_if_int32_skip_val_shared(i32*, i32, i32, i8); declare void @agg_sum_if_double_shared(i64*, double, i8); declare void @agg_sum_if_double_skip_val_shared(i64*, double, double, i8); declare void @agg_sum_if_float_shared(i32*, float, i8); declare void @agg_sum_if_float_skip_val_shared(i32*, float, float, i8); declare void @agg_max_shared(i64*, i64); declare void @agg_max_skip_val_shared(i64*, i64, i64); declare void @agg_max_int32_shared(i32*, i32); declare void @agg_max_int32_skip_val_shared(i32*, i32, i32); declare void @agg_max_int16_shared(i16*, i16); declare void @agg_max_int16_skip_val_shared(i16*, i16, i16); declare void @agg_max_int8_shared(i8*, i8); declare void @agg_max_int8_skip_val_shared(i8*, i8, i8); declare void @agg_max_double_shared(i64*, double); declare void @agg_max_double_skip_val_shared(i64*, double, double); declare void @agg_max_float_shared(i32*, float); declare void @agg_max_float_skip_val_shared(i32*, float, float); declare void @agg_min_shared(i64*, i64); declare void @agg_min_skip_val_shared(i64*, i64, i64); declare void @agg_min_int32_shared(i32*, i32); declare void @agg_min_int32_skip_val_shared(i32*, i32, i32); declare void @agg_min_int16_shared(i16*, i16); declare void @agg_min_int16_skip_val_shared(i16*, i16, i16); declare void @agg_min_int8_shared(i8*, i8); declare void @agg_min_int8_skip_val_shared(i8*, i8, i8); declare void @agg_min_double_shared(i64*, double); declare void @agg_min_double_skip_val_shared(i64*, double, double); declare void @agg_min_float_shared(i32*, float); declare void @agg_min_float_skip_val_shared(i32*, float, float); declare void @agg_id_shared(i64*, i64); declare i8* @agg_id_varlen_shared(i8*, i64, i8*, i64); declare void @agg_id_int32_shared(i32*, i32); declare void @agg_id_int16_shared(i16*, i16); declare void @agg_id_int8_shared(i8*, i8); declare void @agg_id_double_shared(i64*, double); declare void @agg_id_double_shared_slow(i64*, double*); declare void @agg_id_float_shared(i32*, float); declare i32 @checked_single_agg_id_shared(i64*, i64, i64); declare i32 @checked_single_agg_id_double_shared(i64*, double, double); declare i32 @checked_single_agg_id_double_shared_slow(i64*, double*, double); declare i32 @checked_single_agg_id_float_shared(i32*, float, float); declare i1 @slotEmptyKeyCAS(i64*, i64, i64); declare i1 @slotEmptyKeyCAS_int32(i32*, i32, i32); declare i1 @slotEmptyKeyCAS_int16(i16*, i16, i16); declare i1 @slotEmptyKeyCAS_int8(i8*, i8, i8); declare i64 @datetrunc_century(i64); declare i64 @datetrunc_day(i64); declare i64 @datetrunc_decade(i64); declare i64 @datetrunc_hour(i64); declare i64 @datetrunc_millennium(i64); declare i64 @datetrunc_minute(i64); declare i64 @datetrunc_month(i64); declare i64 @datetrunc_quarter(i64); declare i64 @datetrunc_quarterday(i64); declare i64 @datetrunc_week_monday(i64); declare i64 @datetrunc_week_sunday(i64); declare i64 @datetrunc_week_saturday(i64); declare i64 @datetrunc_year(i64); declare i64 @extract_epoch(i64); declare i64 @extract_dateepoch(i64); declare i64 @extract_quarterday(i64); declare i64 @extract_hour(i64); declare i64 @extract_minute(i64); declare i64 @extract_second(i64); declare i64 @extract_millisecond(i64); declare i64 @extract_microsecond(i64); declare i64 @extract_nanosecond(i64); declare i64 @extract_dow(i64); declare i64 @extract_isodow(i64); declare i64 @extract_day(i64); declare i64 @extract_week_monday(i64); declare i64 @extract_week_sunday(i64); declare i64 @extract_week_saturday(i64); declare i64 @extract_day_of_year(i64); declare i64 @extract_month(i64); declare i64 @extract_quarter(i64); declare i64 @extract_year(i64); declare i64 @ExtractTimeFromHPTimestamp(i64,i64); declare i64 @ExtractTimeFromHPTimestampNullable(i64,i64,i64); declare i64 @ExtractTimeFromLPTimestamp(i64); declare i64 @ExtractTimeFromLPTimestampNullable(i64,i64); declare i64 @DateTruncateHighPrecisionToDate(i64, i64); declare i64 @DateTruncateHighPrecisionToDateNullable(i64, i64, i64); declare i64 @DateDiff(i32, i64, i64); declare i64 @DateDiffNullable(i32, i64, i64, i64); declare i64 @DateDiffHighPrecision(i32, i64, i64, i32, i32); declare i64 @DateDiffHighPrecisionNullable(i32, i64, i64, i32, i32, i64); declare i64 @DateAdd(i32, i64, i64); declare i64 @DateAddNullable(i32, i64, i64, i64); declare i64 @DateAddHighPrecision(i32, i64, i64, i32); declare i64 @DateAddHighPrecisionNullable(i32, i64, i64, i32, i64); declare {i8*,i64} @string_decode(i8*, i64); declare i32 @array_size(i8*, i64, i32); declare i32 @array_size_nullable(i8*, i64, i32, i32); declare i32 @array_size_1_nullable(i8*, i64, i32); declare i32 @fast_fixlen_array_size(i8*, i32); declare i1 @array_is_null(i8*, i64); declare i1 @point_coord_array_is_null(i8*, i64); declare i8* @array_buff(i8*, i64); declare i8* @fast_fixlen_array_buff(i8*, i64); declare i64 @determine_fixed_array_len(i8*, i64); declare i8 @array_at_int8_t(i8*, i64, i32); declare i16 @array_at_int16_t(i8*, i64, i32); declare i32 @array_at_int32_t(i8*, i64, i32); declare i64 @array_at_int64_t(i8*, i64, i32); declare float @array_at_float(i8*, i64, i32); declare double @array_at_double(i8*, i64, i32); declare i8 @varlen_array_at_int8_t(i8*, i64, i32); declare i16 @varlen_array_at_int16_t(i8*, i64, i32); declare i32 @varlen_array_at_int32_t(i8*, i64, i32); declare i64 @varlen_array_at_int64_t(i8*, i64, i32); declare float @varlen_array_at_float(i8*, i64, i32); declare double @varlen_array_at_double(i8*, i64, i32); declare i8 @varlen_notnull_array_at_int8_t(i8*, i64, i32); declare i16 @varlen_notnull_array_at_int16_t(i8*, i64, i32); declare i32 @varlen_notnull_array_at_int32_t(i8*, i64, i32); declare i64 @varlen_notnull_array_at_int64_t(i8*, i64, i32); declare float @varlen_notnull_array_at_float(i8*, i64, i32); declare double @varlen_notnull_array_at_double(i8*, i64, i32); declare i8 @array_at_int8_t_checked(i8*, i64, i64, i8); declare i16 @array_at_int16_t_checked(i8*, i64, i64, i16); declare i32 @array_at_int32_t_checked(i8*, i64, i64, i32); declare i64 @array_at_int64_t_checked(i8*, i64, i64, i64); declare float @array_at_float_checked(i8*, i64, i64, float); declare double @array_at_double_checked(i8*, i64, i64, double); declare i32 @char_length(i8*, i32); declare i32 @char_length_nullable(i8*, i32, i32); declare i32 @char_length_encoded(i8*, i32); declare i32 @char_length_encoded_nullable(i8*, i32, i32); declare i32 @key_for_string_encoded(i32); declare i1 @sample_ratio(double, i64); declare double @width_bucket(double, double, double, double, i32); declare double @width_bucket_reverse(double, double, double, double, i32); declare double @width_bucket_nullable(double, double, double, double, i32, double); declare double @width_bucket_reversed_nullable(double, double, double, double, i32, double); declare double @width_bucket_no_oob_check(double, double, double); declare double @width_bucket_reverse_no_oob_check(double, double, double); declare double @width_bucket_expr(double, i1, double, double, i32); declare double @width_bucket_expr_nullable(double, i1, double, double, i32, double); declare double @width_bucket_expr_no_oob_check(double, i1, double, double, i32); declare i1 @string_like(i8*, i32, i8*, i32, i8); declare i1 @string_ilike(i8*, i32, i8*, i32, i8); declare i8 @string_like_nullable(i8*, i32, i8*, i32, i8, i8); declare i8 @string_ilike_nullable(i8*, i32, i8*, i32, i8, i8); declare i1 @string_like_simple(i8*, i32, i8*, i32, i8); declare i1 @string_ilike_simple(i8*, i32, i8*, i32, i8); declare i8 @string_like_simple_nullable(i8*, i32, i8*, i32, i8, i8); declare i8 @string_ilike_simple_nullable(i8*, i32, i8*, i32, i8, i8); declare i1 @string_lt(i8*, i32, i8*, i32); declare i1 @string_le(i8*, i32, i8*, i32); declare i1 @string_gt(i8*, i32, i8*, i32); declare i1 @string_ge(i8*, i32, i8*, i32); declare i1 @string_eq(i8*, i32, i8*, i32); declare i1 @string_ne(i8*, i32, i8*, i32); declare i8 @string_lt_nullable(i8*, i32, i8*, i32, i8); declare i8 @string_le_nullable(i8*, i32, i8*, i32, i8); declare i8 @string_gt_nullable(i8*, i32, i8*, i32, i8); declare i8 @string_ge_nullable(i8*, i32, i8*, i32, i8); declare i8 @string_eq_nullable(i8*, i32, i8*, i32, i8); declare i8 @string_ne_nullable(i8*, i32, i8*, i32, i8); declare i1 @regexp_like(i8*, i32, i8*, i32, i8); declare i8 @regexp_like_nullable(i8*, i32, i8*, i32, i8, i8); declare void @linear_probabilistic_count(i8*, i32, i8*, i32); declare void @agg_count_distinct_bitmap_gpu(i64*, i64, i64, i64, i64, i64, i64, i64); declare void @agg_count_distinct_bitmap_skip_val_gpu(i64*, i64, i64, i64, i64, i64, i64, i64, i64); declare void @agg_approximate_count_distinct_gpu(i64*, i64, i32, i64, i64); declare void @record_error_code(i32, i32*); declare i32 @get_error_code(i32*); declare i1 @dynamic_watchdog(); declare i1 @check_interrupt(); declare void @force_sync(); declare void @sync_warp(); declare void @sync_warp_protected(i64, i64); declare void @sync_threadblock(); declare i64* @get_bin_from_k_heap_int32_t(i64*, i32, i32, i32, i1, i1, i1, i32, i32); declare i64* @get_bin_from_k_heap_int64_t(i64*, i32, i32, i32, i1, i1, i1, i64, i64); declare i64* @get_bin_from_k_heap_float(i64*, i32, i32, i32, i1, i1, i1, float, float); declare i64* @get_bin_from_k_heap_double(i64*, i32, i32, i32, i1, i1, i1, double, double); declare double @decompress_x_coord_geoint(i32); declare double @decompress_y_coord_geoint(i32); declare i32 @compress_x_coord_geoint(double); declare i32 @compress_y_coord_geoint(double); declare i64 @fixed_width_date_encode(i64, i32, i64); declare i64 @fixed_width_date_decode(i64, i32, i64); )" + gen_array_any_all_sigs() +
643 
644 #ifdef HAVE_CUDA
645 
646 namespace {
647 bool check_any_operand_is_stacksave_intrinsic(llvm::Instruction& inst) {
648  for (auto op_it = inst.op_begin(); op_it != inst.op_end(); op_it++) {
649  if (const llvm::IntrinsicInst* inst2 = llvm::dyn_cast<llvm::IntrinsicInst>(*op_it)) {
650  if (inst2->getIntrinsicID() == llvm::Intrinsic::stacksave) {
651  return true;
652  }
653  }
654  }
655  return false;
656 }
657 } // namespace
658 
659 std::string extension_function_decls(const std::unordered_set<std::string>& udf_decls) {
660  const auto decls =
661  ExtensionFunctionsWhitelist::getLLVMDeclarations(udf_decls, /*is_gpu=*/true);
662  return boost::algorithm::join(decls, "\n");
663 }
664 
665 void legalize_nvvm_ir(llvm::Function* query_func) {
666  // optimizations might add attributes to the function
667  // and NVPTX doesn't understand all of them; play it
668  // safe and clear all attributes
669  clear_function_attributes(query_func);
670  verify_function_ir(query_func);
671 
672  std::vector<llvm::Instruction*> stackrestore_intrinsics;
673  std::vector<llvm::Instruction*> stacksave_intrinsics;
674  std::vector<llvm::Instruction*> lifetime;
675  for (auto& BB : *query_func) {
676  for (llvm::Instruction& I : BB) {
677  if (llvm::dyn_cast<llvm::PHINode>(&I)) {
678  if (check_any_operand_is_stacksave_intrinsic(I)) {
679  // AFAIK, the only case we have to remove an non-intrinsic inst is a PHI node
680  // iff at least its one of operands is llvm::stacksave intrinsic
681  stacksave_intrinsics.push_back(&I);
682  VLOG(2) << "Remove PHI node having llvm::stacksave intrinsic as its operand";
683  }
684  } else if (const llvm::IntrinsicInst* II =
685  llvm::dyn_cast<llvm::IntrinsicInst>(&I)) {
686  if (II->getIntrinsicID() == llvm::Intrinsic::stacksave) {
687  stacksave_intrinsics.push_back(&I);
688  } else if (II->getIntrinsicID() == llvm::Intrinsic::stackrestore) {
689  stackrestore_intrinsics.push_back(&I);
690  } else if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_start ||
691  II->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
692  lifetime.push_back(&I);
693  }
694  }
695  }
696  }
697 
698  // stacksave and stackrestore intrinsics appear together, and
699  // stackrestore uses stacksaved result as its argument
700  // so it should be removed first.
701  for (auto& II : stackrestore_intrinsics) {
702  II->eraseFromParent();
703  }
704  for (auto& II : stacksave_intrinsics) {
705  II->eraseFromParent();
706  }
707  // Remove lifetime intrinsics as well. NVPTX don't like them
708  for (auto& II : lifetime) {
709  II->eraseFromParent();
710  }
711 }
712 #endif // HAVE_CUDA
713 
714 } // namespace
715 
716 llvm::StringRef get_gpu_target_triple_string() {
717  return llvm::StringRef("nvptx64-nvidia-cuda");
718 }
719 
720 llvm::StringRef get_gpu_data_layout() {
721  return llvm::StringRef(
722  "e-p:64:64:64-i1:8:8-i8:8:8-"
723  "i16:16:16-i32:32:32-i64:64:64-"
724  "f32:32:32-f64:64:64-v16:16:16-"
725  "v32:32:32-v64:64:64-v128:128:128-n16:32:64");
726 }
727 
728 std::map<std::string, std::string> get_device_parameters(bool cpu_only) {
729  std::map<std::string, std::string> result;
730 
731  result.insert(std::make_pair("cpu_name", llvm::sys::getHostCPUName()));
732  result.insert(std::make_pair("cpu_triple", llvm::sys::getProcessTriple()));
733  result.insert(
734  std::make_pair("cpu_cores", std::to_string(llvm::sys::getHostNumPhysicalCores())));
735  result.insert(std::make_pair("cpu_threads", std::to_string(cpu_threads())));
736 
737  // https://en.cppreference.com/w/cpp/language/types
738  std::string sizeof_types;
739  sizeof_types += "bool:" + std::to_string(sizeof(bool)) + ";";
740  sizeof_types += "size_t:" + std::to_string(sizeof(size_t)) + ";";
741  sizeof_types += "ssize_t:" + std::to_string(sizeof(ssize_t)) + ";";
742  sizeof_types += "char:" + std::to_string(sizeof(char)) + ";";
743  sizeof_types += "uchar:" + std::to_string(sizeof(unsigned char)) + ";";
744  sizeof_types += "short:" + std::to_string(sizeof(short)) + ";";
745  sizeof_types += "ushort:" + std::to_string(sizeof(unsigned short int)) + ";";
746  sizeof_types += "int:" + std::to_string(sizeof(int)) + ";";
747  sizeof_types += "uint:" + std::to_string(sizeof(unsigned int)) + ";";
748  sizeof_types += "long:" + std::to_string(sizeof(long int)) + ";";
749  sizeof_types += "ulong:" + std::to_string(sizeof(unsigned long int)) + ";";
750  sizeof_types += "longlong:" + std::to_string(sizeof(long long int)) + ";";
751  sizeof_types += "ulonglong:" + std::to_string(sizeof(unsigned long long int)) + ";";
752  sizeof_types += "float:" + std::to_string(sizeof(float)) + ";";
753  sizeof_types += "double:" + std::to_string(sizeof(double)) + ";";
754  sizeof_types += "longdouble:" + std::to_string(sizeof(long double)) + ";";
755  sizeof_types += "voidptr:" + std::to_string(sizeof(void*)) + ";";
756 
757  result.insert(std::make_pair("type_sizeof", sizeof_types));
758 
759  std::string null_values;
760  null_values += "boolean1:" + std::to_string(serialized_null_value<bool>()) + ";";
761  null_values += "boolean8:" + std::to_string(serialized_null_value<int8_t>()) + ";";
762  null_values += "int8:" + std::to_string(serialized_null_value<int8_t>()) + ";";
763  null_values += "int16:" + std::to_string(serialized_null_value<int16_t>()) + ";";
764  null_values += "int32:" + std::to_string(serialized_null_value<int32_t>()) + ";";
765  null_values += "int64:" + std::to_string(serialized_null_value<int64_t>()) + ";";
766  null_values += "uint8:" + std::to_string(serialized_null_value<uint8_t>()) + ";";
767  null_values += "uint16:" + std::to_string(serialized_null_value<uint16_t>()) + ";";
768  null_values += "uint32:" + std::to_string(serialized_null_value<uint32_t>()) + ";";
769  null_values += "uint64:" + std::to_string(serialized_null_value<uint64_t>()) + ";";
770  null_values += "float32:" + std::to_string(serialized_null_value<float>()) + ";";
771  null_values += "float64:" + std::to_string(serialized_null_value<double>()) + ";";
772  null_values +=
773  "Array<boolean8>:" + std::to_string(serialized_null_value<int8_t, true>()) + ";";
774  null_values +=
775  "Array<int8>:" + std::to_string(serialized_null_value<int8_t, true>()) + ";";
776  null_values +=
777  "Array<int16>:" + std::to_string(serialized_null_value<int16_t, true>()) + ";";
778  null_values +=
779  "Array<int32>:" + std::to_string(serialized_null_value<int32_t, true>()) + ";";
780  null_values +=
781  "Array<int64>:" + std::to_string(serialized_null_value<int64_t, true>()) + ";";
782  null_values +=
783  "Array<float32>:" + std::to_string(serialized_null_value<float, true>()) + ";";
784  null_values +=
785  "Array<float64>:" + std::to_string(serialized_null_value<double, true>()) + ";";
786 
787  result.insert(std::make_pair("null_values", null_values));
788 
789  llvm::StringMap<bool> cpu_features;
790  if (llvm::sys::getHostCPUFeatures(cpu_features)) {
791  std::string features_str = "";
792  for (auto it = cpu_features.begin(); it != cpu_features.end(); ++it) {
793  features_str += (it->getValue() ? " +" : " -");
794  features_str += it->getKey().str();
795  }
796  result.insert(std::make_pair("cpu_features", features_str));
797  }
798 
799  result.insert(std::make_pair("llvm_version",
800  std::to_string(LLVM_VERSION_MAJOR) + "." +
801  std::to_string(LLVM_VERSION_MINOR) + "." +
802  std::to_string(LLVM_VERSION_PATCH)));
803 
804 #ifdef HAVE_CUDA
805  if (!cpu_only) {
806  int device_count = 0;
807  checkCudaErrors(cuDeviceGetCount(&device_count));
808  if (device_count) {
809  CUdevice device{};
810  char device_name[256];
811  int major = 0, minor = 0;
812  int driver_version;
813  checkCudaErrors(cuDeviceGet(&device, 0)); // assuming homogeneous multi-GPU system
814  checkCudaErrors(cuDeviceGetName(device_name, 256, device));
815  checkCudaErrors(cuDeviceGetAttribute(
816  &major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, device));
817  checkCudaErrors(cuDeviceGetAttribute(
818  &minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, device));
819  checkCudaErrors(cuDriverGetVersion(&driver_version));
820 
821  result.insert(std::make_pair("gpu_name", device_name));
822  result.insert(std::make_pair("gpu_count", std::to_string(device_count)));
823  result.insert(std::make_pair("gpu_compute_capability",
824  std::to_string(major) + "." + std::to_string(minor)));
825  result.insert(std::make_pair("gpu_triple", get_gpu_target_triple_string()));
826  result.insert(std::make_pair("gpu_datalayout", get_gpu_data_layout()));
827  result.insert(std::make_pair("gpu_driver",
828  "CUDA " + std::to_string(driver_version / 1000) + "." +
829  std::to_string((driver_version % 1000) / 10)));
830 
831  auto rt_libdevice_path = get_cuda_libdevice_dir() + "/libdevice.10.bc";
832  result.insert(
833  std::make_pair("gpu_has_libdevice",
834  std::to_string(boost::filesystem::exists(rt_libdevice_path))));
835  }
836  }
837 #endif
838 
839  return result;
840 }
841 
842 namespace {
843 
844 #ifdef HAVE_CUDA
845 std::unordered_set<llvm::Function*> findAliveRuntimeFuncs(
846  llvm::Module& llvm_module,
847  const std::vector<llvm::Function*>& roots) {
848  std::queue<llvm::Function*> queue;
849  std::unordered_set<llvm::Function*> visited;
850  for (llvm::Function* F : roots) {
851  queue.push(F);
852  }
853 
854  while (!queue.empty()) {
855  llvm::Function* F = queue.front();
856  queue.pop();
857  if (visited.find(F) != visited.end()) {
858  continue;
859  }
860  visited.insert(F);
861 
862  for (llvm::inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
863  if (llvm::CallInst* CI = llvm::dyn_cast<llvm::CallInst>(&*I)) {
864  if (CI->isInlineAsm()) { // libdevice calls inline assembly code
865  continue;
866  }
867  llvm::Function* called = CI->getCalledFunction();
868  if (!called || visited.find(called) != visited.end()) {
869  continue;
870  }
871  queue.push(called);
872  }
873  }
874  }
875  return visited;
876 }
877 #endif
878 
879 } // namespace
880 
882  Executor* executor,
883  llvm::Module& llvm_module,
884  llvm::PassManagerBuilder& pass_manager_builder,
885  const GPUTarget& gpu_target) {
886 #ifdef HAVE_CUDA
887  auto timer = DEBUG_TIMER(__func__);
888 
889  if (!executor->has_libdevice_module()) {
890  // raise error
891  throw std::runtime_error(
892  "libdevice library is not available but required by the UDF module");
893  }
894 
895  // Saves functions \in module
896  std::vector<llvm::Function*> roots;
897  for (llvm::Function& fn : llvm_module) {
898  if (!fn.isDeclaration()) {
899  roots.emplace_back(&fn);
900  }
901  }
902 
903  // Bind libdevice to the current module
904  CodeGenerator::link_udf_module(executor->get_libdevice_module(),
905  llvm_module,
906  gpu_target.cgen_state,
907  llvm::Linker::Flags::OverrideFromSrc);
908 
909  std::unordered_set<llvm::Function*> live_funcs =
910  findAliveRuntimeFuncs(llvm_module, roots);
911 
912  std::vector<llvm::Function*> funcs_to_delete;
913  for (llvm::Function& fn : llvm_module) {
914  if (!live_funcs.count(&fn)) {
915  // deleting the function were would invalidate the iterator
916  funcs_to_delete.emplace_back(&fn);
917  }
918  }
919 
920  for (llvm::Function* f : funcs_to_delete) {
921  f->eraseFromParent();
922  }
923 
924  // activate nvvm-reflect-ftz flag on the module
925 #if LLVM_VERSION_MAJOR >= 11
926  llvm::LLVMContext& ctx = llvm_module.getContext();
927  llvm_module.setModuleFlag(llvm::Module::Override,
928  "nvvm-reflect-ftz",
929  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
930  llvm::Type::getInt32Ty(ctx), uint32_t(1))));
931 #else
932  llvm_module.addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", uint32_t(1));
933 #endif
934  for (llvm::Function& fn : llvm_module) {
935  fn.addFnAttr("nvptx-f32ftz", "true");
936  }
937 
938  // add nvvm reflect pass replacing any NVVM conditionals with constants
939  gpu_target.nvptx_target_machine->adjustPassManager(pass_manager_builder);
940  llvm::legacy::FunctionPassManager FPM(&llvm_module);
941  pass_manager_builder.populateFunctionPassManager(FPM);
942 
943  // Run the NVVMReflectPass here rather than inside optimize_ir
944  FPM.doInitialization();
945  for (auto& F : llvm_module) {
946  FPM.run(F);
947  }
948  FPM.doFinalization();
949 #endif
950 }
951 
952 std::shared_ptr<GpuCompilationContext> CodeGenerator::generateNativeGPUCode(
953  Executor* executor,
954  llvm::Function* func,
955  llvm::Function* wrapper_func,
956  const std::unordered_set<llvm::Function*>& live_funcs,
957  const bool is_gpu_smem_used,
959  const GPUTarget& gpu_target) {
960 #ifdef HAVE_CUDA
961  auto timer = DEBUG_TIMER(__func__);
962  auto llvm_module = func->getParent();
963  /*
964  `func` is one of the following generated functions:
965  - `call_table_function(i8** %input_col_buffers, i64*
966  %input_row_count, i64** %output_buffers, i64* %output_row_count)`
967  that wraps the user-defined table function.
968  - `multifrag_query`
969  - `multifrag_query_hoisted_literals`
970  - ...
971 
972  `wrapper_func` is table_func_kernel(i32*, i8**, i64*, i64**,
973  i64*) that wraps `call_table_function`.
974 
975  `llvm_module` is from `build/QueryEngine/RuntimeFunctions.bc` and it
976  contains `func` and `wrapper_func`. `llvm_module` should also contain
977  the definitions of user-defined table functions.
978 
979  `live_funcs` contains table_func_kernel and call_table_function
980 
981  `gpu_target.cgen_state->module_` appears to be the same as `llvm_module`
982  */
983  CHECK(gpu_target.cgen_state->module_ == llvm_module);
984  CHECK(func->getParent() == wrapper_func->getParent());
985  llvm_module->setDataLayout(
986  "e-p:64:64:64-i1:8:8-i8:8:8-"
987  "i16:16:16-i32:32:32-i64:64:64-"
988  "f32:32:32-f64:64:64-v16:16:16-"
989  "v32:32:32-v64:64:64-v128:128:128-n16:32:64");
990  llvm_module->setTargetTriple("nvptx64-nvidia-cuda");
991  CHECK(gpu_target.nvptx_target_machine);
992  llvm::PassManagerBuilder pass_manager_builder = llvm::PassManagerBuilder();
993 
994  pass_manager_builder.OptLevel = 0;
995  llvm::legacy::PassManager module_pass_manager;
996  pass_manager_builder.populateModulePassManager(module_pass_manager);
997 
998  bool requires_libdevice = check_module_requires_libdevice(llvm_module);
999 
1000  if (requires_libdevice) {
1001  linkModuleWithLibdevice(executor, *llvm_module, pass_manager_builder, gpu_target);
1002  }
1003 
1004  // run optimizations
1005  optimize_ir(func, llvm_module, module_pass_manager, live_funcs, is_gpu_smem_used, co);
1006  legalize_nvvm_ir(func);
1007 
1008  std::stringstream ss;
1009  llvm::raw_os_ostream os(ss);
1010 
1011  llvm::LLVMContext& ctx = llvm_module->getContext();
1012  // Get "nvvm.annotations" metadata node
1013  llvm::NamedMDNode* md = llvm_module->getOrInsertNamedMetadata("nvvm.annotations");
1014 
1015  llvm::Metadata* md_vals[] = {llvm::ConstantAsMetadata::get(wrapper_func),
1016  llvm::MDString::get(ctx, "kernel"),
1017  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1018  llvm::Type::getInt32Ty(ctx), 1))};
1019 
1020  // Append metadata to nvvm.annotations
1021  md->addOperand(llvm::MDNode::get(ctx, md_vals));
1022 
1023  std::unordered_set<llvm::Function*> roots{wrapper_func, func};
1024  if (gpu_target.row_func_not_inlined) {
1025  clear_function_attributes(gpu_target.cgen_state->row_func_);
1026  roots.insert(gpu_target.cgen_state->row_func_);
1027  if (gpu_target.cgen_state->filter_func_) {
1028  roots.insert(gpu_target.cgen_state->filter_func_);
1029  }
1030  }
1031 
1032  // prevent helper functions from being removed
1033  for (auto f : gpu_target.cgen_state->helper_functions_) {
1034  roots.insert(f);
1035  }
1036 
1037  if (requires_libdevice) {
1038  for (llvm::Function& F : *llvm_module) {
1039  // Some libdevice functions calls another functions that starts with "__internal_"
1040  // prefix.
1041  // __internal_trig_reduction_slowpathd
1042  // __internal_accurate_pow
1043  // __internal_lgamma_pos
1044  // Those functions have a "noinline" attribute which prevents the optimizer from
1045  // inlining them into the body of @query_func
1046  if (F.hasName() && F.getName().startswith("__internal") && !F.isDeclaration()) {
1047  roots.insert(&F);
1048  }
1049  legalize_nvvm_ir(&F);
1050  }
1051  }
1052 
1053  // Prevent the udf function(s) from being removed the way the runtime functions are
1054  std::unordered_set<std::string> udf_declarations;
1055 
1056  if (executor->has_udf_module(/*is_gpu=*/true)) {
1057  for (auto& f : executor->get_udf_module(/*is_gpu=*/true)->getFunctionList()) {
1058  llvm::Function* udf_function = llvm_module->getFunction(f.getName());
1059 
1060  if (udf_function) {
1061  legalize_nvvm_ir(udf_function);
1062  roots.insert(udf_function);
1063 
1064  // If we have a udf that declares a external function
1065  // note it so we can avoid duplicate declarations
1066  if (f.isDeclaration()) {
1067  udf_declarations.insert(f.getName().str());
1068  }
1069  }
1070  }
1071  }
1072 
1073  if (executor->has_rt_udf_module(/*is_gpu=*/true)) {
1074  for (auto& f : executor->get_rt_udf_module(/*is_gpu=*/true)->getFunctionList()) {
1075  llvm::Function* udf_function = llvm_module->getFunction(f.getName());
1076  if (udf_function) {
1077  legalize_nvvm_ir(udf_function);
1078  roots.insert(udf_function);
1079 
1080  // If we have a udf that declares a external function
1081  // note it so we can avoid duplicate declarations
1082  if (f.isDeclaration()) {
1083  udf_declarations.insert(f.getName().str());
1084  }
1085  }
1086  }
1087  }
1088 
1089  std::vector<llvm::Function*> rt_funcs;
1090  for (auto& Fn : *llvm_module) {
1091  if (roots.count(&Fn)) {
1092  continue;
1093  }
1094  rt_funcs.push_back(&Fn);
1095  }
1096  for (auto& pFn : rt_funcs) {
1097  pFn->removeFromParent();
1098  }
1099 
1100  if (requires_libdevice) {
1101  add_intrinsics_to_module(llvm_module);
1102  }
1103 
1104  if (!llvm_module->getModuleFlag("Debug Info Version")) {
1105  // Fixes QE-705
1106  llvm_module->addModuleFlag(
1107  llvm::Module::Error, "Debug Info Version", llvm::DEBUG_METADATA_VERSION);
1108  }
1109 
1110  llvm_module->print(os, nullptr);
1111  os.flush();
1112 
1113  for (auto& pFn : rt_funcs) {
1114  llvm_module->getFunctionList().push_back(pFn);
1115  }
1116  llvm_module->eraseNamedMetadata(md);
1117 
1118  auto cuda_llir = ss.str() + cuda_rt_decls + extension_function_decls(udf_declarations);
1119  std::string ptx;
1120  try {
1121  ptx = generatePTX(
1122  cuda_llir, gpu_target.nvptx_target_machine, gpu_target.cgen_state->context_);
1123  } catch (ParseIRError& e) {
1124  LOG(WARNING) << "Failed to generate PTX: " << e.what()
1125  << ". Switching to CPU execution target.";
1126  throw QueryMustRunOnCpu();
1127  }
1128  LOG(PTX) << "PTX for the GPU:\n" << ptx << "\nEnd of PTX";
1129 
1130  CubinResult cubin_result = ptx_to_cubin(ptx, gpu_target.cuda_mgr);
1131  auto func_name = wrapper_func->getName().str();
1132  auto gpu_compilation_context = std::make_shared<GpuCompilationContext>();
1133  for (int device_id = 0; device_id < gpu_target.cuda_mgr->getDeviceCount();
1134  ++device_id) {
1135  gpu_compilation_context->addDeviceCode(
1136  std::make_unique<GpuDeviceCompilationContext>(cubin_result.cubin,
1137  cubin_result.cubin_size,
1138  func_name,
1139  device_id,
1140  gpu_target.cuda_mgr,
1141  cubin_result.option_keys.size(),
1142  cubin_result.option_keys.data(),
1143  cubin_result.option_values.data()));
1144  }
1145 
1146  checkCudaErrors(cuLinkDestroy(cubin_result.link_state));
1147  return gpu_compilation_context;
1148 #else
1149  return {};
1150 #endif
1151 }
1152 
1153 std::shared_ptr<CompilationContext> Executor::optimizeAndCodegenGPU(
1154  llvm::Function* query_func,
1155  llvm::Function* multifrag_query_func,
1156  std::unordered_set<llvm::Function*>& live_funcs,
1157  const bool no_inline,
1158  const CudaMgr_Namespace::CudaMgr* cuda_mgr,
1159  const bool is_gpu_smem_used,
1160  const CompilationOptions& co) {
1161 #ifdef HAVE_CUDA
1162  auto timer = DEBUG_TIMER(__func__);
1163 
1164  CHECK(cuda_mgr);
1165  CodeCacheKey key{serialize_llvm_object(query_func),
1166  serialize_llvm_object(cgen_state_->row_func_)};
1167  if (cgen_state_->filter_func_) {
1168  key.push_back(serialize_llvm_object(cgen_state_->filter_func_));
1169  }
1170  for (const auto helper : cgen_state_->helper_functions_) {
1171  key.push_back(serialize_llvm_object(helper));
1172  }
1173  auto cached_code = QueryEngine::getInstance()->gpu_code_accessor->get_value(key);
1174  if (cached_code) {
1175  return cached_code;
1176  }
1177 
1178  bool row_func_not_inlined = false;
1179  if (no_inline) {
1180  for (auto it = llvm::inst_begin(cgen_state_->row_func_),
1181  e = llvm::inst_end(cgen_state_->row_func_);
1182  it != e;
1183  ++it) {
1184  if (llvm::isa<llvm::CallInst>(*it)) {
1185  auto& get_gv_call = llvm::cast<llvm::CallInst>(*it);
1186  auto const func_name = CodegenUtil::getCalledFunctionName(get_gv_call);
1187  if (func_name &&
1188  (*func_name == "array_size" || *func_name == "linear_probabilistic_count")) {
1189  mark_function_never_inline(cgen_state_->row_func_);
1190  row_func_not_inlined = true;
1191  break;
1192  }
1193  }
1194  }
1195  }
1196 
1197  initializeNVPTXBackend();
1198  CodeGenerator::GPUTarget gpu_target{
1199  nvptx_target_machine_.get(), cuda_mgr, cgen_state_.get(), row_func_not_inlined};
1200  std::shared_ptr<GpuCompilationContext> compilation_context;
1201 
1202  try {
1203  compilation_context = CodeGenerator::generateNativeGPUCode(this,
1204  query_func,
1205  multifrag_query_func,
1206  live_funcs,
1207  is_gpu_smem_used,
1208  co,
1209  gpu_target);
1210  } catch (CudaMgr_Namespace::CudaErrorException& cuda_error) {
1211  if (cuda_error.getStatus() == CUDA_ERROR_OUT_OF_MEMORY) {
1212  // Thrown if memory not able to be allocated on gpu
1213  // Retry once after evicting portion of code cache
1214  auto& code_cache_accessor = QueryEngine::getInstance()->gpu_code_accessor;
1215  auto const num_entries_to_evict =
1216  code_cache_accessor->computeNumEntriesToEvict(g_fraction_code_cache_to_evict);
1217  code_cache_accessor->evictEntries(num_entries_to_evict);
1218  compilation_context = CodeGenerator::generateNativeGPUCode(this,
1219  query_func,
1220  multifrag_query_func,
1221  live_funcs,
1222  is_gpu_smem_used,
1223  co,
1224  gpu_target);
1225  } else {
1226  throw;
1227  }
1228  }
1229  QueryEngine::getInstance()->gpu_code_accessor->put(key, compilation_context);
1230  return std::dynamic_pointer_cast<CompilationContext>(compilation_context);
1231 #else
1232  return nullptr;
1233 #endif
1234 }
1235 
1236 std::string CodeGenerator::generatePTX(const std::string& cuda_llir,
1237  llvm::TargetMachine* nvptx_target_machine,
1238  llvm::LLVMContext& context) {
1239  auto timer = DEBUG_TIMER(__func__);
1240  auto mem_buff = llvm::MemoryBuffer::getMemBuffer(cuda_llir, "", false);
1241 
1242  llvm::SMDiagnostic parse_error;
1243 
1244  auto llvm_module = llvm::parseIR(mem_buff->getMemBufferRef(), parse_error, context);
1245  if (!llvm_module) {
1246  LOG(IR) << "CodeGenerator::generatePTX:NVVM IR:\n" << cuda_llir << "\nEnd of NNVM IR";
1247  throw_parseIR_error(parse_error, "generatePTX", /* is_gpu= */ true);
1248  }
1249 
1250  llvm::SmallString<256> code_str;
1251  llvm::raw_svector_ostream formatted_os(code_str);
1252  CHECK(nvptx_target_machine);
1253  {
1254  llvm::legacy::PassManager ptxgen_pm;
1255  llvm_module->setDataLayout(nvptx_target_machine->createDataLayout());
1256 
1257 #if LLVM_VERSION_MAJOR >= 10
1258  nvptx_target_machine->addPassesToEmitFile(
1259  ptxgen_pm, formatted_os, nullptr, llvm::CGFT_AssemblyFile);
1260 #else
1261  nvptx_target_machine->addPassesToEmitFile(
1262  ptxgen_pm, formatted_os, nullptr, llvm::TargetMachine::CGFT_AssemblyFile);
1263 #endif
1264  ptxgen_pm.run(*llvm_module);
1265  }
1266 
1267 #if LLVM_VERSION_MAJOR >= 11
1268  return std::string(code_str);
1269 #else
1270  return code_str.str();
1271 #endif
1272 }
1273 
1275 
1276 std::unique_ptr<llvm::TargetMachine> CodeGenerator::initializeNVPTXBackend(
1278  auto timer = DEBUG_TIMER(__func__);
1279 
1280  std::lock_guard<std::mutex> lock(initialize_nvptx_mutex_);
1281 
1282  llvm::InitializeAllTargets();
1283  llvm::InitializeAllTargetMCs();
1284  llvm::InitializeAllAsmPrinters();
1285  std::string err;
1286  auto target = llvm::TargetRegistry::lookupTarget("nvptx64", err);
1287  if (!target) {
1288  LOG(FATAL) << err;
1289  }
1290  return std::unique_ptr<llvm::TargetMachine>(
1291  target->createTargetMachine("nvptx64-nvidia-cuda",
1293  "",
1294  llvm::TargetOptions(),
1295  llvm::Reloc::Static));
1296 }
1297 
1298 std::string Executor::generatePTX(const std::string& cuda_llir) const {
1300  cuda_llir, nvptx_target_machine_.get(), cgen_state_->context_);
1301 }
1302 
1303 void Executor::initializeNVPTXBackend() const {
1304  if (nvptx_target_machine_) {
1305  return;
1306  }
1307  const auto arch = cudaMgr()->getDeviceArch();
1308  nvptx_target_machine_ = CodeGenerator::initializeNVPTXBackend(arch);
1309 }
1310 
1311 // A small number of runtime functions don't get through CgenState::emitCall. List them
1312 // explicitly here and always clone their implementation from the runtime module.
1313 constexpr std::array<std::string_view, 18> TARGET_RUNTIME_FUNCTIONS_FOR_MODULE_CLONING{
1314  {"query_stub_hoisted_literals",
1315  "multifrag_query_hoisted_literals",
1316  "query_stub",
1317  "multifrag_query",
1318  "fixed_width_int_decode",
1319  "fixed_width_unsigned_decode",
1320  "diff_fixed_width_int_decode",
1321  "fixed_width_double_decode",
1322  "fixed_width_float_decode",
1323  "fixed_width_small_date_decode",
1324  "record_error_code",
1325  "get_error_code",
1326  "pos_start_impl",
1327  "pos_step_impl",
1328  "group_buff_idx_impl",
1329  "init_shared_mem",
1330  "init_shared_mem_nop",
1331  "write_back_nop"}};
1332 bool CodeGenerator::alwaysCloneRuntimeFunction(const llvm::Function* func) {
1333  auto const candidate_func_name = func->getName().str();
1336  [candidate_func_name](std::string_view func_name) {
1337  return candidate_func_name == func_name;
1338  });
1339 }
1340 
1341 std::unique_ptr<llvm::Module> read_llvm_module_from_bc_file(
1342  const std::string& bc_filename,
1343  llvm::LLVMContext& context) {
1344  llvm::SMDiagnostic err;
1345 
1346  auto buffer_or_error = llvm::MemoryBuffer::getFile(bc_filename);
1347  CHECK(!buffer_or_error.getError()) << "bc_filename=" << bc_filename;
1348  llvm::MemoryBuffer* buffer = buffer_or_error.get().get();
1349 
1350  auto owner = llvm::parseBitcodeFile(buffer->getMemBufferRef(), context);
1351  CHECK(!owner.takeError());
1352  CHECK(owner->get());
1353  return std::move(owner.get());
1354 }
1355 
1356 std::unique_ptr<llvm::Module> read_llvm_module_from_ir_file(
1357  const std::string& udf_ir_filename,
1358  llvm::LLVMContext& ctx,
1359  bool is_gpu = false) {
1360  llvm::SMDiagnostic parse_error;
1361 
1362  llvm::StringRef file_name_arg(udf_ir_filename);
1363 
1364  auto owner = llvm::parseIRFile(file_name_arg, parse_error, ctx);
1365  if (!owner) {
1366  throw_parseIR_error(parse_error, udf_ir_filename, is_gpu);
1367  }
1368 
1369  if (is_gpu) {
1370  llvm::Triple gpu_triple(owner->getTargetTriple());
1371  if (!gpu_triple.isNVPTX()) {
1372  LOG(WARNING)
1373  << "Expected triple nvptx64-nvidia-cuda for NVVM IR of loadtime UDFs but got "
1374  << gpu_triple.str() << ". Disabling the NVVM IR module.";
1375  return std::unique_ptr<llvm::Module>();
1376  }
1377  }
1378  return owner;
1379 }
1380 
1381 std::unique_ptr<llvm::Module> read_llvm_module_from_ir_string(
1382  const std::string& udf_ir_string,
1383  llvm::LLVMContext& ctx,
1384  bool is_gpu = false) {
1385  llvm::SMDiagnostic parse_error;
1386 
1387  auto buf = std::make_unique<llvm::MemoryBufferRef>(udf_ir_string,
1388  "Runtime UDF/UDTF LLVM/NVVM IR");
1389 
1390  auto owner = llvm::parseIR(*buf, parse_error, ctx);
1391  if (!owner) {
1392  LOG(IR) << "read_llvm_module_from_ir_string:\n"
1393  << udf_ir_string << "\nEnd of LLVM/NVVM IR";
1394  throw_parseIR_error(parse_error, "", /* is_gpu= */ is_gpu);
1395  }
1396 
1397  if (is_gpu) {
1398  llvm::Triple gpu_triple(owner->getTargetTriple());
1399  if (!gpu_triple.isNVPTX()) {
1400  LOG(IR) << "read_llvm_module_from_ir_string:\n"
1401  << udf_ir_string << "\nEnd of NNVM IR";
1402  LOG(WARNING) << "Expected triple nvptx64-nvidia-cuda for NVVM IR but got "
1403  << gpu_triple.str()
1404  << ". Executing runtime UDF/UDTFs on GPU will be disabled.";
1405  return std::unique_ptr<llvm::Module>();
1406  ;
1407  }
1408  }
1409  return owner;
1410 }
1411 
1412 namespace {
1413 
1414 void bind_pos_placeholders(const std::string& pos_fn_name,
1415  const bool use_resume_param,
1416  llvm::Function* query_func,
1417  llvm::Module* llvm_module) {
1418  for (auto it = llvm::inst_begin(query_func), e = llvm::inst_end(query_func); it != e;
1419  ++it) {
1420  if (!llvm::isa<llvm::CallInst>(*it)) {
1421  continue;
1422  }
1423  auto& pos_call = llvm::cast<llvm::CallInst>(*it);
1424  auto const func_name = CodegenUtil::getCalledFunctionName(pos_call);
1425  if (func_name && *func_name == pos_fn_name) {
1426  if (use_resume_param) {
1427  auto* const row_index_resume = get_arg_by_name(query_func, "row_index_resume");
1428  llvm::ReplaceInstWithInst(
1429  &pos_call,
1430  llvm::CallInst::Create(llvm_module->getFunction(pos_fn_name + "_impl"),
1431  row_index_resume));
1432  } else {
1433  llvm::ReplaceInstWithInst(
1434  &pos_call,
1435  llvm::CallInst::Create(llvm_module->getFunction(pos_fn_name + "_impl")));
1436  }
1437  break;
1438  }
1439  }
1440 }
1441 
1442 void set_row_func_argnames(llvm::Function* row_func,
1443  const size_t in_col_count,
1444  const size_t agg_col_count,
1445  const bool hoist_literals) {
1446  auto arg_it = row_func->arg_begin();
1447 
1448  if (agg_col_count) {
1449  for (size_t i = 0; i < agg_col_count; ++i) {
1450  arg_it->setName("out");
1451  ++arg_it;
1452  }
1453  } else {
1454  arg_it->setName("group_by_buff");
1455  ++arg_it;
1456  arg_it->setName("varlen_output_buff");
1457  ++arg_it;
1458  arg_it->setName("crt_matched");
1459  ++arg_it;
1460  arg_it->setName("total_matched");
1461  ++arg_it;
1462  arg_it->setName("old_total_matched");
1463  ++arg_it;
1464  arg_it->setName("max_matched");
1465  ++arg_it;
1466  }
1467 
1468  arg_it->setName("agg_init_val");
1469  ++arg_it;
1470 
1471  arg_it->setName("pos");
1472  ++arg_it;
1473 
1474  arg_it->setName("frag_row_off");
1475  ++arg_it;
1476 
1477  arg_it->setName("num_rows_per_scan");
1478  ++arg_it;
1479 
1480  if (hoist_literals) {
1481  arg_it->setName("literals");
1482  ++arg_it;
1483  }
1484 
1485  for (size_t i = 0; i < in_col_count; ++i) {
1486  arg_it->setName("col_buf" + std::to_string(i));
1487  ++arg_it;
1488  }
1489 
1490  arg_it->setName("join_hash_tables");
1491  ++arg_it;
1492  arg_it->setName("row_func_mgr");
1493 }
1494 
1495 llvm::Function* create_row_function(const size_t in_col_count,
1496  const size_t agg_col_count,
1497  const bool hoist_literals,
1498  llvm::Module* llvm_module,
1499  llvm::LLVMContext& context) {
1500  std::vector<llvm::Type*> row_process_arg_types;
1501 
1502  if (agg_col_count) {
1503  // output (aggregate) arguments
1504  for (size_t i = 0; i < agg_col_count; ++i) {
1505  row_process_arg_types.push_back(llvm::Type::getInt64PtrTy(context));
1506  }
1507  } else {
1508  // group by buffer
1509  row_process_arg_types.push_back(llvm::Type::getInt64PtrTy(context));
1510  // varlen output buffer
1511  row_process_arg_types.push_back(llvm::Type::getInt64PtrTy(context));
1512  // current match count
1513  row_process_arg_types.push_back(llvm::Type::getInt32PtrTy(context));
1514  // total match count passed from the caller
1515  row_process_arg_types.push_back(llvm::Type::getInt32PtrTy(context));
1516  // old total match count returned to the caller
1517  row_process_arg_types.push_back(llvm::Type::getInt32PtrTy(context));
1518  // max matched (total number of slots in the output buffer)
1519  row_process_arg_types.push_back(llvm::Type::getInt32PtrTy(context));
1520  }
1521 
1522  // aggregate init values
1523  row_process_arg_types.push_back(llvm::Type::getInt64PtrTy(context));
1524 
1525  // position argument
1526  row_process_arg_types.push_back(llvm::Type::getInt64Ty(context));
1527 
1528  // fragment row offset argument
1529  row_process_arg_types.push_back(llvm::Type::getInt64PtrTy(context));
1530 
1531  // number of rows for each scan
1532  row_process_arg_types.push_back(llvm::Type::getInt64PtrTy(context));
1533 
1534  // literals buffer argument
1535  if (hoist_literals) {
1536  row_process_arg_types.push_back(llvm::Type::getInt8PtrTy(context));
1537  }
1538 
1539  // column buffer arguments
1540  for (size_t i = 0; i < in_col_count; ++i) {
1541  row_process_arg_types.emplace_back(llvm::Type::getInt8PtrTy(context));
1542  }
1543 
1544  // join hash table argument
1545  row_process_arg_types.push_back(llvm::Type::getInt64PtrTy(context));
1546 
1547  // row function manager
1548  row_process_arg_types.push_back(llvm::Type::getInt8PtrTy(context));
1549 
1550  // generate the function
1551  auto ft =
1552  llvm::FunctionType::get(get_int_type(32, context), row_process_arg_types, false);
1553 
1554  auto row_func = llvm::Function::Create(
1555  ft, llvm::Function::ExternalLinkage, "row_func", llvm_module);
1557  // set the row function argument names; for debugging purposes only
1558  set_row_func_argnames(row_func, in_col_count, agg_col_count, hoist_literals);
1559 
1560  return row_func;
1561 }
1562 
1563 // Iterate through multifrag_query_func, replacing calls to query_fname with query_func.
1564 void bind_query(llvm::Function* query_func,
1565  const std::string& query_fname,
1566  llvm::Function* multifrag_query_func,
1567  llvm::Module* llvm_module) {
1568  std::vector<llvm::CallInst*> query_stubs;
1569  for (auto it = llvm::inst_begin(multifrag_query_func),
1570  e = llvm::inst_end(multifrag_query_func);
1571  it != e;
1572  ++it) {
1573  if (!llvm::isa<llvm::CallInst>(*it)) {
1574  continue;
1575  }
1576  auto& query_call = llvm::cast<llvm::CallInst>(*it);
1577  auto const call_func_name = CodegenUtil::getCalledFunctionName(query_call);
1578  if (call_func_name && *call_func_name == query_fname) {
1579  query_stubs.push_back(&query_call);
1580  }
1581  }
1582  for (auto& S : query_stubs) {
1583  std::vector<llvm::Value*> args;
1584  for (size_t i = 0; i < S->getNumOperands() - 1; ++i) {
1585  args.push_back(S->getArgOperand(i));
1586  }
1587  llvm::ReplaceInstWithInst(S, llvm::CallInst::Create(query_func, args, ""));
1588  }
1589 }
1590 
1591 std::vector<std::string> get_agg_fnames(const std::vector<Analyzer::Expr*>& target_exprs,
1592  const bool is_group_by) {
1593  std::vector<std::string> result;
1594  for (size_t target_idx = 0, agg_col_idx = 0; target_idx < target_exprs.size();
1595  ++target_idx, ++agg_col_idx) {
1596  const auto target_expr = target_exprs[target_idx];
1597  CHECK(target_expr);
1598  const auto target_type_info = target_expr->get_type_info();
1599  const auto agg_expr = dynamic_cast<Analyzer::AggExpr*>(target_expr);
1600  const bool is_varlen =
1601  (target_type_info.is_string() &&
1602  target_type_info.get_compression() == kENCODING_NONE) ||
1603  target_type_info.is_array(); // TODO: should it use is_varlen_array() ?
1604  if (!agg_expr || agg_expr->get_aggtype() == kSAMPLE) {
1605  result.emplace_back(target_type_info.is_fp() ? "agg_id_double" : "agg_id");
1606  if (is_varlen) {
1607  result.emplace_back("agg_id");
1608  }
1609  if (target_type_info.is_geometry()) {
1610  result.emplace_back("agg_id");
1611  for (auto i = 2; i < 2 * target_type_info.get_physical_coord_cols(); ++i) {
1612  result.emplace_back("agg_id");
1613  }
1614  }
1615  continue;
1616  }
1617  const auto agg_type = agg_expr->get_aggtype();
1618  SQLTypeInfo agg_type_info;
1619  switch (agg_type) {
1620  case kCOUNT:
1621  case kCOUNT_IF:
1622  agg_type_info = target_type_info;
1623  break;
1624  default:
1625  agg_type_info = agg_expr->get_arg()->get_type_info();
1626  break;
1627  }
1628  switch (agg_type) {
1629  case kAVG: {
1630  if (!agg_type_info.is_integer() && !agg_type_info.is_decimal() &&
1631  !agg_type_info.is_fp()) {
1632  throw std::runtime_error("AVG is only valid on integer and floating point");
1633  }
1634  result.emplace_back((agg_type_info.is_integer() || agg_type_info.is_time())
1635  ? "agg_sum"
1636  : "agg_sum_double");
1637  result.emplace_back((agg_type_info.is_integer() || agg_type_info.is_time())
1638  ? "agg_count"
1639  : "agg_count_double");
1640  break;
1641  }
1642  case kMIN: {
1643  if (agg_type_info.is_string() || agg_type_info.is_array() ||
1644  agg_type_info.is_geometry()) {
1645  throw std::runtime_error(
1646  "MIN on strings, arrays or geospatial types not supported yet");
1647  }
1648  result.emplace_back((agg_type_info.is_integer() || agg_type_info.is_time())
1649  ? "agg_min"
1650  : "agg_min_double");
1651  break;
1652  }
1653  case kMAX: {
1654  if (agg_type_info.is_string() || agg_type_info.is_array() ||
1655  agg_type_info.is_geometry()) {
1656  throw std::runtime_error(
1657  "MAX on strings, arrays or geospatial types not supported yet");
1658  }
1659  result.emplace_back((agg_type_info.is_integer() || agg_type_info.is_time())
1660  ? "agg_max"
1661  : "agg_max_double");
1662  break;
1663  }
1664  case kSUM:
1665  case kSUM_IF: {
1666  if (!agg_type_info.is_integer() && !agg_type_info.is_decimal() &&
1667  !agg_type_info.is_fp()) {
1668  throw std::runtime_error(
1669  "SUM and SUM_IF is only valid on integer and floating point");
1670  }
1671  std::string func_name = (agg_type_info.is_integer() || agg_type_info.is_time())
1672  ? "agg_sum"
1673  : "agg_sum_double";
1674  if (agg_type == kSUM_IF) {
1675  func_name += "_if";
1676  }
1677  result.emplace_back(func_name);
1678  break;
1679  }
1680  case kCOUNT:
1681  result.emplace_back(agg_expr->get_is_distinct() ? "agg_count_distinct"
1682  : "agg_count");
1683  break;
1685  result.emplace_back("agg_count_if");
1686  break;
1687  case kSINGLE_VALUE: {
1688  result.emplace_back(agg_type_info.is_fp() ? "agg_id_double" : "agg_id");
1689  break;
1690  }
1691  case kSAMPLE: {
1692  // Note that varlen SAMPLE arguments are handled separately above
1693  result.emplace_back(agg_type_info.is_fp() ? "agg_id_double" : "agg_id");
1694  break;
1695  }
1697  result.emplace_back("agg_approximate_count_distinct");
1698  break;
1699  case kAPPROX_QUANTILE:
1700  result.emplace_back("agg_approx_quantile");
1701  break;
1702  case kMODE:
1703  result.emplace_back("agg_mode_func");
1704  break;
1705  default:
1706  UNREACHABLE() << "Usupported agg_type: " << agg_type;
1707  }
1708  }
1709  return result;
1710 }
1711 
1712 } // namespace
1713 
1714 void Executor::addUdfIrToModule(const std::string& udf_ir_filename,
1715  const bool is_cuda_ir) {
1719  udf_ir_filename;
1720 }
1721 
1722 std::unordered_set<llvm::Function*> CodeGenerator::markDeadRuntimeFuncs(
1723  llvm::Module& llvm_module,
1724  const std::vector<llvm::Function*>& roots,
1725  const std::vector<llvm::Function*>& leaves) {
1726  auto timer = DEBUG_TIMER(__func__);
1727  std::unordered_set<llvm::Function*> live_funcs;
1728  live_funcs.insert(roots.begin(), roots.end());
1729  live_funcs.insert(leaves.begin(), leaves.end());
1730 
1731  if (auto F = llvm_module.getFunction("init_shared_mem_nop")) {
1732  live_funcs.insert(F);
1733  }
1734  if (auto F = llvm_module.getFunction("write_back_nop")) {
1735  live_funcs.insert(F);
1736  }
1738  for (const llvm::Function* F : roots) {
1739  for (const llvm::BasicBlock& BB : *F) {
1740  for (const llvm::Instruction& I : BB) {
1741  if (const llvm::CallInst* CI = llvm::dyn_cast<const llvm::CallInst>(&I)) {
1742  live_funcs.insert(CI->getCalledFunction());
1743  }
1744  }
1745  }
1746  }
1747 
1748  for (llvm::Function& F : llvm_module) {
1749  if (!live_funcs.count(&F) && !F.isDeclaration()) {
1750  F.setLinkage(llvm::GlobalValue::InternalLinkage);
1751  }
1752  }
1753 
1754  return live_funcs;
1755 }
1756 
1757 namespace {
1758 // searches for a particular variable within a specific basic block (or all if bb_name is
1759 // empty)
1760 template <typename InstType>
1761 llvm::Value* find_variable_in_basic_block(llvm::Function* func,
1762  std::string bb_name,
1763  std::string variable_name) {
1764  llvm::Value* result = nullptr;
1765  if (func == nullptr || variable_name.empty()) {
1766  return result;
1767  }
1768  bool is_found = false;
1769  for (auto bb_it = func->begin(); bb_it != func->end() && !is_found; ++bb_it) {
1770  if (!bb_name.empty() && bb_it->getName() != bb_name) {
1771  continue;
1772  }
1773  for (auto inst_it = bb_it->begin(); inst_it != bb_it->end(); inst_it++) {
1774  if (llvm::isa<InstType>(*inst_it)) {
1775  if (inst_it->getName() == variable_name) {
1776  result = &*inst_it;
1777  is_found = true;
1778  break;
1779  }
1780  }
1781  }
1782  }
1783  return result;
1784 }
1785 }; // namespace
1786 
1788  llvm::Function* query_func,
1789  bool run_with_dynamic_watchdog,
1790  bool run_with_allowing_runtime_interrupt,
1791  const std::vector<JoinLoop>& join_loops,
1792  ExecutorDeviceType device_type,
1793  const std::vector<InputTableInfo>& input_table_infos) {
1794  AUTOMATIC_IR_METADATA(cgen_state_.get());
1795 
1796  // check whether the row processing was successful; currently, it can
1797  // fail by running out of group by buffer slots
1798 
1799  if (run_with_dynamic_watchdog && run_with_allowing_runtime_interrupt) {
1800  // when both dynamic watchdog and runtime interrupt turns on
1801  // we use dynamic watchdog
1802  run_with_allowing_runtime_interrupt = false;
1803  }
1804 
1805  {
1806  // disable injecting query interrupt checker if the session info is invalid
1808  executor_session_mutex_);
1809  if (current_query_session_.empty()) {
1810  run_with_allowing_runtime_interrupt = false;
1811  }
1812  }
1813 
1814  llvm::Value* row_count = nullptr;
1815  if ((run_with_dynamic_watchdog || run_with_allowing_runtime_interrupt) &&
1816  device_type == ExecutorDeviceType::GPU) {
1817  row_count =
1818  find_variable_in_basic_block<llvm::LoadInst>(query_func, ".entry", "row_count");
1819  }
1820 
1821  bool done_splitting = false;
1822  for (auto bb_it = query_func->begin(); bb_it != query_func->end() && !done_splitting;
1823  ++bb_it) {
1824  llvm::Value* pos = nullptr;
1825  for (auto inst_it = bb_it->begin(); inst_it != bb_it->end(); ++inst_it) {
1826  if ((run_with_dynamic_watchdog || run_with_allowing_runtime_interrupt) &&
1827  llvm::isa<llvm::PHINode>(*inst_it)) {
1828  if (inst_it->getName() == "pos") {
1829  pos = &*inst_it;
1830  }
1831  continue;
1832  }
1833  if (!llvm::isa<llvm::CallInst>(*inst_it)) {
1834  continue;
1835  }
1836  auto& row_func_call = llvm::cast<llvm::CallInst>(*inst_it);
1837  auto const row_func_name = CodegenUtil::getCalledFunctionName(row_func_call);
1838  if (row_func_name && *row_func_name == "row_process") {
1839  auto next_inst_it = inst_it;
1840  ++next_inst_it;
1841  auto new_bb = bb_it->splitBasicBlock(next_inst_it);
1842  auto& br_instr = bb_it->back();
1843  llvm::IRBuilder<> ir_builder(&br_instr);
1844  llvm::Value* err_lv = &*inst_it;
1845  llvm::Value* err_lv_returned_from_row_func = nullptr;
1846  if (run_with_dynamic_watchdog) {
1847  CHECK(pos);
1848  llvm::Value* call_watchdog_lv = nullptr;
1849  if (device_type == ExecutorDeviceType::GPU) {
1850  // In order to make sure all threads within a block see the same barrier,
1851  // only those blocks whose none of their threads have experienced the critical
1852  // edge will go through the dynamic watchdog computation
1853  CHECK(row_count);
1854  auto crit_edge_rem =
1855  (blockSize() & (blockSize() - 1))
1856  ? ir_builder.CreateSRem(
1857  row_count,
1858  cgen_state_->llInt(static_cast<int64_t>(blockSize())))
1859  : ir_builder.CreateAnd(
1860  row_count,
1861  cgen_state_->llInt(static_cast<int64_t>(blockSize() - 1)));
1862  auto crit_edge_threshold = ir_builder.CreateSub(row_count, crit_edge_rem);
1863  crit_edge_threshold->setName("crit_edge_threshold");
1864 
1865  // only those threads where pos < crit_edge_threshold go through dynamic
1866  // watchdog call
1867  call_watchdog_lv =
1868  ir_builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, pos, crit_edge_threshold);
1869  } else {
1870  // CPU path: run watchdog for every 64th row
1871  auto dw_predicate = ir_builder.CreateAnd(pos, uint64_t(0x3f));
1872  call_watchdog_lv = ir_builder.CreateICmp(
1873  llvm::ICmpInst::ICMP_EQ, dw_predicate, cgen_state_->llInt(int64_t(0LL)));
1874  }
1875  CHECK(call_watchdog_lv);
1876  auto error_check_bb = bb_it->splitBasicBlock(
1877  llvm::BasicBlock::iterator(br_instr), ".error_check");
1878  auto& watchdog_br_instr = bb_it->back();
1879 
1880  auto watchdog_check_bb = llvm::BasicBlock::Create(
1881  cgen_state_->context_, ".watchdog_check", query_func, error_check_bb);
1882  llvm::IRBuilder<> watchdog_ir_builder(watchdog_check_bb);
1883  auto detected_timeout = watchdog_ir_builder.CreateCall(
1884  cgen_state_->module_->getFunction("dynamic_watchdog"), {});
1885  auto timeout_err_lv = watchdog_ir_builder.CreateSelect(
1886  detected_timeout,
1887  cgen_state_->llInt(int32_t(ErrorCode::OUT_OF_TIME)),
1888  err_lv);
1889  watchdog_ir_builder.CreateBr(error_check_bb);
1890 
1891  llvm::ReplaceInstWithInst(
1892  &watchdog_br_instr,
1893  llvm::BranchInst::Create(
1894  watchdog_check_bb, error_check_bb, call_watchdog_lv));
1895  ir_builder.SetInsertPoint(&br_instr);
1896  auto unified_err_lv = ir_builder.CreatePHI(err_lv->getType(), 2);
1897 
1898  unified_err_lv->addIncoming(timeout_err_lv, watchdog_check_bb);
1899  unified_err_lv->addIncoming(err_lv, &*bb_it);
1900  err_lv = unified_err_lv;
1901  } else if (run_with_allowing_runtime_interrupt) {
1902  CHECK(pos);
1903  llvm::Value* call_check_interrupt_lv{nullptr};
1904  llvm::Value* interrupt_err_lv{nullptr};
1905  llvm::BasicBlock* error_check_bb{nullptr};
1906  llvm::BasicBlock* interrupt_check_bb{nullptr};
1907  llvm::Instruction* check_interrupt_br_instr{nullptr};
1908 
1909  auto has_loop_join = std::any_of(
1910  join_loops.begin(), join_loops.end(), [](const JoinLoop& join_loop) {
1911  return join_loop.isNestedLoopJoin();
1912  });
1913  auto codegen_interrupt_checker = [&]() {
1914  error_check_bb = bb_it->splitBasicBlock(llvm::BasicBlock::iterator(br_instr),
1915  ".error_check");
1916  check_interrupt_br_instr = &bb_it->back();
1917 
1918  interrupt_check_bb = llvm::BasicBlock::Create(
1919  cgen_state_->context_, ".interrupt_check", query_func, error_check_bb);
1920  llvm::IRBuilder<> interrupt_checker_ir_builder(interrupt_check_bb);
1921  auto detected_interrupt = interrupt_checker_ir_builder.CreateCall(
1922  cgen_state_->module_->getFunction("check_interrupt"), {});
1923  interrupt_err_lv = interrupt_checker_ir_builder.CreateSelect(
1924  detected_interrupt,
1925  cgen_state_->llInt(int32_t(ErrorCode::INTERRUPTED)),
1926  err_lv);
1927  interrupt_checker_ir_builder.CreateBr(error_check_bb);
1928  };
1929  if (has_loop_join) {
1930  codegen_interrupt_checker();
1931  CHECK(interrupt_check_bb);
1932  CHECK(check_interrupt_br_instr);
1933  llvm::ReplaceInstWithInst(check_interrupt_br_instr,
1934  llvm::BranchInst::Create(interrupt_check_bb));
1935  ir_builder.SetInsertPoint(&br_instr);
1936  err_lv = interrupt_err_lv;
1937  } else {
1938  if (device_type == ExecutorDeviceType::GPU) {
1939  // approximate how many times the %pos variable
1940  // is increased --> the number of iteration
1941  // here we calculate the # bit shift by considering grid/block/fragment
1942  // sizes since if we use the fixed one (i.e., per 64-th increment) some CUDA
1943  // threads cannot enter the interrupt checking block depending on the
1944  // fragment size --> a thread may not take care of 64 threads if an outer
1945  // table is not sufficiently large, and so cannot be interrupted
1946  int32_t num_shift_by_gridDim = shared::getExpOfTwo(gridSize());
1947  int32_t num_shift_by_blockDim = shared::getExpOfTwo(blockSize());
1948  int64_t total_num_shift = num_shift_by_gridDim + num_shift_by_blockDim;
1949  uint64_t interrupt_checking_freq = 32;
1950  auto freq_control_knob = g_running_query_interrupt_freq;
1951  CHECK_GT(freq_control_knob, 0);
1952  CHECK_LE(freq_control_knob, 1.0);
1953  if (!input_table_infos.empty()) {
1954  const auto& outer_table_info = *input_table_infos.begin();
1955  auto num_outer_table_tuples =
1956  outer_table_info.info.getFragmentNumTuplesUpperBound();
1957  if (num_outer_table_tuples > 0) {
1958  // gridSize * blockSize --> pos_step (idx of the next row per thread)
1959  // we additionally multiply two to pos_step since the number of
1960  // dispatched blocks are double of the gridSize
1961  // # tuples (of fragment) / pos_step --> maximum # increment (K)
1962  // also we multiply 1 / freq_control_knob to K to control the frequency
1963  // So, needs to check the interrupt status more frequently? make K
1964  // smaller
1965  auto max_inc = uint64_t(
1966  floor(num_outer_table_tuples / (gridSize() * blockSize() * 2)));
1967  if (max_inc < 2) {
1968  // too small `max_inc`, so this correction is necessary to make
1969  // `interrupt_checking_freq` be valid (i.e., larger than zero)
1970  max_inc = 2;
1971  }
1972  auto calibrated_inc =
1973  uint64_t(floor(max_inc * (1 - freq_control_knob)));
1974  interrupt_checking_freq =
1975  uint64_t(pow(2, shared::getExpOfTwo(calibrated_inc)));
1976  // add the coverage when interrupt_checking_freq > K
1977  // if so, some threads still cannot be branched to the interrupt checker
1978  // so we manually use smaller but close to the max_inc as freq
1979  if (interrupt_checking_freq > max_inc) {
1980  interrupt_checking_freq = max_inc / 2;
1981  }
1982  if (interrupt_checking_freq < 8) {
1983  // such small freq incurs too frequent interrupt status checking,
1984  // so we fixup to the minimum freq value at some reasonable degree
1985  interrupt_checking_freq = 8;
1986  }
1987  }
1988  }
1989  VLOG(1) << "Set the running query interrupt checking frequency: "
1990  << interrupt_checking_freq;
1991  // check the interrupt flag for every interrupt_checking_freq-th iteration
1992  llvm::Value* pos_shifted_per_iteration =
1993  ir_builder.CreateLShr(pos, cgen_state_->llInt(total_num_shift));
1994  auto interrupt_predicate = ir_builder.CreateAnd(pos_shifted_per_iteration,
1995  interrupt_checking_freq);
1996  call_check_interrupt_lv =
1997  ir_builder.CreateICmp(llvm::ICmpInst::ICMP_EQ,
1998  interrupt_predicate,
1999  cgen_state_->llInt(int64_t(0LL)));
2000  } else {
2001  // CPU path: run interrupt checker for every 64th row
2002  auto interrupt_predicate = ir_builder.CreateAnd(pos, uint64_t(0x3f));
2003  call_check_interrupt_lv =
2004  ir_builder.CreateICmp(llvm::ICmpInst::ICMP_EQ,
2005  interrupt_predicate,
2006  cgen_state_->llInt(int64_t(0LL)));
2007  }
2008  codegen_interrupt_checker();
2009  CHECK(call_check_interrupt_lv);
2010  CHECK(interrupt_err_lv);
2011  CHECK(interrupt_check_bb);
2012  CHECK(error_check_bb);
2013  CHECK(check_interrupt_br_instr);
2014  llvm::ReplaceInstWithInst(
2015  check_interrupt_br_instr,
2016  llvm::BranchInst::Create(
2017  interrupt_check_bb, error_check_bb, call_check_interrupt_lv));
2018  ir_builder.SetInsertPoint(&br_instr);
2019  auto unified_err_lv = ir_builder.CreatePHI(err_lv->getType(), 2);
2020 
2021  unified_err_lv->addIncoming(interrupt_err_lv, interrupt_check_bb);
2022  unified_err_lv->addIncoming(err_lv, &*bb_it);
2023  err_lv = unified_err_lv;
2024  }
2025  }
2026  if (!err_lv_returned_from_row_func) {
2027  err_lv_returned_from_row_func = err_lv;
2028  }
2030  // let kernel execution finish as expected, regardless of the observed error,
2031  // unless it is from the dynamic watchdog where all threads within that block
2032  // return together.
2033  err_lv =
2034  ir_builder.CreateICmp(llvm::ICmpInst::ICMP_EQ,
2035  err_lv,
2036  cgen_state_->llInt(int32_t(ErrorCode::OUT_OF_TIME)));
2037  } else {
2038  err_lv = ir_builder.CreateICmp(llvm::ICmpInst::ICMP_NE,
2039  err_lv,
2040  cgen_state_->llInt(static_cast<int32_t>(0)));
2041  }
2042  auto error_bb = llvm::BasicBlock::Create(
2043  cgen_state_->context_, ".error_exit", query_func, new_bb);
2044  const auto error_code_arg = get_arg_by_name(query_func, "error_code");
2045  llvm::CallInst::Create(
2046  cgen_state_->module_->getFunction("record_error_code"),
2047  std::vector<llvm::Value*>{err_lv_returned_from_row_func, error_code_arg},
2048  "",
2049  error_bb);
2050  llvm::ReturnInst::Create(cgen_state_->context_, error_bb);
2051  llvm::ReplaceInstWithInst(&br_instr,
2052  llvm::BranchInst::Create(error_bb, new_bb, err_lv));
2053  done_splitting = true;
2054  break;
2055  }
2056  }
2057  }
2058  CHECK(done_splitting);
2059 }
2060 
2062  llvm::Module* M = cgen_state_->module_;
2063  if (M->getFunction("allocate_varlen_buffer") == nullptr) {
2064  return;
2065  }
2066 
2067  // read metadata
2068  bool should_track = false;
2069  auto* flag = M->getModuleFlag("manage_memory_buffer");
2070  if (auto* cnt = llvm::mdconst::extract_or_null<llvm::ConstantInt>(flag)) {
2071  if (cnt->getZExtValue() == 1) {
2072  should_track = true;
2073  }
2074  }
2075 
2076  if (!should_track) {
2077  // metadata is not present
2078  return;
2079  }
2080 
2081  LOG(INFO) << "Found 'manage_memory_buffer' metadata.";
2082  llvm::SmallVector<llvm::CallInst*, 4> calls_to_analyze;
2083 
2084  for (llvm::Function& F : *M) {
2085  for (llvm::BasicBlock& BB : F) {
2086  for (llvm::Instruction& I : BB) {
2087  if (llvm::CallInst* CI = llvm::dyn_cast<llvm::CallInst>(&I)) {
2088  // Keep track of calls to "allocate_varlen_buffer" for later processing
2089  auto const called_func_name = CodegenUtil::getCalledFunctionName(*CI);
2090  if (called_func_name && *called_func_name == "allocate_varlen_buffer") {
2091  calls_to_analyze.push_back(CI);
2092  }
2093  }
2094  }
2095  }
2096  }
2097 
2098  // for each call to "allocate_varlen_buffer", check if there's a corresponding
2099  // call to "register_buffer_with_executor_rsm". If not, add a call to it
2100  llvm::IRBuilder<> Builder(cgen_state_->context_);
2101  auto i64 = get_int_type(64, cgen_state_->context_);
2102  auto i8p = get_int_ptr_type(8, cgen_state_->context_);
2103  auto void_ = llvm::Type::getVoidTy(cgen_state_->context_);
2104  llvm::FunctionType* fnty = llvm::FunctionType::get(void_, {i64, i8p}, false);
2105  llvm::FunctionCallee register_buffer_fn =
2106  M->getOrInsertFunction("register_buffer_with_executor_rsm", fnty, {});
2107 
2108  int64_t executor_addr = reinterpret_cast<int64_t>(this);
2109  for (llvm::CallInst* CI : calls_to_analyze) {
2110  bool found = false;
2111  // for each user of the function, check if its a callinst
2112  // and if the callinst is calling "register_buffer_with_executor_rsm"
2113  // if no such instruction exist, add one registering the buffer
2114  for (llvm::User* U : CI->users()) {
2115  if (llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(U)) {
2116  auto const func_name = CodegenUtil::getCalledFunctionName(*call);
2117  if (func_name && *func_name == "register_buffer_with_executor_rsm") {
2118  found = true;
2119  break;
2120  }
2121  }
2122  }
2123  if (!found) {
2124  Builder.SetInsertPoint(CI->getNextNode());
2125  Builder.CreateCall(register_buffer_fn,
2126  {ll_int(executor_addr, cgen_state_->context_), CI});
2127  }
2128  }
2129 }
2130 
2131 std::vector<llvm::Value*> Executor::inlineHoistedLiterals() {
2132  AUTOMATIC_IR_METADATA(cgen_state_.get());
2133 
2134  std::vector<llvm::Value*> hoisted_literals;
2135 
2136  // row_func_ is using literals whose defs have been hoisted up to the query_func_,
2137  // extend row_func_ signature to include extra args to pass these literal values.
2138  std::vector<llvm::Type*> row_process_arg_types;
2139 
2140  for (llvm::Function::arg_iterator I = cgen_state_->row_func_->arg_begin(),
2141  E = cgen_state_->row_func_->arg_end();
2142  I != E;
2143  ++I) {
2144  row_process_arg_types.push_back(I->getType());
2145  }
2146 
2147  for (auto& element : cgen_state_->query_func_literal_loads_) {
2148  for (auto value : element.second) {
2149  row_process_arg_types.push_back(value->getType());
2150  }
2151  }
2152 
2153  auto ft = llvm::FunctionType::get(
2154  get_int_type(32, cgen_state_->context_), row_process_arg_types, false);
2155  auto row_func_with_hoisted_literals =
2156  llvm::Function::Create(ft,
2157  llvm::Function::ExternalLinkage,
2158  "row_func_hoisted_literals",
2159  cgen_state_->row_func_->getParent());
2160 
2161  auto row_func_arg_it = row_func_with_hoisted_literals->arg_begin();
2162  for (llvm::Function::arg_iterator I = cgen_state_->row_func_->arg_begin(),
2163  E = cgen_state_->row_func_->arg_end();
2164  I != E;
2165  ++I) {
2166  if (I->hasName()) {
2167  row_func_arg_it->setName(I->getName());
2168  }
2169  ++row_func_arg_it;
2170  }
2171 
2172  decltype(row_func_with_hoisted_literals) filter_func_with_hoisted_literals{nullptr};
2173  decltype(row_func_arg_it) filter_func_arg_it{nullptr};
2174  if (cgen_state_->filter_func_) {
2175  // filter_func_ is using literals whose defs have been hoisted up to the row_func_,
2176  // extend filter_func_ signature to include extra args to pass these literal values.
2177  std::vector<llvm::Type*> filter_func_arg_types;
2178 
2179  for (llvm::Function::arg_iterator I = cgen_state_->filter_func_->arg_begin(),
2180  E = cgen_state_->filter_func_->arg_end();
2181  I != E;
2182  ++I) {
2183  filter_func_arg_types.push_back(I->getType());
2184  }
2185 
2186  for (auto& element : cgen_state_->query_func_literal_loads_) {
2187  for (auto value : element.second) {
2188  filter_func_arg_types.push_back(value->getType());
2189  }
2190  }
2191 
2192  auto ft2 = llvm::FunctionType::get(
2193  get_int_type(32, cgen_state_->context_), filter_func_arg_types, false);
2194  filter_func_with_hoisted_literals =
2195  llvm::Function::Create(ft2,
2196  llvm::Function::ExternalLinkage,
2197  "filter_func_hoisted_literals",
2198  cgen_state_->filter_func_->getParent());
2199 
2200  filter_func_arg_it = filter_func_with_hoisted_literals->arg_begin();
2201  for (llvm::Function::arg_iterator I = cgen_state_->filter_func_->arg_begin(),
2202  E = cgen_state_->filter_func_->arg_end();
2203  I != E;
2204  ++I) {
2205  if (I->hasName()) {
2206  filter_func_arg_it->setName(I->getName());
2207  }
2208  ++filter_func_arg_it;
2209  }
2210  }
2211 
2212  std::unordered_map<int, std::vector<llvm::Value*>>
2213  query_func_literal_loads_function_arguments,
2214  query_func_literal_loads_function_arguments2;
2215 
2216  for (auto& element : cgen_state_->query_func_literal_loads_) {
2217  std::vector<llvm::Value*> argument_values, argument_values2;
2218 
2219  for (auto value : element.second) {
2220  hoisted_literals.push_back(value);
2221  argument_values.push_back(&*row_func_arg_it);
2222  if (cgen_state_->filter_func_) {
2223  argument_values2.push_back(&*filter_func_arg_it);
2224  cgen_state_->filter_func_args_[&*row_func_arg_it] = &*filter_func_arg_it;
2225  }
2226  if (value->hasName()) {
2227  row_func_arg_it->setName("arg_" + value->getName());
2228  if (cgen_state_->filter_func_) {
2229  filter_func_arg_it->getContext();
2230  filter_func_arg_it->setName("arg_" + value->getName());
2231  }
2232  }
2233  ++row_func_arg_it;
2234  ++filter_func_arg_it;
2235  }
2236 
2237  query_func_literal_loads_function_arguments[element.first] = argument_values;
2238  query_func_literal_loads_function_arguments2[element.first] = argument_values2;
2239  }
2240 
2241  // copy the row_func function body over
2242  // see
2243  // https://stackoverflow.com/questions/12864106/move-function-body-avoiding-full-cloning/18751365
2244  row_func_with_hoisted_literals->getBasicBlockList().splice(
2245  row_func_with_hoisted_literals->begin(),
2246  cgen_state_->row_func_->getBasicBlockList());
2247 
2248  // also replace row_func arguments with the arguments from row_func_hoisted_literals
2249  for (llvm::Function::arg_iterator I = cgen_state_->row_func_->arg_begin(),
2250  E = cgen_state_->row_func_->arg_end(),
2251  I2 = row_func_with_hoisted_literals->arg_begin();
2252  I != E;
2253  ++I) {
2254  I->replaceAllUsesWith(&*I2);
2255  I2->takeName(&*I);
2256  cgen_state_->filter_func_args_.replace(&*I, &*I2);
2257  ++I2;
2258  }
2259 
2260  cgen_state_->row_func_ = row_func_with_hoisted_literals;
2261 
2262  // and finally replace literal placeholders
2263  std::vector<llvm::Instruction*> placeholders;
2264  std::string prefix("__placeholder__literal_");
2265  for (auto it = llvm::inst_begin(row_func_with_hoisted_literals),
2266  e = llvm::inst_end(row_func_with_hoisted_literals);
2267  it != e;
2268  ++it) {
2269  if (it->hasName() && it->getName().startswith(prefix)) {
2270  auto offset_and_index_entry =
2271  cgen_state_->row_func_hoisted_literals_.find(llvm::dyn_cast<llvm::Value>(&*it));
2272  CHECK(offset_and_index_entry != cgen_state_->row_func_hoisted_literals_.end());
2273 
2274  int lit_off = offset_and_index_entry->second.offset_in_literal_buffer;
2275  int lit_idx = offset_and_index_entry->second.index_of_literal_load;
2276 
2277  it->replaceAllUsesWith(
2278  query_func_literal_loads_function_arguments[lit_off][lit_idx]);
2279  placeholders.push_back(&*it);
2280  }
2281  }
2282  for (auto placeholder : placeholders) {
2283  placeholder->removeFromParent();
2284  }
2285 
2286  if (cgen_state_->filter_func_) {
2287  // copy the filter_func function body over
2288  // see
2289  // https://stackoverflow.com/questions/12864106/move-function-body-avoiding-full-cloning/18751365
2290  filter_func_with_hoisted_literals->getBasicBlockList().splice(
2291  filter_func_with_hoisted_literals->begin(),
2292  cgen_state_->filter_func_->getBasicBlockList());
2293 
2294  // also replace filter_func arguments with the arguments from
2295  // filter_func_hoisted_literals
2296  for (llvm::Function::arg_iterator I = cgen_state_->filter_func_->arg_begin(),
2297  E = cgen_state_->filter_func_->arg_end(),
2298  I2 = filter_func_with_hoisted_literals->arg_begin();
2299  I != E;
2300  ++I) {
2301  I->replaceAllUsesWith(&*I2);
2302  I2->takeName(&*I);
2303  ++I2;
2304  }
2305 
2306  cgen_state_->filter_func_ = filter_func_with_hoisted_literals;
2307 
2308  // and finally replace literal placeholders
2309  std::vector<llvm::Instruction*> placeholders;
2310  std::string prefix("__placeholder__literal_");
2311  for (auto it = llvm::inst_begin(filter_func_with_hoisted_literals),
2312  e = llvm::inst_end(filter_func_with_hoisted_literals);
2313  it != e;
2314  ++it) {
2315  if (it->hasName() && it->getName().startswith(prefix)) {
2316  auto offset_and_index_entry = cgen_state_->row_func_hoisted_literals_.find(
2317  llvm::dyn_cast<llvm::Value>(&*it));
2318  CHECK(offset_and_index_entry != cgen_state_->row_func_hoisted_literals_.end());
2319 
2320  int lit_off = offset_and_index_entry->second.offset_in_literal_buffer;
2321  int lit_idx = offset_and_index_entry->second.index_of_literal_load;
2322 
2323  it->replaceAllUsesWith(
2324  query_func_literal_loads_function_arguments2[lit_off][lit_idx]);
2325  placeholders.push_back(&*it);
2326  }
2327  }
2328  for (auto placeholder : placeholders) {
2329  placeholder->removeFromParent();
2330  }
2331  }
2332 
2333  return hoisted_literals;
2334 }
2335 
2336 namespace {
2337 
2338 size_t get_shared_memory_size(const bool shared_mem_used,
2339  const QueryMemoryDescriptor* query_mem_desc_ptr) {
2340  return shared_mem_used
2341  ? (query_mem_desc_ptr->getRowSize() * query_mem_desc_ptr->getEntryCount())
2342  : 0;
2343 }
2344 
2345 bool has_count_expr(RelAlgExecutionUnit const& ra_exe_unit) {
2346  for (auto const expr : ra_exe_unit.target_exprs) {
2347  if (auto const agg_expr = dynamic_cast<Analyzer::AggExpr*>(expr)) {
2348  if (shared::is_any<SQLAgg::kCOUNT, SQLAgg::kCOUNT_IF>(agg_expr->get_aggtype())) {
2349  return true;
2350  }
2351  }
2352  }
2353  return false;
2354 }
2355 
2356 class CaseExprDetector : public ScalarExprVisitor<bool> {
2357  public:
2358  CaseExprDetector() : detect_case_expr_(false) {}
2359 
2360  bool detectCaseExpr(const Analyzer::Expr* expr) const {
2361  visit(expr);
2362  return detect_case_expr_;
2363  }
2364 
2365  protected:
2366  bool visitCaseExpr(const Analyzer::CaseExpr*) const override {
2367  detect_case_expr_ = true;
2368  return true;
2369  }
2370 
2371  private:
2372  mutable bool detect_case_expr_;
2373 };
2374 
2375 bool has_case_expr_within_groupby_expr(RelAlgExecutionUnit const& ra_exe_unit) {
2376  if (ra_exe_unit.groupby_exprs.empty() || !ra_exe_unit.groupby_exprs.front()) {
2377  return false;
2378  }
2379  CaseExprDetector detector;
2380  for (auto expr : ra_exe_unit.groupby_exprs) {
2381  if (detector.detectCaseExpr(expr.get())) {
2382  return true;
2383  }
2384  }
2385  return false;
2386 }
2387 
2388 bool is_gpu_shared_mem_supported(const QueryMemoryDescriptor* query_mem_desc_ptr,
2389  const RelAlgExecutionUnit& ra_exe_unit,
2390  const CudaMgr_Namespace::CudaMgr* cuda_mgr,
2391  const ExecutorDeviceType device_type,
2392  const unsigned cuda_blocksize,
2393  const unsigned num_blocks_per_mp) {
2394  if (device_type == ExecutorDeviceType::CPU) {
2395  return false;
2396  }
2397  if (query_mem_desc_ptr->didOutputColumnar()) {
2398  return false;
2399  }
2400  CHECK(query_mem_desc_ptr);
2401  CHECK(cuda_mgr);
2402  /*
2403  * We only use shared memory strategy if GPU hardware provides native shared
2404  * memory atomics support. From CUDA Toolkit documentation:
2405  * https://docs.nvidia.com/cuda/pascal-tuning-guide/index.html#atomic-ops "Like
2406  * Maxwell, Pascal [and Volta] provides native shared memory atomic operations
2407  * for 32-bit integer arithmetic, along with native 32 or 64-bit compare-and-swap
2408  * (CAS)."
2409  *
2410  */
2411  if (!cuda_mgr->isArchMaxwellOrLaterForAll()) {
2412  return false;
2413  }
2414  if (cuda_mgr->isArchPascal() && !ra_exe_unit.join_quals.empty() &&
2415  has_count_expr(ra_exe_unit) && has_case_expr_within_groupby_expr(ra_exe_unit)) {
2416  return false;
2417  }
2418 
2419  if (query_mem_desc_ptr->getQueryDescriptionType() ==
2422  query_mem_desc_ptr->countDistinctDescriptorsLogicallyEmpty()) {
2423  // TODO: relax this, if necessary
2424  if (cuda_blocksize < query_mem_desc_ptr->getEntryCount()) {
2425  return false;
2426  }
2427  // skip shared memory usage when dealing with 1) variable length targets, 2)
2428  // not a COUNT aggregate
2429  const auto target_infos =
2430  target_exprs_to_infos(ra_exe_unit.target_exprs, *query_mem_desc_ptr);
2431  std::unordered_set<SQLAgg> supported_aggs{kCOUNT, kCOUNT_IF};
2432  if (std::find_if(target_infos.begin(),
2433  target_infos.end(),
2434  [&supported_aggs](const TargetInfo& ti) {
2435  if (ti.sql_type.is_varlen() ||
2436  !supported_aggs.count(ti.agg_kind)) {
2437  return true;
2438  } else {
2439  return false;
2440  }
2441  }) == target_infos.end()) {
2442  return true;
2443  }
2444  }
2445  if (query_mem_desc_ptr->getQueryDescriptionType() ==
2456  if (cuda_blocksize < query_mem_desc_ptr->getEntryCount()) {
2457  return false;
2458  }
2459 
2460  // Fundamentally, we should use shared memory whenever the output buffer
2461  // is small enough so that we can fit it in the shared memory and yet expect
2462  // good occupancy.
2463  // For now, we allow keyless, row-wise layout, and only for perfect hash
2464  // group by operations.
2465  if (query_mem_desc_ptr->hasKeylessHash() &&
2466  query_mem_desc_ptr->countDistinctDescriptorsLogicallyEmpty() &&
2467  !query_mem_desc_ptr->useStreamingTopN()) {
2468  const size_t shared_memory_threshold_bytes = std::min(
2469  g_gpu_smem_threshold == 0 ? SIZE_MAX : g_gpu_smem_threshold,
2470  cuda_mgr->getMinSharedMemoryPerBlockForAllDevices() / num_blocks_per_mp);
2471  const auto output_buffer_size =
2472  query_mem_desc_ptr->getRowSize() * query_mem_desc_ptr->getEntryCount();
2473  if (output_buffer_size > shared_memory_threshold_bytes) {
2474  return false;
2475  }
2476 
2477  // skip shared memory usage when dealing with 1) variable length targets, 2)
2478  // non-basic aggregates (COUNT, SUM, MIN, MAX, AVG)
2479  // TODO: relax this if necessary
2480  const auto target_infos =
2481  target_exprs_to_infos(ra_exe_unit.target_exprs, *query_mem_desc_ptr);
2482  std::unordered_set<SQLAgg> supported_aggs{kCOUNT, kCOUNT_IF};
2484  supported_aggs = {kCOUNT, kCOUNT_IF, kMIN, kMAX, kSUM, kSUM_IF, kAVG};
2485  }
2486  if (std::find_if(target_infos.begin(),
2487  target_infos.end(),
2488  [&supported_aggs](const TargetInfo& ti) {
2489  if (ti.sql_type.is_varlen() ||
2490  !supported_aggs.count(ti.agg_kind)) {
2491  return true;
2492  } else {
2493  return false;
2494  }
2495  }) == target_infos.end()) {
2496  return true;
2497  }
2498  }
2499  }
2500  return false;
2501 }
2502 
2503 #ifndef NDEBUG
2504 std::string serialize_llvm_metadata_footnotes(llvm::Function* query_func,
2505  CgenState* cgen_state) {
2506  std::string llvm_ir;
2507  std::unordered_set<llvm::MDNode*> md;
2508 
2509  // Loop over all instructions in the query function.
2510  for (auto bb_it = query_func->begin(); bb_it != query_func->end(); ++bb_it) {
2511  for (auto instr_it = bb_it->begin(); instr_it != bb_it->end(); ++instr_it) {
2512  llvm::SmallVector<std::pair<unsigned, llvm::MDNode*>, 100> imd;
2513  instr_it->getAllMetadata(imd);
2514  for (auto [kind, node] : imd) {
2515  md.insert(node);
2516  }
2517  }
2518  }
2519 
2520  // Loop over all instructions in the row function.
2521  for (auto bb_it = cgen_state->row_func_->begin(); bb_it != cgen_state->row_func_->end();
2522  ++bb_it) {
2523  for (auto instr_it = bb_it->begin(); instr_it != bb_it->end(); ++instr_it) {
2524  llvm::SmallVector<std::pair<unsigned, llvm::MDNode*>, 100> imd;
2525  instr_it->getAllMetadata(imd);
2526  for (auto [kind, node] : imd) {
2527  md.insert(node);
2528  }
2529  }
2530  }
2531 
2532  // Loop over all instructions in the filter function.
2533  if (cgen_state->filter_func_) {
2534  for (auto bb_it = cgen_state->filter_func_->begin();
2535  bb_it != cgen_state->filter_func_->end();
2536  ++bb_it) {
2537  for (auto instr_it = bb_it->begin(); instr_it != bb_it->end(); ++instr_it) {
2538  llvm::SmallVector<std::pair<unsigned, llvm::MDNode*>, 100> imd;
2539  instr_it->getAllMetadata(imd);
2540  for (auto [kind, node] : imd) {
2541  md.insert(node);
2542  }
2543  }
2544  }
2545  }
2546 
2547  // Sort the metadata by canonical number and convert to text.
2548  if (!md.empty()) {
2549  std::map<size_t, std::string> sorted_strings;
2550  for (auto p : md) {
2551  std::string str;
2552  llvm::raw_string_ostream os(str);
2553  p->print(os, cgen_state->module_, true);
2554  os.flush();
2555  auto fields = split(str, {}, 1);
2556  if (fields.empty() || fields[0].empty()) {
2557  continue;
2558  }
2559  sorted_strings.emplace(std::stoul(fields[0].substr(1)), str);
2560  }
2561  llvm_ir += "\n";
2562  for (auto [id, text] : sorted_strings) {
2563  llvm_ir += text;
2564  llvm_ir += "\n";
2565  }
2566  }
2567 
2568  return llvm_ir;
2569 }
2570 #endif // NDEBUG
2571 } // namespace
2572 
2573 std::tuple<CompilationResult, std::unique_ptr<QueryMemoryDescriptor>>
2574 Executor::compileWorkUnit(const std::vector<InputTableInfo>& query_infos,
2575  const PlanState::DeletedColumnsMap& deleted_cols_map,
2576  const RelAlgExecutionUnit& ra_exe_unit,
2577  const CompilationOptions& co,
2578  const ExecutionOptions& eo,
2579  const CudaMgr_Namespace::CudaMgr* cuda_mgr,
2580  const bool allow_lazy_fetch,
2581  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
2582  const size_t max_groups_buffer_entry_guess,
2583  const int8_t crt_min_byte_width,
2584  const bool has_cardinality_estimation,
2585  ColumnCacheMap& column_cache,
2586  RenderInfo* render_info) {
2587  auto timer = DEBUG_TIMER(__func__);
2588 
2590  if (!cuda_mgr) {
2591  throw QueryMustRunOnCpu();
2592  }
2593  }
2594 
2595 #ifndef NDEBUG
2596  static std::uint64_t counter = 0;
2597  ++counter;
2598  VLOG(1) << "CODEGEN #" << counter << ":";
2599  LOG(IR) << "CODEGEN #" << counter << ":";
2600  LOG(PTX) << "CODEGEN #" << counter << ":";
2601  LOG(ASM) << "CODEGEN #" << counter << ":";
2602 #endif
2603 
2604  // cgenstate_manager uses RAII pattern to manage the live time of
2605  // CgenState instances.
2606  Executor::CgenStateManager cgenstate_manager(*this,
2607  allow_lazy_fetch,
2608  query_infos,
2609  deleted_cols_map,
2610  &ra_exe_unit); // locks compilation_mutex
2611  addTransientStringLiterals(ra_exe_unit, row_set_mem_owner);
2612 
2613  GroupByAndAggregate group_by_and_aggregate(
2614  this,
2615  co.device_type,
2616  ra_exe_unit,
2617  query_infos,
2618  row_set_mem_owner,
2619  has_cardinality_estimation ? std::optional<int64_t>(max_groups_buffer_entry_guess)
2620  : std::nullopt);
2621  auto query_mem_desc =
2622  group_by_and_aggregate.initQueryMemoryDescriptor(eo.allow_multifrag,
2623  max_groups_buffer_entry_guess,
2624  crt_min_byte_width,
2625  render_info,
2627 
2628  if (query_mem_desc->getQueryDescriptionType() ==
2630  !has_cardinality_estimation && (!render_info || !render_info->isInSitu()) &&
2631  !eo.just_explain) {
2632  const auto col_range_info = group_by_and_aggregate.getColRangeInfo();
2633  throw CardinalityEstimationRequired(col_range_info.max - col_range_info.min);
2634  }
2635 
2636  const bool output_columnar = query_mem_desc->didOutputColumnar();
2637  const bool gpu_shared_mem_optimization =
2639  ra_exe_unit,
2640  cuda_mgr,
2641  co.device_type,
2642  cuda_mgr ? this->blockSize() : 1,
2643  cuda_mgr ? this->numBlocksPerMP() : 1);
2644  if (gpu_shared_mem_optimization) {
2645  // disable interleaved bins optimization on the GPU
2646  query_mem_desc->setHasInterleavedBinsOnGpu(false);
2647  LOG(DEBUG1) << "GPU shared memory is used for the " +
2648  query_mem_desc->queryDescTypeToString() + " query(" +
2649  std::to_string(get_shared_memory_size(gpu_shared_mem_optimization,
2650  query_mem_desc.get())) +
2651  " out of " + std::to_string(g_gpu_smem_threshold) + " bytes).";
2652  }
2653 
2654  const GpuSharedMemoryContext gpu_smem_context(
2655  get_shared_memory_size(gpu_shared_mem_optimization, query_mem_desc.get()));
2656 
2658  const size_t num_count_distinct_descs =
2659  query_mem_desc->getCountDistinctDescriptorsSize();
2660  for (size_t i = 0; i < num_count_distinct_descs; i++) {
2661  const auto& count_distinct_descriptor =
2662  query_mem_desc->getCountDistinctDescriptor(i);
2663  if (count_distinct_descriptor.impl_type_ == CountDistinctImplType::UnorderedSet ||
2664  (count_distinct_descriptor.impl_type_ != CountDistinctImplType::Invalid &&
2665  !co.hoist_literals)) {
2666  throw QueryMustRunOnCpu();
2667  }
2668  }
2669 
2670  // we currently do not support varlen projection based on baseline groupby when
2671  // 1) target table is multi-fragmented and 2) multiple gpus are involved for query
2672  // processing in this case, we punt the query to cpu to avoid server crash
2673  for (const auto expr : ra_exe_unit.target_exprs) {
2674  if (auto gby_expr = dynamic_cast<Analyzer::AggExpr*>(expr)) {
2675  bool has_multiple_gpus = cuda_mgr ? cuda_mgr->getDeviceCount() > 1 : false;
2676  if (gby_expr->get_aggtype() == SQLAgg::kSAMPLE && has_multiple_gpus &&
2677  !g_leaf_count) {
2678  std::set<const Analyzer::ColumnVar*,
2679  bool (*)(const Analyzer::ColumnVar*, const Analyzer::ColumnVar*)>
2681  gby_expr->collect_column_var(colvar_set, true);
2682  for (const auto cv : colvar_set) {
2683  if (cv->get_type_info().is_varlen()) {
2684  const auto tbl_key = cv->getTableKey();
2685  std::for_each(query_infos.begin(),
2686  query_infos.end(),
2687  [&tbl_key](const InputTableInfo& input_table_info) {
2688  if (input_table_info.table_key == tbl_key &&
2689  input_table_info.info.fragments.size() > 1) {
2690  throw QueryMustRunOnCpu();
2691  }
2692  });
2693  }
2694  }
2695  }
2696  }
2697  }
2698  }
2699 
2700  // Read the module template and target either CPU or GPU
2701  // by binding the stream position functions to the right implementation:
2702  // stride access for GPU, contiguous for CPU
2703  CHECK(cgen_state_->module_ == nullptr);
2704  cgen_state_->set_module_shallow_copy(get_rt_module(), /*always_clone=*/true);
2705 
2706  auto is_gpu = co.device_type == ExecutorDeviceType::GPU;
2707  if (is_gpu) {
2708  cgen_state_->module_->setDataLayout(get_gpu_data_layout());
2709  cgen_state_->module_->setTargetTriple(get_gpu_target_triple_string());
2710  }
2711  if (has_udf_module(/*is_gpu=*/is_gpu)) {
2713  get_udf_module(/*is_gpu=*/is_gpu), *cgen_state_->module_, cgen_state_.get());
2714  }
2715  if (has_rt_udf_module(/*is_gpu=*/is_gpu)) {
2717  get_rt_udf_module(/*is_gpu=*/is_gpu), *cgen_state_->module_, cgen_state_.get());
2718  }
2719 
2720  AUTOMATIC_IR_METADATA(cgen_state_.get());
2721 
2722  auto agg_fnames =
2723  get_agg_fnames(ra_exe_unit.target_exprs, !ra_exe_unit.groupby_exprs.empty());
2724 
2725  const auto agg_slot_count = ra_exe_unit.estimator ? size_t(1) : agg_fnames.size();
2726 
2727  const bool is_group_by{query_mem_desc->isGroupBy()};
2728  auto [query_func, row_func_call] = is_group_by
2729  ? query_group_by_template(cgen_state_->module_,
2730  co.hoist_literals,
2731  *query_mem_desc,
2732  co.device_type,
2733  ra_exe_unit.scan_limit,
2734  gpu_smem_context)
2735  : query_template(cgen_state_->module_,
2736  agg_slot_count,
2737  co.hoist_literals,
2738  !!ra_exe_unit.estimator,
2739  gpu_smem_context);
2740  bind_pos_placeholders("pos_start", true, query_func, cgen_state_->module_);
2741  bind_pos_placeholders("group_buff_idx", false, query_func, cgen_state_->module_);
2742  bind_pos_placeholders("pos_step", false, query_func, cgen_state_->module_);
2743 
2744  cgen_state_->query_func_ = query_func;
2745  cgen_state_->row_func_call_ = row_func_call;
2746  cgen_state_->query_func_entry_ir_builder_.SetInsertPoint(
2747  &query_func->getEntryBlock().front());
2748 
2749  // Generate the function signature and column head fetches s.t.
2750  // double indirection isn't needed in the inner loop
2751  auto& fetch_bb = query_func->front();
2752  llvm::IRBuilder<> fetch_ir_builder(&fetch_bb);
2753  fetch_ir_builder.SetInsertPoint(&*fetch_bb.begin());
2754  auto col_heads = generate_column_heads_load(ra_exe_unit.input_col_descs.size(),
2755  get_arg_by_name(query_func, "byte_stream"),
2756  fetch_ir_builder,
2757  cgen_state_->context_);
2758  CHECK_EQ(ra_exe_unit.input_col_descs.size(), col_heads.size());
2759 
2760  cgen_state_->row_func_ = create_row_function(ra_exe_unit.input_col_descs.size(),
2761  is_group_by ? 0 : agg_slot_count,
2762  co.hoist_literals,
2763  cgen_state_->module_,
2764  cgen_state_->context_);
2765  CHECK(cgen_state_->row_func_);
2766  cgen_state_->row_func_bb_ =
2767  llvm::BasicBlock::Create(cgen_state_->context_, "entry", cgen_state_->row_func_);
2768 
2770  auto filter_func_ft =
2771  llvm::FunctionType::get(get_int_type(32, cgen_state_->context_), {}, false);
2772  cgen_state_->filter_func_ = llvm::Function::Create(filter_func_ft,
2773  llvm::Function::ExternalLinkage,
2774  "filter_func",
2775  cgen_state_->module_);
2776  CHECK(cgen_state_->filter_func_);
2777  cgen_state_->filter_func_bb_ = llvm::BasicBlock::Create(
2778  cgen_state_->context_, "entry", cgen_state_->filter_func_);
2779  }
2780 
2781  cgen_state_->current_func_ = cgen_state_->row_func_;
2782  cgen_state_->ir_builder_.SetInsertPoint(cgen_state_->row_func_bb_);
2783 
2784  preloadFragOffsets(ra_exe_unit.input_descs, query_infos);
2785  RelAlgExecutionUnit body_execution_unit = ra_exe_unit;
2786  const auto join_loops =
2787  buildJoinLoops(body_execution_unit, co, eo, query_infos, column_cache);
2788 
2789  plan_state_->allocateLocalColumnIds(ra_exe_unit.input_col_descs);
2790  for (auto& simple_qual : ra_exe_unit.simple_quals) {
2791  plan_state_->addSimpleQual(simple_qual);
2792  }
2793  const auto is_not_deleted_bb = codegenSkipDeletedOuterTableRow(ra_exe_unit, co);
2794  if (is_not_deleted_bb) {
2795  cgen_state_->row_func_bb_ = is_not_deleted_bb;
2796  }
2797  if (!join_loops.empty()) {
2798  codegenJoinLoops(join_loops,
2799  body_execution_unit,
2800  group_by_and_aggregate,
2801  query_func,
2802  cgen_state_->row_func_bb_,
2803  *(query_mem_desc.get()),
2804  co,
2805  eo);
2806  } else {
2807  const bool can_return_error = compileBody(
2808  ra_exe_unit, group_by_and_aggregate, *query_mem_desc, co, gpu_smem_context);
2809  if (can_return_error || cgen_state_->needs_error_check_ || eo.with_dynamic_watchdog ||
2811  createErrorCheckControlFlow(query_func,
2814  join_loops,
2815  co.device_type,
2816  group_by_and_aggregate.query_infos_);
2817  }
2818  }
2819  std::vector<llvm::Value*> hoisted_literals;
2820 
2821  if (co.hoist_literals) {
2822  VLOG(1) << "number of hoisted literals: "
2823  << cgen_state_->query_func_literal_loads_.size()
2824  << " / literal buffer usage: " << cgen_state_->getLiteralBufferUsage(0)
2825  << " bytes";
2826  }
2827 
2828  if (co.hoist_literals && !cgen_state_->query_func_literal_loads_.empty()) {
2829  // we have some hoisted literals...
2830  hoisted_literals = inlineHoistedLiterals();
2831  }
2832 
2833  // replace the row func placeholder call with the call to the actual row func
2834  std::vector<llvm::Value*> row_func_args;
2835  for (size_t i = 0; i < cgen_state_->row_func_call_->getNumOperands() - 1; ++i) {
2836  row_func_args.push_back(cgen_state_->row_func_call_->getArgOperand(i));
2837  }
2838  row_func_args.insert(row_func_args.end(), col_heads.begin(), col_heads.end());
2839  row_func_args.push_back(get_arg_by_name(query_func, "join_hash_tables"));
2840  row_func_args.push_back(get_arg_by_name(query_func, "row_func_mgr"));
2841  // push hoisted literals arguments, if any
2842  row_func_args.insert(
2843  row_func_args.end(), hoisted_literals.begin(), hoisted_literals.end());
2844  llvm::ReplaceInstWithInst(
2845  cgen_state_->row_func_call_,
2846  llvm::CallInst::Create(cgen_state_->row_func_, row_func_args, ""));
2847 
2848  // replace the filter func placeholder call with the call to the actual filter func
2849  if (cgen_state_->filter_func_) {
2850  std::vector<llvm::Value*> filter_func_args;
2851  for (auto arg_it = cgen_state_->filter_func_args_.begin();
2852  arg_it != cgen_state_->filter_func_args_.end();
2853  ++arg_it) {
2854  filter_func_args.push_back(arg_it->first);
2855  }
2856  llvm::ReplaceInstWithInst(
2857  cgen_state_->filter_func_call_,
2858  llvm::CallInst::Create(cgen_state_->filter_func_, filter_func_args, ""));
2859  }
2860 
2861  // Aggregate
2862  plan_state_->init_agg_vals_ =
2863  init_agg_val_vec(ra_exe_unit.target_exprs, ra_exe_unit.quals, *query_mem_desc);
2864 
2865  /*
2866  * If we have decided to use GPU shared memory (decision is not made here), then
2867  * we generate proper code for extra components that it needs (buffer initialization and
2868  * gpu reduction from shared memory to global memory). We then replace these functions
2869  * into the already compiled query_func (replacing two placeholders, write_back_nop and
2870  * init_smem_nop). The rest of the code should be as before (row_func, etc.).
2871  */
2872  if (gpu_smem_context.isSharedMemoryUsed()) {
2873  if (query_mem_desc->getQueryDescriptionType() ==
2875  GpuSharedMemCodeBuilder gpu_smem_code(
2876  cgen_state_->module_,
2877  cgen_state_->context_,
2878  *query_mem_desc,
2880  plan_state_->init_agg_vals_,
2881  executor_id_);
2882  gpu_smem_code.codegen();
2883  gpu_smem_code.injectFunctionsInto(query_func);
2884 
2885  // helper functions are used for caching purposes later
2886  cgen_state_->helper_functions_.push_back(gpu_smem_code.getReductionFunction());
2887  cgen_state_->helper_functions_.push_back(gpu_smem_code.getInitFunction());
2888  LOG(IR) << gpu_smem_code.toString();
2889  }
2890  }
2891 
2892  auto multifrag_query_func = cgen_state_->module_->getFunction(
2893  "multifrag_query" + std::string(co.hoist_literals ? "_hoisted_literals" : ""));
2894  CHECK(multifrag_query_func);
2895 
2897  insertErrorCodeChecker(multifrag_query_func,
2898  get_index_by_name(query_func, "error_code"),
2899  co.hoist_literals,
2901  }
2902 
2903  bind_query(query_func,
2904  "query_stub" + std::string(co.hoist_literals ? "_hoisted_literals" : ""),
2905  multifrag_query_func,
2906  cgen_state_->module_);
2907 
2908  std::vector<llvm::Function*> root_funcs{query_func, cgen_state_->row_func_};
2909  if (cgen_state_->filter_func_) {
2910  root_funcs.push_back(cgen_state_->filter_func_);
2911  }
2912  auto live_funcs = CodeGenerator::markDeadRuntimeFuncs(
2913  *cgen_state_->module_, root_funcs, {multifrag_query_func});
2914 
2915  // Always inline the row function and the filter function.
2916  // We don't want register spills in the inner loops.
2917  // LLVM seems to correctly free up alloca instructions
2918  // in these functions even when they are inlined.
2919  mark_function_always_inline(cgen_state_->row_func_);
2920  if (cgen_state_->filter_func_) {
2921  mark_function_always_inline(cgen_state_->filter_func_);
2922  }
2923 
2924 #ifndef NDEBUG
2925  // Add helpful metadata to the LLVM IR for debugging.
2927 #endif
2928 
2929  auto const device_str = co.device_type == ExecutorDeviceType::CPU ? "CPU:\n" : "GPU:\n";
2930  // Serialize the important LLVM IR functions to text for SQL EXPLAIN.
2931  std::string llvm_ir =
2932  serialize_llvm_object(multifrag_query_func) + serialize_llvm_object(query_func) +
2933  serialize_llvm_object(cgen_state_->row_func_) +
2934  (cgen_state_->filter_func_ ? serialize_llvm_object(cgen_state_->filter_func_) : "");
2935  VLOG(3) << "Unoptimized IR for the " << device_str << "\n" << llvm_ir << "\nEnd of IR";
2937 #ifdef WITH_JIT_DEBUG
2938  throw std::runtime_error(
2939  "Explain optimized not available when JIT runtime debug symbols are enabled");
2940 #else
2941  // Note that we don't run the NVVM reflect pass here. Use LOG(IR) to get the
2942  // optimized IR after NVVM reflect
2943  llvm::legacy::PassManager pass_manager;
2944  optimize_ir(query_func,
2945  cgen_state_->module_,
2946  pass_manager,
2947  live_funcs,
2948  gpu_smem_context.isSharedMemoryUsed(),
2949  co);
2950 #endif // WITH_JIT_DEBUG
2951  llvm_ir =
2952  serialize_llvm_object(multifrag_query_func) + serialize_llvm_object(query_func) +
2953  serialize_llvm_object(cgen_state_->row_func_) +
2954  (cgen_state_->filter_func_ ? serialize_llvm_object(cgen_state_->filter_func_)
2955  : "");
2956 #ifndef NDEBUG
2957  llvm_ir += serialize_llvm_metadata_footnotes(query_func, cgen_state_.get());
2958 #endif
2959  }
2960  LOG(IR) << "\n\n" << query_mem_desc->toString() << "\n";
2961  LOG(IR) << "IR for the " << device_str;
2962 #ifdef NDEBUG
2963  LOG(IR) << serialize_llvm_object(query_func)
2964  << serialize_llvm_object(cgen_state_->row_func_)
2965  << (cgen_state_->filter_func_ ? serialize_llvm_object(cgen_state_->filter_func_)
2966  : "")
2967  << "\nEnd of IR";
2968 #else
2969  LOG(IR) << serialize_llvm_object(cgen_state_->module_) << "\nEnd of IR";
2970 #endif
2971  // Insert calls to "register_buffer_with_executor_rsm" for allocations
2972  // in runtime functions (i.e. from RBC) without it
2973  AutoTrackBuffersInRuntimeIR();
2974 
2975  // Run some basic validation checks on the LLVM IR before code is generated below.
2976  verify_function_ir(cgen_state_->row_func_);
2977  if (cgen_state_->filter_func_) {
2978  verify_function_ir(cgen_state_->filter_func_);
2979  }
2980 
2981  // Generate final native code from the LLVM IR.
2982  return std::make_tuple(
2985  ? optimizeAndCodegenCPU(query_func, multifrag_query_func, live_funcs, co)
2986  : optimizeAndCodegenGPU(query_func,
2987  multifrag_query_func,
2988  live_funcs,
2989  is_group_by || ra_exe_unit.estimator,
2990  cuda_mgr,
2991  gpu_smem_context.isSharedMemoryUsed(),
2992  co),
2993  cgen_state_->getLiterals(),
2994  output_columnar,
2995  llvm_ir,
2996  std::move(gpu_smem_context)},
2997  std::move(query_mem_desc));
2998 }
2999 
3000 void Executor::insertErrorCodeChecker(llvm::Function* query_func,
3001  unsigned const error_code_idx,
3002  bool hoist_literals,
3003  bool allow_runtime_query_interrupt) {
3004  auto query_stub_func_name =
3005  "query_stub" + std::string(hoist_literals ? "_hoisted_literals" : "");
3006  for (auto bb_it = query_func->begin(); bb_it != query_func->end(); ++bb_it) {
3007  for (auto inst_it = bb_it->begin(); inst_it != bb_it->end(); ++inst_it) {
3008  if (!llvm::isa<llvm::CallInst>(*inst_it)) {
3009  continue;
3010  }
3011  auto& row_func_call = llvm::cast<llvm::CallInst>(*inst_it);
3012  auto const row_func_name = CodegenUtil::getCalledFunctionName(row_func_call);
3013  if (row_func_name && *row_func_name == query_stub_func_name) {
3014  auto next_inst_it = inst_it;
3015  ++next_inst_it;
3016  auto new_bb = bb_it->splitBasicBlock(next_inst_it);
3017  auto& br_instr = bb_it->back();
3018  llvm::IRBuilder<> ir_builder(&br_instr);
3019  llvm::Value* err_lv = &*inst_it;
3020  auto error_check_bb =
3021  bb_it->splitBasicBlock(llvm::BasicBlock::iterator(br_instr), ".error_check");
3022  // query_func does not have parameter names assigned.
3023  llvm::Value* const error_code_arg = get_arg_by_index(query_func, error_code_idx);
3024  CHECK(error_code_arg) << error_code_idx << '/' << query_func->arg_size();
3025  llvm::Value* err_code = nullptr;
3026  if (allow_runtime_query_interrupt) {
3027  // decide the final error code with a consideration of interrupt status
3028  auto& check_interrupt_br_instr = bb_it->back();
3029  auto interrupt_check_bb = llvm::BasicBlock::Create(
3030  cgen_state_->context_, ".interrupt_check", query_func, error_check_bb);
3031  llvm::IRBuilder<> interrupt_checker_ir_builder(interrupt_check_bb);
3032  auto detected_interrupt = interrupt_checker_ir_builder.CreateCall(
3033  cgen_state_->module_->getFunction("check_interrupt"), {});
3034  auto detected_error = interrupt_checker_ir_builder.CreateCall(
3035  cgen_state_->module_->getFunction("get_error_code"),
3036  std::vector<llvm::Value*>{error_code_arg});
3037  err_code = interrupt_checker_ir_builder.CreateSelect(
3038  detected_interrupt,
3039  cgen_state_->llInt(int32_t(ErrorCode::INTERRUPTED)),
3040  detected_error);
3041  interrupt_checker_ir_builder.CreateBr(error_check_bb);
3042  llvm::ReplaceInstWithInst(&check_interrupt_br_instr,
3043  llvm::BranchInst::Create(interrupt_check_bb));
3044  ir_builder.SetInsertPoint(&br_instr);
3045  } else {
3046  // uses error code returned from row_func and skip to check interrupt status
3047  ir_builder.SetInsertPoint(&br_instr);
3048  err_code =
3049  ir_builder.CreateCall(cgen_state_->module_->getFunction("get_error_code"),
3050  std::vector<llvm::Value*>{error_code_arg});
3051  }
3052  err_lv = ir_builder.CreateICmp(
3053  llvm::ICmpInst::ICMP_NE, err_code, cgen_state_->llInt(0));
3054  auto error_bb = llvm::BasicBlock::Create(
3055  cgen_state_->context_, ".error_exit", query_func, new_bb);
3056  llvm::CallInst::Create(cgen_state_->module_->getFunction("record_error_code"),
3057  std::vector<llvm::Value*>{err_code, error_code_arg},
3058  "",
3059  error_bb);
3060  llvm::ReturnInst::Create(cgen_state_->context_, error_bb);
3061  llvm::ReplaceInstWithInst(&br_instr,
3062  llvm::BranchInst::Create(error_bb, new_bb, err_lv));
3063  break;
3064  }
3065  }
3066  }
3067 }
3068 
3070  const RelAlgExecutionUnit& ra_exe_unit,
3071  const CompilationOptions& co) {
3072  AUTOMATIC_IR_METADATA(cgen_state_.get());
3073  if (!co.filter_on_deleted_column) {
3074  return nullptr;
3075  }
3076  CHECK(!ra_exe_unit.input_descs.empty());
3077  const auto& outer_input_desc = ra_exe_unit.input_descs[0];
3078  if (outer_input_desc.getSourceType() != InputSourceType::TABLE) {
3079  return nullptr;
3080  }
3081  const auto& table_key = outer_input_desc.getTableKey();
3082  const auto deleted_cd = plan_state_->getDeletedColForTable(table_key);
3083  if (!deleted_cd) {
3084  return nullptr;
3085  }
3086  CHECK(deleted_cd->columnType.is_boolean());
3087  const auto deleted_expr =
3088  makeExpr<Analyzer::ColumnVar>(deleted_cd->columnType,
3089  shared::ColumnKey{table_key, deleted_cd->columnId},
3090  outer_input_desc.getNestLevel());
3091  CodeGenerator code_generator(this);
3092  const auto is_deleted =
3093  code_generator.toBool(code_generator.codegen(deleted_expr.get(), true, co).front());
3094  const auto is_deleted_bb = llvm::BasicBlock::Create(
3095  cgen_state_->context_, "is_deleted", cgen_state_->row_func_);
3096  llvm::BasicBlock* bb = llvm::BasicBlock::Create(
3097  cgen_state_->context_, "is_not_deleted", cgen_state_->row_func_);
3098  cgen_state_->ir_builder_.CreateCondBr(is_deleted, is_deleted_bb, bb);
3099  cgen_state_->ir_builder_.SetInsertPoint(is_deleted_bb);
3100  cgen_state_->ir_builder_.CreateRet(cgen_state_->llInt<int32_t>(0));
3101  cgen_state_->ir_builder_.SetInsertPoint(bb);
3102  return bb;
3103 }
3104 
3105 bool Executor::compileBody(const RelAlgExecutionUnit& ra_exe_unit,
3106  GroupByAndAggregate& group_by_and_aggregate,
3108  const CompilationOptions& co,
3109  const GpuSharedMemoryContext& gpu_smem_context) {
3110  AUTOMATIC_IR_METADATA(cgen_state_.get());
3111 
3112  // Switch the code generation into a separate filter function if enabled.
3113  // Note that accesses to function arguments are still codegenned from the
3114  // row function's arguments, then later automatically forwarded and
3115  // remapped into filter function arguments by redeclareFilterFunction().
3116  cgen_state_->row_func_bb_ = cgen_state_->ir_builder_.GetInsertBlock();
3117  llvm::Value* loop_done{nullptr};
3118  std::unique_ptr<Executor::FetchCacheAnchor> fetch_cache_anchor;
3119  if (cgen_state_->filter_func_) {
3120  if (cgen_state_->row_func_bb_->getName() == "loop_body") {
3121  auto row_func_entry_bb = &cgen_state_->row_func_->getEntryBlock();
3122  cgen_state_->ir_builder_.SetInsertPoint(row_func_entry_bb,
3123  row_func_entry_bb->begin());
3124  loop_done = cgen_state_->ir_builder_.CreateAlloca(
3125  get_int_type(1, cgen_state_->context_), nullptr, "loop_done");
3126  cgen_state_->ir_builder_.SetInsertPoint(cgen_state_->row_func_bb_);
3127  cgen_state_->ir_builder_.CreateStore(cgen_state_->llBool(true), loop_done);
3128  }
3129  cgen_state_->ir_builder_.SetInsertPoint(cgen_state_->filter_func_bb_);
3130  cgen_state_->current_func_ = cgen_state_->filter_func_;
3131  fetch_cache_anchor = std::make_unique<Executor::FetchCacheAnchor>(cgen_state_.get());
3132  }
3133 
3134  // generate the code for the filter
3135  std::vector<Analyzer::Expr*> primary_quals;
3136  std::vector<Analyzer::Expr*> deferred_quals;
3137  bool short_circuited = CodeGenerator::prioritizeQuals(
3138  ra_exe_unit, primary_quals, deferred_quals, plan_state_->hoisted_filters_);
3139  if (short_circuited) {
3140  VLOG(1) << "Prioritized " << std::to_string(primary_quals.size()) << " quals, "
3141  << "short-circuited and deferred " << std::to_string(deferred_quals.size())
3142  << " quals";
3143  }
3144  llvm::Value* filter_lv = cgen_state_->llBool(true);
3145  CodeGenerator code_generator(this);
3146  for (auto expr : primary_quals) {
3147  // Generate the filter for primary quals
3148  auto cond = code_generator.toBool(code_generator.codegen(expr, true, co).front());
3149  filter_lv = cgen_state_->ir_builder_.CreateAnd(filter_lv, cond);
3150  }
3151  CHECK(filter_lv->getType()->isIntegerTy(1));
3152  llvm::BasicBlock* sc_false{nullptr};
3153  if (!deferred_quals.empty()) {
3154  auto sc_true = llvm::BasicBlock::Create(
3155  cgen_state_->context_, "sc_true", cgen_state_->current_func_);
3156  sc_false = llvm::BasicBlock::Create(
3157  cgen_state_->context_, "sc_false", cgen_state_->current_func_);
3158  cgen_state_->ir_builder_.CreateCondBr(filter_lv, sc_true, sc_false);
3159  cgen_state_->ir_builder_.SetInsertPoint(sc_false);
3160  if (ra_exe_unit.join_quals.empty()) {
3161  cgen_state_->ir_builder_.CreateRet(cgen_state_->llInt(int32_t(0)));
3162  }
3163  cgen_state_->ir_builder_.SetInsertPoint(sc_true);
3164  filter_lv = cgen_state_->llBool(true);
3165  }
3166  for (auto expr : deferred_quals) {
3167  filter_lv = cgen_state_->ir_builder_.CreateAnd(
3168  filter_lv, code_generator.toBool(code_generator.codegen(expr, true, co).front()));
3169  }
3170 
3171  CHECK(filter_lv->getType()->isIntegerTy(1));
3172  auto ret = group_by_and_aggregate.codegen(
3173  filter_lv, sc_false, query_mem_desc, co, gpu_smem_context);
3174 
3175  // Switch the code generation back to the row function if a filter
3176  // function was enabled.
3177  if (cgen_state_->filter_func_) {
3178  if (cgen_state_->row_func_bb_->getName() == "loop_body") {
3179  cgen_state_->ir_builder_.CreateStore(cgen_state_->llBool(false), loop_done);
3180  cgen_state_->ir_builder_.CreateRet(cgen_state_->llInt<int32_t>(0));
3181  }
3182 
3183  cgen_state_->ir_builder_.SetInsertPoint(cgen_state_->row_func_bb_);
3184  cgen_state_->current_func_ = cgen_state_->row_func_;
3185  cgen_state_->filter_func_call_ =
3186  cgen_state_->ir_builder_.CreateCall(cgen_state_->filter_func_, {});
3187 
3188  // Create real filter function declaration after placeholder call
3189  // is emitted.
3190  redeclareFilterFunction();
3191 
3192  if (cgen_state_->row_func_bb_->getName() == "loop_body") {
3193  auto loop_done_true = llvm::BasicBlock::Create(
3194  cgen_state_->context_, "loop_done_true", cgen_state_->row_func_);
3195  auto loop_done_false = llvm::BasicBlock::Create(
3196  cgen_state_->context_, "loop_done_false", cgen_state_->row_func_);
3197  auto loop_done_flag = cgen_state_->ir_builder_.CreateLoad(
3198  loop_done->getType()->getPointerElementType(), loop_done);
3199  cgen_state_->ir_builder_.CreateCondBr(
3200  loop_done_flag, loop_done_true, loop_done_false);
3201  cgen_state_->ir_builder_.SetInsertPoint(loop_done_true);
3202  cgen_state_->ir_builder_.CreateRet(cgen_state_->filter_func_call_);
3203  cgen_state_->ir_builder_.SetInsertPoint(loop_done_false);
3204  } else {
3205  cgen_state_->ir_builder_.CreateRet(cgen_state_->filter_func_call_);
3206  }
3207  }
3208  return ret;
3209 }
3210 
3211 std::vector<llvm::Value*> generate_column_heads_load(const int num_columns,
3212  llvm::Value* byte_stream_arg,
3213  llvm::IRBuilder<>& ir_builder,
3214  llvm::LLVMContext& ctx) {
3215  CHECK(byte_stream_arg);
3216  const auto max_col_local_id = num_columns - 1;
3217 
3218  std::vector<llvm::Value*> col_heads;
3219  for (int col_id = 0; col_id <= max_col_local_id; ++col_id) {
3220  auto* gep = ir_builder.CreateGEP(
3221  byte_stream_arg->getType()->getScalarType()->getPointerElementType(),
3222  byte_stream_arg,
3223  llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), col_id));
3224  auto* load_gep = ir_builder.CreateLoad(gep->getType()->getPointerElementType(), gep);
3225  load_gep->setName(byte_stream_arg->getName() + "_" + std::to_string(col_id) + "_ptr");
3226  col_heads.emplace_back(load_gep);
3227  }
3228  return col_heads;
3229 }
3230 
void createErrorCheckControlFlow(llvm::Function *query_func, bool run_with_dynamic_watchdog, bool run_with_allowing_runtime_interrupt, const std::vector< JoinLoop > &join_loops, ExecutorDeviceType device_type, const std::vector< InputTableInfo > &input_table_infos)
GroupByPerfectHash
Definition: enums.h:58
std::optional< std::string_view > getCalledFunctionName(llvm::CallInst &call_inst)
std::vector< Analyzer::Expr * > target_exprs
#define CHECK_EQ(x, y)
Definition: Logger.h:301
double g_running_query_interrupt_freq
Definition: Execute.cpp:141
llvm::Value * find_variable_in_basic_block(llvm::Function *func, std::string bb_name, std::string variable_name)
bool g_enable_smem_group_by
std::string get_cuda_libdevice_dir(void)
Definition: CudaMgr.cpp:612
bool is_gpu_shared_mem_supported(const QueryMemoryDescriptor *query_mem_desc_ptr, const RelAlgExecutionUnit &ra_exe_unit, const CudaMgr_Namespace::CudaMgr *cuda_mgr, const ExecutorDeviceType device_type, const unsigned cuda_blocksize, const unsigned num_blocks_per_mp)
bool countDistinctDescriptorsLogicallyEmpty() const
std::unordered_map< shared::TableKey, const ColumnDescriptor * > DeletedColumnsMap
Definition: PlanState.h:44
static bool colvar_comp(const ColumnVar *l, const ColumnVar *r)
Definition: Analyzer.h:215
void mark_function_never_inline(llvm::Function *func)
bool codegen(llvm::Value *filter_result, llvm::BasicBlock *sc_false, QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const GpuSharedMemoryContext &gpu_smem_context)
NonGroupedAggregate
Definition: enums.h:58
void collect_column_var(std::set< const ColumnVar *, bool(*)(const ColumnVar *, const ColumnVar *)> &colvar_set, bool include_agg) const override
Definition: Analyzer.h:222
void optimize_ir(llvm::Function *query_func, llvm::Module *llvm_module, llvm::legacy::PassManager &pass_manager, const std::unordered_set< llvm::Function * > &live_funcs, const bool is_gpu_smem_used, const CompilationOptions &co)
Streaming Top N algorithm.
#define LOG(tag)
Definition: Logger.h:285
void eliminate_dead_self_recursive_funcs(llvm::Module &M, const std::unordered_set< llvm::Function * > &live_funcs)
void AutoTrackBuffersInRuntimeIR()
void checkCudaErrors(CUresult err)
Definition: sample.cpp:38
void mark_function_always_inline(llvm::Function *func)
bool is_fp() const
Definition: sqltypes.h:573
llvm::StringRef get_gpu_data_layout()
llvm::ConstantInt * ll_int(const T v, llvm::LLVMContext &context)
std::string assemblyForCPU(ExecutionEngineWrapper &execution_engine, llvm::Module *llvm_module)
std::string join(T const &container, std::string const &delim)
std::vector< InputDescriptor > input_descs
#define UNREACHABLE()
Definition: Logger.h:338
std::string serialize_llvm_metadata_footnotes(llvm::Function *query_func, CgenState *cgen_state)
std::unique_ptr< llvm::Module > read_llvm_module_from_ir_string(const std::string &udf_ir_string, llvm::LLVMContext &ctx, bool is_gpu=false)
std::tuple< llvm::Function *, llvm::CallInst * > query_template(llvm::Module *mod, const size_t aggr_col_count, const bool hoist_literals, const bool is_estimate_query, const GpuSharedMemoryContext &gpu_smem_context)
void insertErrorCodeChecker(llvm::Function *query_func, unsigned const error_code_idx, bool hoist_literals, bool allow_runtime_query_interrupt)
std::vector< std::string > CodeCacheKey
Definition: CodeCache.h:24
ExecutorOptLevel opt_level
bool g_enable_dynamic_watchdog
Definition: Execute.cpp:81
static ExecutionEngineWrapper generateNativeCPUCode(llvm::Function *func, const std::unordered_set< llvm::Function * > &live_funcs, const CompilationOptions &co)
const std::list< std::shared_ptr< Analyzer::Expr > > groupby_exprs
T visit(const Analyzer::Expr *expr) const
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
static std::string generatePTX(const std::string &cuda_llir, llvm::TargetMachine *nvptx_target_machine, llvm::LLVMContext &context)
#define CHECK_GT(x, y)
Definition: Logger.h:305
ExecutionEngineWrapper & operator=(const ExecutionEngineWrapper &other)=delete
void * cubin
Definition: NvidiaKernel.h:31
std::tuple< llvm::Function *, llvm::CallInst * > query_group_by_template(llvm::Module *mod, const bool hoist_literals, const QueryMemoryDescriptor &query_mem_desc, const ExecutorDeviceType device_type, const bool check_scan_limit, const GpuSharedMemoryContext &gpu_smem_context)
bool is_time() const
Definition: sqltypes.h:579
ExecutorDeviceType
std::vector< std::string > get_agg_fnames(const std::vector< Analyzer::Expr * > &target_exprs, const bool is_group_by)
std::string to_string(char const *&&v)
std::vector< std::string > split(std::string_view str, std::string_view delim, std::optional< size_t > maxsplit)
split apart a string into a vector of substrings
std::vector< CUjit_option > option_keys
Definition: NvidiaKernel.h:32
void throw_parseIR_error(const llvm::SMDiagnostic &parse_error, std::string src="", const bool is_gpu=false)
llvm::Function * row_func_
Definition: CgenState.h:374
bool g_enable_smem_non_grouped_agg
Definition: Execute.cpp:150
Definition: sqldefs.h:78
std::shared_lock< T > shared_lock
unsigned getExpOfTwo(unsigned n)
Definition: MathUtils.cpp:23
llvm::StringRef get_gpu_target_triple_string()
llvm::Module * module_
Definition: CgenState.h:373
Supported runtime functions management and retrieval.
std::tuple< CompilationResult, std::unique_ptr< QueryMemoryDescriptor > > compileWorkUnit(const std::vector< InputTableInfo > &query_infos, const PlanState::DeletedColumnsMap &deleted_cols_map, const RelAlgExecutionUnit &ra_exe_unit, const CompilationOptions &co, const ExecutionOptions &eo, const CudaMgr_Namespace::CudaMgr *cuda_mgr, const bool allow_lazy_fetch, std::shared_ptr< RowSetMemoryOwner >, const size_t max_groups_buffer_entry_count, const int8_t crt_min_byte_width, const bool has_cardinality_estimation, ColumnCacheMap &column_cache, RenderInfo *render_info=nullptr)
void scan_function_calls(llvm::Function &F, std::unordered_set< std::string > &defined, std::unordered_set< std::string > &undefined, const std::unordered_set< std::string > &ignored)
void verify_function_ir(const llvm::Function *func)
bool compileBody(const RelAlgExecutionUnit &ra_exe_unit, GroupByAndAggregate &group_by_and_aggregate, QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const GpuSharedMemoryContext &gpu_smem_context={})
llvm::Value * get_arg_by_name(llvm::Function *func, const std::string &name)
Definition: Execute.h:168
static std::unordered_set< llvm::Function * > markDeadRuntimeFuncs(llvm::Module &module, const std::vector< llvm::Function * > &roots, const std::vector< llvm::Function * > &leaves)
std::string generatePTX(const std::string &) const
ExecutionEngineWrapper create_execution_engine(llvm::Module *llvm_module, llvm::EngineBuilder &eb, const CompilationOptions &co)
std::unique_ptr< llvm::JITEventListener > intel_jit_listener_
bool is_integer() const
Definition: sqltypes.h:567
const JoinQualsPerNestingLevel join_quals
std::unique_ptr< llvm::Module > read_llvm_module_from_ir_file(const std::string &udf_ir_filename, llvm::LLVMContext &ctx, bool is_gpu=false)
ExecutorExplainType explain_type
unsigned get_index_by_name(llvm::Function *func, const std::string &name)
Definition: Execute.h:187
std::shared_ptr< CompilationContext > optimizeAndCodegenCPU(llvm::Function *, llvm::Function *, const std::unordered_set< llvm::Function * > &, const CompilationOptions &)
void initializeNVPTXBackend() const
Definition: sqldefs.h:80
size_t getMinSharedMemoryPerBlockForAllDevices() const
Definition: CudaMgr.h:128
static void link_udf_module(const std::unique_ptr< llvm::Module > &udf_module, llvm::Module &module, CgenState *cgen_state, llvm::Linker::Flags flags=llvm::Linker::Flags::None)
const std::shared_ptr< Analyzer::Estimator > estimator
#define AUTOMATIC_IR_METADATA(CGENSTATE)
CubinResult ptx_to_cubin(const std::string &ptx, const CudaMgr_Namespace::CudaMgr *cuda_mgr)
this
Definition: Execute.cpp:285
QueryDescriptionType getQueryDescriptionType() const
static std::mutex initialize_cpu_backend_mutex_
std::map< std::string, std::string > get_device_parameters(bool cpu_only)
static std::string deviceArchToSM(const NvidiaDeviceArch arch)
Definition: CudaMgr.h:162
std::vector< void * > option_values
Definition: NvidiaKernel.h:33
#define AUTOMATIC_IR_METADATA_DONE()
llvm::Function * create_row_function(const size_t in_col_count, const size_t agg_col_count, const bool hoist_literals, llvm::Module *llvm_module, llvm::LLVMContext &context)
ExecutorDeviceType device_type
void bind_pos_placeholders(const std::string &pos_fn_name, const bool use_resume_param, llvm::Function *query_func, llvm::Module *llvm_module)
llvm::Function * filter_func_
Definition: CgenState.h:375
std::unique_ptr< llvm::ExecutionEngine > execution_engine_
static void addUdfIrToModule(const std::string &udf_ir_filename, const bool is_cuda_ir)
bool isArchMaxwellOrLaterForAll() const
Definition: CudaMgr.cpp:437
llvm::BasicBlock * codegenSkipDeletedOuterTableRow(const RelAlgExecutionUnit &ra_exe_unit, const CompilationOptions &co)
void bind_query(llvm::Function *query_func, const std::string &query_fname, llvm::Function *multifrag_query_func, llvm::Module *llvm_module)
#define CHECK_LE(x, y)
Definition: Logger.h:304
void set_row_func_argnames(llvm::Function *row_func, const size_t in_col_count, const size_t agg_col_count, const bool hoist_literals)
std::string cpp_to_llvm_name(const std::string &s)
std::string serialize_llvm_object(const T *llvm_obj)
void clear_function_attributes(llvm::Function *func)
std::shared_ptr< CompilationContext > optimizeAndCodegenGPU(llvm::Function *, llvm::Function *, std::unordered_set< llvm::Function * > &, const bool no_inline, const CudaMgr_Namespace::CudaMgr *cuda_mgr, const bool is_gpu_smem_used, const CompilationOptions &)
static std::shared_ptr< GpuCompilationContext > generateNativeGPUCode(Executor *executor, llvm::Function *func, llvm::Function *wrapper_func, const std::unordered_set< llvm::Function * > &live_funcs, const bool is_gpu_smem_used, const CompilationOptions &co, const GPUTarget &gpu_target)
size_t cubin_size
Definition: NvidiaKernel.h:35
bool g_enable_smem_grouped_non_count_agg
Definition: Execute.cpp:147
Definition: sqldefs.h:81
static bool alwaysCloneRuntimeFunction(const llvm::Function *func)
std::unordered_map< shared::TableKey, std::unordered_map< int, std::shared_ptr< const ColumnarResults >>> ColumnCacheMap
bool has_count_expr(RelAlgExecutionUnit const &ra_exe_unit)
std::vector< llvm::Value * > generate_column_heads_load(const int num_columns, llvm::Value *byte_stream_arg, llvm::IRBuilder<> &ir_builder, llvm::LLVMContext &ctx)
static std::map< ExtModuleKinds, std::string > extension_module_sources
Definition: Execute.h:528
void show_defined(llvm::Module &llvm_module)
torch::Tensor f(torch::Tensor x, torch::Tensor W_target, torch::Tensor b_target)
GroupByBaselineHash
Definition: enums.h:58
int CUdevice
Definition: nocuda.h:20
bool g_enable_filter_function
Definition: Execute.cpp:91
static void linkModuleWithLibdevice(Executor *executor, llvm::Module &module, llvm::PassManagerBuilder &pass_manager_builder, const GPUTarget &gpu_target)
virtual T visitCaseExpr(const Analyzer::CaseExpr *case_) const
float g_fraction_code_cache_to_evict
static bool prioritizeQuals(const RelAlgExecutionUnit &ra_exe_unit, std::vector< Analyzer::Expr * > &primary_quals, std::vector< Analyzer::Expr * > &deferred_quals, const PlanState::HoistedFiltersSet &hoisted_quals)
Definition: LogicalIR.cpp:158
SQLAgg get_aggtype() const
Definition: Analyzer.h:1329
std::list< std::shared_ptr< Analyzer::Expr > > quals
bool g_enable_watchdog false
Definition: Execute.cpp:80
#define CHECK(condition)
Definition: Logger.h:291
bool is_geometry() const
Definition: sqltypes.h:597
#define DEBUG_TIMER(name)
Definition: Logger.h:412
llvm::ValueToValueMapTy vmap_
Definition: CgenState.h:383
std::vector< llvm::Value * > inlineHoistedLiterals()
static std::shared_ptr< QueryEngine > getInstance()
Definition: QueryEngine.h:89
std::vector< TargetInfo > target_exprs_to_infos(const std::vector< Analyzer::Expr * > &targets, const QueryMemoryDescriptor &query_mem_desc)
CUlinkState link_state
Definition: NvidiaKernel.h:34
bool isArchPascal() const
Definition: CudaMgr.h:153
bool any_of(std::vector< Analyzer::Expr * > const &target_exprs)
std::list< std::shared_ptr< const InputColDescriptor > > input_col_descs
bool is_string() const
Definition: sqltypes.h:561
size_t g_leaf_count
Definition: ParserNode.cpp:79
Definition: sqldefs.h:79
int cpu_threads()
Definition: thread_count.h:25
static std::vector< std::string > getLLVMDeclarations(const std::unordered_set< std::string > &udf_decls, const bool is_gpu=false)
std::vector< int64_t > init_agg_val_vec(const std::vector< TargetInfo > &targets, const QueryMemoryDescriptor &query_mem_desc)
bool is_decimal() const
Definition: sqltypes.h:570
Definition: sqldefs.h:77
llvm::Type * get_int_ptr_type(const int width, llvm::LLVMContext &context)
constexpr std::array< std::string_view, 18 > TARGET_RUNTIME_FUNCTIONS_FOR_MODULE_CLONING
Definition: sqldefs.h:86
bool is_array() const
Definition: sqltypes.h:585
#define VLOG(n)
Definition: Logger.h:388
size_t get_shared_memory_size(const bool shared_mem_used, const QueryMemoryDescriptor *query_mem_desc_ptr)
std::list< std::shared_ptr< Analyzer::Expr > > simple_quals
llvm::Value * get_arg_by_index(llvm::Function *func, unsigned const index)
Definition: Execute.h:178
std::unique_ptr< llvm::Module > read_llvm_module_from_bc_file(const std::string &udf_ir_filename, llvm::LLVMContext &ctx)
static std::unique_ptr< llvm::TargetMachine > initializeNVPTXBackend(const CudaMgr_Namespace::NvidiaDeviceArch arch)
bool has_case_expr_within_groupby_expr(RelAlgExecutionUnit const &ra_exe_unit)
static std::mutex initialize_nvptx_mutex_
size_t g_gpu_smem_threshold
Definition: Execute.cpp:142