codegen_c.cc 27.2 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
/*!
 *  Copyright (c) 2017 by Contributors
 * \file codegen_c.cc
 */
24
#include <iomanip>
25
#include <cctype>
26
#include "codegen_c.h"
27
#include "../pass/ir_util.h"
28
#include "../arithmetic/compute_expr.h"
29 30 31 32 33 34

namespace tvm {
namespace codegen {

using namespace ir;

35
void CodeGenC::Init(bool output_ssa) {
36
  print_ssa_form_ = output_ssa;
37 38 39 40 41
}

void CodeGenC::InitFuncState(LoweredFunc f) {
  alloc_storage_scope_.clear();
  handle_data_type_.clear();
42
  CodeGenSourceBase::ClearFuncState();
43
}
44 45

void CodeGenC::ReserveKeywordsAsUnique() {
46
  // skip the first underscore, so SSA variable starts from _1
47
  GetUniqueName("_");
48
  GetUniqueName("extern");
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
  GetUniqueName("void");
  GetUniqueName("int");
  GetUniqueName("float");
  GetUniqueName("double");
  GetUniqueName("char");
  GetUniqueName("unsigned");
  GetUniqueName("short");
  GetUniqueName("long");
  GetUniqueName("if");
  GetUniqueName("else");
  GetUniqueName("switch");
  GetUniqueName("case");
  GetUniqueName("default");
  GetUniqueName("for");
  GetUniqueName("do");
  GetUniqueName("while");
  GetUniqueName("goto");
  GetUniqueName("register");
  GetUniqueName("continue");
  GetUniqueName("break");
  GetUniqueName("typedef");
  GetUniqueName("struct");
  GetUniqueName("enum");
  GetUniqueName("union");
  GetUniqueName("return");
}

void CodeGenC::AddFunction(LoweredFunc f) {
  // clear previous generated state.
  this->InitFuncState(f);
  // reserve keywords
  ReserveKeywordsAsUnique();
81 82
  // add to alloc buffer type.
  for (const auto & kv : f->handle_data_type) {
83
    RegisterHandleType(kv.first.get(), kv.second.type());
84
  }
85

86 87 88
  this->stream << "void " << f->name << "(";
  for (size_t i = 0; i < f->args.size(); ++i) {
    Var v = f->args[i];
89 90
    std::string vid = AllocVarID(v.get());
    if (i != 0) stream << ", ";
91
    if (v.type().is_handle()) {
92
      auto it = alloc_storage_scope_.find(v.get());
93
      if (it != alloc_storage_scope_.end())
94
        PrintStorageScope(it->second, stream);
95 96 97 98 99 100
      stream << ' ';

      if (handle_data_type_.count(v.get())) {
        PrintType(handle_data_type_.at(v.get()), stream);
      } else {
        stream << "void";
101
      }
102
      stream << "*";
103

104 105 106
      if (f->is_restricted && restrict_keyword_.length() != 0) {
        stream << ' ' << restrict_keyword_;
      }
107 108 109
    } else {
      PrintType(v.type(), stream);
    }
110 111 112
    stream << ' ' << vid;
  }
  stream << ") {\n";
113
  this->PreFunctionBody(f);
114
  int func_scope = this->BeginScope();
115
  this->PrintStmt(f->body);
116
  this->EndScope(func_scope);
117
  this->PrintIndent();
118 119 120 121
  this->stream << "}\n\n";
}

std::string CodeGenC::Finish() {
122
  return decl_stream.str() + stream.str();
123 124 125 126 127
}

void CodeGenC::PrintExpr(const Expr& n, std::ostream& os) {  // NOLINT(*)
  if (print_ssa_form_) {
    std::ostringstream temp;
128
    VisitExpr(n, temp);
129 130
    os << SSAGetID(temp.str(), n.type());
  } else {
131
    VisitExpr(n, os);
132 133 134
  }
}

135 136 137 138 139 140 141
void CodeGenC::PrintSSAAssign(
    const std::string& target, const std::string& src, Type t) {
  PrintType(t, stream);
  stream << ' ' << target << " = ";
  if (src.length() > 3 &&
      src[0] == '(' && src[src.length() - 1] == ')') {
    stream << src.substr(1, src.length() - 2);
142
  } else {
143
    stream << src;
144
  }
145
  stream << ";\n";
146 147 148
}

// Print a reference expression to a buffer.
149
std::string CodeGenC::GetBufferRef(
150
    Type t, const Variable* buffer, Expr index) {
151
  std::ostringstream os;
152
  std::string vid = GetVarID(buffer);
153 154 155 156
  std::string scope;
  if (alloc_storage_scope_.count(buffer)) {
    scope = alloc_storage_scope_.at(buffer);
  }
157
  bool is_vol = volatile_buf_.count(buffer) != 0;
158
  if (t.lanes() == 1) {
159
    if (!HandleTypeMatch(buffer, t) || is_vol) {
160
      os << "((";
161 162 163 164 165 166 167
      if (is_vol) {
        os << "volatile ";
      }
      if (scope.length() != 0) {
        PrintStorageScope(scope, os);
      }
      os << ' ';
168 169 170 171 172 173 174 175 176 177 178
      PrintType(t, os);
      os << "*)" << vid << ')';
    } else {
      os << vid;
    }
    os << '[';
    PrintExpr(index, os);
    os << ']';
  } else {
    // Buffer declared as vector type.
    // optimize for case where it is in register,
179
    if (HandleTypeMatch(buffer, t) && !is_vol) {
180 181 182 183 184 185
      // optimize for constant access
      int offset;
      if (arith::GetConstInt(index, &offset)) {
        CHECK_EQ(offset % t.lanes(), 0)
            << "Find unaligned vector load to a vector type";
        os << vid << '[' << (offset / t.lanes()) << ']';
186
        return os.str();
187 188 189
      }
    }
    os << "((";
190 191 192 193 194 195 196
    if (is_vol) {
      os << "volatile ";
    }
    if (scope.length() != 0) {
      PrintStorageScope(scope, os);
    }
    os << ' ';
197 198 199 200
    PrintType(t, os);
    os << "*)(";
    if (!HandleTypeMatch(buffer, t.element_of())) {
      os << '(';
201 202 203 204
      if (scope.length() != 0) {
        PrintStorageScope(scope, os);
      }
      os << ' ';
205 206 207 208 209 210 211
      PrintType(t.element_of(), os);
      os << "*)";
    }
    os << vid << " + ";
    PrintExpr(index, os);
    os << "))[0]";
  }
212
  return os.str();
213 214
}

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
// Print a reference expression to a buffer.
std::string CodeGenC::GetStructRef(
    Type t, const Expr& buffer, const Expr& index, int kind) {
  if (kind < intrinsic::kArrKindBound_) {
    std::ostringstream os;
    os << "(((TVMArray*)";
    this->PrintExpr(buffer, os);
    os << ")";
    if (kind == intrinsic::kArrAddr) {
      os << " + ";
      this->PrintExpr(index, os);
      os << ")";
      return os.str();
    }
    os << '[';
    this->PrintExpr(index, os);
    os << "].";
    // other case: get fields.
    switch (kind) {
      case intrinsic::kArrData: os << "data"; break;
      case intrinsic::kArrShape: os << "shape"; break;
      case intrinsic::kArrStrides: os << "strides"; break;
      case intrinsic::kArrNDim: os << "ndim"; break;
      case intrinsic::kArrTypeCode: os << "dtype.code"; break;
      case intrinsic::kArrTypeBits: os << "dtype.bits"; break;
240
      case intrinsic::kArrByteOffset: os << "byte_offset"; break;
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
      case intrinsic::kArrTypeLanes: os << "dtype.lanes"; break;
      case intrinsic::kArrDeviceId: os << "ctx.device_id"; break;
      case intrinsic::kArrDeviceType: os << "ctx.device_type"; break;
      default: LOG(FATAL) << "unknown field code";
    }
    os << ')';
    return os.str();
  } else {
    CHECK_LT(kind, intrinsic::kTVMValueKindBound_);
    std::ostringstream os;
    os << "(((TVMValue*)";
    this->PrintExpr(buffer, os);
    os << ")[" << index << "].";
    if (t.is_handle()) {
      os << "v_handle";
    } else if (t.is_float()) {
      os << "v_float64";
    } else if (t.is_int()) {
      os << "v_int64";
    } else {
Siju committed
261
      LOG(FATAL) << "Do not know how to handle type" << t;
262 263 264 265 266 267
    }
    os << ")";
    return os.str();
  }
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284

bool CodeGenC::HandleTypeMatch(const Variable* buf_var, Type t) const {
  auto it = handle_data_type_.find(buf_var);
  if (it == handle_data_type_.end()) return false;
  return it->second == t;
}

void CodeGenC::RegisterHandleType(const Variable* buf_var, Type t) {
  auto it = handle_data_type_.find(buf_var);
  if (it == handle_data_type_.end()) {
    handle_data_type_[buf_var] = t;
  } else {
    CHECK(it->second == t)
        << "conflicting buf var type";
  }
}

285 286 287
void CodeGenC::PrintVecElemLoad(const std::string& vec,
                                Type t, int i,
                                std::ostream& os) {  // NOLINT(*)
288
  os << vec << ".s" << std::hex << i << std::dec;
289 290 291 292 293 294 295
}

void CodeGenC::PrintVecElemStore(const std::string& vec,
                                 Type t, int i,
                                 const std::string& value) {
  this->PrintIndent();
  stream << vec << ".s" << std::hex << i
296
         << " = " << value << ";\n" << std::dec;
297 298
}

299 300 301
std::string CodeGenC::GetVecLoad(
    Type t, const Variable* buffer, Expr base) {
  return GetBufferRef(t, buffer, base);
302 303 304 305 306
}

void CodeGenC::PrintVecStore(const Variable* buffer,
                             Type t, Expr base,
                             const std::string& value) {
307
  std::string ref = GetBufferRef(t, buffer, base);
308
  this->PrintIndent();
309
  stream << ref << " = " << value << ";\n";
310 311
}

312 313 314 315 316 317 318 319 320
std::string CodeGenC::CastFromTo(std::string value, Type from, Type target) {
  if (from == target) return value;
  std::ostringstream os;
  os << "((";
  this->PrintType(target, os);
  os << ")" << value << ")";
  return os.str();
}

321
void CodeGenC::BindThreadIndex(const IterVar& iv) {
322
  LOG(FATAL) << "not implemented";
323 324
}

325
void CodeGenC::PrintStorageSync(const Call* op) { // NOLINT(*)
326 327 328 329 330 331
}

void CodeGenC::PrintStorageScope(const std::string& scope, std::ostream& os) { // NOLINT(*)
  CHECK_EQ(scope, "global");
}

332
void CodeGenC::PrintType(Type t, std::ostream& os) {  // NOLINT(*)
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
  CHECK_EQ(t.lanes(), 1)
      << "do not yet support vector types";
  if (t.is_handle()) {
    os << "void*"; return;
  }
  if (t.is_float()) {
    if (t.bits() == 32) {
      os << "float"; return;
    }
    if (t.bits() == 64) {
      os << "double"; return;
    }
  } else if (t.is_uint()) {
    switch (t.bits()) {
      case 8: case 16: case 32: case 64: {
        os << "uint" << t.bits() << "_t"; return;
      }
      case 1: os << "int"; return;
    }
  } else if (t.is_int()) {
    switch (t.bits()) {
      case 8: case 16: case 32: case 64: {
        os << "int" << t.bits() << "_t";  return;
      }
    }
  }
  LOG(FATAL) << "Cannot convert type " << t << " to C type";
}


inline void PrintConst(const IntImm* op, std::ostream& os, CodeGenC* p) { // NOLINT(*)
  if (op->type == Int(32)) {
    std::ostringstream temp;
    temp << op->value;
    p->MarkConst(temp.str());
    os << temp.str();
  } else {
    os << "(";
    p->PrintType(op->type, os);
    os << ")" << op->value;
  }
}

inline void PrintConst(const UIntImm* op, std::ostream& os, CodeGenC* p) { // NOLINT(*)
  if (op->type == UInt(32)) {
    std::ostringstream temp;
    temp << op->value << "U";
    p->MarkConst(temp.str());
    os << temp.str();
  } else {
    os << "(";
    p->PrintType(op->type, os);
    os << ")" << op->value;
  }
}

inline void PrintConst(const FloatImm* op, std::ostream& os, CodeGenC* p) { // NOLINT(*)
  switch (op->type.bits()) {
    case 64: case 32: {
      std::ostringstream temp;
393
      temp << std::scientific << op->value;
394 395 396 397 398 399 400 401
      if (op->type.bits() == 32) temp << 'f';
      p->MarkConst(temp.str());
      os << temp.str();
      break;
    }
    case 16: {
      os << '(';
      p->PrintType(op->type, os);
402
      os << ')' << std::scientific <<op->value << 'f';
403 404 405 406 407 408
      break;
    }
    default: LOG(FATAL) << "Bad bit-width for float: " << op->type << "\n";
  }
}

409 410 411 412 413 414 415 416 417 418 419 420
void CodeGenC::VisitExpr_(const IntImm *op, std::ostream& os) {  // NOLINT(*)
  PrintConst(op, os, this);
}
void CodeGenC::VisitExpr_(const UIntImm *op, std::ostream& os) {  // NOLINT(*)
  PrintConst(op, os, this);
}
void CodeGenC::VisitExpr_(const FloatImm *op, std::ostream& os) { // NOLINT(*)
  PrintConst(op, os, this);
}
void CodeGenC::VisitExpr_(const StringImm *op, std::ostream& os) { // NOLINT(*)
  os << "\"" << op->value << "\"";
}
421 422 423 424 425 426

template<typename T>
inline void PrintBinaryExpr(const T* op,
                            const char *opstr,
                            std::ostream& os,  // NOLINT(*)
                            CodeGenC* p) {
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
  if (op->type.lanes() == 1) {
    if (isalpha(opstr[0])) {
      os << opstr << '(';
      p->PrintExpr(op->a, os);
      os << ", ";
      p->PrintExpr(op->b, os);
      os << ')';
    } else {
      os << '(';
      p->PrintExpr(op->a, os);
      os << ' ' << opstr << ' ';
      p->PrintExpr(op->b, os);
      os << ')';
    }
  } else {
    p->PrintVecBinaryOp(opstr, op->type, op->a, op->b, os);
  }
444 445
}

446
inline void PrintBinaryIntrinsic(const Call* op,
447 448 449
                                  const char *opstr,
                                  std::ostream& os,  // NOLINT(*)
                                  CodeGenC* p) {
450 451 452 453 454 455 456 457 458 459
  if (op->type.lanes() == 1) {
    CHECK_EQ(op->args.size(), 2U);
    os << '(';
    p->PrintExpr(op->args[0], os);
    os << opstr;
    p->PrintExpr(op->args[1], os);
    os << ')';
  } else {
    p->PrintVecBinaryOp(opstr, op->type, op->args[0], op->args[1], os);
  }
460
}
461
void CodeGenC::VisitExpr_(const Cast *op, std::ostream& os) {  // NOLINT(*)
462 463 464
  std::stringstream value;
  this->PrintExpr(op->value, value);
  os << CastFromTo(value.str(), op->value.type(), op->type);
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
}
void CodeGenC::VisitExpr_(const Variable *op, std::ostream& os) {  // NOLINT(*)
  os << GetVarID(op);
}
void CodeGenC::VisitExpr_(const Add *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "+", os, this);
}
void CodeGenC::VisitExpr_(const Sub *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "-", os, this);
}
void CodeGenC::VisitExpr_(const Mul *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "*", os, this);
}
void CodeGenC::VisitExpr_(const Div *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "/", os, this);
}
void CodeGenC::VisitExpr_(const Mod *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "%", os, this);
}
void CodeGenC::VisitExpr_(const Min *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "min", os, this);
}
void CodeGenC::VisitExpr_(const Max *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "max", os, this);
}
void CodeGenC::VisitExpr_(const EQ *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "==", os, this);
}
void CodeGenC::VisitExpr_(const NE *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "!=", os, this);
}
void CodeGenC::VisitExpr_(const LT *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "<", os, this);
}
void CodeGenC::VisitExpr_(const LE *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "<=", os, this);
}
void CodeGenC::VisitExpr_(const GT *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, ">", os, this);
}
void CodeGenC::VisitExpr_(const GE *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, ">=", os, this);
}
void CodeGenC::VisitExpr_(const And *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "&&", os, this);
}
void CodeGenC::VisitExpr_(const Or *op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "||", os, this);
}
void CodeGenC::VisitExpr_(const Not *op, std::ostream& os) {  // NOLINT(*)
  os << '!';
  PrintExpr(op->a, os);
}
518

