ast.cc 33.2 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "ast.h"
29 30 31 32 33

#include <math.h>  // For isfinite.
#include "builtins.h"
#include "conversions.h"
#include "hashmap.h"
34
#include "parser.h"
35 36
#include "property-details.h"
#include "property.h"
37
#include "scopes.h"
38
#include "string-stream.h"
39
#include "type-info.h"
40

41 42
namespace v8 {
namespace internal {
43 44 45 46

// ----------------------------------------------------------------------------
// All the Accept member functions for each syntax tree node type.

47 48
#define DECL_ACCEPT(type)                                       \
  void type::Accept(AstVisitor* v) { v->Visit##type(this); }
49
AST_NODE_LIST(DECL_ACCEPT)
50 51 52 53 54 55
#undef DECL_ACCEPT


// ----------------------------------------------------------------------------
// Implementation of other node functionality.

56 57 58 59 60 61 62 63

bool Expression::IsSmiLiteral() {
  return AsLiteral() != NULL && AsLiteral()->handle()->IsSmi();
}


bool Expression::IsStringLiteral() {
  return AsLiteral() != NULL && AsLiteral()->handle()->IsString();
64 65 66
}


67 68
bool Expression::IsNullLiteral() {
  return AsLiteral() != NULL && AsLiteral()->handle()->IsNull();
69 70 71
}


72 73 74
VariableProxy::VariableProxy(Isolate* isolate, Variable* var)
    : Expression(isolate),
      name_(var->name()),
75 76
      var_(NULL),  // Will be set by the call to BindTo.
      is_this_(var->is_this()),
77
      is_trivial_(false),
78
      is_lvalue_(false),
79 80
      position_(RelocInfo::kNoPosition),
      interface_(var->interface()) {
81 82 83 84
  BindTo(var);
}


85 86
VariableProxy::VariableProxy(Isolate* isolate,
                             Handle<String> name,
87
                             bool is_this,
88 89
                             int position,
                             Interface* interface)
90 91 92 93 94
    : Expression(isolate),
      name_(name),
      var_(NULL),
      is_this_(is_this),
      is_trivial_(false),
95
      is_lvalue_(false),
96 97
      position_(position),
      interface_(interface) {
98
  // Names must be canonicalized for fast equality checks.
99 100 101 102 103 104 105 106 107 108 109 110 111 112
  ASSERT(name->IsSymbol());
}


void VariableProxy::BindTo(Variable* var) {
  ASSERT(var_ == NULL);  // must be bound only once
  ASSERT(var != NULL);  // must bind
  ASSERT((is_this() && var->is_this()) || name_.is_identical_to(var->name()));
  // Ideally CONST-ness should match. However, this is very hard to achieve
  // because we don't know the exact semantics of conflicting (const and
  // non-const) multiple variable declarations, const vars introduced via
  // eval() etc.  Const-ness and variable declarations are a complete mess
  // in JS. Sigh...
  var_ = var;
113
  var->set_is_used(true);
114 115 116
}


117 118
Assignment::Assignment(Isolate* isolate,
                       Token::Value op,
119 120 121
                       Expression* target,
                       Expression* value,
                       int pos)
122 123
    : Expression(isolate),
      op_(op),
124 125 126
      target_(target),
      value_(value),
      pos_(pos),
127 128
      binary_operation_(NULL),
      compound_load_id_(kNoNumber),
129
      assignment_id_(GetNextId(isolate)),
130 131
      block_start_(false),
      block_end_(false),
132
      is_monomorphic_(false) { }
133 134


135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
Token::Value Assignment::binary_op() const {
  switch (op_) {
    case Token::ASSIGN_BIT_OR: return Token::BIT_OR;
    case Token::ASSIGN_BIT_XOR: return Token::BIT_XOR;
    case Token::ASSIGN_BIT_AND: return Token::BIT_AND;
    case Token::ASSIGN_SHL: return Token::SHL;
    case Token::ASSIGN_SAR: return Token::SAR;
    case Token::ASSIGN_SHR: return Token::SHR;
    case Token::ASSIGN_ADD: return Token::ADD;
    case Token::ASSIGN_SUB: return Token::SUB;
    case Token::ASSIGN_MUL: return Token::MUL;
    case Token::ASSIGN_DIV: return Token::DIV;
    case Token::ASSIGN_MOD: return Token::MOD;
    default: UNREACHABLE();
  }
  return Token::ILLEGAL;
}


bool FunctionLiteral::AllowsLazyCompilation() {
  return scope()->AllowsLazyCompilation();
}


159 160 161 162 163 164 165 166 167 168
int FunctionLiteral::start_position() const {
  return scope()->start_position();
}


int FunctionLiteral::end_position() const {
  return scope()->end_position();
}


169 170
LanguageMode FunctionLiteral::language_mode() const {
  return scope()->language_mode();
171 172 173
}


174 175 176
ObjectLiteral::Property::Property(Literal* key,
                                  Expression* value,
                                  Isolate* isolate) {
177
  emit_store_ = true;
178 179 180
  key_ = key;
  value_ = value;
  Object* k = *key->handle();
181 182
  if (k->IsSymbol() &&
      isolate->heap()->Proto_symbol()->Equals(String::cast(k))) {
183
    kind_ = PROTOTYPE;
184 185 186 187
  } else if (value_->AsMaterializedLiteral() != NULL) {
    kind_ = MATERIALIZED_LITERAL;
  } else if (value_->AsLiteral() != NULL) {
    kind_ = CONSTANT;
188
  } else {
189
    kind_ = COMPUTED;
190 191 192 193 194
  }
}


ObjectLiteral::Property::Property(bool is_getter, FunctionLiteral* value) {
195
  emit_store_ = true;
196 197 198 199 200
  value_ = value;
  kind_ = is_getter ? GETTER : SETTER;
}


201 202 203 204 205 206 207
bool ObjectLiteral::Property::IsCompileTimeValue() {
  return kind_ == CONSTANT ||
      (kind_ == MATERIALIZED_LITERAL &&
       CompileTimeValue::IsCompileTimeValue(value_));
}


208 209 210 211 212 213 214 215 216 217 218
void ObjectLiteral::Property::set_emit_store(bool emit_store) {
  emit_store_ = emit_store;
}


bool ObjectLiteral::Property::emit_store() {
  return emit_store_;
}


bool IsEqualString(void* first, void* second) {
219 220
  ASSERT((*reinterpret_cast<String**>(first))->IsString());
  ASSERT((*reinterpret_cast<String**>(second))->IsString());
221 222 223 224 225
  Handle<String> h1(reinterpret_cast<String**>(first));
  Handle<String> h2(reinterpret_cast<String**>(second));
  return (*h1)->Equals(*h2);
}

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

bool IsEqualNumber(void* first, void* second) {
  ASSERT((*reinterpret_cast<Object**>(first))->IsNumber());
  ASSERT((*reinterpret_cast<Object**>(second))->IsNumber());

  Handle<Object> h1(reinterpret_cast<Object**>(first));
  Handle<Object> h2(reinterpret_cast<Object**>(second));
  if (h1->IsSmi()) {
    return h2->IsSmi() && *h1 == *h2;
  }
  if (h2->IsSmi()) return false;
  Handle<HeapNumber> n1 = Handle<HeapNumber>::cast(h1);
  Handle<HeapNumber> n2 = Handle<HeapNumber>::cast(h2);
  ASSERT(isfinite(n1->value()));
  ASSERT(isfinite(n2->value()));
  return n1->value() == n2->value();
242 243
}

244

245
void ObjectLiteral::CalculateEmitStore() {
246 247 248
  ZoneHashMap table(Literal::Match);
  for (int i = properties()->length() - 1; i >= 0; i--) {
    ObjectLiteral::Property* property = properties()->at(i);
249
    Literal* literal = property->key();
250 251
    if (literal->handle()->IsNull()) continue;
    uint32_t hash = literal->Hash();
252 253
    // If the key of a computed property is in the table, do not emit
    // a store for the property later.
254 255 256 257 258 259
    if (property->kind() == ObjectLiteral::Property::COMPUTED &&
        table.Lookup(literal, hash, false) != NULL) {
      property->set_emit_store(false);
    } else {
      // Add key to the table.
      table.Lookup(literal, hash, true);
260 261 262 263 264
    }
  }
}


265
void TargetCollector::AddTarget(Label* target) {
266
  // Add the label to the collector, but discard duplicates.
267
  int length = targets_.length();
268
  for (int i = 0; i < length; i++) {
269
    if (targets_[i] == target) return;
270
  }
271
  targets_.Add(target);
272 273 274
}


275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
bool UnaryOperation::ResultOverwriteAllowed() {
  switch (op_) {
    case Token::BIT_NOT:
    case Token::SUB:
      return true;
    default:
      return false;
  }
}


bool BinaryOperation::ResultOverwriteAllowed() {
  switch (op_) {
    case Token::COMMA:
    case Token::OR:
    case Token::AND:
      return false;
    case Token::BIT_OR:
    case Token::BIT_XOR:
    case Token::BIT_AND:
    case Token::SHL:
    case Token::SAR:
    case Token::SHR:
    case Token::ADD:
    case Token::SUB:
    case Token::MUL:
    case Token::DIV:
    case Token::MOD:
      return true;
    default:
      UNREACHABLE();
  }
  return false;
}


311 312 313 314 315
static bool IsTypeof(Expression* expr) {
  UnaryOperation* maybe_unary = expr->AsUnaryOperation();
  return maybe_unary != NULL && maybe_unary->op() == Token::TYPEOF;
}

316

317 318 319 320 321 322 323 324 325
// Check for the pattern: typeof <expression> equals <string literal>.
static bool MatchLiteralCompareTypeof(Expression* left,
                                      Token::Value op,
                                      Expression* right,
                                      Expression** expr,
                                      Handle<String>* check) {
  if (IsTypeof(left) && right->IsStringLiteral() && Token::IsEqualityOp(op)) {
    *expr = left->AsUnaryOperation()->expression();
    *check = Handle<String>::cast(right->AsLiteral()->handle());
326 327 328 329 330 331
    return true;
  }
  return false;
}


332 333 334 335 336
bool CompareOperation::IsLiteralCompareTypeof(Expression** expr,
                                              Handle<String>* check) {
  return MatchLiteralCompareTypeof(left_, op_, right_, expr, check) ||
      MatchLiteralCompareTypeof(right_, op_, left_, expr, check);
}
337 338


339 340 341 342 343 344 345
static bool IsVoidOfLiteral(Expression* expr) {
  UnaryOperation* maybe_unary = expr->AsUnaryOperation();
  return maybe_unary != NULL &&
      maybe_unary->op() == Token::VOID &&
      maybe_unary->expression()->AsLiteral() != NULL;
}

346

347 348 349 350 351 352 353
// Check for the pattern: void <literal> equals <expression>
static bool MatchLiteralCompareUndefined(Expression* left,
                                         Token::Value op,
                                         Expression* right,
                                         Expression** expr) {
  if (IsVoidOfLiteral(left) && Token::IsEqualityOp(op)) {
    *expr = right;
354 355 356 357 358 359
    return true;
  }
  return false;
}


360 361 362 363
bool CompareOperation::IsLiteralCompareUndefined(Expression** expr) {
  return MatchLiteralCompareUndefined(left_, op_, right_, expr) ||
      MatchLiteralCompareUndefined(right_, op_, left_, expr);
}
364 365


366 367 368 369 370 371 372
// Check for the pattern: null equals <expression>
static bool MatchLiteralCompareNull(Expression* left,
                                    Token::Value op,
                                    Expression* right,
                                    Expression** expr) {
  if (left->IsNullLiteral() && Token::IsEqualityOp(op)) {
    *expr = right;
373 374 375 376 377 378
    return true;
  }
  return false;
}


379 380 381 382 383 384
bool CompareOperation::IsLiteralCompareNull(Expression** expr) {
  return MatchLiteralCompareNull(left_, op_, right_, expr) ||
      MatchLiteralCompareNull(right_, op_, left_, expr);
}


385 386 387
// ----------------------------------------------------------------------------
// Inlining support

388
bool Declaration::IsInlineable() const {
389 390 391
  return proxy()->var()->IsStackAllocated();
}

392 393
bool FunctionDeclaration::IsInlineable() const {
  return false;
394 395 396
}


397 398 399 400 401
// ----------------------------------------------------------------------------
// Recording of type feedback

void Property::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
  // Record type feedback from the oracle in the AST.
402 403 404
  is_uninitialized_ = oracle->LoadIsUninitialized(this);
  if (is_uninitialized_) return;

405
  is_monomorphic_ = oracle->LoadIsMonomorphicNormal(this);
406
  receiver_types_.Clear();
407
  if (key()->IsPropertyName()) {
408
    if (oracle->LoadIsBuiltin(this, Builtins::kLoadIC_ArrayLength)) {
409
      is_array_length_ = true;
410
    } else if (oracle->LoadIsBuiltin(this, Builtins::kLoadIC_StringLength)) {
411
      is_string_length_ = true;
412
    } else if (oracle->LoadIsBuiltin(this,
413
                                     Builtins::kLoadIC_FunctionPrototype)) {
414
      is_function_prototype_ = true;
415 416 417 418
    } else {
      Literal* lit_key = key()->AsLiteral();
      ASSERT(lit_key != NULL && lit_key->handle()->IsString());
      Handle<String> name = Handle<String>::cast(lit_key->handle());
419
      oracle->LoadReceiverTypes(this, name, &receiver_types_);
420
    }
421
  } else if (oracle->LoadIsBuiltin(this, Builtins::kKeyedLoadIC_String)) {
422
    is_string_access_ = true;
423
  } else if (is_monomorphic_) {
424
    receiver_types_.Add(oracle->LoadMonomorphicReceiverType(this));
425
  } else if (oracle->LoadIsMegamorphicWithTypeInfo(this)) {
426 427
    receiver_types_.Reserve(kMaxKeyedPolymorphism);
    oracle->CollectKeyedReceiverTypes(this->id(), &receiver_types_);
428 429 430 431 432 433 434
  }
}


void Assignment::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
  Property* prop = target()->AsProperty();
  ASSERT(prop != NULL);
435
  is_monomorphic_ = oracle->StoreIsMonomorphicNormal(this);
436
  receiver_types_.Clear();
437 438 439 440
  if (prop->key()->IsPropertyName()) {
    Literal* lit_key = prop->key()->AsLiteral();
    ASSERT(lit_key != NULL && lit_key->handle()->IsString());
    Handle<String> name = Handle<String>::cast(lit_key->handle());
441
    oracle->StoreReceiverTypes(this, name, &receiver_types_);
442
  } else if (is_monomorphic_) {
443
    // Record receiver type for monomorphic keyed stores.
444
    receiver_types_.Add(oracle->StoreMonomorphicReceiverType(this));
445
  } else if (oracle->StoreIsMegamorphicWithTypeInfo(this)) {
446 447
    receiver_types_.Reserve(kMaxKeyedPolymorphism);
    oracle->CollectKeyedReceiverTypes(this->id(), &receiver_types_);
448 449 450 451 452
  }
}


void CountOperation::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
453
  is_monomorphic_ = oracle->StoreIsMonomorphicNormal(this);
454
  receiver_types_.Clear();
455
  if (is_monomorphic_) {
456
    // Record receiver type for monomorphic keyed stores.
457
    receiver_types_.Add(oracle->StoreMonomorphicReceiverType(this));
458
  } else if (oracle->StoreIsMegamorphicWithTypeInfo(this)) {
459 460
    receiver_types_.Reserve(kMaxKeyedPolymorphism);
    oracle->CollectKeyedReceiverTypes(this->id(), &receiver_types_);
461 462 463 464 465 466 467 468
  }
}


