ast.h 118 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#ifndef V8_AST_AST_H_
#define V8_AST_AST_H_
7

8
#include "src/assembler.h"
9 10 11
#include "src/ast/ast-value-factory.h"
#include "src/ast/modules.h"
#include "src/ast/variables.h"
12
#include "src/bailout-reason.h"
13
#include "src/base/flags.h"
rmcilroy's avatar
rmcilroy committed
14
#include "src/base/smart-pointers.h"
15 16
#include "src/factory.h"
#include "src/isolate.h"
17
#include "src/list.h"
18
#include "src/parsing/token.h"
19
#include "src/runtime/runtime.h"
20 21 22
#include "src/small-pointer-list.h"
#include "src/types.h"
#include "src/utils.h"
23

24 25
namespace v8 {
namespace internal {
26 27 28 29 30 31 32 33 34 35 36 37 38 39

// The abstract syntax tree is an intermediate, light-weight
// representation of the parsed JavaScript code suitable for
// compilation to native code.

// Nodes are allocated in a separate zone, which allows faster
// allocation and constant-time deallocation of the entire syntax
// tree.


// ----------------------------------------------------------------------------
// Nodes of the abstract syntax tree. Only concrete classes are
// enumerated here.

arv@chromium.org's avatar
arv@chromium.org committed
40 41 42 43 44
#define DECLARATION_NODE_LIST(V) \
  V(VariableDeclaration)         \
  V(FunctionDeclaration)         \
  V(ImportDeclaration)           \
  V(ExportDeclaration)
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#define STATEMENT_NODE_LIST(V)    \
  V(Block)                        \
  V(ExpressionStatement)          \
  V(EmptyStatement)               \
  V(SloppyBlockFunctionStatement) \
  V(IfStatement)                  \
  V(ContinueStatement)            \
  V(BreakStatement)               \
  V(ReturnStatement)              \
  V(WithStatement)                \
  V(SwitchStatement)              \
  V(DoWhileStatement)             \
  V(WhileStatement)               \
  V(ForStatement)                 \
  V(ForInStatement)               \
  V(ForOfStatement)               \
  V(TryCatchStatement)            \
  V(TryFinallyStatement)          \
64 65
  V(DebuggerStatement)

arv@chromium.org's avatar
arv@chromium.org committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
#define EXPRESSION_NODE_LIST(V) \
  V(FunctionLiteral)            \
  V(ClassLiteral)               \
  V(NativeFunctionLiteral)      \
  V(Conditional)                \
  V(VariableProxy)              \
  V(Literal)                    \
  V(RegExpLiteral)              \
  V(ObjectLiteral)              \
  V(ArrayLiteral)               \
  V(Assignment)                 \
  V(Yield)                      \
  V(Throw)                      \
  V(Property)                   \
  V(Call)                       \
  V(CallNew)                    \
  V(CallRuntime)                \
  V(UnaryOperation)             \
  V(CountOperation)             \
  V(BinaryOperation)            \
  V(CompareOperation)           \
87
  V(Spread)                     \
arv@chromium.org's avatar
arv@chromium.org committed
88
  V(ThisFunction)               \
89 90
  V(SuperPropertyReference)     \
  V(SuperCallReference)         \
91
  V(CaseClause)                 \
92
  V(EmptyParentheses)           \
93
  V(DoExpression)               \
94
  V(RewritableExpression)
95

96
#define AST_NODE_LIST(V)                        \
97
  DECLARATION_NODE_LIST(V)                      \
98
  STATEMENT_NODE_LIST(V)                        \
99
  EXPRESSION_NODE_LIST(V)
100

101
// Forward declarations
102
class AstNodeFactory;
103
class AstVisitor;
104
class Declaration;
105
class Module;
106 107 108
class BreakableStatement;
class Expression;
class IterationStatement;
109
class MaterializedLiteral;
110
class Statement;
111
class TypeFeedbackOracle;
112

113
#define DEF_FORWARD_DECLARATION(type) class type;
114
AST_NODE_LIST(DEF_FORWARD_DECLARATION)
115 116 117 118
#undef DEF_FORWARD_DECLARATION


// Typedef only introduced to avoid unreadable code.
119 120
typedef ZoneList<Handle<String>> ZoneStringList;
typedef ZoneList<Handle<Object>> ZoneObjectList;
121 122


123
#define DECLARE_NODE_TYPE(type)                                          \
124 125
  void Accept(AstVisitor* v) override;                                   \
  AstNode::NodeType node_type() const final { return AstNode::k##type; } \
126
  friend class AstNodeFactory;
127 128


129
class FeedbackVectorSlotCache {
130
 public:
131
  explicit FeedbackVectorSlotCache(Zone* zone)
jkummerow's avatar
jkummerow committed
132 133 134
      : zone_(zone),
        hash_map_(HashMap::PointersMatch, ZoneHashMap::kDefaultHashMapCapacity,
                  ZoneAllocationPolicy(zone)) {}
135

136
  void Put(Variable* variable, FeedbackVectorSlot slot) {
jkummerow's avatar
jkummerow committed
137 138 139 140 141 142 143 144
    ZoneHashMap::Entry* entry = hash_map_.LookupOrInsert(
        variable, ComputePointerHash(variable), ZoneAllocationPolicy(zone_));
    entry->value = reinterpret_cast<void*>(slot.ToInt());
  }

  ZoneHashMap::Entry* Get(Variable* variable) const {
    return hash_map_.Lookup(variable, ComputePointerHash(variable));
  }
145 146

 private:
jkummerow's avatar
jkummerow committed
147 148
  Zone* zone_;
  ZoneHashMap hash_map_;
149 150 151
};


152
class AstProperties final BASE_EMBEDDED {
153
 public:
154 155 156 157 158 159 160
  enum Flag {
    kNoFlags = 0,
    kDontSelfOptimize = 1 << 0,
    kDontCrankshaft = 1 << 1
  };

  typedef base::Flags<Flag> Flags;
161

162
  explicit AstProperties(Zone* zone) : node_count_(0), spec_(zone) {}
163

164 165
  Flags& flags() { return flags_; }
  Flags flags() const { return flags_; }
166 167 168
  int node_count() { return node_count_; }
  void add_node_count(int count) { node_count_ += count; }

169 170
  const FeedbackVectorSpec* get_spec() const { return &spec_; }
  FeedbackVectorSpec* get_spec() { return &spec_; }
171

172 173 174
 private:
  Flags flags_;
  int node_count_;
175
  FeedbackVectorSpec spec_;
176 177
};

178 179
DEFINE_OPERATORS_FOR_FLAGS(AstProperties::Flags)

180

181
class AstNode: public ZoneObject {
182
 public:
183
#define DECLARE_TYPE_ENUM(type) k##type,
184
  enum NodeType {
185 186 187 188 189
    AST_NODE_LIST(DECLARE_TYPE_ENUM)
    kInvalid = -1
  };
#undef DECLARE_TYPE_ENUM

190
  void* operator new(size_t size, Zone* zone) { return zone->New(size); }
191

192
  explicit AstNode(int position): position_(position) {}
193
  virtual ~AstNode() {}
194

195
  virtual void Accept(AstVisitor* v) = 0;
196
  virtual NodeType node_type() const = 0;
197
  int position() const { return position_; }
198

199 200
#ifdef DEBUG
  void PrettyPrint(Isolate* isolate);
201
  void Print(Isolate* isolate);
202 203
#endif  // DEBUG

204
  // Type testing & conversion functions overridden by concrete subclasses.
205
#define DECLARE_NODE_FUNCTIONS(type) \
206 207 208
  V8_INLINE bool Is##type() const;   \
  V8_INLINE type* As##type();        \
  V8_INLINE const type* As##type() const;
209 210
  AST_NODE_LIST(DECLARE_NODE_FUNCTIONS)
#undef DECLARE_NODE_FUNCTIONS
211 212 213

  virtual BreakableStatement* AsBreakableStatement() { return NULL; }
  virtual IterationStatement* AsIterationStatement() { return NULL; }
214
  virtual MaterializedLiteral* AsMaterializedLiteral() { return NULL; }
215

216 217 218 219
  // The interface for feedback slots, with default no-op implementations for
  // node types which don't actually have this. Note that this is conceptually
  // not really nice, but multiple inheritance would introduce yet another
  // vtable entry per node, something we don't want for space reasons.
220 221
  virtual void AssignFeedbackVectorSlots(Isolate* isolate,
                                         FeedbackVectorSpec* spec,
222
                                         FeedbackVectorSlotCache* cache) {}
223

224 225 226 227 228
 private:
  // Hidden to prevent accidental usage. It would have to load the
  // current zone from the TLS.
  void* operator new(size_t size);

229
  friend class CaseClause;  // Generates AST IDs.
230 231

  int position_;
232 233 234
};


235
class Statement : public AstNode {
236
 public:
237
  explicit Statement(Zone* zone, int position) : AstNode(position) {}
238

239
  bool IsEmpty() { return AsEmptyStatement() != NULL; }
240
  virtual bool IsJump() const { return false; }
241 242 243
};


244
class SmallMapList final {
245 246
 public:
  SmallMapList() {}
247
  SmallMapList(int capacity, Zone* zone) : list_(capacity, zone) {}
248

249
  void Reserve(int capacity, Zone* zone) { list_.Reserve(capacity, zone); }
250
  void Clear() { list_.Clear(); }
251
  void Sort() { list_.Sort(); }
252 253 254 255

  bool is_empty() const { return list_.is_empty(); }
  int length() const { return list_.length(); }

256
  void AddMapIfMissing(Handle<Map> map, Zone* zone) {
257
    if (!Map::TryUpdate(map).ToHandle(&map)) return;
258 259 260 261 262 263
    for (int i = 0; i < length(); ++i) {
      if (at(i).is_identical_to(map)) return;
    }
    Add(map, zone);
  }

264 265 266 267 268 269 270 271
  void FilterForPossibleTransitions(Map* root_map) {
    for (int i = list_.length() - 1; i >= 0; i--) {
      if (at(i)->FindRootMap() != root_map) {
        list_.RemoveElement(list_.at(i));
      }
    }
  }

272 273
  void Add(Handle<Map> handle, Zone* zone) {
    list_.Add(handle.location(), zone);
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  }

  Handle<Map> at(int i) const {
    return Handle<Map>(list_.at(i));
  }

  Handle<Map> first() const { return at(0); }
  Handle<Map> last() const { return at(length() - 1); }

 private:
  // The list stores pointers to Map*, that is Map**, so it's GC safe.
  SmallPointerList<Map*> list_;

  DISALLOW_COPY_AND_ASSIGN(SmallMapList);
};


291
class Expression : public AstNode {
292
 public:
293 294 295 296 297 298 299 300 301 302 303 304
  enum Context {
    // Not assigned a context yet, or else will not be visited during
    // code generation.
    kUninitialized,
    // Evaluated for its side effects.
    kEffect,
    // Evaluated for its value (and side effects).
    kValue,
    // Evaluated for control flow (and side effects).
    kTest
  };

rossberg's avatar
rossberg committed
305 306 307
  // Mark this expression as being in tail position.
  virtual void MarkTail() {}

308
  // True iff the expression is a valid reference expression.
309
  virtual bool IsValidReferenceExpression() const { return false; }
310

311
  // Helpers for ToBoolean conversion.
312 313
  virtual bool ToBooleanIsTrue() const { return false; }
  virtual bool ToBooleanIsFalse() const { return false; }
314

315 316 317
  // Symbols that cannot be parsed as array indices are considered property
  // names.  We do not treat symbols that can be array indexes as property
  // names because [] for string objects is handled only by keyed ICs.
318
  virtual bool IsPropertyName() const { return false; }
319

320 321 322 323
  // True iff the expression is a class or function expression without
  // a syntactic name.
  virtual bool IsAnonymousFunctionDefinition() const { return false; }

324
  // True iff the expression is a literal represented as a smi.
325
  bool IsSmiLiteral() const;
326

327
  // True iff the expression is a string literal.
328
  bool IsStringLiteral() const;
329 330

  // True iff the expression is the null literal.
331
  bool IsNullLiteral() const;
332

333 334 335
  // True if we can prove that the expression is the undefined literal. Note
  // that this also checks for loads of the global "undefined" variable.
  bool IsUndefinedLiteral() const;
336

337 338 339
  // True iff the expression is a valid target for an assignment.
  bool IsValidReferenceExpressionOrThis() const;

340 341 342 343 344
  // Type feedback information for assignments and properties.
  virtual bool IsMonomorphic() {
    UNREACHABLE();
    return false;
  }
345
  virtual SmallMapList* GetReceiverTypes() {
346 347 348
    UNREACHABLE();
    return NULL;
  }
349
  virtual KeyedAccessStoreMode GetStoreMode() const {
350 351 352
    UNREACHABLE();
    return STANDARD_STORE;
  }
353
  virtual IcCheckType GetKeyType() const {
354 355 356
    UNREACHABLE();
    return ELEMENT;
  }
357

358
  // TODO(rossberg): this should move to its own AST node eventually.
359
  virtual void RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle);
360
  uint16_t to_boolean_types() const {
361 362
    return ToBooleanTypesField::decode(bit_field_);
  }
363

364 365 366 367
  void set_base_id(int id) { base_id_ = id; }
  static int num_ids() { return parent_num_ids() + 2; }
  BailoutId id() const { return BailoutId(local_id(0)); }
  TypeFeedbackId test_id() const { return TypeFeedbackId(local_id(1)); }
368

369
 protected:
370
  Expression(Zone* zone, int pos)
371
      : AstNode(pos),
372
        base_id_(BailoutId::None().ToInt()),
373
        bit_field_(0) {}
374
  static int parent_num_ids() { return 0; }
375
  void set_to_boolean_types(uint16_t types) {
376 377
    bit_field_ = ToBooleanTypesField::update(bit_field_, types);
  }
378

379 380 381 382
  int base_id() const {
    DCHECK(!BailoutId(base_id_).IsNone());
    return base_id_;
  }
383

384
 private:
385 386 387
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

  int base_id_;
388
  class ToBooleanTypesField : public BitField16<uint16_t, 0, 9> {};
389 390 391
  uint16_t bit_field_;
  // Ends with 16-bit field; deriving classes in turn begin with
  // 16-bit fields for optimum packing efficiency.
392 393 394
};


395
class BreakableStatement : public Statement {
396
 public:
397
  enum BreakableType {
398 399 400 401 402 403
    TARGET_FOR_ANONYMOUS,
    TARGET_FOR_NAMED_ONLY
  };

  // The labels associated with this statement. May be NULL;
  // if it is != NULL, guaranteed to contain at least one entry.
404
  ZoneList<const AstRawString*>* labels() const { return labels_; }
405 406

  // Type testing & conversion.
407
  BreakableStatement* AsBreakableStatement() final { return this; }
408 409

  // Code generation
410
  Label* break_target() { return &break_target_; }
411 412

  // Testers.
413 414 415
  bool is_target_for_anonymous() const {
    return breakable_type_ == TARGET_FOR_ANONYMOUS;
  }
416

417 418 419 420
  void set_base_id(int id) { base_id_ = id; }
  static int num_ids() { return parent_num_ids() + 2; }
  BailoutId EntryId() const { return BailoutId(local_id(0)); }
  BailoutId ExitId() const { return BailoutId(local_id(1)); }
421

422
 protected:
423
  BreakableStatement(Zone* zone, ZoneList<const AstRawString*>* labels,
424
                     BreakableType breakable_type, int position)
425
      : Statement(zone, position),
426
        labels_(labels),
427
        breakable_type_(breakable_type),
428
        base_id_(BailoutId::None().ToInt()) {
429
    DCHECK(labels == NULL || labels->length() > 0);
430
  }
431
  static int parent_num_ids() { return 0; }
432

433 434 435 436
  int base_id() const {
    DCHECK(!BailoutId(base_id_).IsNone());
    return base_id_;
  }
437 438

 private:
439 440
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

441
  ZoneList<const AstRawString*>* labels_;
442
  BreakableType breakable_type_;
443
  Label break_target_;
444
  int base_id_;
445 446 447
};


448
class Block final : public BreakableStatement {
449
 public:
450
  DECLARE_NODE_TYPE(Block)
451

452
  ZoneList<Statement*>* statements() { return &statements_; }
453
  bool ignore_completion_value() const { return ignore_completion_value_; }
454

455 456
  static int num_ids() { return parent_num_ids() + 1; }
  BailoutId DeclsId() const { return BailoutId(local_id(0)); }
457

458
  bool IsJump() const override {
459 460 461 462
    return !statements_.is_empty() && statements_.last()->IsJump()
        && labels() == NULL;  // Good enough as an approximation...
  }

463 464
  Scope* scope() const { return scope_; }
  void set_scope(Scope* scope) { scope_ = scope; }
465

466
 protected:
467
  Block(Zone* zone, ZoneList<const AstRawString*>* labels, int capacity,
468
        bool ignore_completion_value, int pos)
469
      : BreakableStatement(zone, labels, TARGET_FOR_NAMED_ONLY, pos),
470
        statements_(capacity, zone),
471
        ignore_completion_value_(ignore_completion_value),
472
        scope_(NULL) {}
473
  static int parent_num_ids() { return BreakableStatement::num_ids(); }
474

475
 private:
476 477
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

478
  ZoneList<Statement*> statements_;
479
  bool ignore_completion_value_;
480
  Scope* scope_;
481 482 483
};


484 485 486 487 488
class DoExpression final : public Expression {
 public:
  DECLARE_NODE_TYPE(DoExpression)