519
void CodeGenC::VisitExpr_(const Call *op, std::ostream& os) {  // NOLINT(*)
520 521 522 523 524 525 526 527 528 529 530
  if (op->call_type == Call::Extern ||
      op->call_type == Call::PureExtern) {
    os << op->name << "(";
    for (size_t i = 0; i < op->args.size(); i++) {
      this->PrintExpr(op->args[i], os);
      if (i < op->args.size() - 1) {
        os << ", ";
      }
    }
    os << ")";
  } else if (op->is_intrinsic(Call::bitwise_and)) {
531
    PrintBinaryIntrinsic(op, " & ", os, this);
532
  } else if (op->is_intrinsic(Call::bitwise_xor)) {
533
    PrintBinaryIntrinsic(op, " ^ ", os, this);
534
  } else if (op->is_intrinsic(Call::bitwise_or)) {
535
    PrintBinaryIntrinsic(op, " | ", os, this);
536 537 538
  } else if (op->is_intrinsic(Call::bitwise_not)) {
    CHECK_EQ(op->args.size(), 1U);
    os << "(~";
539
    this->PrintExpr(op->args[0], os);
540 541
    os << ')';
  } else if (op->is_intrinsic(Call::shift_left)) {
542
    PrintBinaryIntrinsic(op, " << ", os, this);
543
  } else if (op->is_intrinsic(Call::shift_right)) {
544
    PrintBinaryIntrinsic(op, " >> ", os, this);
545 546 547 548 549 550 551 552
  } else if (op->is_intrinsic(intrinsic::tvm_if_then_else)) {
    os << "(";
    PrintExpr(op->args[0], os);
    os << " ? ";
    PrintExpr(op->args[1], os);
    os << " : ";
    PrintExpr(op->args[2], os);
    os << ")";
553
  } else if (op->is_intrinsic(intrinsic::tvm_address_of)) {
554 555 556
    const Load *l = op->args[0].as<Load>();
    CHECK(op->args.size() == 1 && l);
    os << "((";
557 558
    this->PrintType(l->type.element_of(), os);
    os << " *)" << this->GetVarID(l->buffer_var.get())
559
       << " + ";
560
    this->PrintExpr(l->index, os);
561
    os << ')';
562
  } else if (op->is_intrinsic(intrinsic::tvm_struct_get)) {
563
    CHECK_EQ(op->args.size(), 3U);
564 565 566
    os << GetStructRef(
        op->type, op->args[0], op->args[1],
        op->args[2].as<IntImm>()->value);
567 568 569
  } else if (op->is_intrinsic(intrinsic::tvm_handle_is_null)) {
    CHECK_EQ(op->args.size(), 1U);
    os << "(";
570
    this->PrintExpr(op->args[0], os);
571
    os << " == NULL)";
572 573 574 575 576 577 578
  } else if (op->is_intrinsic(Call::reinterpret)) {
    // generate (*( TYPE *)(&(ARG)))
    os << "(*(";
    this->PrintType(op->type, os);
    os << " *)(&(";
    this->PrintExpr(op->args[0], os);
    os << ")))";
579 580 581 582 583 584
  } else if (op->is_intrinsic(Call::isnan)) {
    os << "(";
    this->PrintExpr(op->args[0], os);
    os << " != ";
    this->PrintExpr(op->args[0], os);
    os << ")";
585
  } else {
586 587 588 589 590 591
    if (op->call_type == Call::Intrinsic ||
        op->call_type == Call::PureIntrinsic) {
      LOG(FATAL) << "Unresolved intrinsic " << op->name
                 << " with return type " << op->type;
    } else {
      LOG(FATAL) << "Unresolved call type " << op->call_type;
592 593 594 595
    }
  }
}