void CaseClause::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
  TypeInfo info = oracle->SwitchType(this);
  if (info.IsSmi()) {
    compare_type_ = SMI_ONLY;
469 470 471 472
  } else if (info.IsSymbol()) {
    compare_type_ = SYMBOL_ONLY;
  } else if (info.IsNonSymbol()) {
    compare_type_ = STRING_ONLY;
473 474 475 476 477 478 479 480 481
  } else if (info.IsNonPrimitive()) {
    compare_type_ = OBJECT_ONLY;
  } else {
    ASSERT(compare_type_ == NONE);
  }
}


bool Call::ComputeTarget(Handle<Map> type, Handle<String> name) {
482
  // If there is an interceptor, we can't compute the target for a direct call.
483 484
  if (type->has_named_interceptor()) return false;

485
  if (check_type_ == RECEIVER_MAP_CHECK) {
486 487 488 489
    // For primitive checks the holder is set up to point to the corresponding
    // prototype object, i.e. one step of the algorithm below has been already
    // performed. For non-primitive checks we clear it to allow computing
    // targets for polymorphic calls.
490 491
    holder_ = Handle<JSObject>::null();
  }
492
  LookupResult lookup(type->GetIsolate());
493 494
  while (true) {
    type->LookupInDescriptors(NULL, *name, &lookup);
495 496 497 498
    if (lookup.IsFound()) {
      switch (lookup.type()) {
        case CONSTANT_FUNCTION:
          // We surely know the target for a constant function.
499 500
          target_ =
              Handle<JSFunction>(lookup.GetConstantFunctionFromMap(*type));
501 502 503 504 505 506 507 508 509 510 511 512 513 514
          return true;
        case NORMAL:
        case FIELD:
        case CALLBACKS:
        case HANDLER:
        case INTERCEPTOR:
          // We don't know the target.
          return false;
        case MAP_TRANSITION:
        case ELEMENTS_TRANSITION:
        case CONSTANT_TRANSITION:
        case NULL_DESCRIPTOR:
          // Perhaps something interesting is up in the prototype chain...
          break;
515
      }
516
    }
517 518 519 520 521
    // If we reach the end of the prototype chain, we don't know the target.
    if (!type->prototype()->IsJSObject()) return false;
    // Go up the prototype chain, recording where we are currently.
    holder_ = Handle<JSObject>(JSObject::cast(type->prototype()));
    type = Handle<Map>(holder()->map());
522 523 524 525 526
  }
}