  Block* block() { return block_; }
489
  void set_block(Block* b) { block_ = b; }
490
  VariableProxy* result() { return result_; }
491
  void set_result(VariableProxy* v) { result_ = v; }
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

 protected:
  DoExpression(Zone* zone, Block* block, VariableProxy* result, int pos)
      : Expression(zone, pos), block_(block), result_(result) {
    DCHECK_NOT_NULL(block_);
    DCHECK_NOT_NULL(result_);
  }
  static int parent_num_ids() { return Expression::num_ids(); }

 private:
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

  Block* block_;
  VariableProxy* result_;
};


509
class Declaration : public AstNode {
510
 public:
511 512 513
  VariableProxy* proxy() const { return proxy_; }
  VariableMode mode() const { return mode_; }
  Scope* scope() const { return scope_; }
514
  virtual InitializationFlag initialization() const = 0;
515
  virtual bool IsInlineable() const;
516

517
 protected:
518
  Declaration(Zone* zone, VariableProxy* proxy, VariableMode mode, Scope* scope,
519
              int pos)
520
      : AstNode(pos), mode_(mode), proxy_(proxy), scope_(scope) {
521
    DCHECK(IsDeclaredVariableMode(mode));
522 523 524
  }

 private:
525
  VariableMode mode_;
526
  VariableProxy* proxy_;
527 528 529

  // Nested scope from which the declaration originated.
  Scope* scope_;
530 531 532
};


533
class VariableDeclaration final : public Declaration {
534 535 536
 public:
  DECLARE_NODE_TYPE(VariableDeclaration)

537
  InitializationFlag initialization() const override {
538 539 540 541
    return mode() == VAR ? kCreatedInitialized : kNeedsInitialization;
  }

 protected:
542
  VariableDeclaration(Zone* zone, VariableProxy* proxy, VariableMode mode,
543 544
                      Scope* scope, int pos)
      : Declaration(zone, proxy, mode, scope, pos) {}
545 546
};

547

548
class FunctionDeclaration final : public Declaration {
549 550 551 552
 public:
  DECLARE_NODE_TYPE(FunctionDeclaration)

  FunctionLiteral* fun() const { return fun_; }
553
  void set_fun(FunctionLiteral* f) { fun_ = f; }
554
  InitializationFlag initialization() const override {
555 556
    return kCreatedInitialized;
  }
557
  bool IsInlineable() const override;
558 559

 protected:
560 561
  FunctionDeclaration(Zone* zone,
                      VariableProxy* proxy,
562 563
                      VariableMode mode,
                      FunctionLiteral* fun,
564 565
                      Scope* scope,
                      int pos)
566
      : Declaration(zone, proxy, mode, scope, pos),
567
        fun_(fun) {
568
    DCHECK(mode == VAR || mode == LET || mode == CONST);
569
    DCHECK(fun != NULL);
570 571 572 573 574 575 576
  }

 private:
  FunctionLiteral* fun_;
};


577
class ImportDeclaration final : public Declaration {
578 579 580
 public:
  DECLARE_NODE_TYPE(ImportDeclaration)

581 582 583 584 585 586
  const AstRawString* import_name() const { return import_name_; }
  const AstRawString* module_specifier() const { return module_specifier_; }
  void set_module_specifier(const AstRawString* module_specifier) {
    DCHECK(module_specifier_ == NULL);
    module_specifier_ = module_specifier;
  }
587
  InitializationFlag initialization() const override {
588
    return kNeedsInitialization;
589 590 591
  }

 protected:
592 593 594
  ImportDeclaration(Zone* zone, VariableProxy* proxy,
                    const AstRawString* import_name,
                    const AstRawString* module_specifier, Scope* scope, int pos)
595
      : Declaration(zone, proxy, CONST, scope, pos),
596 597
        import_name_(import_name),
        module_specifier_(module_specifier) {}
598 599

 private:
600 601
  const AstRawString* import_name_;
  const AstRawString* module_specifier_;
602 603 604
};


605
class ExportDeclaration final : public Declaration {
606 607 608
 public:
  DECLARE_NODE_TYPE(ExportDeclaration)

609
  InitializationFlag initialization() const override {
610 611 612 613
    return kCreatedInitialized;
  }

 protected:
614 615
  ExportDeclaration(Zone* zone, VariableProxy* proxy, Scope* scope, int pos)
      : Declaration(zone, proxy, LET, scope, pos) {}
616 617 618
};


619
class Module : public AstNode {
620
 public:
621
  ModuleDescriptor* descriptor() const { return descriptor_; }
622
  Block* body() const { return body_; }
623

624
 protected:
625
  Module(Zone* zone, int pos)
626 627 628
      : AstNode(pos), descriptor_(ModuleDescriptor::New(zone)), body_(NULL) {}
  Module(Zone* zone, ModuleDescriptor* descriptor, int pos, Block* body = NULL)
      : AstNode(pos), descriptor_(descriptor), body_(body) {}
629 630

 private:
631
  ModuleDescriptor* descriptor_;
632
  Block* body_;
633 634 635
};


636
class IterationStatement : public BreakableStatement {
637 638
 public:
  // Type testing & conversion.
639
  IterationStatement* AsIterationStatement() final { return this; }
640 641

  Statement* body() const { return body_; }
642
  void set_body(Statement* s) { body_ = s; }
643

644 645
  int yield_count() const { return yield_count_; }
  int first_yield_id() const { return first_yield_id_; }
646
  void set_yield_count(int yield_count) { yield_count_ = yield_count; }
647 648 649
  void set_first_yield_id(int first_yield_id) {
    first_yield_id_ = first_yield_id;
  }
650

651 652
  static int num_ids() { return parent_num_ids() + 1; }
  BailoutId OsrEntryId() const { return BailoutId(local_id(0)); }
653 654
  virtual BailoutId ContinueId() const = 0;
  virtual BailoutId StackCheckId() const = 0;
655

656
  // Code generation
657
  Label* continue_target()  { return &continue_target_; }
658 659

 protected:
660 661
  IterationStatement(Zone* zone, ZoneList<const AstRawString*>* labels, int pos)
      : BreakableStatement(zone, labels, TARGET_FOR_ANONYMOUS, pos),
662
        body_(NULL),
663 664
        yield_count_(0),
        first_yield_id_(0) {}
665 666
  static int parent_num_ids() { return BreakableStatement::num_ids(); }
  void Initialize(Statement* body) { body_ = body; }
667

668
 private:
669 670
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

671
  Statement* body_;
672
  Label continue_target_;
673
  int yield_count_;
674
  int first_yield_id_;
675 676 677
};


678
class DoWhileStatement final : public IterationStatement {
679
 public:
680 681
  DECLARE_NODE_TYPE(DoWhileStatement)

682 683 684 685
  void Initialize(Expression* cond, Statement* body) {
    IterationStatement::Initialize(body);
    cond_ = cond;
  }
686

687
  Expression* cond() const { return cond_; }
688
  void set_cond(Expression* e) { cond_ = e; }
689

690
  static int num_ids() { return parent_num_ids() + 2; }
691 692
  BailoutId ContinueId() const override { return BailoutId(local_id(0)); }
  BailoutId StackCheckId() const override { return BackEdgeId(); }
693
  BailoutId BackEdgeId() const { return BailoutId(local_id(1)); }
694

695
 protected:
696 697 698
  DoWhileStatement(Zone* zone, ZoneList<const AstRawString*>* labels, int pos)
      : IterationStatement(zone, labels, pos), cond_(NULL) {}
  static int parent_num_ids() { return IterationStatement::num_ids(); }
699

700
 private:
701 702
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

703 704 705 706
  Expression* cond_;
};


707
class WhileStatement final : public IterationStatement {
708
 public:
709 710
  DECLARE_NODE_TYPE(WhileStatement)

711 712 713 714 715 716
  void Initialize(Expression* cond, Statement* body) {
    IterationStatement::Initialize(body);
    cond_ = cond;
  }

  Expression* cond() const { return cond_; }
717
  void set_cond(Expression* e) { cond_ = e; }
718

719
  static int num_ids() { return parent_num_ids() + 1; }
720 721
  BailoutId ContinueId() const override { return EntryId(); }
  BailoutId StackCheckId() const override { return BodyId(); }
722
  BailoutId BodyId() const { return BailoutId(local_id(0)); }
723

724
 protected:
725
  WhileStatement(Zone* zone, ZoneList<const AstRawString*>* labels, int pos)
726
      : IterationStatement(zone, labels, pos), cond_(NULL) {}
727
  static int parent_num_ids() { return IterationStatement::num_ids(); }
728

729
 private:
730 731
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

732 733 734 735
  Expression* cond_;
};


736
class ForStatement final : public IterationStatement {
737
 public:
738
  DECLARE_NODE_TYPE(ForStatement)
739 740 741 742 743 744 745 746 747 748 749

  void Initialize(Statement* init,
                  Expression* cond,
                  Statement* next,
                  Statement* body) {
    IterationStatement::Initialize(body);
    init_ = init;
    cond_ = cond;
    next_ = next;
  }

750 751 752
  Statement* init() const { return init_; }
  Expression* cond() const { return cond_; }
  Statement* next() const { return next_; }
753

754 755 756 757
  void set_init(Statement* s) { init_ = s; }
  void set_cond(Expression* e) { cond_ = e; }
  void set_next(Statement* s) { next_ = s; }

758
  static int num_ids() { return parent_num_ids() + 2; }
759 760
  BailoutId ContinueId() const override { return BailoutId(local_id(0)); }
  BailoutId StackCheckId() const override { return BodyId(); }
761
  BailoutId BodyId() const { return BailoutId(local_id(1)); }
762

763
 protected:
764 765
  ForStatement(Zone* zone, ZoneList<const AstRawString*>* labels, int pos)
      : IterationStatement(zone, labels, pos),
766 767
        init_(NULL),
        cond_(NULL),
768
        next_(NULL) {}
769
  static int parent_num_ids() { return IterationStatement::num_ids(); }
770

771
 private:
772 773
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

774 775 776 777 778 779
  Statement* init_;
  Expression* cond_;
  Statement* next_;
};


780
class ForEachStatement : public IterationStatement {
781
 public:
782 783 784 785
  enum VisitMode {
    ENUMERATE,   // for (each in subject) body;
    ITERATE      // for (each of subject) body;
  };
786

787
  using IterationStatement::Initialize;
788

789 790 791 792
  static const char* VisitModeString(VisitMode mode) {
    return mode == ITERATE ? "for-of" : "for-in";
  }

793
 protected:
794
  ForEachStatement(Zone* zone, ZoneList<const AstRawString*>* labels, int pos)
795
      : IterationStatement(zone, labels, pos) {}
796 797 798
};


799
class ForInStatement final : public ForEachStatement {
800 801 802
 public:
  DECLARE_NODE_TYPE(ForInStatement)

803 804 805 806 807 808
  void Initialize(Expression* each, Expression* subject, Statement* body) {
    ForEachStatement::Initialize(body);
    each_ = each;
    subject_ = subject;
  }

809 810 811 812
  Expression* enumerable() const {
    return subject();
  }

813 814 815 816 817 818
  Expression* each() const { return each_; }
  Expression* subject() const { return subject_; }

  void set_each(Expression* e) { each_ = e; }
  void set_subject(Expression* e) { subject_ = e; }

819
  // Type feedback information.
820
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
821 822
                                 FeedbackVectorSlotCache* cache) override;
  FeedbackVectorSlot EachFeedbackSlot() const { return each_slot_; }
823 824
  FeedbackVectorSlot ForInFeedbackSlot() {
    DCHECK(!for_in_feedback_slot_.IsInvalid());
825 826 827
    return for_in_feedback_slot_;
  }

828 829
  enum ForInType { FAST_FOR_IN, SLOW_FOR_IN };
  ForInType for_in_type() const { return for_in_type_; }
830
  void set_for_in_type(ForInType type) { for_in_type_ = type; }
831

832
  static int num_ids() { return parent_num_ids() + 6; }
833
  BailoutId BodyId() const { return BailoutId(local_id(0)); }
834 835
  BailoutId EnumId() const { return BailoutId(local_id(1)); }
  BailoutId ToObjectId() const { return BailoutId(local_id(2)); }
836 837 838
  BailoutId PrepareId() const { return BailoutId(local_id(3)); }
  BailoutId FilterId() const { return BailoutId(local_id(4)); }
  BailoutId AssignmentId() const { return BailoutId(local_id(5)); }
839 840
  BailoutId ContinueId() const override { return EntryId(); }
  BailoutId StackCheckId() const override { return BodyId(); }
841

842
 protected:
843
  ForInStatement(Zone* zone, ZoneList<const AstRawString*>* labels, int pos)
844 845 846 847
      : ForEachStatement(zone, labels, pos),
        each_(nullptr),
        subject_(nullptr),
        for_in_type_(SLOW_FOR_IN) {}
848
  static int parent_num_ids() { return ForEachStatement::num_ids(); }
849

850
 private:
851 852
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

853 854
  Expression* each_;
  Expression* subject_;
855
  ForInType for_in_type_;
856
  FeedbackVectorSlot each_slot_;
857
  FeedbackVectorSlot for_in_feedback_slot_;
858
};
859

860

861
class ForOfStatement final : public ForEachStatement {
862 863 864
 public:
  DECLARE_NODE_TYPE(ForOfStatement)

865 866 867 868
  void Initialize(Statement* body, Variable* iterator,
                  Expression* assign_iterator, Expression* next_result,
                  Expression* result_done, Expression* assign_each) {
    ForEachStatement::Initialize(body);
869
    iterator_ = iterator;
870 871 872 873 874 875
    assign_iterator_ = assign_iterator;
    next_result_ = next_result;
    result_done_ = result_done;
    assign_each_ = assign_each;
  }

876 877 878 879
  Variable* iterator() const {
    return iterator_;
  }

880
  // iterator = subject[Symbol.iterator]()
881 882 883 884
  Expression* assign_iterator() const {
    return assign_iterator_;
  }

885
  // result = iterator.next()  // with type check
886 887 888 889 890 891 892 893 894 895 896 897 898 899
  Expression* next_result() const {
    return next_result_;
  }

  // result.done
  Expression* result_done() const {
    return result_done_;
  }

  // each = result.value
  Expression* assign_each() const {
    return assign_each_;
  }

900 901 902 903 904
  void set_assign_iterator(Expression* e) { assign_iterator_ = e; }
  void set_next_result(Expression* e) { next_result_ = e; }
  void set_result_done(Expression* e) { result_done_ = e; }
  void set_assign_each(Expression* e) { assign_each_ = e; }

905 906
  BailoutId ContinueId() const override { return EntryId(); }
  BailoutId StackCheckId() const override { return BackEdgeId(); }
907

908 909
  static int num_ids() { return parent_num_ids() + 1; }
  BailoutId BackEdgeId() const { return BailoutId(local_id(0)); }
910

911
 protected:
912 913
  ForOfStatement(Zone* zone, ZoneList<const AstRawString*>* labels, int pos)
      : ForEachStatement(zone, labels, pos),
914
        iterator_(NULL),
915 916 917
        assign_iterator_(NULL),
        next_result_(NULL),
        result_done_(NULL),
918
        assign_each_(NULL) {}
919
  static int parent_num_ids() { return ForEachStatement::num_ids(); }
920

921
 private:
922 923
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

924
  Variable* iterator_;
925 926 927 928
  Expression* assign_iterator_;
  Expression* next_result_;
  Expression* result_done_;
  Expression* assign_each_;
929 930 931
};


932
class ExpressionStatement final : public Statement {
933
 public:
934
  DECLARE_NODE_TYPE(ExpressionStatement)
935 936

  void set_expression(Expression* e) { expression_ = e; }
937
  Expression* expression() const { return expression_; }
938
  bool IsJump() const override { return expression_->IsThrow(); }
939

940
 protected:
941 942
  ExpressionStatement(Zone* zone, Expression* expression, int pos)
      : Statement(zone, pos), expression_(expression) { }
943

944 945 946 947 948
 private:
  Expression* expression_;
};


949
class JumpStatement : public Statement {
950
 public:
951
  bool IsJump() const final { return true; }
952 953

 protected:
954
  explicit JumpStatement(Zone* zone, int pos) : Statement(zone, pos) {}
955 956 957
};


958
class ContinueStatement final : public JumpStatement {
959
 public:
960
  DECLARE_NODE_TYPE(ContinueStatement)
961

962
  IterationStatement* target() const { return target_; }
963 964

 protected:
965 966
  explicit ContinueStatement(Zone* zone, IterationStatement* target, int pos)
      : JumpStatement(zone, pos), target_(target) { }
967 968 969 970 971 972

 private:
  IterationStatement* target_;
};


973
class BreakStatement final : public JumpStatement {
974
 public:
975
  DECLARE_NODE_TYPE(BreakStatement)
976

977
  BreakableStatement* target() const { return target_; }
978 979

 protected:
980 981
  explicit BreakStatement(Zone* zone, BreakableStatement* target, int pos)
      : JumpStatement(zone, pos), target_(target) { }
982 983 984 985 986 987

 private:
  BreakableStatement* target_;
};


988
class ReturnStatement final : public JumpStatement {
989
 public:
990
  DECLARE_NODE_TYPE(ReturnStatement)
991

992
  Expression* expression() const { return expression_; }
993

994 995
  void set_expression(Expression* e) { expression_ = e; }

996
 protected:
997 998
  explicit ReturnStatement(Zone* zone, Expression* expression, int pos)
      : JumpStatement(zone, pos), expression_(expression) { }
999 1000 1001 1002 1003 1004

