bytecode-array-builder.h 27.6 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2015 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.

#ifndef V8_INTERPRETER_BYTECODE_ARRAY_BUILDER_H_
#define V8_INTERPRETER_BYTECODE_ARRAY_BUILDER_H_

8
#include "src/ast/ast.h"
9 10
#include "src/base/compiler-specific.h"
#include "src/globals.h"
11
#include "src/interpreter/bytecode-array-writer.h"
12
#include "src/interpreter/bytecode-flags.h"
13
#include "src/interpreter/bytecode-register-allocator.h"
14
#include "src/interpreter/bytecode-register.h"
15
#include "src/interpreter/bytecode-source-info.h"
16
#include "src/interpreter/bytecodes.h"
17
#include "src/interpreter/constant-array-builder.h"
18
#include "src/interpreter/handler-table-builder.h"
19
#include "src/zone/zone-containers.h"
20 21 22 23

namespace v8 {
namespace internal {

24
class FeedbackVectorSpec;
25 26 27 28
class Isolate;

namespace interpreter {

29
class BytecodeLabel;
30
class BytecodeNode;
31
class BytecodeRegisterOptimizer;
32
class BytecodeJumpTable;
33 34
class Register;

35
class V8_EXPORT_PRIVATE BytecodeArrayBuilder final {
36
 public:
37
  BytecodeArrayBuilder(
38
      Zone* zone, int parameter_count, int locals_count,
39
      FeedbackVectorSpec* feedback_vector_spec = nullptr,
40 41
      SourcePositionTableBuilder::RecordingMode source_position_mode =
          SourcePositionTableBuilder::RECORD_SOURCE_POSITIONS);
42

43
  Handle<BytecodeArray> ToBytecodeArray(Isolate* isolate);
44

45
  // Get the number of parameters expected by function.
46 47 48 49
  int parameter_count() const {
    DCHECK_GE(parameter_count_, 0);
    return parameter_count_;
  }
50

51
  // Get the number of locals required for bytecode array.
52 53 54 55
  int locals_count() const {
    DCHECK_GE(local_register_count_, 0);
    return local_register_count_;
  }
56

57
  // Returns the number of fixed (non-temporary) registers.
58
  int fixed_register_count() const { return locals_count(); }
59

60
  // Returns the number of fixed and temporary registers.
61 62 63 64
  int total_register_count() const {
    DCHECK_LE(fixed_register_count(),
              register_allocator()->maximum_register_count());
    return register_allocator()->maximum_register_count();
65 66
  }

67
  Register Local(int index) const;
68
  Register Parameter(int parameter_index) const;
69
  Register Receiver() const;
70

71
  // Constant loads to accumulator.
72
  BytecodeArrayBuilder& LoadConstantPoolEntry(size_t entry);
73
  BytecodeArrayBuilder& LoadLiteral(v8::internal::Smi* value);
74
  BytecodeArrayBuilder& LoadLiteral(double value);
75 76
  BytecodeArrayBuilder& LoadLiteral(const AstRawString* raw_string);
  BytecodeArrayBuilder& LoadLiteral(const Scope* scope);
77 78
  BytecodeArrayBuilder& LoadLiteral(AstBigInt bigint);
  BytecodeArrayBuilder& LoadLiteral(AstSymbol symbol);
79 80 81 82 83
  BytecodeArrayBuilder& LoadUndefined();
  BytecodeArrayBuilder& LoadNull();
  BytecodeArrayBuilder& LoadTheHole();
  BytecodeArrayBuilder& LoadTrue();
  BytecodeArrayBuilder& LoadFalse();
84
  BytecodeArrayBuilder& LoadBoolean(bool value);
85

86
  // Global loads to the accumulator and stores from the accumulator.
87
  BytecodeArrayBuilder& LoadGlobal(const AstRawString* name, int feedback_slot,
88
                                   TypeofMode typeof_mode);
89 90
  BytecodeArrayBuilder& StoreGlobal(const AstRawString* name,
                                    int feedback_slot);
91

92 93
  // Load the object at |slot_index| at |depth| in the context chain starting
  // with |context| into the accumulator.
94
  enum ContextSlotMutability { kImmutableSlot, kMutableSlot };
95
  BytecodeArrayBuilder& LoadContextSlot(Register context, int slot_index,
96 97
                                        int depth,
                                        ContextSlotMutability immutable);
98 99 100 101 102