596
void CodeGenC::PrintVecBinaryOp(
597
    const std::string& op, Type t,
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    Expr lhs, Expr rhs, std::ostream& os) {  // NOLINT(*)
  if (isalpha(op[0])) {
    os << op << "(";
    this->PrintExpr(lhs, os);
    os << ", ";
    this->PrintExpr(rhs, os);
    os << ")";
  } else {
    os <<"(";
    this->PrintExpr(lhs, os);
    os << ' ' << op << ' ';
    this->PrintExpr(rhs, os);
    os << ")";
  }
}

614
void CodeGenC::VisitExpr_(const Load* op, std::ostream& os) {  // NOLINT(*)
615
  int lanes = op->type.lanes();
616
  // delcare type.
617
  if (op->type.lanes() == 1) {
618
    std::string ref = GetBufferRef(op->type, op->buffer_var.get(), op->index);
619
    os << ref;
620
  } else {
621 622
    CHECK(is_one(op->predicate))
        << "predicated load is not supported";
623
    Expr base;
624
    if (GetRamp1Base(op->index, op->type.lanes(), &base)) {
625
      std::string ref = GetVecLoad(op->type, op->buffer_var.get(), base);
626
      os << ref;
627
    } else {
628 629 630 631
      // The assignment below introduces side-effect, and the resulting value cannot
      // be reused across multiple expression, thus a new scope is needed
      int vec_scope = BeginScope();

632 633 634 635 636
      // load seperately.
      std::string svalue = GetUniqueName("_");
      this->PrintIndent();
      this->PrintType(op->type, stream);
      stream << ' ' << svalue << ";\n";
637 638 639 640 641 642 643
      std::string sindex = SSAGetID(PrintExpr(op->index), op->index.type());
      std::string vid = GetVarID(op->buffer_var.get());
      Type elem_type = op->type.element_of();
      for (int i = 0; i < lanes; ++i) {
        std::ostringstream value_temp;
        if (!HandleTypeMatch(op->buffer_var.get(), elem_type)) {
          value_temp << "((";
644 645 646 647 648 649 650
          if (op->buffer_var.get()->type.is_handle()) {
            auto it = alloc_storage_scope_.find(op->buffer_var.get());
            if (it != alloc_storage_scope_.end()) {
              PrintStorageScope(it->second, value_temp);
              value_temp << ' ';
            }
          }
651
          PrintType(elem_type, value_temp);
652 653 654 655 656 657 658 659 660
          value_temp << "*)" << vid << ')';
        } else {
          value_temp << vid;
        }
        value_temp << '[';
        PrintVecElemLoad(sindex, op->index.type(), i, value_temp);
        value_temp << ']';
        PrintVecElemStore(svalue, op->type, i, value_temp.str());
      }
661
      os << svalue;
662
      EndScope(vec_scope);
663 664 665 666
    }
  }
}