bool Call::ComputeGlobalTarget(Handle<GlobalObject> global,
527
                               LookupResult* lookup) {
528 529
  target_ = Handle<JSFunction>::null();
  cell_ = Handle<JSGlobalPropertyCell>::null();
530
  ASSERT(lookup->IsFound() &&
531 532 533 534 535 536 537
         lookup->type() == NORMAL &&
         lookup->holder() == *global);
  cell_ = Handle<JSGlobalPropertyCell>(global->GetPropertyCell(lookup));
  if (cell_->value()->IsJSFunction()) {
    Handle<JSFunction> candidate(JSFunction::cast(cell_->value()));
    // If the function is in new space we assume it's more likely to
    // change and thus prefer the general IC code.
538
    if (!HEAP->InNewSpace(*candidate)) {
539 540
      target_ = candidate;
      return true;
541 542 543 544 545 546
    }
  }
  return false;
}


547 548
void Call::RecordTypeFeedback(TypeFeedbackOracle* oracle,
                              CallKind call_kind) {
549
  is_monomorphic_ = oracle->CallIsMonomorphic(this);
550
  Property* property = expression()->AsProperty();
551 552 553 554 555 556 557 558 559 560
  if (property == NULL) {
    // Function call.  Specialize for monomorphic calls.
    if (is_monomorphic_) target_ = oracle->GetCallTarget(this);
  } else {
    // Method call.  Specialize for the receiver types seen at runtime.
    Literal* key = property->key()->AsLiteral();
    ASSERT(key != NULL && key->handle()->IsString());
    Handle<String> name = Handle<String>::cast(key->handle());
    receiver_types_.Clear();
    oracle->CallReceiverTypes(this, name, call_kind, &receiver_types_);
561
#ifdef DEBUG
562 563 564 565 566 567
    if (FLAG_enable_slow_asserts) {
      int length = receiver_types_.length();
      for (int i = 0; i < length; i++) {
        Handle<Map> map = receiver_types_.at(i);
        ASSERT(!map.is_null() && *map != NULL);
      }
568 569
    }
#endif
570 571 572 573 574 575 576 577 578 579 580 581 582
    check_type_ = oracle->GetCallCheckType(this);
    if (is_monomorphic_) {
      Handle<Map> map;
      if (receiver_types_.length() > 0) {
        ASSERT(check_type_ == RECEIVER_MAP_CHECK);
        map = receiver_types_.at(0);
      } else {
        ASSERT(check_type_ != RECEIVER_MAP_CHECK);
        holder_ = Handle<JSObject>(
            oracle->GetPrototypeForPrimitiveCheck(check_type_));
        map = Handle<Map>(holder_->map());
      }
      is_monomorphic_ = ComputeTarget(map, name);
583
    }
584 585 586 587
  }
}


