v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
cc-generator.cc
Go to the documentation of this file.
1// Copyright 2020 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
6
7#include <optional>
8
12#include "src/torque/types.h"
13#include "src/torque/utils.h"
14
15namespace v8::internal::torque {
16
17std::optional<Stack<std::string>> CCGenerator::EmitGraph(
18 Stack<std::string> parameters) {
19 for (BottomOffset i = {0}; i < parameters.AboveTop(); ++i) {
21 parameters.Peek(i));
22 }
23
24 // Redirect the output of non-declarations into a buffer and only output
25 // declarations right away.
26 std::stringstream out_buffer;
27 std::ostream* old_out = out_;
28 out_ = &out_buffer;
29
30 EmitInstruction(GotoInstruction{cfg_.start()}, &parameters);
31
32 for (Block* block : cfg_.blocks()) {
33 if (cfg_.end() && *cfg_.end() == block) continue;
34 if (block->IsDead()) continue;
35 EmitBlock(block);
36 }
37
38 std::optional<Stack<std::string>> result;
39 if (cfg_.end()) {
40 result = EmitBlock(*cfg_.end());
41 }
42
43 // All declarations have been printed now, so we can append the buffered
44 // output and redirect back to the original output stream.
45 out_ = old_out;
46 out() << out_buffer.str();
47
48 return result;
49}
50
52 out() << "\n";
53 out() << " " << BlockName(block) << ":\n";
54
56
57 for (BottomOffset i = {0}; i < block->InputTypes().AboveTop(); ++i) {
58 const auto& def = block->InputDefinitions().Peek(i);
59 stack.Push(DefinitionToVariable(def));
60 if (def.IsPhiFromBlock(block)) {
61 decls() << " "
62 << (is_cc_debug_ ? block->InputTypes().Peek(i)->GetDebugType()
63 : block->InputTypes().Peek(i)->GetRuntimeType())
64 << " " << stack.Top() << "{}; USE(" << stack.Top() << ");\n";
65 }
66 }
67
68 for (const Instruction& instruction : block->instructions()) {
69 TorqueCodeGenerator::EmitInstruction(instruction, &stack);
70 }
71 return stack;
72}
73
75 const std::string& file = SourceFileMap::AbsolutePath(pos.source);
76 if (always_emit || !previous_position_.CompareStartIgnoreColumn(pos)) {
77 // Lines in Torque SourcePositions are zero-based, while the
78 // CodeStubAssembler and downwind systems are one-based.
79 out() << " // " << file << ":" << (pos.start.line + 1) << "\n";
81 }
82}
83
85 const PushUninitializedInstruction& instruction,
86 Stack<std::string>* stack) {
87 ReportError("Not supported in C++ output: PushUninitialized");
88}
89
91 const PushBuiltinPointerInstruction& instruction,
92 Stack<std::string>* stack) {
93 ReportError("Not supported in C++ output: PushBuiltinPointer");
94}
95
97 const NamespaceConstantInstruction& instruction,
98 Stack<std::string>* stack) {
99 ReportError("Not supported in C++ output: NamespaceConstantInstruction");
100}
101
102std::vector<std::string> CCGenerator::ProcessArgumentsCommon(
103 const TypeVector& parameter_types,
104 std::vector<std::string> constexpr_arguments, Stack<std::string>* stack) {
105 std::vector<std::string> args;
106 for (auto it = parameter_types.rbegin(); it != parameter_types.rend(); ++it) {
107 const Type* type = *it;
108 if (type->IsConstexpr()) {
109 args.push_back(std::move(constexpr_arguments.back()));
110 constexpr_arguments.pop_back();
111 } else {
112 std::stringstream s;
113 size_t slot_count = LoweredSlotCount(type);
114 VisitResult arg = VisitResult(type, stack->TopRange(slot_count));
115 EmitCCValue(arg, *stack, s);
116 args.push_back(s.str());
117 stack->PopMany(slot_count);
118 }
119 }
120 std::reverse(args.begin(), args.end());
121 return args;
122}
123
125 Stack<std::string>* stack) {
126 TypeVector parameter_types =
127 instruction.intrinsic->signature().parameter_types.types;
128 std::vector<std::string> args = ProcessArgumentsCommon(
129 parameter_types, instruction.constexpr_arguments, stack);
130
131 Stack<std::string> pre_call_stack = *stack;
132 const Type* return_type = instruction.intrinsic->signature().return_type;
133 std::vector<std::string> results;
134
135 const auto lowered = LowerType(return_type);
136 for (std::size_t i = 0; i < lowered.size(); ++i) {
137 results.push_back(DefinitionToVariable(instruction.GetValueDefinition(i)));
138 stack->Push(results.back());
139 decls() << " "
140 << (is_cc_debug_ ? lowered[i]->GetDebugType()
141 : lowered[i]->GetRuntimeType())
142 << " " << stack->Top() << "{}; USE(" << stack->Top() << ");\n";
143 }
144
145 out() << " ";
146 if (return_type->StructSupertype()) {
147 out() << "std::tie(";
148 PrintCommaSeparatedList(out(), results);
149 out() << ") = ";
150 } else {
151 if (results.size() == 1) {
152 out() << results[0] << " = ";
153 }
154 }
155
156 if (instruction.intrinsic->ExternalName() == "%RawDownCast") {
157 if (parameter_types.size() != 1) {
158 ReportError("%RawDownCast must take a single parameter");
159 }
160 const Type* original_type = parameter_types[0];
161 bool is_subtype =
162 return_type->IsSubtypeOf(original_type) ||
163 (original_type == TypeOracle::GetUninitializedHeapObjectType() &&
165 if (!is_subtype) {
166 ReportError("%RawDownCast error: ", *return_type, " is not a subtype of ",
167 *original_type);
168 }
169 if (!original_type->StructSupertype() &&
170 return_type->GetRuntimeType() != original_type->GetRuntimeType()) {
171 out() << "static_cast<" << return_type->GetRuntimeType() << ">";
172 }
173 } else if (instruction.intrinsic->ExternalName() == "%GetClassMapConstant") {
174 ReportError("C++ generator doesn't yet support %GetClassMapConstant");
175 } else if (instruction.intrinsic->ExternalName() == "%FromConstexpr") {
176 if (parameter_types.size() != 1 || !parameter_types[0]->IsConstexpr()) {
178 "%FromConstexpr must take a single parameter with constexpr "
179 "type");
180 }
181 if (return_type->IsConstexpr()) {
182 ReportError("%FromConstexpr must return a non-constexpr type");
183 }
184 if (return_type->IsSubtypeOf(TypeOracle::GetSmiType())) {
185 if (is_cc_debug_) {
186 out() << "Internals::IntToSmi";
187 } else {
188 out() << "Smi::FromInt";
189 }
190 }
191 // Wrap the raw constexpr value in a static_cast to ensure that
192 // enums get properly casted to their backing integral value.
193 out() << "(CastToUnderlyingTypeIfEnum";
194 } else {
195 ReportError("no built in intrinsic with name " +
196 instruction.intrinsic->ExternalName());
197 }
198
199 out() << "(";
201 if (instruction.intrinsic->ExternalName() == "%FromConstexpr") {
202 out() << ")";
203 }
204 out() << ");\n";
205}
206
207void CCGenerator::EmitInstruction(const CallCsaMacroInstruction& instruction,
208 Stack<std::string>* stack) {
209 TypeVector parameter_types =
210 instruction.macro->signature().parameter_types.types;
211 std::vector<std::string> args = ProcessArgumentsCommon(
212 parameter_types, instruction.constexpr_arguments, stack);
213
214 Stack<std::string> pre_call_stack = *stack;
215 const Type* return_type = instruction.macro->signature().return_type;
216 std::vector<std::string> results;
217
218 const auto lowered = LowerType(return_type);
219 for (std::size_t i = 0; i < lowered.size(); ++i) {
220 results.push_back(DefinitionToVariable(instruction.GetValueDefinition(i)));
221 stack->Push(results.back());
222 decls() << " "
223 << (is_cc_debug_ ? lowered[i]->GetDebugType()
224 : lowered[i]->GetRuntimeType())
225 << " " << stack->Top() << "{}; USE(" << stack->Top() << ");\n";
226 }
227
228 // We should have inlined any calls requiring complex control flow.
229 CHECK(!instruction.catch_block);
230 out() << (is_cc_debug_ ? " ASSIGN_OR_RETURN(" : " ");
231 if (return_type->StructSupertype().has_value()) {
232 out() << "std::tie(";
233 PrintCommaSeparatedList(out(), results);
234 out() << (is_cc_debug_ ? "), " : ") = ");
235 } else {
236 if (results.size() == 1) {
237 out() << results[0] << (is_cc_debug_ ? ", " : " = ");
238 } else {
239 DCHECK_EQ(0, results.size());
240 }
241 }
242
243 if (is_cc_debug_) {
244 out() << instruction.macro->CCDebugName() << "(accessor";
245 if (!args.empty()) out() << ", ";
246 } else {
247 out() << instruction.macro->CCName() << "(";
248 }
250 if (is_cc_debug_) {
251 out() << "));\n";
252 } else {
253 out() << ");\n";
254 }
255}
256
258 const CallCsaMacroAndBranchInstruction& instruction,
259 Stack<std::string>* stack) {
260 ReportError("Not supported in C++ output: CallCsaMacroAndBranch");
261}
262
263void CCGenerator::EmitInstruction(const MakeLazyNodeInstruction& instruction,
264 Stack<std::string>* stack) {
265 ReportError("Not supported in C++ output: MakeLazyNode");
266}
267
268void CCGenerator::EmitInstruction(const CallBuiltinInstruction& instruction,
269 Stack<std::string>* stack) {
270 ReportError("Not supported in C++ output: CallBuiltin");
271}
272
274 const CallBuiltinPointerInstruction& instruction,
275 Stack<std::string>* stack) {
276 ReportError("Not supported in C++ output: CallBuiltinPointer");
277}
278
279void CCGenerator::EmitInstruction(const CallRuntimeInstruction& instruction,
280 Stack<std::string>* stack) {
281 ReportError("Not supported in C++ output: CallRuntime");
282}
283
284void CCGenerator::EmitInstruction(const BranchInstruction& instruction,
285 Stack<std::string>* stack) {
286 out() << " if (" << stack->Pop() << ") {\n";
287 EmitGoto(instruction.if_true, stack, " ");
288 out() << " } else {\n";
289 EmitGoto(instruction.if_false, stack, " ");
290 out() << " }\n";
291}
292
293void CCGenerator::EmitInstruction(const ConstexprBranchInstruction& instruction,
294 Stack<std::string>* stack) {
295 out() << " if ((" << instruction.condition << ")) {\n";
296 EmitGoto(instruction.if_true, stack, " ");
297 out() << " } else {\n";
298 EmitGoto(instruction.if_false, stack, " ");
299 out() << " }\n";
300}
301
303 std::string indentation) {
304 const auto& destination_definitions = destination->InputDefinitions();
305 DCHECK_EQ(stack->Size(), destination_definitions.Size());
306 for (BottomOffset i = {0}; i < stack->AboveTop(); ++i) {
307 DefinitionLocation def = destination_definitions.Peek(i);
308 if (def.IsPhiFromBlock(destination)) {
309 out() << indentation << DefinitionToVariable(def) << " = "
310 << stack->Peek(i) << ";\n";
311 }
312 }
313 out() << indentation << "goto " << BlockName(destination) << ";\n";
314}
315
316void CCGenerator::EmitInstruction(const GotoInstruction& instruction,
317 Stack<std::string>* stack) {
318 EmitGoto(instruction.destination, stack, " ");
319}
320
321void CCGenerator::EmitInstruction(const GotoExternalInstruction& instruction,
322 Stack<std::string>* stack) {
323 ReportError("Not supported in C++ output: GotoExternal");
324}
325
326void CCGenerator::EmitInstruction(const ReturnInstruction& instruction,
327 Stack<std::string>* stack) {
328 ReportError("Not supported in C++ output: Return");
329}
330
331void CCGenerator::EmitInstruction(const PrintErrorInstruction& instruction,
332 Stack<std::string>* stack) {
333 out() << " std::cerr << " << StringLiteralQuote(instruction.message)
334 << ";\n";
335}
336
337void CCGenerator::EmitInstruction(const AbortInstruction& instruction,
338 Stack<std::string>* stack) {
339 switch (instruction.kind) {
341 DCHECK(instruction.message.empty());
342 out() << " UNREACHABLE();\n";
343 break;
345 DCHECK(instruction.message.empty());
346 out() << " base::OS::DebugBreak();\n";
347 break;
349 std::string file = StringLiteralQuote(
350 SourceFileMap::PathFromV8Root(instruction.pos.source));
351 out() << " CHECK(false, \"Failed Torque assertion: '\""
352 << StringLiteralQuote(instruction.message) << "\"' at \"" << file
353 << "\":\""
355 std::to_string(instruction.pos.start.line + 1))
356 << ");\n";
357 break;
358 }
359 }
360}
361
362void CCGenerator::EmitInstruction(const UnsafeCastInstruction& instruction,
363 Stack<std::string>* stack) {
364 const std::string str = "static_cast<" +
365 instruction.destination_type->GetRuntimeType() +
366 ">(" + stack->Top() + ")";
367 stack->Poke(stack->AboveTop() - 1, str);
368 SetDefinitionVariable(instruction.GetValueDefinition(), str);
369}
370
371void CCGenerator::EmitInstruction(const LoadReferenceInstruction& instruction,
372 Stack<std::string>* stack) {
373 std::string result_name =
374 DefinitionToVariable(instruction.GetValueDefinition());
375
376 std::string offset = stack->Pop();
377 std::string object = stack->Pop();
378 stack->Push(result_name);
379
380 if (!is_cc_debug_) {
381 std::string result_type = instruction.type->GetRuntimeType();
382 decls() << " " << result_type << " " << result_name << "{}; USE("
383 << result_name << ");\n";
384 out() << " " << result_name << " = ";
385 if (instruction.type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
386 // Currently, all of the tagged loads we emit are for smi values, so there
387 // is no point in providing an PtrComprCageBase. If at some point we start
388 // emitting loads for tagged fields which might be HeapObjects, then we
389 // should plumb an PtrComprCageBase through the generated functions that
390 // need it.
391 if (!instruction.type->IsSubtypeOf(TypeOracle::GetSmiType())) {
392 Error(
393 "Not supported in C++ output: LoadReference on non-smi tagged "
394 "value");
395 }
396 if (instruction.synchronization != FieldSynchronization::kNone) {
397 // TODO(ishell): generate proper TaggedField<..>::load() call once
398 // there's a real use case.
400 "Torque doesn't support @cppRelaxedLoad/@cppAcquireLoad on tagged "
401 "data");
402 }
403 // References and slices can cause some values to have the Torque type
404 // HeapObject|TaggedZeroPattern, which is output as "Object". TaggedField
405 // requires HeapObject, so we need a cast.
406 out() << "TaggedField<" << result_type
407 << ">::load(UncheckedCast<HeapObject>(" << object
408 << "), static_cast<int>(" << offset << "));\n";
409 } else {
410 // This code replicates the way we load the field in accessors, see
411 // CppClassGenerator::EmitLoadFieldStatement().
412 const char* load;
413 switch (instruction.synchronization) {
415 load = "ReadField";
416 break;
418 load = "Relaxed_ReadField";
419 break;
422 "Torque doesn't support @cppAcquireLoad on untagged data");
423 }
424 out() << "(" << object << ")->" << load << "<" << result_type << ">("
425 << offset << ");\n";
426 }
427 } else {
428 std::string result_type = instruction.type->GetDebugType();
429 decls() << " " << result_type << " " << result_name << "{}; USE("
430 << result_name << ");\n";
431 if (instruction.type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
432 out() << " READ_TAGGED_FIELD_OR_FAIL(" << result_name << ", accessor, "
433 << object << ", static_cast<int>(" << offset << "));\n";
434 } else {
435 out() << " READ_FIELD_OR_FAIL(" << result_type << ", " << result_name
436 << ", accessor, " << object << ", " << offset << ");\n";
437 }
438 }
439}
440
441void CCGenerator::EmitInstruction(const StoreReferenceInstruction& instruction,
442 Stack<std::string>* stack) {
443 ReportError("Not supported in C++ output: StoreReference");
444}
445
446namespace {
447std::string GetBitFieldSpecialization(const Type* container,
448 const BitField& field) {
449 std::stringstream stream;
450 stream << "base::BitField<"
451 << field.name_and_type.type->GetConstexprGeneratedTypeName() << ", "
452 << field.offset << ", " << field.num_bits << ", "
453 << container->GetConstexprGeneratedTypeName() << ">";
454 return stream.str();
455}
456} // namespace
457
458void CCGenerator::EmitInstruction(const LoadBitFieldInstruction& instruction,
459 Stack<std::string>* stack) {
460 std::string result_name =
461 DefinitionToVariable(instruction.GetValueDefinition());
462
463 std::string bit_field_struct = stack->Pop();
464 stack->Push(result_name);
465
466 const Type* struct_type = instruction.bit_field_struct_type;
467
468 decls() << " " << instruction.bit_field.name_and_type.type->GetRuntimeType()
469 << " " << result_name << "{}; USE(" << result_name << ");\n";
470
471 std::optional<const Type*> smi_tagged_type =
473 if (smi_tagged_type) {
474 // Get the untagged value and its type.
475 if (is_cc_debug_) {
476 bit_field_struct = "Internals::SmiValue(" + bit_field_struct + ")";
477 } else {
478 bit_field_struct = bit_field_struct + ".value()";
479 }
480 struct_type = *smi_tagged_type;
481 }
482
483 out() << " " << result_name << " = CastToUnderlyingTypeIfEnum("
484 << GetBitFieldSpecialization(struct_type, instruction.bit_field)
485 << "::decode(" << bit_field_struct << "));\n";
486}
487
488void CCGenerator::EmitInstruction(const StoreBitFieldInstruction& instruction,
489 Stack<std::string>* stack) {
490 ReportError("Not supported in C++ output: StoreBitField");
491}
492
493namespace {
494
495void CollectAllFields(const VisitResult& result,
496 const Stack<std::string>& values,
497 std::vector<std::string>& all_fields) {
498 if (!result.IsOnStack()) {
499 all_fields.push_back(result.constexpr_value());
500 } else if (auto struct_type = result.type()->StructSupertype()) {
501 for (const Field& field : (*struct_type)->fields()) {
502 CollectAllFields(ProjectStructField(result, field.name_and_type.name),
503 values, all_fields);
504 }
505 } else {
506 DCHECK_EQ(1, result.stack_range().Size());
507 all_fields.push_back(values.Peek(result.stack_range().begin()));
508 }
509}
510
511} // namespace
512
513// static
515 const Stack<std::string>& values,
516 std::ostream& out) {
517 std::vector<std::string> all_fields;
518 CollectAllFields(result, values, all_fields);
519 if (all_fields.size() == 1) {
520 out << all_fields[0];
521 } else {
522 out << "std::make_tuple(";
523 PrintCommaSeparatedList(out, all_fields);
524 out << ")";
525 }
526}
527
528} // namespace v8::internal::torque
SourcePosition pos
std::optional< Stack< std::string > > EmitGraph(Stack< std::string > parameters)
void EmitGoto(const Block *destination, Stack< std::string > *stack, std::string indentation)
Stack< std::string > EmitBlock(const Block *block)
void EmitSourcePosition(SourcePosition pos, bool always_emit=false) override
std::vector< std::string > ProcessArgumentsCommon(const TypeVector &parameter_types, std::vector< std::string > constexpr_arguments, Stack< std::string > *stack)
static void EmitCCValue(VisitResult result, const Stack< std::string > &values, std::ostream &out)
bool IsPhiFromBlock(const Block *block) const
static DefinitionLocation Parameter(std::size_t index)
static const std::string & PathFromV8Root(SourceId file)
static std::string AbsolutePath(SourceId file)
BottomOffset AboveTop() const
Definition utils.h:280
const T & Peek(BottomOffset from_bottom) const
Definition utils.h:244
void SetDefinitionVariable(const DefinitionLocation &definition, const std::string &str)
std::string DefinitionToVariable(const DefinitionLocation &location)
std::string BlockName(const Block *block)
void EmitInstruction(const Instruction &instruction, Stack< std::string > *stack)
static GenericType * GetSmiTaggedGeneric()
static const Type * GetUninitializedHeapObjectType()
static const Type * GetTaggedType()
static const Type * GetHeapObjectType()
static const Type * GetSmiType()
static std::optional< const Type * > MatchUnaryGeneric(const Type *type, GenericType *generic)
Definition types.cc:573
virtual bool IsSubtypeOf(const Type *supertype) const
Definition types.cc:101
virtual std::string GetRuntimeType() const
Definition types.cc:1444
std::optional< const StructType * > StructSupertype() const
Definition types.cc:133
virtual bool IsConstexpr() const
Definition types.h:136
base::Vector< const DirectHandle< Object > > args
Definition execution.cc:74
int32_t offset
ZoneVector< RpoNumber > & result
ZoneStack< RpoNumber > & stack
InstructionOperand destination
int s
Definition mul-fft.cc:297
size_t LoweredSlotCount(const Type *type)
Definition types.cc:1216
std::string StringLiteralQuote(const std::string &s)
Definition utils.cc:54
void ReportError(Args &&... args)
Definition utils.h:96
VisitResult ProjectStructField(VisitResult structure, const std::string &fieldname)
Definition types.cc:1177
std::vector< const Type * > TypeVector
Definition types.h:85
TypeVector LowerType(const Type *type)
Definition types.cc:1210
void PrintCommaSeparatedList(std::ostream &os, const T &list, C &&transform)
Definition utils.h:163
MessageBuilder Error(Args &&... args)
Definition utils.h:81
#define CHECK(condition)
Definition logging.h:124
#define DCHECK(condition)
Definition logging.h:482
#define DCHECK_EQ(v1, v2)
Definition logging.h:485
bool CompareStartIgnoreColumn(const SourcePosition &pos) const