667
void CodeGenC::VisitStmt_(const Store* op) {
668 669 670
  Type t = op->value.type();
  if (t.lanes() == 1) {
    std::string value = this->PrintExpr(op->value);
671
    std::string ref  = this->GetBufferRef(t, op->buffer_var.get(), op->index);
672
    this->PrintIndent();
673
    stream << ref << " = " << value << ";\n";
674
  } else {
675 676
    CHECK(is_one(op->predicate))
        << "Predicated store is not supported";
677
    Expr base;
678
    if (GetRamp1Base(op->index, t.lanes(), &base)) {
679 680 681
      std::string value = this->PrintExpr(op->value);
      this->PrintVecStore(op->buffer_var.get(), t, base, value);
    } else {
682 683 684 685
      // The assignment below introduces side-effect, and the resulting value cannot
      // be reused across multiple expression, thus a new scope is needed
      int vec_scope = BeginScope();

686 687 688 689 690 691 692 693 694
      // store elements seperately
      std::string index = SSAGetID(PrintExpr(op->index), op->index.type());
      std::string value = SSAGetID(PrintExpr(op->value), op->value.type());
      std::string vid = GetVarID(op->buffer_var.get());
      for (int i = 0; i < t.lanes(); ++i) {
        this->PrintIndent();
        Type elem_type = t.element_of();
        if (!HandleTypeMatch(op->buffer_var.get(), elem_type)) {
          stream << "((";
695 696 697 698 699 700 701
          if (op->buffer_var.get()->type.is_handle()) {
            auto it = alloc_storage_scope_.find(op->buffer_var.get());
            if (it != alloc_storage_scope_.end()) {
              PrintStorageScope(it->second, stream);
              stream << ' ';
            }
          }
702 703 704 705 706 707 708 709 710 711 712
          PrintType(elem_type, stream);
          stream << "*)" << vid << ')';
        } else {
          stream << vid;
        }
        stream << '[';
        PrintVecElemLoad(index, op->index.type(), i, stream);
        stream << "] = ";
        PrintVecElemLoad(value, op->value.type(), i, stream);
        stream << ";\n";
      }
713
      EndScope(vec_scope);
714
    }
715
  }
716 717
}