588 589 590 591 592 593 594 595
void CallNew::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
  is_monomorphic_ = oracle->CallNewIsMonomorphic(this);
  if (is_monomorphic_) {
    target_ = oracle->GetCallNewTarget(this);
  }
}


596
void CompareOperation::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
597 598
  TypeInfo info = oracle->CompareType(this);
  if (info.IsSmi()) {
599
    compare_type_ = SMI_ONLY;
600
  } else if (info.IsNonPrimitive()) {
601 602 603 604 605 606 607
    compare_type_ = OBJECT_ONLY;
  } else {
    ASSERT(compare_type_ == NONE);
  }
}


608 609 610 611 612 613 614
void ObjectLiteral::Property::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
  receiver_type_ = oracle->ObjectLiteralStoreIsMonomorphic(this)
      ? oracle->GetObjectLiteralStoreMap(this)
      : Handle<Map>::null();
}


615
// ----------------------------------------------------------------------------
616
// Implementation of AstVisitor
617

618 619
bool AstVisitor::CheckStackOverflow() {
  if (stack_overflow_) return true;
620
  StackLimitCheck check(isolate_);
621 622 623 624
  if (!check.HasOverflowed()) return false;
  return (stack_overflow_ = true);
}

625

626 627 628 629 630 631 632
void AstVisitor::VisitDeclarations(ZoneList<Declaration*>* declarations) {
  for (int i = 0; i < declarations->length(); i++) {
    Visit(declarations->at(i));
  }
}