  // Stores the object in the accumulator into |slot_index| at |depth| in the
  // context chain starting with |context|.
  BytecodeArrayBuilder& StoreContextSlot(Register context, int slot_index,
                                         int depth);
103

104 105 106 107 108 109 110 111
  // Load from a module variable into the accumulator. |depth| is the depth of
  // the current context relative to the module context.
  BytecodeArrayBuilder& LoadModuleVariable(int cell_index, int depth);

  // Store from the accumulator into a module variable. |depth| is the depth of
  // the current context relative to the module context.
  BytecodeArrayBuilder& StoreModuleVariable(int cell_index, int depth);

112 113 114
  // Register-accumulator transfers.
  BytecodeArrayBuilder& LoadAccumulatorWithRegister(Register reg);
  BytecodeArrayBuilder& StoreAccumulatorInRegister(Register reg);
115

116 117 118
  // Register-register transfer.
  BytecodeArrayBuilder& MoveRegister(Register from, Register to);

119
  // Named load property.
120
  BytecodeArrayBuilder& LoadNamedProperty(Register object,
121
                                          const AstRawString* name,
122
                                          int feedback_slot);
123
  // Keyed load property. The key should be in the accumulator.
124
  BytecodeArrayBuilder& LoadKeyedProperty(Register object, int feedback_slot);
125 126 127
  // Named load property of the @@iterator symbol.
  BytecodeArrayBuilder& LoadIteratorProperty(Register object,
                                             int feedback_slot);
128 129 130
  // Named load property of the @@asyncIterator symbol.
  BytecodeArrayBuilder& LoadAsyncIteratorProperty(Register object,
                                                  int feedback_slot);
131

132 133
  // Store properties. Flag for NeedsSetFunctionName() should
  // be in the accumulator.
134
  BytecodeArrayBuilder& StoreDataPropertyInLiteral(
135 136
      Register object, Register name, DataPropertyInLiteralFlags flags,
      int feedback_slot);
137

138 139
  // Collect type information for developer tools. The value for which we
  // record the type is stored in the accumulator.
140
  BytecodeArrayBuilder& CollectTypeProfile(int position);
141

142 143 144 145 146 147 148 149
  // Store a property named by a property name. The value to be stored should be
  // in the accumulator.
  BytecodeArrayBuilder& StoreNamedProperty(Register object,
                                           const AstRawString* name,
                                           int feedback_slot,
                                           LanguageMode language_mode);
  // Store a property named by a constant from the constant pool. The value to
  // be stored should be in the accumulator.
150
  BytecodeArrayBuilder& StoreNamedProperty(Register object,
151
                                           size_t constant_pool_entry,
152 153
                                           int feedback_slot,
                                           LanguageMode language_mode);
154 155 156 157 158
  // Store an own property named by a constant from the constant pool. The
  // value to be stored should be in the accumulator.
  BytecodeArrayBuilder& StoreNamedOwnProperty(Register object,
                                              const AstRawString* name,
                                              int feedback_slot);
159 160
  // Store a property keyed by a value in a register. The value to be stored
  // should be in the accumulator.
161 162 163
  BytecodeArrayBuilder& StoreKeyedProperty(Register object, Register key,
                                           int feedback_slot,
                                           LanguageMode language_mode);
164 165 166 167
  // Store an own element in an array literal. The value to be stored should be
  // in the accumulator.
  BytecodeArrayBuilder& StoreInArrayLiteral(Register array, Register index,
                                            int feedback_slot);
168 169 170 171 172
  // Store the home object property. The value to be stored should be in the
  // accumulator.
  BytecodeArrayBuilder& StoreHomeObjectProperty(Register object,
                                                int feedback_slot,
                                                LanguageMode language_mode);
173

174 175 176 177 178 179 180 181 182
  // Store the class fields property. The initializer to be stored should
  // be in the accumulator.
  BytecodeArrayBuilder& StoreClassFieldsInitializer(Register constructor,
                                                    int feedback_slot);