718
void CodeGenC::VisitExpr_(const Let* op, std::ostream& os) {  // NOLINT(*)
719 720 721
  std::string value = PrintExpr(op->value);
  CHECK(!var_idmap_.count(op->var.get()));
  var_idmap_[op->var.get()] = value;
722
  os << PrintExpr(op->body);
723 724
}

725
void CodeGenC::VisitExpr_(const Ramp* op, std::ostream& os) {  // NOLINT(*)
726 727
  // constraint of current logic
  CHECK_EQ(op->base.type(), Int(32));
728 729 730 731 732 733 734
  os << "((int" << op->lanes << ")(";
  for (int i = 0; i < op->lanes; i++) {
    os << "(" << PrintExpr(op->base) << ")" << "+(" << PrintExpr(op->stride) << "*" << i <<")";
    if (i != op->lanes - 1)
      os << ", ";
  }
  os << "))";
735 736
}

737 738 739 740
void CodeGenC::VisitExpr_(const Shuffle* op, std::ostream& os) {
  LOG(FATAL) << "Shuffle: not supported ";
}

741
void CodeGenC::VisitExpr_(const Broadcast* op, std::ostream& os) {   // NOLINT(*)
742
  LOG(FATAL) << "Broadcast: not supported ";
743 744
}

745
void CodeGenC::VisitExpr_(const Select* op, std::ostream& os) {  // NOLINT(*)
746 747 748 749 750 751 752
  os << "(";
  PrintExpr(op->condition, os);
  os << " ? ";
  PrintExpr(op->true_value, os);
  os << " : ";
  PrintExpr(op->false_value, os);
  os << ")";
753 754
}