633
void AstVisitor::VisitStatements(ZoneList<Statement*>* statements) {
634 635 636 637 638 639
  for (int i = 0; i < statements->length(); i++) {
    Visit(statements->at(i));
  }
}


640
void AstVisitor::VisitExpressions(ZoneList<Expression*>* expressions) {
641 642 643 644 645 646 647 648 649 650 651
  for (int i = 0; i < expressions->length(); i++) {
    // The variable statement visiting code may pass NULL expressions
    // to this code. Maybe this should be handled by introducing an
    // undefined expression or literal?  Revisit this code if this
    // changes
    Expression* expression = expressions->at(i);
    if (expression != NULL) Visit(expression);
  }
}


652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
// ----------------------------------------------------------------------------
// Regular expressions

#define MAKE_ACCEPT(Name)                                            \
  void* RegExp##Name::Accept(RegExpVisitor* visitor, void* data) {   \
    return visitor->Visit##Name(this, data);                         \
  }
FOR_EACH_REG_EXP_TREE_TYPE(MAKE_ACCEPT)
#undef MAKE_ACCEPT

#define MAKE_TYPE_CASE(Name)                                         \
  RegExp##Name* RegExpTree::As##Name() {                             \
    return NULL;                                                     \
  }                                                                  \
  bool RegExpTree::Is##Name() { return false; }
667
FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE)
668 669 670 671 672 673 674 675 676 677 678
#undef MAKE_TYPE_CASE

#define MAKE_TYPE_CASE(Name)                                        \
  RegExp##Name* RegExp##Name::As##Name() {                          \
    return this;                                                    \
  }                                                                 \
  bool RegExp##Name::Is##Name() { return true; }
FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE)
#undef MAKE_TYPE_CASE


679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
static Interval ListCaptureRegisters(ZoneList<RegExpTree*>* children) {
  Interval result = Interval::Empty();
  for (int i = 0; i < children->length(); i++)
    result = result.Union(children->at(i)->CaptureRegisters());
  return result;
}