  // Load class fields property.
  BytecodeArrayBuilder& LoadClassFieldsInitializer(Register constructor,
                                                   int feedback_slot);

183
  // Lookup the variable with |name|.
184
  BytecodeArrayBuilder& LoadLookupSlot(const AstRawString* name,
185 186
                                       TypeofMode typeof_mode);

187 188 189
  // Lookup the variable with |name|, which is known to be at |slot_index| at
  // |depth| in the context chain if not shadowed by a context extension
  // somewhere in that context chain.
190
  BytecodeArrayBuilder& LoadLookupContextSlot(const AstRawString* name,
191 192 193
                                              TypeofMode typeof_mode,
                                              int slot_index, int depth);

194 195 196
  // Lookup the variable with |name|, which has its feedback in |feedback_slot|
  // and is known to be global if not shadowed by a context extension somewhere
  // up to |depth| in that context chain.
197
  BytecodeArrayBuilder& LoadLookupGlobalSlot(const AstRawString* name,
198 199 200
                                             TypeofMode typeof_mode,
                                             int feedback_slot, int depth);

201
  // Store value in the accumulator into the variable with |name|.
202 203 204
  BytecodeArrayBuilder& StoreLookupSlot(
      const AstRawString* name, LanguageMode language_mode,
      LookupHoistingMode lookup_hoisting_mode);
205

206
  // Create a new closure for a SharedFunctionInfo which will be inserted at
207 208 209
  // constant pool index |shared_function_info_entry|.
  BytecodeArrayBuilder& CreateClosure(size_t shared_function_info_entry,
                                      int slot, int flags);
210

211
  // Create a new local context for a |scope|.
212
  BytecodeArrayBuilder& CreateBlockContext(const Scope* scope);
213

214
  // Create a new context for a catch block with |exception| and |scope|.
215
  BytecodeArrayBuilder& CreateCatchContext(Register exception,
216
                                           const Scope* scope);
217

218 219
  // Create a new context with the given |scope| and size |slots|.
  BytecodeArrayBuilder& CreateFunctionContext(const Scope* scope, int slots);
220

221 222
  // Create a new eval context with the given |scope| and size |slots|.
  BytecodeArrayBuilder& CreateEvalContext(const Scope* scope, int slots);
223

224
  // Creates a new context with the given |scope| for a with-statement
225
  // with the |object| in a register.
226
  BytecodeArrayBuilder& CreateWithContext(Register object, const Scope* scope);
227

228 229 230
  // Create a new arguments object in the accumulator.
  BytecodeArrayBuilder& CreateArguments(CreateArgumentsType type);

231
  // Literals creation.  Constant elements should be in the accumulator.
232
  BytecodeArrayBuilder& CreateRegExpLiteral(const AstRawString* pattern,
233
                                            int literal_index, int flags);
234 235
  BytecodeArrayBuilder& CreateArrayLiteral(size_t constant_elements_entry,
                                           int literal_index, int flags);
236
  BytecodeArrayBuilder& CreateEmptyArrayLiteral(int literal_index);
237 238 239
  BytecodeArrayBuilder& CreateObjectLiteral(size_t constant_properties_entry,
                                            int literal_index, int flags,
                                            Register output);
240
  BytecodeArrayBuilder& CreateEmptyObjectLiteral();
241

242 243 244
  // Gets or creates the template for a TemplateObjectDescription which will
  // be inserted at constant pool index |template_object_description_entry|.
  BytecodeArrayBuilder& GetTemplateObject(
245
      size_t template_object_description_entry, int feedback_slot);
246

247 248 249
  // Push the context in accumulator as the new context, and store in register
  // |context|.
  BytecodeArrayBuilder& PushContext(Register context);
250

251 252 253
  // Pop the current context and replace with |context|.
  BytecodeArrayBuilder& PopContext(Register context);

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  // Call a JS function which is known to be a property of a JS object. The
  // JSFunction or Callable to be called should be in |callable|. The arguments
  // should be in |args|, with the receiver in |args[0]|. The call type of the
  // expression is in |call_type|. Type feedback is recorded in the
  // |feedback_slot| in the type feedback vector.
  BytecodeArrayBuilder& CallProperty(Register callable, RegisterList args,
                                     int feedback_slot);

  // Call a JS function with an known undefined receiver. The JSFunction or
  // Callable to be called should be in |callable|. The arguments should be in
  // |args|, with no receiver as it is implicitly set to undefined. Type
  // feedback is recorded in the |feedback_slot| in the type feedback vector.
  BytecodeArrayBuilder& CallUndefinedReceiver(Register callable,
                                              RegisterList args,
                                              int feedback_slot);

  // Call a JS function with an any receiver, possibly (but not necessarily)
  // undefined. The JSFunction or Callable to be called should be in |callable|.
  // The arguments should be in |args|, with the receiver in |args[0]|. Type
  // feedback is recorded in the |feedback_slot| in the type feedback vector.
  BytecodeArrayBuilder& CallAnyReceiver(Register callable, RegisterList args,
                                        int feedback_slot);