755
void CodeGenC::VisitStmt_(const LetStmt* op) {
756 757 758 759 760 761
  std::string value = PrintExpr(op->value);
  if (print_ssa_form_) {
    CHECK(!var_idmap_.count(op->var.get()));
    var_idmap_[op->var.get()] = value;
  } else {
    PrintIndent();
762 763 764 765 766 767 768 769 770 771 772 773 774 775
    if (op->var.type() == Handle() &&
        handle_data_type_.count(op->var.get())) {
      PrintType(handle_data_type_.at(op->var.get()), stream);
      stream << "* "
             << AllocVarID(op->var.get())
             << " = (";
      PrintType(handle_data_type_.at(op->var.get()), stream);
      stream << "*)"  << value << ";\n";
    } else {
      PrintType(op->var.type(), this->stream);
      this->stream << ' '
                   << AllocVarID(op->var.get())
                   << " = " << value << ";\n";
    }
776 777 778 779
  }
  PrintStmt(op->body);
}

780
void CodeGenC::VisitStmt_(const Allocate* op) {
781
  CHECK(!is_zero(op->condition));
782 783 784 785 786 787 788 789 790 791 792 793 794
  std::string vid = AllocVarID(op->buffer_var.get());
  if (op->new_expr.defined()) {
    // Prefer global static allocation for the program
    CHECK_EQ(op->free_function, "nop");
    std::string new_data = PrintExpr(op->new_expr);
    this->PrintIndent();
    PrintType(op->type, stream);
    stream << "* "<< vid << '=' << new_data << ";\n";
  } else {
    this->PrintIndent();
    int32_t constant_size = op->constant_allocation_size();
    CHECK_GT(constant_size, 0)
        << "Can only handle constant size stack allocation for now";
795 796 797
    const Variable* buffer = op->buffer_var.as<Variable>();
    std::string scope = alloc_storage_scope_.at(buffer);
    PrintStorageScope(scope, stream);
798
    stream << ' ';
799 800
    PrintType(op->type, stream);
    stream << ' '<< vid << '['
801
           << constant_size << "];\n";
802
  }
803
  RegisterHandleType(op->buffer_var.get(), op->type);
804 805 806
  this->PrintStmt(op->body);
}