 private:
  Expression* expression_;
};


1005
class WithStatement final : public Statement {
1006
 public:
1007
  DECLARE_NODE_TYPE(WithStatement)
1008

1009
  Scope* scope() { return scope_; }
1010
  Expression* expression() const { return expression_; }
1011
  void set_expression(Expression* e) { expression_ = e; }
1012
  Statement* statement() const { return statement_; }
1013
  void set_statement(Statement* s) { statement_ = s; }
1014

1015
  void set_base_id(int id) { base_id_ = id; }
1016 1017 1018
  static int num_ids() { return parent_num_ids() + 2; }
  BailoutId ToObjectId() const { return BailoutId(local_id(0)); }
  BailoutId EntryId() const { return BailoutId(local_id(1)); }
1019

1020
 protected:
1021 1022
  WithStatement(Zone* zone, Scope* scope, Expression* expression,
                Statement* statement, int pos)
1023
      : Statement(zone, pos),
1024
        scope_(scope),
1025
        expression_(expression),
1026 1027 1028 1029 1030 1031 1032 1033
        statement_(statement),
        base_id_(BailoutId::None().ToInt()) {}
  static int parent_num_ids() { return 0; }

  int base_id() const {
    DCHECK(!BailoutId(base_id_).IsNone());
    return base_id_;
  }
1034

1035
 private:
1036 1037
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

1038
  Scope* scope_;
1039
  Expression* expression_;
1040
  Statement* statement_;
1041
  int base_id_;
1042 1043 1044
};


1045
class CaseClause final : public Expression {
1046
 public:
1047
  DECLARE_NODE_TYPE(CaseClause)
1048

1049 1050
  bool is_default() const { return label_ == NULL; }
  Expression* label() const {
1051 1052 1053
    CHECK(!is_default());
    return label_;
  }
1054
  void set_label(Expression* e) { label_ = e; }
1055
  Label* body_target() { return &body_target_; }
1056
  ZoneList<Statement*>* statements() const { return statements_; }
1057

1058 1059 1060
  static int num_ids() { return parent_num_ids() + 2; }
  BailoutId EntryId() const { return BailoutId(local_id(0)); }
  TypeFeedbackId CompareId() { return TypeFeedbackId(local_id(1)); }
1061

1062 1063
  Type* compare_type() { return compare_type_; }
  void set_compare_type(Type* type) { compare_type_ = type; }
1064

1065 1066 1067
 protected:
  static int parent_num_ids() { return Expression::num_ids(); }

1068
 private:
1069
  CaseClause(Zone* zone, Expression* label, ZoneList<Statement*>* statements,
1070 1071
             int pos);
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }
1072

1073
  Expression* label_;
1074
  Label body_target_;
1075
  ZoneList<Statement*>* statements_;
1076
  Type* compare_type_;
1077 1078 1079
};


1080
class SwitchStatement final : public BreakableStatement {
1081
 public:
1082 1083
  DECLARE_NODE_TYPE(SwitchStatement)

1084 1085 1086 1087 1088
  void Initialize(Expression* tag, ZoneList<CaseClause*>* cases) {
    tag_ = tag;
    cases_ = cases;
  }

1089 1090
  Expression* tag() const { return tag_; }
  ZoneList<CaseClause*>* cases() const { return cases_; }
1091

1092 1093
  void set_tag(Expression* t) { tag_ = t; }

1094
 protected:
1095 1096
  SwitchStatement(Zone* zone, ZoneList<const AstRawString*>* labels, int pos)
      : BreakableStatement(zone, labels, TARGET_FOR_ANONYMOUS, pos),
1097
        tag_(NULL),
1098
        cases_(NULL) {}
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110

 private:
  Expression* tag_;
  ZoneList<CaseClause*>* cases_;
};


// If-statements always have non-null references to their then- and
// else-parts. When parsing if-statements with no explicit else-part,
// the parser implicitly creates an empty statement. Use the
// HasThenStatement() and HasElseStatement() functions to check if a
// given if-statement has a then- or an else-part containing code.
1111
class IfStatement final : public Statement {
1112
 public:
1113
  DECLARE_NODE_TYPE(IfStatement)
1114 1115 1116 1117 1118 1119 1120 1121

  bool HasThenStatement() const { return !then_statement()->IsEmpty(); }
  bool HasElseStatement() const { return !else_statement()->IsEmpty(); }

  Expression* condition() const { return condition_; }
  Statement* then_statement() const { return then_statement_; }
  Statement* else_statement() const { return else_statement_; }

1122
  void set_condition(Expression* e) { condition_ = e; }
1123 1124 1125
  void set_then_statement(Statement* s) { then_statement_ = s; }
  void set_else_statement(Statement* s) { else_statement_ = s; }

1126
  bool IsJump() const override {
1127 1128 1129 1130
    return HasThenStatement() && then_statement()->IsJump()
        && HasElseStatement() && else_statement()->IsJump();
  }

1131 1132 1133 1134 1135
  void set_base_id(int id) { base_id_ = id; }
  static int num_ids() { return parent_num_ids() + 3; }
  BailoutId IfId() const { return BailoutId(local_id(0)); }
  BailoutId ThenId() const { return BailoutId(local_id(1)); }
  BailoutId ElseId() const { return BailoutId(local_id(2)); }
1136

1137
 protected:
1138
  IfStatement(Zone* zone, Expression* condition, Statement* then_statement,
1139
              Statement* else_statement, int pos)
1140
      : Statement(zone, pos),
1141
        condition_(condition),
1142 1143
        then_statement_(then_statement),
        else_statement_(else_statement),
1144 1145
        base_id_(BailoutId::None().ToInt()) {}
  static int parent_num_ids() { return 0; }
1146

1147 1148 1149 1150
  int base_id() const {
    DCHECK(!BailoutId(base_id_).IsNone());
    return base_id_;
  }
1151

1152
 private:
1153 1154
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

1155 1156 1157
  Expression* condition_;
  Statement* then_statement_;
  Statement* else_statement_;
1158
  int base_id_;
1159 1160 1161
};


1162
class TryStatement : public Statement {
1163 1164
 public:
  Block* try_block() const { return try_block_; }
1165
  void set_try_block(Block* b) { try_block_ = b; }
1166 1167

 protected:
1168
  TryStatement(Zone* zone, Block* try_block, int pos)
1169
      : Statement(zone, pos), try_block_(try_block) {}
1170 1171 1172 1173 1174 1175

 private:
  Block* try_block_;
};


1176
class TryCatchStatement final : public TryStatement {
1177
 public:
1178 1179 1180 1181 1182
  DECLARE_NODE_TYPE(TryCatchStatement)

  Scope* scope() { return scope_; }
  Variable* variable() { return variable_; }
  Block* catch_block() const { return catch_block_; }
1183
  void set_catch_block(Block* b) { catch_block_ = b; }
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194

  // The clear_pending_message flag indicates whether or not to clear the
  // isolate's pending exception message before executing the catch_block.  In
  // the normal use case, this flag is always on because the message object
  // is not needed anymore when entering the catch block and should not be kept
  // alive.
  // The use case where the flag is off is when the catch block is guaranteed to
  // rethrow the caught exception (using %ReThrow), which reuses the pending
  // message instead of generating a new one.
  // (When the catch block doesn't rethrow but is guaranteed to perform an
  // ordinary throw, not clearing the old message is safe but not very useful.)
1195
  bool clear_pending_message() { return clear_pending_message_; }
1196 1197

 protected:
1198
  TryCatchStatement(Zone* zone, Block* try_block, Scope* scope,
1199 1200
                    Variable* variable, Block* catch_block,
                    bool clear_pending_message, int pos)
1201
      : TryStatement(zone, try_block, pos),
1202 1203
        scope_(scope),
        variable_(variable),
1204 1205
        catch_block_(catch_block),
        clear_pending_message_(clear_pending_message) {}
1206 1207

 private:
1208 1209
  Scope* scope_;
  Variable* variable_;
1210
  Block* catch_block_;
1211
  bool clear_pending_message_;
1212 1213 1214
};


1215
class TryFinallyStatement final : public TryStatement {
1216
 public:
1217
  DECLARE_NODE_TYPE(TryFinallyStatement)
1218 1219

  Block* finally_block() const { return finally_block_; }
1220
  void set_finally_block(Block* b) { finally_block_ = b; }
1221 1222

 protected:
1223 1224 1225
  TryFinallyStatement(Zone* zone, Block* try_block, Block* finally_block,
                      int pos)
      : TryStatement(zone, try_block, pos), finally_block_(finally_block) {}
1226 1227 1228 1229 1230 1231

 private:
  Block* finally_block_;
};


1232
class DebuggerStatement final : public Statement {
1233
 public:
1234
  DECLARE_NODE_TYPE(DebuggerStatement)
1235

1236 1237 1238
  void set_base_id(int id) { base_id_ = id; }
  static int num_ids() { return parent_num_ids() + 1; }
  BailoutId DebugBreakId() const { return BailoutId(local_id(0)); }
1239

1240
 protected:
1241 1242 1243
  explicit DebuggerStatement(Zone* zone, int pos)
      : Statement(zone, pos), base_id_(BailoutId::None().ToInt()) {}
  static int parent_num_ids() { return 0; }
1244

1245 1246 1247 1248
  int base_id() const {
    DCHECK(!BailoutId(base_id_).IsNone());
    return base_id_;
  }
1249 1250

 private:
1251 1252 1253
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

  int base_id_;
1254 1255 1256
};


1257
class EmptyStatement final : public Statement {
1258
 public:
1259
  DECLARE_NODE_TYPE(EmptyStatement)
1260

1261
 protected:
1262
  explicit EmptyStatement(Zone* zone, int pos): Statement(zone, pos) {}
1263 1264 1265
};


1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
// Delegates to another statement, which may be overwritten.
// This was introduced to implement ES2015 Annex B3.3 for conditionally making
// sloppy-mode block-scoped functions have a var binding, which is changed
// from one statement to another during parsing.
class SloppyBlockFunctionStatement final : public Statement {
 public:
  DECLARE_NODE_TYPE(SloppyBlockFunctionStatement)

  Statement* statement() const { return statement_; }
  void set_statement(Statement* statement) { statement_ = statement; }
  Scope* scope() const { return scope_; }

 private:
  SloppyBlockFunctionStatement(Zone* zone, Statement* statement, Scope* scope)
      : Statement(zone, RelocInfo::kNoPosition),
        statement_(statement),
        scope_(scope) {}

  Statement* statement_;
  Scope* const scope_;
};


1289
class Literal final : public Expression {
1290
 public:
1291 1292
  DECLARE_NODE_TYPE(Literal)

1293
  bool IsPropertyName() const override { return value_->IsPropertyName(); }
1294

1295
  Handle<String> AsPropertyName() {
1296
    DCHECK(IsPropertyName());
1297 1298 1299 1300
    return Handle<String>::cast(value());
  }

  const AstRawString* AsRawPropertyName() {
1301
    DCHECK(IsPropertyName());
1302
    return value_->AsString();
1303 1304
  }

1305 1306
  bool ToBooleanIsTrue() const override { return value()->BooleanValue(); }
  bool ToBooleanIsFalse() const override { return !value()->BooleanValue(); }
1307

1308 1309
  Handle<Object> value() const { return value_->value(); }
  const AstValue* raw_value() const { return value_; }
1310

1311 1312
  // Support for using Literal as a HashMap key. NOTE: Currently, this works
  // only for string and number literals!
1313 1314
  uint32_t Hash();
  static bool Match(void* literal1, void* literal2);
1315

1316
  static int num_ids() { return parent_num_ids() + 1; }
1317
  TypeFeedbackId LiteralFeedbackId() const {
1318
    return TypeFeedbackId(local_id(0));
1319
  }
1320

1321
 protected:
1322 1323 1324
  Literal(Zone* zone, const AstValue* value, int position)
      : Expression(zone, position), value_(value) {}
  static int parent_num_ids() { return Expression::num_ids(); }
1325

1326
 private:
1327 1328
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

1329
  const AstValue* value_;
1330 1331 1332
};


1333 1334
class AstLiteralReindexer;

1335
// Base class for literals that needs space in the corresponding JSFunction.
1336
class MaterializedLiteral : public Expression {
1337
 public:
1338
  MaterializedLiteral* AsMaterializedLiteral() final { return this; }
1339

1340
  int literal_index() { return literal_index_; }
1341

1342 1343
  int depth() const {
    // only callable after initialization.
1344
    DCHECK(depth_ >= 1);
1345 1346 1347
    return depth_;
  }

1348
 protected:
1349
  MaterializedLiteral(Zone* zone, int literal_index, int pos)
1350
      : Expression(zone, pos),
1351
        literal_index_(literal_index),
1352 1353
        is_simple_(false),
        depth_(0) {}
1354 1355 1356 1357 1358 1359 1360

  // A materialized literal is simple if the values consist of only
  // constants and simple object and array literals.
  bool is_simple() const { return is_simple_; }
  void set_is_simple(bool is_simple) { is_simple_ = is_simple; }
  friend class CompileTimeValue;

1361
  void set_depth(int depth) {
1362
    DCHECK(depth >= 1);
1363 1364 1365
    depth_ = depth;
  }

1366
  // Populate the constant properties/elements fixed array.
1367
  void BuildConstants(Isolate* isolate);
1368 1369 1370 1371 1372 1373 1374 1375 1376
  friend class ArrayLiteral;
  friend class ObjectLiteral;

  // If the expression is a literal, return the literal value;
  // if the expression is a materialized literal and is simple return a
  // compile time value as encoded by CompileTimeValue::GetValue().
  // Otherwise, return undefined literal as the placeholder
  // in the object literal boilerplate.
  Handle<Object> GetBoilerplateValue(Expression* expression, Isolate* isolate);
1377

1378 1379
 private:
  int literal_index_;
1380
  bool is_simple_;
1381
  int depth_;
1382 1383

  friend class AstLiteralReindexer;
1384 1385 1386
};


1387 1388 1389
// Property is used for passing information
// about an object literal's properties from the parser
// to the code generator.
1390
class ObjectLiteralProperty final : public ZoneObject {
1391 1392 1393 1394 1395 1396 1397 1398 1399
 public:
  enum Kind {
    CONSTANT,              // Property with constant value (compile time).
    COMPUTED,              // Property with computed value (execution time).
    MATERIALIZED_LITERAL,  // Property value is a materialized literal.
    GETTER, SETTER,        // Property is an accessor function.
    PROTOTYPE              // Property is __proto__.
  };

arv's avatar
arv committed
1400
  Expression* key() { return key_; }
1401 1402 1403
  Expression* value() { return value_; }
  Kind kind() { return kind_; }

1404 1405 1406
  void set_key(Expression* e) { key_ = e; }
  void set_value(Expression* e) { value_ = e; }

1407 1408 1409 1410 1411 1412 1413 1414 1415
  // Type feedback information.
  bool IsMonomorphic() { return !receiver_type_.is_null(); }
  Handle<Map> GetReceiverType() { return receiver_type_; }

  bool IsCompileTimeValue();

  void set_emit_store(bool emit_store);
  bool emit_store();

1416
  bool is_static() const { return is_static_; }
arv's avatar
arv committed
1417
  bool is_computed_name() const { return is_computed_name_; }
1418

1419 1420 1421 1422 1423 1424 1425
  FeedbackVectorSlot GetSlot(int offset = 0) const {
    DCHECK_LT(offset, static_cast<int>(arraysize(slots_)));
    return slots_[offset];
  }
  void SetSlot(FeedbackVectorSlot slot, int offset = 0) {
    DCHECK_LT(offset, static_cast<int>(arraysize(slots_)));
    slots_[offset] = slot;
1426 1427
  }

1428 1429
  void set_receiver_type(Handle<Map> map) { receiver_type_ = map; }

1430
  bool NeedsSetFunctionName() const;
1431

1432
 protected:
1433
  friend class AstNodeFactory;
1434

1435 1436 1437 1438
  ObjectLiteralProperty(Expression* key, Expression* value, Kind kind,
                        bool is_static, bool is_computed_name);
  ObjectLiteralProperty(AstValueFactory* ast_value_factory, Expression* key,
                        Expression* value, bool is_static,
arv's avatar
arv committed
1439
                        bool is_computed_name);
1440 1441

 private:
arv's avatar
arv committed
1442
  Expression* key_;
1443
  Expression* value_;
1444
  FeedbackVectorSlot slots_[2];
1445 1446
  Kind kind_;
  bool emit_store_;
arv@chromium.org's avatar
arv@chromium.org committed
1447
  bool is_static_;
arv's avatar
arv committed
1448
  bool is_computed_name_;
1449 1450 1451 1452
  Handle<Map> receiver_type_;
};


1453 1454
// An object literal has a boilerplate object that is used
// for minimizing the work when constructing it at runtime.
1455
class ObjectLiteral final : public MaterializedLiteral {
1456
 public:
1457
  typedef ObjectLiteralProperty Property;
1458

1459
  DECLARE_NODE_TYPE(ObjectLiteral)
1460 1461 1462 1463