  // Tail call into a JS function. The JSFunction or Callable to be called
  // should be in |callable|. The arguments should be in |args|, with the
  // receiver in |args[0]|. Type feedback is recorded in the |feedback_slot| in
  // the type feedback vector.
  BytecodeArrayBuilder& TailCall(Register callable, RegisterList args,
                                 int feedback_slot);
283

284
  // Call a JS function. The JSFunction or Callable to be called should be in
285
  // |callable|, the receiver in |args[0]| and the arguments in |args[1]|
286
  // onwards. The final argument must be a spread.
287 288
  BytecodeArrayBuilder& CallWithSpread(Register callable, RegisterList args,
                                       int feedback_slot);
289

290
  // Call the Construct operator. The accumulator holds the |new_target|.
291
  // The |constructor| is in a register and arguments are in |args|.
292 293
  BytecodeArrayBuilder& Construct(Register constructor, RegisterList args,
                                  int feedback_slot);
294

295 296
  // Call the Construct operator for use with a spread. The accumulator holds
  // the |new_target|. The |constructor| is in a register and arguments are in
297
  // |args|. The final argument must be a spread.
298
  BytecodeArrayBuilder& ConstructWithSpread(Register constructor,
299 300
                                            RegisterList args,
                                            int feedback_slot);
301

302
  // Call the runtime function with |function_id| and arguments |args|.
303
  BytecodeArrayBuilder& CallRuntime(Runtime::FunctionId function_id,
304 305 306 307 308 309
                                    RegisterList args);
  // Call the runtime function with |function_id| with single argument |arg|.
  BytecodeArrayBuilder& CallRuntime(Runtime::FunctionId function_id,
                                    Register arg);
  // Call the runtime function with |function_id| with no arguments.
  BytecodeArrayBuilder& CallRuntime(Runtime::FunctionId function_id);
310

311 312
  // Call the runtime function with |function_id| and arguments |args|, that
  // returns a pair of values. The return values will be returned in
313
  // |return_pair|.
314
  BytecodeArrayBuilder& CallRuntimeForPair(Runtime::FunctionId function_id,
315
                                           RegisterList args,
316 317 318 319
                                           RegisterList return_pair);
  // Call the runtime function with |function_id| with single argument |arg|
  // that returns a pair of values. The return values will be returned in
  // |return_pair|.
320
  BytecodeArrayBuilder& CallRuntimeForPair(Runtime::FunctionId function_id,
321 322
                                           Register arg,
                                           RegisterList return_pair);
323

324 325
  // Call the JS runtime function with |context_index| and arguments |args|,
  // with no receiver as it is implicitly set to undefined.
326
  BytecodeArrayBuilder& CallJSRuntime(int context_index, RegisterList args);
327

328
  // Operators (register holds the lhs value, accumulator holds the rhs value).
329 330 331
  // Type feedback will be recorded in the |feedback_slot|
  BytecodeArrayBuilder& BinaryOperation(Token::Value binop, Register reg,
                                        int feedback_slot);
332
  // Same as above, but lhs in the accumulator and rhs in |literal|.
333 334 335
  BytecodeArrayBuilder& BinaryOperationSmiLiteral(Token::Value binop,
                                                  Smi* literal,
                                                  int feedback_slot);
336

337
  // Unary and Count Operators (value stored in accumulator).
338
  // Type feedback will be recorded in the |feedback_slot|
339
  BytecodeArrayBuilder& UnaryOperation(Token::Value op, int feedback_slot);
340

341 342 343 344 345
  enum class ToBooleanMode {
    kConvertToBoolean,  // Perform ToBoolean conversion on accumulator.
    kAlreadyBoolean,    // Accumulator is already a Boolean.
  };

346
  // Unary Operators.
347
  BytecodeArrayBuilder& LogicalNot(ToBooleanMode mode);
348 349
  BytecodeArrayBuilder& TypeOf();

350 351 352 353 354
  // Expects a heap object in the accumulator. Returns its super constructor in
  // the register |out| if it passes the IsConstructor test. Otherwise, it
  // throws a TypeError exception.
  BytecodeArrayBuilder& GetSuperConstructor(Register out);

355 356 357 358
  // Deletes property from an object. This expects that accumulator contains
  // the key to be deleted and the register contains a reference to the object.
  BytecodeArrayBuilder& Delete(Register object, LanguageMode language_mode);

359 360 361
  // JavaScript defines two kinds of 'nil'.
  enum NilValue { kNullValue, kUndefinedValue };

362
  // Tests.
363
  BytecodeArrayBuilder& CompareOperation(Token::Value op, Register reg,
364 365
                                         int feedback_slot);
  BytecodeArrayBuilder& CompareOperation(Token::Value op, Register reg);
366
  BytecodeArrayBuilder& CompareReference(Register reg);
367 368 369 370
  BytecodeArrayBuilder& CompareUndetectable();
  BytecodeArrayBuilder& CompareUndefined();
  BytecodeArrayBuilder& CompareNull();
  BytecodeArrayBuilder& CompareNil(Token::Value op, NilValue nil);
371 372
  BytecodeArrayBuilder& CompareTypeOf(
      TestTypeOfFlags::LiteralFlag literal_flag);
373

374
  // Converts accumulator and stores result in register |out|.
375 376
  BytecodeArrayBuilder& ToObject(Register out);
  BytecodeArrayBuilder& ToName(Register out);
377
  BytecodeArrayBuilder& ToString();
378 379 380