807
void CodeGenC::VisitStmt_(const AttrStmt* op) {
808
  if (op->attr_key == ir::attr::thread_extent) {
809
    IterVar iv = Downcast<IterVar>(op->node);
810
    if (iv->thread_tag.length() != 0) {
811
      if (!var_idmap_.count(iv->var.get())) {
812
        BindThreadIndex(iv);
813
      }
814
    }
815
  } else if (op->attr_key == ir::attr::storage_scope) {
816 817 818
    const Variable* v = op->node.as<Variable>();
    CHECK(v);
    alloc_storage_scope_[v] = op->value.as<StringImm>()->value;
819
  } else if (op->attr_key == ir::attr::volatile_scope) {
820 821 822
    const Variable* v = op->node.as<Variable>();
    CHECK(v);
    volatile_buf_.insert(v);
823 824 825 826
  }
  this->PrintStmt(op->body);
}

827
void CodeGenC::VisitStmt_(const AssertStmt* op) {
828 829
  std::string cond = PrintExpr(op->condition);
  PrintIndent();
830
  if (const auto* str = op->message.as<StringImm>()) {
831
    // GLOG style check
832
    stream << "CHECK(" << cond << ") << \"" << str->value << "\";\n";
833 834 835
  } else {
    stream << "assert(" << cond << ");\n";
  }
836
  this->PrintStmt(op->body);
837 838
}

