codegen.cc 9.75 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16 17 18 19
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

20 21 22 23
/*!
 * \file codegen.cc
 * \brief Common utilities to generated C style code.
 */
24 25
#include <tvm/target/codegen.h>
#include <tvm/target/target.h>
26 27

#include <tvm/ir/module.h>
28
#include <tvm/tir/ir_pass.h>
29 30 31
#include <tvm/tir/function.h>

#include <tvm/runtime/container.h>
32 33
#include <tvm/runtime/registry.h>
#include <tvm/runtime/module.h>
34
#include <tvm/runtime/c_runtime_api.h>
35 36
#include <dmlc/memory_io.h>
#include <sstream>
37 38 39 40
#include <vector>
#include <cstdint>
#include <unordered_set>
#include <cstring>
41 42 43 44

namespace tvm {
namespace codegen {

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
// The new build function.
// adapt the old function to the new one
runtime::Module BuildForIRModule(const IRModule& module,
                                 const Target& target) {
  std::string build_f_name = "target.build." + target->target_name;
  // the build function.
  const PackedFunc* bf = runtime::Registry::Get(build_f_name);
  CHECK(bf != nullptr)
      << "target.build." << target << " is not enabled";
  return (*bf)(module, target->str());
}

// convert legacy LoweredFunc to PrimFunc.
tir::PrimFunc ToPrimFunc(tir::LoweredFunc from) {
  // remap args to attach type annotations.
  Array<tir::Var> args;
  Map<tir::Var, PrimExpr> remap_vars;

  for (auto var : from->args) {
    if (from->handle_data_type.count(var)) {
      tir::Var new_var(var->name_hint,
                       PointerType(PrimType(var->dtype)));
      args.push_back(new_var);
      remap_vars.Set(var, new_var);
    } else {
      args.push_back(var);
    }
  }
  tir::PrimFunc func(args, Substitute(from->body, remap_vars));

  func = WithAttr(std::move(func), attr::kGlobalSymbol, runtime::String(from->name));
  func = WithAttr(std::move(func), tir::attr::kDeviceThreadAxis, from->thread_axis);
  if (from->func_type == tir::LoweredFuncType::kDeviceFunc) {
    func = WithAttr(std::move(func),
                    attr::kCallingConv, Integer(CallingConv::kDeviceKernelLaunch));
  }
  if (from->is_restricted) {
    func = WithAttr(std::move(func), tir::attr::kNoAlias, Integer(1));
  }
  return func;
}

IRModule ToIRModule(const Array<tir::LoweredFunc>& funcs) {
  Map<GlobalVar, BaseFunc> functions;
  for (size_t i = 0; i < funcs.size(); ++i) {
    auto f = funcs[i];
    tir::PrimFunc pf = ToPrimFunc(f);
    if (i == 0) {
      pf = WithAttr(std::move(pf), tir::attr::kIsEntryFunc, Integer(1));
    }
    functions.Set(GlobalVar(f->name), pf);
  }
  return IRModule(functions);
}

100
runtime::Module Build(const Array<tir::LoweredFunc>& funcs,
101 102
                      const std::string& target) {
  std::string mode = target;
103
  size_t pos = mode.find(' ');
104 105 106
  if (pos != std::string::npos) {
    mode = mode.substr(0, pos);
  }
107
  Array<tir::LoweredFunc> transformed_funcs;
108 109
  if (BuildConfig::Current()->disable_assert) {
    for (const auto& x : funcs) {
110
      auto func = tir::SkipAssert(x);
111 112 113
      transformed_funcs.push_back(func);
    }
  }
114 115 116 117

  return BuildForIRModule(
      transformed_funcs.size() != 0 ? ToIRModule(transformed_funcs) : ToIRModule(funcs),
      Target::Create(target));
118 119
}

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
/*! \brief Helper class to serialize module */
class ModuleSerializer {
 public:
  explicit ModuleSerializer(runtime::Module mod) : mod_(mod) {
    Init();
  }

  void SerializeModule(dmlc::Stream* stream) {
    // Only have one DSO module and it is in the root, then
    // we will not produce import_tree_.
    bool has_import_tree = true;
    if (DSOExportable(mod_.operator->()) && mod_->imports().empty()) {
      has_import_tree = false;
    }
    uint64_t sz = 0;
    if (has_import_tree) {
      // we will append one key for _import_tree
      // The layout is the same as before: binary_size, key, logic, key, logic...
      sz = mod_vec_.size() + 1;
    } else {
      // Keep the old behaviour
      sz = mod_->imports().size();
    }
    stream->Write(sz);

    for (auto m : mod_vec_) {
      std::string mod_type_key = m->type_key();
      if (!DSOExportable(m)) {
        stream->Write(mod_type_key);
        m->SaveToBinary(stream);
      } else if (has_import_tree) {
        mod_type_key = "_lib";
        stream->Write(mod_type_key);
      }
    }

    // Write _import_tree key if we have
    if (has_import_tree) {
      std::string import_key = "_import_tree";
      stream->Write(import_key);
      stream->Write(import_tree_row_ptr_);
      stream->Write(import_tree_child_indices_);
    }
  }

 private:
  void Init() {
    CreateModuleIndex();
    CreateImportTree();
  }

  // invariance: root module is always at location 0.
  // The module order is collected via DFS
  void CreateModuleIndex() {
    std::unordered_set<const runtime::ModuleNode*> visited {mod_.operator->()};
    std::vector<runtime::ModuleNode*> stack {mod_.operator->()};
    uint64_t module_index = 0;

    while (!stack.empty()) {
      runtime::ModuleNode* n = stack.back();
      stack.pop_back();
      mod2index_[n] = module_index++;
      mod_vec_.emplace_back(n);
      for (runtime::Module m : n->imports()) {
        runtime::ModuleNode* next = m.operator->();
        if (visited.count(next) == 0) {
          visited.insert(next);
          stack.push_back(next);
        }
      }
    }
  }