  // Converts accumulator and stores result back in accumulator.
  BytecodeArrayBuilder& ToNumber(int feedback_slot);
381
  BytecodeArrayBuilder& ToNumeric(int feedback_slot);
382

383
  // Flow Control.
384
  BytecodeArrayBuilder& Bind(BytecodeLabel* label);
385
  BytecodeArrayBuilder& Bind(const BytecodeLabel& target, BytecodeLabel* label);
386
  BytecodeArrayBuilder& Bind(BytecodeJumpTable* jump_table, int case_value);
387

388
  BytecodeArrayBuilder& Jump(BytecodeLabel* label);
389 390 391 392
  BytecodeArrayBuilder& JumpLoop(BytecodeLabel* label, int loop_depth);

  BytecodeArrayBuilder& JumpIfTrue(ToBooleanMode mode, BytecodeLabel* label);
  BytecodeArrayBuilder& JumpIfFalse(ToBooleanMode mode, BytecodeLabel* label);
393
  BytecodeArrayBuilder& JumpIfNotHole(BytecodeLabel* label);
394
  BytecodeArrayBuilder& JumpIfJSReceiver(BytecodeLabel* label);
395
  BytecodeArrayBuilder& JumpIfNull(BytecodeLabel* label);
396
  BytecodeArrayBuilder& JumpIfNotNull(BytecodeLabel* label);
397
  BytecodeArrayBuilder& JumpIfUndefined(BytecodeLabel* label);
398 399 400 401 402
  BytecodeArrayBuilder& JumpIfNotUndefined(BytecodeLabel* label);
  BytecodeArrayBuilder& JumpIfNil(BytecodeLabel* label, Token::Value op,
                                  NilValue nil);
  BytecodeArrayBuilder& JumpIfNotNil(BytecodeLabel* label, Token::Value op,
                                     NilValue nil);
403

404 405
  BytecodeArrayBuilder& SwitchOnSmiNoFeedback(BytecodeJumpTable* jump_table);

406
  BytecodeArrayBuilder& StackCheck(int position);
407

408 409 410 411
  // Sets the pending message to the value in the accumulator, and returns the
  // previous pending message in the accumulator.
  BytecodeArrayBuilder& SetPendingMessage();

412
  BytecodeArrayBuilder& Throw();
413
  BytecodeArrayBuilder& ReThrow();
414
  BytecodeArrayBuilder& Abort(AbortReason reason);
415
  BytecodeArrayBuilder& Return();
416 417 418
  BytecodeArrayBuilder& ThrowReferenceErrorIfHole(const AstRawString* name);
  BytecodeArrayBuilder& ThrowSuperNotCalledIfHole();
  BytecodeArrayBuilder& ThrowSuperAlreadyCalledIfNotHole();
419

420 421 422
  // Debugger.
  BytecodeArrayBuilder& Debugger();

423 424 425
  // Increment the block counter at the given slot (block code coverage).
  BytecodeArrayBuilder& IncBlockCounter(int slot);

426
  // Complex flow control.
427 428 429
  BytecodeArrayBuilder& ForInEnumerate(Register receiver);
  BytecodeArrayBuilder& ForInPrepare(RegisterList cache_info_triple,
                                     int feedback_slot);
430
  BytecodeArrayBuilder& ForInContinue(Register index, Register cache_length);
431
  BytecodeArrayBuilder& ForInNext(Register receiver, Register index,
432
                                  RegisterList cache_type_array_pair,
433
                                  int feedback_slot);
434
  BytecodeArrayBuilder& ForInStep(Register index);
435

436
  // Generators.
437
  BytecodeArrayBuilder& SuspendGenerator(Register generator,
438 439
                                         RegisterList registers,
                                         int suspend_id);
440 441
  BytecodeArrayBuilder& SwitchOnGeneratorState(Register generator,
                                               BytecodeJumpTable* jump_table);
442 443
  BytecodeArrayBuilder& ResumeGenerator(Register generator,
                                        RegisterList registers);
444

445
  // Exception handling.
446 447
  BytecodeArrayBuilder& MarkHandler(int handler_id,
                                    HandlerTable::CatchPrediction will_catch);
448 449 450 451 452 453 454
  BytecodeArrayBuilder& MarkTryBegin(int handler_id, Register context);
  BytecodeArrayBuilder& MarkTryEnd(int handler_id);