  Handle<FixedArray> constant_properties() const {
    return constant_properties_;
  }
1464
  int properties_count() const { return constant_properties_->length() / 2; }
1465
  ZoneList<Property*>* properties() const { return properties_; }
1466
  bool fast_elements() const { return fast_elements_; }
1467
  bool may_store_doubles() const { return may_store_doubles_; }
1468
  bool has_elements() const { return has_elements_; }
1469 1470 1471
  bool has_shallow_properties() const {
    return depth() == 1 && !has_elements() && !may_store_doubles();
  }
1472

1473 1474 1475 1476
  // Decide if a property should be in the object boilerplate.
  static bool IsBoilerplateProperty(Property* property);

  // Populate the constant properties fixed array.
1477
  void BuildConstantProperties(Isolate* isolate);
1478

1479 1480 1481
  // Mark all computed expressions that are bound to a key that
  // is shadowed by a later occurrence of the same key. For the
  // marked expressions, no store code is emitted.
1482
  void CalculateEmitStore(Zone* zone);
1483

1484
  // Assemble bitfield of flags for the CreateObjectLiteral helper.
1485
  int ComputeFlags(bool disable_mementos = false) const {
1486
    int flags = fast_elements() ? kFastElements : kNoFlags;
1487
    if (has_shallow_properties()) {
1488 1489
      flags |= kShallowProperties;
    }
1490 1491 1492
    if (disable_mementos) {
      flags |= kDisableMementos;
    }
1493 1494 1495
    return flags;
  }

1496 1497 1498
  enum Flags {
    kNoFlags = 0,
    kFastElements = 1,
1499 1500
    kShallowProperties = 1 << 1,
    kDisableMementos = 1 << 2
1501 1502
  };

1503
  struct Accessors: public ZoneObject {
1504
    Accessors() : getter(NULL), setter(NULL) {}
1505 1506
    ObjectLiteralProperty* getter;
    ObjectLiteralProperty* setter;
1507 1508
  };

1509 1510
  BailoutId CreateLiteralId() const { return BailoutId(local_id(0)); }

1511
  // Return an AST id for a property that is used in simulate instructions.
1512 1513 1514 1515 1516 1517
  BailoutId GetIdForPropertyName(int i) {
    return BailoutId(local_id(2 * i + 1));
  }
  BailoutId GetIdForPropertySet(int i) {
    return BailoutId(local_id(2 * i + 2));
  }
1518 1519 1520

  // Unlike other AST nodes, this number of bailout IDs allocated for an
  // ObjectLiteral can vary, so num_ids() is not a static method.
1521 1522 1523
  int num_ids() const {
    return parent_num_ids() + 1 + 2 * properties()->length();
  }
1524

1525 1526
  // Object literals need one feedback slot for each non-trivial value, as well
  // as some slots for home objects.
1527
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
1528
                                 FeedbackVectorSlotCache* cache) override;
1529

1530
 protected:
1531
  ObjectLiteral(Zone* zone, ZoneList<Property*>* properties, int literal_index,
1532
                int boilerplate_properties, int pos)
1533
      : MaterializedLiteral(zone, literal_index, pos),
1534
        properties_(properties),
1535 1536
        boilerplate_properties_(boilerplate_properties),
        fast_elements_(false),
1537
        has_elements_(false),
1538
        may_store_doubles_(false) {}
1539
  static int parent_num_ids() { return MaterializedLiteral::num_ids(); }
1540

1541
 private:
1542
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }
1543 1544
  Handle<FixedArray> constant_properties_;
  ZoneList<Property*>* properties_;
1545
  int boilerplate_properties_;
1546
  bool fast_elements_;
1547
  bool has_elements_;
1548
  bool may_store_doubles_;
1549
  FeedbackVectorSlot slot_;
1550 1551 1552
};


1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
// A map from property names to getter/setter pairs allocated in the zone.
class AccessorTable : public TemplateHashMap<Literal, ObjectLiteral::Accessors,
                                             ZoneAllocationPolicy> {
 public:
  explicit AccessorTable(Zone* zone)
      : TemplateHashMap<Literal, ObjectLiteral::Accessors,
                        ZoneAllocationPolicy>(Literal::Match,
                                              ZoneAllocationPolicy(zone)),
        zone_(zone) {}

  Iterator lookup(Literal* literal) {
    Iterator it = find(literal, true, ZoneAllocationPolicy(zone_));
    if (it->second == NULL) it->second = new (zone_) ObjectLiteral::Accessors();
    return it;
  }

 private:
  Zone* zone_;
};


1574
// Node for capturing a regexp literal.
1575
class RegExpLiteral final : public MaterializedLiteral {
1576
 public:
1577 1578
  DECLARE_NODE_TYPE(RegExpLiteral)

1579
  Handle<String> pattern() const { return pattern_->string(); }
1580
  int flags() const { return flags_; }
1581 1582

 protected:
1583
  RegExpLiteral(Zone* zone, const AstRawString* pattern, int flags,
1584 1585
                int literal_index, int pos)
      : MaterializedLiteral(zone, literal_index, pos),
1586
        pattern_(pattern),
1587 1588 1589
        flags_(flags) {
    set_depth(1);
  }
1590 1591

 private:
1592 1593
  const AstRawString* const pattern_;
  int const flags_;
1594 1595
};

1596

1597
// An array literal has a literals object that is used
1598
// for minimizing the work when constructing it at runtime.
1599
class ArrayLiteral final : public MaterializedLiteral {
1600
 public:
1601 1602 1603
  DECLARE_NODE_TYPE(ArrayLiteral)

  Handle<FixedArray> constant_elements() const { return constant_elements_; }
1604 1605 1606 1607 1608 1609
  ElementsKind constant_elements_kind() const {
    DCHECK_EQ(2, constant_elements_->length());
    return static_cast<ElementsKind>(
        Smi::cast(constant_elements_->get(0))->value());
  }

1610 1611
  ZoneList<Expression*>* values() const { return values_; }

1612
  BailoutId CreateLiteralId() const { return BailoutId(local_id(0)); }
1613

1614
  // Return an AST id for an element that is used in simulate instructions.
1615 1616 1617 1618 1619
  BailoutId GetIdForElement(int i) { return BailoutId(local_id(i + 1)); }

  // Unlike other AST nodes, this number of bailout IDs allocated for an
  // ArrayLiteral can vary, so num_ids() is not a static method.
  int num_ids() const { return parent_num_ids() + 1 + values()->length(); }
1620

1621
  // Populate the constant elements fixed array.
1622
  void BuildConstantElements(Isolate* isolate);
1623

1624
  // Assemble bitfield of flags for the CreateArrayLiteral helper.
1625
  int ComputeFlags(bool disable_mementos = false) const {
1626
    int flags = depth() == 1 ? kShallowElements : kNoFlags;
1627 1628 1629
    if (disable_mementos) {
      flags |= kDisableMementos;
    }
1630 1631 1632
    return flags;
  }

nikolaos's avatar
nikolaos committed
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
  // Provide a mechanism for iterating through values to rewrite spreads.
  ZoneList<Expression*>::iterator FirstSpread() const {
    return (first_spread_index_ >= 0) ? values_->begin() + first_spread_index_
                                      : values_->end();
  }
  ZoneList<Expression*>::iterator EndValue() const { return values_->end(); }

  // Rewind an array literal omitting everything from the first spread on.
  void RewindSpreads() {
    values_->Rewind(first_spread_index_);
    first_spread_index_ = -1;
  }

1646 1647 1648
  enum Flags {
    kNoFlags = 0,
    kShallowElements = 1,
1649
    kDisableMementos = 1 << 1
1650 1651
  };

1652 1653 1654 1655
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
                                 FeedbackVectorSlotCache* cache) override;
  FeedbackVectorSlot LiteralFeedbackSlot() const { return literal_slot_; }

1656
 protected:
1657
  ArrayLiteral(Zone* zone, ZoneList<Expression*>* values,
1658 1659
               int first_spread_index, int literal_index, int pos)
      : MaterializedLiteral(zone, literal_index, pos),
1660 1661
        values_(values),
        first_spread_index_(first_spread_index) {}
1662
  static int parent_num_ids() { return MaterializedLiteral::num_ids(); }
1663

1664
 private:
1665 1666
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

1667
  Handle<FixedArray> constant_elements_;
1668
  ZoneList<Expression*>* values_;
1669
  int first_spread_index_;
1670
  FeedbackVectorSlot literal_slot_;
1671 1672 1673
};


1674
class VariableProxy final : public Expression {
1675
 public:
1676
  DECLARE_NODE_TYPE(VariableProxy)
1677

1678 1679 1680
  bool IsValidReferenceExpression() const override {
    return !is_this() && !is_new_target();
  }
1681

1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
  bool IsArguments() const { return is_resolved() && var()->is_arguments(); }

  Handle<String> name() const { return raw_name()->string(); }
  const AstRawString* raw_name() const {
    return is_resolved() ? var_->raw_name() : raw_name_;
  }

  Variable* var() const {
    DCHECK(is_resolved());
    return var_;
  }
  void set_var(Variable* v) {
    DCHECK(!is_resolved());
    DCHECK_NOT_NULL(v);
    var_ = v;
  }
1698

1699
  bool is_this() const { return IsThisField::decode(bit_field_); }
1700

1701 1702 1703 1704
  bool is_assigned() const { return IsAssignedField::decode(bit_field_); }
  void set_is_assigned() {
    bit_field_ = IsAssignedField::update(bit_field_, true);
  }
1705

1706 1707 1708 1709
  bool is_resolved() const { return IsResolvedField::decode(bit_field_); }
  void set_is_resolved() {
    bit_field_ = IsResolvedField::update(bit_field_, true);
  }
1710

1711 1712 1713 1714 1715
  bool is_new_target() const { return IsNewTargetField::decode(bit_field_); }
  void set_is_new_target() {
    bit_field_ = IsNewTargetField::update(bit_field_, true);
  }

1716 1717
  int end_position() const { return end_position_; }

1718
  // Bind this proxy to the variable var.
1719 1720
  void BindTo(Variable* var);

1721
  bool UsesVariableFeedbackSlot() const {
1722
    return var()->IsUnallocated() || var()->IsLookupSlot();
1723 1724
  }

1725
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
1726
                                 FeedbackVectorSlotCache* cache) override;
1727

1728
  FeedbackVectorSlot VariableFeedbackSlot() { return variable_feedback_slot_; }
1729

1730 1731 1732
  static int num_ids() { return parent_num_ids() + 1; }
  BailoutId BeforeId() const { return BailoutId(local_id(0)); }

1733
 protected:
1734 1735
  VariableProxy(Zone* zone, Variable* var, int start_position,
                int end_position);
1736

1737 1738 1739
  VariableProxy(Zone* zone, const AstRawString* name,
                Variable::Kind variable_kind, int start_position,
                int end_position);
1740 1741
  static int parent_num_ids() { return Expression::num_ids(); }
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }
1742

1743 1744 1745
  class IsThisField : public BitField8<bool, 0, 1> {};
  class IsAssignedField : public BitField8<bool, 1, 1> {};
  class IsResolvedField : public BitField8<bool, 2, 1> {};
1746
  class IsNewTargetField : public BitField8<bool, 3, 1> {};
1747 1748 1749 1750

  // Start with 16-bit (or smaller) field, which should get packed together
  // with Expression's trailing 16-bit field.
  uint8_t bit_field_;
1751
  FeedbackVectorSlot variable_feedback_slot_;
1752 1753 1754 1755
  union {
    const AstRawString* raw_name_;  // if !is_resolved_
    Variable* var_;                 // if is_resolved_
  };
1756 1757 1758 1759
  // Position is stored in the AstNode superclass, but VariableProxy needs to
  // know its end position too (for error messages). It cannot be inferred from
  // the variable name length because it can contain escapes.
  int end_position_;
1760 1761 1762
};


1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
// Left-hand side can only be a property, a global or a (parameter or local)
// slot.
enum LhsKind {
  VARIABLE,
  NAMED_PROPERTY,
  KEYED_PROPERTY,
  NAMED_SUPER_PROPERTY,
  KEYED_SUPER_PROPERTY
};


1774
class Property final : public Expression {
1775
 public:
1776
  DECLARE_NODE_TYPE(Property)
1777

1778
  bool IsValidReferenceExpression() const override { return true; }
1779 1780 1781 1782

  Expression* obj() const { return obj_; }
  Expression* key() const { return key_; }

1783 1784 1785
  void set_obj(Expression* e) { obj_ = e; }
  void set_key(Expression* e) { key_ = e; }

1786
  static int num_ids() { return parent_num_ids() + 1; }
1787
  BailoutId LoadId() const { return BailoutId(local_id(0)); }
1788

1789 1790 1791
  bool IsStringAccess() const {
    return IsStringAccessField::decode(bit_field_);
  }
1792

1793
  // Type feedback information.
1794 1795 1796 1797
  bool IsMonomorphic() override { return receiver_types_.length() == 1; }
  SmallMapList* GetReceiverTypes() override { return &receiver_types_; }
  KeyedAccessStoreMode GetStoreMode() const override { return STANDARD_STORE; }
  IcCheckType GetKeyType() const override {
1798
    return KeyTypeField::decode(bit_field_);
1799
  }
1800 1801 1802 1803
  bool IsUninitialized() const {
    return !is_for_call() && HasNoTypeInformation();
  }
  bool HasNoTypeInformation() const {
1804
    return GetInlineCacheState() == UNINITIALIZED;
1805
  }
1806 1807
  InlineCacheState GetInlineCacheState() const {
    return InlineCacheStateField::decode(bit_field_);
1808
  }
1809 1810 1811
  void set_is_string_access(bool b) {
    bit_field_ = IsStringAccessField::update(bit_field_, b);
  }
1812 1813 1814
  void set_key_type(IcCheckType key_type) {
    bit_field_ = KeyTypeField::update(bit_field_, key_type);
  }
1815 1816 1817
  void set_inline_cache_state(InlineCacheState state) {
    bit_field_ = InlineCacheStateField::update(bit_field_, state);
  }
1818 1819 1820 1821
  void mark_for_call() {
    bit_field_ = IsForCallField::update(bit_field_, true);
  }
  bool is_for_call() const { return IsForCallField::decode(bit_field_); }
1822

1823
  bool IsSuperAccess() { return obj()->IsSuperPropertyReference(); }
1824

1825
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
1826
                                 FeedbackVectorSlotCache* cache) override {
1827 1828 1829 1830
    FeedbackVectorSlotKind kind = key()->IsPropertyName()
                                      ? FeedbackVectorSlotKind::LOAD_IC
                                      : FeedbackVectorSlotKind::KEYED_LOAD_IC;
    property_feedback_slot_ = spec->AddSlot(kind);
1831
  }
1832

1833
  FeedbackVectorSlot PropertyFeedbackSlot() const {
1834 1835
    return property_feedback_slot_;
  }
1836

1837 1838 1839 1840 1841 1842 1843 1844
  static LhsKind GetAssignType(Property* property) {
    if (property == NULL) return VARIABLE;
    bool super_access = property->IsSuperAccess();
    return (property->key()->IsPropertyName())
               ? (super_access ? NAMED_SUPER_PROPERTY : NAMED_PROPERTY)
               : (super_access ? KEYED_SUPER_PROPERTY : KEYED_PROPERTY);
  }

1845
 protected:
1846 1847
  Property(Zone* zone, Expression* obj, Expression* key, int pos)
      : Expression(zone, pos),
1848
        bit_field_(IsForCallField::encode(false) |
1849 1850
                   IsStringAccessField::encode(false) |
                   InlineCacheStateField::encode(UNINITIALIZED)),
1851 1852
        obj_(obj),
        key_(key) {}
1853
  static int parent_num_ids() { return Expression::num_ids(); }
1854

1855
 private:
1856 1857
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

1858
  class IsForCallField : public BitField8<bool, 0, 1> {};
1859 1860 1861
  class IsStringAccessField : public BitField8<bool, 1, 1> {};
  class KeyTypeField : public BitField8<IcCheckType, 2, 1> {};
  class InlineCacheStateField : public BitField8<InlineCacheState, 3, 4> {};
1862
  uint8_t bit_field_;
1863
  FeedbackVectorSlot property_feedback_slot_;
1864 1865 1866
  Expression* obj_;
  Expression* key_;
  SmallMapList receiver_types_;
1867 1868 1869
};


1870
class Call final : public Expression {
1871
 public:
1872
  DECLARE_NODE_TYPE(Call)
1873 1874 1875 1876

  Expression* expression() const { return expression_; }
  ZoneList<Expression*>* arguments() const { return arguments_; }

1877 1878
  void set_expression(Expression* e) { expression_ = e; }

1879
  // Type feedback information.
1880
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
1881
                                 FeedbackVectorSlotCache* cache) override;
1882

1883
  FeedbackVectorSlot CallFeedbackSlot() const { return stub_slot_; }
1884

1885
  FeedbackVectorSlot CallFeedbackICSlot() const { return ic_slot_; }
1886

1887
  SmallMapList* GetReceiverTypes() override {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1888 1889 1890 1891
    if (expression()->IsProperty()) {
      return expression()->AsProperty()->GetReceiverTypes();
    }
    return NULL;
1892 1893
  }

1894
  bool IsMonomorphic() override {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1895 1896 1897 1898
    if (expression()->IsProperty()) {
      return expression()->AsProperty()->IsMonomorphic();
    }
    return !target_.is_null();
1899 1900
  }

1901 1902
  bool global_call() const {
    VariableProxy* proxy = expression_->AsVariableProxy();
1903
    return proxy != NULL && proxy->var()->IsUnallocatedOrGlobalSlot();
1904 1905 1906 1907 1908 1909
  }

  bool known_global_function() const {
    return global_call() && !target_.is_null();
  }