Interval RegExpAlternative::CaptureRegisters() {
  return ListCaptureRegisters(nodes());
}


Interval RegExpDisjunction::CaptureRegisters() {
  return ListCaptureRegisters(alternatives());
}


Interval RegExpLookahead::CaptureRegisters() {
  return body()->CaptureRegisters();
}


Interval RegExpCapture::CaptureRegisters() {
  Interval self(StartRegister(index()), EndRegister(index()));
  return self.Union(body()->CaptureRegisters());
}


Interval RegExpQuantifier::CaptureRegisters() {
  return body()->CaptureRegisters();
}


713
bool RegExpAssertion::IsAnchoredAtStart() {
714 715 716 717
  return type() == RegExpAssertion::START_OF_INPUT;
}


718 719 720 721 722 723
bool RegExpAssertion::IsAnchoredAtEnd() {
  return type() == RegExpAssertion::END_OF_INPUT;
}


bool RegExpAlternative::IsAnchoredAtStart() {
724 725 726
  ZoneList<RegExpTree*>* nodes = this->nodes();
  for (int i = 0; i < nodes->length(); i++) {
    RegExpTree* node = nodes->at(i);
727 728 729 730 731 732 733 734 735 736 737 738
    if (node->IsAnchoredAtStart()) { return true; }
    if (node->max_match() > 0) { return false; }
  }
  return false;
}


bool RegExpAlternative::IsAnchoredAtEnd() {
  ZoneList<RegExpTree*>* nodes = this->nodes();
  for (int i = nodes->length() - 1; i >= 0; i--) {
    RegExpTree* node = nodes->at(i);
    if (node->IsAnchoredAtEnd()) { return true; }
739 740 741
    if (node->max_match() > 0) { return false; }
  }
  return false;
742 743 744
}


745
bool RegExpDisjunction::IsAnchoredAtStart() {
746 747
  ZoneList<RegExpTree*>* alternatives = this->alternatives();
  for (int i = 0; i < alternatives->length(); i++) {
748
    if (!alternatives->at(i)->IsAnchoredAtStart())
749 750 751 752 753 754
      return false;
  }
  return true;
}


755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
bool RegExpDisjunction::IsAnchoredAtEnd() {
  ZoneList<RegExpTree*>* alternatives = this->alternatives();
  for (int i = 0; i < alternatives->length(); i++) {
    if (!alternatives->at(i)->IsAnchoredAtEnd())
      return false;
  }
  return true;
}


bool RegExpLookahead::IsAnchoredAtStart() {
  return is_positive() && body()->IsAnchoredAtStart();
}


bool RegExpCapture::IsAnchoredAtStart() {
  return body()->IsAnchoredAtStart();
772 773 774
}


775 776
bool RegExpCapture::IsAnchoredAtEnd() {
  return body()->IsAnchoredAtEnd();
777 778 779
}


780 781 782 783 784 785 786 787 788
// Convert regular expression trees to a simple sexp representation.
// This representation should be different from the input grammar
// in as many cases as possible, to make it more difficult for incorrect
// parses to look as correct ones which is likely if the input and
// output formats are alike.
class RegExpUnparser: public RegExpVisitor {
 public:
  RegExpUnparser();
  void VisitCharacterRange(CharacterRange that);
789
  SmartArrayPointer<const char> ToString() { return stream_.ToCString(); }
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
#define MAKE_CASE(Name) virtual void* Visit##Name(RegExp##Name*, void* data);
  FOR_EACH_REG_EXP_TREE_TYPE(MAKE_CASE)
#undef MAKE_CASE
 private:
  StringStream* stream() { return &stream_; }
  HeapStringAllocator alloc_;
  StringStream stream_;
};


RegExpUnparser::RegExpUnparser() : stream_(&alloc_) {
}


void* RegExpUnparser::VisitDisjunction(RegExpDisjunction* that, void* data) {
  stream()->Add("(|");
  for (int i = 0; i <  that->alternatives()->length(); i++) {
    stream()->Add(" ");
    that->alternatives()->at(i)->Accept(this, data);
  }
  stream()->Add(")");
  return NULL;
}


void* RegExpUnparser::VisitAlternative(RegExpAlternative* that, void* data) {
  stream()->Add("(:");
  for (int i = 0; i <  that->nodes()->length(); i++) {
    stream()->Add(" ");
    that->nodes()->at(i)->Accept(this, data);
  }
  stream()->Add(")");
  return NULL;
}


void RegExpUnparser::VisitCharacterRange(CharacterRange that) {
  stream()->Add("%k", that.from());
  if (!that.IsSingleton()) {
    stream()->Add("-%k", that.to());
  }
}



void* RegExpUnparser::VisitCharacterClass(RegExpCharacterClass* that,
                                          void* data) {
  if (that->is_negated())
    stream()->Add("^");
  stream()->Add("[");
  for (int i = 0; i < that->ranges()->length(); i++) {
    if (i > 0) stream()->Add(" ");
    VisitCharacterRange(that->ranges()->at(i));
  }
  stream()->Add("]");
  return NULL;
}