  // Creates a new handler table entry and returns a {hander_id} identifying the
  // entry, so that it can be referenced by above exception handling support.
  int NewHandlerEntry() { return handler_table_builder()->NewHandlerEntry(); }

455 456 457 458
  // Allocates a new jump table of given |size| and |case_value_base| in the
  // constant pool.
  BytecodeJumpTable* AllocateJumpTable(int size, int case_value_base);

459 460
  // Gets a constant pool entry.
  size_t GetConstantPoolEntry(const AstRawString* raw_string);
461
  size_t GetConstantPoolEntry(AstBigInt bigint);
462
  size_t GetConstantPoolEntry(const Scope* scope);
463
  size_t GetConstantPoolEntry(double number);
464 465 466 467 468 469 470 471
#define ENTRY_GETTER(NAME, ...) size_t NAME##ConstantPoolEntry();
  SINGLETON_CONSTANT_ENTRY_TYPES(ENTRY_GETTER)
#undef ENTRY_GETTER

  // Allocates a slot in the constant pool which can later be set.
  size_t AllocateDeferredConstantPoolEntry();
  // Sets the deferred value into an allocated constant pool entry.
  void SetDeferredConstantPoolEntry(size_t entry, Handle<Object> object);
472

473 474
  void InitializeReturnPosition(FunctionLiteral* literal);

475 476 477 478 479 480
  void SetStatementPosition(Statement* stmt) {
    if (stmt->position() == kNoSourcePosition) return;
    latest_source_info_.MakeStatementPosition(stmt->position());
  }

  void SetExpressionPosition(Expression* expr) {
481 482 483 484 485
    SetExpressionPosition(expr->position());
  }

  void SetExpressionPosition(int position) {
    if (position == kNoSourcePosition) return;
486 487 488
    if (!latest_source_info_.is_statement()) {
      // Ensure the current expression position is overwritten with the
      // latest value.
489
      latest_source_info_.MakeExpressionPosition(position);
490 491 492 493 494 495 496
    }
  }

  void SetExpressionAsStatementPosition(Expression* expr) {
    if (expr->position() == kNoSourcePosition) return;
    latest_source_info_.MakeStatementPosition(expr->position());
  }
497

498 499 500 501 502 503 504 505
  void SetReturnPosition(int source_position, FunctionLiteral* literal) {
    if (source_position != kNoSourcePosition) {
      latest_source_info_.MakeStatementPosition(source_position);
    } else if (literal->return_position() != kNoSourcePosition) {
      latest_source_info_.MakeStatementPosition(literal->return_position());
    }
  }

506
  bool RequiresImplicitReturn() const { return !return_seen_in_block_; }
507

508 509 510 511 512 513
  // Returns the raw operand value for the given register or register list.
  uint32_t GetInputRegisterOperand(Register reg);
  uint32_t GetOutputRegisterOperand(Register reg);
  uint32_t GetInputRegisterListOperand(RegisterList reg_list);
  uint32_t GetOutputRegisterListOperand(RegisterList reg_list);

514 515 516 517 518 519
  // Outputs raw register transfer bytecodes without going through the register
  // optimizer.
  void OutputLdarRaw(Register reg);
  void OutputStarRaw(Register reg);
  void OutputMovRaw(Register src, Register dest);

520 521 522
  // Accessors
  BytecodeRegisterAllocator* register_allocator() {
    return &register_allocator_;
523
  }
524 525
  const BytecodeRegisterAllocator* register_allocator() const {
    return &register_allocator_;
526
  }
527
  Zone* zone() const { return zone_; }
528

529
 private:
530 531 532 533 534 535
  friend class BytecodeRegisterAllocator;
  template <Bytecode bytecode, AccumulatorUse accumulator_use,
            OperandType... operand_types>
  friend class BytecodeNodeBuilder;

