1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include <math.h> // For isfinite.
32 #include "conversions.h"
35 #include "property-details.h"
38 #include "string-stream.h"
39 #include "type-info.h"
44 // ----------------------------------------------------------------------------
45 // All the Accept member functions for each syntax tree node type.
47 #define DECL_ACCEPT(type) \
48 void type::Accept(AstVisitor* v) { v->Visit##type(this); }
49 AST_NODE_LIST(DECL_ACCEPT)
53 // ----------------------------------------------------------------------------
54 // Implementation of other node functionality.
57 bool Expression::IsSmiLiteral() {
58 return AsLiteral() != NULL && AsLiteral()->handle()->IsSmi();
62 bool Expression::IsStringLiteral() {
63 return AsLiteral() != NULL && AsLiteral()->handle()->IsString();
67 bool Expression::IsNullLiteral() {
68 return AsLiteral() != NULL && AsLiteral()->handle()->IsNull();
72 VariableProxy::VariableProxy(Isolate* isolate, Variable* var)
73 : Expression(isolate),
75 var_(NULL), // Will be set by the call to BindTo.
76 is_this_(var->is_this()),
79 position_(RelocInfo::kNoPosition),
80 interface_(var->interface()) {
85 VariableProxy::VariableProxy(Isolate* isolate,
90 : Expression(isolate),
97 interface_(interface) {
98 // Names must be canonicalized for fast equality checks.
99 ASSERT(name->IsSymbol());
103 void VariableProxy::BindTo(Variable* var) {
104 ASSERT(var_ == NULL); // must be bound only once
105 ASSERT(var != NULL); // must bind
106 ASSERT((is_this() && var->is_this()) || name_.is_identical_to(var->name()));
107 // Ideally CONST-ness should match. However, this is very hard to achieve
108 // because we don't know the exact semantics of conflicting (const and
109 // non-const) multiple variable declarations, const vars introduced via
110 // eval() etc. Const-ness and variable declarations are a complete mess
113 var->set_is_used(true);
117 Assignment::Assignment(Isolate* isolate,
122 : Expression(isolate),
127 binary_operation_(NULL),
128 compound_load_id_(kNoNumber),
129 assignment_id_(GetNextId(isolate)),
132 is_monomorphic_(false) { }
135 Token::Value Assignment::binary_op() const {
137 case Token::ASSIGN_BIT_OR: return Token::BIT_OR;
138 case Token::ASSIGN_BIT_XOR: return Token::BIT_XOR;
139 case Token::ASSIGN_BIT_AND: return Token::BIT_AND;
140 case Token::ASSIGN_SHL: return Token::SHL;
141 case Token::ASSIGN_SAR: return Token::SAR;
142 case Token::ASSIGN_SHR: return Token::SHR;
143 case Token::ASSIGN_ADD: return Token::ADD;
144 case Token::ASSIGN_SUB: return Token::SUB;
145 case Token::ASSIGN_MUL: return Token::MUL;
146 case Token::ASSIGN_DIV: return Token::DIV;
147 case Token::ASSIGN_MOD: return Token::MOD;
148 default: UNREACHABLE();
150 return Token::ILLEGAL;
154 bool FunctionLiteral::AllowsLazyCompilation() {
155 return scope()->AllowsLazyCompilation();
159 int FunctionLiteral::start_position() const {
160 return scope()->start_position();
164 int FunctionLiteral::end_position() const {
165 return scope()->end_position();
169 LanguageMode FunctionLiteral::language_mode() const {
170 return scope()->language_mode();
174 ObjectLiteral::Property::Property(Literal* key,
180 Object* k = *key->handle();
182 isolate->heap()->Proto_symbol()->Equals(String::cast(k))) {
184 } else if (value_->AsMaterializedLiteral() != NULL) {
185 kind_ = MATERIALIZED_LITERAL;
186 } else if (value_->AsLiteral() != NULL) {
194 ObjectLiteral::Property::Property(bool is_getter, FunctionLiteral* value) {
197 kind_ = is_getter ? GETTER : SETTER;
201 bool ObjectLiteral::Property::IsCompileTimeValue() {
202 return kind_ == CONSTANT ||
203 (kind_ == MATERIALIZED_LITERAL &&
204 CompileTimeValue::IsCompileTimeValue(value_));
208 void ObjectLiteral::Property::set_emit_store(bool emit_store) {
209 emit_store_ = emit_store;
213 bool ObjectLiteral::Property::emit_store() {
218 bool IsEqualString(void* first, void* second) {
219 ASSERT((*reinterpret_cast<String**>(first))->IsString());
220 ASSERT((*reinterpret_cast<String**>(second))->IsString());
221 Handle<String> h1(reinterpret_cast<String**>(first));
222 Handle<String> h2(reinterpret_cast<String**>(second));
223 return (*h1)->Equals(*h2);
227 bool IsEqualNumber(void* first, void* second) {
228 ASSERT((*reinterpret_cast<Object**>(first))->IsNumber());
229 ASSERT((*reinterpret_cast<Object**>(second))->IsNumber());
231 Handle<Object> h1(reinterpret_cast<Object**>(first));
232 Handle<Object> h2(reinterpret_cast<Object**>(second));
234 return h2->IsSmi() && *h1 == *h2;
236 if (h2->IsSmi()) return false;
237 Handle<HeapNumber> n1 = Handle<HeapNumber>::cast(h1);
238 Handle<HeapNumber> n2 = Handle<HeapNumber>::cast(h2);
239 ASSERT(isfinite(n1->value()));
240 ASSERT(isfinite(n2->value()));
241 return n1->value() == n2->value();
245 void ObjectLiteral::CalculateEmitStore() {
246 ZoneHashMap table(Literal::Match);
247 for (int i = properties()->length() - 1; i >= 0; i--) {
248 ObjectLiteral::Property* property = properties()->at(i);
249 Literal* literal = property->key();
250 if (literal->handle()->IsNull()) continue;
251 uint32_t hash = literal->Hash();
252 // If the key of a computed property is in the table, do not emit
253 // a store for the property later.
254 if (property->kind() == ObjectLiteral::Property::COMPUTED &&
255 table.Lookup(literal, hash, false) != NULL) {
256 property->set_emit_store(false);
258 // Add key to the table.
259 table.Lookup(literal, hash, true);
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;
271 targets_.Add(target);
275 bool UnaryOperation::ResultOverwriteAllowed() {
286 bool BinaryOperation::ResultOverwriteAllowed() {
311 static bool IsTypeof(Expression* expr) {
312 UnaryOperation* maybe_unary = expr->AsUnaryOperation();
313 return maybe_unary != NULL && maybe_unary->op() == Token::TYPEOF;
317 // Check for the pattern: typeof <expression> equals <string literal>.
318 static bool MatchLiteralCompareTypeof(Expression* left,
322 Handle<String>* check) {
323 if (IsTypeof(left) && right->IsStringLiteral() && Token::IsEqualityOp(op)) {
324 *expr = left->AsUnaryOperation()->expression();
325 *check = Handle<String>::cast(right->AsLiteral()->handle());
332 bool CompareOperation::IsLiteralCompareTypeof(Expression** expr,
333 Handle<String>* check) {
334 return MatchLiteralCompareTypeof(left_, op_, right_, expr, check) ||
335 MatchLiteralCompareTypeof(right_, op_, left_, expr, check);
339 static bool IsVoidOfLiteral(Expression* expr) {
340 UnaryOperation* maybe_unary = expr->AsUnaryOperation();
341 return maybe_unary != NULL &&
342 maybe_unary->op() == Token::VOID &&
343 maybe_unary->expression()->AsLiteral() != NULL;
347 // Check for the pattern: void <literal> equals <expression>
348 static bool MatchLiteralCompareUndefined(Expression* left,
352 if (IsVoidOfLiteral(left) && Token::IsEqualityOp(op)) {
360 bool CompareOperation::IsLiteralCompareUndefined(Expression** expr) {
361 return MatchLiteralCompareUndefined(left_, op_, right_, expr) ||
362 MatchLiteralCompareUndefined(right_, op_, left_, expr);
366 // Check for the pattern: null equals <expression>
367 static bool MatchLiteralCompareNull(Expression* left,
371 if (left->IsNullLiteral() && Token::IsEqualityOp(op)) {
379 bool CompareOperation::IsLiteralCompareNull(Expression** expr) {
380 return MatchLiteralCompareNull(left_, op_, right_, expr) ||
381 MatchLiteralCompareNull(right_, op_, left_, expr);
385 // ----------------------------------------------------------------------------
388 bool Declaration::IsInlineable() const {
389 return proxy()->var()->IsStackAllocated();
392 bool FunctionDeclaration::IsInlineable() const {
397 // ----------------------------------------------------------------------------
398 // Recording of type feedback
400 void Property::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
401 // Record type feedback from the oracle in the AST.
402 is_uninitialized_ = oracle->LoadIsUninitialized(this);
403 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;
416 Literal* lit_key = key()->AsLiteral();
417 ASSERT(lit_key != NULL && lit_key->handle()->IsString());
418 Handle<String> name = Handle<String>::cast(lit_key->handle());
419 oracle->LoadReceiverTypes(this, name, &receiver_types_);
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 receiver_types_.Reserve(kMaxKeyedPolymorphism);
427 oracle->CollectKeyedReceiverTypes(this->id(), &receiver_types_);
432 void Assignment::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
433 Property* prop = target()->AsProperty();
434 ASSERT(prop != NULL);
435 is_monomorphic_ = oracle->StoreIsMonomorphicNormal(this);
436 receiver_types_.Clear();
437 if (prop->key()->IsPropertyName()) {
438 Literal* lit_key = prop->key()->AsLiteral();
439 ASSERT(lit_key != NULL && lit_key->handle()->IsString());
440 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 receiver_types_.Reserve(kMaxKeyedPolymorphism);
447 oracle->CollectKeyedReceiverTypes(this->id(), &receiver_types_);
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 receiver_types_.Reserve(kMaxKeyedPolymorphism);
460 oracle->CollectKeyedReceiverTypes(this->id(), &receiver_types_);
465 void CaseClause::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
466 TypeInfo info = oracle->SwitchType(this);
468 compare_type_ = SMI_ONLY;
469 } else if (info.IsSymbol()) {
470 compare_type_ = SYMBOL_ONLY;
471 } else if (info.IsNonSymbol()) {
472 compare_type_ = STRING_ONLY;
473 } else if (info.IsNonPrimitive()) {
474 compare_type_ = OBJECT_ONLY;
476 ASSERT(compare_type_ == NONE);
481 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 if (type->has_named_interceptor()) return false;
485 if (check_type_ == RECEIVER_MAP_CHECK) {
486 // For primitive checks the holder is set up to point to the corresponding
487 // prototype object, i.e. one step of the algorithm below has been already
488 // performed. For non-primitive checks we clear it to allow computing
489 // targets for polymorphic calls.
490 holder_ = Handle<JSObject>::null();
492 LookupResult lookup(type->GetIsolate());
494 type->LookupInDescriptors(NULL, *name, &lookup);
495 if (lookup.IsFound()) {
496 switch (lookup.type()) {
497 case CONSTANT_FUNCTION:
498 // We surely know the target for a constant function.
500 Handle<JSFunction>(lookup.GetConstantFunctionFromMap(*type));
507 // We don't know the target.
510 case ELEMENTS_TRANSITION:
511 case CONSTANT_TRANSITION:
512 case NULL_DESCRIPTOR:
513 // Perhaps something interesting is up in the prototype chain...
517 // If we reach the end of the prototype chain, we don't know the target.
518 if (!type->prototype()->IsJSObject()) return false;
519 // Go up the prototype chain, recording where we are currently.
520 holder_ = Handle<JSObject>(JSObject::cast(type->prototype()));
521 type = Handle<Map>(holder()->map());
526 bool Call::ComputeGlobalTarget(Handle<GlobalObject> global,
527 LookupResult* lookup) {
528 target_ = Handle<JSFunction>::null();
529 cell_ = Handle<JSGlobalPropertyCell>::null();
530 ASSERT(lookup->IsFound() &&
531 lookup->type() == NORMAL &&
532 lookup->holder() == *global);
533 cell_ = Handle<JSGlobalPropertyCell>(global->GetPropertyCell(lookup));
534 if (cell_->value()->IsJSFunction()) {
535 Handle<JSFunction> candidate(JSFunction::cast(cell_->value()));
536 // If the function is in new space we assume it's more likely to
537 // change and thus prefer the general IC code.
538 if (!HEAP->InNewSpace(*candidate)) {
547 void Call::RecordTypeFeedback(TypeFeedbackOracle* oracle,
548 CallKind call_kind) {
549 is_monomorphic_ = oracle->CallIsMonomorphic(this);
550 Property* property = expression()->AsProperty();
551 if (property == NULL) {
552 // Function call. Specialize for monomorphic calls.
553 if (is_monomorphic_) target_ = oracle->GetCallTarget(this);
555 // Method call. Specialize for the receiver types seen at runtime.
556 Literal* key = property->key()->AsLiteral();
557 ASSERT(key != NULL && key->handle()->IsString());
558 Handle<String> name = Handle<String>::cast(key->handle());
559 receiver_types_.Clear();
560 oracle->CallReceiverTypes(this, name, call_kind, &receiver_types_);
562 if (FLAG_enable_slow_asserts) {
563 int length = receiver_types_.length();
564 for (int i = 0; i < length; i++) {
565 Handle<Map> map = receiver_types_.at(i);
566 ASSERT(!map.is_null() && *map != NULL);
570 check_type_ = oracle->GetCallCheckType(this);
571 if (is_monomorphic_) {
573 if (receiver_types_.length() > 0) {
574 ASSERT(check_type_ == RECEIVER_MAP_CHECK);
575 map = receiver_types_.at(0);
577 ASSERT(check_type_ != RECEIVER_MAP_CHECK);
578 holder_ = Handle<JSObject>(
579 oracle->GetPrototypeForPrimitiveCheck(check_type_));
580 map = Handle<Map>(holder_->map());
582 is_monomorphic_ = ComputeTarget(map, name);
588 void CallNew::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
589 is_monomorphic_ = oracle->CallNewIsMonomorphic(this);
590 if (is_monomorphic_) {
591 target_ = oracle->GetCallNewTarget(this);
596 void CompareOperation::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
597 TypeInfo info = oracle->CompareType(this);
599 compare_type_ = SMI_ONLY;
600 } else if (info.IsNonPrimitive()) {
601 compare_type_ = OBJECT_ONLY;
603 ASSERT(compare_type_ == NONE);
608 void ObjectLiteral::Property::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
609 receiver_type_ = oracle->ObjectLiteralStoreIsMonomorphic(this)
610 ? oracle->GetObjectLiteralStoreMap(this)
611 : Handle<Map>::null();
615 // ----------------------------------------------------------------------------
616 // Implementation of AstVisitor
618 bool AstVisitor::CheckStackOverflow() {
619 if (stack_overflow_) return true;
620 StackLimitCheck check(isolate_);
621 if (!check.HasOverflowed()) return false;
622 return (stack_overflow_ = true);
626 void AstVisitor::VisitDeclarations(ZoneList<Declaration*>* declarations) {
627 for (int i = 0; i < declarations->length(); i++) {
628 Visit(declarations->at(i));
633 void AstVisitor::VisitStatements(ZoneList<Statement*>* statements) {
634 for (int i = 0; i < statements->length(); i++) {
635 Visit(statements->at(i));
640 void AstVisitor::VisitExpressions(ZoneList<Expression*>* expressions) {
641 for (int i = 0; i < expressions->length(); i++) {
642 // The variable statement visiting code may pass NULL expressions
643 // to this code. Maybe this should be handled by introducing an
644 // undefined expression or literal? Revisit this code if this
646 Expression* expression = expressions->at(i);
647 if (expression != NULL) Visit(expression);
652 // ----------------------------------------------------------------------------
653 // Regular expressions
655 #define MAKE_ACCEPT(Name) \
656 void* RegExp##Name::Accept(RegExpVisitor* visitor, void* data) { \
657 return visitor->Visit##Name(this, data); \
659 FOR_EACH_REG_EXP_TREE_TYPE(MAKE_ACCEPT)
662 #define MAKE_TYPE_CASE(Name) \
663 RegExp##Name* RegExpTree::As##Name() { \
666 bool RegExpTree::Is##Name() { return false; }
667 FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE)
668 #undef MAKE_TYPE_CASE
670 #define MAKE_TYPE_CASE(Name) \
671 RegExp##Name* RegExp##Name::As##Name() { \
674 bool RegExp##Name::Is##Name() { return true; }
675 FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE)
676 #undef MAKE_TYPE_CASE
679 static Interval ListCaptureRegisters(ZoneList<RegExpTree*>* children) {
680 Interval result = Interval::Empty();
681 for (int i = 0; i < children->length(); i++)
682 result = result.Union(children->at(i)->CaptureRegisters());
687 Interval RegExpAlternative::CaptureRegisters() {
688 return ListCaptureRegisters(nodes());
692 Interval RegExpDisjunction::CaptureRegisters() {
693 return ListCaptureRegisters(alternatives());
697 Interval RegExpLookahead::CaptureRegisters() {
698 return body()->CaptureRegisters();
702 Interval RegExpCapture::CaptureRegisters() {
703 Interval self(StartRegister(index()), EndRegister(index()));
704 return self.Union(body()->CaptureRegisters());
708 Interval RegExpQuantifier::CaptureRegisters() {
709 return body()->CaptureRegisters();
713 bool RegExpAssertion::IsAnchoredAtStart() {
714 return type() == RegExpAssertion::START_OF_INPUT;
718 bool RegExpAssertion::IsAnchoredAtEnd() {
719 return type() == RegExpAssertion::END_OF_INPUT;
723 bool RegExpAlternative::IsAnchoredAtStart() {
724 ZoneList<RegExpTree*>* nodes = this->nodes();
725 for (int i = 0; i < nodes->length(); i++) {
726 RegExpTree* node = nodes->at(i);
727 if (node->IsAnchoredAtStart()) { return true; }
728 if (node->max_match() > 0) { return false; }
734 bool RegExpAlternative::IsAnchoredAtEnd() {
735 ZoneList<RegExpTree*>* nodes = this->nodes();
736 for (int i = nodes->length() - 1; i >= 0; i--) {
737 RegExpTree* node = nodes->at(i);
738 if (node->IsAnchoredAtEnd()) { return true; }
739 if (node->max_match() > 0) { return false; }
745 bool RegExpDisjunction::IsAnchoredAtStart() {
746 ZoneList<RegExpTree*>* alternatives = this->alternatives();
747 for (int i = 0; i < alternatives->length(); i++) {
748 if (!alternatives->at(i)->IsAnchoredAtStart())
755 bool RegExpDisjunction::IsAnchoredAtEnd() {
756 ZoneList<RegExpTree*>* alternatives = this->alternatives();
757 for (int i = 0; i < alternatives->length(); i++) {
758 if (!alternatives->at(i)->IsAnchoredAtEnd())
765 bool RegExpLookahead::IsAnchoredAtStart() {
766 return is_positive() && body()->IsAnchoredAtStart();
770 bool RegExpCapture::IsAnchoredAtStart() {
771 return body()->IsAnchoredAtStart();
775 bool RegExpCapture::IsAnchoredAtEnd() {
776 return body()->IsAnchoredAtEnd();
780 // Convert regular expression trees to a simple sexp representation.
781 // This representation should be different from the input grammar
782 // in as many cases as possible, to make it more difficult for incorrect
783 // parses to look as correct ones which is likely if the input and
784 // output formats are alike.
785 class RegExpUnparser: public RegExpVisitor {
788 void VisitCharacterRange(CharacterRange that);
789 SmartArrayPointer<const char> ToString() { return stream_.ToCString(); }
790 #define MAKE_CASE(Name) virtual void* Visit##Name(RegExp##Name*, void* data);
791 FOR_EACH_REG_EXP_TREE_TYPE(MAKE_CASE)
794 StringStream* stream() { return &stream_; }
795 HeapStringAllocator alloc_;
796 StringStream stream_;
800 RegExpUnparser::RegExpUnparser() : stream_(&alloc_) {
804 void* RegExpUnparser::VisitDisjunction(RegExpDisjunction* that, void* data) {
806 for (int i = 0; i < that->alternatives()->length(); i++) {
808 that->alternatives()->at(i)->Accept(this, data);
815 void* RegExpUnparser::VisitAlternative(RegExpAlternative* that, void* data) {
817 for (int i = 0; i < that->nodes()->length(); i++) {
819 that->nodes()->at(i)->Accept(this, data);
826 void RegExpUnparser::VisitCharacterRange(CharacterRange that) {
827 stream()->Add("%k", that.from());
828 if (!that.IsSingleton()) {
829 stream()->Add("-%k", that.to());
835 void* RegExpUnparser::VisitCharacterClass(RegExpCharacterClass* that,
837 if (that->is_negated())
840 for (int i = 0; i < that->ranges()->length(); i++) {
841 if (i > 0) stream()->Add(" ");
842 VisitCharacterRange(that->ranges()->at(i));
849 void* RegExpUnparser::VisitAssertion(RegExpAssertion* that, void* data) {
850 switch (that->type()) {
851 case RegExpAssertion::START_OF_INPUT:
852 stream()->Add("@^i");
854 case RegExpAssertion::END_OF_INPUT:
855 stream()->Add("@$i");
857 case RegExpAssertion::START_OF_LINE:
858 stream()->Add("@^l");
860 case RegExpAssertion::END_OF_LINE:
861 stream()->Add("@$l");
863 case RegExpAssertion::BOUNDARY:
866 case RegExpAssertion::NON_BOUNDARY:
874 void* RegExpUnparser::VisitAtom(RegExpAtom* that, void* data) {
876 Vector<const uc16> chardata = that->data();
877 for (int i = 0; i < chardata.length(); i++) {
878 stream()->Add("%k", chardata[i]);
885 void* RegExpUnparser::VisitText(RegExpText* that, void* data) {
886 if (that->elements()->length() == 1) {
887 that->elements()->at(0).data.u_atom->Accept(this, data);
890 for (int i = 0; i < that->elements()->length(); i++) {
892 that->elements()->at(i).data.u_atom->Accept(this, data);
900 void* RegExpUnparser::VisitQuantifier(RegExpQuantifier* that, void* data) {
901 stream()->Add("(# %i ", that->min());
902 if (that->max() == RegExpTree::kInfinity) {
905 stream()->Add("%i ", that->max());
907 stream()->Add(that->is_greedy() ? "g " : that->is_possessive() ? "p " : "n ");
908 that->body()->Accept(this, data);
914 void* RegExpUnparser::VisitCapture(RegExpCapture* that, void* data) {
915 stream()->Add("(^ ");
916 that->body()->Accept(this, data);
922 void* RegExpUnparser::VisitLookahead(RegExpLookahead* that, void* data) {
923 stream()->Add("(-> ");
924 stream()->Add(that->is_positive() ? "+ " : "- ");
925 that->body()->Accept(this, data);
931 void* RegExpUnparser::VisitBackReference(RegExpBackReference* that,
933 stream()->Add("(<- %i)", that->index());
938 void* RegExpUnparser::VisitEmpty(RegExpEmpty* that, void* data) {
944 SmartArrayPointer<const char> RegExpTree::ToString() {
945 RegExpUnparser unparser;
946 Accept(&unparser, NULL);
947 return unparser.ToString();
951 RegExpDisjunction::RegExpDisjunction(ZoneList<RegExpTree*>* alternatives)
952 : alternatives_(alternatives) {
953 ASSERT(alternatives->length() > 1);
954 RegExpTree* first_alternative = alternatives->at(0);
955 min_match_ = first_alternative->min_match();
956 max_match_ = first_alternative->max_match();
957 for (int i = 1; i < alternatives->length(); i++) {
958 RegExpTree* alternative = alternatives->at(i);
959 min_match_ = Min(min_match_, alternative->min_match());
960 max_match_ = Max(max_match_, alternative->max_match());
965 RegExpAlternative::RegExpAlternative(ZoneList<RegExpTree*>* nodes)
967 ASSERT(nodes->length() > 1);
970 for (int i = 0; i < nodes->length(); i++) {
971 RegExpTree* node = nodes->at(i);
972 min_match_ += node->min_match();
973 int node_max_match = node->max_match();
974 if (kInfinity - max_match_ < node_max_match) {
975 max_match_ = kInfinity;
977 max_match_ += node->max_match();
983 CaseClause::CaseClause(Isolate* isolate,
985 ZoneList<Statement*>* statements,
988 statements_(statements),
991 compare_id_(AstNode::GetNextId(isolate)),
992 entry_id_(AstNode::GetNextId(isolate)) {
996 #define INCREASE_NODE_COUNT(NodeType) \
997 void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
998 increase_node_count(); \
1001 INCREASE_NODE_COUNT(VariableDeclaration)
1002 INCREASE_NODE_COUNT(FunctionDeclaration)
1003 INCREASE_NODE_COUNT(ModuleDeclaration)
1004 INCREASE_NODE_COUNT(ImportDeclaration)
1005 INCREASE_NODE_COUNT(ExportDeclaration)
1006 INCREASE_NODE_COUNT(ModuleLiteral)
1007 INCREASE_NODE_COUNT(ModuleVariable)
1008 INCREASE_NODE_COUNT(ModulePath)
1009 INCREASE_NODE_COUNT(ModuleUrl)
1010 INCREASE_NODE_COUNT(Block)
1011 INCREASE_NODE_COUNT(ExpressionStatement)
1012 INCREASE_NODE_COUNT(EmptyStatement)
1013 INCREASE_NODE_COUNT(IfStatement)
1014 INCREASE_NODE_COUNT(ContinueStatement)
1015 INCREASE_NODE_COUNT(BreakStatement)
1016 INCREASE_NODE_COUNT(ReturnStatement)
1017 INCREASE_NODE_COUNT(Conditional)
1018 INCREASE_NODE_COUNT(Literal)
1019 INCREASE_NODE_COUNT(ObjectLiteral)
1020 INCREASE_NODE_COUNT(Assignment)
1021 INCREASE_NODE_COUNT(Throw)
1022 INCREASE_NODE_COUNT(Property)
1023 INCREASE_NODE_COUNT(UnaryOperation)
1024 INCREASE_NODE_COUNT(CountOperation)
1025 INCREASE_NODE_COUNT(BinaryOperation)
1026 INCREASE_NODE_COUNT(CompareOperation)
1027 INCREASE_NODE_COUNT(ThisFunction)
1028 INCREASE_NODE_COUNT(Call)
1029 INCREASE_NODE_COUNT(CallNew)
1031 #undef INCREASE_NODE_COUNT
1034 void AstConstructionVisitor::VisitWithStatement(WithStatement* node) {
1035 increase_node_count();
1036 add_flag(kDontOptimize);
1037 add_flag(kDontInline);
1041 void AstConstructionVisitor::VisitSwitchStatement(SwitchStatement* node) {
1042 increase_node_count();
1043 add_flag(kDontInline);
1047 void AstConstructionVisitor::VisitDoWhileStatement(DoWhileStatement* node) {
1048 increase_node_count();
1049 add_flag(kDontSelfOptimize);
1053 void AstConstructionVisitor::VisitWhileStatement(WhileStatement* node) {
1054 increase_node_count();
1055 add_flag(kDontSelfOptimize);
1059 void AstConstructionVisitor::VisitForStatement(ForStatement* node) {
1060 increase_node_count();
1061 add_flag(kDontSelfOptimize);
1065 void AstConstructionVisitor::VisitForInStatement(ForInStatement* node) {
1066 increase_node_count();
1067 add_flag(kDontSelfOptimize);
1071 void AstConstructionVisitor::VisitTryCatchStatement(TryCatchStatement* node) {
1072 increase_node_count();
1073 add_flag(kDontOptimize);
1074 add_flag(kDontInline);
1078 void AstConstructionVisitor::VisitTryFinallyStatement(
1079 TryFinallyStatement* node) {
1080 increase_node_count();
1081 add_flag(kDontOptimize);
1082 add_flag(kDontInline);
1086 void AstConstructionVisitor::VisitDebuggerStatement(DebuggerStatement* node) {
1087 increase_node_count();
1088 add_flag(kDontOptimize);
1089 add_flag(kDontInline);
1093 void AstConstructionVisitor::VisitFunctionLiteral(FunctionLiteral* node) {
1094 increase_node_count();
1095 add_flag(kDontInline);
1099 void AstConstructionVisitor::VisitSharedFunctionInfoLiteral(
1100 SharedFunctionInfoLiteral* node) {
1101 increase_node_count();
1102 add_flag(kDontOptimize);
1103 add_flag(kDontInline);
1107 void AstConstructionVisitor::VisitVariableProxy(VariableProxy* node) {
1108 increase_node_count();
1109 // In theory, we'd have to add:
1110 // if(node->var()->IsLookupSlot()) { add_flag(kDontInline); }
1111 // However, node->var() is usually not bound yet at VariableProxy creation
1112 // time, and LOOKUP variables only result from constructs that cannot
1113 // be inlined anyway.
1117 void AstConstructionVisitor::VisitRegExpLiteral(RegExpLiteral* node) {
1118 increase_node_count();
1119 add_flag(kDontInline); // TODO(1322): Allow materialized literals.
1123 void AstConstructionVisitor::VisitArrayLiteral(ArrayLiteral* node) {
1124 increase_node_count();
1125 add_flag(kDontInline); // TODO(1322): Allow materialized literals.
1129 void AstConstructionVisitor::VisitCallRuntime(CallRuntime* node) {
1130 increase_node_count();
1131 if (node->is_jsruntime()) {
1132 // Don't try to inline JS runtime calls because we don't (currently) even
1134 add_flag(kDontInline);
1135 } else if (node->function()->intrinsic_type == Runtime::INLINE &&
1136 (node->name()->IsEqualTo(CStrVector("_ArgumentsLength")) ||
1137 node->name()->IsEqualTo(CStrVector("_Arguments")))) {
1138 // Don't inline the %_ArgumentsLength or %_Arguments because their
1139 // implementation will not work. There is no stack frame to get them
1141 add_flag(kDontInline);
1146 Handle<String> Literal::ToString() {
1147 if (handle_->IsString()) return Handle<String>::cast(handle_);
1148 ASSERT(handle_->IsNumber());
1150 Vector<char> buffer(arr, ARRAY_SIZE(arr));
1152 if (handle_->IsSmi()) {
1153 // Optimization only, the heap number case would subsume this.
1154 OS::SNPrintF(buffer, "%d", Smi::cast(*handle_)->value());
1157 str = DoubleToCString(handle_->Number(), buffer);
1159 return FACTORY->NewStringFromAscii(CStrVector(str));
1163 } } // namespace v8::internal