void* RegExpUnparser::VisitAssertion(RegExpAssertion* that, void* data) {
  switch (that->type()) {
    case RegExpAssertion::START_OF_INPUT:
      stream()->Add("@^i");
      break;
    case RegExpAssertion::END_OF_INPUT:
      stream()->Add("@$i");
      break;
    case RegExpAssertion::START_OF_LINE:
      stream()->Add("@^l");
      break;
    case RegExpAssertion::END_OF_LINE:
      stream()->Add("@$l");
       break;
    case RegExpAssertion::BOUNDARY:
      stream()->Add("@b");
      break;
    case RegExpAssertion::NON_BOUNDARY:
      stream()->Add("@B");
      break;
  }
  return NULL;
}


void* RegExpUnparser::VisitAtom(RegExpAtom* that, void* data) {
  stream()->Add("'");
  Vector<const uc16> chardata = that->data();
  for (int i = 0; i < chardata.length(); i++) {
    stream()->Add("%k", chardata[i]);
  }
  stream()->Add("'");
  return NULL;
}


void* RegExpUnparser::VisitText(RegExpText* that, void* data) {
  if (that->elements()->length() == 1) {
    that->elements()->at(0).data.u_atom->Accept(this, data);
  } else {
    stream()->Add("(!");
    for (int i = 0; i < that->elements()->length(); i++) {
      stream()->Add(" ");
      that->elements()->at(i).data.u_atom->Accept(this, data);
    }
    stream()->Add(")");
  }
  return NULL;
}


void* RegExpUnparser::VisitQuantifier(RegExpQuantifier* that, void* data) {
  stream()->Add("(# %i ", that->min());
902
  if (that->max() == RegExpTree::kInfinity) {
903 904 905 906
    stream()->Add("- ");
  } else {
    stream()->Add("%i ", that->max());
  }
907
  stream()->Add(that->is_greedy() ? "g " : that->is_possessive() ? "p " : "n ");
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
  that->body()->Accept(this, data);
  stream()->Add(")");
  return NULL;
}


void* RegExpUnparser::VisitCapture(RegExpCapture* that, void* data) {
  stream()->Add("(^ ");
  that->body()->Accept(this, data);
  stream()->Add(")");
  return NULL;
}


void* RegExpUnparser::VisitLookahead(RegExpLookahead* that, void* data) {
  stream()->Add("(-> ");
  stream()->Add(that->is_positive() ? "+ " : "- ");
  that->body()->Accept(this, data);
  stream()->Add(")");
  return NULL;
}


void* RegExpUnparser::VisitBackReference(RegExpBackReference* that,
                                         void* data) {
  stream()->Add("(<- %i)", that->index());
  return NULL;
}


void* RegExpUnparser::VisitEmpty(RegExpEmpty* that, void* data) {
  stream()->Put('%');
  return NULL;
}


944
SmartArrayPointer<const char> RegExpTree::ToString() {
945 946 947 948 949 950
  RegExpUnparser unparser;
  Accept(&unparser, NULL);
  return unparser.ToString();
}


951 952
RegExpDisjunction::RegExpDisjunction(ZoneList<RegExpTree*>* alternatives)
    : alternatives_(alternatives) {
953
  ASSERT(alternatives->length() > 1);
954 955 956 957 958 959 960 961 962 963 964
  RegExpTree* first_alternative = alternatives->at(0);
  min_match_ = first_alternative->min_match();
  max_match_ = first_alternative->max_match();
  for (int i = 1; i < alternatives->length(); i++) {
    RegExpTree* alternative = alternatives->at(i);
    min_match_ = Min(min_match_, alternative->min_match());
    max_match_ = Max(max_match_, alternative->max_match());
  }
}


965 966 967 968 969 970 971 972
static int IncreaseBy(int previous, int increase) {
  if (RegExpTree::kInfinity - previous < increase) {
    return RegExpTree::kInfinity;
  } else {
    return previous + increase;
  }
}

973 974
RegExpAlternative::RegExpAlternative(ZoneList<RegExpTree*>* nodes)
    : nodes_(nodes) {
975
  ASSERT(nodes->length() > 1);
976 977 978 979
  min_match_ = 0;
  max_match_ = 0;
  for (int i = 0; i < nodes->length(); i++) {
    RegExpTree* node = nodes->at(i);
980 981
    int node_min_match = node->min_match();
    min_match_ = IncreaseBy(min_match_, node_min_match);
982
    int node_max_match = node->max_match();
983
    max_match_ = IncreaseBy(max_match_, node_max_match);
984 985 986
  }
}

987

988 989
CaseClause::CaseClause(Isolate* isolate,
                       Expression* label,
990 991 992 993 994
                       ZoneList<Statement*>* statements,
                       int pos)
    : label_(label),
      statements_(statements),
      position_(pos),
995
      compare_type_(NONE),