1910
  Handle<JSFunction> target() { return target_; }
1911

1912 1913
  Handle<AllocationSite> allocation_site() { return allocation_site_; }

1914 1915 1916 1917
  void SetKnownGlobalTarget(Handle<JSFunction> target) {
    target_ = target;
    set_is_uninitialized(false);
  }
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1918
  void set_target(Handle<JSFunction> target) { target_ = target; }
1919 1920 1921
  void set_allocation_site(Handle<AllocationSite> site) {
    allocation_site_ = site;
  }
1922

1923
  static int num_ids() { return parent_num_ids() + 4; }
1924
  BailoutId ReturnId() const { return BailoutId(local_id(0)); }
1925 1926
  BailoutId EvalId() const { return BailoutId(local_id(1)); }
  BailoutId LookupId() const { return BailoutId(local_id(2)); }
1927
  BailoutId CallId() const { return BailoutId(local_id(3)); }
1928

1929 1930 1931 1932 1933 1934 1935
  bool is_uninitialized() const {
    return IsUninitializedField::decode(bit_field_);
  }
  void set_is_uninitialized(bool b) {
    bit_field_ = IsUninitializedField::update(bit_field_, b);
  }

ishell's avatar
ishell committed
1936 1937 1938 1939
  TailCallMode tail_call_mode() const {
    return IsTailField::decode(bit_field_) ? TailCallMode::kAllow
                                           : TailCallMode::kDisallow;
  }
rossberg's avatar
rossberg committed
1940 1941 1942 1943
  void MarkTail() override {
    bit_field_ = IsTailField::update(bit_field_, true);
  }

1944 1945 1946 1947
  enum CallType {
    POSSIBLY_EVAL_CALL,
    GLOBAL_CALL,
    LOOKUP_SLOT_CALL,
1948 1949 1950 1951
    NAMED_PROPERTY_CALL,
    KEYED_PROPERTY_CALL,
    NAMED_SUPER_PROPERTY_CALL,
    KEYED_SUPER_PROPERTY_CALL,
1952
    SUPER_CALL,
1953 1954 1955 1956 1957
    OTHER_CALL
  };

  // Helpers to determine how to handle the call.
  CallType GetCallType(Isolate* isolate) const;
1958
  bool IsUsingCallFeedbackSlot(Isolate* isolate) const;
1959
  bool IsUsingCallFeedbackICSlot(Isolate* isolate) const;
1960

1961 1962 1963 1964 1965
#ifdef DEBUG
  // Used to assert that the FullCodeGenerator records the return site.
  bool return_is_recorded_;
#endif

1966
 protected:
1967
  Call(Zone* zone, Expression* expression, ZoneList<Expression*>* arguments,
1968 1969
       int pos)
      : Expression(zone, pos),
1970
        expression_(expression),
1971
        arguments_(arguments),
1972
        bit_field_(IsUninitializedField::encode(false)) {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1973 1974 1975 1976
    if (expression->IsProperty()) {
      expression->AsProperty()->mark_for_call();
    }
  }
1977
  static int parent_num_ids() { return Expression::num_ids(); }
1978

1979
 private:
1980 1981
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

1982 1983
  FeedbackVectorSlot ic_slot_;
  FeedbackVectorSlot stub_slot_;
1984 1985
  Expression* expression_;
  ZoneList<Expression*>* arguments_;
1986
  Handle<JSFunction> target_;
1987
  Handle<AllocationSite> allocation_site_;
1988
  class IsUninitializedField : public BitField8<bool, 0, 1> {};
rossberg's avatar
rossberg committed
1989
  class IsTailField : public BitField8<bool, 1, 1> {};
1990
  uint8_t bit_field_;
1991
};
1992

1993

1994
class CallNew final : public Expression {
1995
 public:
1996 1997 1998 1999 2000
  DECLARE_NODE_TYPE(CallNew)

  Expression* expression() const { return expression_; }
  ZoneList<Expression*>* arguments() const { return arguments_; }

2001 2002
  void set_expression(Expression* e) { expression_ = e; }

2003
  // Type feedback information.
2004
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
2005
                                 FeedbackVectorSlotCache* cache) override {
2006
    callnew_feedback_slot_ = spec->AddGeneralSlot();
2007 2008
  }

2009 2010 2011 2012
  FeedbackVectorSlot CallNewFeedbackSlot() {
    DCHECK(!callnew_feedback_slot_.IsInvalid());
    return callnew_feedback_slot_;
  }
2013

2014
  bool IsMonomorphic() override { return is_monomorphic_; }
2015
  Handle<JSFunction> target() const { return target_; }
2016 2017
  Handle<AllocationSite> allocation_site() const {
    return allocation_site_;
2018
  }
2019

2020
  static int num_ids() { return parent_num_ids() + 1; }
2021
  static int feedback_slots() { return 1; }
2022
  BailoutId ReturnId() const { return BailoutId(local_id(0)); }
2023

2024 2025 2026 2027 2028
  void set_allocation_site(Handle<AllocationSite> site) {
    allocation_site_ = site;
  }
  void set_is_monomorphic(bool monomorphic) { is_monomorphic_ = monomorphic; }
  void set_target(Handle<JSFunction> target) { target_ = target; }
2029 2030 2031 2032
  void SetKnownGlobalTarget(Handle<JSFunction> target) {
    target_ = target;
    is_monomorphic_ = true;
  }
2033

2034
 protected:
2035
  CallNew(Zone* zone, Expression* expression, ZoneList<Expression*>* arguments,
2036 2037
          int pos)
      : Expression(zone, pos),
2038 2039
        expression_(expression),
        arguments_(arguments),
2040
        is_monomorphic_(false) {}
2041

2042
  static int parent_num_ids() { return Expression::num_ids(); }
2043

2044
 private:
2045 2046
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2047 2048
  Expression* expression_;
  ZoneList<Expression*>* arguments_;
2049 2050
  bool is_monomorphic_;
  Handle<JSFunction> target_;
2051
  Handle<AllocationSite> allocation_site_;
2052
  FeedbackVectorSlot callnew_feedback_slot_;
2053 2054 2055
};


2056 2057 2058 2059
// The CallRuntime class does not represent any official JavaScript
// language construct. Instead it is used to call a C or JS function
// with a set of arguments. This is used from the builtins that are
// implemented in JavaScript (see "v8natives.js").
2060
class CallRuntime final : public Expression {
2061
 public:
2062 2063 2064 2065 2066
  DECLARE_NODE_TYPE(CallRuntime)

  ZoneList<Expression*>* arguments() const { return arguments_; }
  bool is_jsruntime() const { return function_ == NULL; }

2067 2068 2069
  int context_index() const {
    DCHECK(is_jsruntime());
    return context_index_;
2070
  }
2071 2072 2073
  const Runtime::Function* function() const {
    DCHECK(!is_jsruntime());
    return function_;
2074 2075
  }

2076 2077
  static int num_ids() { return parent_num_ids() + 1; }
  BailoutId CallId() { return BailoutId(local_id(0)); }
2078

2079 2080 2081 2082
  const char* debug_name() {
    return is_jsruntime() ? "(context function)" : function_->name;
  }

2083
 protected:
2084
  CallRuntime(Zone* zone, const Runtime::Function* function,
2085
              ZoneList<Expression*>* arguments, int pos)
2086 2087 2088 2089
      : Expression(zone, pos), function_(function), arguments_(arguments) {}

  CallRuntime(Zone* zone, int context_index, ZoneList<Expression*>* arguments,
              int pos)
2090
      : Expression(zone, pos),
2091 2092 2093 2094
        function_(NULL),
        context_index_(context_index),
        arguments_(arguments) {}

2095
  static int parent_num_ids() { return Expression::num_ids(); }
2096

2097
 private:
2098 2099
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2100
  const Runtime::Function* function_;
2101
  int context_index_;
2102 2103 2104 2105
  ZoneList<Expression*>* arguments_;
};


2106
class UnaryOperation final : public Expression {
2107
 public:
2108 2109 2110 2111
  DECLARE_NODE_TYPE(UnaryOperation)

  Token::Value op() const { return op_; }
  Expression* expression() const { return expression_; }
2112
  void set_expression(Expression* e) { expression_ = e; }
2113

2114 2115
  // For unary not (Token::NOT), the AST ids where true and false will
  // actually be materialized, respectively.
2116 2117 2118
  static int num_ids() { return parent_num_ids() + 2; }
  BailoutId MaterializeTrueId() const { return BailoutId(local_id(0)); }
  BailoutId MaterializeFalseId() const { return BailoutId(local_id(1)); }
2119

2120
  void RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle) override;
2121

2122
 protected:
2123 2124
  UnaryOperation(Zone* zone, Token::Value op, Expression* expression, int pos)
      : Expression(zone, pos), op_(op), expression_(expression) {
2125
    DCHECK(Token::IsUnaryOp(op));
2126
  }
2127
  static int parent_num_ids() { return Expression::num_ids(); }
2128

2129
 private:
2130 2131
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2132 2133 2134 2135 2136
  Token::Value op_;
  Expression* expression_;
};


2137
class BinaryOperation final : public Expression {
2138
 public:
2139
  DECLARE_NODE_TYPE(BinaryOperation)
2140

2141
  Token::Value op() const { return static_cast<Token::Value>(op_); }
2142
  Expression* left() const { return left_; }
2143
  void set_left(Expression* e) { left_ = e; }
2144
  Expression* right() const { return right_; }
2145
  void set_right(Expression* e) { right_ = e; }
2146 2147 2148 2149
  Handle<AllocationSite> allocation_site() const { return allocation_site_; }
  void set_allocation_site(Handle<AllocationSite> allocation_site) {
    allocation_site_ = allocation_site;
  }
2150

rossberg's avatar
rossberg committed
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
  void MarkTail() override {
    switch (op()) {
      case Token::COMMA:
      case Token::AND:
      case Token::OR:
        right_->MarkTail();
      default:
        break;
    }
  }

2162 2163
  // The short-circuit logical operations need an AST ID for their
  // right-hand subexpression.
2164 2165
  static int num_ids() { return parent_num_ids() + 2; }
  BailoutId RightId() const { return BailoutId(local_id(0)); }
2166

2167
  TypeFeedbackId BinaryOperationFeedbackId() const {
2168
    return TypeFeedbackId(local_id(1));
2169
  }
2170
  Maybe<int> fixed_right_arg() const {
2171
    return has_fixed_right_arg_ ? Just(fixed_right_arg_value_) : Nothing<int>();
2172 2173
  }
  void set_fixed_right_arg(Maybe<int> arg) {
2174 2175
    has_fixed_right_arg_ = arg.IsJust();
    if (arg.IsJust()) fixed_right_arg_value_ = arg.FromJust();
2176
  }
2177

2178
  void RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle) override;
2179

2180
 protected:
2181
  BinaryOperation(Zone* zone, Token::Value op, Expression* left,
2182 2183
                  Expression* right, int pos)
      : Expression(zone, pos),
2184
        op_(static_cast<byte>(op)),
2185 2186
        has_fixed_right_arg_(false),
        fixed_right_arg_value_(0),
2187
        left_(left),
2188
        right_(right) {
2189
    DCHECK(Token::IsBinaryOp(op));
2190
  }
2191
  static int parent_num_ids() { return Expression::num_ids(); }
2192

2193
 private:
2194 2195
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2196 2197 2198 2199 2200
  const byte op_;  // actually Token::Value
  // TODO(rossberg): the fixed arg should probably be represented as a Constant
  // type for the RHS. Currenty it's actually a Maybe<int>
  bool has_fixed_right_arg_;
  int fixed_right_arg_value_;
2201 2202
  Expression* left_;
  Expression* right_;
2203
  Handle<AllocationSite> allocation_site_;
2204 2205 2206
};


2207
class CountOperation final : public Expression {
2208
 public:
2209
  DECLARE_NODE_TYPE(CountOperation)
2210

2211 2212
  bool is_prefix() const { return IsPrefixField::decode(bit_field_); }
  bool is_postfix() const { return !is_prefix(); }
2213

2214
  Token::Value op() const { return TokenField::decode(bit_field_); }
2215
  Token::Value binary_op() {
2216
    return (op() == Token::INC) ? Token::ADD : Token::SUB;
2217
  }
2218

2219
  Expression* expression() const { return expression_; }
2220
  void set_expression(Expression* e) { expression_ = e; }
2221

2222 2223 2224
  bool IsMonomorphic() override { return receiver_types_.length() == 1; }
  SmallMapList* GetReceiverTypes() override { return &receiver_types_; }
  IcCheckType GetKeyType() const override {
2225 2226
    return KeyTypeField::decode(bit_field_);
  }
2227
  KeyedAccessStoreMode GetStoreMode() const override {
2228
    return StoreModeField::decode(bit_field_);
2229
  }
2230
  Type* type() const { return type_; }
2231 2232 2233 2234 2235 2236
  void set_key_type(IcCheckType type) {
    bit_field_ = KeyTypeField::update(bit_field_, type);
  }
  void set_store_mode(KeyedAccessStoreMode mode) {
    bit_field_ = StoreModeField::update(bit_field_, mode);
  }
2237
  void set_type(Type* type) { type_ = type; }
2238

2239
  static int num_ids() { return parent_num_ids() + 4; }
2240
  BailoutId AssignmentId() const { return BailoutId(local_id(0)); }
2241
  BailoutId ToNumberId() const { return BailoutId(local_id(1)); }
2242
  TypeFeedbackId CountBinOpFeedbackId() const {
2243
    return TypeFeedbackId(local_id(2));
2244 2245
  }
  TypeFeedbackId CountStoreFeedbackId() const {
2246
    return TypeFeedbackId(local_id(3));
2247
  }
2248

2249
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
2250 2251
                                 FeedbackVectorSlotCache* cache) override;
  FeedbackVectorSlot CountSlot() const { return slot_; }
2252

2253
 protected:
2254
  CountOperation(Zone* zone, Token::Value op, bool is_prefix, Expression* expr,
2255 2256
                 int pos)
      : Expression(zone, pos),
2257 2258 2259
        bit_field_(
            IsPrefixField::encode(is_prefix) | KeyTypeField::encode(ELEMENT) |
            StoreModeField::encode(STANDARD_STORE) | TokenField::encode(op)),
2260
        type_(NULL),
2261
        expression_(expr) {}
2262
  static int parent_num_ids() { return Expression::num_ids(); }
2263

2264
 private:
2265 2266
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2267 2268
  class IsPrefixField : public BitField16<bool, 0, 1> {};
  class KeyTypeField : public BitField16<IcCheckType, 1, 1> {};
2269 2270
  class StoreModeField : public BitField16<KeyedAccessStoreMode, 2, 3> {};
  class TokenField : public BitField16<Token::Value, 5, 8> {};
2271 2272 2273 2274

  // Starts with 16-bit field, which should get packed together with
  // Expression's trailing 16-bit field.
  uint16_t bit_field_;
2275
  Type* type_;
2276
  Expression* expression_;
2277
  SmallMapList receiver_types_;
2278
  FeedbackVectorSlot slot_;
2279 2280 2281
};


2282
class CompareOperation final : public Expression {
2283
 public:
2284
  DECLARE_NODE_TYPE(CompareOperation)
2285 2286 2287 2288 2289

  Token::Value op() const { return op_; }
  Expression* left() const { return left_; }
  Expression* right() const { return right_; }

2290 2291 2292
  void set_left(Expression* e) { left_ = e; }
  void set_right(Expression* e) { right_ = e; }

2293
  // Type feedback information.
2294
  static int num_ids() { return parent_num_ids() + 1; }
2295
  TypeFeedbackId CompareOperationFeedbackId() const {
2296
    return TypeFeedbackId(local_id(0));
2297
  }
2298 2299
  Type* combined_type() const { return combined_type_; }
  void set_combined_type(Type* type) { combined_type_ = type; }
2300

2301 2302
  // Match special cases.
  bool IsLiteralCompareTypeof(Expression** expr, Handle<String>* check);
2303
  bool IsLiteralCompareUndefined(Expression** expr);
2304
  bool IsLiteralCompareNull(Expression** expr);
2305

2306
 protected:
2307
  CompareOperation(Zone* zone, Token::Value op, Expression* left,
2308 2309
                   Expression* right, int pos)
      : Expression(zone, pos),
2310 2311 2312
        op_(op),
        left_(left),
        right_(right),
2313
        combined_type_(Type::None()) {
2314
    DCHECK(Token::IsCompareOp(op));
2315
  }
2316
  static int parent_num_ids() { return Expression::num_ids(); }
2317

2318
 private:
2319 2320
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2321 2322 2323
  Token::Value op_;
  Expression* left_;
  Expression* right_;
2324

2325
  Type* combined_type_;
2326 2327 2328
};


2329
class Spread final : public Expression {
2330 2331 2332 2333
 public:
  DECLARE_NODE_TYPE(Spread)

  Expression* expression() const { return expression_; }
2334
  void set_expression(Expression* e) { expression_ = e; }
2335

nikolaos's avatar
nikolaos committed
2336 2337
  int expression_position() const { return expr_pos_; }

2338 2339 2340
  static int num_ids() { return parent_num_ids(); }

 protected:
nikolaos's avatar
nikolaos committed
2341 2342
  Spread(Zone* zone, Expression* expression, int pos, int expr_pos)
      : Expression(zone, pos), expression_(expression), expr_pos_(expr_pos) {}
2343 2344 2345 2346 2347 2348
  static int parent_num_ids() { return Expression::num_ids(); }