839
void CodeGenC::VisitStmt_(const For* op) {
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
  std::string extent = PrintExpr(op->extent);
  PrintIndent();
  std::string vid = AllocVarID(op->loop_var.get());
  CHECK(is_zero(op->min));
  stream << "for (";
  PrintType(op->loop_var.type(), stream);
  stream << ' ' << vid << " = 0; "
            << vid << " < " << extent
            << "; ++" << vid << ") {\n";
  int for_scope = BeginScope();
  PrintStmt(op->body);
  this->EndScope(for_scope);
  PrintIndent();
  stream << "}\n";
}

856
void CodeGenC::VisitStmt_(const IfThenElse* op) {
857 858
  std::string cond = PrintExpr(op->condition);
  PrintIndent();
859 860 861 862 863
  if (cond[0] == '(' && cond[cond.length() - 1] == ')') {
    stream << "if " << cond << " {\n";
  } else {
    stream << "if (" << cond << ") {\n";
  }
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
  int then_scope = BeginScope();
  PrintStmt(op->then_case);
  this->EndScope(then_scope);

  if (op->else_case.defined()) {
    PrintIndent();
    stream << "} else {\n";
    int else_scope = BeginScope();
    PrintStmt(op->else_case);
    this->EndScope(else_scope);
  }
  PrintIndent();
  stream << "}\n";
}

879 880 881 882 883 884 885 886
void CodeGenC::VisitStmt_(const Block *op) {
  PrintStmt(op->first);
  if (op->rest.defined()) PrintStmt(op->rest);
}

void CodeGenC::VisitStmt_(const Evaluate *op) {
  if (is_const(op->value)) return;
  const Call* call = op->value.as<Call>();
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
  if (call) {
    if (call->is_intrinsic(intrinsic::tvm_storage_sync)) {
      this->PrintStorageSync(call); return;
    } else if (call->is_intrinsic(intrinsic::tvm_struct_set)) {
      CHECK_EQ(call->args.size(), 4);
      std::string value = PrintExpr(call->args[3]);
      std::string ref = GetStructRef(
          call->args[3].type(),
          call->args[0],
          call->args[1],
          call->args[2].as<IntImm>()->value);
      this->PrintIndent();
      this->stream << ref << " = " << value << ";\n";
      return;
    }
902
  }
903
  std::string vid = this->PrintExpr(op->value);
904 905 906 907
  if (vid != "") {
    this->PrintIndent();
    this->stream << "(void)" << vid << ";\n";
  }
908 909 910 911 912
}

void CodeGenC::VisitStmt_(const ProducerConsumer *op) {
  PrintStmt(op->body);
}
913

914 915
}  // namespace codegen
}  // namespace tvm