cc-generator.cc 18.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/torque/cc-generator.h"

#include "src/common/globals.h"
#include "src/torque/global-context.h"
#include "src/torque/type-oracle.h"
#include "src/torque/types.h"
#include "src/torque/utils.h"

namespace v8 {
namespace internal {
namespace torque {

base::Optional<Stack<std::string>> CCGenerator::EmitGraph(
    Stack<std::string> parameters) {
  for (BottomOffset i = {0}; i < parameters.AboveTop(); ++i) {
    SetDefinitionVariable(DefinitionLocation::Parameter(i.offset),
                          parameters.Peek(i));
  }

  // Redirect the output of non-declarations into a buffer and only output
  // declarations right away.
  std::stringstream out_buffer;
  std::ostream* old_out = out_;
  out_ = &out_buffer;

  EmitInstruction(GotoInstruction{cfg_.start()}, &parameters);

  for (Block* block : cfg_.blocks()) {
    if (cfg_.end() && *cfg_.end() == block) continue;
    if (block->IsDead()) continue;
    EmitBlock(block);
  }

  base::Optional<Stack<std::string>> result;
  if (cfg_.end()) {
    result = EmitBlock(*cfg_.end());
  }

  // All declarations have been printed now, so we can append the buffered
  // output and redirect back to the original output stream.
  out_ = old_out;
  out() << out_buffer.str();

  return result;
}

Stack<std::string> CCGenerator::EmitBlock(const Block* block) {
  out() << "\n";
  out() << "  " << BlockName(block) << ":\n";

  Stack<std::string> stack;

  for (BottomOffset i = {0}; i < block->InputTypes().AboveTop(); ++i) {
    const auto& def = block->InputDefinitions().Peek(i);
    stack.Push(DefinitionToVariable(def));
    if (def.IsPhiFromBlock(block)) {
61 62 63 64
      decls() << "  "
              << (is_cc_debug_ ? block->InputTypes().Peek(i)->GetDebugType()
                               : block->InputTypes().Peek(i)->GetRuntimeType())
              << " " << stack.Top() << "{}; USE(" << stack.Top() << ");\n";
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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    }
  }

  for (const Instruction& instruction : block->instructions()) {
    TorqueCodeGenerator::EmitInstruction(instruction, &stack);
  }
  return stack;
}

void CCGenerator::EmitSourcePosition(SourcePosition pos, bool always_emit) {
  const std::string& file = SourceFileMap::AbsolutePath(pos.source);
  if (always_emit || !previous_position_.CompareStartIgnoreColumn(pos)) {
    // Lines in Torque SourcePositions are zero-based, while the
    // CodeStubAssembler and downwind systems are one-based.
    out() << "  // " << file << ":" << (pos.start.line + 1) << "\n";
    previous_position_ = pos;
  }
}

void CCGenerator::EmitInstruction(
    const PushUninitializedInstruction& instruction,
    Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: PushUninitialized");
}

void CCGenerator::EmitInstruction(
    const PushBuiltinPointerInstruction& instruction,
    Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: PushBuiltinPointer");
}

void CCGenerator::EmitInstruction(
    const NamespaceConstantInstruction& instruction,
    Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: NamespaceConstantInstruction");
}

std::vector<std::string> CCGenerator::ProcessArgumentsCommon(
    const TypeVector& parameter_types,
    std::vector<std::string> constexpr_arguments, Stack<std::string>* stack) {
  std::vector<std::string> args;
  for (auto it = parameter_types.rbegin(); it != parameter_types.rend(); ++it) {
    const Type* type = *it;
    VisitResult arg;
    if (type->IsConstexpr()) {
      args.push_back(std::move(constexpr_arguments.back()));
      constexpr_arguments.pop_back();
    } else {
      std::stringstream s;
      size_t slot_count = LoweredSlotCount(type);
      VisitResult arg = VisitResult(type, stack->TopRange(slot_count));
      EmitCCValue(arg, *stack, s);
      args.push_back(s.str());
      stack->PopMany(slot_count);
    }
  }
  std::reverse(args.begin(), args.end());
  return args;
}

void CCGenerator::EmitInstruction(const CallIntrinsicInstruction& instruction,
                                  Stack<std::string>* stack) {
  TypeVector parameter_types =
      instruction.intrinsic->signature().parameter_types.types;
  std::vector<std::string> args = ProcessArgumentsCommon(
      parameter_types, instruction.constexpr_arguments, stack);

  Stack<std::string> pre_call_stack = *stack;
  const Type* return_type = instruction.intrinsic->signature().return_type;
  std::vector<std::string> results;

  const auto lowered = LowerType(return_type);
  for (std::size_t i = 0; i < lowered.size(); ++i) {
    results.push_back(DefinitionToVariable(instruction.GetValueDefinition(i)));
    stack->Push(results.back());
140 141 142 143
    decls() << "  "
            << (is_cc_debug_ ? lowered[i]->GetDebugType()
                             : lowered[i]->GetRuntimeType())
            << " " << stack->Top() << "{}; USE(" << stack->Top() << ");\n";
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
  }

  out() << "  ";
  if (return_type->StructSupertype()) {
    out() << "std::tie(";
    PrintCommaSeparatedList(out(), results);
    out() << ") = ";
  } else {
    if (results.size() == 1) {
      out() << results[0] << " = ";
    }
  }

  if (instruction.intrinsic->ExternalName() == "%RawDownCast") {
    if (parameter_types.size() != 1) {
      ReportError("%RawDownCast must take a single parameter");
    }
    const Type* original_type = parameter_types[0];
    bool is_subtype =
        return_type->IsSubtypeOf(original_type) ||
        (original_type == TypeOracle::GetUninitializedHeapObjectType() &&
         return_type->IsSubtypeOf(TypeOracle::GetHeapObjectType()));
    if (!is_subtype) {
      ReportError("%RawDownCast error: ", *return_type, " is not a subtype of ",
                  *original_type);
    }
    if (!original_type->StructSupertype() &&
        return_type->GetRuntimeType() != original_type->GetRuntimeType()) {
      out() << "static_cast<" << return_type->GetRuntimeType() << ">";
    }
  } else if (instruction.intrinsic->ExternalName() == "%GetClassMapConstant") {
    ReportError("C++ generator doesn't yet support %GetClassMapConstant");
  } else if (instruction.intrinsic->ExternalName() == "%FromConstexpr") {
    if (parameter_types.size() != 1 || !parameter_types[0]->IsConstexpr()) {
      ReportError(
          "%FromConstexpr must take a single parameter with constexpr "
          "type");
    }
    if (return_type->IsConstexpr()) {
      ReportError("%FromConstexpr must return a non-constexpr type");
    }
185 186 187 188 189 190 191 192 193 194
    if (return_type->IsSubtypeOf(TypeOracle::GetSmiType())) {
      if (is_cc_debug_) {
        out() << "Internals::IntToSmi";
      } else {
        out() << "Smi::FromInt";
      }
    }
    // Wrap the raw constexpr value in a static_cast to ensure that
    // enums get properly casted to their backing integral value.
    out() << "(CastToUnderlyingTypeIfEnum";
195 196 197 198 199 200 201
  } else {
    ReportError("no built in intrinsic with name " +
                instruction.intrinsic->ExternalName());
  }

  out() << "(";
  PrintCommaSeparatedList(out(), args);
202 203 204
  if (instruction.intrinsic->ExternalName() == "%FromConstexpr") {
    out() << ")";
  }
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  out() << ");\n";
}

void CCGenerator::EmitInstruction(const CallCsaMacroInstruction& instruction,
                                  Stack<std::string>* stack) {
  TypeVector parameter_types =
      instruction.macro->signature().parameter_types.types;
  std::vector<std::string> args = ProcessArgumentsCommon(
      parameter_types, instruction.constexpr_arguments, stack);

  Stack<std::string> pre_call_stack = *stack;
  const Type* return_type = instruction.macro->signature().return_type;
  std::vector<std::string> results;

  const auto lowered = LowerType(return_type);
  for (std::size_t i = 0; i < lowered.size(); ++i) {
    results.push_back(DefinitionToVariable(instruction.GetValueDefinition(i)));
    stack->Push(results.back());
223 224 225 226
    decls() << "  "
            << (is_cc_debug_ ? lowered[i]->GetDebugType()
                             : lowered[i]->GetRuntimeType())
            << " " << stack->Top() << "{}; USE(" << stack->Top() << ");\n";
227 228 229 230
  }

  // We should have inlined any calls requiring complex control flow.
  CHECK(!instruction.catch_block);
231
  out() << (is_cc_debug_ ? "  ASSIGN_OR_RETURN(" : "  ");
232 233 234
  if (return_type->StructSupertype().has_value()) {
    out() << "std::tie(";
    PrintCommaSeparatedList(out(), results);
235
    out() << (is_cc_debug_ ? "), " : ") = ");
236 237
  } else {
    if (results.size() == 1) {
238
      out() << results[0] << (is_cc_debug_ ? ", " : " = ");
239 240 241 242 243
    } else {
      DCHECK_EQ(0, results.size());
    }
  }

244 245
  if (is_cc_debug_) {
    out() << instruction.macro->CCDebugName() << "(accessor";
246
    if (!args.empty()) out() << ", ";
247
  } else {
248
    out() << instruction.macro->CCName() << "(";
249
  }
250
  PrintCommaSeparatedList(out(), args);
251 252 253 254 255
  if (is_cc_debug_) {
    out() << "));\n";
  } else {
    out() << ");\n";
  }
256 257 258 259 260 261 262 263
}

void CCGenerator::EmitInstruction(
    const CallCsaMacroAndBranchInstruction& instruction,
    Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: CallCsaMacroAndBranch");
}

264 265 266 267 268
void CCGenerator::EmitInstruction(const MakeLazyNodeInstruction& instruction,
                                  Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: MakeLazyNode");
}

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 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
void CCGenerator::EmitInstruction(const CallBuiltinInstruction& instruction,
                                  Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: CallBuiltin");
}

void CCGenerator::EmitInstruction(
    const CallBuiltinPointerInstruction& instruction,
    Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: CallBuiltinPointer");
}

void CCGenerator::EmitInstruction(const CallRuntimeInstruction& instruction,
                                  Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: CallRuntime");
}

void CCGenerator::EmitInstruction(const BranchInstruction& instruction,
                                  Stack<std::string>* stack) {
  out() << "  if (" << stack->Pop() << ") {\n";
  EmitGoto(instruction.if_true, stack, "    ");
  out() << "  } else {\n";
  EmitGoto(instruction.if_false, stack, "    ");
  out() << "  }\n";
}

void CCGenerator::EmitInstruction(const ConstexprBranchInstruction& instruction,
                                  Stack<std::string>* stack) {
  out() << "  if ((" << instruction.condition << ")) {\n";
  EmitGoto(instruction.if_true, stack, "    ");
  out() << "  } else {\n";
  EmitGoto(instruction.if_false, stack, "    ");
  out() << "  }\n";
}

void CCGenerator::EmitGoto(const Block* destination, Stack<std::string>* stack,
                           std::string indentation) {
  const auto& destination_definitions = destination->InputDefinitions();
  DCHECK_EQ(stack->Size(), destination_definitions.Size());
  for (BottomOffset i = {0}; i < stack->AboveTop(); ++i) {
    DefinitionLocation def = destination_definitions.Peek(i);
    if (def.IsPhiFromBlock(destination)) {
      out() << indentation << DefinitionToVariable(def) << " = "
            << stack->Peek(i) << ";\n";
    }
  }
  out() << indentation << "goto " << BlockName(destination) << ";\n";
}

void CCGenerator::EmitInstruction(const GotoInstruction& instruction,
                                  Stack<std::string>* stack) {
  EmitGoto(instruction.destination, stack, "  ");
}

void CCGenerator::EmitInstruction(const GotoExternalInstruction& instruction,
                                  Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: GotoExternal");
}

void CCGenerator::EmitInstruction(const ReturnInstruction& instruction,
                                  Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: Return");
}

void CCGenerator::EmitInstruction(
    const PrintConstantStringInstruction& instruction,
    Stack<std::string>* stack) {
  out() << "  std::cout << " << StringLiteralQuote(instruction.message)
        << ";\n";
}

void CCGenerator::EmitInstruction(const AbortInstruction& instruction,
                                  Stack<std::string>* stack) {
  switch (instruction.kind) {
    case AbortInstruction::Kind::kUnreachable:
      DCHECK(instruction.message.empty());
      out() << "  UNREACHABLE();\n";
      break;
    case AbortInstruction::Kind::kDebugBreak:
      DCHECK(instruction.message.empty());
      out() << "  base::OS::DebugBreak();\n";
      break;
    case AbortInstruction::Kind::kAssertionFailure: {
      std::string file = StringLiteralQuote(
          SourceFileMap::PathFromV8Root(instruction.pos.source));
      out() << "  CHECK(false, \"Failed Torque assertion: '\""
            << StringLiteralQuote(instruction.message) << "\"' at \"" << file
            << "\":\""
            << StringLiteralQuote(
                   std::to_string(instruction.pos.start.line + 1))
            << ");\n";
      break;
    }
  }
}

void CCGenerator::EmitInstruction(const UnsafeCastInstruction& instruction,
                                  Stack<std::string>* stack) {
  const std::string str = "static_cast<" +
                          instruction.destination_type->GetRuntimeType() +
                          ">(" + stack->Top() + ")";
  stack->Poke(stack->AboveTop() - 1, str);
  SetDefinitionVariable(instruction.GetValueDefinition(), str);
}

void CCGenerator::EmitInstruction(const LoadReferenceInstruction& instruction,
                                  Stack<std::string>* stack) {
  std::string result_name =
      DefinitionToVariable(instruction.GetValueDefinition());

  std::string offset = stack->Pop();
  std::string object = stack->Pop();
  stack->Push(result_name);

382 383 384 385 386 387
  if (!is_cc_debug_) {
    std::string result_type = instruction.type->GetRuntimeType();
    decls() << "  " << result_type << " " << result_name << "{}; USE("
            << result_name << ");\n";
    out() << "  " << result_name << " = ";
    if (instruction.type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
388
      // Currently, all of the tagged loads we emit are for smi values, so there
389
      // is no point in providing an PtrComprCageBase. If at some point we start
390
      // emitting loads for tagged fields which might be HeapObjects, then we
391 392
      // should plumb an PtrComprCageBase through the generated functions that
      // need it.
393 394 395 396 397 398 399 400 401 402 403 404
      if (!instruction.type->IsSubtypeOf(TypeOracle::GetSmiType())) {
        Error(
            "Not supported in C++ output: LoadReference on non-smi tagged "
            "value");
      }

      // References and slices can cause some values to have the Torque type
      // HeapObject|TaggedZeroPattern, which is output as "Object". TaggedField
      // requires HeapObject, so we need a cast.
      out() << "TaggedField<" << result_type
            << ">::load(*static_cast<HeapObject*>(&" << object
            << "), static_cast<int>(" << offset << "));\n";
405 406 407 408
    } else {
      out() << "(" << object << ").ReadField<" << result_type << ">(" << offset
            << ");\n";
    }
409
  } else {
410 411 412 413 414 415 416 417 418 419
    std::string result_type = instruction.type->GetDebugType();
    decls() << "  " << result_type << " " << result_name << "{}; USE("
            << result_name << ");\n";
    if (instruction.type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
      out() << "  READ_TAGGED_FIELD_OR_FAIL(" << result_name << ", accessor, "
            << object << ", static_cast<int>(" << offset << "));\n";
    } else {
      out() << "  READ_FIELD_OR_FAIL(" << result_type << ", " << result_name
            << ", accessor, " << object << ", " << offset << ");\n";
    }
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
  }
}

void CCGenerator::EmitInstruction(const StoreReferenceInstruction& instruction,
                                  Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: StoreReference");
}

namespace {
std::string GetBitFieldSpecialization(const Type* container,
                                      const BitField& field) {
  std::stringstream stream;
  stream << "base::BitField<"
         << field.name_and_type.type->GetConstexprGeneratedTypeName() << ", "
         << field.offset << ", " << field.num_bits << ", "
         << container->GetConstexprGeneratedTypeName() << ">";
  return stream.str();
}
}  // namespace

void CCGenerator::EmitInstruction(const LoadBitFieldInstruction& instruction,
                                  Stack<std::string>* stack) {
  std::string result_name =
      DefinitionToVariable(instruction.GetValueDefinition());

  std::string bit_field_struct = stack->Pop();
  stack->Push(result_name);

  const Type* struct_type = instruction.bit_field_struct_type;

  decls() << "  " << instruction.bit_field.name_and_type.type->GetRuntimeType()
          << " " << result_name << "{}; USE(" << result_name << ");\n";

  base::Optional<const Type*> smi_tagged_type =
      Type::MatchUnaryGeneric(struct_type, TypeOracle::GetSmiTaggedGeneric());
  if (smi_tagged_type) {
    // Get the untagged value and its type.
457 458 459 460 461
    if (is_cc_debug_) {
      bit_field_struct = "Internals::SmiValue(" + bit_field_struct + ")";
    } else {
      bit_field_struct = bit_field_struct + ".value()";
    }
462 463 464
    struct_type = *smi_tagged_type;
  }

465
  out() << "  " << result_name << " = CastToUnderlyingTypeIfEnum("
466
        << GetBitFieldSpecialization(struct_type, instruction.bit_field)
467
        << "::decode(" << bit_field_struct << "));\n";
468 469 470 471 472 473 474
}

void CCGenerator::EmitInstruction(const StoreBitFieldInstruction& instruction,
                                  Stack<std::string>* stack) {
  ReportError("Not supported in C++ output: StoreBitField");
}

475 476 477 478 479
namespace {

void CollectAllFields(const VisitResult& result,
                      const Stack<std::string>& values,
                      std::vector<std::string>& all_fields) {
480
  if (!result.IsOnStack()) {
481
    all_fields.push_back(result.constexpr_value());
482
  } else if (auto struct_type = result.type()->StructSupertype()) {
483 484 485
    for (const Field& field : (*struct_type)->fields()) {
      CollectAllFields(ProjectStructField(result, field.name_and_type.name),
                       values, all_fields);
486 487 488
    }
  } else {
    DCHECK_EQ(1, result.stack_range().Size());
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    all_fields.push_back(values.Peek(result.stack_range().begin()));
  }
}

}  // namespace

// static
void CCGenerator::EmitCCValue(VisitResult result,
                              const Stack<std::string>& values,
                              std::ostream& out) {
  std::vector<std::string> all_fields;
  CollectAllFields(result, values, all_fields);
  if (all_fields.size() == 1) {
    out << all_fields[0];
  } else {
    out << "std::make_tuple(";
    PrintCommaSeparatedList(out, all_fields);
    out << ")";
507 508 509 510 511 512
  }
}

}  // namespace torque
}  // namespace internal
}  // namespace v8