 private:
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

  Expression* expression_;
nikolaos's avatar
nikolaos committed
2349
  int expr_pos_;
2350 2351 2352
};


2353
class Conditional final : public Expression {
2354
 public:
2355 2356 2357 2358 2359 2360
  DECLARE_NODE_TYPE(Conditional)

  Expression* condition() const { return condition_; }
  Expression* then_expression() const { return then_expression_; }
  Expression* else_expression() const { return else_expression_; }

2361 2362 2363 2364
  void set_condition(Expression* e) { condition_ = e; }
  void set_then_expression(Expression* e) { then_expression_ = e; }
  void set_else_expression(Expression* e) { else_expression_ = e; }

rossberg's avatar
rossberg committed
2365 2366 2367 2368 2369
  void MarkTail() override {
    then_expression_->MarkTail();
    else_expression_->MarkTail();
  }

2370 2371 2372
  static int num_ids() { return parent_num_ids() + 2; }
  BailoutId ThenId() const { return BailoutId(local_id(0)); }
  BailoutId ElseId() const { return BailoutId(local_id(1)); }
2373 2374

 protected:
2375
  Conditional(Zone* zone, Expression* condition, Expression* then_expression,
2376 2377
              Expression* else_expression, int position)
      : Expression(zone, position),
2378
        condition_(condition),
2379
        then_expression_(then_expression),
2380
        else_expression_(else_expression) {}
2381
  static int parent_num_ids() { return Expression::num_ids(); }
2382

2383
 private:
2384 2385
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2386 2387 2388 2389 2390 2391
  Expression* condition_;
  Expression* then_expression_;
  Expression* else_expression_;
};


2392
class Assignment final : public Expression {
2393
 public:
2394
  DECLARE_NODE_TYPE(Assignment)
2395

2396 2397
  Assignment* AsSimpleAssignment() { return !is_compound() ? this : NULL; }

2398 2399
  Token::Value binary_op() const;

2400
  Token::Value op() const { return TokenField::decode(bit_field_); }
2401 2402
  Expression* target() const { return target_; }
  Expression* value() const { return value_; }
2403

2404 2405 2406
  void set_target(Expression* e) { target_ = e; }
  void set_value(Expression* e) { value_ = e; }

2407 2408
  BinaryOperation* binary_operation() const { return binary_operation_; }

2409 2410
  // This check relies on the definition order of token in token.h.
  bool is_compound() const { return op() > Token::ASSIGN; }
2411

2412 2413
  static int num_ids() { return parent_num_ids() + 2; }
  BailoutId AssignmentId() const { return BailoutId(local_id(0)); }
2414

2415
  // Type feedback information.
2416
  TypeFeedbackId AssignmentFeedbackId() { return TypeFeedbackId(local_id(1)); }
2417
  bool IsMonomorphic() override { return receiver_types_.length() == 1; }
2418 2419 2420
  bool IsUninitialized() const {
    return IsUninitializedField::decode(bit_field_);
  }
2421
  bool HasNoTypeInformation() {
2422
    return IsUninitializedField::decode(bit_field_);
2423
  }
2424 2425
  SmallMapList* GetReceiverTypes() override { return &receiver_types_; }
  IcCheckType GetKeyType() const override {
2426 2427
    return KeyTypeField::decode(bit_field_);
  }
2428
  KeyedAccessStoreMode GetStoreMode() const override {
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
    return StoreModeField::decode(bit_field_);
  }
  void set_is_uninitialized(bool b) {
    bit_field_ = IsUninitializedField::update(bit_field_, b);
  }
  void set_key_type(IcCheckType key_type) {
    bit_field_ = KeyTypeField::update(bit_field_, key_type);
  }
  void set_store_mode(KeyedAccessStoreMode mode) {
    bit_field_ = StoreModeField::update(bit_field_, mode);
2439
  }
2440

2441
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
2442 2443
                                 FeedbackVectorSlotCache* cache) override;
  FeedbackVectorSlot AssignmentSlot() const { return slot_; }
2444

2445
 protected:
2446
  Assignment(Zone* zone, Token::Value op, Expression* target, Expression* value,
2447 2448
             int pos);
  static int parent_num_ids() { return Expression::num_ids(); }
2449

2450
 private:
2451 2452
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2453
  class IsUninitializedField : public BitField16<bool, 0, 1> {};
2454 2455 2456 2457 2458 2459
  class KeyTypeField
      : public BitField16<IcCheckType, IsUninitializedField::kNext, 1> {};
  class StoreModeField
      : public BitField16<KeyedAccessStoreMode, KeyTypeField::kNext, 3> {};
  class TokenField : public BitField16<Token::Value, StoreModeField::kNext, 8> {
  };
2460 2461 2462 2463

  // Starts with 16-bit field, which should get packed together with
  // Expression's trailing 16-bit field.
  uint16_t bit_field_;
2464 2465 2466
  Expression* target_;
  Expression* value_;
  BinaryOperation* binary_operation_;
2467
  SmallMapList receiver_types_;
2468
  FeedbackVectorSlot slot_;
2469 2470 2471
};


2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
// The RewritableExpression class is a wrapper for AST nodes that wait
// for some potential rewriting.  However, even if such nodes are indeed
// rewritten, the RewritableExpression wrapper nodes will survive in the
// final AST and should be just ignored, i.e., they should be treated as
// equivalent to the wrapped nodes.  For this reason and to simplify later
// phases, RewritableExpressions are considered as exceptions of AST nodes
// in the following sense:
//
// 1. IsRewritableExpression and AsRewritableExpression behave as usual.
// 2. All other Is* and As* methods are practically delegated to the
//    wrapped node, i.e. IsArrayLiteral() will return true iff the
//    wrapped node is an array literal.
//
// Furthermore, an invariant that should be respected is that the wrapped
// node is not a RewritableExpression.
class RewritableExpression : public Expression {
2488
 public:
2489
  DECLARE_NODE_TYPE(RewritableExpression)
2490

2491
  Expression* expression() const { return expr_; }
2492 2493 2494 2495 2496
  bool is_rewritten() const { return is_rewritten_; }

  void Rewrite(Expression* new_expression) {
    DCHECK(!is_rewritten());
    DCHECK_NOT_NULL(new_expression);
2497
    DCHECK(!new_expression->IsRewritableExpression());
2498 2499 2500 2501 2502 2503 2504
    expr_ = new_expression;
    is_rewritten_ = true;
  }

  static int num_ids() { return parent_num_ids(); }

 protected:
2505
  RewritableExpression(Zone* zone, Expression* expression)
2506 2507
      : Expression(zone, expression->position()),
        is_rewritten_(false),
2508 2509 2510
        expr_(expression) {
    DCHECK(!expression->IsRewritableExpression());
  }
2511 2512 2513 2514 2515 2516 2517 2518

 private:
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

  bool is_rewritten_;
  Expression* expr_;
};

2519 2520 2521
// Our Yield is different from the JS yield in that it "returns" its argument as
// is, without wrapping it in an iterator result object.  Such wrapping, if
// desired, must be done beforehand (see the parser).
2522
class Yield final : public Expression {
2523 2524 2525
 public:
  DECLARE_NODE_TYPE(Yield)

2526
  Expression* generator_object() const { return generator_object_; }
2527
  Expression* expression() const { return expression_; }
2528
  int yield_id() const { return yield_id_; }
2529

2530 2531
  void set_generator_object(Expression* e) { generator_object_ = e; }
  void set_expression(Expression* e) { expression_ = e; }
2532
  void set_yield_id(int yield_id) { yield_id_ = yield_id; }
2533

2534
 protected:
2535
  Yield(Zone* zone, Expression* generator_object, Expression* expression,
2536
        int pos)
2537
      : Expression(zone, pos),
2538
        generator_object_(generator_object),
2539 2540
        expression_(expression),
        yield_id_(-1) {}
2541 2542

 private:
2543
  Expression* generator_object_;
2544
  Expression* expression_;
2545
  int yield_id_;
2546 2547 2548
};


2549
class Throw final : public Expression {
2550
 public:
2551
  DECLARE_NODE_TYPE(Throw)
2552

2553
  Expression* exception() const { return exception_; }
2554
  void set_exception(Expression* e) { exception_ = e; }
2555 2556

 protected:
2557 2558
  Throw(Zone* zone, Expression* exception, int pos)
      : Expression(zone, pos), exception_(exception) {}
2559 2560 2561 2562 2563 2564

 private:
  Expression* exception_;
};


2565
class FunctionLiteral final : public Expression {
2566
 public:
2567
  enum FunctionType {
2568 2569 2570
    kAnonymousExpression,
    kNamedExpression,
    kDeclaration,
2571
    kAccessorOrMethod
2572 2573
  };

2574
  enum ParameterFlag { kNoDuplicateParameters, kHasDuplicateParameters };
2575

2576
  enum EagerCompileHint { kShouldEagerCompile, kShouldLazyCompile };
2577

2578
  DECLARE_NODE_TYPE(FunctionLiteral)
2579

2580
  Handle<String> name() const { return raw_name_->string(); }
2581 2582
  const AstString* raw_name() const { return raw_name_; }
  void set_raw_name(const AstString* name) { raw_name_ = name; }
2583 2584
  Scope* scope() const { return scope_; }
  ZoneList<Statement*>* body() const { return body_; }
2585 2586
  void set_function_token_position(int pos) { function_token_position_ = pos; }
  int function_token_position() const { return function_token_position_; }
2587 2588
  int start_position() const;
  int end_position() const;
2589
  int SourceSize() const { return end_position() - start_position(); }
2590
  bool is_declaration() const { return function_type() == kDeclaration; }
2591
  bool is_named_expression() const {
2592
    return function_type() == kNamedExpression;
2593 2594
  }
  bool is_anonymous_expression() const {
2595
    return function_type() == kAnonymousExpression;
2596
  }
2597
  LanguageMode language_mode() const;
2598

2599
  static bool NeedsHomeObject(Expression* expr);
2600 2601 2602

  int materialized_literal_count() { return materialized_literal_count_; }
  int expected_property_count() { return expected_property_count_; }
2603
  int parameter_count() { return parameter_count_; }
2604 2605

  bool AllowsLazyCompilation();
2606
  bool AllowsLazyCompilationWithoutContext();
2607

2608
  Handle<String> debug_name() const {
2609 2610 2611
    if (raw_name_ != NULL && !raw_name_->IsEmpty()) {
      return raw_name_->string();
    }
2612 2613 2614
    return inferred_name();
  }

2615 2616
  Handle<String> inferred_name() const {
    if (!inferred_name_.is_null()) {
2617
      DCHECK(raw_inferred_name_ == NULL);
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
      return inferred_name_;
    }
    if (raw_inferred_name_ != NULL) {
      return raw_inferred_name_->string();
    }
    UNREACHABLE();
    return Handle<String>();
  }

  // Only one of {set_inferred_name, set_raw_inferred_name} should be called.
2628
  void set_inferred_name(Handle<String> inferred_name) {
2629
    DCHECK(!inferred_name.is_null());
2630
    inferred_name_ = inferred_name;
2631
    DCHECK(raw_inferred_name_== NULL || raw_inferred_name_->IsEmpty());
2632 2633 2634 2635
    raw_inferred_name_ = NULL;
  }

  void set_raw_inferred_name(const AstString* raw_inferred_name) {
2636
    DCHECK(raw_inferred_name != NULL);
2637
    raw_inferred_name_ = raw_inferred_name;
2638
    DCHECK(inferred_name_.is_null());
2639
    inferred_name_ = Handle<String>();
2640 2641
  }

2642 2643
  bool pretenure() const { return Pretenure::decode(bitfield_); }
  void set_pretenure() { bitfield_ = Pretenure::update(bitfield_, true); }
2644

2645
  bool has_duplicate_parameters() const {
2646 2647
    return HasDuplicateParameters::decode(bitfield_);
  }
2648

2649
  bool is_function() const { return IsFunction::decode(bitfield_); }
2650

2651 2652 2653 2654 2655
  // This is used as a heuristic on when to eagerly compile a function
  // literal. We consider the following constructs as hints that the
  // function will be called immediately:
  // - (function() { ... })();
  // - var x = function() { ... }();
2656
  bool should_eager_compile() const {
2657
    return ShouldEagerCompile::decode(bitfield_);
2658
  }
2659
  void set_should_eager_compile() {
2660
    bitfield_ = ShouldEagerCompile::update(bitfield_, true);
2661
  }
2662

2663 2664 2665
  // A hint that we expect this function to be called (exactly) once,
  // i.e. we suspect it's an initialization function.
  bool should_be_used_once_hint() const {
2666
    return ShouldBeUsedOnceHint::decode(bitfield_);
2667 2668
  }
  void set_should_be_used_once_hint() {
2669
    bitfield_ = ShouldBeUsedOnceHint::update(bitfield_, true);
2670 2671
  }

2672 2673 2674
  FunctionType function_type() const {
    return FunctionTypeBits::decode(bitfield_);
  }
2675
  FunctionKind kind() const { return FunctionKindBits::decode(bitfield_); }
2676

2677
  int ast_node_count() { return ast_properties_.node_count(); }
2678
  AstProperties::Flags flags() const { return ast_properties_.flags(); }
2679 2680 2681
  void set_ast_properties(AstProperties* ast_properties) {
    ast_properties_ = *ast_properties;
  }
2682
  const FeedbackVectorSpec* feedback_vector_spec() const {
2683
    return ast_properties_.get_spec();
2684
  }
2685 2686 2687 2688 2689 2690
  bool dont_optimize() { return dont_optimize_reason_ != kNoReason; }
  BailoutReason dont_optimize_reason() { return dont_optimize_reason_; }
  void set_dont_optimize_reason(BailoutReason reason) {
    dont_optimize_reason_ = reason;
  }

2691
  bool IsAnonymousFunctionDefinition() const final {
2692
    return is_anonymous_expression();
2693 2694
  }

2695 2696 2697
  int yield_count() { return yield_count_; }
  void set_yield_count(int yield_count) { yield_count_ = yield_count; }

2698
 protected:
2699
  FunctionLiteral(Zone* zone, const AstString* name,
2700 2701
                  AstValueFactory* ast_value_factory, Scope* scope,
                  ZoneList<Statement*>* body, int materialized_literal_count,
2702 2703
                  int expected_property_count, int parameter_count,
                  FunctionType function_type,
2704
                  ParameterFlag has_duplicate_parameters,
2705
                  EagerCompileHint eager_compile_hint, FunctionKind kind,
2706
                  int position, bool is_function)
2707
      : Expression(zone, position),
2708
        raw_name_(name),
2709 2710
        scope_(scope),
        body_(body),
2711
        raw_inferred_name_(ast_value_factory->empty_string()),
2712
        ast_properties_(zone),
2713
        dont_optimize_reason_(kNoReason),
2714 2715 2716
        materialized_literal_count_(materialized_literal_count),
        expected_property_count_(expected_property_count),
        parameter_count_(parameter_count),
2717 2718
        function_token_position_(RelocInfo::kNoPosition),
        yield_count_(0) {
2719
    bitfield_ =
2720
        FunctionTypeBits::encode(function_type) | Pretenure::encode(false) |
2721 2722
        HasDuplicateParameters::encode(has_duplicate_parameters ==
                                       kHasDuplicateParameters) |
2723
        IsFunction::encode(is_function) |
2724 2725
        ShouldEagerCompile::encode(eager_compile_hint == kShouldEagerCompile) |
        FunctionKindBits::encode(kind) | ShouldBeUsedOnceHint::encode(false);
2726
    DCHECK(IsValidFunctionKind(kind));
2727 2728
  }

2729
 private:
2730 2731 2732 2733 2734 2735 2736
  class FunctionTypeBits : public BitField16<FunctionType, 0, 2> {};
  class Pretenure : public BitField16<bool, 2, 1> {};
  class HasDuplicateParameters : public BitField16<bool, 3, 1> {};
  class IsFunction : public BitField16<bool, 4, 1> {};
  class ShouldEagerCompile : public BitField16<bool, 5, 1> {};
  class ShouldBeUsedOnceHint : public BitField16<bool, 6, 1> {};
  class FunctionKindBits : public BitField16<FunctionKind, 7, 9> {};
2737 2738 2739 2740 2741

  // Start with 16-bit field, which should get packed together
  // with Expression's trailing 16-bit field.
  uint16_t bitfield_;

2742
  const AstString* raw_name_;
2743 2744
  Scope* scope_;
  ZoneList<Statement*>* body_;
2745
  const AstString* raw_inferred_name_;
2746
  Handle<String> inferred_name_;
2747
  AstProperties ast_properties_;
2748
  BailoutReason dont_optimize_reason_;
2749

2750 2751
  int materialized_literal_count_;
  int expected_property_count_;
2752
  int parameter_count_;
2753
  int function_token_position_;
2754
  int yield_count_;
2755 2756 2757
};


2758
class ClassLiteral final : public Expression {
arv@chromium.org's avatar
arv@chromium.org committed
2759 2760 2761 2762 2763
 public:
  typedef ObjectLiteralProperty Property;