  void CreateImportTree() {
    for (auto m : mod_vec_) {
      for (runtime::Module im : m->imports()) {
        uint64_t mod_index = mod2index_[im.operator->()];
        import_tree_child_indices_.push_back(mod_index);
      }
      import_tree_row_ptr_.push_back(import_tree_child_indices_.size());
    }
  }

  bool DSOExportable(const runtime::ModuleNode* mod) {
    return !std::strcmp(mod->type_key(), "llvm") ||
           !std::strcmp(mod->type_key(), "c");
  }

  runtime::Module mod_;
  // construct module to index
  std::unordered_map<runtime::ModuleNode*, size_t> mod2index_;
  // index -> module
  std::vector<runtime::ModuleNode*> mod_vec_;
  std::vector<uint64_t> import_tree_row_ptr_ {0};
  std::vector<uint64_t> import_tree_child_indices_;
};

217 218 219 220 221 222 223 224 225 226 227 228
namespace {
  std::string SerializeModule(const runtime::Module& mod) {
    std::string bin;
    dmlc::MemoryStringStream ms(&bin);
    dmlc::Stream* stream = &ms;

    ModuleSerializer module_serializer(mod);
    module_serializer.SerializeModule(stream);

    return bin;
  }
}  // namespace
229

230 231
std::string PackImportsToC(const runtime::Module& mod, bool system_lib) {
  std::string bin = SerializeModule(mod);
232

233 234
  // translate to C program
  std::ostringstream os;
235 236 237 238 239
  os << "#ifdef _WIN32\n"
     << "#define TVM_EXPORT __declspec(dllexport)\n"
     << "#else\n"
     << "#define TVM_EXPORT\n"
     << "#endif\n";
240 241 242
  os << "#ifdef __cplusplus\n"
     << "extern \"C\" {\n"
     << "#endif\n";
243
  os << "TVM_EXPORT extern const unsigned char " << runtime::symbol::tvm_dev_mblob << "[];\n";
244
  uint64_t nbytes = bin.length();
245
  os << "const unsigned char " << runtime::symbol::tvm_dev_mblob
246
     << "[" << bin.length() + sizeof(nbytes) << "] = {\n  ";
247 248
  os << std::hex;
  size_t nunit = 80 / 4;
249
  for (size_t i = 0; i < sizeof(nbytes); ++i) {
250 251
    // sperators
    if (i != 0) {
252 253 254 255 256 257 258 259 260 261
      os << ",";
    }
    os << "0x" << ((nbytes >> (i * 8)) & 0xffUL);
  }
  for (size_t i = 0; i < bin.length(); ++i) {
    // sperators
    if ((i + sizeof(nbytes)) % nunit == 0) {
      os << ",\n  ";
    } else {
      os << ",";
262 263 264 265
    }
    int c = bin[i];
    os << "0x" << (c & 0xff);
  }
266 267 268 269 270 271 272 273
  os << "\n};\n";
  if (system_lib) {
    os << "extern int TVMBackendRegisterSystemLibSymbol(const char*, void*);\n";
    os << "static int " << runtime::symbol::tvm_dev_mblob << "_reg_ = "
       << "TVMBackendRegisterSystemLibSymbol(\"" << runtime::symbol::tvm_dev_mblob << "\", (void*)"
       << runtime::symbol::tvm_dev_mblob << ");\n";
  }
  os << "#ifdef __cplusplus\n"
274 275 276 277
     << "}\n"
     << "#endif\n";
  return os.str();
}
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301

runtime::Module PackImportsToLLVM(const runtime::Module& mod,
                                  bool system_lib,
                                  const std::string& target_triple) {
  std::string bin = SerializeModule(mod);

  uint64_t nbytes = bin.length();
  std::string header;
  for (size_t i = 0; i < sizeof(nbytes); ++i) {
    header.push_back(((nbytes >> (i * 8)) & 0xffUL));
  }
  std::string blob = header + bin;
  TVMByteArray blob_byte_array;
  blob_byte_array.size = blob.length();
  blob_byte_array.data = blob.data();

  // Call codegen_blob to generate LLVM module
  std::string codegen_f_name = "codegen.codegen_blob";
  // the codegen function.
  const PackedFunc* codegen_f = runtime::Registry::Get(codegen_f_name);
  CHECK(codegen_f != nullptr)  << "codegen.codegen_blob is not presented.";
  return (*codegen_f)(blob_byte_array, system_lib, target_triple);
}

302
TVM_REGISTER_GLOBAL("target.Build")
303 304 305 306 307 308 309 310
.set_body([](TVMArgs args, TVMRetValue *ret) {
  if (args[0].IsObjectRef<tir::LoweredFunc>()) {
      *ret = Build({args[0]}, args[1]);
    } else {
      *ret = Build(args[0], args[1]);
    }
  });

311 312 313
TVM_REGISTER_GLOBAL("testing.LoweredFuncsToIRModule")
.set_body_typed(ToIRModule);

314 315 316 317 318 319 320
// Export two auxiliary function to the runtime namespace.
TVM_REGISTER_GLOBAL("runtime.ModulePackImportsToC")
.set_body_typed(PackImportsToC);

TVM_REGISTER_GLOBAL("runtime.ModulePackImportsToLLVM")
.set_body_typed(PackImportsToLLVM);

321 322
}  // namespace codegen
}  // namespace tvm