  const FeedbackVectorSpec* feedback_vector_spec() const {
536
    return feedback_vector_spec_;
537 538 539
  }

  // Returns the current source position for the given |bytecode|.
540 541 542 543 544 545 546 547 548
  V8_INLINE BytecodeSourceInfo CurrentSourcePosition(Bytecode bytecode);

#define DECLARE_BYTECODE_OUTPUT(Name, ...)                         \
  template <typename... Operands>                                  \
  V8_INLINE BytecodeNode Create##Name##Node(Operands... operands); \
  template <typename... Operands>                                  \
  V8_INLINE void Output##Name(Operands... operands);               \
  template <typename... Operands>                                  \
  V8_INLINE void Output##Name(BytecodeLabel* label, Operands... operands);
549 550
  BYTECODE_LIST(DECLARE_BYTECODE_OUTPUT)
#undef DECLARE_OPERAND_TYPE_INFO
551

552
  V8_INLINE void OutputSwitchOnSmiNoFeedback(BytecodeJumpTable* jump_table);
553

554
  bool RegisterIsValid(Register reg) const;
555
  bool RegisterListIsValid(RegisterList reg_list) const;
556

557 558 559
  // Sets a deferred source info which should be emitted before any future
  // source info (either attached to a following bytecode or as a nop).
  void SetDeferredSourceInfo(BytecodeSourceInfo source_info);
560 561 562 563 564 565 566 567
  // Either attach deferred source info to node, or emit it as a nop bytecode
  // if node already have valid source info.
  void AttachOrEmitDeferredSourceInfo(BytecodeNode* node);

  // Write bytecode to bytecode array.
  void Write(BytecodeNode* node);
  void WriteJump(BytecodeNode* node, BytecodeLabel* label);
  void WriteSwitch(BytecodeNode* node, BytecodeJumpTable* label);
568

569
  // Not implemented as the illegal bytecode is used inside internally
570
  // to indicate a bytecode field is not valid or an error has occurred
571 572 573
  // during bytecode generation.
  BytecodeArrayBuilder& Illegal();

574
  template <Bytecode bytecode, AccumulatorUse accumulator_use>
575
  void PrepareToOutputBytecode();
576

577
  void LeaveBasicBlock() { return_seen_in_block_ = false; }
578

579 580 581
  BytecodeArrayWriter* bytecode_array_writer() {
    return &bytecode_array_writer_;
  }
582 583 584 585 586 587
  ConstantArrayBuilder* constant_array_builder() {
    return &constant_array_builder_;
  }
  const ConstantArrayBuilder* constant_array_builder() const {
    return &constant_array_builder_;
  }
588 589 590
  HandlerTableBuilder* handler_table_builder() {
    return &handler_table_builder_;
  }
591

592
  Zone* zone_;
593
  FeedbackVectorSpec* feedback_vector_spec_;
594
  bool bytecode_generated_;
595
  ConstantArrayBuilder constant_array_builder_;
596
  HandlerTableBuilder handler_table_builder_;
597 598 599
  bool return_seen_in_block_;
  int parameter_count_;
  int local_register_count_;
600
  BytecodeRegisterAllocator register_allocator_;
601
  BytecodeArrayWriter bytecode_array_writer_;
602
  BytecodeRegisterOptimizer* register_optimizer_;
603
  BytecodeSourceInfo latest_source_info_;
604
  BytecodeSourceInfo deferred_source_info_;
605

606
  DISALLOW_COPY_AND_ASSIGN(BytecodeArrayBuilder);
607 608
};

609 610 611
V8_EXPORT_PRIVATE std::ostream& operator<<(
    std::ostream& os, const BytecodeArrayBuilder::ToBooleanMode& mode);

612 613 614 615 616
}  // namespace interpreter
}  // namespace internal
}  // namespace v8

#endif  // V8_INTERPRETER_BYTECODE_ARRAY_BUILDER_H_