  DECLARE_NODE_TYPE(ClassLiteral)

2764 2765
  Scope* scope() const { return scope_; }
  VariableProxy* class_variable_proxy() const { return class_variable_proxy_; }
arv@chromium.org's avatar
arv@chromium.org committed
2766
  Expression* extends() const { return extends_; }
2767
  void set_extends(Expression* e) { extends_ = e; }
2768
  FunctionLiteral* constructor() const { return constructor_; }
2769
  void set_constructor(FunctionLiteral* f) { constructor_ = f; }
arv@chromium.org's avatar
arv@chromium.org committed
2770
  ZoneList<Property*>* properties() const { return properties_; }
2771 2772
  int start_position() const { return position(); }
  int end_position() const { return end_position_; }
arv@chromium.org's avatar
arv@chromium.org committed
2773

2774 2775 2776
  BailoutId EntryId() const { return BailoutId(local_id(0)); }
  BailoutId DeclsId() const { return BailoutId(local_id(1)); }
  BailoutId ExitId() { return BailoutId(local_id(2)); }
2777
  BailoutId CreateLiteralId() const { return BailoutId(local_id(3)); }
2778
  BailoutId PrototypeId() { return BailoutId(local_id(4)); }
2779

2780
  // Return an AST id for a property that is used in simulate instructions.
2781
  BailoutId GetIdForProperty(int i) { return BailoutId(local_id(i + 5)); }
2782 2783 2784

  // Unlike other AST nodes, this number of bailout IDs allocated for an
  // ClassLiteral can vary, so num_ids() is not a static method.
2785
  int num_ids() const { return parent_num_ids() + 5 + properties()->length(); }
2786

2787 2788
  // Object literals need one feedback slot for each non-trivial value, as well
  // as some slots for home objects.
2789
  void AssignFeedbackVectorSlots(Isolate* isolate, FeedbackVectorSpec* spec,
2790
                                 FeedbackVectorSlotCache* cache) override;
2791 2792

  bool NeedsProxySlot() const {
2793
    return class_variable_proxy() != nullptr &&
2794
           class_variable_proxy()->var()->IsUnallocated();
2795 2796
  }

2797 2798
  FeedbackVectorSlot PrototypeSlot() const { return prototype_slot_; }
  FeedbackVectorSlot ProxySlot() const { return proxy_slot_; }
2799

2800 2801 2802 2803
  bool IsAnonymousFunctionDefinition() const final {
    return constructor()->raw_name()->length() == 0;
  }

arv@chromium.org's avatar
arv@chromium.org committed
2804
 protected:
2805 2806 2807 2808
  ClassLiteral(Zone* zone, Scope* scope, VariableProxy* class_variable_proxy,
               Expression* extends, FunctionLiteral* constructor,
               ZoneList<Property*>* properties, int start_position,
               int end_position)
2809
      : Expression(zone, start_position),
2810 2811
        scope_(scope),
        class_variable_proxy_(class_variable_proxy),
arv@chromium.org's avatar
arv@chromium.org committed
2812 2813
        extends_(extends),
        constructor_(constructor),
2814
        properties_(properties),
2815
        end_position_(end_position) {}
2816

2817
  static int parent_num_ids() { return Expression::num_ids(); }
arv@chromium.org's avatar
arv@chromium.org committed
2818 2819

 private:
2820 2821
  int local_id(int n) const { return base_id() + parent_num_ids() + n; }

2822 2823
  Scope* scope_;
  VariableProxy* class_variable_proxy_;
arv@chromium.org's avatar
arv@chromium.org committed
2824
  Expression* extends_;
2825
  FunctionLiteral* constructor_;
arv@chromium.org's avatar
arv@chromium.org committed
2826
  ZoneList<Property*>* properties_;
2827
  int end_position_;
2828 2829
  FeedbackVectorSlot prototype_slot_;
  FeedbackVectorSlot proxy_slot_;
arv@chromium.org's avatar
arv@chromium.org committed
2830 2831 2832
};


2833
class NativeFunctionLiteral final : public Expression {
2834
 public:
2835
  DECLARE_NODE_TYPE(NativeFunctionLiteral)
2836

2837
  Handle<String> name() const { return name_->string(); }
2838
  v8::Extension* extension() const { return extension_; }
2839 2840

 protected:
2841
  NativeFunctionLiteral(Zone* zone, const AstRawString* name,
2842 2843
                        v8::Extension* extension, int pos)
      : Expression(zone, pos), name_(name), extension_(extension) {}
2844 2845

 private:
2846
  const AstRawString* name_;
2847
  v8::Extension* extension_;
2848 2849 2850
};


2851
class ThisFunction final : public Expression {
2852
 public:
2853
  DECLARE_NODE_TYPE(ThisFunction)
2854 2855

 protected:
2856
  ThisFunction(Zone* zone, int pos) : Expression(zone, pos) {}
2857 2858
};

2859

2860
class SuperPropertyReference final : public Expression {
2861
 public:
2862
  DECLARE_NODE_TYPE(SuperPropertyReference)
2863 2864

  VariableProxy* this_var() const { return this_var_; }
2865
  void set_this_var(VariableProxy* v) { this_var_ = v; }
2866
  Expression* home_object() const { return home_object_; }
2867
  void set_home_object(Expression* e) { home_object_ = e; }
2868

2869
 protected:
2870
  SuperPropertyReference(Zone* zone, VariableProxy* this_var,
2871 2872
                         Expression* home_object, int pos)
      : Expression(zone, pos), this_var_(this_var), home_object_(home_object) {
2873
    DCHECK(this_var->is_this());
2874
    DCHECK(home_object->IsProperty());
2875
  }
2876

2877
 private:
2878
  VariableProxy* this_var_;
2879
  Expression* home_object_;
2880 2881 2882
};


2883 2884 2885 2886 2887
class SuperCallReference final : public Expression {
 public:
  DECLARE_NODE_TYPE(SuperCallReference)

  VariableProxy* this_var() const { return this_var_; }
2888
  void set_this_var(VariableProxy* v) { this_var_ = v; }
2889
  VariableProxy* new_target_var() const { return new_target_var_; }
2890
  void set_new_target_var(VariableProxy* v) { new_target_var_ = v; }
2891
  VariableProxy* this_function_var() const { return this_function_var_; }
2892
  void set_this_function_var(VariableProxy* v) { this_function_var_ = v; }
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902

 protected:
  SuperCallReference(Zone* zone, VariableProxy* this_var,
                     VariableProxy* new_target_var,
                     VariableProxy* this_function_var, int pos)
      : Expression(zone, pos),
        this_var_(this_var),
        new_target_var_(new_target_var),
        this_function_var_(this_function_var) {
    DCHECK(this_var->is_this());
2903
    DCHECK(new_target_var->raw_name()->IsOneByteEqualTo(".new.target"));
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
    DCHECK(this_function_var->raw_name()->IsOneByteEqualTo(".this_function"));
  }

 private:
  VariableProxy* this_var_;
  VariableProxy* new_target_var_;
  VariableProxy* this_function_var_;
};


2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
// This class is produced when parsing the () in arrow functions without any
// arguments and is not actually a valid expression.
class EmptyParentheses final : public Expression {
 public:
  DECLARE_NODE_TYPE(EmptyParentheses)

 private:
  EmptyParentheses(Zone* zone, int pos) : Expression(zone, pos) {}
};


2925 2926
#undef DECLARE_NODE_TYPE

2927 2928 2929 2930 2931

// ----------------------------------------------------------------------------
// Basic visitor
// - leaf node visitors are abstract.

2932
class AstVisitor BASE_EMBEDDED {
2933
 public:
2934
  AstVisitor() {}
2935
  virtual ~AstVisitor() {}
2936

2937
  // Stack overflow check and dynamic dispatch.
2938
  virtual void Visit(AstNode* node) = 0;
2939

2940
  // Iteration left-to-right.
2941
  virtual void VisitDeclarations(ZoneList<Declaration*>* declarations);
2942 2943 2944
  virtual void VisitStatements(ZoneList<Statement*>* statements);
  virtual void VisitExpressions(ZoneList<Expression*>* expressions);

2945
  // Individual AST nodes.
2946 2947
#define DEF_VISIT(type)                         \
  virtual void Visit##type(type* node) = 0;
2948
  AST_NODE_LIST(DEF_VISIT)
2949
#undef DEF_VISIT
2950
};
2951

2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
#define DEFINE_AST_VISITOR_SUBCLASS_MEMBERS()               \
 public:                                                    \
  void Visit(AstNode* node) final {                         \
    if (!CheckStackOverflow()) node->Accept(this);          \
  }                                                         \
                                                            \
  void SetStackOverflow() { stack_overflow_ = true; }       \
  void ClearStackOverflow() { stack_overflow_ = false; }    \
  bool HasStackOverflow() const { return stack_overflow_; } \
                                                            \
  bool CheckStackOverflow() {                               \
    if (stack_overflow_) return true;                       \
    if (GetCurrentStackPosition() < stack_limit_) {         \
      stack_overflow_ = true;                               \
      return true;                                          \
    }                                                       \
    return false;                                           \
  }                                                         \
                                                            \
 private:                                                   \
  void InitializeAstVisitor(Isolate* isolate) {             \
    stack_limit_ = isolate->stack_guard()->real_climit();   \
    stack_overflow_ = false;                                \
  }                                                         \
                                                            \
2977 2978 2979 2980 2981
  void InitializeAstVisitor(uintptr_t stack_limit) {        \
    stack_limit_ = stack_limit;                             \
    stack_overflow_ = false;                                \
  }                                                         \
                                                            \
2982
  uintptr_t stack_limit_;                                   \
2983
  bool stack_overflow_
2984

2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
#define DEFINE_AST_REWRITER_SUBCLASS_MEMBERS()        \
 public:                                              \
  AstNode* Rewrite(AstNode* node) {                   \
    DCHECK_NULL(replacement_);                        \
    DCHECK_NOT_NULL(node);                            \
    Visit(node);                                      \
    if (HasStackOverflow()) return node;              \
    if (replacement_ == nullptr) return node;         \
    AstNode* result = replacement_;                   \
    replacement_ = nullptr;                           \
    return result;                                    \
  }                                                   \
                                                      \
 private:                                             \
  void InitializeAstRewriter(Isolate* isolate) {      \
    InitializeAstVisitor(isolate);                    \
    replacement_ = nullptr;                           \
  }                                                   \
                                                      \
  void InitializeAstRewriter(uintptr_t stack_limit) { \
    InitializeAstVisitor(stack_limit);                \
    replacement_ = nullptr;                           \
  }                                                   \
                                                      \
  DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();              \
                                                      \
 protected:                                           \
  AstNode* replacement_

// Generic macro for rewriting things; `GET` is the expression to be
// rewritten; `SET` is a command that should do the rewriting, i.e.
// something sensible with the variable called `replacement`.
#define AST_REWRITE(Type, GET, SET)                            \
  do {                                                         \
    DCHECK(!HasStackOverflow());                               \
    DCHECK_NULL(replacement_);                                 \
    Visit(GET);                                                \
    if (HasStackOverflow()) return;                            \
    if (replacement_ == nullptr) break;                        \
    Type* replacement = reinterpret_cast<Type*>(replacement_); \
    do {                                                       \
      SET;                                                     \
    } while (false);                                           \
    replacement_ = nullptr;                                    \
  } while (false)