996 997
      compare_id_(AstNode::GetNextId(isolate)),
      entry_id_(AstNode::GetNextId(isolate)) {
998
}
999

1000

1001
#define REGULAR_NODE(NodeType) \
1002 1003 1004
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
  }
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
#define DONT_OPTIMIZE_NODE(NodeType) \
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
    add_flag(kDontOptimize); \
    add_flag(kDontInline); \
    add_flag(kDontSelfOptimize); \
  }
#define DONT_INLINE_NODE(NodeType) \
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
    add_flag(kDontInline); \
  }
#define DONT_SELFOPTIMIZE_NODE(NodeType) \
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
    add_flag(kDontSelfOptimize); \
  }
1022

1023 1024 1025 1026 1027 1028 1029 1030 1031
REGULAR_NODE(VariableDeclaration)
REGULAR_NODE(FunctionDeclaration)
REGULAR_NODE(Block)
REGULAR_NODE(ExpressionStatement)
REGULAR_NODE(EmptyStatement)
REGULAR_NODE(IfStatement)
REGULAR_NODE(ContinueStatement)
REGULAR_NODE(BreakStatement)
REGULAR_NODE(ReturnStatement)
1032
REGULAR_NODE(SwitchStatement)
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
REGULAR_NODE(Conditional)
REGULAR_NODE(Literal)
REGULAR_NODE(ObjectLiteral)
REGULAR_NODE(Assignment)
REGULAR_NODE(Throw)
REGULAR_NODE(Property)
REGULAR_NODE(UnaryOperation)
REGULAR_NODE(CountOperation)
REGULAR_NODE(BinaryOperation)
REGULAR_NODE(CompareOperation)
REGULAR_NODE(ThisFunction)
REGULAR_NODE(Call)
REGULAR_NODE(CallNew)
// In theory, for VariableProxy we'd have to add:
// if (node->var()->IsLookupSlot()) add_flag(kDontInline);
// But node->var() is usually not bound yet at VariableProxy creation time, and
// LOOKUP variables only result from constructs that cannot be inlined anyway.
REGULAR_NODE(VariableProxy)

DONT_OPTIMIZE_NODE(ModuleDeclaration)
DONT_OPTIMIZE_NODE(ImportDeclaration)
DONT_OPTIMIZE_NODE(ExportDeclaration)
DONT_OPTIMIZE_NODE(ModuleLiteral)
DONT_OPTIMIZE_NODE(ModuleVariable)
DONT_OPTIMIZE_NODE(ModulePath)
DONT_OPTIMIZE_NODE(ModuleUrl)
DONT_OPTIMIZE_NODE(WithStatement)
DONT_OPTIMIZE_NODE(TryCatchStatement)
DONT_OPTIMIZE_NODE(TryFinallyStatement)
DONT_OPTIMIZE_NODE(DebuggerStatement)
DONT_OPTIMIZE_NODE(SharedFunctionInfoLiteral)

DONT_INLINE_NODE(FunctionLiteral)
DONT_INLINE_NODE(RegExpLiteral)  // TODO(1322): Allow materialized literals.
DONT_INLINE_NODE(ArrayLiteral)  // TODO(1322): Allow materialized literals.

DONT_SELFOPTIMIZE_NODE(DoWhileStatement)
DONT_SELFOPTIMIZE_NODE(WhileStatement)
DONT_SELFOPTIMIZE_NODE(ForStatement)
DONT_SELFOPTIMIZE_NODE(ForInStatement)
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089

void AstConstructionVisitor::VisitCallRuntime(CallRuntime* node) {
  increase_node_count();
  if (node->is_jsruntime()) {
    // Don't try to inline JS runtime calls because we don't (currently) even
    // optimize them.
    add_flag(kDontInline);
  } else if (node->function()->intrinsic_type == Runtime::INLINE &&
      (node->name()->IsEqualTo(CStrVector("_ArgumentsLength")) ||
       node->name()->IsEqualTo(CStrVector("_Arguments")))) {
    // Don't inline the %_ArgumentsLength or %_Arguments because their
    // implementation will not work.  There is no stack frame to get them
    // from.
    add_flag(kDontInline);
  }
}

1090 1091 1092 1093 1094
#undef REGULAR_NODE
#undef DONT_OPTIMIZE_NODE
#undef DONT_INLINE_NODE
#undef DONT_SELFOPTIMIZE_NODE

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

Handle<String> Literal::ToString() {
  if (handle_->IsString()) return Handle<String>::cast(handle_);
  ASSERT(handle_->IsNumber());
  char arr[100];
  Vector<char> buffer(arr, ARRAY_SIZE(arr));
  const char* str;
  if (handle_->IsSmi()) {
    // Optimization only, the heap number case would subsume this.
    OS::SNPrintF(buffer, "%d", Smi::cast(*handle_)->value());
    str = arr;
  } else {
    str = DoubleToCString(handle_->Number(), buffer);
  }
  return FACTORY->NewStringFromAscii(CStrVector(str));
}


1113
} }  // namespace v8::internal