// Macro for rewriting object properties; it assumes that `object` has
// `property` with a public getter and setter.
#define AST_REWRITE_PROPERTY(Type, object, property)                        \
  do {                                                                      \
    auto _obj = (object);                                                   \
    AST_REWRITE(Type, _obj->property(), _obj->set_##property(replacement)); \
  } while (false)

// Macro for rewriting list elements; it assumes that `list` has methods
// `at` and `Set`.
#define AST_REWRITE_LIST_ELEMENT(Type, list, index)                        \
  do {                                                                     \
    auto _list = (list);                                                   \
    auto _index = (index);                                                 \
    AST_REWRITE(Type, _list->at(_index), _list->Set(_index, replacement)); \
  } while (false)

3048

3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072
// ----------------------------------------------------------------------------
// Traversing visitor
// - fully traverses the entire AST.

class AstTraversalVisitor : public AstVisitor {
 public:
  explicit AstTraversalVisitor(Isolate* isolate);
  virtual ~AstTraversalVisitor() {}

  // Iteration left-to-right.
  void VisitDeclarations(ZoneList<Declaration*>* declarations) override;
  void VisitStatements(ZoneList<Statement*>* statements) override;
  void VisitExpressions(ZoneList<Expression*>* expressions) override;

// Individual nodes
#define DECLARE_VISIT(type) void Visit##type(type* node) override;
  AST_NODE_LIST(DECLARE_VISIT)
#undef DECLARE_VISIT

 private:
  DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
  DISALLOW_COPY_AND_ASSIGN(AstTraversalVisitor);
};

3073 3074 3075
// ----------------------------------------------------------------------------
// AstNode factory

3076
class AstNodeFactory final BASE_EMBEDDED {
3077
 public:
3078
  explicit AstNodeFactory(AstValueFactory* ast_value_factory)
3079 3080
      : local_zone_(ast_value_factory->zone()),
        parser_zone_(ast_value_factory->zone()),
3081
        ast_value_factory_(ast_value_factory) {}
3082

neis's avatar
neis committed
3083 3084
  AstValueFactory* ast_value_factory() const { return ast_value_factory_; }

3085 3086 3087
  VariableDeclaration* NewVariableDeclaration(VariableProxy* proxy,
                                              VariableMode mode, Scope* scope,
                                              int pos) {
3088
    return new (parser_zone_)
3089
        VariableDeclaration(parser_zone_, proxy, mode, scope, pos);
3090 3091
  }

3092 3093 3094
  FunctionDeclaration* NewFunctionDeclaration(VariableProxy* proxy,
                                              VariableMode mode,
                                              FunctionLiteral* fun,
3095 3096
                                              Scope* scope,
                                              int pos) {
3097 3098
    return new (parser_zone_)
        FunctionDeclaration(parser_zone_, proxy, mode, fun, scope, pos);
3099 3100
  }

3101
  ImportDeclaration* NewImportDeclaration(VariableProxy* proxy,
3102 3103 3104
                                          const AstRawString* import_name,
                                          const AstRawString* module_specifier,
                                          Scope* scope, int pos) {
3105 3106
    return new (parser_zone_) ImportDeclaration(
        parser_zone_, proxy, import_name, module_specifier, scope, pos);
3107 3108 3109
  }

  ExportDeclaration* NewExportDeclaration(VariableProxy* proxy,
3110 3111
                                          Scope* scope,
                                          int pos) {
3112 3113
    return new (parser_zone_)
        ExportDeclaration(parser_zone_, proxy, scope, pos);
3114 3115
  }

3116 3117
  Block* NewBlock(ZoneList<const AstRawString*>* labels, int capacity,
                  bool ignore_completion_value, int pos) {
3118 3119
    return new (local_zone_)
        Block(local_zone_, labels, capacity, ignore_completion_value, pos);
3120 3121
  }

3122
#define STATEMENT_WITH_LABELS(NodeType)                                     \
3123
  NodeType* New##NodeType(ZoneList<const AstRawString*>* labels, int pos) { \
3124
    return new (local_zone_) NodeType(local_zone_, labels, pos);            \
3125 3126 3127 3128 3129 3130 3131
  }
  STATEMENT_WITH_LABELS(DoWhileStatement)
  STATEMENT_WITH_LABELS(WhileStatement)
  STATEMENT_WITH_LABELS(ForStatement)
  STATEMENT_WITH_LABELS(SwitchStatement)
#undef STATEMENT_WITH_LABELS

3132
  ForEachStatement* NewForEachStatement(ForEachStatement::VisitMode visit_mode,
3133
                                        ZoneList<const AstRawString*>* labels,
3134
                                        int pos) {
3135 3136
    switch (visit_mode) {
      case ForEachStatement::ENUMERATE: {
3137
        return new (local_zone_) ForInStatement(local_zone_, labels, pos);
3138 3139
      }
      case ForEachStatement::ITERATE: {
3140
        return new (local_zone_) ForOfStatement(local_zone_, labels, pos);
3141 3142 3143 3144 3145 3146
      }
    }
    UNREACHABLE();
    return NULL;
  }

3147
  ExpressionStatement* NewExpressionStatement(Expression* expression, int pos) {
3148
    return new (local_zone_) ExpressionStatement(local_zone_, expression, pos);
3149 3150
  }

3151
  ContinueStatement* NewContinueStatement(IterationStatement* target, int pos) {
3152
    return new (local_zone_) ContinueStatement(local_zone_, target, pos);
3153 3154
  }

3155
  BreakStatement* NewBreakStatement(BreakableStatement* target, int pos) {
3156
    return new (local_zone_) BreakStatement(local_zone_, target, pos);
3157 3158
  }

3159
  ReturnStatement* NewReturnStatement(Expression* expression, int pos) {
3160
    return new (local_zone_) ReturnStatement(local_zone_, expression, pos);
3161 3162
  }

3163 3164
  WithStatement* NewWithStatement(Scope* scope,
                                  Expression* expression,
3165 3166
                                  Statement* statement,
                                  int pos) {
3167 3168
    return new (local_zone_)
        WithStatement(local_zone_, scope, expression, statement, pos);
3169 3170 3171 3172
  }

  IfStatement* NewIfStatement(Expression* condition,
                              Statement* then_statement,
3173 3174
                              Statement* else_statement,
                              int pos) {
3175 3176
    return new (local_zone_) IfStatement(local_zone_, condition, then_statement,
                                         else_statement, pos);
3177 3178
  }

3179
  TryCatchStatement* NewTryCatchStatement(Block* try_block, Scope* scope,
3180
                                          Variable* variable,
3181
                                          Block* catch_block, int pos) {
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192
    return new (local_zone_) TryCatchStatement(
        local_zone_, try_block, scope, variable, catch_block, true, pos);
  }

  TryCatchStatement* NewTryCatchStatementForReThrow(Block* try_block,
                                                    Scope* scope,
                                                    Variable* variable,
                                                    Block* catch_block,
                                                    int pos) {
    return new (local_zone_) TryCatchStatement(
        local_zone_, try_block, scope, variable, catch_block, false, pos);
3193 3194
  }

3195 3196
  TryFinallyStatement* NewTryFinallyStatement(Block* try_block,
                                              Block* finally_block, int pos) {
3197 3198
    return new (local_zone_)
        TryFinallyStatement(local_zone_, try_block, finally_block, pos);
3199 3200
  }

3201
  DebuggerStatement* NewDebuggerStatement(int pos) {
3202
    return new (local_zone_) DebuggerStatement(local_zone_, pos);
3203 3204
  }

3205
  EmptyStatement* NewEmptyStatement(int pos) {
3206
    return new (local_zone_) EmptyStatement(local_zone_, pos);
3207 3208
  }

3209 3210
  SloppyBlockFunctionStatement* NewSloppyBlockFunctionStatement(
      Statement* statement, Scope* scope) {
3211 3212
    return new (parser_zone_)
        SloppyBlockFunctionStatement(parser_zone_, statement, scope);
3213 3214
  }

3215 3216
  CaseClause* NewCaseClause(
      Expression* label, ZoneList<Statement*>* statements, int pos) {
3217
    return new (local_zone_) CaseClause(local_zone_, label, statements, pos);
3218 3219
  }

3220
  Literal* NewStringLiteral(const AstRawString* string, int pos) {
3221 3222
    return new (local_zone_)
        Literal(local_zone_, ast_value_factory_->NewString(string), pos);
3223 3224 3225 3226
  }

  // A JavaScript symbol (ECMA-262 edition 6).
  Literal* NewSymbolLiteral(const char* name, int pos) {
3227 3228
    return new (local_zone_)
        Literal(local_zone_, ast_value_factory_->NewSymbol(name), pos);
3229 3230
  }

3231
  Literal* NewNumberLiteral(double number, int pos, bool with_dot = false) {
3232 3233
    return new (local_zone_) Literal(
        local_zone_, ast_value_factory_->NewNumber(number, with_dot), pos);
3234 3235 3236
  }

  Literal* NewSmiLiteral(int number, int pos) {
3237 3238
    return new (local_zone_)
        Literal(local_zone_, ast_value_factory_->NewSmi(number), pos);
3239 3240 3241
  }

  Literal* NewBooleanLiteral(bool b, int pos) {
3242 3243
    return new (local_zone_)
        Literal(local_zone_, ast_value_factory_->NewBoolean(b), pos);
3244 3245 3246
  }

  Literal* NewNullLiteral(int pos) {
3247 3248
    return new (local_zone_)
        Literal(local_zone_, ast_value_factory_->NewNull(), pos);
3249 3250 3251
  }

  Literal* NewUndefinedLiteral(int pos) {
3252 3253
    return new (local_zone_)
        Literal(local_zone_, ast_value_factory_->NewUndefined(), pos);
3254 3255 3256
  }

  Literal* NewTheHoleLiteral(int pos) {
3257 3258
    return new (local_zone_)
        Literal(local_zone_, ast_value_factory_->NewTheHole(), pos);
3259 3260 3261 3262 3263
  }

  ObjectLiteral* NewObjectLiteral(
      ZoneList<ObjectLiteral::Property*>* properties,
      int literal_index,
3264
      int boilerplate_properties,
3265
      int pos) {
3266 3267
    return new (local_zone_) ObjectLiteral(
        local_zone_, properties, literal_index, boilerplate_properties, pos);
3268 3269
  }

3270 3271 3272
  ObjectLiteral::Property* NewObjectLiteralProperty(
      Expression* key, Expression* value, ObjectLiteralProperty::Kind kind,
      bool is_static, bool is_computed_name) {
3273
    return new (local_zone_)
3274 3275 3276
        ObjectLiteral::Property(key, value, kind, is_static, is_computed_name);
  }

arv's avatar
arv committed
3277
  ObjectLiteral::Property* NewObjectLiteralProperty(Expression* key,
arv@chromium.org's avatar
arv@chromium.org committed
3278
                                                    Expression* value,
arv's avatar
arv committed
3279 3280
                                                    bool is_static,
                                                    bool is_computed_name) {
3281 3282
    return new (local_zone_) ObjectLiteral::Property(
        ast_value_factory_, key, value, is_static, is_computed_name);
3283 3284
  }

3285
  RegExpLiteral* NewRegExpLiteral(const AstRawString* pattern, int flags,
3286 3287 3288
                                  int literal_index, int pos) {
    return new (local_zone_)
        RegExpLiteral(local_zone_, pattern, flags, literal_index, pos);
3289 3290
  }

3291
  ArrayLiteral* NewArrayLiteral(ZoneList<Expression*>* values,
3292
                                int literal_index,
3293
                                int pos) {
3294
    return new (local_zone_)
3295
        ArrayLiteral(local_zone_, values, -1, literal_index, pos);
3296 3297 3298 3299
  }

  ArrayLiteral* NewArrayLiteral(ZoneList<Expression*>* values,
                                int first_spread_index, int literal_index,
3300
                                int pos) {
3301
    return new (local_zone_) ArrayLiteral(
3302
        local_zone_, values, first_spread_index, literal_index, pos);
3303 3304
  }

3305
  VariableProxy* NewVariableProxy(Variable* var,
3306 3307
                                  int start_position = RelocInfo::kNoPosition,
                                  int end_position = RelocInfo::kNoPosition) {
3308 3309
    return new (parser_zone_)
        VariableProxy(parser_zone_, var, start_position, end_position);
3310 3311
  }

3312 3313
  VariableProxy* NewVariableProxy(const AstRawString* name,
                                  Variable::Kind variable_kind,
3314 3315
                                  int start_position = RelocInfo::kNoPosition,
                                  int end_position = RelocInfo::kNoPosition) {
3316
    DCHECK_NOT_NULL(name);
3317 3318
    return new (parser_zone_) VariableProxy(parser_zone_, name, variable_kind,
                                            start_position, end_position);
3319 3320 3321
  }

  Property* NewProperty(Expression* obj, Expression* key, int pos) {
3322
    return new (local_zone_) Property(local_zone_, obj, key, pos);
3323 3324 3325 3326 3327
  }

  Call* NewCall(Expression* expression,
                ZoneList<Expression*>* arguments,
                int pos) {
3328
    return new (local_zone_) Call(local_zone_, expression, arguments, pos);
3329 3330 3331 3332 3333
  }

  CallNew* NewCallNew(Expression* expression,
                      ZoneList<Expression*>* arguments,
                      int pos) {
3334
    return new (local_zone_) CallNew(local_zone_, expression, arguments, pos);
3335 3336
  }

3337 3338
  CallRuntime* NewCallRuntime(Runtime::FunctionId id,
                              ZoneList<Expression*>* arguments, int pos) {
3339 3340
    return new (local_zone_)
        CallRuntime(local_zone_, Runtime::FunctionForId(id), arguments, pos);
3341 3342 3343 3344
  }

  CallRuntime* NewCallRuntime(const Runtime::Function* function,
                              ZoneList<Expression*>* arguments, int pos) {
3345
    return new (local_zone_) CallRuntime(local_zone_, function, arguments, pos);
3346 3347 3348 3349
  }

  CallRuntime* NewCallRuntime(int context_index,
                              ZoneList<Expression*>* arguments, int pos) {
3350 3351
    return new (local_zone_)
        CallRuntime(local_zone_, context_index, arguments, pos);
3352 3353 3354 3355 3356
  }

  UnaryOperation* NewUnaryOperation(Token::Value op,
                                    Expression* expression,
                                    int pos) {
3357
    return new (local_zone_) UnaryOperation(local_zone_, op, expression, pos);
3358 3359 3360 3361 3362 3363
  }

  BinaryOperation* NewBinaryOperation(Token::Value op,
                                      Expression* left,
                                      Expression* right,
                                      int pos) {
3364
    return new (local_zone_) BinaryOperation(local_zone_, op, left, right, pos);
3365 3366 3367 3368 3369 3370
  }

  CountOperation* NewCountOperation(Token::Value op,
                                    bool is_prefix,
                                    Expression* expr,
                                    int pos) {
3371 3372
    return new (local_zone_)
        CountOperation(local_zone_, op, is_prefix, expr, pos);
3373 3374 3375 3376 3377 3378
  }

  CompareOperation* NewCompareOperation(Token::Value op,
                                        Expression* left,
                                        Expression* right,
                                        int pos) {
3379 3380
    return new (local_zone_)
        CompareOperation(local_zone_, op, left, right, pos);
3381 3382
  }

nikolaos's avatar
nikolaos committed
3383 3384
  Spread* NewSpread(Expression* expression, int pos, int expr_pos) {
    return new (local_zone_) Spread(local_zone_, expression, pos, expr_pos);
3385 3386
  }

3387 3388 3389
  Conditional* NewConditional(Expression* condition,
                              Expression* then_expression,
                              Expression* else_expression,
3390
                              int position) {
3391 3392
    return new (local_zone_) Conditional(
        local_zone_, condition, then_expression, else_expression, position);
3393 3394
  }

3395
  RewritableExpression* NewRewritableExpression(Expression* expression) {
3396
    DCHECK_NOT_NULL(expression);
3397
    return new (local_zone_) RewritableExpression(local_zone_, expression);
3398 3399
  }

3400 3401 3402 3403
  Assignment* NewAssignment(Token::Value op,
                            Expression* target,
                            Expression* value,
                            int pos) {
3404
    DCHECK(Token::IsAssignmentOp(op));
3405 3406
    Assignment* assign =
        new (local_zone_) Assignment(local_zone_, op, target, value, pos);
3407 3408 3409 3410 3411 3412
    if (assign->is_compound()) {
      DCHECK(Token::IsAssignmentOp(op));
      assign->binary_operation_ =
          NewBinaryOperation(assign->binary_op(), target, value, pos + 1);
    }
    return assign;
3413 3414
  }

3415 3416 3417
  Yield* NewYield(Expression *generator_object,
                  Expression* expression,
                  int pos) {
3418
    if (!expression) expression = NewUndefinedLiteral(pos);
3419
    return new (local_zone_)
3420
        Yield(local_zone_, generator_object, expression, pos);
3421 3422
  }

3423
  Throw* NewThrow(Expression* exception, int pos) {
3424
    return new (local_zone_) Throw(local_zone_, exception, pos);
3425 3426 3427
  }

  FunctionLiteral* NewFunctionLiteral(
3428 3429 3430
      const AstRawString* name, Scope* scope, ZoneList<Statement*>* body,
      int materialized_literal_count, int expected_property_count,
      int parameter_count,
3431
      FunctionLiteral::ParameterFlag has_duplicate_parameters,
3432
      FunctionLiteral::FunctionType function_type,
3433
      FunctionLiteral::EagerCompileHint eager_compile_hint, FunctionKind kind,
3434
      int position) {
3435
    return new (parser_zone_) FunctionLiteral(
3436
        parser_zone_, name, ast_value_factory_, scope, body,
3437
        materialized_literal_count, expected_property_count, parameter_count,
3438
        function_type, has_duplicate_parameters, eager_compile_hint, kind,
3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
        position, true);
  }

  // Creates a FunctionLiteral representing a top-level script, the
  // result of an eval (top-level or otherwise), or the result of calling
  // the Function constructor.
  FunctionLiteral* NewScriptOrEvalFunctionLiteral(
      Scope* scope, ZoneList<Statement*>* body, int materialized_literal_count,
      int expected_property_count) {
    return new (parser_zone_) FunctionLiteral(
        parser_zone_, ast_value_factory_->empty_string(), ast_value_factory_,
        scope, body, materialized_literal_count, expected_property_count, 0,
        FunctionLiteral::kAnonymousExpression,
        FunctionLiteral::kNoDuplicateParameters,
        FunctionLiteral::kShouldLazyCompile, FunctionKind::kNormalFunction, 0,
        false);
3455 3456
  }

3457 3458
  ClassLiteral* NewClassLiteral(Scope* scope, VariableProxy* proxy,
                                Expression* extends,
3459
                                FunctionLiteral* constructor,
arv@chromium.org's avatar
arv@chromium.org committed
3460
                                ZoneList<ObjectLiteral::Property*>* properties,
3461
                                int start_position, int end_position) {
3462
    return new (parser_zone_)
3463
        ClassLiteral(parser_zone_, scope, proxy, extends, constructor,
3464
                     properties, start_position, end_position);
arv@chromium.org's avatar
arv@chromium.org committed
3465 3466
  }

3467 3468 3469
  NativeFunctionLiteral* NewNativeFunctionLiteral(const AstRawString* name,
                                                  v8::Extension* extension,
                                                  int pos) {
3470 3471
    return new (parser_zone_)
        NativeFunctionLiteral(parser_zone_, name, extension, pos);
3472 3473
  }

3474 3475 3476 3477 3478
  DoExpression* NewDoExpression(Block* block, Variable* result_var, int pos) {
    VariableProxy* result = NewVariableProxy(result_var, pos);
    return new (parser_zone_) DoExpression(parser_zone_, block, result, pos);
  }

3479
  ThisFunction* NewThisFunction(int pos) {
3480
    return new (local_zone_) ThisFunction(local_zone_, pos);
3481 3482
  }

3483 3484 3485
  SuperPropertyReference* NewSuperPropertyReference(VariableProxy* this_var,
                                                    Expression* home_object,
                                                    int pos) {
3486 3487
    return new (parser_zone_)
        SuperPropertyReference(parser_zone_, this_var, home_object, pos);
3488 3489 3490 3491 3492 3493
  }

  SuperCallReference* NewSuperCallReference(VariableProxy* this_var,
                                            VariableProxy* new_target_var,
                                            VariableProxy* this_function_var,
                                            int pos) {
3494 3495
    return new (parser_zone_) SuperCallReference(
        parser_zone_, this_var, new_target_var, this_function_var, pos);
3496 3497
  }

3498
  EmptyParentheses* NewEmptyParentheses(int pos) {
3499
    return new (local_zone_) EmptyParentheses(local_zone_, pos);
3500 3501
  }

3502 3503 3504 3505 3506
  Zone* zone() const { return local_zone_; }

  // Handles use of temporary zones when parsing inner function bodies.
  class BodyScope {
   public:
3507
    BodyScope(AstNodeFactory* factory, Zone* temp_zone, bool use_temp_zone)
3508
        : factory_(factory), prev_zone_(factory->local_zone_) {
3509
      if (use_temp_zone) {
3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520
        factory->local_zone_ = temp_zone;
      }
    }

    ~BodyScope() { factory_->local_zone_ = prev_zone_; }

   private:
    AstNodeFactory* factory_;
    Zone* prev_zone_;
  };

3521
 private:
3522 3523 3524 3525 3526 3527 3528 3529
  // This zone may be deallocated upon returning from parsing a function body
  // which we can guarantee is not going to be compiled or have its AST
  // inspected.
  // See ParseFunctionLiteral in parser.cc for preconditions.
  Zone* local_zone_;
  // ZoneObjects which need to persist until scope analysis must be allocated in
  // the parser-level zone.
  Zone* parser_zone_;
3530
  AstValueFactory* ast_value_factory_;
3531 3532 3533
};


3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573
// Type testing & conversion functions overridden by concrete subclasses.
// Inline functions for AstNode.

#define DECLARE_NODE_FUNCTIONS(type)                                          \
  bool AstNode::Is##type() const {                                            \
    NodeType mine = node_type();                                              \
    if (mine == AstNode::kRewritableExpression &&                             \
        AstNode::k##type != AstNode::kRewritableExpression)                   \
      mine = reinterpret_cast<const RewritableExpression*>(this)              \
                 ->expression()                                               \
                 ->node_type();                                               \
    return mine == AstNode::k##type;                                          \
  }                                                                           \
  type* AstNode::As##type() {                                                 \
    NodeType mine = node_type();                                              \
    AstNode* result = this;                                                   \
    if (mine == AstNode::kRewritableExpression &&                             \
        AstNode::k##type != AstNode::kRewritableExpression) {                 \
      result =                                                                \
          reinterpret_cast<const RewritableExpression*>(this)->expression();  \
      mine = result->node_type();                                             \
    }                                                                         \
    return mine == AstNode::k##type ? reinterpret_cast<type*>(result) : NULL; \
  }                                                                           \
  const type* AstNode::As##type() const {                                     \
    NodeType mine = node_type();                                              \
    const AstNode* result = this;                                             \
    if (mine == AstNode::kRewritableExpression &&                             \
        AstNode::k##type != AstNode::kRewritableExpression) {                 \
      result =                                                                \
          reinterpret_cast<const RewritableExpression*>(this)->expression();  \
      mine = result->node_type();                                             \
    }                                                                         \
    return mine == AstNode::k##type ? reinterpret_cast<const type*>(result)   \
                                    : NULL;                                   \
  }
AST_NODE_LIST(DECLARE_NODE_FUNCTIONS)
#undef DECLARE_NODE_FUNCTIONS


3574 3575
}  // namespace internal
}  // namespace v8
3576

3577
#endif  // V8_AST_AST_H_